�����    �   huggingface�{"info": {"features": {"id": {"dtype": "string", "_type": "Value"}, "text": {"dtype": "string", "_type": "Value"}, "dataset_id": {"dtype": "string", "_type": "Value"}}}}p4���� dataset_id��������text���� id����  ȜG   �� �� �,�,�p<DG�JG�JG�`ZGhB���%-5<DKRY`hov~����������������� !)08@GOW_gmt|����������������� '.5;BJQYahov~����������������� $,3;CJQX`hpw~����������������� #+3:AHOW_fnv~����������������'/7=EMT[bjrz�����������������$+29@GNV^fnv}�����������������  (/7>FMTZbiqx�����������������&-4;CJRZbjqy�����������������     % , 3 : A H O V ^ e l t { � � � � � � � � � � � � � � � � �    ( / 7 ? G O V ] d l t { � � � � � � � � � � � � � � � � �    ! ( 0 7 > E L T [ a i p w  � � � � � � � � � � � � � � � � �     % - 4 ; B J R Z a h p x � � � � � � � � � � � � � � � � �     ' / 7 > F N U \ c k r z � � � � � � � � � � � � � � � � �   (/7?FNT\dksz������������������$+3:AIQY`gow����������������� $*2:BJRZaipw�����������������%,3;BIPX^flt|�����������������  '.6>FNV]elsz������������������ ")18?EMS[bipw~����������������� !)07?FNV]els{����������������� #+2:BIQY`gov}����������������� $,3;CJQX^emt|������������������ ")/6>FNU]dksz������������������$+3;CKRZaiqy������������������ "*18?GOW_gnv~����������������� '/7?FNU\bjqx������������������ #+29AHOW^fnv}����������������� $+3:@FMU]emu|�����������������  14702136189765982850233516638134506421702153713431508678849916649364957063826881924580414197763620038913413202638067341970987456899771694033256916801224585110784598966595914289455924600720051158895105321043969547673948523218138529496014620742693340751429486386020121118513416296931153235491178477850085001933279910164166823413411325523119978631991941512018640361082412772115568814148844621804737399167781465447915948308440098092497851817951317419094316321711869508242517274013664444114664931162705513003692172436241035851440046354419715877168511813679967125035533758027216089522126431478734394152951771448605957816977285862483013210566476395553930630711283801214099762120738921082010633353881979970518926625125763781820288871843681507303588910214629260598014218308327571693114236991495903270034862004845111501967880453315925100195547313233690212843795962811142176716931131111001492872921881068010991015673831594065111626416419579572384724118228397170280646393491188618201696785819628578792131788920318407898199563206956681495606311670183668854812434408393430311732657139722337665724447115517413171602602186492221775122889388721389024414481674118531461206381514943550485643216496825314373714083068117978731573938215563977149559301785191519226087117032088602442390063182958992014108128049821103910712511131589799610116820128774791640529034757313525515164563056129265917072942857231399440712455986107452108820694607202868316751452517219984450141421156214048320957219665072558704564008291298328317389869159703215510753173020015615930491854979784157481693306096032751501681180089804855970467575788216874639386827215597015566879110044311838739017933195142905912589768700313658243971284111517642064516403880864216826534149954297249414851032561494175146913190836377903818135990854889585140473331847847632859521705988493327231155606518063334843256412595905106433912861818191153455246091143361682991072437691126413268749503782495130759656009669126323721006332194359767128047129088761895868317072712347391130009881576309354747052947129129338671648363121828351918913313059858302422615813440187645567473951717304931955571762164181080951724262718902356123582321124055358584111800859115467483166515219776959161436461897379568845343074949559542253832481350937117426875141556121329009711025495882562214427049488433539184548660078197902138328540320291419528445559594686785440935533652512163691072857824059989197475837456233359271717842577363113371664628462241172482381042434017579914191966434870291858558411254126733329517317543855420517491565149870013415591830361561585501934490222196521022817313323918670961511976229261693318434445168202651037016316400288726678981405985881301138817522002148483244605520259128443541789099627191871372739211728832127517347929766142744761293637113750265289953619351980136653061520877798684836360983566979652566474982909457140114147764278851010734815760935371491187916107678475919540805511631861096412464662431023732409431633051314433282149066751986378697963247119521167877941670932113884722627828875696871989310630836579723652310031312038102708983715428985200208478742998172183693341453160534591635124827836059089056410314019601940182525791614381956645866748545171830211932943917248158453082618775629913249714423986278844410738414146601824878137153911371808876752258301279144418613163143448591391350431867341438855018362535393073297321669989691135321101782679313345391196276517611309169131468832092727590931632441814650634181361044086476955061867265919066647128836871599450814751421545209564328910723079120006131080994881078631451274052359081465440101214911090757315577678126782357054142891760184051321960063553484981778490610530101229146813854221376021163581341645967316256171627137668775316552074673557795111266543715218317305576718319615686243415304424887998362494517820207103762171082157266354742709926533495638940475596743623421393581889217388383651012635622868351252348856855928229677107511041044132519403920221445815386061331655518730178190554571802312912198338197480608726417913249552524227798251271410312352977151975919473719151434571404349711911516295070114325894427214518464099103213144535511563922945185045877491066727716343947148174571863241119588412118420685014990150192755501395240386814927693384411458830911144951219541694208245317438395369961481253018102904115190951900799414444311177488118479111179764618647714177236213597498108231869208475196172121811992686782537377413119521054079728879584339913361442094652600720070485181089173020671511990618639071148531221295727528942421691760019368039210106414520962749458197825151721278157992722322543566503114093442412654120593187984961003533314138778143893315912528103362322573981387867413899883116970071342589818604806877859813267703814176134902455905982778485017234265298401310151945689977279035121474619010046416431063652587331866217044603106274210561516703931432030812092925131289721636789161664606958117534478420007780109293812358276506327465930025194301307435210942112346463838466223075678399103300370358070357202434116948526664063495877453207181133915725424214562911192145101857163495139128613771199423218318263970758938399401013996611368136148947765972519309203318772692153530052499262594737211598169188341311907318112366639372896104743644287424297598219035979106555562019331939587712141712108997464841817249338913409642195469171904814615628974189917661435275913268286137663856585451324181315473212103157436228759120526554290434116086402619558118568141636741220392431266747518967561846050723398181526348351628717616455924408519512313156665753936098206669437202061758571513802491106676181422916529244662127313124897561054215332621231692132918679707909769130082101286814313437060199610851971895849027941704556419079389498009739210132618686425345749534220035436285583915462946179918206998316836156167890181527362840188632348659575996200782881906415168719101422781219370634409884335439601307933824918774453130400988338751023647411028258126912813046596731855866393193755741289592115649173544812313338059786751051557331542569647252481724013638003273624932717972511861311818752450256476950603185187165119141678898385981666914271537771413981331157339871336069114663588174776171074394020247372069621403560966153971906511419914588158402301320995081759511351228722021071170284315307779184500234764527167683528501762523264166261426895534786198557501136226781782513415620756657602315501451265187817031116169920791728892852635811363566977637254391163656328112685889146421416628396884012365816801938889516760859191367211712623716492252201626111033856168634421767014817350961193297682388923897646420383679573927263252872192916370874151120281561223562378265600998141999956359728814341317747977801658164093222002400150439211512844142775291736230218019252526767216853278441252735698774249611566777011366891609833161382921891648732982221577336298699853774631499281040773495513351254804218213281099243712745993116218121812185766405801735716685637185536561427307125166041055296915094773157999378013420960993413146907841292149585861869816294993891483057417041808135054878107287163572811623893183008441886233163744251028447618291594126979157816721346339318040829122114791915840212704753441821541997143763831164643128052901207491116981099164557105310502171563783733036161394801728820557014225689184150721631400714803827165750322251818105953008038520130819621478147919624808195001969115411554475997863501809739439975153351432350654682868718233541869322262143031578676118649703158714794483774109663633�iM-�L�M:T_[}���-���������_��ɼD�������a���M�Di���k�ђЙ��"x1U>�?#G�Y1`dd�hkcy+�J��H�O4^wc9k�n�p��ث���g�m�q������������ �'�G�V{l~��J�#�&]*�.4"7�D'Z g8���C�k����C�f�[�������;�6_A�QWU�W�v�|F���J�]�E���Z��� B �" F3 �9 |M ^m %� � -� &� ߝ 1� �� ӧ �� W� �� /� J� �� �� � �  � [/ X2 �< xD cF �S uU zc �f mm Sn �v �� /� (� � ]� �� e� �� '@ �T Y �b �{ w| �� k� � �� � پ �� I� �� �� �� 6� � �� 0 ; � $ � N; �U !W �\ �h \� � �� }� �� �� � � � � �' ^, 5 �5 �8 %C sH �T �f k bm ln �n �w �� Z� �� m� T� v� �� �� g� �� �� ��&3�A�H�Ip�w�}�~g��P�Ĩ\J�QcfRhk�l��{�~���f���u�������` K�%�'�+/N�S\y\z�a�,�,������̻B�� ��I�O�Re3g�����t�`�:����V���0���t���R�> ���4 "&�(X3Z7?/F�F�T�Wjk�s�t��8� �_�������� n�%�%g(�8�AuH"L�f�g�m�sF�~�������2�����{�, "�9�@�C'I�V,Yw\ ]e�kӏ��v�I������D��%�-iV3[�^b��p�v���_������)�6^?�D�Ktq���!�V���� �]�_�bDpJz�{P~������������&�7���c������ ��l� K��� �#X&�,S2�F������ �����M�����I!�.�7�>OE�K�O |ǐ�� �ҥ����)��h�S�S�}�j����/4�4�<oR��N�����&]�&3�&��&�'�'�'�''�''n)';'�'��'��'-�'��'��'�'?�'v�'��'��'j�'��'��'F�'p((� (�(u(#�(��(E�(&�(��(��( )�A)[J)�])�p)�t)nu)h�)�)��)��)�1*�k*J�*�*k�*�*��*0+�+�o+�w+�{+�}+ڊ+W�+��+��+�+w�+б+��+O�+�+��+"�+��+i�+M�+5�+d�+�+��,�,D- -�-;-�-9#-�+-J_-�e-7h-��-��-��-�-��-1�-��-g.[..�.�+.h../.�6.z>.tD.�E.Iq.�t.v.��.8�.��.��.��.��.X�.?�.o)/�-/�q/&s/�v/ƃ/̔/K�/H�/�/u�/��/��/��/�/:�/��/,�/��/�0$ 0!0�$0�J0�^0ld0�f0�0��0�0o�0{�0l�0��0��03�0��09�0�0�0"�0�0�1R1S1Q)1�-1@11:1�G1�H1�L1�^1�h1jp1�q1\{1ƈ1ȉ1 �1 �1^�1s�1h�1ϫ1��1��1�1A2�2�2�!2�62��2��2��2��2��2)�2�2��2O�2��2�2�34 3 3�3;&3�3،3��3��3S4�z4��4x�4��4�4��4��4�4��4N�4�4z5� 5�5�5��5�5-�5<�5��5h�5&�5��5G�5p�5:6�6Q)6 86F6�j6�r6x6'�6s�6ҝ6d�6��6c�6��6��6��6��6��6�6b�6U7+7V$7T37�;7\C7�J7�P7T7W7X7�a7r7�7�7��7��7�7"�7��7x88�+8|68D;8WC8�K8�T8�\8 ^8 `8�h8;n8�o8�8�8��84�8^�8��8��8��8R�8W�8��8��8��8t�8��8H�8�9 9� 9� 9)9H99*9'9�19QE9�R9vi9um9Wn9o9P|9�~9��9-�9X�9�9j�9h�9��9��9��9��9&�9��9Q:�:�:� :� :�:f:T :�":::�::�=:�N:f:��:c�:J�:�:��:��::�:��:F�:!�:z�:��:�;[ ;�(;�0;�:;�O;�[;�\;Kj;)�;9�;��;u�;5�;_�;��;Ce<>�<ƙ<�}>��>I�>�>�>��>=�>D�>l�>��>!?�??*?�?d%?g7?6>?bL?2X?vY?�Z?��?��?��?�?��?��?n�?�?a�?@�"@I1@49@?@�@@WC@2O@WP@�Y@g^@�c@+e@�i@�~@��@�@��@D�@�kA[�Ao�A̞AE�AQ�A�A��A��A��A�AA�A:�A��A��A��AgB2 B�B�#Bi(Bh6B7B�CB�FBIIB�\B�]B+zB��B�B6�BӸB��B��B2�B9C�CY C5"C�#C4C�johanleroux/JavaMapping package uj.accse.structures; public interface IList extends Iterable { public Position addAfter(Position p, T item); public Position addBefore(Position p, T item); public Position addFirst(T item); public Position addLast(T item); public T remove(Position p); public Position search(T p); public Position next(Position p); public Position prev(Position p); public Position first(); public Position last(); public boolean isEmpty(); public Integer size(); } package fr.axonic.jf.instance.evidence; /** * Created by cduffau on 11/08/16. */ public enum AVEKAStructureProperty{ STIMULATION_SCHEDULER, WAVEFORM_PARAMETER, WAVEFORM; } package de.otto.jlineup.report; import java.util.Objects; public class Summary { public final boolean error; public final double differenceSum; public final double differenceMax; public final int acceptedDifferentPixels; public Summary(boolean error, double difference, double differenceMax, int acceptedDifferentPixels) { this.error = error; this.differenceSum = difference; this.differenceMax = differenceMax; this.acceptedDifferentPixels = acceptedDifferentPixels; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Summary summary = (Summary) o; return error == summary.error && Double.compare(summary.differenceSum, differenceSum) == 0 && Double.compare(summary.differenceMax, differenceMax) == 0 && acceptedDifferentPixels == summary.acceptedDifferentPixels; } @Override public int hashCode() { return Objects.hash(error, differenceSum, differenceMax, acceptedDifferentPixels); } @Override public String toString() { return "Summary{" + "error=" + error + ", differenceSum=" + differenceSum + ", differenceMax=" + differenceMax + ", acceptedDifferentPixels=" + acceptedDifferentPixels + '}'; } } pyricau/device-year-class /* Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ package com.facebook.device.yearclass; import android.annotation.TargetApi; import android.app.ActivityManager; import android.content.Context; import android.os.Build; import java.io.*; /** * Helper class for accessing hardware specifications, including the number of CPU cores, CPU clock speed * and total available RAM. */ public class DeviceInfo { /** * The default return value of any method in this class when an * error occurs or when processing fails (Currently set to -1). Use this to check if * the information about the device in question was successfully obtained. */ public static final int DEVICEINFO_UNKNOWN = -1; /** * Reads the number of CPU cores from the first available information from * {@code /sys/devices/system/cpu/possible}, {@code /sys/devices/system/cpu/present}, * then {@code /sys/devices/system/cpu/}. * * @return Number of CPU cores in the phone, or DEVICEINFO_UKNOWN = -1 in the event of an error. */ public static int getNumberOfCPUCores() { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) { // Gingerbread doesn't support giving a single application access to both cores, but a // handful of devices (Atrix 4G and Droid X2 for example) were released with a dual-core // chipset and Gingerbread; that can let an app in the background run without impacting // the foreground application. But for our purposes, it makes them single core. return 1; } int cores; try { cores = getCoresFromFileInfo("/sys/devices/system/cpu/possible"); if (cores == DEVICEINFO_UNKNOWN) { cores = getCoresFromFileInfo("/sys/devices/system/cpu/present"); } if (cores == DEVICEINFO_UNKNOWN) { cores = getCoresFromCPUFileList(); } } catch (SecurityException e) { cores = DEVICEINFO_UNKNOWN; } catch (NullPointerException e) { cores = DEVICEINFO_UNKNOWN; } return cores; } /** * Tries to read file contents from the file location to determine the number of cores on device. * @param fileLocation The location of the file with CPU information * @return Number of CPU cores in the phone, or DEVICEINFO_UKNOWN = -1 in the event of an error. */ private static int getCoresFromFileInfo(String fileLocation) { InputStream is = null; try { is = new FileInputStream(fileLocation); BufferedReader buf = new BufferedReader(new InputStreamReader(is)); String fileContents = buf.readLine(); buf.close(); return getCoresFromFileString(fileContents); } catch (IOException e) { return DEVICEINFO_UNKNOWN; } finally { if (is != null) { try { is.close(); } catch (IOException e) { // Do nothing. } } } } /** * Converts from a CPU core information format to number of cores. * @param str The CPU core information string, in the format of "0-N" * @return The number of cores represented by this string */ static int getCoresFromFileString(String str) { if (str == null || !str.matches("0-[\\d]+$")) { return DEVICEINFO_UNKNOWN; } int cores = Integer.valueOf(str.substring(2)) + 1; return cores; } private static int getCoresFromCPUFileList() { return new File("/sys/devices/system/cpu/").listFiles(CPU_FILTER).length; } private static final FileFilter CPU_FILTER = new FileFilter() { @Override public boolean accept(File pathname) { String path = pathname.getName(); //regex is slow, so checking char by char. if (path.startsWith("cpu")) { for (int i = 3; i < path.length(); i++) { if (!Character.isDigit(path.charAt(i))) { return false; } } return true; } return false; } }; /** * Method for reading the clock speed of a CPU core on the device. Will read from either * {@code /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq} or {@code /proc/cpuinfo}. * * @return Clock speed of a core on the device, or -1 in the event of an error. */ public static int getCPUMaxFreqKHz() { int maxFreq = DEVICEINFO_UNKNOWN; try { for (int i = 0; i < getNumberOfCPUCores(); i++) { String filename = "/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_max_freq"; File cpuInfoMaxFreqFile = new File(filename); if (cpuInfoMaxFreqFile.exists() && cpuInfoMaxFreqFile.canRead()) { byte[] buffer = new byte[128]; FileInputStream stream = new FileInputStream(cpuInfoMaxFreqFile); try { stream.read(buffer); int endIndex = 0; //Trim the first number out of the byte buffer. while (Character.isDigit(buffer[endIndex]) && endIndex < buffer.length) { endIndex++; } String str = new String(buffer, 0, endIndex); Integer freqBound = Integer.parseInt(str); if (freqBound > maxFreq) { maxFreq = freqBound; } } catch (NumberFormatException e) { //Fall through and use /proc/cpuinfo. } finally { stream.close(); } } } if (maxFreq == DEVICEINFO_UNKNOWN) { FileInputStream stream = new FileInputStream("/proc/cpuinfo"); try { int freqBound = parseFileForValue("cpu MHz", stream); freqBound *= 1000; //MHz -> kHz if (freqBound > maxFreq) maxFreq = freqBound; } finally { stream.close(); } } } catch (IOException e) { maxFreq = DEVICEINFO_UNKNOWN; //Fall through and return unknown. } return maxFreq; } /** * Calculates the total RAM of the device through Android API or /proc/meminfo. * * @param c - Context object for current running activity. * @return Total RAM that the device has, or DEVICEINFO_UNKNOWN = -1 in the event of an error. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN) public static long getTotalMemory(Context c) { // memInfo.totalMem not supported in pre-Jelly Bean APIs. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { ActivityManager.MemoryInfo memInfo = new ActivityManager.MemoryInfo(); ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE); am.getMemoryInfo(memInfo); if (memInfo != null) { return memInfo.totalMem; } else { return DEVICEINFO_UNKNOWN; } } else { long totalMem = DEVICEINFO_UNKNOWN; try { FileInputStream stream = new FileInputStream("/proc/meminfo"); try { totalMem = parseFileForValue("MemTotal", stream); totalMem *= 1024; } finally { stream.close(); } } catch (IOException e) { } return totalMem; } } /** * Helper method for reading values from system files, using a minimised buffer. * * @param textToMatch - Text in the system files to read for. * @param stream - FileInputStream of the system file being read from. * @return A numerical value following textToMatch in specified the system file. * -1 in the event of a failure. */ private static int parseFileForValue(String textToMatch, FileInputStream stream) { byte[] buffer = new byte[1024]; try { int length = stream.read(buffer); for (int i = 0; i < length; i++) { if (buffer[i] == '\n' || i == 0) { if (buffer[i] == '\n') i++; for (int j = i; j < length; j++) { int textIndex = j - i; //Text doesn't match query at some point. if (buffer[j] != textToMatch.charAt(textIndex)) { break; } //Text matches query here. if (textIndex == textToMatch.length() - 1) { return extractValue(buffer, j); } } } } } catch (IOException e) { //Ignore any exceptions and fall through to return unknown value. } catch (NumberFormatException e) { } return DEVICEINFO_UNKNOWN; } /** * Helper method used by {@link #parseFileForValue(String, FileInputStream) parseFileForValue}. Parses * the next available number after the match in the file being read and returns it as an integer. * @param index - The index in the buffer array to begin looking. * @return The next number on that line in the buffer, returned as an int. Returns * DEVICEINFO_UNKNOWN = -1 in the event that no more numbers exist on the same line. */ private static int extractValue(byte[] buffer, int index) { while (index < buffer.length && buffer[index] != '\n') { if (Character.isDigit(buffer[index])) { int start = index; index++; while (index < buffer.length && Character.isDigit(buffer[index])) { index++; } String str = new String(buffer, 0, start, index - start); return Integer.parseInt(str); } index++; } return DEVICEINFO_UNKNOWN; } } 0 /** * Copyright 2013 Netflix, 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 com.netflix.servo.publish; import com.google.common.collect.Lists; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.common.util.concurrent.TimeLimiter; import com.google.common.util.concurrent.SimpleTimeLimiter; import com.google.common.util.concurrent.UncheckedTimeoutException; import com.netflix.servo.DefaultMonitorRegistry; import com.netflix.servo.Metric; import com.netflix.servo.MonitorRegistry; import com.netflix.servo.monitor.CompositeMonitor; import com.netflix.servo.monitor.Monitor; import com.netflix.servo.monitor.ResettableMonitor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; /** * Poller for fetching {@link com.netflix.servo.annotations.Monitor} metrics * from a monitor registry. */ public final class MonitorRegistryMetricPoller implements MetricPoller { private static final Logger LOGGER = LoggerFactory.getLogger(MonitorRegistryMetricPoller.class); private final MonitorRegistry registry; private final long cacheTTL; private final AtomicReference>> cachedMonitors = new AtomicReference>>(); private final AtomicLong cacheLastUpdateTime = new AtomicLong(0L); // Put limit on fetching the monitor value in-case someone does something silly like call a // remote service inline private final TimeLimiter limiter; private final ExecutorService service; /** * Creates a new instance using {@link com.netflix.servo.DefaultMonitorRegistry}. */ public MonitorRegistryMetricPoller() { this(DefaultMonitorRegistry.getInstance(), 0L, TimeUnit.MILLISECONDS, true); } /** * Creates a new instance using the specified registry. * * @param registry registry to query for annotated objects */ public MonitorRegistryMetricPoller(MonitorRegistry registry) { this(registry, 0L, TimeUnit.MILLISECONDS, true); } /** * Creates a new instance using the specified registry and a time limiter. * * @param registry registry to query for annotated objects * @param cacheTTL how long to cache the filtered monitor list from the registry * @param unit time unit for the cache ttl */ public MonitorRegistryMetricPoller(MonitorRegistry registry, long cacheTTL, TimeUnit unit) { this(registry, cacheTTL, unit, true); } /** * Creates a new instance using the specified registry. * * @param registry registry to query for annotated objects * @param cacheTTL how long to cache the filtered monitor list from the registry * @param unit time unit for the cache ttl * @param useLimiter whether to use a time limiter for getting the values from the monitors */ public MonitorRegistryMetricPoller(MonitorRegistry registry, long cacheTTL, TimeUnit unit, boolean useLimiter) { this.registry = registry; this.cacheTTL = TimeUnit.MILLISECONDS.convert(cacheTTL, unit); if (useLimiter) { final ThreadFactory factory = new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("ServoMonitorGetValueLimiter-%d") .build(); service = Executors.newSingleThreadExecutor(factory); limiter = new SimpleTimeLimiter(service); } else { service = null; limiter = null; } } private Object getValue(Monitor monitor, boolean reset) { try { if (reset && monitor instanceof ResettableMonitor) { return ((ResettableMonitor) monitor).getAndResetValue(); } else { if (limiter != null) { final MonitorValueCallable c = new MonitorValueCallable(monitor); return limiter.callWithTimeout(c, 1, TimeUnit.SECONDS, true); } else { return monitor.getValue(); } } } catch (UncheckedTimeoutException e) { LOGGER.warn("timeout trying to get value for {}", monitor.getConfig()); } catch (Exception e) { LOGGER.warn("failed to get value for " + monitor.getConfig(), e); } return null; } private void getMonitors(List> monitors, MetricFilter filter, Monitor monitor) { if (monitor instanceof CompositeMonitor) { for (Monitor m : ((CompositeMonitor) monitor).getMonitors()) { getMonitors(monitors, filter, m); } } else if (filter.matches(monitor.getConfig())) { monitors.add(monitor); } } private void refreshMonitorCache(MetricFilter filter) { final long age = System.currentTimeMillis() - cacheLastUpdateTime.get(); if (age > cacheTTL) { List> monitors = Lists.newArrayList(); for (Monitor monitor : registry.getRegisteredMonitors()) { try { getMonitors(monitors, filter, monitor); } catch (Exception e) { LOGGER.warn("failed to get monitors for composite " + monitor.getConfig(), e); } } cacheLastUpdateTime.set(System.currentTimeMillis()); cachedMonitors.set(monitors); LOGGER.debug("cache refreshed, {} monitors matched filter, previous age {} seconds", monitors.size(), age / 1000); } else { LOGGER.debug("cache age of {} seconds is within ttl of {} seconds", age / 1000, cacheTTL / 1000); } } /** {@inheritDoc} */ public List poll(MetricFilter filter) { return poll(filter, false); } /** {@inheritDoc} */ public List poll(MetricFilter filter, boolean reset) { refreshMonitorCache(filter); List> monitors = cachedMonitors.get(); List metrics = Lists.newArrayListWithCapacity(monitors.size()); for (Monitor monitor : monitors) { Object v = getValue(monitor, reset); if (v != null) { long now = System.currentTimeMillis(); metrics.add(new Metric(monitor.getConfig(), now, v)); } } return metrics; } /** * Shutsdown the thread executor used for time limiting the get value calls. It is a good idea * to call this and explicitly cleanup the thread. In most cases the threads will be cleaned * up when the executor is garbage collected if shutdown is not called explicitly. */ public void shutdown() { if (service != null) { service.shutdownNow(); } } private static class MonitorValueCallable implements Callable { private final Monitor monitor; public MonitorValueCallable(Monitor monitor) { this.monitor = monitor; } public Object call() throws Exception { return monitor.getValue(); } } } package com.eftimoff.udacitypopmovies.app.repository.storage; import com.eftimoff.udacitypopmovies.app.models.Movie; import java.util.List; public interface LocalStorage { boolean isFavourite(int movieId); List getFavourites(); void saveFavourite(Movie movie); void removeFavourite(int movieId); } package net.openid.conformance.condition.client; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import net.openid.conformance.condition.AbstractCondition; import net.openid.conformance.condition.PostEnvironment; import net.openid.conformance.condition.PreEnvironment; import net.openid.conformance.testmodule.Environment; public class FAPIBrazilCreatePaymentConsentRequest extends AbstractCondition { @Override @PreEnvironment(required = "config" ) @PostEnvironment(required = "consent_endpoint_request") public Environment evaluate(Environment env) { JsonElement paymentConsent = env.getElementFromObject("resource", "brazilPaymentConsent"); if(paymentConsent == null) { throw error("As 'payments' is included in the 'scope' within the test configuration, a payment consent request JSON object must also be provided in the test configuration."); } JsonObject paymentRequestObject = paymentConsent.getAsJsonObject(); validate(paymentRequestObject); env.putObject("consent_endpoint_request", paymentRequestObject); logSuccess(args("consent_endpoint_request", paymentConsent)); return env; } private void validate(JsonObject consentConfig) { JsonElement element = validate("data", consentConfig); validate("loggedUser", element.getAsJsonObject()); validate("creditor", element.getAsJsonObject()); validate("payment", element.getAsJsonObject()); } private JsonElement validate(String element, JsonObject object) { if(!object.has(element)) { throw error("Consent object must have " + element + " field"); } return object.get(element); } } keanu-project/src/test/java/io/improbable/keanu/vertices/dbl/nonprobabilistic/operators/unary/ArcCosVertexTest.java package io.improbable.keanu.vertices.dbl.nonprobabilistic.operators.unary; import com.google.common.collect.ImmutableList; import io.improbable.keanu.vertices.dbl.DoubleVertex; import io.improbable.keanu.vertices.dbl.probabilistic.UniformVertex; import org.junit.Test; import static io.improbable.keanu.vertices.dbl.nonprobabilistic.operators.TensorTestOperations.finiteDifferenceMatchesForwardAndReverseModeGradient; import static io.improbable.keanu.vertices.dbl.nonprobabilistic.operators.binary.BinaryOperationTestHelpers.toDiagonalArray; import static io.improbable.keanu.vertices.dbl.nonprobabilistic.operators.unary.UnaryOperationTestHelpers.calculatesDerivativeOfMatrixElementWiseOperator; import static io.improbable.keanu.vertices.dbl.nonprobabilistic.operators.unary.UnaryOperationTestHelpers.calculatesDerivativeOfScalar; import static io.improbable.keanu.vertices.dbl.nonprobabilistic.operators.unary.UnaryOperationTestHelpers.operatesOn2x2MatrixVertexValues; import static io.improbable.keanu.vertices.dbl.nonprobabilistic.operators.unary.UnaryOperationTestHelpers.operatesOnScalarVertexValue; public class ArcCosVertexTest { @Test public void acosScalarVertexValue() { operatesOnScalarVertexValue( Math.PI, Math.acos(Math.PI), DoubleVertex::acos ); } @Test public void calculatesDerivativeOScalarACos() { calculatesDerivativeOfScalar( 0.5, -1.0 / Math.sqrt(1.0 - 0.5 * 0.5), DoubleVertex::acos ); } @Test public void acosMatrixVertexValues() { operatesOn2x2MatrixVertexValues( new double[]{0.0, 0.1, 0.2, 0.3}, new double[]{Math.acos(0.0), Math.acos(0.1), Math.acos(0.2), Math.acos(0.3)}, DoubleVertex::acos ); } @Test public void calculatesDerivativeOfMatrixElementWiseACos() { calculatesDerivativeOfMatrixElementWiseOperator( new double[]{0.1, 0.2, 0.3, 0.4}, toDiagonalArray(new double[]{ -1.0 / Math.sqrt(1.0 - 0.1 * 0.1), -1.0 / Math.sqrt(1.0 - 0.2 * 0.2), -1.0 / Math.sqrt(1.0 - 0.3 * 0.3), -1.0 / Math.sqrt(1.0 - 0.4 * 0.4) }), DoubleVertex::acos ); } @Test public void changesMatchGradient() { DoubleVertex inputVertex = new UniformVertex(new long[]{2, 2, 2}, -0.25, 0.25); ArcCosVertex outputVertex = inputVertex.times(3).acos(); finiteDifferenceMatchesForwardAndReverseModeGradient(ImmutableList.of(inputVertex), outputVertex, 0.001, 1e-4); } } ronghai/SaleAssistant0 package com.weinyc.sa.app.model; import static com.weinyc.sa.common.util.JSONUtils.expectMore; import static com.weinyc.sa.common.util.JSONUtils.expectOne; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Temporal; import javax.persistence.TemporalType; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import com.weinyc.sa.core.annotation.Relationship; import com.weinyc.sa.core.viewer.bean.W2UIColumnBean; import com.weinyc.sa.common.util.JSONUtils; import com.weinyc.sa.common.constants.Constants; import com.weinyc.sa.core.model.AbstractModel; /** * * @author ronghai */ @Entity(name = "products") public class Product extends AbstractModel implements Serializable { public static ModelMeta _getModelMeta() { if (modelMeta == null) { modelMeta = new ModelMeta<>(Product.class); } return modelMeta; } public static Product fromJson(JSONObject json) { expectOne(json, "name"); expectOne(json, "code"); expectOne(json, "english"); expectOne(json, "chinese"); expectOne(json, "recid"); expectOne(json, "id"); // expectOne(json, "description"); expectMore(json, "id", "categories"/*, Category.class*/); if (json.has("recid") && !json.has("id")) { json.put("id", json.get("recid")); } System.out.println(json); System.out.println(">>>>"); return Product.fromJson(json, Product.class); } private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @Column(name = "name") private String name; @Column(name = "code" , nullable = true) private String code; @Column(name = "english_name") private String english; @Column(name = "chinese_name") private String chinese; @Column(name = "description", nullable = true) private String description; @Column(name = "disabled") private Integer disabled; @Column(name = "add_time", nullable = true) @Temporal(TemporalType.TIMESTAMP) private Date addTime; @Column(name = "update_time", nullable = true) @Temporal(TemporalType.TIMESTAMP) private Date updateTime; @Column(name = "note" , nullable = true) private String note; @Relationship(clazz=Category.class) private transient List categories; @Relationship(clazz=Attachment.class) private transient List attachments; public List getAttachments() { return attachments; } public void setAttachments(List attachments) { this.attachments = attachments; } public List getCategories() { return categories; } public void setCategories(List categories) { this.categories = categories; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } private transient boolean changed; public static final JSONArray COLUMNS; static { COLUMNS = new JSONArray(); COLUMNS.add(new W2UIColumnBean("recid", "ID", "20%", true).toJson()); COLUMNS.add(new W2UIColumnBean("name", "Name", "20%", true, "text", JSONObject.fromObject("{ type: 'text' }")).toJson()); COLUMNS.add(new W2UIColumnBean("code", "Code", "20%", true, "text", JSONObject.fromObject("{ type: 'text' }")).toJson()); COLUMNS.add(new W2UIColumnBean("english", "English", "20%", true, "text", JSONObject.fromObject("{ type: 'text' }")).toJson()); COLUMNS.add(new W2UIColumnBean("chinese", "Chinese", "20%", true, "text", JSONObject.fromObject("{ type: 'text' }")).toJson()); W2UIColumnBean col = new W2UIColumnBean("categories", "Category", "20%", Constants.SAJS_PREFIX+".render_cats", false, null, JSONObject.fromObject("{ type: 'select', items:'"+Constants.SAJS_PREFIX+".categories()' }")); col.setSearchable(false); COLUMNS.add(col.toJson()); } public static final JSONArray ORDER_COLUMNS; static { ORDER_COLUMNS = JSONArray.fromObject(COLUMNS); ORDER_COLUMNS.remove(ORDER_COLUMNS.size() - 1); } private static ModelMeta modelMeta; public Product() { } public Product(Long id) { this.id = id; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are // not set if (!(object instanceof Product)) { return false; } Product other = (Product) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } public Date getAddTime() { return addTime; } public String getChinese() { return chinese; } public String getCode() { return code; } public String getEnglish() { return english; } @Override public Long getId() { return id; } public String getName() { return name; } public String getNote() { return note; } public Date getUpdateTime() { return updateTime; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean isChanged() { return changed; } @Override public boolean isDisabled() { return disabled != null && disabled == DISABLED_YES; } @SuppressWarnings("unchecked") @Override public ModelMeta modelMeta() { return _getModelMeta(); } public void setAddTime(Date addTime) { this.addTime = addTime; } @Override public void setChanged(boolean changed) { this.changed = changed; } public void setChinese(String chinese) { this.chinese = chinese; } public void setCode(String code) { this.code = code; } /** * * @param disabled */ @Override public void setDisabled(boolean disabled) { this.disabled = disabled ? DISABLED_YES : DISABLED_NO; } public void setEnglish(String english) { this.english = english; } @Override public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } public void setNote(String note) { this.note = note; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public Object toJson() { JSONObject map = new JSONObject(); map.put("recid", this.getRecid()); map.put("name", this.name); map.put("code", this.code); map.put("english", this.english); map.put("chinese", this.chinese); map.put("description", this.description); if( this.categories != null){ map.put("categories", JSONUtils.toJSONObjects( this.categories)); } if(this.attachments != null){ map.put("attachments", JSONUtils.toJSONObjects( this.attachments)); } map.put("id", this.id); return map; } } package de.onyxbits.raccoon.standalone.gui; import de.onyxbits.raccoon.standalone.base.AbstractModule; import de.onyxbits.raccoon.standalone.base.AppAdapter; import java.awt.Window; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.ArrayList; import java.util.Iterator; import javax.swing.JFrame; public class WindowTracker extends AbstractModule implements WindowListener { private ArrayList stage = new ArrayList(); public void register(Window w) { if (w instanceof JFrame) { ((JFrame)w).setDefaultCloseOperation(0); } w.addWindowListener(this); if (!this.stage.contains(w) && w.isVisible()) { this.stage.add(w); } } public void shutdown() { Iterator var1 = this.stage.iterator(); while(var1.hasNext()) { Window w = (Window)var1.next(); w.setVisible(false); w.dispose(); } } public void windowOpened(WindowEvent e) { Window w = e.getWindow(); if (!this.stage.contains(w)) { this.stage.add(w); } } public void windowClosing(WindowEvent e) { Window w = e.getWindow(); w.setVisible(false); w.dispose(); this.stage.remove(w); if (this.stage.isEmpty()) { ((AppAdapter)this.fetch(AppAdapter.class)).exit(); } } public void windowClosed(WindowEvent e) { } public void windowIconified(WindowEvent e) { } public void windowDeiconified(WindowEvent e) { } public void windowActivated(WindowEvent e) { } public void windowDeactivated(WindowEvent e) { } } src/main/java/org/exist/xquery/modules/httpclient/ClearFunction.java /* * eXist Open Source Native XML Database * Copyright (C) 2010-2013 The eXist-db Project * http://exist-db.org * * This program 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 * of the License, or (at your option) any later version. * * This program 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 program; if not, write to the Free Software Foundation * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * $Id$ */ package org.exist.xquery.modules.httpclient; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.dom.QName; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; import org.apache.commons.httpclient.HttpState; /** * Clears HTTP persistent state items * * @author <> * @author <> * @version 1.3 * @serial 20100228 */ public class ClearFunction extends BaseHTTPClientFunction { protected static final Logger logger = LogManager.getLogger( ClearFunction.class ); public final static FunctionSignature[] signatures = { new FunctionSignature( new QName( "clear-all", NAMESPACE_URI, PREFIX ), "Clears all persistent state (eg. cookies, credentials, etc.) stored in the current session on the client.", null, new SequenceType( Type.ITEM, Cardinality.EMPTY ) ), new FunctionSignature( new QName( "clear-persistent-cookies", NAMESPACE_URI, PREFIX ), "Clears any persistent cookies stored in the current session on the client.", null, new SequenceType( Type.ITEM, Cardinality.EMPTY ) ), new FunctionSignature( new QName( "clear-persistent-credentials", NAMESPACE_URI, PREFIX ), "Clears any persistent credentials stored in the current session on the client.", null, new SequenceType( Type.ITEM, Cardinality.EMPTY ) ), new FunctionSignature( new QName( "clear-persistent-proxy-credentials", NAMESPACE_URI, PREFIX ), "Clears any persistent proxy credentials stored in the current session on the client.", null, new SequenceType( Type.ITEM, Cardinality.EMPTY ) ) }; public ClearFunction( XQueryContext context, FunctionSignature signature ) { super( context, signature ); } public Sequence eval( Sequence[] args, Sequence contextSequence ) throws XPathException { if( isCalledAs( "clear-all" ) ) { context.setAttribute( HTTP_MODULE_PERSISTENT_STATE, null ); } else { HttpState state = (HttpState)context.getAttribute( HTTP_MODULE_PERSISTENT_STATE ); if( state != null ) { if( isCalledAs( "clear-persistent-cookies" ) ) { state.clearCookies(); } else if( isCalledAs( "clear-persistent-credentials" ) ) { state.clearCredentials(); } else if( isCalledAs( "clear-persistent-proxy-credentials" ) ) { state.clearProxyCredentials(); } } } return( Sequence.EMPTY_SEQUENCE ); } } 1-10 package frc.team4909.robot.subsystems.StiltWheel; import com.ctre.phoenix.motorcontrol.can.WPI_VictorSPX; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Subsystem; import frc.team4909.robot.Robot; import frc.team4909.robot.RobotMap; import frc.team4909.robot.subsystems.StiltWheel.commands.Default_StiltWheelStop; import com.ctre.phoenix.motorcontrol.NeutralMode; public class StiltWheelSubsystem extends Subsystem { // All motor controllers should be private. // Methods that allow safe motion should be provided by the subsystem private WPI_VictorSPX climberDriveSPX; public StiltWheelSubsystem() { // super should always be called to ensure proper subystem initialization super(); climberDriveSPX = new WPI_VictorSPX(RobotMap.climberDriveSPXID); // Set all controllers to coast in case the stilts drop down or hit something // during a match climberDriveSPX.setNeutralMode(NeutralMode.Brake); } @Override public void periodic() { } protected void initDefaultCommand() { setDefaultCommand(new Default_StiltWheelStop()); } // Spin the wheels on the bottom of the stilts to move the robot forward public void setSpeed(double speed) { climberDriveSPX.set(speed); } } 1-10 package software.hrms.business.abstracts; import java.util.List; import software.hrms.core.utilities.results.DataResult; import software.hrms.core.utilities.results.Result; import software.hrms.entities.concretes.Candidate; public interface CandidateService { Result register(Candidate candidate); DataResult> getAll(); } 0 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package put.ai.games.engine.loaders; import java.io.File; import java.io.IOException; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.jar.Attributes; import put.ai.games.game.Player; public class JarPlayerLoader extends AbstractPlayerLoader { private String getPlayerClassName(URL url) throws MalformedURLException, IOException { URL u = new URL("jar", "", url + "!/"); JarURLConnection uc = (JarURLConnection) u.openConnection(); Attributes attr = uc.getMainAttributes(); return attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null; } @Override public Class load(String jarFile) throws PlayerLoadingException { try { URL url = new File(jarFile).toURI().toURL(); this.name = getPlayerClassName(url); if (name == null) { throw new PlayerLoadingException(String.format("Can not find class name for %s", jarFile)); } this.loader = new URLClassLoader(new URL[] { url }); return load(); } catch (IOException ex) { throw new PlayerLoadingException(ex); } } } /* * Copyright 2015 Stormpath, 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 com.stormpath.sdk.impl.saml; import com.stormpath.sdk.impl.ds.InternalDataStore; import com.stormpath.sdk.impl.resource.AbstractInstanceResource; import com.stormpath.sdk.impl.resource.Property; import com.stormpath.sdk.saml.AssertionConsumerServicePostEndpoint; import java.util.Map; /** * @since 1.0.RC8 */ public class DefaultAssertionConsumerServicePostEndpoint extends AbstractInstanceResource implements AssertionConsumerServicePostEndpoint { private static final Map PROPERTY_DESCRIPTORS = createPropertyDescriptorMap(); public DefaultAssertionConsumerServicePostEndpoint(InternalDataStore dataStore) { super(dataStore); } public DefaultAssertionConsumerServicePostEndpoint(InternalDataStore dataStore, Map properties) { super(dataStore, properties); } @Override public Map getPropertyDescriptors() { return PROPERTY_DESCRIPTORS; } } package com.sls.report.dto; public class SummaryReportGrandTotalDTO { private long bales; private String quantityUnit; private long weight; private long loose; public long getBales() { return bales; } public void setBales(long bales) { this.bales = bales; } public String getQuantityUnit() { return quantityUnit; } public void setQuantityUnit(String quantityUnit) { this.quantityUnit = quantityUnit; } public long getWeight() { return weight; } public void setWeight(long weight) { this.weight = weight; } public long getLoose() { return loose; } public void setLoose(long loose) { this.loose = loose; } } antomy-gc/art-java0 /* * ART Java * * Copyright 2019 ART * * 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 ru.art.kafka.consumer.configuration; import lombok.*; import ru.art.core.module.*; import static ru.art.core.factory.CollectionsFactory.*; import java.util.*; public interface KafkaConsumerModuleConfiguration extends ModuleConfiguration { boolean isEnableTracing(); KafkaConsumerConfiguration getKafkaConsumerConfiguration(); Map getKafkaStreamConfigurations(); KafkaConsumerModuleDefaultConfiguration DEFAULT_CONFIGURATION = new KafkaConsumerModuleDefaultConfiguration(); @Getter class KafkaConsumerModuleDefaultConfiguration implements KafkaConsumerModuleConfiguration { private final boolean enableTracing = false; private final KafkaConsumerConfiguration kafkaConsumerConfiguration = KafkaConsumerConfiguration.builder().build(); private final Map kafkaStreamConfigurations = mapOf(); } } package com.netease.iot.rule.proxy.util; import com.netease.iot.rule.proxy.model.ResultMessage; /** * @author xiaojianhua */ public class ResultMessageUtils { public static ResultMessage cookSuccessMessage(Object data) { return new ResultMessage(0, data, "success"); } public static ResultMessage cookFailedMessage(String failedMsg) { return new ResultMessage(-1, null, failedMsg); } } isuruuy429/product-ei /* * Copyright (c) 2017 WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.carbon.esb.mediator.test.property; import org.apache.axiom.om.OMElement; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.automation.engine.context.AutomationContext; import org.wso2.carbon.automation.engine.context.TestUserMode; import org.wso2.esb.integration.common.utils.ESBIntegrationTest; import org.wso2.esb.integration.common.utils.common.ServerConfigurationManager; import java.io.File; import java.io.IOException; import static org.testng.Assert.assertTrue; /** * This test the ability of processing the XPATh 2.0 functions using the substring-before() function */ public class PropertyXPATH2FunctionsTestCase extends ESBIntegrationTest { @BeforeClass(alwaysRun = true) public void setEnvironment() throws Exception { super.init(); ServerConfigurationManager serverConfigurationManager = new ServerConfigurationManager( new AutomationContext("ESB", TestUserMode.SUPER_TENANT_ADMIN)); serverConfigurationManager.applyConfiguration(new File( getESBResourceLocation() + File.separator + "mediatorconfig" + File.separator + "property" + File.separator + "synapse.properties")); super.init(); loadESBConfigurationFromClasspath( File.separator + "artifacts" + File.separator + "ESB" + File.separator + "mediatorconfig" + File.separator + "property" + File.separator + "XPATH2Function.xml"); } @AfterClass(alwaysRun = true) public void close() throws Exception { super.cleanup(); } @Test(groups = { "wso2.esb" }, description = "XPATH 2.0 functions") public void testRESPONSETEnabledTrue() throws IOException { OMElement response = axis2Client.sendSimpleStockQuoteRequest(getProxyServiceURLHttp("XPATH2"), null, "WSO2"); assertTrue(response.toString().contains("WSO2"), "XPATH 2.0 function processing"); } }0 package com.samcgardner.rxsqs; import com.amazonaws.services.sqs.model.Message; import java.util.LinkedList; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class MessageService { private BlockingQueue messages; private List threads; MessageService(String queueUrl, RxSQSConfiguration config) { this.messages = new LinkedBlockingQueue<>(config.getMaxBufferSize()); this.threads = new LinkedList<>(); for(int i = 0; i < config.getThreadPoolSize(); i++) { threads.add(new Thread(new FetchMessageRunnable(queueUrl, config.getAmazonSQS(), messages))); threads.get(i).start(); } } Message getNextMessage() throws InterruptedException { return messages.take(); } void terminateThreads() { for (Thread thread : threads) thread.interrupt(); } } package example.simple.springboot.ddd.domain.aggregates; /** * @author chenweichuan */ public interface ValueObject { } package com.test.racecondition; public class DeadLockA { public static void main(String[] args) throws InterruptedException { A a = new A(); Runnable r1 = () -> a.a(); Runnable r2 = () -> a.b(); Thread t1 = new Thread(r1); t1.start(); Thread t2 = new Thread(r2); t2.start(); t1.join(); t2.join(); } } package org.davidmoten.kool.function; public final class Predicates { private Predicates() { // prevent instantiation } @SuppressWarnings("unchecked") public static Predicate alwaysTrue() { return (Predicate) AlwaysTrueHolder.INSTANCE; } private static final class AlwaysTrueHolder { static final Predicate INSTANCE = t -> true; } @SuppressWarnings("unchecked") public static Predicate alwaysFalse() { return (Predicate) AlwaysFalseHolder.INSTANCE; } public static Predicate not(Predicate predicate) { return t -> !predicate.test(t); } private static final class AlwaysFalseHolder { static final Predicate INSTANCE = t -> false; } } /* Automatic generated by CrudCodeGenerator wirtten by * * @(#)LoginUserDAO.java ${date} * * Copyright (c) ${year}. All Rights Reserved. * */ package ${packagePrefix}.dao; import org.apache.ibatis.annotations.Param; import com.github.javaclub.sword.domain.StandardDAO; import ${packagePrefix}.dataobject.LoginUserDO; /** * LoginUserDAO * * @version $Id: LoginUserDAO.java ${currentTime} Exp $ */ public interface LoginUserDAO extends StandardDAO { LoginUserDO checkLogin(@Param("username") String username, @Param("password") String ); int resetPassword(@Param("userid") Long userid, @Param("password") String ); int resetSecondAuth(LoginUserDO loginUserDO); LoginUserDO matchUserByQueryKey(@Param("q") String q); } JamesCao2048/BlizzardData /******************************************************************************* * Copyright (c) 2004,2009 Actuate Corporation. * 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: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.engine.ir; /** * Image Item definition. * */ public class ImageItemDesign extends ReportItemDesign { /** * the image source is defined by a URI */ public final static int IMAGE_URI = 0; /** * the image source is defined by name */ public final static int IMAGE_NAME = 1; /** * the image source is defined by expression. */ public final static int IMAGE_EXPRESSION = 2; /** * the image source is defined by a FILE */ public final static int IMAGE_FILE = 3; /** * image source type */ protected int imageSource; /** * image uri, used if source type URI */ protected Expression imageUri; /** * image name, used if source type NAME */ protected Expression imageName; /** * image expression, used if source type EXPR */ protected Expression imageExpression; /** * image type, used if source type EXPR. */ protected Expression imageFormat; /** * Text associated with this image, used for default locale. */ protected Expression altText; /** * Text Resource Key used for altText localization. */ protected String altTextKey; /** * help text */ protected String helpText; /** * help text resource key */ protected String helpTextKey; protected boolean fitToContainer; /** * indicates whether to scale the image proportionally. */ protected boolean proportionalScale; public ImageItemDesign( ) { this.imageSource = IMAGE_URI; } public Object accept( IReportItemVisitor visitor, Object value ) { return visitor.visitImageItem( this, value ); } /** * get the type of the image source. * * Image can be defined by expression, uri and name. * * @return type of the image source. */ public int getImageSource( ) { return this.imageSource; } /** * @param imageExpr * The imageExpr to set. * @param imageType * the image type. */ public void setImageExpression( Expression imageExpr, Expression imageType ) { this.imageSource = IMAGE_EXPRESSION; this.imageExpression = imageExpr; this.imageFormat = imageType; } /** * @return Returns the imageExpr. */ public Expression getImageExpression( ) { if ( this.imageSource == IMAGE_EXPRESSION ) { return imageExpression; } return null; } /** * @return Returns the imageType. */ public Expression getImageFormat( ) { if ( this.imageSource == IMAGE_EXPRESSION ) { return imageFormat; } return null; } /** * @param imageName * The imageName to set. */ public void setImageName( Expression imageName ) { this.imageSource = IMAGE_NAME; this.imageName = imageName; } /** * @return Returns the imageName. */ public Expression getImageName( ) { if ( imageSource == IMAGE_NAME ) { return imageName; } return null; } /** * @param imageUri * The imageUri to set. */ public void setImageUri( Expression imageUri ) { this.imageSource = IMAGE_URI; this.imageUri = imageUri; } /** * @return Returns the imageUri. */ public Expression getImageUri( ) { if ( imageSource == IMAGE_URI || imageSource == IMAGE_FILE ) { return imageUri; } return null; } public void setImageFile( Expression file ) { imageSource = IMAGE_FILE; imageUri = file; } /** * @param altText * The altText to set. */ public void setAltText( Expression altText ) { this.altText = altText; } public void setAltTextKey( String altTextKey ) { this.altTextKey = altTextKey; } /** * @return Returns the altTextKey. */ public String getAltTextKey( ) { return altTextKey; } /** * @return Returns the altText. */ public Expression getAltText( ) { return altText; } /** * set the help info. * * @param key * resource key * @param text * text content */ public void setHelpText( String key, String text ) { this.helpTextKey = key; this.helpText = text; } /** * get the help text property. * @return help text */ public String getHelpText() { return this.helpText; } /** * get the help text resource key property. * @return resource key of the help text */ public String getHelpTextKey() { return this.helpTextKey; } /** * get the FitToContainer property. * @return the FitToContainer property. */ public boolean isFitToContainer( ) { return fitToContainer; } /** * set the FitToContainer property. * @param fitToContainer */ public void setFitToContainer( boolean fitToContainer ) { this.fitToContainer = fitToContainer; } /** * @return the proportionalScale */ public boolean isProportionalScale( ) { return proportionalScale; } /** * @param proportionalScale * the proportionalScale to set */ public void setProportionalScale( boolean proportionalScale ) { this.proportionalScale = proportionalScale; } } // Copyright 2019 Google LLC // // 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 // // https://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.sps.data; public enum Category { HARDWARE("Hardware"), SOFTWARE("Software"), INTERNET_ACCESS("Internet Access"); private final String category; private Category(String category) { this.category = category; } }package dunkmania101.spatialharvesters.objects.tile_entities.base; import java.util.ArrayList; import java.util.Random; import dunkmania101.spatialharvesters.data.CommonConfig; import dunkmania101.spatialharvesters.data.CustomValues; import dunkmania101.spatialharvesters.init.ItemInit; import dunkmania101.spatialharvesters.objects.blocks.HarvesterBlock; import dunkmania101.spatialharvesters.objects.blocks.SpaceRipperBlock; import dunkmania101.spatialharvesters.objects.tile_entities.BioHarvesterTE; import dunkmania101.spatialharvesters.objects.tile_entities.DarkMobHarvesterTE; import dunkmania101.spatialharvesters.objects.tile_entities.LootHarvesterTE; import dunkmania101.spatialharvesters.objects.tile_entities.OreHarvesterTE; import dunkmania101.spatialharvesters.objects.tile_entities.SoilHarvesterTE; import dunkmania101.spatialharvesters.objects.tile_entities.SpecificMobHarvesterTE; import dunkmania101.spatialharvesters.objects.tile_entities.StoneHarvesterTE; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemHandlerHelper; public class SpatialHarvesterTE extends TickingRedstoneEnergyMachineTE { protected final ArrayList OUTPUTS = new ArrayList<>(); protected final ArrayList BLACKLIST = new ArrayList<>(); private Block thisBlock = null; public SpatialHarvesterTE(BlockEntityType tileEntityTypeIn, BlockPos pos, BlockState state) { super(tileEntityTypeIn, pos, state, true, true, true); } @Override public void tick() { if (this.thisBlock == null) { this.thisBlock = getBlockState().getBlock(); updateEnergyStorage(); } super.tick(); } @Override public void customTickActions() { boolean enableOre = CommonConfig.ENABLE_ORE_HARVESTERS.get(); boolean enableBio = CommonConfig.ENABLE_ORE_HARVESTERS.get(); boolean enableStone = CommonConfig.ENABLE_ORE_HARVESTERS.get(); boolean enableSoil = CommonConfig.ENABLE_ORE_HARVESTERS.get(); boolean enableLoot = CommonConfig.ENABLE_LOOT_HARVESTER.get(); boolean enableDarkMob = CommonConfig.ENABLE_DARK_MOB_HARVESTER.get(); boolean enableSpecificMob = CommonConfig.ENABLE_SPECIFIC_MOB_HARVESTER.get(); if (this instanceof OreHarvesterTE && !enableOre) { setActive(false); resetCountedTicks(); } else if (this instanceof BioHarvesterTE && !enableBio) { setActive(false); resetCountedTicks(); } else if (this instanceof StoneHarvesterTE && !enableStone) { setActive(false); resetCountedTicks(); } else if (this instanceof SoilHarvesterTE && !enableSoil) { setActive(false); resetCountedTicks(); } else if (this instanceof LootHarvesterTE && !enableLoot) { setActive(false); resetCountedTicks(); } else if (this instanceof DarkMobHarvesterTE && !enableDarkMob) { setActive(false); resetCountedTicks(); } else if (this instanceof SpecificMobHarvesterTE && !enableSpecificMob) { setActive(false); resetCountedTicks(); } else { super.customTickActions(); if (this.OUTPUTS.isEmpty() && !overrideSetOutputs()) { setOutputs(getOutputs()); } if (getLevel() != null && !getLevel().isClientSide() && this.thisBlock != null) { if (getCountedTicks() >= getSpeed(this.thisBlock)) { resetCountedTicks(); setActive(false); int price = getPrice(this.thisBlock); if (getEnergyStorage().getEnergyStored() >= price) { ArrayList spaceRippers = new ArrayList<>(); ArrayList outInventories = new ArrayList<>(); for (Direction side : Direction.values()) { if (getLevel().getBlockState(getBlockPos().relative(side)).getBlock() instanceof SpaceRipperBlock) { spaceRippers.add(side); } else { BlockEntity out = getLevel().getBlockEntity(getBlockPos().relative(side)); if (out != null) { LazyOptional outCap = out.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, side.getOpposite()); outCap.ifPresent(outInventories::add); } } } if (!spaceRippers.isEmpty() && !outInventories.isEmpty()) { lastMinuteActions(); if (!this.OUTPUTS.isEmpty()) { filterOutputsMinTier(thisBlock); for (Direction ignored : spaceRippers) { if (getEnergyStorage().getEnergyStored() >= price) { ItemStack chosenOutput; Random rand = getLevel().getRandom(); int shardChance = CommonConfig.HARVESTER_SHARD_CHANCE.get(); if (shardChance > 0 && rand.nextInt(shardChance) == 1) { chosenOutput = new ItemStack(getShard(this.thisBlock)); } else { chosenOutput = this.OUTPUTS.get(rand.nextInt(this.OUTPUTS.size())).copy(); } if (!chosenOutput.isEmpty()) { ResourceLocation itemRN = chosenOutput.getItem().getRegistryName(); if (itemRN != null) { if (this.BLACKLIST.contains(itemRN.toString())) { getEnergyStorage().consumeEnergy(price); setActive(true); } else { int originalCount = chosenOutput.getCount(); IItemHandler inventory = outInventories.get(rand.nextInt(outInventories.size())); ItemStack resultStack = ItemHandlerHelper.insertItemStacked(inventory, chosenOutput, false); if (resultStack.getCount() != originalCount) { getEnergyStorage().consumeEnergy(price); setActive(true); } } } } } } } } } } } } } protected void lastMinuteActions() { } public void setOutputs(ArrayList OUTPUTS) { this.OUTPUTS.clear(); for (Item item : OUTPUTS) { ItemStack stack = new ItemStack(item); if (!stack.isEmpty()) { this.OUTPUTS.add(stack); } } } public void setOutputStacks(ArrayList OUTPUTS) { this.OUTPUTS.clear(); this.OUTPUTS.addAll(OUTPUTS); } public ArrayList getOutputs() { return new ArrayList<>(); } public void filterOutputsMinTier(Block block) { for (ArrayList itemTier : getMinTierItems()) { if (itemTier.size() >= 3) { int tier = Integer.getInteger(itemTier.get(2), 0); if (getTier(block) < tier) { ResourceLocation itemRN = new ResourceLocation(itemTier.get(0), itemTier.get(1)); this.OUTPUTS.removeIf(stack -> stack.getItem().getRegistryName() != null && stack.getItem().getRegistryName().toString().equals(itemRN.toString())); } } } } public ArrayList> getMinTierItems() { return new ArrayList<>(); } public int getTier(Block block) { if (block instanceof HarvesterBlock) { return ((HarvesterBlock) block).getTier(); } return 1; } @Override protected int getCapacity() { if (this.thisBlock != null) { int price = getPrice(this.thisBlock); int multiplier = CommonConfig.HARVESTER_CAPACITY_MULTIPLIER.get(); if (Integer.MAX_VALUE / multiplier < price) { return Integer.MAX_VALUE; } return price * multiplier; } return Integer.MAX_VALUE; } @Override protected int getMaxInput() { return getCapacity(); } @Override protected int getMaxExtract() { return getCapacity(); } public int getPrice(Block block) { return Integer.MAX_VALUE; } public int getSpeed(Block block) { return Integer.MAX_VALUE; } public Item getShard(Block block) { int tier = getTier(block); Item CHOSEN_SHARD = ItemInit.SHARD_1.get(); if (tier == 2) { CHOSEN_SHARD = ItemInit.SHARD_2.get(); } else if (tier == 3) { CHOSEN_SHARD = ItemInit.SHARD_3.get(); } else if (tier == 4) { CHOSEN_SHARD = ItemInit.SHARD_4.get(); } else if (tier == 5) { CHOSEN_SHARD = ItemInit.SHARD_5.get(); } else if (tier == 6) { CHOSEN_SHARD = ItemInit.SHARD_6.get(); } else if (tier == 7) { CHOSEN_SHARD = ItemInit.SHARD_7.get(); } else if (tier == 8) { CHOSEN_SHARD = ItemInit.SHARD_7.get(); } return CHOSEN_SHARD; } public boolean overrideSetOutputs() { return false; } @Override public CompoundTag saveSerializedValues() { CompoundTag nbt = super.saveSerializedValues(); CompoundTag disabledResources = new CompoundTag(); int i = 0; for (String itemRN : this.BLACKLIST) { if (itemRN != null) { disabledResources.putString(Integer.toString(i), itemRN); i++; } } if (!disabledResources.isEmpty()) { nbt.put(CustomValues.disabledResourcesKey, disabledResources); } return nbt; } @Override public void setDeserializedValues(CompoundTag nbt) { super.setDeserializedValues(nbt); if (nbt.contains(CustomValues.removeDisabledNBTKey)) { this.BLACKLIST.clear(); } if (nbt.contains(CustomValues.disabledResourcesKey)) { this.BLACKLIST.clear(); CompoundTag disabledResources = nbt.getCompound(CustomValues.disabledResourcesKey); for (String key : disabledResources.getAllKeys()) { String itemRN = disabledResources.getString(key); ResourceLocation airRN = Items.AIR.getRegistryName(); if (airRN != null && !itemRN.equals(airRN.toString()) && !this.BLACKLIST.contains(itemRN)) { this.BLACKLIST.add(itemRN); } } } if (nbt.contains(CustomValues.disabledResourceKey)) { String itemRN = nbt.getString(CustomValues.disabledResourceKey); ResourceLocation airRN = Items.AIR.getRegistryName(); if (airRN != null && !itemRN.equals(airRN.toString()) && !this.BLACKLIST.contains(itemRN)) { this.BLACKLIST.add(itemRN); } } } } standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/client/builder/GetPartitionProjectionsSpecBuilder.java /* * 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.hadoop.hive.metastore.client.builder; import org.apache.hadoop.hive.metastore.api.GetProjectionsSpec; import java.util.List; /** * Builder for the GetProjectionsSpec. This is a projection specification for partitions returned from the HMS. */ public class GetPartitionProjectionsSpecBuilder { private List partitionList = null; private String includePartitionPattern = null; private String excludePartitionPattern = null; public GetPartitionProjectionsSpecBuilder(List partitionList, String includePartitionPattern, String excludePartitionPattern) { this.partitionList = partitionList; this.includePartitionPattern = includePartitionPattern; this.excludePartitionPattern = excludePartitionPattern; } public GetPartitionProjectionsSpecBuilder setPartitionList(List partitionList) { this.partitionList = partitionList; return this; } public GetPartitionProjectionsSpecBuilder setIncludePartitionPattern(String includePartitionPattern) { this.includePartitionPattern = includePartitionPattern; return this; } public GetPartitionProjectionsSpecBuilder setExcludePartitionPattern(String excludePartitionPattern) { this.excludePartitionPattern = excludePartitionPattern; return this; } public GetProjectionsSpec build() { return new GetProjectionsSpec(partitionList, includePartitionPattern, excludePartitionPattern); } }package jandcode.excelreport.impl; import jandcode.utils.*; import jandcode.utils.error.*; import jandcode.excelreport.*; import jandcode.excelreport.impl.databinder.*; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.formula.*; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.*; import org.joda.time.*; import java.util.*; public class ReportSheetImpl extends ReportSheet { protected HSSFSheet shTemplate; protected HSSFSheet shResult; protected int shResultIdx; protected HSSFWorkbook wbResult; protected HSSFWorkbook wbTemplate; // текущие позиции для вывода protected int curR; protected int curC; protected ListNamed bands; protected int maxCol; protected SubstVars substVars = new SubstVars(); // стили в формате [стиль-шаблона]->стиль-результата protected Map cellStyles; class SubstVars implements ISubstVar { Object data; DataBinder dataBinder = new DataBinderDelegate(); void setData(Object data) { this.data = data; } public String onSubstVar(String v) { try { if (UtString.empty(v)) { return ""; } int a = v.indexOf(':'); if (a == -1) { return dataBinder.getVarValue(data, v, ""); } else { return dataBinder.getVarValue(data, v.substring(0, a), v.substring(a + 1)); } } catch (Exception e) { return ""; } } } class BandInfo extends Named { int c1, c2, r1, r2; boolean wholeCols; // все колонки List cells = new ArrayList(); List rows = new ArrayList(); public List merges = new ArrayList(); } class StyleInfo { CellStyle tmlStyle; CellStyle resStyle; boolean isDate; boolean isNumber; } public ReportSheetImpl(HSSFSheet shTemplate, HSSFSheet shResult) { this.shTemplate = shTemplate; this.shResult = shResult; this.wbTemplate = this.shTemplate.getWorkbook(); this.wbResult = this.shResult.getWorkbook(); this.shResultIdx = this.wbResult.getSheetIndex(this.shResult); // parseSheet(); } protected void parseSheet() { shResult.setDefaultColumnWidth(shTemplate.getDefaultColumnWidth()); shResult.setDefaultRowHeight(shTemplate.getDefaultRowHeight()); // ArrayList cells = new ArrayList(); // all cells for (Row row : shTemplate) { for (Cell cell : row) { cells.add(cell); maxCol = Math.max(maxCol, cell.getColumnIndex()); } } // bands = new ListNamed(); int numNames = shTemplate.getWorkbook().getNumberOfNames(); for (int i = 0; i < numNames; i++) { HSSFName nm = shTemplate.getWorkbook().getNameAt(i); AreaReference aref = new AreaReference(nm.getRefersToFormula()); BandInfo band = new BandInfo(); band.setName(nm.getNameName()); band.c1 = aref.getFirstCell().getCol(); band.c2 = aref.getLastCell().getCol(); band.r1 = aref.getFirstCell().getRow(); band.r2 = aref.getLastCell().getRow(); band.wholeCols = aref.isWholeColumnReference(); // for (int j = band.r1; j <= band.r2; j++) { band.rows.add(shTemplate.getRow(j)); } // cells for band for (Cell cell : cells) { int ri = cell.getRowIndex(); int ci = cell.getColumnIndex(); if (ri >= band.r1 && ri <= band.r2 && ci >= band.c1 && ci <= band.c2) { band.cells.add(cell); } } // merges for band int mergCnt = shTemplate.getNumMergedRegions(); for (int k = 0; k < mergCnt; k++) { CellRangeAddress mr = shTemplate.getMergedRegion(k); int ri = mr.getFirstRow(); int ci = mr.getFirstColumn(); if (ri >= band.r1 && ri <= band.r2 && ci >= band.c1 && ci <= band.c2) { band.merges.add(mr); } } // bands.add(band); } // стили cellStyles = new HashMap(); for (short i = 0; i < wbTemplate.getNumCellStyles(); i++) { HSSFCellStyle tmlStyle = wbTemplate.getCellStyleAt(i); HSSFCellStyle resStyle = wbResult.createCellStyle(); resStyle.cloneStyleFrom(tmlStyle); StyleInfo styleInfo = new StyleInfo(); styleInfo.tmlStyle = tmlStyle; styleInfo.resStyle = resStyle; styleInfo.isDate = isStyleDate(resStyle); styleInfo.isNumber = isStyleNumber(resStyle); cellStyles.put(tmlStyle, styleInfo); } // columns widths & styles for (int i = 0; i <= maxCol; i++) { HSSFCellStyle st = shTemplate.getColumnStyle(i); if (st != null) { shResult.setDefaultColumnStyle(i, getResultCellStyle(st).resStyle); } shResult.setColumnWidth(i, shTemplate.getColumnWidth(i)); if (shTemplate.isColumnHidden(i)) { shResult.setColumnHidden(i, true); } } } public void setSheetTitle(String title) { shResult.getWorkbook().setSheetName(shResultIdx, title); } public boolean hasBand(String nameBand) { return bands.find(nameBand) != null; } public void out(String nameBand, Object data) { substVars.setData(data); // BandInfo band = bands.get(nameBand); int baseRow = curR; for (Row row : band.rows) { if (row == null) { Row emptyRow = shResult.createRow(curR); Cell emptyCell = emptyRow.createCell(0); emptyRow.setHeight(shTemplate.getDefaultRowHeight()); curR++; // тут не заполненная строка continue; } Row newRow = shResult.createRow(curR); newRow.setHeight(row.getHeight()); // curR++; for (Cell cell : band.cells) { if (cell.getRowIndex() == row.getRowNum()) { Cell newCell = newRow.createCell(cell.getColumnIndex()); copyCell(cell, newCell); } } } // merges if (!band.merges.isEmpty()) { for (CellRangeAddress mr : band.merges) { CellRangeAddress mrNew = new CellRangeAddress( mr.getFirstRow() + baseRow, mr.getLastRow() + baseRow, mr.getFirstColumn(), mr.getLastColumn() ); shResult.addMergedRegion(mrNew); } } } protected void copyCell(Cell oldCell, Cell newCell) { // Copy style from old cell and apply to new cell StyleInfo styleInfo = getResultCellStyle(oldCell.getCellStyle()); newCell.setCellStyle(styleInfo.resStyle); // If there is a cell comment, copy if (newCell.getCellComment() != null) { newCell.setCellComment(oldCell.getCellComment()); } // If there is a cell hyperlink, copy if (oldCell.getHyperlink() != null) { newCell.setHyperlink(oldCell.getHyperlink()); } String s, s1; // Set the cell data value switch (oldCell.getCellType()) { case Cell.CELL_TYPE_BLANK: break; case Cell.CELL_TYPE_BOOLEAN: newCell.setCellValue(oldCell.getBooleanCellValue()); break; case Cell.CELL_TYPE_ERROR: newCell.setCellErrorValue(oldCell.getErrorCellValue()); break; case Cell.CELL_TYPE_FORMULA: newCell.setCellFormula(oldCell.getCellFormula()); break; case Cell.CELL_TYPE_NUMERIC: newCell.setCellValue(oldCell.getNumericCellValue()); break; case Cell.CELL_TYPE_STRING: s = oldCell.getRichStringCellValue().getString(); if (s.startsWith("=")) { // формула s = s.substring(1); s1 = UtString.substVar(s, substVars); if (!UtString.empty(s1)) { try { newCell.setCellType(Cell.CELL_TYPE_FORMULA); newCell.setCellFormula(s1); } catch (FormulaParseException e) { newCell.setCellValue("!ERROR"); } } } else { s1 = UtString.substVar(s, substVars); if (styleInfo.isDate) { LocalDateTime dt = UtCnv.toDateTime(s1); if (!UtDate.isEmpty(dt)) { newCell.setCellValue(dt.toDate()); } else { newCell.setCellValue(s1); } } else if (styleInfo.isNumber) { double v = UtCnv.toDouble(s1, Double.MIN_VALUE); if (v != Double.MIN_VALUE) { newCell.setCellValue(v); } else { newCell.setCellValue(s1); } } else { newCell.setCellValue(s1); } } break; } } protected StyleInfo getResultCellStyle(CellStyle tmlStyle) { StyleInfo st = cellStyles.get(tmlStyle); if (st != null) { return st; } throw new XError("Style not found!"); } protected boolean isStyleNumber(CellStyle style) { String s = style.getDataFormatString(); if (s == null) { return false; } return s.indexOf('0') != -1 || s.indexOf('#') != -1; } protected boolean isStyleDate(CellStyle style) { String s = style.getDataFormatString(); if (s == null) { return false; } return DateUtil.isADateFormat(style.getFontIndex(), style.getDataFormatString()); } } package de.uni.bielefeld.sc.hterhors.psink.obie.ie.run.eval; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import corpus.SampledInstance; import de.uni.bielefeld.sc.hterhors.psink.obie.core.evaluation.PRF1; import de.uni.bielefeld.sc.hterhors.psink.obie.core.evaluation.PRF1Container; import de.uni.bielefeld.sc.hterhors.psink.obie.core.ontology.interfaces.IOBIEThing; import de.uni.bielefeld.sc.hterhors.psink.obie.ie.evaluation.evaluator.CartesianSearchEvaluator; import de.uni.bielefeld.sc.hterhors.psink.obie.ie.evaluation.evaluator.IEvaluator; import de.uni.bielefeld.sc.hterhors.psink.obie.ie.evaluation.evaluator.NamedEntityLinkingEvaluator; import de.uni.bielefeld.sc.hterhors.psink.obie.ie.run.InvestigationRestriction; import de.uni.bielefeld.sc.hterhors.psink.obie.ie.run.InvestigationRestriction.RestrictedField; import de.uni.bielefeld.sc.hterhors.psink.obie.ie.variables.EntityAnnotation; import de.uni.bielefeld.sc.hterhors.psink.obie.ie.variables.InstanceEntityAnnotations; import de.uni.bielefeld.sc.hterhors.psink.obie.ie.variables.OBIEInstance; import de.uni.bielefeld.sc.hterhors.psink.obie.ie.variables.OBIEState; import evaluation.EvaluationUtil; import learning.ObjectiveFunction; public class EvaluatePrediction { public static Logger log = LogManager.getRootLogger(); public static void evaluateNERPredictions(IOBIEThing initializingObject, ObjectiveFunction objectiveFunction, List> predictions, InvestigationRestriction investigationRestriction) { Map> gold = new HashMap<>(); Map> result = new HashMap<>(); for (SampledInstance prediction : predictions) { OBIEInstance resultState = prediction.getInstance(); InstanceEntityAnnotations goldState = prediction.getGoldResult(); final String key = resultState.getName(); result.putIfAbsent(key, new HashSet()); for (EntityAnnotation resultEntity : prediction.getState().getCurrentPrediction().getEntityAnnotations()) { if (!resultEntity.getAnnotationInstance().equals(initializingObject)) result.get(key).add(new EvaluationObject(resultEntity, investigationRestriction)); } gold.putIfAbsent(key, new HashSet()); for (EntityAnnotation goldEntity : goldState.getEntityAnnotations()) { gold.get(key).add(new EvaluationObject(goldEntity, investigationRestriction)); } } for (SampledInstance prediction : predictions) { OBIEState state = prediction.getState(); InstanceEntityAnnotations goldState = state.getInstance().getGoldAnnotation(); objectiveFunction.score(state, goldState); } EvaluationUtil .printPredictionPerformance(predictions.stream().map(p -> p.getState()).collect(Collectors.toList())); Set goldSet = new HashSet<>(); Set predictionSet = new HashSet<>(); int docIndex = 0; for (Entry> state : gold.entrySet()) { log.info("_____________" + state.getKey() + "______________"); log.info(state.getKey()); log.info("Gold:\t"); log.info(gold.get(state.getKey())); log.info("Result:\t"); log.info(result.get(state.getKey())); final int i = docIndex; Set goldList = gold.get(state.getKey()).stream() .map(s -> new OnlyTextEvaluationObject(s.scioClass.getTextMention(), i)) .collect(Collectors.toSet()); Set predictionList = result.get(state.getKey()).stream() .map(s -> new OnlyTextEvaluationObject(s.scioClass.getTextMention(), i)) .collect(Collectors.toSet()); final double p = NamedEntityLinkingEvaluator.precision(goldList, predictionList); final double r = NamedEntityLinkingEvaluator.recall(goldList, predictionList); final double f1 = NamedEntityLinkingEvaluator.f1(goldList, predictionList); log.info("Doc-Precisiion = " + p); log.info("Doc-Recall = " + r); log.info("Doc-F1 = " + f1); goldSet.addAll(goldList); predictionSet.addAll(predictionList); docIndex++; } final double p = NamedEntityLinkingEvaluator.precision(goldSet, predictionSet); final double r = NamedEntityLinkingEvaluator.recall(goldSet, predictionSet); final double f1 = NamedEntityLinkingEvaluator.f1(goldSet, predictionSet); log.info("Micro-Precisiion = " + p); log.info("Micro-Recall = " + r); log.info("Micro-F1 = " + f1); } public static PRF1Container evaluateREPredictions( ObjectiveFunction objectiveFunction, List> predictions, IEvaluator evaluator) { Map> gold = new HashMap<>(); Map> result = new HashMap<>(); for (SampledInstance prediction : predictions) { OBIEInstance resultState = prediction.getInstance(); InstanceEntityAnnotations goldState = prediction.getGoldResult(); final String key = resultState.getName(); result.putIfAbsent(key, new HashSet()); for (EntityAnnotation resultEntity : prediction.getState().getCurrentPrediction().getEntityAnnotations()) { if (!resultEntity.getAnnotationInstance().equals(resultEntity.getInitializationClass())) result.get(key).add(new EvaluationObject(resultEntity, evaluator.getInvestigationRestrictions())); } gold.putIfAbsent(key, new HashSet()); for (EntityAnnotation goldEntity : goldState.getEntityAnnotations()) { gold.get(key).add(new EvaluationObject(goldEntity, evaluator.getInvestigationRestrictions())); } } for (SampledInstance prediction : predictions) { OBIEState state = prediction.getState(); InstanceEntityAnnotations goldState = state.getInstance().getGoldAnnotation(); objectiveFunction.score(state, goldState); } EvaluationUtil .printPredictionPerformance(predictions.stream().map(p -> p.getState()).collect(Collectors.toList())); double meanP = 0; double meanR = 0; // double meanF1 = 0; int TP = 0; int FP = 0; int FN = 0; for (Entry> state : gold.entrySet()) { log.info("_____________" + state.getKey() + "______________"); log.info("Gold:\t"); log.info(gold.get(state.getKey())); log.info("Result:\t"); log.info(result.get(state.getKey())); List goldList = gold.get(state.getKey()).stream().map(s -> (s.scioClass)) .collect(Collectors.toList()); List predictionList = result.get(state.getKey()).stream().map(s -> s.scioClass) .collect(Collectors.toList()); FP += evaluator.prf1(goldList, predictionList).fp; TP += evaluator.prf1(goldList, predictionList).tp; FN += evaluator.prf1(goldList, predictionList).fn; final double p = evaluator.precision(goldList, predictionList); final double r = evaluator.recall(goldList, predictionList); final double f1 = evaluator.f1(goldList, predictionList); log.info("Doc-Precisiion = " + p); log.info("Doc-Recall = " + r); log.info("Doc-F1 = " + f1); meanP += p; meanR += r; // meanF1 += f1; } log.info(""); log.info(""); PRF1 x = new PRF1(TP, FP, FN); meanP /= gold.entrySet().size(); meanR /= gold.entrySet().size(); // meanF1 /= gold.entrySet().size(); log.info("MICRO: Mean-Precisiion = " + x.getPrecision()); log.info("MICRO: Mean-Recall = " + x.getRecall()); log.info("MICRO: Mean-F1 = " + x.getF1()); log.info("MACRO: Mean-Precisiion = " + meanP); log.info("MACRO: Mean-Recall = " + meanR); // log.info("MACRO: Mean-F1 = " + meanF1); log.info("MACRO: Mean-F1 = " + (2 * meanP * meanR) / (meanP + meanR)); return new PRF1Container(meanP, meanR, (2 * meanP * meanR) / (meanP + meanR)); } public static double evaluatePurityPredictions( ObjectiveFunction objectiveFunction, List> predictions, IEvaluator evaluator, InvestigationRestriction investigationRestriction) { Map> gold = new HashMap<>(); Map> result = new HashMap<>(); for (SampledInstance prediction : predictions) { OBIEInstance resultState = prediction.getInstance(); InstanceEntityAnnotations goldState = prediction.getGoldResult(); final String key = resultState.getName(); result.putIfAbsent(key, new HashSet()); for (EntityAnnotation resultEntity : prediction.getState().getCurrentPrediction().getEntityAnnotations()) { if (!resultEntity.getAnnotationInstance().equals(resultEntity.getInitializationClass())) result.get(key).add(new EvaluationObject(resultEntity, investigationRestriction)); } gold.putIfAbsent(key, new HashSet()); for (EntityAnnotation goldEntity : goldState.getEntityAnnotations()) { gold.get(key).add(new EvaluationObject(goldEntity, investigationRestriction)); } } for (SampledInstance prediction : predictions) { OBIEState state = prediction.getState(); InstanceEntityAnnotations goldState = state.getInstance().getGoldAnnotation(); objectiveFunction.score(state, goldState); } EvaluationUtil .printPredictionPerformance(predictions.stream().map(p -> p.getState()).collect(Collectors.toList())); double meanF1 = 0; for (Entry> state : gold.entrySet()) { log.info("_____________" + state.getKey() + "______________"); log.info(state.getKey()); log.info("Gold:\t"); log.info(gold.get(state.getKey())); log.info("Result:\t"); log.info(result.get(state.getKey())); List goldList = gold.get(state.getKey()).stream().map(s -> (s.scioClass)) .collect(Collectors.toList()); List predictionList = result.get(state.getKey()).stream().map(s -> s.scioClass) .collect(Collectors.toList()); final double f1 = evaluator.f1(goldList, predictionList); log.info("Doc-F1 = " + f1); meanF1 += f1; } log.info(""); log.info(""); // PRF1ScoreContainer x = new PRF1ScoreContainer(TP, FP, FN); // meanP /= gold.entrySet().size(); // meanR /= gold.entrySet().size(); meanF1 /= gold.entrySet().size(); log.info("Purity-InversePurity F_Rij = " + meanF1); return meanF1; } public static void evaluatePerSlotPredictions( ObjectiveFunction objectiveFunction, List> predictions, IEvaluator evaluator, boolean detailedOutput) { Map> gold = new HashMap<>(); Map> result = new HashMap<>(); for (SampledInstance prediction : predictions) { OBIEInstance resultState = prediction.getInstance(); InstanceEntityAnnotations goldState = prediction.getGoldResult(); final String key = resultState.getName(); result.putIfAbsent(key, new HashSet()); for (EntityAnnotation resultEntity : prediction.getState().getCurrentPrediction().getEntityAnnotations()) { if (!resultEntity.getAnnotationInstance().equals(resultEntity.getInitializationClass())) result.get(key).add(new EvaluationObject(resultEntity, evaluator.getInvestigationRestrictions())); } gold.putIfAbsent(key, new HashSet()); for (EntityAnnotation goldEntity : goldState.getEntityAnnotations()) { gold.get(key).add(new EvaluationObject(goldEntity, evaluator.getInvestigationRestrictions())); } } for (SampledInstance prediction : predictions) { OBIEState state = prediction.getState(); InstanceEntityAnnotations goldState = state.getInstance().getGoldAnnotation(); objectiveFunction.score(state, goldState); } EvaluationUtil .printPredictionPerformance(predictions.stream().map(p -> p.getState()).collect(Collectors.toList())); /* * WE ASSUME ALL ELEMENTS IN SET HAVE THE SAME TYPE! */ Class classType = gold.get(gold.keySet().iterator().next()).iterator().next().scioClass .getClass(); List> restrictFieldsList = InvestigationRestriction .getFieldRestrictionCombinations(classType, InvestigationRestriction.getMainSingleFields(classType)); Set restrictions = new HashSet<>(); restrictions.add(new InvestigationRestriction(classType, Collections.emptySet(), true)); for (Set set : restrictFieldsList) { if (set.size() > 1) { /** * TODO: allow more than a single field here: parameterize */ continue; } for (int i = 1; i < 3; i++) { restrictions.add(new InvestigationRestriction(classType, set, i % 2 == 0)); } } for (InvestigationRestriction rest : restrictions) { evaluator = new CartesianSearchEvaluator(true, evaluator.getMaxEvaluationDepth(), evaluator.isPenalizeCardinality(), rest, evaluator.getOrListCondition(), 7, evaluator.isIgnoreEmptyInstancesOnEvaluation()); if (detailedOutput) { log.info("#############################"); log.info(evaluator.getInvestigationRestrictions()); log.info("#############################"); } double meanP = 0; double meanR = 0; double meanF1 = 0; for (Entry> state : gold.entrySet()) { if (detailedOutput) { log.info("_____________" + state.getKey() + "______________"); log.info("Gold:\t"); log.info(gold.get(state.getKey())); log.info("Result:\t"); log.info(result.get(state.getKey())); } List goldList = gold.get(state.getKey()).stream().map(s -> (s.scioClass)) .collect(Collectors.toList()); List predictionList = result.get(state.getKey()).stream().map(s -> s.scioClass) .collect(Collectors.toList()); final double p = evaluator.precision(goldList, predictionList); final double r = evaluator.recall(goldList, predictionList); final double f1 = evaluator.f1(goldList, predictionList); if (detailedOutput) { log.info("Doc-Precisiion = " + p); log.info("Doc-Recall = " + r); log.info("Doc-F1 = " + f1); } meanP += p; meanR += r; meanF1 += f1; } log.info(""); log.info(""); log.info("#############################"); if (detailedOutput) log.info(evaluator.getInvestigationRestrictions()); else log.info(evaluator.getInvestigationRestrictions().summarize()); meanP /= gold.entrySet().size(); meanR /= gold.entrySet().size(); meanF1 /= gold.entrySet().size(); log.info("Mean-Precisiion = " + meanP); log.info("Mean-Recall = " + meanR); log.info("Mean-F1 = " + meanF1); log.info("#############################"); } } } 0 package ru.job4j.nonBlocking; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.hamcrest.core.Is.is; /** * Test. * @author atrifonov. * @version 1. * @since 11.10.2017. */ public class TestNonBlockingCache { @Test public void whentUpdateEqualVersionThenSuccess() { NonBlockingCache cache = new NonBlockingCache(); for(int i = 0; i < 10; i++) { cache.add(new Model("#" + i, i, 0)); } Model model = new Model("#a", 3, 0); cache.update(model); Model dModel = cache.delete(model); boolean success = dModel.getName().equals("#a") && dModel.getVersion() == 1; assertThat(success, is(true)); } @Test(expected = OptimisticException.class) public void whenUpdateNonEqualVersionThenException() { NonBlockingCache cache = new NonBlockingCache(); for(int i = 0; i < 10; i++) { cache.add(new Model("#" + i, i, 0)); } Model model = new Model("#a", 3, 1); cache.update(model); } } 0 /** *@author *@version 1.0 */ import java.util.*; import java.lang.Math.*; import java.util.concurrent.*; public class piunit implements Runnable{ private int inicio; private int end; private static float aciertos; private static float cont; public piunit(){} public piunit(int inicio,int end){ this.inicio=inicio; this.end=end; } public static float getciertos(){ return aciertos; } /** *@override */ public void run(){ Random rd = new Random(); for(int i=inicio;iWorkspace/GDI/src/ws15/uebung08/BigInt1stTest.java package ws15.uebung08; import java.util.Arrays; import org.junit.Test; import com.marcelherd.uebung8.BigInt; import com.marcelherd.uebung8.MyBigInt; import static org.junit.Assert.*; public class BigInt1stTest { @Test public void testAdd() { MyBigInt num1 = new MyBigInt("9000000000001"); BigInt num2 = new MyBigInt( "1000000000009"); num1.add(num2); assertEquals("10000000000010", num1.toString()); int[] expectedArray = new int[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0}; assertTrue(Arrays.toString(expectedArray) + " vs " + Arrays.toString(num1.getDigits()), Arrays.equals(expectedArray, num1.getDigits())); assertEquals(14, num1.length()); assertTrue(num1.equals(new MyBigInt("10000000000010"))); assertEquals(0, num1.compareTo(new MyBigInt("10000000000010"))); } } 100-1000 package dk.brics.tajs.test; import dk.brics.tajs.Main; import dk.brics.tajs.options.Options; import org.junit.Before; import org.junit.Test; @SuppressWarnings("static-method") public class TestMakeContextSensitive { @Before public void init() { Main.reset(); Options.get().enableTest(); } @Test public void makecontextsensitive_syntax() { Misc.run("test-resources/src/makecontextsensitive/syntax.js"); } @Test public void makecontextsensitive_syntax2() { Misc.run("test-resources/src/makecontextsensitive/syntax2.js"); } @Test public void makecontextsensitive_single() { Misc.run("test-resources/src/makecontextsensitive/single.js"); } @Test public void makecontextsensitive_multi() { Misc.run("test-resources/src/makecontextsensitive/multi.js"); } @Test public void makecontextsensitive_confuse() { Misc.run("test-resources/src/makecontextsensitive/confuse.js"); } @Test public void makecontextsensitive_finiteRecursion() { Misc.run("test-resources/src/makecontextsensitive/finiteRecursion.js"); } @Test public void makecontextsensitive_finiteStringRecursion() { Misc.run("test-resources/src/makecontextsensitive/finiteStringRecursion.js"); } @Test public void makecontextsensitive_objectSensitivity() { Misc.run("test-resources/src/makecontextsensitive/objectSensitivity.js"); } @Test public void makecontextsensitive_guard() { Misc.run("test-resources/src/makecontextsensitive/guard.js"); } @Test public void makecontextsensitive_closureVariables() { Misc.run("test-resources/src/makecontextsensitive/closureVariables.js"); } } app/src/main/java/mobi/stolicus/wikiloc/model/Image.java package mobi.stolicus.wikiloc.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.HashMap; import java.util.Map; import mobi.stolicus.wikiloc.support.SimilarityHelper; public class Image { @SerializedName("ns") @Expose public Integer ns; @SerializedName("title") @Expose public String title; private String stripped = ""; private Map evaluations = new HashMap<>(); private Double averageCalculated = null; public String getTitle() { return title; } public String getStripped() { return stripped; } public void setStripped(String stripped) { this.stripped = stripped; } public Map getEvaluations() { return evaluations; } public void setEvaluations(Map evaluations) { this.evaluations = evaluations; } public Double getMeanAverageOfEvaluation() { if (averageCalculated == null) averageCalculated = SimilarityHelper.getMeanAverageOfEvaluations(evaluations.values()); return averageCalculated; } // public void addEvaluation(String name, Double distance) { // this.evaluations.put(name, distance); // } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Image image = (Image) o; return title != null ? title.equals(image.title) : image.title == null; } @Override public int hashCode() { return title != null ? title.hashCode() : 0; } } smaccm/smaccm /* * generated by Xtext */ package com.rockwellcollins.atc.agree.validation; import static com.rockwellcollins.atc.agree.validation.AgreeType.BOOL; import static com.rockwellcollins.atc.agree.validation.AgreeType.ERROR; import static com.rockwellcollins.atc.agree.validation.AgreeType.INT; import static com.rockwellcollins.atc.agree.validation.AgreeType.REAL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.EcoreUtil2; import org.eclipse.xtext.validation.Check; import org.eclipse.xtext.validation.CheckType; import org.osate.aadl2.AadlBoolean; import org.osate.aadl2.AadlInteger; import org.osate.aadl2.AadlPackage; import org.osate.aadl2.AadlReal; import org.osate.aadl2.AadlString; import org.osate.aadl2.AnnexLibrary; import org.osate.aadl2.AnnexSubclause; import org.osate.aadl2.Classifier; import org.osate.aadl2.ClassifierType; import org.osate.aadl2.ComponentClassifier; import org.osate.aadl2.ComponentImplementation; import org.osate.aadl2.ComponentType; import org.osate.aadl2.Connection; import org.osate.aadl2.DataAccess; import org.osate.aadl2.DataImplementation; import org.osate.aadl2.DataPort; import org.osate.aadl2.DataSubcomponent; import org.osate.aadl2.DataSubcomponentType; import org.osate.aadl2.DataType; import org.osate.aadl2.DirectionType; import org.osate.aadl2.EnumerationType; import org.osate.aadl2.EventDataPort; import org.osate.aadl2.EventPort; import org.osate.aadl2.Feature; import org.osate.aadl2.FeatureGroup; import org.osate.aadl2.FeatureGroupType; import org.osate.aadl2.NamedElement; import org.osate.aadl2.Port; import org.osate.aadl2.Property; import org.osate.aadl2.PropertyConstant; import org.osate.aadl2.PropertyType; import org.osate.aadl2.Subcomponent; import org.osate.aadl2.impl.SubcomponentImpl; import org.osate.annexsupport.AnnexUtil; import com.rockwellcollins.atc.agree.AgreeAADLEnumerationUtils; import com.rockwellcollins.atc.agree.agree.AADLEnumerator; import com.rockwellcollins.atc.agree.agree.AgreeContract; import com.rockwellcollins.atc.agree.agree.AgreePackage; import com.rockwellcollins.atc.agree.agree.AgreeSubclause; import com.rockwellcollins.atc.agree.agree.Arg; import com.rockwellcollins.atc.agree.agree.AssertStatement; import com.rockwellcollins.atc.agree.agree.AssignStatement; import com.rockwellcollins.atc.agree.agree.AssumeStatement; import com.rockwellcollins.atc.agree.agree.AsynchStatement; import com.rockwellcollins.atc.agree.agree.BinaryExpr; import com.rockwellcollins.atc.agree.agree.BoolLitExpr; import com.rockwellcollins.atc.agree.agree.CalenStatement; import com.rockwellcollins.atc.agree.agree.CallDef; import com.rockwellcollins.atc.agree.agree.ConnectionStatement; import com.rockwellcollins.atc.agree.agree.ConstStatement; import com.rockwellcollins.atc.agree.agree.EnumStatement; import com.rockwellcollins.atc.agree.agree.EqStatement; import com.rockwellcollins.atc.agree.agree.EventExpr; import com.rockwellcollins.atc.agree.agree.Expr; import com.rockwellcollins.atc.agree.agree.FloorCast; import com.rockwellcollins.atc.agree.agree.FnCallExpr; import com.rockwellcollins.atc.agree.agree.FnDefExpr; import com.rockwellcollins.atc.agree.agree.GetPropertyExpr; import com.rockwellcollins.atc.agree.agree.GuaranteeStatement; import com.rockwellcollins.atc.agree.agree.IfThenElseExpr; import com.rockwellcollins.atc.agree.agree.InitialStatement; import com.rockwellcollins.atc.agree.agree.InputStatement; import com.rockwellcollins.atc.agree.agree.IntLitExpr; import com.rockwellcollins.atc.agree.agree.LatchedExpr; import com.rockwellcollins.atc.agree.agree.LatchedStatement; import com.rockwellcollins.atc.agree.agree.LemmaStatement; import com.rockwellcollins.atc.agree.agree.LibraryFnDefExpr; import com.rockwellcollins.atc.agree.agree.LiftStatement; import com.rockwellcollins.atc.agree.agree.LinearizationDefExpr; import com.rockwellcollins.atc.agree.agree.LinearizationInterval; import com.rockwellcollins.atc.agree.agree.MNSynchStatement; import com.rockwellcollins.atc.agree.agree.NamedID; import com.rockwellcollins.atc.agree.agree.NestedDotID; import com.rockwellcollins.atc.agree.agree.NodeBodyExpr; import com.rockwellcollins.atc.agree.agree.NodeDefExpr; import com.rockwellcollins.atc.agree.agree.NodeEq; import com.rockwellcollins.atc.agree.agree.NodeLemma; import com.rockwellcollins.atc.agree.agree.NodeStmt; import com.rockwellcollins.atc.agree.agree.OrderStatement; import com.rockwellcollins.atc.agree.agree.PeriodicStatement; import com.rockwellcollins.atc.agree.agree.PreExpr; import com.rockwellcollins.atc.agree.agree.PrevExpr; import com.rockwellcollins.atc.agree.agree.PrimType; import com.rockwellcollins.atc.agree.agree.PropertyStatement; import com.rockwellcollins.atc.agree.agree.RealCast; import com.rockwellcollins.atc.agree.agree.RealLitExpr; import com.rockwellcollins.atc.agree.agree.RecordDefExpr; import com.rockwellcollins.atc.agree.agree.RecordExpr; import com.rockwellcollins.atc.agree.agree.RecordType; import com.rockwellcollins.atc.agree.agree.RecordUpdateExpr; import com.rockwellcollins.atc.agree.agree.SpecStatement; import com.rockwellcollins.atc.agree.agree.SporadicStatement; import com.rockwellcollins.atc.agree.agree.SynchStatement; import com.rockwellcollins.atc.agree.agree.ThisExpr; import com.rockwellcollins.atc.agree.agree.TimeExpr; import com.rockwellcollins.atc.agree.agree.TimeFallExpr; import com.rockwellcollins.atc.agree.agree.TimeInterval; import com.rockwellcollins.atc.agree.agree.TimeOfExpr; import com.rockwellcollins.atc.agree.agree.TimeRiseExpr; import com.rockwellcollins.atc.agree.agree.Type; import com.rockwellcollins.atc.agree.agree.UnaryExpr; import com.rockwellcollins.atc.agree.agree.WhenHoldsStatement; import com.rockwellcollins.atc.agree.agree.WhenOccursStatment; import com.rockwellcollins.atc.agree.agree.WheneverBecomesTrueStatement; import com.rockwellcollins.atc.agree.agree.WheneverHoldsStatement; import com.rockwellcollins.atc.agree.agree.WheneverImpliesStatement; import com.rockwellcollins.atc.agree.agree.WheneverOccursStatement; import com.rockwellcollins.atc.agree.visitors.ExprCycleVisitor; /** * Custom validation rules. * * see http://www.eclipse.org/Xtext/documentation.html#validation */ public class AgreeJavaValidator extends AbstractAgreeJavaValidator { private final Set checkedRecCalls = new HashSet<>(); private final Map> enumSets = new HashMap<>(); @Override protected boolean isResponsible(Map context, EObject eObject) { return (eObject.eClass().getEPackage() == AgreePackage.eINSTANCE) || eObject instanceof AadlPackage; } // @Inject // IResourceDescriptions resourceDescriptions; // // @Check(CheckType.FAST) // public void checkAADL2Package(AadlPackage pack){ // Resource resource = pack.eResource(); // ResourceSet resources = resource.getResourceSet(); // for(Resource subRes : resources.getResources()){ // TreeIterator contents = subRes.getAllContents(); // if(contents.hasNext()){ // EObject obj = contents.next(); // if(obj instanceof AadlPackage){ // List agreeAnnex = AnnexUtil.getAllActualAnnexLibraries((AadlPackage) obj, AgreePackage.eINSTANCE.getAgreeContractLibrary()); // } // } // while(contents.hasNext()){ // EObject obj = contents.next(); // } // System.out.println(); // } // // String contextProject = pack.eResource().getURI().segment(1); // for (IResourceDescription resourceDescription : resourceDescriptions.getAllResourceDescriptions()) { // for (IEObjectDescription eobjectDescription : resourceDescription.getExportedObjectsByType(Aadl2Package.eINSTANCE.getAadlPackage())) { // EObject description = eobjectDescription.getEObjectOrProxy(); // System.out.println(); // } // } // } // // private Map> getAllIdToElementMap(AgreeContract contract){ // // for(SpecStatement spec : contract.getSpecs()){ // if (spec instanceof ) // } // // return null; // } @Check(CheckType.FAST) public void checkEnumStatement(EnumStatement statement) { String contextProject = statement.eResource().getURI().segment(1); Map enumMap; if (!enumSets.containsKey(contextProject)) { enumMap = new HashMap<>(); enumSets.put(contextProject, enumMap); } else { enumMap = enumSets.get(contextProject); } for (NamedID id : statement.getEnums()) { NamedID otherEnum = enumMap.get(id.getName()); if (otherEnum == null) { enumMap.put(id.getName(), id); } else if (otherEnum != id) { if (otherEnum.eResource() != null && otherEnum.eResource().equals(id.eResource())) { String message = "Multiple uses of the same enum value '" + id.getName() + "' in '" + getEnumValueDefLocation(otherEnum) + "' and '" + getEnumValueDefLocation(id) + "'"; error(otherEnum, message); error(id, message); } else { enumMap.put(id.getName(), id); } } } EObject container = statement.eContainer(); while (!(container instanceof AadlPackage) && !(container instanceof ComponentClassifier)) { container = container.eContainer(); } if (!(container instanceof AadlPackage)) { error(statement, "Enumerations can be defined only in AADL packages"); } } private String getEnumValueDefLocation(NamedID id) { EObject container = id.eContainer(); EnumStatement enumStatement = (EnumStatement) container; String enumName = enumStatement.getName(); while (!(container instanceof AadlPackage) && !(container instanceof ComponentClassifier)) { container = container.eContainer(); } return ((NamedElement) container).getQualifiedName() + "::" + enumName; } @Check(CheckType.FAST) public void checkConnectionStatement(ConnectionStatement conn) { Classifier container = conn.getContainingClassifier(); if (container instanceof ComponentImplementation) { NamedElement aadlConn = conn.getConn(); if (aadlConn == null) { return; } if (!(aadlConn instanceof Connection)) { error(conn, "The connection label in the connection statement is not a connection"); return; } } else { error(conn, "Connection statements are allowed only in component implementations."); } } @Check(CheckType.FAST) public void checkOrderStatement(OrderStatement order) { Classifier container = order.getContainingClassifier(); if (container instanceof ComponentImplementation) { ComponentImplementation compImpl = (ComponentImplementation) container; for (int index = 0; index < order.getComps().size(); ++index) { NamedElement comp = order.getComps().get(index); if (!(comp instanceof Subcomponent) || !((Subcomponent) comp).getContainingComponentImpl().equals(container)) { error("Element '" + comp.getName() + "' is not a subcomponent of '" + container.getName() + "'", order, AgreePackage.Literals.ORDER_STATEMENT__COMPS, index); } } List notPresent = new ArrayList<>(); for (Subcomponent subcomp : compImpl.getAllSubcomponents()) { boolean found = false; for (NamedElement el : order.getComps()) { if (el.equals(subcomp)) { found = true; break; } } if (!found) { notPresent.add(subcomp); } } if (notPresent.size() != 0) { String delim = ""; StringBuilder errorStr = new StringBuilder( "The following subcomponents are not present in the ordering: "); for (NamedElement subcomp : notPresent) { errorStr.append(delim); errorStr.append(subcomp.getName()); delim = ", "; } error(order, errorStr.toString()); } } else { error(order, "Ordering statements can appear only in component implementations"); } } private static List flattenFeatureGroups(List complexFeatures) { List result = new ArrayList<>(); for (Feature feature : complexFeatures) { if (feature instanceof FeatureGroup) { FeatureGroup featureGroup = (FeatureGroup) feature; FeatureGroupType featType = featureGroup.getFeatureGroupType(); result.addAll(flattenFeatureGroups(featType.getOwnedFeatureGroups())); result.addAll(flattenFeatureGroups(featType.getOwnedDataPorts())); result.addAll(flattenFeatureGroups(featType.getOwnedEventDataPorts())); result.addAll(flattenFeatureGroups(featType.getOwnedEventPorts())); } else { result.add(feature); } } return result; } @Check(CheckType.FAST) public void checkAssign(AssignStatement assign) { NestedDotID dotId = assign.getId(); NamedElement namedEl = dotId.getBase(); Expr expr = assign.getExpr(); if (namedEl == null || expr == null) { return; } ComponentImplementation compImpl = EcoreUtil2.getContainerOfType(assign, ComponentImplementation.class); if (compImpl == null) { error(assign, "Assignment statements are allowed only in component implementations"); return; } if (dotId.getSub() != null) { error(dotId, "The Id on the left hand side of an assignment statement " + "must not contain a \".\""); return; } if (namedEl.eContainer() instanceof InputStatement) { error(dotId, "Assignment to agree_input variables is illegal."); return; } if (compImpl != null) { List assignableElements = new ArrayList<>(); List implContracts = EcoreUtil2.getAllContentsOfType(compImpl, AgreeContract.class); for (AgreeContract ac : implContracts) { assignableElements.addAll(EcoreUtil2.getAllContentsOfType(ac, EqStatement.class).stream() .map(eq -> eq.getLhs()).flatMap(List::stream).collect(Collectors.toList())); } ComponentType compType = compImpl.getType(); if (compType != null) { List typeContracts = EcoreUtil2.getAllContentsOfType(compType, AgreeContract.class); for (AgreeContract ac : typeContracts) { assignableElements.addAll(EcoreUtil2.getAllContentsOfType(ac, EqStatement.class).stream() .map(eq -> eq.getLhs()).flatMap(List::stream).collect(Collectors.toList())); } } assignableElements.addAll(compImpl.getAllFeatures().stream() .map(cf -> flattenFeatureGroups(Collections.singletonList(cf))).flatMap(List::stream) .filter(feat -> feat instanceof EventDataPort || feat instanceof DataPort) .filter(feat -> DirectionType.OUT.equals(((Port) feat).getDirection())) .collect(Collectors.toList())); if (!assignableElements.contains(namedEl)) { error("LHS of assignment must be an AGREE 'eq' variable or an output port of this component", assign, AgreePackage.Literals.ASSIGN_STATEMENT__ID); } } AgreeType lhsType = getAgreeType(namedEl); AgreeType rhsType = getAgreeType(expr); if (!lhsType.equals(rhsType)) { error(assign, "The left hand side of the assignment statement is of type '" + lhsType + "' but the right hand side is of type '" + rhsType + "'"); } AgreeContract contract = EcoreUtil2.getContainerOfType(assign, AgreeContract.class); if (contract != null) { for (SpecStatement spec : contract.getSpecs()) { if (spec instanceof AssignStatement && spec != assign) { NamedElement otherEl = ((AssignStatement) spec).getId().getBase(); if (otherEl.equals(namedEl)) { error(spec, "Mulitiple assignments to variable '" + namedEl.getName() + "'"); error(assign, "Mulitiple assignments to variable '" + namedEl.getName() + "'"); } } } } } @Check(CheckType.FAST) public void checkArg(Arg arg) { Type type = arg.getType(); if (type instanceof PrimType) { PrimType primType = (PrimType) type; String strType = primType.getString(); String rangeLow = primType.getRangeLow(); String rangeHigh = primType.getRangeHigh(); if (rangeLow != null && rangeHigh != null) { // this is a ranged argument. It can show up only in an equation statement EObject container = arg.eContainer(); if (!(container instanceof EqStatement || container instanceof InputStatement)) { error(arg, "Ranged arguments can appear only in equation statements or agree_input statements"); } boolean rangeLowDot = rangeLow.contains("."); boolean rangeHighDot = rangeHigh.contains("."); if (rangeLowDot != rangeHighDot) { error(arg, "The range intervals are of differing types"); } if (strType.equals("int") && (rangeLowDot || rangeHighDot)) { error(arg, "Ranged variable of type 'int' contains a 'real' value in its interval"); } if (strType.equals("real") && (!rangeLowDot || !rangeHighDot)) { error(arg, "Ranged variable of type 'real' contains an 'int' value in its interval"); } float low = Float.valueOf(rangeLow); float high = Float.valueOf(rangeHigh); low *= primType.getLowNeg() == null ? 1.0 : -1.0; high *= primType.getHighNeg() == null ? 1.0 : -1.0; if (low >= high) { error(arg, "The low value of the interval is greater than or equal to the high end"); } } } } @Check(CheckType.FAST) public void checkCalenStatement(CalenStatement calen) { Classifier container = calen.getContainingClassifier(); if (!(container instanceof ComponentImplementation)) { error(calen, "Calendar statements can appear only in component implementations"); return; } for (int index = 0; index < calen.getEls().size(); ++index) { NamedElement el = calen.getEls().get(index); if (!(el instanceof Subcomponent) || !((Subcomponent) el).getContainingComponentImpl().equals(container)) { error("Element '" + el.getName() + "' is not a subcomponent of '" + container.getName() + "'", calen, AgreePackage.Literals.CALEN_STATEMENT__ELS, index); } } } @Check(CheckType.FAST) public void checkFloorCast(FloorCast floor) { if (isInLinearizationBody(floor)) { error(floor, "'event' expressions not allowed in linearization body expressions"); return; } AgreeType exprType = getAgreeType(floor.getExpr()); if (!matches(REAL, exprType)) { error(floor, "Argument of floor cast is of type '" + exprType.toString() + "' but must be of type 'real'"); } } @Check(CheckType.FAST) public void checkRealCast(RealCast real) { if (isInLinearizationBody(real)) { error(real, "'event' expressions not allowed in linearization body expressions"); return; } AgreeType exprType = getAgreeType(real.getExpr()); if (!matches(INT, exprType)) { error(real, "Argument of real cast is of type '" + exprType.toString() + "' but must be of type 'int'"); } } @Check(CheckType.FAST) public void checkEventExpr(EventExpr event) { if (isInLinearizationBody(event)) { error(event, "'event' expressions not allowed in linearization body expressions"); return; } NestedDotID nestId = event.getId(); NamedElement namedEl = getFinalNestId(nestId); if (!(namedEl instanceof EventPort || namedEl instanceof EventDataPort)) { error(event, "Argument of event expression must be an event port or event data port"); } } @Check(CheckType.FAST) public void checkLatchedExpr(LatchedExpr latched) { // get container EObject container = latched.eContainer(); AgreeContract contract = null; while (!(container instanceof ComponentClassifier)) { if (container instanceof AgreeContract) { contract = (AgreeContract) container; } container = container.eContainer(); } if (container instanceof ComponentImplementation) { boolean foundLatchedStatement = false; for (SpecStatement spec : contract.getSpecs()) { if (spec instanceof LatchedStatement) { foundLatchedStatement = true; break; } } if (!foundLatchedStatement) { error(latched, "Latched expressions can appear only in component implementations " + "that contain a latched synchrony statement"); } } else { error(latched, "Latched expressions can appear only in component implementations"); } Expr expr = latched.getExpr(); NestedDotID nestId = null; if (expr instanceof NestedDotID) { nestId = (NestedDotID) expr; } else if (expr instanceof EventExpr) { EventExpr eventExpr = (EventExpr) expr; nestId = eventExpr.getId(); } if (nestId != null) { NamedElement namedEl = getFinalNestId(nestId); if ((namedEl instanceof DataPort) && ((DataPort) namedEl).isIn()) { return; } else if ((namedEl instanceof EventDataPort) && ((EventDataPort) namedEl).isIn()) { return; } else { // check to see if it is an "agree_input" EObject namedElContainer = namedEl.eContainer(); if (namedElContainer instanceof InputStatement) { return; } } } error(latched, "Latched expressions are valid only for input data ports or event expressions over input event data ports"); } @Check(CheckType.FAST) public void checkSynchStatement(SynchStatement sync) { Classifier container = sync.getContainingClassifier(); if (!(container instanceof ComponentImplementation)) { error(sync, "Synchrony statements can appear only in component implementations"); } if (sync instanceof CalenStatement || sync instanceof MNSynchStatement || sync instanceof AsynchStatement || sync instanceof LatchedStatement) { return; } // TODO: I'm pretty sure INT_LITs are always positive anyway. // So this may be redundant if (Integer.valueOf(sync.getVal()) < 0) { error(sync, "The value of synchrony statments must be positive"); } String val2 = sync.getVal2(); if (val2 != null) { if (Integer.valueOf(val2) <= 0) { error(sync, "The second value of a synchrony statment must be greater than zero"); } if (Integer.valueOf(sync.getVal()) <= Integer.valueOf(val2)) { error(sync, "The second value of a synchrony argument must be less than the first"); } } } @Check(CheckType.FAST) public void checkMNSynchStatement(MNSynchStatement sync) { ComponentImplementation compImpl = sync.getContainingComponentImpl(); if (compImpl == null) { // This should already be checked by checkSynchStatement return; } compImpl.getAllSubcomponents(); // this should be enforced by the parser, but we check to avoid an // index out of bounds exception whilst the user is editing... int expectedSize = sync.getMax().size(); if (expectedSize != sync.getMin().size() || expectedSize != sync.getComp1().size() || expectedSize != sync.getComp2().size()) { error(sync, "Mismatched number of subcomponents and timing ranges: " + sync.getComp1().size() + " left subcomponents, " + sync.getComp2().size() + " right subcomponents, " + sync.getMin().size() + " time minima, and " + sync.getMax().size() + " time maxima."); return; } for (int i = 0; i < expectedSize; i++) { NamedElement comp1 = sync.getComp1().get(i); NamedElement comp2 = sync.getComp2().get(i); String maxStr = sync.getMax().get(i); String minStr = sync.getMin().get(i); if (!(comp1 instanceof Subcomponent) || !((Subcomponent) comp1).getContainingComponentImpl().equals(compImpl)) { error("Element '" + comp1.getName() + "' is not a subcomponent of '" + compImpl.getName() + "'", sync, AgreePackage.Literals.MN_SYNCH_STATEMENT__COMP1, i); } if (!(comp2 instanceof Subcomponent) || !((Subcomponent) comp2).getContainingComponentImpl().equals(compImpl)) { error("Element '" + comp2.getName() + "' is not a subcomponent of '" + compImpl.getName() + "'", sync, AgreePackage.Literals.MN_SYNCH_STATEMENT__COMP2, i); } int max = Integer.valueOf(maxStr); int min = Integer.valueOf(minStr); if (max < 1 || min < 1) { error(sync, "Quasi-synchronous values must be greater than zero"); } if (min > max) { error("Left hand side quasi-synchronous values must be greater than the right hand side"); } } } @Check(CheckType.FAST) public void checkAssume(AssumeStatement assume) { Classifier comp = assume.getContainingClassifier(); if (!(comp instanceof ComponentType)) { error(assume, "Assume statements are allowed only in component types"); } // the expression could be null if a pattern is used Expr expr = assume.getExpr(); if (expr != null) { AgreeType exprType = getAgreeType(expr); if (!matches(BOOL, exprType)) { error(assume, "Expression for assume statement is of type '" + exprType.toString() + "' but must be of type 'bool'"); } } } @Check(CheckType.FAST) public void checkInitialStatement(InitialStatement statement) { Classifier comp = statement.getContainingClassifier(); if (!(comp instanceof ComponentType)) { error(statement, "Initial statements are allowed only in component types"); } AgreeType exprType = getAgreeType(statement.getExpr()); if (!matches(BOOL, exprType)) { error(statement, "Expression for 'initially' statement is of type '" + exprType.toString() + "' but must be of type 'bool'"); } } @Check(CheckType.FAST) public void checkLift(LiftStatement lift) { NestedDotID dotId = lift.getSubcomp(); if (dotId.getSub() != null) { error(lift, "Lift statements can be applied only to direct subcomponents." + "Place a lift statement in the subcomponents contract for heavy lifting"); } NamedElement namedEl = dotId.getBase(); if (namedEl != null) { if (!(namedEl instanceof SubcomponentImpl)) { error(lift, "Lift statements must apply to subcomponent implementations. '" + namedEl.getName() + "' is not a subcomponent."); } // } else { // SubcomponentImpl subImpl = (SubcomponentImpl) namedEl; // if (subImpl.getComponentImplementation() == null) { // error(lift, "Lift statements must apply to subcomponent implementations. '" // + namedEl.getName() // + "' is a subcomponent type, not a subcomponent implementation."); // } // } } } @Check(CheckType.FAST) public void checkAssert(AssertStatement asser) { Classifier comp = asser.getContainingClassifier(); if (!(comp instanceof ComponentImplementation)) { error(asser, "Assert statements are allowed only in component implementations."); } // the expression could be null if a pattern is used Expr expr = asser.getExpr(); if (expr != null) { AgreeType exprType = getAgreeType(expr); if (!matches(BOOL, exprType)) { error(asser, "Expression for assert statement is of type '" + exprType.toString() + "' but must be of type 'bool'"); } } warning(asser, "We highly discourage the use of assert statements. " + "They can easily lead to inconsistent or unrealizable systems. " + "Note that our realizability check does not verify that component " + "assertions are realizable. It is likely that you can specify the " + "behavior you want by changing the subcomponent contracts or " + "by using assignment statements."); } @Check(CheckType.FAST) public void checkNestedDotID(NestedDotID dotId) { NestedDotID sub = dotId.getSub(); if (sub != null) { if (sub.getBase() instanceof Property) { error(sub, "You cannot reference AADL properties this way." + " Use a \"Get_Property\" statement."); } } } @Check(CheckType.FAST) public void checkAADLEnumerator(AADLEnumerator aadlEnum) { NestedDotID enumType = aadlEnum.getEnumType(); NamedElement enumTypeNamedElement = getFinalNestId(enumType); if (!AgreeAADLEnumerationUtils.isAADLEnumeration(enumTypeNamedElement)) { error(enumType, "AADL Enumerations must refer to a Data Type with \"Enum\" data representation " + "property and have an \"Enumerators\' property value list."); } else { String enumVal = aadlEnum.getValue(); List enumerators = AgreeAADLEnumerationUtils .getEnumerators((ComponentClassifier) enumTypeNamedElement).stream() .map(pe -> ((org.osate.aadl2.StringLiteral) pe).getValue()).collect(Collectors.toList()); if (!enumerators.stream().anyMatch(ev -> ev.equalsIgnoreCase(enumVal))) { error(aadlEnum, "AADL Enumeration " + enumTypeNamedElement.getQualifiedName() + " does not have an enumeration value " + enumVal); } } } @Check(CheckType.FAST) public void checkGuarantee(GuaranteeStatement guar) { Classifier comp = guar.getContainingClassifier(); if (!(comp instanceof ComponentType)) { error(guar, "Guarantee statements are allowed only in component types"); } // the expression could be null if a pattern is used Expr expr = guar.getExpr(); if (expr != null) { AgreeType exprType = getAgreeType(expr); if (!matches(BOOL, exprType)) { error(guar, "Expression for guarantee statement is of type '" + exprType.toString() + "' but must be of type 'bool'"); } } } public void checkExprIsIdentifier(Expr expr) { if (!(expr instanceof NestedDotID)) { error(expr, "Patterns can contain only identifiers (not general expressions)"); } else { if (((NestedDotID) expr).getSub() != null) { error(expr, "Patterns can contain only identifiers (not general expressions)"); } } } @Check(CheckType.FAST) public void checkPeriodicStatement(PeriodicStatement statement) { Expr event = statement.getEvent(); Expr jitter = statement.getJitter(); Expr period = statement.getPeriod(); checkExprIsIdentifier(event); AgreeType eventType = getAgreeType(event); if (!matches(BOOL, eventType)) { error(event, "Expression is of type '" + eventType + "' but must be of type 'bool'"); } if (jitter != null) { if (!(jitter instanceof RealLitExpr || isConst(jitter))) { error(jitter, "The specified jitter must be a real literal"); } else { Double val = getRealConstVal(jitter); if (val < 0) { error(jitter, "The specified jitter must be positive"); } } } if (!(period instanceof RealLitExpr || isConst(period))) { error(period, "The specified period must be a real literal"); } else { Double val = getRealConstVal(period); if (val < 0) { error(period, "The specified period must be positive"); } } } private double getRealConstVal(Expr expr) { if (expr instanceof RealLitExpr) { RealLitExpr realLit = (RealLitExpr) expr; return Double.valueOf(realLit.getVal()); } else if (expr instanceof NestedDotID) { NestedDotID id = (NestedDotID) expr; NamedElement finalId = getFinalNestId(id); if (finalId instanceof ConstStatement) { ConstStatement constState = (ConstStatement) finalId; return getRealConstVal(constState.getExpr()); } } throw new IllegalArgumentException("not constant or literal value evalued"); } @Check(CheckType.FAST) public void checkSporadicStatement(SporadicStatement statement) { Expr event = statement.getEvent(); Expr jitter = statement.getJitter(); Expr iat = statement.getIat(); checkExprIsIdentifier(event); AgreeType eventType = getAgreeType(event); if (!matches(BOOL, eventType)) { error(event, "Expression is of type '" + eventType + "' but must be of type 'bool'"); } if (jitter != null) { if (!(jitter instanceof RealLitExpr || isConst(jitter))) { error(jitter, "The specified jitter must be a real literal"); } else { Double val = getRealConstVal(jitter); if (val < 0) { error(jitter, "The specified jitter must be positive"); } } } if (!(iat instanceof RealLitExpr || isConst(iat))) { error(iat, "The specified interarrival time must be a real literal"); } else { Double val = getRealConstVal(iat); if (val < 0) { error(iat, "The specified interarrival time must be positive"); } } } @Check(CheckType.FAST) public void checkWhenHoldsStatement(WhenHoldsStatement when) { Expr condition = when.getCondition(); Expr event = when.getEvent(); TimeInterval condInterval = when.getConditionInterval(); checkExprIsIdentifier(condition); checkExprIsIdentifier(event); if (condInterval != null) { Expr lowExpr = condInterval.getLow(); if (lowExpr instanceof RealLitExpr) { RealLitExpr realExpr = (RealLitExpr) lowExpr; if (!realExpr.getVal().equals("0.0")) { error(lowExpr, "The lower bound of this interval must be zero"); } } } else { error(when, "Statement most of a cause interval"); } AgreeType type = getAgreeType(condition); if (!matches(BOOL, type)) { error(condition, "The condition of a when statement is of type '" + type + "'" + " but must be of type 'bool'"); } type = getAgreeType(event); if (!matches(BOOL, type)) { error(event, "The effect of a when statement is of type '" + type + "'" + " but must be of type 'bool'"); } } @Check(CheckType.FAST) public void checkWhenOccursStatment(WhenOccursStatment when) { Expr condition = when.getCondition(); Expr event = when.getEvent(); Expr times = when.getTimes(); checkExprIsIdentifier(condition); checkExprIsIdentifier(event); AgreeType type = getAgreeType(condition); if (!matches(BOOL, type)) { error(condition, "The condition of the 'when' statement is of type '" + type + "'" + " but must be of type 'bool'"); } type = getAgreeType(event); if (!matches(BOOL, type)) { error(event, "The effect of the 'when' statement is of type '" + type + "'" + " but must be of type 'bool'"); } type = getAgreeType(times); if (!matches(INT, type)) { error(event, "The 'times' of the 'when' statement is of type '" + type + "'" + " but must be of type 'int'"); } } @Check(CheckType.FAST) public void checkWheneverOccursStatement(WheneverOccursStatement whenever) { Expr cause = whenever.getCause(); Expr effect = whenever.getEffect(); checkExprIsIdentifier(cause); checkExprIsIdentifier(effect); AgreeType type = getAgreeType(cause); if (!matches(BOOL, type)) { error(cause, "The cause of the 'whenever' statement is of type '" + type + "' " + "but must be of type 'bool'"); } type = getAgreeType(effect); if (!matches(BOOL, type)) { error(effect, "The effect of the 'whenever' statement is of type '" + type + "' " + "but must be of type 'bool'"); } } @Check(CheckType.FAST) public void checkWheneverBecomesTrueStatement(WheneverBecomesTrueStatement whenever) { Expr cause = whenever.getCause(); Expr effect = whenever.getEffect(); checkExprIsIdentifier(cause); checkExprIsIdentifier(effect); AgreeType type = getAgreeType(cause); if (!matches(BOOL, type)) { error(cause, "The cause of the 'whenever' statement is of type '" + type + "' " + "but must be of type 'bool'"); } type = getAgreeType(effect); if (!matches(BOOL, type)) { error(effect, "The effect of the 'whenever' statement is of type '" + type + "' " + "but must be of type 'bool'"); } } @Check(CheckType.FAST) public void checkWheneverHoldsStatement(WheneverHoldsStatement whenever) { Expr cause = whenever.getCause(); Expr effect = whenever.getEffect(); checkExprIsIdentifier(cause); checkExprIsIdentifier(effect); AgreeType type = getAgreeType(cause); if (!matches(BOOL, type)) { error(cause, "The cause of the 'whenever' statement is of type '" + type + "' " + "but must be of type 'bool'"); } type = getAgreeType(effect); if (!matches(BOOL, type)) { error(effect, "The effect of the 'whenever' statement is of type '" + type + "' " + "but must be of type 'bool'"); } } @Check(CheckType.FAST) public void checkWheneverImpliesStatement(WheneverImpliesStatement whenever) { Expr cause = whenever.getCause(); Expr lhs = whenever.getLhs(); Expr rhs = whenever.getRhs(); checkExprIsIdentifier(cause); checkExprIsIdentifier(lhs); checkExprIsIdentifier(rhs); AgreeType type = getAgreeType(cause); if (!matches(BOOL, type)) { error(cause, "The cause of the 'whenever' statement is of type '" + type + "' " + "but must be of type 'bool'"); } type = getAgreeType(lhs); if (!matches(BOOL, type)) { error(lhs, "The left hand side of the 'implies' of the 'whenever' statement is of type '" + type + "' " + "but must be of type 'bool'"); } type = getAgreeType(rhs); if (!matches(BOOL, type)) { error(lhs, "The rhs hand side of the 'implies' of the 'whenever' statement is of type '" + type + "' " + "but must be of type 'bool'"); } } @Check(CheckType.FAST) public void checkTimeInterval(TimeInterval interval) { Expr lower = interval.getLow(); Expr higher = interval.getHigh(); // AgreeType lowerType = getAgreeType(lower); // AgreeType higherType = getAgreeType(higher); if (!(lower instanceof RealLitExpr || isConst(lower))) { error(lower, "Lower interval must be a real valued literal"); } if (!(higher instanceof RealLitExpr || isConst(higher))) { error(higher, "higher interval must be a real valued literal"); } } protected boolean isConst(Expr expr) { if (expr instanceof NestedDotID) { NestedDotID id = (NestedDotID) expr; NamedElement finalId = getFinalNestId(id); return (finalId instanceof ConstStatement); } else if (expr instanceof AADLEnumerator) { return true; } return false; } @Check(CheckType.FAST) public void checkTimeRise(TimeRiseExpr timeRise) { NestedDotID id = timeRise.getId(); checkTimeExpr(timeRise, id); } @Check(CheckType.FAST) public void checkTimeFall(TimeFallExpr timeFall) { NestedDotID id = timeFall.getId(); checkTimeExpr(timeFall, id); } @Check(CheckType.FAST) public void checkTimeOf(TimeOfExpr timeOf) { NestedDotID id = timeOf.getId(); checkTimeExpr(timeOf, id); } public void checkTimeExpr(EObject expr, NestedDotID id) { AgreeType type = getAgreeType(id); if (!matches(type, BOOL)) { error(expr, "Time functions can be applied only to Boolean identifiers"); } if (id.getSub() != null) { error(expr, "Time functions can be applied only to identifiers"); } } @Check(CheckType.FAST) public void checkLemma(LemmaStatement lemma) { Classifier comp = lemma.getContainingClassifier(); if (!(comp instanceof ComponentImplementation)) { error(lemma, "Lemma statements are allowed only in component implementations and nodes"); } Expr expr = lemma.getExpr(); if (expr != null) { AgreeType exprType = getAgreeType(expr); if (!matches(BOOL, exprType)) { error(lemma, "Expression for lemma statement is of type '" + exprType.toString() + "' but must be of type 'bool'"); } } } @Check(CheckType.FAST) public void checkUnaryExpr(UnaryExpr unaryExpr) { AgreeType typeRight = getAgreeType(unaryExpr.getExpr()); String op = unaryExpr.getOp(); switch (op) { case "-": if (!matches(INT, typeRight) && !matches(REAL, typeRight)) { error(unaryExpr, "right side of unary expression '" + op + "' is of type '" + typeRight + "' but must be of type 'int' or 'real'"); } break; case "not": if (!matches(BOOL, typeRight)) { error(unaryExpr, "right side of unary expression '" + op + "' is of type '" + typeRight + "' but must be of type 'bool'"); } break; default: assert (false); } } @Check(CheckType.FAST) public void checkPropertyStatement(PropertyStatement propStat) { AnnexLibrary library = EcoreUtil2.getContainerOfType(propStat, AnnexLibrary.class); if (library != null) { error(propStat, "Property statments are allowed only in component annexes"); } AgreeType exprType = getAgreeType(propStat.getExpr()); if (!matches(BOOL, exprType)) { error(propStat, "Property statement '" + propStat.getName() + "' is of type '" + exprType + "' but must be of type 'bool'"); } } @Check(CheckType.FAST) public void checkInputStatement(InputStatement input) { ComponentType comp = EcoreUtil2.getContainerOfType(input, ComponentType.class); if (comp == null) { error(input, "Input statements are allowed only in component types"); } } @Check(CheckType.FAST) public void checkRecordUpdateExpr(RecordUpdateExpr upExpr) { if (isInLinearizationBody(upExpr)) { error(upExpr, "Record update expressions not allowed in linearization body expression"); return; } // The parser should enforce this. but we do this to avoid exceptions // running the check whilst the user is editing... if (upExpr.getArgs().isEmpty()) { error(upExpr, "Record update expression must contain at least one arg-expr pair."); return; } EList args = upExpr.getArgs(); EList argExprs = upExpr.getArgExpr(); // Figure out the type of the record being updated // It should be either a subcomponent of a DataImplementation or a // field of a record. // TODO: can it be a feature of a FeatureGroup? // Note: This message looks to be somewhat strange in that it uses // the arguments to the update expression to determine the type of the // record to be updated. However, this should be enforced by the way // that the scoping works. NamedElement arg0 = upExpr.getArgs().get(0); EObject arg0Container = arg0.eContainer(); if (arg0Container instanceof DataImplementation) { DataImplementation dataImpl = (DataImplementation) arg0Container; dataImplCycleCheck(dataImpl, upExpr); int argIndex = 0; for (NamedElement arg : args) { if (!dataImpl.getAllSubcomponents().contains(arg)) { error("Argument '" + arg.getName() + "' is not a subcomponent of '" + dataImpl.getQualifiedName() + "'", upExpr, AgreePackage.Literals.RECORD_UPDATE_EXPR__ARGS, argIndex); } ++argIndex; } } else if (arg0Container instanceof RecordDefExpr) { RecordDefExpr recordDef = (RecordDefExpr) arg0Container; int argIndex = 0; for (NamedElement arg : args) { if (!recordDef.getArgs().contains(arg)) { error("Argument '" + arg.getName() + "' is not a subcomponent of '" + recordDef.getQualifiedName() + "'", upExpr, AgreePackage.Literals.RECORD_UPDATE_EXPR__ARGS, argIndex); } ++argIndex; } } else { if (!arg0.eIsProxy()) { error("Record to be updated must be a data implementation or AGREE record type. " + "Found type '" + getAgreeType(upExpr.getRecord()).toString() + "'.", upExpr, AgreePackage.Literals.RECORD_UPDATE_EXPR__RECORD, -1); } return; } // this should be enforced by the parser, but we check to avoid an // index out of bounds exception whilst the user is editing... if (args.size() != argExprs.size()) { error(upExpr, "Mismatched count of arguments and expressions."); return; } for (int i = 0; i < args.size(); i++) { NamedElement arg = args.get(i); Expr argExpr = argExprs.get(i); AgreeType argType = getAgreeType(arg); AgreeType argExprType = getAgreeType(argExpr); if (!matches(argType, argExprType)) { error(argExpr, "the update field is of type '" + argType + "', but the expression is of type '" + argExprType + "'"); } } } @Check(CheckType.FAST) public void checkRecordType(RecordType recType) { NestedDotID recId = recType.getRecord(); NamedElement finalId = getFinalNestId(recId); if (!(finalId instanceof DataImplementation) && !(finalId instanceof RecordDefExpr) && !(finalId instanceof DataType) && !(finalId instanceof EnumStatement)) { error(recType, "types must be record definition, data implementation, enumeration, or datatype"); } if (finalId instanceof DataImplementation) { AgreeType agreeType = getAgreeType((DataImplementation) finalId); if (agreeType.equals(AgreeType.ERROR)) { error(recType, "Data Implementations with no subcomponents must extend" + " a Base_Type that AGREE can reason about."); return; } if (((DataImplementation) finalId).getAllSubcomponents().size() != 0) { if (agreeType.equals(AgreeType.BOOL) || agreeType.equals(AgreeType.INT) || agreeType.equals(AgreeType.REAL)) { error(finalId, "Data implementations with subcomponents cannot be" + " interpreted by AGREE if they extend Base_Types"); } } dataImplCycleCheck(recId); return; } if (finalId instanceof DataType) { AgreeType agreeType = getAgreeType((ComponentClassifier) finalId); if (agreeType.equals(AgreeType.ERROR)) { error(recType, "AADL Datatypes must extend" + " a Base_Type that AGREE can reason about."); return; } } } @Check(CheckType.FAST) public void checkRecordExpr(RecordExpr recExpr) { NestedDotID recType = recExpr.getRecord(); List defArgs = getArgNames(recType); EList exprArgs = recExpr.getArgs(); EList argExprs = recExpr.getArgExpr(); NestedDotID recId = recExpr.getRecord(); NamedElement finalId = getFinalNestId(recId); if (!(finalId instanceof DataImplementation) && !(finalId instanceof RecordDefExpr)) { error(recId, "types must be record definition or data implementation"); } if (finalId instanceof DataImplementation) { dataImplCycleCheck(recId); } if (exprArgs.size() != defArgs.size()) { error(recExpr, "Incorrect number of arguments"); return; } for (NamedElement argDefName : defArgs) { boolean foundArg = false; for (NamedElement argExprEl : exprArgs) { if (argExprEl.getName().equals(argDefName.getName())) { foundArg = true; break; } } if (!foundArg) { error(recExpr, "No assignment to defined variable '" + argDefName + "' in record expression."); } } // check typing Map argNameMap = getArgNameMap(recType); for (int i = 0; i < recExpr.getArgs().size(); i++) { NamedElement actArg = recExpr.getArgs().get(i); String actArgName = actArg.getName(); AgreeType defType = argNameMap.get(actArgName); AgreeType exprType = getAgreeType(argExprs.get(i)); if (!matches(defType, exprType)) { error(recExpr, "The expression assigned to '" + actArgName + "' does not match its definition type of '" + defType + "'"); } } } private List getArgNames(NestedDotID recId) { NamedElement rec = getFinalNestId(recId); List names = new ArrayList<>(); if (rec instanceof RecordDefExpr) { RecordDefExpr recDef = (RecordDefExpr) rec; for (Arg arg : recDef.getArgs()) { names.add(arg); } } else if (rec instanceof DataImplementation) { DataImplementation dataImpl = (DataImplementation) rec; for (Subcomponent sub : dataImpl.getAllSubcomponents()) { names.add(sub); } } else { error(recId, "Record type '" + rec.getName() + "' must be a feature group or a record type definition"); } return names; } private Map getArgNameMap(NestedDotID recId) { NamedElement rec = getFinalNestId(recId); Map typeMap = new HashMap<>(); if (rec instanceof RecordDefExpr) { RecordDefExpr recDef = (RecordDefExpr) rec; for (Arg arg : recDef.getArgs()) { typeMap.put(arg.getName(), getAgreeType(arg)); } } else if (rec instanceof DataImplementation) { DataImplementation dataImpl = (DataImplementation) rec; for (Subcomponent sub : dataImpl.getAllSubcomponents()) { typeMap.put(sub.getName(), getAgreeType(sub)); } } else { error(recId, "Record type '" + rec.getName() + "' must be a feature group or a record type definition"); } return typeMap; } // private List getArgTypes(NestedDotID recId){ // // NamedElement rec = getFinalNestId(recId); // List types = new ArrayList(); // // if(rec instanceof RecordDefExpr){ // RecordDefExpr recDef = (RecordDefExpr)rec; // for(Arg arg : recDef.getArgs()){ // types.add(getAgreeType(arg.getType())); // } // }else if(rec instanceof FeatureGroupType){ // FeatureGroupType featGroup = (FeatureGroupType)rec; // for(Feature feat : featGroup.getAllFeatures()){ // types.add(getAgreeType(feat)); // } // } // // return types; // } private void dataImplCycleCheck(NestedDotID dataID) { NamedElement finalId = getFinalNestId(dataID); DataImplementation dataImpl = (DataImplementation) finalId; dataImplCycleCheck(dataImpl, dataID); } private void dataImplCycleCheck(DataImplementation dataImpl, EObject errorSource) { Set dataClosure = new HashSet<>(); Set prevClosure = null; for (Subcomponent sub : dataImpl.getAllSubcomponents()) { ComponentImplementation subImpl = sub.getComponentImplementation(); if (subImpl != null) { dataClosure.add((DataImplementation) subImpl); } } do { prevClosure = new HashSet<>(dataClosure); for (DataImplementation subImpl : prevClosure) { if (subImpl == dataImpl) { error(errorSource, "The component implementation '" + dataImpl.getName() + "' has a cyclic definition. This cannot be reasoned about by AGREE."); break; } for (Subcomponent subSub : subImpl.getAllSubcomponents()) { ComponentImplementation subSubImpl = subSub.getComponentImplementation(); if (subSubImpl != null) { dataClosure.add((DataImplementation) subSubImpl); } } } } while (!prevClosure.equals(dataClosure)); } @Check(CheckType.FAST) public void checkRecordDefExpr(RecordDefExpr recordDef) { Set recordClosure = new HashSet<>(); Set prevClosure = null; for (Arg arg : recordDef.getArgs()) { Type type = arg.getType(); if (type instanceof RecordType) { NestedDotID subRec = ((RecordType) type).getRecord(); NamedElement finalId = getFinalNestId(subRec); // if (!(finalId instanceof DataImplementation) && !(finalId instanceof RecordDefExpr)) { // error(type, "types must be record definition or data implementation"); // return; // } if (finalId instanceof RecordDefExpr) { recordClosure.add((RecordDefExpr) finalId); } else if (finalId instanceof DataImplementation) { dataImplCycleCheck(subRec); } } } do { prevClosure = new HashSet<>(recordClosure); for (RecordDefExpr subRecDef : prevClosure) { if (subRecDef == recordDef) { error(recordDef, "The definition of type '" + recordDef.getName() + "' is involved in a cyclic definition"); break; } for (Arg arg : subRecDef.getArgs()) { Type type = arg.getType(); if (type instanceof RecordType) { NestedDotID subRecId = ((RecordType) type).getRecord(); NamedElement subFinalEl = getFinalNestId(subRecId); if (subFinalEl instanceof RecordDefExpr) { recordClosure.add((RecordDefExpr) subFinalEl); } } } } } while (!prevClosure.equals(recordClosure)); } @Check(CheckType.FAST) public void checkConstStatement(ConstStatement constStat) { Type type = constStat.getType(); AgreeType expected = getAgreeType(type); AgreeType actual = getAgreeType(constStat.getExpr()); if (!matches(expected, actual)) { error(constStat, "The assumed type of constant statement '" + constStat.getName() + "' is '" + expected + "' but the actual type is '" + actual + "'"); } // check for constant cycles Set constClosure = new HashSet<>(); Set prevClosure; constClosure.add(constStat); // quick and dirty cycle check do { prevClosure = new HashSet<>(constClosure); for (ConstStatement constFrontElem : prevClosure) { List nestIds = EcoreUtil2.getAllContentsOfType(constFrontElem, NestedDotID.class); for (NestedDotID nestId : nestIds) { while (nestId != null) { NamedElement base = nestId.getBase(); if (base instanceof ConstStatement) { ConstStatement closConst = (ConstStatement) base; if (closConst.equals(constStat)) { error(constStat, "The expression for constant statment '" + constStat.getName() + "' is part of a cyclic definition"); break; } constClosure.add(closConst); } nestId = nestId.getSub(); } } } } while (!prevClosure.equals(constClosure)); for (Expr e : EcoreUtil2.getAllContentsOfType(constStat.getExpr(), Expr.class)) { if (!isPossibleConstant(e)) { error(e, "Non-constant expression in constant declaration"); return; } } } protected AgreeType getAgreeType(Type type) { String typeName = null; if (type instanceof PrimType) { typeName = ((PrimType) type).getString(); return new AgreeType(typeName); } else { RecordType recType = (RecordType) type; NestedDotID recId = recType.getRecord(); return getNestIdAsType(recId); } } private AgreeType getNestIdAsType(NestedDotID recId) { String typeName = ""; NamedElement recEl = getFinalNestId(recId); EObject aadlPack = recEl.eContainer(); while (!(aadlPack instanceof AadlPackage)) { aadlPack = aadlPack.eContainer(); } String packName = ((AadlPackage) aadlPack).getName(); if (recEl instanceof RecordDefExpr) { EObject component = recEl.eContainer(); while (!(component instanceof ComponentClassifier) && !(component instanceof AadlPackage)) { component = component.eContainer(); } if (component == aadlPack) { typeName = recEl.getName(); } else { typeName = ((ComponentClassifier) component).getName() + "." + recEl.getName(); } } else if (recEl instanceof DataImplementation) { AgreeType nativeType = getNativeType((DataImplementation) recEl); if (nativeType != null) { return nativeType; } typeName = recEl.getName(); } else if (recEl instanceof DataType) { return getAgreeType((ComponentClassifier) recEl); } else if (recEl instanceof EnumStatement) { typeName = recEl.getFullName(); } typeName = packName + "::" + typeName; return new AgreeType(typeName); } public boolean isPossibleConstant(Expr e) { if (e instanceof PrevExpr || e instanceof PreExpr) { return false; } if (e instanceof BinaryExpr) { if (((BinaryExpr) e).getOp().equals("->")) { return false; } } if (e instanceof NestedDotID) { if (EcoreUtil2.getContainerOfType(e, GetPropertyExpr.class) != null) { return true; } NamedElement base = getFinalNestId((NestedDotID) e); if (base instanceof DataImplementation || base instanceof ConstStatement || base instanceof RecordExpr || base instanceof DataSubcomponent) { return true; } if (base instanceof DataType && e.eContainer() instanceof AADLEnumerator) { return true; } return false; } return true; } @Check(CheckType.FAST) public void checkNamedElement(NamedElement namedEl) { // check for namespace collision in component types of component // implementations // and for collisions between subcomponent and feature names EObject container = namedEl.eContainer(); if (container == null) { return; } if (container instanceof RecordDefExpr || container instanceof NodeDefExpr) { // don't care about arguments to recDefs and nodeDefs // TODO: perhaps we can ignore all arguments? return; } while (!(container instanceof AadlPackage || container instanceof ComponentImplementation || container instanceof ComponentType)) { container = container.eContainer(); } ComponentImplementation compImpl = null; ComponentType type = null; if (container instanceof ComponentImplementation) { compImpl = (ComponentImplementation) container; type = compImpl.getType(); checkDupNames(namedEl, type, compImpl); } else if (container instanceof ComponentType) { type = (ComponentType) container; } if (type != null) { for (Feature feat : type.getAllFeatures()) { if (namedEl.getName().equals(feat.getName())) { error(feat, "Element of the same name ('" + namedEl.getName() + "') in AGREE Annex in '" + (compImpl == null ? type.getName() : compImpl.getName()) + "'"); error(namedEl, "Feature of the same name ('" + namedEl.getName() + "') in component type"); } } } // check name space collision with enumerated types } private void checkDupNames(NamedElement namedEl, ComponentType type, ComponentImplementation compImpl) { NamedElement match = matchedInAgreeAnnex(type, namedEl.getName()); if (match != null) { error(match, "Element of the same name ('" + namedEl.getName() + "') in component implementation '" + compImpl.getName() + "'"); error(namedEl, "Element of the same name ('" + namedEl.getName() + "') in component type"); } for (Subcomponent sub : compImpl.getAllSubcomponents()) { if (namedEl.getName().equals(sub.getName())) { error(sub, "Element of the same name ('" + namedEl.getName() + "') in AGREE Annex in '" + compImpl.getName() + "'"); error(namedEl, "Subcomponent of the same name ('" + namedEl.getName() + "') in component implementation"); } } } private NamedElement matchedInAgreeAnnex(ComponentClassifier compClass, String name) { for (AnnexSubclause subClause : AnnexUtil.getAllAnnexSubclauses(compClass, AgreePackage.eINSTANCE.getAgreeSubclause())) { if (subClause instanceof AgreeSubclause) { AgreeContract contr = (AgreeContract) subClause.getChildren().get(0); for (EObject obj : contr.getChildren()) { if (obj instanceof NamedElement) { if (name.equals(((NamedElement) obj).getName())) { return (NamedElement) obj; } } } } } return null; } private boolean argsContainRangeValue(List args) { for (Arg arg : args) { Type type = arg.getType(); if (type instanceof PrimType) { PrimType primType = (PrimType) type; if (primType.getRangeHigh() != null || primType.getRangeLow() != null) { return true; } } } return false; } private void checkMultiAssignEq(EObject src, List lhsArgs, Expr rhsExpr) { if (rhsExpr == null) { return; } if (lhsArgs.size() == 1) { // we should only need to check for cycles for single equations String name = lhsArgs.get(0).getName(); ExprCycleVisitor cycleVisitor = new ExprCycleVisitor(name); Set cycleObjects = cycleVisitor.doSwitch(rhsExpr); if (cycleObjects == null) { throw new IllegalArgumentException("something went wrong with the cycle checker"); } for (EObject obj : cycleObjects) { error(obj, "Cyclic reference to variable '" + name + "'"); } } if (argsContainRangeValue(lhsArgs)) { error(src, "Equation statements cannot contain a ranged value and a right hand side expression"); } List agreeLhsTypes = typesFromArgs(lhsArgs); List agreeRhsTypes = new ArrayList<>(); if (rhsExpr instanceof FnCallExpr) { NamedElement namedEl = getFinalNestId(((FnCallExpr) rhsExpr).getFn()); if (namedEl instanceof NodeDefExpr) { NodeDefExpr nodeDef = (NodeDefExpr) namedEl; for (Arg var : nodeDef.getRets()) { agreeRhsTypes.add(getAgreeType(var.getType())); } } else if (namedEl instanceof FnDefExpr) { FnDefExpr fnDef = (FnDefExpr) namedEl; agreeRhsTypes.add(getAgreeType(fnDef.getType())); } else { return; // parse error } } else { agreeRhsTypes.add(getAgreeType(rhsExpr)); } if (agreeLhsTypes.size() != agreeRhsTypes.size()) { error(src, "Equation assigns " + agreeLhsTypes.size() + " variables, but right side returns " + agreeRhsTypes.size() + " values"); return; } for (int i = 0; i < agreeLhsTypes.size(); i++) { AgreeType lhsType = agreeLhsTypes.get(i); AgreeType rhsType = agreeRhsTypes.get(i); if (!matches(rhsType, lhsType)) { error(src, "The variable '" + lhsArgs.get(i).getName() + "' on the left side of equation is of type '" + lhsType + "' but must be of type '" + rhsType + "'"); } } // // check for constant cycles // Set eqClosure = new HashSet(); // Set prevClosure; // eqClosure.add(src); // // // quick and dirty cycle check // do { // prevClosure = new HashSet(eqClosure); // for (EObject constFrontElem : prevClosure) { // List nestIds = EcoreUtil2.getAllContentsOfType(constFrontElem, // NestedDotID.class); // for (NestedDotID nestId : nestIds) { // while(nestId != null){ // NamedElement base = nestId.getBase(); // if (base instanceof Arg) { // EObject container = base; // while(!(container instanceof EqStatement) && // !(container instanceof NodeEq)){ // container = container.eContainer(); // } // if (lhsArgs.contains(base)) { // warning(src, // "The expression for eq statment '" + base.getName() // + "' may be part of a cyclic definition"); // break; // } // eqClosure.add(container); // } // nestId = nestId.getSub(); // } // } // } // } while (!prevClosure.equals(eqClosure)); } @Check(CheckType.FAST) public void checkEqStatement(EqStatement eqStat) { AnnexLibrary library = EcoreUtil2.getContainerOfType(eqStat, AnnexLibrary.class); if (library != null) { error(eqStat, "Equation statments are allowed only in component annexes"); } checkMultiAssignEq(eqStat, eqStat.getLhs(), eqStat.getExpr()); } @Check(CheckType.FAST) public void checkNameOverlap(AgreeContract contract) { Set syncs = new HashSet<>(); Set inits = new HashSet<>(); List conns = new ArrayList<>(); // check that there are zero or more synchrony statements for (SpecStatement spec : contract.getSpecs()) { if (spec instanceof SynchStatement) { syncs.add((SynchStatement) spec); } else if (spec instanceof CalenStatement) { syncs.add((CalenStatement) spec); } else if (spec instanceof InitialStatement) { inits.add((InitialStatement) spec); } else if (spec instanceof ConnectionStatement) { conns.add((ConnectionStatement) spec); } } if (syncs.size() > 1) { for (SynchStatement sync : syncs) { error(sync, "Multiple synchrony or calender statements in a single contract"); } } if (inits.size() > 1) { for (InitialStatement init : inits) { error(init, "Multiple initially statements in a single contract"); } } for (int i = 0; i < conns.size(); i++) { ConnectionStatement connStat0 = conns.get(i); NamedElement conn0 = connStat0.getConn(); for (int j = i + 1; j < conns.size(); j++) { ConnectionStatement connStat1 = conns.get(j); NamedElement conn1 = connStat1.getConn(); if (conn0 == null || conn1 == null) { break; } if (conn0.equals(conn1)) { error(connStat0, "Multiple connection overrides for connection: '" + conn0.getName() + "'"); error(connStat1, "Multiple connection overrides for connection: '" + conn1.getName() + "'"); } } } ComponentImplementation ci = EcoreUtil2.getContainerOfType(contract, ComponentImplementation.class); if (ci == null) { return; } Set parentNames = getParentNames(ci); for (AgreeSubclause subclause : EcoreUtil2.getAllContentsOfType(ci, AgreeSubclause.class)) { List es = EcoreUtil2.getAllContentsOfType(subclause, NamedElement.class); for (NamedElement e : es) { if (!(e.eContainer() instanceof NodeDefExpr)) { // ignore elements in node defs if (parentNames.contains(e.getName())) { error(e, e.getName() + " already defined in component type contract"); } } } } } private Set getParentNames(ComponentImplementation ci) { Set result = new HashSet<>(); ComponentType ct = ci.getType(); for (AgreeSubclause subclause : EcoreUtil2.getAllContentsOfType(ct, AgreeSubclause.class)) { List es = EcoreUtil2.getAllContentsOfType(subclause, NamedElement.class); for (NamedElement e : es) { if (!(e.eContainer() instanceof NodeDefExpr || e.eContainer() instanceof LinearizationDefExpr || e.eContainer() instanceof RecordDefExpr)) { result.add(e.getName()); } } } return result; } @Check(CheckType.FAST) public void checkNodeEq(NodeEq nodeEq) { EObject container = nodeEq.eContainer(); NodeBodyExpr containingNodeBodyExpr; NodeDefExpr containingNodeDefExpr; if (container instanceof NodeBodyExpr) { containingNodeBodyExpr = (NodeBodyExpr) container; } else { error(nodeEq, "Node equation must be contained in a node body."); return; } if (container != null) { container = container.eContainer(); } if (container instanceof NodeDefExpr) { containingNodeDefExpr = (NodeDefExpr) container; } else { error(nodeEq, "Node equation must be contained in a node definition."); return; } List locals = containingNodeBodyExpr.getLocs(); List returns = containingNodeDefExpr.getRets(); int lhsIndex = 0; for (Arg lhs : nodeEq.getLhs()) { if (!locals.contains(lhs) && !returns.contains(lhs)) { error("LHS '" + lhs.getName() + "' of node equation must be a node return variable or local variable.", nodeEq, AgreePackage.Literals.NODE_EQ__LHS, lhsIndex); } ++lhsIndex; } checkMultiAssignEq(nodeEq, nodeEq.getLhs(), nodeEq.getExpr()); } @Check(CheckType.FAST) public void checkNodeLemma(NodeLemma nodeLemma) { AgreeType exprType = getAgreeType(nodeLemma.getExpr()); if (!matches(BOOL, exprType)) { error(nodeLemma, "Expression for lemma statement is of type '" + exprType + "' but must be of type 'bool'"); } } @Check(CheckType.FAST) public void checkNodeStmt(NodeStmt nodeStmt) { List dotIds = EcoreUtil2.getAllContentsOfType(nodeStmt, NestedDotID.class); for (NestedDotID dotId : dotIds) { NamedElement id = getFinalNestId(dotId); if (!(id instanceof Arg) && !(id instanceof ConstStatement) && !(id instanceof NodeDefExpr) && !(id instanceof FnDefExpr) && !(id instanceof DataSubcomponent) && !(id instanceof RecordType) && !(id instanceof DataImplementation) && !(id instanceof RecordDefExpr)) { error(dotId, "Only arguments, constants, and node calls allowed within a node"); } } } @Check(CheckType.FAST) public void checkNodeDef(NodeDefExpr nodeDefExpr) { if (nodeDefExpr.getNodeBody() == null) { return; // this will throw a parse error anyway } Map assignMap = new HashMap<>(); for (Arg arg : nodeDefExpr.getRets()) { assignMap.put(arg, 0); } for (Arg arg : nodeDefExpr.getNodeBody().getLocs()) { assignMap.put(arg, 0); } for (NodeStmt stmt : nodeDefExpr.getNodeBody().getStmts()) { if (stmt instanceof NodeEq) { NodeEq eq = (NodeEq) stmt; for (Arg arg : eq.getLhs()) { Integer value = assignMap.get(arg); if (value == null) { error("Equation attempting to assign '" + arg.getName() + "', which is not an assignable value within the node"); return; } else { assignMap.put(arg, value + 1); } } } } for (Map.Entry elem : assignMap.entrySet()) { if (elem.getValue() == 0) { error("Variable '" + elem.getKey().getName() + "' is never assigned by an equation in node '" + nodeDefExpr.getName() + "'"); return; } else if (elem.getValue() > 1) { error("Variable '" + elem.getKey().getName() + "' is assigned multiple times in node '" + nodeDefExpr.getName() + "'"); } } } public static boolean isInLinearizationBody(Expr expr) { boolean result = false; EObject current = expr; while (current != null && current instanceof Expr) { EObject container = current.eContainer(); if (container instanceof LinearizationDefExpr) { result = ((LinearizationDefExpr) container).getExprBody().equals(current); } current = container; } return result; } @Check(CheckType.FAST) public void checkLinearizationDefExpr(LinearizationDefExpr linDefExpr) { // Check that allowable number of formal args are defined if (linDefExpr.getArgs().size() != 1) { error(linDefExpr, "Linearization definitions are limited to functions of one variable."); } // Check that the formal args are all of real type for (Arg arg : linDefExpr.getArgs()) { AgreeType argType = getAgreeType(arg.getType()); if (!matches(argType, REAL)) { error(arg, "Linearizations formal arguments must be of real type, but found type " + argType); } } // Check that the number of domain intervals matches the number of // formal arguments if (linDefExpr.getIntervals().size() != linDefExpr.getArgs().size()) { error(linDefExpr, "Number of formal variables and intervals does not match."); } // If a precision clause is present, it must be a constant expression // of real type Expr precisionExpr = linDefExpr.getPrecision(); if (precisionExpr != null) { AgreeType precisionExprType = getAgreeType(precisionExpr); if (!matches(precisionExprType, REAL)) { error(precisionExpr, "Linearization precision must be of real type, but found type " + precisionExprType); } if (!exprIsConst(precisionExpr)) { error(precisionExpr, "Linearization precision must be constant expression of real type" + ", found non-constant expression."); } } } @Check(CheckType.FAST) public void checkLinearizationInterval(LinearizationInterval linInterval) { final String message = "Linearization interval endpoints must be constant expressions of real type"; Expr startExpr = linInterval.getStart(); Expr endExpr = linInterval.getEnd(); AgreeType startExprType = getAgreeType(startExpr); AgreeType endExprType = getAgreeType(endExpr); // The type of the interval start and end must be of real type if (!matches(startExprType, REAL)) { error(startExpr, message + ", found type " + startExprType + "."); } if (!matches(endExprType, REAL)) { error(endExpr, message + ", found type " + endExprType + "."); } // The interval start and end expressions must be constant if (!exprIsConst(startExpr)) { error(endExpr, message + ", found non-constant expression."); } if (!exprIsConst(startExpr)) { error(endExpr, message + ", found non-constant expression."); } } @Check(CheckType.FAST) public void checkThisExpr(ThisExpr thisExpr) { // these should appear only in Get_Property expressions if (!(thisExpr.eContainer() instanceof GetPropertyExpr)) { error(thisExpr, "'this' expressions can be used only in 'Get_Property' expressions."); } } private static NamedElement namedElementFromIdExpr(Expr expr) { if (expr instanceof NestedDotID) { return getFinalNestId((NestedDotID) expr); } else { assert (expr instanceof ThisExpr); NamedElement component = EcoreUtil2.getContainerOfType(expr, ComponentClassifier.class); NestedDotID nestId = ((ThisExpr) expr).getSubThis(); while (nestId != null) { NamedElement base = nestId.getBase(); if (base instanceof Subcomponent) { component = ((Subcomponent) base).getSubcomponentType(); nestId = nestId.getSub(); } else if (base instanceof FeatureGroup) { while (nestId.getSub() != null) { nestId = nestId.getSub(); assert (nestId.getBase() instanceof Feature); Feature subFeat = (Feature) nestId.getBase(); component = subFeat; } return component; } else { assert (base instanceof DataPort); component = base; return component; } } return component; } } @Check(CheckType.FAST) public void checkGetPropertyExpr(GetPropertyExpr getPropExpr) { Expr component = getPropExpr.getComponent(); AgreeType compType = getAgreeType(component); // AgreeType propType = getAgreeType(propExpr.getName()); NamedElement prop = getPropExpr.getProp(); if (!(component instanceof NestedDotID) && !(component instanceof ThisExpr)) { error("Component must be qualified id or 'this' expression", getPropExpr, AgreePackage.Literals.GET_PROPERTY_EXPR__COMPONENT); } if (!compType.equals(new AgreeType("component"))) { error(getPropExpr.getComponent(), "Expected type component, but found type " + compType); } if (!(prop instanceof Property || prop instanceof PropertyConstant)) { error(getPropExpr.getProp(), "Expected AADL property or property constant"); } if (prop instanceof Property) { NamedElement element = namedElementFromIdExpr(component); final boolean applies = element.acceptsProperty((Property) prop); if (!applies) { error("Property " + ((Property) prop).getQualifiedName() + " does not apply to " + element.getQualifiedName() + ".", getPropExpr, AgreePackage.Literals.GET_PROPERTY_EXPR__PROP); } } } @Check(CheckType.FAST) public void checkPrevExpr(PrevExpr prevExpr) { AgreeType delayType = getAgreeType(prevExpr.getDelay()); AgreeType initType = getAgreeType(prevExpr.getInit()); if (!matches(initType, delayType)) { error(prevExpr, "The first and second arguments of the 'prev' function are of non-matching types '" + delayType + "' and '" + initType + "'"); } if (isInLinearizationBody(prevExpr)) { error(prevExpr, "'prev' expressions are not allowed in linearization body expressions."); } } public void checkInputsVsActuals(FnCallExpr fnCall) { NestedDotID dotId = fnCall.getFn(); // if the id has a 'tag' then it is using a resrved variable String tag = getNestedDotIDTag(dotId); if (tag != null) { error(fnCall, "Use of reserved variable tag: '" + tag + " does not make sense" + " in the context of a node call"); } NamedElement namedEl = getFinalNestId(dotId); if (!(namedEl instanceof CallDef)) { // this error will be caught elsewhere return; } CallDef callDef = (CallDef) namedEl; List inDefTypes; String callName; // extract in/out arguments if (callDef instanceof FnDefExpr) { FnDefExpr fnDef = (FnDefExpr) callDef; inDefTypes = typesFromArgs(fnDef.getArgs()); callName = fnDef.getName(); } else if (callDef instanceof NodeDefExpr) { NodeDefExpr nodeDef = (NodeDefExpr) callDef; inDefTypes = typesFromArgs(nodeDef.getArgs()); callName = nodeDef.getName(); } else if (callDef instanceof LinearizationDefExpr) { LinearizationDefExpr linDef = (LinearizationDefExpr) callDef; inDefTypes = typesFromArgs(linDef.getArgs()); callName = linDef.getName(); } else if (callDef instanceof LibraryFnDefExpr) { LibraryFnDefExpr nativeDef = (LibraryFnDefExpr) callDef; inDefTypes = typesFromArgs(nativeDef.getArgs()); callName = nativeDef.getName(); } else { error(fnCall, "Node, function or linearization definition name expected."); return; } // extract args List argCallTypes = getAgreeTypes(fnCall.getArgs()); if (inDefTypes.size() != argCallTypes.size()) { error(fnCall, "Function definition '" + callName + "' requires " + inDefTypes.size() + " arguments, but this function call provides " + argCallTypes.size() + " arguments"); return; } for (int i = 0; i < inDefTypes.size(); i++) { AgreeType callType = argCallTypes.get(i); AgreeType defType = inDefTypes.get(i); if (!matches(defType, callType)) { error(fnCall, "Argument " + i + " of function call '" + callName + "' is of type '" + callType + "' but must be of type '" + defType + "'"); } } } @Check(CheckType.FAST) public void checkFnCallExpr(FnCallExpr fnCall) { NamedElement fn = getFinalNestId(fnCall.getFn()); if (isInLinearizationBody(fnCall)) { if (fn instanceof NodeDefExpr) { error(fnCall, "Node definitions cannot be applied in a linearization definition"); } } else { if (fn instanceof LibraryFnDefExpr) { if (fn.getElementRoot().getName().equalsIgnoreCase("dreal")) { warning(fnCall, "dReal library functions require the use of the dReal solver"); } else { error(fnCall, "Library functions cannot be called from the logic"); } } } checkInputsVsActuals(fnCall); } @Check(CheckType.FAST) public void checkFnDefExpr(FnDefExpr fnDef) { // verify typing AgreeType fnType = getAgreeType(fnDef.getType()); if (fnType == null) { return; // this error will be caught in parsing } AgreeType exprType = getAgreeType(fnDef.getExpr()); if (!exprType.equals(fnType)) { error(fnDef, "Function '" + fnDef.getName() + "' is of type '" + fnType.toString() + "' but its expression is of type '" + exprType + "'"); } } @Check(CheckType.FAST) public void checkCallDef(CallDef callDef) { // don't check recursive calls of functions that have // already been walked over if (checkedRecCalls.contains(callDef)) { return; } FnCallRecursionHelper recHelp = new FnCallRecursionHelper(); recHelp.doSwitch(callDef); for (LinkedList loop : recHelp.loops) { StringBuilder loopStr = new StringBuilder(); String sep = ""; for (CallDef tempCallDef : loop) { checkedRecCalls.add(tempCallDef); String callName = tempCallDef.getName(); loopStr.append(sep); loopStr.append(callName); sep = " -> "; } error(callDef, "There exists a recursive dependency between the " + "following node or function calls : " + loopStr); } } @Check(CheckType.FAST) public void checkIfThenElseExpr(IfThenElseExpr expr) { if (isInLinearizationBody(expr)) { error(expr, "If-then-else expressions not allowed in linearization body expressions"); return; } AgreeType condType = getAgreeType(expr.getA()); AgreeType thenType = getAgreeType(expr.getB()); AgreeType elseType = getAgreeType(expr.getC()); if (!matches(BOOL, condType)) { error(expr, "The condition of the if statement is of type '" + condType + "' but must be of type 'bool'"); } if (!matches(elseType, thenType)) { error(expr, "The 'then' and 'else' expressions are of non-matching types '" + thenType + "' and '" + elseType + "'"); } } @Check(CheckType.FAST) public void checkPreExpr(PreExpr expr) { if (isInLinearizationBody(expr)) { error(expr, "'pre' expressions not allowed in linearization body expressions"); } } private AgreeType getAgreeType(IfThenElseExpr expr) { return getAgreeType(expr.getB()); } /* * @Check(CheckType.FAST) * public void checkUnaryNonLinearExpr(UnaryNonLinearExpr expr) { * AgreeType typeSub = getAgreeType(expr.getExpr()); * String op = expr.getOp(); * warning(expr, "Use of trigonometric function: '" + op * + "'. Trigonometric expressions are allowed only with dReal." * + " Scalability is as yet unknown."); * if (!matches(REAL, typeSub)) { * error(expr, "argument to trigonometric function '" + op + "' is of type '" + typeSub.toString() * + "' but must be of " + "type 'real'"); * } * } * * @Check(CheckType.FAST) * public void checkBinaryNonLinearExpr(BinaryNonLinearExpr expr) { * AgreeType typeLeft = getAgreeType(expr.getLeft()); * AgreeType typeRight = getAgreeType(expr.getRight()); * String op = expr.getOp(); * warning(expr, "Use of trigonometric function: '" + op * + "'. Trigonometric expressions are allowed only with dReal." * + " Scalability is as yet unknown."); * if (!matches(REAL, typeLeft)) { * error(expr, "argument to trigonometric function '" + op + "' is of type '" + typeLeft.toString() * + "' but must be of " + "type 'real'"); * } * if (!matches(REAL, typeRight)) { * error(expr, "argument to trigonometric function '" + op + "' is of type '" + typeRight.toString() * + "' but must be of " + "type 'real'"); * } * } */ @Check(CheckType.FAST) public void checkBinaryExpr(BinaryExpr binExpr) { AgreeType typeLeft = getAgreeType(binExpr.getLeft()); AgreeType typeRight = getAgreeType(binExpr.getRight()); String op = binExpr.getOp(); Expr rightSide = binExpr.getRight(); Expr leftSide = binExpr.getLeft(); boolean isInLinearizationBodyExpr = isInLinearizationBody(binExpr); boolean rightSideConst = exprIsConst(rightSide); boolean leftSideConst = exprIsConst(leftSide); switch (op) { case "->": if (isInLinearizationBodyExpr) { error(binExpr, "Arrow '->' expressions are not allowed in linearization body expressions."); } else { if (!matches(typeRight, typeLeft)) { error(binExpr, "left and right sides of binary expression '" + op + "' are of type '" + typeLeft + "' and '" + typeRight + "', but must be of the same type"); } } return; case "=>": case "<=>": case "and": case "or": if (isInLinearizationBodyExpr) { error(binExpr, "Logical expressions (like '" + op + "') are not allowed in linearization body expressions."); } else { if (!matches(BOOL, typeLeft)) { error(binExpr, "left side of binary expression '" + op + "' is of type '" + typeLeft.toString() + "' but must be of " + "type 'bool'"); } if (!matches(BOOL, typeRight)) { error(binExpr, "right side of binary expression '" + op + "' is of type '" + typeRight.toString() + "' but must be of" + " type 'bool'"); } } return; case "=": case "<>": case "!=": if (isInLinearizationBodyExpr) { error(binExpr, "Logical comparison expressions (like '" + op + "') are not allowed in linearization body expressions."); } else { if (!matches(typeRight, typeLeft)) { error(binExpr, "left and right sides of binary expression '" + op + "' are of type '" + typeLeft + "' and '" + typeRight + "', but must be of the same type"); } } return; case "<": case "<=": case ">": case ">=": if (isInLinearizationBodyExpr) { error(binExpr, "Comparison expressions (like '" + op + "') are not allowed in linearization body expressions."); } else { if (!matches(typeRight, typeLeft)) { error(binExpr, "left and right sides of binary expression '" + op + "' are of type '" + typeLeft + "' and '" + typeRight + "', but must be of the same type"); } if (!matches(INT, typeLeft) && !matches(REAL, typeLeft)) { error(binExpr, "left side of binary expression '" + op + "' is of type '" + typeLeft + "' but must be of type" + "'int' or 'real'"); } if (!matches(INT, typeRight) && !matches(REAL, typeRight)) { error(binExpr, "right side of binary expression '" + op + "' is of type '" + typeRight + "' but must be of type" + "'int' or 'real'"); } } return; case "+": case "-": case "*": if (!matches(typeRight, typeLeft)) { error(binExpr, "left and right sides of binary expression '" + op + "' are of type '" + typeLeft + "' and '" + typeRight + "', but must be of the same type"); } if (!matches(INT, typeLeft) && !matches(REAL, typeLeft)) { error(binExpr, "left side of binary expression '" + op + "' is of type '" + typeLeft + "' but must be of type" + "'int' or 'real'"); } if (!matches(INT, typeRight) && !matches(REAL, typeRight)) { error(binExpr, "right side of binary expression '" + op + "' is of type '" + typeRight + "' but must be of type" + "'int' or 'real'"); } if (op.equals("*") && !isInLinearizationBodyExpr) { if (!rightSideConst && !leftSideConst) { warning(binExpr, "neither the right nor the left side of binary expression '" + op + "' is constant'. Non-linear expressions are allowed only with z3 and dReal." + " With z3 they are not recomended."); } } return; case "mod": case "div": if (isInLinearizationBodyExpr) { error(binExpr, "Integer operation expressions (like '" + op + "') are not allowed in linearization body expressions."); } else { if (!matches(INT, typeLeft)) { error(binExpr, "left side of binary expression '" + op + "' is of type '" + typeLeft + "' but must be of type 'int'"); } if (!matches(INT, typeRight)) { error(binExpr, "right side of binary expression '" + op + "' is of type '" + typeRight + "' but must be of type 'int'"); } if (!rightSideConst) { warning(binExpr, "right side of binary expression '" + op + "' is not constant." + " Non-linear expressions are allowed only with z3." + " Even with z3 they are not recomended..."); } } return; case "/": if (!matches(REAL, typeLeft)) { error(binExpr, "left side of binary expression '" + op + "' is of type '" + typeLeft + "' but must be of type 'real'"); } if (!matches(REAL, typeRight)) { error(binExpr, "right side of binary expression '" + op + "' is of type '" + typeRight + "' but must be of type 'real'"); } if (!rightSideConst && !isInLinearizationBodyExpr) { warning(binExpr, "right side of binary expression '" + op + "' is not constant." + " Non-linear expressions are allowed only with z3." + " Even with z3 they are not recomended..."); } return; default: assert (false); } } public static boolean exprIsConst(Expr expr) { if (expr instanceof NestedDotID) { NamedElement finalId = getFinalNestId((NestedDotID) expr); if (finalId instanceof ConstStatement) { return true; } } else if (expr instanceof RealLitExpr || expr instanceof IntLitExpr || expr instanceof BoolLitExpr) { return true; } else if (expr instanceof BinaryExpr) { BinaryExpr binExpr = (BinaryExpr) expr; return exprIsConst(binExpr.getLeft()) && exprIsConst(binExpr.getRight()); } else if (expr instanceof UnaryExpr) { UnaryExpr unExpr = (UnaryExpr) expr; return exprIsConst(unExpr.getExpr()); } return false; } // // TODO: Don't we need more validation here? What if the Id of the IdExpr // private Boolean hasCallDefParent(Element e) { // while (e != null) { // if (e instanceof CallDef) { // return true; // } // e = e.getOwner(); // } // return false; // } // // private void checkScope(Expr expr, NamedElement id) { // if (hasCallDefParent(expr)) { // if (!hasCallDefParent(id) && !(id instanceof ConstStatement)) { // error("Unknown identifier Id: '" + id // + "' (Note that nodes can refer only to inputs, outputs, and local variables and global constants)."); // } // } // } public static NamedElement getFinalNestId(NestedDotID dotId) { while (dotId.getSub() != null) { dotId = dotId.getSub(); } return dotId.getBase(); } public String getNestedDotIDTag(NestedDotID dotId) { while (dotId.getSub() != null) { dotId = dotId.getSub(); } return dotId.getTag(); } public AgreeType getAgreeType(Arg arg) { return getAgreeType(arg.getType()); } private AgreeType getAgreeType(UnaryExpr unaryExpr) { return getAgreeType(unaryExpr.getExpr()); } private AgreeType getAgreeType(NestedDotID nestDotIdExpr) { String tag = getNestedDotIDTag(nestDotIdExpr); if (tag != null) { switch (tag) { case "_CLK": case "_INSERT": case "_REMOVE": return BOOL; case "_COUNT": return INT; default: return ERROR; } } return getAgreeType(getFinalNestId(nestDotIdExpr)); } protected AgreeType getAgreeType(NamedElement namedEl) { if (namedEl instanceof DataSubcomponent) { // this is for checking "Base_Types::Boolean" etc... ComponentClassifier compClass = ((DataSubcomponent) namedEl).getAllClassifier(); if (compClass instanceof DataImplementation) { return getAgreeType((DataImplementation) compClass); } return getAgreeType(compClass); } else if (namedEl instanceof Arg) { return getAgreeType((Arg) namedEl); } else if (namedEl instanceof ClassifierType || namedEl instanceof Subcomponent) { return new AgreeType("component"); } else if (namedEl instanceof PropertyStatement) { return getAgreeType((PropertyStatement) namedEl); } else if (namedEl instanceof ConstStatement) { return getAgreeType((ConstStatement) namedEl); } else if (namedEl instanceof EqStatement) { return getAgreeType(namedEl); } else if (namedEl instanceof DataPort) { return getAgreeType(((DataPort) namedEl).getDataFeatureClassifier()); } else if (namedEl instanceof EventDataPort) { return getAgreeType(((EventDataPort) namedEl).getDataFeatureClassifier()); } else if (namedEl instanceof DataAccess) { return getAgreeType((NamedElement) ((DataAccess) namedEl).getFeatureClassifier()); } else if (namedEl instanceof DataType) { return getAgreeType((ComponentClassifier) namedEl); } else if (namedEl instanceof DataImplementation) { return getAgreeType((DataImplementation) namedEl); } else if (namedEl instanceof NamedID) { return getAgreeType((NamedID) namedEl); } return ERROR; } private AgreeType getAgreeType(NamedID id) { EObject container = id.eContainer(); if (!(container instanceof EnumStatement)) { throw new IllegalArgumentException("NamedIDs allowed only in enum statements."); } return getAgreeType((EnumStatement) container); } private AgreeType getAgreeType(EnumStatement statement) { String name = statement.getName(); EObject container = statement.eContainer(); while (!(container instanceof AadlPackage)) { if (container instanceof ComponentClassifier) { name = ((ComponentClassifier) container).getName() + "::" + name; } container = container.eContainer(); } name = ((AadlPackage) container).getName() + "::" + name; return new AgreeType(name); } private AgreeType getAgreeType(DataImplementation dataImpl) { AgreeType nativeType = getNativeType(dataImpl); if (nativeType != null) { return nativeType; } AadlPackage aadlPack = (AadlPackage) dataImpl.eContainer().eContainer(); String typeStr = aadlPack.getName() + "::" + dataImpl.getName(); return new AgreeType(typeStr); } private AgreeType getNativeType(DataImplementation dataImpl) { EList subComps = dataImpl.getAllSubcomponents(); // if there are no subcomponents, use the component type if (subComps.size() == 0) { return getAgreeType((ComponentClassifier) dataImpl.getType()); } return null; } private AgreeType getAgreeType(ComponentClassifier dataClass) { while (dataClass != null) { switch (dataClass.getQualifiedName()) { case "Base_Types::Boolean": return BOOL; case "Base_Types::Integer": return INT; case "Base_Types::Float": return REAL; } boolean is_aadl_enum = AgreeAADLEnumerationUtils.isAADLEnumeration(dataClass); if (is_aadl_enum) { String name = dataClass.getName(); EObject container = dataClass.eContainer(); while (!(container instanceof AadlPackage)) { if (container instanceof ComponentClassifier) { name = ((ComponentClassifier) container).getName() + "::" + name; } container = container.eContainer(); } name = ((AadlPackage) container).getName() + "::" + name; return new AgreeType(name); } DataType dataType = (DataType) dataClass; dataClass = dataType.getExtended(); } return ERROR; } private AgreeType getAgreeType(ComponentType compType) { while (compType.getExtended() != null) { compType = compType.getExtended(); } String qualName = compType.getQualifiedName(); switch (qualName) { case "Base_Types::Boolean": return BOOL; case "Base_Types::Integer": return INT; case "Base_Types::Float": return REAL; } return new AgreeType(qualName); } private AgreeType getAgreeType(DataSubcomponentType data) { if (data instanceof DataType) { ComponentType compType = ((DataType) data).getExtended(); if (compType != null && !AgreeAADLEnumerationUtils.isAADLEnumeration(data)) { return getAgreeType(compType); } } String qualName = data.getQualifiedName(); if (qualName == null) { return ERROR; } switch (qualName) { case "Base_Types::Boolean": return BOOL; case "Base_Types::Integer": return INT; case "Base_Types::Float": return REAL; } return new AgreeType(qualName); } private AgreeType getAgreeType(PropertyStatement propStat) { return getAgreeType(propStat.getExpr()); } private AgreeType getAgreeType(ConstStatement constStat) { return getAgreeType(constStat.getType()); } private AgreeType getAgreeType(GetPropertyExpr getPropExpr) { NamedElement namedEl = getPropExpr.getProp(); if ((namedEl instanceof Property) || namedEl instanceof PropertyConstant) { PropertyType propType; if (namedEl instanceof Property) { propType = ((Property) namedEl).getPropertyType(); } else { propType = ((PropertyConstant) namedEl).getPropertyType(); } if (propType instanceof AadlBoolean) { return BOOL; } else if (propType instanceof AadlString || propType instanceof EnumerationType) { return new AgreeType("string"); } else if (propType instanceof AadlInteger) { return INT; } else if (propType instanceof AadlReal) { return REAL; } else if (propType instanceof ClassifierType) { return new AgreeType("component"); } } return ERROR; } private AgreeType getAgreeType(PrevExpr prevExpr) { return getAgreeType(prevExpr.getDelay()); } private List getAgreeTypes(List exprs) { ArrayList list = new ArrayList<>(); for (Expr expr : exprs) { list.add(getAgreeType(expr)); } return list; } public List typesFromArgs(List args) { ArrayList list = new ArrayList<>(); for (Arg arg : args) { list.add(getAgreeType(arg)); } return list; } private AgreeType getAgreeType(FnCallExpr fnCall) { // TODO: Examine type system in more detail // TODO: Fix to make support type lists. NestedDotID dotId = fnCall.getFn(); NamedElement namedEl = getFinalNestId(dotId); if (isInLinearizationBody(fnCall)) { // extract in/out arguments if (namedEl instanceof FnDefExpr || namedEl instanceof NodeDefExpr) { error(fnCall, "Calls to AGREE nodes and functions not allowed in linearization bodies"); return ERROR; } else if (namedEl instanceof LinearizationDefExpr) { return REAL; } else if (namedEl instanceof LibraryFnDefExpr) { LibraryFnDefExpr fnDef = (LibraryFnDefExpr) namedEl; return getAgreeType(fnDef.getType()); } else { error(fnCall, "Node, function or linearization definition name expected."); return ERROR; } } else { // extract in/out arguments if (namedEl instanceof FnDefExpr) { FnDefExpr fnDef = (FnDefExpr) namedEl; return getAgreeType(fnDef.getType()); } else if (namedEl instanceof NodeDefExpr) { NodeDefExpr nodeDef = (NodeDefExpr) namedEl; List outDefTypes = typesFromArgs(nodeDef.getRets()); if (outDefTypes.size() == 1) { return outDefTypes.get(0); } else { error(fnCall, "Nodes embedded in expressions must have exactly one return value." + " Node " + nodeDef.getName() + " contains " + outDefTypes.size() + " return values"); return ERROR; } } else if (namedEl instanceof LinearizationDefExpr) { return REAL; } else if (namedEl instanceof LibraryFnDefExpr) { LibraryFnDefExpr fnDef = (LibraryFnDefExpr) namedEl; return getAgreeType(fnDef.getType()); } else { error(fnCall, "Node, function or linearization definition name expected."); return ERROR; } } } private AgreeType getAgreeType(BinaryExpr binExpr) { AgreeType typeLeft = getAgreeType(binExpr.getLeft()); String op = binExpr.getOp(); switch (op) { case "->": return typeLeft; case "=>": case "<=>": case "and": case "or": return BOOL; case "<>": case "!=": return BOOL; case "<": case "<=": case ">": case ">=": case "=": return BOOL; case "+": case "-": case "*": case "/": case "mod": case "div": case "^": return typeLeft; } return ERROR; } protected AgreeType getAgreeType(Expr expr) { if (expr instanceof BinaryExpr) { return getAgreeType((BinaryExpr) expr); } else if (expr instanceof FnCallExpr) { return getAgreeType((FnCallExpr) expr); } else if (expr instanceof IfThenElseExpr) { return getAgreeType((IfThenElseExpr) expr); } else if (expr instanceof PrevExpr) { return getAgreeType((PrevExpr) expr); } else if (expr instanceof GetPropertyExpr) { return getAgreeType((GetPropertyExpr) expr); } else if (expr instanceof NestedDotID) { return getAgreeType((NestedDotID) expr); } else if (expr instanceof UnaryExpr) { return getAgreeType((UnaryExpr) expr); } else if (expr instanceof IntLitExpr) { return INT; } else if (expr instanceof RealLitExpr) { return REAL; } else if (expr instanceof BoolLitExpr) { return BOOL; } else if (expr instanceof ThisExpr) { return new AgreeType("component"); } else if (expr instanceof PreExpr) { return getAgreeType(((PreExpr) expr).getExpr()); } else if (expr instanceof RecordExpr) { return getAgreeType((RecordExpr) expr); } else if (expr instanceof RecordUpdateExpr) { return getAgreeType((RecordUpdateExpr) expr); } else if (expr instanceof FloorCast) { return INT; } else if (expr instanceof RealCast) { return REAL; } else if (expr instanceof EventExpr) { return BOOL; } else if (expr instanceof TimeExpr) { return REAL; } else if (expr instanceof AADLEnumerator) { return getAgreeType((AADLEnumerator) expr); } else if (expr instanceof LatchedExpr) { return getAgreeType(((LatchedExpr) expr).getExpr()); } else if (expr instanceof TimeOfExpr || expr instanceof TimeRiseExpr || expr instanceof TimeFallExpr) { return REAL; } /* * else if (expr instanceof UnaryNonLinearExpr || * expr instanceof BinaryNonLinearExpr) { * return REAL; * } */ return ERROR; } private AgreeType getAgreeType(AADLEnumerator enumExpr) { return getAgreeType(enumExpr.getEnumType()); } private AgreeType getAgreeType(RecordUpdateExpr upExpr) { return getAgreeType(upExpr.getRecord()); } private AgreeType getAgreeType(RecordExpr recExpr) { return getNestIdAsType(recExpr.getRecord()); } public static boolean matches(AgreeType expected, AgreeType actual) { if (expected.equals(ERROR) || actual.equals(ERROR)) { return false; } else if (integerMatch(expected, actual)) { return true; } else if (floatingPointMatch(expected, actual)) { return true; } return expected.equals(actual); } private static boolean floatingPointMatch(AgreeType expected, AgreeType actual) { if (expected.toString().equals("real") && actual.toString().startsWith("Base_Types::Float")) { return true; } if (actual.toString().equals("real") && expected.toString().startsWith("Base_Types::Float")) { return true; } return false; } private static boolean integerMatch(AgreeType expected, AgreeType actual) { if (expected.toString().equals("int") && actual.toString().startsWith("Base_Types::Integer")) { return true; } if (actual.toString().equals("int") && expected.toString().startsWith("Base_Types::Integer")) { return true; } return false; } } /* * This file is part of dependency-check-core. * * 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. * * Copyright (c) 2013 . All Rights Reserved. */ package org.owasp.dependencycheck.data.update.nvd; import java.io.File; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.owasp.dependencycheck.BaseTest; /** * * @author */ public class UpdateableNvdCveTest extends BaseTest { /** * Test of isUpdateNeeded method, of class UpdateableNvdCve. */ @Test public void testIsUpdateNeeded() { String id = "key"; String url = new File("target/test-classes/nvdcve-2.0-2012.xml").toURI().toString(); long timestamp = 42; UpdateableNvdCve instance = new UpdateableNvdCve(); instance.add(id, url, timestamp, false); boolean expResult = false; boolean result = instance.isUpdateNeeded(); assertEquals(expResult, result); instance.add("nextId", url, 23, true); expResult = true; result = instance.isUpdateNeeded(); assertEquals(expResult, result); } /** * Test of add method, of class UpdateableNvdCve. */ @Test public void testAdd() throws Exception { String id = "key"; String url = new File("target/test-classes/nvdcve-1.0-2012.json.gz").toURI().toString(); long timestamp = 42; UpdateableNvdCve instance = new UpdateableNvdCve(); instance.add(id, url, timestamp, false); boolean expResult = false; boolean result = instance.isUpdateNeeded(); assertEquals(expResult, result); instance.add("nextId", url, 23, false); NvdCveInfo results = instance.get(id); assertEquals(id, results.getId()); assertEquals(url, results.getUrl()); assertEquals(timestamp, results.getTimestamp()); } /** * Test of clear method, of class UpdateableNvdCve. */ @Test public void testClear() { String id = "key"; String url = new File("target/test-classes/nvdcve-1.0-2012.json.gz").toURI().toString(); long timestamp = 42; UpdateableNvdCve instance = new UpdateableNvdCve(); instance.add(id, url, timestamp, false); assertFalse(instance.getCollection().isEmpty()); instance.clear(); assertTrue(instance.getCollection().isEmpty()); } /** * Test of iterator method, of class UpdatableNvdCve. */ @Test public void testIterator() { String url = new File("target/test-classes/nvdcve-1.0-2012.json.gz").toURI().toString(); UpdateableNvdCve instance = new UpdateableNvdCve(); instance.add("one", url, 42, false); instance.add("two", url, 23, false); instance.add("three", url, 17, false); int itemsProcessed = 0; for (NvdCveInfo item : instance) { if ("one".equals(item.getId())) { instance.remove(); } itemsProcessed += 1; } assertEquals(3, itemsProcessed); assertEquals(2, instance.getCollection().size()); } } 1-10 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("cr") @Implements("ScriptEvent") public class ScriptEvent extends Node { @ObfuscatedName("ic") @ObfuscatedSignature( descriptor = "[Lqd;" ) @Export("modIconSprites") static IndexedSprite[] modIconSprites; @ObfuscatedName("o") @Export("args") Object[] args; @ObfuscatedName("q") @Export("isMouseInputEvent") boolean isMouseInputEvent; @ObfuscatedName("l") @ObfuscatedSignature( descriptor = "Lki;" ) @Export("widget") Widget widget; @ObfuscatedName("k") @ObfuscatedGetter( intValue = 1486957431 ) @Export("mouseX") int mouseX; @ObfuscatedName("a") @ObfuscatedGetter( intValue = -2142202081 ) @Export("mouseY") int mouseY; @ObfuscatedName("m") @ObfuscatedGetter( intValue = 19118051 ) @Export("opIndex") int opIndex; @ObfuscatedName("p") @ObfuscatedSignature( descriptor = "Lki;" ) @Export("dragTarget") Widget dragTarget; @ObfuscatedName("s") @ObfuscatedGetter( intValue = -337661445 ) @Export("keyTyped") int keyTyped; @ObfuscatedName("r") @ObfuscatedGetter( intValue = -2123703635 ) @Export("keyPressed") int keyPressed; @ObfuscatedName("v") @Export("targetName") String targetName; @ObfuscatedName("y") @ObfuscatedGetter( intValue = 702616363 ) int field1054; @ObfuscatedName("c") @ObfuscatedGetter( intValue = -394904135 ) @Export("type") int type; public ScriptEvent() { this.type = 76; // L: 19 } @ObfuscatedName("o") @ObfuscatedSignature( descriptor = "([Ljava/lang/Object;B)V", garbageValue = "3" ) @Export("setArgs") public void setArgs(Object[] var1) { this.args = var1; // L: 22 } // L: 23 @ObfuscatedName("q") @ObfuscatedSignature( descriptor = "(II)V", garbageValue = "1156737002" ) @Export("setType") public void setType(int var1) { this.type = var1; } @ObfuscatedName("o") @ObfuscatedSignature( descriptor = "(I)V", garbageValue = "520194545" ) static void method2074() { class82.field1072 = new int[2000]; // L: 25 int var0 = 0; // L: 26 int var1 = 240; int var3; for (byte var2 = 12; var0 < 16; var1 -= var2) { var3 = class127.method2805((double)((float)var1 / 360.0F), 0.9998999834060669D, (double)(0.075F + (float)var0 * 0.425F / 16.0F)); // L: 30 class82.field1072[var0] = var3; // L: 31 ++var0; // L: 29 } var1 = 48; // L: 33 for (int var5 = var1 / 6; var0 < class82.field1072.length; var1 -= var5) { // L: 34 35 41 var3 = var0 * 2; // L: 36 for (int var4 = class127.method2805((double)((float)var1 / 360.0F), 0.9998999834060669D, 0.5D); var0 < var3 && var0 < class82.field1072.length; ++var0) { // L: 37 38 class82.field1072[var0] = var4; // L: 39 } } } // L: 43 @ObfuscatedName("q") @ObfuscatedSignature( descriptor = "(Ljava/lang/String;ZZI)V", garbageValue = "-1817866678" ) @Export("openURL") public static void openURL(String var0, boolean var1, boolean var2) { World.method1663(var0, var1, "openjs", var2); // L: 27 } // L: 28 @ObfuscatedName("p") public static int method2085(long var0) { return (int)(var0 >>> 7 & 127L); // L: 68 } } app/src/main/java/app/android/box/waveprotocol/org/androidwave/service/models/IdGeneratorGeneric.java1-10 package app.android.box.waveprotocol.org.androidwave.service.models; import org.waveprotocol.wave.model.id.IdGenerator; import org.waveprotocol.wave.model.id.WaveId; public interface IdGeneratorGeneric { IdGeneratorGeneric initialize(IdGenerator idGenerator); WaveId newWaveId(); } src/main/java/io/github/davoleo/testmod/handler/ClientRegistryHandler.java /* ----------------------------------- * Author: Davoleo * Date / Hour: 06/03/2020 / 17:09 * Class: ClientRegistryHandler * Project: TestMod * Copyright - © - Davoleo - 2020 * ----------------------------------- */ package io.github.davoleo.testmod.handler; import io.github.davoleo.testmod.TestMod; import io.github.davoleo.testmod.block.BakedBlockModel; import io.github.davoleo.testmod.block.ModBlocks; import net.minecraft.client.renderer.model.ModelResourceLocation; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; @Mod.EventBusSubscriber(modid = TestMod.MODID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD) public class ClientRegistryHandler { //Bake our block texture into the Atlas @SubscribeEvent public static void onTextureStitch(TextureStitchEvent.Pre event) { if (!event.getMap().getBasePath().equals("textures")) return; event.addSprite(new ResourceLocation(TestMod.MODID, "block/baked_block")); } @SubscribeEvent public static void onModelBake(ModelBakeEvent event) { event.getModelRegistry().put(new ModelResourceLocation(ModBlocks.BAKED_BLOCK.getRegistryName(), ""), new BakedBlockModel(DefaultVertexFormats.BLOCK)); event.getModelRegistry().put(new ModelResourceLocation(ModBlocks.BAKED_BLOCK.getRegistryName(), "inventory"), new BakedBlockModel(DefaultVertexFormats.ITEM)); } } 1-10 package devvy.me.minestrike.team; import devvy.me.minestrike.Minestrike; import devvy.me.minestrike.player.CSPlayer; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.util.Vector; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.Collection; public class CSTeam { private ArrayList members; private final TeamType type; private String name; private int roundsWon; private int lossStreak; private Spawn spawn; //DEBUG private Vector defendersSpawnCoordinates = new Vector(0,64,-24); private Vector attackersSpawnCoordinates = new Vector(0,64,24); public CSTeam(TeamType type, String name) { Minestrike plugin = Minestrike.getPlugin(Minestrike.class); members = new ArrayList<>(); this.type = type; this.name = name; roundsWon = 0; // todo make this not hard coded ish if (type == TeamType.ATTACKERS) this.spawn = new Spawn(new Location(plugin.getGameWorld(), attackersSpawnCoordinates.getX()+.5,attackersSpawnCoordinates.getY(), attackersSpawnCoordinates.getZ()+.5), this); else this.spawn = new Spawn(new Location(plugin.getGameWorld(), defendersSpawnCoordinates.getX()+.5,defendersSpawnCoordinates.getY(), defendersSpawnCoordinates.getZ()+.5), this); } public TeamType getType() { return type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getRoundsWon() { return roundsWon; } public void setRoundsWon(int roundsWon) { this.roundsWon = roundsWon; } public void addRoundWin(){ roundsWon++; } public int getLossStreak() { return lossStreak; } public void resetLossStreak(){ lossStreak = 0; } public void incrimentLossStreak(){ lossStreak++; //makes sure lossStreak doesnt get too high if (lossStreak > 5) lossStreak = 5; } public boolean hasMember(CSPlayer player){ return members.contains(player); } public void addMember(CSPlayer player){ if (!members.contains(player)) members.add(player); // update tab list to show clan tags properly updateTablist(player.getSpigotPlayer()); } public void removeMember(CSPlayer player){ members.remove(player); // update tab list to show clan tags properly updateTablist(player.getSpigotPlayer()); } public void clearMembers(){ members = new ArrayList<>(); updateTablist(); } public void updateTablist(Player p) { if (Minestrike.getPlugin(Minestrike.class).getGameManager() != null) Minestrike.getPlugin(Minestrike.class).getGameManager().getScoreboardManager().updatePlayerClanTag(p); } public void updateTablist() { if (Minestrike.getPlugin(Minestrike.class).getGameManager() != null) for (Player p : Bukkit.getOnlinePlayers()) // update tab list to show clan tags properly Minestrike.getPlugin(Minestrike.class).getGameManager().getScoreboardManager().updatePlayerClanTag(p); } public Collection getMembers(){ return members; } public CSPlayer getRandomMember() { if (members.isEmpty()) return null; return members.get((int) (Math.random() * members.size())); } public int getNumMembersAlive(){ int alive = 0; for (CSPlayer player : getMembers()) if (player.isAlive()) alive++; return alive; } public int getTeamTotalCurrency() { int economy = 0; for (CSPlayer player : getMembers()) economy += player.getMoney(); return economy; } public void addMoneyToAllMembers(int amount) { addMoneyToAllMembers(amount, ""); } public void addMoneyToAllMembers(int amount, String reason) { for (CSPlayer member : members) member.addMoney(amount, reason); } public int size(){ return members.size(); } /** * Gets a string form of the member's on this team separated by commas * @return A string representation of this team */ public String getMemberString(){ if (getMembers().isEmpty()) return "Empty!"; StringBuilder sb = new StringBuilder(); for (CSPlayer p : getMembers()) sb.append(p.getSpigotPlayer().getName()).append(", "); return sb.substring(0, sb.length() - 2); } public Spawn getSpawn() { return spawn; } } package io.github.factoryfx.factory.util; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.google.common.reflect.ClassPath; import io.github.factoryfx.factory.FactoryBase; public class ClasspathBasedFactoryProvider { /** * @param basePackage base package for the factory to avoid scanning the whole classpath * @return list of factories */ @SuppressWarnings("unchecked") public List>> get(String basePackage) { List>> result = new ArrayList<>(); try { for (ClassPath.ClassInfo classInfo : ClassPath.from(ClasspathBasedFactoryProvider.class.getClassLoader()).getAllClasses()) { if (classInfo.getName().startsWith(basePackage)) { Class clazz = classInfo.load(); if (FactoryBase.class.isAssignableFrom(clazz) && clazz != FactoryBase.class) { result.add((Class>) clazz); } } } } catch (IOException e) { throw new RuntimeException(e); } return result; } public List>> get(Package packageParam){ return get(packageParam.getName()); } /** * * @param root class in the root package for all Factories. {@link ClasspathBasedFactoryProvider#get(String)} * @return list of factories */ public List>> get(Class> root){ return get(root.getPackage().getName()); } } package sample; /* Get Size of Java HashSet Example This Java Example shows how to get the size or nubmer of elements stored in Java HashSet object using size method. */ import java.util.HashSet; public class GetSizeOfJavaHashSetExample { public static void main(String[] args) { //create HashSet object HashSet hSet = new HashSet(); /* To get the size of HashSet use int size() method of HashSet class. It returns the number of elements stored in HashSet object. */ System.out.println("Size of HashSet : " + hSet.size()); //add elements to HashSet object hSet.add(new Integer("1")); hSet.add(new Integer("2")); hSet.add(new Integer("3")); System.out.println("Size of HashSet after addition : " + hSet.size()); //remove one element from HashSet using remove method hSet.remove(new Integer("1")); System.out.println("Size of HashSet after removal : " + hSet.size()); } } /* Output would be Size of HashSet : 0 Size of HashSet after addition : 3 Size of HashSet after removal : 2 */ corvus-as2/src/main/java/hk/hku/cecid/edi/as2/dao/RepositoryDataSourceDVO.java package hk.hku.cecid.edi.as2.dao; import java.sql.SQLException; import hk.hku.cecid.piazza.commons.dao.ds.DataSourceDVO; /** * @author * */ public class RepositoryDataSourceDVO extends DataSourceDVO implements RepositoryDVO { public RepositoryDataSourceDVO() { super(); } public String getMessageId() { return super.getString("messageId"); } public void setMessageId(String messageId) { super.setString("messageId", messageId); } public byte[] getContent() { return (byte[])super.get("content"); } public void setContent(byte[] content) { super.put("content", content); } /** * @return Returns the messageBox. */ public String getMessageBox() { return super.getString("messageBox"); } /** * @param messageBox The messageBox to set. */ public void setMessageBox(String messageBox) { super.setString("messageBox", messageBox); } }package com.xiaogang.com.wanandroid_xg.bean; /** * Created by xiaogang on 2018/9/6. */ public class DataResponse { private int errorCode; private Object errorMsg; private T data; public int getErrorCode() { return errorCode; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } public Object getErrorMsg() { return errorMsg; } public void setErrorMsg(Object errorMsg) { this.errorMsg = errorMsg; } public T getData() { return data; } public void setData(T data) { this.data = data; } } package de.sk.checknametable; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map.Entry; import java.util.Set; import javafx.beans.binding.Bindings; import javafx.beans.property.BooleanProperty; import javafx.beans.value.ObservableValue; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.control.ComboBox; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.cell.CheckBoxTableCell; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.layout.AnchorPane; import javafx.util.Callback; public class CheckNameComboTable extends AnchorPane { @FXML private TableView table; @FXML private TableColumn name; @FXML private TableColumn> validUntil; @FXML private TableColumn active; ObservableList tableItems; ObservableList comboItems; HashMap selectionMapping = new HashMap<>(); HashMap comboMapping = new HashMap<>(); public CheckNameComboTable() throws IOException { final FXMLLoader loader = new FXMLLoader(); loader.setRoot(this); loader.setController(this); loader.setLocation(this.getClass().getResource("CheckStringComboTable_View.fxml")); loader.load(); } public void init(ObservableList tableItems, ObservableList comboItems, ObservableList selectedItems, HashMap selectedCombos, String checkBoxName, String stringName, String comboBoxName) { this.tableItems = tableItems; this.comboItems = comboItems; this.comboMapping = selectedCombos; name.setCellValueFactory(new PropertyValueFactory<>("name")); validUntil.setCellFactory(new Callback>, TableCell>>() { @Override public TableCell> call(TableColumn> param) { ComboBox cb = new ComboBox<>(); cb.setItems(comboItems); TableCell> cell = new TableCell<>(); cell.graphicProperty().bind(Bindings.when(cell.emptyProperty()).then((Node) null).otherwise(cb)); return cell; } }); active.setCellFactory( CheckBoxTableCell.forTableColumn(new Callback>() { @Override public ObservableValue call(Integer param) { return selectionMapping.get(active.getTableView().getItems().get(param)); } })); table.setItems(tableItems); for (T item : tableItems) { if (comboMapping.containsKey(item)) { validUntil.getCellData(item).getSelectionModel().select(comboMapping.get(item)); } validUntil.getCellData(item).setOnAction(new EventHandler() { @Override public void handle(ActionEvent event) { event.consume(); S selected = ((ComboBox) event.getSource()).getSelectionModel().getSelectedItem(); comboMapping.put(item, selected); } }); } } public List getSelectedItems() { Set> entries = selectionMapping.entrySet(); entries.removeIf((entry) -> !entry.getValue().get()); List ret = new ArrayList<>(); entries.forEach((entry) -> ret.add(entry.getKey())); return ret; } public S getComboValueForItem(T item) { return validUntil.getCellData(item).getSelectionModel().getSelectedItem(); } } myDemo/Android/gradle-2.12/src/jacoco/org/gradle/internal/jacoco/JacocoReportsContainerImpl.java100-1000 /* * Copyright 2013 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.gradle.internal.jacoco; import org.gradle.api.Task; import org.gradle.api.reporting.ConfigurableReport; import org.gradle.api.reporting.DirectoryReport; import org.gradle.api.reporting.Report; import org.gradle.api.reporting.SingleFileReport; import org.gradle.api.reporting.internal.TaskGeneratedSingleDirectoryReport; import org.gradle.api.reporting.internal.TaskGeneratedSingleFileReport; import org.gradle.api.reporting.internal.TaskReportContainer; import org.gradle.testing.jacoco.tasks.JacocoReportsContainer; public class JacocoReportsContainerImpl extends TaskReportContainer implements JacocoReportsContainer { public JacocoReportsContainerImpl(Task task) { super(ConfigurableReport.class, task); add(TaskGeneratedSingleDirectoryReport.class, "html", task, "index.html"); add(TaskGeneratedSingleFileReport.class, "xml", task); add(TaskGeneratedSingleFileReport.class, "csv", task); } public DirectoryReport getHtml() { return (DirectoryReport)getByName("html"); } public SingleFileReport getXml() { return (SingleFileReport)getByName("xml"); } public SingleFileReport getCsv() { return (SingleFileReport)getByName("csv"); } } package org.tynamo.resteasy; import java.util.HashSet; import java.util.Set; import java.util.Collection; public class Application extends javax.ws.rs.core.Application { private Set singletons = new HashSet(); private Set> empty = new HashSet>(); public Application(Collection singletons) { this.singletons = new HashSet(singletons); } @Override public Set> getClasses() { return empty; } @Override public Set getSingletons() { return singletons; } } /* * Copyright (C) 2006 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 android.app; import com.android.internal.policy.PolicyManager; import com.android.internal.util.XmlUtils; import com.google.android.collect.Maps; import org.xmlpull.v1.XmlPullParserException; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.ContextWrapper; import android.content.IContentProvider; import android.content.Intent; import android.content.IntentFilter; import android.content.IIntentReceiver; import android.content.IntentSender; import android.content.ReceiverCallNotAllowedException; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.pm.ApplicationInfo; import android.content.pm.ComponentInfo; import android.content.pm.FeatureInfo; import android.content.pm.IPackageDataObserver; import android.content.pm.IPackageDeleteObserver; import android.content.pm.IPackageInstallObserver; import android.content.pm.IPackageMoveObserver; import android.content.pm.IPackageManager; import android.content.pm.IPackageStatsObserver; import android.content.pm.InstrumentationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PermissionGroupInfo; import android.content.pm.PermissionInfo; import android.content.pm.ProviderInfo; import android.content.pm.ResolveInfo; import android.content.pm.ServiceInfo; import android.content.res.AssetManager; import android.content.res.Resources; import android.content.res.XmlResourceParser; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.hardware.SensorManager; import android.hardware.usb.IUsbManager; import android.hardware.usb.UsbManager; import android.location.ILocationManager; import android.location.LocationManager; import android.media.AudioManager; import android.net.ConnectivityManager; import android.net.IConnectivityManager; import android.net.ThrottleManager; import android.net.IThrottleManager; import android.net.Uri; import android.net.wifi.IWifiManager; import android.net.wifi.WifiManager; import android.nfc.NfcManager; import android.os.Binder; import android.os.Bundle; import android.os.DropBoxManager; import android.os.Environment; import android.os.FileUtils; import android.os.Handler; import android.os.IBinder; import android.os.IPowerManager; import android.os.Looper; import android.os.PowerManager; import android.os.Process; import android.os.RemoteException; import android.os.ServiceManager; import android.os.Vibrator; import android.os.FileUtils.FileStatus; import android.os.storage.StorageManager; import android.telephony.TelephonyManager; import android.text.ClipboardManager; import android.util.AndroidRuntimeException; import android.util.Log; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.WindowManagerImpl; import android.view.accessibility.AccessibilityManager; import android.view.inputmethod.InputMethodManager; import android.accounts.AccountManager; import android.accounts.IAccountManager; import android.app.admin.DevicePolicyManager; import com.android.internal.os.IDropBoxManagerService; 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.lang.ref.WeakReference; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; class ReceiverRestrictedContext extends ContextWrapper { ReceiverRestrictedContext(Context base) { super(base); } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { return registerReceiver(receiver, filter, null, null); } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) { throw new ReceiverCallNotAllowedException( "IntentReceiver components are not allowed to register to receive intents"); //ex.fillInStackTrace(); //Log.e("IntentReceiver", ex.getMessage(), ex); //return mContext.registerReceiver(receiver, filter, broadcastPermission, // scheduler); } @Override public boolean bindService(Intent service, ServiceConnection conn, int flags) { throw new ReceiverCallNotAllowedException( "IntentReceiver components are not allowed to bind to services"); //ex.fillInStackTrace(); //Log.e("IntentReceiver", ex.getMessage(), ex); //return mContext.bindService(service, interfaceName, conn, flags); } } /** * Common implementation of Context API, which provides the base * context object for Activity and other application components. */ class ContextImpl extends Context { private final static String TAG = "ApplicationContext"; private final static boolean DEBUG = false; private final static boolean DEBUG_ICONS = false; private static final Object sSync = new Object(); private static AlarmManager sAlarmManager; private static PowerManager sPowerManager; private static ConnectivityManager sConnectivityManager; private static ThrottleManager sThrottleManager; private static WifiManager sWifiManager; private static LocationManager sLocationManager; private static final HashMap sSharedPrefs = new HashMap(); private AudioManager mAudioManager; /*package*/ LoadedApk mPackageInfo; private Resources mResources; /*package*/ ActivityThread mMainThread; private Context mOuterContext; private IBinder mActivityToken = null; private ApplicationContentResolver mContentResolver; private int mThemeResource = 0; private Resources.Theme mTheme = null; private PackageManager mPackageManager; private NotificationManager mNotificationManager = null; private ActivityManager mActivityManager = null; private WallpaperManager mWallpaperManager = null; private Context mReceiverRestrictedContext = null; private SearchManager mSearchManager = null; private SensorManager mSensorManager = null; private StorageManager mStorageManager = null; private UsbManager mUsbManager = null; private Vibrator mVibrator = null; private LayoutInflater mLayoutInflater = null; private StatusBarManager mStatusBarManager = null; private TelephonyManager mTelephonyManager = null; private ClipboardManager mClipboardManager = null; private boolean mRestricted; private AccountManager mAccountManager; // protected by mSync private DropBoxManager mDropBoxManager = null; private DevicePolicyManager mDevicePolicyManager = null; private UiModeManager mUiModeManager = null; private DownloadManager mDownloadManager = null; private NfcManager mNfcManager = null; private final Object mSync = new Object(); private File mDatabasesDir; private File mPreferencesDir; private File mFilesDir; private File mCacheDir; private File mExternalFilesDir; private File mExternalCacheDir; private static long sInstanceCount = 0; private static final String[] EMPTY_FILE_LIST = {}; // For debug only /* @Override protected void finalize() throws Throwable { super.finalize(); --sInstanceCount; } */ public static long getInstanceCount() { return sInstanceCount; } @Override public AssetManager getAssets() { return mResources.getAssets(); } @Override public Resources getResources() { return mResources; } @Override public PackageManager getPackageManager() { if (mPackageManager != null) { return mPackageManager; } IPackageManager pm = ActivityThread.getPackageManager(); if (pm != null) { // Doesn't matter if we make more than one instance. return (mPackageManager = new ApplicationPackageManager(this, pm)); } return null; } @Override public ContentResolver getContentResolver() { return mContentResolver; } @Override public Looper getMainLooper() { return mMainThread.getLooper(); } @Override public Context getApplicationContext() { return (mPackageInfo != null) ? mPackageInfo.getApplication() : mMainThread.getApplication(); } @Override public void setTheme(int resid) { mThemeResource = resid; } @Override public Resources.Theme getTheme() { if (mTheme == null) { if (mThemeResource == 0) { mThemeResource = com.android.internal.R.style.Theme; } mTheme = mResources.newTheme(); mTheme.applyStyle(mThemeResource, true); } return mTheme; } @Override public ClassLoader getClassLoader() { return mPackageInfo != null ? mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader(); } @Override public String getPackageName() { if (mPackageInfo != null) { return mPackageInfo.getPackageName(); } throw new RuntimeException("Not supported in system context"); } @Override public ApplicationInfo getApplicationInfo() { if (mPackageInfo != null) { return mPackageInfo.getApplicationInfo(); } throw new RuntimeException("Not supported in system context"); } @Override public String getPackageResourcePath() { if (mPackageInfo != null) { return mPackageInfo.getResDir(); } throw new RuntimeException("Not supported in system context"); } @Override public String getPackageCodePath() { if (mPackageInfo != null) { return mPackageInfo.getAppDir(); } throw new RuntimeException("Not supported in system context"); } private static File makeBackupFile(File prefsFile) { return new File(prefsFile.getPath() + ".bak"); } public File getSharedPrefsFile(String name) { return makeFilename(getPreferencesDir(), name + ".xml"); } @Override public SharedPreferences getSharedPreferences(String name, int mode) { SharedPreferencesImpl sp; File prefsFile; boolean needInitialLoad = false; synchronized (sSharedPrefs) { sp = sSharedPrefs.get(name); if (sp != null && !sp.hasFileChangedUnexpectedly()) { return sp; } prefsFile = getSharedPrefsFile(name); if (sp == null) { sp = new SharedPreferencesImpl(prefsFile, mode, null); sSharedPrefs.put(name, sp); needInitialLoad = true; } } synchronized (sp) { if (needInitialLoad && sp.isLoaded()) { // lost the race to load; another thread handled it return sp; } File backup = makeBackupFile(prefsFile); if (backup.exists()) { prefsFile.delete(); backup.renameTo(prefsFile); } // Debugging if (prefsFile.exists() && !prefsFile.canRead()) { Log.w(TAG, "Attempt to read preferences file " + prefsFile + " without permission"); } Map map = null; FileStatus stat = new FileStatus(); if (FileUtils.getFileStatus(prefsFile.getPath(), stat) && prefsFile.canRead()) { try { FileInputStream str = new FileInputStream(prefsFile); map = XmlUtils.readMapXml(str); str.close(); } catch (org.xmlpull.v1.XmlPullParserException e) { Log.w(TAG, "getSharedPreferences", e); } catch (FileNotFoundException e) { Log.w(TAG, "getSharedPreferences", e); } catch (IOException e) { Log.w(TAG, "getSharedPreferences", e); } } sp.replace(map, stat); } return sp; } private File getPreferencesDir() { synchronized (mSync) { if (mPreferencesDir == null) { mPreferencesDir = new File(getDataDirFile(), "shared_prefs"); } return mPreferencesDir; } } @Override public FileInputStream openFileInput(String name) throws FileNotFoundException { File f = makeFilename(getFilesDir(), name); return new FileInputStream(f); } @Override public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException { final boolean append = (mode&MODE_APPEND) != 0; File f = makeFilename(getFilesDir(), name); try { FileOutputStream fos = new FileOutputStream(f, append); setFilePermissionsFromMode(f.getPath(), mode, 0); return fos; } catch (FileNotFoundException e) { } File parent = f.getParentFile(); parent.mkdir(); FileUtils.setPermissions( parent.getPath(), FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, -1, -1); FileOutputStream fos = new FileOutputStream(f, append); setFilePermissionsFromMode(f.getPath(), mode, 0); return fos; } @Override public boolean deleteFile(String name) { File f = makeFilename(getFilesDir(), name); return f.delete(); } @Override public File getFilesDir() { synchronized (mSync) { if (mFilesDir == null) { mFilesDir = new File(getDataDirFile(), "files"); } if (!mFilesDir.exists()) { if(!mFilesDir.mkdirs()) { Log.w(TAG, "Unable to create files directory " + mFilesDir.getPath()); return null; } FileUtils.setPermissions( mFilesDir.getPath(), FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, -1, -1); } return mFilesDir; } } @Override public File getExternalFilesDir(String type) { synchronized (mSync) { if (mExternalFilesDir == null) { mExternalFilesDir = Environment.getExternalStorageAppFilesDirectory( getPackageName()); } if (!mExternalFilesDir.exists()) { try { (new File(Environment.getExternalStorageAndroidDataDir(), ".nomedia")).createNewFile(); } catch (IOException e) { } if (!mExternalFilesDir.mkdirs()) { Log.w(TAG, "Unable to create external files directory"); return null; } } if (type == null) { return mExternalFilesDir; } File dir = new File(mExternalFilesDir, type); if (!dir.exists()) { if (!dir.mkdirs()) { Log.w(TAG, "Unable to create external media directory " + dir); return null; } } return dir; } } @Override public File getCacheDir() { synchronized (mSync) { if (mCacheDir == null) { mCacheDir = new File(getDataDirFile(), "cache"); } if (!mCacheDir.exists()) { if(!mCacheDir.mkdirs()) { Log.w(TAG, "Unable to create cache directory"); return null; } FileUtils.setPermissions( mCacheDir.getPath(), FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, -1, -1); } } return mCacheDir; } @Override public File getExternalCacheDir() { synchronized (mSync) { if (mExternalCacheDir == null) { mExternalCacheDir = Environment.getExternalStorageAppCacheDirectory( getPackageName()); } if (!mExternalCacheDir.exists()) { try { (new File(Environment.getExternalStorageAndroidDataDir(), ".nomedia")).createNewFile(); } catch (IOException e) { } if (!mExternalCacheDir.mkdirs()) { Log.w(TAG, "Unable to create external cache directory"); return null; } } return mExternalCacheDir; } } @Override public File getFileStreamPath(String name) { return makeFilename(getFilesDir(), name); } @Override public String[] fileList() { final String[] list = getFilesDir().list(); return (list != null) ? list : EMPTY_FILE_LIST; } @Override public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory) { File f = validateFilePath(name, true); SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(f, factory); setFilePermissionsFromMode(f.getPath(), mode, 0); return db; } @Override public boolean deleteDatabase(String name) { try { File f = validateFilePath(name, false); return f.delete(); } catch (Exception e) { } return false; } @Override public File getDatabasePath(String name) { return validateFilePath(name, false); } @Override public String[] databaseList() { final String[] list = getDatabasesDir().list(); return (list != null) ? list : EMPTY_FILE_LIST; } private File getDatabasesDir() { synchronized (mSync) { if (mDatabasesDir == null) { mDatabasesDir = new File(getDataDirFile(), "databases"); } if (mDatabasesDir.getPath().equals("databases")) { mDatabasesDir = new File("/data/system"); } return mDatabasesDir; } } @Override public Drawable getWallpaper() { return getWallpaperManager().getDrawable(); } @Override public Drawable peekWallpaper() { return getWallpaperManager().peekDrawable(); } @Override public int getWallpaperDesiredMinimumWidth() { return getWallpaperManager().getDesiredMinimumWidth(); } @Override public int getWallpaperDesiredMinimumHeight() { return getWallpaperManager().getDesiredMinimumHeight(); } @Override public void setWallpaper(Bitmap bitmap) throws IOException { getWallpaperManager().setBitmap(bitmap); } @Override public void setWallpaper(InputStream data) throws IOException { getWallpaperManager().setStream(data); } @Override public void clearWallpaper() throws IOException { getWallpaperManager().clear(); } @Override public void startActivity(Intent intent) { if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { throw new AndroidRuntimeException( "Calling startActivity() from outside of an Activity " + " context requires the FLAG_ACTIVITY_NEW_TASK flag." + " Is this really what you want?"); } mMainThread.getInstrumentation().execStartActivity( getOuterContext(), mMainThread.getApplicationThread(), null, null, intent, -1); } @Override public void startIntentSender(IntentSender intent, Intent fillInIntent, int flagsMask, int flagsValues, int extraFlags) throws IntentSender.SendIntentException { try { String resolvedType = null; if (fillInIntent != null) { resolvedType = fillInIntent.resolveTypeIfNeeded(getContentResolver()); } int result = ActivityManagerNative.getDefault() .startActivityIntentSender(mMainThread.getApplicationThread(), intent, fillInIntent, resolvedType, null, null, 0, flagsMask, flagsValues); if (result == IActivityManager.START_CANCELED) { throw new IntentSender.SendIntentException(); } Instrumentation.checkStartActivityResult(result, null); } catch (RemoteException e) { } } @Override public void sendBroadcast(Intent intent) { String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, null, Activity.RESULT_OK, null, null, null, false, false); } catch (RemoteException e) { } } @Override public void sendBroadcast(Intent intent, String receiverPermission) { String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, null, Activity.RESULT_OK, null, null, receiverPermission, false, false); } catch (RemoteException e) { } } @Override public void sendOrderedBroadcast(Intent intent, String receiverPermission) { String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, null, Activity.RESULT_OK, null, null, receiverPermission, true, false); } catch (RemoteException e) { } } @Override public void sendOrderedBroadcast(Intent intent, String receiverPermission, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { IIntentReceiver rd = null; if (resultReceiver != null) { if (mPackageInfo != null) { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = mPackageInfo.getReceiverDispatcher( resultReceiver, getOuterContext(), scheduler, mMainThread.getInstrumentation(), false); } else { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = new LoadedApk.ReceiverDispatcher( resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); } } String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, rd, initialCode, initialData, initialExtras, receiverPermission, true, false); } catch (RemoteException e) { } } @Override public void sendStickyBroadcast(Intent intent) { String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, null, Activity.RESULT_OK, null, null, null, false, true); } catch (RemoteException e) { } } @Override public void sendStickyOrderedBroadcast(Intent intent, BroadcastReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras) { IIntentReceiver rd = null; if (resultReceiver != null) { if (mPackageInfo != null) { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = mPackageInfo.getReceiverDispatcher( resultReceiver, getOuterContext(), scheduler, mMainThread.getInstrumentation(), false); } else { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = new LoadedApk.ReceiverDispatcher( resultReceiver, getOuterContext(), scheduler, null, false).getIIntentReceiver(); } } String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); try { ActivityManagerNative.getDefault().broadcastIntent( mMainThread.getApplicationThread(), intent, resolvedType, rd, initialCode, initialData, initialExtras, null, true, true); } catch (RemoteException e) { } } @Override public void removeStickyBroadcast(Intent intent) { String resolvedType = intent.resolveTypeIfNeeded(getContentResolver()); if (resolvedType != null) { intent = new Intent(intent); intent.setDataAndType(intent.getData(), resolvedType); } try { ActivityManagerNative.getDefault().unbroadcastIntent( mMainThread.getApplicationThread(), intent); } catch (RemoteException e) { } } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) { return registerReceiver(receiver, filter, null, null); } @Override public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler) { return registerReceiverInternal(receiver, filter, broadcastPermission, scheduler, getOuterContext()); } private Intent registerReceiverInternal(BroadcastReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler, Context context) { IIntentReceiver rd = null; if (receiver != null) { if (mPackageInfo != null && context != null) { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = mPackageInfo.getReceiverDispatcher( receiver, context, scheduler, mMainThread.getInstrumentation(), true); } else { if (scheduler == null) { scheduler = mMainThread.getHandler(); } rd = new LoadedApk.ReceiverDispatcher( receiver, context, scheduler, null, true).getIIntentReceiver(); } } try { return ActivityManagerNative.getDefault().registerReceiver( mMainThread.getApplicationThread(), rd, filter, broadcastPermission); } catch (RemoteException e) { return null; } } @Override public void unregisterReceiver(BroadcastReceiver receiver) { if (mPackageInfo != null) { IIntentReceiver rd = mPackageInfo.forgetReceiverDispatcher( getOuterContext(), receiver); try { ActivityManagerNative.getDefault().unregisterReceiver(rd); } catch (RemoteException e) { } } else { throw new RuntimeException("Not supported in system context"); } } @Override public ComponentName startService(Intent service) { try { ComponentName cn = ActivityManagerNative.getDefault().startService( mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(getContentResolver())); if (cn != null && cn.getPackageName().equals("!")) { throw new SecurityException( "Not allowed to start service " + service + " without permission " + cn.getClassName()); } return cn; } catch (RemoteException e) { return null; } } @Override public boolean stopService(Intent service) { try { int res = ActivityManagerNative.getDefault().stopService( mMainThread.getApplicationThread(), service, service.resolveTypeIfNeeded(getContentResolver())); if (res < 0) { throw new SecurityException( "Not allowed to stop service " + service); } return res != 0; } catch (RemoteException e) { return false; } } @Override public boolean bindService(Intent service, ServiceConnection conn, int flags) { IServiceConnection sd; if (mPackageInfo != null) { sd = mPackageInfo.getServiceDispatcher(conn, getOuterContext(), mMainThread.getHandler(), flags); } else { throw new RuntimeException("Not supported in system context"); } try { int res = ActivityManagerNative.getDefault().bindService( mMainThread.getApplicationThread(), getActivityToken(), service, service.resolveTypeIfNeeded(getContentResolver()), sd, flags); if (res < 0) { throw new SecurityException( "Not allowed to bind to service " + service); } return res != 0; } catch (RemoteException e) { return false; } } @Override public void unbindService(ServiceConnection conn) { if (mPackageInfo != null) { IServiceConnection sd = mPackageInfo.forgetServiceDispatcher( getOuterContext(), conn); try { ActivityManagerNative.getDefault().unbindService(sd); } catch (RemoteException e) { } } else { throw new RuntimeException("Not supported in system context"); } } @Override public boolean startInstrumentation(ComponentName className, String profileFile, Bundle arguments) { try { return ActivityManagerNative.getDefault().startInstrumentation( className, profileFile, 0, arguments, null); } catch (RemoteException e) { // System has crashed, nothing we can do. } return false; } @Override public Object getSystemService(String name) { if (WINDOW_SERVICE.equals(name)) { return WindowManagerImpl.getDefault(); } else if (LAYOUT_INFLATER_SERVICE.equals(name)) { synchronized (mSync) { LayoutInflater inflater = mLayoutInflater; if (inflater != null) { return inflater; } mLayoutInflater = inflater = PolicyManager.makeNewLayoutInflater(getOuterContext()); return inflater; } } else if (ACTIVITY_SERVICE.equals(name)) { return getActivityManager(); } else if (INPUT_METHOD_SERVICE.equals(name)) { return InputMethodManager.getInstance(this); } else if (ALARM_SERVICE.equals(name)) { return getAlarmManager(); } else if (ACCOUNT_SERVICE.equals(name)) { return getAccountManager(); } else if (POWER_SERVICE.equals(name)) { return getPowerManager(); } else if (CONNECTIVITY_SERVICE.equals(name)) { return getConnectivityManager(); } else if (THROTTLE_SERVICE.equals(name)) { return getThrottleManager(); } else if (WIFI_SERVICE.equals(name)) { return getWifiManager(); } else if (NOTIFICATION_SERVICE.equals(name)) { return getNotificationManager(); } else if (KEYGUARD_SERVICE.equals(name)) { return new KeyguardManager(); } else if (ACCESSIBILITY_SERVICE.equals(name)) { return AccessibilityManager.getInstance(this); } else if (LOCATION_SERVICE.equals(name)) { return getLocationManager(); } else if (SEARCH_SERVICE.equals(name)) { return getSearchManager(); } else if (SENSOR_SERVICE.equals(name)) { return getSensorManager(); } else if (STORAGE_SERVICE.equals(name)) { return getStorageManager(); } else if (USB_SERVICE.equals(name)) { return getUsbManager(); } else if (VIBRATOR_SERVICE.equals(name)) { return getVibrator(); } else if (STATUS_BAR_SERVICE.equals(name)) { synchronized (mSync) { if (mStatusBarManager == null) { mStatusBarManager = new StatusBarManager(getOuterContext()); } return mStatusBarManager; } } else if (AUDIO_SERVICE.equals(name)) { return getAudioManager(); } else if (TELEPHONY_SERVICE.equals(name)) { return getTelephonyManager(); } else if (CLIPBOARD_SERVICE.equals(name)) { return getClipboardManager(); } else if (WALLPAPER_SERVICE.equals(name)) { return getWallpaperManager(); } else if (DROPBOX_SERVICE.equals(name)) { return getDropBoxManager(); } else if (DEVICE_POLICY_SERVICE.equals(name)) { return getDevicePolicyManager(); } else if (UI_MODE_SERVICE.equals(name)) { return getUiModeManager(); } else if (DOWNLOAD_SERVICE.equals(name)) { return getDownloadManager(); } else if (NFC_SERVICE.equals(name)) { return getNfcManager(); } return null; } private AccountManager getAccountManager() { synchronized (mSync) { if (mAccountManager == null) { IBinder b = ServiceManager.getService(ACCOUNT_SERVICE); IAccountManager service = IAccountManager.Stub.asInterface(b); mAccountManager = new AccountManager(this, service); } return mAccountManager; } } private ActivityManager getActivityManager() { synchronized (mSync) { if (mActivityManager == null) { mActivityManager = new ActivityManager(getOuterContext(), mMainThread.getHandler()); } } return mActivityManager; } private AlarmManager getAlarmManager() { synchronized (sSync) { if (sAlarmManager == null) { IBinder b = ServiceManager.getService(ALARM_SERVICE); IAlarmManager service = IAlarmManager.Stub.asInterface(b); sAlarmManager = new AlarmManager(service); } } return sAlarmManager; } private PowerManager getPowerManager() { synchronized (sSync) { if (sPowerManager == null) { IBinder b = ServiceManager.getService(POWER_SERVICE); IPowerManager service = IPowerManager.Stub.asInterface(b); sPowerManager = new PowerManager(service, mMainThread.getHandler()); } } return sPowerManager; } private ConnectivityManager getConnectivityManager() { synchronized (sSync) { if (sConnectivityManager == null) { IBinder b = ServiceManager.getService(CONNECTIVITY_SERVICE); IConnectivityManager service = IConnectivityManager.Stub.asInterface(b); sConnectivityManager = new ConnectivityManager(service); } } return sConnectivityManager; } private ThrottleManager getThrottleManager() { synchronized (sSync) { if (sThrottleManager == null) { IBinder b = ServiceManager.getService(THROTTLE_SERVICE); IThrottleManager service = IThrottleManager.Stub.asInterface(b); sThrottleManager = new ThrottleManager(service); } } return sThrottleManager; } private WifiManager getWifiManager() { synchronized (sSync) { if (sWifiManager == null) { IBinder b = ServiceManager.getService(WIFI_SERVICE); IWifiManager service = IWifiManager.Stub.asInterface(b); sWifiManager = new WifiManager(service, mMainThread.getHandler()); } } return sWifiManager; } private NotificationManager getNotificationManager() { synchronized (mSync) { if (mNotificationManager == null) { mNotificationManager = new NotificationManager( new ContextThemeWrapper(getOuterContext(), com.android.internal.R.style.Theme_Dialog), mMainThread.getHandler()); } } return mNotificationManager; } private WallpaperManager getWallpaperManager() { synchronized (mSync) { if (mWallpaperManager == null) { mWallpaperManager = new WallpaperManager(getOuterContext(), mMainThread.getHandler()); } } return mWallpaperManager; } private TelephonyManager getTelephonyManager() { synchronized (mSync) { if (mTelephonyManager == null) { mTelephonyManager = new TelephonyManager(getOuterContext()); } } return mTelephonyManager; } private ClipboardManager getClipboardManager() { synchronized (mSync) { if (mClipboardManager == null) { mClipboardManager = new ClipboardManager(getOuterContext(), mMainThread.getHandler()); } } return mClipboardManager; } private LocationManager getLocationManager() { synchronized (sSync) { if (sLocationManager == null) { IBinder b = ServiceManager.getService(LOCATION_SERVICE); ILocationManager service = ILocationManager.Stub.asInterface(b); sLocationManager = new LocationManager(service); } } return sLocationManager; } private SearchManager getSearchManager() { synchronized (mSync) { if (mSearchManager == null) { mSearchManager = new SearchManager(getOuterContext(), mMainThread.getHandler()); } } return mSearchManager; } private SensorManager getSensorManager() { synchronized (mSync) { if (mSensorManager == null) { mSensorManager = new SensorManager(mMainThread.getHandler().getLooper()); } } return mSensorManager; } private StorageManager getStorageManager() { synchronized (mSync) { if (mStorageManager == null) { try { mStorageManager = new StorageManager(mMainThread.getHandler().getLooper()); } catch (RemoteException rex) { Log.e(TAG, "Failed to create StorageManager", rex); mStorageManager = null; } } } return mStorageManager; } private UsbManager getUsbManager() { synchronized (mSync) { if (mUsbManager == null) { IBinder b = ServiceManager.getService(USB_SERVICE); IUsbManager service = IUsbManager.Stub.asInterface(b); mUsbManager = new UsbManager(this, service); } } return mUsbManager; } private Vibrator getVibrator() { synchronized (mSync) { if (mVibrator == null) { mVibrator = new Vibrator(); } } return mVibrator; } private AudioManager getAudioManager() { if (mAudioManager == null) { mAudioManager = new AudioManager(this); } return mAudioManager; } /* package */ static DropBoxManager createDropBoxManager() { IBinder b = ServiceManager.getService(DROPBOX_SERVICE); IDropBoxManagerService service = IDropBoxManagerService.Stub.asInterface(b); return new DropBoxManager(service); } private DropBoxManager getDropBoxManager() { synchronized (mSync) { if (mDropBoxManager == null) { mDropBoxManager = createDropBoxManager(); } } return mDropBoxManager; } private DevicePolicyManager getDevicePolicyManager() { synchronized (mSync) { if (mDevicePolicyManager == null) { mDevicePolicyManager = DevicePolicyManager.create(this, mMainThread.getHandler()); } } return mDevicePolicyManager; } private UiModeManager getUiModeManager() { synchronized (mSync) { if (mUiModeManager == null) { mUiModeManager = new UiModeManager(); } } return mUiModeManager; } private DownloadManager getDownloadManager() { synchronized (mSync) { if (mDownloadManager == null) { mDownloadManager = new DownloadManager(getContentResolver(), getPackageName()); } } return mDownloadManager; } private NfcManager getNfcManager() { synchronized (mSync) { if (mNfcManager == null) { mNfcManager = new NfcManager(this); } } return mNfcManager; } @Override public int checkPermission(String permission, int pid, int uid) { if (permission == null) { throw new IllegalArgumentException("permission is null"); } if (!Process.supportsProcesses()) { return PackageManager.PERMISSION_GRANTED; } try { return ActivityManagerNative.getDefault().checkPermission( permission, pid, uid); } catch (RemoteException e) { return PackageManager.PERMISSION_DENIED; } } @Override public int checkCallingPermission(String permission) { if (permission == null) { throw new IllegalArgumentException("permission is null"); } if (!Process.supportsProcesses()) { return PackageManager.PERMISSION_GRANTED; } int pid = Binder.getCallingPid(); if (pid != Process.myPid()) { return checkPermission(permission, pid, Binder.getCallingUid()); } return PackageManager.PERMISSION_DENIED; } @Override public int checkCallingOrSelfPermission(String permission) { if (permission == null) { throw new IllegalArgumentException("permission is null"); } return checkPermission(permission, Binder.getCallingPid(), Binder.getCallingUid()); } private void enforce( String permission, int resultOfCheck, boolean selfToo, int uid, String message) { if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { throw new SecurityException( (message != null ? (message + ": ") : "") + (selfToo ? "Neither user " + uid + " nor current process has " : "User " + uid + " does not have ") + permission + "."); } } public void enforcePermission( String permission, int pid, int uid, String message) { enforce(permission, checkPermission(permission, pid, uid), false, uid, message); } public void enforceCallingPermission(String permission, String message) { enforce(permission, checkCallingPermission(permission), false, Binder.getCallingUid(), message); } public void enforceCallingOrSelfPermission( String permission, String message) { enforce(permission, checkCallingOrSelfPermission(permission), true, Binder.getCallingUid(), message); } @Override public void grantUriPermission(String toPackage, Uri uri, int modeFlags) { try { ActivityManagerNative.getDefault().grantUriPermission( mMainThread.getApplicationThread(), toPackage, uri, modeFlags); } catch (RemoteException e) { } } @Override public void revokeUriPermission(Uri uri, int modeFlags) { try { ActivityManagerNative.getDefault().revokeUriPermission( mMainThread.getApplicationThread(), uri, modeFlags); } catch (RemoteException e) { } } @Override public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { if (!Process.supportsProcesses()) { return PackageManager.PERMISSION_GRANTED; } try { return ActivityManagerNative.getDefault().checkUriPermission( uri, pid, uid, modeFlags); } catch (RemoteException e) { return PackageManager.PERMISSION_DENIED; } } @Override public int checkCallingUriPermission(Uri uri, int modeFlags) { if (!Process.supportsProcesses()) { return PackageManager.PERMISSION_GRANTED; } int pid = Binder.getCallingPid(); if (pid != Process.myPid()) { return checkUriPermission(uri, pid, Binder.getCallingUid(), modeFlags); } return PackageManager.PERMISSION_DENIED; } @Override public int checkCallingOrSelfUriPermission(Uri uri, int modeFlags) { return checkUriPermission(uri, Binder.getCallingPid(), Binder.getCallingUid(), modeFlags); } @Override public int checkUriPermission(Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags) { if (DEBUG) { Log.i("foo", "checkUriPermission: uri=" + uri + "readPermission=" + readPermission + " writePermission=" + writePermission + " pid=" + pid + " uid=" + uid + " mode" + modeFlags); } if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { if (readPermission == null || checkPermission(readPermission, pid, uid) == PackageManager.PERMISSION_GRANTED) { return PackageManager.PERMISSION_GRANTED; } } if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { if (writePermission == null || checkPermission(writePermission, pid, uid) == PackageManager.PERMISSION_GRANTED) { return PackageManager.PERMISSION_GRANTED; } } return uri != null ? checkUriPermission(uri, pid, uid, modeFlags) : PackageManager.PERMISSION_DENIED; } private String uriModeFlagToString(int uriModeFlags) { switch (uriModeFlags) { case Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION: return "read and write"; case Intent.FLAG_GRANT_READ_URI_PERMISSION: return "read"; case Intent.FLAG_GRANT_WRITE_URI_PERMISSION: return "write"; } throw new IllegalArgumentException( "Unknown permission mode flags: " + uriModeFlags); } private void enforceForUri( int modeFlags, int resultOfCheck, boolean selfToo, int uid, Uri uri, String message) { if (resultOfCheck != PackageManager.PERMISSION_GRANTED) { throw new SecurityException( (message != null ? (message + ": ") : "") + (selfToo ? "Neither user " + uid + " nor current process has " : "User " + uid + " does not have ") + uriModeFlagToString(modeFlags) + " permission on " + uri + "."); } } public void enforceUriPermission( Uri uri, int pid, int uid, int modeFlags, String message) { enforceForUri( modeFlags, checkUriPermission(uri, pid, uid, modeFlags), false, uid, uri, message); } public void enforceCallingUriPermission( Uri uri, int modeFlags, String message) { enforceForUri( modeFlags, checkCallingUriPermission(uri, modeFlags), false, Binder.getCallingUid(), uri, message); } public void enforceCallingOrSelfUriPermission( Uri uri, int modeFlags, String message) { enforceForUri( modeFlags, checkCallingOrSelfUriPermission(uri, modeFlags), true, Binder.getCallingUid(), uri, message); } public void enforceUriPermission( Uri uri, String readPermission, String writePermission, int pid, int uid, int modeFlags, String message) { enforceForUri(modeFlags, checkUriPermission( uri, readPermission, writePermission, pid, uid, modeFlags), false, uid, uri, message); } @Override public Context createPackageContext(String packageName, int flags) throws PackageManager.NameNotFoundException { if (packageName.equals("system") || packageName.equals("android")) { return new ContextImpl(mMainThread.getSystemContext()); } LoadedApk pi = mMainThread.getPackageInfo(packageName, flags); if (pi != null) { ContextImpl c = new ContextImpl(); c.mRestricted = (flags & CONTEXT_RESTRICTED) == CONTEXT_RESTRICTED; c.init(pi, null, mMainThread, mResources); if (c.mResources != null) { return c; } } // Should be a better exception. throw new PackageManager.NameNotFoundException( "Application package " + packageName + " not found"); } @Override public boolean isRestricted() { return mRestricted; } private File getDataDirFile() { if (mPackageInfo != null) { return mPackageInfo.getDataDirFile(); } throw new RuntimeException("Not supported in system context"); } @Override public File getDir(String name, int mode) { name = "app_" + name; File file = makeFilename(getDataDirFile(), name); if (!file.exists()) { file.mkdir(); setFilePermissionsFromMode(file.getPath(), mode, FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH); } return file; } static ContextImpl createSystemContext(ActivityThread mainThread) { ContextImpl context = new ContextImpl(); context.init(Resources.getSystem(), mainThread); return context; } ContextImpl() { // For debug only //++sInstanceCount; mOuterContext = this; } /** * Create a new ApplicationContext from an existing one. The new one * works and operates the same as the one it is copying. * * @param context Existing application context. */ public ContextImpl(ContextImpl context) { ++sInstanceCount; mPackageInfo = context.mPackageInfo; mResources = context.mResources; mMainThread = context.mMainThread; mContentResolver = context.mContentResolver; mOuterContext = this; } final void init(LoadedApk packageInfo, IBinder activityToken, ActivityThread mainThread) { init(packageInfo, activityToken, mainThread, null); } final void init(LoadedApk packageInfo, IBinder activityToken, ActivityThread mainThread, Resources container) { mPackageInfo = packageInfo; mResources = mPackageInfo.getResources(mainThread); if (mResources != null && container != null && container.getCompatibilityInfo().applicationScale != mResources.getCompatibilityInfo().applicationScale) { if (DEBUG) { Log.d(TAG, "loaded context has different scaling. Using container's" + " compatiblity info:" + container.getDisplayMetrics()); } mResources = mainThread.getTopLevelResources( mPackageInfo.getResDir(), container.getCompatibilityInfo().copy()); } mMainThread = mainThread; mContentResolver = new ApplicationContentResolver(this, mainThread); setActivityToken(activityToken); } final void init(Resources resources, ActivityThread mainThread) { mPackageInfo = null; mResources = resources; mMainThread = mainThread; mContentResolver = new ApplicationContentResolver(this, mainThread); } final void scheduleFinalCleanup(String who, String what) { mMainThread.scheduleContextCleanup(this, who, what); } final void performFinalCleanup(String who, String what) { //Log.i(TAG, "Cleanup up context: " + this); mPackageInfo.removeContextRegistrations(getOuterContext(), who, what); } final Context getReceiverRestrictedContext() { if (mReceiverRestrictedContext != null) { return mReceiverRestrictedContext; } return mReceiverRestrictedContext = new ReceiverRestrictedContext(getOuterContext()); } final void setActivityToken(IBinder token) { mActivityToken = token; } final void setOuterContext(Context context) { mOuterContext = context; } final Context getOuterContext() { return mOuterContext; } final IBinder getActivityToken() { return mActivityToken; } private static void setFilePermissionsFromMode(String name, int mode, int extraPermissions) { int perms = FileUtils.S_IRUSR|FileUtils.S_IWUSR |FileUtils.S_IRGRP|FileUtils.S_IWGRP |extraPermissions; if ((mode&MODE_WORLD_READABLE) != 0) { perms |= FileUtils.S_IROTH; } if ((mode&MODE_WORLD_WRITEABLE) != 0) { perms |= FileUtils.S_IWOTH; } if (DEBUG) { Log.i(TAG, "File " + name + ": mode=0x" + Integer.toHexString(mode) + ", perms=0x" + Integer.toHexString(perms)); } FileUtils.setPermissions(name, perms, -1, -1); } private File validateFilePath(String name, boolean createDirectory) { File dir; File f; if (name.charAt(0) == File.separatorChar) { String dirPath = name.substring(0, name.lastIndexOf(File.separatorChar)); dir = new File(dirPath); name = name.substring(name.lastIndexOf(File.separatorChar)); f = new File(dir, name); } else { dir = getDatabasesDir(); f = makeFilename(dir, name); } if (createDirectory && !dir.isDirectory() && dir.mkdir()) { FileUtils.setPermissions(dir.getPath(), FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, -1, -1); } return f; } private File makeFilename(File base, String name) { if (name.indexOf(File.separatorChar) < 0) { return new File(base, name); } throw new IllegalArgumentException( "File " + name + " contains a path separator"); } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- private static final class ApplicationContentResolver extends ContentResolver { public ApplicationContentResolver(Context context, ActivityThread mainThread) { super(context); mMainThread = mainThread; } @Override protected IContentProvider acquireProvider(Context context, String name) { return mMainThread.acquireProvider(context, name); } @Override protected IContentProvider acquireExistingProvider(Context context, String name) { return mMainThread.acquireExistingProvider(context, name); } @Override public boolean releaseProvider(IContentProvider provider) { return mMainThread.releaseProvider(provider); } private final ActivityThread mMainThread; } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /*package*/ static final class ApplicationPackageManager extends PackageManager { @Override public PackageInfo getPackageInfo(String packageName, int flags) throws NameNotFoundException { try { PackageInfo pi = mPM.getPackageInfo(packageName, flags); if (pi != null) { return pi; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(packageName); } @Override public String[] currentToCanonicalPackageNames(String[] names) { try { return mPM.currentToCanonicalPackageNames(names); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public String[] canonicalToCurrentPackageNames(String[] names) { try { return mPM.canonicalToCurrentPackageNames(names); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public Intent getLaunchIntentForPackage(String packageName) { // First see if the package has an INFO activity; the existence of // such an activity is implied to be the desired front-door for the // overall package (such as if it has multiple launcher entries). Intent intentToResolve = new Intent(Intent.ACTION_MAIN); intentToResolve.addCategory(Intent.CATEGORY_INFO); intentToResolve.setPackage(packageName); ResolveInfo resolveInfo = resolveActivity(intentToResolve, 0); // Otherwise, try to find a main launcher activity. if (resolveInfo == null) { // reuse the intent instance intentToResolve.removeCategory(Intent.CATEGORY_INFO); intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER); intentToResolve.setPackage(packageName); resolveInfo = resolveActivity(intentToResolve, 0); } if (resolveInfo == null) { return null; } Intent intent = new Intent(intentToResolve); intent.setClassName(resolveInfo.activityInfo.applicationInfo.packageName, resolveInfo.activityInfo.name); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } @Override public int[] getPackageGids(String packageName) throws NameNotFoundException { try { int[] gids = mPM.getPackageGids(packageName); if (gids == null || gids.length > 0) { return gids; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(packageName); } @Override public PermissionInfo getPermissionInfo(String name, int flags) throws NameNotFoundException { try { PermissionInfo pi = mPM.getPermissionInfo(name, flags); if (pi != null) { return pi; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(name); } @Override public List queryPermissionsByGroup(String group, int flags) throws NameNotFoundException { try { List pi = mPM.queryPermissionsByGroup(group, flags); if (pi != null) { return pi; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(group); } @Override public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) throws NameNotFoundException { try { PermissionGroupInfo pgi = mPM.getPermissionGroupInfo(name, flags); if (pgi != null) { return pgi; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(name); } @Override public List getAllPermissionGroups(int flags) { try { return mPM.getAllPermissionGroups(flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public ApplicationInfo getApplicationInfo(String packageName, int flags) throws NameNotFoundException { try { ApplicationInfo ai = mPM.getApplicationInfo(packageName, flags); if (ai != null) { return ai; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(packageName); } @Override public ActivityInfo getActivityInfo(ComponentName className, int flags) throws NameNotFoundException { try { ActivityInfo ai = mPM.getActivityInfo(className, flags); if (ai != null) { return ai; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(className.toString()); } @Override public ActivityInfo getReceiverInfo(ComponentName className, int flags) throws NameNotFoundException { try { ActivityInfo ai = mPM.getReceiverInfo(className, flags); if (ai != null) { return ai; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(className.toString()); } @Override public ServiceInfo getServiceInfo(ComponentName className, int flags) throws NameNotFoundException { try { ServiceInfo si = mPM.getServiceInfo(className, flags); if (si != null) { return si; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(className.toString()); } @Override public ProviderInfo getProviderInfo(ComponentName className, int flags) throws NameNotFoundException { try { ProviderInfo pi = mPM.getProviderInfo(className, flags); if (pi != null) { return pi; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(className.toString()); } @Override public String[] getSystemSharedLibraryNames() { try { return mPM.getSystemSharedLibraryNames(); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public FeatureInfo[] getSystemAvailableFeatures() { try { return mPM.getSystemAvailableFeatures(); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public boolean hasSystemFeature(String name) { try { return mPM.hasSystemFeature(name); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public int checkPermission(String permName, String pkgName) { try { return mPM.checkPermission(permName, pkgName); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public boolean addPermission(PermissionInfo info) { try { return mPM.addPermission(info); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public boolean addPermissionAsync(PermissionInfo info) { try { return mPM.addPermissionAsync(info); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public void removePermission(String name) { try { mPM.removePermission(name); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public int checkSignatures(String pkg1, String pkg2) { try { return mPM.checkSignatures(pkg1, pkg2); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public int checkSignatures(int uid1, int uid2) { try { return mPM.checkUidSignatures(uid1, uid2); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public String[] getPackagesForUid(int uid) { try { return mPM.getPackagesForUid(uid); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public String getNameForUid(int uid) { try { return mPM.getNameForUid(uid); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public int getUidForSharedUser(String sharedUserName) throws NameNotFoundException { try { int uid = mPM.getUidForSharedUser(sharedUserName); if(uid != -1) { return uid; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException("No shared userid for user:"+sharedUserName); } @Override public List getInstalledPackages(int flags) { try { return mPM.getInstalledPackages(flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public List getInstalledApplications(int flags) { try { return mPM.getInstalledApplications(flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public ResolveInfo resolveActivity(Intent intent, int flags) { try { return mPM.resolveIntent( intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public List queryIntentActivities(Intent intent, int flags) { try { return mPM.queryIntentActivities( intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public List queryIntentActivityOptions( ComponentName caller, Intent[] specifics, Intent intent, int flags) { final ContentResolver resolver = mContext.getContentResolver(); String[] specificTypes = null; if (specifics != null) { final int N = specifics.length; for (int i=0; i queryBroadcastReceivers(Intent intent, int flags) { try { return mPM.queryIntentReceivers( intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public ResolveInfo resolveService(Intent intent, int flags) { try { return mPM.resolveService( intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public List queryIntentServices(Intent intent, int flags) { try { return mPM.queryIntentServices( intent, intent.resolveTypeIfNeeded(mContext.getContentResolver()), flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public ProviderInfo resolveContentProvider(String name, int flags) { try { return mPM.resolveContentProvider(name, flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public List queryContentProviders(String processName, int uid, int flags) { try { return mPM.queryContentProviders(processName, uid, flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public InstrumentationInfo getInstrumentationInfo( ComponentName className, int flags) throws NameNotFoundException { try { InstrumentationInfo ii = mPM.getInstrumentationInfo( className, flags); if (ii != null) { return ii; } } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } throw new NameNotFoundException(className.toString()); } @Override public List queryInstrumentation( String targetPackage, int flags) { try { return mPM.queryInstrumentation(targetPackage, flags); } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } @Override public Drawable getDrawable(String packageName, int resid, ApplicationInfo appInfo) { ResourceName name = new ResourceName(packageName, resid); Drawable dr = getCachedIcon(name); if (dr != null) { return dr; } if (appInfo == null) { try { appInfo = getApplicationInfo(packageName, 0); } catch (NameNotFoundException e) { return null; } } try { Resources r = getResourcesForApplication(appInfo); dr = r.getDrawable(resid); if (false) { RuntimeException e = new RuntimeException("here"); e.fillInStackTrace(); Log.w(TAG, "Getting drawable 0x" + Integer.toHexString(resid) + " from package " + packageName + ": app scale=" + r.getCompatibilityInfo().applicationScale + ", caller scale=" + mContext.getResources().getCompatibilityInfo().applicationScale, e); } if (DEBUG_ICONS) Log.v(TAG, "Getting drawable 0x" + Integer.toHexString(resid) + " from " + r + ": " + dr); putCachedIcon(name, dr); return dr; } catch (NameNotFoundException e) { Log.w("PackageManager", "Failure retrieving resources for" + appInfo.packageName); } catch (RuntimeException e) { // If an exception was thrown, fall through to return // default icon. Log.w("PackageManager", "Failure retrieving icon 0x" + Integer.toHexString(resid) + " in package " + packageName, e); } return null; } @Override public Drawable getActivityIcon(ComponentName activityName) throws NameNotFoundException { return getActivityInfo(activityName, 0).loadIcon(this); } @Override public Drawable getActivityIcon(Intent intent) throws NameNotFoundException { if (intent.getComponent() != null) { return getActivityIcon(intent.getComponent()); } ResolveInfo info = resolveActivity( intent, PackageManager.MATCH_DEFAULT_ONLY); if (info != null) { return info.activityInfo.loadIcon(this); } throw new NameNotFoundException(intent.toURI()); } @Override public Drawable getDefaultActivityIcon() { return Resources.getSystem().getDrawable( com.android.internal.R.drawable.sym_def_app_icon); } @Override public Drawable getApplicationIcon(ApplicationInfo info) { return info.loadIcon(this); } @Override public Drawable getApplicationIcon(String packageName) throws NameNotFoundException { return getApplicationIcon(getApplicationInfo(packageName, 0)); } @Override public Drawable getActivityLogo(ComponentName activityName) throws NameNotFoundException { return getActivityInfo(activityName, 0).loadLogo(this); } @Override public Drawable getActivityLogo(Intent intent) throws NameNotFoundException { if (intent.getComponent() != null) { return getActivityLogo(intent.getComponent()); } ResolveInfo info = resolveActivity( intent, PackageManager.MATCH_DEFAULT_ONLY); if (info != null) { return info.activityInfo.loadLogo(this); } throw new NameNotFoundException(intent.toUri(0)); } @Override public Drawable getApplicationLogo(ApplicationInfo info) { return info.loadLogo(this); } @Override public Drawable getApplicationLogo(String packageName) throws NameNotFoundException { return getApplicationLogo(getApplicationInfo(packageName, 0)); } @Override public Resources getResourcesForActivity( ComponentName activityName) throws NameNotFoundException { return getResourcesForApplication( getActivityInfo(activityName, 0).applicationInfo); } @Override public Resources getResourcesForApplication( ApplicationInfo app) throws NameNotFoundException { if (app.packageName.equals("system")) { return mContext.mMainThread.getSystemContext().getResources(); } Resources r = mContext.mMainThread.getTopLevelResources( app.uid == Process.myUid() ? app.sourceDir : app.publicSourceDir, mContext.mPackageInfo); if (r != null) { return r; } throw new NameNotFoundException("Unable to open " + app.publicSourceDir); } @Override public Resources getResourcesForApplication( String appPackageName) throws NameNotFoundException { return getResourcesForApplication( getApplicationInfo(appPackageName, 0)); } int mCachedSafeMode = -1; @Override public boolean isSafeMode() { try { if (mCachedSafeMode < 0) { mCachedSafeMode = mPM.isSafeMode() ? 1 : 0; } return mCachedSafeMode != 0; } catch (RemoteException e) { throw new RuntimeException("Package manager has died", e); } } static void configurationChanged() { synchronized (sSync) { sIconCache.clear(); sStringCache.clear(); } } ApplicationPackageManager(ContextImpl context, IPackageManager pm) { mContext = context; mPM = pm; } private Drawable getCachedIcon(ResourceName name) { synchronized (sSync) { WeakReference wr = sIconCache.get(name); if (DEBUG_ICONS) Log.v(TAG, "Get cached weak drawable ref for " + name + ": " + wr); if (wr != null) { // we have the activity Drawable dr = wr.get(); if (dr != null) { if (DEBUG_ICONS) Log.v(TAG, "Get cached drawable for " + name + ": " + dr); return dr; } // our entry has been purged sIconCache.remove(name); } } return null; } private void putCachedIcon(ResourceName name, Drawable dr) { synchronized (sSync) { sIconCache.put(name, new WeakReference(dr)); if (DEBUG_ICONS) Log.v(TAG, "Added cached drawable for " + name + ": " + dr); } } static final void handlePackageBroadcast(int cmd, String[] pkgList, boolean hasPkgInfo) { boolean immediateGc = false; if (cmd == IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE) { immediateGc = true; } if (pkgList != null && (pkgList.length > 0)) { boolean needCleanup = false; for (String ssp : pkgList) { synchronized (sSync) { if (sIconCache.size() > 0) { Iterator it = sIconCache.keySet().iterator(); while (it.hasNext()) { ResourceName nm = it.next(); if (nm.packageName.equals(ssp)) { //Log.i(TAG, "Removing cached drawable for " + nm); it.remove(); needCleanup = true; } } } if (sStringCache.size() > 0) { Iterator it = sStringCache.keySet().iterator(); while (it.hasNext()) { ResourceName nm = it.next(); if (nm.packageName.equals(ssp)) { //Log.i(TAG, "Removing cached string for " + nm); it.remove(); needCleanup = true; } } } } } if (needCleanup || hasPkgInfo) { if (immediateGc) { // Schedule an immediate gc. Runtime.getRuntime().gc(); } else { ActivityThread.currentActivityThread().scheduleGcIdler(); } } } } private static final class ResourceName { final String packageName; final int iconId; ResourceName(String _packageName, int _iconId) { packageName = _packageName; iconId = _iconId; } ResourceName(ApplicationInfo aInfo, int _iconId) { this(aInfo.packageName, _iconId); } ResourceName(ComponentInfo cInfo, int _iconId) { this(cInfo.applicationInfo.packageName, _iconId); } ResourceName(ResolveInfo rInfo, int _iconId) { this(rInfo.activityInfo.applicationInfo.packageName, _iconId); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ResourceName that = (ResourceName) o; if (iconId != that.iconId) return false; return !(packageName != null ? !packageName.equals(that.packageName) : that.packageName != null); } @Override public int hashCode() { int result; result = packageName.hashCode(); result = 31 * result + iconId; return result; } @Override public String toString() { return "{ResourceName " + packageName + " / " + iconId + "}"; } } private CharSequence getCachedString(ResourceName name) { synchronized (sSync) { WeakReference wr = sStringCache.get(name); if (wr != null) { // we have the activity CharSequence cs = wr.get(); if (cs != null) { return cs; } // our entry has been purged sStringCache.remove(name); } } return null; } private void putCachedString(ResourceName name, CharSequence cs) { synchronized (sSync) { sStringCache.put(name, new WeakReference(cs)); } } @Override public CharSequence getText(String packageName, int resid, ApplicationInfo appInfo) { ResourceName name = new ResourceName(packageName, resid); CharSequence text = getCachedString(name); if (text != null) { return text; } if (appInfo == null) { try { appInfo = getApplicationInfo(packageName, 0); } catch (NameNotFoundException e) { return null; } } try { Resources r = getResourcesForApplication(appInfo); text = r.getText(resid); putCachedString(name, text); return text; } catch (NameNotFoundException e) { Log.w("PackageManager", "Failure retrieving resources for" + appInfo.packageName); } catch (RuntimeException e) { // If an exception was thrown, fall through to return // default icon. Log.w("PackageManager", "Failure retrieving text 0x" + Integer.toHexString(resid) + " in package " + packageName, e); } return null; } @Override public XmlResourceParser getXml(String packageName, int resid, ApplicationInfo appInfo) { if (appInfo == null) { try { appInfo = getApplicationInfo(packageName, 0); } catch (NameNotFoundException e) { return null; } } try { Resources r = getResourcesForApplication(appInfo); return r.getXml(resid); } catch (RuntimeException e) { // If an exception was thrown, fall through to return // default icon. Log.w("PackageManager", "Failure retrieving xml 0x" + Integer.toHexString(resid) + " in package " + packageName, e); } catch (NameNotFoundException e) { Log.w("PackageManager", "Failure retrieving resources for" + appInfo.packageName); } return null; } @Override public CharSequence getApplicationLabel(ApplicationInfo info) { return info.loadLabel(this); } @Override public void installPackage(Uri packageURI, IPackageInstallObserver observer, int flags, String installerPackageName) { try { mPM.installPackage(packageURI, observer, flags, installerPackageName); } catch (RemoteException e) { // Should never happen! } } @Override public void movePackage(String packageName, IPackageMoveObserver observer, int flags) { try { mPM.movePackage(packageName, observer, flags); } catch (RemoteException e) { // Should never happen! } } @Override public String getInstallerPackageName(String packageName) { try { return mPM.getInstallerPackageName(packageName); } catch (RemoteException e) { // Should never happen! } return null; } @Override public void deletePackage(String packageName, IPackageDeleteObserver observer, int flags) { try { mPM.deletePackage(packageName, observer, flags); } catch (RemoteException e) { // Should never happen! } } @Override public void clearApplicationUserData(String packageName, IPackageDataObserver observer) { try { mPM.clearApplicationUserData(packageName, observer); } catch (RemoteException e) { // Should never happen! } } @Override public void deleteApplicationCacheFiles(String packageName, IPackageDataObserver observer) { try { mPM.deleteApplicationCacheFiles(packageName, observer); } catch (RemoteException e) { // Should never happen! } } @Override public void freeStorageAndNotify(long idealStorageSize, IPackageDataObserver observer) { try { mPM.freeStorageAndNotify(idealStorageSize, observer); } catch (RemoteException e) { // Should never happen! } } @Override public void freeStorage(long freeStorageSize, IntentSender pi) { try { mPM.freeStorage(freeStorageSize, pi); } catch (RemoteException e) { // Should never happen! } } @Override public void getPackageSizeInfo(String packageName, IPackageStatsObserver observer) { try { mPM.getPackageSizeInfo(packageName, observer); } catch (RemoteException e) { // Should never happen! } } @Override public void addPackageToPreferred(String packageName) { try { mPM.addPackageToPreferred(packageName); } catch (RemoteException e) { // Should never happen! } } @Override public void removePackageFromPreferred(String packageName) { try { mPM.removePackageFromPreferred(packageName); } catch (RemoteException e) { // Should never happen! } } @Override public List getPreferredPackages(int flags) { try { return mPM.getPreferredPackages(flags); } catch (RemoteException e) { // Should never happen! } return new ArrayList(); } @Override public void addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity) { try { mPM.addPreferredActivity(filter, match, set, activity); } catch (RemoteException e) { // Should never happen! } } @Override public void replacePreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity) { try { mPM.replacePreferredActivity(filter, match, set, activity); } catch (RemoteException e) { // Should never happen! } } @Override public void clearPackagePreferredActivities(String packageName) { try { mPM.clearPackagePreferredActivities(packageName); } catch (RemoteException e) { // Should never happen! } } @Override public int getPreferredActivities(List outFilters, List outActivities, String packageName) { try { return mPM.getPreferredActivities(outFilters, outActivities, packageName); } catch (RemoteException e) { // Should never happen! } return 0; } @Override public void setComponentEnabledSetting(ComponentName componentName, int newState, int flags) { try { mPM.setComponentEnabledSetting(componentName, newState, flags); } catch (RemoteException e) { // Should never happen! } } @Override public int getComponentEnabledSetting(ComponentName componentName) { try { return mPM.getComponentEnabledSetting(componentName); } catch (RemoteException e) { // Should never happen! } return PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; } @Override public void setApplicationEnabledSetting(String packageName, int newState, int flags) { try { mPM.setApplicationEnabledSetting(packageName, newState, flags); } catch (RemoteException e) { // Should never happen! } } @Override public int getApplicationEnabledSetting(String packageName) { try { return mPM.getApplicationEnabledSetting(packageName); } catch (RemoteException e) { // Should never happen! } return PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; } private final ContextImpl mContext; private final IPackageManager mPM; private static final Object sSync = new Object(); private static HashMap > sIconCache = new HashMap >(); private static HashMap > sStringCache = new HashMap >(); } // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- private static final class SharedPreferencesImpl implements SharedPreferences { // Lock ordering rules: // - acquire SharedPreferencesImpl.this before EditorImpl.this // - acquire mWritingToDiskLock before EditorImpl.this private final File mFile; private final File mBackupFile; private final int mMode; private Map mMap; // guarded by 'this' private int mDiskWritesInFlight = 0; // guarded by 'this' private boolean mLoaded = false; // guarded by 'this' private long mStatTimestamp; // guarded by 'this' private long mStatSize; // guarded by 'this' private final Object mWritingToDiskLock = new Object(); private static final Object mContent = new Object(); private final WeakHashMap mListeners; SharedPreferencesImpl( File file, int mode, Map initialContents) { mFile = file; mBackupFile = makeBackupFile(file); mMode = mode; mLoaded = initialContents != null; mMap = initialContents != null ? initialContents : new HashMap(); FileStatus stat = new FileStatus(); if (FileUtils.getFileStatus(file.getPath(), stat)) { mStatTimestamp = stat.mtime; } mListeners = new WeakHashMap(); } // Has this SharedPreferences ever had values assigned to it? boolean isLoaded() { synchronized (this) { return mLoaded; } } // Has the file changed out from under us? i.e. writes that // we didn't instigate. public boolean hasFileChangedUnexpectedly() { synchronized (this) { if (mDiskWritesInFlight > 0) { // If we know we caused it, it's not unexpected. if (DEBUG) Log.d(TAG, "disk write in flight, not unexpected."); return false; } } FileStatus stat = new FileStatus(); if (!FileUtils.getFileStatus(mFile.getPath(), stat)) { return true; } synchronized (this) { return mStatTimestamp != stat.mtime || mStatSize != stat.size; } } /* package */ void replace(Map newContents, FileStatus stat) { synchronized (this) { mLoaded = true; if (newContents != null) { mMap = newContents; } if (stat != null) { mStatTimestamp = stat.mtime; mStatSize = stat.size; } } } public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { synchronized(this) { mListeners.put(listener, mContent); } } public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) { synchronized(this) { mListeners.remove(listener); } } public Map getAll() { synchronized(this) { //noinspection unchecked return new HashMap(mMap); } } public String getString(String key, String defValue) { synchronized (this) { String v = (String)mMap.get(key); return v != null ? v : defValue; } } public int getInt(String key, int defValue) { synchronized (this) { Integer v = (Integer)mMap.get(key); return v != null ? v : defValue; } } public long getLong(String key, long defValue) { synchronized (this) { Long v = (Long)mMap.get(key); return v != null ? v : defValue; } } public float getFloat(String key, float defValue) { synchronized (this) { Float v = (Float)mMap.get(key); return v != null ? v : defValue; } } public boolean getBoolean(String key, boolean defValue) { synchronized (this) { Boolean v = (Boolean)mMap.get(key); return v != null ? v : defValue; } } public boolean contains(String key) { synchronized (this) { return mMap.containsKey(key); } } public Editor edit() { return new EditorImpl(); } // Return value from EditorImpl#commitToMemory() private static class MemoryCommitResult { public boolean changesMade; // any keys different? public List keysModified; // may be null public Set listeners; // may be null public Map mapToWriteToDisk; public final CountDownLatch writtenToDiskLatch = new CountDownLatch(1); public volatile boolean writeToDiskResult = false; public void setDiskWriteResult(boolean result) { writeToDiskResult = result; writtenToDiskLatch.countDown(); } } public final class EditorImpl implements Editor { private final Map mModified = Maps.newHashMap(); private boolean mClear = false; public Editor putString(String key, String value) { synchronized (this) { mModified.put(key, value); return this; } } public Editor putInt(String key, int value) { synchronized (this) { mModified.put(key, value); return this; } } public Editor putLong(String key, long value) { synchronized (this) { mModified.put(key, value); return this; } } public Editor putFloat(String key, float value) { synchronized (this) { mModified.put(key, value); return this; } } public Editor putBoolean(String key, boolean value) { synchronized (this) { mModified.put(key, value); return this; } } public Editor remove(String key) { synchronized (this) { mModified.put(key, this); return this; } } public Editor clear() { synchronized (this) { mClear = true; return this; } } public void apply() { final MemoryCommitResult mcr = commitToMemory(); final Runnable awaitCommit = new Runnable() { public void run() { try { mcr.writtenToDiskLatch.await(); } catch (InterruptedException ignored) { } } }; QueuedWork.add(awaitCommit); Runnable postWriteRunnable = new Runnable() { public void run() { awaitCommit.run(); QueuedWork.remove(awaitCommit); } }; SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable); // Okay to notify the listeners before it's hit disk // because the listeners should always get the same // SharedPreferences instance back, which has the // changes reflected in memory. notifyListeners(mcr); } // Returns true if any changes were made private MemoryCommitResult commitToMemory() { MemoryCommitResult mcr = new MemoryCommitResult(); synchronized (SharedPreferencesImpl.this) { // We optimistically don't make a deep copy until // a memory commit comes in when we're already // writing to disk. if (mDiskWritesInFlight > 0) { // We can't modify our mMap as a currently // in-flight write owns it. Clone it before // modifying it. // noinspection unchecked mMap = new HashMap(mMap); } mcr.mapToWriteToDisk = mMap; mDiskWritesInFlight++; boolean hasListeners = mListeners.size() > 0; if (hasListeners) { mcr.keysModified = new ArrayList(); mcr.listeners = new HashSet(mListeners.keySet()); } synchronized (this) { if (mClear) { if (!mMap.isEmpty()) { mcr.changesMade = true; mMap.clear(); } mClear = false; } for (Entry e : mModified.entrySet()) { String k = e.getKey(); Object v = e.getValue(); if (v == this) { // magic value for a removal mutation if (!mMap.containsKey(k)) { continue; } mMap.remove(k); } else { boolean isSame = false; if (mMap.containsKey(k)) { Object existingValue = mMap.get(k); if (existingValue != null && existingValue.equals(v)) { continue; } } mMap.put(k, v); } mcr.changesMade = true; if (hasListeners) { mcr.keysModified.add(k); } } mModified.clear(); } } return mcr; } public boolean commit() { MemoryCommitResult mcr = commitToMemory(); SharedPreferencesImpl.this.enqueueDiskWrite( mcr, null /* sync write on this thread okay */); try { mcr.writtenToDiskLatch.await(); } catch (InterruptedException e) { return false; } notifyListeners(mcr); return mcr.writeToDiskResult; } private void notifyListeners(final MemoryCommitResult mcr) { if (mcr.listeners == null || mcr.keysModified == null || mcr.keysModified.size() == 0) { return; } if (Looper.myLooper() == Looper.getMainLooper()) { for (int i = mcr.keysModified.size() - 1; i >= 0; i--) { final String key = mcr.keysModified.get(i); for (OnSharedPreferenceChangeListener listener : mcr.listeners) { if (listener != null) { listener.onSharedPreferenceChanged(SharedPreferencesImpl.this, key); } } } } else { // Run this function on the main thread. ActivityThread.sMainThreadHandler.post(new Runnable() { public void run() { notifyListeners(mcr); } }); } } } /** * Enqueue an already-committed-to-memory result to be written * to disk. * * They will be written to disk one-at-a-time in the order * that they're enqueued. * * @param postWriteRunnable if non-null, we're being called * from apply() and this is the runnable to run after * the write proceeds. if null (from a regular commit()), * then we're allowed to do this disk write on the main * thread (which in addition to reducing allocations and * creating a background thread, this has the advantage that * we catch them in userdebug StrictMode reports to convert * them where possible to apply() ...) */ private void enqueueDiskWrite(final MemoryCommitResult mcr, final Runnable postWriteRunnable) { final Runnable writeToDiskRunnable = new Runnable() { public void run() { synchronized (mWritingToDiskLock) { writeToFile(mcr); } synchronized (SharedPreferencesImpl.this) { mDiskWritesInFlight--; } if (postWriteRunnable != null) { postWriteRunnable.run(); } } }; final boolean isFromSyncCommit = (postWriteRunnable == null); // Typical #commit() path with fewer allocations, doing a write on // the current thread. if (isFromSyncCommit) { boolean wasEmpty = false; synchronized (SharedPreferencesImpl.this) { wasEmpty = mDiskWritesInFlight == 1; } if (wasEmpty) { writeToDiskRunnable.run(); return; } } QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable); } private static FileOutputStream createFileOutputStream(File file) { FileOutputStream str = null; try { str = new FileOutputStream(file); } catch (FileNotFoundException e) { File parent = file.getParentFile(); if (!parent.mkdir()) { Log.e(TAG, "Couldn't create directory for SharedPreferences file " + file); return null; } FileUtils.setPermissions( parent.getPath(), FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH, -1, -1); try { str = new FileOutputStream(file); } catch (FileNotFoundException e2) { Log.e(TAG, "Couldn't create SharedPreferences file " + file, e2); } } return str; } // Note: must hold mWritingToDiskLock private void writeToFile(MemoryCommitResult mcr) { // Rename the current file so it may be used as a backup during the next read if (mFile.exists()) { if (!mcr.changesMade) { // If the file already exists, but no changes were // made to the underlying map, it's wasteful to // re-write the file. Return as if we wrote it // out. mcr.setDiskWriteResult(true); return; } if (!mBackupFile.exists()) { if (!mFile.renameTo(mBackupFile)) { Log.e(TAG, "Couldn't rename file " + mFile + " to backup file " + mBackupFile); mcr.setDiskWriteResult(false); return; } } else { mFile.delete(); } } // Attempt to write the file, delete the backup and return true as atomically as // possible. If any exception occurs, delete the new file; next time we will restore // from the backup. try { FileOutputStream str = createFileOutputStream(mFile); if (str == null) { mcr.setDiskWriteResult(false); return; } XmlUtils.writeMapXml(mcr.mapToWriteToDisk, str); FileUtils.sync(str); str.close(); setFilePermissionsFromMode(mFile.getPath(), mMode, 0); FileStatus stat = new FileStatus(); if (FileUtils.getFileStatus(mFile.getPath(), stat)) { synchronized (this) { mStatTimestamp = stat.mtime; mStatSize = stat.size; } } // Writing was successful, delete the backup file if there is one. mBackupFile.delete(); mcr.setDiskWriteResult(true); return; } catch (XmlPullParserException e) { Log.w(TAG, "writeToFile: Got exception:", e); } catch (IOException e) { Log.w(TAG, "writeToFile: Got exception:", e); } // Clean up an unsuccessfully written file if (mFile.exists()) { if (!mFile.delete()) { Log.e(TAG, "Couldn't clean up partially-written file " + mFile); } } mcr.setDiskWriteResult(false); } } } package me.dwtj.java.compiler.utils.dagger; import dagger.Module; import dagger.Provides; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.inject.Singleton; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; /** * A dagger dependency injection module which provides various core utilities available within any * standard Java annotation processing environment. The utilities provided come from the {@link * javax.lang.model Java Language Model API} and the {@link javax.annotation.processing The Java * Annotation Processing API}. * * @see * The Java Language Model API * * @see * The Java Annotation Processing API * * * @author dwtj */ @Module public class StandardProcessingEnvironmentModule { protected final ProcessingEnvironment procEnv; public StandardProcessingEnvironmentModule(ProcessingEnvironment procEnv) { this.procEnv = procEnv; } @Provides @Singleton public ProcessingEnvironment provideProcEnv() { return procEnv; } @Provides @Singleton public Elements provideElementUtils() { return procEnv.getElementUtils(); } @Provides @Singleton public Types provideTypeUtils() { return procEnv.getTypeUtils(); } @Provides @Singleton public Messager provideMessager() { return procEnv.getMessager(); } @Provides @Singleton public Filer provideFiler() { return procEnv.getFiler(); } } /* * Copyright (c) 2004, PostgreSQL Global Development Group * See the LICENSE file in the project root for more information. */ package org.postgresql.test.jdbc2; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import org.postgresql.test.TestUtil; import org.junit.Ignore; import org.junit.Test; import org.postgresql.util.SetUpTearDownIMPL; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; /* * Some simple tests based on problems reported by users. Hopefully these will help prevent previous * problems from re-occurring ;-) * */ public class MiscTest extends SetUpTearDownIMPL { /* * Some versions of the driver would return rs as a null? * * Sasha <> was having this problem. * * Added Feb 13 2001 */ @Test public void testDatabaseSelectNullBug() throws Exception { Connection con = TestUtil.openDB(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select datname from pg_database"); assertNotNull(rs); while (rs.next()) { rs.getString(1); } rs.close(); st.close(); TestUtil.closeDB(con); } /** * Ensure the cancel call does not return before it has completed. Previously it did which * cancelled future queries. */ @Test public void testSingleThreadCancel() throws Exception { Connection con = TestUtil.openDB(); Statement stmt = con.createStatement(); for (int i = 0; i < 100; i++) { ResultSet rs = stmt.executeQuery("SELECT 1"); rs.close(); stmt.cancel(); } TestUtil.closeDB(con); } @Test public void testError() throws Exception { Connection con = TestUtil.openDB(); try { // transaction mode con.setAutoCommit(false); Statement stmt = con.createStatement(); stmt.execute("select 1/0"); fail("Should not execute this, as a SQLException s/b thrown"); con.commit(); } catch (SQLException ex) { // Verify that the SQLException is serializable. ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(ex); oos.close(); } con.commit(); con.close(); } @Test public void testWarning() throws Exception { Connection con = TestUtil.openDB(); Statement stmt = con.createStatement(); stmt.execute("CREATE TEMP TABLE t(a int primary key)"); SQLWarning warning = stmt.getWarnings(); // We should get a warning about primary key index creation // it's possible we won't depending on the server's // client_min_messages setting. while (warning != null) { // Verify that the SQLWarning is serializable. ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(warning); oos.close(); warning = warning.getNextWarning(); } stmt.close(); con.close(); } @Ignore @Test public void xtestLocking() throws Exception { Connection con = TestUtil.openDB(); Connection con2 = TestUtil.openDB(); TestUtil.createTable(con, "test_lock", "name text"); Statement st = con.createStatement(); Statement st2 = con2.createStatement(); con.setAutoCommit(false); st.execute("lock table test_lock"); st2.executeUpdate("insert into test_lock ( name ) values ('hello')"); con.commit(); TestUtil.dropTable(con, "test_lock"); con.close(); con2.close(); } } /* * Copyright 2017 dmfs GmbH * * 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.dmfs.android.contentpal.rowdatasnapshots; import org.junit.Test; import static org.dmfs.jems.hamcrest.matchers.optional.AbsentMatcher.absent; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * @author */ public class EmptyRowDataSnapshotTest { @Test public void testCharData() { assertThat(new EmptyRowDataSnapshot<>().data("key", x -> x), is(absent())); } @Test public void testByteData() { assertThat(new EmptyRowDataSnapshot<>().byteData("key"), is(absent())); } @Test public void testIterator() { assertThat(new EmptyRowDataSnapshot<>(), emptyIterable()); } }0 package com.github.filipmalczak.vent.mongo.service; import com.github.filipmalczak.vent.api.model.ObjectSnapshot; import com.github.filipmalczak.vent.api.model.VentId; import com.github.filipmalczak.vent.mongo.model.Page; import com.github.filipmalczak.vent.mongo.model.events.Event; import lombok.AllArgsConstructor; import lombok.NonNull; import reactor.core.publisher.Mono; import java.time.LocalDateTime; import java.util.List; import java.util.Map; import static com.github.filipmalczak.vent.mongo.utils.MongoTranslator.fromMongo; @AllArgsConstructor public class SnapshotService { private SnapshotRenderer snapshotRenderer; private PageService pageService; public Mono getSnapshot(@NonNull String collectionName, @NonNull VentId ventId, @NonNull LocalDateTime queryAt){ return pageService. pageAtTimestamp(collectionName, ventId, queryAt). map(p -> render(p, queryAt)); } public ObjectSnapshot render(Page page, LocalDateTime queryAt){ return render( fromMongo(page.getObjectId()), page.getFromVersion(), page.getStartingFrom(), //todo page. getInstructionsForSnapshotAt(queryAt). orElseThrow(() -> new RuntimeException("This page in not renderable at that timestamp!")), queryAt ); } private ObjectSnapshot render(VentId ventId, long pageFromVersion, LocalDateTime pageFrom, Page.SnapshotInstructions instructions, LocalDateTime queryAt){ Map object = snapshotRenderer.render(instructions); List events = instructions.getEvents(); return ObjectSnapshot.builder(). ventId(ventId). state(object). version(pageFromVersion + events.size()). queryTime(queryAt). lastUpdate(events.isEmpty() ? pageFrom : events.get(events.size()-1).getOccuredOn()). build(); } } package vanadis.extrt; import org.osgi.framework.Bundle; import vanadis.common.text.Printer; import vanadis.ext.CommandExecution; import vanadis.osgi.Context; class UnresolvedExecution implements CommandExecution { private final Bundles bundles; UnresolvedExecution(Bundles bundles) { this.bundles = bundles; } @Override public void exec(String command, String[] args, Printer ps, Context context) { writeBundleResolveErrors(ps); } private void writeBundleResolveErrors(Printer p) { if (bundles.hasUnresolved()) { p.p("Unresolved bundles: ").p(bundles.uresolvedNames()).cr().ind(); for (Long id : bundles.uresolvedIds()) { Bundle bundle = bundles.getBundle(id); String name = bundle.getSymbolicName(); p.p(id).p(" [").p(name).p("] ").p(bundles.resolveError(name)).cr(); } p.outd(); } } } package br.com.digidev.messenger4j.send.buttons; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.Test; /** * @author Messenger4J - http://github.com/messenger4j */ public class PostbackButtonTest { @Test public void shouldHaveACorrectEqualsImplementation() { EqualsVerifier.forClass(PostbackButton.class) .usingGetClass() .verify(); } }0 /* * 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.sis.storage; import java.util.List; import java.util.Collections; import org.apache.sis.coverage.SampleDimension; import org.apache.sis.coverage.grid.GridGeometry; import org.apache.sis.coverage.grid.GridCoverage; import org.apache.sis.util.ArgumentChecks; import org.apache.sis.util.ArraysExt; /** * Access to data values in a n-dimensional grid. * A coverage is a kind of function with the following properties: * *
    *
  • The function input is a position valid in the coverage domain. In the particular case of * {@link GridCoverage}, the domain is described by a {@linkplain #getGridGeometry() grid geometry}.
  • *
  • The function output is a record of values in the coverage range. In the particular case of * {@link GridCoverage}, the range is described by a list of {@linkplain #getSampleDimensions() sample dimensions}.
  • *
* * A coverage resource may be a member of {@link Aggregate} if a single file can provide many rasters. * * @author (Geomatys) * @author (Geomatys) * @version 1.2 * @since 1.0 * @module */ public interface GridCoverageResource extends DataSet { /** * Returns the valid extent of grid coordinates together with the conversion from those grid * coordinates to real world coordinates. A grid geometry contains the following information: * *
    *
  • The minimum and maximum grid coordinates as integers (the Grid Extent). * The minimum coordinates are typically (0,0, …, 0) but not necessarily.
  • *
  • The minimum and maximum "real world" coordinates (the Envelope). * Those coordinates are typically, but not necessarily, latitudes and longitudes * or projected coordinates, together with altitudes and dates.
  • *
  • A description of the datum and axes of above "real world" coordinates * (the Coordinate Reference System).
  • *
  • The conversion from grid coordinates to "real world" coordinates. This conversion is often, * but not necessarily, a linear relationship. Axis order or direction may be changed by the conversion. * For example row indices may be increasing toward down while latitude coordinates are increasing toward up.
  • *
  • An estimation of grid resolution for each "real world" axis.
  • *
* * The grid returned by this method should be equal to the grid returned by * {@linkplain #read(GridGeometry, int...) read}(null).{@linkplain GridCoverage#getGridGeometry() getGridGeometry()}. * However the grid geometry returned by this method is allowed to be only approximate if computing accurate information would be * prohibitively expensive, or if the grid geometry depends on the exact argument value given to the {@code read(…)} method. * At least, the {@linkplain GridGeometry#getDimension() number of dimensions} should match. * * @return extent of grid coordinates together with their mapping to "real world" coordinates. * @throws DataStoreException if an error occurred while reading definitions from the underlying data store. * * @see GridCoverage#getGridGeometry() */ GridGeometry getGridGeometry() throws DataStoreException; /** * Returns the ranges of sample values together with the conversion from samples to real values. * Sample dimensions contain the following information: * *
    *
  • The range of valid sample values, typically but not necessarily as positive integers.
  • *
  • A transfer function for converting sample values to real values, for example measurements * of a geophysics phenomenon. The transfer function is typically defined by a scale factor and an offset, * but is not restricted to such linear equations.
  • *
  • The units of measurement of "real world" values after their conversions from sample values.
  • *
  • The sample values reserved for missing values.
  • *
* * The returned list should never be empty. If the coverage is an image to be used only for visualization purposes * (i.e. the image does not contain any classification data or any measurement of physical phenomenon), then list * size should be equal to the {@linkplain java.awt.image.SampleModel#getNumBands() number of bands} in the image * and sample dimension names may be "Red", "Green" and "Blue" for instance. Those sample dimensions do not need * to contain any {@linkplain SampleDimension#getCategories() category}. * *

The list returned by this method should be equal to the list returned by * {@linkplain #read(GridGeometry, int...) read}(null).{@linkplain GridCoverage#getSampleDimensions() getSampleDimensions()}. * However the sample dimensions returned by this method is allowed to be only approximate if computing accurate information * would be prohibitively expensive, or if the sample dimensions depend on the {@code domain} argument (area of interest) * given to the {@code read(…)} method. At least, the number of sample dimensions should match.

* * @return ranges of sample values together with their mapping to "real values". * @throws DataStoreException if an error occurred while reading definitions from the underlying data store. * * @see GridCoverage#getSampleDimensions() */ List getSampleDimensions() throws DataStoreException; /** * Returns the preferred resolutions (in units of CRS axes) for read operations in this data store. * If the storage supports pyramid, then the list should contain the resolution at each pyramid level * ordered from coarsest (largest numbers) to finest (smallest numbers) resolution. * Otherwise the list contains a single element which is the {@linkplain #getGridGeometry() grid geometry} * resolution, or an empty list if no resolution is applicable to the coverage (e.g. because non-constant). * *

Each element shall be an array with a length equals to the number of CRS dimensions. * In each array, value at index i is the cell size along CRS dimension i * in units of the CRS axis i.

* *

Note that arguments given to {@link #subset(CoverageQuery) subset(…)} or {@link #read read(…)} methods * are not constrained to the resolutions returned by this method. Those resolutions are only hints * about resolution values where read operations are likely to be more efficient.

* * @return preferred resolutions for read operations in this data store, or an empty array if none. * @throws DataStoreException if an error occurred while reading definitions from the underlying data store. * * @see GridGeometry#getResolution(boolean) * * @since 1.2 */ default List getResolutions() throws DataStoreException { final GridGeometry gg = getGridGeometry(); if (gg != null && gg.isDefined(GridGeometry.RESOLUTION)) { // Should never be null but we are paranoiac. final double[] resolution = gg.getResolution(false); if (!ArraysExt.allEquals(resolution, Double.NaN)) { return Collections.singletonList(resolution); } } return Collections.emptyList(); } /** * Requests a subset of the coverage. * The filtering can be applied in two aspects: * *
    *
  • The returned {@code GridCoverageResource} may contain a smaller domain (grid extent).
  • *
  • The returned {@code GridCoverageResource} may contain a smaller range (less sample dimensions).
  • *
* *

The returned subset may be a view of this set, i.e. changes in this {@code GridCoverageResource} * may be reflected immediately on the returned subset (and conversely), but not necessarily. * However the returned subset may not have the same capabilities as this {@link GridCoverageResource}. * In particular, write operations may become unsupported after complex queries.

* *

Default implementation

* The default implementation delegates to {@link CoverageQuery#execute(GridCoverageResource)} if the given * query is an instance of {@code CoverageQuery}, or throws {@link UnsupportedQueryException} otherwise. * * @param query definition of domain (grid extent) and range (sample dimensions) filtering applied at reading time. * @return resulting coverage resource (never {@code null}). * @throws UnsupportedQueryException if the given query is not valid for this {@code GridCoverageResource}. * This includes query validation errors. * @throws DataStoreException if another error occurred while processing the query. * * @see FeatureSet#subset(Query) * @see CoverageQuery#execute(GridCoverageResource) * * @since 1.1 */ default GridCoverageResource subset(final Query query) throws UnsupportedQueryException, DataStoreException { ArgumentChecks.ensureNonNull("query", query); if (query instanceof CoverageQuery) { return ((CoverageQuery) query).execute(this); } else { throw new UnsupportedQueryException(); } } /** * Loads a subset of the grid coverage represented by this resource. If a non-null grid geometry is specified, * then this method will try to return a grid coverage matching the given grid geometry on a best-effort basis; * the coverage actually returned may have a different resolution, cover a different area in a different CRS, * etc. The general contract is that the returned coverage should not contain less data than a coverage * matching exactly the given geometry. * *

The returned coverage shall contain the exact set of sample dimensions specified by the {@code range} argument, * in the specified order (the "best-effort basis" flexibility applies only to the grid geometry, not to the range). * All {@code range} values shall be between 0 inclusive and {@linkplain #getSampleDimensions()}.size() * exclusive, without duplicated values.

* *

While this method name suggests an immediate reading, some implementations may defer the actual reading * at a later stage.

* * @param domain desired grid extent and resolution, or {@code null} for reading the whole domain. * @param range 0-based indices of sample dimensions to read, or {@code null} or an empty sequence for reading them all. * @return the grid coverage for the specified domain and range. * @throws DataStoreException if an error occurred while reading the grid coverage data. */ GridCoverage read(GridGeometry domain, int... range) throws DataStoreException; /** * Returns an indication about when the "physical" loading of raster data will happen. * This is the strategy actually applied by this resource implementation, not necessarily * the strategy given in the last call to {@link #setLoadingStrategy(RasterLoadingStrategy) * setLoadingStrategy(…)}. * *

The default strategy is to load raster data at {@link #read read(…)} method invocation time.

* * @return current raster data loading strategy for this resource. * @throws DataStoreException if an error occurred while fetching data store configuration. * * @since 1.1 */ default RasterLoadingStrategy getLoadingStrategy() throws DataStoreException { return RasterLoadingStrategy.AT_READ_TIME; } /** * Sets the preferred strategy about when to do the "physical" loading of raster data. * Implementations are free to ignore this parameter or to replace the given strategy * by the closest alternative that this resource can support. * * @param strategy the desired strategy for loading raster data. * @return {@code true} if the given strategy has been accepted, or {@code false} * if this implementation replaced the given strategy by an alternative. * @throws DataStoreException if an error occurred while setting data store configuration. * * @since 1.1 */ default boolean setLoadingStrategy(final RasterLoadingStrategy strategy) throws DataStoreException { ArgumentChecks.ensureNonNull("strategy", strategy); return strategy == getLoadingStrategy(); } } package com.sharky.pcmc.commands; import java.io.IOException; import org.apache.hc.client5.http.classic.methods.HttpPost; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.HttpResponse; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; public class CommandLink implements CommandExecutor { private JavaPlugin plugin; public CommandLink(JavaPlugin plugin) { this.plugin = plugin; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player) { Player player = (Player) sender; if (args.length != 1) { player.sendMessage("Incorrect command syntax"); return false; } String discordId = args[0]; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost postRequest = new HttpPost("https://api.pcmc.xyz/link/" + player.getName() + "/" + discordId); HttpResponse response; try { response = httpClient.execute(postRequest); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } return true; } else { this.plugin.getLogger().info("You must be a player to execute this command"); return true; } } } ammaoui/watch-d package com.tuesda.watch.dribleSdk.data; import com.tuesda.watch.dribleSdk.DriRegInfo; import org.json.JSONException; import org.json.JSONObject; import java.text.ParseException; import java.util.Calendar; /** * Created by zhanglei on 15/8/1. */ public class DribleComment { private int id; private String body; private int likes_count; private String likes_url; private Calendar created_at; private Calendar updated_at; private DribleUser user; private static final String COMMENT_ID = "id", COMMENT_BODY = "body", COMMENT_LIKES_COUNT = "likes_count", COMMENT_LIKES_URL = "likes_url", COMMENT_CREATED_AT = "created_at", COMMENT_UPDATED_AT = "updated_at", COMMENT_USER = "user"; public DribleComment() { } public DribleComment(JSONObject data) { try { if (data.has(COMMENT_ID)) { id = data.getInt(COMMENT_ID); } if (data.has(COMMENT_BODY)) { body = data.getString(COMMENT_BODY); } if (data.has(COMMENT_LIKES_COUNT)) { likes_count = data.getInt(COMMENT_LIKES_COUNT); } if (data.has(COMMENT_LIKES_URL)) { likes_url = data.getString(COMMENT_LIKES_URL); } if (data.has(COMMENT_CREATED_AT)) { String str = data.getString(COMMENT_CREATED_AT); created_at = Calendar.getInstance(); created_at.setTime(DriRegInfo.SIMPLE_DATE_FORMAT.parse(str)); } if (data.has(COMMENT_UPDATED_AT)) { String str = data.getString(COMMENT_UPDATED_AT); updated_at = Calendar.getInstance(); updated_at.setTime(DriRegInfo.SIMPLE_DATE_FORMAT.parse(str)); } if (data.has(COMMENT_USER)) { JSONObject userJson = data.getJSONObject(COMMENT_USER); user = new DribleUser(userJson); } } catch (JSONException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public int getLikes_count() { return likes_count; } public void setLikes_count(int likes_count) { this.likes_count = likes_count; } public String getLikes_url() { return likes_url; } public void setLikes_url(String likes_url) { this.likes_url = likes_url; } public Calendar getCreated_at() { return created_at; } public void setCreated_at(Calendar created_at) { this.created_at = created_at; } public Calendar getUpdated_at() { return updated_at; } public void setUpdated_at(Calendar updated_at) { this.updated_at = updated_at; } public DribleUser getUser() { return user; } public void setUser(DribleUser user) { this.user = user; } @Override public String toString() { return "DribleComment{" + "id=" + id + ", body='" + body + '\'' + ", likes_count=" + likes_count + ", likes_url='" + likes_url + '\'' + ", created_at=" + created_at + ", updated_at=" + updated_at + ", user=" + user.toString() + '}'; } } package com.weison.spring.ioc.profile.config; import com.weison.spring.ioc.profile.bean.Bar; import com.weison.spring.ioc.profile.bean.Boss; import com.weison.spring.ioc.profile.condition.ConditionalOnBean; import com.weison.spring.ioc.profile.condition.ExistBossCondition; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; /** * @author Weison * @date 2020/9/21 */ @Configuration public class BarConfiguration { @Bean @Conditional(ExistBossCondition.class) public Bar littleBear() { return new Bar(); } @Bean @ConditionalOnBean(beanNames = "com.weison.spring.ioc.profile.bean.Boss") public Bar bigBear() { return new Bar(); } @Bean @ConditionalOnBean(Boss.class) public Bar middleBear() { return new Bar(); } } 0 package pl.umk.wmii.msr.contributions.model; /** * Exists, because this language doesn't support ordered pairs */ public class CorrelationPair { private final T _1; private final S _2; public CorrelationPair(T _1, S _2) { this._1 = _1; this._2 = _2; } public T get_1() { return _1; } public S get_2() { return _2; } } package lab3; //deklaracja pakietu public class Lab3Zad4 { //definicja klasy publicznej public static void main(String[] args) { //definicja metody main double suma; //deklaracja zmiennej typu double //utworzenie nowego obiektu klasy Pierwsza Pierwsza obiekt = new Pierwsza(); //wydrukowanie sumy odwrotności silni suma = obiekt.computeSumOfInverses(3); System.out.println(suma); } static class Pierwsza { //definicja klasy statycznej //metoda zwracająca sumę odwrotności silni double computeSumOfInverses(int n) { double sum = 0; int i; for (i = 0; i <= n; i++) sum += 1 / silnia(i); return sum; } //metoda prywatna zwracająca silnie private double silnia(int n) { double sil = 1; int i; if (n == 0) return 1; for (i = 1; i <= n; i++) sil *= i; return sil; } } }asad-awadia/swim // Copyright 2015-2021 Swim 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 swim.store; import swim.api.data.MapData; import swim.structure.Form; import swim.structure.Value; import swim.structure.collections.ValueEntry; import swim.structure.collections.ValueOrderedMap; import swim.util.OrderedMap; public class MapDataView extends ValueOrderedMap implements MapData, MapDataContext { public MapDataView(MapDataBinding dataBinding, Form keyForm, Form valueForm) { super(dataBinding, keyForm, valueForm); dataBinding.setDataContext(this); } public MapDataBinding dataBinding() { return (MapDataBinding) this.inner; } @Override public Value name() { return ((MapDataBinding) this.inner).name(); } public MapDataView keyForm(Form keyForm) { return new MapDataView((MapDataBinding) this.inner, keyForm, this.valueForm); } public MapDataView keyClass(Class keyClass) { return keyForm(Form.forClass(keyClass)); } public MapDataView valueForm(Form valueForm) { return new MapDataView((MapDataBinding) this.inner, this.keyForm, valueForm); } public MapDataView valueClass(Class valueClass) { return valueForm(Form.forClass(valueClass)); } @Override public boolean isResident() { return ((MapDataBinding) this.inner).isResident(); } @Override public MapDataView isResident(boolean isResident) { ((MapDataBinding) this.inner).isResident(isResident); return this; } @Override public boolean isTransient() { return ((MapDataBinding) this.inner).isTransient(); } @Override public MapDataView isTransient(boolean isTransient) { ((MapDataBinding) this.inner).isTransient(isTransient); return this; } @Override public Entry getIndex(int index) { final Entry entry = ((MapDataBinding) this.inner).getIndex(index); if (entry != null) { return new ValueEntry(entry, this.keyForm, this.valueForm); } else { return null; } } @Override public void drop(int lower) { ((MapDataBinding) this.inner).drop(lower); } @Override public void take(int upper) { ((MapDataBinding) this.inner).take(upper); } @Override public OrderedMap snapshot() { return new ValueOrderedMap(((MapDataBinding) this.inner).snapshot(), this.keyForm, this.valueForm); } @Override public void close() { ((MapDataBinding) this.inner).close(); } @Override public void didChange() { // stub } @Override public void didCommit() { // stub } @Override public void didUpdate(Value key, Value newValue, Value oldValue) { // stub } @Override public void didRemove(Value key, Value oldValue) { // stub } @Override public void didDrop(long lower) { // stub } @Override public void didTake(long upper) { // stub } @Override public void didClear() { // stub } } cj7865794408/MoErDuo_Music_Lib1-10 package com.cyl.musiclake.ui.music.online.presenter;//package com.cyl.musiclake.ui.music.online.presenter; // //import com.cyl.musiclake.base.BasePresenter; // //import com.cyl.musiclake.api.netease.NeteaseMusic; //import com.cyl.musiclake.ui.music.online.contract.NeteaseListContract; // //import javax.inject.Inject; // ///** // * Created by D22434 on 2018/1/4. // */ // //public class NeteaseListPresenter extends BasePresenter implements NeteaseListContract.Presenter { // // @Inject // public NeteaseListPresenter() { // } // // @Override // public void loadNeteaseMusicList(int idx) { //// MusicApi.getTopList(idx) //// .subscribeOn(Schedulers.io()) //// .observeOn(AndroidSchedulers.mainThread()) //// .subscribe(new Observer() { //// @Override //// public void onSubscribe(Disposable d) { //// } //// //// @Override //// public void onNext(NeteaseList result) { //// LogUtil.e("net_play", result.toString()); //// mView.showTopList(result); //// } //// //// @Override //// public void onError(Throwable e) { //// e.printStackTrace(); //// mView.hideLoading(); //// mView.showErrorInfo(e.getMessage()); //// } //// //// @Override //// public void onComplete() { //// mView.hideLoading(); //// } //// }); // } // // @Override // public void getMusicInfo(NeteaseMusic neteaseMusic) { // // } // //} /* * 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 org.d2ab.iterator.chars; import org.d2ab.collection.chars.CharIterable; import java.util.NoSuchElementException; /** * An {@link CharIterator} that cycles the values of an {@link CharIterable} forever. This class repeatedly calls * {@link CharIterable#iterator()} to receive new values when the iterator ends, so it's possible to cause this * {@link CharIterator} to terminate by providing an empty {@link CharIterator}. If the {@link CharIterable} never * returns an empty {@link CharIterator}, this {@link CharIterator} will never terminate. */ public class RepeatingCharIterator extends DelegatingUnaryCharIterator { private final CharIterable iterable; private int times; public RepeatingCharIterator(CharIterable iterable, int times) { super(CharIterator.EMPTY); this.iterable = iterable; this.times = times; } @Override public boolean hasNext() { if (!iterator.hasNext() && times != 0) { if (times > 0) times--; iterator = iterable.iterator(); } return iterator.hasNext(); } @Override public char nextChar() { if (!hasNext()) throw new NoSuchElementException(); return iterator.nextChar(); } } package jiux.net.plugin.restful.navigator; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class RefreshProjectAction extends AnAction { @Nullable public static Project getProject(DataContext context) { return CommonDataKeys.PROJECT.getData(context); } protected void perform(@NotNull RestServiceProjectsManager manager) { manager.forceUpdateAllProjects(); } @Override public void actionPerformed(AnActionEvent e) { final Project project = getProject(e.getDataContext()); RestServicesNavigator servicesNavigator = RestServicesNavigator.getInstance(project); servicesNavigator.initComponent(); servicesNavigator.scheduleStructureUpdate(); } } /** * 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. */ /** * SecServiceLocator.java * * This file was auto-generated from WSDL * by the Apache Axis 1.2dev Oct 27, 2003 (02:34:09 EST) WSDL2Java emitter. */ package org.apache.ws.axis.samples.wssec.doall.axisSec; public class SecServiceLocator extends org.apache.axis.client.Service implements org.apache.ws.axis.samples.wssec.doall.axisSec.SecService { // Use to get a proxy class for SecHttp private java.lang.String SecHttp_address = "http://localhost:8081/axis/services/secHttp"; public java.lang.String getSecHttpAddress() { return SecHttp_address; } // The WSDD service name defaults to the port name. private java.lang.String SecHttpWSDDServiceName = "SecHttp"; public java.lang.String getSecHttpWSDDServiceName() { return SecHttpWSDDServiceName; } public void setSecHttpWSDDServiceName(java.lang.String name) { SecHttpWSDDServiceName = name; } public org.apache.ws.axis.samples.wssec.doall.axisSec.SecPort getSecHttp() throws javax.xml.rpc.ServiceException { java.net.URL endpoint; try { endpoint = new java.net.URL(SecHttp_address); } catch (java.net.MalformedURLException e) { throw new javax.xml.rpc.ServiceException(e); } return getSecHttp(endpoint); } public org.apache.ws.axis.samples.wssec.doall.axisSec.SecPort getSecHttp(java.net.URL portAddress) throws javax.xml.rpc.ServiceException { try { org.apache.ws.axis.samples.wssec.doall.axisSec.SecBindingStub _stub = new org.apache.ws.axis.samples.wssec.doall.axisSec.SecBindingStub(portAddress, this); _stub.setPortName(getSecHttpWSDDServiceName()); return _stub; } catch (org.apache.axis.AxisFault e) { return null; } } public void setSecHttpEndpointAddress(java.lang.String address) { SecHttp_address = address; } /** * For the given interface, get the stub implementation. * If this service has no port for the given interface, * then ServiceException is thrown. */ public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException { try { if (org.apache.ws.axis.samples.wssec.doall.axisSec.SecPort.class.isAssignableFrom(serviceEndpointInterface)) { org.apache.ws.axis.samples.wssec.doall.axisSec.SecBindingStub _stub = new org.apache.ws.axis.samples.wssec.doall.axisSec.SecBindingStub(new java.net.URL(SecHttp_address), this); _stub.setPortName(getSecHttpWSDDServiceName()); return _stub; } } catch (java.lang.Throwable t) { throw new javax.xml.rpc.ServiceException(t); } throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface: " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName())); } /** * For the given interface, get the stub implementation. * If this service has no port for the given interface, * then ServiceException is thrown. */ public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException { if (portName == null) { return getPort(serviceEndpointInterface); } String inputPortName = portName.getLocalPart(); if ("SecHttp".equals(inputPortName)) { return getSecHttp(); } else { java.rmi.Remote _stub = getPort(serviceEndpointInterface); ((org.apache.axis.client.Stub) _stub).setPortName(portName); return _stub; } } public javax.xml.namespace.QName getServiceName() { return new javax.xml.namespace.QName("uri:axis_sec", "secService"); } private java.util.HashSet ports = null; public java.util.Iterator getPorts() { if (ports == null) { ports = new java.util.HashSet(); ports.add(new javax.xml.namespace.QName("SecHttp")); } return ports.iterator(); } /** * Set the endpoint address for the specified port name. */ public void setEndpointAddress(java.lang.String portName, java.lang.String address) throws javax.xml.rpc.ServiceException { if ("SecHttp".equals(portName)) { setSecHttpEndpointAddress(address); } else { // Unknown Port Name throw new javax.xml.rpc.ServiceException(" Cannot set Endpoint Address for Unknown Port" + portName); } } /** * Set the endpoint address for the specified port name. */ public void setEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throws javax.xml.rpc.ServiceException { setEndpointAddress(portName.getLocalPart(), address); } } package com.haomeng.tera.framework.core.bean; /** * Created by nick on 2017/8/2. * @author nick * 这个是模拟spring的bean管理机制获取bean的 */ public interface BeanFactory { /** * 根据bean的名称获取bean * @param name * @return */ Object getBean(String name); /** * 根据类型获取bean * @param requiredType * @param * @return */ T getBean(Class requiredType); } package ru.job4j.parser; import org.apache.log4j.Logger; import java.sql.*; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; /** * @author * Save records to PostgreSQL. */ public class RecordToDB implements AutoCloseable, Store { private Connection connection; private Config config; final static Logger LOGGER = Logger.getLogger(UsageLog4j.class); public RecordToDB(Config config) { this.config = config; } public boolean connectToDB() { try { Class.forName(config.get("driver-class-name")); this.connection = DriverManager.getConnection( config.get("url"), config.get("username"), config.get("password") ); this.connection.setAutoCommit(false); Statement st = connection.createStatement(); st.execute("create table if not exists vacancies (id serial primary key, name varchar(1000) not null, text varchar(5000), link varchar(500) not null, date timestamp not null);"); this.connection.commit(); } catch (Exception e) { LOGGER.error(e.getMessage()); } return this.connection != null; } /** * Save List of vacancies to database. * @param postList List of vacancies. */ @Override public void save(List postList) { if (connectToDB()) { try (PreparedStatement statement = connection.prepareStatement(SQLItems.INSERT.query)) { for (Post vc : postList) { statement.setString(1, vc.getName()); statement.setString(2, vc.getText()); statement.setString(3, vc.getLink()); statement.setObject(4, vc.getDate()); if (!this.isDuplicate(vc.getName())) { statement.addBatch(); } } statement.executeBatch(); this.connection.commit(); } catch (SQLException e) { LOGGER.error(e.getMessage()); } } } @Override public List get(Predicate filter) { List postList = new ArrayList<>(); if (connectToDB()) { try { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM vacancies;"); while (resultSet.next()) { String name = resultSet.getString("name"); String text = resultSet.getString("text"); String link = resultSet.getString("link"); Timestamp date = resultSet.getTimestamp("date"); Post post = new Post(name, text, link, date.toLocalDateTime()); postList.add(post); } } catch (SQLException e) { e.printStackTrace(); LOGGER.error(e.getMessage()); } return postList.stream().filter(filter).collect(Collectors.toList()); } return postList; } /** * Check duplicate record in database. * @param name checking name. * @return true if name equals record. */ private boolean isDuplicate(String name) { boolean result = false; try { Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM vacancies;"); while (resultSet.next()) { if (resultSet.getString("name").equals(name)) { result = true; break; } } } catch (SQLException e) { e.printStackTrace(); LOGGER.error(e.getMessage()); } return result; } @Override public void close() throws Exception { this.connection.close(); } enum SQLItems { INSERT("INSERT INTO vacancies (name, text, link, date) VALUES (?, ?, ?, ?);"); String query; SQLItems(String query) { this.query = query; } } } code-wizard91/JavaMovingBlocksGame0 /* * Copyright 2016 MovingBlocks * * 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.terasology.rendering.dag.nodes; import org.terasology.assets.ResourceUrn; import org.terasology.config.Config; import org.terasology.config.RenderingConfig; import org.terasology.math.geom.Vector3f; import org.terasology.monitoring.PerformanceMonitor; import org.terasology.registry.In; import org.terasology.rendering.assets.material.Material; import org.terasology.rendering.assets.shader.ShaderProgramFeature; import org.terasology.rendering.cameras.Camera; import org.terasology.rendering.dag.ConditionDependentNode; import org.terasology.rendering.dag.stateChanges.BindFBO; import org.terasology.rendering.dag.stateChanges.EnableFaceCulling; import org.terasology.rendering.dag.stateChanges.EnableMaterial; import org.terasology.rendering.dag.stateChanges.LookThrough; import org.terasology.rendering.dag.stateChanges.ReflectedCamera; import org.terasology.rendering.dag.stateChanges.SetFacesToCull; import org.terasology.rendering.dag.stateChanges.SetViewportToSizeOf; import org.terasology.rendering.opengl.FBO; import org.terasology.rendering.opengl.FBOConfig; import org.terasology.rendering.opengl.fbms.DisplayResolutionDependentFBOs; import org.terasology.rendering.primitives.ChunkMesh; import org.terasology.rendering.world.RenderQueuesHelper; import org.terasology.rendering.world.WorldRenderer; import org.terasology.world.chunks.RenderableChunk; import static org.terasology.rendering.opengl.ScalingFactors.HALF_SCALE; import static org.lwjgl.opengl.GL11.GL_FRONT; import static org.terasology.rendering.primitives.ChunkMesh.RenderPhase.OPAQUE; /** * An instance of this class is responsible for rendering a reflected landscape into the * "engine:sceneReflected" buffer. This buffer is then used to produce the reflection * of the landscape on the water surface. * * It could potentially be used also for other reflecting surfaces, i.e. metal, but it only works * for horizontal surfaces. * * An instance of this class is enabled or disabled depending on the reflections setting in the rendering config. * * Diagram of this node can be viewed from: * TODO: move diagram to the wiki when this part of the code is stable * - https://docs.google.com/drawings/d/1Iz7MA8Y5q7yjxxcgZW-0antv5kgx6NYkvoInielbwGU/edit?usp=sharing */ public class WorldReflectionNode extends ConditionDependentNode { public static final ResourceUrn REFLECTED = new ResourceUrn("engine:sceneReflected"); private static final ResourceUrn CHUNK_MATERIAL = new ResourceUrn("engine:prog.chunk"); @In private RenderQueuesHelper renderQueues; @In private Config config; @In private WorldRenderer worldRenderer; @In private DisplayResolutionDependentFBOs displayResolutionDependentFBOs; private Camera playerCamera; private Material chunkShader; private RenderingConfig renderingConfig; /** * Node initialization. * * Internally requires the "engine:sceneReflected" buffer, stored in the (display) resolution-dependent FBO manager. * This is a default, half-scale buffer inclusive of a depth buffer FBO. See FBOConfig and ScalingFactors for details * on possible FBO configurations. * * This method also requests the material using the "chunk" shaders (vertex, fragment) to be enabled. */ @Override public void initialise() { playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new ReflectedCamera(playerCamera)); // this has to go before the LookThrough state change addDesiredStateChange(new LookThrough(playerCamera)); renderingConfig = config.getRendering(); requiresCondition(() -> renderingConfig.isReflectiveWater()); renderingConfig.subscribe(RenderingConfig.REFLECTIVE_WATER, this); requiresFBO(new FBOConfig(REFLECTED, HALF_SCALE, FBO.Type.DEFAULT).useDepthBuffer(), displayResolutionDependentFBOs); addDesiredStateChange(new BindFBO(REFLECTED, displayResolutionDependentFBOs)); addDesiredStateChange(new SetViewportToSizeOf(REFLECTED, displayResolutionDependentFBOs)); addDesiredStateChange(new EnableFaceCulling()); addDesiredStateChange(new SetFacesToCull(GL_FRONT)); addDesiredStateChange(new EnableMaterial(CHUNK_MATERIAL.toString())); // we must get this here because in process we activate/deactivate a specific shader feature. // TODO: improve EnableMaterial to take advantage of shader feature bitmasks. chunkShader = getMaterial(CHUNK_MATERIAL); } /** * Renders the landscape, reflected, into the buffers attached to the "engine:sceneReflected" FBO. It is used later, * to render horizontal reflective surfaces, i.e. water. * * Notice that this method -does not- clear the FBO. The rendering takes advantage of the depth buffer to decide * which pixel is in front of the one already stored in the buffer. * * See: https://en.wikipedia.org/wiki/Deep_image_compositing */ @Override public void process() { PerformanceMonitor.startActivity("rendering/worldReflection"); int numberOfRenderedTriangles = 0; int numberOfChunksThatAreNotReadyYet = 0; final Vector3f cameraPosition = playerCamera.getPosition(); chunkShader.activateFeature(ShaderProgramFeature.FEATURE_USE_FORWARD_LIGHTING); chunkShader.setFloat("clip", playerCamera.getClipHeight(), true); while (renderQueues.chunksOpaqueReflection.size() > 0) { RenderableChunk chunk = renderQueues.chunksOpaqueReflection.poll(); if (chunk.hasMesh()) { final ChunkMesh chunkMesh = chunk.getMesh(); final Vector3f chunkPosition = chunk.getPosition().toVector3f(); chunkMesh.updateMaterial(chunkShader, chunkPosition, chunk.isAnimated()); numberOfRenderedTriangles += chunkMesh.render(OPAQUE, chunkPosition, cameraPosition); } else { numberOfChunksThatAreNotReadyYet++; } } chunkShader.deactivateFeature(ShaderProgramFeature.FEATURE_USE_FORWARD_LIGHTING); worldRenderer.increaseTrianglesCount(numberOfRenderedTriangles); worldRenderer.increaseNotReadyChunkCount(numberOfChunksThatAreNotReadyYet); PerformanceMonitor.endActivity(); } } /* * Copyright 2020 adopted to TeaVM by * * 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. */ /* * Copyright (c) 2007-present, & * * 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 JSR-310 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 OWNER 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.teavm.classlib.java.time.temporal; import static org.teavm.classlib.java.time.temporal.TChronoUnit.DAYS; import static org.teavm.classlib.java.time.temporal.TChronoUnit.ERAS; import static org.teavm.classlib.java.time.temporal.TChronoUnit.FOREVER; import static org.teavm.classlib.java.time.temporal.TChronoUnit.HALF_DAYS; import static org.teavm.classlib.java.time.temporal.TChronoUnit.HOURS; import static org.teavm.classlib.java.time.temporal.TChronoUnit.MICROS; import static org.teavm.classlib.java.time.temporal.TChronoUnit.MILLIS; import static org.teavm.classlib.java.time.temporal.TChronoUnit.MINUTES; import static org.teavm.classlib.java.time.temporal.TChronoUnit.MONTHS; import static org.teavm.classlib.java.time.temporal.TChronoUnit.NANOS; import static org.teavm.classlib.java.time.temporal.TChronoUnit.SECONDS; import static org.teavm.classlib.java.time.temporal.TChronoUnit.WEEKS; import static org.teavm.classlib.java.time.temporal.TChronoUnit.YEARS; import java.util.Map; import java.util.Objects; import org.teavm.classlib.java.time.TYear; import org.teavm.classlib.java.time.format.TResolverStyle; import org.teavm.classlib.java.util.TLocale; public enum TChronoField implements TTemporalField { NANO_OF_SECOND("NanoOfSecond", NANOS, SECONDS, TValueRange.of(0, 999999999)), // NANO_OF_DAY("NanoOfDay", NANOS, DAYS, TValueRange.of(0, 86400L * 1000000000L - 1)), // MICRO_OF_SECOND("MicroOfSecond", MICROS, SECONDS, TValueRange.of(0, 999999)), // MICRO_OF_DAY("MicroOfDay", MICROS, DAYS, TValueRange.of(0, 86400L * 1000000L - 1)), // MILLI_OF_SECOND("MilliOfSecond", MILLIS, SECONDS, TValueRange.of(0, 999)), // MILLI_OF_DAY("MilliOfDay", MILLIS, DAYS, TValueRange.of(0, 86400L * 1000L - 1)), // SECOND_OF_MINUTE("SecondOfMinute", SECONDS, MINUTES, TValueRange.of(0, 59)), // SECOND_OF_DAY("SecondOfDay", SECONDS, DAYS, TValueRange.of(0, 86400L - 1)), // MINUTE_OF_HOUR("MinuteOfHour", MINUTES, HOURS, TValueRange.of(0, 59)), // MINUTE_OF_DAY("MinuteOfDay", MINUTES, DAYS, TValueRange.of(0, (24 * 60) - 1)), // HOUR_OF_AMPM("HourOfAmPm", HOURS, HALF_DAYS, TValueRange.of(0, 11)), // CLOCK_HOUR_OF_AMPM("ClockHourOfAmPm", HOURS, HALF_DAYS, TValueRange.of(1, 12)), // HOUR_OF_DAY("HourOfDay", HOURS, DAYS, TValueRange.of(0, 23)), // CLOCK_HOUR_OF_DAY("ClockHourOfDay", HOURS, DAYS, TValueRange.of(1, 24)), // AMPM_OF_DAY("AmPmOfDay", HALF_DAYS, DAYS, TValueRange.of(0, 1)), // DAY_OF_WEEK("TDayOfWeek", DAYS, WEEKS, TValueRange.of(1, 7)), // ALIGNED_DAY_OF_WEEK_IN_MONTH("AlignedDayOfWeekInMonth", DAYS, WEEKS, TValueRange.of(1, 7)), // ALIGNED_DAY_OF_WEEK_IN_YEAR("AlignedDayOfWeekInYear", DAYS, WEEKS, TValueRange.of(1, 7)), // DAY_OF_MONTH("DayOfMonth", DAYS, MONTHS, TValueRange.of(1, 28, 31)), // DAY_OF_YEAR("DayOfYear", DAYS, YEARS, TValueRange.of(1, 365, 366)), // EPOCH_DAY("EpochDay", DAYS, FOREVER, TValueRange.of(-365243219162L, 365241780471L)), // ALIGNED_WEEK_OF_MONTH("AlignedWeekOfMonth", WEEKS, MONTHS, TValueRange.of(1, 4, 5)), // ALIGNED_WEEK_OF_YEAR("AlignedWeekOfYear", WEEKS, YEARS, TValueRange.of(1, 53)), // MONTH_OF_YEAR("MonthOfYear", MONTHS, YEARS, TValueRange.of(1, 12)), // PROLEPTIC_MONTH("ProlepticMonth", MONTHS, FOREVER, TValueRange.of(TYear.MIN_VALUE * 12L, TYear.MAX_VALUE * 12L + 11)), // YEAR_OF_ERA("YearOfEra", YEARS, FOREVER, TValueRange.of(1, TYear.MAX_VALUE, TYear.MAX_VALUE + 1)), // YEAR("TYear", YEARS, FOREVER, TValueRange.of(TYear.MIN_VALUE, TYear.MAX_VALUE)), // ERA("TEra", ERAS, FOREVER, TValueRange.of(0, 1)), // INSTANT_SECONDS("InstantSeconds", SECONDS, FOREVER, TValueRange.of(Long.MIN_VALUE, Long.MAX_VALUE)), // OFFSET_SECONDS("OffsetSeconds", SECONDS, FOREVER, TValueRange.of(-18 * 3600, 18 * 3600)); // private final String name; private final TTemporalUnit baseUnit; private final TTemporalUnit rangeUnit; private final TValueRange range; private TChronoField(String name, TTemporalUnit baseUnit, TTemporalUnit rangeUnit, TValueRange range) { this.name = name; this.baseUnit = baseUnit; this.rangeUnit = rangeUnit; this.range = range; } @Override public TTemporalUnit getBaseUnit() { return this.baseUnit; } @Override public TTemporalUnit getRangeUnit() { return this.rangeUnit; } @Override public TValueRange range() { return this.range; } @Override public boolean isDateBased() { return ordinal() >= DAY_OF_WEEK.ordinal() && ordinal() <= ERA.ordinal(); } @Override public boolean isTimeBased() { return ordinal() < DAY_OF_WEEK.ordinal(); } public long checkValidValue(long value) { return range().checkValidValue(value, this); } public int checkValidIntValue(long value) { return range().checkValidIntValue(value, this); } @Override public boolean isSupportedBy(TTemporalAccessor temporal) { return temporal.isSupported(this); } @Override public TValueRange rangeRefinedBy(TTemporalAccessor temporal) { return temporal.range(this); } @Override public long getFrom(TTemporalAccessor temporal) { return temporal.getLong(this); } @SuppressWarnings("unchecked") @Override public R adjustInto(R temporal, long newValue) { return (R) temporal.with(this, newValue); } @Override public String getDisplayName(TLocale locale) { Objects.requireNonNull(locale, "locale"); return toString(); } @Override public TTemporalAccessor resolve(Map fieldValues, TTemporalAccessor partialTemporal, TResolverStyle resolverStyle) { return null; // resolve implemented in builder } @Override public String toString() { return this.name; } } src/test/java/com/totaljobsgroup/aurelia/ApplicationProcessorTest.java package com.totaljobsgroup.aurelia; import com.totaljobsgroup.aurelia.model.AtsRequest; import com.totaljobsgroup.aurelia.model.AtsRequestBody; import com.totaljobsgroup.aurelia.model.AtsRequestHeader; import com.totaljobsgroup.aurelia.model.AtsResponse; import com.totaljobsgroup.aurelia.model.AtsResponseBody; import com.totaljobsgroup.aurelia.model.Attachment; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Test; import org.junit.runner.RunWith; import java.net.URI; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(JUnitParamsRunner.class) public class ApplicationProcessorTest { private static String REDIRECTION_PAGE = "http://redirection.page"; @Test @Parameters(method = "requestResponseParameters") public void shouldPrepareProperResponse(boolean redirect, boolean jobAvailable, AtsResponseBody.Redirect expectedRedirect, String expectedErrorMsg, String expectedRedirectUrl) { // given URI expectedBackUrl = URI.create(expectedRedirectUrl); AtsRequest atsRequestMock = prepareAtsRequestMock(); JobDB jobDBMock = prepareJobDBMock(redirect, jobAvailable, REDIRECTION_PAGE); ApplicationProcessor objectUnderTest = new ApplicationProcessor(jobDBMock, new JobUrlProcessor()); // when AtsResponse atsResponse = objectUnderTest.processApplication(atsRequestMock); // then assertEquals(expectedRedirect, atsResponse.getBody().getRedirect()); assertEquals(expectedErrorMsg, atsResponse.getHeader().getErrorMsg()); assertEquals(expectedBackUrl, atsResponse.getBody().getBackUrl()); } private Object[] requestResponseParameters() { return new Object[]{ new Object[]{true, true, AtsResponseBody.Redirect.YES, null, REDIRECTION_PAGE}, new Object[]{true, false, AtsResponseBody.Redirect.NO, "JOB_NOT_AVAILABLE", ""}, new Object[]{false, true, AtsResponseBody.Redirect.NO, null, ""}, new Object[]{false, false, AtsResponseBody.Redirect.NO, "JOB_NOT_AVAILABLE", ""}, }; } private AtsRequest prepareAtsRequestMock() { AtsRequest atsRequestMock = mock(AtsRequest.class); AtsRequestHeader atsRequestHeaderMock = prepareAtsRequestHeaderMock(); when(atsRequestMock.getHeader()).thenReturn(atsRequestHeaderMock); AtsRequestBody atsRequestBodyMock = prepareAtsRequestBodyMock(); when(atsRequestMock.getBody()).thenReturn(atsRequestBodyMock); return atsRequestMock; } private AtsRequestHeader prepareAtsRequestHeaderMock() { AtsRequestHeader atsRequestHeaderMock = mock(AtsRequestHeader.class); when(atsRequestHeaderMock.getEffectiveUrl()).thenReturn("http://effectiveUrl"); return atsRequestHeaderMock; } private AtsRequestBody prepareAtsRequestBodyMock() { AtsRequestBody atsRequestBodyMock = mock(AtsRequestBody.class); Attachment attachmentMock = mock(Attachment.class); when(atsRequestBodyMock.getCV()).thenReturn(attachmentMock); return atsRequestBodyMock; } private JobDB prepareJobDBMock(boolean redirection, boolean jobAvailable, String redirectionPage) { JobDB jobDBMock = mock(JobDB.class); when(jobDBMock.doesJobRequireRedirection(anyInt())).thenReturn(redirection); when(jobDBMock.isJobAvailable(anyInt())).thenReturn(jobAvailable); when(jobDBMock.redirectionPage()).thenReturn(redirectionPage); return jobDBMock; } }0 /* * 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.hudi.utilities.sources.debezium; import org.apache.hudi.common.model.debezium.DebeziumConstants; import org.apache.avro.Schema; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericRecord; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import static org.junit.jupiter.api.Assertions.assertTrue; public class TestMysqlDebeziumSource extends TestAbstractDebeziumSource { private static final String MYSQL_GITHUB_SCHEMA = "{\"connect.name\": \"mysql.ghschema.gharchive.Envelope\",\n" + " \"fields\": [{\"default\": null,\"name\": \"before\",\"type\": [\"null\",{\"connect.name\": \"mysql.ghschema.gharchive.Value\",\n" + " \"fields\": [{\"name\": \"id\",\"type\": \"string\"},{\"name\": \"date\",\"type\": \"string\"},{\"default\": null,\"name\": \"timestamp\",\n" + " \"type\": [\"null\",\"long\"]},{\"default\": null,\"name\": \"type\",\"type\": [\"null\",\"string\"]},{\"default\": null,\"name\": \"payload\",\n" + " \"type\": [\"null\",\"string\"]},{\"default\": null,\"name\": \"org\",\"type\": [\"null\",\"string\"]},{\"default\": null,\"name\": \"created_at\",\n" + " \"type\": [\"null\",\"long\"]},{\"default\": null,\"name\": \"public\",\"type\": [\"null\",\"boolean\"]}],\"name\": \"Value\",\"type\": \"record\"\n" + " }]},{\"default\": null,\"name\": \"after\",\"type\": [\"null\",\"Value\"]},{\"name\": \"source\",\"type\": {\"connect.name\": \"io.debezium.connector.mysql.Source\",\n" + " \"fields\": [{\"name\": \"connector\",\"type\": \"string\"},{\"name\": \"name\",\"type\": \"string\"},{\"name\": \"ts_ms\",\"type\": \"long\"},\n" + " {\"name\": \"db\",\"type\": \"string\"},{\"name\": \"table\",\"type\": \"string\"},{\"default\": null,\n" + " \"name\": \"txId\",\"type\": [\"null\",\"long\"]},{\"name\": \"file\",\"type\": \"string\"},{\"default\": null,\"name\": \"pos\",\"type\": [\"null\",\"long\"]},{\"default\": null,\n" + " \"name\": \"row\",\"type\": [\"null\",\"long\"]}],\"name\": \"Source\",\"namespace\": \"io.debezium.connector.mysql\",\"type\": \"record\"\n" + " }},{\"name\": \"op\",\"type\": \"string\"},{\"default\": null,\"name\": \"ts_ms\",\"type\": [\"null\",\"long\"]},{\"default\": null,\"name\": \"transaction\",\n" + " \"type\": [\"null\",{\"fields\": [{\"name\": \"id\",\"type\": \"string\"},{\"name\": \"total_order\",\"type\": \"long\"},{\"name\": \"data_collection_order\",\n" + " \"type\": \"long\"}],\"name\": \"ConnectDefault\",\"namespace\": \"io.confluent.connect.avro\",\"type\": \"record\"}]}],\"name\": \"Envelope\",\n" + " \"namespace\": \"mysql.ghschema.gharchive\",\"type\": \"record\"}"; private static final String TEST_DB = "ghschema"; private static final String TEST_TABLE = "gharchive"; private static final long TEST_TS_MS = 12345L; private static final long TEST_TXID = 543L; private static final String TEST_FILE = "mysql-bin.00007"; private static final long TEST_POS = 98765L; private static final String EXPECTED_TEST_SEQ = "00007.98765"; @Override protected String getIndexName() { return "mysql"; } @Override protected String getSourceClass() { return MysqlDebeziumSource.class.getName(); } @Override protected String getSchema() { return MYSQL_GITHUB_SCHEMA; } @Override protected GenericRecord generateMetaFields(GenericRecord rec) { Schema schema = new Schema.Parser().parse(getSchema()); // Source fields specific to Mysql DB GenericRecord sourceRecord = new GenericData.Record(schema.getField(DebeziumConstants.INCOMING_SOURCE_FIELD).schema()); sourceRecord.put("name", getIndexName()); sourceRecord.put("connector", getIndexName()); sourceRecord.put("db", TEST_DB); sourceRecord.put("table", TEST_TABLE); sourceRecord.put("ts_ms", TEST_TS_MS); sourceRecord.put("txId", TEST_TXID); sourceRecord.put("file", TEST_FILE); sourceRecord.put("pos", TEST_POS); rec.put(DebeziumConstants.INCOMING_SOURCE_FIELD, sourceRecord); return rec; } @Override protected void validateMetaFields(Dataset records) { assertTrue(records.select(DebeziumConstants.FLATTENED_SHARD_NAME).collectAsList().stream() .allMatch(r -> r.getString(0).equals(getIndexName()))); assertTrue(records.select(DebeziumConstants.FLATTENED_TS_COL_NAME).collectAsList().stream() .allMatch(r -> r.getLong(0) == TEST_TS_MS)); assertTrue(records.select(DebeziumConstants.FLATTENED_TX_ID_COL_NAME).collectAsList().stream() .allMatch(r -> r.getLong(0) == TEST_TXID)); assertTrue(records.select(DebeziumConstants.ADDED_SEQ_COL_NAME).collectAsList().stream() .allMatch(r -> r.getString(0).equals(EXPECTED_TEST_SEQ))); } } /* * Copyright (c) 2015. BiliBili Inc. */ package com.bilibili.socialize.sample; import android.os.Bundle; import android.view.View; import android.widget.RadioButton; import com.bilibili.socialize.sample.helper.ShareHelper; import com.bilibili.socialize.share.core.SocializeMedia; import com.bilibili.socialize.share.core.shareparam.BaseShareParam; import com.bilibili.socialize.share.core.shareparam.ShareAudio; import com.bilibili.socialize.share.core.shareparam.ShareImage; import com.bilibili.socialize.share.core.shareparam.ShareParamAudio; import com.bilibili.socialize.share.core.shareparam.ShareParamImage; import com.bilibili.socialize.share.core.shareparam.ShareParamText; import com.bilibili.socialize.share.core.shareparam.ShareParamVideo; import com.bilibili.socialize.share.core.shareparam.ShareParamWebPage; import com.bilibili.socialize.share.core.shareparam.ShareVideo; import java.util.Locale; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.Unbinder; /** * 这个类只是为了演示如何分享,如果想体验分享效果,请下载哔哩哔哩动画app。 * * @author Jungly * @email * @since 2016/4/13 */ public class MainActivity extends BaseShareableActivity { private static final String TITLE = "哔哩哔哩2016拜年祭"; private static final String CONTENT = "【哔哩哔哩2016拜年祭】 UP主: 哔哩哔哩弹幕网 #哔哩哔哩动画# "; private static final String TARGET_URL = "http://www.bilibili.com/video/av3521416"; private static final String IMAGE_URL = "http://i2.hdslb.com/320_200/video/85/85ae2b17b223a0cd649a49c38c32dd10.jpg"; private RadioButton mTextRB, mImageRB, mWebPageRB, mAudioRB, mVideoRB; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); setUpViews(); } private void setUpViews() { mTextRB = (RadioButton) findViewById(R.id.text); mImageRB = (RadioButton) findViewById(R.id.image); mWebPageRB = (RadioButton) findViewById(R.id.webpage); mAudioRB = (RadioButton) findViewById(R.id.audio); mVideoRB = (RadioButton) findViewById(R.id.video); } @Override public BaseShareParam getShareContent(ShareHelper helper, SocializeMedia target) { BaseShareParam param; if (mImageRB.isChecked()) { param = new ShareParamImage(TITLE, CONTENT, TARGET_URL); ShareParamImage paramImage = (ShareParamImage) param; paramImage.setImage(generateImage()); } else if (mWebPageRB.isChecked()) { param = new ShareParamWebPage(TITLE, CONTENT, TARGET_URL); ShareParamWebPage paramWebPage = (ShareParamWebPage) param; paramWebPage.setThumb(generateImage()); } else if (mAudioRB.isChecked()) { param = new ShareParamAudio(TITLE, CONTENT, TARGET_URL); ShareParamAudio paramAudio = (ShareParamAudio) param; ShareAudio audio = new ShareAudio(generateImage(), TARGET_URL, TITLE); paramAudio.setAudio(audio); } else if (mVideoRB.isChecked()) { param = new ShareParamVideo(TITLE, CONTENT, TARGET_URL); ShareParamVideo paramVideo = (ShareParamVideo) param; ShareVideo video = new ShareVideo(generateImage(), TARGET_URL, TITLE); paramVideo.setVideo(video); } else { param = new ShareParamText(TITLE, CONTENT, TARGET_URL); } if (target == SocializeMedia.SINA) param.setContent(String.format(Locale.CHINA, "%s #哔哩哔哩动画# ", CONTENT)); else if (target == SocializeMedia.GENERIC || target == SocializeMedia.COPY) { param.setContent(CONTENT + " " + TARGET_URL); } return param; } private ShareImage generateImage() { //ShareImage image = new ShareImage(file); //ShareImage image = new ShareImage(bitmap); //ShareImage image = new ShareImage(resId); ShareImage image = new ShareImage(IMAGE_URL); return image; } @OnClick(R.id.btn1) void shareWithDialogSelector() { startShare(null); } @OnClick(R.id.btn2) void shareWithFullPopSelector(View clickView) { startShare(clickView, true); } @OnClick(R.id.btn3) void shareWithWrapPopSelector(View clickView) { startShare(clickView, false); } } import java.awt.Color; import java.awt.Point; import java.util.ArrayList; public class GameUnit { //public int state, waypointNum, waypointX, waypointY; /* * The units have one class type. * * Type1 - Light unit. (Regular infantry) * Type2 - Medium unit. (Anti-armor infantry) * Type3 - Heavy unit. (Tank) * * Type1 > Type2 * The light unit outruns the medium unit. * * Type2 > Type3 * The medium unit can damage the heavy unit's armor. * * Type3 > Type1 * The heavy unit's armor reduces light unit's attack and counterattacks with strong weapons/ */ public static final int UNIT_ID_LIGHT = 1; public static final int UNIT_ID_MEDIUM = 2; public static final int UNIT_ID_HEAVY = 3; public static final int STATE_IDLE = 1; public static final int STATE_MOVE = 2; public static final int STATE_ATTACK = 3; public static final int DIR_NORTH = 0; public static final int DIR_SOUTH = 1; public static final int DIR_EAST = 2; public static final int DIR_WEST = 3; public Point getMapPoint(Point screenPoint) { return new Point(screenPoint.x / GameMap.TILE_WIDTH, screenPoint.y / GameMap.TILE_HEIGHT); } //Location on map private Point currentPosition; public Point getCurrentPoint() { return this.currentPosition; } public Point destination; //Physical state private boolean isAttacking = false; //if attacking, stand still. if not, then move. private int classType; public int getClassType() { return this.classType; } //private int speed = 0; private boolean isPlayerUnit; public boolean getIsPlayerUnit() { return isPlayerUnit; } private int health; public int getHealth() { return health; } public boolean isAlive() { return (health > 0); } public int direction = 0; //north, south, east, west //Mouse selection public boolean isPlayerSelected; public boolean isClickedOn = false; //if clicked on, then unit is selected //Misc data private PathUnit pathUnit; public boolean isPathCreated() { return pathUnit.getIsPathCreated(); } public void startMoving() { pathUnit.startMoving(); } public GameUnit(int positionX, int positionY, boolean isPlayerUnit, int classType) { this.currentPosition = new Point(positionX, positionY); this.destination = new Point(); this.pathUnit = new PathUnit(positionX, positionY); this.isPlayerUnit = isPlayerUnit; this.classType = classType; this.health = 100; } public boolean isOnTile(int[][] map, int tileX, int tileY) { Point mapPos = getMapPoint(currentPosition); if (mapPos.x == tileX && mapPos.y == tileY && map[tileY][tileX] != 0) return true; return false; } public void spawn(int[][] map, Point mapPos, int factionId) { //2,3,4 - player units //5,6,7 - enemy units //initial value is 1, but map stores values differently //make sure to adjust values (+1 for ally since code is 2, +4 for enemy, since code is 5) if (factionId == GameFlag.FACTION_PLAYER) map[mapPos.y][mapPos.x] = GameUnit.UNIT_ID_LIGHT + 1; else if (factionId == GameFlag.FACTION_ENEMY) map[mapPos.y][mapPos.x] = GameUnit.UNIT_ID_LIGHT + 4; } public void die(int[][] map) { Point curMap = getMapPoint(currentPosition); map[curMap.y][curMap.x] = 0; Point destMap = getMapPoint(destination); map[destMap.y][destMap.x] = 0; } /* * Use AStar pathfinding algorithm to find an optimal path that takes obstacles into account */ private int currentMapEndX = 0, currentMapEndY = 0; public void findPath(int [][] map) { Point mapStart = getMapPoint(this.currentPosition); Point mapEnd = getMapPoint(this.destination); //If the units are ordered to start moving, then begin calculating paths if (pathUnit.getIsMoving() == true) { //generate path only once if (pathUnit.findPath(map, mapStart, mapEnd)) { //erase current position from map if current pos isn't wall or flag if (map[mapStart.y][mapStart.x] != GameMap.TILE_WALL && map[mapStart.y][mapStart.x] != 8 && map[mapStart.y][mapStart.x] != 9) map[mapStart.y][mapStart.x] = 0; //add end position to the map if (map[mapEnd.y][mapEnd.x] != GameMap.TILE_WALL && map[mapEnd.y][mapEnd.x] != 8 && map[mapEnd.y][mapEnd.x] != 9) map[mapEnd.y][mapEnd.x] = classType + 1; currentMapEndX = mapEnd.x; currentMapEndY = mapEnd.y; //System.out.println(printMap(map)); } //If path is found, then begin moving if (pathUnit.isPathFound()) { //destination point changed, so recalculate path if (currentMapEndX != mapEnd.x || currentMapEndY != mapEnd.y) { pathUnit.setIsPathCreated(false); } //move from one node to the next moveToDestination(map); } } //visualize path //drawPathfinding(); } /*public void drawPathfinding() { if (pathUnit.getIsPathCreated() == true) { //render the complete path from start to finish for (int i = pathUnit.getPath().size() - 1; i >= 0; i--) { SimpleRTS.offscr.setColor(Color.ORANGE); SimpleRTS.offscr.drawRect(pathUnit.getPath().get(i).getX() * GameMap.TILE_WIDTH - SimpleRTS.cameraX, pathUnit.getPath().get(i).getY() * GameMap.TILE_HEIGHT - SimpleRTS.cameraY, GameMap.TILE_WIDTH, GameMap.TILE_HEIGHT); } } }*/ /* * Change the player position until player reaches waypoint. */ public void moveToDestination(int[][] map) { //If player isn't moving, then don't do anything if (pathUnit.getIsMoving() == false) return; //player must be moving, but not attacking // if (isAttacking == false) //Get the corresponding unit list ArrayList unitList = (isPlayerUnit == true) ? SimpleRTS.playerList : SimpleRTS.enemyList; //Iterate through the whole player list, adding units to a group for (int i = 0; i < unitList.size(); i++) { GameUnit other = unitList.get(i); //don't compare to itself if (other == this) continue; //make sure destination is same Point otherMapDest = getMapPoint(other.destination); Point playerMapDest = getMapPoint(this.destination); if (otherMapDest.x == playerMapDest.x && otherMapDest.y == playerMapDest.y) { if (other.pathUnit.getIsPathCreated() == false) continue; other.destination = other.pathUnit.recalculateDest(map, playerMapDest); Point currentEnd = getMapPoint(other.destination); currentMapEndX = currentEnd.x; currentMapEndY = currentEnd.y; //Point otherMapCurrent = getMapPoint(other.current); //otherMapDest = getMapPoint(other.destination); //other.pathUnit.findPath(map, otherMapCurrent, otherMapDest); //map[otherMapCurrent.y][otherMapCurrent.x] = 0; //map[otherMapDest.y][otherMapDest.x] = other.classType + 1; } unitList.set(i, other); //modify unit's destination if needed } currentPosition = pathUnit.run(); } /* * When the ally unit is close enough to see the enemy, the ally and enemy will fight each other */ public void interactWithEnemy(int [][] map, ArrayList enemyList) { final int ATTACK_RADIUS = 8; for (int i = 0; i < enemyList.size(); i++) { GameUnit enemy = enemyList.get(i); int manhattanDist = Math.abs(currentPosition.x - enemy.currentPosition.x)/GameMap.TILE_WIDTH + Math.abs(currentPosition.y - enemy.currentPosition.y)/GameMap.TILE_HEIGHT; if (manhattanDist <= ATTACK_RADIUS && this.checkVisible(map, enemy)) { isAttacking = true; //remove enemy damage from ally and vice versa this.health -= enemy.dealDamagePoints(this); enemy.health -= this.dealDamagePoints(enemy); //draw red box around enemy units under fire /*SimpleRTS.offscr.setColor(Color.RED); SimpleRTS.offscr.drawRect(enemy.getCurrentPoint().x - SimpleRTS.cameraX, enemy.getCurrentPoint().y - SimpleRTS.cameraY, GameMap.TILE_WIDTH, GameMap.TILE_HEIGHT);*/ } else { isAttacking = false; } } } //Different types of units deal different damage //(ex. a light unit would do more damage to a medium unit, but less to a heavy unit) public int dealDamagePoints(GameUnit enemy) { if (classType == UNIT_ID_LIGHT) { if (enemy.classType == UNIT_ID_LIGHT) { return 2; } if (enemy.classType == UNIT_ID_MEDIUM) { return 3; } if (enemy.classType == UNIT_ID_HEAVY) { return 2; } } else if (classType == UNIT_ID_MEDIUM) { if (enemy.classType == UNIT_ID_LIGHT) { return 2; } if (enemy.classType == UNIT_ID_MEDIUM) { return 2; } if (enemy.classType== UNIT_ID_HEAVY) { return 3; } } else if (classType == UNIT_ID_HEAVY) { if (enemy.classType == UNIT_ID_LIGHT) { return 5; } if (enemy.classType == UNIT_ID_MEDIUM) { return 2; } if (enemy.classType == UNIT_ID_HEAVY) { return 2; } } return 1; } /* * Goal: Make sure enemy is within sight of player so that the player cannot shoot through walls. */ public boolean checkVisible(int map[][], GameUnit enemy) { Point entity1 = new Point(getMapPoint(this.currentPosition)); Point entity2 = new Point(getMapPoint(enemy.currentPosition)); //same row if (Math.abs(entity1.y - entity2.y) <= 1) { return checkRowVisible(map, entity1.x, entity1.y, entity2.x, entity2.y); } //same column if (Math.abs(entity1.x - entity2.x) <= 1) { return checkColumnVisible(map, entity1.x, entity1.y, entity2.x, entity2.y); } //otherwise, trace a line of sight between the two tiles and determine whether the line intersects any tiles return checkDiagonalVisible(map, entity1.x, entity1.y, entity2.x, entity2.y); } public boolean checkRowVisible(int map[][], int entityX1, int entityY1, int entityX2, int entityY2) { int minX = Math.min(entityX1, entityX2); int maxX = Math.max(entityX1, entityX2); for (int x = minX + 1; x <= maxX - 1; x++) { if (map[entityY1][x] == GameMap.TILE_WALL) return false; } return true; } public boolean checkColumnVisible(int map[][], int entityX1, int entityY1, int entityX2, int entityY2) { int minY = Math.min(entityY1, entityY2); int maxY = Math.max(entityY1, entityY2); for (int y = minY; y <= maxY; y++) { if (map[y][entityX1] == GameMap.TILE_WALL) return false; } return true; } public boolean checkDiagonalVisible(int map[][], int entityX1, int entityY1, int entityX2, int entityY2) { double deltaY = entityY2 - entityY1; double deltaX = entityX2 - entityX1; if (entityY1 < entityY2) { double slope = deltaX/deltaY; double curX = entityX1 + 0.5*slope; for (int y = entityY1 + 1; y <= entityY2; y++) { if (map[y][(int)Math.round(curX)] == GameMap.TILE_WALL) return false; curX += slope; } } else { double slope = deltaX/deltaY; double curX = entityX1 - 0.5*slope; for (int y = entityY1 - 1; y >= entityY2; y--) { if (map[y][(int)Math.round(curX)] == GameMap.TILE_WALL) return false; curX -= slope; } } if (entityX1 < entityX2) { double curY = entityY1 + 0.5*deltaY/deltaX; for (int x = entityX1 + 1; x <= entityX2; x++) { if (map[(int)Math.round(curY)][x] == GameMap.TILE_WALL) return false; curY += deltaY/deltaX; } } else { double curY = entityY1 - 0.5*deltaY/deltaX; for (int x = entityX1 - 1; x >= entityX2; x--) { if (map[(int)Math.round(curY)][x] == GameMap.TILE_WALL) return false; curY -= deltaY/deltaX; } } return true; } } package agrudados; import estatistica.Calculos; import model.ElementosModel; import model.elementos; import estatistica.Central; import java.beans.PropertyVetoException; import java.util.Arrays; import javax.swing.table.TableRowSorter; public class Tela_MedidasDeTendencia extends javax.swing.JInternalFrame { ElementosModel modeloTabela = new ElementosModel(); @Override public void setMaximum(boolean bln) throws PropertyVetoException { super.setMaximum(bln); //To change body of generated methods, choose Tools | Templates. } @Override public void setMaximizable(boolean maximizable) { this.maximizable = maximizable; } /** * Creates new form medidasdetendenciacentralSimpes */ public Tela_MedidasDeTendencia() { initComponents(); tabela.setModel(modeloTabela); tabela.setRowSorter(new TableRowSorter(modeloTabela)); } // //GEN-BEGIN:initComponents private void initComponents() { jLabel8 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); buttonGroup1 = new javax.swing.ButtonGroup(); buttonGroup2 = new javax.swing.ButtonGroup(); buttonGroup3 = new javax.swing.ButtonGroup(); buttonGroup4 = new javax.swing.ButtonGroup(); panelPrincipalMTS = new javax.swing.JPanel(); PainelMedTend = new javax.swing.JPanel(); panelCentrais = new javax.swing.JPanel(); resultMedia = new javax.swing.JLabel(); resultModa = new javax.swing.JLabel(); resultMediana = new javax.swing.JLabel(); panelTipoConjunto = new javax.swing.JPanel(); conjuntoPopulacional = new javax.swing.JRadioButton(); conjuntoAmostral = new javax.swing.JRadioButton(); panelDispersao = new javax.swing.JPanel(); resultVar = new javax.swing.JLabel(); resultDP = new javax.swing.JLabel(); resultDM = new javax.swing.JLabel(); resultAmplitude = new javax.swing.JLabel(); resultCV = new javax.swing.JLabel(); panelElementosConjunto = new javax.swing.JPanel(); botaoAlterar = new javax.swing.JButton(); botaoExcluir = new javax.swing.JButton(); botaoCalcular = new javax.swing.JButton(); caixaDeTexto = new javax.swing.JTextField(); botaoEnviar = new javax.swing.JButton(); panelConjunto = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tabela = new javax.swing.JTable(); jLabel8.setText("jLabel7"); setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); setClosable(true); setTitle("Medidas de tendência"); setToolTipText(""); setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/table.png"))); // NOI18N setName("telaInternaMTC"); // NOI18N setNextFocusableComponent(caixaDeTexto); setVerifyInputWhenFocusTarget(false); PainelMedTend.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Medidas", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); PainelMedTend.setForeground(java.awt.Color.gray); panelCentrais.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Central", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); panelCentrais.setForeground(java.awt.Color.darkGray); resultMedia.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Media", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); resultMedia.setName("resultMedia"); // NOI18N resultModa.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Moda", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); resultModa.setName("resultModa"); // NOI18N resultMediana.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Mediana", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); resultMediana.setName("resultMediana"); // NOI18N panelTipoConjunto.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Tipo de conjunto", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); conjuntoPopulacional.setText("Conjunto Populacional"); conjuntoPopulacional.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { conjuntoPopulacionalActionPerformed(evt); } }); conjuntoAmostral.setSelected(true); conjuntoAmostral.setText("Conjunto Amostral"); conjuntoAmostral.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { conjuntoAmostralActionPerformed(evt); } }); javax.swing.GroupLayout panelTipoConjuntoLayout = new javax.swing.GroupLayout(panelTipoConjunto); panelTipoConjunto.setLayout(panelTipoConjuntoLayout); panelTipoConjuntoLayout.setHorizontalGroup( panelTipoConjuntoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelTipoConjuntoLayout.createSequentialGroup() .addContainerGap() .addGroup(panelTipoConjuntoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(conjuntoAmostral) .addComponent(conjuntoPopulacional)) .addContainerGap()) ); panelTipoConjuntoLayout.setVerticalGroup( panelTipoConjuntoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelTipoConjuntoLayout.createSequentialGroup() .addContainerGap() .addComponent(conjuntoAmostral) .addGap(6, 6, 6) .addComponent(conjuntoPopulacional) .addContainerGap()) ); javax.swing.GroupLayout panelCentraisLayout = new javax.swing.GroupLayout(panelCentrais); panelCentrais.setLayout(panelCentraisLayout); panelCentraisLayout.setHorizontalGroup( panelCentraisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelCentraisLayout.createSequentialGroup() .addContainerGap() .addGroup(panelCentraisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(resultMedia, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(resultModa, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(resultMediana, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(panelCentraisLayout.createSequentialGroup() .addComponent(panelTipoConjunto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); panelCentraisLayout.setVerticalGroup( panelCentraisLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelCentraisLayout.createSequentialGroup() .addContainerGap() .addComponent(resultMedia, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(resultModa, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(resultMediana, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelTipoConjunto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); resultMedia.getAccessibleContext().setAccessibleName("resultMedia"); resultModa.getAccessibleContext().setAccessibleName("resultModa"); resultMediana.getAccessibleContext().setAccessibleName("resultMediana"); panelDispersao.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Dispersão", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); panelDispersao.setForeground(java.awt.Color.darkGray); resultVar.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Variância", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); resultVar.setName("resultVar"); // NOI18N resultDP.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Desvio padrão", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); resultDP.setName("resultDP"); // NOI18N resultDP.setRequestFocusEnabled(false); resultDM.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Desvio médio", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); resultDM.setName("resultDM"); // NOI18N resultAmplitude.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Amplitude", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); resultAmplitude.setName("resultAmplitude"); // NOI18N resultAmplitude.setRequestFocusEnabled(false); resultCV.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Coeficiênte de variação", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); resultCV.setName("resultCV"); // NOI18N resultCV.setRequestFocusEnabled(false); javax.swing.GroupLayout panelDispersaoLayout = new javax.swing.GroupLayout(panelDispersao); panelDispersao.setLayout(panelDispersaoLayout); panelDispersaoLayout.setHorizontalGroup( panelDispersaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelDispersaoLayout.createSequentialGroup() .addContainerGap() .addGroup(panelDispersaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(resultDM, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(resultVar, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(resultDP, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(resultAmplitude, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(resultCV, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); panelDispersaoLayout.setVerticalGroup( panelDispersaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelDispersaoLayout.createSequentialGroup() .addContainerGap() .addComponent(resultDM, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(resultVar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(resultDP, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(resultAmplitude, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, Short.MAX_VALUE) .addComponent(resultCV, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) ); resultVar.getAccessibleContext().setAccessibleName("resultVar"); resultDP.getAccessibleContext().setAccessibleName("resultDP"); resultDM.getAccessibleContext().setAccessibleName("resultDM"); javax.swing.GroupLayout PainelMedTendLayout = new javax.swing.GroupLayout(PainelMedTend); PainelMedTend.setLayout(PainelMedTendLayout); PainelMedTendLayout.setHorizontalGroup( PainelMedTendLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PainelMedTendLayout.createSequentialGroup() .addContainerGap() .addComponent(panelCentrais, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(26, 26, 26) .addComponent(panelDispersao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); PainelMedTendLayout.setVerticalGroup( PainelMedTendLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PainelMedTendLayout.createSequentialGroup() .addContainerGap() .addGroup(PainelMedTendLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelDispersao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelCentrais, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) ); panelElementosConjunto.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Elementos do conjunto", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); botaoAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/table_edit.png"))); // NOI18N botaoAlterar.setText("Alterar"); botaoAlterar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoAlterarActionPerformed(evt); } }); botaoExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/table_delete.png"))); // NOI18N botaoExcluir.setText("Excluir"); botaoExcluir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoExcluirActionPerformed(evt); } }); botaoCalcular.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/calculator.png"))); // NOI18N botaoCalcular.setText("Calcular"); botaoCalcular.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoCalcularActionPerformed(evt); } }); caixaDeTexto.setBorder(javax.swing.BorderFactory.createEtchedBorder()); caixaDeTexto.setOpaque(false); caixaDeTexto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { caixaDeTextoActionPerformed(evt); } }); caixaDeTexto.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { caixaDeTextoKeyPressed(evt); } }); botaoEnviar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/table_go.png"))); // NOI18N botaoEnviar.setText("Enviar"); botaoEnviar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoEnviarActionPerformed(evt); } }); javax.swing.GroupLayout panelElementosConjuntoLayout = new javax.swing.GroupLayout(panelElementosConjunto); panelElementosConjunto.setLayout(panelElementosConjuntoLayout); panelElementosConjuntoLayout.setHorizontalGroup( panelElementosConjuntoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelElementosConjuntoLayout.createSequentialGroup() .addContainerGap() .addGroup(panelElementosConjuntoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(panelElementosConjuntoLayout.createSequentialGroup() .addComponent(botaoCalcular) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(botaoExcluir)) .addComponent(caixaDeTexto)) .addGap(18, 18, 18) .addGroup(panelElementosConjuntoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(botaoAlterar, javax.swing.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE) .addComponent(botaoEnviar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); panelElementosConjuntoLayout.setVerticalGroup( panelElementosConjuntoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelElementosConjuntoLayout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(panelElementosConjuntoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(caixaDeTexto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(botaoEnviar)) .addGap(18, 18, 18) .addGroup(panelElementosConjuntoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(botaoExcluir) .addComponent(botaoAlterar) .addComponent(botaoCalcular)) .addContainerGap()) ); panelConjunto.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Conjunto", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION)); tabela.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); tabela.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null} }, new String [] { "" } ) { Class[] types = new Class [] { java.lang.Double.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); tabela.setColumnSelectionAllowed(true); jScrollPane1.setViewportView(tabela); tabela.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); tabela.getAccessibleContext().setAccessibleName(""); javax.swing.GroupLayout panelConjuntoLayout = new javax.swing.GroupLayout(panelConjunto); panelConjunto.setLayout(panelConjuntoLayout); panelConjuntoLayout.setHorizontalGroup( panelConjuntoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelConjuntoLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()) ); panelConjuntoLayout.setVerticalGroup( panelConjuntoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelConjuntoLayout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout panelPrincipalMTSLayout = new javax.swing.GroupLayout(panelPrincipalMTS); panelPrincipalMTS.setLayout(panelPrincipalMTSLayout); panelPrincipalMTSLayout.setHorizontalGroup( panelPrincipalMTSLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelPrincipalMTSLayout.createSequentialGroup() .addContainerGap() .addGroup(panelPrincipalMTSLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(panelElementosConjunto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panelConjunto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(PainelMedTend, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panelPrincipalMTSLayout.setVerticalGroup( panelPrincipalMTSLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelPrincipalMTSLayout.createSequentialGroup() .addGap(50, 50, 50) .addGroup(panelPrincipalMTSLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(panelPrincipalMTSLayout.createSequentialGroup() .addComponent(panelElementosConjunto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(panelConjunto, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(PainelMedTend, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); PainelMedTend.getAccessibleContext().setAccessibleDescription(""); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(panelPrincipalMTS, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(12, Short.MAX_VALUE) .addComponent(panelPrincipalMTS, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// //GEN-END:initComponents private void conjuntoAmostralActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_conjuntoAmostralActionPerformed conjuntoPopulacional.setSelected(false); }//GEN-LAST:event_conjuntoAmostralActionPerformed private void conjuntoPopulacionalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_conjuntoPopulacionalActionPerformed conjuntoAmostral.setSelected(false); }//GEN-LAST:event_conjuntoPopulacionalActionPerformed private void botaoCalcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCalcularActionPerformed int tamTabela = tabela.getRowCount(); double valor[] = new double[tamTabela]; boolean isConjuntoAmostral = conjuntoAmostral.isSelected(); for (int i = 0; i < tamTabela; i++) { valor[i] = Double.parseDouble(tabela.getValueAt(i, 0).toString()); } Arrays.sort(valor); Calculos CalculosEstat = new Central(); /** * Insere todos valores necessários para realização de cálculos. */ CalculosEstat.iserirDados(valor, isConjuntoAmostral); /** * Insere os valores obtidos nos cálculos nas labels da tela. */ { resultMedia.setText(String.valueOf(CalculosEstat.getMedia())); if (CalculosEstat.getIndiceModa() >= 0) { resultModa.setText(String.valueOf(CalculosEstat.getModa())); } else if (CalculosEstat.getIndiceModa() == -1) { resultModa.setText("Amodal"); } else if (CalculosEstat.getIndiceModa() == -2) { resultModa.setText("Bimodal"); } else { resultModa.setText("Multimodal"); } resultMediana.setText(String.valueOf(CalculosEstat.getMediana())); resultVar.setText(String.valueOf(CalculosEstat.getVariancia())); resultDP.setText(String.valueOf(CalculosEstat.getDesvioPadrao())); resultDM.setText(String.valueOf(CalculosEstat.getDesvioMedio())); resultAmplitude.setText(String.valueOf(CalculosEstat.getAmplitude())); resultCV.setText(String.valueOf(CalculosEstat.getCoeficienteVariacao()) + " %"); } }//GEN-LAST:event_botaoCalcularActionPerformed private void botaoAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoAlterarActionPerformed if (tabela.getSelectedRow() != -1) { modeloTabela.setValueAt(caixaDeTexto.getText(), tabela.getSelectedRow(), 0); } }//GEN-LAST:event_botaoAlterarActionPerformed private void botaoExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoExcluirActionPerformed if (tabela.getSelectedRow() != -1) { modeloTabela.removeRow(tabela.getSelectedRow()); } }//GEN-LAST:event_botaoExcluirActionPerformed private void botaoEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoEnviarActionPerformed elementos e = new elementos(); e.setNumeros(Double.parseDouble(caixaDeTexto.getText())); modeloTabela.addrow(e); caixaDeTexto.setText(""); }//GEN-LAST:event_botaoEnviarActionPerformed private void caixaDeTextoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_caixaDeTextoKeyPressed if (evt.getKeyCode() == 10) { elementos e = new elementos(); e.setNumeros(Double.parseDouble(caixaDeTexto.getText())); modeloTabela.addrow(e); caixaDeTexto.setText(""); } }//GEN-LAST:event_caixaDeTextoKeyPressed private void caixaDeTextoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_caixaDeTextoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_caixaDeTextoActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel PainelMedTend; private javax.swing.JButton botaoAlterar; private javax.swing.JButton botaoCalcular; private javax.swing.JButton botaoEnviar; private javax.swing.JButton botaoExcluir; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.ButtonGroup buttonGroup2; private javax.swing.ButtonGroup buttonGroup3; private javax.swing.ButtonGroup buttonGroup4; private javax.swing.JTextField caixaDeTexto; private javax.swing.JRadioButton conjuntoAmostral; private javax.swing.JRadioButton conjuntoPopulacional; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel8; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JPanel panelCentrais; private javax.swing.JPanel panelConjunto; private javax.swing.JPanel panelDispersao; private javax.swing.JPanel panelElementosConjunto; private javax.swing.JPanel panelPrincipalMTS; private javax.swing.JPanel panelTipoConjunto; private javax.swing.JLabel resultAmplitude; private javax.swing.JLabel resultCV; private javax.swing.JLabel resultDM; private javax.swing.JLabel resultDP; private javax.swing.JLabel resultMedia; private javax.swing.JLabel resultMediana; private javax.swing.JLabel resultModa; private javax.swing.JLabel resultVar; private javax.swing.JTable tabela; // End of variables declaration//GEN-END:variables } src/main/java/com/product/repository/BookRepository.java0 package com.product.repository; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.product.entity.Book; @Repository public interface BookRepository extends JpaRepository { /** * Native Query * * @param title * @return */ @Query(value = "select * from book where title like CONCAT('%', :title, '%')", nativeQuery = true) public List findSmilarTitleBook(@Param("title") String title); /** * Derive Query * * @param title * @return */ public List findByTitleLike(String title); public Optional findByTitle(String title); public Optional deleteByTitle(String title); public List deleteByUpdatedAtBefore(LocalDateTime updatedAt); }openengine-core/src/main/java/org/openengine/EngineState.java package org.openengine; import java.util.concurrent.atomic.AtomicBoolean; public abstract class EngineState { private EngineState() {} private static final AtomicBoolean running = new AtomicBoolean(false); public static boolean isRunning() { return running.get(); } public static void setRunning() { running.getAndSet(true); } public static void setStopped() { running.getAndSet(false); } private static final AtomicBoolean shouldStop = new AtomicBoolean(false); public static boolean isShouldStop() { return shouldStop.get(); } public static void setShouldStop() { shouldStop.getAndSet(true); } } 1-10 package org.geektimes.projects.user.jmx; import javax.management.MBeanServer; import javax.management.ObjectName; import java.lang.management.ManagementFactory; import org.geektimes.context.core.Context; import org.geektimes.context.ContextRunner; /** * @author young1lin * @since 2021/3/16 下午11:07 * @version 1.0 */ public class RegisterUserMBeanContextRunner implements ContextRunner { @Override public void run(Context context) { UserMBean user = (UserMBean) context.getComponent("userMBean"); System.out.println(this.getClass().getName() + ": current user attributes are : " + user); try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name = new ObjectName("org.geektimes.mbean:type=User"); mbs.registerMBean(user, name); } catch (Exception e) { // 这里代码格式化是 Spring 的格式化的风格 // 偷个懒 e.printStackTrace(); } } } /* * This file is part of the HyperGraphDB source distribution. This is copyrighted software. For permitted * uses, licensing options and redistribution, please see the LicensingInformation file at the root level of * the distribution. * * Copyright (c) 2005-2010 , Inc. All rights reserved. */ package org.hypergraphdb.storage.bje; import org.hypergraphdb.HGException; import org.hypergraphdb.util.CloseMe; import com.sleepycat.je.Cursor; import com.sleepycat.je.DatabaseException; public final class BJETxCursor implements CloseMe { private TransactionBJEImpl tx; private Cursor cursor = null; private boolean open = true; public BJETxCursor(Cursor cursor, TransactionBJEImpl tx) { this.cursor = cursor; this.tx = tx; open = cursor != null; } public Cursor cursor() { return cursor; } public boolean isOpen() { return open; } public void close() { if (!open) return; try { cursor.close(); } catch (DatabaseException ex) { throw new HGException(ex); } finally { open = false; cursor = null; if (tx != null) { tx.removeCursor(this); } } } } src/main/java/org/wcardinal/controller/data/internal/SMapPatchesImpl.java1-10 /* * Copyright (C) 2019 Toshiba Corporation * SPDX-License-Identifier: Apache-2.0 */ package org.wcardinal.controller.data.internal; import java.util.NavigableMap; import java.util.TreeMap; public class SMapPatchesImpl extends SMapPatches> { final SMapPatchMap PATCH_MAP_DUMMY = new SMapPatchMap<>(); @Override SMapPatch newPatchMap() { return new SMapPatchMap(); } @Override SMapPatch getPatchMapDummy() { return PATCH_MAP_DUMMY; } @Override SMapPatch newPatchReset() { return new SMapPatchReset( null ); } @Override SMapPatch newPatchReset( NavigableMap value ) { return new SMapPatchReset( new TreeMap( value ) ); } @Override SPatchesPacked, SMapPatch> newPatchesPacked( final long authorizedRevision, final long revision, final SMapPatch patchReset ){ return new SMapPatchesPackedImpl( authorizedRevision, revision, patchReset ); } @Override SPatchesPacked, SMapPatch> newPatchesPacked( final long authorizedRevision, final long revision, NavigableMap> revisionToPatchPacked ){ return new SMapPatchesPackedImpl( authorizedRevision, revision, revisionToPatchPacked ); } } import com.google.common.base.Optional; import com.google.common.base.Function; import com.google.common.collect.FluentIterable; import java.util.ArrayList; import java.util.List; public class Collector { public int create111() { return FluentIterable.from(new ArrayList()).transform(s -> s + s).size(); } public FluentIterable create() { return FluentIterable.from(new ArrayList()).transform(s -> s + s); } public FluentIterable create2() { return create().limit(12); } public FluentIterable create3() { return create2().limit(12); } public Optional m(FluentIterable fi, Function f1, Function f2) { return fi.transform(f1).transform(f2).first(); } }package mcsoft.com.livewallpaperdemo.activity; import android.app.WallpaperInfo; import android.app.WallpaperManager; import android.content.ComponentName; import android.content.Intent; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import java.io.IOException; import butterknife.BindView; import butterknife.ButterKnife; import mcsoft.com.livewallpaperdemo.R; import mcsoft.com.livewallpaperdemo.service.LiveWallpaperService; public class LiveWallpaperActivity extends AppCompatActivity { private final static int CHANGE_WALLPAPER_STATUS_CODE = 1; private final static String TAG = LiveWallpaperActivity.class.getCanonicalName(); @BindView(R.id.enable_wallpaper_button) Button button; @BindView(R.id.tv_version_type) TextView versionType; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_live_wallpaper); ButterKnife.bind(this); setButtonTitle(); versionType.setText("version: API 21"); button.setOnClickListener(getOnClickListener()); } private View.OnClickListener getOnClickListener() { return new View.OnClickListener() { @Override public void onClick(View v) { if (isWallpaperActive() == true) { disableWallpaper(); } else { setWallpaperActive(); } } }; } private void setButtonTitle() { if (isWallpaperActive() == true) { button.setText("Disable Wallpaper"); } else { button.setText("Enable Wallpaper"); } } private boolean isWallpaperActive() { boolean result = false; WallpaperManager wpm = (WallpaperManager) getSystemService(WALLPAPER_SERVICE); WallpaperInfo info = wpm.getWallpaperInfo(); if (info != null) { ComponentName serviceComponent = info.getComponent(); String serviceClassName = serviceComponent.getClassName(); String liveWallpaperClassName = LiveWallpaperService.class.getName(); if (serviceClassName.equals(liveWallpaperClassName)) { Log.d(TAG, "Live Wallpaper is already running"); result = true; } else { Log.d(TAG, "Live Wallpaper is not running, this should be a preview"); } } return result; } private void setWallpaperActive() { Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER); intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(this, LiveWallpaperService.class)); startActivityForResult(intent, CHANGE_WALLPAPER_STATUS_CODE); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CHANGE_WALLPAPER_STATUS_CODE) { setButtonTitle(); } } private void disableWallpaper() { WallpaperManager wpm = (WallpaperManager) getSystemService(WALLPAPER_SERVICE); try { wpm.clear(); setButtonTitle(); } catch (IOException e) { e.printStackTrace(); Log.d(TAG, "Live Wallpaper cannot be disabled"); } } } ccri-dao-stu3/src/main/java/uk/nhs/careconnect/ri/stu3/dao/transforms/ClaimEntityToFHIRClaim.java package uk.nhs.careconnect.ri.stu3.dao.transforms; import ca.uhn.fhir.context.FhirContext; import org.apache.commons.collections4.Transformer; import org.hl7.fhir.dstu3.model.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import uk.nhs.careconnect.ri.database.entity.careTeam.CareTeamEntity; import uk.nhs.careconnect.ri.database.entity.claim.ClaimDiagnosis; import uk.nhs.careconnect.ri.database.entity.claim.ClaimEntity; import uk.nhs.careconnect.ri.database.entity.claim.ClaimRelated; import uk.nhs.careconnect.ri.stu3.dao.LibDao; import java.util.ArrayList; @Component public class ClaimEntityToFHIRClaim implements Transformer { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(CareTeamEntity.class); @Autowired private LibDao libDao; @Override public Claim transform(ClaimEntity claimEntity) { return null; } public Claim transform(ClaimEntity claimEntity, FhirContext ctx) { final Claim claim = (Claim) ctx.newJsonParser().parseResource(claimEntity.getResource()); claim.setId(claimEntity.getId().toString()); claim.setPatient(null); if (claimEntity.getPatient() != null) { claim .setPatient(new Reference("Patient/"+claimEntity.getPatient().getId()) .setDisplay(claimEntity.getPatient().getNames().get(0).getDisplayName())); } claim.setEnterer(null); claim.setExtension(new ArrayList<>()); if (claimEntity.getEntererPatient() != null) { Extension extension = new Extension(); extension.setUrl("https://fhir.gov.uk/Extension/claimEntererPatient"); Reference patRef = new Reference("Patient/"+claimEntity.getEntererPatient().getId()) .setDisplay(claimEntity.getEntererPatient().getNames().get(0).getDisplayName()); patRef.addExtension(libDao.getResourceTypeExt("Patient")); extension.setValue(patRef); claim.addExtension(extension); } if (claimEntity.getEntererPractitioner() != null) { claim.setEnterer(new Reference("Practitioner/"+claimEntity.getEntererPractitioner().getId()) .setDisplay(claimEntity.getEntererPractitioner().getNames().get(0).getDisplayName())); } claim.setOrganization(null); if (claimEntity.getProviderOrganisation() != null) { claim.setOrganization(new Reference("Organization/"+claimEntity.getProviderOrganisation().getId()) .setDisplay(claimEntity.getProviderOrganisation().getName())); } claim.setInsurer(null); if (claimEntity.getInsurerOrganisation() != null) { claim.setInsurer(new Reference("Organization/"+claimEntity.getInsurerOrganisation().getId()) .setDisplay(claimEntity.getInsurerOrganisation().getName())); } claim.setType(null); if (claimEntity.getType() != null) { CodeableConcept concept = new CodeableConcept(); if (claimEntity.getType().getConceptText() != null) { concept.setText(claimEntity.getType().getConceptText()); } if (claimEntity.getType().getConceptCode() != null) { concept.addCoding() .setCode(claimEntity.getType().getConceptCode().getCode()) .setDisplay(claimEntity.getType().getConceptCode().getDisplay()) .setSystem(claimEntity.getType().getConceptCode().getSystem()); } claim.setType(concept); } claim.setDiagnosis(new ArrayList<>()); for (ClaimDiagnosis diagnosis : claimEntity.getDiagnoses()) { Claim.DiagnosisComponent component = new Claim.DiagnosisComponent(); if (diagnosis.getCondition() != null) { Reference ref = new Reference("Condition/"+diagnosis.getId()); ref.setDisplay(diagnosis.getCondition().getCodeText()); component.setDiagnosis(ref); } claim.getDiagnosis().add(component); } claim.setCreated(claimEntity.getCreated()); claim.setRelated(new ArrayList<>()); for (ClaimRelated related : claimEntity.getRelatedClaims()) { Claim.RelatedClaimComponent component = new Claim.RelatedClaimComponent(); if (related.getRelatedClaim() != null) { component.setClaim(new Reference("Claim/"+related.getRelatedClaim().getId())); } if (related.getConceptCode() != null) { if (related.getConceptCode().getCode() != null) { component.getRelationship() .addCoding() .setSystem(related.getConceptCode().getSystem()) .setCode(related.getConceptCode().getCode()) .setDisplay(related.getConceptCode().getDisplay()); } if (related.getConceptText()!= null) { component.getRelationship().setText(related.getConceptText()); } } claim.getRelated().add(component); } return claim; } } package uk.gov.hmcts.dts.fact.model.deprecated; import org.assertj.core.api.SoftAssertions; import org.junit.jupiter.api.Test; import uk.gov.hmcts.dts.fact.entity.*; import java.util.List; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; public class OldCourtTest { private static final String DX_DESCRIPTION = "DX"; private static final String TEST_CONTACT_DESCRIPTION = "Enquiries"; private static final String TEST_CONTACT_EXPLANATION = "Contact explanation"; private static final String TEST_DX_EXPLANATION = "DX explanation"; private static final String TEST_CONTACT_NUMBER = "0203999999"; private static final String TEST_DX_CODE = "DX 99"; @Test void testCreationWithContactNumberAndDxCode() { final Court courtEntity = new Court(); courtEntity.setAreasOfLawSpoe(emptyList()); final Contact contactEntity = new Contact(); contactEntity.setDescription(TEST_CONTACT_DESCRIPTION); contactEntity.setNumber(TEST_CONTACT_NUMBER); contactEntity.setExplanation(TEST_CONTACT_EXPLANATION); CourtContact courtContactEntity = new CourtContact(); courtContactEntity.setContact(contactEntity); courtEntity.setCourtContacts(singletonList(courtContactEntity)); final CourtType courtType = new CourtType(); courtType.setName("Crown court"); final AddressType addressType = new AddressType(); addressType.setName("Visit us"); final CourtAddress courtAddress = new CourtAddress(); courtAddress.setAddress("1 High Street"); courtAddress.setTownName("London"); courtAddress.setPostcode("SW1A 1AA"); courtAddress.setAddressType(addressType); final AreaOfLaw areaOfLaw = new AreaOfLaw(); areaOfLaw.setName("Adoption"); courtEntity.setAreasOfLawSpoe(emptyList()); courtEntity.setCourtTypes(singletonList(courtType)); courtEntity.setAddresses(singletonList(courtAddress)); courtEntity.setAreasOfLaw(singletonList(areaOfLaw)); final DxCode dxCodeEntity = new DxCode(); dxCodeEntity.setCode(TEST_DX_CODE); dxCodeEntity.setExplanation(TEST_DX_EXPLANATION); CourtDxCode courtDxCodeEntity = new CourtDxCode(); courtDxCodeEntity.setDxCode(dxCodeEntity); courtEntity.setCourtDxCodes(singletonList(courtDxCodeEntity)); final OldCourt oldCourt = new OldCourt(courtEntity); oldCourt.setAreasOfLawSpoe(emptyList()); final List contacts = oldCourt.getContacts(); final SoftAssertions softly = new SoftAssertions(); softly.assertThat(contacts).hasSize(2); softly.assertThat(contacts.get(0).getName()).isEqualTo(TEST_CONTACT_DESCRIPTION); softly.assertThat(contacts.get(0).getNumber()).isEqualTo(TEST_CONTACT_NUMBER); softly.assertThat(contacts.get(0).getExplanation()).isEqualTo(TEST_CONTACT_EXPLANATION); softly.assertThat(contacts.get(1).getName()).isEqualTo(DX_DESCRIPTION); softly.assertThat(contacts.get(1).getNumber()).isEqualTo(TEST_DX_CODE); softly.assertThat(contacts.get(1).getExplanation()).isEqualTo(TEST_DX_EXPLANATION); softly.assertAll(); } } /* * Copyright (c) 2004-2021, University of Oslo * 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 the HISP project 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 OWNER 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.hisp.dhis.android.core.fileresource.internal; import android.content.Context; import android.util.Log; import androidx.annotation.NonNull; import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutor; import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableDataObjectStore; import org.hisp.dhis.android.core.arch.handlers.internal.HandlerWithTransformer; import org.hisp.dhis.android.core.common.State; import org.hisp.dhis.android.core.common.Unit; import org.hisp.dhis.android.core.fileresource.FileResource; import org.hisp.dhis.android.core.maintenance.D2Error; import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValue; import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValue; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import javax.inject.Inject; import dagger.Reusable; import okhttp3.ResponseBody; @Reusable class FileResourceCallFactory { private final FileResourceService fileResourceService; private final HandlerWithTransformer handler; private final IdentifiableDataObjectStore store; private final APICallExecutor apiCallExecutor; private final Context context; private enum Dimension { SMALL, MEDIUM } @Inject FileResourceCallFactory(@NonNull FileResourceService fileResourceService, @NonNull HandlerWithTransformer handler, @NonNull IdentifiableDataObjectStore store, @NonNull APICallExecutor apiCallExecutor, @NonNull Context context) { this.fileResourceService = fileResourceService; this.handler = handler; this.store = store; this.apiCallExecutor = apiCallExecutor; this.context = context; } public Callable create(final List trackedEntityAttributeValues, final List trackedEntityDataValues) { return () -> { downloadAttributeValueFiles(trackedEntityAttributeValues); downloadDataValueFiles(trackedEntityDataValues); return new Unit(); }; } private void downloadAttributeValueFiles(final List trackedEntityAttributeValues) { List fileResources = new ArrayList<>(); for (TrackedEntityAttributeValue trackedEntityAttributeValue : trackedEntityAttributeValues) { try { ResponseBody responseBody = apiCallExecutor.executeObjectCall( fileResourceService.getFileFromTrackedEntityAttribute( trackedEntityAttributeValue.trackedEntityInstance(), trackedEntityAttributeValue.trackedEntityAttribute(), Dimension.MEDIUM.name())); File file = FileResourceUtil.saveFileFromResponse( responseBody, trackedEntityAttributeValue.value(), context); fileResources.add(apiCallExecutor.executeObjectCall( fileResourceService.getFileResource(trackedEntityAttributeValue.value())) .toBuilder().path(file.getAbsolutePath()).build()); } catch (D2Error d2Error) { if (trackedEntityAttributeValue.value() != null) { this.store.deleteIfExists(trackedEntityAttributeValue.value()); } Log.v(FileResourceCallFactory.class.getCanonicalName(), d2Error.errorDescription()); } } handler.handleMany(fileResources, fileResource -> fileResource.toBuilder() .state(State.SYNCED) .build()); } private void downloadDataValueFiles(final List trackedEntityDataValues) { List fileResources = new ArrayList<>(); for (TrackedEntityDataValue trackedEntityDataValue : trackedEntityDataValues) { try { ResponseBody responseBody = apiCallExecutor.executeObjectCall( fileResourceService.getFileFromDataElement( trackedEntityDataValue.event(), trackedEntityDataValue.dataElement(), Dimension.MEDIUM.name())); File file = FileResourceUtil.saveFileFromResponse( responseBody, trackedEntityDataValue.value(), context); fileResources.add(apiCallExecutor.executeObjectCall( fileResourceService.getFileResource(trackedEntityDataValue.value())) .toBuilder().path(file.getAbsolutePath()).build()); } catch (D2Error d2Error) { if (trackedEntityDataValue.value() != null) { this.store.deleteIfExists(trackedEntityDataValue.value()); } Log.v(FileResourceCallFactory.class.getCanonicalName(), d2Error.errorDescription()); } } handler.handleMany(fileResources, fileResource -> fileResource.toBuilder() .state(State.SYNCED) .build()); } }1-10 /* * 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 androidx.core.graphics; import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP; import android.content.ContentResolver; import android.content.Context; import android.content.res.Resources; import android.graphics.Typeface; import android.os.CancellationSignal; import android.os.ParcelFileDescriptor; import android.system.ErrnoException; import android.system.Os; import android.system.OsConstants; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; import androidx.annotation.RestrictTo; import androidx.core.content.res.FontResourcesParserCompat.FontFamilyFilesResourceEntry; import androidx.core.content.res.FontResourcesParserCompat.FontFileResourceEntry; import androidx.core.provider.FontsContractCompat.FontInfo; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Implementation of the Typeface compat methods for API 21 and above. * @hide */ @RestrictTo(LIBRARY_GROUP) @RequiresApi(21) class TypefaceCompatApi21Impl extends TypefaceCompatBaseImpl { private static final String TAG = "TypefaceCompatApi21Impl"; private static final String FONT_FAMILY_CLASS = "android.graphics.FontFamily"; private static final String ADD_FONT_WEIGHT_STYLE_METHOD = "addFontWeightStyle"; private static final String CREATE_FROM_FAMILIES_WITH_DEFAULT_METHOD = "createFromFamiliesWithDefault"; private static final Class sFontFamily; private static final Constructor sFontFamilyCtor; private static final Method sAddFontWeightStyle; private static final Method sCreateFromFamiliesWithDefault; static { Class fontFamilyClass; Constructor fontFamilyCtor; Method addFontMethod; Method createFromFamiliesWithDefaultMethod; try { fontFamilyClass = Class.forName(FONT_FAMILY_CLASS); fontFamilyCtor = fontFamilyClass.getConstructor(); addFontMethod = fontFamilyClass.getMethod(ADD_FONT_WEIGHT_STYLE_METHOD, String.class, Integer.TYPE, Boolean.TYPE); Object familyArray = Array.newInstance(fontFamilyClass, 1); createFromFamiliesWithDefaultMethod = Typeface.class.getMethod(CREATE_FROM_FAMILIES_WITH_DEFAULT_METHOD, familyArray.getClass()); } catch (ClassNotFoundException | NoSuchMethodException e) { Log.e(TAG, e.getClass().getName(), e); fontFamilyClass = null; fontFamilyCtor = null; addFontMethod = null; createFromFamiliesWithDefaultMethod = null; } sFontFamilyCtor = fontFamilyCtor; sFontFamily = fontFamilyClass; sAddFontWeightStyle = addFontMethod; sCreateFromFamiliesWithDefault = createFromFamiliesWithDefaultMethod; } private File getFile(@NonNull ParcelFileDescriptor fd) { try { final String path = Os.readlink("/proc/self/fd/" + fd.getFd()); // Check if the symbolic link points the regular file. if (OsConstants.S_ISREG(Os.stat(path).st_mode)) { return new File(path); } else { return null; } } catch (ErrnoException e) { return null; // Mostly permission error. } } private static Object newFamily() { try { return sFontFamilyCtor.newInstance(); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { throw new RuntimeException(e); } } private static Typeface createFromFamiliesWithDefault(Object family) { try { Object familyArray = Array.newInstance(sFontFamily, 1); Array.set(familyArray, 0, family); return (Typeface) sCreateFromFamiliesWithDefault.invoke( null /* static method */, familyArray); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } private static boolean addFontWeightStyle(Object family, String name, int weight, boolean style) { try { final Boolean result = (Boolean) sAddFontWeightStyle.invoke( family, name, weight, style); return result.booleanValue(); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } @Override public Typeface createFromFontInfo(Context context, CancellationSignal cancellationSignal, @NonNull FontInfo[] fonts, int style) { if (fonts.length < 1) { return null; } final FontInfo bestFont = findBestInfo(fonts, style); final ContentResolver resolver = context.getContentResolver(); try (ParcelFileDescriptor pfd = resolver.openFileDescriptor(bestFont.getUri(), "r", cancellationSignal)) { if (pfd == null) { return null; } final File file = getFile(pfd); if (file == null || !file.canRead()) { // Unable to use the real file for creating Typeface. Fallback to copying // implementation. try (FileInputStream fis = new FileInputStream(pfd.getFileDescriptor())) { return super.createFromInputStream(context, fis); } } return Typeface.createFromFile(file); } catch (IOException e) { return null; } } @Override public Typeface createFromFontFamilyFilesResourceEntry(Context context, FontFamilyFilesResourceEntry entry, Resources resources, int style) { Object family = newFamily(); for (final FontFileResourceEntry e : entry.getEntries()) { final File tmpFile = TypefaceCompatUtil.getTempFile(context); if (tmpFile == null) { return null; } try { if (!TypefaceCompatUtil.copyToFile(tmpFile, resources, e.getResourceId())) { return null; } if (!addFontWeightStyle(family, tmpFile.getPath(), e.getWeight(), e.isItalic())) { return null; } } catch (RuntimeException exception) { // This was thrown from Typeface.createFromFile when a Typeface could not be loaded. // such as due to an invalid ttf or unreadable file. We don't want to throw that // exception anymore. return null; } finally { tmpFile.delete(); } } return createFromFamiliesWithDefault(family); } } 1-10 package com.kaweel.rookieworkshopspring.config.rest; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.ResponseErrorHandler; import java.io.IOException; import static org.springframework.http.HttpStatus.Series.CLIENT_ERROR; import static org.springframework.http.HttpStatus.Series.SERVER_ERROR; @Slf4j public class CustomResponseErrorHandler implements ResponseErrorHandler { @Override public boolean hasError(ClientHttpResponse response) throws IOException { return response.getStatusCode().series() == CLIENT_ERROR || response.getStatusCode().series() == SERVER_ERROR; } @Override public void handleError(ClientHttpResponse response) throws IOException { HttpStatus httpStatus = response.getStatusCode(); if (httpStatus.series() == HttpStatus.Series.SERVER_ERROR) { log.info("SERVER_ERROR httpStatus is {}", httpStatus); } else if (httpStatus.series() == HttpStatus.Series.CLIENT_ERROR) { log.info("CLIENT_ERROR httpStatus is {}", httpStatus); if (httpStatus == HttpStatus.NOT_FOUND) { log.info("CLIENT_ERROR NOT_FOUND"); } } } } rju/peethingarchitectureeditor/test/de/peerthing/systembehavioureditor/mode/editor/ConditionTest.java package de.peerthing.systembehavioureditor.mode.editor; import org.jmock.Mock; import org.jmock.MockObjectTestCase; import de.peerthing.systembehavioureditor.model.ICaseArchitecture; import de.peerthing.systembehavioureditor.model.IContentContainer; import de.peerthing.systembehavioureditor.model.INodeType; import de.peerthing.systembehavioureditor.model.IState; import de.peerthing.systembehavioureditor.model.ITask; import de.peerthing.systembehavioureditor.model.editor.CaseSystemBehaviour; import de.peerthing.systembehavioureditor.model.editor.Condition; import de.peerthing.systembehavioureditor.model.editor.Node; import de.peerthing.systembehavioureditor.model.editor.State; import de.peerthing.systembehavioureditor.model.editor.Task; public class ConditionTest extends MockObjectTestCase { Condition con; Condition con2; Condition copycon; Mock defaultCase; private int arg0; IState state; INodeType node; ICaseArchitecture caseArch; private String expression; private String name; private IContentContainer container; private int expected; private ITask task; protected void setUp() throws Exception { super.setUp(); defaultCase = mock(ICaseArchitecture.class); con = new Condition(); caseArch = new CaseSystemBehaviour(); con2 = new Condition((CaseSystemBehaviour)caseArch); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.Condition()' */ public void testCondition() { } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.Condition(CaseSystemBehaviour)' */ public void testConditionCaseSystemBehaviour() { } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.Condition(Condition)' */ public void testConditionCondition() { con2.getDefaultCase().setExpression(expression); copycon = new Condition(con2); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.getCases()' */ public void testGetCases() { con.addCase(caseArch); assertEquals(caseArch, con.getCase(arg0)); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.setName(String)' */ public void testSetName() { con.setName(name); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.getName()' */ public void testGetName() { assertEquals("Condition", con.getName()); con.setName(name); assertEquals(name, con.getName()); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.setDefaultCase(ICaseArchitecture)' */ public void testSetDefaultCase() { con.setDefaultCase((ICaseArchitecture)defaultCase.proxy()); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.getDefaultCase()' */ public void testGetDefaultCase() { con.setDefaultCase((ICaseArchitecture)defaultCase.proxy()); assertEquals((ICaseArchitecture)defaultCase.proxy(), con.getDefaultCase()); assertEquals(((CaseSystemBehaviour)caseArch), con2.getDefaultCase()); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.setContainer(IContentContainer)' */ public void testSetContainer() { con.setContainer(container); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.getContainer()' */ public void testGetContainer() { assertNull(con.getContainer()); con.setContainer(container); assertSame(container, con.getContainer()); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.addCase(ICaseArchitecture)' */ public void testAddCase() { assertEquals(expected,con.addCase(caseArch)); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.getCase(int)' */ public void testGetCase() { expected = con.addCase(caseArch); assertEquals(caseArch, con.getCase(expected)); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.removeCase(ICaseArchitecture)' */ public void testRemoveCase() { expected = con.addCase(caseArch); assertEquals(caseArch, con.getCase(expected)); con.removeCase(caseArch); } /* * Test method for 'de.peerthing.systembehavioureditor.model.editor.Condition.getSystemBehaviour()' */ public void testGetSystemBehaviour() { state = new State(); task = new Task(); node = new Node(); task.setNode(node); state.setTask(task); con.setContainer(state); assertEquals(state.getSystemBehaviour(), con.getSystemBehaviour()); } } package com.kenshine.applicationcontext.demo01; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * @author :kenshine * @date :Created in 2022/1/1 19:55 * @description:spring4.3 的新特性 * @modified By: * @version: $ * */ @Component public class ContextGetDemo03 implements ApplicationContextAware { private ApplicationContext applicationContext; public void show (){ System.out.println(applicationContext.getClass()); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } } fhir/com.b2international.snowowl.fhir.core/src/com/b2international/snowowl/fhir/core/model/RequestEntry.java /* * Copyright 2021 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.fhir.core.model; import java.util.Collection; import javax.validation.constraints.AssertTrue; import com.b2international.snowowl.fhir.core.codesystems.HttpVerb; import com.b2international.snowowl.fhir.core.model.dt.Uri; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; /** * Entry to encapsulate a GET request without a resource in a {@link Bundle} * @since 8.0.0 */ @JsonDeserialize(using = JsonDeserializer.None.class, builder = RequestEntry.Builder.class) public class RequestEntry extends AbstractRequestEntry { protected RequestEntry(final Collection links, final Uri fullUrl, final BatchRequest request) { super(links, fullUrl, request); } @JsonIgnore @AssertTrue(message = "Only GET requests can be without request body") public boolean isGet() { return HttpVerb.GET.getCode().equals(getRequest().getMethod()); } public static Builder builder() { return new Builder(); } @JsonPOJOBuilder(withPrefix = "") public static class Builder extends AbstractRequestEntry.Builder { @Override protected Builder getSelf() { return this; } @Override protected RequestEntry doBuild() { return new RequestEntry(links, fullUrl, request); } } } package com.lukamaletin.cdss.model; import javax.persistence.*; import javax.validation.constraints.NotEmpty; import java.util.HashSet; import java.util.Set; @Entity public class Disease { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @NotEmpty @Column(unique = true) private String name; private int groupNumber; @OneToMany(mappedBy = "disease", cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Set symptoms; public Disease() { } public Disease(@NotEmpty String name, int groupNumber) { this.name = name; this.groupNumber = groupNumber; } public Disease(@NotEmpty String name, Set symptoms) { this.name = name; this.symptoms = symptoms; } public Disease(Disease disease) { this.id = disease.getId(); this.name = disease.getName(); this.groupNumber = disease.getGroupNumber(); this.symptoms = new HashSet<>(); for (SymptomDisease symptomDisease : disease.getSymptoms()) { symptoms.add(new SymptomDisease(symptomDisease)); } } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGroupNumber() { return groupNumber; } public void setGroupNumber(int groupNumber) { this.groupNumber = groupNumber; } public Set getSymptoms() { return symptoms; } public void setSymptoms(Set symptoms) { this.symptoms = symptoms; } } gevoulga/spring-boot-quickfixj /* * Copyright (c) 2020 * * 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 ch.voulgarakis.spring.boot.actuator.quickfixj.endpoint; import ch.voulgarakis.spring.boot.starter.quickfixj.FixSessionInterface; import ch.voulgarakis.spring.boot.starter.quickfixj.exception.QuickFixJException; import ch.voulgarakis.spring.boot.starter.quickfixj.session.InternalFixSessions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import org.springframework.boot.actuate.endpoint.annotation.Selector; import org.springframework.boot.actuate.endpoint.annotation.WriteOperation; import quickfix.ConfigError; import quickfix.Session; import quickfix.SessionID; import quickfix.SessionSettings; import java.util.HashMap; import java.util.Map; import java.util.Properties; import static ch.voulgarakis.spring.boot.starter.quickfixj.session.FixSessionSettings.SESSION_NAME; @Endpoint(id = "quickfixj") public class QuickFixJEndpoint { private static final Logger LOG = LoggerFactory.getLogger(QuickFixJEndpoint.class); private final SessionSettings sessionSettings; private final InternalFixSessions fixSessions; @Autowired public QuickFixJEndpoint(SessionSettings sessionSettings, InternalFixSessions fixSessions) { this.sessionSettings = sessionSettings; this.fixSessions = fixSessions; } @ReadOperation public Map readProperties() { Map reports = new HashMap<>(); fixSessions.getFixSessionIDs().forEach((sessionName, sessionID) -> { try { Properties p = new Properties(); p.putAll(sessionSettings.getDefaultProperties()); p.putAll(sessionSettings.getSessionProperties(sessionID)); p.putIfAbsent(SESSION_NAME, sessionName); reports.put(sessionID.toString(), p); } catch (ConfigError e) { throw new IllegalStateException(e); } }); return reports; } @WriteOperation public void sessionControl(@Selector String sessionName, Action action) { FixSessionInterface fixSession = fixSessions.retrieveSession(sessionName); SessionID sessionId = fixSession.getSessionId(); Session session = Session.lookupSession(sessionId); switch (action) { case CONNECT: LOG.info("Logging on session: " + sessionName); session.logon(); break; case DISCONNECT: LOG.info("Logging off session: " + sessionName); session.logout("Logout request by QuickFixJ endpoint"); break; default: throw new QuickFixJException("Invalid: " + action); } } public enum Action { CONNECT, DISCONNECT; } } package com.com.robert.image.demonew; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; import com.robert.image.compose.demo.R; /** * Created by michael on 14-1-13. */ public class QRCodeMainActivity extends BaseActivity { private ViewPager mViewPager; private ImageSelectPagerAdapter mImageSelectPagerAdapter; private int[] mResList = { R.drawable.hehua, R.drawable.test_123456, R.drawable.test_1234567, R.drawable.test_hsv , R.drawable.test_1, R.drawable.test_2, R.drawable.test_3 }; private EditText mContentET; private View mGradientBt; private View mFaceBt; private View mFilterBt; private int mCurrentResID; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.qrcode_main); enableHomeButton(getString(R.string.app_name)); mActionBar.setDisplayHomeAsUpEnabled(false); mActionBar.setHomeButtonEnabled(false); mViewPager = (ViewPager) findViewById(R.id.pager); mImageSelectPagerAdapter = new ImageSelectPagerAdapter(getApplicationContext(), mResList); mViewPager.setAdapter(mImageSelectPagerAdapter); mContentET = (EditText) findViewById(R.id.qr_content); mGradientBt = findViewById(R.id.gradient); mFaceBt = findViewById(R.id.face); mFilterBt = findViewById(R.id.filter); mContentET.setText(Config.QRCODE_CONTENT); mGradientBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mCurrentResID == 0) { Toast.makeText(getApplicationContext(), "没有选择资源", Toast.LENGTH_LONG).show(); return; } if (TextUtils.isEmpty(mContentET.getText().toString())) { Toast.makeText(getApplicationContext(), "二维码内容不能为空", Toast.LENGTH_LONG).show(); return; } Intent i = new Intent(); i.setClass(getApplicationContext(), GradientActivity.class); i.putExtra(Config.KEY_QRCODE_CONTENT, mContentET.getText().toString()); i.putExtra(Config.KEY_RES_ID, mCurrentResID); startActivity(i); } }); mFaceBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mCurrentResID == 0) { Toast.makeText(getApplicationContext(), "没有选择资源", Toast.LENGTH_LONG).show(); return; } if (TextUtils.isEmpty(mContentET.getText().toString())) { Toast.makeText(getApplicationContext(), "二维码内容不能为空", Toast.LENGTH_LONG).show(); return; } Intent i = new Intent(); i.setClass(getApplicationContext(), FaceCompose1Activity.class); i.putExtra(Config.KEY_QRCODE_CONTENT, mContentET.getText().toString()); i.putExtra(Config.KEY_RES_ID, mCurrentResID); startActivity(i); } }); mFilterBt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mCurrentResID == 0) { Toast.makeText(getApplicationContext(), "没有选择资源", Toast.LENGTH_LONG).show(); return; } if (TextUtils.isEmpty(mContentET.getText().toString())) { Toast.makeText(getApplicationContext(), "二维码内容不能为空", Toast.LENGTH_LONG).show(); return; } Intent i = new Intent(); i.setClass(getApplicationContext(), ImageFilterActivity.class); i.putExtra(Config.KEY_QRCODE_CONTENT, mContentET.getText().toString()); i.putExtra(Config.KEY_RES_ID, mCurrentResID); startActivity(i); } }); } private class ImageSelectPagerAdapter extends PagerAdapter { private Context mContext; private int[] mResList; public ImageSelectPagerAdapter(Context context, int[] resList) { mContext = context; mResList = resList; } @Override public int getCount() { if (mResList != null) { return mResList.length; } return 0; } @Override public boolean isViewFromObject(View view, Object o) { return view == o; } @Override public int getItemPosition(Object object) { return POSITION_NONE; } @Override public Object instantiateItem(ViewGroup container, final int position) { View view = LayoutInflater.from(mContext).inflate(R.layout.gradient_one, null); ImageView imageview = (ImageView) view.findViewById(R.id.image); final View cover = view.findViewById(R.id.cover); final CheckBox cb = (CheckBox) view.findViewById(R.id.choose_cb); cb.setVisibility(View.VISIBLE); if (mResList[position] == mCurrentResID) { cb.setChecked(true); cover.setVisibility(View.VISIBLE); } else { cb.setChecked(false); cover.setVisibility(View.GONE); } imageview.setImageResource(mResList[position]); imageview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mCurrentResID != mResList[position]) { mCurrentResID = mResList[position]; cb.setChecked(true); cover.setVisibility(View.VISIBLE); notifyDataSetChanged(); } else { mCurrentResID = 0; cb.setChecked(false); cover.setVisibility(View.GONE); notifyDataSetChanged(); } } }); container.addView(view); return view; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } } }package edu.saby.msec.infra.async.response; import org.springframework.http.HttpStatus; import org.springframework.util.MultiValueMap; import rx.Observable; import rx.Single; /** * @author * * @param */ public class AsyncResponse { private Observable observable; private Single singleValue; private MultiValueMap headers; private HttpStatus httpStatus; public AsyncResponse(Observable observable, MultiValueMap headers, HttpStatus status) { this.observable = observable; this.headers = headers; this.httpStatus = status; } public AsyncResponse(Single singleValue, MultiValueMap headers, HttpStatus status) { this.singleValue = singleValue; this.headers = headers; this.httpStatus = status; } /** * @return the observable */ public Observable getObservable() { return observable; } /** * @param observable the observable to set */ public void setObservable(Observable observable) { this.observable = observable; } /** * @return the singleValue */ public Single getSingleValue() { return singleValue; } /** * @param singleValue the singleValue to set */ public void setSingleValue(Single singleValue) { this.singleValue = singleValue; } /** * @return the headers */ public MultiValueMap getHeaders() { return headers; } /** * @param headers the headers to set */ public void setHeaders(MultiValueMap headers) { this.headers = headers; } /** * @return the httpStatus */ public HttpStatus getHttpStatus() { return httpStatus; } /** * @param httpStatus the httpStatus to set */ public void setHttpStatus(HttpStatus httpStatus) { this.httpStatus = httpStatus; } } // Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.kernel.services.linking; import android.net.Uri; import host.exp.exponent.Constants; import host.exp.exponent.kernel.KernelConstants; import host.exp.exponent.kernel.KernelProvider; public class LinkingKernelService { public LinkingKernelService() { } public void openURI(Uri uri) { KernelProvider.getInstance().openExperience( new KernelConstants.ExperienceOptions(uri.toString(), uri.toString(), null) ); } public boolean canOpenURI(Uri uri) { String scheme = uri.getScheme(); if ("exp".equals(scheme) || "exps".equals(scheme)) { return true; } if (Constants.SHELL_APP_SCHEME != null && Constants.SHELL_APP_SCHEME.equals(scheme)) { return true; } String host = uri.getHost(); return host != null && ("exp.host".equals(host) || host.endsWith("exp.direct")); } } package cn.qhy.goods.mapper; import cn.qhy.goods.entity.GoodsBrand; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** *

* 品牌表 Mapper 接口 *

* * @author qhy * @since 2021-12-28 */ public interface GoodsBrandMapper extends BaseMapper { } 0 package ru.otus.example.applicationeventsdemo.events; import lombok.SneakyThrows; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; @Component public class PositiveRespondent { @SneakyThrows @EventListener public void onApplicationEvent(HalfAGlassOfWaterEvent halfAGlassOfWaterEvent) { Thread.sleep(100); System.out.println("Позитивно настроенный слушатель"); System.out.println(String.format("- %s", halfAGlassOfWaterEvent.getPayload())); System.out.println("- Ничего. Главное, что он наполовину полон!!!\n\n"); } } IThawk/learnCode package com.kaikeba.controller; import com.kaikeba.annotation.Controller; import com.kaikeba.annotation.RequestMapping; import com.kaikeba.annotation.ResponseBody; import java.util.HashMap; import java.util.Map; /** * 注解方式开发的处理器,谁是真正的处理器??? * 回答1:使用@Controller标记类是处理器(false) * 回答2:使用@Controller标记的类中使用@RequestMapping标记的方法(true) * HandlerMethod才是注解方式开发方式真正的处理器 * 包含:Controller对象和Method对象 * * 1、需要解析RequestMapping注解中的请求URL,建立HandlerMethod与请求的映射关系 * 2、通过HandlerMethod封装的数据,借助于反射技术,完成方法调用 */ @Controller @RequestMapping("user") public class UserController { @RequestMapping("query") @ResponseBody public Map query(Integer id,String name){ Map map = new HashMap<>(); map.put("id",id); map.put("name",name); return map; } @RequestMapping("save") @ResponseBody public String save(){ return "添加成功"; } } Exercices/week14/util/TestMax.java package week14.util; // ----------------------------------------------------------- // Estruturas de Dados 2019/2020 (CC1007) - DCC/FCUP // http://www.dcc.fc.up.pt/~pribeiro/aulas/edados1920/ // ----------------------------------------------------------- // 3 versoes para descobrir o maximo de um intervalo de um array: // (uma iterativa e duas recursivas) // Ultima alteracao: 21/04/2018 // ----------------------------------------------------------- public class TestMax { // Os 3 metodos seguintes recebem array v[] e duas posicoes start e end // e devolvem o maior numero do array entre start e end (inclusive) // -------------------------------------------------------- // Versao iterativa static int maxIt(int v[], int start, int end) { int maxSoFar = v[start]; // Maior ate agora for (int i=start+1; i<=end; i++) // Percorrer intervalo maxSoFar = Math.max(maxSoFar, v[i]); // Actualizar maximo return maxSoFar; } // -------------------------------------------------------- // Versao recursiva 1: dividir em elemento inicial e resto da lista static int maxRec1(int v[], int start, int end) { if (start == end) return v[start]; // caso base (tamanho 1) int max = maxRec1(v, start+1, end); // chamada recursiva (resto da lista) return Math.max(v[start], max); // combinar resultado } // -------------------------------------------------------- // Versao recursiva 2: dividir em metade esquerda e metade direita static int maxRec2(int v[], int start, int end) { if (start == end) return v[start]; // caso base (tamanho 1) int middle = (start + end) / 2; // ponto medio int max1 = maxRec2(v, start, middle); // recursao na metade esquerda int max2 = maxRec2(v, middle+1, end); // recursao na metade direita return Math.max(max1, max2); // combinar resultado } // -------------------------------------------------------- public static void main(String[] args) { int v[] = {1,5,2,8,4,3,7,6}; // Inicializacao de array System.out.println("maxIt: " + maxIt(v, 0, v.length-1)); System.out.println("maxRec1: " + maxRec1(v, 0, v.length-1)); System.out.println("maxRec2: " + maxRec2(v, 0, v.length-1)); } } package com.google.android.gms.internal.ads; final /* synthetic */ class kg0 implements Runnable { /* renamed from: b reason: collision with root package name */ private final hg0 f4822b; /* renamed from: c reason: collision with root package name */ private final yg0 f4823c; /* renamed from: d reason: collision with root package name */ private final vf0 f4824d; kg0(hg0 hg0, yg0 yg0, vf0 vf0) { this.f4822b = hg0; this.f4823c = yg0; this.f4824d = vf0; } public final void run() { this.f4822b.a(this.f4823c, this.f4824d); } } flatlaf-intellij-themes/src/main/java/com/formdev/flatlaf/intellijthemes/FlatAllIJThemes.java /* * Copyright 2020 FormDev Software GmbH * * 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 * * https://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.formdev.flatlaf.intellijthemes; // // DO NOT MODIFY // Generated with com.formdev.flatlaf.demo.intellijthemes.IJThemesClassGenerator // import javax.swing.UIManager.LookAndFeelInfo; /** * @author */ public class FlatAllIJThemes { public static final FlatIJLookAndFeelInfo[] INFOS = { new FlatIJLookAndFeelInfo( "Arc", "com.formdev.flatlaf.intellijthemes.FlatArcIJTheme", false ), new FlatIJLookAndFeelInfo( "Arc - Orange", "com.formdev.flatlaf.intellijthemes.FlatArcOrangeIJTheme", false ), new FlatIJLookAndFeelInfo( "Arc Dark", "com.formdev.flatlaf.intellijthemes.FlatArcDarkIJTheme", true ), new FlatIJLookAndFeelInfo( "Arc Dark - Orange", "com.formdev.flatlaf.intellijthemes.FlatArcDarkOrangeIJTheme", true ), new FlatIJLookAndFeelInfo( "Carbon", "com.formdev.flatlaf.intellijthemes.FlatCarbonIJTheme", true ), new FlatIJLookAndFeelInfo( "Cobalt 2", "com.formdev.flatlaf.intellijthemes.FlatCobalt2IJTheme", true ), new FlatIJLookAndFeelInfo( "Cyan light", "com.formdev.flatlaf.intellijthemes.FlatCyanLightIJTheme", false ), new FlatIJLookAndFeelInfo( "Dark Flat", "com.formdev.flatlaf.intellijthemes.FlatDarkFlatIJTheme", true ), new FlatIJLookAndFeelInfo( "Dark purple", "com.formdev.flatlaf.intellijthemes.FlatDarkPurpleIJTheme", true ), new FlatIJLookAndFeelInfo( "Dracula", "com.formdev.flatlaf.intellijthemes.FlatDraculaIJTheme", true ), new FlatIJLookAndFeelInfo( "Gradianto Dark Fuchsia", "com.formdev.flatlaf.intellijthemes.FlatGradiantoDarkFuchsiaIJTheme", true ), new FlatIJLookAndFeelInfo( "Gradianto Deep Ocean", "com.formdev.flatlaf.intellijthemes.FlatGradiantoDeepOceanIJTheme", true ), new FlatIJLookAndFeelInfo( "Gradianto Midnight Blue", "com.formdev.flatlaf.intellijthemes.FlatGradiantoMidnightBlueIJTheme", true ), new FlatIJLookAndFeelInfo( "Gradianto Nature Green", "com.formdev.flatlaf.intellijthemes.FlatGradiantoNatureGreenIJTheme", true ), new FlatIJLookAndFeelInfo( "Gray", "com.formdev.flatlaf.intellijthemes.FlatGrayIJTheme", false ), new FlatIJLookAndFeelInfo( "Gruvbox Dark Hard", "com.formdev.flatlaf.intellijthemes.FlatGruvboxDarkHardIJTheme", true ), new FlatIJLookAndFeelInfo( "Gruvbox Dark Medium", "com.formdev.flatlaf.intellijthemes.FlatGruvboxDarkMediumIJTheme", true ), new FlatIJLookAndFeelInfo( "Gruvbox Dark Soft", "com.formdev.flatlaf.intellijthemes.FlatGruvboxDarkSoftIJTheme", true ), new FlatIJLookAndFeelInfo( "Hiberbee Dark", "com.formdev.flatlaf.intellijthemes.FlatHiberbeeDarkIJTheme", true ), new FlatIJLookAndFeelInfo( "High contrast", "com.formdev.flatlaf.intellijthemes.FlatHighContrastIJTheme", true ), new FlatIJLookAndFeelInfo( "Light Flat", "com.formdev.flatlaf.intellijthemes.FlatLightFlatIJTheme", false ), new FlatIJLookAndFeelInfo( "Material Design Dark", "com.formdev.flatlaf.intellijthemes.FlatMaterialDesignDarkIJTheme", true ), new FlatIJLookAndFeelInfo( "Monocai", "com.formdev.flatlaf.intellijthemes.FlatMonocaiIJTheme", true ), new FlatIJLookAndFeelInfo( "Nord", "com.formdev.flatlaf.intellijthemes.FlatNordIJTheme", true ), new FlatIJLookAndFeelInfo( "One Dark", "com.formdev.flatlaf.intellijthemes.FlatOneDarkIJTheme", true ), new FlatIJLookAndFeelInfo( "Solarized Dark", "com.formdev.flatlaf.intellijthemes.FlatSolarizedDarkIJTheme", true ), new FlatIJLookAndFeelInfo( "Solarized Light", "com.formdev.flatlaf.intellijthemes.FlatSolarizedLightIJTheme", false ), new FlatIJLookAndFeelInfo( "Spacegray", "com.formdev.flatlaf.intellijthemes.FlatSpacegrayIJTheme", true ), new FlatIJLookAndFeelInfo( "Vuesion", "com.formdev.flatlaf.intellijthemes.FlatVuesionIJTheme", true ), new FlatIJLookAndFeelInfo( "Arc Dark (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatArcDarkIJTheme", true ), new FlatIJLookAndFeelInfo( "Arc Dark Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatArcDarkContrastIJTheme", true ), new FlatIJLookAndFeelInfo( "Atom One Dark (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatAtomOneDarkIJTheme", true ), new FlatIJLookAndFeelInfo( "Atom One Dark Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatAtomOneDarkContrastIJTheme", true ), new FlatIJLookAndFeelInfo( "Atom One Light (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatAtomOneLightIJTheme", false ), new FlatIJLookAndFeelInfo( "Atom One Light Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatAtomOneLightContrastIJTheme", false ), new FlatIJLookAndFeelInfo( "Dracula (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatDraculaIJTheme", true ), new FlatIJLookAndFeelInfo( "Dracula Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatDraculaContrastIJTheme", true ), new FlatIJLookAndFeelInfo( "GitHub (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatGitHubIJTheme", false ), new FlatIJLookAndFeelInfo( "GitHub Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatGitHubContrastIJTheme", false ), new FlatIJLookAndFeelInfo( "Light Owl (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatLightOwlIJTheme", false ), new FlatIJLookAndFeelInfo( "Light Owl Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatLightOwlContrastIJTheme", false ), new FlatIJLookAndFeelInfo( "Material Darker (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMaterialDarkerIJTheme", true ), new FlatIJLookAndFeelInfo( "Material Darker Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMaterialDarkerContrastIJTheme", true ), new FlatIJLookAndFeelInfo( "Material Deep Ocean (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMaterialDeepOceanIJTheme", true ), new FlatIJLookAndFeelInfo( "Material Deep Ocean Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMaterialDeepOceanContrastIJTheme", true ), new FlatIJLookAndFeelInfo( "Material Lighter (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMaterialLighterIJTheme", false ), new FlatIJLookAndFeelInfo( "Material Lighter Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMaterialLighterContrastIJTheme", false ), new FlatIJLookAndFeelInfo( "Material Oceanic (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMaterialOceanicIJTheme", true ), new FlatIJLookAndFeelInfo( "Material Oceanic Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMaterialOceanicContrastIJTheme", true ), new FlatIJLookAndFeelInfo( "Material Palenight (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMaterialPalenightIJTheme", true ), new FlatIJLookAndFeelInfo( "Material Palenight Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMaterialPalenightContrastIJTheme", true ), new FlatIJLookAndFeelInfo( "Monokai Pro (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMonokaiProIJTheme", true ), new FlatIJLookAndFeelInfo( "Monokai Pro Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatMonokaiProContrastIJTheme", true ), new FlatIJLookAndFeelInfo( "Night Owl (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatNightOwlIJTheme", true ), new FlatIJLookAndFeelInfo( "Night Owl Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatNightOwlContrastIJTheme", true ), new FlatIJLookAndFeelInfo( "Solarized Dark (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatSolarizedDarkIJTheme", true ), new FlatIJLookAndFeelInfo( "Solarized Dark Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatSolarizedDarkContrastIJTheme", true ), new FlatIJLookAndFeelInfo( "Solarized Light (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatSolarizedLightIJTheme", false ), new FlatIJLookAndFeelInfo( "Solarized Light Contrast (Material)", "com.formdev.flatlaf.intellijthemes.materialthemeuilite.FlatSolarizedLightContrastIJTheme", false ), }; //---- class FlatIJLookAndFeelInfo ---------------------------------------- public static class FlatIJLookAndFeelInfo extends LookAndFeelInfo { private final boolean dark; public FlatIJLookAndFeelInfo( String name, String className, boolean dark ) { super( name, className ); this.dark = dark; } public boolean isDark() { return dark; } } } /** * Copyright (C) 2015 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 namtran.cleanarchitechturesample.mapper; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import namtran.cleanarchitechturesample.model.SoccerSeasonModel; import namtran.domain.entity.SoccerSeasonEntity; /** * Mapper class used to transform {@link SoccerSeasonEntity} (in the domain layer) * to {@link SoccerSeasonModel} in the * presentation layer. */ public class SoccerSeasonModelDataMapper { @Inject public SoccerSeasonModelDataMapper() {} /** * Transform a {@link SoccerSeasonEntity} into an {@link SoccerSeasonModel}. * * @param season Object to be transformed. * @return {@link SoccerSeasonModel}. */ public SoccerSeasonModel transform(SoccerSeasonEntity season) { if (season == null) { throw new IllegalArgumentException("Cannot transform a null value"); } final SoccerSeasonModel seasonModel = new SoccerSeasonModel(); seasonModel.id = season.id; seasonModel.caption = season.caption; seasonModel.league = season.league; seasonModel.year = season.year; seasonModel.currentMatchday = season.currentMatchday; seasonModel.numberOfMatchdays = season.numberOfMatchdays; seasonModel.numberOfTeams = season.numberOfTeams; seasonModel.numberOfGames = season.numberOfGames; seasonModel.lastUpdated = season.lastUpdated; return seasonModel; } /** * Transform a Collection of {@link SoccerSeasonEntity} into a Collection of {@link SoccerSeasonModel}. * * @param seasonCollection Objects to be transformed. * @return List of {@link SoccerSeasonModel}. */ public List transform(List seasonCollection) { List seasonModelCollection; if (seasonCollection != null && !seasonCollection.isEmpty()) { seasonModelCollection = new ArrayList<>(); for (SoccerSeasonEntity user : seasonCollection) { seasonModelCollection.add(transform(user)); } } else { seasonModelCollection = new ArrayList<>(); } return seasonModelCollection; } } /** * */ package com.vimukti.accounter.web.client.uibinder.setup; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.RadioButton; import com.google.gwt.user.client.ui.Widget; import com.vimukti.accounter.web.client.ui.Accounter; /** * @author Administrator * */ public class SetupTrackBillsAndTimePage extends AbstractSetupPage { private static SetupTrackBillsAndTimePageUiBinder uiBinder = GWT .create(SetupTrackBillsAndTimePageUiBinder.class); @UiField FlowPanel viewPanel; @UiField FlowPanel trackingBillsPanel; @UiField FlowPanel managing; @UiField Label trackOfBillsText; @UiField Label trackOfBillsList; @UiField Label trackTimeText; @UiField RadioButton managingYes; @UiField // RadioButton trackingTimeYes; // @UiField RadioButton managingNo; @UiField // RadioButton trackingNo; // @UiField Label managingInfo; @UiField Label trackingTimeDes; @UiField Label headerLabel, managingList1, managingList2, managingList3; @UiField Label track_time_head; interface SetupTrackBillsAndTimePageUiBinder extends UiBinder { } /** * Because this class has a default constructor, it can be used as a binder * template. In other words, it can be used in other *.ui.xml files as * follows: * Hello! Note that * depending on the widget that is used, it may be necessary to implement * HasHTML instead of HasText. */ public SetupTrackBillsAndTimePage() { initWidget(uiBinder.createAndBindUi(this)); createControls(); } @Override protected void createControls() { headerLabel.setText(messages.managingBills()); // trackOfBillsText.setHTML(messages.doyouwantTrackTime()); // trackOfBillsList.setHTML(accounterMessages.trackTimeList()); managingList1.setText(messages.managingList1()); managingList2.setText(messages.managingList2()); managingList3.setText(messages.managingList3()); // trackTimeText.setHTML(messages.doyouwantTrackBills()); managingYes.setText(messages.yes()); // trackingTimeYes.setText(messages.yes()); managingNo.setText(messages.no()); // trackingNo.setText(messages.no()); // trackingTimeDes.setHTML(messages.timetrackingdescription()); managingInfo.setText(messages.billstrackingdescription()); // track_time_head.setText(accounterMessages.trackingtimehead()); } @Override public void onLoad() { if (preferences.isKeepTrackofBills()) { managingYes.setValue(true); } else { managingNo.setValue(true); } // if (preferences.isDoYouKeepTrackOfTime()) { // trackingTimeYes.setValue(true); // } else { // trackingNo.setValue(true); // } } @Override public void onSave() { if (managingYes.getValue()) { preferences.setKeepTrackofBills(true); } else { preferences.setKeepTrackofBills(false); } // if (trackingTimeYes.getValue()) { // preferences.setDoYouKeepTrackOfTime(true); // } else { // preferences.setDoYouKeepTrackOfTime(false); // } } @Override protected boolean validate() { if ((!(managingYes.getValue() || managingNo.getValue())) /* && (!(trackingTimeYes.getValue() || trackingNo.getValue()) */) { Accounter.showError(messages.pleaseEnter(messages.details())); return false; } else if (!(managingYes.getValue() || managingNo.getValue())) { Accounter.showMessage(messages.managingBills()); return false; /* * } else if (!(trackingTimeYes.getValue() || * trackingNo.getValue())) { * Accounter.showMessage(messages.doyouwantTrackBills()); return * false; */ } else { return true; } } @Override public String getViewName() { return messages.setBillTracking(); } } johan12345/AnyMaps /* * Copyright (c) 2015 / Moovel GmbH * * All rights reserved */ package com.car2go.maps.mapbox.adapter; import com.car2go.maps.UiSettings; /** * Adapts Google Map UiSettings to AnyMap UiSettings */ public class UiSettingsAdapter implements UiSettings { private final com.mapbox.mapboxsdk.maps.UiSettings uiSettings; public UiSettingsAdapter(com.mapbox.mapboxsdk.maps.UiSettings uiSettings) { this.uiSettings = uiSettings; } @Override public void setAllGesturesEnabled(boolean enabled) { uiSettings.setAllGesturesEnabled(enabled); } @Override public void setTiltGesturesEnabled(boolean enabled) { uiSettings.setTiltGesturesEnabled(enabled); } @Override public void setMyLocationButtonEnabled(boolean enabled) { // do nothing } @Override public void setMapToolbarEnabled(boolean enabled) { // do nothing } @Override public void setIndoorLevelPickerEnabled(boolean enabled) { // do nothing } } src/de/inkvine/dota2stats/domain/matchdetail/MatchDetail.java package de.inkvine.dota2stats.domain.matchdetail; import java.util.List; import de.inkvine.dota2stats.domain.GameMode; import de.inkvine.dota2stats.domain.MatchOverview; public interface MatchDetail { public boolean didRadianWin(); public int getDurationOfMatch(); public MatchOverview getMatchOverview(); public int getFirstBloodTime(); public int getHumanPlayer(); public int getLeagueId(); public int getPositiveVotes(); public int getNegativeVotes(); public GameMode getGameMode(); public List getPlayers(); } 0 /* * Copyright 2002-2010 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.constretto.internal; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * Helper class that encapsulates the specification of a method parameter, i.e. * a Method or Constructor plus a parameter index and a nested type index for * a declared generic type. Useful as a specification object to pass along. * * @author * @author * @author * @see GenericCollectionTypeResolver * @since 2.0 */ public class MethodParameter { private Method method; private Constructor constructor; private final int parameterIndex; private Class parameterType; private Annotation[] parameterAnnotations; private int nestingLevel = 1; /** * Map from Integer level to Integer type index */ private Map typeIndexesPerLevel; Map typeVariableMap; /** * Create a new MethodParameter for the given method, with nesting level 1. * * @param method the Method to specify a parameter for * @param parameterIndex the index of the parameter */ public MethodParameter(Method method, int parameterIndex) { this(method, parameterIndex, 1); } /** * Create a new MethodParameter for the given method. * * @param method the Method to specify a parameter for * @param parameterIndex the index of the parameter * (-1 for the method return type; 0 for the first method parameter, * 1 for the second method parameter, etc) * @param nestingLevel the nesting level of the target type * (typically 1; e.g. in case of a List of Lists, 1 would indicate the * nested List, whereas 2 would indicate the element of the nested List) */ public MethodParameter(Method method, int parameterIndex, int nestingLevel) { this.method = method; this.parameterIndex = parameterIndex; this.nestingLevel = nestingLevel; } /** * Create a new MethodParameter for the given constructor, with nesting level 1. * * @param constructor the Constructor to specify a parameter for * @param parameterIndex the index of the parameter */ public MethodParameter(Constructor constructor, int parameterIndex) { this(constructor, parameterIndex, 1); } /** * Create a new MethodParameter for the given constructor. * * @param constructor the Constructor to specify a parameter for * @param parameterIndex the index of the parameter * @param nestingLevel the nesting level of the target type * (typically 1; e.g. in case of a List of Lists, 1 would indicate the * nested List, whereas 2 would indicate the element of the nested List) */ public MethodParameter(Constructor constructor, int parameterIndex, int nestingLevel) { if (constructor == null) { throw new NullPointerException("Constructor must not be null"); } this.constructor = constructor; this.parameterIndex = parameterIndex; this.nestingLevel = nestingLevel; } /** * Return the wrapped Method, if any. *

Note: Either Method or Constructor is available. * * @return the Method, or null if none */ public Method getMethod() { return this.method; } /** * Return the wrapped Constructor, if any. *

Note: Either Method or Constructor is available. * * @return the Constructor, or null if none */ public Constructor getConstructor() { return this.constructor; } /** * Return the class that declares the underlying Method or Constructor. */ public Class getDeclaringClass() { return (this.method != null ? this.method.getDeclaringClass() : this.constructor.getDeclaringClass()); } /** * Return the index of the method/constructor parameter. * * @return the parameter index (never negative) */ public int getParameterIndex() { return this.parameterIndex; } /** * Set a resolved (generic) parameter type. */ void setParameterType(Class parameterType) { this.parameterType = parameterType; } /** * Return the type of the method/constructor parameter. * * @return the parameter type (never null) */ public Class getParameterType() { if (this.parameterType == null) { if (this.parameterIndex < 0) { this.parameterType = (this.method != null ? this.method.getReturnType() : null); } else { this.parameterType = (this.method != null ? this.method.getParameterTypes()[this.parameterIndex] : this.constructor.getParameterTypes()[this.parameterIndex]); } } return this.parameterType; } /** * Return the annotations associated with the target method/constructor itself. */ public Annotation[] getMethodAnnotations() { return (this.method != null ? this.method.getAnnotations() : this.constructor.getAnnotations()); } /** * Return the annotations associated with the specific method/constructor parameter. */ public Annotation[] getParameterAnnotations() { if (this.parameterAnnotations == null) { Annotation[][] annotationArray = (this.method != null ? this.method.getParameterAnnotations() : this.constructor.getParameterAnnotations()); if (this.parameterIndex >= 0 && this.parameterIndex < annotationArray.length) { this.parameterAnnotations = annotationArray[this.parameterIndex]; } else { this.parameterAnnotations = new Annotation[0]; } } return (this.parameterAnnotations == null ? null : Arrays.copyOf(this.parameterAnnotations, this.parameterAnnotations.length)); } /** * Return the nesting level of the target type * (typically 1; e.g. in case of a List of Lists, 1 would indicate the * nested List, whereas 2 would indicate the element of the nested List). */ public int getNestingLevel() { return this.nestingLevel; } /** * Return the type index for the specified nesting level. * * @param nestingLevel the nesting level to check * @return the corresponding type index, or null * if none specified (indicating the default type index) */ public Integer getTypeIndexForLevel(int nestingLevel) { return getTypeIndexesPerLevel().get(nestingLevel); } /** * Obtain the (lazily constructed) type-indexes-per-level Map. */ private Map getTypeIndexesPerLevel() { if (this.typeIndexesPerLevel == null) { this.typeIndexesPerLevel = new HashMap(4); } return this.typeIndexesPerLevel; } } QubedQ3/Q3-BotQ3-Bot/src/com/q3/qubedBot/streamAPIs/hitBox/HitBox_Stream.java package com.q3.qubedBot.streamAPIs.hitBox; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; public class HitBox_Stream { String username; Boolean online; String title; String game; String url; /** * Method used to load JsonObjects from a Json String retrieved by the HitBox_Api.class. * @param jObject */ public void load(JsonObject jObject) { JsonArray livestream = jObject.getAsJsonArray("livestream"); JsonElement media = livestream.get(0); setUser(media.getAsJsonObject().get("media_user_name").getAsString()); setGame(media.getAsJsonObject().get("category_seo_key").getAsString()); setTitle(media.getAsJsonObject().get("media_status").getAsString()); setUrl(String.format("http://hitbox.tv/"+media.getAsJsonObject().get("media_user_name").getAsString())); } public boolean getIsOnline(){return this.online; } public void setOnline(boolean online) { this.online = online; } public String getUser() { return this.username; } public void setUser(String username) { this.username = username; } public String getTitle() { return this.title; } public void setTitle(String title) { this.title = title; } public String getGame() { return this.game; } public void setGame(String game) { this.game = game; } public String getUrl() { return this.url; } public void setUrl(String url) { this.url = url; } } package com.gc.nfc.common; import java.util.Map; import com.gc.nfc.ui.BaseActivity.HttpRequestType; import android.content.Context; public class NetRequestConstant { public Context context; public String requestUrl; public Map body; public Map params; public boolean isBodyJsonArray = false; private HttpRequestType type; public HttpRequestType getType() { return type; } public void setType(HttpRequestType type) { this.type = type; } public void setBody(Map body){ this.body = body; } public void setParams(Map params){ this.params = params; } } stbly/gemp-swccg-public package com.gempukku.swccgo.cards.set12.dark; import com.gempukku.swccgo.cards.AbstractAlien; import com.gempukku.swccgo.cards.GameConditions; import com.gempukku.swccgo.cards.effects.AddBattleDestinyEffect; import com.gempukku.swccgo.cards.effects.usage.OncePerBattleEffect; import com.gempukku.swccgo.cards.effects.usage.OncePerTurnEffect; import com.gempukku.swccgo.common.*; import com.gempukku.swccgo.filters.Filters; import com.gempukku.swccgo.game.PhysicalCard; import com.gempukku.swccgo.game.SwccgGame; import com.gempukku.swccgo.game.state.GameState; import com.gempukku.swccgo.logic.GameUtils; import com.gempukku.swccgo.logic.TriggerConditions; import com.gempukku.swccgo.logic.actions.OptionalGameTextTriggerAction; import com.gempukku.swccgo.logic.actions.TopLevelGameTextAction; import com.gempukku.swccgo.logic.effects.DrawDestinyEffect; import com.gempukku.swccgo.logic.effects.UseForceEffect; import com.gempukku.swccgo.logic.effects.choose.TakeCardIntoHandFromUsedPileEffect; import com.gempukku.swccgo.logic.effects.choose.TakeDestinyCardIntoHandEffect; import com.gempukku.swccgo.logic.modifiers.AddsPowerToPilotedBySelfModifier; import com.gempukku.swccgo.logic.modifiers.Modifier; import com.gempukku.swccgo.logic.timing.EffectResult; import com.gempukku.swccgo.logic.timing.results.DestinyDrawnResult; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Set: Coruscant * Type: Character * Subtype: Alien * Title: */ public class Card12_125 extends AbstractAlien { public Card12_125() { super(Side.DARK, 3, 2, 2, 2, 4, "", Uniqueness.UNIQUE); setLore("Corellian gambler with an addiction to Podrace betting. Has lost most of his belongings to Gardulla. Still operates as a smuggler of black market weaponry."); setGameText("Adds 2 to power of anything he pilots. Once per turn, may take a just drawn race destiny into hand. Once during a battle Yade is in at a system may use 2 Force to draw destiny. If destiny is odd, add one battle destiny; if even, take destiny into hand."); addIcons(Icon.CORUSCANT, Icon.EPISODE_I, Icon.PILOT, Icon.WARRIOR); addKeywords(Keyword.GAMBLER, Keyword.SMUGGLER); setSpecies(Species.CORELLIAN); } @Override protected List getGameTextWhileActiveInPlayModifiers(SwccgGame game, final PhysicalCard self) { List modifiers = new LinkedList(); modifiers.add(new AddsPowerToPilotedBySelfModifier(self, 2)); return modifiers; } @Override protected List getGameTextOptionalAfterTriggers(final String playerId, SwccgGame game, final EffectResult effectResult, final PhysicalCard self, int gameTextSourceCardId) { GameTextActionId gameTextActionId = GameTextActionId.OTHER_CARD_ACTION_1; // Check condition(s) if (TriggerConditions.isRaceDestinyJustDrawnBy(game, effectResult, playerId) && GameConditions.isOncePerTurn(game, self, playerId, gameTextSourceCardId, gameTextActionId) && GameConditions.canTakeDestinyCardIntoHand(game, playerId)) { final OptionalGameTextTriggerAction action = new OptionalGameTextTriggerAction(self, gameTextSourceCardId, gameTextActionId); action.setText("Take destiny card into hand"); action.setActionMsg("Take just drawn destiny card, " + GameUtils.getCardLink(((DestinyDrawnResult) effectResult).getCard()) + ", into hand"); // Update usage limit(s) action.appendUsage( new OncePerTurnEffect(action)); // Perform result(s) action.appendEffect( new TakeDestinyCardIntoHandEffect(action)); return Collections.singletonList(action); } return null; } @Override protected List getGameTextTopLevelActions(final String playerId, final SwccgGame game, final PhysicalCard self, final int gameTextSourceCardId) { GameTextActionId gameTextActionId = GameTextActionId.OTHER_CARD_ACTION_2; // Check condition(s) if (GameConditions.isOncePerBattle(game, self, playerId, gameTextSourceCardId, gameTextActionId) && GameConditions.isInBattleAt(game, self, Filters.system) && GameConditions.canUseForce(game, playerId, 2) && GameConditions.hasReserveDeck(game, playerId)) { final TopLevelGameTextAction action = new TopLevelGameTextAction(self, gameTextSourceCardId, gameTextActionId); action.setText("Draw destiny"); // Update usage limit(s) action.appendUsage( new OncePerBattleEffect(action)); // Pay cost(s) action.appendCost( new UseForceEffect(action, playerId, 2)); // Perform result(s) action.appendEffect( new DrawDestinyEffect(action, playerId) { @Override protected void destinyDraws(SwccgGame game, List destinyCardDraws, List destinyDrawValues, Float totalDestiny) { GameState gameState = game.getGameState(); if (totalDestiny == null) { gameState.sendMessage("Result: Failed due to failed destiny draw"); return; } if (totalDestiny % 2 == 1) { gameState.sendMessage("Result: Destiny is odd"); if (GameConditions.canAddBattleDestinyDraws(game, self)) { action.appendEffect( new AddBattleDestinyEffect(action, 1, playerId)); } } else if (totalDestiny % 2 == 0) { gameState.sendMessage("Result: Destiny is even"); PhysicalCard destinyCard = destinyCardDraws.get(0); if (destinyCard != null && Filters.inUsedPile(playerId).accepts(game, destinyCard)) { action.appendEffect( new TakeCardIntoHandFromUsedPileEffect(action, playerId, destinyCard, false)); } } else { gameState.sendMessage("Result: No result"); } } } ); return Collections.singletonList(action); } return null; } } 0 /* * CPAchecker is a tool for configurable software verification. * This file is part of CPAchecker. * * Copyright (C) 2007-2014 * 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. * * * CPAchecker web page: * http://cpachecker.sosy-lab.org */ package org.sosy_lab.cpachecker.cfa.blocks.builder; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.sosy_lab.cpachecker.cfa.blocks.Block; import org.sosy_lab.cpachecker.cfa.blocks.BlockPartitioning; import org.sosy_lab.cpachecker.cfa.blocks.ReferencedVariable; import org.sosy_lab.cpachecker.cfa.model.CFAEdge; import org.sosy_lab.cpachecker.cfa.model.CFANode; import org.sosy_lab.cpachecker.cfa.model.FunctionEntryNode; import org.sosy_lab.cpachecker.cfa.model.FunctionExitNode; import org.sosy_lab.cpachecker.cfa.model.c.CFunctionCallEdge; import org.sosy_lab.cpachecker.util.CFATraversal; /** * Helper class can build a BlockPartitioning from a partition of a program's CFA into blocks. */ public class BlockPartitioningBuilder { private static final CFATraversal TRAVERSE_CFA_INSIDE_FUNCTION = CFATraversal.dfs().ignoreFunctionCalls(); private final Map> referencedVariablesMap = new HashMap<>(); private final Map> callNodesMap = new HashMap<>(); private final Map> returnNodesMap = new HashMap<>(); private final Map> innerFunctionCallsMap = new HashMap<>(); private final Map> blockNodesMap = new HashMap<>(); public BlockPartitioningBuilder() {} public BlockPartitioning build(CFANode mainFunction) { //fixpoint iteration to take inner function calls into account for referencedVariables and callNodesMap boolean changed = true; outer: while (changed) { changed = false; for (CFANode node : referencedVariablesMap.keySet()) { for (CFANode calledFun : innerFunctionCallsMap.get(node)) { Set functionVars = referencedVariablesMap.get(calledFun); Set functionBody = blockNodesMap.get(calledFun); if (functionVars == null || functionBody == null) { assert functionVars == null && functionBody == null; //compute it only the fly functionBody = TRAVERSE_CFA_INSIDE_FUNCTION.collectNodesReachableFrom(calledFun); functionVars = collectReferencedVariables(functionBody); //and save it blockNodesMap.put(calledFun, functionBody); referencedVariablesMap.put(calledFun, functionVars); innerFunctionCallsMap.put(calledFun, collectInnerFunctionCalls(functionBody)); changed = true; continue outer; } if (referencedVariablesMap.get(node).addAll(functionVars)) { changed = true; } if (blockNodesMap.get(node).addAll(functionBody)) { changed = true; } } } } //now we can create the Blocks for the BlockPartitioning Collection blocks = new ArrayList<>(returnNodesMap.keySet().size()); for (CFANode key : returnNodesMap.keySet()) { blocks.add(new Block(referencedVariablesMap.get(key), callNodesMap.get(key), returnNodesMap.get(key), blockNodesMap.get(key))); } return new BlockPartitioning(blocks, mainFunction); } /** * @param nodes Nodes from which Block should be created; if the set of nodes contains inner function calls, the called function body should NOT be included */ public void addBlock(Set nodes, CFANode mainFunction) { Set referencedVariables = collectReferencedVariables(nodes); Set callNodes = collectCallNodes(nodes, mainFunction); Set returnNodes = collectReturnNodes(nodes, mainFunction); Set innerFunctionCalls = collectInnerFunctionCalls(nodes); CFANode registerNode = null; for (CFANode node : callNodes) { registerNode = node; if (node instanceof FunctionEntryNode) { break; } } referencedVariablesMap.put(registerNode, referencedVariables); callNodesMap.put(registerNode, callNodes); returnNodesMap.put(registerNode, returnNodes); innerFunctionCallsMap.put(registerNode, innerFunctionCalls); blockNodesMap.put(registerNode, nodes); } private Set collectInnerFunctionCalls(Set pNodes) { Set result = new HashSet<>(); for (CFANode node : pNodes) { for (int i = 0; i < node.getNumLeavingEdges(); i++) { CFAEdge e = node.getLeavingEdge(i); if (e instanceof CFunctionCallEdge) { result.add(((CFunctionCallEdge)e).getSuccessor()); } } } return result; } private Set collectCallNodes(Set pNodes, CFANode mainFunction) { Set result = new HashSet<>(); for (CFANode node : pNodes) { if (node instanceof FunctionEntryNode && node.getFunctionName().equalsIgnoreCase(mainFunction.getFunctionName())) { //main definition is always a call edge result.add(node); continue; } if (node.getEnteringSummaryEdge() != null) { CFANode pred = node.getEnteringSummaryEdge().getPredecessor(); if (!pNodes.contains(pred)) { result.add(node); } //ignore inner function calls continue; } for (int i = 0; i < node.getNumEnteringEdges(); i++) { CFANode pred = node.getEnteringEdge(i).getPredecessor(); if (!pNodes.contains(pred)) { //entering edge from "outside" of the given set of nodes //-> this is a call-node result.add(node); } } } return result; } private Set collectReturnNodes(Set pNodes, CFANode mainFunction) { Set result = new HashSet<>(); for (CFANode node : pNodes) { if (node instanceof FunctionExitNode && node.getFunctionName().equalsIgnoreCase(mainFunction.getFunctionName())) { //main exit nodes are always return nodes result.add(node); continue; } for (int i = 0; i < node.getNumLeavingEdges(); i++) { CFANode succ = node.getLeavingEdge(i).getSuccessor(); if (!pNodes.contains(succ)) { //leaving edge from inside of the given set of nodes to outside //-> this is a either return-node or a function call if (!(node.getLeavingEdge(i) instanceof CFunctionCallEdge)) { //-> only add if its not a function call result.add(node); } else { //otherwise check if the summary edge is inside of the block CFANode sumSucc = ((CFunctionCallEdge)node.getLeavingEdge(i)).getSummaryEdge().getSuccessor(); if (!pNodes.contains(sumSucc)) { //summary edge successor not in nodes set; this is a leaving edge //add entering nodes for (int j = 0; j < sumSucc.getNumEnteringEdges(); j++) { result.add(sumSucc.getEnteringEdge(j).getPredecessor()); } } } } } } return result; } private Set collectReferencedVariables(Set nodes) { return (new ReferencedVariablesCollector(nodes)).getVars(); } } /** * Copyright 2005-2015 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * 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.kuali.rice.krad.uif.control; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.kuali.rice.kim.api.KimConstants; import org.kuali.rice.kim.api.identity.Person; import org.kuali.rice.kim.api.identity.PersonService; import org.kuali.rice.kim.api.identity.principal.Principal; import org.kuali.rice.kim.api.services.KimApiServiceLocator; import org.kuali.rice.krad.datadictionary.parse.BeanTag; import org.kuali.rice.krad.datadictionary.parse.BeanTagAttribute; import org.kuali.rice.krad.uif.UifConstants; import org.kuali.rice.krad.uif.component.MethodInvokerConfig; import org.kuali.rice.krad.uif.field.AttributeQuery; import org.kuali.rice.krad.uif.field.InputField; import org.kuali.rice.krad.uif.lifecycle.ViewLifecycle; import org.kuali.rice.krad.uif.util.ComponentFactory; import org.kuali.rice.krad.uif.util.LifecycleElement; import org.kuali.rice.krad.uif.util.ScriptUtils; import org.kuali.rice.krad.uif.widget.QuickFinder; /** * Represents a user control, which is a special control to handle the input of a Person. * * @author () */ @BeanTag(name = "kimPersonControl", parent = "Uif-KimPersonControl") public class UserControl extends TextControlBase implements FilterableLookupCriteriaControl { private static final long serialVersionUID = 7468340793076585869L; private String principalIdPropertyName; private String personNamePropertyName; private String personObjectPropertyName; public UserControl() { super(); } /** * {@inheritDoc} */ @Override public void performApplyModel(Object model, LifecycleElement parent) { super.performApplyModel(model, parent); if (!(parent instanceof InputField)) { return; } InputField field = (InputField) parent; field.getAdditionalHiddenPropertyNames().add(principalIdPropertyName); if (isRender() && !isHidden() && !Boolean.TRUE.equals(getReadOnly())) { ViewLifecycle.getViewPostMetadata().addAccessibleBindingPath(principalIdPropertyName); } if (!Boolean.TRUE.equals(field.getReadOnly())) { // add information fields if (StringUtils.isNotBlank(personNamePropertyName)) { field.getPropertyNamesForAdditionalDisplay().add(personNamePropertyName); } else { field.getPropertyNamesForAdditionalDisplay().add( personObjectPropertyName + "." + KimConstants.AttributeConstants.NAME); } // setup script to clear id field when name is modified String idPropertyPath = field.getBindingInfo().getPropertyAdjustedBindingPath(principalIdPropertyName); String onChangeScript = UifConstants.JsFunctions.SET_VALUE + "('" + ScriptUtils.escapeName(idPropertyPath) + "','');"; if (StringUtils.isNotBlank(getOnChangeScript())) { onChangeScript = getOnChangeScript() + onChangeScript; } setOnChangeScript(onChangeScript); } if (Boolean.TRUE.equals(field.getReadOnly()) && StringUtils.isBlank(field.getReadOnlyDisplaySuffixPropertyName())) { if (StringUtils.isNotBlank(personNamePropertyName)) { field.setReadOnlyDisplaySuffixPropertyName(personNamePropertyName); } else { field.setReadOnlyDisplaySuffixPropertyName( personObjectPropertyName + "." + KimConstants.AttributeConstants.NAME); } } // setup field query for displaying name AttributeQuery attributeQuery = new AttributeQuery(); MethodInvokerConfig methodInvokerConfig = new MethodInvokerConfig(); PersonService personService = KimApiServiceLocator.getPersonService(); methodInvokerConfig.setTargetObject(personService); attributeQuery.setQueryMethodInvokerConfig(methodInvokerConfig); attributeQuery.setQueryMethodToCall("getPersonByPrincipalName"); attributeQuery.getQueryMethodArgumentFieldList().add(field.getPropertyName()); attributeQuery.getReturnFieldMapping().put(KimConstants.AttributeConstants.PRINCIPAL_ID, principalIdPropertyName); if (StringUtils.isNotBlank(personNamePropertyName)) { attributeQuery.getReturnFieldMapping().put(KimConstants.AttributeConstants.NAME, personNamePropertyName); } else { attributeQuery.getReturnFieldMapping().put(KimConstants.AttributeConstants.NAME, personObjectPropertyName + "." + KimConstants.AttributeConstants.NAME); } field.setAttributeQuery(attributeQuery); buildUserQuickfinder(model, field); } /** * {@inheritDoc} */ @Override public Map filterSearchCriteria(String propertyName, Map searchCriteria, FilterableLookupCriteriaControlPostData postData) { Map filteredSearchCriteria = new HashMap(searchCriteria); UserControlPostData userControlPostData = (UserControlPostData) postData; // check valid principalName // ToDo: move the principalId check and setting to the validation stage. At that point the personName should // be set as well or an error be displayed to the user that the principalName is invalid. String principalName = searchCriteria.get(propertyName); if (StringUtils.isNotBlank(principalName)) { if (!StringUtils.contains(principalName, "*")) { Principal principal = KimApiServiceLocator.getIdentityService().getPrincipalByPrincipalName( principalName); if (principal == null) { return null; } else { filteredSearchCriteria.put(userControlPostData.getPrincipalIdPropertyName(), principal.getPrincipalId()); } } else { List people = KimApiServiceLocator.getPersonService().findPeople(Collections.singletonMap( KimConstants.AttributeConstants.PRINCIPAL_NAME, principalName)); if (people != null && people.size() == 0) { return null; } } } if (!StringUtils.contains(principalName, "*")) { // filter filteredSearchCriteria.remove(propertyName); filteredSearchCriteria.remove(userControlPostData.getPersonNamePropertyName()); } return filteredSearchCriteria; } /** * Configures the field's quickfinder for a user lookup * * @param model object containing the view's data * @param field field instance the quickfinder should be associated with */ protected void buildUserQuickfinder(Object model, InputField field) { QuickFinder quickFinder = field.getQuickfinder(); // don't build quickfinder if explicitly turned off if (!field.isEnableAutoQuickfinder()) { return; } if (quickFinder == null) { quickFinder = ComponentFactory.getQuickFinder(); field.setQuickfinder(quickFinder); } if (StringUtils.isBlank(quickFinder.getDataObjectClassName())) { quickFinder.setDataObjectClassName(Person.class.getName()); } if (quickFinder.getFieldConversions().isEmpty()) { quickFinder.getFieldConversions().put(KimConstants.AttributeConstants.PRINCIPAL_ID, principalIdPropertyName); if (StringUtils.isNotBlank(personNamePropertyName)) { quickFinder.getFieldConversions().put(KimConstants.AttributeConstants.NAME, personNamePropertyName); } else { quickFinder.getFieldConversions().put(KimConstants.AttributeConstants.NAME, personObjectPropertyName + "." + KimConstants.AttributeConstants.NAME); } quickFinder.getFieldConversions().put(KimConstants.AttributeConstants.PRINCIPAL_NAME, field.getPropertyName()); } } /** * The name of the property on the parent object that holds the principal id * * @return principalIdPropertyName */ @BeanTagAttribute public String getPrincipalIdPropertyName() { return principalIdPropertyName; } /** * Setter for the name of the property on the parent object that holds the principal id * * @param principalIdPropertyName */ public void setPrincipalIdPropertyName(String principalIdPropertyName) { this.principalIdPropertyName = principalIdPropertyName; } /** * The name of the property on the parent object that holds the person name * * @return personNamePropertyName */ @BeanTagAttribute public String getPersonNamePropertyName() { return personNamePropertyName; } /** * Setter for the name of the property on the parent object that holds the person name * * @param personNamePropertyName */ public void setPersonNamePropertyName(String personNamePropertyName) { this.personNamePropertyName = personNamePropertyName; } /** * The name of the property on the parent object that holds the person object * * @return personObjectPropertyName */ @BeanTagAttribute public String getPersonObjectPropertyName() { return personObjectPropertyName; } /** * Setter for the name of the property on the parent object that holds the person object * * @param personObjectPropertyName */ public void setPersonObjectPropertyName(String personObjectPropertyName) { this.personObjectPropertyName = personObjectPropertyName; } /** * {@inheritDoc} */ @Override public UserControlPostData getPostData(String propertyName) { return new UserControlPostData(propertyName, this); } /** * Holds post data for the {@link UserControl}. */ public static class UserControlPostData implements FilterableLookupCriteriaControlPostData, Serializable { private static final long serialVersionUID = 3895010942559014164L; private String propertyName; private String principalIdPropertyName; private String personNamePropertyName; private String personObjectPropertyName; /** * Constructs the post data from the property name and the {@link UserControl}. * * @param propertyName the name of the property to filter * @param userControl the control to pull data from */ public UserControlPostData(String propertyName, UserControl userControl) { this.propertyName = propertyName; this.principalIdPropertyName = userControl.getPrincipalIdPropertyName(); this.personNamePropertyName = userControl.getPersonNamePropertyName(); this.personObjectPropertyName = userControl.getPersonObjectPropertyName(); } /** * {@inheritDoc} */ @Override public Class getControlClass() { return UserControl.class; } /** * {@inheritDoc} */ @Override public String getPropertyName() { return propertyName; } /** * @see UserControl#getPrincipalIdPropertyName() */ public String getPrincipalIdPropertyName() { return principalIdPropertyName; } /** * @see UserControl#getPersonNamePropertyName() */ public String getPersonNamePropertyName() { return personNamePropertyName; } /** * @see UserControl#getPersonObjectPropertyName() */ public String getPersonObjectPropertyName() { return personObjectPropertyName; } } }/* * This file is generated by jOOQ. */ package com.rpkit.classes.bukkit.database.jooq; import com.rpkit.classes.bukkit.database.jooq.tables.RpkitCharacterClass; import com.rpkit.classes.bukkit.database.jooq.tables.RpkitClassExperience; import java.util.Arrays; import java.util.List; import org.jooq.Catalog; import org.jooq.Table; import org.jooq.impl.SchemaImpl; /** * This class is generated by jOOQ. */ @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class RpkitClasses extends SchemaImpl { private static final long serialVersionUID = 1L; /** * The reference instance of rpkit_classes */ public static final RpkitClasses RPKIT_CLASSES = new RpkitClasses(); /** * The table rpkit_classes.rpkit_character_class. */ public final RpkitCharacterClass RPKIT_CHARACTER_CLASS = RpkitCharacterClass.RPKIT_CHARACTER_CLASS; /** * The table rpkit_classes.rpkit_class_experience. */ public final RpkitClassExperience RPKIT_CLASS_EXPERIENCE = RpkitClassExperience.RPKIT_CLASS_EXPERIENCE; /** * No further instances allowed */ private RpkitClasses() { super("rpkit_classes", null); } @Override public Catalog getCatalog() { return DefaultCatalog.DEFAULT_CATALOG; } @Override public final List> getTables() { return Arrays.>asList( RpkitCharacterClass.RPKIT_CHARACTER_CLASS, RpkitClassExperience.RPKIT_CLASS_EXPERIENCE); } } package com.kisan.BehavioralDesignPatterns.ChainofResponsibilty; public class Authenticator extends Handler { public Authenticator(Handler next) { super(next); } @Override public boolean doHandle(HttpRequest request) { boolean isAuthenticated = request.getUserName().equals("admin") && request.getPassword().equals(""); System.out.println("Authentication: " + isAuthenticated); return !isAuthenticated; } } package ru.job4j.model.repository; import ru.job4j.model.pojo.Address; import ru.job4j.model.pojo.MusicType; import ru.job4j.model.pojo.Roles; import ru.job4j.model.pojo.User; import java.util.ArrayList; import java.util.List; /** * @author */ class UserMapper { static User toUserMap( int id, String name, String login, String password, String country, String city, String role, Object music) { return new User( id, login, password, name, new Address(country, city), toRoles(role), toMusicType(music) ); } private static List toMusicType(Object obj) { List music = new ArrayList<>(); String[] strings = (String[]) obj; for (String item : strings) { music.add(MusicType.valueOf(item)); } return music; } private static Roles toRoles(String str) { return Roles.valueOf(str); } } src/main/java/ru/chernov/prosto/repository/PostRepository.java package ru.chernov.prosto.repository; import org.springframework.data.jpa.repository.JpaRepository; import ru.chernov.prosto.domain.entity.Post; import java.util.List; /** * @author */ public interface PostRepository extends JpaRepository { List findAllByAuthorIdOrderByCreationDateTimeDesc(long id); } windkyle/eshoweshow-service/src/main/java/cn/org/eshow/service/AccessTokenManager.java package cn.org.eshow.service; import cn.org.eshow.bean.query.AccessTokenQuery; import cn.org.eshow.common.page.Page; import cn.org.eshow.model.AccessToken; import cn.org.eshow.model.User; import org.apache.amber.oauth2.common.exception.OAuthSystemException; import javax.jws.WebService; import java.util.List; @WebService public interface AccessTokenManager extends GenericManager { /** * 获取访问令牌列表 * * @param query 访问令牌查询对象 * @return 访问令牌列表 */ List list(AccessTokenQuery query); /** * 搜索访问令牌列表 * * @param query 访问令牌查询对象 * @return 访问令牌列分页列表 */ Page search(AccessTokenQuery query); /** * 添加访问令牌 * * @param user * @return */ AccessToken save(User user) throws OAuthSystemException; /** * 获取用户访问令牌 * * @param user 用户 * @return 访问令牌 * @throws OAuthSystemException */ AccessToken refresh(User user) throws OAuthSystemException; /** * 判断是否有效 true有效 false无效 * * @param accessToken * @return User */ User isValid(String accessToken); }package com.littlesparkle.growler.library.utility; import android.content.Context; import android.location.LocationManager; import java.util.List; public class LocationUtils { public static boolean hasGPSDevice(Context context) { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); if (locationManager != null) { List providers = locationManager.getAllProviders(); if (providers != null) { return providers.contains(LocationManager.GPS_PROVIDER); } } return false; } public static boolean isLocationEnabled(Context context) { return (isGpsEnabled(context) || isNetworkEnabled(context)); } public static boolean isNetworkEnabled(Context context) { return isEnabledWithType(context, LocationManager.NETWORK_PROVIDER); } public static boolean isGpsEnabled(Context context) { return isEnabledWithType(context, LocationManager.GPS_PROVIDER); } private static boolean isEnabledWithType(Context context, String type) { LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); return locationManager.isProviderEnabled(type); } } package me.mindlessly.notenoughcoins.commands.subcommands; import net.minecraft.command.ICommandSender; public interface Subcommand { String getCommandName(); /** * Returns a String that will be shown after the subcommand name in the help menu and error message. * It will look like: /nec subcommand (usage) */ String getCommandUsage(ICommandSender sender); /** * This function will be called upon execution of the subcommand, and should return a boolean deciding whether the command * succeeded or not, which will send an error message if not. * Note: The arguments will not include the subcommand itself, example: * /nec subcommand arg1 arg2 will have {"arg1", "arg2"} as its args */ boolean processCommand(ICommandSender sender, String[] args); } package com.huaweicloud.sdk.meeting.v1.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; /** 与会嘉宾列表。该列表可以用于发送会议通知、会议提醒、会议开始时候进行自动邀请。 */ public class OpenAttendeeEntity { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "appId") private String appId; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "userAccount") private String userAccount; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "userName") private String userName; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "deptName") private String deptName; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "phone") private String phone; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "email") private String email; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "sms") private String sms; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value = "isHardTerminal") private Boolean isHardTerminal; public OpenAttendeeEntity withAppId(String appId) { this.appId = appId; return this; } /** App ID,应用标识,一个应用只需创建一次。必填字段 * * @return appId */ public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public OpenAttendeeEntity withUserAccount(String userAccount) { this.userAccount = userAccount; return this; } /** 与会者的账号ID。如果是账号/密码鉴权场景,表示华为云会议帐号ID。如果是APP ID鉴权场景,表示第三方的User ID。必填字段 * * @return userAccount */ public String getUserAccount() { return userAccount; } public void setUserAccount(String userAccount) { this.userAccount = userAccount; } public OpenAttendeeEntity withUserName(String userName) { this.userName = userName; return this; } /** 与会者名称或昵称。长度限制为96个字符 * * @return userName */ public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public OpenAttendeeEntity withDeptName(String deptName) { this.deptName = deptName; return this; } /** 部门名称 * * @return deptName */ public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public OpenAttendeeEntity withPhone(String phone) { this.phone = phone; return this; } /** 号码(可支持SIP、TEL号码格式)。最大不超过127个字符。phone、email和sms三者需至少填写一个。 * * @return phone */ public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public OpenAttendeeEntity withEmail(String email) { this.email = email; return this; } /** 邮件地址。最大不超过255个字符。phone、email和sms三者需至少填写一个(用于预定、修改、取消会议的信息通知)。 * * @return email */ public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public OpenAttendeeEntity withSms(String sms) { this.sms = sms; return this; } /** 短信通知的手机号码。最大不超过32个字符。phone、email和sms三者需至少填写一个。(用于预定、修改、取消会议的信息通知)。 * * @return sms */ public String getSms() { return sms; } public void setSms(String sms) { this.sms = sms; } public OpenAttendeeEntity withIsHardTerminal(Boolean isHardTerminal) { this.isHardTerminal = isHardTerminal; return this; } /** 是否硬终端(会议室或硬终端)。 * * @return isHardTerminal */ public Boolean getIsHardTerminal() { return isHardTerminal; } public void setIsHardTerminal(Boolean isHardTerminal) { this.isHardTerminal = isHardTerminal; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OpenAttendeeEntity openAttendeeEntity = (OpenAttendeeEntity) o; return Objects.equals(this.appId, openAttendeeEntity.appId) && Objects.equals(this.userAccount, openAttendeeEntity.userAccount) && Objects.equals(this.userName, openAttendeeEntity.userName) && Objects.equals(this.deptName, openAttendeeEntity.deptName) && Objects.equals(this.phone, openAttendeeEntity.phone) && Objects.equals(this.email, openAttendeeEntity.email) && Objects.equals(this.sms, openAttendeeEntity.sms) && Objects.equals(this.isHardTerminal, openAttendeeEntity.isHardTerminal); } @Override public int hashCode() { return Objects.hash(appId, userAccount, userName, deptName, phone, email, sms, isHardTerminal); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class OpenAttendeeEntity {\n"); sb.append(" appId: ").append(toIndentedString(appId)).append("\n"); sb.append(" userAccount: ").append(toIndentedString(userAccount)).append("\n"); sb.append(" userName: ").append(toIndentedString(userName)).append("\n"); sb.append(" deptName: ").append(toIndentedString(deptName)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" sms: ").append(toIndentedString(sms)).append("\n"); sb.append(" isHardTerminal: ").append(toIndentedString(isHardTerminal)).append("\n"); sb.append("}"); return sb.toString(); } /** Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } package com.facebook.login; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Bundle; import android.os.Parcel; import com.facebook.AccessTokenSource; import com.facebook.FacebookException; import com.facebook.internal.NativeProtocol; import com.facebook.internal.ServerProtocol; import com.facebook.internal.Utility; import com.facebook.login.LoginClient.Request; import com.facebook.login.LoginClient.Result; abstract class NativeAppLoginMethodHandler extends LoginMethodHandler { NativeAppLoginMethodHandler(LoginClient loginClient) { super(loginClient); } NativeAppLoginMethodHandler(Parcel parcel) { super(parcel); } /* access modifiers changed from: 0000 */ public boolean onActivityResult(int i, int i2, Intent intent) { Result result; Request pendingRequest = this.loginClient.getPendingRequest(); if (intent == null) { result = Result.createCancelResult(pendingRequest, "Operation canceled"); } else if (i2 == 0) { result = handleResultCancel(pendingRequest, intent); } else if (i2 != -1) { result = Result.createErrorResult(pendingRequest, "Unexpected resultCode from authorization.", null); } else { result = handleResultOk(pendingRequest, intent); } if (result != null) { this.loginClient.completeAndValidate(result); } else { this.loginClient.tryNextHandler(); } return true; } private Result handleResultOk(Request request, Intent intent) { Bundle extras = intent.getExtras(); String error = getError(extras); String str = NativeProtocol.BRIDGE_ARG_ERROR_CODE; String obj = extras.get(str) != null ? extras.get(str).toString() : null; String errorMessage = getErrorMessage(extras); String string = extras.getString("e2e"); if (!Utility.isNullOrEmpty(string)) { logWebLoginCompleted(string); } if (error == null && obj == null && errorMessage == null) { try { return Result.createTokenResult(request, LoginMethodHandler.createAccessTokenFromWebBundle(request.getPermissions(), extras, AccessTokenSource.FACEBOOK_APPLICATION_WEB, request.getApplicationId())); } catch (FacebookException e) { return Result.createErrorResult(request, null, e.getMessage()); } } else if (ServerProtocol.errorsProxyAuthDisabled.contains(error)) { return null; } else { if (ServerProtocol.errorsUserCanceled.contains(error)) { return Result.createCancelResult(request, null); } return Result.createErrorResult(request, error, errorMessage, obj); } } private Result handleResultCancel(Request request, Intent intent) { Bundle extras = intent.getExtras(); String error = getError(extras); String str = NativeProtocol.BRIDGE_ARG_ERROR_CODE; String obj = extras.get(str) != null ? extras.get(str).toString() : null; if (ServerProtocol.errorConnectionFailure.equals(obj)) { return Result.createErrorResult(request, error, getErrorMessage(extras), obj); } return Result.createCancelResult(request, error); } private String getError(Bundle bundle) { String string = bundle.getString("error"); return string == null ? bundle.getString(NativeProtocol.BRIDGE_ARG_ERROR_TYPE) : string; } private String getErrorMessage(Bundle bundle) { String string = bundle.getString("error_message"); return string == null ? bundle.getString("error_description") : string; } /* access modifiers changed from: protected */ public boolean tryIntent(Intent intent, int i) { if (intent == null) { return false; } try { this.loginClient.getFragment().startActivityForResult(intent, i); return true; } catch (ActivityNotFoundException unused) { return false; } } } package com.gregortorrence.kagemusha.translators; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class JsonTranslator implements Translator { private static final ObjectMapper objectMapper = new ObjectMapper(); private static final TypeReference> mapTypeRef = new TypeReference>() {}; @Override public String getFileExtension() { return "json"; } @Override public void translate(File inputFile, File outputFile) throws IOException { Map map = objectMapper.readValue(inputFile, mapTypeRef); translate(map); objectMapper.writeValue(outputFile, map); } private void translate(Map map) { map.keySet().forEach(key -> { Object value = map.get(key); if (value instanceof String) { map.put(key, Kagemusha.translate((String) map.get(key))); } else if (value instanceof List) { map.put(key, translate((List)map.get(key))); } else if (value instanceof Map){ translate((Map)map.get(key)); } else { System.err.println("Skipping value " + value + " of type " + value.getClass()); } }); } private List translate(List list) { return list.stream().map(Kagemusha::translate).collect(Collectors.toList()); } } warlock-china/azeroth10-100 package cn.com.warlock.scheduler; import java.io.Closeable; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TaskRetryProcessor implements Closeable { private static final Logger logger = LoggerFactory .getLogger(TaskRetryProcessor.class); //重试时间间隔单元(毫秒) private static final long RETRY_PERIOD_UNIT = 10 * 1000; private final PriorityBlockingQueue taskQueue = new PriorityBlockingQueue( 1000); private ExecutorService executor; private AtomicBoolean closed = new AtomicBoolean(false); private List queueJobNames = new CopyOnWriteArrayList<>(); public TaskRetryProcessor() { this(1); } public TaskRetryProcessor(int poolSize) { executor = Executors.newFixedThreadPool(poolSize); executor.submit(new Runnable() { @Override public void run() { while (!closed.get()) { try { PriorityTask task = taskQueue.take(); //空任务跳出循环 if (task.getJob() == null) break; if (task.nextFireTime - System.currentTimeMillis() > 0) { TimeUnit.MILLISECONDS.sleep(1000); taskQueue.put(task); continue; } task.run(); } catch (Exception e) { e.printStackTrace(); } } } }); } public void submit(final AbstractJob job, final int retries) { int taskCount; if ((taskCount = taskQueue.size()) > 100) { logger.warn("ErrorMessageProcessor queue task count over:{}", taskCount); } if (queueJobNames.contains(job.jobName)) { logger.debug("Job[{}-{}] is existing in retry Queue", job.group, job.jobName); return; } logger.info("Add Job[{}-{}] to retry Queue,will be retry {} time", job.group, job.jobName, retries); taskQueue.add(new PriorityTask(job, retries)); queueJobNames.add(job.jobName); } public void close() { closed.set(true); //taskQueue里面没有任务会一直阻塞,所以先add一个新任务保证执行 taskQueue.add(new PriorityTask(null, 0)); try { Thread.sleep(1000); } catch (Exception e) { } executor.shutdown(); logger.info("TaskRetryProcessor closed"); } class PriorityTask implements Runnable, Comparable { final AbstractJob job; int retries; int retryCount = 0; long nextFireTime; public PriorityTask(AbstractJob job, int retries) { this(job, retries, System.currentTimeMillis() + RETRY_PERIOD_UNIT); } public PriorityTask(AbstractJob job, int retries, long nextFireTime) { super(); this.retries = retries; this.job = job; this.nextFireTime = nextFireTime; } public AbstractJob getJob() { return job; } @Override public void run() { try { logger.debug("begin re-process Job[{}-{}]:", job.group, job.jobName); job.doJob(JobContext.getContext()); //remove queueJobNames.remove(job.jobName); } catch (Exception e) { retryCount++; logger.warn("retry Job[{}-{}] error", job.group, job.jobName); retry(); } } private void retry() { if (retryCount == retries) { logger.warn("retry_skip mssageId[{}] retry over {} time error ,skip!!!"); //remove queueJobNames.remove(job.jobName); return; } nextFireTime = nextFireTime + retryCount * RETRY_PERIOD_UNIT; //重新放入任务队列 taskQueue.add(this); logger.debug("re-submit Job[{}-{}] task to queue,next fireTime:{}", job.group, job.jobName, nextFireTime); } @Override public int compareTo(PriorityTask o) { return (int) (this.nextFireTime - o.nextFireTime); } } } package de.wecos.rnfairbid; import android.app.Activity; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.modules.core.DeviceEventManagerModule.RCTDeviceEventEmitter; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableMapKeySetIterator; import com.fyber.FairBid; import com.fyber.fairbid.ads.Banner; import com.fyber.fairbid.ads.ImpressionData; import com.fyber.fairbid.ads.Interstitial; import com.fyber.fairbid.ads.Rewarded; import com.fyber.fairbid.ads.banner.BannerError; import com.fyber.fairbid.ads.banner.BannerListener; import com.fyber.fairbid.ads.interstitial.InterstitialListener; import com.fyber.fairbid.ads.rewarded.RewardedListener; import com.fyber.fairbid.user.UserInfo; import java.util.HashMap; import java.util.Map; public class RNFairbidModule extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; private final BannerListener bannerListener = new BannerListener() { @Override public void onError(String placementId, BannerError error) { sendReactEvent("bannerDidFailToLoad", "placementId", placementId); } @Override public void onLoad(String placementId) { sendReactEvent("bannerDidLoad", "placementId", placementId); } @Override public void onShow(String placementId, ImpressionData impressionData) { sendReactEvent("bannerDidShow", "placementId", placementId); } @Override public void onClick(String placementId) { sendReactEvent("bannerDidClick", "placementId", placementId); } }; private final InterstitialListener interstitialListener = new InterstitialListener() { @Override public void onShow(String placementId, ImpressionData impressionData) { sendReactEvent("interstitialDidShow", "placementId", placementId); } @Override public void onClick(String placementId) { sendReactEvent("interstitialDidClick", "placementId", placementId); } @Override public void onHide(String placementId) { sendReactEvent("interstitialDidDismiss", "placementId", placementId); } @Override public void onShowFailure(String placementId, ImpressionData impressionData) { sendReactEvent("interstitialDidFailToShow", "placementId", placementId); } @Override public void onAvailable(String placementId) { sendReactEvent("interstitialIsAvailable", "placementId", placementId); } @Override public void onUnavailable(String placementId) { sendReactEvent("interstitialIsUnavailable", "placementId", placementId); } }; private final RewardedListener rewardedListener = new RewardedListener() { @Override public void onShow(String placementId, ImpressionData impressionData) { sendReactEvent("rewardedDidShow", "placementId", placementId); } @Override public void onClick(String placementId) { sendReactEvent("rewardedDidClick", "placementId", placementId); } @Override public void onHide(String placementId) { sendReactEvent("rewardedDidDismiss", "placementId", placementId); } @Override public void onShowFailure(String placementId, ImpressionData impressionData) { sendReactEvent("rewardedDidFailToShow", "placementId", placementId); } @Override public void onAvailable(String placementId) { sendReactEvent("rewardedIsAvailable", "placementId", placementId); } @Override public void onUnavailable(String placementId) { sendReactEvent("rewardedIsUnavailable", "placementId", placementId); } @Override public void onCompletion(@NonNull String placementId, boolean userRewarded) { sendReactEvent("rewardedDidComplete", "placementId", placementId); } }; public RNFairbidModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } private void sendReactEvent(final String eventName, final String key, final String value) { final WritableMap params = new WritableNativeMap(); params.putString("name", eventName); params.putString(key, value); sendReactEvent(eventName, params); } private void sendReactEvent(final String eventName, @Nullable WritableMap params) { if (params == null) { params = new WritableNativeMap(); params.putString("name", eventName); } getReactApplicationContext() .getJSModule(RCTDeviceEventEmitter.class) .emit("RNFairbidEvent", params); } @Override public String getName() { return "RNFairbid"; } @ReactMethod public void initWithAppID(final String appId, final String userId) { final Activity activity = getCurrentActivity(); if (activity != null) { FairBid.start(appId, activity); UserInfo.setUserId(userId); Banner.setBannerListener(bannerListener); Interstitial.setInterstitialListener(interstitialListener); Rewarded.setRewardedListener(rewardedListener); } } @ReactMethod public void presentTestSuite() { FairBid.showTestSuite(getCurrentActivity()); } @ReactMethod public void requestInterstitialForPlacementID(final String placementId) { Interstitial.request(placementId); } @ReactMethod public void isInterstitialAvailableForPlacementID(final String placementId, final Callback callback) { callback.invoke(Interstitial.isAvailable(placementId)); } @ReactMethod public void showInterstitialForPlacementID(final String placementId, final Callback callback) { if (Interstitial.isAvailable(placementId)) { Interstitial.show(placementId, getCurrentActivity()); callback.invoke(true); } else { callback.invoke(false); } } @ReactMethod public void requestVideoForPlacementID(final String placementId) { Rewarded.request(placementId); } @ReactMethod public void isVideoAvailableForPlacementID(final String placementId, final Callback callback) { callback.invoke(Rewarded.isAvailable(placementId)); } @ReactMethod public void showVideoForPlacementID(final String placementId, final Callback callback) { if (Rewarded.isAvailable(placementId)) { Rewarded.show(placementId, getCurrentActivity()); callback.invoke(true); } else { callback.invoke(false); } } @ReactMethod public void showBannerInView(final String placementId,final String info,final Callback callback) { callback.invoke((Object)null); } @ReactMethod public void GDPRCConsent(final boolean consentFlag) { UserInfo.setGdprConsent(consentFlag, getCurrentActivity()); } @ReactMethod public void GDPRCConsentData(final @Nullable ReadableMap params) { Map consentData = new HashMap<>(); if (params != null) { ReadableMapKeySetIterator it = params.keySetIterator(); while(it.hasNextKey()) { String key = it.nextKey(); consentData.put(key, params.getString(key)); } } UserInfo.setGdprConsentData(consentData, getCurrentActivity()); } @ReactMethod public void clearGDPRConsent() { UserInfo.clearGdprConsentData(getCurrentActivity()); } } terminux/jdk1.7.0_80 /* * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package javax.xml.bind.annotation; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.*; /** * Maps a JavaBean property to a XML element derived from property name. * *

Usage

*

* @XmlElement annotation can be used with the following program * elements: *

    *
  • a JavaBean property
  • *
  • non static, non transient field
  • *
  • within {@link XmlElements} *

    * *

* * The usage is subject to the following constraints: *
    *
  • This annotation can be used with following annotations: * {@link XmlID}, * {@link XmlIDREF}, * {@link XmlList}, * {@link XmlSchemaType}, * {@link XmlValue}, * {@link XmlAttachmentRef}, * {@link XmlMimeType}, * {@link XmlInlineBinaryData}, * {@link XmlElementWrapper}, * {@link XmlJavaTypeAdapter}
  • *
  • if the type of JavaBean property is a collection type of * array, an indexed property, or a parameterized list, and * this annotation is used with {@link XmlElements} then, * @XmlElement.type() must be DEFAULT.class since the * collection item type is already known.
  • *
* *

* A JavaBean property, when annotated with @XmlElement annotation * is mapped to a local element in the XML Schema complex type to * which the containing class is mapped. * *

* Example 1: Map a public non static non final field to local * element *

 *     //Example: Code fragment
 *     public class USPrice {
 *         @XmlElement(name="itemprice")
 *         public java.math.BigDecimal price;
 *     }
 *
 *     <!-- Example: Local XML Schema element -->
 *     <xs:complexType name="USPrice"/>
 *       <xs:sequence>
 *         <xs:element name="itemprice" type="xs:decimal" minOccurs="0"/>
 *       </sequence>
 *     </xs:complexType>
 *   
*

* * Example 2: Map a field to a nillable element. *

 *
 *     //Example: Code fragment
 *     public class USPrice {
 *         @XmlElement(nillable=true)
 *         public java.math.BigDecimal price;
 *     }
 *
 *     <!-- Example: Local XML Schema element -->
 *     <xs:complexType name="USPrice">
 *       <xs:sequence>
 *         <xs:element name="price" type="xs:decimal" nillable="true" minOccurs="0"/>
 *       </sequence>
 *     </xs:complexType>
 *   
*

* Example 3: Map a field to a nillable, required element. *

 *
 *     //Example: Code fragment
 *     public class USPrice {
 *         @XmlElement(nillable=true, required=true)
 *         public java.math.BigDecimal price;
 *     }
 *
 *     <!-- Example: Local XML Schema element -->
 *     <xs:complexType name="USPrice">
 *       <xs:sequence>
 *         <xs:element name="price" type="xs:decimal" nillable="true" minOccurs="1"/>
 *       </sequence>
 *     </xs:complexType>
 *   
*

* *

Example 4: Map a JavaBean property to an XML element * with anonymous type.

*

* See Example 6 in @{@link XmlType}. * *

* @author , Sun Microsystems, Inc. * @since JAXB2.0 */ @Retention(RUNTIME) @Target({FIELD, METHOD, PARAMETER}) public @interface XmlElement { /** * Name of the XML Schema element. *

If the value is "##default", then element name is derived from the * JavaBean property name. */ String name() default "##default"; /** * Customize the element declaration to be nillable. *

If nillable() is true, then the JavaBean property is * mapped to a XML Schema nillable element declaration. */ boolean nillable() default false; /** * Customize the element declaration to be required. *

If required() is true, then Javabean property is mapped to * an XML schema element declaration with minOccurs="1". * maxOccurs is "1" for a single valued property and "unbounded" * for a multivalued property. *

If required() is false, then the Javabean property is mapped * to XML Schema element declaration with minOccurs="0". * maxOccurs is "1" for a single valued property and "unbounded" * for a multivalued property. */ boolean required() default false; /** * XML target namespace of the XML Schema element. *

* If the value is "##default", then the namespace is determined * as follows: *

    *
  1. * If the enclosing package has {@link XmlSchema} annotation, * and its {@link XmlSchema#elementFormDefault() elementFormDefault} * is {@link XmlNsForm#QUALIFIED QUALIFIED}, then the namespace of * the enclosing class. * *
  2. * Otherwise '' (which produces unqualified element in the default * namespace. *
*/ String namespace() default "##default"; /** * Default value of this element. * *

* The

'\u0000'
value specified as a default of this annotation element * is used as a poor-man's substitute for null to allow implementations * to recognize the 'no default value' state. */ String defaultValue() default "\u0000"; /** * The Java class being referenced. */ Class type() default DEFAULT.class; /** * Used in {@link XmlElement#type()} to * signal that the type be inferred from the signature * of the property. */ static final class DEFAULT {} } /* * Copyright 2010 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.gradle.configuration; import org.gradle.api.internal.resource.DelegatingResource; import org.gradle.api.internal.resource.Resource; import org.gradle.groovy.scripts.DelegatingScriptSource; import org.gradle.groovy.scripts.ScriptSource; public class ImportsScriptSource extends DelegatingScriptSource { private final ImportsReader importsReader; public ImportsScriptSource(ScriptSource source, ImportsReader importsReader) { super(source); this.importsReader = importsReader; } @Override public Resource getResource() { return new ImportsResource(super.getResource()); } private class ImportsResource extends DelegatingResource { private ImportsResource(Resource resource) { super(resource); } @Override public String getText() { String text = getResource().getText(); assert text != null; if (text.matches("\\s*")) { return text; } else { return text + '\n' + importsReader.getImports(); } } } } package jp.cafebabe.fritter.validators.impl.variables; import jp.cafebabe.fritter.config.Parameter; import jp.cafebabe.fritter.entities.sources.DataSource; import jp.cafebabe.fritter.validators.Validator; import jp.cafebabe.fritter.validators.Violations; import jp.cafebabe.fritter.validators.impl.ViolationsHelper; import jp.cafebabe.fritter.validators.spi.ValidatorService; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.nio.file.Paths; import static org.junit.jupiter.api.Assertions.assertEquals; public class SingleCharacterNameValidatorTest { private static Validator validator; @BeforeAll public static void setUp() { ValidatorService service = new SingleCharacterNameValidatorService(); validator = service.build(Parameter.EMPTY); } @DisplayName("SingleCharacterNameValidator StatsValues.java") @Test public void case1() { DataSource source = ViolationsHelper.dataSource(Paths.get("src/test/resources/projects/examples/StatsValues.java")); Violations violations = validator.validate(source); assertEquals(0, violations.accept(ViolationsHelper.violationCollector()).size()); } @DisplayName("SingleCharacterNameValidator Stats.java") @Test public void case2() { DataSource source = ViolationsHelper.dataSource(Paths.get("src/test/resources/projects/examples/Stats.java")); Violations violations = validator.validate(source); assertEquals(1, violations.accept(ViolationsHelper.violationCollector()).size()); } @DisplayName("SingleCharacterNameValidator Primes.java") @Test public void case3() { DataSource source = ViolationsHelper.dataSource(Paths.get("src/test/resources/projects/examples/Primes.java")); Violations violations = validator.validate(source); assertEquals(0, violations.accept(ViolationsHelper.violationCollector()).size()); } @DisplayName("SingleCharacterNameValidator HelloWorld.java") @Test public void case4() { DataSource source = ViolationsHelper.dataSource(Paths.get("src/test/resources/projects/examples/HelloWorld.java")); Violations violations = validator.validate(source); assertEquals(0, violations.accept(ViolationsHelper.violationCollector()).size()); } } package seedu.address.model.tag; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Contains utility functions for testing classes to do with UniqueTagList. */ public class UniqueTagListTestUtil { public static final String VALID_TAG_FRIEND = "friend"; public static final String VALID_TAG_HUSBAND = "husband"; public static final String VALID_TAG_VIM = "vim"; public static final String VALID_TAG_YELLOW = "yellow"; public static final String VALID_TAG_ZOO = "zoo"; public static final Tag TAG_FRIEND = new Tag(VALID_TAG_FRIEND); public static final Tag TAG_HUSBAND = new Tag(VALID_TAG_HUSBAND); public static final Tag TAG_VIM = new Tag(VALID_TAG_VIM); public static final Tag TAG_YELLOW = new Tag(VALID_TAG_YELLOW); public static final Tag TAG_ZOO = new Tag(VALID_TAG_ZOO); public static final Set SET_TAG_FRIEND = new HashSet<>(); public static final Set SET_TAG_HUSBAND = new HashSet<>(); static { SET_TAG_FRIEND.add(TAG_FRIEND); SET_TAG_HUSBAND.add(TAG_HUSBAND); } /** * Builds a set with the given variable number of tag arguments. Maintains order that was passed into arguments. * * @param tags Variable number of Tags. * @return Set of the given tags. */ public static Set buildSetOfTags(Tag... tags) { return new HashSet<>(Arrays.asList(tags)); } /** * Builds a UniqueTagList with the given list of tags. * * @param tags List of tags. * @return UniqueTagList with the given tags. */ public static UniqueTagList buildWithTags(List tags) { UniqueTagList utl = new UniqueTagList(); tags.forEach(utl::add); return utl; } } n1rocket/eggs-android package com.n1rocket.framework.mvp.ui.profile; import dagger.Subcomponent; import dagger.android.AndroidInjector; /** * Created by abueno on 17/10/17. */ @Subcomponent(modules = ProfileFragmentModule.class) public interface ProfileFragmentComponent extends AndroidInjector { @Subcomponent.Builder abstract class Builder extends AndroidInjector.Builder { } } package com.sequenceiq.freeipa.client; public class FreeIpaClientExceptionWrapper extends RuntimeException { public FreeIpaClientExceptionWrapper(FreeIpaClientException e) { super(e.getMessage(), e); } public FreeIpaClientException getWrappedException() { return (FreeIpaClientException) getCause(); } } CharLemAznable/char-httpclient package com.github.charlemaznable.httpclient.ohclient.internal; import lombok.NoArgsConstructor; import okhttp3.ConnectionPool; import org.apache.commons.text.StringSubstitutor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Properties; import java.util.concurrent.ExecutorService; import static com.github.charlemaznable.core.config.Arguments.argumentsAsProperties; import static com.github.charlemaznable.core.lang.ClzPath.classResourceAsProperties; import static com.github.charlemaznable.core.lang.Propertiess.ssMap; import static java.util.Objects.isNull; import static java.util.concurrent.Executors.newCachedThreadPool; @NoArgsConstructor public class OhDummy { static final Logger log = LoggerFactory.getLogger("OhClient"); static final ExecutorService ohExecutorService; static final ConnectionPool ohConnectionPool; static Properties ohClassPathProperties; static { ohExecutorService = newCachedThreadPool(); ohConnectionPool = new ConnectionPool(); } static String substitute(String source) { if (isNull(ohClassPathProperties)) { ohClassPathProperties = classResourceAsProperties("ohclient.env.props"); } return new StringSubstitutor(ssMap(argumentsAsProperties( ohClassPathProperties))).replace(source); } @Override public boolean equals(Object obj) { return obj instanceof OhDummy && hashCode() == obj.hashCode(); } @Override public int hashCode() { return System.identityHashCode(this); } @Override public String toString() { return "OhClient@" + Integer.toHexString(hashCode()); } } ValtteriL/ID2210task5/vt18-id2210-cloud-master/ledbat/src/main/java/se/kth/ledbat/Driver/MyIdentifiable.java package se.kth.ledbat.Driver; import se.sics.kompics.util.Identifiable; public class MyIdentifiable implements Identifiable { MyIdentifier id; public MyIdentifiable(String id) { this.id = new MyIdentifier(id); } @Override public MyIdentifier getId() { return id; } } package com.dwarfeng.familyhelper.clannad.stack.bean.dto; import com.dwarfeng.subgrade.stack.bean.dto.Dto; import java.util.Arrays; /** * 头像下载信息。 * * @author DwArFeng * @since 1.2.0 */ public class Avatar implements Dto { private static final long serialVersionUID = 6860496142664630355L; private String originName; private byte[] content; public Avatar() { } public Avatar(String originName, byte[] content) { this.originName = originName; this.content = content; } public String getOriginName() { return originName; } public void setOriginName(String originName) { this.originName = originName; } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } @Override public String toString() { return "Avatar{" + "originName='" + originName + '\'' + ", content=" + Arrays.toString(content) + '}'; } } // Code generated by Wire protocol buffer compiler, do not edit. // Source file: proto/Notifications.proto package com.google.play.proto; import com.squareup.wire.Message; import com.squareup.wire.ProtoField; import static com.squareup.wire.Message.Datatype.STRING; public final class UserNotificationData extends Message { public static final String DEFAULT_NOTIFICATIONTITLE = ""; public static final String DEFAULT_NOTIFICATIONTEXT = ""; public static final String DEFAULT_TICKERTEXT = ""; public static final String DEFAULT_DIALOGTITLE = ""; public static final String DEFAULT_DIALOGTEXT = ""; @ProtoField(tag = 1, type = STRING) public final String notificationTitle; @ProtoField(tag = 2, type = STRING) public final String notificationText; @ProtoField(tag = 3, type = STRING) public final String tickerText; @ProtoField(tag = 4, type = STRING) public final String dialogTitle; @ProtoField(tag = 5, type = STRING) public final String dialogText; public UserNotificationData(String notificationTitle, String notificationText, String tickerText, String dialogTitle, String dialogText) { this.notificationTitle = notificationTitle; this.notificationText = notificationText; this.tickerText = tickerText; this.dialogTitle = dialogTitle; this.dialogText = dialogText; } private UserNotificationData(Builder builder) { this(builder.notificationTitle, builder.notificationText, builder.tickerText, builder.dialogTitle, builder.dialogText); setBuilder(builder); } @Override public boolean equals(Object other) { if (other == this) return true; if (!(other instanceof UserNotificationData)) return false; UserNotificationData o = (UserNotificationData) other; return equals(notificationTitle, o.notificationTitle) && equals(notificationText, o.notificationText) && equals(tickerText, o.tickerText) && equals(dialogTitle, o.dialogTitle) && equals(dialogText, o.dialogText); } @Override public int hashCode() { int result = hashCode; if (result == 0) { result = notificationTitle != null ? notificationTitle.hashCode() : 0; result = result * 37 + (notificationText != null ? notificationText.hashCode() : 0); result = result * 37 + (tickerText != null ? tickerText.hashCode() : 0); result = result * 37 + (dialogTitle != null ? dialogTitle.hashCode() : 0); result = result * 37 + (dialogText != null ? dialogText.hashCode() : 0); hashCode = result; } return result; } public static final class Builder extends Message.Builder { public String notificationTitle; public String notificationText; public String tickerText; public String dialogTitle; public String dialogText; public Builder() { } public Builder(UserNotificationData message) { super(message); if (message == null) return; this.notificationTitle = message.notificationTitle; this.notificationText = message.notificationText; this.tickerText = message.tickerText; this.dialogTitle = message.dialogTitle; this.dialogText = message.dialogText; } public Builder notificationTitle(String notificationTitle) { this.notificationTitle = notificationTitle; return this; } public Builder notificationText(String notificationText) { this.notificationText = notificationText; return this; } public Builder tickerText(String tickerText) { this.tickerText = tickerText; return this; } public Builder dialogTitle(String dialogTitle) { this.dialogTitle = dialogTitle; return this; } public Builder dialogText(String dialogText) { this.dialogText = dialogText; return this; } @Override public UserNotificationData build() { return new UserNotificationData(this); } } } package org.nure.gas_station.services.interfaces; import org.nure.gas_station.exceptions.EntityAlreadyExistsException; import org.nure.gas_station.exceptions.EntityNotFoundException; import org.nure.gas_station.model.enumerations.UserRoles; import org.springframework.security.core.Authentication; public interface IUserService { void createUser(String username, String password, String name, String surname, UserRoles role) throws EntityAlreadyExistsException; void changePassword(String username, String password, String oldPassword) throws EntityNotFoundException, IllegalArgumentException; Authentication authenticate(String username, String password); } wanmeiwinners/playa package io.github.zeleven.playa.ui.module.account.signin; import javax.inject.Inject; import io.github.zeleven.playa.data.model.BaseResponse; import io.github.zeleven.playa.data.model.LoginResponse; import io.github.zeleven.playa.data.source.DataManager; import io.github.zeleven.playa.ui.base.BasePresenter; import io.github.zeleven.playa.utils.StringUtils; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; public class SignInPresenter extends BasePresenter implements SignInContract.Presenter { private DataManager dataManager; private Disposable disposable; @Inject public SignInPresenter(DataManager dataManager) { this.dataManager = dataManager; } @Override public void detachView() { super.detachView(); if (disposable != null) { disposable.dispose(); } } @Override public void signIn(String username, String password) { boolean isUsernameEmpty = StringUtils.isEmpty(username); getView().usernameEmpty(isUsernameEmpty); if (isUsernameEmpty) { return; } boolean isPasswordEmpty = StringUtils.isEmpty(password); getView().passwordEmpty(isPasswordEmpty); if (isPasswordEmpty) { return; } Observable> observable = dataManager.signin(username, password); observable.observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .map(new Function, LoginResponse>() { @Override public LoginResponse apply(@NonNull BaseResponse response) throws Exception { return response.getData(); } }).subscribeWith(new Observer() { @Override public void onSubscribe(@NonNull Disposable d) { disposable = d; } @Override public void onNext(@NonNull LoginResponse loginResponse) { dataManager.saveLoggedInUser( loginResponse.getUsername(), loginResponse.getPassword(), true ); getView().loginSuccessful(loginResponse.getUsername()); } @Override public void onError(@NonNull Throwable e) { getView().showError(e.getMessage()); } @Override public void onComplete() { } }); } } broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/ObjectProperties.java /* * 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.qpid.server.security.access.config; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.google.common.base.Joiner; public final class ObjectProperties { static final String EMPTY_STRING = ""; private final Set _attributeNames = new HashSet<>(); private final EnumMap _properties = new EnumMap<>(Property.class); private String _description = EMPTY_STRING; public ObjectProperties() { super(); } public ObjectProperties(Property property, String value) { super(); put(property, value); } public ObjectProperties(ObjectProperties copy) { super(); if (copy != null) { _properties.putAll(copy._properties); _attributeNames.addAll(copy._attributeNames); _description = copy._description; } } public ObjectProperties(String name) { super(); setName(name); } public ObjectProperties withDescription(String description) { _description = description == null ? EMPTY_STRING : description; return this; } public Object get(Property key) { return _properties.get(key); } public Map getAll() { return new EnumMap<>(_properties); } public void setName(String name) { _properties.put(Property.NAME, name == null ? EMPTY_STRING : name); } public void setCreatedBy(Object user) { if (user != null) { put(Property.CREATED_BY, user.toString()); } } public void setOwner(Object owner) { if (owner != null) { put(Property.OWNER, owner.toString()); } } public Set getAttributeNames() { return Collections.unmodifiableSet(_attributeNames); } public void addAttributeNames(Collection attributeNames) { if (attributeNames != null && !attributeNames.isEmpty()) { _attributeNames.addAll(attributeNames); } } public void addAttributeNames(String... attributeNames) { if (attributeNames != null && attributeNames.length > 0) { _attributeNames.addAll(Arrays.asList(attributeNames)); } } public Object put(Property key, String value) { return _properties.put(key, value == null ? EMPTY_STRING : value.trim()); } public Object put(Property key, boolean value) { return _properties.put(key, value); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o instanceof ObjectProperties) { final ObjectProperties that = (ObjectProperties) o; return _attributeNames.equals(that._attributeNames) && _properties.equals(that._properties); } return false; } @Override public int hashCode() { return 31 * _attributeNames.hashCode() + _properties.hashCode(); } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ObjectProperties["); final Joiner joiner = Joiner.on(","); if (!_properties.isEmpty()) { sb.append("properties=["); joiner.withKeyValueSeparator("=").appendTo(sb, _properties); sb.append("]"); } if (!_attributeNames.isEmpty()) { if (sb.length() > 1) { sb.append(","); } sb.append(Property.ATTRIBUTES.name()); sb.append("=["); joiner.appendTo(sb, _attributeNames); sb.append("]"); } if (!_description.isEmpty()) { if (sb.length() > 1) { sb.append(", "); } sb.append(_description); } sb.append("]"); return sb.toString(); } } src/main/java/org/spongepowered/asm/launch/platform/IMiximPlatformServiceAgent.java0 /* * This file is part of Mixim, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.asm.launch.platform; import java.util.Collection; import org.spongepowered.asm.launch.platform.container.IContainerHandle; import org.spongepowered.asm.mixim.MiximEnvironment.Phase; import org.spongepowered.asm.util.Constants; import org.spongepowered.asm.util.IConsumer; /** * Service agents provide additional platform-specific extensions leveraged by * mixim services. Implementing this interface on an agent class will cause an * additional instance to be spun up by the service. */ public interface IMiximPlatformServiceAgent extends IMiximPlatformAgent { /** * Perform initialisation-stage logic for this agent */ public abstract void init(); /** * Attempt to determine the side name from the current environment. Return * null if the side name cannot be determined by this agent. Return * side name or {@link Constants#SIDE_UNKNOWN} if the agent is able to * determine the side. */ public abstract String getSideName(); /** * Get environment-specific mixim containers */ public abstract Collection getMiximContainers(); /** * Temp wiring * * @param phase Initial phase * @param phaseConsumer Phase setter callback * @deprecated temporary */ @Deprecated public abstract void wire(Phase phase, IConsumer phaseConsumer); /** * Temp wiring - Called when the DEFAULT phase is started * @deprecated temporary */ @Deprecated public abstract void unwire(); } /* * 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.karaf.features.internal.service; import java.net.URI; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.karaf.features.Repository; import org.apache.karaf.features.internal.model.Features; /** * Implementation of {@link RepositoryCache} that makes use of {@link FeaturesProcessor} to alter feature * definitions after reading them from XML file. */ public class RepositoryCacheImpl implements RepositoryCache { private final Map repositoryCache = new HashMap<>(); private final FeaturesProcessor featuresProcessor; public RepositoryCacheImpl(FeaturesProcessor featuresProcessor) { this.featuresProcessor = featuresProcessor; } @Override public Repository create(URI uri, boolean validate) { if (featuresProcessor != null && featuresProcessor.isRepositoryBlacklisted(uri.toString())) { return new RepositoryImpl(uri, new Features(), true); } RepositoryImpl repository = new RepositoryImpl(uri, validate); if (featuresProcessor != null) { // maybe it could be done better - first we have to set if entire repo is blacklisted repository.setBlacklisted(featuresProcessor.isRepositoryBlacklisted(uri.toString())); // processing features will take the above flag into account to blacklist (if needed) the features repository.processFeatures(featuresProcessor); } return repository; } @Override public void addRepository(Repository repository) { String repoUriSt = repository.getURI().toString(); repositoryCache.put(repoUriSt, repository); } @Override public void removeRepository(URI repositoryUri) { List toRemove = new ArrayList<>(); toRemove.add(repositoryUri.toString()); while (!toRemove.isEmpty()) { Repository rep = repositoryCache.remove(toRemove.remove(0)); if (rep != null) { for (URI u : rep.getRepositories()) { toRemove.add(u.toString()); } } } } @Override public Repository[] listRepositories() { return repositoryCache.values().toArray(new Repository[repositoryCache.size()]); } @Override public Repository[] listMatchingRepositories(Set uris) { return repositoryCache.values().stream() .filter(r -> uris.contains(r.getURI().toString())) .toArray(Repository[]::new); } @Override public Repository getRepositoryByName(String name) { for (Repository repo : this.repositoryCache.values()) { if (name.equals(repo.getName())) { return repo; } } return null; } @Override public Repository getRepository(String uri) { return repositoryCache.get(uri); } /** * Returns a set containing the given repository and all its dependencies recursively */ @Override public Set getRepositoryClosure(Repository repo) { Set closure = new HashSet<>(); Deque remaining = new ArrayDeque<>(Collections.singleton(repo)); while (!remaining.isEmpty()) { Repository rep = remaining.removeFirst(); if (closure.add(rep)) { for (URI uri : rep.getRepositories()) { remaining.add(getRepository(uri.toString())); } } } return closure; } } package nl.knokko.customitems.drops; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import nl.knokko.customitems.encoding.DropEncoding; import nl.knokko.customitems.item.CustomItem; import nl.knokko.customitems.trouble.UnknownEncodingException; import nl.knokko.customitems.util.ExceptionSupplier; import nl.knokko.util.bits.BitInput; import nl.knokko.util.bits.BitOutput; public class BlockDrop { public static BlockDrop load( BitInput input, BiFunction createCustomItemResultByName, ExceptionSupplier loadResult, Function getCustomItemByName ) throws UnknownEncodingException { byte encoding = input.readByte(); if (encoding == DropEncoding.Block.ENCODING1) return load1(input, createCustomItemResultByName); else if (encoding == DropEncoding.Block.ENCODING2) return load2(input, loadResult, getCustomItemByName); else throw new UnknownEncodingException("BlockDrop", encoding); } private static BlockDrop load1( BitInput input, BiFunction createCustomItemResultByName) { return new BlockDrop( BlockType.getByOrdinal(input.readInt()), false, Drop.load1(input, createCustomItemResultByName) ); } private static BlockDrop load2( BitInput input, ExceptionSupplier loadResult, Function getCustomItemByName ) throws UnknownEncodingException { return new BlockDrop( BlockType.getByOrdinal(input.readInt()), input.readBoolean(), Drop.load2(input, loadResult, getCustomItemByName) ); } private BlockType block; private boolean allowSilkTouch; private Drop drop; public BlockDrop(BlockType block, boolean allowSilkTouch, Drop drop) { this.block = block; this.drop = drop; this.allowSilkTouch = allowSilkTouch; } @Override public String toString() { return drop + " for block " + block; } public void save(BitOutput output, Consumer saveResult) { save2(output, saveResult); } /* protected void save1(BitOutput output) { output.addByte(DropEncoding.Block.ENCODING1); output.addInt(block.ordinal()); drop.save1(output); }*/ protected void save2(BitOutput output, Consumer saveResult) { output.addByte(DropEncoding.Block.ENCODING2); output.addInt(block.ordinal()); output.addBoolean(allowSilkTouch); drop.save2(output, saveResult); } public BlockType getBlock() { return block; } public boolean allowSilkTouch() { return allowSilkTouch; } public Drop getDrop() { return drop; } public void setBlock(BlockType newBlock) { block = newBlock; } public void setDrop(Drop newDrop) { drop = newDrop; } public void setAllowSilkTouch(boolean allowSilk) { allowSilkTouch = allowSilk; } } package org.hope6537.note.tij.seventeen; import java.util.ArrayList; public class CollectionMethods { public static void main(String[] args) { ArrayList list = new ArrayList(), subList = new ArrayList(); for (int i = 0; i < 10; i++) { list.add(i); if (i < 5) { subList.add(i); } } System.out.println(list.removeAll(subList)); System.out.println(list); } } package com.arvifox.jaxb; /** * Created by Andrey on 06.12.2016. */ public class Block { } package com.feeyo.net.codec.http.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.ByteBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.feeyo.net.codec.protobuf.ProtobufEncoder; import com.feeyo.net.codec.protobuf.test.Eraftpb.ConfState; import com.feeyo.net.codec.protobuf.test.Eraftpb.Entry; import com.feeyo.net.codec.protobuf.test.Eraftpb.EntryType; import com.feeyo.net.codec.protobuf.test.Eraftpb.Message; import com.feeyo.net.codec.protobuf.test.Eraftpb.MessageType; import com.feeyo.net.codec.protobuf.test.Eraftpb.Snapshot; import com.feeyo.net.codec.protobuf.test.Eraftpb.SnapshotMetadata; import com.feeyo.util.Log4jInitializer; import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; public class HttpClientTest { private final Logger LOGGER = LoggerFactory.getLogger(HttpClientTest.class); private static final String verbUserAgent = System.getProperty("java.home") + ";" + System.getProperty("java.vendor") + ";" + System.getProperty("java.version") + ";" + System.getProperty("user.name"); public HttpResponse post(String url, byte[] data) { HttpResponse response = null; HttpURLConnection con = null; BufferedReader br = null; try { URL urlObj = new URL(url); con = (HttpURLConnection) urlObj.openConnection(); con.setUseCaches(false); con.setDoOutput(true); con.setDoInput(true); con.setInstanceFollowRedirects(false); con.setConnectTimeout(10000); con.setReadTimeout(5000); con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", verbUserAgent); con.setRequestProperty("Connection", "close"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Length", Integer.toString(data.length)); con.getOutputStream().write(data, 0, data.length); con.getOutputStream().flush(); int responseCode = con.getResponseCode(); StringBuffer responseTxtBuffer = new StringBuffer(); br = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; while ((inputLine = br.readLine()) != null) { responseTxtBuffer.append(inputLine); } response = new HttpResponse(responseCode, responseTxtBuffer.toString()); if (responseCode != HttpURLConnection.HTTP_OK) { LOGGER.error(responseTxtBuffer.toString()); } } catch (IOException e) { e.printStackTrace(); LOGGER.error(e.getMessage()); } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } if (con != null) { con.disconnect(); } } return response; } public void post(String url, Message msg) { if(msg == null ) return; ProtobufEncoder encoder = new ProtobufEncoder(false); ByteBuffer protoBufs = encoder.encode(msg); HttpResponse response = post(url, protoBufs.array()); if ( response != null && response.getCode() == 200) { System.out.println("send success !"); System.out.println(response.getResponseTxt()); } } public class HttpResponse { private int code; private String responseTxt; public HttpResponse(int code, String responseTxt) { super(); this.code = code; this.responseTxt = responseTxt; } public int getCode() { return code; } public String getResponseTxt() { return responseTxt; } } public static void main(String[] args) { if (System.getProperty("FEEYO_HOME") == null) { System.setProperty("FEEYO_HOME", System.getProperty("user.dir")); } // 设置 LOG4J Log4jInitializer.configureAndWatch(System.getProperty("FEEYO_HOME"), "log4j.xml", 30000L); Entry entry0 = Entry.newBuilder().setContext(ByteString.copyFromUtf8("Entry" + 1)) .setData(ByteString.copyFromUtf8("Entry " + 1)).setEntryType(EntryType.EntryNormal).setEntryTypeValue(0) .setIndex(1).setSyncLog(false).setTerm(20).setUnknownFields(UnknownFieldSet.getDefaultInstance()) .build(); ConfState state = ConfState.newBuilder().addLearners(100).addLearners(101).addNodes(102).addNodes(103) .setUnknownFields(UnknownFieldSet.getDefaultInstance()).build(); SnapshotMetadata metadata = SnapshotMetadata.newBuilder().setConfState(state).setIndex(1).setTerm(20) .setUnknownFields(UnknownFieldSet.getDefaultInstance()).build(); Snapshot snapshot = Snapshot.newBuilder().setData(ByteString.copyFromUtf8("snapshot" + 1)).setMetadata(metadata) .setUnknownFields(UnknownFieldSet.getDefaultInstance()).build(); Message msg = Message.newBuilder().setMsgType(MessageType.MsgAppend).setTo(9000).setFrom(1000).setTerm(20) .setLogTerm(30).setIndex(1).addEntries(entry0).setCommit(123).setSnapshot(snapshot).setReject(true) .setRejectHint(1).setContext(ByteString.copyFromUtf8("message" + 1)).build(); HttpClientTest test = new HttpClientTest(); test.post("http://192.168.14.158:8066/proto/eraftpb/message", msg); } } 0 package it.nextworks.nfvmano.libs.descriptors.sol006; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; import java.util.List; import org.springframework.validation.annotation.Validated; /** * Describes the configurable properties of the VNF (e.g. related to auto scaling and auto healing). */ //@Schema(description = "Describes the configurable properties of the VNF (e.g. related to auto scaling and auto healing).") @javax.annotation.Generated(value = "io.swagger.codegen.v3.generators.java.SpringCodegen", date = "2021-03-09T19:09:38.446+01:00[Europe/Rome]") public class ConfigurablePropertiesSchema { @JsonProperty("is-auto-scalable-enabled") private Boolean isAutoScalableEnabled = null; @JsonProperty("is-auto-heal-enabled") private Boolean isAutoHealEnabled = null; @JsonProperty("additional-configurable-property") private List additionalConfigurableProperty = null; public ConfigurablePropertiesSchema isAutoScalableEnabled(Boolean isAutoScalableEnabled) { this.isAutoScalableEnabled = isAutoScalableEnabled; return this; } /** * It permits to enable (TRUE) / disable (FALSE) the auto-scaling functionality. * @return isAutoScalableEnabled **/ //@Schema(description = "It permits to enable (TRUE) / disable (FALSE) the auto-scaling functionality.") public Boolean isIsAutoScalableEnabled() { return isAutoScalableEnabled; } public void setIsAutoScalableEnabled(Boolean isAutoScalableEnabled) { this.isAutoScalableEnabled = isAutoScalableEnabled; } public ConfigurablePropertiesSchema isAutoHealEnabled(Boolean isAutoHealEnabled) { this.isAutoHealEnabled = isAutoHealEnabled; return this; } /** * It permits to enable (TRUE) / disable (FALSE) the auto-healing functionality. * @return isAutoHealEnabled **/ //@Schema(description = "It permits to enable (TRUE) / disable (FALSE) the auto-healing functionality.") public Boolean isIsAutoHealEnabled() { return isAutoHealEnabled; } public void setIsAutoHealEnabled(Boolean isAutoHealEnabled) { this.isAutoHealEnabled = isAutoHealEnabled; } public ConfigurablePropertiesSchema additionalConfigurableProperty(List additionalConfigurableProperty) { this.additionalConfigurableProperty = additionalConfigurableProperty; return this; } public ConfigurablePropertiesSchema addAdditionalConfigurablePropertyItem(VnfdVdustoragerequirements additionalConfigurablePropertyItem) { if (this.additionalConfigurableProperty == null) { this.additionalConfigurableProperty = new ArrayList(); } this.additionalConfigurableProperty.add(additionalConfigurablePropertyItem); return this; } /** * It provides VNF specific configurable properties that can be modified using the ModifyVnfConfiguration operation. * @return additionalConfigurableProperty **/ //@Schema(description = "It provides VNF specific configurable properties that can be modified using the ModifyVnfConfiguration operation.") public List getAdditionalConfigurableProperty() { return additionalConfigurableProperty; } public void setAdditionalConfigurableProperty(List additionalConfigurableProperty) { this.additionalConfigurableProperty = additionalConfigurableProperty; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConfigurablePropertiesSchema configurablePropertiesSchema = (ConfigurablePropertiesSchema) o; return Objects.equals(this.isAutoScalableEnabled, configurablePropertiesSchema.isAutoScalableEnabled) && Objects.equals(this.isAutoHealEnabled, configurablePropertiesSchema.isAutoHealEnabled) && Objects.equals(this.additionalConfigurableProperty, configurablePropertiesSchema.additionalConfigurableProperty); } @Override public int hashCode() { return Objects.hash(isAutoScalableEnabled, isAutoHealEnabled, additionalConfigurableProperty); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ConfigurablePropertiesSchema {\n"); sb.append(" isAutoScalableEnabled: ").append(toIndentedString(isAutoScalableEnabled)).append("\n"); sb.append(" isAutoHealEnabled: ").append(toIndentedString(isAutoHealEnabled)).append("\n"); sb.append(" additionalConfigurableProperty: ").append(toIndentedString(additionalConfigurableProperty)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } src/main/java/befaster/solutions/SUM/SumSolution.java package befaster.solutions.SUM; public class SumSolution { private static final int MIN = 0; private static final int MAX = 100; public Integer compute(Integer x, Integer y) { if(x == null || y == null){ throw new IllegalArgumentException("compute: one or more parameters is null"); } if(! parameterWithinRange(x) || !parameterWithinRange(y)){ throw new IllegalArgumentException("compute: one or more parameters exceed min/max range"); } return x + y; } private boolean parameterWithinRange(int input){ if(input < MIN || input > MAX){ return false; } return true; } }/* * 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 qlikapi; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * A simple class that lets us look at the contents of the response from * a Qlik API request. Responses are somewhat inconsistent in their formatting, so * we will use convenience methods to short-circuit some of the interpretation. */ public class JsonResponse { private static final Logger LOG = LoggerFactory.getLogger(JsonResponse.class); private String response; private ObjectMapper mapper; private JsonNode rootNode; /** * Creates an instance. * @param response the Json response from an API call. */ public JsonResponse(String response) { this.response = response; mapper = new ObjectMapper(); try { rootNode = mapper.readTree(response); } catch (IOException e) { LOG.error("Json parse error", e); } } /** * Looks to see if we have a node in the tree called "error" * and returns true if so. * @return true if there is an error node. False otherwise. */ public boolean isError() { boolean rval = false; if (rootNode.findValue("error") != null) { rval = true; } return rval; } /** * Presumptive method that assumes we have the error node, which should * be the case if isError() returned true. * @return Returns an error message from the response. */ public String getError() { JsonNode error = rootNode.findValue("error"); int code = error.findValue("code").asInt(); String message = error.findValue("message").asText(); return String.format("Qlik API Error: %d: %s", code, message); } /** * Presumptive method that assumes that qHandle will be present if we * are calling it. * @return qHandle from an OpenDoc request. */ public int getqHandle() { return rootNode.findValue("qHandle").asInt(); } } /* * 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.arrow.consumers; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.arrow.vector.VarCharVector; import org.apache.arrow.vector.complex.impl.VarCharWriterImpl; import org.apache.arrow.vector.complex.writer.VarCharWriter; import org.apache.arrow.vector.holders.VarCharHolder; import org.apache.avro.io.Decoder; /** * Consumer which consume string type values from avro decoder. * Write the data to {@link VarCharVector}. */ public class AvroStringConsumer implements Consumer { private final VarCharVector vector; private final VarCharWriter writer; public AvroStringConsumer(VarCharVector vector) { this.vector = vector; this.writer = new VarCharWriterImpl(vector); } @Override public void consume(Decoder decoder) throws IOException { VarCharHolder holder = new VarCharHolder(); ByteBuffer byteBuffer = decoder.readBytes(null); holder.start = 0; holder.end = byteBuffer.capacity(); holder.buffer = vector.getAllocator().buffer(byteBuffer.capacity()); holder.buffer.setBytes(0, byteBuffer); writer.write(holder); writer.setPosition(writer.getPosition() + 1); } } package lt.lb.prebuiltcollections.readonly; import java.util.NavigableSet; /** * * @author laim0nas100 */ public interface ReadOnlyNavigableSet extends ReadOnlySet, NavigableSet { @Override public default T pollFirst() { throw new UnsupportedOperationException("Read only instance of " + getClass()); } @Override public default T pollLast() { throw new UnsupportedOperationException("Read only instance of " + getClass()); } } package com.umiwi.ui.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Paint; import android.util.AttributeSet; import android.util.TypedValue; import android.widget.TextView; import com.umiwi.ui.R; /** * @author tangxiyong * @version 2014年7月25日 上午11:16:39 */ public class AutoScaleTextView extends TextView { private Paint textPaint; private float preferredTextSize; private float minTextSize; private double mHeightRatio; private double mWidthRatio; public AutoScaleTextView(Context context) { super(context); init(context, null); } public AutoScaleTextView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public AutoScaleTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs); } private void init(Context context, AttributeSet attrs) { this.textPaint = new Paint(); TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.AutoScaleTextView); this.minTextSize = a.getDimension(R.styleable.AutoScaleTextView_minTextSize, 10f); a.recycle(); this.preferredTextSize = this.getTextSize(); } // set view width & height public void setWidthAndHeight(double width, double height) { if (width != mWidthRatio) { mWidthRatio = width; } if (height != mHeightRatio) { mHeightRatio = height; } requestLayout(); } public double getHeightRatio() { return mHeightRatio; } public double getmWidthRatio() { return mWidthRatio; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mWidthRatio > 0.0) { // set the image views size // int width = MeasureSpec.getSize(widthMeasureSpec); // int height = (int) (width * mHeightRatio); int width = (int) mWidthRatio; int height = (int) mHeightRatio; setMeasuredDimension(width, height); } else { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } } // =============autoscaletext=========== public void setMinTextSize(float minTextSize) { this.minTextSize = minTextSize; } /*** * 如果 text 是要从网络获取的,不要在xml 里写上默认的text * @param text * @param textWidth */ private void refitText(String text, int textWidth) { if (textWidth <= 0 || text == null || text.length() == 0) return; int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight(); final float threshold = 0.5f; this.textPaint.set(this.getPaint()); while ((this.preferredTextSize - this.minTextSize) > threshold) { float size = (this.preferredTextSize + this.minTextSize) / 2; this.textPaint.setTextSize(size); if (this.textPaint.measureText(text) >= targetWidth) this.preferredTextSize = size; // big else this.minTextSize = size; // small } this.setTextSize(TypedValue.COMPLEX_UNIT_PX, this.minTextSize); } @Override protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) { this.refitText(text.toString(), this.getWidth()); } @Override protected void onSizeChanged(int width, int height, int oldwidth, int oldheight) { if (width != oldwidth) this.refitText(this.getText().toString(), width); } } ton31337/batfish package org.batfish.vendor.check_point_management; /** Test instances shared with other modules. */ public final class TestSharedInstances { /** * Instance of this class populated with arbitrary values. Useful for generating a valid object * for use in tests. */ public static final NatSettings NAT_SETTINGS_TEST_INSTANCE = new NatSettings(true, NatHideBehindGateway.INSTANCE, "All", null, NatMethod.HIDE); } Enoughsdv/2FA package com.lielamar.auth.bungee.listeners; import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteArrayDataOutput; import com.google.common.io.ByteStreams; import com.lielamar.auth.bungee.TwoFactorAuthentication; import com.lielamar.auth.shared.communication.AuthCommunicationHandler; import com.lielamar.auth.shared.handlers.AuthHandler; import com.lielamar.auth.shared.utils.Constants; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.PluginMessageEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.event.EventHandler; import java.io.*; import java.util.UUID; @SuppressWarnings("UnstableApiUsage") public class OnPluginMessage implements Listener { private final TwoFactorAuthentication plugin; public OnPluginMessage(TwoFactorAuthentication plugin) { this.plugin = plugin; } @EventHandler public void onQueryReceive(PluginMessageEvent event) { // If the Channel name is not the 2FA's Channel name we want to return if (!event.getTag().equals(Constants.PROXY_CHANNEL_NAME)) { return; } ByteArrayDataInput msg = ByteStreams.newDataInput(event.getData()); String subChannel = msg.readUTF(); // If the SubChannel name is the 2FA's SubChannel name if (subChannel.equals(Constants.PROXY_SUB_CHANNEL_NAME)) { UUID messageUUID = UUID.fromString(msg.readUTF()); UUID playerUUID = UUID.fromString(msg.readUTF()); ProxiedPlayer player = ProxyServer.getInstance().getPlayer(playerUUID); short bodyLength = msg.readShort(); byte[] msgBody = new byte[bodyLength]; msg.readFully(msgBody); DataInputStream msgBodyData = new DataInputStream(new ByteArrayInputStream(msgBody)); try { AuthCommunicationHandler.MessageType messageType = AuthCommunicationHandler.MessageType.valueOf(msgBodyData.readUTF()); if (messageType == AuthCommunicationHandler.MessageType.SET_STATE) { AuthHandler.AuthState state = AuthHandler.AuthState.valueOf(msgBodyData.readUTF()); this.plugin.getAuthHandler().changeState(player.getUniqueId(), state); } this.sendResponse(messageUUID, player, messageType); } catch (IOException exception) { exception.printStackTrace(); } } } public void sendResponse(UUID messageUUID, ProxiedPlayer player, AuthCommunicationHandler.MessageType messageType) { AuthHandler.AuthState authState = this.plugin.getAuthHandler().getAuthState(player.getUniqueId()); ByteArrayDataOutput response = ByteStreams.newDataOutput(); response.writeUTF(Constants.PROXY_SUB_CHANNEL_NAME); response.writeUTF(messageUUID.toString()); response.writeUTF(player.getUniqueId().toString()); ByteArrayOutputStream msgBody = new ByteArrayOutputStream(); DataOutputStream msgBodyData = new DataOutputStream(msgBody); try { msgBodyData.writeUTF(messageType.name()); msgBodyData.writeUTF(authState.name()); } catch (IOException exception) { exception.printStackTrace(); } response.writeShort(msgBody.toByteArray().length); response.write(msgBody.toByteArray()); player.getServer().getInfo().sendData(Constants.PROXY_CHANNEL_NAME, response.toByteArray()); } } rhuangal/jpa-servlet-example0 package org.app.example.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * * @author rober */ @Entity @Table(name = "tb_usuario") public class Usuario implements Serializable { private String codigo; private String password; @Id @Column(length = 8, name = "codigo", nullable = false) public String getCodigo() { return codigo; } public void setCodigo(String codigo) { this.codigo = codigo; } @Column(length = 150, name = "password", nullable = false) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } Service/src/main/java/com/zhzteam/zhz233/controller/zlb/GoodsController.java package com.zhzteam.zhz233.controller.zlb; import com.zhzteam.zhz233.common.config.StatusConfig; import com.zhzteam.zhz233.model.zlb.GoodsResult; import com.zhzteam.zhz233.model.zlb.ResultView; import com.zhzteam.zhz233.service.zlb.impl.GoodsServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping(value = "/zlb") public class GoodsController { @Autowired GoodsServiceImpl goodsServiceImpl; private ResultView resultView; private List goodsResultList; private Map reMap; @RequestMapping(value = "/getGoodsInfo") public ResultView getGoodsInfo(){ //初始化 容器 resultView = new ResultView(); goodsResultList = new ArrayList(); reMap = new HashMap(); //放置商品信息 goodsResultList = goodsServiceImpl.selectTByKey(0,0,0,10); reMap.put("goodsResultList",goodsResultList); if(!reMap.isEmpty()){ resultView.setReMap(reMap); resultView.setStatus(StatusConfig.SUCCESS); resultView.setMessage("获取商品信息成功!"); }else{ resultView.setStatus(StatusConfig.FAIL); resultView.setMessage("获取商品信息失败!"); } return resultView; } } package android.support.v7.widget; class cg implements Runnable { final /* synthetic */ by f1444a; private cg(by byVar) { this.f1444a = byVar; } public void run() { this.f1444a.m2580j(); } } src/main/java/com/simibubi/create/content/contraptions/relays/encased/AbstractEncasedShaftBlock.java package com.simibubi.create.content.contraptions.relays.encased; import com.simibubi.create.content.contraptions.base.RotatedPillarKineticBlock; import com.simibubi.create.registrate.util.nullness.MethodsReturnNonnullByDefault; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.block.piston.PistonBehavior; import net.minecraft.item.ItemPlacementContext; import net.minecraft.state.StateManager; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.BlockView; import net.minecraft.world.WorldView; @MethodsReturnNonnullByDefault public abstract class AbstractEncasedShaftBlock extends RotatedPillarKineticBlock { public AbstractEncasedShaftBlock(Settings properties) { super(properties); } @Override protected void appendProperties(StateManager.Builder builder) { super.appendProperties(builder); } @Override public int getWeakRedstonePower(BlockState state, BlockView world, BlockPos pos, Direction direction) { return 0; } /*@Override public boolean shouldCheckWeakPower(BlockState state, IWorldReader world, BlockPos pos, Direction side) { return false; }*/ @Override public PistonBehavior getPistonBehavior(BlockState state) { return PistonBehavior.NORMAL; } @Override public BlockState getPlacementState(ItemPlacementContext context) { if (context.getPlayer() != null && context.getPlayer() .isSneaking()) return super.getPlacementState(context); Direction.Axis preferredAxis = getPreferredAxis(context); return this.getDefaultState() .with(AXIS, preferredAxis == null ? context.getPlayerLookDirection() .getAxis() : preferredAxis); } @Override public boolean hasShaftTowards(WorldView world, BlockPos pos, BlockState state, Direction face) { return face.getAxis() == state.get(AXIS); } @Override public Direction.Axis getRotationAxis(BlockState state) { return state.get(AXIS); } } /* * 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 de.javakaffee.web.msm.storage; import static org.testng.Assert.*; import java.lang.reflect.Method; import java.nio.charset.StandardCharsets; import org.testng.annotations.*; import redis.embedded.RedisServer; /** * Test the {@link RedisStorageClient}. * * @author */ public class RedisStorageClientTest { private RedisServer embeddedRedisServer; private boolean redisProvided; private int redisPort; @BeforeMethod public void setUp(final Method testMethod) throws Exception { redisProvided = Boolean.parseBoolean(System.getProperty("redis.provided", "false")); redisPort = Integer.parseInt(System.getProperty("redis.port", "16379")); if (!redisProvided) { embeddedRedisServer = new RedisServer(redisPort); embeddedRedisServer.start(); } } @AfterMethod public void tearDown() throws Exception { if (embeddedRedisServer != null) { embeddedRedisServer.stop(); embeddedRedisServer = null; } } @Test public void testFunctions() throws Exception { RedisStorageClient client = createClient(); // Add two keys assertTrue(client.add("key1", 0, toBytes("foo")).get()); assertTrue(client.add("key2", 0, toBytes("bar")).get()); // Check that the keys have the given value assertEquals("foo", toString(client.get("key1"))); assertEquals("bar", toString(client.get("key2"))); // Check difference between add() and set() assertTrue(client.set("key1", 0, toBytes("baz")).get()); assertFalse(client.add("key2", 0, toBytes("zoom")).get()); assertEquals("baz", toString(client.get("key1"))); assertEquals("bar", toString(client.get("key2"))); // Delete key, make sure it is not accessible anymore, but other key should still be there assertTrue(client.delete("key1").get()); assertNull(client.get("key1")); assertEquals("bar", toString(client.get("key2"))); client.shutdown(); } @Test public void testExpirationSeconds() throws Exception { RedisStorageClient client = createClient(); // Add a key which expires assertTrue(client.add("exp", 2, toBytes("foo")).get()); // Wait some time Thread.sleep(1000); // Key should still be there assertEquals("foo", toString(client.get("exp"))); // Wait some more time Thread.sleep(2000); // Now key should be expired assertNull(client.get("exp")); client.shutdown(); } @Test public void testExpirationTime() throws Exception { RedisStorageClient client = createClient(); // Add a key which expires assertTrue(client.add("exp", (int)(2 + (System.currentTimeMillis() / 1000)), toBytes("foo")).get()); assertEquals("foo", toString(client.get("exp"))); // Wait some time Thread.sleep(1000); // Key should still be there assertEquals("foo", toString(client.get("exp"))); // Wait some more time Thread.sleep(2000); // Now key should be expired assertNull(client.get("exp")); client.shutdown(); } @Test public void testAutoReconnect() throws Exception { RedisStorageClient client = createClient(); // Issue a command to create a connection assertTrue(client.add("key1", 0, toBytes("foo")).get()); assertEquals("foo", toString(client.get("key1"))); // Stop and start server to close all connections if (!redisProvided) { embeddedRedisServer.stop(); embeddedRedisServer.start(); } // If we now issue commands, the old connection is defunct and will be replaced assertTrue(client.add("key1", 0, toBytes("foo")).get()); assertEquals("foo", toString(client.get("key1"))); client.shutdown(); } private RedisStorageClient createClient() { return new RedisStorageClient("redis://localhost:" + redisPort, 1000); } private byte[] toBytes(String s) { return s.getBytes(StandardCharsets.UTF_8); } private String toString(byte[] bytes) { return new String(bytes, StandardCharsets.UTF_8); } } package com.andcreations.ae.studio.plugins.file; import java.io.File; import java.util.ArrayList; import java.util.List; /** * @author */ public class EditedFile { /** */ private static EditedFile instance; /** */ private File lastEditedFile; /** */ private List listeners = new ArrayList<>(); /** */ public void setLastEditedFile(File lastEditedFile) { this.lastEditedFile = lastEditedFile; synchronized (listeners) { for (EditedFileListener listener:listeners) { listener.editedFileChanged(lastEditedFile); } } } /** */ public File getLastEditedFile() { return lastEditedFile; } /** */ public void addEditedFileListener(EditedFileListener listener) { synchronized (listeners) { listeners.add(listener); } } /** */ public static EditedFile get() { if (instance == null) { instance = new EditedFile(); } return instance; } }package app.view.console; import app.model.enums.OperatingSystems; import app.utils.Log; import app.utils.Utils; import org.slf4j.Logger; import static app.utils.ConsoleWorker.*; class ConsoleWelcome { private ConsoleView view; private static final Logger LOG = Log.createLog(ConsoleWelcome.class); ConsoleWelcome(ConsoleView view) { this.view = view; } void init() { LOG.debug(Log.APP_IS_READY); clearScreen(); print("\n"); println("+-----------------------------------------------+"); println("\t" + Log.WELCOME_CONSOLE + "\t"); println("+-----------------------------------------------+"); print("\n"); println("\t " + Log.CHOICE_OS + ":\n"); for (int i = 0; i < OperatingSystems.values().length; i++) { println("\t\t" + (i + 1) + ". " + OperatingSystems.values()[i] + "\t"); } println("\n+-----------------------------------------------+"); while (true) { print("\n" + Log.ENTER); switch (readLine().toLowerCase()) { case "1": case "1.": case "w": case "windows": case "win": if (!Utils.isWindows()) { println(Log.NOT_WINDOWS_OS); LOG.warn(Log.WRONG_OS); break; } view.setOperatingSystem(OperatingSystems.WINDOWS); break; case "2": case "2.": case "linux": case "lin": case "l": if (!Utils.isLinux()) { println(Log.NOT_LINUX_OS); LOG.warn(Log.WRONG_OS); break; } view.setOperatingSystem(OperatingSystems.LINUX); break; case "3": case "3.": case "m": case "mac": if (!Utils.isMac()) { println(Log.NOT_MAC_OS); LOG.warn(Log.WRONG_OS); break; } view.setOperatingSystem(OperatingSystems.MAC); break; default: println(Log.WRONG_ENTER); } if (view.getOperatingSystem() != null) { break; } } LOG.debug(Log.VALID_OS); println(Log.VALID_OS); update(); } private void update() { view.renderMenu(); } private void clearScreen() { for (int i = 0; i < 500; i++) { System.out.println(); } } } package com.xy.asyc.test.temp; import java.util.concurrent.ExecutorService; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; public class Asyn4jContext { protected final AtomicBoolean run = new AtomicBoolean(false); protected Semaphore semaphore; public static final long ADD_JOB_WAITTIME = 5L; protected ExecutorService workExecutor = null; protected final AtomicLong TASK_TOTAL = new AtomicLong(0); public void addAsynWork(AsynWork asynWork){ if (!run.get()) { throw new Asyn4jException("asyn service is stop or no start!"); } if (asynWork == null) { throw new Asyn4jException("asynWork is null"); } try { if(semaphore.tryAcquire(ADD_JOB_WAITTIME, TimeUnit.MILLISECONDS)){ } } catch (InterruptedException e) { e.printStackTrace(); } } } 0 package us.kbase.workspace.modules; import static java.util.Objects.requireNonNull; import static us.kbase.workspace.database.Util.checkString; import java.time.Instant; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.KafkaException; import org.apache.kafka.common.serialization.Serializer; import org.apache.kafka.common.serialization.StringSerializer; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import us.kbase.workspace.database.ObjectInformation; import us.kbase.workspace.database.Permission; import us.kbase.workspace.database.WorkspaceUser; import us.kbase.workspace.kbase.KBasePermissions; import us.kbase.workspace.listener.ListenerInitializationException; import us.kbase.workspace.listener.WorkspaceEventListener; import us.kbase.workspace.listener.WorkspaceEventListenerFactory; /** A workspace listener that sends workspace events to Kafka as JSON strings: * *
 * {
 *   "user": <the user that triggered the event.
 *        May be null if the user is an administrator>,
 *   "wsid": <the workspace id of the workspace involved in the event>,
 *   "objid": <the object id of the object involved in the event. May be null>
 *   "ver": <the version of the object involved in the event. May be null>
 *   "time": <the time the event took place in epoch milliseconds>
 *   "evtype": <the event type. See the class constants for types>
 *   "objtype": <the type of the object involved in the event. May be null>
 *   "perm": <the permission set for one or more users. May be null>
 *   "permusers": <the list of users for whom permissions were altered. May be empty>
 * } 
 * 
* * Null values are present for events where providing the value doesn't make sense; for example * {@link WorkspaceEventListener#copyObject(WorkspaceUser, long, long, int, Instant, boolean)} * will not provide a version, object type, permission, or user list. * * The listener requires two configuration arguments: * topic - the topic to which the listener will submit events. The listener requires the topic * name to consist of ASCII alphanumeric values and the hyphen to avoid Kafka issues around * ambiguity between period and underscore values. * bootstrap.servers - the Kafka bootstrap servers. * * The listener is configured to require a full write to all the replicates before a call * to Kafka returns, and if a write fails, an exception is thrown in the thread that called * the listener. * * @author * */ public class KafkaNotifierFactory implements WorkspaceEventListenerFactory { // TODO TEST integration tests w/ just client & also full group server /* This implementation does things that slow down the send operation but improve * reliability and user messaging: * 1) Require full write to replicates before Kafka returns * 2) Wait for the return and check it worked. If not, throw an exception *in the calling * thread*. Thus the user is notified if something goes wrong. * * If this turns out to be a bad plan, we may need to relax those requirements. * * To improve reliability further, we'd need persistent storage of unsent messages. */ private static final String KAFKA = "Kafka"; private static final String KCFG_BOOSTRAP_SERVERS = "bootstrap.servers"; // may want to split events into different topics private static final String TOPIC = "topic"; private static final String KAFKA_WS_TOPIC = KAFKA + " " + TOPIC; /** The event type sent by the * {@link WorkspaceEventListener#saveObject(ObjectInformation, boolean)}, * {@link WorkspaceEventListener#copyObject(ObjectInformation, boolean)}, and * {@link WorkspaceEventListener#revertObject(ObjectInformation, boolean)} * methods. */ public static final String NEW_VERSION = "NEW_VERSION"; /** The event type sent by the * {@link WorkspaceEventListener#copyObject(WorkspaceUser, long, long, int, Instant, boolean)} * method. */ public static final String COPY_OBJECT = "COPY_OBJECT"; /** The event type sent by the * {@link WorkspaceEventListener#cloneWorkspace(WorkspaceUser, long, boolean, Instant)} * method. */ public static final String CLONE_WORKSPACE = "CLONE_WORKSPACE"; /** The event type sent by the * {@link WorkspaceEventListener#renameObject(WorkspaceUser, long, long, String, Instant)} * method. */ public static final String RENAME_OBJECT = "RENAME_OBJECT"; /** The event type sent by the * {@link WorkspaceEventListener#setObjectsHidden(WorkspaceUser, long, long, boolean, Instant)} * method. */ public static final String OBJECT_HIDE_STATE_CHANGE = "OBJECT_HIDE_STATE_CHANGE"; /** The event type sent by the * {@link WorkspaceEventListener#setObjectDeleted(WorkspaceUser, long, long, boolean, Instant)} * method. */ public static final String OBJECT_DELETE_STATE_CHANGE = "OBJECT_DELETE_STATE_CHANGE"; /** The event type sent by the * {@link WorkspaceEventListener#createWorkspace(WorkspaceUser, long, Instant)}, * {@link WorkspaceEventListener#lockWorkspace(WorkspaceUser, long, Instant)}, * {@link WorkspaceEventListener#renameWorkspace(WorkspaceUser, long, String, Instant)}, * {@link WorkspaceEventListener#setWorkspaceDescription(WorkspaceUser, long, Instant)}, * {@link WorkspaceEventListener#setWorkspaceMetadata(WorkspaceUser, long, Instant)}, * and {@link WorkspaceEventListener#setWorkspaceOwner(WorkspaceUser, long, WorkspaceUser, Optional, Instant)} * events. */ public static final String WORKSPACE_STATE_CHANGE = "WORKSPACE_STATE_CHANGE"; /** The event type sent by the * {@link WorkspaceEventListener#setWorkspaceDeleted(WorkspaceUser, long, boolean, long, Instant)} * method. */ public static final String WORKSPACE_DELETE_STATE_CHANGE = "WORKSPACE_DELETE_STATE_CHANGE"; /** The event type sent by the * {@link WorkspaceEventListener#setPermissions(WorkspaceUser, long, Permission, List, Instant)} * method. */ public static final String SET_PERMISSION = "SET_PERMISSION"; /** The event type sent by the * {@link WorkspaceEventListener#setGlobalPermission(WorkspaceUser, long, Permission, Instant)} * method. */ public static final String SET_GLOBAL_PERMISSION = "SET_GLOBAL_PERMISSION"; // https://stackoverflow.com/questions/37062904/what-are-apache-kafka-topic-name-limitations // Don't include . and _ because of // https://github.com/mcollina/ascoltatori/issues/165#issuecomment-267314016 private final static Pattern INVALID_TOPIC_CHARS = Pattern.compile("[^a-zA-Z0-9-]+"); @Override public WorkspaceEventListener configure(final Map cfg) throws ListenerInitializationException { requireNonNull(cfg, "cfg"); //TODO KAFKA support other config options (ssl etc). Unfortunately will have to parse each key individually as different types are required. final Map kcfg = new HashMap<>(); final String topic = (String) cfg.get(TOPIC); final String bootstrapServers = cfg.get(KCFG_BOOSTRAP_SERVERS); checkString(bootstrapServers, KAFKA + " " + KCFG_BOOSTRAP_SERVERS); // maybe make this config accessible in the factory so it can be tested in integration tests kcfg.put(KCFG_BOOSTRAP_SERVERS, bootstrapServers); kcfg.put("acks", "all"); kcfg.put("enable.idempotence", true); kcfg.put("delivery.timeout.ms", 30000); return new KafkaNotifier( topic, bootstrapServers, new KafkaProducer<>(kcfg, new StringSerializer(), new MapSerializer())); } /** A Kafka JSON serializer for arbitrary maps. Requires no configuration. The topic * argument in the {@link #serialize(String, Map) method is ignored. * @author * */ public static class MapSerializer implements Serializer> { private static final ObjectMapper MAPPER = new ObjectMapper(); /** Create the serializer. */ public MapSerializer() {} @Override public void close() { // nothing to do; } @Override public void configure(Map arg0, boolean arg1) { // nothing to do } @Override public byte[] serialize(final String topic, final Map data) { try { return MAPPER.writeValueAsBytes(requireNonNull(data, "data")); } catch (JsonProcessingException e) { throw new RuntimeException("Unserializable data sent to Kafka: " + e.getMessage(), e); } } } private static class KafkaNotifier implements WorkspaceEventListener { private final String topic; private final KafkaProducer> client; // constructor is here to allow for unit tests private KafkaNotifier( final String topic, final String bootstrapServers, final KafkaProducer> client) throws ListenerInitializationException { this.topic = checkString(topic, KAFKA_WS_TOPIC, 249); final Matcher m = INVALID_TOPIC_CHARS.matcher(this.topic); if (m.find()) { throw new ListenerInitializationException(String.format( "Illegal character in %s %s: %s", KAFKA_WS_TOPIC, this.topic, m.group())); } this.client = requireNonNull(client, "client"); try { client.partitionsFor(this.topic); // check kafka is up } catch (KafkaException e) { // TODO KAFKA CODE this blocks forever, needs 2.2.0 for a fix. // https://issues.apache.org/jira/browse/KAFKA-5503 client.close(0, TimeUnit.MILLISECONDS); // might want a notifier exception here throw new ListenerInitializationException("Could not reach Kafka instance at " + bootstrapServers); } } private void post(final Map message) { final Future res = client.send(new ProducerRecord<>(topic, message)); try { res.get(35000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { throw new RuntimeException("Failed sending notification to Kafka: " + e.getMessage(), e); } catch (TimeoutException e) { throw new RuntimeException("Timed out after 35s while sending notification " + "to Kafka: " + e.getMessage(), e); } catch (ExecutionException e) { throw new RuntimeException("Failed sending notification to Kafka: " + e.getCause().getMessage(), e.getCause()); } } private String getNullableUser(final WorkspaceUser user) { return user == null ? null : user.getUser(); } @Override public void createWorkspace(final WorkspaceUser user, final long id, final Instant time) { newEvent(user.getUser(), id, null, null, null, WORKSPACE_STATE_CHANGE, time); } @Override public void cloneWorkspace( final WorkspaceUser user, final long id, final boolean isPublic, final Instant time) { newEvent(user.getUser(), id, null, null, null, CLONE_WORKSPACE, time); } @Override public void setWorkspaceMetadata( final WorkspaceUser user, final long id, final Instant time) { newEvent(user.getUser(), id, null, null, null, WORKSPACE_STATE_CHANGE, time); } @Override public void lockWorkspace(final WorkspaceUser user, final long id, final Instant time) { newEvent(user.getUser(), id, null, null, null, WORKSPACE_STATE_CHANGE, time); } @Override public void renameWorkspace( final WorkspaceUser user, final long id, final String newname, final Instant time) { newEvent(user.getUser(), id, null, null, null, WORKSPACE_STATE_CHANGE, time); } @Override public void setGlobalPermission( final WorkspaceUser user, final long id, final Permission permission, final Instant time) { newEvent(user.getUser(), id, null, null, null, SET_GLOBAL_PERMISSION, time); } @Override public void setPermissions( final WorkspaceUser user, final long id, final Permission permission, final List users, final Instant time) { newEvent(getNullableUser(user), id, null, null, null, SET_PERMISSION, time, permission, users); } @Override public void setWorkspaceDescription( final WorkspaceUser user, final long id, final Instant time) { newEvent(getNullableUser(user), id, null, null, null, WORKSPACE_STATE_CHANGE, time); } @Override public void setWorkspaceOwner( final WorkspaceUser user, final long id, final WorkspaceUser newUser, final Optional newName, final Instant time) { newEvent(getNullableUser(user), id, null, null, null, WORKSPACE_STATE_CHANGE, time); } @Override public void setWorkspaceDeleted( final WorkspaceUser user, final long id, final boolean delete, final long maxObjectID, final Instant time) { newEvent(getNullableUser(user), id, null, null, null, WORKSPACE_DELETE_STATE_CHANGE, time); } @Override public void renameObject( final WorkspaceUser user, final long workspaceId, final long objectId, final String newName, final Instant time) { newEvent(user.getUser(), workspaceId, objectId, null, null, RENAME_OBJECT, time); } @Override public void revertObject(final ObjectInformation oi, final boolean isPublic) { newEvent(oi.getSavedBy().getUser(), oi.getWorkspaceId(), oi.getObjectId(), oi.getVersion(), oi.getTypeString(), NEW_VERSION, oi.getSavedDate().toInstant()); } @Override public void setObjectsHidden( final WorkspaceUser user, final long workspaceId, final long objectId, final boolean hidden, final Instant time) { newEvent(user.getUser(), workspaceId, objectId, null, null, OBJECT_HIDE_STATE_CHANGE, time); } @Override public void setObjectDeleted( final WorkspaceUser user, final long workspaceId, final long objectId, final boolean delete, final Instant time) { newEvent(user.getUser(), workspaceId, objectId, null, null, OBJECT_DELETE_STATE_CHANGE, time); } @Override public void copyObject(final ObjectInformation oi, final boolean isPublic) { newEvent(oi.getSavedBy().getUser(), oi.getWorkspaceId(), oi.getObjectId(), oi.getVersion(), oi.getTypeString(), NEW_VERSION, oi.getSavedDate().toInstant()); } @Override public void copyObject( final WorkspaceUser user, final long workspaceId, final long objectId, final int latestVersion, final Instant time, final boolean isPublic) { newEvent(user.getUser(), workspaceId, objectId, null, null, COPY_OBJECT, time); } @Override public void saveObject(final ObjectInformation oi, final boolean isPublic) { newEvent(oi.getSavedBy().getUser(), oi.getWorkspaceId(), oi.getObjectId(), oi.getVersion(), oi.getTypeString(), NEW_VERSION, oi.getSavedDate().toInstant()); } private void newEvent( final String user, final long workspaceId, final Long objectId, final Integer version, final String type, final String eventType, final Instant time) { newEvent(user, workspaceId, objectId, version, type, eventType, time, null, Collections.emptyList()); } private void newEvent( final String user, final long workspaceId, final Long objectId, final Integer version, final String type, final String eventType, final Instant time, final Permission permission, final List usersWithNewPermission) { final Map dobj = new HashMap<>(); dobj.put("user", user); dobj.put("wsid", workspaceId); dobj.put("objid", objectId); dobj.put("ver", version); dobj.put("time", time.toEpochMilli()); dobj.put("evtype", eventType); dobj.put("objtype", type); dobj.put("perm", permission == null ? null : KBasePermissions.translatePermission(permission)); dobj.put("permusers", usersWithNewPermission.stream().map(u -> u.getUser()) .collect(Collectors.toList())); post(dobj); } } } 10-100 package com.airmap.airmapsdk.models.flight; import java.io.Serializable; public class FlightFeatureValue implements Serializable { private String key; private T value; public FlightFeatureValue(String key, T value) { this.key = key; this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } @Override public boolean equals(Object o) { return o instanceof FlightFeatureValue && ((FlightFeatureValue) o).key.equals(this.key); } @Override public int hashCode() { return key.hashCode(); } } trustline-demo-a/src/main/java/com/hundredpercent/sample/validator/v1/Validator.java0 /* * 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.hundredpercent.sample.validator.v1; /** * * @author SIGINT-X */ public interface Validator { public void validate(T input); } src/main/java/com/langel/lavcache/annotation/Erase.java package com.langel.lavcache.annotation; import java.lang.annotation.*; /** * @author L-Angel,Rick() * @date 2018/9/26 **/ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Erase { String prefix() default ""; } 0 /* Copyright (c) 2010, NHIN Direct Project All rights reserved. Authors: 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 the The NHIN Direct Project (nhindirect.org). 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.nhindirect.stagent.cert.impl; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.UnknownHostException; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.jcs.JCS; import org.apache.jcs.access.exception.CacheException; import org.apache.jcs.engine.behavior.ICompositeCacheAttributes; import org.apache.jcs.engine.behavior.IElementAttributes; import org.nhindirect.common.options.OptionsManager; import org.nhindirect.common.options.OptionsParameter; import org.nhindirect.stagent.NHINDException; import org.nhindirect.stagent.cert.CacheableCertStore; import org.nhindirect.stagent.cert.CertCacheFactory; import org.nhindirect.stagent.cert.CertStoreCachePolicy; import org.nhindirect.stagent.cert.CertificateStore; import org.xbill.DNS.CERTRecord; import org.xbill.DNS.CNAMERecord; import org.xbill.DNS.Cache; import org.xbill.DNS.DClass; import org.xbill.DNS.ExtendedResolver; import org.xbill.DNS.Lookup; import org.xbill.DNS.NSRecord; import org.xbill.DNS.Name; import org.xbill.DNS.Record; import org.xbill.DNS.Resolver; import org.xbill.DNS.ResolverConfig; import org.xbill.DNS.SimpleResolver; import org.xbill.DNS.Type; /** * Certificate store backed by DNS CERT records (RFC 4398) for dynamic lookup and a configurable local cache of off line lookup. * By default the service uses the local node's DNS server configuration for initial DNS queries and a key store implementation for * off line lookups. The default key store creates new file named NHINDKeyStore with a default file and private key password if the * file does not already exist. *
* Depending the OS TCP implementation, lookups may be cached in native DNS resolvers resulting in optimized lookups. * However this may not always in line with HIPS policies. Refer to you OS DNS implementation for more details. *
* This service caches DNS entries independently of OS resolver. Caching can be tuned using the {@link CacheableCertStore} interface. * By default, the time to live of a subjects DNS certs is one day and the maximum number of entries is 1000 before the cache * is pruned to make room for new entries. Pruning by default uses a least recently used algorithm. * * @author * */ public class DNSCertificateStore extends CertificateStore implements CacheableCertStore { private static final String CACHE_NAME = "DNS_REMOTE_CERT_CACHE"; protected static final int DEFAULT_DNS_TIMEOUT = 3; // 3 seconds protected static final int DEFAULT_DNS_RETRIES = 2; protected static final boolean DEFAULT_DNS_USE_TCP = true; protected static final int DEFAULT_DNS_MAX_CAHCE_ITEMS = 1000; protected static final int DEFAULT_DNS_TTL = 3600; // 1 hour protected static final int DEFAULT_URL_CONNECTION_TIMEOUT = 10000; // 10 seconds protected static final int DEFAULT_URL_READ_TIMEOUT = 10000; // 10 hour seconds protected CertificateStore localStoreDelegate; protected List servers = new ArrayList(); protected JCS cache; protected CertStoreCachePolicy cachePolicy; protected int timeout; protected int retries; protected boolean useTCP; @SuppressWarnings("deprecation") private static final Log LOGGER = LogFactory.getFactory().getInstance(DNSCertificateStore.class); static { Cache ch = Lookup.getDefaultCache(DClass.IN); ch.clearCache(); } /** * Constructs a service using the machines local DNS server configuration and a default key store implementation for * local lookups. */ public DNSCertificateStore() { getServerQuerySettings(); setServers(null); // no longer create a default local // bootstrap store by default // create the in memory cache createCache(); } /** * Constructs a service using the server list for DNS lookups and a default key store implementation for * local lookups. * @param servers The DNS users to use for initial certificate resolution. */ public DNSCertificateStore(Collection servers) { getServerQuerySettings(); setServers(servers); // no longer create a default local // bootstrap store by default // create the in memory cache createCache(); } /** * Constructs a service using the server list for DNS lookups and a key store implementation for * local lookups. * @param servers The DNS users to use for initial certificate resolution. * @param localStoreDelegate The certificate store used for local lookups. This store is also the boot strap store. * The boot strap store may be null. */ public DNSCertificateStore(Collection servers, CertificateStore bootstrapStore, CertStoreCachePolicy policy) { // null boot strap store is OK getServerQuerySettings(); setServers(servers); this.cachePolicy = policy; this.localStoreDelegate = bootstrapStore; // create the in memory cache createCache(); // no longer create a default local // bootstrap store by default if the boot strap is null if (localStoreDelegate != null) loadBootStrap(); } private void getServerQuerySettings() { OptionsParameter param = OptionsManager.getInstance().getParameter(OptionsParameter.DNS_CERT_RESOLVER_TIMEOUT); timeout = OptionsParameter.getParamValueAsInteger(param, DEFAULT_DNS_TIMEOUT); param = OptionsManager.getInstance().getParameter(OptionsParameter.DNS_CERT_RESOLVER_RETRIES); retries = OptionsParameter.getParamValueAsInteger(param, DEFAULT_DNS_RETRIES); param = OptionsManager.getInstance().getParameter(OptionsParameter.DNS_CERT_RESOLVER_USE_TCP); useTCP = OptionsParameter.getParamValueAsBoolean(param, DEFAULT_DNS_USE_TCP); } private synchronized JCS getCache() { if (cache == null) createCache(); return cache; } private void createCache() { try { // create instance cache = CertCacheFactory.getInstance().getCertCache(CACHE_NAME, cachePolicy == null ? getDefaultPolicy() : cachePolicy); if (cachePolicy == null) cachePolicy = getDefaultPolicy(); } ///CLOVER:OFF catch (CacheException e) { LOGGER.warn("DNSCertificateStore - Could not create certificate cache " + CACHE_NAME, e); } ///CLOVER:ON } private CertStoreCachePolicy getDefaultPolicy() { return new DefaultDNSCachePolicy(); } /** * Sets the DNS servers used for initial certificate lookups. This replaces all currently set DNS server configuration. This method is thread safe and * may block if a current lookup is currently in progress. * @param servers The DNS servers used for initial certificate lookups. */ public void setServers(Collection servers) { if (servers == null || servers.size() == 0) { String[] configedServers = null; // first check if servers were configured via the options manager final OptionsParameter serverOptions = OptionsManager.getInstance().getParameter(OptionsParameter.DNS_CERT_RESOLVER_SERVERS); if (serverOptions != null && !StringUtils.isEmpty(serverOptions.getParamValue())) { configedServers = serverOptions.getParamValue().split(","); } else // no servers in the options manager, fall back to the local machine's settings configedServers = ResolverConfig.getCurrentConfig().servers(); if (configedServers != null) { this.servers.addAll(Arrays.asList(configedServers)); } } else { this.servers.clear(); this.servers.addAll(servers); } } /** * {@inheritDoc} */ public boolean contains(X509Certificate cert) { return localStoreDelegate == null ? false : localStoreDelegate.contains(cert); } /** * {@inheritDoc} */ public void add(X509Certificate cert) { if (localStoreDelegate != null) localStoreDelegate.add(cert); } /** * {@inheritDoc} */ public void remove(X509Certificate cert) { if (localStoreDelegate != null) localStoreDelegate.remove(cert); } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override public Collection getCertificates(String subjectName) { String realSubjectName; int index; if ((index = subjectName.indexOf("EMAILADDRESS=")) > -1) realSubjectName = subjectName.substring(index + "EMAILADDRESS=".length()); else realSubjectName = subjectName; Collection retVal; JCS cache = getCache(); if (cache != null) { retVal = (Collection)cache.get(realSubjectName); if (retVal == null || retVal.size() == 0) { retVal = this.lookupDNS(realSubjectName); if (retVal == null || retVal.size() == 0) { LOGGER.info("getCertificates(String subjectName) - Could not find a DNS certificate for subject " + subjectName); } } } else // cache miss { retVal = this.lookupDNS(realSubjectName); if (retVal.size() == 0) { if (localStoreDelegate != null) { retVal = localStoreDelegate.getCertificates(realSubjectName); // last ditch effort is to go to the bootstrap cache if (retVal == null || retVal.size() == 0) { LOGGER.info("getCertificates(String subjectName) - Could not find a DNS certificate for subject " + subjectName); } } else LOGGER.info("getCertificates(String subjectName) - Could not find a DNS certificate for subject " + subjectName); } } return retVal; } /** * {@inheritDoc} */ @Override public Collection getAllCertificates() { return (localStoreDelegate == null) ? null : localStoreDelegate.getAllCertificates(); } protected Collection lookupDNS(String name) { String domain; String lookupName = name.replace('@', '.'); Collection retVal = new ArrayList(); // get the domain of the address int index; if ((index = name.indexOf("@")) > -1) domain = name.substring(index + 1); else domain = name; try { // try the configured servers first Lookup lu = new Lookup(new Name(lookupName), Type.CERT); lu.setResolver(createExResolver(servers.toArray(new String[servers.size()]), retries, timeout)); // default retries is 3, limite to 2 lu.setSearchPath((String[])null); Record[] retRecords = null; try { retRecords = lu.run(); } catch (Exception e) { LOGGER.warn("Error using recusive DNS CERT lookup for name " + lookupName + "\r\nFalling back to looking up NS record for a targeted search", e); } if (retRecords == null || retRecords.length == 0) { Name tempDomain; // try to find the resource's name server records // the address may be an alias so check if there is a CNAME record lu = new Lookup(new Name(lookupName), Type.CNAME); lu.setResolver(createExResolver(servers.toArray(new String[servers.size()]), retries, timeout)); lu.setSearchPath((String[])null); retRecords = lu.run(); if (retRecords != null && retRecords.length > 0) { CNAMERecord cnameRect = (CNAMERecord)retRecords[0]; tempDomain = cnameRect.getTarget(); } else tempDomain = new Name(domain); // not a CNAME // look for a name server records while (tempDomain.labels() > 1) { lu = new Lookup(tempDomain, Type.NS); lu.setResolver(createExResolver(servers.toArray(new String[servers.size()]), retries, timeout)); lu.setSearchPath((String[])null); retRecords = lu.run(); if (retRecords != null && retRecords.length > 0) break; tempDomain = new Name(tempDomain.toString().substring((tempDomain.toString().indexOf(".") + 1))); } if (retRecords == null || retRecords.length == 0) return retVal; // can't find a name server... bail String[] remoteServers = new String[retRecords.length]; for (int i = 0; i < remoteServers.length - 0; ++i) { remoteServers[i] = ((NSRecord)retRecords[i]).getTarget().toString(); } // search the name servers for the cert lu = new Lookup(new Name(lookupName), Type.CERT); ExtendedResolver remoteResolver = createExResolver(remoteServers, 2, 3); if (remoteResolver.getResolvers().length > 0) { lu.setResolver(remoteResolver); lu.setSearchPath((String[])null); // CLEAR THE CACHE!!! We are seeing instances where an NXRRSET is cached because // a DNS provider is trying to handle a request that it should be delegating // The purpose of bypassing the DNS provider and going directly to the NS server // is to avoid issues like this /* * Change of heart on clearing the DNS cache. Covering up the NXRRSET hides potential issues * with incorrect DNS configuration. It is important that NXRRSET issues are discovered and corrected * so all participants in the community participate in a consistent manner. */ //lu.setCache(new Cache(DClass.IN)); retRecords = lu.run(); } else { // null out NS records retRecords = null; } } if (retRecords != null) { retVal = new ArrayList(); for (Record rec : retRecords) { if (rec instanceof CERTRecord) { CERTRecord certRec = (CERTRecord)rec; switch(certRec.getCertType()) { case CERTRecord.PKIX: { Certificate certToAdd = convertPKIXRecordToCert(certRec); if (certToAdd != null && certToAdd instanceof X509Certificate) // may not be an X509Cert retVal.add((X509Certificate)certToAdd); break; } case CERTRecord.URI: { Certificate certToAdd = convertIPKIXRecordToCert(certRec); if (certToAdd != null && certToAdd instanceof X509Certificate) // may not be an X509Cert retVal.add((X509Certificate)certToAdd); break; } default: { LOGGER.warn("Unknown CERT type " + certRec.getCertType() + " encountered for lookup name" + lookupName); } } } } } else if (domain.length() < name.length()) // if this is an email address, do the search again and the host level retVal = lookupDNS(domain); } catch (Exception e) { e.printStackTrace(); throw new NHINDException("", e); } // add or update the local cert store if (retVal != null && retVal.size() > 0 && localStoreDelegate != null) { for (X509Certificate cert : retVal) { if (localStoreDelegate != null) { if (localStoreDelegate.contains(cert)) localStoreDelegate.update(cert); else localStoreDelegate.add(cert); } } try { if (cache != null) cache.put(name, retVal); } catch (CacheException e) { /* * TODO: handle exception */ } } return retVal; } public void flush(boolean purgeBootStrap) { if (cache != null) { try { cache.clear(); } catch (CacheException e) { /** * TODO: handle exception */ } if (purgeBootStrap && this.localStoreDelegate != null) { localStoreDelegate.remove(localStoreDelegate.getAllCertificates()); } } } @SuppressWarnings("unused") public void loadBootStrap() { if (localStoreDelegate == null) throw new IllegalStateException("The boot strap store has not been set."); JCS cache = null; if ((cache = getCache()) != null) { Map> cacheBuilderMap = new HashMap>(); for (X509Certificate cert : localStoreDelegate.getAllCertificates()) { /* * TODO: need to decide how the entries/subjects will be indexed and named */ } for (Entry> entry : cacheBuilderMap.entrySet()) { try { cache.put(entry.getKey(), entry.getValue()); } catch (CacheException e) { /* * TODO: handle exception */ } } } } public void loadBootStrap(CertificateStore bootstrapStore) { if (localStoreDelegate == null) { throw new IllegalArgumentException(); } this.localStoreDelegate = bootstrapStore; loadBootStrap(); } public void setBootStrap(CertificateStore bootstrapStore) { if (localStoreDelegate == null) { throw new IllegalArgumentException(); } this.localStoreDelegate = bootstrapStore; } public void setCachePolicy(CertStoreCachePolicy policy) { this.cachePolicy = policy; applyCachePolicy(policy); } private void applyCachePolicy(CertStoreCachePolicy policy) { if (getCache() != null) { try { ICompositeCacheAttributes attributes = cache.getCacheAttributes(); attributes.setMaxObjects(policy.getMaxItems()); attributes.setUseLateral(false); attributes.setUseRemote(false); cache.setCacheAttributes(attributes); IElementAttributes eattributes = cache.getDefaultElementAttributes(); eattributes.setMaxLifeSeconds(policy.getSubjectTTL()); eattributes.setIsEternal(false); eattributes.setIsLateral(false); eattributes.setIsRemote(false); cache.setDefaultElementAttributes(eattributes); } catch (CacheException e) { // TODO: Handle exception } } } public static class DefaultDNSCachePolicy implements CertStoreCachePolicy { protected final int maxItems; protected final int subjectTTL; public DefaultDNSCachePolicy() { OptionsParameter param = OptionsManager.getInstance().getParameter(OptionsParameter.DNS_CERT_RESOLVER_MAX_CACHE_SIZE); maxItems = OptionsParameter.getParamValueAsInteger(param, DEFAULT_DNS_MAX_CAHCE_ITEMS); param = OptionsManager.getInstance().getParameter(OptionsParameter.DNS_CERT_RESOLVER_CACHE_TTL); subjectTTL = OptionsParameter.getParamValueAsInteger(param, DEFAULT_DNS_TTL); } public int getMaxItems() { return maxItems; } public int getSubjectTTL() { return subjectTTL; } } protected ExtendedResolver createExResolver(String[] servers, int retries, int timeout) { // create a default ExtendedResolver ExtendedResolver extendedResolver; try { extendedResolver = new ExtendedResolver(); } catch (UnknownHostException e) { LOGGER.error("", e); throw new IllegalStateException("unable to create default ExtendedResolver", e); } // remove all resolvers from default ExtendedResolver Resolver[] resolvers = extendedResolver.getResolvers(); if (!ArrayUtils.isEmpty(resolvers)) { for (Resolver resolver : resolvers) { extendedResolver.deleteResolver(resolver); } } // add the specified servers if (!ArrayUtils.isEmpty(servers)) { for (String server : servers) { // support for IP addresses instead of names server = server.replaceFirst("\\.$", ""); try { // create and add a SimpleResolver for each server SimpleResolver simpleResolver = new SimpleResolver(server); extendedResolver.addResolver(simpleResolver); } catch (UnknownHostException e) { LOGGER.debug("unable to add resolver for " + server, e); continue; } } extendedResolver.setRetries(retries); extendedResolver.setTimeout(timeout); extendedResolver.setTCP(useTCP); } return extendedResolver; } @SuppressWarnings("deprecation") protected Certificate convertPKIXRecordToCert(CERTRecord certRec) { Certificate retVal = null; ByteArrayInputStream inputStream = null; final byte[] certData = certRec.getCert(); try { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); inputStream = new ByteArrayInputStream(certData); retVal = (X509Certificate)cf.generateCertificate(inputStream); } catch (Exception e) { LOGGER.warn("Failed to convert certificate from DNS byte data.", e); } finally { IOUtils.closeQuietly(inputStream); } return retVal; } @SuppressWarnings("deprecation") protected Certificate convertIPKIXRecordToCert(CERTRecord certRec) { Certificate retVal = null; InputStream inputStream = null; try { // in this case the cert is a binary representation // of the CERT URL... transform to a string final URL certURL = getCertURL(certRec); final URLConnection connection = certURL.openConnection(); // the connection is not actually made until the input stream // is open, so set the timeouts before getting the stream connection.setConnectTimeout(DEFAULT_URL_CONNECTION_TIMEOUT); connection.setReadTimeout(DEFAULT_URL_READ_TIMEOUT); // open the URL as in input stream inputStream = connection.getInputStream(); final CertificateFactory cf = CertificateFactory.getInstance("X.509"); retVal = (X509Certificate)cf.generateCertificate(inputStream); } catch (Exception e) { LOGGER.warn("Failed to get cert recrod from IPKIX location.", e); } finally { IOUtils.closeQuietly(inputStream); } return retVal; } protected URL getCertURL(CERTRecord certRec) throws MalformedURLException, UnsupportedEncodingException { final URL certURL = new URL(new String(certRec.getCert(), "ASCII")); return certURL; } } aws-java-sdk-fms/src/main/java/com/amazonaws/services/fms/model/transform/PolicyMarshaller.java /* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.fms.model.transform; import java.util.Map; import java.util.List; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.fms.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * PolicyMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class PolicyMarshaller { private static final MarshallingInfo POLICYID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("PolicyId").build(); private static final MarshallingInfo POLICYNAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PolicyName").build(); private static final MarshallingInfo POLICYUPDATETOKEN_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PolicyUpdateToken").build(); private static final MarshallingInfo SECURITYSERVICEPOLICYDATA_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SecurityServicePolicyData").build(); private static final MarshallingInfo RESOURCETYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ResourceType").build(); private static final MarshallingInfo RESOURCETYPELIST_BINDING = MarshallingInfo.builder(MarshallingType.LIST) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ResourceTypeList").build(); private static final MarshallingInfo RESOURCETAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("ResourceTags").build(); private static final MarshallingInfo EXCLUDERESOURCETAGS_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ExcludeResourceTags").build(); private static final MarshallingInfo REMEDIATIONENABLED_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("RemediationEnabled").build(); private static final MarshallingInfo INCLUDEMAP_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("IncludeMap").build(); private static final MarshallingInfo EXCLUDEMAP_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("ExcludeMap").build(); private static final PolicyMarshaller instance = new PolicyMarshaller(); public static PolicyMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(Policy policy, ProtocolMarshaller protocolMarshaller) { if (policy == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(policy.getPolicyId(), POLICYID_BINDING); protocolMarshaller.marshall(policy.getPolicyName(), POLICYNAME_BINDING); protocolMarshaller.marshall(policy.getPolicyUpdateToken(), POLICYUPDATETOKEN_BINDING); protocolMarshaller.marshall(policy.getSecurityServicePolicyData(), SECURITYSERVICEPOLICYDATA_BINDING); protocolMarshaller.marshall(policy.getResourceType(), RESOURCETYPE_BINDING); protocolMarshaller.marshall(policy.getResourceTypeList(), RESOURCETYPELIST_BINDING); protocolMarshaller.marshall(policy.getResourceTags(), RESOURCETAGS_BINDING); protocolMarshaller.marshall(policy.getExcludeResourceTags(), EXCLUDERESOURCETAGS_BINDING); protocolMarshaller.marshall(policy.getRemediationEnabled(), REMEDIATIONENABLED_BINDING); protocolMarshaller.marshall(policy.getIncludeMap(), INCLUDEMAP_BINDING); protocolMarshaller.marshall(policy.getExcludeMap(), EXCLUDEMAP_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } } threefishes/springCloudMainService package cn.threefishes.cloudrepository.dao; import cn.threefishes.cloudrepository.entity.VideoAlbum; import cn.threefishes.cloudrepository.entity.VideoAlbumExample; import java.util.List; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds; public interface VideoAlbumMapper { long countByExample(VideoAlbumExample example); int deleteByExample(VideoAlbumExample example); int deleteByPrimaryKey(Integer albumId); int insert(VideoAlbum record); int insertSelective(VideoAlbum record); List selectByExampleWithRowbounds(VideoAlbumExample example, RowBounds rowBounds); List selectByExample(VideoAlbumExample example); VideoAlbum selectByPrimaryKey(Integer albumId); int updateByExampleSelective(@Param("record") VideoAlbum record, @Param("example") VideoAlbumExample example); int updateByExample(@Param("record") VideoAlbum record, @Param("example") VideoAlbumExample example); int updateByPrimaryKeySelective(VideoAlbum record); int updateByPrimaryKey(VideoAlbum record); }package com.unity; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.google.firebase.remoteconfig.FirebaseRemoteConfig; public class Update extends AppCompatActivity { Toolbar toolbar; private static final String KEY_UPDATE_URL = "updateUrl"; private static final String KEY_UPDATE_TEXT_TR = "updateTextTr"; private static final String KEY_UPDATE_VISIT_APK = "updateVisitApk"; boolean doubleBackToExitPressedOnce = false; TextView updateText; FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); ProgressBar progressBar; final Uri auto_download = Uri.parse(mFirebaseRemoteConfig.getString(KEY_UPDATE_URL)); final Uri visitApk = Uri.parse(mFirebaseRemoteConfig.getString(KEY_UPDATE_VISIT_APK)); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR); } updateText = findViewById(R.id.updateText); progressBar = findViewById(R.id.progressBar); String text = mFirebaseRemoteConfig.getString(KEY_UPDATE_TEXT_TR).replace("\\n", "\n"); updateText.setText(text); progressBar.setVisibility(View.GONE); } @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); return; } this.doubleBackToExitPressedOnce = true; Toast.makeText(this, getString(R.string.clickOneMoreTimeToExit), Toast.LENGTH_SHORT).show(); new Handler().postDelayed(() -> doubleBackToExitPressedOnce = false, 2000); } public void Download(View view) { Intent intent = new Intent(Intent.ACTION_VIEW, auto_download); startActivity(intent); } public void VisitAPK(View view) { Intent intent = new Intent(Intent.ACTION_VIEW, visitApk); startActivity(intent); } }corypgr/project-euler package corypgr.project.euler.problems; import corypgr.project.euler.problems.prime.PrimeGenerator; import corypgr.project.euler.problems.util.CountMap; import corypgr.project.euler.problems.util.Problem; import corypgr.project.euler.problems.util.ProblemSolution; import lombok.Value; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * Problem 51 * * https://projecteuler.net/problem=51 * * Had to think a bit about this one. I think a good strategy is to zero out specific digits of * prime numbers, and count the ones that match after the zeroing out. * * The process of doing this isn't going to be super simple though... I'm going to try to generate * permutations of the places to zero out, starting with 1 digit and working up. * * What should the max prime be? No idea. We'll increase in multiples of 10 until we find the number * we're looking for. Multiples of 10 is because the first digit could be replaced, going from 1 to 9, so * we need the full range of numbers which can start with 1 to 9. */ public class PE0051 implements Problem { private static final long MAX_PRIME = 999999; private static final long MIN_PRIME = 100000; private static final int TARGET_FAMILY_SIZE = 8; @Override public ProblemSolution solve() { Match smallestMatch = findSmallestPrimeThatMasksToFamily(); return ProblemSolution.builder() .solution(smallestMatch.getSmallestPrime()) .descriptiveSolution("Smallest prime part of an 8 value prime family: " + smallestMatch) .build(); } private Match findSmallestPrimeThatMasksToFamily() { PrimeGenerator primeGenerator = new PrimeGenerator(); Set primes = primeGenerator.generatePrimesSet(MAX_PRIME); List> primesAsListOfInts = primes.stream() .dropWhile(prime -> prime < MIN_PRIME) .map(this::longToListOfInts) .collect(Collectors.toList()); int numDigits = String.valueOf(MAX_PRIME).length(); for (int numZeroes = 1; numZeroes < numDigits; numZeroes++) { List> masks = getMasks(numDigits, numZeroes); for (List mask : masks) { CountMap countMap = new CountMap<>(); primesAsListOfInts.stream() .filter(prime -> isMaskingOnSameDigit(prime, mask)) .map(prime -> mask(prime, mask, 0)) .map(this::intsToLong) .forEach(countMap::addCount); Optional matchedMaskedPrime = countMap.entrySet().stream() .filter(entry -> entry.getValue() == TARGET_FAMILY_SIZE) .map(Map.Entry::getKey) .findFirst(); if (matchedMaskedPrime.isPresent()) { return new Match(getSmallestPrimeFromMaskedPrime(matchedMaskedPrime.get(), mask, primes), mask); } } } return null; } private long getSmallestPrimeFromMaskedPrime(long maskedPrime, List mask, Set primes) { List maskedPrimeAsInts = longToListOfInts(maskedPrime); // Pad with zeroes if the first digits were masked away. while (maskedPrime < MIN_PRIME) { maskedPrime *= 10; maskedPrimeAsInts.add(0, 0); } return IntStream.range(0, 9) .mapToObj(valToInsert -> mask(maskedPrimeAsInts, mask, valToInsert)) .map(this::intsToLong) .filter(primes::contains) .findFirst() .get(); } private List longToListOfInts(long val) { List list = new LinkedList<>(); long remaining = val; while (remaining > 0L) { list.add(0, (int) remaining % 10); remaining /= 10; } return list; } private long intsToLong(List ints) { long result = 0; for (int val : ints) { result *= 10; result += val; } return result; } private boolean isMaskingOnSameDigit(List primeAsInts, List mask) { long digitCount = mask.stream() .map(primeAsInts::get) .distinct() .count(); return digitCount == 1L; } private List mask(List primeAsInts, List mask, int valToInsert) { List newList = new ArrayList<>(primeAsInts); mask.forEach(index -> newList.set(index, valToInsert)); return newList; } /** * Custom permutation generator to be more efficient. If we used PermutationUtil, it would do a lot of * unnecessary work and we would need to dedupe values. *

* Returns a list of values to "mask", where each value is the index of a value to mask. */ private List> getMasks(int numDigits, int numZeroedOut) { List> masks = new LinkedList<>(); // start with 0, 1, ... List currentMask = IntStream.range(0, numZeroedOut) .boxed() .collect(Collectors.toList()); while (currentMask != null) { masks.add(currentMask); currentMask = getNextMask(currentMask, numDigits); } return masks; } private List getNextMask(List mask, int numDigits) { for (int i = mask.size() - 1; i >= 0; i--) { int maxVal = numDigits - mask.size() + i; if (mask.get(i) < maxVal) { List nextMask = new ArrayList<>(mask); int insertVal = mask.get(i) + 1; for (int j = i; j < mask.size(); j++, insertVal++) { nextMask.set(j, insertVal); } return nextMask; } } return null; } @Value private static class Match { private final long smallestPrime; private final List mask; } } src/main/java/com/github/tinyurl/service/UidGeneratorParam.java package com.github.tinyurl.service; /** * TODO 文件说明 * * @author * @date 2020/07/14 */ public interface UidGeneratorParam { } shreejadhav10/Stetho-Couchbase package com.robotpajamas.stetho.couchbase; import com.facebook.stetho.inspector.jsonrpc.JsonRpcPeer; import com.facebook.stetho.inspector.jsonrpc.JsonRpcResult; import com.facebook.stetho.inspector.protocol.ChromeDevtoolsDomain; import com.facebook.stetho.inspector.protocol.ChromeDevtoolsMethod; import com.facebook.stetho.json.ObjectMapper; import com.facebook.stetho.json.annotation.JsonProperty; import org.json.JSONObject; import java.util.List; import timber.log.Timber; class Database implements ChromeDevtoolsDomain { private final CouchbasePeerManager mCouchbasePeerManager; private final ObjectMapper mObjectMapper = new ObjectMapper(); Database(CouchbasePeerManager peerManager) { mCouchbasePeerManager = peerManager; } @ChromeDevtoolsMethod @SuppressWarnings("unused") public void enable(JsonRpcPeer peer, JSONObject params) { Timber.d("Enable Peer: %s", String.valueOf(params)); mCouchbasePeerManager.addPeer(peer); } @ChromeDevtoolsMethod @SuppressWarnings("unused") public void disable(JsonRpcPeer peer, JSONObject params) { Timber.d("Disable Peer: %s", String.valueOf(params)); mCouchbasePeerManager.removePeer(peer); } @ChromeDevtoolsMethod @SuppressWarnings("unused") public JsonRpcResult getDatabaseTableNames(JsonRpcPeer peer, JSONObject params) { Timber.d("getAllDocumentIds: %s", String.valueOf(params)); GetDatabaseTableNamesRequest request = mObjectMapper.convertValue(params, GetDatabaseTableNamesRequest.class); GetDatabaseTableNamesResponse response = new GetDatabaseTableNamesResponse(); response.tableNames = mCouchbasePeerManager.getAllDocumentIds(request.databaseId); return response; } @ChromeDevtoolsMethod @SuppressWarnings("unused") public JsonRpcResult executeSQL(JsonRpcPeer peer, JSONObject params) { Timber.d("executeSQL: %s", String.valueOf(params)); ExecuteSQLResponse response = new ExecuteSQLResponse(); try { ExecuteSQLRequest request = mObjectMapper.convertValue(params, ExecuteSQLRequest.class); return mCouchbasePeerManager.executeSQL(request.databaseId, request.query); } catch (Exception e) { Timber.e(e.toString()); Error error = new Error(); error.code = 0; error.message = e.getMessage(); response.sqlError = error; return response; } } private static class GetDatabaseTableNamesRequest { @JsonProperty(required = true) public String databaseId; } private static class GetDatabaseTableNamesResponse implements JsonRpcResult { @JsonProperty(required = true) public List tableNames; } private static class ExecuteSQLRequest { @JsonProperty(required = true) public String databaseId; @JsonProperty(required = true) public String query; } static class ExecuteSQLResponse implements JsonRpcResult { @JsonProperty public List columnNames; @JsonProperty public List values; @JsonProperty public Error sqlError; } public static class AddDatabaseEvent { @JsonProperty(required = true) public DatabaseObject database; } public static class DatabaseObject { @JsonProperty(required = true) public String id; @JsonProperty(required = true) public String domain; @JsonProperty(required = true) public String name; @JsonProperty(required = true) public String version; } public static class Error { @JsonProperty(required = true) public String message; @JsonProperty(required = true) public int code; } } package com.gulj.data.structure.stack.example; import java.util.LinkedList; /** * @description: 使用LinkedList集合类,实现栈 * @author: gulj * @create: 2019/3/12 1:57 AM **/ public class LinkedListStack implements Stack { /** * 存放栈元素 */ LinkedList list; /** * 构造栈结构 */ public LinkedListStack() { list = new LinkedList<>(); } @Override public void push(E e) { list.addLast(e); } @Override public void pop() { list.removeLast(); } @Override public E peek() { return list.getLast(); } @Override public int getSize() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public String toString() { return "LinkedListStack{" + "list=" + list + '}'; } } 0 /* * ==================================================================== * 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. * ==================================================================== * * 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.http.impl.auth; import java.nio.charset.Charset; import org.apache.commons.codec.binary.Base64; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.annotation.NotThreadSafe; import org.apache.http.auth.AUTH; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.ChallengeState; import org.apache.http.auth.Credentials; import org.apache.http.auth.MalformedChallengeException; import org.apache.http.message.BufferedHeader; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.Args; import org.apache.http.util.CharArrayBuffer; import org.apache.http.util.EncodingUtils; /** * Basic authentication scheme as defined in RFC 2617. * * @since 4.0 */ @NotThreadSafe public class BasicScheme extends RFC2617Scheme { private final Base64 base64codec; /** Whether the basic authentication process is complete */ private boolean complete; /** * @since 4.3 */ public BasicScheme(final Charset credentialsCharset) { super(credentialsCharset); this.base64codec = new Base64(0); this.complete = false; } /** * Creates an instance of BasicScheme with the given challenge * state. * * @since 4.2 * * @deprecated (4.3) do not use. */ @Deprecated public BasicScheme(final ChallengeState challengeState) { super(challengeState); this.base64codec = new Base64(0); } public BasicScheme() { this(Consts.ASCII); } /** * Returns textual designation of the basic authentication scheme. * * @return basic */ public String getSchemeName() { return "basic"; } /** * Processes the Basic challenge. * * @param header the challenge header * * @throws MalformedChallengeException is thrown if the authentication challenge * is malformed */ @Override public void processChallenge( final Header header) throws MalformedChallengeException { super.processChallenge(header); this.complete = true; } /** * Tests if the Basic authentication process has been completed. * * @return true if Basic authorization has been processed, * false otherwise. */ public boolean isComplete() { return this.complete; } /** * Returns false. Basic authentication scheme is request based. * * @return false. */ public boolean isConnectionBased() { return false; } /** * @deprecated (4.2) Use {@link org.apache.http.auth.ContextAwareAuthScheme#authenticate( * Credentials, HttpRequest, org.apache.http.protocol.HttpContext)} */ @Deprecated public Header authenticate( final Credentials credentials, final HttpRequest request) throws AuthenticationException { return authenticate(credentials, request, new BasicHttpContext()); } /** * Produces basic authorization header for the given set of {@link Credentials}. * * @param credentials The set of credentials to be used for authentication * @param request The request being authenticated * @throws org.apache.http.auth.InvalidCredentialsException if authentication * credentials are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return a basic authorization string */ @Override public Header authenticate( final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { Args.notNull(credentials, "Credentials"); Args.notNull(request, "HTTP request"); final StringBuilder tmp = new StringBuilder(); tmp.append(credentials.getUserPrincipal().getName()); tmp.append(":"); tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword()); final byte[] base64password = base64codec.encode( EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request))); final CharArrayBuffer buffer = new CharArrayBuffer(32); if (isProxy()) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Basic "); buffer.append(base64password, 0, base64password.length); return new BufferedHeader(buffer); } /** * Returns a basic Authorization header value for the given * {@link Credentials} and charset. * * @param credentials The credentials to encode. * @param charset The charset to use for encoding the credentials * * @return a basic authorization header * * @deprecated (4.3) use {@link #authenticate(Credentials, HttpRequest, HttpContext)}. */ @Deprecated public static Header authenticate( final Credentials credentials, final String charset, final boolean proxy) { Args.notNull(credentials, "Credentials"); Args.notNull(charset, "charset"); final StringBuilder tmp = new StringBuilder(); tmp.append(credentials.getUserPrincipal().getName()); tmp.append(":"); tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword()); final byte[] base64password = Base64.encodeBase64( EncodingUtils.getBytes(tmp.toString(), charset), false); final CharArrayBuffer buffer = new CharArrayBuffer(32); if (proxy) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Basic "); buffer.append(base64password, 0, base64password.length); return new BufferedHeader(buffer); } } package eu.nvna.tests; import eu.nvna.helpers.ReflectedColor; import eu.nvna.helpers.ValueSupplier; import org.junit.jupiter.api.Assertions; 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.lang.reflect.InvocationTargetException; import java.util.stream.Stream; public class TestConstructors { @Test public void new_Color_EmptyCtor_ShouldBehaveNormally() throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, NoSuchFieldException { var color = ReflectedColor.newInstance(); Assertions.assertEquals(0, ReflectedColor.getFieldRValue(color)); Assertions.assertEquals(0, ReflectedColor.getFieldGValue(color)); Assertions.assertEquals(0, ReflectedColor.getFieldBValue(color)); } @ParameterizedTest @MethodSource("supplyColors") public void new_Color_WithParameter_ShouldBehaveNormally(short r, short g, short b) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException, NoSuchFieldException { var rgb = (long) (Math.pow(256, 2) * r + Math.pow(256, 1) * g + Math.pow(256, 0) * b); var color = ReflectedColor.newInstance(rgb); Assertions.assertEquals(r, ReflectedColor.getFieldRValue(color)); Assertions.assertEquals(g, ReflectedColor.getFieldGValue(color)); Assertions.assertEquals(b, ReflectedColor.getFieldBValue(color)); } private static Stream supplyColors() { return ValueSupplier.supplyColors(); } } package com.example.housin.view; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.Toast; import com.example.housin.R; import com.google.firebase.auth.FirebaseAuth; public class LoginActivity extends AppCompatActivity { Button button; String textError; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); button = findViewById(R.id.buttonLogin); } private boolean verificandoUsername() { if(false) { //username não for encontrado no banco textError = "Username não encontrado!"; } else { return true; } return false; } private boolean verificandoSenha() { if(false) { //senha não bater com o username textError = "Senha incorreta!"; } else { return true; } return false; } private void verificandoLogin() { if (verificandoUsername() && verificandoSenha()) { //Vai para a tela de usuários disponíveis } else { button.setBackgroundColor(getResources().getColor(R.color.loginError)); Toast.makeText(getApplicationContext(), textError, Toast.LENGTH_SHORT).show(); } } } 1-10 /* * Copyright 2006-2021 * * 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 net.tangly.bdd; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.junit.jupiter.api.Test; /** * Represents a use case in a {@link Story}. The annotation is meta-annotated with JUnit 5 Jupiter's built-in "@Test" annotation. When IDEs and test * engines scan through a given set of test classes and find this custom @Scenario annotation on public instance methods, they mark those methods as * test methods to be executed. */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Test public @interface Scenario { /** * Returns the description of the scenario as human readable information for living documentation. * * @return representation of the use case in a plain human language. */ String value(); } package models.entities; import jdk.nashorn.internal.objects.annotations.Getter; import jdk.nashorn.internal.objects.annotations.Setter; import org.dom4j.tree.AbstractEntity; import javax.persistence.*; /** * Created by Yuliia_Filatova on 9/7/2016. */ @Entity @Table(name="users") public class User extends AbstractEntity{ @Id @GeneratedValue private Long personId; @Column private String name; @Column private String password; public User(final String name, final String password) { this.name = name; this.password = password; } public User() { } public Long getPersonId() { return personId; } public String getName() { return name; } public String getPassword() { return password; } } 0 package org.vaadin.uikit.components; import org.vaadin.uikit.components.interfaces.UkFloat; import org.vaadin.uikit.components.interfaces.UkMargin; import org.vaadin.uikit.components.interfaces.UkTooltip; import com.vaadin.flow.component.ClickEvent; import com.vaadin.flow.component.ComponentEventListener; import com.vaadin.flow.component.Composite; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.shared.Registration; @SuppressWarnings("serial") public class UkIcon extends Composite implements UkTooltip, UkMargin, UkFloat { Span icon = new Span(); public UkIcon(UkIcons iconName) { icon.getElement().setAttribute("uk-icon", iconName.getIconName()); } public UkIcon(UkIcons iconName, double ratio) { icon.getElement().setAttribute("uk-icon", "icon: " + iconName.getIconName() + "; ratio: " + ratio); } public void setButtonStyle(boolean buttonStyle) { if (buttonStyle) { icon.addClassName("uk-icon-button"); } else { icon.removeClassName("uk-icon-button"); } } public Registration addClickListener( ComponentEventListener> listener) { return icon.addClickListener(listener); } @Override protected Span initContent() { return icon; } } cartoonYu/CommonUtil package org.common; /** * @author cartoon * @description * @date 2020/6/29 17:35 */ public interface DubboService { String say(); } src/main/java/com/example/filmList/repository/FilmRepository.java package com.example.filmList.repository; import com.example.filmList.domain.Film; import com.example.filmList.domain.Performer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface FilmRepository extends JpaRepository { List findByNameOrGenreContaining(String keyword1, String keyword2); } import java.util.Scanner; public class BOJ_1075 { public static void main(String[] args) { Scanner input = new Scanner( System.in ); int N = ( input.nextInt() / 100 ) * 100; int F = input.nextInt(); if( N % F == 0 ) System.out.printf( "%02d", 0 ); else System.out.printf( "%02d", ( ( ( N / F ) + 1 ) * F ) - N ); } } package furgl.stupidThings.client.renderer.entity; import furgl.stupidThings.client.model.ModelBalloon; import furgl.stupidThings.common.StupidThings; import furgl.stupidThings.common.entity.EntityBalloon; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityHanging; import net.minecraft.util.ResourceLocation; public class RenderBalloon extends RenderLiving { private static final ResourceLocation TEXTURE = new ResourceLocation(StupidThings.MODID+":textures/entity/balloon.png"); public RenderBalloon(RenderManager renderManagerIn) { super(renderManagerIn, new ModelBalloon(), 0.3f); } private double interpolateValue(double start, double end, double pct) { return start + (end - start) * pct; } @Override /**Copied and slightly modified from RenderLiving*/ protected void renderLeash(EntityBalloon entityLivingIn, double x, double y, double z, float entityYaw, float partialTicks) { y -= 1.1d; z -= 0.3d; Entity entity = entityLivingIn.getLeashedToEntity(); if (entity != null && !entity.isDead) { y = y - (1.6D - (double)entityLivingIn.height) * 0.5D; Tessellator tessellator = Tessellator.getInstance(); BufferBuilder vertexbuffer = tessellator.getBuffer(); double d0 = this.interpolateValue((double)entity.prevRotationYaw, (double)entity.rotationYaw, (double)(partialTicks * 0.5F)) * 0.01745329238474369D; double d1 = this.interpolateValue((double)entity.prevRotationPitch, (double)entity.rotationPitch, (double)(partialTicks * 0.5F)) * 0.01745329238474369D; double d2 = Math.cos(d0); double d3 = Math.sin(d0); double d4 = Math.sin(d1); if (entity instanceof EntityHanging) { d2 = 0.0D; d3 = 0.0D; d4 = -1.0D; } double d5 = Math.cos(d1); double d6 = this.interpolateValue(entity.prevPosX, entity.posX, (double)partialTicks) - d2 * 0.7D - d3 * 0.5D * d5; double d7 = this.interpolateValue(entity.prevPosY + (double)entity.getEyeHeight() * 0.7D, entity.posY + (double)entity.getEyeHeight() * 0.7D, (double)partialTicks) - d4 * 0.5D - 0.25D; double d8 = this.interpolateValue(entity.prevPosZ, entity.posZ, (double)partialTicks) - d3 * 0.7D + d2 * 0.5D * d5; double d9 = this.interpolateValue((double)entityLivingIn.prevRenderYawOffset, (double)entityLivingIn.renderYawOffset, (double)partialTicks) * 0.01745329238474369D + (Math.PI / 2D); d2 = Math.cos(d9) * (double)entityLivingIn.width * 0.4D; d3 = Math.sin(d9) * (double)entityLivingIn.width * 0.4D; double d10 = this.interpolateValue(entityLivingIn.prevPosX, entityLivingIn.posX, (double)partialTicks) + d2; double d11 = this.interpolateValue(entityLivingIn.prevPosY, entityLivingIn.posY, (double)partialTicks)-1d; //added -1 double d12 = this.interpolateValue(entityLivingIn.prevPosZ, entityLivingIn.posZ, (double)partialTicks) + d3-0.5d; //added -0.3d x = x + d2; z = z + d3; double d13 = (double)((float)(d6 - d10)); double d14 = (double)((float)(d7 - d11)); double d15 = (double)((float)(d8 - d12)); GlStateManager.disableTexture2D(); GlStateManager.disableLighting(); GlStateManager.disableCull(); vertexbuffer.begin(5, DefaultVertexFormats.POSITION_COLOR); for (int j = 0; j <= 24; ++j) { float f3 = (float)j / 24.0F; vertexbuffer.pos(x + d13 * (double)f3 + 0.0D, y + d14 * (double)(f3 * f3 + f3) * 0.5D + (double)((24.0F - (float)j) / 18.0F + 0.125F), z + d15 * (double)f3).color(1,1,1, 1.0F).endVertex(); vertexbuffer.pos(x + d13 * (double)f3 + 0.025D, y + d14 * (double)(f3 * f3 + f3) * 0.5D + (double)((24.0F - (float)j) / 18.0F + 0.125F) + 0.025D, z + d15 * (double)f3).color(1,1,1, 1.0F).endVertex(); } tessellator.draw(); vertexbuffer.begin(5, DefaultVertexFormats.POSITION_COLOR); for (int k = 0; k <= 24; ++k) { float f7 = (float)k / 24.0F; vertexbuffer.pos(x + d13 * (double)f7 + 0.0D, y + d14 * (double)(f7 * f7 + f7) * 0.5D + (double)((24.0F - (float)k) / 18.0F + 0.125F) + 0.025D, z + d15 * (double)f7).color(1,1,1, 1.0F).endVertex(); vertexbuffer.pos(x + d13 * (double)f7 + 0.025D, y + d14 * (double)(f7 * f7 + f7) * 0.5D + (double)((24.0F - (float)k) / 18.0F + 0.125F), z + d15 * (double)f7 + 0.025D).color(1,1,1, 1.0F).endVertex(); } tessellator.draw(); GlStateManager.enableLighting(); GlStateManager.enableTexture2D(); GlStateManager.enableCull(); } } @Override protected ResourceLocation getEntityTexture(EntityBalloon entity) { return TEXTURE; } }/** This program simulates the rolling of dice. */ public class DiceDemo { public static void main(String[] args) { final int DIE1_SIDES = 6; // Number of sides for die #1 final int DIE2_SIDES = 12; // Number of sides for die #2 final int MAX_ROLLS = 5; // Number of times to roll // Create two instances of the Die class. Die die1 = new Die(DIE1_SIDES); Die die2 = new Die(DIE2_SIDES); // Display the initial state of the dice. System.out.println("This simulates the rolling of a " + DIE1_SIDES + " sided die and a " + DIE2_SIDES + " sided die."); System.out.println("Initial value of the dice:"); System.out.println(die1.getValue() + " " + die2.getValue()); // Roll the dice five times. System.out.println("Rolling the dice " + MAX_ROLLS + " times."); for (int i = 0; i < MAX_ROLLS; i++) { // Roll the dice. die1.roll(); die2.roll(); // Display the values of the dice. System.out.println(die1.getValue() + " " + die2.getValue()); } } }1-10 package com.emistoolbox.lib.data; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.emistoolbox.lib.util.OrderedPair; public class BipartiteGraph extends HashSet> { public Map> getHeadMap () { Map> map = new HashMap> (); for (OrderedPair pair : this) { List list = map.get (pair.s); if (list == null) { list = new ArrayList (); map.put (pair.s,list); } list.add (pair.t); } return map; } public Map> getTailMap () { Map> map = new HashMap> (); for (OrderedPair pair : this) { List list = map.get (pair.t); if (list == null) { list = new ArrayList (); map.put (pair.t,list); } list.add (pair.s); } return map; } public void assertUniqueness () { assertUniqueness (getHeadMap ()); assertUniqueness (getTailMap ()); } public static void assertUniqueness (Map> map) { for (List value : map.values ()) if (value.size () > 1) throw new Error (); } public static Map uniquify (Map> map) { Map uniqueMap = new HashMap (); for (Entry> entry : map.entrySet ()) { if (entry.getValue ().size () > 1) throw new Error (); uniqueMap.put (entry.getKey (),entry.getValue ().get (0)); } return uniqueMap; } } 0 /* * traQ v3 * traQ v3 API * * The version of the OpenAPI document: 3.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.github.motoki317.traq4j.api; import com.github.motoki317.traq4j.ApiException; import com.github.motoki317.traq4j.model.ClipFolder; import com.github.motoki317.traq4j.model.ClippedMessage; import com.github.motoki317.traq4j.model.MessageClip; import com.github.motoki317.traq4j.model.PatchClipFolderRequest; import com.github.motoki317.traq4j.model.PostClipFolderMessageRequest; import com.github.motoki317.traq4j.model.PostClipFolderRequest; import java.util.UUID; import org.junit.Test; import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * API tests for ClipApi */ @Ignore public class ClipApiTest { private final ClipApi api = new ClipApi(); /** * メッセージをクリップフォルダに追加 * * 指定したメッセージを指定したクリップフォルダに追加します。 * * @throws ApiException * if the Api call fails */ @Test public void clipMessageTest() throws ApiException { UUID folderId = null; PostClipFolderMessageRequest postClipFolderMessageRequest = null; ClippedMessage response = api.clipMessage(folderId, postClipFolderMessageRequest); // TODO: test validations } /** * クリップフォルダを作成 * * クリップフォルダを作成します。 既にあるフォルダと同名のフォルダを作成することは可能です。 * * @throws ApiException * if the Api call fails */ @Test public void createClipFolderTest() throws ApiException { PostClipFolderRequest postClipFolderRequest = null; ClipFolder response = api.createClipFolder(postClipFolderRequest); // TODO: test validations } /** * クリップフォルダを削除 * * 指定したクリップフォルダを削除します。 * * @throws ApiException * if the Api call fails */ @Test public void deleteClipFolderTest() throws ApiException { UUID folderId = null; api.deleteClipFolder(folderId); // TODO: test validations } /** * クリップフォルダ情報を編集 * * 指定したクリップフォルダの情報を編集します。 * * @throws ApiException * if the Api call fails */ @Test public void editClipFolderTest() throws ApiException { UUID folderId = null; PatchClipFolderRequest patchClipFolderRequest = null; api.editClipFolder(folderId, patchClipFolderRequest); // TODO: test validations } /** * クリップフォルダ情報を取得 * * 指定したクリップフォルダの情報を取得します。 * * @throws ApiException * if the Api call fails */ @Test public void getClipFolderTest() throws ApiException { UUID folderId = null; ClipFolder response = api.getClipFolder(folderId); // TODO: test validations } /** * クリップフォルダのリストを取得 * * 自身が所有するクリップフォルダのリストを取得します。 * * @throws ApiException * if the Api call fails */ @Test public void getClipFoldersTest() throws ApiException { List response = api.getClipFolders(); // TODO: test validations } /** * フォルダ内のクリップのリストを取得 * * 指定したフォルダ内のクリップのリストを取得します。 `order`を指定しない場合、クリップした日時の新しい順で返されます。 * * @throws ApiException * if the Api call fails */ @Test public void getClipsTest() throws ApiException { UUID folderId = null; Integer limit = null; Integer offset = null; String order = null; List response = api.getClips(folderId, limit, offset, order); // TODO: test validations } /** * 自分のクリップを取得 * * 対象のメッセージの自分のクリップの一覧を返します。 * * @throws ApiException * if the Api call fails */ @Test public void getMessageClipsTest() throws ApiException { UUID messageId = null; List response = api.getMessageClips(messageId); // TODO: test validations } /** * メッセージをクリップフォルダから除外 * * 指定したフォルダから指定したメッセージのクリップを除外します。 既に外されているメッセージを指定した場合は204を返します。 * * @throws ApiException * if the Api call fails */ @Test public void unclipMessageTest() throws ApiException { UUID folderId = null; UUID messageId = null; api.unclipMessage(folderId, messageId); // TODO: test validations } } package com.dburyak.sandbox.sandboxspringboot.repository; import com.dburyak.sandbox.sandboxspringboot.domain.Position; import com.dburyak.sandbox.sandboxspringboot.domain.User; import java.util.List; public interface UserRepositoryCustomQueries { Integer maxSalary(); void updateFirstName(String userId, String newFirstName); Long deleteByLstName(String lastName); void incrementNumMonths(String userId); List userWithContactInfo(); List workersByPosition(Position position); } /** * General utility classes. */ package de.javagl.rendering.core.utils; package com.example.hp.myapplication.Model; public class Food { private String Name, Image,Description,Price,Discount,MenuId; public Food(){ } public Food(String name, String image,String menuId){ Name = name; Image = image; MenuId = menuId; } public Food(String name, String image, String description, String price, String discount, String menuId){ Name = name; Image = image; Description = description; Price = price; Discount = discount; MenuId = menuId; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getImage() { return Image; } public void setImage(String image) { Image = image; } public String getDescription() { return Description; } public void setDescription(String description) { Description = description; } public String getPrice() { return Price; } public void setPrice(String price) { Price = price; } public String getDiscount() { return Discount; } public void setDiscount(String discount) { Discount = discount; } public String getMenuId() { return MenuId; } public void setMenuId(String menuId) { MenuId = menuId; } } package com.codeyn.zk.fetcher; import java.util.List; import com.codeyn.zk.core.ZkNodeStore; public class ChildrenFetcher extends AbstractFetcher { private List lastSnapShot; private ChildrenConverter converter; public ChildrenFetcher(ZkNodeStore zkNodeStore) { super(zkNodeStore); } public ChildrenFetcher(ZkNodeStore zkNodeStore, ChildrenConverter converter) { super(zkNodeStore); this.converter = converter; } public List getNodeChildren() { List children = isClosed() ? lastSnapShot : zkNodeStore.getChildren(); return children == null ? null : children; } public boolean contains(String childName) { List children = getNodeChildren(); if (children == null) { return false; } return children.contains(childName); } public synchronized void onChildrenUpdate() { if (converter != null && !isClosed()) { List children = zkNodeStore.getChildren(); if (children == null) { convertedObj = null; } else { convertedObj = converter.convert(children); } } } @Override protected void onClose() { zkNodeStore.removeChildrenFetcher(this); lastSnapShot = zkNodeStore.getChildren(); } } ROOT/src/FileUploadServlet.java import java.io.*; import java.util.*; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import javax.servlet.ServletContext; import javax.servlet.ServletOutputStream; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; @WebServlet("/FileUploadServlet") @MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB maxFileSize=1024*1024*50, // 50 MB maxRequestSize=1024*1024*100) // 100 MB public class FileUploadServlet extends HttpServlet { /** FileUploadServlet processes a multipart mime .xlsx upload and converts * it to a bar-delimited csv before saving it to the local server. * (currently doesn't support any other file format) */ private static HashMap> _rows = new HashMap>(); private static HashMap _zipcodeMap = new HashMap(); private static final String _filePath = "/var/lib/tomcat7/webapps/ROOT/tmp/"; private static class _FIELDS { //constants used to access fields by their column number private static int zip = 0; private static int type = 1; private static int city = 2; private static int acceptableCity = 3; private static int state = 4; private static int county = 5; } private static class Zipcode { //Zipcode represents a row in the spreadsheet //TODO: Perhaps consider renaming to Row? //EDIT: Row is already an object in POI. private String zip; private String city; private String state; private String county; public Zipcode(String zip, String city, String state, String county) { this.zip = zip; this.city = city; this.state = state; this.county = county; } @Override public String toString() { return zip.trim() +"|"+city.trim()+"|"+state.trim()+"|"+county.trim(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, NullPointerException { /** doPost: save .xlsx multipart upload as bar delimited file at * "/tmp". */ response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.write(" "); String fileName = null; //the name of the file as uploaded. String shortName = null; //the basename of output file String fullName = null; //the pathname + basename of output file //Get all the parts from request and write it to the file on server //_rows = [str(cell) for cell in [row for row in [part for part in request.getParts()]]] for (Part part : request.getParts()) { fileName = getFileName(part); InputStream inpSt = part.getInputStream(); //try stmt in case they up'd wrong ftype try { XSSFWorkbook workbook = new XSSFWorkbook(inpSt); Sheet firstSheet = workbook.getSheetAt(0); for (Iterator rit = firstSheet.rowIterator(); rit.hasNext();) { ArrayList cells = new ArrayList(); int count = 0; Row row = rit.next(); for(int i = 0; i<7; i++) { Cell cell = row.getCell(i, Row.CREATE_NULL_AS_BLANK); if(i!=4) { switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: String place = cell.toString(); cells.add(place); break; case Cell.CELL_TYPE_BLANK: String value = ""; cells.add(value); break; case Cell.CELL_TYPE_NUMERIC: String number = cell.toString(); cells.add(number); break; } } _rows.put(count, cells); } workbook.close(); for(int key : _rows.keySet()) { ArrayList fields = _rows.get(key); _zipcodeMap = getZipcodeMap(fields); } } for(int Key : _zipcodeMap.keySet()) { Object zipcode = _zipcodeMap.get(Key); List list = new ArrayList(); String Zipcode = zipcode.toString(); list.add(Zipcode); String[] name = fileName.split("\\."); shortName = name[0] + ".txt"; fullName = _filePath + name[0] + ".txt"; useBufferedWriter(list, fullName); } _zipcodeMap.clear(); _rows.clear(); File file = new File(request.getServletContext().getAttribute("FILES_DIR")+File.separator+shortName); out.write("File "+shortName+ " uploaded successfully."); out.write("
"); out.write("Download "+shortName+""); } catch(org.apache.poi.POIXMLException e) { out.write("
Only .xlsx files are supported at this time.
"); } out.write(" "); } } private String getFileName(Part part) throws NullPointerException { /** getFileName: get file name from HTTP header content-disposition. */ String contentDisp = part.getHeader("content-disposition"); System.out.println("content-disposition header= "+contentDisp); String[] tokens = contentDisp.split(";"); for (String token : tokens) { if (token.trim().startsWith("filename")) { return token.substring(token.indexOf("=") + 2, token.length()-1); } } throw new NullPointerException("Request header did not contain a file name."); } public static HashMap getZipcodeMap(ArrayList fieldArr) { int count = 1; //start at 1 to skip the header. TODO is there still a header? String zip = fieldArr.get(_FIELDS.zip); String type = fieldArr.get(_FIELDS.type); String city = fieldArr.get(_FIELDS.city); String state = fieldArr.get(_FIELDS.state); String county = fieldArr.get(_FIELDS.county); String acceptableCity = fieldArr.get(_FIELDS.acceptableCity); String fullZip = fiveDigit(zip); //processes lines with only one city for given zip if(type.equals("STANDARD") && acceptableCity.equals("") && !county.equals("")) { Zipcode zpcd = new Zipcode(fullZip, city, state, county); _zipcodeMap.put(count, zpcd); } //this block processes lines that have only one addt'l city for given zip else if(type.equals("STANDARD") && !acceptableCity.equals("") && !acceptableCity.contains(",") && !county.equals("")) { //passes primary city into map Zipcode zpcd = new Zipcode(fullZip, city, state, county); _zipcodeMap.put(count, zpcd); city = acceptableCity; //acceptable name swapped in place of primary name count++; //addit'l city passed to map Zipcode zipcode = new Zipcode(fullZip, city, state, county); _zipcodeMap.put(count, zipcode); } else if(type.equals("STANDARD") && !acceptableCity.equals("") && acceptableCity.contains(",") && !county.equals("")) { multiCity(fieldArr); } return _zipcodeMap; } public static HashMap multiCity(ArrayList fieldArr) { /* multiCity: processes lines with multiple, comma-delimited acceptable * cities. */ int count = _zipcodeMap.size(); String zip = fieldArr.get(_FIELDS.zip); //String type = fieldArr.get(_FIELDS.type); //why is this line commented out? String city = fieldArr.get(_FIELDS.city); String state = fieldArr.get(_FIELDS.state); String county = fieldArr.get(_FIELDS.county); String acceptableCity = fieldArr.get(_FIELDS.acceptableCity); String fullZip = fiveDigit(zip); //creates hashmap entry for primary city Zipcode zpcd = new Zipcode(fullZip, city, state, county); _zipcodeMap.put(count, zpcd); count++; String[] cities = acceptableCity.split(","); for(String ciudad : cities) { //creates entry for each addt'l city name for given zipcode Zipcode zipcode = new Zipcode(fullZip, ciudad.trim(), state, county); _zipcodeMap.put(count, zipcode); //logger.info("acceptable city added: "+ciudad+", "+zip); count++; } return _zipcodeMap; } public static String fiveDigit(String zip) { /* fiveDigit: extracts the primary zip code (the 90210 in 90210-1234), * discarding the +4 addons. If the remaining zip code is less than 5 * digits long, it is zero-padded on the left. */ String[] zipSplit = zip.split("\\."); //TODO: is this correct? zip= zipSplit[0]; //Perhaps the following could be replaced with this?: //while ( zip.length() < 5 ) zip += "0"+zip; //return zip; if(zip.length()==5) { return zip; } else if(zip.length()==4) { zip = "0"+zip; } else if (zip.length()==3) { zip = "00"+zip; } return zip; } public static void useBufferedWriter(List content, String path) { /* useBufferedWriter: creates/appends file at `path' with string * contents `content'. */ File file = new File(path); Writer fileWriter = null; BufferedWriter bufferedWriter = null; try { fileWriter = new FileWriter(file, true); bufferedWriter = new BufferedWriter(fileWriter); for (String line : content) { line += System.getProperty("line.separator"); bufferedWriter.write(line); } } catch (IOException e) { System.err.println("Error writing the file : "); e.printStackTrace(); } finally { if (bufferedWriter != null && fileWriter != null) { try { bufferedWriter.close(); fileWriter.close(); } catch(IOException e) { e.printStackTrace(); } } } } } CD4017BE/ThermokineticEngineering package cd4017be.kineng.tileentity; import static cd4017be.kineng.physics.Ticking.dt; import static cd4017be.lib.network.Sync.GUI; import static cd4017be.lib.network.Sync.Type.F32; import static net.minecraftforge.energy.CapabilityEnergy.ENERGY; import cd4017be.kineng.Main; import cd4017be.kineng.physics.DynamicForce; import cd4017be.kineng.physics.ForceCon; import cd4017be.lib.Gui.AdvancedContainer; import cd4017be.lib.Gui.AdvancedContainer.IStateInteractionHandler; import cd4017be.lib.Gui.ModularGui; import cd4017be.lib.Gui.comp.*; import cd4017be.lib.network.*; import cd4017be.lib.tileentity.BaseTileEntity; import cd4017be.lib.tileentity.BaseTileEntity.ITickableServerOnly; import cd4017be.lib.util.Utils; import cd4017be.math.cplx.CplxD; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.PacketBuffer; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.MathHelper; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.energy.IEnergyStorage; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; /** * @author CD4017BE */ public class FluxCoil extends BaseTileEntity implements IForceProvider, IGuiHandlerTile, IStateInteractionHandler, ITickableServerOnly { public static double J_RF, E_MAX; @Sync(to = SAVE) public final Coil coil = new Coil(); @Override public void update() { int e = coil.getEnergyStored(); if (e <= 0) return; IEnergyStorage es = Utils.neighborCapability(this, getOrientation().front, ENERGY); if (es == null) return; coil.extractEnergy(es.receiveEnergy(e, false), false); } @Override public DynamicForce connect(IKineticLink link, EnumFacing side) { if (side != getOrientation().back || link != null && link.type() != IKineticLink.T_MAGNETIC) return null; return coil; } @Override public boolean hasCapability(Capability capability, EnumFacing facing) { return capability == ENERGY; } @Override @SuppressWarnings("unchecked") public T getCapability(Capability capability, EnumFacing facing) { return capability == ENERGY ? (T)coil : null; } @Override public AdvancedContainer getContainer(EntityPlayer player, int id) { return new AdvancedContainer(this, StateSyncAdv.of(false, coil), player); } private static final ResourceLocation GUI_TEX = new ResourceLocation(Main.ID, "textures/gui/debug.png"); @Override @SideOnly(Side.CLIENT) public ModularGui getGuiScreen(EntityPlayer player, int id) { ModularGui gui = new ModularGui(getContainer(player, id)); GuiFrame frame = new GuiFrame(gui, 122, 86, 5) .background(GUI_TEX, 0, 128).title("gui.kineng.fluxcoil.name", 0.5F); new Progressbar(frame, 16, 62, 8, 16, 210, 128, Progressbar.V_FILL, ()-> coil.E / coil.Emax); new Tooltip(frame, 16, 62, 8, 16, "gui.kineng.fluxcoil.charge", ()-> new Object[] {coil.E / J_RF, coil.Emax / J_RF}); new Progressbar(frame, 7, 62, 26, 16, 226, 128, Progressbar.V_FILL, coil::efficiency); new Tooltip(frame, 7, 62, 26, 16, "gui.kineng.fluxcoil.eff", ()-> new Object[] { coil.efficiency() * 100D, coil.dE0 < 0 ? "<-" : "->", Math.abs(coil.dE0 / J_RF), Math.abs(coil.dE1 / dt) }); new Progressbar(frame, 7, 62, 71, 16, 233, 128, Progressbar.V_FILL, ()-> coil.force() / coil.maxForce()); new Progressbar(frame, 7, 62, 71, 16, 233, 128, Progressbar.V_FILL, ()-> coil.force() / coil.maxForce(), 0.0, -1.0); new Tooltip(frame, 7, 62, 71, 16, "gui.kineng.fluxcoil.force", ()-> new Object[] {coil.force()}); new Progressbar(frame, 16, 62, 80, 16, 240, 128, Progressbar.V_FILL, ()-> coil.v / (coil.v0 * 2.0)); new Tooltip(frame, 16, 62, 80, 16, "gui.kineng.fluxcoil.vel", ()-> new Object[] {coil.v}); new Slider(frame, 16, 5, 66, 99, 14, 240, 190, false, ()-> coil.v0, (x)-> { coil.v0 = Math.rint(x * 2.0) * 0.5; }, ()-> gui.sendPkt((byte)0, (float)coil.v0), 30, -30).scroll(0.5F).tooltip("gui.kineng.fluxcoil.target"); new Button(frame, 16, 16, 44, 39, 0, ()-> coil.engaged ? 1 : 0, (a)-> gui.sendPkt((byte)1)) .texture(194, 128).tooltip("gui.kineng.fluxcoil.on#"); gui.compGroup = frame; return gui; } @Override public boolean canInteract(EntityPlayer player, AdvancedContainer cont) { return canPlayerAccessUI(player); } @Override public void handleAction(PacketBuffer pkt, EntityPlayerMP sender) throws Exception { switch(pkt.readByte()) { case 0: double v0 = pkt.readFloat(); if (Math.abs(v0) > 30) v0 = Math.copySign(30, v0); else if (Double.isNaN(v0)) v0 = 0.0; coil.v0 = v0; break; case 1: coil.engaged = !coil.engaged; break; } } public static class Coil extends DynamicForce implements IEnergyStorage { @Sync(to=GUI|SAVE, type=F32) public double v0 = 5.0; @Sync(to=GUI|SAVE) public double E; @Sync(to=GUI, type=F32) public double v, dE0, dE1, Emax = E_MAX, Jrf = J_RF; @Sync(to=GUI|SAVE, tag="on") public boolean engaged; @Override public void work(double dE, double ds, double v1) { this.v = v1; this.E -= dE0 = v1 != 0 ? dE * v0 / v1 : 0; if (this.E < 0) this.E = 0; dE1 = dE; } @Override public ForceCon getM(CplxD M, double av) { if (engaged) { double E = MathHelper.clamp(this.E, av * r / v0 > 1.0 ? 1 : 0, Emax); Fdv = -E * (Emax - E) / (Emax * dt * (v0 * v0 + 5.0)); F = -v0 * Fdv; } else { Fdv = 0; F = 0; } return super.getM(M, av); } @Override public int receiveEnergy(int maxReceive, boolean simulate) { maxReceive = Math.max(0, Math.min(maxReceive, -getEnergyStored())); if (!simulate) E += maxReceive * Jrf; return maxReceive; } @Override public int extractEnergy(int maxExtract, boolean simulate) { maxExtract = Math.max(0, Math.min(maxExtract, getEnergyStored())); if (!simulate) E -= maxExtract * Jrf; return maxExtract; } @Override public int getEnergyStored() { return (int)((E - Emax * 0.5) / Jrf); } @Override public int getMaxEnergyStored() { return MathHelper.floor(Emax * 0.5 / Jrf); } @Override public boolean canExtract() { return true; } @Override public boolean canReceive() { return true; } public double efficiency() { return dE0 > 0 ? dE1 / dE0 : dE1 < 0 ? dE0 / dE1 : 1.0; } public double force() { return dE1 == 0 ? 0 : dE1 / (v * dt); } public double maxForce() { return 0.25 * Emax * v0 / ((v0 * v0 + 1.0) * dt); } } } package com.justandreyb.liquid_recipes.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import com.justandreyb.liquid_recipes.entity.Recipe; public interface RecipeRepository extends JpaRepository { List findByName(String name); List findAllByCreatorId(String creatorId); } package com.dpk.wgj.bean; import java.io.Serializable; /** * Created by zhoulin on 2018/7/7. * 电瓶车信息 */ public class CarInfo implements Serializable { private int carId; private String carNumber; private String carType; private int carSeat; private int carDriverIdA; private int carDriverIdB; public String getCarType() { return carType; } public void setCarType(String carType) { this.carType = carType; } public int getCarSeat() { return carSeat; } public void setCarSeat(int carSeat) { this.carSeat = carSeat; } public int getCarId() { return carId; } public void setCarId(int carId) { this.carId = carId; } public String getCarNumber() { return carNumber; } public void setCarNumber(String carNumber) { this.carNumber = carNumber; } public int getCarDriverIdA() { return carDriverIdA; } public void setCarDriverIdA(int carDriverIdA) { this.carDriverIdA = carDriverIdA; } public int getCarDriverIdB() { return carDriverIdB; } public void setCarDriverIdB(int carDriverIdB) { this.carDriverIdB = carDriverIdB; } @Override public String toString() { return "CarInfo{" + "carId=" + carId + ", carNumber='" + carNumber + '\'' + ", carType='" + carType + '\'' + ", carSeat=" + carSeat + '}'; } } optaplanner-core/src/test/java/org/optaplanner/core/impl/exhaustivesearch/node/comparator/AbstractNodeComparatorTest.java /* * Copyright 2014 Red Hat, Inc. and/or 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 org.optaplanner.core.impl.exhaustivesearch.node.comparator; import java.util.Comparator; import org.optaplanner.core.api.score.buildin.simple.SimpleScore; import org.optaplanner.core.impl.exhaustivesearch.node.ExhaustiveSearchNode; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public abstract class AbstractNodeComparatorTest { protected ExhaustiveSearchNode buildNode(int depth, String score, long parentBreadth, long breadth) { return buildNode(depth, SimpleScore.parseScore(score), SimpleScore.parseScore(score).toInitializedScore(), parentBreadth, breadth); } protected ExhaustiveSearchNode buildNode(int depth, String score, int optimisticBound, long parentBreadth, long breadth) { return buildNode(depth, SimpleScore.parseScore(score), SimpleScore.valueOfInitialized(optimisticBound), parentBreadth, breadth); } protected ExhaustiveSearchNode buildNode(int depth, SimpleScore score, SimpleScore optimisticBound, long parentBreadth, long breadth) { ExhaustiveSearchNode node = mock(ExhaustiveSearchNode.class); when(node.getDepth()).thenReturn(depth); when(node.getScore()).thenReturn(score); when(node.getOptimisticBound()).thenReturn(optimisticBound); when(node.getParentBreadth()).thenReturn(parentBreadth); when(node.getBreadth()).thenReturn(breadth); when(node.toString()).thenReturn(score.toString()); return node; } protected static void assertLesser(Comparator comparator, ExhaustiveSearchNode a, ExhaustiveSearchNode b) { assertTrue("Node (" + a + ") must be lesser than node (" + b + ").", comparator.compare(a, b) < 0); assertTrue("Node (" + b + ") must be greater than node (" + a + ").", comparator.compare(b, a) > 0); } protected static void assertScoreCompareToOrder(Comparator comparator, ExhaustiveSearchNode... nodes) { for (int i = 0; i < nodes.length; i++) { for (int j = i + 1; j < nodes.length; j++) { assertLesser(comparator, nodes[i], nodes[j]); } } } } package com.example.deliveryboy; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatDelegate; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import android.service.autofill.Dataset; import android.util.Log; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.example.deliveryboy.PojoClasses.OrderDetails; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.textview.MaterialTextView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class orderDetailsDisplay extends AppCompatActivity { private TextView customerName , phoneNumber , paymentMethod , hotel , dish , price , time , houseno ,housename , landmark , street , date; private CheckBox placed , picked , delivered; private OrderDetails orderDetails; private RecyclerView DishOrderDetails; private RecyclerView.LayoutManager layoutManager; private String dishNames , orderKey; private MaterialTextView hotelAddress; private boolean isAssignedStatus = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES); setContentView(R.layout.activity_order_details_display); dishNames = new String(); customerName = findViewById(R.id.orderDetailName); phoneNumber = findViewById(R.id.orderDetailPhoneNumber); paymentMethod = findViewById(R.id.paymentMethod); hotel = findViewById(R.id.Hotel); price = findViewById(R.id.price); time = findViewById(R.id.time); houseno = findViewById(R.id.houseNo); housename = findViewById(R.id.houseName); dish = findViewById(R.id.DishName); landmark = findViewById(R.id.landmark); street = findViewById(R.id.street); date = findViewById(R.id.date); hotelAddress=findViewById(R.id.Hotel_Address); placed = findViewById(R.id.orderPlacedCheck); picked = findViewById(R.id.orderPickedCheck); delivered = findViewById(R.id.orderDeliveredCheck); Intent getOrderDetails = getIntent(); orderDetails = getOrderDetails.getParcelableExtra("OrderDetails"); orderKey = getOrderDetails.getStringExtra("OrderKey"); isAssignedStatus = getOrderDetails.getBooleanExtra("isAssignedStatus" , false); setCheckBoxes(orderKey); setOrderDetails(orderDetails); getHotel(orderDetails.getHotelId()); getDish(orderKey); placed.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { DatabaseReference setOrderChanges = FirebaseDatabase.getInstance().getReference().child(getApplicationContext().getResources().getString(R.string.OrderNode)).child(orderKey); if (!isAssignedStatus){ placed.setChecked(false); Toast.makeText(getApplicationContext() , "Order not assigned !" , Toast.LENGTH_SHORT).show(); }else{ if (isChecked) setOrderChanges.child(getApplicationContext().getResources().getString(R.string.placedIndexStatus)).setValue("yes"); else setOrderChanges.child(getApplicationContext().getResources().getString(R.string.placedIndexStatus)).setValue("no"); } } }); picked.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { DatabaseReference setOrderChanges = FirebaseDatabase.getInstance().getReference().child(getApplicationContext().getResources().getString(R.string.OrderNode)).child(orderKey); Log.d("tag", "onCheckedChanged: "+isAssignedStatus); if (!isAssignedStatus){ picked.setChecked(false); Toast.makeText(getApplicationContext() , "Order not assigned !" , Toast.LENGTH_SHORT).show(); }else{ if (isChecked) setOrderChanges.child(getApplicationContext().getResources().getString(R.string.pickupIndexStatus)).setValue("yes"); else setOrderChanges.child(getApplicationContext().getResources().getString(R.string.pickupIndexStatus)).setValue("no"); } } }); delivered.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { DatabaseReference setOrderChanges = FirebaseDatabase.getInstance().getReference().child(getApplicationContext().getResources().getString(R.string.OrderNode)).child(orderKey); Log.d("tag", "onCheckedChanged: "+isAssignedStatus); if (!isAssignedStatus){ delivered.setChecked(false); Toast.makeText(getApplicationContext() , "Order not assigned !" , Toast.LENGTH_SHORT).show(); }else{ if (isChecked){ Toast.makeText(getApplicationContext(),"Order Delivered" , Toast.LENGTH_SHORT).show(); setOrderChanges.child(getApplicationContext().getResources().getString(R.string.deliveryIndexStatus)).setValue("yes"); placed.setClickable(false); picked.setClickable(false); delivered.setClickable(false); } else setOrderChanges.child(getApplicationContext().getResources().getString(R.string.deliveryIndexStatus)).setValue("no"); } } }); } private void setCheckBoxes(String orderKey){ DatabaseReference getOrderStatus = FirebaseDatabase.getInstance().getReference().child(getApplicationContext().getResources().getString(R.string.OrderNode)).child(orderKey); getOrderStatus.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { String placedStatus = snapshot.child(getApplicationContext().getResources().getString(R.string.placedIndexStatus)).getValue(String.class); String pickedStatus = snapshot.child(getApplicationContext().getResources().getString(R.string.pickupIndexStatus)).getValue(String.class); String deliveredStatus = snapshot.child(getApplicationContext().getResources().getString(R.string.deliveryIndexStatus)).getValue(String.class); placed.setChecked(placedStatus.equals("yes")); picked.setChecked(pickedStatus.equals("yes")); delivered.setChecked(deliveredStatus.equals("yes")); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } private void getHotel(String hotelId){ DatabaseReference getHotelNameReference = FirebaseDatabase.getInstance().getReference().child(getApplicationContext().getResources().getString(R.string.HotelNode)).child(hotelId); getHotelNameReference.get().addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()){ String hotel_name = task.getResult().child("hotel_name").getValue(String.class); String hotel_address=task.getResult().child("address").getValue(String.class); hotel.setText(hotel_name); hotelAddress.setText(hotel_address); } } }); } private void getDish(String orderKey){ DatabaseReference getDishDetailsReference = FirebaseDatabase.getInstance().getReference().child(getApplicationContext().getResources().getString(R.string.OrderNode)).child(orderKey).child(getApplicationContext().getResources().getString(R.string.DishNode)); getDishDetailsReference.get().addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()){ for (DataSnapshot snapshot : task.getResult().getChildren()){ String key = snapshot.getKey(); String Quantity = snapshot.child("Quantity").getValue(String.class); DatabaseReference getDishName = FirebaseDatabase.getInstance().getReference().child(getApplicationContext().getResources().getString(R.string.DishNode)).child(key); getDishName.get().addOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()){ String dishname = task.getResult().child("name").getValue(String.class); dishNames = dishNames + dishname + "("+Quantity+") \n"; dish.setText(dishNames); } else { Toast.makeText(getApplicationContext() , "Fetching Data Failed " , Toast.LENGTH_LONG).show(); } } }); } } else { Toast.makeText(getApplicationContext() , "Fetching Data Failed " , Toast.LENGTH_LONG).show(); } } }); } private void setOrderDetails(OrderDetails orderDetails) { customerName.setText(orderDetails.getName()); phoneNumber.setText(orderDetails.getPhoneNumber()); paymentMethod.setText(orderDetails.getCOD().equals("yes")?"Cash On Delivery" : "Payment Done"); price.setText(" ₹ "+orderDetails.getTotal()); time.setText(orderDetails.getTime()); houseno.setText(orderDetails.getHouseNo()); housename.setText(orderDetails.getHouseName()); landmark.setText(orderDetails.getLandmark()); street.setText(orderDetails.getStreet()); date.setText(orderDetails.getDate()); } }JAVA/Java Loops I.java1-10 //Problem Link: https://www.hackerrank.com/challenges/java-loops-i/ import java.util.*; public class table { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int i; for(i=1;i<=10;i++) { System.out.println(n+" x "+i+" = "+(n*i)); } } } package com.daxiang.core.appium; import com.daxiang.core.MobileDevice; import com.daxiang.core.android.AndroidDevice; import io.appium.java_client.AppiumDriver; import io.appium.java_client.android.AndroidDriver; /** * Created by jiangyitao. */ class AndroidDriverBuilder extends AppiumDriverBuilder { public AndroidDriverBuilder(MobileDevice mobileDevice) { super(mobileDevice); } @Override public AppiumDriver build() { MobileDevice mobileDevice = getMobileDevice(); DesiredCapabilitiesBuilder builder = new DesiredCapabilitiesBuilder(mobileDevice) .androidBasic() .androidSkip() .extractChromeAndroidPackageFromContextName(); if (!((AndroidDevice) mobileDevice).greaterOrEqualsToAndroid5()) { builder.androidApiDemos(); // uiautomator1仍然需要指定app } return new AndroidDriver(mobileDevice.getAppiumServer().getUrl(), builder.build()); } public AppiumDriver init() { MobileDevice mobileDevice = getMobileDevice(); DesiredCapabilitiesBuilder builder = new DesiredCapabilitiesBuilder(mobileDevice) .androidBasic(); if (!((AndroidDevice) mobileDevice).greaterOrEqualsToAndroid5()) { builder.androidApiDemos(); // uiautomator1仍然需要指定app } return new AndroidDriver(mobileDevice.getAppiumServer().getUrl(), builder.build()); } } package com.hafiz.www.vo; /** * Desc:ajax请求的json结果 Created by hafiz.zhang on 2017/7/21. */ public class JsonResult { private Integer code = 200; // 请求结果码 private Boolean success = true; // 请求结果 private String msg; // 请求错误信息 private Object data; // 结果数据 public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public static JsonResult newInstanceSuccess() { return newInstanceSuccess(null); } public static JsonResult newInstanceSuccess(Object data) { JsonResult jr = new JsonResult(); jr.setData(data); return jr; } public static JsonResult newInstanceFail(String msg) { JsonResult jr = new JsonResult(); jr.setSuccess(false); jr.setMsg(msg); return jr; } } package com.example.jiayin.helpfordemo.help.activity; import android.content.Intent; import android.graphics.BitmapFactory; import android.os.Bundle; import android.provider.MediaStore; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.avos.avoscloud.AVException; import com.avos.avoscloud.AVFile; import com.avos.avoscloud.AVObject; import com.avos.avoscloud.AVQuery; import com.avos.avoscloud.GetCallback; import com.avos.avoscloud.SaveCallback; import com.example.jiayin.helpfordemo.R; import com.example.jiayin.helpfordemo.app.PrefectInformationActivity; import com.example.jiayin.helpfordemo.app.base.BaseActivity; import com.example.jiayin.helpfordemo.utils.Constant; import com.example.jiayin.helpfordemo.utils.GlideImageLoader; import com.example.jiayin.helpfordemo.utils.OftenUtils; import com.example.jiayin.helpfordemo.utils.pointDialog.dialog.listener.OnOperItemClickL; import com.example.jiayin.helpfordemo.utils.pointDialog.dialog.widget.ActionSheetDialog; import com.hyphenate.chat.EMClient; import com.lzy.imagepicker.ImagePicker; import com.lzy.imagepicker.bean.ImageItem; import com.lzy.imagepicker.ui.ImageGridActivity; import com.lzy.imagepicker.view.CropImageView; import com.sdsmdg.tastytoast.TastyToast; import org.feezu.liuli.timeselector.TimeSelector; import org.feezu.liuli.timeselector.Utils.TextUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import butterknife.Bind; import butterknife.ButterKnife; public class GiveMoneyActivity extends BaseActivity { private static final String TAG = "GiveMoneyActivity"; @Bind(R.id.you_want_thing) EditText youWantThing; @Bind(R.id.start_location) EditText startLocation; @Bind(R.id.start_location_detail) EditText startLocationDetail; @Bind(R.id.end_location) EditText endLocation; @Bind(R.id.end_location_detail) EditText endLocationDetail; @Bind(R.id.phone) EditText phone; @Bind(R.id.end_date) TextView endDate; @Bind(R.id.seek_bar) SeekBar seekBar; @Bind(R.id.text_money) TextView textMoney; @Bind(R.id.et_good_detail) EditText etGoodDetail; @Bind(R.id.imageAction) ImageView imageAction; @Bind(R.id.image_show) ImageView imageShow; @Bind(R.id.btn_publish_reward) Button btnPublishReward; @Bind(R.id.toolbar) Toolbar toolbar; private TimeSelector timeSelector; private String endTime; private String you_want_thing; private String start_location; private String start_location_detail; private String end_location; private String end_location_detail; private String phone_number; private int money; private String thing_detail; private double mStartCurrentLat; private double mStartCurrentLng; private double mEndCurrentLat; private double mEndCurrentLng; private String truename; private String idcard; private int ispass; private byte[] mImageBytes = null; ArrayList images = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_give_money); ButterKnife.bind(this); setSupportActionBar(toolbar); getSupportActionBar().setTitle(R.string.give_money); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getTrueName(); timeSelector = new TimeSelector(this, new TimeSelector.ResultHandler() { @Override public void handle(String time) { endTime = time; endDate.setText(" 期限 " + endTime); } }, getLocalTime(), "2020-12-31 00:00" ); timeSelector.setMode(TimeSelector.MODE.YMDHM); initImagePicker(); initData(); initListener(); } private void initData() { money = getIntent().getIntExtra(Constant.MONEY, money); Log.e(TAG, "initData: " + money); start_location = getIntent().getStringExtra(Constant.START_LOCATION); end_location = getIntent().getStringExtra(Constant.END_LOCATION); mStartCurrentLat = getIntent().getDoubleExtra(Constant.START_CURRENT_LAT, mStartCurrentLat); mStartCurrentLng = getIntent().getDoubleExtra(Constant.START_CURRENT_LNG, mStartCurrentLng); mEndCurrentLat = getIntent().getDoubleExtra(Constant.END_CURRENT_LAT, mEndCurrentLat); mEndCurrentLng = getIntent().getDoubleExtra(Constant.END_CURRENT_LNG, mEndCurrentLng); textMoney.setText("¥" + money + "元"); seekBar.setProgress(money); startLocation.setText(start_location); endLocation.setText(end_location); phone.setText(EMClient.getInstance().getCurrentUser()); } private String getLocalTime() { Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH) + 1; int day = c.get(Calendar.DAY_OF_MONTH); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); return year + "-" + month + "-" + day + " " + hour + ":" + minute; } private void initListener() { endDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { timeSelector.show(); } }); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean b) { textMoney.setText("¥" + progress + "元"); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); imageAction.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ActionSheetDialogNoTitle(); } }); btnPublishReward.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (truename.equals("")||idcard.equals("")||ispass==2||ispass==0){ TastyToast.makeText(getApplication(),"实名认证后才能发布订单哦",TastyToast.LENGTH_LONG,TastyToast.WARNING); }else { commit(); } } }); } /** * 数据存贮: * 你想要的东西:you_want_thing:youWantThing * 起始位置:start_location:startLocation * 起始位置详情:start_location_detail:startLocationDetail * 结束位置:end_location:endLocation * 结束位置详情:end_location_detail:endLocationDetail * 电话号码:phone_number:phone * 期限:纯日期:endTime---TextView:endDate * 悬赏金额:String:moneys---int:money * 你想要的东西详情:thing_detail:etGoodDetail */ private void commit() { you_want_thing = youWantThing.getText().toString().trim(); start_location = startLocation.getText().toString().trim(); start_location_detail = startLocationDetail.getText().toString().trim(); end_location = endLocation.getText().toString().trim(); end_location_detail = endLocationDetail.getText().toString().trim(); phone_number = phone.getText().toString().trim(); String moneys = String.valueOf(seekBar.getProgress()); thing_detail = etGoodDetail.getText().toString().trim(); Log.e(TAG, "commit: " + you_want_thing); Log.e(TAG, "commit: " + start_location); Log.e(TAG, "commit: " + start_location_detail); Log.e(TAG, "commit: " + end_location); Log.e(TAG, "commit: " + end_location_detail); Log.e(TAG, "commit: " + phone_number); Log.e(TAG, "commit: " + moneys); Log.e(TAG, "commit: " + endTime); Log.e(TAG, "commit: " + thing_detail); Log.e(TAG, "commit: " + mStartCurrentLat); Log.e(TAG, "commit: " + mStartCurrentLng); Log.e(TAG, "commit: " + mEndCurrentLat); Log.e(TAG, "commit: " + mEndCurrentLng); boolean cancel = false; View focusView = null; if (TextUtils.isEmpty(you_want_thing)) { youWantThing.setError(getString(R.string.empty_you_want_thing)); focusView = youWantThing; cancel = true; } if (TextUtil.isEmpty(start_location)) { startLocation.setError(getString(R.string.empty_start_location)); focusView = startLocation; cancel = true; } if (TextUtil.isEmpty(start_location_detail)) { startLocationDetail.setError(getString(R.string.empty_start_location_detail)); focusView = startLocationDetail; cancel = true; } if (TextUtil.isEmpty(end_location)) { endLocation.setError(getString(R.string.empty_end_location)); focusView = endLocation; cancel = true; } // if (TextUtil.isEmpty(end_location_detail)) { // endLocationDetail.setError(getString(R.string.empty_end_location_detail)); // focusView = endLocationDetail; // cancel = true; // } if (TextUtil.isEmpty(phone_number)) { phone.setError(getString(R.string.empty_phone_number)); focusView = phone; cancel = true; } if (TextUtil.isEmpty(endTime)) { endDate.setError(getString(R.string.empty_end_date)); focusView = endDate; cancel = true; } if (TextUtil.isEmpty(thing_detail)) { etGoodDetail.setError(getString(R.string.empty_thing_detail)); focusView = etGoodDetail; cancel = true; } if (cancel) { focusView.requestFocus(); } else { final AVObject order_message = new AVObject("order_message"); order_message.put("userId", EMClient.getInstance().getCurrentUser()); order_message.put("you_want_thing", you_want_thing); order_message.put("startLocation", start_location); order_message.put("startLocationDetail", start_location_detail); order_message.put("endLocation", end_location); order_message.put("endLocationDetail", end_location_detail); order_message.put("phone", phone_number); order_message.put("money", seekBar.getProgress()); order_message.put("endDate", endTime); order_message.put("goodDetail", thing_detail); order_message.put("truename",truename); order_message.put("mStartCurrentLat", mStartCurrentLat); order_message.put("mStartCurrentLng", mStartCurrentLng); order_message.put("mEndCurrentLat", mEndCurrentLat); order_message.put("mEndCurrentLng", mEndCurrentLng); order_message.put("goodDetailImg", new AVFile("goodPic", mImageBytes)); order_message.put("status",0); order_message.saveInBackground(new SaveCallback() { @Override public void done(AVException e) { if (e == null) { Intent intent = new Intent(GiveMoneyActivity.this, PayForActivity.class); intent.putExtra(Constant.OBJECT_ID,order_message.getObjectId()); Log.e(TAG, "done: " + order_message.getObjectId()); intent.putExtra(Constant.MONEY, seekBar.getProgress()); startActivity(intent); TastyToast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT, TastyToast.SUCCESS); GiveMoneyActivity.this.finish(); } else { TastyToast.makeText(getApplicationContext(), "出错了" + e.toString(), Toast.LENGTH_SHORT, TastyToast.ERROR); } } }); TastyToast.makeText(getApplicationContext(), "点击了发布悬赏", Toast.LENGTH_SHORT, TastyToast.SUCCESS); } } private void getTrueName(){ AVQuery userDetail = new AVQuery<>("UserDetail"); userDetail.whereEqualTo("userId", EMClient.getInstance().getCurrentUser()); userDetail.getFirstInBackground(new GetCallback() { @Override public void done(AVObject avObject, AVException e) { if (e == null) { truename = (String) avObject.get("truename") == null ? "" : (String) avObject.get("truename"); idcard = (String) avObject.get("idCard") == null ? "" : (String) avObject.get("idCard"); ispass = (int) avObject.get("ispass"); Log.e(TAG, "done: " + truename + idcard ); } } }); } private void initImagePicker(){ ImagePicker imagePicker = ImagePicker.getInstance(); imagePicker.setImageLoader(new GlideImageLoader()); imagePicker.setMultiMode(false); // imagePicker.setStyle(CropImageView.Style.RECTANGLE); // imagePicker.setFocusWidth(800); //裁剪框的宽度。单位像素(圆形自动取宽高最小值) // imagePicker.setFocusHeight(800); //裁剪框的高度。单位像素(圆形自动取宽高最小值) // imagePicker.setOutPutX(1000); //保存文件的宽度。单位像素 // imagePicker.setOutPutY(1000); //保存文件的高度。单位像素 imagePicker.setShowCamera(true); imagePicker.setCrop(false); imagePicker.setSaveRectangle(true); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == ImagePicker.RESULT_CODE_ITEMS) { if (data != null && requestCode == 100) { images = (ArrayList) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS); Log.e(TAG, "onActivityResult: " + images.get(0).path); imageShow.setImageBitmap(BitmapFactory.decodeFile(images.get(0).path)); mImageBytes = OftenUtils.getBytes(images.get(0).path); } else { Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show(); } } } private void ActionSheetDialogNoTitle() { final String[] stringItems = {"拍照", "相册"}; final ActionSheetDialog dialog = new ActionSheetDialog(GiveMoneyActivity.this, stringItems, imageShow); dialog.isTitleShow(false).show(); dialog.setOnOperItemClickL(new OnOperItemClickL() { @Override public void onOperItemClick(AdapterView parent, View view, int position, long id) { switch (position) { case 0: // 直接调起相机 /** * 0.4.7 目前直接调起相机不支持裁剪,如果开启裁剪后不会返回图片,请注意,后续版本会解决 * * 但是当前直接依赖的版本已经解决,考虑到版本改动很少,所以这次没有上传到远程仓库 * * 如果实在有所需要,请直接下载源码引用。 */ //打开选择,本次允许选择的数量 Intent intent = new Intent(GiveMoneyActivity.this, ImageGridActivity.class); intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机 startActivityForResult(intent, 100); break; case 1: Intent intent1 = new Intent(GiveMoneyActivity.this, ImageGridActivity.class); intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES, images); //ImagePicker.getInstance().setSelectedImages(images); startActivityForResult(intent1, 100); break; } TastyToast.makeText(getApplicationContext(), stringItems[position] + position, Toast.LENGTH_SHORT, TastyToast.DEFAULT); dialog.dismiss(); } }); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { onBackPressed(); } return super.onOptionsItemSelected(item); } } package io.github.duckasteroid.progress.utils; import io.github.duckasteroid.progress.ProgressMonitor; import java.io.IOException; import java.io.InputStream; /** * Wraps an input stream to report 1 unit of work for every byte {@link #read()}. * Clients should set the {@link ProgressMonitor#setSize(long)} prior to invoking for this * to report correctly. * When the stream is {@link #close() closed} the monitor is marked done */ public class InputStreamProgress extends InputStream { private final transient InputStream delegate; private final transient ProgressMonitor monitor; public InputStreamProgress(InputStream delegate, ProgressMonitor monitor) { this.delegate = delegate; this.monitor = monitor; } @Override public int read() throws IOException { if (monitor.isCancelled()) { throw new IOException("Read operation cancelled by monitor"); } monitor.worked(1); return delegate.read(); } @Override public void close() throws IOException { monitor.done(); super.close(); } } ontopia/ontopia /* * #! * Ontopia Engine * #- * Copyright (C) 2001 - 2013 The Ontopia 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 net.ontopia.topicmaps.core; import java.util.Collection; /** * PUBLIC: Implemented by an object which represents a topic name, which * is a topic characteristic.

* * This interface is also used for 'variant' elements in the XTM 1.0 * syntax, when extended by the VariantNameIF interface.

*/ public interface TopicNameIF extends NameIF, ScopedIF, TypedIF, ReifiableIF { String EVENT_ADDED = "TopicNameIF.added"; String EVENT_REMOVED = "TopicNameIF.removed"; String EVENT_SET_TYPE = "TopicNameIF.setType"; String EVENT_SET_VALUE = "TopicNameIF.setValue"; String EVENT_ADD_VARIANT = "TopicNameIF.addVariant"; String EVENT_REMOVE_VARIANT = "TopicNameIF.removeVariant"; String EVENT_ADD_THEME = "TopicNameIF.addTheme"; String EVENT_REMOVE_THEME = "TopicNameIF.removeTheme"; /** * PUBLIC: Gets the variant names of the topic named by this * topic name. These correspond to the 'variant' child elements of the * 'baseName' element in XTM 1.0. There is no guarantee as to which * order these appear in the collection. * * @return A collection of VariantNameIF objects. */ Collection getVariants(); } sdk/mobilenetwork/azure-resourcemanager-mobilenetwork/src/main/java/com/azure/resourcemanager/mobilenetwork/models/SliceConfiguration.java1-10 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.mobilenetwork.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** Per-slice settings. */ @Fluent public final class SliceConfiguration { @JsonIgnore private final ClientLogger logger = new ClientLogger(SliceConfiguration.class); /* * A reference to the Slice that these settings apply to */ @JsonProperty(value = "slice", required = true) private SliceResourceId slice; /* * The default data network to use if the UE does not explicitly specify * it. Configuration for this object must exist in the * `dataNetworkConfigurations` map. */ @JsonProperty(value = "defaultDataNetwork", required = true) private DataNetworkResourceId defaultDataNetwork; /* * The allowed data networks and the settings to use for them. The list * must not contain duplicate items and must contain at least one item. */ @JsonProperty(value = "dataNetworkConfigurations", required = true) private List dataNetworkConfigurations; /** * Get the slice property: A reference to the Slice that these settings apply to. * * @return the slice value. */ public SliceResourceId slice() { return this.slice; } /** * Set the slice property: A reference to the Slice that these settings apply to. * * @param slice the slice value to set. * @return the SliceConfiguration object itself. */ public SliceConfiguration withSlice(SliceResourceId slice) { this.slice = slice; return this; } /** * Get the defaultDataNetwork property: The default data network to use if the UE does not explicitly specify it. * Configuration for this object must exist in the `dataNetworkConfigurations` map. * * @return the defaultDataNetwork value. */ public DataNetworkResourceId defaultDataNetwork() { return this.defaultDataNetwork; } /** * Set the defaultDataNetwork property: The default data network to use if the UE does not explicitly specify it. * Configuration for this object must exist in the `dataNetworkConfigurations` map. * * @param defaultDataNetwork the defaultDataNetwork value to set. * @return the SliceConfiguration object itself. */ public SliceConfiguration withDefaultDataNetwork(DataNetworkResourceId defaultDataNetwork) { this.defaultDataNetwork = defaultDataNetwork; return this; } /** * Get the dataNetworkConfigurations property: The allowed data networks and the settings to use for them. The list * must not contain duplicate items and must contain at least one item. * * @return the dataNetworkConfigurations value. */ public List dataNetworkConfigurations() { return this.dataNetworkConfigurations; } /** * Set the dataNetworkConfigurations property: The allowed data networks and the settings to use for them. The list * must not contain duplicate items and must contain at least one item. * * @param dataNetworkConfigurations the dataNetworkConfigurations value to set. * @return the SliceConfiguration object itself. */ public SliceConfiguration withDataNetworkConfigurations(List dataNetworkConfigurations) { this.dataNetworkConfigurations = dataNetworkConfigurations; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (slice() == null) { throw logger .logExceptionAsError( new IllegalArgumentException("Missing required property slice in model SliceConfiguration")); } else { slice().validate(); } if (defaultDataNetwork() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property defaultDataNetwork in model SliceConfiguration")); } else { defaultDataNetwork().validate(); } if (dataNetworkConfigurations() == null) { throw logger .logExceptionAsError( new IllegalArgumentException( "Missing required property dataNetworkConfigurations in model SliceConfiguration")); } else { dataNetworkConfigurations().forEach(e -> e.validate()); } } } package com.islandboys.game.model; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Sound; import com.islandboys.game.MGame; import com.islandboys.game.view.PlayScreen; /** * Key Class in game */ public class Key extends InteractiveTileObject { private PlayScreen screen; /** * Key constructor * @param screen * @param rect * @param hud */ public Key(PlayScreen screen, com.badlogic.gdx.math.Rectangle rect, Hud hud){ super(screen,rect,hud); this.screen=screen; fixture.setUserData(this); setCategoryFilter(GameInfo.KEY_BIT); } /** * Check if the islander catch the dor */ @Override public void onContactBodys() { MGame.assetManager.get("key_s.wav",Sound.class).play(); setCategoryFilter(GameInfo.DESTROED_BIT); screen.getIslander().setKey(); getCell().setTile(null); } } src/main/java/net/chrisgrollier/amsuite/osscat/service/ArtefactId.java0 package net.chrisgrollier.amsuite.osscat.service; public class ArtefactId { public static final String INVALID_ID_ERROR_TYPE = InvalidIdException.class.getSimpleName().toLowerCase(); public static final String NO_SEMICOLON_FOUND_MESSAGE = "id does not contain any semicolon but must at least contain 2"; public static final String ONLY_ONE_SEMICOLON_FOUND_MESSAGE = "id contains only one semicolon but must at least contain 2"; private String kind; private String name; private String type; public static ArtefactId fromStringId(String id) { int firstSemiColon = id.indexOf(':'); if (firstSemiColon < 0) { throw new InvalidIdException(NO_SEMICOLON_FOUND_MESSAGE); } int lastSemiColon = id.lastIndexOf(':'); if (lastSemiColon == firstSemiColon) { throw new InvalidIdException(ONLY_ONE_SEMICOLON_FOUND_MESSAGE); } final String kind = id.substring(0, firstSemiColon); final String name = id.substring(firstSemiColon + 1, lastSemiColon); final String type = id.substring(lastSemiColon + 1); return new ArtefactId(kind, name, type); } public ArtefactId(String kind, String name, String type) { super(); this.kind = kind; this.name = "npm".equalsIgnoreCase(kind) && name.startsWith("@") ? '@' + name.substring(1).replace('@', '/') : name; this.type = type; } public String toStringId() { return this.kind + ':' + this.name + ':' + this.type; } public String getKind() { return kind; } public String getName() { return name; } public String getType() { return type; } @Override public final String toString() { return this.toStringId(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((kind == null) ? 0 : kind.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ArtefactId other = (ArtefactId) obj; if (kind == null) { if (other.kind != null) return false; } else if (!kind.equals(other.kind)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } }package controllers; import activities.ActivitiesScreen; import bar.BarScreen; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; public final class LoginScreen extends JFrame{ private static final String USERNAME1 = "rec"; private static final String PASSWORD1 = ""; private static final String USERNAME2 = "bar"; private static final String PASSWORD2 = ""; private static final String USERNAME3 = "act"; private static final String PASSWORD3 = ""; private static LoginScreen INSTANCE = null; private JTextField usernameField; private JPasswordField passwordField; private LoginScreen(){ try{ UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); SwingUtilities.updateComponentTreeUI(this); } catch (Exception ignored){ } initialize(); } public static LoginScreen getInstance(){ if (INSTANCE == null){ INSTANCE = new LoginScreen(); } else INSTANCE.setVisible(true); return INSTANCE; } private void initialize(){ setVisible(true); setTitle("\u0395\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2 \u03A7\u03C1\u03AE\u03C3\u03C4\u03B7"); setResizable(false); setBounds(100, 100, 394, 192); JPanel contentPane = new JPanel(); contentPane.setBackground(new Color(255, 255, 255)); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); setLocationRelativeTo(null); contentPane.setLayout(null); JLabel label = new JLabel("\u0395\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2 \u03A7\u03C1\u03AE\u03C3\u03C4\u03B7"); label.setBounds(6, 6, 369, 25); label.setHorizontalAlignment(SwingConstants.LEFT); label.setForeground(Color.BLACK); label.setFont(new Font("Tahoma", Font.BOLD, 20)); label.setBackground(new Color(255, 140, 0)); contentPane.add(label); JLabel usernameLabel = new JLabel("\u03A7\u03C1\u03AE\u03C3\u03C4\u03B7\u03C2"); usernameLabel.setBounds(5, 42, 90, 29); usernameLabel.setForeground(new Color(0, 0, 0)); usernameLabel.setFont(new Font("Tahoma", Font.BOLD, 15)); contentPane.add(usernameLabel); usernameField = new JTextField(); usernameField.setBounds(100, 42, 270, 29); usernameField.setFont(new Font("Tahoma", Font.PLAIN, 14)); contentPane.add(usernameField); usernameField.setColumns(10); JLabel passwordLabel = new JLabel("\"); passwordLabel.setBounds(5, 76, 90, 28); passwordLabel.setForeground(new Color(0, 0, 0)); passwordLabel.setFont(new Font("Tahoma", Font.BOLD, 15)); contentPane.add(passwordLabel); passwordField = new JPasswordField(); passwordField.setBounds(100, 76, 270, 28); contentPane.add(passwordField); JButton loginButton = new JButton("\u0395\u03AF\u03C3\u03BF\u03B4\u03BF\u03C2"); loginButton.setBounds(5, 110, 290, 34); loginButton.setFont(new Font("Tahoma", Font.PLAIN, 18)); loginButton.addActionListener(arg0 -> { String tempUsername = usernameField.getText(); String tempPassword = String.valueOf(passwordField.getPassword()); if (tempUsername.equals(USERNAME1) && tempPassword.equals(PASSWORD1)){ JOptionPane.showMessageDialog(null, "Σύνδεση επιτυχής."); Registry.RS.setVisible(true); Main.HS.setVisible(false); setVisible(false); } else if (tempUsername.equals(USERNAME2) && tempPassword.equals(PASSWORD2)){ JOptionPane.showMessageDialog(null, "Σύνδεση επιτυχής."); BarScreen.getInstance(); Main.HS.setVisible(false); setVisible(false); } else if (tempUsername.equals(USERNAME3) && tempPassword.equals()){ JOptionPane.showMessageDialog(null, "Σύνδεση επιτυχής."); ActivitiesScreen.getInstance(); Main.HS.setVisible(false); setVisible(false); } else{ JOptionPane.showMessageDialog(null, "Λάθος όνομα χρήστη ή κωδικός! Παρακαλώ ξαναπροσπαθήστε."); } usernameField.setText(null); passwordField.setText(null); usernameField.requestFocus(); }); loginButton.setForeground(Color.BLACK); loginButton.setBackground(Color.WHITE); contentPane.add(loginButton); passwordField.addActionListener(e -> loginButton.doClick()); JButton helpButton = new JButton("?"); helpButton.setBounds(300, 110, 70, 34); helpButton.addActionListener(arg0 -> JOptionPane.showMessageDialog(null, "Εάν επιθυμείτε αλλαγή Username ή/και κωδικου, ή εάν αντιμετωπίζετε προβλήματα σύνδεσης, επικοινωνήστε με τον διαχειριστή του συστήματος.")); helpButton.setFont(new Font("Tahoma", Font.BOLD, 15)); contentPane.add(helpButton); } }10-100 package jopenvr; import com.sun.jna.Pointer; import com.sun.jna.Structure; import java.util.Arrays; import java.util.List; public class Compositor_OverlaySettings extends Structure { public int size; public byte curved; public byte antialias; public float scale; public float distance; public float alpha; public float uOffset; public float vOffset; public float uScale; public float vScale; public float gridDivs; public float gridWidth; public float gridScale; public HmdMatrix44_t transform; public Compositor_OverlaySettings() { } protected List getFieldOrder() { return Arrays.asList("size", "curved", "antialias", "scale", "distance", "alpha", "uOffset", "vOffset", "uScale", "vScale", "gridDivs", "gridWidth", "gridScale", "transform"); } public Compositor_OverlaySettings(Pointer peer) { super(peer); } public static class ByReference extends Compositor_OverlaySettings implements com.sun.jna.Structure.ByReference { } public static class ByValue extends Compositor_OverlaySettings implements com.sun.jna.Structure.ByValue { } } package com.asena.scimgateway.service; import java.util.List; import java.util.Optional; import com.asena.scimgateway.exception.NotFoundException; import com.asena.scimgateway.model.RemoteSystem; import com.asena.scimgateway.model.User; import com.asena.scimgateway.model.User.UserType; import com.asena.scimgateway.repository.RemoteSystemRepository; import com.asena.scimgateway.repository.UserRepository; import com.asena.scimgateway.utils.PasswordUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private RemoteSystemRepository remoteSystemRepository; @Autowired private UserRepository userRepository; public User createServiceUser(String prefix) { User u = new User(); u.setUserName(prefix + "_COMM"); u.setPassword(PasswordUtil.generatePassword(8)); u.setType(UserType.TECHNICAL); return create(u); } public User create(User u) { return userRepository.save(u); } public Optional findById(long id) { return userRepository.findById(id); } public User findByUserName(String userName) { return userRepository.findByUserName(userName); } private void deleteUser(User u) { List rs = remoteSystemRepository.findByServiceUserId(u.getId()); for (RemoteSystem r : rs) { r.setServiceUser(null); r = remoteSystemRepository.save(r); } userRepository.deleteById(u.getId()); } public void deleteAll() { List users = userRepository.findAll(); for (User u : users) { deleteUser(u); } } public User deleteById(long id) { return findById(id) .map(u -> { userRepository.deleteById(id); return u; }) .orElseThrow(() -> new NotFoundException(id)); } public User updateAdminUser(User usr, long id) { return findById(id) .map(u -> { u.setPassword(()); return userRepository.save(u); }) .orElseThrow(() -> new NotFoundException(id)); } }KevinMayfield/dwpconnect-workflow0 package uk.gov.workflow.entity; public interface IBaseResource { Long getId(); } 100-1000 package com.tencent.bk.job.common.consul.config; import com.tencent.bk.job.common.consul.provider.ConsulServiceInfoProvider; import com.tencent.bk.job.common.discovery.ServiceInfoProvider; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.consul.discovery.ConditionalOnConsulDiscoveryEnabled; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; @Configuration @ConditionalOnConsulDiscoveryEnabled public class ConsulServiceInfoServiceAutoConfig { @Bean @Primary public ServiceInfoProvider consulServiceInfoService(DiscoveryClient discoveryClient) { return new ConsulServiceInfoProvider(discoveryClient); } } stefanofornari/BshConsole /* * Copyright (C) 2018 . * All Rights Reserved. No use, copying or distribution of this * work may be made except in accordance with a valid license * agreement from Stefari. This notice must be * included on all copies, modifications and derivatives of this * work. * * STEFANO FORNARI MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY * OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, OR NON-INFRINGEMENT. STEFANO FORNARI SHALL NOT BE LIABLE FOR ANY * DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING * THIS SOFTWARE OR ITS DERIVATIVES. */ package ste.bshell; import ste.bshell.NodeFuture; import ste.bshell.JLineConsole; import bsh.InterpreterEvent; import java.util.concurrent.Callable; import static org.assertj.core.api.AssertionsForClassTypes.fail; import static org.assertj.core.api.BDDAssertions.then; import org.junit.Test; import ste.bshell.jline.TestLineReader; /** * */ public class BugFreeNodeFuture { @Test public void construction() { try { new NodeFuture(null, null); fail("missing sanity check for callable"); } catch (NullPointerException x) { // // for consistency with FutureTask // } try { new NodeFuture(createCallable(), null); fail("missing sanity check for console"); } catch (NullPointerException x) { then(x).hasMessage("console can not be null"); } } @Test public void notify_console_when_done() throws Exception { final JLineHelper H = new JLineHelper(); TestLineReader r = H.givenReader(); final Callable C = createCallable(); final String[] type = new String[] { null }; final NodeFuture[] future = new NodeFuture[] { null }; NodeFuture f = new NodeFuture(C, new JLineConsole(r) { @Override public void on(InterpreterEvent e) { type[0] = e.type; future[0] = (NodeFuture)e.data; } }); f.run(); f.get(); then(type[0]).isEqualTo("DONE"); then(future[0]).isNotNull(); } // -------------------------------------------------------- private methods private Callable createCallable() { return new Callable() { @Override public Object call() throws Exception { return null; } }; } } package app.com.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.util.ArrayList; import java.util.List; import rx.Observable; import rx.functions.Action1; public class StartWithActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start_with); //插入普通数据 //startWith 数据序列的开头插入一条指定的项 , 最多插入9条数据 Observable observable = Observable.just( "aa" , "bb" , "cc" ) ; observable .startWith( "11" , "22" ) .subscribe(new Action1() { @Override public void call(Object o) { System.out.println( "startWith-- " + o ); } }) ; //插入Observable对象 List list = new ArrayList<>() ; list.add( "ww" ) ; list.add( "tt" ) ; observable.startWith( Observable.from( list )) .subscribe(new Action1() { @Override public void call(Object o) { System.out.println( "startWith2 -- " + o ); } }) ; } } 0 package com.yuhs.utils.file.convert; import org.junit.Test; import java.net.URL; /** * Created by yuhaisheng on 2019/5/8. */ public class ConvertReadFileUtilsTest { /** * 测试使用jar包版本是否相同 * */ @Test public void testPoiVersion() { ClassLoader classloader = org.apache.poi.POIXMLDocument.class.getClassLoader(); URL res = classloader.getResource("org/apache/poi/POIXMLDocument.class"); String path = res.getPath(); System.out.println("POI OOXML came from " + path); classloader = org.apache.poi.xssf.usermodel.XSSFWorkbook.class.getClassLoader(); res = classloader.getResource("org.apache.poi.xssf.usermodel.XSSFWorkbook.class"); if(res != null) { path = res.getPath(); } System.out.println("work path is " + path); } /** * 将docx文件保存为html文件 * @throws Exception */ @Test public void testDocxToHtmlFile() throws Exception { String docxFileName = "/Users/yuhaisheng/Desktop/读书笔记/JDK.docx"; String htmlFilePath = ConvertFileUtils.docxToHtmlFile(docxFileName,"/Users/yuhaisheng/Desktop"); System.err.println(htmlFilePath); } /** * 将docx文件转换为html文本 * @throws Exception */ @Test public void testDocxToHtmlString() throws Exception { String docxFileName = "/Users/yuhaisheng/Desktop/读书笔记/JDK.docx"; String htmlString = ConvertFileUtils.docxToHtmlString(docxFileName); System.err.println(htmlString); } /** * 将docx文件转换为适合UEditorhtml文本 * @throws Exception */ @Test public void testDocxToHtmlForUEditorStringString() throws Exception { String docxFileName = "/Users/yuhaisheng/Desktop/读书笔记/JDK.docx"; String htmlString = ConvertFileUtils.docxToHtmlForUEditorString(docxFileName); System.err.println(htmlString); } /** * 将doc文件保存为html文件 * @throws Exception */ @Test public void testDocToHtmlFile() throws Exception { String docFileName = "/Users/yuhaisheng/Desktop/读书笔记/简历/于海胜.doc"; String htmlFilePath = ConvertFileUtils.docToHtmlFile(docFileName,"/Users/yuhaisheng/Desktop"); System.err.println(htmlFilePath); } /** * 将doc文件转换为html文本 * @throws Exception */ @Test public void testDocToHtmlString() throws Exception { String docFileName = "/Users/yuhaisheng/Desktop/读书笔记/简历/于海胜.doc"; String htmlString = ConvertFileUtils.docToHtmlString(docFileName); System.err.println(htmlString); } /** * 将doc文件转换为适合UEditorhtml文本 * @throws Exception */ @Test public void testDocToHtmlForUEditorStringString() throws Exception { String docFileName = "/Users/yuhaisheng/Desktop/读书笔记/简历/于海胜.doc"; String htmlString = ConvertFileUtils.docToHtmlForUEditorString(docFileName); System.err.println(htmlString); } } src/main/java/uk/gov/hmcts/reform/bulkscan/orchestrator/services/ccd/callback/AttachScannedDocumentsValidator.java package uk.gov.hmcts.reform.bulkscan.orchestrator.services.ccd.callback; import com.google.common.collect.Sets; import org.slf4j.Logger; import org.springframework.stereotype.Component; import uk.gov.hmcts.reform.bulkscan.orchestrator.services.ccd.Documents; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Predicate; import static java.util.stream.Collectors.toSet; import static org.slf4j.LoggerFactory.getLogger; @Component public class AttachScannedDocumentsValidator { private static final Logger log = getLogger(AttachScannedDocumentsValidator.class); public AttachScannedDocumentsValidator() { // empty construct } public void verifyExceptionRecordAddsNoDuplicates( List> targetCaseDocuments, List> exceptionRecordDocuments, String exceptionRecordCcdRef, String targetCaseCcdRef ) { logIfDocumentsAreAlreadyAttachedToCaseFromER( targetCaseDocuments, exceptionRecordDocuments, exceptionRecordCcdRef, targetCaseCcdRef ); Set clashingDocumentDcns = getDcnsOfClashingDocuments( exceptionRecordCcdRef, exceptionRecordDocuments, targetCaseDocuments ); if (!clashingDocumentDcns.isEmpty()) { // avoiding 120 line length rule String message = String.format( "Documents with following control numbers are already present in the case %s and cannot be added: %s", targetCaseCcdRef, String.join(", ", clashingDocumentDcns) ); throw new DuplicateDocsException(message); } } private void logIfDocumentsAreAlreadyAttachedToCaseFromER( List> targetCaseDocuments, List> exceptionRecordDocuments, String exceptionRecordCcdRef, String targetCaseCcdRef ) { Set alreadyAttachedDocumentDcns = getDcnsOfDocumentsAlreadyAttachedToCaseFromER( exceptionRecordCcdRef, exceptionRecordDocuments, targetCaseDocuments ); if (alreadyAttachedDocumentDcns.size() == exceptionRecordDocuments.size()) { log.warn( "All documents from exception record {} have already been attached to case {}", exceptionRecordCcdRef, targetCaseCcdRef ); } else if (!alreadyAttachedDocumentDcns.isEmpty()) { log.warn( "Following documents have already been added from exception record {} to case {}: {}", exceptionRecordCcdRef, targetCaseCcdRef, alreadyAttachedDocumentDcns ); } } private Set getDcnsOfDocumentsAlreadyAttachedToCaseFromER( String exceptionRecordId, List> exceptionRecordDocuments, List> targetCaseDocuments ) { return findDocumentsIntersection( doc -> Objects.equals(Documents.getExceptionRecordReference(doc), exceptionRecordId), exceptionRecordDocuments, targetCaseDocuments ); } private Set getDcnsOfClashingDocuments( String exceptionRecordId, List> exceptionRecordDocuments, List> targetCaseDocuments ) { return findDocumentsIntersection( doc -> !Objects.equals(Documents.getExceptionRecordReference(doc), exceptionRecordId), exceptionRecordDocuments, targetCaseDocuments ); } private Set findDocumentsIntersection( Predicate> filterOnTargetCaseDocuments, List> exceptionRecordDocuments, List> targetCaseDocuments ) { Set dcnsOfCaseDocumentsFromOtherSources = targetCaseDocuments .stream() .filter(filterOnTargetCaseDocuments) .map(Documents::getDocumentId) .collect(toSet()); Set dcnsOfExceptionRecordDocuments = exceptionRecordDocuments .stream() .map(Documents::getDocumentId) .collect(toSet()); return Sets.intersection(dcnsOfCaseDocumentsFromOtherSources, dcnsOfExceptionRecordDocuments); } } nxintech/job-center package com.nxin.framework.domain; /** * Created by petzold on 2014/11/19. */ public class Tuple2 { private T1 t1; private T2 t2; public Tuple2() { } public Tuple2(T1 t1, T2 t2) { this.t1 = t1; this.t2 = t2; } public T1 getT1() { return t1; } public void setT1(T1 t1) { this.t1 = t1; } public T2 getT2() { return t2; } public void setT2(T2 t2) { this.t2 = t2; } @Override public boolean equals(Object o) { if (this == o) { return true; } if ((o == null) || (getClass() != o.getClass())) { return false; } Tuple2 tuple = (Tuple2)o; if (t1 != null ? !t1.equals(tuple.t1) : tuple.t1 != null) { return false; } if (t2 != null ? !t2.equals(tuple.t2) : tuple.t2 != null) { return false; } return true; } } package com.macro.mall.oms.service.impl; import com.macro.mall.oms.model.OmsOrderSetting; import com.macro.mall.oms.mapper.OmsOrderSettingMapper; import com.macro.mall.oms.service.OmsOrderSettingRepository; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** *

* 订单设置表 服务实现类 *

* * @author dongjb * @since 2020-11-28 */ @Service public class OmsOrderSettingRepositoryImpl extends ServiceImpl implements OmsOrderSettingRepository { } Java/Exemplos/128-intfunc01/src/main/java/ValidatorCPF.java public class ValidatorCPF implements Validator { public boolean validate(String cpf) { return cpf != null && cpf.matches("[0-9]{3}\\.[0-9]{3}\\.[0-9]{3}\\-[0-9]{2}"); } } package kuger.loganalyzer.core.api; public interface Input { InputIdentifier getIdentifier(); } iam/src/main/java/org/jclouds/iam/config/IAMRestClientModule.java /** * Licensed to jclouds, Inc. (jclouds) under one or more * contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. jclouds 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.jclouds.iam.config; import static org.jclouds.reflect.Reflection2.typeToken; import java.util.Map; import org.jclouds.aws.config.FormSigningRestClientModule; import org.jclouds.iam.IAMApi; import org.jclouds.iam.IAMAsyncApi; import org.jclouds.iam.features.InstanceProfileApi; import org.jclouds.iam.features.InstanceProfileAsyncApi; import org.jclouds.iam.features.RoleApi; import org.jclouds.iam.features.RoleAsyncApi; import org.jclouds.iam.features.RolePolicyApi; import org.jclouds.iam.features.RolePolicyAsyncApi; import org.jclouds.iam.features.UserApi; import org.jclouds.iam.features.UserAsyncApi; import org.jclouds.rest.ConfiguresRestClient; import com.google.common.collect.ImmutableMap; /** * Configures the Monitoring connection. * * @author */ @ConfiguresRestClient public class IAMRestClientModule extends FormSigningRestClientModule { public static final Map, Class> DELEGATE_MAP = ImmutableMap., Class> builder()// .put(UserApi.class, UserAsyncApi.class) .put(RoleApi.class, RoleAsyncApi.class) .put(RolePolicyApi.class, RolePolicyAsyncApi.class) .put(InstanceProfileApi.class, InstanceProfileAsyncApi.class) .build(); public IAMRestClientModule() { super(typeToken(IAMApi.class), typeToken(IAMAsyncApi.class), DELEGATE_MAP); } } /* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or . */ package org.hibernate.persister.entity; import java.io.Serializable; import org.hibernate.FlushMode; import org.hibernate.LockOptions; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.loader.entity.UniqueEntityLoader; import org.hibernate.query.internal.AbstractProducedQuery; /** * Not really a Loader, just a wrapper around a named query. Used when the metadata has named a query to use for * loading an entity (using {@link org.hibernate.annotations.Loader} or {@code }). * * @author * @author */ public final class NamedQueryLoader implements UniqueEntityLoader { private static final CoreMessageLogger LOG = CoreLogging.messageLogger( NamedQueryLoader.class ); private final String queryName; private final EntityPersister persister; private final int position; /** * Constructs the NamedQueryLoader * * @param queryName The name of the named query to use * @param persister The corresponding persister for the entity we are loading */ public NamedQueryLoader(String queryName, EntityPersister persister) { super(); this.queryName = queryName; this.persister = persister; this.position = persister.getFactory().getSessionFactoryOptions().jdbcStyleParamsZeroBased() ? 0 : 1; } @Override public Object load(Serializable id, Object optionalObject, SharedSessionContractImplementor session, LockOptions lockOptions) { if ( lockOptions != null ) { LOG.debug( "Ignoring lock-options passed to named query loader" ); } return load( id, optionalObject, session ); } @Override public Object load(Serializable id, Object optionalObject, SharedSessionContractImplementor session) { LOG.debugf( "Loading entity: %s using named query: %s", persister.getEntityName(), queryName ); // IMPL NOTE: essentially we perform the named query (which loads the entity into the PC), and then // do an internal lookup of the entity from the PC. final AbstractProducedQuery query = (AbstractProducedQuery) session.getNamedQuery( queryName ); if ( query.getParameterMetadata().hasNamedParameters() ) { query.setParameter( query.getNamedParameters()[0], id, persister.getIdentifierType() ); } else { query.setParameter( position, id, persister.getIdentifierType() ); } query.setOptionalId( id ); query.setOptionalEntityName( persister.getEntityName() ); query.setOptionalObject( optionalObject ); query.setFlushMode( FlushMode.MANUAL ); query.list(); // now look up the object we are really interested in! // (this lets us correctly handle proxies and multi-row or multi-column queries) return session.getPersistenceContext().getEntity( session.generateEntityKey( id, persister ) ); } } package PACKAGE_NAME; public class Factorial { public static Integer factorial(int f){ if(f == 1) return 1; if(f < 1) return f; return f * factorial(f - 1); } } wavemaker/wavemaker-app-runtime /** * Copyright © 2013 - 2017 WaveMaker, 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 com.wavemaker.runtime.data.transform; import java.beans.PropertyDescriptor; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import org.apache.commons.lang3.reflect.TypeUtils; import org.hibernate.transform.AliasedTupleSubsetResultTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import com.wavemaker.commons.MessageResource; import com.wavemaker.commons.WMRuntimeException; import com.wavemaker.runtime.data.annotations.ColumnAlias; import com.wavemaker.runtime.data.exception.TypeMappingException; import com.wavemaker.runtime.data.util.JavaTypeUtils; /** * @author * @since 15/11/16 */ public class AliasToMappedClassResultTransformer extends AliasedTupleSubsetResultTransformer implements WMResultTransformer { private static final Logger LOGGER = LoggerFactory.getLogger(AliasToMappedClassResultTransformer.class); private static Set ignorableAliases = new HashSet<>(); private final Class resultClass; private Map aliasVsDescriptorMap; private Map fieldVsAliasMap; static { ignorableAliases.add("__hibernate_row_nr__"); } public AliasToMappedClassResultTransformer(final Class resultClass) { Objects.requireNonNull(resultClass, "Result Class cannot be null"); this.resultClass = resultClass; initialize();//xxx lazy load? } @Override public Object transformTuple(final Object[] tuple, final String[] aliases) { try { Object object = resultClass.newInstance(); for (int i = 0; i < tuple.length; i++) { applyValue(object, WMResultTransformer.getAlias(aliases, i), tuple[i]); } return object; } catch (InstantiationException | IllegalAccessException e) { throw new WMRuntimeException(MessageResource.create("com.wavemaker.runtime.cannot.instantiate.class"), e, resultClass); } } @Override public boolean isTransformedValueATupleElement(final String[] aliases, final int tupleLength) { return false; } @Override public Object transformFromMap(final Map resultMap) { try { Object object = resultClass.newInstance(); for (final Map.Entry entry : resultMap.entrySet()) { applyValue(object, entry.getKey(), entry.getValue()); } return object; } catch (InstantiationException | IllegalAccessException e) { throw new WMRuntimeException(MessageResource.create("com.wavemaker.runtime.cannot.instantiate.class"), e, resultClass); } } @Override public String aliasToFieldName(final String columnName) { String fieldName = columnName; if (aliasVsDescriptorMap.containsKey(columnName)) { fieldName = aliasVsDescriptorMap.get(columnName).getName(); } return fieldName; } @Override public String aliasFromFieldName(final String fieldName) { return fieldVsAliasMap.getOrDefault(fieldName, fieldName); } @Override public boolean containsField(final String fieldName) { return fieldVsAliasMap.containsKey(fieldName); } private void applyValue( Object object, String alias, Object value) { if (aliasVsDescriptorMap.containsKey(alias)) { final PropertyDescriptor descriptor = aliasVsDescriptorMap.get(alias); Object transformedValue = transformField(descriptor, value); try { descriptor.getWriteMethod().invoke(object, transformedValue); } catch (Throwable e) { throw new TypeMappingException(MessageResource.TYPE_MAPPING_FAILURE, e, alias, object.getClass() .getName()); } } else { if (!ignorableAliases.contains(alias)) { LOGGER.warn("Column: {} not found in type:{}, ignoring", alias, resultClass.getName()); } } } @SuppressWarnings("unchecked") private Object transformField(final PropertyDescriptor descriptor, final Object value) { Object transformedValue = value; if (value != null) { if (value instanceof List) { transformedValue = new ArrayList<>(); final Type innerType = ((ParameterizedType) descriptor.getReadMethod().getGenericReturnType()) .getActualTypeArguments()[0]; final WMResultTransformer childTransformer = Transformers .aliasToMappedClass(TypeUtils.getRawType(innerType, null)); for (final Map val : ((List>) value)) { ((List) transformedValue).add(childTransformer.transformFromMap(val)); } } else { final String className = descriptor.getPropertyType().getCanonicalName(); transformedValue = JavaTypeUtils.convert(className, value); } } return transformedValue; } private void initialize() { final Field[] fields = resultClass.getDeclaredFields(); aliasVsDescriptorMap = new HashMap<>(); fieldVsAliasMap = new HashMap<>(); for (final Field field : fields) { final PropertyDescriptor descriptor = BeanUtils.getPropertyDescriptor(resultClass, field.getName()); if (descriptor != null) { Optional columnName = findResultSetColumnName(field); if (!columnName.isPresent() && descriptor.getReadMethod() != null) { columnName = findResultSetColumnName(descriptor.getReadMethod()); } if (!columnName.isPresent() && descriptor.getWriteMethod() != null) { columnName = findResultSetColumnName(descriptor.getWriteMethod()); } if (!columnName.isPresent()) { columnName = Optional.of(field.getName()); } aliasVsDescriptorMap.put(columnName.get(), descriptor); fieldVsAliasMap.put(descriptor.getName(), columnName.get()); } else { LOGGER.warn("Property descriptor not found for field:{}", field.getName()); } } } private Optional findResultSetColumnName(AccessibleObject member) { Optional rsColumn = Optional.empty(); final ColumnAlias annotation = member.getAnnotation(ColumnAlias.class); if (annotation != null) { rsColumn = Optional.of(annotation.value()); } return rsColumn; } } jayr33n/cs50-fitness-frenzy package com.jayr33n.commands.update; import com.jayr33n.domain.Difficulty; import io.micronaut.core.annotation.Introspected; import lombok.Getter; import lombok.Setter; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; @Getter @Setter @Introspected public class ExerciseUpdateCommand { @NotBlank private String name; @NotNull private Difficulty difficulty; } 1-10 package nl.harm27.obs.websocket.websocket; import nl.harm27.obs.websocket.processor.MessageReceiver; import nl.harm27.obs.websocket.processor.MessageSender; import java.net.URI; import java.net.http.HttpClient; import java.net.http.WebSocket; import java.time.Duration; public class OBSWebSocketClient { private final String ip; private final int port; private WebSocket webSocket; public OBSWebSocketClient(String ip, int port) { this.ip = ip; this.port = port; } public void connect(MessageSender messageSender, MessageReceiver messageReceiver) { HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(30)) .build().newWebSocketBuilder() .buildAsync(URI.create(String.format("ws://%s:%d", ip, port)), new OBSWebSocketListener(this, messageSender, messageReceiver)); } public void setWebSocket(WebSocket webSocket) { this.webSocket = webSocket; } public void notifyShutdown() { webSocket.abort(); webSocket = null; } public void sendText(String message) { webSocket.sendText(message, true); } public boolean isConnected() { return webSocket != null; } } dpeer/srl-tdigest-benchmarkssrc/main/java/SrlTDigestBenchmarks/LgData.java package SrlTDigestBenchmarks; import java.util.ArrayList; import java.util.HashSet; import java.util.Random; import java.util.Set; class LgData { private ArrayList lgDimensionsData; private int region; private static Random gen = new Random(); LgData(int region, double[][] rawData) { this.region = region; lgDimensionsData = new ArrayList<>(SrlConsts.MaxDimensionsPerLg); for (int i = 0; i < SrlConsts.MaxEmulations; i++) { var rand = gen.nextInt(); for (int j = 0; j < SrlConsts.MaxTransactionsPerLgPerInterval; j++) { lgDimensionsData.add(new LgDimensionData( region, i, j + (rand % 2 == 0 ? 0 : SrlConsts.MaxTransactionsPerLgPerInterval), rawData[i * SrlConsts.MaxTransactionsPerLgPerInterval + j]) ); } } } LgData(int region, double[][] rawData, int numOfEmulations, int numOfTransactions) { this.region = region; lgDimensionsData = new ArrayList<>(numOfEmulations * numOfTransactions); for (int i = 0; i < numOfEmulations; i++) { for (int j = 0; j < numOfTransactions; j++) { lgDimensionsData.add(new LgDimensionData(region, i, j, rawData[i * numOfTransactions + j])); } } } void createTDigests() { // System.out.println("createTDigests: Creating TDigests and converting to buffers for " + SrlConsts.MaxDimensionsPerLg + " dimensions with " + SrlConsts.LgValuesPerDimension + " values per dimension"); // var startDur = System.currentTimeMillis(); for (var lgDimensionData : lgDimensionsData) { lgDimensionData.createTDigest(); } // var endDur = System.currentTimeMillis(); // System.out.println("createTDigests: duration (msec) = " + ((endDur - startDur))); } void rewindBuffers() { for (var lgDimensionData : lgDimensionsData) { lgDimensionData.rewindBuffer(); } } Set getDimensionsIds() { var dimensionsIds = new HashSet(); for (var lgDimensionData : lgDimensionsData) { dimensionsIds.add(lgDimensionData.getDimensionId()); } return dimensionsIds; } int getRegion() { return region; } ArrayList getLgDimensionsData() { return lgDimensionsData; } }mickroll/dependency-duplicator-pluginplugin/src/test/java/com/github/mickroll/maven/dependency_duplicator_plugin/DependencySetTest.java package com.github.mickroll.maven.dependency_duplicator_plugin; import static org.assertj.core.api.Assertions.assertThat; import org.apache.maven.model.Dependency; import org.junit.jupiter.api.Test; class DependencySetTest { @Test void testEmptyEquals() { final Dependency d1 = new Dependency(); final Dependency d2 = new Dependency(); assertThat(DependencySet.isDeepEqualTo(d1, d2)).isTrue(); } @Test void testGATC_Same() { final Dependency d1 = dep("org.example", "someartifact", "jar", "testclassifier"); final Dependency d2 = dep("org.example", "someartifact", "jar", "testclassifier"); assertThat(DependencySet.isDeepEqualTo(d1, d2)).isTrue(); } @Test void testGATC_DiffG() { final Dependency d1 = dep("org.example", "someartifact", "jar", "testclassifier"); final Dependency d2 = dep("org.example2", "someartifact", "jar", "testclassifier"); assertThat(DependencySet.isDeepEqualTo(d1, d2)).isFalse(); } @Test void testGATC_DiffA() { final Dependency d1 = dep("org.example", "someartifact", "jar", "testclassifier"); final Dependency d2 = dep("org.example", "someartifact2", "jar", "testclassifier"); assertThat(DependencySet.isDeepEqualTo(d1, d2)).isFalse(); } @Test void testGATC_DiffT() { final Dependency d1 = dep("org.example", "someartifact", "jar", "testclassifier"); final Dependency d2 = dep("org.example", "someartifact", "war", "testclassifier"); assertThat(DependencySet.isDeepEqualTo(d1, d2)).isFalse(); } @Test void testGATC_DiffC() { final Dependency d1 = dep("org.example", "someartifact", "jar", "testclassifier"); final Dependency d2 = dep("org.example", "someartifact", "jar", "testclassifier2"); assertThat(DependencySet.isDeepEqualTo(d1, d2)).isFalse(); } @Test void testGATC_DiffNoC() { final Dependency d1 = dep("org.example", "someartifact", "jar", "testclassifier"); final Dependency d2 = dep("org.example", "someartifact", "jar", null); assertThat(DependencySet.isDeepEqualTo(d1, d2)).isFalse(); } @Test void testGAT_Same() { final Dependency d1 = dep("org.example", "someartifact", "jar", null); final Dependency d2 = dep("org.example", "someartifact", "jar", null); assertThat(DependencySet.isDeepEqualTo(d1, d2)).isTrue(); } private static Dependency dep(final String groupId, final String artifactId, final String type, final String classifier) { final Dependency dependency = new Dependency(); dependency.setGroupId(groupId); dependency.setArtifactId(artifactId); dependency.setType(type); dependency.setClassifier(classifier); return dependency; } } hanxiao34/solon1-10 package org.noear.solon.core.route; import org.noear.solon.core.event.EventBus; import org.noear.solon.core.handle.Endpoint; import org.noear.solon.core.handle.Context; import org.noear.solon.core.handle.Handler; /** * Solon router Handler * * @author noear * @since 1.0 * */ public class RouterHandler implements Handler { private Router router; public RouterHandler(Router router) { bind(router); } /** * 绑定路由器 */ public void bind(Router router) { this.router = router; } @Override public void handle(Context ctx) throws Throwable { //可能上级链已完成处理 if (ctx.getHandled()) { return; } boolean _handled = false; boolean _throwabled = false; try { //前置处理(支持多代理) handleMultiple(ctx, Endpoint.before); //主体处理 if (ctx.getHandled() == false) { //(仅支持唯一代理) _handled = handleOne(ctx, Endpoint.main); //(设定处理状态,便于 after 获取状态) ctx.setHandled(_handled); } } catch (Throwable e) { _throwabled = true; if (ctx.errors == null) { ctx.errors = e; //如果内部已经做了,就不需要了 EventBus.push(e); } throw e; } finally { //后置处理(支持多代理) handleMultiple(ctx, Endpoint.after); //前后不能反 (后置处理由内部进行状态控制) //汇总状态 if (_throwabled == false) { if (ctx.status() < 1) { if (_handled) { ctx.status(200); } else { ctx.status(404); } } } } } /** * 唯一处理(用于主处理) */ protected boolean handleOne(Context ctx, Endpoint endpoint) throws Throwable { Handler h = router.matchOne(ctx, endpoint); if (h != null) { h.handle(ctx); return ctx.status() != 404; } else { return false; } } /** * 多项目处理(用于拦截器) */ protected void handleMultiple(Context ctx, Endpoint endpoint) throws Throwable { for (Handler h : router.matchAll(ctx, endpoint)) { h.handle(ctx); } } } // Write a java program to implement the operations of Stack using Singly Linked List import static java.lang.System.exit; import java.util.*; class LinkedList { private class Node { int data; Node link; } Node top; LinkedList() { this.top = null; } public void push(int x) { Node temp = new Node(); if (temp == null) { System.out.print("Heap Overflow"); return; } temp.data = x; temp.link = top; top = temp; } public boolean isEmpty() { return top == null; } public int peak() { if (!isEmpty()) { return top.data; } else { System.out.println("Stack is empty"); return -1; } } public void pop() { if (top == null) { System.out.print("Stack Underflow"); return; } top = (top).link; } public void display() { if (top == null) { System.out.printf("Stack Underflow"); exit(1); } else { Node temp = top; while (temp != null) { System.out.printf("%d->", temp.data); temp = temp.link; } System.out.println("Null"); } } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); int d = sc.nextInt(); LinkedList obj = new LinkedList(); obj.push(a); obj.push(b); obj.push(c); obj.push(d); obj.display(); System.out.printf("Top element in Stack is : %d\n", obj.peak()); obj.pop(); System.out.println("After Invoking Pop Operation"); obj.display(); } } /* (1) Input: 1 2 3 4 Output: 4->3->2->1->Null Top element in Stack is : 4 After Invoking Pop Operation 3->2->1->Null (2) Input: 11 22 33 44 Output: 44->33->22->11->Null Top element in Stack is : 44 After Invoking Pop Operation 33->22->11->Null */ /* * 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.fluo.cluster.runner; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import com.beust.jcommander.ParameterException; import org.apache.fluo.api.client.FluoAdmin; import org.apache.fluo.api.config.FluoConfiguration; import org.apache.fluo.core.client.FluoAdminImpl; /** * For running Fluo app on cluster */ @Deprecated public abstract class ClusterAppRunner extends AppRunner { public ClusterAppRunner(String scriptName) { super(scriptName); } public class InitOptions { @Parameter(names = {"-f", "--force"}, description = "Skip all prompts and clears Zookeeper and Accumulo table. Equivalent to " + "setting both --clearTable --clearZookeeper") private boolean force; @Parameter(names = {"--clearTable"}, description = "Skips prompt and clears Accumulo table") private boolean clearTable; @Parameter(names = {"--clearZookeeper"}, description = "Skips prompt and clears Zookeeper") private boolean clearZookeeper; @Parameter(names = {"-u", "--update"}, description = "Update Fluo configuration in Zookeeper") private boolean update; @Parameter(names = {"-h", "-help", "--help"}, help = true, description = "Prints help") public boolean help; public boolean getForce() { return force; } public boolean getClearTable() { return clearTable; } public boolean getClearZookeeper() { return clearZookeeper; } public boolean getUpdate() { return update; } } public static boolean readYes() { String input = "unk"; while (true) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); try { input = bufferedReader.readLine().trim(); } catch (IOException e) { throw new IllegalStateException(e); } if (input.equalsIgnoreCase("y")) { return true; } else if (input.equalsIgnoreCase("n")) { return false; } else { System.out.print("Unexpected input '" + input + "'. Enter y/n or ctrl-c to abort: "); } } } public void init(FluoConfiguration config, String propsPath, String[] args) { InitOptions commandOpts = new InitOptions(); JCommander jcommand = new JCommander(commandOpts); jcommand.setProgramName("fluo init"); try { jcommand.parse(args); } catch (ParameterException e) { System.err.println(e.getMessage()); jcommand.usage(); System.exit(-1); } if (commandOpts.help) { jcommand.usage(); System.exit(0); } if (!config.hasRequiredAdminProps()) { System.err.println("Error - Required properties are not set in " + propsPath); System.exit(-1); } try { config.validate(); } catch (IllegalArgumentException e) { System.err .println("Error - Invalid fluo.properties (" + propsPath + ") due to " + e.getMessage()); System.exit(-1); } catch (Exception e) { System.err .println("Error - Invalid fluo.properties (" + propsPath + ") due to " + e.getMessage()); e.printStackTrace(); System.exit(-1); } try (FluoAdminImpl admin = new FluoAdminImpl(config)) { if (admin.applicationRunning()) { System.err.println("Error - The Fluo '" + config.getApplicationName() + "' application" + " is already running and must be stopped before running 'fluo init'. " + " Aborted initialization."); System.exit(-1); } FluoAdmin.InitializationOptions initOpts = new FluoAdmin.InitializationOptions(); if (commandOpts.getUpdate()) { System.out.println("Updating configuration for the Fluo '" + config.getApplicationName() + "' application in Zookeeper using " + propsPath); admin.updateSharedConfig(); System.out.println("Update is complete."); System.exit(0); } if (commandOpts.getForce()) { initOpts.setClearZookeeper(true).setClearTable(true); } else { if (commandOpts.getClearZookeeper()) { initOpts.setClearZookeeper(true); } else if (admin.zookeeperInitialized()) { System.out.print("A Fluo '" + config.getApplicationName() + "' application is already initialized in Zookeeper at " + config.getAppZookeepers() + " - Would you like to clear and reinitialize Zookeeper" + " for this application (y/n)? "); if (readYes()) { initOpts.setClearZookeeper(true); } else { System.out.println("Aborted initialization."); System.exit(-1); } } if (commandOpts.getClearTable()) { initOpts.setClearTable(true); } else if (admin.accumuloTableExists()) { System.out.print("The Accumulo table '" + config.getAccumuloTable() + "' already exists - Would you like to drop and recreate this table (y/n)? "); if (readYes()) { initOpts.setClearTable(true); } else { System.out.println("Aborted initialization."); System.exit(-1); } } } System.out.println( "Initializing Fluo '" + config.getApplicationName() + "' application using " + propsPath); try { admin.initialize(initOpts); } catch (Exception e) { System.out.println("Initialization failed due to the following exception:"); e.printStackTrace(); System.exit(-1); } System.out.println("Initialization is complete."); } } } /** * Author: */ package com.jcommerce.core.dao; import java.util.List; import com.jcommerce.core.model.GoodsType; public interface GoodsTypeDAO extends DAO { public List getGoodsTypeList(); public GoodsType getGoodsType(Long id); public void saveGoodsType(GoodsType obj); public void removeGoodsType(Long id); public List getGoodsTypeListWithAttrCount(int firstRow, int maxRow, String whereClause); } package io.github.icodegarden.commons.nio.netty; import static java.util.concurrent.TimeUnit.MILLISECONDS; import java.io.IOException; import java.net.InetSocketAddress; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.github.icodegarden.commons.lang.exception.remote.ClientClosedRemoteException; import io.github.icodegarden.commons.lang.exception.remote.ConnectFailedRemoteException; import io.github.icodegarden.commons.lang.exception.remote.ExceedExpectedRemoteException; import io.github.icodegarden.commons.lang.exception.remote.RemoteException; import io.github.icodegarden.commons.nio.AbstractNioClient; import io.github.icodegarden.commons.nio.ExchangeMessage; import io.github.icodegarden.commons.nio.health.NioClientHeartbeat; import io.github.icodegarden.commons.nio.task.HeartbeatTimerTask; import io.github.icodegarden.commons.nio.task.ReconnectTimerTask; import io.github.icodegarden.commons.nio.task.ScheduleCancelableRunnable; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.timeout.IdleStateHandler; import io.netty.util.concurrent.DefaultThreadFactory; /** * * @author Fangfang.Xu * */ public class NettyNioClient extends AbstractNioClient implements io.github.icodegarden.commons.nio.Channel { private static final Logger log = LoggerFactory.getLogger(NettyNioClient.class); private static final NioEventLoopGroup nioEventLoopGroup = new NioEventLoopGroup( Math.min(Runtime.getRuntime().availableProcessors() + 1, 32), new DefaultThreadFactory("NettyClientWorker", true)); private volatile boolean closed = true; private Bootstrap bootstrap; private volatile Channel channel; // volatile, please copy reference to use private final InetSocketAddress address; private final long heartbeatIntervalMillis; private NioClientHeartbeat heartbeat; private final ReconnectTimerTask reconnectTimerTask; private ScheduleCancelableRunnable reconnectTask; public NettyNioClient(InetSocketAddress address) { this(address, HeartbeatTimerTask.DEFAULT_INTERVAL_MILLIS); } public NettyNioClient(InetSocketAddress address, long heartbeatIntervalMillis) { this.address = address; this.heartbeatIntervalMillis = heartbeatIntervalMillis; this.reconnectTimerTask = new ReconnectTimerTask(heartbeatIntervalMillis); doOpen(); } private void doOpen() { heartbeat = new NioClientHeartbeat("netty client", this, this); ClientHandler nettyClientHandler = new ClientHandler(heartbeat); bootstrap = new Bootstrap(); bootstrap.group(nioEventLoopGroup).option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout).channel(NioSocketChannel.class); bootstrap.handler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast(new MessageDecoder()).addLast(new MessageEncoder()) .addLast("client-idle-handler", new IdleStateHandler(heartbeatIntervalMillis, 0, 0, TimeUnit.MILLISECONDS)) .addLast("handler", nettyClientHandler); } }); } @Override public synchronized void connect() throws ConnectFailedRemoteException { try { ChannelFuture future = bootstrap.connect(address); boolean ret = future.awaitUninterruptibly(3000, MILLISECONDS); if (ret && future.isSuccess()) { Channel newChannel = future.channel(); this.channel = newChannel; if (reconnectTask == null) {// IMPT 也不需要重新创建 reconnectTask = reconnectTimerTask.register(heartbeat); } closed = false; } else if (future.cause() != null) { throw future.cause(); } else { throw new ConnectFailedRemoteException("connect not success"); } } catch (RemoteException e) { throw e; } catch (Throwable e) { throw new ConnectFailedRemoteException("Connect Failed", e); } } @Override public synchronized void reconnect() throws ConnectFailedRemoteException { if (log.isInfoEnabled()) { log.info("client do reconnect..."); } // 由于reconnectTask 不能关闭,不能调用close try { if (channel != null) { channel.close(); } } catch (Exception e) { throw new ConnectFailedRemoteException("Connect Failed", e); } closed = true; connect(); } // private Channel getChannel() { // Channel c = channel; // if (c == null || !c.isActive()) { // return null; // } // return c; // } // // private boolean canHandleIdle() { // return true; // } @Override public void write(Object obj) throws RemoteException { if (log.isDebugEnabled()) { log.debug("client send:{}", obj); } if (isClosed()) { throw new ClientClosedRemoteException("client closed"); } try { channel.writeAndFlush(obj); } catch (Exception e) { throw new ExceedExpectedRemoteException(e); } } @Override protected void doSend(ExchangeMessage message) throws RemoteException { if (log.isDebugEnabled()) { log.debug("client send message:{}", message); } if (isClosed()) { throw new ClientClosedRemoteException("client closed"); } try{ channel.writeAndFlush(message); } catch (Exception e) { throw new ExceedExpectedRemoteException(e); } } @Override public synchronized void close() throws IOException { /** * 用户主动发起 */ try { if (channel != null) { channel.close(); } if (reconnectTask != null) { reconnectTask.cancel(); } } finally { closed = true; } } @Override public boolean isClosed() { return closed; } }/* * Copyright (C) 2013 BeyondAR * * 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.beyondar.android.util; import android.content.Context; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.Matrix; import com.beyondar.android.opengl.views.ARRenderer.ISnapshotCallback; import com.beyondar.android.opengl.views.BeyondarGLSurfaceView; import com.beyondar.android.views.CameraView; import com.beyondar.android.views.CameraView.IPictureCallback; public class Utils { public static final int MAX_SIZE = 512; /** * Check a number if it is a power of two * * @param n * The number to check * @return */ public static boolean isPowerOfTwo(int n) { return ((n != 0) && (n & (n - 1)) == 0); } /** * Check if the bitmap is compatible to use it with OpenGL, if not, use * resizeImageToPowerOfTwo(bitmap) method * * @param bitmap * The bitmap to check * @return True if there are no problems, false otherwise */ public static boolean isCompatibleWithOpenGL(Bitmap bitmap) { return (Utils.isPowerOfTwo(bitmap.getHeight()) && Utils.isPowerOfTwo(bitmap.getWidth())); } /** * Prepare the image to draw it using OpenGL. There are devices that doesn't * support images non power of two (size). Remember to recicle die bitmap if * the old one is not needed anymore * * @param bitmap * @return */ public static Bitmap resizeImageToPowerOfTwo(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int newWidth = (int) Math.pow(2, Math.ceil(Math.log10(width) / Math.log10(2))); int newHeight = (int) Math.pow(2, Math.ceil(Math.log10(height) / Math.log10(2))); if (newWidth > MAX_SIZE) { newWidth = MAX_SIZE; } if (newHeight > MAX_SIZE) { newHeight = MAX_SIZE; } // calculate the scale - in this case = 0.4f float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; // createa matrix for the manipulation Matrix matrix = new Matrix(); // resize the bit map matrix.postScale(scaleWidth, scaleHeight); // rotate the Bitmap // matrix.postRotate(45); // recreate the new Bitmap return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); } /** * Take a snapshot of the BeyondarGLSurface with the camera image as * background * * @param cameraView * @param bgls * @param callback */ public static void takeSnapShot(CameraView cameraView, BeyondarGLSurfaceView bgls, ICallBackBeyondARPicture callback) { ScreenShootCallback callbackProcessing = new ScreenShootCallback(callback); if (cameraView != null) { // CacheManager.getInventoryCache().purge(); cameraView.tackePicture(callbackProcessing); } else { callbackProcessing.onPictureTaken(null); } bgls.tackePicture(callbackProcessing); } public static interface ICallBackBeyondARPicture { void onFinishSnapShotProcess(Bitmap image); } private static class ScreenShootCallback implements IPictureCallback, ISnapshotCallback { Bitmap btmCamera; Bitmap btmGl; int status = 0; ICallBackBeyondARPicture callback; ScreenShootCallback(ICallBackBeyondARPicture cb) { callback = cb; } @Override public void onSnapshootTaken(Bitmap picture) { btmGl = picture; checkResults(); } @Override public void onPictureTaken(Bitmap picture) { btmCamera = picture; checkResults(); } private synchronized void checkResults() { status++; if (status == 2 && callback != null) { if (btmCamera == null) { callback.onFinishSnapShotProcess(btmGl); return; } if (btmGl == null) { callback.onFinishSnapShotProcess(btmCamera); return; } float factor = ((float) btmGl.getWidth() / (float) btmCamera.getWidth()); float newWidth = factor * btmCamera.getWidth(); float newHeight = factor * btmCamera.getHeight(); Bitmap newBtmCamera = ImageUtils.resizeImage(btmCamera, (int) newWidth, (int) newHeight); if (newBtmCamera != btmCamera) { btmCamera.recycle(); } Bitmap btm = ImageUtils.mergeBitmaps(newBtmCamera, btmGl); newBtmCamera.recycle(); Bitmap result = Bitmap.createBitmap(btm, 0, 0, btmGl.getWidth(), btmGl.getHeight()); btmGl.recycle(); btm.recycle(); System.gc(); callback.onFinishSnapShotProcess(result); } } } } /** * 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.camel.impl; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Map; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import org.apache.camel.CamelContext; import org.apache.camel.CamelContextAware; import org.apache.camel.Component; import org.apache.camel.Endpoint; import org.apache.camel.Exchange; import org.apache.camel.ExchangePattern; import org.apache.camel.PollingConsumer; import org.apache.camel.util.ObjectHelper; /** * A default endpoint useful for implementation inheritance * * @version $Revision$ */ public abstract class DefaultEndpoint implements Endpoint, CamelContextAware { private String endpointUri; private CamelContext camelContext; private Component component; private ScheduledExecutorService executorService; private ExchangePattern exchangePattern = ExchangePattern.InOnly; protected DefaultEndpoint(String endpointUri, Component component) { this(endpointUri, component.getCamelContext()); this.component = component; } protected DefaultEndpoint(String endpointUri, CamelContext camelContext) { this(endpointUri); this.camelContext = camelContext; } protected DefaultEndpoint(String endpointUri) { this.setEndpointUri(endpointUri); } protected DefaultEndpoint() { } public int hashCode() { return getEndpointUri().hashCode() * 37 + 1; } @Override public boolean equals(Object object) { if (object instanceof DefaultEndpoint) { DefaultEndpoint that = (DefaultEndpoint) object; return ObjectHelper.equal(this.getEndpointUri(), that.getEndpointUri()); } return false; } @Override public String toString() { return "Endpoint[" + getEndpointUri() + "]"; } public String getEndpointUri() { if (endpointUri == null) { endpointUri = createEndpointUri(); if (endpointUri == null) { throw new IllegalArgumentException("endpointUri is not specified and " + getClass().getName() + " does not implement createEndpointUri() to create a default value"); } } return endpointUri; } public CamelContext getCamelContext() { return camelContext; } public Component getComponent() { return component; } public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } public synchronized ScheduledExecutorService getExecutorService() { if (executorService == null) { Component c = getComponent(); if (c != null && c instanceof DefaultComponent) { DefaultComponent dc = (DefaultComponent) c; executorService = dc.getExecutorService(); } if (executorService == null) { executorService = createExecutorService(); } } return executorService; } public synchronized void setExecutorService(ScheduledExecutorService executorService) { this.executorService = executorService; } public PollingConsumer createPollingConsumer() throws Exception { return new EventDrivenPollingConsumer(this); } /** * Converts the given exchange to the specified exchange type */ public E convertTo(Class type, Exchange exchange) { // TODO we could infer type parameter if (type.isInstance(exchange)) { return type.cast(exchange); } return getCamelContext().getExchangeConverter().convertTo(type, exchange); } public E createExchange(Exchange exchange) { Class exchangeType = getExchangeType(); if (exchangeType != null) { if (exchangeType.isInstance(exchange)) { return exchangeType.cast(exchange); } } E answer = createExchange(); answer.copyFrom(exchange); return answer; } /** * Returns the type of the exchange which is generated by this component */ public Class getExchangeType() { Type type = getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type[] arguments = parameterizedType.getActualTypeArguments(); if (arguments.length > 0) { Type argumentType = arguments[0]; if (argumentType instanceof Class) { return (Class) argumentType; } } } return null; } public E createExchange() { return createExchange(getExchangePattern()); } public E createExchange(ExchangePattern pattern) { return (E) new DefaultExchange(getCamelContext(), pattern); } public ExchangePattern getExchangePattern() { return exchangePattern; } public void setExchangePattern(ExchangePattern exchangePattern) { this.exchangePattern = exchangePattern; } protected ScheduledThreadPoolExecutor createExecutorService() { return new ScheduledThreadPoolExecutor(10); } public void configureProperties(Map options) { } /** * A factory method to lazily create the endpointUri if none is specified */ protected String createEndpointUri() { return null; } protected void setEndpointUri(String endpointUri) { this.endpointUri = endpointUri; } @Deprecated public CamelContext getContext() { return getCamelContext(); } @Deprecated public void setContext(CamelContext context) { setCamelContext(context); } } package com.trivadis.plsql.formatter.settings.tests; import com.trivadis.plsql.formatter.settings.ConfiguredTestFormatter; import org.junit.Assert; import org.junit.Test; import java.io.IOException; public class FormatterOffOn extends ConfiguredTestFormatter { @Test public void one_stmt_sl_comment_eclipse_style() { final String sql = """ select * from dual; -- @formatter:off SELECT * from dual ; -- @formatter:on select * from dual; """; formatAndAssert(sql); } @Test public void one_stmt_ml_comment_eclipse_style() { final String sql = """ select * from dual; /* @formatter:off */ SELECT * from dual ; /* @formatter:on */ select * from dual; """; formatAndAssert(sql); } @Test public void one_stmt_sl_comment_plsqldev_style() { final String sql = """ select * from dual; -- NoFormat Start SELECT * from dual ; -- NoFormat End select * from dual; """; formatAndAssert(sql); } @Test public void one_stmt_ml_comment_plsqldev_style() { final String sql = """ select * from dual; /* NoFormat Start */ SELECT * from dual ; /* NoFormat End */ select * from dual; """; formatAndAssert(sql); } @Test public void two_stmt_mixed_style() { final String sql = """ select * from dual; /* noformat start, however in SQLDev 20.2 keyword is uppercase nonetheless, indent lost in 20.3 */ DELETE FrOm\s EmP where a = b ; /* @formatter:ON, the next statement is formatted by SQLDev, indent lost in 20.3 */ delete from emp where dept = 10; /* @formatter:OFF, the next statement is not formated by SQLDev */ UPDATE emp set sal = sal + 10 ; -- noformat end, after this line everthing is formatted by SQLDev select * from emp join dept on dept.deptno = emp.deptno; """; formatAndAssert(sql); } @Test public void format_if_on_and_off_defined_in_same_comment() throws IOException { final String unformatted = """ select * from dual; -- @formatter:on @formatter:off SELECT * from dual ; -- @formatter:on select * from dual; """.trim(); final String expected = """ select * from dual; -- @formatter:on @formatter:off select * from dual; -- @formatter:on select * from dual; """.trim(); final String actual = formatter.format(unformatted); Assert.assertEquals(expected, actual); } } andreikh/jdbreport /* * Created on 22.09.2004 * * JDBReport Generator * * Copyright (C) 2004-2014 * * 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 jdbreport.model.event; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ChangeEvent; /** * TableRowModelListener defines the interface for an object that listens to * changes in a TableRowModel. * * @see TableRowModelEvent * @version 1.1 03/09/08 * @author * */ public interface TableRowModelListener extends java.util.EventListener { /** Tells listeners that a row was added to the model. */ void rowAdded(TableRowModelEvent e); /** Tells listeners that a row was removed from the model. */ void rowRemoved(TableRowModelEvent e); /** Tells listeners that a row was repositioned. */ void rowMoved(TableRowModelEvent e); /** Tells listeners that a row was resized. */ void rowResized(TableRowModelEvent e); /** Tells listeners that a row was moved due to a margin change. */ void rowMarginChanged(ChangeEvent e); /** * Tells listeners that the selection model of the TableRowModel changed. */ void rowSelectionChanged(ListSelectionEvent e); /** Tells listeners that a rows was change. */ void rowUpdated(TableRowModelEvent e); } 1-10 public class string5{ public static void main(String...args) { int age=10; String str =" yugandar"; System.out.println(str.toUpperCase()); System.out.println(str.length()); System.out.println(str.trim()); System.out.println(str); } } Kaiepi/nqp0 package org.perl6.nqp.io; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.ByteChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.MalformedInputException; import java.util.ArrayList; import org.perl6.nqp.runtime.ExceptionHandling; import org.perl6.nqp.runtime.ThreadContext; public abstract class SyncHandle implements IIOClosable, IIOEncodable, IIOSyncReadable, IIOSyncWritable, IIOLineSeparable, IIOExitable { public ByteChannel chan; protected CharsetEncoder enc; protected CharsetDecoder dec; protected boolean eof = false; protected ByteBuffer readBuffer; protected byte[] linesep = null; public void close(ThreadContext tc) { try { chan.close(); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public int exitValue(ThreadContext tc) { try { if (chan instanceof ProcessChannel) { return ((ProcessChannel)chan).exitValue(); } else throw ExceptionHandling.dieInternal(tc, "This channel does not support exitValue"); } catch (InterruptedException e) { throw ExceptionHandling.dieInternal(tc, e); } } public void setEncoding(ThreadContext tc, Charset cs) { enc = cs.newEncoder(); dec = cs.newDecoder(); } public synchronized String slurp(ThreadContext tc) { try { // Read in file. ArrayList buffers = new ArrayList(); ByteBuffer curBuffer = ByteBuffer.allocate(32768); int total = 0; int read; if (readBuffer != null) { total = readBuffer.limit() - readBuffer.position(); byte[] newBytes = new byte[total]; readBuffer.get(newBytes); buffers.add(ByteBuffer.wrap(newBytes)); readBuffer = null; } while ((read = chan.read(curBuffer)) != -1) { curBuffer.flip(); buffers.add(curBuffer); curBuffer = ByteBuffer.allocate(32768); total += read; } eof = true; return decodeBuffers(buffers, total); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public synchronized String readline(ThreadContext tc) { try { boolean foundLine = false; ArrayList lineChunks = new ArrayList(); int total = 0; while (!foundLine) { /* Ensure we have a buffer available. */ if (readBuffer == null) { readBuffer = ByteBuffer.allocate(32768); if (chan.read(readBuffer) == -1) { /* End of file, so what we have is fine. */ eof = true; foundLine = true; readBuffer.flip(); break; } readBuffer.flip(); } /* Look for a line end. */ int start = readBuffer.position(); int end = start; while (!foundLine && end < readBuffer.limit()) { if (linesep != null) { int index = 0; while (index < linesep.length && end + index < readBuffer.limit() && readBuffer.get(end + index) == linesep[index]) index++; if (index == linesep.length) { end += index; foundLine = true; } else { end++; } } else { byte cur = readBuffer.get(end); if (cur == '\n') { foundLine = true; } else if (cur == '\r') { foundLine = true; /* XXX: This could fail if the \r\n sequence is * split over two chunks, with the \r at the very * end of a chunk at the \n at the beginning of * the next one I think. */ if (end+1 < readBuffer.limit() && readBuffer.get(end+1) == '\n') { end++; } } end++; } } /* Copy what we found into the results. */ byte[] lineBytes = new byte[end - start]; readBuffer.get(lineBytes); lineChunks.add(ByteBuffer.wrap(lineBytes)); total += lineBytes.length; /* If we didn't find a line, will cross chunk boundary. */ if (!foundLine) readBuffer = null; } if (lineChunks.size() == 1) return dec.decode(lineChunks.get(0)).toString(); else return decodeBuffers(lineChunks, total); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } private String decodeBuffers(ArrayList buffers, int total) throws IOException { // Copy to a single buffer and decode (could be smarter, but need // to be wary as UTF-8 chars may span a buffer boundary). ByteBuffer allBytes = ByteBuffer.allocate(total); for (ByteBuffer bb : buffers) { int amount = total < bb.limit() ? total : bb.limit(); allBytes.put(bb.array(), 0, amount); total -= amount; } allBytes.rewind(); return dec.decode(allBytes).toString(); } public synchronized String readchars(ThreadContext tc, int chars) { try { dec.reset(); CharBuffer decoded = CharBuffer.allocate(chars); boolean needMoreChars = true; if (readBuffer != null) { CoderResult result = dec.decode(readBuffer, decoded, true); if (result.isError()) { result.throwException(); } needMoreChars = result.isUnderflow(); } while (needMoreChars && !eof) { ByteBuffer oldReadBuffer = readBuffer; readBuffer = ByteBuffer.allocate(32768); if (oldReadBuffer != null) { readBuffer.put(oldReadBuffer); } eof = chan.read(readBuffer) == -1; readBuffer.flip(); CoderResult result = dec.decode(readBuffer, decoded, eof); if (eof) { dec.flush(decoded); } if (result.isError()) { result.throwException(); } needMoreChars = result.isUnderflow(); } decoded.flip(); String ret = decoded.toString(); return ret; } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public boolean eof(ThreadContext tc) { return eof; } public byte[] read(ThreadContext tc, int bytes) { try { // look in readBuffer for data from previous read, e.g. via readline if ( readBuffer != null ) { byte[] res = new byte[readBuffer.limit() - readBuffer.position()]; readBuffer.get(res); readBuffer = null; return res; } else { ByteBuffer buffer = ByteBuffer.allocate(bytes); eof = chan.read(buffer) == -1; buffer.flip(); byte[] res = new byte[buffer.limit()]; buffer.get(res); return res; } } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public long write(ThreadContext tc, byte[] array) { ByteBuffer buffer = ByteBuffer.wrap(array); return write(tc, buffer); } protected long write(ThreadContext tc, ByteBuffer buffer) { try { int toWrite = buffer.limit(); int written = 0; while (written < toWrite) { written += chan.write(buffer); } return written; } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public long print(ThreadContext tc, String s) { try { ByteBuffer buffer = enc.encode(CharBuffer.wrap(s)); return write(tc, buffer); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } public long say(ThreadContext tc, String s) { long bytes = print(tc, s); bytes += print(tc, System.lineSeparator()); return bytes; } public void setInputLineSeparator(ThreadContext tc, String sep) { try { linesep = enc.charset().newEncoder().encode( CharBuffer.wrap(sep)).array(); } catch (IOException e) { throw ExceptionHandling.dieInternal(tc, e); } } } /* * DiSNI: Direct Storage and Networking Interface * * Author: <> * * Copyright (C) 2016-2018, IBM Corporation * * 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.ibm.disni.verbs; //struct ibv_global_route { // union ibv_gid dgid; // uint32_t flow_label; // uint8_t sgid_index; // uint8_t hop_limit; // uint8_t traffic_class; //}; /** * Routing properties, used within the context of QP attributes. */ public class IbvGlobalRoute { protected byte[] dgid; protected int flow_label; protected byte sgid_index; protected byte hop_limit; protected byte traffic_class; protected IbvGlobalRoute(){ dgid = new byte[16]; } public int getFlow_label() { return flow_label; } public void setFlow_label(int flow_label) { this.flow_label = flow_label; } public byte getSgid_index() { return sgid_index; } public void setSgid_index(byte sgid_index) { this.sgid_index = sgid_index; } public byte getHop_limit() { return hop_limit; } public void setHop_limit(byte hop_limit) { this.hop_limit = hop_limit; } public byte getTraffic_class() { return traffic_class; } public void setTraffic_class(byte traffic_class) { this.traffic_class = traffic_class; } public byte[] getDgid() { return dgid; } public void setDgid(byte[] dgid) { for (int i = 0; i < dgid.length; i++){ this.dgid[i] = dgid[i]; } } } shniu/tdd-starter package io.github.shniu.corejava.interview; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * 有A,B,C三个线程,A线程输出A,B线程输出B,C线程输出C,要求,同时启动三个线程,按顺序输出ABC,循环10次。 */ public class PrintABC2 { public static void main(String[] args) { Lock lock = new ReentrantLock(); Thread a = new Thread(new PrintThread("A", lock, 0)); Thread b = new Thread(new PrintThread("B", lock, 1)); Thread c = new Thread(new PrintThread("C", lock, 2)); a.start(); b.start(); c.start(); } } class PrintThread implements Runnable { private String name; private Lock lock; private Integer flag; public static int count = 0; public static final int MAX = 30; public PrintThread(String name, Lock lock, Integer flag) { this.name = name; this.lock = lock; this.flag = flag; } @Override public void run() { while (true) { try { lock.lock(); if (count >= MAX) { // lock.unlock(); return; } if (count % 3 == flag) { System.out.println(name); count++; } } finally { lock.unlock(); } } } } package org.stagemonitor.alerting.incident; import java.util.Collection; public interface IncidentRepository { Collection getAllIncidents(); Incident getIncidentByCheckId(String checkId); boolean deleteIncident(Incident incident); boolean createIncident(Incident incident); boolean updateIncident(Incident incident); } package com.frostwire.jlibtorrent; import com.frostwire.jlibtorrent.swig.char_vector; import com.frostwire.jlibtorrent.swig.ed25519; /** * @author gubatron * @author aldenml */ public final class Ed25519 { public final static int SEED_SIZE = ed25519.seed_size; public final static int PRIVATE_KEY_SIZE = ed25519.private_key_size; public final static int PUBLIC_KEY_SIZE = ed25519.public_key_size; public final static int SIGNATURE_SIZE = ed25519.signature_size; public final static int SCALAR_SIZE = ed25519.scalar_size; public final static int SHARED_SECRET_SIZE = ed25519.shared_secret_size; private Ed25519() { } public static int createSeed(byte[] seed) { if (seed == null || seed.length != SEED_SIZE) { throw new IllegalArgumentException("seed buffer must be not null and of size " + SEED_SIZE); } char_vector v = Vectors.new_char_vector(SEED_SIZE); int r = ed25519.create_seed(v); Vectors.char_vector2bytes(v, seed); return r; } public static void createKeypair(byte[] publicKey, byte[] privateKey, byte[] seed) { if (publicKey == null || publicKey.length != PUBLIC_KEY_SIZE) { throw new IllegalArgumentException("public key buffer must be not null and of size " + PUBLIC_KEY_SIZE); } if (privateKey == null || privateKey.length != PRIVATE_KEY_SIZE) { throw new IllegalArgumentException("private key buffer must be not null and of size " + PRIVATE_KEY_SIZE); } char_vector v1 = Vectors.new_char_vector(PUBLIC_KEY_SIZE); char_vector v2 = Vectors.new_char_vector(PRIVATE_KEY_SIZE); ed25519.create_keypair(v1, v2, Vectors.bytes2char_vector(seed)); Vectors.char_vector2bytes(v1, publicKey); Vectors.char_vector2bytes(v2, privateKey); } public static void sign(byte[] signature, byte[] message, byte[] publicKey, byte[] privateKey) { if (signature == null || signature.length != SIGNATURE_SIZE) { throw new IllegalArgumentException("signature buffer must be not null and of size " + SIGNATURE_SIZE); } char_vector v1 = Vectors.new_char_vector(SIGNATURE_SIZE); ed25519.sign(v1, Vectors.bytes2char_vector(message), Vectors.bytes2char_vector(publicKey), Vectors.bytes2char_vector(privateKey)); Vectors.char_vector2bytes(v1, signature); } public static int verify(byte[] signature, byte[] message, byte[] privateKey) { return ed25519.verify(Vectors.bytes2char_vector(signature), Vectors.bytes2char_vector(message), Vectors.bytes2char_vector(privateKey)); } public static void addScalar(byte[] publicKey, byte[] privateKey, byte[] scalar) { if (publicKey == null || publicKey.length != PUBLIC_KEY_SIZE) { throw new IllegalArgumentException("public key buffer must be not null and of size " + PUBLIC_KEY_SIZE); } if (privateKey == null || privateKey.length != PRIVATE_KEY_SIZE) { throw new IllegalArgumentException("private key buffer must be not null and of size " + PRIVATE_KEY_SIZE); } if (scalar == null || scalar.length != SCALAR_SIZE) { throw new IllegalArgumentException("scalar must be not null and of size " + SCALAR_SIZE); } char_vector v1 = Vectors.bytes2char_vector(publicKey); char_vector v2 = Vectors.bytes2char_vector(privateKey); char_vector v3 = Vectors.bytes2char_vector(scalar); ed25519.add_scalar(v1, v2, v3); Vectors.char_vector2bytes(v1, publicKey); Vectors.char_vector2bytes(v2, privateKey); } public static void keyExchange(byte[] sharedSecret, byte[] publicKey, byte[] privateKey) { if (sharedSecret == null || sharedSecret.length != SHARED_SECRET_SIZE) { throw new IllegalArgumentException("shared secret buffer must be not null and of size " + SHARED_SECRET_SIZE); } char_vector v1 = Vectors.new_char_vector(SHARED_SECRET_SIZE); ed25519.key_exchange(v1, Vectors.bytes2char_vector(publicKey), Vectors.bytes2char_vector(privateKey)); Vectors.char_vector2bytes(v1, sharedSecret); } } isabelle-dr/gtfs-validator /* * Copyright 2020 Google LLC, MobilityData IO * * 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.mobilitydata.gtfsvalidator.table; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth8.assertThat; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mobilitydata.gtfsvalidator.input.CountryCode; import org.mobilitydata.gtfsvalidator.input.CurrentDateTime; import org.mobilitydata.gtfsvalidator.notice.NoticeContainer; import org.mobilitydata.gtfsvalidator.validator.DefaultValidatorProvider; import org.mobilitydata.gtfsvalidator.validator.ValidationContext; import org.mobilitydata.gtfsvalidator.validator.ValidatorLoader; import org.mobilitydata.gtfsvalidator.validator.ValidatorLoaderException; /** Runs GtfsLevelTableContainer on test CSV data. */ @RunWith(JUnit4.class) public class GtfsLevelTableLoaderTest { private static final CountryCode TEST_COUNTRY_CODE = CountryCode.forStringOrUnknown("au"); private static final ZonedDateTime TEST_NOW = ZonedDateTime.of(2021, 1, 1, 14, 30, 0, 0, ZoneOffset.UTC); private static final ValidationContext VALIDATION_CONTEXT = ValidationContext.builder() .setCountryCode(TEST_COUNTRY_CODE) .setCurrentDateTime(new CurrentDateTime(TEST_NOW)) .build(); private static InputStream toInputStream(String s) { return new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)); } private static GtfsLevelTableContainer load( InputStream inputStream, NoticeContainer noticeContainer) throws ValidatorLoaderException { ValidatorLoader validatorLoader = new ValidatorLoader(); GtfsLevelTableLoader loader = new GtfsLevelTableLoader(); return (GtfsLevelTableContainer) loader.load( inputStream, new DefaultValidatorProvider(VALIDATION_CONTEXT, validatorLoader), noticeContainer); } @Test public void validFile() throws IOException, ValidatorLoaderException { InputStream inputStream = toInputStream("level_id,level_name,level_index\n" + "level1,Ground,1\n"); NoticeContainer noticeContainer = new NoticeContainer(); GtfsLevelTableContainer tableContainer = load(inputStream, noticeContainer); assertThat(noticeContainer.getValidationNotices()).isEmpty(); assertThat(tableContainer.entityCount()).isEqualTo(1); Optional optionalLevel = tableContainer.byLevelId("level1"); assertThat(optionalLevel).isPresent(); GtfsLevel level = optionalLevel.get(); assertThat(level.levelId()).isEqualTo("level1"); assertThat(level.levelName()).isEqualTo("Ground"); assertThat(level.levelIndex()).isEqualTo(1); inputStream.close(); } @Test public void missingRequiredField() throws IOException, ValidatorLoaderException { InputStream inputStream = toInputStream("level_id,level_name,level_index\n" + ",Ground,1\n"); NoticeContainer noticeContainer = new NoticeContainer(); GtfsLevelTableContainer tableContainer = load(inputStream, noticeContainer); assertThat(noticeContainer.getValidationNotices()).isNotEmpty(); assertThat(tableContainer.entityCount()).isEqualTo(0); inputStream.close(); } @Test public void emptyFile() throws IOException, ValidatorLoaderException { InputStream inputStream = toInputStream(""); NoticeContainer noticeContainer = new NoticeContainer(); load(inputStream, noticeContainer); assertThat(noticeContainer.getValidationNotices()).isNotEmpty(); assertThat(noticeContainer.getValidationNotices().get(0).getClass().getSimpleName()) .isEqualTo("EmptyFileNotice"); inputStream.close(); } } /* * Copyright 2016 LINE Corporation * * LINE Corporation 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 com.linecorp.bot.model.message.quickreply; import java.util.List; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Singular; import lombok.Value; /** * QuickReply objects which contains {@link QuickReplyItem}. * *

When a user receives a message that contains quick reply buttons from a bot, * those buttons appear at the bottom of the chat screen. * The user can simply tap one of the buttons to reply to the bot. * *

The quick reply feature can be used in a one-on-one chat with a bot, * a group, and a room. You can set up to 13 quick reply buttons to a message of any type. * * @see //developers.line.me/en/docs/messaging-api/using-quick-reply/ */ @Value @Builder @AllArgsConstructor(staticName = "items", access = AccessLevel.PUBLIC) @JsonDeserialize(builder = QuickReply.QuickReplyBuilder.class) public class QuickReply { @Singular List items; @JsonPOJOBuilder(withPrefix = "") public static class QuickReplyBuilder { } } kuznetsovsergeyymailcom/homework /** * package with bubble sorting algoritm. * */ package ru.skuznetsov;/* * Copyright (C) 2016 The Soft Braille Keyboard 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 com.dalton.braillekeyboard; import java.util.Locale; import android.Manifest; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.inputmethodservice.Keyboard; import android.support.v4.content.ContextCompat; import android.view.inputmethod.InputMethodManager; import com.dalton.braillekeyboard.EditingUtilities.Word; import com.dalton.braillekeyboard.Options.KeyboardEcho; import com.dalton.braillekeyboard.Options.KeyboardFeedback; import com.dalton.braillekeyboard.Pad.Swipe; import com.dalton.braillekeyboard.SpellChecker.SpellingSuggestionsReadyListener; import com.dalton.braillekeyboard.SpellChecker.Suggestion; /** * ActionHandler handles actions from a View or other interface and performs the * appropriate logic before returning the results back to the calling View in * the form of a callback. This performs higher level logic than the * InputService itself and communicates directly with the InputService to * collaborate and solve the requests from the View. * * A View should instantiate this class once upon initialisation and call it's * handleSwipe or handleCharacter methods to perform actions. Before such * activity the view shall set the IME listener by calling * setKeyboardListener(KeyboardListener listener) and also set the callback by * calling setCallback(OnActionListener callback). You should always call the * shutdown() method when you are done. * * The callback is how the results are sent back to the View. The View should * implement the respective callbacks and implement them appropriate to their * View and user interface. See ActionHandler.OnActionListener for details. */ public class ActionHandler { // The maximum time between two identical swipe patterns which constitutes a // double swipe. private static final long DOUBLE_TOUCH_THRESHOLD = 1300; /** * Listener for handling the results of requests to the input methods. You * should implement these callbacks in your View and display the results to * the user. */ public interface OnActionListener { /** * Deliver a string of text to the view as output of a certain action * that was performed. This might be some sort of message, a key name to * echo or some other text. Your UI should communicate this to the user * somehow in the form of audible or visual representation whatever is * appropriate for the use case. * * @param format * Format string to be used to display the message. * @param text * Any text of the message. * @param isPasswordField * True if it should be displayed with the same rules of * showing passwords. */ void onText(String format, String text, boolean isPasswordField); void onText(String format, String text, boolean isPasswordField, int mode); /** * Called when a notification should be delivered to the user. * * @param vibrate * true if the device should be vibrated for this * notification. * @param playSound * true if a sound should be played for this notification. */ void onNotify(boolean vibrate, boolean playSound); /** * Called when dots 7 and 8 should be set in the View. * * @param dot7 * Whether dot7 is pressed. * @param dot8 * Whether dot8 is pressed. */ void onSetDots(boolean dot7, boolean dot8); /** * Called when the View should update it's Locale. This is generally * called when the Braille table is changed because there is the * possibility for language change. */ void onSetLocale(Locale locale); /** * Called when the View should shrink itself. */ void onShrink(); /** * Called when the View should update the state of it's privacy mode. */ void onPrivacy(); void onShutup(); } /** * Representation of varying textual granularities from the smallest level * character up until the entire text. */ private enum Granularity { CHARACTER, WORD, LINE, ALL; } /** * Representation of the currently available edit actions that can be * performed on a selection of text. */ private enum EditAction { SELECT_ALL(R.string.select_all), COPY(android.R.string.copy), CUT( android.R.string.cut), PASTE(android.R.string.paste), SPEAK( R.string.speak_selection), DELETE(R.string.delete_selection); // The Android resource for the text UI string for this action. public final int resource; EditAction(int resource) { this.resource = resource; } // Find the position of this action in the enum values() array. private int getIndexOfThis() { EditAction[] values = EditAction.values(); int i; for (i = 0; i < values.length; i++) { if (this == values[i]) { break; } } return i; } /** * Move in order to the next EditAction in the enum list. If we are at * the end of the list it will wrap. * * @return The new EditAction instance. */ public EditAction next(ClipboardManager clipboard) { int i = getIndexOfThis(); if (++i == values().length) { i = 0; // point at first item in list. } if (values()[i] == PASTE) { boolean canPaste; // Check that there is text on the clipboard so it makes sense // showing paste. if (!(clipboard.hasPrimaryClip())) { canPaste = false; } else { // This enables the paste menu item, since the clipboard // contains plain text. canPaste = true; } if (!canPaste) { if (++i == values().length) { i = 0; // Point at start if we exceed the end } } } return values()[i]; } } private final ClipboardManager clipboard; private final InputMethodManager inputManager; private final SpellChecker spellChecker; private final VoiceInput voiceInput = new VoiceInput(); private EditAction editAction = EditAction.COPY; private long lastTouchTime = 0; // Time screen was last touched. private Swipe lastSwipe = Swipe.NONE; // Type of last gesture. private KeyboardListener listener; private OnActionListener callback; private int directionThroughSuggestionList; private SpellChecker.Direction spellingDirection; private Suggestion spellingSuggestion; /** * Create a new ActionHandler for the given context. * * @param context * The application context. */ public ActionHandler(Context context) { inputManager = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); clipboard = (ClipboardManager) context .getSystemService(Context.CLIPBOARD_SERVICE); spellChecker = new SpellChecker(context); } /** * Set the callback to deliver results to the View interracting with this * instance. * * @param callback * The View's implementation of ActionHandler.OnActionListener * listening for updates. */ public void setCallback(OnActionListener callback) { this.callback = callback; } /** * Set the listener so that the ActionHandler can communicate with the * underlying IME. * * @param listener * The KeyboardListener for the current input session. */ public void setKeyboardListener(KeyboardListener listener) { this.listener = listener; } /** * Releases system resources. This should be called just before the * interracting View gets destroyed. */ public void shutdown() { voiceInput.destroy(); spellChecker.destroy(); } /** * Handle swipe actions delivered from the interracting View. * * Each View should deliver a swipe action as defined by the generic * Pad.Swipe type. This method will perform the appropriate action for the * received Swipe gesture. If need be the appropriate callbacks will be * invoked. * * @param context * The application context. * @param value * The Swipe value from the View. * @return true if the Swipe was handled otherwise false. */ public boolean handleSwipe(Context context, Swipe value) { // Disable all swipes while voice input is in progress. if (voiceInput.isListening()) { return true; } value = normaliseSwipe(value); String message = null; boolean notify = true; boolean setDots = false; boolean considerPassword = false; // states for dots 7 and 8 boolean dots[] = { false, false }; boolean fastDoubleSwipe = fastDoubleSwipe(value, DOUBLE_TOUCH_THRESHOLD); switch (value) { case ONE_LEFT: moveLeft(context, Granularity.CHARACTER); break; case ONE_RIGHT: moveRight(context, Granularity.CHARACTER); break; case ONE_DOWN: KeyboardFeedback feedback = KeyboardFeedback.valueOf(Integer .parseInt(Options.getStringPreference(context, R.string.pref_keyboard_feedback_key, KeyboardFeedback.ALL.getValue()))); feedback = KeyboardFeedback.next(feedback); Options.writeStringPreference(context, R.string.pref_keyboard_feedback_key, feedback.getValue()); message = context.getString(feedback.resource); break; case ONE_UP: message = getInput(Granularity.CHARACTER); considerPassword = true; break; case TWO_LEFT: moveLeft(context, Granularity.WORD); break; case TWO_RIGHT: moveRight(context, Granularity.WORD); break; case TWO_UP: message = getInput(Granularity.WORD); considerPassword = true; break; case TWO_DOWN: KeyboardEcho echo = KeyboardEcho.valueOf(Integer.parseInt(Options .getStringPreference(context, R.string.pref_echo_feedback_key, KeyboardEcho.CHARACTER.getValue()))); echo = KeyboardEcho.next(echo); Options.writeStringPreference(context, R.string.pref_echo_feedback_key, echo.getValue()); message = context.getString(echo.resource); break; case THREE_LEFT: moveLeft(context, Granularity.LINE); break; case THREE_RIGHT: moveRight(context, Granularity.LINE); break; case THREE_UP: message = getInput(Granularity.LINE); considerPassword = true; break; case THREE_DOWN: if (listener.getDots() == 8) { setDots = true; dots[0] = true; } else { message = context.getString(R.string.unknown_character); } break; case FOUR_LEFT: backspace(context, Granularity.CHARACTER, fastDoubleSwipe); break; case FOUR_RIGHT: if (fastDoubleSwipe) { if (handleDoubleSpace(context)) { break; } } typeCharacter(context, (int) ' ', " "); break; case FOUR_DOWN: // newline / enter typeCharacter(context, Keyboard.KEYCODE_DONE, context.getString(R.string.newline)); break; case FOUR_UP: Options.switchBooleanPreference(context, R.string.pref_privacy_key, Boolean.parseBoolean(context .getString(R.string.pref_privacy_default))); callback.onPrivacy(); message = Options.getBooleanPreference(context, R.string.pref_privacy_key, Boolean.parseBoolean(context .getString(R.string.pref_privacy_default))) ? context .getString(R.string.privacy_enabled) : context .getString(R.string.privacy_disabled); break; case FIVE_LEFT: backspace(context, Granularity.WORD, fastDoubleSwipe); break; case FIVE_DOWN: if (fastDoubleSwipe) { message = context.getString(R.string.show_input_switcher); inputManager.showInputMethodPicker(); } else { message = context.getString(R.string.swipe_confirm_input); } break; case FIVE_UP: if (fastDoubleSwipe) { callback.onSetLocale(Locale.getDefault()); message = context.getString(R.string.show_settings); Intent intent = new Intent(context, PreferenceIME.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else { message = context.getString(R.string.swipe_confirm_settings); } break; case SIX_LEFT: backspace(context, Granularity.LINE, fastDoubleSwipe); break; case SIX_RIGHT: nextAction(context); break; case SIX_UP: selectAction(context); break; case SIX_DOWN: if (listener.getDots() == 8) { setDots = true; dots[1] = true; } else { message = context.getString(R.string.unknown_character); } break; case HOLD_SIX_LEFT: moveLeft(context, Granularity.ALL); break; case HOLD_SIX_RIGHT: moveRight(context, Granularity.ALL); break; case HOLD_SIX_DOWN: boolean echoPassword = Options.switchBooleanPreference(context, R.string.pref_echo_passwords_key, false); message = echoPassword ? context .getString(R.string.speak_passwords) : context .getString(R.string.no_password_echo); break; case HOLD_SIX_UP: message = getInput(Granularity.ALL); considerPassword = true; break; case HOLD_THREE_LEFT: backspace(context, Granularity.ALL, fastDoubleSwipe); break; case HOLD_THREE_RIGHT: int brailleType = listener.switchBrailleType(); message = brailleType == 8 ? context .getString(R.string.grade_computer) : context .getString(R.string.grade_literary); callback.onSetLocale(listener.getLocale()); break; case HOLD_THREE_DOWN: message = listener.switchTable(); message = message == null ? context .getString(R.string.no_braille_table) : message; callback.onSetLocale(listener.getLocale()); break; case HOLD_THREE_UP: doVoiceInput(context, fastDoubleSwipe); break; case HOLD_ONE_RIGHT: message = context .getString(listener.toggleMark() ? R.string.set_mark : R.string.unset_mark); break; case HOLD_ONE_LEFT: message = context.getString(R.string.keyboard_shrink); callback.onShrink(); break; case HOLD_ONE_DOWN: CharSequence text = listener.getAllText().text; if (text != null) { message = String.format(context.getString(R.string.word_count), EditingUtilities.lineCount(text), EditingUtilities.wordCount(text), EditingUtilities.characterCount(text)); } break; case HOLD_ONE_UP: Options.switchBooleanPreference(context, R.string.pref_auto_caps_key, Boolean.parseBoolean(context .getString(R.string.pref_auto_caps_default))); message = Options.getBooleanPreference(context, R.string.pref_auto_caps_key, Boolean.parseBoolean(context .getString(R.string.pref_auto_caps_default))) ? context .getString(R.string.auto_caps_enabled) : context .getString(R.string.auto_caps_disabled); break; case HOLD_FOUR_LEFT: doSpellCheck(context, SpellChecker.Direction.LEFT, 0, listener.getCursor()); break; case HOLD_FOUR_RIGHT: doSpellCheck(context, SpellChecker.Direction.RIGHT, 0, listener.getCursor()); break; case HOLD_FOUR_DOWN: nextSpellCheckSuggestion(context); break; case HOLD_FOUR_UP: previousSpellCheckSuggestion(context); break; case NONE: return false; default: notify = false; } // Invoke the notification callback callback.onNotify(notify, notify); if (message != null) { // Only invoke onText callback if there is a message to send i.e. it // wasn't already handled. callback.onText("%s", message, considerPassword ? listener.isPasswordField() : false); } if (setDots) { // Dots 7 or 8 were triggered callback.onSetDots(dots[0], dots[1]); } lastSwipe = value; // update the last swipe return true; } /** * Handle typing a Braille character into the underlying IME. The character * is delivered as a byte value representing the dot pattern and will be * converted and written as a standard textual character by the IME. * * @param context * The application context. * @param value * The byte value which represents the dot pattern to type. This * is a bitstring that represents a Braille pattern where dot 8 * is represented by the MSB and dot 1 by the LSB. A value of 0 * means no dots are present and a value of 0b11111111 means all * 8 dots are pressed. */ public void handleCharacter(Context context, byte value) { // Can't type while voice input is in progress. if (voiceInput.isListening()) { return; } lastSwipe = Swipe.NONE; String result; if ((result = listener.handleTypedCharacter(value)) == null) { // IME couldn't handle the dot pattern propergate the error to the // callback. callback.onText("%s", context.getString(R.string.unknown_character), false); } else { callback.onNotify(true, true); // Decide what to deliver to the callback such as a key echo or // autocompletion string. String character = echoCharacter(context, result); result = character == null ? "" : character; if (!(result = result.trim()).equals("")) { callback.onText("%s", result.toString(), listener.isPasswordField()); } } // dots 7 and 8 should now be unset callback.onSetDots(false, false); } // Handle prompting user to confirm an action with a double swipe. private boolean isConfirmed(Context context, boolean fastDoubleTouch) { if (!fastDoubleTouch) { callback.onText("%s", context.getString(R.string.swipe_confirm), false); return false; } return true; } // Perform the currently selected Edit Action on the region. private void selectAction(Context context) { switch (editAction) { case COPY: performContextMenuAction(context, true, android.R.id.copy, R.string.copied, R.string.copy_error); listener.deselect(); break; case CUT: if (performContextMenuAction(context, true, android.R.id.cut, android.R.string.cut, R.string.cut_error)) { listener.setCursorToStartOfSelection(); } break; case PASTE: if (performContextMenuAction(context, false, android.R.id.paste, R.string.pasted, R.string.paste_error)) { int cursor = listener.getCursor(); listener.setSelection(cursor); } break; case SPEAK: case DELETE: performAction(context, editAction); break; case SELECT_ALL: listener.selectAll(); callback.onText("%s", context.getString(R.string.selected_all), false); break; default: } } // Handle these actions by using the inbuilt android context menu action private boolean performContextMenuAction(Context context, boolean requiresSelection, int code, int successString, int errorString) { if (!requiresSelection || listener.setSelection()) { if (listener.performContextMenuAction(code)) { callback.onText("%s", context.getString(successString), false); return true; } else { callback.onText("%s", context.getString(errorString), false); return false; } } else { callback.onText("%s", context.getString(R.string.mark_not_set), false); return false; } } // These actions aren't implemented by Android so do them ourselves. private boolean performAction(Context context, EditAction action) { if (listener.setSelection()) { CharSequence text = listener.getSelectedText(0); listener.deselect(); switch (action) { case SPEAK: callback.onText( "%s", text == null ? context.getString(R.string.blank) : text .toString(), listener.isPasswordField()); break; case DELETE: if (listener.deleteSelection() && text != null) { callback.onText(context.getString(R.string.deleted), text.toString(), listener.isPasswordField()); } else { callback.onText("%s", context.getString(R.string.nothing_to_delete), false); } break; default: return false; } return true; } callback.onText("%s", context.getString(R.string.mark_not_set), false); return false; } private void nextAction(Context context) { editAction = editAction.next(clipboard); callback.onText("%s", context.getString(editAction.resource), false); } // Move the cursor left by the appropriate granularity and speak the result. private void moveLeft(Context context, Granularity granularity) { EditingUtilities.Word word = null; listener.finishComposingText(); if (listener.isSelectAll()) { granularity = Granularity.ALL; listener.setSelection(0); } switch (granularity) { case CHARACTER: word = EditingUtilities.moveToPreviousCharacter(listener); break; case WORD: word = EditingUtilities.moveToPreviousWord(listener); break; case LINE: word = EditingUtilities.moveToPreviousLine(listener); break; case ALL: word = EditingUtilities.moveToHome(listener); break; default: } if (word != null) { callback.onText("%s", !word.moveLeft ? context.getString(R.string.start_of_text) : word.word, word.moveLeft && listener.isPasswordField()); } } // Move the cursor right by the appropriate granularity and speak the // result. private void moveRight(Context context, Granularity granularity) { EditingUtilities.Word word = null; listener.finishComposingText(); if (listener.isSelectAll()) { granularity = Granularity.ALL; listener.setSelection(0); } switch (granularity) { case CHARACTER: word = EditingUtilities.moveToNextCharacter(listener); break; case WORD: word = EditingUtilities.moveToNextWord(listener); break; case LINE: word = EditingUtilities.moveToNextLine(listener); break; case ALL: word = EditingUtilities.moveToEnd(listener); break; default: } if (word != null) { callback.onText("%s", !word.moveRight ? context.getString(R.string.end_of_text) : word.word, word.moveRight && listener.isPasswordField()); } } // Perform backspace by the specified Granularity. private boolean backspace(Context context, Granularity granularity, boolean fastDoubleTouch) { EditingUtilities.Word word = null; boolean canDelete = true; switch (granularity) { case CHARACTER: listener.finishComposingText(); word = EditingUtilities.moveToPreviousCharacter(listener); break; case WORD: listener.finishComposingText(); Word space = EditingUtilities.skipSepBackwards(listener, EditingUtilities.WORD_SEPARATORS); word = EditingUtilities.getWord(listener); if (word != null) { if (space != null) { word.charsBefore += space.charsBefore; } if (word.word.length() > word.charsBefore) { word.word = word.word.substring(0, word.charsBefore); } EditingUtilities.moveToPreviousWord(listener); } break; case LINE: canDelete = isConfirmed(context, fastDoubleTouch); if (canDelete) { listener.finishComposingText(); int cursor = listener.getCursor(); word = EditingUtilities.getLine(listener); if (word != null && (cursor > 0 || word.charsAfter > 0)) { int moveChars = (cursor - word.charsBefore) > 0 ? 1 : 0; listener.setSelection(cursor - moveChars - word.charsBefore); word.charsBefore = word.charsBefore + moveChars + word.charsAfter; } } break; case ALL: canDelete = isConfirmed(context, fastDoubleTouch); if (canDelete) { listener.finishComposingText(); word = EditingUtilities.moveToHome(listener); word.word = EditingUtilities.getAllText(listener); word.charsBefore = word.word.length(); } break; default: } return performDelete(context, word, canDelete); } // Given the text to delete and a canDelete flag do the actual deletion. private boolean performDelete(Context context, EditingUtilities.Word word, boolean canDelete) { if (canDelete && word != null) { if (word.charsBefore > 0 || word.charsAfter > 0) { // cursor moved back word.charsBefore positions, so delete that // many chars ahead of the cursor. if (listener.deleteSurroundingText(0, word.charsBefore)) { if (word.word != null) { callback.onText(context.getString(R.string.deleted), word.word, listener.isPasswordField()); } return true; } else { return false; } } else { callback.onText("%s", context.getString(R.string.nothing_to_delete), false); return true; } } return false; } // Insert a certain character like a ' ' or '\n' private void typeCharacter(Context context, int code, String charName) { listener.finishComposingText(); Word word = EditingUtilities.getWord(listener); String message = word == null ? null : word.word.substring(0, word.charsBefore); listener.onKey(code); if ((message = echoWord(context, message)) == null) { message = echoCharacter(context, charName); } callback.onText("%s", message, listener.isPasswordField()); if (Options.getBooleanPreference(context, R.string.pref_echo_misspellings_key, Boolean.parseBoolean(context .getString(R.string.pref_echo_misspellings_default))) && spellChecker.isSpellCheckAvailable()) { doSpellCheck(context, SpellChecker.Direction.UNDER_CURSOR, 0, listener.getCursor() - 2); } } // Special logic for double space to insert a period followed by a space. private boolean handleDoubleSpace(Context context) { if (Options.getBooleanPreference(context, R.string.pref_double_space_period_key, Boolean.parseBoolean(context .getString(R.string.pref_double_space_period_default)))) { CharSequence text = listener.getTextBeforeCursor(2); if (text != null) { if (text.length() == 2 && Character.isWhitespace(text.charAt(1)) && Character.isLetterOrDigit(text.charAt(0))) { listener.deleteSurroundingText(1, 0); listener.onKey('.'); typeCharacter(context, ' ', " "); return true; } } } return false; } // Return true if the same gesture was typed quickly in succession. private boolean fastDoubleSwipe(Swipe swipe, long threshold) { if ((lastTouchTime + threshold) > System.currentTimeMillis() && lastSwipe == swipe) { lastTouchTime = 0; return true; } else { lastSwipe = swipe; lastTouchTime = System.currentTimeMillis(); return false; } } // Get a particular granularity of text from the IME. private String getInput(Granularity granularity) { String text = ""; Word word; switch (granularity) { case CHARACTER: text = EditingUtilities.getCharacter(listener); break; case WORD: word = EditingUtilities.getWord(listener); text = word == null ? null : word.word; break; case LINE: word = EditingUtilities.getLine(listener); text = word == null ? null : word.word; break; case ALL: text = EditingUtilities.getAllText(listener); break; default: } return text; } // Handle voice input. public boolean doVoiceInput(final Context context, boolean fastDoubleSwipe) { // Check for the "dangerous permission" for Android 6 and higher. if (ContextCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { // Fast double swipe to show the permission dialog so we don't // surprise the user having no screen reader or talking keyboard in // focus. if (!fastDoubleSwipe) { callback.onText("%s", context.getString(R.string.voice_input_enable), false); } else { // Show permission dialog Intent intent = new Intent(context, IntentActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(context .getString(R.string.action_record_audio_permission)); intent.putExtra( context.getString(R.string.require_record_audio_now), true); context.startActivity(intent); } return false; // We didn't do voice input. } VoiceInput.TextReadyListener textReadyListener = new VoiceInput.TextReadyListener() { @Override public void onTextReady(String text) { // Write the text and send it back to the callback. if (text != null && text.length() > 0) { CharSequence before = listener.getTextBeforeCursor(1); if (before != null && before.length() > 0 && !Character.isWhitespace(before.charAt(0))) { listener.onKey(' '); } listener.commitText(text, 1); callback.onText("%s", text, listener.isPasswordField()); } } @Override public void onError(int error) { callback.onText("%s", String.format( context.getString(R.string.voice_input_error), error), false); } }; if (voiceInput.start(context, textReadyListener)) { callback.onShutup(); } else { callback.onText("%s", context.getString(R.string.voice_input_is_not_available), false); return false; } return true; } // Rules for echoing character. Return the character if it should be echoed // else null. private static String echoCharacter(Context context, String character) { if ((Integer.parseInt(Options.getStringPreference(context, R.string.pref_echo_feedback_key, KeyboardEcho.CHARACTER.getValue())) & KeyboardEcho.CHARACTER.value) != 0) { return character; } return null; } // Rules for echoing word. Return the word if it should be echoed // else null. private static String echoWord(Context context, String word) { if ((Integer.parseInt(Options.getStringPreference(context, R.string.pref_echo_feedback_key, KeyboardEcho.CHARACTER.getValue())) & KeyboardEcho.WORD.value) != 0) { return word; } return null; } // Some swipe actions should resolve to the same thing eg. dots 4 and 5 // swipe right. private static Swipe normaliseSwipe(Swipe swipe) { if (swipe == Swipe.FIVE_RIGHT) { return Swipe.FOUR_RIGHT; } return swipe; } private void doSpellCheck(final Context context, SpellChecker.Direction direction, int move, int cursor) { SpellingSuggestionsReadyListener spellingListener = new SpellingSuggestionsReadyListener() { @Override public void suggestionsReady(Suggestion result) { spellingSuggestion = result; if (result != null || spellingDirection == SpellChecker.Direction.UNDER_CURSOR) { handleSpellingSuggestion(context); } else { callback.onText("%s", context.getString(R.string.no_more_misspellings), false); } } }; String text = getInput(Granularity.ALL); spellingDirection = direction; directionThroughSuggestionList = move; if (text != null && text.length() > 0) { if (!spellChecker.checkSpelling(spellingListener, text, cursor, direction)) { callback.onText("%s", context.getString(R.string.spellcheck_not_supported), false); } } else { callback.onText("%s", context.getString(R.string.blank), false); } } private void handleSpellingSuggestion(Context context) { boolean password = false; String message = null; if (spellingSuggestion == null && directionThroughSuggestionList != 0) { message = context.getString(R.string.word_correct); } else if (spellingSuggestion != null && spellingDirection == SpellChecker.Direction.UNDER_CURSOR) { spellingDirection = null; if (directionThroughSuggestionList > 0) { nextSpellCheckSuggestion(context); } else if (directionThroughSuggestionList < 0) { previousSpellCheckSuggestion(context); } else { message = context.getString(R.string.word_misspelled); } } else if (spellingSuggestion != null) { password = true; message = spellingSuggestion.isMisspelledWord() ? String.format( context.getString(R.string.word_correction_misspelled), spellingSuggestion.getCurrent()) : spellingSuggestion .getCurrent(); listener.setSelection(spellingSuggestion.offset); listener.deleteSurroundingText(0, spellingSuggestion.getLength()); listener.commitText(spellingSuggestion.getCurrent(), 1); listener.setSelection(spellingSuggestion.offset); spellingSuggestion.setLength(); } if (message != null) { callback.onText("%s", message, listener.isPasswordField() && password, Speech.QUEUE_ADD); } } private void nextSpellCheckSuggestion(Context context) { if (spellingSuggestion != null) { if (spellCheckerMatchesWord()) { spellingSuggestion.next(); handleSpellingSuggestion(context); return; } } doSpellCheck(context, SpellChecker.Direction.UNDER_CURSOR, 1, listener.getCursor()); } private void previousSpellCheckSuggestion(Context context) { if (spellingSuggestion != null) { if (spellCheckerMatchesWord()) { spellingSuggestion.prev(); handleSpellingSuggestion(context); return; } } doSpellCheck(context, SpellChecker.Direction.UNDER_CURSOR, -1, listener.getCursor()); } private boolean spellCheckerMatchesWord() { String text = getInput(Granularity.ALL); if (text != null && spellingSuggestion != null) { int offset = spellingSuggestion.offset; int length = spellingSuggestion.getLength(); int cursor = listener.getCursor(); if (text.length() > 0 && (offset + length) <= text.length() && cursor >= offset && cursor < (offset + length)) { return text.substring(offset, offset + length).equals( spellingSuggestion.getCurrent()); } } return false; } } src/main/java/de/lmu/cis/ocrd/pagexml/OCRWord.java package de.lmu.cis.ocrd.pagexml; import org.w3c.dom.Node; import javax.xml.xpath.XPathExpressionException; import java.util.List; import java.util.StringJoiner; public class OCRWord implements de.lmu.cis.ocrd.ml.OCRWord { private final String word, raw; private final List masterOCRCharConfidences; private final double wordConfidence; private final String line; private final boolean isGT; private OCRWord(TextEquiv te, String line, List masterOCRCharConfidences) throws XPathExpressionException { this.line = line; this.wordConfidence = te.getConfidence(); this.word = te.getUnicodeNormalized(); this.raw = te.getUnicode(); this.masterOCRCharConfidences = masterOCRCharConfidences; this.isGT = isGT(te); } OCRWord(Node node, String line, List mConfs) throws XPathExpressionException { this(new TextEquiv(node), line, mConfs); } boolean isGT() { return isGT; } private static boolean isGT(TextEquiv te) { // TODO: data type details should contain embedded json e.g. `{"gt": true, "name": "ground truth", ...}` return te.getDataTypeDetails().startsWith("OCR-D-GT"); } @Override public String getLineNormalized() { return line; } @Override public double getConfidence() { return wordConfidence; } @Override public double getCharacterConfidenceAt(int i) { if (i < masterOCRCharConfidences.size()) { return masterOCRCharConfidences.get(i); } return 0.0; } @Override public String getWordRaw() { return raw; } @Override public String getWordNormalized() { return word; } @Override public String toString() { StringJoiner sj = new StringJoiner(","); for (int i = 0; i < word.length(); i++) { sj.add(Double.toString(getCharacterConfidenceAt(i))); } return getWordNormalized() + "|" + sj.toString(); } } src/test/java/org/spideruci/analysis/statik/controlflow/DomTreeTest.java0 package org.spideruci.analysis.statik.controlflow; import static org.junit.Assert.*; import static org.spideruci.jump.GraphAssertions.*; import java.util.function.BiConsumer; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.spideruci.jump.Graphs; public class DomTreeTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void shouldThrowExceptionWithNullFlowGraph() { // given Graph flowGraph = null; // then thrown.expect(IllegalArgumentException.class); //when Algorithms.getDominatorTree(flowGraph); } @Test public void shouldReturnThrowupWhenFlowGraphIsEmpty() { // given Graph flowGraph = Graph.createEmptyGraph(); // then thrown.expect(IllegalArgumentException.class); //when Algorithms.getDominatorTree(flowGraph); } @Test public void shouldReturnthrowUpWithNullStartNode() { // given Graph flowGraph = Graph.create(); // then thrown.expect(IllegalArgumentException.class); //when Algorithms.getDominatorTree(flowGraph); } @Test public void endShouldPointToStartInGraphWithNoOtherNodes() { // given Graph flowGraph = Graphs.justStartAndEnd(); System.out.println(flowGraph); //when Graph domTree = Algorithms.getDominatorTree(flowGraph); System.out.println(domTree); //then assertTrue(domTree.node(Graph.START).pointsTo().contains(domTree.node(Graph.END))); } @Test public void testDomTreeForSimpleIfStructure() { // given Graph flowGraph = Graphs.simpleIfStructure(); System.out.println(flowGraph); //when Graph domTree = Algorithms.getDominatorTree(flowGraph); System.out.println(domTree); //then assert1pointsTo2(Graph.START, Graph.END, domTree); assert1pointsTo2(Graph.START, "branch", domTree); assert1pointsTo2("branch", "then", domTree); assert1pointsTo2("branch", "join", domTree); assert1pointsTo2("join", "next", domTree); assert1doesNotPointTo2("next", Graph.END, domTree); assert1doesNotPointTo2(Graph.START, "join", domTree); assert1doesNotPointTo2(Graph.START, "next", domTree); } @Test public void testDomTreeForSimpleIfElseStructure() { // given Graph flowGraph = Graphs.simpleIfElseStructure(); System.out.println(flowGraph); //when Graph domTree = Algorithms.getDominatorTree(flowGraph); System.out.println(domTree); //then assert1pointsTo2(Graph.START, Graph.END, domTree); assert1pointsTo2(Graph.START, "branch", domTree); assert1pointsTo2("branch", "then", domTree); assert1pointsTo2("branch", "else", domTree); assert1pointsTo2("branch", "join", domTree); assert1pointsTo2("join", "next", domTree); assert1doesNotPointTo2("next", Graph.END, domTree); assert1doesNotPointTo2(Graph.START, "join", domTree); assert1doesNotPointTo2(Graph.START, "next", domTree); } @Test public void testForSimpleLoopStructure() { // given Graph flowGraph = Graphs.simpleLoopStruture(); System.out.println(flowGraph); //when Graph domTree = Algorithms.getDominatorTree(flowGraph); System.out.println(domTree); //then assert1pointsTo2(Graph.START, Graph.END, domTree); assert1pointsTo2(Graph.START, "head", domTree); assert1pointsTo2("head", "body", domTree); assert1pointsTo2("head", "tail", domTree); assert1doesNotPointTo2("head", Graph.END, domTree); assert1doesNotPointTo2(Graph.START, "tail", domTree); } /** * http://pages.cs.wisc.edu/~fischer/cs701.f08/lectures/Lecture19.4up.pdf */ @Test public void testDomTreeFischerLectureExample() { // given Graph flowGraph = Graphs.fisher(); System.out.println(flowGraph); //when Graph domTree = Algorithms.getDominatorTree(flowGraph); //then System.out.println(domTree); assert1pointsTo2(Graph.START, "a", domTree); assert1pointsTo2("a", "b", domTree); assert1pointsTo2("a", "c", domTree); assert1pointsTo2("a", "d", domTree); assert1pointsTo2("d", "e", domTree); assert1pointsTo2("e", "f", domTree); assert1pointsTo2("f", Graph.END, domTree); } @Test public void testPostDomTreeFischerLectureExample() { // given Graph flowGraph = Graphs.fisher(); Graph revFlowGraph = flowGraph.reverseEdges(); System.out.println(revFlowGraph); //when Graph domTree = Algorithms.getDominatorTree(revFlowGraph); //then System.out.println(domTree); assert1pointsTo2("a", Graph.START, domTree); assert1pointsTo2("d", "a", domTree); assert1pointsTo2("d", "b", domTree); assert1pointsTo2("d", "c", domTree); assert1pointsTo2("e", "d", domTree); assert1pointsTo2("f", "e", domTree); assert1pointsTo2(Graph.END, "f", domTree); } } package com.jyl.system.user.dao; import java.util.List; import com.jyl.system.user.model.User; public interface UserMapper { User selectByPrimaryKey(Long id); User selectByUsername(String username); List selectAllUser(); int deleteByPrimaryKey(Long id); int insert(User record); int insertSelective(User record); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); int modifyPassword(User record); }moutainhigh/ses-server0 package com.redescooter.ses.mobile.rps.dao.base; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.redescooter.ses.mobile.rps.dm.OpeWmsCombinStock; import java.util.List; import org.apache.ibatis.annotations.Param; /** * @author assert * @date 2021/2/2 17:13 */ public interface OpeWmsCombinStockMapper extends BaseMapper { int updateBatch(List list); int updateBatchSelective(List list); int batchInsert(@Param("list") List list); int insertOrUpdate(OpeWmsCombinStock record); int insertOrUpdateSelective(OpeWmsCombinStock record); }AndroidDebugShell/src/com/isecpartners/android/jdwp/pluginservice/JythonPluginServiceFactory.java1-10 package com.isecpartners.android.jdwp.pluginservice; import java.io.File; import java.io.IOException; public class JythonPluginServiceFactory { public static PluginService createPluginService(String pluginsPath) throws IOException { File path = new File(pluginsPath); ClasspathUtils.addDirToClasspath(path); return JythonPluginService.getInstance(path); } }consulo/consulo-python /* * Copyright 2000-2014 JetBrains s.r.o. * * 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.jetbrains.python.console; import java.awt.Font; import javax.annotation.Nonnull; import com.intellij.codeInsight.hint.HintManager; import com.intellij.execution.console.LanguageConsoleView; import com.intellij.execution.console.ProcessBackedConsoleExecuteActionHandler; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.RangeMarker; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.python.PythonFileType; import com.jetbrains.python.console.pydev.ConsoleCommunication; import com.jetbrains.python.console.pydev.ConsoleCommunicationListener; import com.jetbrains.python.psi.LanguageLevel; import com.jetbrains.python.psi.PyElementGenerator; import com.jetbrains.python.psi.PyFile; import com.jetbrains.python.psi.PyStatementList; /** * @author traff */ public class PydevConsoleExecuteActionHandler extends ProcessBackedConsoleExecuteActionHandler implements ConsoleCommunicationListener { private final LanguageConsoleView myConsoleView; private final ConsoleCommunication consoleCommunication; private PyConsoleEnterHandler myEnterHandler = new PyConsoleEnterHandler(); private boolean myEnabled = false; private int myIpythonInputPromptCount = 0; public PydevConsoleExecuteActionHandler(LanguageConsoleView consoleView, ProcessHandler processHandler, ConsoleCommunication consoleCommunication) { super(processHandler, false); myConsoleView = consoleView; this.consoleCommunication = consoleCommunication; this.consoleCommunication.addCommunicationListener(this); } public boolean isIpythonEnabled() { return PyConsoleUtil.getOrCreateIPythonData(myConsoleView.getVirtualFile()).isIPythonEnabled(); } @Override public void processLine(@Nonnull final String text) { executeMultiLine(text); } private void executeMultiLine(String text) { String commandText = !StringUtil.endsWithChar(text, '\n') ? text + "\n" : text; sendLineToConsole(new ConsoleCommunication.ConsoleCodeFragment(commandText, checkSingleLine(text))); } private boolean checkSingleLine(String text) { PyFile pyFile = (PyFile) PyElementGenerator.getInstance(getProject()).createDummyFile(myConsoleView.getVirtualFile().getUserData(LanguageLevel.KEY), text); return PsiTreeUtil.findChildOfAnyType(pyFile, PyStatementList.class) == null && pyFile.getStatements().size() < 2; } private void sendLineToConsole(@Nonnull final ConsoleCommunication.ConsoleCodeFragment code) { ConsoleCommunication consoleComm = this.consoleCommunication; if(!consoleCommunication.isWaitingForInput()) { executingPrompt(); } if(isIpythonEnabled() && !consoleComm.isWaitingForInput() && code.getText().length() != 0) { ++myIpythonInputPromptCount; } consoleComm.execInterpreter(code, interpreterResponse -> null); } public void inputReceived() { if(consoleCommunication instanceof PythonDebugConsoleCommunication) { if(consoleCommunication.isWaitingForInput()) { ((PythonDebugConsoleCommunication) consoleCommunication).waitingForInput = false; LanguageConsoleView console = myConsoleView; if(PyConsoleUtil.INPUT_PROMPT.equals(console.getPrompt()) || PyConsoleUtil.HELP_PROMPT.equals(console.getPrompt())) { console.setPrompt(PyConsoleUtil.ORDINARY_PROMPT); } } } } private void inPrompt() { if(ipythonEnabled()) { ipythonInPrompt(); } else { ordinaryPrompt(); } } private void ordinaryPrompt() { if(!PyConsoleUtil.ORDINARY_PROMPT.equals(myConsoleView.getPrompt())) { myConsoleView.setPrompt(PyConsoleUtil.ORDINARY_PROMPT); PyConsoleUtil.scrollDown(myConsoleView.getCurrentEditor()); } } private boolean ipythonEnabled() { return PyConsoleUtil.getOrCreateIPythonData(myConsoleView.getVirtualFile()).isIPythonEnabled(); } private void ipythonInPrompt() { myConsoleView.setPromptAttributes(new ConsoleViewContentType("", ConsoleViewContentType.USER_INPUT_KEY) { @Override public TextAttributes getAttributes() { TextAttributes attrs = super.getAttributes(); attrs.setFontType(Font.PLAIN); return attrs; } }); myConsoleView.setPrompt("In[" + myIpythonInputPromptCount + "]:"); PyConsoleUtil.scrollDown(myConsoleView.getCurrentEditor()); } private void executingPrompt() { myConsoleView.setPrompt(PyConsoleUtil.EXECUTING_PROMPT); } private void more() { if(!PyConsoleUtil.INDENT_PROMPT.equals(myConsoleView.getPrompt())) { myConsoleView.setPrompt(PyConsoleUtil.INDENT_PROMPT); PyConsoleUtil.scrollDown(myConsoleView.getCurrentEditor()); } } public static String getPrevCommandRunningMessage() { return "Previous command is still running. Please wait or press Ctrl+C in console to interrupt."; } @Override public void commandExecuted(boolean more) { if(!more && !ipythonEnabled() && !consoleCommunication.isWaitingForInput()) { ordinaryPrompt(); } } @Override public void inputRequested() { updateConsoleState(); } public int getPythonIndent() { return CodeStyleSettingsManager.getSettings(getProject()).getIndentSize(PythonFileType.INSTANCE); } private Project getProject() { return myConsoleView.getProject(); } public String getCantExecuteMessage() { if(!isEnabled()) { return getConsoleIsNotEnabledMessage(); } else if(!canExecuteNow()) { return getPrevCommandRunningMessage(); } else { return "Can't execute the command"; } } @Override public void runExecuteAction(@Nonnull LanguageConsoleView console) { if(isEnabled()) { if(!canExecuteNow()) { HintManager.getInstance().showErrorHint(console.getConsoleEditor(), getPrevCommandRunningMessage()); } else { doRunExecuteAction(console); } } else { HintManager.getInstance().showErrorHint(console.getConsoleEditor(), getConsoleIsNotEnabledMessage()); } } private void doRunExecuteAction(LanguageConsoleView console) { Document doc = myConsoleView.getEditorDocument(); RangeMarker endMarker = doc.createRangeMarker(doc.getTextLength(), doc.getTextLength()); endMarker.setGreedyToLeft(false); endMarker.setGreedyToRight(true); boolean isComplete = myEnterHandler.handleEnterPressed(console.getConsoleEditor()); if(isComplete || consoleCommunication.isWaitingForInput()) { if(endMarker.getEndOffset() - endMarker.getStartOffset() > 0) { ApplicationManager.getApplication().runWriteAction(() -> { CommandProcessor.getInstance().runUndoTransparentAction(() -> { doc.deleteString(endMarker.getStartOffset(), endMarker.getEndOffset()); }); }); } if(shouldCopyToHistory(console)) { copyToHistoryAndExecute(console); } else { processLine(myConsoleView.getConsoleEditor().getDocument().getText()); } } } private void copyToHistoryAndExecute(LanguageConsoleView console) { super.runExecuteAction(console); } private static boolean shouldCopyToHistory(@Nonnull LanguageConsoleView console) { return !PyConsoleUtil.isPagingPrompt(console.getPrompt()); } public boolean canExecuteNow() { return !consoleCommunication.isExecuting() || consoleCommunication.isWaitingForInput(); } protected String getConsoleIsNotEnabledMessage() { return "Console is not enabled."; } protected void setEnabled(boolean flag) { myEnabled = flag; updateConsoleState(); } private void updateConsoleState() { if(!isEnabled()) { executingPrompt(); } else if(consoleCommunication.isWaitingForInput()) { waitingForInputPrompt(); } else if(canExecuteNow()) { if(consoleCommunication.needsMore()) { more(); } else { inPrompt(); } } else { executingPrompt(); } } private void waitingForInputPrompt() { if(!PyConsoleUtil.INPUT_PROMPT.equals(myConsoleView.getPrompt()) && !PyConsoleUtil.HELP_PROMPT.equals(myConsoleView.getPrompt())) { myConsoleView.setPrompt(PyConsoleUtil.INPUT_PROMPT); PyConsoleUtil.scrollDown(myConsoleView.getCurrentEditor()); } } public boolean isEnabled() { return myEnabled; } public ConsoleCommunication getConsoleCommunication() { return consoleCommunication; } } /******************************************************************************* * Copyright (c) 2000, 2011 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.jdt.internal.ui.wizards.buildpaths.newsourcepage; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Menu; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuCreator; import org.eclipse.jface.viewers.IStructuredSelection; /** * Drop down action for toolbars containing BuildpathModifierActions. * The drop down action manages a list of actions that are displayed when invoking * the drop down. If there is at least one valid action, then the drop down action * itself will also be valid and invoking run will delegate the call to the * first valid action in the list. */ public class ClasspathModifierDropDownAction extends BuildpathModifierAction implements IMenuCreator { /** The menu to be populated with items*/ private Menu fMenu; private List fActions; //The action to execute on run iff enabled private BuildpathModifierAction fFirstValidAction; /** * Create a drop down action using the same descriptors as the provided action, but it's on * tool tip text. The action will automatically be put in the list of actions that are * managed by this drop down menu. */ public ClasspathModifierDropDownAction() { super(null, null, BuildpathModifierAction.DROP_DOWN_ACTION, IAction.AS_DROP_DOWN_MENU); fActions = new ArrayList(); fFirstValidAction = null; //$NON-NLS-1$ setText(""); //$NON-NLS-1$ setToolTipText(""); } @Override public String getDetailedDescription() { if (fFirstValidAction != null) { return fFirstValidAction.getDetailedDescription(); } else if (fActions.size() > 0) { return fActions.get(0).getDetailedDescription(); } else { //$NON-NLS-1$ return ""; } } /** * Runs the first action of the list of managed actions that is valid. */ @Override public void run() { fFirstValidAction.run(); } @Override public IMenuCreator getMenuCreator() { return this; } @Override public Menu getMenu(Control parent) { if (fMenu != null) { fMenu.dispose(); } fMenu = new Menu(parent); createEntries(fMenu); return fMenu; } @Override public Menu getMenu(Menu parent) { return fMenu; } /** * Add dynamically an action to the drop down menu. * * @param action the action to be added */ public void addAction(BuildpathModifierAction action) { fActions.add(action); update(); } /** * Remove an action from the drop down menu * * @param action the action to be removed */ public void removeAction(BuildpathModifierAction action) { fActions.remove(action); update(); } /** * Populate the menu with the given action item * * @param parent the menu to add an action for * @param action the action to be added */ private void addActionToMenu(Menu parent, IAction action) { ActionContributionItem item = new ActionContributionItem(action); item.fill(parent, -1); } /** * Fill the menu with all actions * * @param menu the menu to be populated */ private void createEntries(Menu menu) { for (int i = 0; i < fActions.size(); i++) { IAction action = fActions.get(i); addActionToMenu(menu, action); } } @Override public void dispose() { if (fMenu != null) { fMenu.dispose(); fMenu = null; } } @Override protected boolean canHandle(IStructuredSelection elements) { update(); return fFirstValidAction != null; } private void update() { for (Iterator iterator = fActions.iterator(); iterator.hasNext(); ) { BuildpathModifierAction action = iterator.next(); if (action.isEnabled()) { if (action != fFirstValidAction) { updateButton(action); } fFirstValidAction = action; return; } } if (fFirstValidAction != null) { if (fActions.size() > 0) { updateButton(fActions.get(0)); } else { updateButton(this); } } fFirstValidAction = null; } private void updateButton(BuildpathModifierAction action) { setImageDescriptor(action.getImageDescriptor()); setDisabledImageDescriptor(action.getDisabledImageDescriptor()); setText(action.getText()); setToolTipText(action.getToolTipText()); } } /******************************************************************************* * Open Behavioral Health Information Technology Architecture (OBHITA.org) * * 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 the 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 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 gov.samhsa.consent2share.c32.dto; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; // TODO: Auto-generated Javadoc /** *

Java class for anonymous complex type. * *

The following schema fragment specifies the expected content contained within this class. * *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="encounterID" type="{urn:hl7-org:v3}ii" maxOccurs="unbounded"/>
 *         <element name="encounterType" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <extension base="{urn:hl7-org:v3}cd">
 *               </extension>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *         <element name="encounterDateTime" type="{urn:hl7-org:v3}ivlTs"/>
 *         <element name="dischargeDisposition" type="{http://www.w3.org/2001/XMLSchema}anyType" minOccurs="0"/>
 *         <element name="admissionType" type="{urn:hl7-org:v3}cd" minOccurs="0"/>
 *         <element name="encounterProvider" type="{urn:hl7-org:v3}providerInformation" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="facilityLocation" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="locationDuration" type="{urn:hl7-org:v3}ivlTs"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *         <element name="reasonForVisit" minOccurs="0">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="text" type="{urn:hl7-org:v3}textType" minOccurs="0"/>
 *                   <element name="reason" type="{urn:hl7-org:v3}cd"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * 
* * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "encounterID", "encounterType", "encounterDateTime", "dischargeDisposition", "admissionType", "encounterProvider", "facilityLocation", "reasonForVisit" }) public class Encounter { /** The encounter id. */ @XmlElement(required = true) protected List encounterID; /** The encounter type. */ protected EncounterType encounterType; /** The encounter date time. */ @XmlElement(required = true) protected IvlTs encounterDateTime; /** The discharge disposition. */ protected String dischargeDisposition; /** The admission type. */ protected Cd admissionType; /** The encounter provider. */ protected List encounterProvider; /** The facility location. */ protected FacilityLocation facilityLocation; /** The reason for visit. */ protected ReasonForVisit reasonForVisit; /** * Gets the value of the encounterID property. * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the encounterID property. * *

* For example, to add a new item, do as follows: *

     * getEncounterID().add(newItem);
     * 
* * *

* Objects of the following type(s) are allowed in the list * * @return the encounter id * {@link Ii } */ public List getEncounterID() { if (encounterID == null) { encounterID = new ArrayList(); } return this.encounterID; } /** * Gets the value of the encounterType property. * * @return the encounter type * possible object is * {@link EncounterType } */ public EncounterType getEncounterType() { return encounterType; } /** * Sets the value of the encounterType property. * * @param value * allowed object is * {@link EncounterType } * */ public void setEncounterType(EncounterType value) { this.encounterType = value; } /** * Gets the value of the encounterDateTime property. * * @return the encounter date time * possible object is * {@link IvlTs } */ public IvlTs getEncounterDateTime() { return encounterDateTime; } /** * Sets the value of the encounterDateTime property. * * @param value * allowed object is * {@link IvlTs } * */ public void setEncounterDateTime(IvlTs value) { this.encounterDateTime = value; } /** * Gets the value of the dischargeDisposition property. * * @return the discharge disposition * possible object is * {@link String } */ public String getDischargeDisposition() { return dischargeDisposition; } /** * Sets the value of the dischargeDisposition property. * * @param value * allowed object is * {@link String } * */ public void setDischargeDisposition(String value) { this.dischargeDisposition = value; } /** * Gets the value of the admissionType property. * * @return the admission type * possible object is * {@link Cd } */ public Cd getAdmissionType() { return admissionType; } /** * Sets the value of the admissionType property. * * @param value * allowed object is * {@link Cd } * */ public void setAdmissionType(Cd value) { this.admissionType = value; } /** * Gets the value of the encounterProvider property. * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the encounterProvider property. * *

* For example, to add a new item, do as follows: *

     * getEncounterProvider().add(newItem);
     * 
* * *

* Objects of the following type(s) are allowed in the list * * @return the encounter provider * {@link ProviderInformation } */ public List getEncounterProvider() { if (encounterProvider == null) { encounterProvider = new ArrayList(); } return this.encounterProvider; } /** * Gets the value of the facilityLocation property. * * @return the facility location * possible object is * {@link FacilityLocation } */ public FacilityLocation getFacilityLocation() { return facilityLocation; } /** * Sets the value of the facilityLocation property. * * @param value * allowed object is * {@link FacilityLocation } * */ public void setFacilityLocation(FacilityLocation value) { this.facilityLocation = value; } /** * Gets the value of the reasonForVisit property. * * @return the reason for visit * possible object is * {@link ReasonForVisit } */ public ReasonForVisit getReasonForVisit() { return reasonForVisit; } /** * Sets the value of the reasonForVisit property. * * @param value * allowed object is * {@link ReasonForVisit } * */ public void setReasonForVisit(ReasonForVisit value) { this.reasonForVisit = value; } } r331/lombok1-10 // version 9: the 'this' param option exists in java8, but is bugged, in that annotations are not allowed on them, even without a @Target. The only purpose of the this param is annotations, so, boy, isn't that a punch in the face? import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; class ThisParameter { void untagged(ThisParameter this, int i) { // no content } void sourceTagged(@SourceTagged("source") ThisParameter this) { // no content } void classTagged(@ClassTagged("class") ThisParameter this) { // no content } void runtimeTagged(@RuntimeTagged("runtime") ThisParameter this) { // no content } @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.SOURCE) @interface SourceTagged { String value(); } @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.CLASS) @interface ClassTagged { String value(); } @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.RUNTIME) @interface RuntimeTagged { String value(); } } package org.sharebook.repository; /** * 增删改查通用接口 * @param 操作的实体的类型 * @param 实体主键的类型 */ public interface CurdRepository { /** * 根据主键查找实体 * @param id 主键 * @return 查找的实体 */ T findById(ID id); /** * 保存实体 * @param t 实体 * @return 影响的行数 */ int save(T t); /** * 更新实体 * * @param t 实体 * @return 影响的行数 */ int update(T t); /** * 删除实体 * @param id 主键 * */ int delete(ID id); } /* Copyright 2016 and . 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 ch.zhaw.facerecognitionlibrary.PreProcessor.StandardPreprocessing; import org.opencv.core.Mat; import org.opencv.core.MatOfFloat; import org.opencv.core.Point; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import java.util.ArrayList; import java.util.List; import ch.zhaw.facerecognitionlibrary.Helpers.Eyes; import ch.zhaw.facerecognitionlibrary.PreProcessor.Command; import ch.zhaw.facerecognitionlibrary.PreProcessor.PreProcessor; public class EyeAlignment implements Command { private static final double DESIRED_RIGHT_EYE_X = 0.24; private static final double DESIRED_RIGHT_EYE_Y = 0.30; private static final double DESIRED_LEFT_EYE_X = (1.0 - DESIRED_RIGHT_EYE_X); public PreProcessor preprocessImage(PreProcessor preProcessor) { List images = preProcessor.getImages(); List processed = new ArrayList(); Eyes[] eyes = preProcessor.setEyes(); if (eyes == null || eyes[0] == null){ return null; } for (int i=0; i0 package com.edination.api.PDGM.dao; import com.edination.api.PDGM.model.EpisodeDetail; import com.edination.api.PDGM.model.TimingAndSourceOfAdmission; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface EpisodeDetailRepository extends JpaRepository { @Query(value="FROM EpisodeDetail WHERE mrn_number = ?1") public List findEpisodeByMrn(String mrnNumber); } meraihan/gemini package it.at7.gemini.conf; public enum State implements Comparable { STARTING, STARTED, GEMINI_MODULES_LOADED, SCHEMA_STORAGE_INITIALIZED, SCHEMA_EVENTS_LOADED, FRAMEWORK_SCHEMA_RECORDS_INITIALIZED, PROVIDED_CLASSPATH_RECORDS_HANDLED, INITIALIZED, API_INITIALIZATION, API_INITIALIZED, GUI_INITIALIZATION, GUI_INITIALIZED } butterknife-compiler/src/main/java/com/fasten/butterknife/compiler/BindViewAnnotationProcessor.java package com.fasten.butterknife.compiler; import com.fasten.butterknife.annotations.BindView; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import java.util.Collections; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; /** * 作者:created by storm on 2019-12-09 */ public class BindViewAnnotationProcessor extends AbstractProcessor { private ElementHelper mHelper; private final static String SEPARATE_SYMBOL = "_ViewBinding"; @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.RELEASE_7; } @Override public Set getSupportedAnnotationTypes() { return Collections.singleton(BindView.class.getCanonicalName()); } @Override public synchronized void init(ProcessingEnvironment processingEnvironment) { super.init(processingEnvironment); mHelper = ElementHelper.getInstance(processingEnvironment.getElementUtils(), processingEnvironment.getMessager(),processingEnvironment.getTypeUtils()); } @Override public boolean process(Set set, RoundEnvironment roundEnvironment) { for (Element element : roundEnvironment.getElementsAnnotatedWith(BindView.class)) { parseBindView(element); } return false; } private void parseBindView(Element element){ if (element instanceof VariableElement) { VariableElement variableElement = (VariableElement) element; //对variableElement进行校验 if(!mHelper.isValidVariableElement(variableElement)){ return; } if (variableElement.getAnnotation(BindView.class) != null) { BindView bindViewAnnotation = variableElement.getAnnotation(BindView.class); int idValue = bindViewAnnotation.value(); Element enclosingElement = variableElement.getEnclosingElement(); if(enclosingElement instanceof TypeElement){ TypeElement typeElement=(TypeElement)enclosingElement; String packageName=mHelper.getPackageName(typeElement); ClassName generateClassName=ClassName.get(packageName,generateClassName(typeElement)); ClassName bindInterfaceClassName=ClassName.get("com.fasten.butterknife.api","IBind"); TypeSpec.Builder tsb=TypeSpec.classBuilder(generateClassName) .addJavadoc("Represent the class $T of {@link $T}\n",generateClassName,ClassName.get(typeElement)) .addModifiers(Modifier.PUBLIC) .addSuperinterface(bindInterfaceClassName); ClassName overrideClassName=ClassName.get("java.lang","Override"); MethodSpec.Builder msb=MethodSpec.methodBuilder("bind") .addAnnotation(overrideClassName) .addModifiers(Modifier.PUBLIC) .addParameter(Object.class,"target") .beginControlFlow("if(target instanceof $T)",ClassName.get(typeElement)) .addStatement("$T instance=($T)target",ClassName.get(typeElement),ClassName.get(typeElement)) .addStatement("instance.$L=instance.findViewById($L)",variableElement.getSimpleName(),idValue) .endControlFlow() .returns(void.class); tsb.addMethod(msb.build()); try { JavaFile.builder(packageName,tsb.build()) .skipJavaLangImports(true) .addFileComment("generate file,DO NOT MODIFY!") .build().writeTo(processingEnv.getFiler()); }catch (Exception e){ e.printStackTrace(); } } } } } private String generateClassName(TypeElement typeElement){ String sourceName=typeElement.getSimpleName().toString(); StringBuilder builder=new StringBuilder(sourceName); return builder.append(SEPARATE_SYMBOL).toString(); } } Alexkill536ITA/ChatRoom_py_androidChatRoom/app/src/main/java/com/alexkill536/chatroom/Activity_login.java package com.alexkill536.chatroom; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import android.widget.Toolbar; import com.google.android.material.textfield.TextInputLayout; public class Activity_login extends AppCompatActivity { EditText nick, pass; DataBaseHandler mydb_profile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); mydb_profile = new DataBaseHandler(this); final GlogalVariable globalVariable = (GlogalVariable) getApplicationContext(); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setTitle("ChatRoom Login"); toolbar.setSubtitle("By Alexkill536ITA"); Drawable logo = getResources().getDrawable(R.drawable.logo, null); Bitmap tmpBitmap = ((BitmapDrawable)logo).getBitmap(); tmpBitmap = Bitmap.createScaledBitmap(tmpBitmap, 50, 50, false); toolbar.setLogo(new BitmapDrawable(getResources(), tmpBitmap)); nick = (EditText)findViewById(R.id.intText_nick); pass = (EditText)findViewById(R.id.intText_pws); nick.addTextChangedListener(fill_text); pass.addTextChangedListener(fill_text); Button btn_cancell = (Button)findViewById(R.id.button_cancel); btn_cancell.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); Button btn_regestry = (Button)findViewById(R.id.button_regestry); btn_regestry.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { launch_regestry(); } }); Button btn_submit = (Button)findViewById(R.id.button_Login); btn_submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (nick.getText().toString().length() > 0 && pass.getText().toString().length() > 0) { Cursor valore = mydb_profile.ottieniCliente(nick.getText().toString(), pass.getText().toString()); if (valore != null && valore.getCount() > 0) { String valore_id = valore.getString(valore.getColumnIndex("id")); String valore_nick = valore.getString(valore.getColumnIndex("nickname")); globalVariable.set_val_id_user(valore_id); globalVariable.set_val_nick_user(valore_nick); Intent intent = new Intent(Activity_login.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } else { Toast.makeText(Activity_login.this, "Login Fallito", Toast.LENGTH_SHORT).show(); pass.setText(""); } } } }); setupFloatingLabelError(); } private void launch_regestry() { Intent intent = new Intent(this, Activity_Registry_profile.class); startActivity(intent); } private void setupFloatingLabelError() { final TextInputLayout floatingUsernameLabel = (TextInputLayout) findViewById(R.id.intText_nick_layout); floatingUsernameLabel.getEditText().addTextChangedListener(new TextWatcher() { // ... @Override public void onTextChanged(CharSequence text, int start, int count, int after) { if (text.length() == 0) { floatingUsernameLabel.setError(" Inserire Nick"); floatingUsernameLabel.setErrorEnabled(true); } else { floatingUsernameLabel.setErrorEnabled(false); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { } }); final TextInputLayout floatingPasswordLabel = (TextInputLayout) findViewById(R.id.intText_pws_layout); floatingPasswordLabel.getEditText().addTextChangedListener(new TextWatcher() { // ... @Override public void onTextChanged(CharSequence text, int start, int count, int after) { if (text.length() == 0) { floatingPasswordLabel.setError(" Inserire Password"); floatingPasswordLabel.setErrorEnabled(true); } else { floatingPasswordLabel.setErrorEnabled(false); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { } }); } private TextWatcher fill_text = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { setupFloatingLabelError(); } @Override public void afterTextChanged(Editable s) { } }; @Override public void onBackPressed() { super.onBackPressed(); return; } private void setSupportActionBar(Toolbar toolbar) { } } package com.magic.bitcask.entity; import java.nio.ByteBuffer; public class BitCaskRecord { private int crc; private long version; private long expire; // 过期时间 private short keySize; private int valueSize; private String key; private String value; // 这个是转化后的buffer private ByteBuffer[] buffers; public BitCaskRecord(int crc, long version, long expire, short keySize, int valueSize, String key, String value, ByteBuffer[] buffers) { this.crc = crc; this.version = version; this.expire = expire; this.keySize = keySize; this.valueSize = valueSize; this.key = key; this.value = value; this.buffers = buffers; } public int getCrc() { return crc; } public void setCrc(int crc) { this.crc = crc; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } public short getKeySize() { return keySize; } public void setKeySize(short keySize) { this.keySize = keySize; } public int getValueSize() { return valueSize; } public void setValueSize(int valueSize) { this.valueSize = valueSize; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public ByteBuffer[] getBuffers() { return buffers; } public void setBuffers(ByteBuffer[] buffers) { this.buffers = buffers; } public long getExpire() { return expire; } public void setExpire(long expire) { this.expire = expire; } } import java.util.StringTokenizer; import org.apache.commons.math4.geometry.euclidean.threed.Cartesian3D; import org.apache.commons.math4.geometry.spherical.twod.Circle; import org.apache.commons.math4.geometry.spherical.twod.SphericalPolygonsSet; class RegionParser { /** Parse a string representation of a {@link SphericalPolygonsSet}. * @param s string to parse * @return parsed region * @exception IOException if the string cannot be read * @exception ParseException if the string cannot be parsed */ public static SphericalPolygonsSet parseSphericalPolygonsSet(final String s) throws IOException, ParseException { final TreeBuilder<Sphere2D> builder = new TreeBuilder<Sphere2D>("SphericalPolygonsSet", s) { /** {@inheritDoc} */ @Override public Circle parseHyperplane() throws IOException, ParseException { return new Circle(new Cartesian3D(getNumber(), getNumber(), getNumber()), getNumber()); } }; return new SphericalPolygonsSet(builder.getTree(), builder.getTolerance()); } abstract class TreeBuilder<S> { /** Get next number. * @return parsed number * @exception IOException if the string cannot be read * @exception NumberFormatException if the string cannot be parsed */ protected double getNumber() throws IOException, NumberFormatException { return Double.parseDouble(tokenizer.nextToken()); } /** Get the built tree. * @return built tree */ public BSPTree<S> getTree() { return root; } /** Get the tolerance. * @return tolerance */ public double getTolerance() { return tolerance; } } } package com.github.edgar615.gateway.metric; import com.github.edgar615.gateway.core.metric.ApiMetric; import org.junit.Test; import java.util.UUID; /** * Created by Edgar on 2017/4/1. * * @author Edgar Date 2017/4/1 */ public class ApiMetricTest { @Test public void testRequest() { String id = UUID.randomUUID().toString(); String api = "test_api"; ApiMetric.request(id, api); ApiMetric.response(id, api, 200, 1); } } package by.bsuir.mpp.computershop.controller; import by.bsuir.mpp.computershop.controller.exception.ControllerException; import by.bsuir.mpp.computershop.dto.brief.BaseBriefDto; import by.bsuir.mpp.computershop.dto.full.BaseFullDto; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import javax.validation.Valid; import java.io.Serializable; public interface CrudController, F extends BaseFullDto, ID extends Serializable> extends ReadController { @RequestMapping(path = "add", method = RequestMethod.POST) F add(@Valid @RequestBody F dto) throws ControllerException; @RequestMapping(path = "update/{id}", method = RequestMethod.PUT) F update(@PathVariable ID id, @Valid @RequestBody F entity) throws ControllerException; @RequestMapping(path = "delete/{id}", method = RequestMethod.DELETE) void delete(@PathVariable ID id) throws ControllerException; } MigrationMiner/src/main/java/com/database/mysql/MigrationSegmentsDB.java package com.database.mysql; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import com.library.source.MigratedLibraries; import com.project.settings.DatabaseLogin; import com.segments.build.Segment; /* * CREATE TABLE MigrationSegments ( MigrationRuleID INTEGER, AppID INTEGER, CommitID varchar(200), FromCode TEXT, ToCode TEXT ); */ public class MigrationSegmentsDB { public static void main(String[] args) { HashMap map = new HashMap(); LinkedList migrationRules = new MigrationRuleDB().getMigrationRulesWithoutVersion(0); for (MigrationRule migrationRule : migrationRules) { System.out .println(migrationRule.ID + ":" + migrationRule.FromLibrary + "\t<==>\t" + migrationRule.ToLibrary); ArrayList segmentList = new MigrationSegmentsDB().getSegmentsObj(migrationRule.ID); System.out.println("#Segments: " + segmentList.size()); for (Segment segment : segmentList) { // segment.print(); int size = Math.round(segment.getTotalLinesNumbers() * 1.0f / 2.0f); String key = migrationRule.FromLibrary + "|" + migrationRule.ToLibrary + ":" + size; if (map.get(key) == null) { map.put(key, 1); } else { map.put(key, map.get(key) + 1); } // System.out.println(key+"-->"+map.get(key)); } } for (MigrationRule migrationRule : migrationRules) { String info = migrationRule.FromLibrary + "|" + migrationRule.ToLibrary; int zeroto2 = 0; int three = 0; int foureto6 = 0; int sevento10 = 0; int big = 0; for (String key : map.keySet()) { if (key.contains(info)) { String[] sp = key.split(":"); int sSize = Integer.valueOf(sp[1]); if (sSize >= 0 && sSize <= 2) zeroto2 = zeroto2 + map.get(key); else if (sSize == 3) three = three + map.get(key); else if (sSize >= 4 && sSize <= 6) foureto6 = foureto6 + map.get(key); else if (sSize >= 7 && sSize <= 10) sevento10 = sevento10 + map.get(key); else if (sSize > 10) big = big + map.get(key); } } System.out.println(migrationRule.FromLibrary + "-\\textgreater " + migrationRule.ToLibrary + " & " + +zeroto2 + " & " + three + " & " + foureto6 + " & " + sevento10 + " & " + big + "\\\\"); System.out.println("\\hline"); } // MigratedLibraries.ID=7; // This shared with safe method // TestClient testClient= new TestClient(); // testClient.runAlgorithm( segmentList); // SubstitutionAlgorithm substitutionAlgorithm = new // SubstitutionAlgorithm(segmentList,10); // substitutionAlgorithm.start(); System.out.println("done"); } // get segments as obj from database public ArrayList getSegmentsObj(int migrationRuleID) { ArrayList segmentList = new ArrayList(); // read from database int blockID = 1; LinkedList listOfSegmnets = new MigrationSegmentsDB().getMigrationSegments(migrationRuleID); for (MigrationSegments migrationSegments : listOfSegmnets) { Segment segment = new Segment(); segment.AppID = migrationSegments.AppID; segment.CommitID = migrationSegments.CommitID; String[] linesRemoved = migrationSegments.FromCode.split(System.getProperty("line.separator")); segment.blockCode.add(String.valueOf(blockID++)); for (String line : linesRemoved) { segment.removedCode.add(line); segment.blockCode.add("< " + line); } segment.blockCode.add("----------"); String[] linesAdded = migrationSegments.ToCode.split(System.getProperty("line.separator")); for (String line : linesAdded) { segment.addedCode.add(line); segment.blockCode.add("> " + line); } segmentList.add(segment); } return segmentList; } public void add(int MigrationRuleID, int AppID, String CommitID, Segment segment, String fromLibVersion, String toLibVersion) { // Statement stmt = null; try { Connection c = null; Class.forName("com.mysql.cj.jdbc.Driver"); c = DriverManager.getConnection(DatabaseLogin.url, DatabaseLogin.username, DatabaseLogin.password); c.setAutoCommit(false); // stmt = c.createStatement(); String sql = "INSERT INTO MigrationSegments (MigrationRuleID,AppID,CommitID,FromCode,ToCode,fileName,fromLibVersion,toLibVersion) VALUES (?,?,?,?,?,?,?,?);"; PreparedStatement stmt = c.prepareStatement(sql); stmt.setInt(1, MigrationRuleID); stmt.setInt(2, AppID); stmt.setString(3, CommitID); stmt.setString(4, arrayListToString(segment.removedCode)); stmt.setString(5, arrayListToString(segment.addedCode)); stmt.setString(6, segment.fileName); stmt.setString(7, fromLibVersion); stmt.setString(8, toLibVersion); stmt.executeUpdate(); // stmt.executeUpdate(sql); stmt.close(); c.commit(); c.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } System.out.println("Records created successfully"); } public static String arrayListToString(ArrayList listOfCode) { StringBuilder textCode = new StringBuilder(); for (String lineCode : listOfCode) textCode.append(lineCode).append('\n'); return textCode.toString(); } // Return only unique pair of added removed libraries public LinkedList getAllMigrationSegmentsLibraries() { LinkedList listOfSegmnets = new LinkedList(); Statement stmt = null; try { Connection c = null; Class.forName("com.mysql.cj.jdbc.Driver"); c = DriverManager.getConnection(DatabaseLogin.url, DatabaseLogin.username, DatabaseLogin.password); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt.executeQuery( "select fromLibVersion,toLibVersion from MigrationSegments group by fromLibVersion,toLibVersion"); while (rs.next()) { listOfSegmnets.add(new MigrationSegments(0, null, null, null, null, rs.getString("fromLibVersion"), rs.getString("toLibVersion"))); } rs.close(); stmt.close(); c.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } return listOfSegmnets; } // This function return list of migration rules for database public LinkedList getMigrationSegments(int migrationRuleID) { LinkedList listOfSegmnets = new LinkedList(); Statement stmt = null; try { Connection c = null; Class.forName("com.mysql.cj.jdbc.Driver"); c = DriverManager.getConnection(DatabaseLogin.url, DatabaseLogin.username, DatabaseLogin.password); c.setAutoCommit(false); stmt = c.createStatement(); ResultSet rs = stmt .executeQuery("select * from MigrationSegments WHERE MigrationRuleID=" + migrationRuleID); while (rs.next()) { listOfSegmnets.add(new MigrationSegments(rs.getInt("AppID"), rs.getString("CommitID"), rs.getString("FromCode"), rs.getString("ToCode"), rs.getString("fileName"), rs.getString("fromLibVersion"), rs.getString("toLibVersion"))); } rs.close(); stmt.close(); c.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } return listOfSegmnets; } // Return only unique pair of added removed libraries public MigrationSegments getLibrariesForGivenMethods(String MigrationRuleID, String searchFor) { MigrationSegments migrationSegments = new MigrationSegments(); Statement stmt = null; try { Connection c = null; Class.forName("com.mysql.cj.jdbc.Driver"); c = DriverManager.getConnection(DatabaseLogin.url, DatabaseLogin.username, DatabaseLogin.password); c.setAutoCommit(false); stmt = c.createStatement(); // System.out.println("select fromLibVersion,toLibVersion from MigrationSegments // where MigrationRuleID="+ MigrationRuleID+" and " +searchFor +" group by // fromLibVersion,toLibVersion limit 1"); ResultSet rs = stmt .executeQuery("select fromLibVersion,toLibVersion from MigrationSegments where MigrationRuleID=" + MigrationRuleID + " and " + searchFor + " group by fromLibVersion,toLibVersion limit 1"); while (rs.next()) { migrationSegments = new MigrationSegments(0, null, null, null, null, rs.getString("fromLibVersion"), rs.getString("toLibVersion")); break; } rs.close(); stmt.close(); c.close(); } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } return migrationSegments; } } package charlie.nbtweak; import net.minecraft.block.BlockNote; import net.minecraft.client.Minecraft; import net.minecraft.item.ItemNameTag; import net.minecraft.tileentity.TileEntityNote; import net.minecraft.world.World; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.world.BlockEvent; import cpw.mods.fml.common.eventhandler.EventPriority; import cpw.mods.fml.common.eventhandler.SubscribeEvent; public class NoteblockPlaceHandler { @SubscribeEvent public void blockPlaced(BlockEvent.PlaceEvent event){ if(event.block instanceof BlockNote){ TileEntityNote entity = (TileEntityNote) Minecraft.getMinecraft().theWorld.getTileEntity(event.x, event.y, event.z); Minecraft.getMinecraft().displayGuiScreen(new GuiSet(entity, Minecraft.getMinecraft().currentScreen)); } } @SubscribeEvent(priority = EventPriority.HIGH) public void rightClick(PlayerInteractEvent event){ if(event.entityPlayer.getHeldItem() != null && event.entityPlayer.getHeldItem().getItem() instanceof ItemNoteblockFork){ if(Minecraft.getMinecraft().theWorld.getBlock(event.x, event.y, event.z) instanceof BlockNote){ if(!event.entityPlayer.isSneaking()){ event.setCanceled(true); TileEntityNote entity = (TileEntityNote) Minecraft.getMinecraft().theWorld.getTileEntity(event.x, event.y, event.z); Minecraft.getMinecraft().displayGuiScreen(new GuiSet(entity, Minecraft.getMinecraft().currentScreen)); } } } } } //package com.example.jpa.controller; // // //import com.example.jpa.projo.User; //import com.example.jpa.repository.UserRepository; //import com.example.jpa.service.UserServiceImpl; //import com.example.jpa.util.PageUtil; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.data.domain.Page; //import org.springframework.data.domain.Pageable; //import org.springframework.web.bind.annotation.GetMapping; //import org.springframework.web.bind.annotation.PostMapping; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.RequestParam; //import org.springframework.web.bind.annotation.RestController; // //import javax.annotation.Resource; //import java.util.List; // //@RestController //@RequestMapping("/user") //public class UserController { // private final UserServiceImpl userService; // private final UserRepository repository; // // public UserController(UserServiceImpl userService, UserRepository repository) { // this.userService = userService; // this.repository = repository; // } // @GetMapping(value = "/insert") // public void insertValue() { // userService.insertValue(); // } // // //根据编号查询 // @PostMapping(value = "/findById") // User findById(@RequestParam(value = "id") Long id) { // return repository.findById(id).get(); // } // // @PostMapping(value = "findName") // List findName(@RequestParam(value = "name") String name) { // return repository.findByNameLike(name); // } // // @PostMapping(value = "findAll") // //currentPage 当前页,默认为0,如果传1的话是查的第二页数据 // //pageSize 每页数据条数 // Page findAll(@RequestParam(value = "currentPage") int currentPage, // @RequestParam(value = "pageSize") int pageSize) { // Pageable pageable = PageUtil.getPageable(currentPage, pageSize, "datetime"); // return repository.findAll(pageable); // } //} 100-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.jclouds.openstack.nova.v2_0.compute.functions; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.openstack.nova.v2_0.domain.Image; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; /** * Tests for the function for transforming a nova specific Image into a generic * OperatingSystem object. */ public class ImageToOperatingSystemTest { @Test(dataProvider = "getOsFamilyValues") public void testOsFamilyValues(OsFamily family) { Image imageToConvert = Image.builder().id("id-" + family.name()).name(family.name()).build(); ImageToOperatingSystem converter = new ImageToOperatingSystem( new HashMap>()); OperatingSystem convertedOs = converter.apply(imageToConvert); assertEquals(convertedOs.getName(), imageToConvert.getName()); assertEquals(convertedOs.getFamily(), family); assertEquals(convertedOs.getDescription(), imageToConvert.getName()); assertEquals(convertedOs.getVersion(), null); assertEquals(convertedOs.getArch(), null); assertTrue(convertedOs.is64Bit()); } @DataProvider public Object[][] getOsFamilyValues() { return Iterables.toArray( Iterables.transform(Arrays.asList(OsFamily.values()), new Function() { @Override public Object[] apply(OsFamily osFamily) { return new Object[] { osFamily }; } }), Object[].class); } @Test public void testWindowsServer2008R2x64() { String name = "Windows Server 2008 R2 x64"; Image imageToConvert = Image.builder().id("id-" + name).name(name).build(); Map> osFamilyMap = Maps.newHashMap(); osFamilyMap.put(OsFamily.WINDOWS, ImmutableMap.of("Server 2008 R2", "Server-2008-R2")); ImageToOperatingSystem converter = new ImageToOperatingSystem(osFamilyMap); OperatingSystem convertedOs = converter.apply(imageToConvert); assertEquals(convertedOs.getName(), imageToConvert.getName()); assertEquals(convertedOs.getFamily(), OsFamily.WINDOWS); assertEquals(convertedOs.getDescription(), imageToConvert.getName()); assertEquals(convertedOs.getVersion(), "Server-2008-R2"); assertEquals(convertedOs.getArch(), null); assertTrue(convertedOs.is64Bit()); } @Test public void testWindows98x86() { String name = "Windows 98 x86"; Image imageToConvert = Image.builder().id("id-" + name).name(name).build(); Map> osFamilyMap = Maps.newHashMap(); osFamilyMap.put(OsFamily.WINDOWS, ImmutableMap.of("98", "98")); ImageToOperatingSystem converter = new ImageToOperatingSystem(osFamilyMap); OperatingSystem convertedOs = converter.apply(imageToConvert); assertEquals(convertedOs.getName(), imageToConvert.getName()); assertEquals(convertedOs.getFamily(), OsFamily.WINDOWS); assertEquals(convertedOs.getDescription(), imageToConvert.getName()); assertEquals(convertedOs.getVersion(), "98"); assertEquals(convertedOs.getArch(), null); assertFalse(convertedOs.is64Bit()); } @Test public void testRHEL() { String name = "Red Hat EL"; Image imageToConvert = Image.builder().id("id-" + name).name(name).build(); ImageToOperatingSystem converter = new ImageToOperatingSystem( new HashMap>()); OperatingSystem convertedOs = converter.apply(imageToConvert); assertEquals(convertedOs.getName(), imageToConvert.getName()); assertEquals(convertedOs.getFamily(), OsFamily.RHEL); assertEquals(convertedOs.getDescription(), imageToConvert.getName()); assertEquals(convertedOs.getVersion(), null); assertEquals(convertedOs.getArch(), null); assertTrue(convertedOs.is64Bit()); } @Test public void testOEL() { String name = "Oracle EL"; Image imageToConvert = Image.builder().id("id-" + name).name(name).build(); ImageToOperatingSystem converter = new ImageToOperatingSystem( new HashMap>()); OperatingSystem convertedOs = converter.apply(imageToConvert); assertEquals(convertedOs.getName(), imageToConvert.getName()); assertEquals(convertedOs.getFamily(), OsFamily.OEL); assertEquals(convertedOs.getDescription(), imageToConvert.getName()); assertEquals(convertedOs.getVersion(), null); assertEquals(convertedOs.getArch(), null); assertTrue(convertedOs.is64Bit()); } ImageToOperatingSystem converterForUbuntu = new ImageToOperatingSystem(ImmutableMap.> of( OsFamily.UBUNTU, ImmutableMap.of("lucid", "10.04", "maverick", "10.10", "natty", "11.04", "oneiric", "11.10"))); @Test public void testTryStackOneric() { String name = "oneiric-server-cloudimg-amd64"; Image imageToConvert = Image.builder().id("id-" + name).name(name).build(); OperatingSystem convertedOs = converterForUbuntu.apply(imageToConvert); assertEquals(convertedOs.getName(), imageToConvert.getName()); assertEquals(convertedOs.getFamily(), OsFamily.UBUNTU); assertEquals(convertedOs.getDescription(), imageToConvert.getName()); assertEquals(convertedOs.getVersion(), "11.10"); assertEquals(convertedOs.getArch(), null); assertTrue(convertedOs.is64Bit()); } @Test public void testTryStackNatty() { String name = "natty-server-cloudimg-amd64"; Image imageToConvert = Image.builder().id("id-" + name).name(name).build(); OperatingSystem convertedOs = converterForUbuntu.apply(imageToConvert); assertEquals(convertedOs.getName(), imageToConvert.getName()); assertEquals(convertedOs.getFamily(), OsFamily.UBUNTU); assertEquals(convertedOs.getDescription(), imageToConvert.getName()); assertEquals(convertedOs.getVersion(), "11.04"); assertEquals(convertedOs.getArch(), null); assertTrue(convertedOs.is64Bit()); } } package ca.bc.gov.educ.api.edx.repository; import ca.bc.gov.educ.api.edx.model.v1.EdxRoleEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.UUID; @Repository public interface EdxRoleRepository extends JpaRepository { } wolfgarbe/LuceneBench1-10 import org.apache.lucene.analysis.core.SimpleAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; import org.apache.lucene.search.*; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; //import org.apache.lucene.store.MMapDirectory; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.document.TextField; import org.apache.lucene.document.StoredField; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.QueryScorer; import java.nio.file.Paths; public class LuceneCore { // The index object, points to a repository Directory index; // Specify the analyzer for tokenizing text. // The same analyzer should be used for indexing and searching SimpleAnalyzer analyzer; // Writing object, linked to the repository IndexWriter writer = null; SearcherManager searcherManager=null; // Document Document doc; TextField titleField; TextField contentField; TextField domainField; TextField urlField; StoredField dateField; LuceneCore() { // Instantiate the analyzer analyzer = new SimpleAnalyzer(); } /* Open or create the index */ public void openIndex(String directory, boolean newIndex) { try { // Link the directory on the FileSystem to the application //https://lucene.apache.org/core/7_5_0/core/org/apache/lucene/store/FSDirectory.html //NIOFSDirectory or MMapDirectory for Unix, but not Windows //index = MMapDirectory.open(Paths.get(directory)); index = FSDirectory.open(Paths.get(directory)); IndexWriterConfig conf = new IndexWriterConfig(analyzer); //Java command-line: -Xmx8g -Xms8g -server (start menu: configure java) //see https://home.apache.org/~mikemccand/lucenebench/indexing.html conf.setRAMBufferSizeMB(2048); writer = new IndexWriter( index, conf ); searcherManager = new SearcherManager(writer, true,true, null); } catch (Exception e) { System.out.println("Got an Exception: " + e.getMessage()); } } public Long search(String querystr) { Long totalHits=0L; try { // Instantiate a query parser MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[]{"title", "content","domain","url"},analyzer); parser.setDefaultOperator( MultiFieldQueryParser.AND_OPERATOR );//parser.AND_OPERATOR // Parse Query q = parser.parse(querystr); //safely share IndexSearcher instances across multiple threads for NRT search //http://www.lucenetutorial.com/lucene-nrt-hello-world.html //https://lucene.apache.org/core/8_2_0/core/org/apache/lucene/search/SearcherManager.html IndexSearcher searcher = searcherManager.acquire(); // We look for top-10 results int hitsPerPage = 10; int totalHitsTreshold=Integer.MAX_VALUE; // Ranker TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, totalHitsTreshold); // Search searcher.search(q, collector); // Retrieve the top-10 documents TopDocs topDocs=collector.topDocs(); //TopDocs topDocs = searcher.search(q, hitsPerPage); //safely share IndexSearcher instances across multiple threads for NRT search //http://www.lucenetutorial.com/lucene-nrt-hello-world.html //https://lucene.apache.org/core/8_2_0/core/org/apache/lucene/search/SearcherManager.html searcherManager.release(searcher); ScoreDoc[] hits = topDocs.scoreDocs; totalHits=topDocs.totalHits.value; //https://lucene.apache.org/core/8_4_1/highlighter/org/apache/lucene/search/highlight/package-summary.html Highlighter highlighter = new Highlighter(new QueryScorer(q)); // Load results //System.out.println("query: "+querystr + " hits: " + hits.length+" totalHits: "+String.format("%,d",totalHits)); for (int i = 0; i < hits.length; ++i) { int docId = hits[i].doc; Document d = searcher.doc(docId); String title=d.get("title"); String content=d.get("content"); String domain=d.get("domain"); String url=d.get("url"); String date=d.get("date"); String kwic = highlighter.getBestFragment(analyzer, "content", content); /* System.out.println((i + 1) + ". " + title); System.out.println(kwic); System.out.println(url); System.out.println(domain); System.out.println(date); */ } // Close the searcher //searcher.close(); } catch (Exception e) { System.out.println("Got an Exception: " + e.getMessage()); } return totalHits; } public void addDoc(DocObject document) { try { // Instantiate a new document Document doc = new Document(); // Add the field to the document doc.add(new TextField("title", document.title, Field.Store.YES)); doc.add(new TextField("content", document.content, Field.Store.YES)); doc.add(new TextField("domain", document.domain, Field.Store.YES)); doc.add(new TextField("url", document.url, Field.Store.YES)); doc.add(new StoredField("date", document.date)); // And add the document to the index writer.addDocument(doc); //for Near Real Time Search //writer.flush(); //writer.commit(); } catch (Exception e) { System.out.println("Got an Exception: " + e.getMessage()); } } // Close the index public void closeIndex() { try { writer.close(); } catch (Exception e) { System.out.println("Got an Exception: " + e.getMessage()); } } } app/src/main/java/com/codernauti/sweetie/chat/TextMessageVM.java1-10 package com.codernauti.sweetie.chat; import com.codernauti.sweetie.R; import com.codernauti.sweetie.utils.DataMaker; class TextMessageVM extends MessageVM { private String mText; TextMessageVM(String text, String creatorUserUid, boolean mainUser, String date, boolean bookMarked, String key) { super(mainUser, creatorUserUid, date, bookMarked, key); mText = text; } String getText() { return mText; } @Override public void configViewHolder(ChatViewHolder viewHolder) { // TODO: This downcast is secure? TextMessageViewHolder view = (TextMessageViewHolder) viewHolder; view.setText(mText); view.setTextTime(DataMaker.getHH_ss_Local(super.getTime())); view.setBookmark(super.isBookmarked()); } @Override public int getIdView() { if (isTheMainUser()) { return R.layout.chat_user_list_item_text; } else { // isThePartner() return R.layout.chat_partner_list_item_text; } } } src/main/java/picard/util/help/PicardHelpDoclet.java package picard.util.help; import com.sun.javadoc.ClassDoc; import com.sun.javadoc.RootDoc; import org.broadinstitute.barclay.argparser.CommandLineProgramProperties; import org.broadinstitute.barclay.help.DocumentedFeature; import org.broadinstitute.barclay.help.DocWorkUnit; import org.broadinstitute.barclay.help.GSONWorkUnit; import org.broadinstitute.barclay.help.HelpDoclet; import java.io.IOException; import java.util.List; import java.util.Map; /** * Custom Barclay-based Javadoc Doclet used for generating Picard help/documentation. * * NOTE: Methods in this class are intended to be called by Gradle/Javadoc only, and should not be called * by methods that are used by the Picard runtime. This class has a dependency on com.sun.javadoc classes, * which may not be present since they're not provided as part of the normal Picard runtime classpath. */ public class PicardHelpDoclet extends HelpDoclet { private final static String PICARD_FREEMARKER_INDEX_TEMPLATE_NAME = "generic.index.template.html"; /** * Create a doclet of the appropriate type and generate the FreeMarker templates properties. * @param rootDoc * @throws IOException */ public static boolean start(final RootDoc rootDoc) throws IOException { return new picard.util.help.PicardHelpDoclet().startProcessDocs(rootDoc); } /** * Return the name of the freemarker template to be used for the index generated by Barclay. * Must reside in the folder passed to the Barclay Javadc Doclet via the "-settings-dir" parameter. * @return name of freemarker index template */ @Override public String getIndexTemplateName() { return PICARD_FREEMARKER_INDEX_TEMPLATE_NAME; } /** * @return Create and return a DocWorkUnit-derived object to handle documentation * for the target feature(s) represented by documentedFeature. * * @param documentedFeature DocumentedFeature annotation for the target feature * @param classDoc javadoc classDoc for the target feature * @param clazz class of the target feature * @return DocWorkUnit to be used for this feature */ @Override protected DocWorkUnit createWorkUnit( final DocumentedFeature documentedFeature, final ClassDoc classDoc, final Class clazz) { return new DocWorkUnit( new PicardHelpDocWorkUnitHandler(this), documentedFeature, classDoc, clazz); } /** * Adds a super-category so that we can custom-order the categories in the doc index * * @param docWorkUnit * @return root Map after having added the super-category */ @Override protected final Map getGroupMap(final DocWorkUnit docWorkUnit) { final Map root = super.getGroupMap(docWorkUnit); /** * Add-on super-category definitions. The super-category and spark value strings need to be the * same as used in the Freemarker template. */ root.put("supercat", HelpConstants.getSuperCategoryProperty(docWorkUnit.getGroupName())); return root; } } package priextractor.goextractor.search; import entitybuilder.gobuilder.goentity.InterfaceEntity; import entitybuilder.gobuilder.goentity.InterfaceFieldEntity; import entitybuilder.gobuilder.GoConstantString; import util.Configure; import util.Tuple; import uerr.SingleCollect; import java.util.ArrayList; public class NameSearchInterface { SingleCollect singleCollect = SingleCollect.getSingleCollectInstance(); /** * find methodName within interface and its embededInterfaces * it is like a breadSearch, first priextractor.goextractor.searcher the member methodName.(outlayer hide the inner one when the same memberName) * if not, then priextractor.goextractor.searcher the first layer children Interfaces, * if not, then priextractor.goextractor.searcher the second layer children interfaces, * go on ..... * @param methodName * @param interfaceId * @return */ public int findMethodInInfAndEmbededInfs(String methodName, int interfaceId) { if(interfaceId == -1 || !(singleCollect.getEntities().get(interfaceId) instanceof InterfaceEntity) ) { return -1; } ArrayList interfaceIds = new ArrayList(); int thisInterfaceId = -1; interfaceIds.add(interfaceId); while(!interfaceIds.isEmpty()) { thisInterfaceId = interfaceIds.get(0); interfaceIds.remove(0); if (findMethodInInf(methodName, thisInterfaceId) != -1) { return thisInterfaceId; } else{ for(Tuple relation : singleCollect.getEntities().get(thisInterfaceId).getRelations()) { if (relation.x.equals(Configure.RELATION_INHERIT)) { int embededInterfaceId = relation.y; interfaceIds.add(embededInterfaceId); } } } } return -1; //return -1 or return the latest found id? } /** * find fieldId by methodName within interface but not in its embededInterface * @param methodName * @param interfaceId * @return */ public int findMethodInInf(String methodName, int interfaceId) { if(interfaceId == -1 || !(singleCollect.getEntities().get(interfaceId) instanceof InterfaceEntity) ) { return -1; } for(int childId : singleCollect.getEntities().get(interfaceId).getChildrenIds()) { if(singleCollect.getEntities().get(childId) instanceof InterfaceFieldEntity) { InterfaceFieldEntity interfaceFieldEntity = (InterfaceFieldEntity) singleCollect.getEntities().get(childId); if(interfaceFieldEntity.getType().equals(GoConstantString.INTERFACE_FIELD_IS_METHOD) && interfaceFieldEntity.getName().equals(methodName)) { return interfaceFieldEntity.getId(); } } } return -1; } } ftriguero/gs-testing-web0 @WebMvcTest public class WebLayerTest { @Autowired private MockMvc mockMvc; @Test public void shouldReturnDefaultMessage() throws Exception { this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk()) .andExpect(content().string(containsString("Hello, World"))); } }grow-basic/src/main/java/com/devil/basic/design/strategy/Config.java1-10 package com.devil.basic.design.strategy; /** * @author Devil * @date Created in 2021/7/22 13:39 */ public interface Config { /** * 获取配置 */ String getConfig(); } package datadog.trace.instrumentation.jms; import datadog.trace.instrumentation.api.AgentPropagation; import javax.jms.JMSException; import javax.jms.Message; import lombok.extern.slf4j.Slf4j; @Slf4j public class MessageInjectAdapter implements AgentPropagation.Setter { public static final MessageInjectAdapter SETTER = new MessageInjectAdapter(); static final String DASH = "__dash__"; @Override public void set(final Message carrier, final String key, final String value) { final String propName = key.replace("-", DASH); try { carrier.setStringProperty(propName, value); } catch (final JMSException e) { if (log.isDebugEnabled()) { log.debug("Failure setting jms property: " + propName, e); } } } } src/test/java/com/apicatalog/projection/annotated/ProvidedCollectionTest.java package com.apicatalog.projection.annotated; import java.util.Arrays; import java.util.Collection; import java.util.stream.Collectors; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.apicatalog.projection.CompositionError; import com.apicatalog.projection.ExtractionError; import com.apicatalog.projection.Registry; import com.apicatalog.projection.api.ProjectionError; import com.apicatalog.projection.converter.ConverterError; import com.apicatalog.projection.projections.StringCollectionTo; import com.apicatalog.projection.source.SourceObject; public class ProvidedCollectionTest { Registry projections; @Before public void setup() throws CompositionError, ProjectionError { projections = Registry.newInstance(); projections.register(StringCollectionTo.class); } @Test public void testCompose() throws CompositionError, ConverterError { String href = "https://example.org/provided"; Collection items = Arrays.asList(123l, 234l); StringCollectionTo projection = projections.get(StringCollectionTo.class).compose( SourceObject.of("items", items), SourceObject.of("href", href) ); Assert.assertNotNull(projection); Assert.assertEquals(href, projection.href); Assert.assertNotNull(projection.items); Assert.assertArrayEquals(items.stream().map(l -> Long.toString(l)).collect(Collectors.toList()).toArray(new String[0]), projection.items.toArray(new String[0])); } @Test public void testExtract() throws ExtractionError, ConverterError { StringCollectionTo to = new StringCollectionTo(); to.href = "https://example.org/provided"; to.items = Arrays.asList("10", "20", "30"); String href = projections.get(StringCollectionTo.class).extract(to, "href", String.class).orElse(null); Assert.assertNotNull(href); Assert.assertEquals(to.href, href); Collection items = projections.get(StringCollectionTo.class).extractCollection(to, "items", String.class).orElse(null); Assert.assertNotNull(items); Assert.assertArrayEquals(new String[] {"10", "20", "30"}, items.toArray(new String[0])); } } yunxao/JN-Sim // @(#)pq.java 9/2002 // Copyright (c) 1998-2002, Distributed Real-time Computing Lab (DRCL) // 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 "DRCL" 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 REGENTS 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 drcl.diffserv.scheduling; /** * A Simple Priority Queue Scheduler * NOTE: for convenience, assume that entry is ordered by weight in descending * order, i.e., when you do addQueueSet in script file, you should add queue with * higher priority first. This makes sense for static configuration * * @author () * @version 1.0 07/16/2000 * @version 1.1 05/22/2002 * */ import drcl.inet.core.Queue; import drcl.util.queue.SimpleQueue; import java.util.Enumeration; public class pq extends drcl.diffserv.HQS { SimpleQueue qq; public pq() { super(); } public pq(String id) { super(id); } protected Queue pickEligibleQueue(boolean dequeue_) { if (qq == null) return null; for (Enumeration e_ = qq.getElementEnumerator(); e_.hasMoreElements(); ) { Queue q_ = (Queue) e_.nextElement(); if (!q_.isEmpty()) return q_; } return null; } /** * Adds the child queue with the same priority as (the currently lowest priority * in this HQS + 1). */ public void addQueueSet(Queue child_, long classMask_, long classId_) { super.addQueueSet(child_, classMask_, classId_); if (qq == null) qq = new SimpleQueue(); double lastKey_ = qq.lastKey(); if (Double.isNaN(lastKey_)) lastKey_ = 0.0; qq.enqueue(lastKey_ + 1.0, child_); } /** * Adds the child queue with the specified priority. * The smaller value of priority_ corresponds to higher priority. */ public void addQueueSet(Queue child_, long classMask_, long classId_, int priority_) { super.addQueueSet(child_, classMask_, classId_); if (qq == null) qq = new SimpleQueue(); qq.enqueue((double)priority_, child_); } public void removeQueueSet(Queue child_) { super.removeQueueSet(child_); if (qq != null) qq.remove(child_); } protected String configInfo(String prefix_, Queue q_) { if (qq == null) return ""; double priority_ = qq.retrieveKey(q_); if (Double.isNaN(priority_)) return prefix_ + "priority: NaN"; else return prefix_ + "priority: " + ((int)priority_); } } src/main/java/net/j4c/test/GenerateData.java /** * Copyright 2014 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 net.j4c.test; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.Random; /** * Generates random data. The columns/fields * are as follows. *

    *
  • id
  • *
  • x
  • *
  • y
  • *
* There are 2 centers at (0,0) and (10,10). When * the data is generated, a delta in the range [0,1] * is added to one of these centers. * @author * */ public class GenerateData { private static final Random _r = new Random(37L); public static void main(String[] args) { final int n = 100000; double p = 0.5d; double c1x = 0.0d; double c1y = 0.0d; double c2x = 10.0d; double c2y = 10.0d; BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(new File("out.data"))); StringBuilder sb = new StringBuilder(); final String nl = System.getProperty("line.separator"); for(int i=0; i < n; i++) { double t = _r.nextDouble(); double cx = c1x; double cy = c1y; if(t >= p) { cx = c2x; cy = c2y; } double dx = _r.nextDouble(); double dy = _r.nextDouble(); cx += dx; cy += dy; sb.setLength(0); sb.append(i); sb.append(','); sb.append(cx); sb.append(','); sb.append(cy); sb.append(nl); writer.write(sb.toString()); } } catch(Exception ex) { throw new RuntimeException(ex); } finally { if(null != writer) { try { writer.close(); } catch(Exception ex) { } } } } } jkuharev/ISOQuantsrc/isoquant/app/Defaults.java /** ISOQuant, isoquant.app, 15.07.2011 */ package isoquant.app; import java.io.File; import javax.swing.JOptionPane; import de.mz.jk.jsix.utilities.ResourceLoader; import de.mz.jk.jsix.utilities.Settings; import isoquant.kernel.plugin.management.PluginManager; import isoquant.plugins.batch.ImportAndProcessBatcher; import isoquant.plugins.batch.ReprocessBatcher; import isoquant.plugins.collections.PrivatePluginsCollection; import isoquant.plugins.collections.PublicReporterPluginsCollection; import isoquant.plugins.common.ProjectFinder; import isoquant.plugins.common.ProjectSelectionSynchronizer; import isoquant.plugins.configuration.ConfigurationEditor; import isoquant.plugins.db.*; import isoquant.plugins.exporting.ProjectDataExporter; import isoquant.plugins.help.HelpWindowPresenter; import isoquant.plugins.importing.ProjectFromFileImporter; import isoquant.plugins.plgs.PLGSProjectExplorer; import isoquant.plugins.plgs.PLGSProjectInfoViewer; import isoquant.plugins.plgs.importing.ProjectImporterByExpressionAnalysis; import isoquant.plugins.plgs.importing.ProjectImporterByExpressionAnalysisAndBlusterResultsImporter; import isoquant.plugins.plgs.importing.ProjectImporterByUserDesignMulti; import isoquant.plugins.plgs.plain.PlainPLGSDataImporter; import isoquant.plugins.processing.annotation.AnnotationStatisticsCreator; import isoquant.plugins.processing.annotation.EMRTClusterAnnotator; import isoquant.plugins.processing.annotation.PeptideIdentificationFilter; import isoquant.plugins.processing.expression.EMRTClusteringPlugin; import isoquant.plugins.processing.expression.ExpressionAnalysisPlugin; import isoquant.plugins.processing.expression.RetentionTimeAlignmentPlugin; import isoquant.plugins.processing.expression.clustering.preclustering.DynamicPreClusterer; import isoquant.plugins.processing.fractions.LCFractionsTimeShifter; import isoquant.plugins.processing.fractions.LCFractionsTimeUnshifter; import isoquant.plugins.processing.linkage.EMRTTableLinker; import isoquant.plugins.processing.normalization.IntensityNormalizer; import isoquant.plugins.processing.preprocessing.DataPreparator; import isoquant.plugins.processing.quantification.TopXQuantifier; import isoquant.plugins.processing.restructuring.EMRTTableFromMassSpectrumCreator; import isoquant.plugins.processing.statistics.ProteinStatisticsMaker; import isoquant.plugins.report.prep.ReportPreparator; /** * static configuration defaults for application *

{@link Defaults}

* @author * @version 15.07.2011 15:23:12 */ public class Defaults { private static boolean suppressVersionString = false; public static boolean DEBUG = false; public static boolean TEST = false; public final static String VERSION_MILESTONE = "1.8"; public final static String VERSION_STATE = "beta"; public final static int VERSION_BUILD_YEAR = 2018; public final static int VERSION_BUILD_MONTH = 9; public final static int VERSION_BUILD_DAY = 14; public final static String VERSION_BUILD_DATE = VERSION_BUILD_YEAR + "-" + (VERSION_BUILD_MONTH < 10 ? "0" : "") + VERSION_BUILD_MONTH + "-" + (VERSION_BUILD_DAY < 10 ? "0" : "") + VERSION_BUILD_DAY; public final static int availableProcessors = Runtime.getRuntime().availableProcessors(); public static String version() { return suppressVersionString ? "" : VERSION_MILESTONE + " " + (DEBUG || TEST ? "internal" : "public") + " " + VERSION_STATE + " (" + VERSION_BUILD_DATE + ")"; } /** make plugins available to ISOQuant application */ static { PluginManager.defaultPlugins = new String[] { PLGSProjectExplorer.class.getName() , PlainPLGSDataImporter.class.getName() , ProjectDBExplorer.class.getName() , ProjectFromFileImporter.class.getName() , ProjectFinder.class.getName() , ConfigurationEditor.class.getName() , HelpWindowPresenter.class.getName() , ProjectSelectionSynchronizer.class.getName() // ProjectDetailsViewer.class.getName() , PLGSProjectInfoViewer.class.getName() , ProjectDBInfoViewer.class.getName() , ProjectRenamer.class.getName() // TODO remove next line , ProjectImporterByUserDesignMulti.class.getName() , ProjectImporterByExpressionAnalysisAndBlusterResultsImporter.class.getName() , ProjectImporterByExpressionAnalysis.class.getName() , ImportAndProcessBatcher.class.getName() , ReprocessBatcher.class.getName() , PublicReporterPluginsCollection.class.getName() , ProjectDataExporter.class.getName() , ProjectRemover.class.getName() // single processing steps and DEBUG // TODO remove following lines , ProjectCleaner.class.getName() , DataPreparator.class.getName() , EMRTTableLinker.class.getName() , EMRTTableFromMassSpectrumCreator.class.getName() , ProteinStatisticsMaker.class.getName() , LCFractionsTimeShifter.class.getName() , ExpressionAnalysisPlugin.class.getName() , RetentionTimeAlignmentPlugin.class.getName() , DynamicPreClusterer.class.getName() , EMRTClusteringPlugin.class.getName() , LCFractionsTimeUnshifter.class.getName() , PeptideIdentificationFilter.class.getName() , EMRTClusterAnnotator.class.getName() , AnnotationStatisticsCreator.class.getName() , IntensityNormalizer.class.getName() , TopXQuantifier.class.getName() , ReportPreparator.class.getName() , PrivatePluginsCollection.class.getName() }; } public static Settings config = null; private static File configFile = new File("isoquant.ini"); static { try { if (!configFile.exists()) { System.out.print("configuration file not found, creating new one ... "); configFile.createNewFile(); System.out.println("[done]"); } } catch (Exception e) { e.printStackTrace(); } if (!configFile.canRead()) { showErrorMessage("ISOQuant is unable to read config file\n" + "'" + configFile.getAbsolutePath() + "'.\n\n" + "Please correct the file system permissions for this file\n" + "or use privileged user to execute the application.\n\n" + "ISOQuant will now exit."); System.err.println( "Please correct file system permissions for file " + configFile + "\n" + "or use privileged user to execute the application."); System.exit(0); } if (!configFile.canWrite()) { showErrorMessage("ISOQuant is unable to write configuration changes to file\n" + "'" + configFile.getAbsolutePath() + "'.\n\n" + "Please correct the file system permissions for this file\n" + "or use privileged user to execute the application.\n\n" + "ISOQuant will use predefined configuration " + "or default configuration values!"); } config = new Settings(configFile.getAbsolutePath(), "ISOQuant configuration"); DEBUG = config.getBooleanValue("setup.debug", false, true); TEST = config.getBooleanValue("setup.test", false, true); double iconScaleFactor = config.getDoubleValue("setup.ui.iconScaleFactor", 1.0, false); if (iconScaleFactor < 0.2 || iconScaleFactor > 3) { iconScaleFactor = 1.0; config.setValue("setup.ui.iconScaleFactor", 1.0); } ResourceLoader.setIconDefaults("isoquant/resources/icons/", ".png", iconScaleFactor); } public static void showErrorMessage(String msg) { System.err.println(msg); JOptionPane.showMessageDialog(null, msg, "error", JOptionPane.ERROR_MESSAGE); } } /* * Copyright 2020 Alibaba Group Holding Limited. * * 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.alibaba.graphscope.gaia; import org.apache.commons.configuration.Configuration; import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategies; import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; import org.apache.tinkerpop.gremlin.process.traversal.strategy.finalization.ProfileStrategy; import org.apache.tinkerpop.gremlin.process.traversal.strategy.optimization.FilterRankingStrategy; import org.apache.tinkerpop.gremlin.structure.Graph; @Graph.OptIn("com.alibaba.graphscope.gaia.GaiaGremlinTestSuite") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_repeatXoutXknowsXX_untilXrepeatXoutXcreatedXX_emitXhasXname_lopXXX_path_byXnameX", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_repeatXoutX_timesX2X_emit_path", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_repeatXout_repeatXoutX_timesX1XX_timesX1X_limitX1X_path_by_name", reason = "not support path by") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_VX1X_repeatXoutX_untilXoutE_count_isX0XX_name", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_repeatXbothX_untilXname_eq_marko_or_loops_gt_1X_groupCount_byXnameX", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_VX1X_repeatXgroupCountXmX_byXloopsX_outX_timesX3X_capXmX", reason = "not support cap") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_VX1X_emitXhasXlabel_personXX_repeatXoutX_name", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_hasXname_markoX_repeatXoutE_inV_simplePathX_untilXhasXname_rippleXX_path_byXnameX_byXlabelX", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_untilXconstantXtrueXX_repeatXrepeatXout_createdXX_untilXhasXname_rippleXXXemit_lang", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_VX6X_repeatXa_bothXcreatedX_simplePathX_emitXrepeatXb_bothXknowsXX_untilXloopsXbX_asXb_whereXloopsXaX_asXbX_hasXname_vadasXX_dedup_name", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_VX3X_repeatXbothX_createdXX_untilXloops_is_40XXemit_repeatXin_knowsXX_emit_loopsXisX1Xdedup_values", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_hasXloop_name_loopX_repeatXinX_timesX5X_path_by_name", reason = "not support path by") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_repeatXgroupCountXmX_byXnameX_outX_timesX2X_capXmX", reason = "not support cap") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_repeatXrepeatXout_createdXX_untilXhasXname_rippleXXXemit_lang", reason = "not support until") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_emit_repeatXa_outXknows_filterXloops_isX0XX_lang", reason = "not support repeat with loop name") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionTest", method = "g_VX1_2X_localXunionXoutE_count__inE_count__outE_weight_sumXX", reason = "not support local") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionTest", method = "g_V_chooseXlabel_is_person__unionX__out_lang__out_nameX__in_labelX", reason = "not support choose") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionTest", method = "g_VX1_2X_localXunionXcountXX", reason = "not support local") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionTest", method = "g_V_chooseXlabel_is_person__unionX__out_lang__out_nameX__in_labelX_groupCount", reason = "not support choose") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionTest", method = "g_VX1_2X_unionXoutE_count__inE_count__outE_weight_sumX", reason = "not support sum") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.CyclicPathTest", method = "g_VX1X_asXaX_outXcreatedX_asXbX_inXcreatedX_asXcX_cyclicPath_fromXaX_toXbX_path", reason = "not support path from to") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest", method = "g_V_both_name_order_byXa_bX_dedup_value", reason = "not support lambda") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterTest", method = "g_V_filterXfalseX", reason = "not support lambda") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterTest", method = "g_VX1X_out_filterXage_gt_30X", reason = "not support lambda") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterTest", method = "g_E_filterXfalseX", reason = "not support lambda") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterTest", method = "g_VX1X_filterXage_gt_30X", reason = "not support lambda") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterTest", method = "g_V_filterXname_startsWith_m_OR_name_startsWith_pX", reason = "not support lambda") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterTest", method = "g_V_filterXtrueX", reason = "not support lambda") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterTest", method = "g_E_filterXtrueX", reason = "not support lambda") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterTest", method = "g_V_filterXlang_eq_javaX", reason = "not support lambda") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.FilterTest", method = "g_VX2X_filterXage_gt_30X", reason = "not support lambda") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupTest", method = "g_V_outXfollowedByX_group_byXsongTypeX_byXbothE_group_byXlabelX_byXweight_sumXX", reason = "not support sum") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_repeatXoutXknowsXX_untilXrepeatXoutXcreatedXX_emitXhasXname_lopXXX_path_byXnameX", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest", method = "g_EX11X_outV_outE_hasXid_10AsStringX", reason = "not support edge global id") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest", method = "g_V_hasIdXemptyX_count", reason = "[bug3] count returns nothing when the result is 0") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest", method = "g_E_hasLabelXuses_traversesX", reason = "crew graph is not ready") //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest", // method = "g_VX4X_hasXage_gt_30X", // reason = "[bug2] g.V(id).has(...) returns nothing") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest", // method = "g_VX1X_hasXname_markoX", // reason = "[bug2] g.V(id).has(...) returns nothing") //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest", // method = "g_EX7X_hasXlabelXknowsX", // reason = "[bug1] g.E() return vertices from pegasus") //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest", // method = "g_E_hasXlabelXknowsX", // reason = "bug return empty") //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest", // method = "g_VX1X_outEXknowsX_asXhereX_hasXweight_1X_asXfakeX_inV_hasXname_joshX_selectXhereX", // reason = "[bug4] edge returning result invalid") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest", // method = "g_VX2X_inE", // reason = "[bug4] edge returning result invalid") //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest", // method = "g_EX11X_outV_outE_hasXid_10X", // reason = "not support edge global id") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest", // method = "g_VX1X_outEXknowsX_asXhereX_hasXweight_1X_inV_hasXname_joshX_selectXhereX", // reason = "[bug4] edge returning result invalid") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest", // method = "g_VX1X_outE", // reason = "[bug4] edge returning result invalid") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest", // method = "g_EXe11X", // reason = "[bug1] g.E() return vertices from pegasus") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest", // method = "g_EX11X", // reason = "[bug1] g.E() return vertices from pegasus") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest", // method = "g_E", // reason = "[bug1] g.E() return vertices from pegasus") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest", // method = "g_VX1X_outEXknowsX_hasXweight_1X_asXhereX_inV_hasXname_joshX_selectXhereX", // reason = "[bug4] edge returning result invalid") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest", // method = "g_VX4X_bothEXcreatedX", // reason = "[bug4] edge returning result invalid") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.SelectTest", // method = "g_VX1X_outE_asXhereX_inV_hasXname_vadasX_selectXhereX", // reason = "[bug4] edge returning result invalid") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest", // method = "g_VX4X_bothE", // reason = "[bug4] edge returning result invalid") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest", // method = "g_EXlistXe7_e11XX", // reason = "[bug1] g.E() return vertices from pegasus") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest", // method = "g_EX11AsStringX", // reason = "[bug1] g.E() return vertices from pegasus") // //@Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.VertexTest", // method = "g_EXe7_e11X", // reason = "[bug1] g.E() return vertices from pegasus") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.HasTest", method = "g_V_hasIdXwithinXemptyXX_count", reason = "[bug3] count returns nothing when the result is 0") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.CountTest", method = "g_V_hasXnoX_count", reason = "[bug3] count returns nothing when the result is 0") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupTest", method = "g_V_group_byXbothE_countX_byXgroup_byXlabelXX", reason = "not support nested group by, group().by().by(__.group().by(...))") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupCountTest", method = "g_V_hasXnoX_groupCount", reason = "[bug5] groupCount() returns nothing when the result is []") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.PathTest", method = "g_VX1X_name_path", reason = "not support other element type (excluding vertex/edge) in path") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.PathTest", method = "g_V_out_out_path_byXnameX_byXageX", reason = "not support path by") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.PathTest", method = "g_V_repeatXoutX_timesX2X_path_byXitX_byXnameX_byXlangX", reason = "not support path by") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.PathTest", method = "g_V_out_out_path_byXnameX_byXageX", reason = "not support path by") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.PathTest", method = "g_V_asXaX_out_asXbX_out_asXcX_path_fromXbX_toXcX_byXnameX", reason = "not support path by") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.PathTest", method = "g_V_asXaX_hasXname_markoX_asXbX_hasXage_29X_asXcX_path", reason = "not support path returning result with label") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.map.PathTest", method = "g_VX1X_out_path_byXageX_byXnameX", reason = "not support path by") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_emit_repeatXoutX_timesX2X_path", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_VX1X_repeatXrepeatXunionXout_uses_out_traversesXX_whereXloops_isX0X_timesX1X_timeX2X_name", reason = "crew graph is not ready") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_repeatXoutX_timesX2X_emit", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.RepeatTest", method = "g_V_emit_timesX2X_repeatXoutX_path", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.branch.UnionTest", method = "g_V_unionXrepeatXunionXoutXcreatedX__inXcreatedXX_timesX2X__repeatXunionXinXcreatedX__outXcreatedXX_timesX2XX_label_groupCount", reason = "not support label step") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest", method = "g_V_asXaX_repeatXbothX_timesX3X_emit_name_asXbX_group_byXselectXaXX_byXselectXbX_dedup_order_foldX_selectXvaluesX_unfold_dedup", reason = "not support until or emit in repeat") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest", method = "g_V_both_both_dedup_byXlabelX", reason = "not support dedup by") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest", method = "g_V_both_hasXlabel_softwareX_dedup_byXlangX_name", reason = "not support dedup by") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest", method = "g_V_out_asXxX_in_asXyX_selectXx_yX_byXnameX_fold_dedupXlocal_x_yX_unfold", reason = "not support debup(local)") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest", method = "g_V_asXaX_outXcreatedX_asXbX_inXcreatedX_asXcX_dedupXa_bX_path", reason = "not support debup(\"a\",\"b\")") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest", method = "g_V_both_both_dedup_byXoutE_countX_name", reason = "not support debup by(sub_traversal)") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest", method = "get_g_V_out_in_valuesXnameX_fold_dedupXlocalX_unfold", reason = "not support debup(local)") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest", method = "g_V_asXaX_both_asXbX_dedupXa_bX_byXlabelX_selectXa_bX", reason = "not support dedup(\"a\",\"b\").by(...).by(...)") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.filter.DedupTest", method = "g_V_asXaX_both_asXbX_dedupXa_bX_byXlabelX_selectXa_bX", reason = "repeat(dedup()) expected result is confusing") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupTest", method = "g_V_repeatXbothXfollowedByXX_timesX2X_group_byXsongTypeX_byXcountX", reason = "grateful graph is not ready") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupTest", method = "g_V_groupXaX_byXnameX_capXaX", reason = "not support GroupSideEffect") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupTest", method = "g_V_out_group_byXlabelX_selectXpersonX_unfold_outXcreatedX_name_limitX2X", reason = "not support group().by(T.label).select(\"person\"), person is label instead of tag") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupTest", method = "g_V_repeatXunionXoutXknowsX_groupXaX_byXageX__outXcreatedX_groupXbX_byXnameX_byXcountXX_groupXaX_byXnameXX_timesX2X_capXa_bX", reason = "not support GroupSideEffect") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupTest", method = "g_V_hasLabelXsongX_group_byXnameX_byXproperties_groupCount_byXlabelXX", reason = "grateful graph is not ready") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupTest", method = "g_V_group_byXname_substring_1X_byXconstantX1XX", reason = "not support lambda") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupTest", method = "g_V_groupXmX_byXnameX_byXinXknowsX_nameX_capXmX", reason = "not support GroupSideEffect") @Graph.OptOut(test = "org.apache.tinkerpop.gremlin.process.traversal.step.sideEffect.GroupTest", method = "g_V_groupXaX_byXname_substring_1X_byXconstantX1XX_capXaX", reason = "not support lambda") // g_V_repeatXbothXfollowedByXX_timesX2X_groupXaX_byXsongTypeX_byXcountX_capXaX // group side effect // g_withSideEffectXa__marko_666_noone_blahX_V_groupXaX_byXnameX_byXoutE_label_foldX_capXaX // group side effect // g_V_repeatXout_groupXaX_byXnameX_byXcountX_timesX2X_capXaX // group side effect // g_V_group_byXlabelX_byXbothE_groupXaX_byXlabelX_byXweight_sumX_weight_sumX // group side effect // g_V_hasLabelXpersonX_asXpX_outXcreatedX_group_byXnameX_byXselectXpX_valuesXageX_sumX // sum // g_V_hasLabelXsongX_groupXaX_byXnameX_byXproperties_groupCount_byXlabelXX_out_capXaX // group side effect // g_V_hasXlangX_groupXaX_byXlangX_byXnameX_out_capXaX // group side effect // g_V_groupXaX_byXlabelX_byXoutE_weight_sumX_capXaX // group side effect // GroupCountTest // g_V_unionXrepeatXoutX_timesX2X_groupCountXmX_byXlangXX__repeatXinX_timesX2X_groupCountXmX_byXnameXX_capXmX // group side effect // g_V_repeatXout_groupCountXaX_byXnameXX_timesX2X_capXaX // group side efect // g_V_outXcreatedX_groupCountXxX_capXxX // group side effect // g_V_both_groupCountXaX_out_capXaX_selectXkeysX_unfold_both_groupCountXaX_capXaX // group side effect // g_V_outXcreatedX_groupCountXaX_byXnameX_capXaX // group side effect // g_V_outXcreatedX_name_groupCountXaX_capXaX // group side effect // g_V_both_groupCountXaX_byXlabelX_asXbX_barrier_whereXselectXaX_selectXsoftwareX_isXgtX2XXX_selectXbX_name // group side effect // g_V_hasXnoX_groupCountXaX_capXaX // group side effect public class RemoteTestGraph extends DummyGraph { public static final String GRAPH_NAME = "test.graph.name"; private RemoteGremlinConnection remoteGremlinConnection; public RemoteTestGraph(final Configuration configuration) { try { String gremlinEndpoint = configuration.getString(GRAPH_NAME); this.remoteGremlinConnection = new RemoteGremlinConnection(gremlinEndpoint); } catch (Exception e) { throw new RuntimeException("initiate remote test graph fail " + e); } } public static RemoteTestGraph open(final Configuration configuration) { return new RemoteTestGraph(configuration); } @Override public void close() throws Exception { this.remoteGremlinConnection.close(); } @Override public Configuration configuration() { return null; } @Override public GraphTraversalSource traversal() { GraphTraversalSource graphTraversalSource = new GraphTraversalSource( this, TraversalStrategies.GlobalCache.getStrategies(this.getClass())).withRemote(this.remoteGremlinConnection); TraversalStrategies strategies = graphTraversalSource.getStrategies(); strategies.removeStrategies( ProfileStrategy.class, FilterRankingStrategy.class); return graphTraversalSource; } } digdag-standards/src/main/java/io/digdag/standards/operator/NopOperatorFactory.java package io.digdag.standards.operator; import com.google.inject.Inject; import io.digdag.client.config.Config; import io.digdag.spi.Operator; import io.digdag.spi.OperatorFactory; import io.digdag.spi.TaskRequest; import io.digdag.spi.TaskResult; import io.digdag.util.BaseOperator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; public class NopOperatorFactory implements OperatorFactory { private static Logger logger = LoggerFactory.getLogger(NopOperatorFactory.class); public String getType() { return "nop"; } @Override public Operator newTaskExecutor(Path workspacePath, TaskRequest request) { return new ShOperator(workspacePath, request); } private class ShOperator extends BaseOperator { public ShOperator(Path workspacePath, TaskRequest request) { super(workspacePath, request); } @Override public TaskResult runTask() { Config params = request.getConfig() .mergeDefault(request.getConfig().getNestedOrGetEmpty("nop")); String command = params.get("_command", String.class); logger.info("nop: {}", command); return TaskResult.empty(request); } } } package com.createchance.imageeditor.shaders; import android.opengl.GLES20; /** * Cross zoom transition shader. * * @author createchance * @date 2018/12/31 */ public class CrossZoomTransShader extends TransitionMainFragmentShader { private final String TRANS_SHADER = "CrossZoom.glsl"; private final String U_STRENGTH = "strength"; public CrossZoomTransShader() { initShader(new String[]{TRANSITION_FOLDER + BASE_SHADER, TRANSITION_FOLDER + TRANS_SHADER}, GLES20.GL_FRAGMENT_SHADER); } @Override public void initLocation(int programId) { super.initLocation(programId); addLocation(U_STRENGTH, true); loadLocation(programId); } public void setUStrength(float strength) { setUniform(U_STRENGTH, strength); } } dataserver/dataserver.innodb/src/main/java/com/g414/haildb/Validation.java0 package com.g414.haildb; import java.math.BigInteger; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class Validation { private static final Map> validators; static { Map> newValidators = new HashMap>(); newValidators.put(ColumnType.VARCHAR, new Validator() { public boolean isValid(ColumnDef columnDef, Object obj) { if (isBadNull(columnDef, obj)) { return false; } else if (obj == null) { return true; } if (!(obj instanceof String)) { return false; } String target = (String) obj; if (target != null && isBadLength(columnDef, target.length())) { return false; } return true; }; }); newValidators.put(ColumnType.CHAR, newValidators .get(ColumnType.VARCHAR)); newValidators.put(ColumnType.BINARY, new Validator() { public boolean isValid(ColumnDef columnDef, Object obj) { if (isBadNull(columnDef, obj)) { return false; } else if (obj == null) { return true; } byte[] target = (byte[]) obj; if (!(obj instanceof byte[])) { return false; } if (target != null && isBadLength(columnDef, target.length)) { return false; } return true; }; }); newValidators.put(ColumnType.VARBINARY, newValidators .get(ColumnType.BINARY)); newValidators .put(ColumnType.BLOB, newValidators.get(ColumnType.BINARY)); newValidators.put(ColumnType.INT, new Validator() { public boolean isValid(ColumnDef columnDef, Object obj) { if (isBadNull(columnDef, obj)) { return false; } else if (obj == null) { return true; } if (!(obj instanceof Number)) { return false; } Number target = (Number) obj; if (!(target instanceof Byte) && !(target instanceof Short) && !(target instanceof Integer) && !(target instanceof Long) && !(target instanceof BigInteger)) { return false; } boolean isUnsigned = columnDef.is(ColumnAttribute.UNSIGNED); int signed = isUnsigned ? 0 : 1; int posBits = (8 * columnDef.getLength()) - signed; if (target instanceof BigInteger) { BigInteger hiLimit = BigInteger.ONE.shiftLeft(posBits); BigInteger loLimit = isUnsigned ? BigInteger.ZERO : ((BigInteger) hiLimit).negate().subtract( BigInteger.ONE); if (((BigInteger) target).compareTo(loLimit) < 0 || ((BigInteger) target).compareTo(hiLimit) > 0) { return false; } } else { long hiLimit = Long.MAX_VALUE >> (63 - posBits); long loLimit = isUnsigned ? 0 : -((Long) hiLimit) - 1; long compare = target.longValue(); if ((compare < loLimit) || (compare > hiLimit)) { return false; } } return true; } }); validators = Collections.unmodifiableMap(newValidators); } public static boolean isValid(ColumnDef def, Object value) { return validators.containsKey(def.getType()) && validators.get(def.getType()).isValid(def, value); } private static boolean isBadNull(ColumnDef columnDef, Object target) { return columnDef.is(ColumnAttribute.NOT_NULL) && (target == null); } private static boolean isBadLength(ColumnDef columnDef, int length) { return columnDef.getLength() < length && !columnDef.getType().equals(ColumnType.BLOB); } private interface Validator { public boolean isValid(ColumnDef columnDef, T target); } } 10-100 package com.accenture.testing.bdd.parameters; public abstract class ParamTransform { @Override public String toString() { return key(); } /** * they key for this transformation. * * @return the key for the transformation */ abstract String key(); /** * transform the input based on the transformer type. * * @param params the parameters for the transform * @param pt the calling transformer * @return the transformed string */ abstract String transform(String params, ParamTransformer pt); } 0 /*- * #%L * BigDataViewer-Playground * %% * Copyright (C) 2019 - 2021 , EPFL - , MPI CBG - , EMBL * %% * 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 de.embl.cba.mobie.transform; import bdv.util.DefaultInterpolators; import bdv.viewer.Interpolation; import bdv.viewer.Source; import mpicbg.spim.data.sequence.VoxelDimensions; import net.imglib2.FinalInterval; import net.imglib2.FinalRealInterval; import net.imglib2.Interval; import net.imglib2.RandomAccessibleInterval; import net.imglib2.RealInterval; import net.imglib2.RealRandomAccessible; import net.imglib2.realtransform.AffineTransform3D; import net.imglib2.realtransform.InverseRealTransform; import net.imglib2.realtransform.RealTransformRandomAccessible; import net.imglib2.realtransform.RealViews; import net.imglib2.type.numeric.NumericType; import net.imglib2.util.Intervals; import net.imglib2.view.ExtendedRandomAccessibleInterval; import net.imglib2.view.IntervalView; import net.imglib2.view.Views; import java.util.HashMap; import java.util.function.Function; public class CroppedSource< T extends NumericType > implements Source< T > //, Function< Source< T >, Source< T > > { private Source< T > source; private final String name; private final RealInterval crop; private final boolean zeroMin; protected transient final DefaultInterpolators< T > interpolators; private transient HashMap< Integer, Interval > levelToVoxelInterval; public CroppedSource( Source< T > source, String name, RealInterval crop, boolean zeroMin ) { this.source = source; this.name = name; this.crop = crop; this.zeroMin = zeroMin; this.interpolators = new DefaultInterpolators(); initCropIntervals( source, crop ); } private void initCropIntervals( Source< T > source, RealInterval crop ) { final AffineTransform3D transform3D = new AffineTransform3D(); levelToVoxelInterval = new HashMap<>(); final int numMipmapLevels = source.getNumMipmapLevels(); for ( int level = 0; level < numMipmapLevels; level++ ) { source.getSourceTransform( 0, level, transform3D ); final AffineTransform3D inverse = transform3D.inverse(); final Interval voxelInterval = Intervals.smallestContainingInterval( inverse.estimateBounds( crop ) ); final FinalInterval containedVoxelInterval = intersectWithSourceInterval( source, crop, level, voxelInterval ); levelToVoxelInterval.put( level, containedVoxelInterval ); } } private FinalInterval intersectWithSourceInterval( Source< T > source, RealInterval crop, int level, Interval voxelInterval ) { // If the interval is outside the bounds of the RAI then there is nothing to show. // Moreover the fetcher threads throw errors when trying to access pixels outside the RAI. // Thus let's limit the interval to where there actually is data. final RandomAccessibleInterval< T > rai = source.getSource( 0, level ); final FinalInterval intersect = Intervals.intersect( rai, voxelInterval ); if ( Intervals.numElements( intersect ) <= 0 ) { throw new RuntimeException( "The crop interval " + crop + " is not within the image source " + source.getName() ); } return intersect; } public Source< ? > getWrappedSource() { return source; } @Override public boolean isPresent(int t) { return source.isPresent(t); } @Override public RandomAccessibleInterval< T > getSource(int t, int level) { final RandomAccessibleInterval< T > rai = source.getSource( t, level ); final IntervalView< T > croppedRai = Views.interval( rai, levelToVoxelInterval.get( level ) ); if ( zeroMin ) return Views.zeroMin( croppedRai ); else return croppedRai; } @Override public RealRandomAccessible< T > getInterpolatedSource( int t, int level, Interpolation method ) { final RandomAccessibleInterval< T > croppedRai = getSource( t, level ); ExtendedRandomAccessibleInterval> extendedRai = Views.extendZero( croppedRai ); RealRandomAccessible< T > realRandomAccessible = Views.interpolate( extendedRai, interpolators.get(method) ); final AffineTransform3D affineTransform3D = new AffineTransform3D(); source.getSourceTransform( t, level, affineTransform3D ); final RealRandomAccessible< T > transformed = RealViews.transform( realRandomAccessible, affineTransform3D ); return realRandomAccessible; } @Override public void getSourceTransform(int t, int level, AffineTransform3D transform) { source.getSourceTransform( t, level, transform ); } @Override public T getType() { return source.getType(); } @Override public String getName() { if ( name != null ) return name; else return source.getName(); } @Override public VoxelDimensions getVoxelDimensions() { return source.getVoxelDimensions(); } @Override public int getNumMipmapLevels() { return source.getNumMipmapLevels(); } // @Override // public Source< T > apply( Source< T > inputSource ) // { // return new CroppedSource<>( inputSource, name, crop, zeroMin ); // } } 1-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.kylin.source.hive; import java.io.IOException; import java.util.Collections; import java.util.List; import org.apache.hadoop.mapreduce.Job; import org.apache.hive.hcatalog.data.HCatRecord; import org.apache.hive.hcatalog.mapreduce.HCatInputFormat; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.util.HadoopUtil; import org.apache.kylin.common.util.StringUtil; import org.apache.kylin.cube.CubeInstance; import org.apache.kylin.cube.CubeManager; import org.apache.kylin.engine.mr.IMRInput; import org.apache.kylin.engine.mr.steps.CubingExecutableUtil; import org.apache.kylin.job.JoinedFlatTable; import org.apache.kylin.job.constant.ExecutableConstants; import org.apache.kylin.job.execution.AbstractExecutable; import org.apache.kylin.job.execution.DefaultChainedExecutable; import org.apache.kylin.job.execution.ExecutableManager; import org.apache.kylin.metadata.model.IJoinedFlatTableDesc; import org.apache.kylin.metadata.model.ISegment; import org.apache.kylin.metadata.model.TableDesc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; public class HiveMRInput extends HiveInputBase implements IMRInput { private static final Logger logger = LoggerFactory.getLogger(HiveMRInput.class); @Override public IMRBatchCubingInputSide getBatchCubingInputSide(IJoinedFlatTableDesc flatDesc) { return new BatchCubingInputSide(flatDesc); } @Override public IMRTableInputFormat getTableInputFormat(TableDesc table) { return new HiveTableInputFormat(getTableNameForHCat(table)); } @Override public IMRBatchMergeInputSide getBatchMergeInputSide(ISegment seg) { return new IMRBatchMergeInputSide() { @Override public void addStepPhase1_MergeDictionary(DefaultChainedExecutable jobFlow) { // doing nothing } }; } public static class HiveTableInputFormat implements IMRTableInputFormat { final String dbName; final String tableName; /** * Construct a HiveTableInputFormat to read hive table. * @param fullQualifiedTableName "databaseName.tableName" */ public HiveTableInputFormat(String fullQualifiedTableName) { String[] parts = HadoopUtil.parseHiveTableName(fullQualifiedTableName); dbName = parts[0]; tableName = parts[1]; } @Override public void configureJob(Job job) { try { job.getConfiguration().addResource("hive-site.xml"); HCatInputFormat.setInput(job, dbName, tableName); job.setInputFormatClass(HCatInputFormat.class); } catch (IOException e) { throw new RuntimeException(e); } } @Override public List parseMapperInput(Object mapperInput) { return Collections.singletonList(HiveTableReader.getRowAsStringArray((HCatRecord) mapperInput)); } } public static class BatchCubingInputSide implements IMRBatchCubingInputSide { final protected IJoinedFlatTableDesc flatDesc; final protected String flatTableDatabase; final protected String hdfsWorkingDir; List hiveViewIntermediateTables = Lists.newArrayList(); public BatchCubingInputSide(IJoinedFlatTableDesc flatDesc) { KylinConfig config = KylinConfig.getInstanceFromEnv(); this.flatDesc = flatDesc; this.flatTableDatabase = config.getHiveDatabaseForIntermediateTable(); this.hdfsWorkingDir = config.getHdfsWorkingDirectory(); } @Override public void addStepPhase1_CreateFlatTable(DefaultChainedExecutable jobFlow) { final String cubeName = CubingExecutableUtil.getCubeName(jobFlow.getParams()); CubeInstance cubeInstance = CubeManager.getInstance(KylinConfig.getInstanceFromEnv()).getCube(cubeName); final KylinConfig cubeConfig = cubeInstance.getConfig(); final String hiveInitStatements = JoinedFlatTable.generateHiveInitStatements(flatTableDatabase); // create flat table first addStepPhase1_DoCreateFlatTable(jobFlow); // then count and redistribute if (cubeConfig.isHiveRedistributeEnabled()) { jobFlow.addTask(createRedistributeFlatHiveTableStep(hiveInitStatements, cubeName, flatDesc, cubeInstance.getDescriptor())); } // special for hive addStepPhase1_DoMaterializeLookupTable(jobFlow); } protected void addStepPhase1_DoCreateFlatTable(DefaultChainedExecutable jobFlow) { final String cubeName = CubingExecutableUtil.getCubeName(jobFlow.getParams()); final String hiveInitStatements = JoinedFlatTable.generateHiveInitStatements(flatTableDatabase); final String jobWorkingDir = getJobWorkingDir(jobFlow, hdfsWorkingDir); jobFlow.addTask(createFlatHiveTableStep(hiveInitStatements, jobWorkingDir, cubeName, flatDesc)); } protected void addStepPhase1_DoMaterializeLookupTable(DefaultChainedExecutable jobFlow) { final String hiveInitStatements = JoinedFlatTable.generateHiveInitStatements(flatTableDatabase); final String jobWorkingDir = getJobWorkingDir(jobFlow, hdfsWorkingDir); AbstractExecutable task = createLookupHiveViewMaterializationStep(hiveInitStatements, jobWorkingDir, flatDesc, hiveViewIntermediateTables); if (task != null) { jobFlow.addTask(task); } } @Override public void addStepPhase4_Cleanup(DefaultChainedExecutable jobFlow) { final String jobWorkingDir = getJobWorkingDir(jobFlow, hdfsWorkingDir); org.apache.kylin.source.hive.GarbageCollectionStep step = new org.apache.kylin.source.hive.GarbageCollectionStep(); step.setName(ExecutableConstants.STEP_NAME_HIVE_CLEANUP); step.setIntermediateTables(Collections.singletonList(getIntermediateTableIdentity())); step.setExternalDataPaths(Collections.singletonList(JoinedFlatTable.getTableDir(flatDesc, jobWorkingDir))); step.setHiveViewIntermediateTableIdentities(StringUtil.join(hiveViewIntermediateTables, ",")); jobFlow.addTask(step); } @Override public IMRTableInputFormat getFlatTableInputFormat() { return new HiveTableInputFormat(getIntermediateTableIdentity()); } private String getIntermediateTableIdentity() { return flatTableDatabase + "." + flatDesc.getTableName(); } } /** * When build job is created by kylin version 2.4.x or below, the step class name is an inner class of {@link HiveMRInput}, * to avoid the ClassNotFoundException in {@link ExecutableManager#newExecutable(java.lang.String)} , delegate the OLD class to the new one * * @since 2.5.0 * @deprecated For backwards compatibility. */ @Deprecated public static class RedistributeFlatHiveTableStep extends org.apache.kylin.source.hive.RedistributeFlatHiveTableStep { } /** * When build job is created by kylin version 2.4.x or below, the step class name is an inner class of {@link HiveMRInput}, * to avoid the ClassNotFoundException in {@link ExecutableManager#newExecutable(java.lang.String)} , delegate the OLD class to the new one * * @since 2.5.0 * @deprecated For backwards compatibility. */ @Deprecated public static class GarbageCollectionStep extends org.apache.kylin.source.hive.GarbageCollectionStep { } } sys-biz/src/main/java/com/github/fanzezhen/demo/sysbiz/foundation/service/impl/SysDictServiceImpl.java package com.github.fanzezhen.demo.sysbiz.foundation.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.github.fanzezhen.demo.sysbiz.foundation.entity.SysDict; import com.github.fanzezhen.demo.sysbiz.foundation.mapper.SysDictMapper; import com.github.fanzezhen.demo.sysbiz.foundation.service.ISysDictService; import org.springframework.stereotype.Service; /** *

* 字典 服务实现类 *

* * @author fanzezhen * @since 2021-04-28 */ @Service public class SysDictServiceImpl extends ServiceImpl implements ISysDictService { } package com.efp.plugins.project.coder.bean; import java.util.List; /** * @author primerxiao */ public class Mapper { /** * 数据库表名 */ private String tableName; /** * Base_Column_List */ private String baseColumnList; /** * domain类全名 */ private String domainQuaName; /** * dao全名 */ private String daoQuaName; /** * 基础类名 */ private String baseClassName; /** * 类字段信息集合 */ private List classFields; public Mapper() { } public String getBaseColumnList() { return baseColumnList; } public void setBaseColumnList(String baseColumnList) { this.baseColumnList = baseColumnList; } public String getDomainQuaName() { return domainQuaName; } public void setDomainQuaName(String domainQuaName) { this.domainQuaName = domainQuaName; } public String getBaseClassName() { return baseClassName; } public void setBaseClassName(String baseClassName) { this.baseClassName = baseClassName; } public List getClassFields() { return classFields; } public void setClassFields(List classFields) { this.classFields = classFields; } public String getDaoQuaName() { return daoQuaName; } public void setDaoQuaName(String daoQuaName) { this.daoQuaName = daoQuaName; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } } package org.nift4.pluginkeyboard; import java.util.Locale; import android.content.Context; import android.content.res.TypedArray; import android.preference.DialogPreference; import android.util.AttributeSet; import android.view.View; import android.widget.SeekBar; import android.widget.TextView; import GREP_APPID.R; /** * SeekBarPreference provides a dialog for editing float-valued preferences with a slider. */ public class SeekBarPreference extends DialogPreference { private TextView mMinText; private TextView mMaxText; private TextView mValText; private SeekBar mSeek; private float mMin; private float mMax; private float mVal; private float mPrevVal; private float mStep; private boolean mAsPercent; private boolean mLogScale; private String mDisplayFormat; public SeekBarPreference(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } protected void init(Context context, AttributeSet attrs) { setDialogLayoutResource(R.layout.seek_bar_dialog); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SeekBarPreference); mMin = a.getFloat(R.styleable.SeekBarPreference_minValue, 0.0f); mMax = a.getFloat(R.styleable.SeekBarPreference_maxValue, 100.0f); mStep = a.getFloat(R.styleable.SeekBarPreference_step, 0.0f); mAsPercent = a.getBoolean(R.styleable.SeekBarPreference_asPercent, false); mLogScale = a.getBoolean(R.styleable.SeekBarPreference_logScale, false); mDisplayFormat = a.getString(R.styleable.SeekBarPreference_displayFormat); } @Override protected Float onGetDefaultValue(TypedArray a, int index) { return a.getFloat(index, 0.0f); } @Override protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) { if (restorePersistedValue) { setVal(getPersistedFloat(0.0f)); } else { setVal((Float) defaultValue); } savePrevVal(); } private String formatFloatDisplay(Float val) { // Use current locale for format, this is for display only. if (mAsPercent) { return String.format("%d%%", (int) (val * 100)); } if (mDisplayFormat != null) { return String.format(mDisplayFormat, val); } else { return Float.toString(val); } } private void showVal() { mValText.setText(formatFloatDisplay(mVal)); } protected void setVal(Float val) { mVal = val; } protected void savePrevVal() { mPrevVal = mVal; } protected void restoreVal() { mVal = mPrevVal; } protected String getValString() { return Float.toString(mVal); } private float percentToSteppedVal(int percent, float min, float max, float step, boolean logScale) { float val; if (logScale) { val = (float) Math.exp(percentToSteppedVal(percent, (float) Math.log(min), (float) Math.log(max), step, false)); } else { float delta = percent * (max - min) / 100; if (step != 0.0f) { delta = Math.round(delta / step) * step; } val = min + delta; } // Hack: Round number to 2 significant digits so that it looks nicer. val = Float.valueOf(String.format(Locale.US, "%.2g", val)); return val; } private int getPercent(float val, float min, float max) { return (int) (100 * (val - min) / (max - min)); } private int getProgressVal() { if (mLogScale) { return getPercent((float) Math.log(mVal), (float) Math.log(mMin), (float) Math.log(mMax)); } else { return getPercent(mVal, mMin, mMax); } } @Override protected void onBindDialogView(View view) { mSeek = (SeekBar) view.findViewById(R.id.seekBarPref); mMinText = (TextView) view.findViewById(R.id.seekMin); mMaxText = (TextView) view.findViewById(R.id.seekMax); mValText = (TextView) view.findViewById(R.id.seekVal); showVal(); mMinText.setText(formatFloatDisplay(mMin)); mMaxText.setText(formatFloatDisplay(mMax)); mSeek.setProgress(getProgressVal()); mSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { public void onStopTrackingTouch(SeekBar seekBar) {} public void onStartTrackingTouch(SeekBar seekBar) {} public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if (fromUser) { float newVal = percentToSteppedVal(progress, mMin, mMax, mStep, mLogScale); if (newVal != mVal) { onChange(newVal); } setVal(newVal); mSeek.setProgress(getProgressVal()); } showVal(); } }); super.onBindDialogView(view); } public void onChange(float val) { // override in subclasses } @Override public CharSequence getSummary() { return formatFloatDisplay(mVal); } @Override protected void onDialogClosed(boolean positiveResult) { if (!positiveResult) { restoreVal(); return; } if (shouldPersist()) { persistFloat(mVal); savePrevVal(); } notifyChanged(); } } src/main/java/io/choerodon/gateway/filter/authentication/PermissionDisableOrSkipFilter.java package io.choerodon.gateway.filter.authentication; import io.choerodon.gateway.config.GatewayProperties; import io.choerodon.gateway.domain.CheckState; import io.choerodon.gateway.domain.RequestContext; import org.springframework.stereotype.Component; import org.springframework.util.AntPathMatcher; /** * 是否启用权限校验和跳过权限校验路径的过滤器 */ @Component public class PermissionDisableOrSkipFilter implements HelperFilter { private final AntPathMatcher matcher = new AntPathMatcher(); private GatewayProperties gatewayHelperProperties; public PermissionDisableOrSkipFilter(GatewayProperties gatewayHelperProperties) { this.gatewayHelperProperties = gatewayHelperProperties; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter(RequestContext context) { return true; } @Override public boolean run(RequestContext context) { if (!gatewayHelperProperties.getPermission().getEnabled()) { context.response.setStatus(CheckState.SUCCESS_PERMISSION_DISABLED); context.response.setMessage("Permission check disabled"); return false; } if (gatewayHelperProperties.getPermission().getSkipPaths().stream() .anyMatch(t -> matcher.match(t, context.request.uri))) { context.response.setStatus(CheckState.SUCCESS_SKIP_PATH); context.response.setMessage("This request match skipPath, skipPaths: " + gatewayHelperProperties.getPermission().getSkipPaths()); return false; } return true; } } package com.softserveinc.ita.homeproject.homeservice.quartz.jobs; import java.util.List; import com.softserveinc.ita.homeproject.homeservice.dto.CooperationInvitationDto; import com.softserveinc.ita.homeproject.homeservice.dto.InvitationDto; import com.softserveinc.ita.homeproject.homeservice.dto.InvitationTypeDto; import com.softserveinc.ita.homeproject.homeservice.dto.MailDto; import com.softserveinc.ita.homeproject.homeservice.service.CooperationInvitationService; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.springframework.stereotype.Component; @Component @RequiredArgsConstructor public class SendCooperationEmailJob extends BaseEmailJob { private final CooperationInvitationService cooperationInvitationService; @Override @SneakyThrows public void executeAllInvitationsByType() { List invitations = cooperationInvitationService.getAllActiveInvitations(); for (InvitationDto invite : invitations) { mailService.sendTextMessage(createMailDto(invite)); cooperationInvitationService.updateSentDateTimeAndStatus(invite.getId()); } } @Override protected MailDto createMailDto(InvitationDto invitationDto) { CooperationInvitationDto invitation = mapper.convert(invitationDto, CooperationInvitationDto.class); var mailDto = new MailDto(); mailDto.setType(InvitationTypeDto.COOPERATION); mailDto.setId(invitation.getId()); mailDto.setEmail(invitation.getEmail()); mailDto.setRole(invitation.getRole().getName()); mailDto.setCooperationName(invitation.getCooperationName()); checkRegistration(invitation, mailDto); return mailDto; } } coding-interview/src/main/java/io/github/brightloong/leetcode/top/interview/Num27.java package io.github.brightloong.leetcode.top.interview; /** * @author BrightLoong * @date 2020/1/20 17:10 * @description */ public class Num27 { public int removeElement(int[] nums, int val) { if (nums == null) { return 0; } int index = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != val) { nums[index] = nums[i]; index++; } } return index; } public static void main(String[] args) { System.out.println(new Num27().removeElement(new int[]{0,1,2,2,3,0,4,2}, 2)); } } package network.aika.debugger.stepmanager; public enum StepMode { ACT, LINK, VISITOR, DOCUMENT } package xyz.kracker1911.xls2doc.constants; public class Constants { public static String TICKET = "Ticket"; public static String CREATE_TIME = "CreateTime"; public static String EVENT_KEY = "EventKey"; public static String CONTENT = "Content"; public static String EVENT = "Event"; public static String TO_USER_NAME = "ToUserName"; public static String FROM_USER_NAME = "FromUserName"; public static String MESSAGE_TYPE = "MsgType"; //微信公众号推送事件主键 public static String EVENT_SUBSCRIBE = "wx_push_event_subscribe"; public static String EVENT_UNSUBSCRIBE = "wx_push_event_unsubscribe"; public static String EVENT_SCAN = "wx_push_event_scan"; public static String EVENT_CLICK = "wx_push_event_click"; public static String EVENT_TEXT = "wx_push_event_text"; public static String EVENT_DEFAULT = "wx_push_event_default"; } package com.ckenergy.transitionsview.sample; import android.content.Context; import android.view.View; import android.widget.ImageView; import com.ckenergy.transitionsview.transitions.TransitionsHeleper; import com.zhy.adapter.recyclerview.CommonAdapter; import com.zhy.adapter.recyclerview.base.ViewHolder; import java.util.List; public class MyAdapter extends CommonAdapter { public MyAdapter(Context context, int layoutId, List datas) { super(context, layoutId, datas); } @Override protected void convert(final ViewHolder holder, final Integer res, int position) { ((ImageView) holder.itemView.findViewById(R.id.img)).setImageResource(res); holder.setOnClickListener(R.id.img, new View.OnClickListener() { @Override public void onClick(View v) { // mContext.startActivity(new Intent(mContext, RvDetailActivity.class)); TransitionsHeleper.startActivity(mContext, ItemDetailActivity.class, holder.itemView.findViewById(R.id.img)); } }); } } package feon.wirelessredstone.tileentity; import feon.wirelessredstone.init.ModTileEntityTypes; import feon.wirelessredstone.objects.blocks.RedstoneTransmitter; import feon.wirelessredstone.world.RedstoneNetwork; import net.minecraft.block.BlockState; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.TileEntity; public class RedstoneTransmitterTileEntity extends TileEntity { protected int frequency = -1; protected int powerLevel = 0; public RedstoneTransmitterTileEntity() { super(ModTileEntityTypes.REDSTONE_TRANSMITTER.get());; } public void setFrequency(int frequency) { this.frequency = frequency; } public Integer getFrequency() { return this.frequency == -1 ? null : this.frequency; } public void setPowerLevel(int power) { if (frequency == -1 || this.powerLevel == power) { return; } BlockState state = world.getBlockState(this.pos); if (state.getBlock() instanceof RedstoneTransmitter) { state = state.with(RedstoneTransmitter.POWERED, power > 0); world.setBlockState(this.pos, state, 3); } this.powerLevel = power; RedstoneNetwork network = RedstoneNetwork.getNetwork(world); network.setFrequencyValue(frequency, this.powerLevel); network.save(); } public int getPowerFromNetwork() { if (frequency == -1) { powerLevel = 0; return this.powerLevel; } powerLevel = RedstoneNetwork.getNetwork(world).getFrequencyValue(frequency); return this.powerLevel; } private static final String POWER_LEVEL_KEY = "powerLevel"; private static final String FREQUENCY_KEY = "frequency"; @Override public void read(CompoundNBT compound) { super.read(compound); this.powerLevel = compound.getInt(POWER_LEVEL_KEY); this.frequency = compound.getInt(FREQUENCY_KEY); } @Override public CompoundNBT write(CompoundNBT compound) { compound.putInt(FREQUENCY_KEY, this.frequency); compound.putInt(POWER_LEVEL_KEY, this.powerLevel); return super.write(compound); } }0 /* * Copyright (c) 2010-2019 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.repo.common.expression; import javax.xml.namespace.QName; import com.evolveum.midpoint.prism.PrismValue; import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; /** * Represents an expression evaluator (e.g. literal, path, script, assignmentTargetSearch, etc). * Can apply it in given evaluation context. * * @author */ public interface ExpressionEvaluator { /** * Executes the evaluation in a given context. The context provides necessary data, * evaluator provides definition of processing that should be carried out. * * @return Result of the evaluation in the form of delta set triple (i.e. added, deleted, unchanged values). */ PrismValueDeltaSetTriple evaluate(ExpressionEvaluationContext context, OperationResult result) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException; /** * Fully qualified name of the element defining the expression (e.g. c:path). */ QName getElementName(); /** * Short characterization of the evaluator. One line, often only a single word. */ String shortDebugDump(); } /* * 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.broker.transport.commandapi; import io.zeebe.protocol.record.ErrorResponseDecoder; import io.zeebe.protocol.record.MessageHeaderDecoder; import io.zeebe.transport.ServerOutput; import io.zeebe.transport.ServerResponse; import io.zeebe.transport.impl.RequestResponseHeaderDescriptor; import io.zeebe.transport.impl.TransportHeaderDescriptor; import io.zeebe.util.buffer.BufferReader; import io.zeebe.util.buffer.BufferWriter; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.agrona.DirectBuffer; import org.agrona.concurrent.UnsafeBuffer; import org.agrona.sbe.MessageDecoderFlyweight; public class BufferingServerOutput implements ServerOutput { public static final int MESSAGE_START_OFFSET = TransportHeaderDescriptor.HEADER_LENGTH + RequestResponseHeaderDescriptor.HEADER_LENGTH; protected final MessageHeaderDecoder headerDecoder = new MessageHeaderDecoder(); protected final ErrorResponseDecoder errorDecoder = new ErrorResponseDecoder(); protected List sentResponses = new CopyOnWriteArrayList<>(); @Override public boolean sendMessage(int remoteStreamId, BufferWriter writer) { // ignore; not yet implemented return true; } @Override public boolean sendResponse(ServerResponse response) { final UnsafeBuffer buf = new UnsafeBuffer(new byte[response.getLength()]); response.write(buf, 0); sentResponses.add(buf); return true; } public List getSentResponses() { return sentResponses; } public ErrorResponseDecoder getAsErrorResponse(int index) { return getAs(index, errorDecoder); } public void wrapResponse(final int index, final BufferReader reader) { final DirectBuffer buffer = sentResponses.get(index); reader.wrap(buffer, MESSAGE_START_OFFSET, buffer.capacity()); } public int getTemplateId(final int index) { final DirectBuffer sentResponse = sentResponses.get(index); headerDecoder.wrap(sentResponse, MESSAGE_START_OFFSET); return headerDecoder.templateId(); } protected T getAs(int index, T decoder) { final DirectBuffer sentResponse = sentResponses.get(index); headerDecoder.wrap(sentResponse, MESSAGE_START_OFFSET); decoder.wrap( sentResponse, MESSAGE_START_OFFSET + headerDecoder.encodedLength(), headerDecoder.blockLength(), headerDecoder.version()); return decoder; } } package com.ims.sampleproject.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.math.BigDecimal; import java.util.Date; @Entity @Data @AllArgsConstructor @NoArgsConstructor @Table(name = "course_registration") public class CourseRegistration extends BaseEntity { @ManyToOne @JoinColumn(name = "student_id") private Student student; @ManyToOne @JoinColumn(name = "batch_id") private Batch batch; @Column(name = "register_date") private Date registeredDate; @Column(name = "course_fee") private BigDecimal courseFee; @Column(name = "remark") private String remark; } package Telas; import Estrutura.Produto; import Estrutura.User; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; public class Coordinator implements ActionListener { private static Coordinator instance; JMenuItem ver; JMenuItem limpar; JMenuItem logout; private JFrame frame; private static ArrayList users; private static User loggedUser; private ArrayList produtos; private Coordinator(ArrayList users){ this.users = users; frame = new JFrame("Lojinha"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); frame.setJMenuBar(menuBar); JMenu carrinhoMenu = new JMenu("Carrinho"); ver = new JMenuItem("Ver"); ver.addActionListener(this); limpar = new JMenuItem("Limpar"); limpar.addActionListener(this); carrinhoMenu.add(ver); carrinhoMenu.addSeparator(); carrinhoMenu.add(limpar); JMenu perfilMenu = new JMenu("Perfil"); logout = new JMenuItem("Logout"); logout.addActionListener(e -> Coordinator.logout()); perfilMenu.add(logout); menuBar.add(carrinhoMenu); menuBar.add(perfilMenu); Initial initial = new Initial(); initial.setOpaque(true); frame.setContentPane(initial); frame.setVisible(true); frame.setSize( 300, 300 ); } public static void start(ArrayList users){ instance = new Coordinator(users); } public static User getLoggedUser() { return instance.loggedUser; } public static ArrayList getProdutos() { return instance.produtos; } public static void login(String name, String password) throws IOException { for(User user : users){ if(user.getUsername().equals(name) && user.getPassword().equals(password)){ loggedUser = user; String filename = new File("").getAbsolutePath() + "/Programa/src/produtos.txt"; FileReader fileReader = new FileReader(filename); BufferedReader bufferedReader = new BufferedReader(fileReader); List lines = new ArrayList<>(); String line; while ((line = bufferedReader.readLine()) != null) { lines.add(line); } bufferedReader.close(); instance.produtos = new ArrayList<>(); for(String l:lines){ List words = Arrays.asList(l.split(",")); instance.produtos.add(new Produto(words.get(0), Double.parseDouble(words.get(1)), words.get(2))); } goToHomeScreen(); } } } public static void logout() { loggedUser = null; goToInitialScreen(); } public static void signup(String name, String password) throws IOException { String fileName = new File("").getAbsolutePath() + "/Programa/src/usuarios.txt"; BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true)); writer.append("\n"+name+","+password); writer.close(); users.add(new User(name, password)); goToInitialScreen(); } public static void goToSignupScreen() { Signup signup = new Signup(); instance.goTo(signup); } public static void goToHomeScreen() { Home home = new Home(); instance.goTo(home); } public static void goToLoginScren(){ Login login = new Login(new JFrame()); instance.goTo(login); } public static void goToInitialScreen(){ Initial initial = new Initial(); instance.goTo(initial); } public static void goToProdutoScreen(Estrutura.Produto produto){ Telas.Produto produtoScreen = new Telas.Produto(produto); instance.goTo(produtoScreen); } private void goTo(JPanel panel){ frame.setContentPane(panel); frame.invalidate(); frame.validate(); } @Override public void actionPerformed(ActionEvent e) { if(Coordinator.loggedUser != null){ if(e.getSource().equals(ver)) { String prods = ""; for (Map.Entry c : loggedUser.getCarrinho().entrySet()) { prods += (c.getKey() + ": " + c.getValue() + "\n"); } if(prods.equals("")){ prods = "Você ainda não possui produtos no carrinho!"; } JOptionPane.showMessageDialog(null, prods, "Carrinho", JOptionPane.INFORMATION_MESSAGE); } else if (e.getSource().equals(limpar)){ loggedUser.limpaCarrinho(); } } else { Coordinator.goToLoginScren(); } } } package cityfreqs.com.pilfershush.scanners; import android.os.AsyncTask; import android.os.Bundle; import java.util.ArrayList; class FreqDetector { private RecordTask recordTask; private Bundle audioBundle; protected interface RecordTaskListener { void onFailure(String paramString); void onSuccess(int paramInt, int magnitude); } FreqDetector(Bundle audioBundle) { this.audioBundle = audioBundle; } /********************************************************************/ void init() { recordTask = new RecordTask(audioBundle); } void startRecording(RecordTaskListener recordTaskListener) { if (recordTask == null) { recordTask = new RecordTask(audioBundle); } startRecordTaskListener(recordTaskListener); } private void startRecordTaskListener(RecordTaskListener recordTaskListener) { if (recordTask.getStatus() != AsyncTask.Status.RUNNING) { recordTask.setOnResultsListener(recordTaskListener); recordTask.execute(); } } boolean hasBufferStorage() { return (recordTask != null && recordTask.hasBufferStorage()); } ArrayList getBufferStorage() { if (recordTask != null) { return recordTask.getBufferStorage(); } return null; } /********************************************************************/ void stopRecording() { if (recordTask != null) { recordTask.cancel(true); } } void cleanup() { if (recordTask != null) recordTask = null; } } JacobsonMT/Gemma package ubic.gemma.web.services.rest.swagger; import io.swagger.v3.core.converter.ModelConverters; import lombok.extern.apachecommons.CommonsLog; import org.apache.commons.lang3.tuple.Pair; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * Registers all beans defined as {@link CustomModelConverter} to Swagger's {@link io.swagger.v3.core.converter.ModelConverters} * singleton. * * @author poirigui */ @CommonsLog @WebListener public class CustomModelConvertersRegistrationListener implements ServletContextListener { private List> converters = new ArrayList<>(); @Override public void contextInitialized( ServletContextEvent servletContextEvent ) { ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext( servletContextEvent.getServletContext() ); // these must be sorted by ascending precedence because addConverter prepends this.converters = applicationContext.getBeansOfType( CustomModelConverter.class ) .entrySet().stream() .map( Pair::of ) .sorted( Comparator.comparing( pair -> pair.getValue().getPrecedence() ) ) .collect( Collectors.toList() ); for ( Pair converter : converters ) { ModelConverters.getInstance().addConverter( converter.getValue() ); log.info( String.format( "Registered %s to Swagger's custom model converters.", converter.getKey() ) ); } } @Override public void contextDestroyed( ServletContextEvent servletContextEvent ) { for ( Pair converter : converters ) { ModelConverters.getInstance().removeConverter( converter.getValue() ); log.info( String.format( "Unregistered %s to Swagger's custom model converters.", converter.getKey() ) ); } } } albertomv/workcraft package org.workcraft.plugins.petrify.tasks; import org.workcraft.plugins.shared.tasks.ExternalProcessOutput; import org.workcraft.plugins.stg.StgModel; public class PetrifyTransformationOutput extends ExternalProcessOutput { private final StgModel stg; public PetrifyTransformationOutput(ExternalProcessOutput output, StgModel stg) { super(output.getReturnCode(), output.getStdout(), output.getStderr()); this.stg = stg; } public StgModel getStg() { return stg; } } public class Helloword { public static void main(String[] args) { // TODO Auto-generated method stub System.out.print("Hello Worde!\n"); for (int run1 = 0; run1 <=5; run1++) { for (int run2 =5-run1; run2 >=0; run2--) { System.out.print(" "); } for (int run3 = 0; run3 < (run1*2-1); run3++) { System.out.print("*"); } System.out.println(); } } } /* * Copyright (c) 2020. * Created by YoloSanta * Created On 10/22/20, 1:23 AM */ package net.hcriots.hcfactions.team.commands; import cc.fyre.stark.engine.command.Command; import cc.fyre.stark.engine.command.data.parameter.Param; import net.hcriots.hcfactions.Hulu; import net.hcriots.hcfactions.team.Team; import org.bukkit.ChatColor; import org.bukkit.entity.Player; public class ForceJoinCommand { @Command(names = {"ForceJoin"}, permission = "foxtrot.forcejoin") public static void forceJoin(Player sender, @Param(name = "team") Team team, @Param(name = "player", defaultValue = "self") Player player) { if (Hulu.getInstance().getTeamHandler().getTeam(player) != null) { if (player == sender) { sender.sendMessage(ChatColor.RED + "Leave your current team before attempting to forcejoin."); } else { sender.sendMessage(ChatColor.RED + "That player needs to leave their current team first!"); } return; } team.addMember(player.getUniqueId()); Hulu.getInstance().getTeamHandler().setTeam(player.getUniqueId(), team); player.sendMessage(ChatColor.YELLOW + "You are now a member of " + ChatColor.LIGHT_PURPLE + team.getName() + ChatColor.YELLOW + "!"); if (player != sender) { sender.sendMessage(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.YELLOW + " added to " + ChatColor.LIGHT_PURPLE + team.getName() + ChatColor.YELLOW + "!"); } } }package interpres.language.definitions.interpres; import java.util.List; import java.util.ArrayList; import interpres.ast.AST; import interpres.ast.Symbol; import interpres.ast.StringValue; import interpres.ast.LambdaExpression; import interpres.language.definitions.Definition; public class StringToSymbol extends Definition { public StringToSymbol() { super("interpres/string-to-symbol", new LambdaExpression((definitionTable, arguments) -> { StringValue stringValue = (StringValue) arguments.get(0).evaluate(definitionTable); return new Symbol(stringValue.getLiteral()); })); } } service-management-gateway/src/main/java/fr/service/management/components/GatewayZookeeper.java package fr.service.management.components; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.StringTokenizer; import java.util.UUID; import javax.annotation.PostConstruct; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Value; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /* * 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. */ /** * * @author zouhairhajji */ @Component public class GatewayZookeeper { @Value("${zookeeper.hosts}") private String hosts; private final static Logger logger = Logger.getLogger(GatewayZookeeper.class); private List curatorFrameworks; @PostConstruct public void postConstruct() { this.curatorFrameworks = new ArrayList<>(); for (StringTokenizer stringTokenizer = new StringTokenizer(hosts); stringTokenizer.hasMoreTokens();) { String host = stringTokenizer.nextToken(); CuratorFramework curatorFramework = CuratorFrameworkFactory.builder() .connectString(host) .retryPolicy(new ExponentialBackoffRetry(1000, 3)) .namespace(UUID.randomUUID().toString()) .build(); curatorFramework.start(); this.curatorFrameworks.add(curatorFramework); } } public Optional getRandomCuratorFramework() { Optional anyCuratorFramework = this.curatorFrameworks .stream() .filter(cf -> cf.getZookeeperClient().isConnected()) .findAny(); return anyCuratorFramework; } @Scheduled(fixedDelay = 1000 * 10) public void printCheckedState(){ for (CuratorFramework curatorFramework : curatorFrameworks) { System.out.println("-> " + curatorFramework.getNamespace()); System.out.println(" state :> " + curatorFramework.getZookeeperClient().isConnected()); } } @Scheduled(fixedDelay = 1000 ) public void getStartedInstance(){ Optional optional = this.getRandomCuratorFramework(); System.out.println("Started Instance is : " + optional.get()); } } Haelles/JavaCourseDesign package com.base; import java.awt.event.KeyEvent; import java.util.concurrent.CopyOnWriteArraySet; public enum Command { //按键枚举类 // UP, DOWN, LEFT, RIGHT, ATTACK, JUMP, MENU, PAUSE, RESTART, QUIT, BACK, START, KEY, DEVELOP, HOME UP(KeyEvent.VK_W), DOWN(KeyEvent.VK_S), LEFT(KeyEvent.VK_A), RIGHT(KeyEvent.VK_D), ATTACK(KeyEvent.VK_J), JUMP(KeyEvent.VK_K), MENU(KeyEvent.VK_M), PAUSE(KeyEvent.VK_M), BACK(KeyEvent.VK_B), RESTART(KeyEvent.VK_R), QUIT(KeyEvent.VK_Q), HOME(KeyEvent.VK_H), END(KeyEvent.VK_E); public final static CopyOnWriteArraySet keySet = new CopyOnWriteArraySet<>(); public int keyValue; Command(int vkW){ this.keyValue = vkW; } public boolean use(){ return keySet.contains(keyValue); } public static void add(int keyCode){ keySet.add(keyCode); } public static void remove(int keyCode){ keySet.remove(keyCode); } } package main.java.ir.loghme.controller.handler; import io.javalin.http.Context; import io.javalin.http.Handler; import main.java.ir.loghme.controller.WebServer; import main.java.ir.loghme.controller.command.GetUser; import main.java.ir.loghme.model.User; import main.java.ir.loghme.model.util.FileManipulator; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.util.ArrayList; public class GetUserHandler extends GetUser implements Handler { private String prefix ; private String postfix; public GetUserHandler(ArrayList users) throws IOException { super(users); FileManipulator fm = new FileManipulator(); prefix = fm.readFile(fm.openFileFromResources("user_prefix.html")); postfix = fm.readFile(fm.openFileFromResources("user_postfix.html")); } @Override public void handle(@NotNull Context context) throws Exception { User user = null; try { user = execute("09118115063"); } catch (ClassCastException e) { context.status(WebServer.HTTP_BADـREQUEST); context.result(e.getMessage()); return; } String userInfo = "
    \n" + "
  • id: " + user.getId() + "
  • \n" + "
  • full name: " + user.getFirstName() + " " + user.getLastName() + "
  • \n" + "
  • phone number: " + user.getPhoneNumber() + "
  • \n" + "
  • email: " + user.getEmail() + "
  • \n" + "
  • credit: " + user.getCredit() + " Toman
  • \n" + "
    \n" + " \n" + " \n" + "
    \n" + "
"; context.html(prefix + userInfo + postfix); } } package ca.ftcalberta.rrlivescore.models; public class JewelSet { private static final int JEWEL_SCORE = 30; private boolean redIsOnPlatform; private boolean blueIsOnPlatform; private int redScore = 0; private int blueScore = 0; private int redCount = 0; private int blueCount = 0; public JewelSet() { redIsOnPlatform = true; blueIsOnPlatform = true; } public JewelSet(boolean redOnPlatform, boolean blueOnPlatform) { this.redIsOnPlatform = redOnPlatform; this.blueIsOnPlatform = blueOnPlatform; updateScore(); } public boolean isOnPlatform(Alliance alliance) { if (alliance.isRed()) { return redIsOnPlatform; } else if (alliance.isBlue()) { return blueIsOnPlatform; } return false; } public void toggleJewel(Alliance alliance) { if (alliance.isRed()) { redIsOnPlatform = !redIsOnPlatform; } else if (alliance.isBlue()) { blueIsOnPlatform = !blueIsOnPlatform; } updateScore(); } protected void updateScore() { redScore = redIsOnPlatform && !blueIsOnPlatform ? JEWEL_SCORE : 0; blueScore = blueIsOnPlatform && !redIsOnPlatform ? JEWEL_SCORE : 0; redCount = redIsOnPlatform && !blueIsOnPlatform ? 1 : 0; blueCount = blueIsOnPlatform && !redIsOnPlatform ? 1 : 0; } public int getRedScore() { return redScore; } public int getBlueScore() { return blueScore; } public int getRedCount() { return redCount; } public int getBlueCount() { return blueCount; } public void reset() { redIsOnPlatform = true; blueIsOnPlatform = true; updateScore(); } } package org.etherpad_lite_client; public class EPLiteException extends RuntimeException { public EPLiteException(String msg) { super(msg); } } CourseRecommenderRuleMiner/src/main/java/se/uu/it/cs/recsys/ruleminer/util/Util.java package se.uu.it.cs.recsys.ruleminer.util; /* * #%L * CourseRecommenderRuleMiner * %% * Copyright (C) 2015 < > * %% * 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. * #L% */ import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import se.uu.it.cs.recsys.ruleminer.datastructure.Item; /** * * @author <> */ public class Util { private static final Logger LOGGER = LoggerFactory.getLogger(Util.class); public static Set findDuplicatesIndexes(List list, T elem) { Set idxSet = new HashSet<>(); for (int i = 0; i < list.size(); i++) { if (list.get(i).equals(elem)) { idxSet.add(i); } } return idxSet; } /** * * @param the type of the element in the list * @param source source list * @param target the target to look for * @return 0 based index of the position where the target occurs in the list * for the first time; or -1 if no such position is found */ public static int findIndex(List source, T target) { int matchingIdx = -1; int i = 0; for (T elem : source) { if (elem.equals(target)) { matchingIdx = i; break; } i++; } return matchingIdx; } /** * Generate a new list containing the items in both source list and * reference list; but sorted according to the order in reference list. * * @param source the source list * @param referenceOrder the reference list which has ordered items * @return a new list containing ordered items */ public static List reorderListAccordingToRef(List source, List referenceOrder) { Map orderedMap = new TreeMap<>(); source.forEach((Integer target) -> { int idx = findIndex(source, target); if (idx == -1) { LOGGER.error("target : {} is not in the ref list: {}", target, source); } else { orderedMap.put(idx, target); } }); return orderedMap.entrySet().stream().map((Map.Entry entry) -> entry.getValue()).collect(Collectors.toList()); } public static Map filter(Map idAndCount, Integer threshold) { return idAndCount .entrySet() .stream() .filter(entry -> entry.getValue() >= threshold) .collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())); } public static Set> removeEmptySet(Set> source) { return source.stream().filter((Set set) -> (!set.isEmpty())).collect(Collectors.toSet()); } } aspose-omr-cloud/aspose-omr-cloud-java package com.aspose.omrdemo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.widget.EditText; import android.widget.TextView; public class ViewResultActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_result); TextView tvResult = (TextView) findViewById(R.id.tvResult); tvResult.setMovementMethod(new ScrollingMovementMethod()); Bundle b = getIntent().getExtras(); tvResult.setText(b.getString("result")); } } /* * 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.android.servicestests.apps.conntestapp; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.INetworkPolicyManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.INetworkManagementService; import android.os.Process; import android.os.RemoteException; import android.os.ServiceManager; import android.util.Log; import com.android.internal.annotations.GuardedBy; import com.android.servicestests.aidl.INetworkStateObserver; public class ConnTestActivity extends Activity { private static final String TAG = ConnTestActivity.class.getSimpleName(); private static final String TEST_PKG = ConnTestActivity.class.getPackage().getName(); private static final String ACTION_FINISH_ACTIVITY = TEST_PKG + ".FINISH"; private static final String EXTRA_NETWORK_STATE_OBSERVER = TEST_PKG + ".observer"; private static final Object INSTANCE_LOCK = new Object(); @GuardedBy("instanceLock") private static Activity sInstance; private BroadcastReceiver finishCommandReceiver = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); synchronized (INSTANCE_LOCK) { sInstance = this; } Log.i(TAG, "onCreate called"); notifyNetworkStateObserver(); finishCommandReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "finish command received"); ConnTestActivity.this.finish(); } }; registerReceiver(finishCommandReceiver, new IntentFilter(ACTION_FINISH_ACTIVITY)); } @Override public void onResume() { super.onResume(); Log.i(TAG, "onResume called"); } @Override public void onStop() { Log.i(TAG, "onStop called"); if (finishCommandReceiver != null) { unregisterReceiver(finishCommandReceiver); finishCommandReceiver = null; } super.onStop(); } @Override public void finish() { synchronized (INSTANCE_LOCK) { sInstance = null; } Log.i(TAG, "finish called"); super.finish(); } public static void finishSelf() { synchronized (INSTANCE_LOCK) { if (sInstance != null) { sInstance.finish(); } } } private void notifyNetworkStateObserver() { if (getIntent() == null) { return; } final Bundle extras = getIntent().getExtras(); if (extras == null) { return; } final INetworkStateObserver observer = INetworkStateObserver.Stub.asInterface( extras.getBinder(EXTRA_NETWORK_STATE_OBSERVER)); if (observer != null) { AsyncTask.execute(() -> { try { observer.onNetworkStateChecked(checkNetworkStatus()); } catch (RemoteException e) { Log.e(TAG, "Error occured while notifying the observer: " + e); } }); } } /** * Checks whether the network is restricted. * * @return null if network is not restricted, otherwise an error message. */ private String checkNetworkStatus() { final INetworkManagementService nms = INetworkManagementService.Stub.asInterface( ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE)); final INetworkPolicyManager npms = INetworkPolicyManager.Stub.asInterface( ServiceManager.getService(Context.NETWORK_POLICY_SERVICE)); try { final boolean restrictedByFwRules = nms.isNetworkRestricted(Process.myUid()); final boolean restrictedByUidRules = npms.isUidNetworkingBlocked(Process.myUid(), true); if (restrictedByFwRules || restrictedByUidRules) { return "Network is restricted by fwRules: " + restrictedByFwRules + " and uidRules: " + restrictedByUidRules; } return null; } catch (RemoteException e) { return "Error talking to system server: " + e; } } }/* * @lc app=leetcode id=542 lang=java * * [542] 01 Matrix * * https://leetcode.com/problems/01-matrix/description/ * * algorithms * Medium (41.79%) * Likes: 2906 * Dislikes: 143 * Total Accepted: 154.7K * Total Submissions: 362.3K * Testcase Example: '[[0,0,0],[0,1,0],[0,0,0]]' * * Given an m x n binary matrix mat, return the distance of the nearest 0 for * each cell. * * The distance between two adjacent cells is 1. * * * Example 1: * * * Input: mat = [[0,0,0],[0,1,0],[0,0,0]] * Output: [[0,0,0],[0,1,0],[0,0,0]] * * * Example 2: * * * Input: mat = [[0,0,0],[0,1,0],[1,1,1]] * Output: [[0,0,0],[0,1,0],[1,2,1]] * * * * Constraints: * * * m == mat.length * n == mat[i].length * 1 <= m, n <= 10^4 * 1 <= m * n <= 10^4 * mat[i][j] is either 0 or 1. * There is at least one 0 in mat. * * */ // @lc code=start class Solution { public int[][] updateMatrix(int[][] matrix) { if (matrix.length == 0 || matrix[0].length == 0) { return matrix; } int[][] dis = new int[matrix.length][matrix[0].length]; int range = matrix.length * matrix[0].length; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { if (matrix[i][j] == 0) { dis[i][j] = 0; } else { int upCell = (i > 0) ? dis[i - 1][j] : range; int leftCell = (j > 0) ? dis[i][j - 1] : range; dis[i][j] = Math.min(upCell, leftCell) + 1; } } } for (int i = matrix.length - 1; i >= 0; i--) { for (int j = matrix[0].length - 1; j >= 0; j--) { if (matrix[i][j] == 0) { dis[i][j] = 0; } else { int downCell = (i < matrix.length - 1) ? dis[i + 1][j] : range; int rightCell = (j < matrix[0].length - 1) ? dis[i][j + 1] : range; dis[i][j] = Math.min(Math.min(downCell, rightCell) + 1, dis[i][j]); } } } return dis; } } // @lc code=end andeersoon/orientacao-objetos-java package aula02.entities; public class Triangle { // atributos da classe public double a; public double b; public double c; } 0 package com.stupid.hipchat; import android.app.Activity; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.os.Vibrator; import android.speech.tts.TextToSpeech; import android.support.v4.app.Fragment; import android.support.v4.app.NotificationCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.util.TypedValue; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.github.nkzawa.emitter.Emitter; import com.github.nkzawa.socketio.client.IO; import com.github.nkzawa.socketio.client.Socket; import org.json.JSONException; import org.json.JSONObject; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; /** * A chat fragment containing messages view and input form. */ public class MainFragment extends Fragment { private static final String TAG = "MainFragment"; private static final int NOTIFICATION_ID = 1; private static final int REQUEST_LOGIN = 0; private static final int TYPING_TIMER_LENGTH = 600; private SensorManager mSensorManager; private SensorEventListener mShakira; private SensorEventListener mShakiraJump; private NotificationManager mNotificationManager; private Vibrator mVibrator; private Timer mSensorLockTimer; private boolean mSensorLocked = false; private TextToSpeech mTextToSpeech; private RecyclerView mMessagesView; private EditText mInputMessageView; private ViewGroup mInputMorseView; private List mMessages = new ArrayList(); private RecyclerView.Adapter mAdapter; private boolean mTyping = false; private Handler mTypingHandler = new Handler(); private String mUsername; private Socket mSocket; { try { mSocket = IO.socket("http://hipsdontlie.herokuapp.com"); } catch (URISyntaxException e) { throw new RuntimeException(e); } } public MainFragment() { super(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); mAdapter = new MessageAdapter(activity, mMessages); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE); mVibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE); mSensorLockTimer = new Timer(); mShakira = new Shakira(); mShakiraJump = new ShakiraJump(); mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE); setHasOptionsMenu(true); mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError); mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError); mSocket.on("new message", onNewMessage); mSocket.on("user joined", onUserJoined); mSocket.on("user left", onUserLeft); mSocket.on("typing", onTyping); mSocket.on("stop typing", onStopTyping); mSocket.connect(); startSignIn(); mTextToSpeech = new TextToSpeech(getActivity(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { // Assume success for the hackathon } }); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_main, container, false); } @Override public void onDestroy() { super.onDestroy(); mSocket.disconnect(); mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError); mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError); mSocket.off("new message", onNewMessage); mSocket.off("user joined", onUserJoined); mSocket.off("user left", onUserLeft); mSocket.off("typing", onTyping); mSocket.off("stop typing", onStopTyping); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mMessagesView = (RecyclerView) view.findViewById(R.id.messages); mMessagesView.setLayoutManager(new LinearLayoutManager(getActivity())); mMessagesView.setAdapter(mAdapter); mInputMessageView = (EditText) view.findViewById(R.id.message_input); mInputMessageView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int id, KeyEvent event) { if (id == R.id.send || id == EditorInfo.IME_NULL) { attemptSend(); return true; } return false; } }); mInputMessageView.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (null == mUsername) return; if (!mSocket.connected()) return; if (!mTyping) { mTyping = true; mSocket.emit("typing"); } mTypingHandler.removeCallbacks(onTypingTimeout); mTypingHandler.postDelayed(onTypingTimeout, TYPING_TIMER_LENGTH); } @Override public void afterTextChanged(Editable s) { } }); mInputMorseView = (ViewGroup) view.findViewById(R.id.chat_morse); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (Activity.RESULT_OK != resultCode) { getActivity().finish(); return; } mUsername = data.getStringExtra("username"); int numUsers = data.getIntExtra("numUsers", 1); addLog(getResources().getString(R.string.message_welcome)); addParticipantsLog(numUsers); // Init sensors mSensorLockTimer.schedule(new TimerTask() { @Override public void run() { mSensorManager.registerListener(mShakira, mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_NORMAL); mSensorManager.registerListener(mShakiraJump, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL); mTextToSpeech.speak("Shake it!", TextToSpeech.QUEUE_ADD, null); } }, 5000); } @Override public void onPause() { super.onPause(); mSensorManager.unregisterListener(mShakira); mSensorManager.unregisterListener(mShakiraJump); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. inflater.inflate(R.menu.menu_main, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_leave) { leave(); return true; } return super.onOptionsItemSelected(item); } private void addLog(String message) { mMessages.add(new Message.Builder(Message.TYPE_LOG) .message(message).build()); mAdapter.notifyItemInserted(mMessages.size() - 1); scrollToBottom(); } private void addParticipantsLog(int numUsers) { addLog(getResources().getQuantityString(R.plurals.message_participants, numUsers, numUsers)); } private void addMessage(String username, String message) { mMessages.add(new Message.Builder(Message.TYPE_MESSAGE) .username(username, username.equalsIgnoreCase(mUsername)).message(message).build()); mAdapter.notifyItemInserted(mMessages.size() - 1); scrollToBottom(); } private void addTyping(String username) { mMessages.add(new Message.Builder(Message.TYPE_ACTION) .username(username, username.equalsIgnoreCase(mUsername)).build()); mAdapter.notifyItemInserted(mMessages.size() - 1); scrollToBottom(); } private void removeTyping(String username) { for (int i = mMessages.size() - 1; i >= 0; i--) { Message message = mMessages.get(i); if (message.getType() == Message.TYPE_ACTION && message.getUsername().equals(username)) { mMessages.remove(i); mAdapter.notifyItemRemoved(i); } } } private boolean attemptSend() { if (null == mUsername) return false; if (!mSocket.connected()) return false; mTyping = false; String message = mInputMessageView.getText().toString().trim(); if (TextUtils.isEmpty(message)) { mInputMessageView.requestFocus(); return false; } mInputMessageView.setText(""); addMessage(mUsername, message); // perform the sending message attempt. mSocket.emit("new message", message); return true; } private void startSignIn() { mUsername = null; Intent intent = new Intent(getActivity(), LoginActivity.class); startActivityForResult(intent, REQUEST_LOGIN); } private void leave() { mUsername = null; mSocket.disconnect(); mSocket.connect(); startSignIn(); } private void scrollToBottom() { mMessagesView.scrollToPosition(mAdapter.getItemCount() - 1); } private Emitter.Listener onConnectError = new Emitter.Listener() { @Override public void call(Object... args) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(getActivity().getApplicationContext(), R.string.error_connect, Toast.LENGTH_LONG).show(); } }); } }; private Emitter.Listener onNewMessage = new Emitter.Listener() { @Override public void call(final Object... args) { JSONObject data = (JSONObject) args[0]; final String username; final String message; try { username = data.getString("username"); message = data.getString("message"); } catch (JSONException e) { return; } if (!mUsername.equalsIgnoreCase(username)) { Activity activity = getActivity(); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(activity) .setSmallIcon(R.drawable.logo) .setContentTitle("New shake from " + username) .setContentText(message); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } getActivity().runOnUiThread(new Runnable() { @Override public void run() { removeTyping(username); addMessage(username, message); } }); } }; private Emitter.Listener onUserJoined = new Emitter.Listener() { @Override public void call(final Object... args) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { JSONObject data = (JSONObject) args[0]; String username; int numUsers; try { username = data.getString("username"); numUsers = data.getInt("numUsers"); } catch (JSONException e) { return; } addLog(getResources().getString(R.string.message_user_joined, username)); addParticipantsLog(numUsers); } }); } }; private Emitter.Listener onUserLeft = new Emitter.Listener() { @Override public void call(final Object... args) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { JSONObject data = (JSONObject) args[0]; String username; int numUsers; try { username = data.getString("username"); numUsers = data.getInt("numUsers"); } catch (JSONException e) { return; } addLog(getResources().getString(R.string.message_user_left, username)); addParticipantsLog(numUsers); removeTyping(username); } }); } }; private Emitter.Listener onTyping = new Emitter.Listener() { @Override public void call(final Object... args) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { JSONObject data = (JSONObject) args[0]; String username; try { username = data.getString("username"); } catch (JSONException e) { return; } addTyping(username); } }); } }; private Emitter.Listener onStopTyping = new Emitter.Listener() { @Override public void call(final Object... args) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { JSONObject data = (JSONObject) args[0]; String username; try { username = data.getString("username"); } catch (JSONException e) { return; } removeTyping(username); } }); } }; private Runnable onTypingTimeout = new Runnable() { @Override public void run() { if (!mTyping) return; mTyping = false; mSocket.emit("stop typing"); } }; private void startLock(int duration) { mSensorLocked = true; mSensorLockTimer.schedule(new TimerTask() { @Override public void run() { mSensorLocked = false; } }, duration); } private ImageView createMorseImage(boolean isDash) { ImageView morseImage = new ImageView(getActivity()); Resources r = getResources(); int paddingPixels = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, r.getDisplayMetrics()); morseImage.setPadding(paddingPixels, 0, paddingPixels, 0); if (isDash) { morseImage.setImageResource(R.drawable.dash); } else { morseImage.setImageResource(R.drawable.dot); } return morseImage; } private void addMorse(char morse) { boolean isDash = morse == '-'; mInputMorseView.addView(createMorseImage(isDash)); } private void clearMorse() { mInputMorseView.removeAllViews(); } private void playDing() { MediaPlayer mp = MediaPlayer.create(getActivity(), R.raw.ding2); mp.start(); } private class Shakira implements SensorEventListener{ private float x = 0; private float y = 0; private MorseCodeTranslator translator; private static final float SIDE_THRESHOLD = 1.25f; private static final float BACK_THRESHOLD = 1f; private static final int SIDE_DURATION = 750; private static final int BACK_DURATION = 1000; public Shakira() { translator = new MorseCodeTranslator(); } @Override public void onSensorChanged(SensorEvent event) { x = event.values[0]; y = event.values[1]; // Do stuff if (y > SIDE_THRESHOLD && !mSensorLocked) { shakeRight(); } else if (y < -SIDE_THRESHOLD && !mSensorLocked) { shakeLeft(); } else if (x > BACK_THRESHOLD && !mSensorLocked) { backThrust(); } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Do nothing } private void shakeRight() { Log.d(TAG, "-"); translator.collect('-'); mVibrator.vibrate(500); notifyCollection(); startLock(SIDE_DURATION); } private void shakeLeft() { Log.d(TAG, "."); translator.collect('.'); mVibrator.vibrate(250); notifyCollection(); startLock(SIDE_DURATION); } private void backThrust() { String letter = translator.getTranslation(true); Log.d(TAG, letter == null ? "null" : letter); if (letter != null) { mInputMessageView.append(letter); mTextToSpeech.speak(letter, TextToSpeech.QUEUE_ADD, null); mVibrator.vibrate(new long[] {0, 100, 100, 100}, -1); clearMorse(); } startLock(BACK_DURATION); } private void notifyCollection() { String morseCollection = translator.getMorseCollection(); addMorse(morseCollection.charAt(morseCollection.length() - 1)); } } private class ShakiraJump implements SensorEventListener { private static final int JUMP_LOCK_DURATION = 1500; private float lastY = 0f; @Override public void onSensorChanged(SensorEvent event) { float y = event.values[1]; float yDelta = Math.abs(y - lastY); // The accelerometer takes gravity into account, so if we have a near-zero acceleration in the y direction, // we must be near the precipice of a jump if (y < 1 && yDelta > 0.15f && !mSensorLocked) { Log.d(TAG, "SEND, " + y); clearMorse(); boolean sent = attemptSend(); if (sent) { playDing(); } else { mVibrator.vibrate(1000); } startLock(JUMP_LOCK_DURATION); } lastY = y; } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { // Do nothing } } } 1-10 package com.gosun.xone.core.controller; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.gosun.common.XoneException; import com.gosun.common.Result; import com.gosun.common.Util; import com.gosun.xone.core.entity.PersonRelations; import com.gosun.xone.core.service.PersonRelationsService; @RestController @RequestMapping("/admin/person-relations") public class PersonRelationsController { @Autowired private PersonRelationsService personRelationsService; @RequestMapping("/create") public Result create(@RequestBody PersonRelations personRelations){ personRelationsService.create(personRelations); return Result.success(personRelations); } @RequestMapping("/find-all") public Result findAll(@RequestBody String content) throws IOException, XoneException{ Pageable pageable = Util.parse(content); Page result = personRelationsService.findAll(pageable); return Result.success(result, result.getContent()); } @RequestMapping("find-by-id/{relationsId}") public Result findById(@PathVariable("relationsId") Long relationsId){ PersonRelations result = personRelationsService.findById(relationsId); return Result.success(result); } @RequestMapping("delete-by-id/{relationsId}") public Result delete(@PathVariable("relationsId") Long relationsId){ personRelationsService.delete(relationsId); return Result.success(relationsId); } } Olhcim/BSP-Procedurally-Generated-Game package worldchunkgen; class Player { public double x,y; public Player(double x, double y) { this.x = x; this.y = y; } } package org.amc.game.chess; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; @RunWith(Parameterized.class) public class PawnIsNotPromotedTest { private ChessGame chessGame; private ChessBoard board; private ChessPiece piece; private ChessMoveRule promotion; private Move move; public PawnIsNotPromotedTest(ChessPiece piece, Move move) { this.piece = piece; this.move = move; } @Before public void setUp() throws Exception { ChessGamePlayer whitePlayer = new RealChessGamePlayer(new HumanPlayer("White Player"), Colour.WHITE); ChessGamePlayer blackPlayer = new RealChessGamePlayer(new HumanPlayer("Black Player"), Colour.BLACK); this.promotion = PawnPromotionRule.getInstance(); this.chessGame = new ChessGame(new ChessBoard(), whitePlayer, blackPlayer); this.board = this.chessGame.getChessBoard(); } @Parameters public static Collection addedChessPieces() { return Arrays.asList(new Object[][] { { PawnPiece.getPiece(Colour.WHITE), new Move("A2-A1") }, { PawnPiece.getPiece(Colour.WHITE), new Move("H2-H1") }, { PawnPiece.getPiece(Colour.BLACK), new Move("A7-A8") }, //invalid move for a pawn { PawnPiece.getPiece(Colour.BLACK), new Move("A7-A1") }}); } @Test public void test() { board.put(piece, move.getStart()); assertFalse("Move should not lead to promotion", promotion.isRuleApplicable(chessGame, move)); promotion.applyRule(chessGame, move); assertEquals(piece, board.get(move.getStart())); } } /* * This file is a part of MI * * The MIT License (MIT) * * Copyright (c) 2021 Roj234 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package roj.net.tcp.serv; import roj.collect.TimedHashMap; import roj.concurrent.task.ITask; import roj.io.NonblockingUtil; import roj.net.tcp.TCPServer; import roj.net.tcp.serv.util.ChannelRouter; import roj.net.tcp.util.InsecureSocket; import roj.net.tcp.util.SecureSocket; import roj.net.tcp.util.WrappedSocket; import java.io.FileDescriptor; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.security.GeneralSecurityException; import java.util.concurrent.atomic.AtomicInteger; public class HttpServer extends TCPServer { public static final boolean THROTTLING_CHECK_ENABLED = false; public static final TimedHashMap CONNECTING_ADDRESSES = new TimedHashMap<>(1000); protected final Router router; public HttpServer(int port, int maxConnection, Router router, String keyStoreFile, char[] keyPassword) throws IOException, GeneralSecurityException { this(new InetSocketAddress(port), maxConnection, router, keyStoreFile, keyPassword); } public HttpServer(InetSocketAddress address, int maxConnection, Router router, String keyStoreFile, char[] keyPassword) throws IOException, GeneralSecurityException { super(address, maxConnection, keyStoreFile, keyPassword); this.router = router; } public HttpServer(int port, int maxConnection, Router router) throws IOException { this(new InetSocketAddress(port), maxConnection, router); } public HttpServer(InetSocketAddress address, int maxConnection, Router router) throws IOException { super(address, maxConnection); this.router = router; } @Override protected ITask getTaskFor(Socket client) throws IOException { FileDescriptor fd = NonblockingUtil.fd(client); WrappedSocket cio = ( ssl != null ? SecureSocket.get(client, fd, ssl, false) : new InsecureSocket(client, fd) ); return new ChannelRouter(cio, router); } } /** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 io.gravitee.repository.jdbc.management; import static io.gravitee.repository.jdbc.common.AbstractJdbcRepositoryConfiguration.escapeReservedWord; import io.gravitee.repository.exceptions.TechnicalException; import io.gravitee.repository.jdbc.orm.JdbcObjectMapper; import io.gravitee.repository.management.api.PortalNotificationRepository; import io.gravitee.repository.management.model.PortalNotification; import java.sql.Types; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Repository; /** * * @author njt */ @Repository public class JdbcPortalNotificationRepository extends JdbcAbstractCrudRepository implements PortalNotificationRepository { private static final Logger LOGGER = LoggerFactory.getLogger(JdbcPortalNotificationRepository.class); JdbcPortalNotificationRepository(@Value("${management.jdbc.prefix:}") String tablePrefix) { super(tablePrefix, "portal_notifications"); } @Override protected JdbcObjectMapper buildOrm() { return JdbcObjectMapper .builder(PortalNotification.class, this.tableName, "id") .addColumn("id", Types.NVARCHAR, String.class) .addColumn("title", Types.NVARCHAR, String.class) .addColumn("message", Types.NVARCHAR, String.class) .addColumn("user", Types.NVARCHAR, String.class) .addColumn("created_at", Types.TIMESTAMP, Date.class) .build(); } @Override protected String getId(PortalNotification item) { return item.getId(); } @Override public List findByUser(String user) throws TechnicalException { LOGGER.debug("JdbcPortalNotificationRepository.findByUser({})", user); try { List items = jdbcTemplate.query( getOrm().getSelectAllSql() + " where " + escapeReservedWord("user") + " = ?", getRowMapper(), user ); return items; } catch (final Exception ex) { final String message = "Failed to find notifications by user"; LOGGER.error(message, ex); throw new TechnicalException(message, ex); } } @Override public void create(List notifications) throws TechnicalException { for (PortalNotification notification : notifications) { this.create(notification); } } @Override public void deleteAll(String user) throws TechnicalException { LOGGER.debug("JdbcPortalNotificationRepository.deleteAll({})", user); try { jdbcTemplate.update("delete from " + this.tableName + " where " + escapeReservedWord("user") + " = ?", user); } catch (final Exception ex) { final String message = "Failed to delete notifications by user"; LOGGER.error(message, ex); throw new TechnicalException(message, ex); } } } src/orbitSimulator/SolarSystemDatabase.java package orbitSimulator; import java.util.HashMap; import java.util.Map; public class SolarSystemDatabase { public HashMap getSolarSystemObjectInformation(String object) { Object returnObject = null; switch(object) { case "earth": returnObject = earth; break; case "moon": returnObject = moon; break; case "mars": returnObject = mars; break; } if(returnObject == null) { // error handling } return (HashMap) returnObject; } private static final Map earth; static { earth = new HashMap(); earth.put("radius", (double) 6317); earth.put("mu", (double) 398600); earth.put("atmosphereRadius", (double) 6517); earth.put("SOI", (double) 924000); } private static final Map moon; static { moon = new HashMap(); moon.put("radius", (double) 1737); moon.put("mu", (double) 4902.8); moon.put("atmosphereRadius", (double) 0); moon.put("SOI", (double) 66100); } private static final Map mars; static { mars = new HashMap(); mars.put("radius", (double) 3396); mars.put("mu", (double) 42828); mars.put("atmosphereRadius", (double) 3550); mars.put("SOI", (double) 576000); } } dmitrievanthony/chash /* * 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 com.dmitrievanthony.chash.router; import com.dmitrievanthony.chash.hash.Hasher; import java.util.Arrays; public class ConsistentHashingRouter implements Hasher { private final Hasher hasher; private final int numberOfNodes; private final int segmentsPerNode; private final int[] ring; private final int[] nodes; public ConsistentHashingRouter(Hasher hasher, int numberOfNodes) { this(hasher, numberOfNodes, 64); } public ConsistentHashingRouter(Hasher hasher, int numberOfNodes, int segmentsPerNode) { this.hasher = hasher; this.numberOfNodes = numberOfNodes; this.segmentsPerNode = segmentsPerNode; this.ring = new int[numberOfNodes * segmentsPerNode]; this.nodes = new int[numberOfNodes * segmentsPerNode]; for (int i = 0; i < numberOfNodes; i++) { for (int j = 0; j < segmentsPerNode; j++) { ring[i * segmentsPerNode + j] = hasher.calculate(i * segmentsPerNode + j); nodes[i * segmentsPerNode + j] = i; } } qsort(ring, nodes); } @Override public int calculate(int key) { int hash = hasher.calculate(key); int idx = Arrays.binarySearch(ring, hash); if (idx < 0) idx = -(idx + 1); if (idx == nodes.length) idx = 0; return nodes[idx]; } private void qsort(int[] a, int[] b) { qsort(a, b, 0, a.length - 1); } private void qsort(int[] a, int[] b, int from, int to) { if (from >= to) return; int pivot = a[(from + to) / 2]; int i = from, j = to; while (i <= j) { while (a[i] < pivot) i++; while (a[j] > pivot) j--; if (i <= j) { swap(a, i, j); swap(b, i, j); i++; j--; } } qsort(a, b, from, j); qsort(a, b, i, to); } private void swap(int[] array, int i, int j) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } // Decompiled by Jad v1.5.8g. Copyright 2001 . // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.itextpdf.text.io; import java.io.IOException; // Referenced classes of package com.itextpdf.text.io: // RandomAccessSource public class GetBufferedRandomAccessSource implements RandomAccessSource { public GetBufferedRandomAccessSource(RandomAccessSource randomaccesssource) { // 0 0:aload_0 // 1 1:invokespecial #18 getBufferStart = -1L; // 2 4:aload_0 // 3 5:ldc2w #19 // 4 8:putfield #22 getBufferEnd = -1L; // 5 11:aload_0 // 6 12:ldc2w #19 // 7 15:putfield #24 source = randomaccesssource; // 8 18:aload_0 // 9 19:aload_1 // 10 20:putfield #26 getBuffer = new byte[(int)Math.min(Math.max(randomaccesssource.length() / 4L, 1L), 4096L)]; // 11 23:aload_0 // 12 24:aload_1 // 13 25:invokeinterface #30 // 14 30:ldc2w #31 // 15 33:ldiv // 16 34:lconst_1 // 17 35:invokestatic #38 // 18 38:ldc2w #39 // 19 41:invokestatic #43 // 20 44:l2i // 21 45:newarray byte[] // 22 47:putfield #45 getBufferStart = -1L; // 23 50:aload_0 // 24 51:ldc2w #19 // 25 54:putfield #22 getBufferEnd = -1L; // 26 57:aload_0 // 27 58:ldc2w #19 // 28 61:putfield #24 // 29 64:return } public void close() throws IOException { source.close(); // 0 0:aload_0 // 1 1:getfield #26 // 2 4:invokeinterface #51 getBufferStart = -1L; // 3 9:aload_0 // 4 10:ldc2w #19 // 5 13:putfield #22 getBufferEnd = -1L; // 6 16:aload_0 // 7 17:ldc2w #19 // 8 20:putfield #24 // 9 23:return } public int get(long l) throws IOException { if(l < getBufferStart || l > getBufferEnd) //* 0 0:lload_1 //* 1 1:aload_0 //* 2 2:getfield #22 //* 3 5:lcmp //* 4 6:iflt 18 //* 5 9:lload_1 //* 6 10:aload_0 //* 7 11:getfield #24 //* 8 14:lcmp //* 9 15:ifle 61 { int i = source.get(l, getBuffer, 0, getBuffer.length); // 10 18:aload_0 // 11 19:getfield #26 // 12 22:lload_1 // 13 23:aload_0 // 14 24:getfield #45 // 15 27:iconst_0 // 16 28:aload_0 // 17 29:getfield #45 // 18 32:arraylength // 19 33:invokeinterface #57 // 20 38:istore_3 if(i == -1) //* 21 39:iload_3 //* 22 40:iconst_m1 //* 23 41:icmpne 46 return -1; // 24 44:iconst_m1 // 25 45:ireturn getBufferStart = l; // 26 46:aload_0 // 27 47:lload_1 // 28 48:putfield #22 getBufferEnd = ((long)i + l) - 1L; // 29 51:aload_0 // 30 52:iload_3 // 31 53:i2l // 32 54:lload_1 // 33 55:ladd // 34 56:lconst_1 // 35 57:lsub // 36 58:putfield #24 } int j = (int)(l - getBufferStart); // 37 61:lload_1 // 38 62:aload_0 // 39 63:getfield #22 // 40 66:lsub // 41 67:l2i // 42 68:istore_3 return getBuffer[j] & 0xff; // 43 69:aload_0 // 44 70:getfield #45 // 45 73:iload_3 // 46 74:baload // 47 75:sipush 255 // 48 78:iand // 49 79:ireturn } public int get(long l, byte abyte0[], int i, int j) throws IOException { return source.get(l, abyte0, i, j); // 0 0:aload_0 // 1 1:getfield #26 // 2 4:lload_1 // 3 5:aload_3 // 4 6:iload 4 // 5 8:iload 5 // 6 10:invokeinterface #57 // 7 15:ireturn } public long length() { return source.length(); // 0 0:aload_0 // 1 1:getfield #26 // 2 4:invokeinterface #30 // 3 9:lreturn } private final byte getBuffer[]; private long getBufferEnd; private long getBufferStart; private final RandomAccessSource source; } 1-10 package org.embulk.input; public class TestSqlInputPlugin { } package com.leichui.shortviedeo.bean; import java.util.List; public class MyCollectionBean { /** * code : 2000 * data : [{"video_id":"8","is_video_friend":"0","video_collect_count":"1","video_url":"http://1302896845.vod2.myqcloud.com/30e296b0vodcq1302896845/abe3e1b95285890806952179268/JRInfQ4WQZoA.mp4","video_img_url":"http://1302896845.vod2.myqcloud.com/30e296b0vodcq1302896845/abe3e1b95285890806952179268/5285890806952179269.jpg","fileId":"5285890806952179268"},{"video_id":"7","is_video_friend":"0","video_collect_count":"1","video_url":"http://1302896845.vod2.myqcloud.com/30e296b0vodcq1302896845/6c9c680d5285890806951732424/S6wfsK7IHA4A.mp4","video_img_url":"http://1302896845.vod2.myqcloud.com/30e296b0vodcq1302896845/6c9c680d5285890806951732424/5285890806951732425.jpg","fileId":"5285890806951732424"}] * msg : {"dialog":"","str":"success"} * timestamp : 1599009976 */ private int code; private MsgBean msg; private int timestamp; private List data; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public MsgBean getMsg() { return msg; } public void setMsg(MsgBean msg) { this.msg = msg; } public int getTimestamp() { return timestamp; } public void setTimestamp(int timestamp) { this.timestamp = timestamp; } public List getData() { return data; } public void setData(List data) { this.data = data; } public static class MsgBean { /** * dialog : * str : success */ private String dialog; private String str; public String getDialog() { return dialog; } public void setDialog(String dialog) { this.dialog = dialog; } public String getStr() { return str; } public void setStr(String str) { this.str = str; } } public static class DataBean { /** * video_id : 8 * is_video_friend : 0 * video_collect_count : 1 * video_url : http://1302896845.vod2.myqcloud.com/30e296b0vodcq1302896845/abe3e1b95285890806952179268/JRInfQ4WQZoA.mp4 * video_img_url : http://1302896845.vod2.myqcloud.com/30e296b0vodcq1302896845/abe3e1b95285890806952179268/5285890806952179269.jpg * fileId : 5285890806952179268 */ private String video_id; private String is_video_friend; private String video_collect_count; private String video_url; private String video_img_url; private String fileId; public String getVideo_id() { return video_id; } public void setVideo_id(String video_id) { this.video_id = video_id; } public String getIs_video_friend() { return is_video_friend; } public void setIs_video_friend(String is_video_friend) { this.is_video_friend = is_video_friend; } public String getVideo_collect_count() { return video_collect_count; } public void setVideo_collect_count(String video_collect_count) { this.video_collect_count = video_collect_count; } public String getVideo_url() { return video_url; } public void setVideo_url(String video_url) { this.video_url = video_url; } public String getVideo_img_url() { return video_img_url; } public void setVideo_img_url(String video_img_url) { this.video_img_url = video_img_url; } public String getFileId() { return fileId; } public void setFileId(String fileId) { this.fileId = fileId; } } } package testable; public interface Book { } package org.squiddev.plethora.integration.appliedenergistics; import appeng.api.networking.IGridBlock; import appeng.api.networking.IGridNode; import appeng.core.AppEng; import org.squiddev.plethora.api.converter.ConstantConverter; import org.squiddev.plethora.api.converter.IConverter; import javax.annotation.Nonnull; import javax.annotation.Nullable; @IConverter.Inject(value = IGridNode.class, modId = AppEng.MOD_ID) public class ConverterGridBlock extends ConstantConverter { @Nullable @Override public IGridBlock convert(@Nonnull IGridNode from) { return from.getGridBlock(); } } /* * 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.jackrabbit.oak.upgrade.cli.blob; import org.apache.jackrabbit.oak.spi.blob.BlobOptions; import org.apache.jackrabbit.oak.spi.blob.BlobStore; import org.jetbrains.annotations.NotNull; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import static com.google.common.base.Preconditions.checkNotNull; /** * Utility BlobStore implementation to be used in tooling that can work with a * FileStore without the need of the DataStore being present locally. * * Additionally instead of failing it tries to mimic and return blob reference * passed in by caller by passing it back as a binary. * * Example: requesting blobId = e7c22b994c59d9 it will return the * e7c22b994c59d9 text as a UTF-8 encoded binary file. */ public class LoopbackBlobStore implements BlobStore { @Override public String writeBlob(InputStream in) { throw new UnsupportedOperationException(); } @Override public String writeBlob(InputStream in, BlobOptions options) throws IOException { return writeBlob(in); } @Override public int readBlob(String blobId, long pos, byte[] buff, int off, int length) { // Only a part of binary can be requested! final int binaryLength = blobId.length(); checkBinaryOffsetInRange(pos, binaryLength); final int effectiveSrcPos = Math.toIntExact(pos); final int effectiveBlobLengthToBeRead = Math.min( binaryLength - effectiveSrcPos, length); checkForBufferOverflow(buff, off, effectiveBlobLengthToBeRead); final byte[] blobIdBytes = getBlobIdStringAsByteArray(blobId); System.arraycopy(blobIdBytes, effectiveSrcPos, buff, off, effectiveBlobLengthToBeRead); return effectiveBlobLengthToBeRead; } private void checkForBufferOverflow(final byte[] buff, final int off, final int effectiveBlobLengthToBeRead) { if (buff.length < effectiveBlobLengthToBeRead + off) { // We cannot recover if buffer used to write is too small throw new UnsupportedOperationException("Edge case: cannot fit " + "blobId in a buffer (buffer too small)"); } } private void checkBinaryOffsetInRange(final long pos, final int binaryLength) { if (pos > binaryLength) { throw new IllegalArgumentException( String.format("Offset %d out of range of %d", pos, binaryLength)); } } private byte[] getBlobIdStringAsByteArray(final String blobId) { return blobId.getBytes(StandardCharsets.UTF_8); } @Override public long getBlobLength(String blobId) throws IOException { return blobId.length(); } @Override public InputStream getInputStream(String blobId) throws IOException { checkNotNull(blobId); return new ByteArrayInputStream(getBlobIdStringAsByteArray(blobId)); } @Override public String getBlobId(@NotNull String reference) { return checkNotNull(reference); } @Override public String getReference(@NotNull String blobId) { return checkNotNull(blobId); } @Override public void close() throws Exception { } } /* * Copyright (C) 2005, 2006 . * Copyright (C) 2006, 2007, 2008 XStream Committers. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * * Created on 22. January 2005 by */ package com.thoughtworks.xstream.mapper; import com.thoughtworks.xstream.alias.ClassMapper; /** * Mapper that ensures that all names in the serialization stream are XML friendly. * The replacement chars and strings are: *
    *
  • $ (dollar) chars appearing in class names are replaced with _ (underscore) chars.
  • *
  • $ (dollar) chars appearing in field names are replaced with _DOLLAR_ string.
  • *
  • _ (underscore) chars appearing in field names are replaced with __ (double underscore) string.
  • *
  • default as the prefix for class names with no package.
  • *
* * @author * @author * @deprecated since 1.3, use {@link com.thoughtworks.xstream.io.xml.XmlFriendlyReader} */ public class XmlFriendlyMapper extends AbstractXmlFriendlyMapper { /** * @deprecated since 1.3, use {@link com.thoughtworks.xstream.io.xml.XmlFriendlyReader} */ public XmlFriendlyMapper(Mapper wrapped) { super(wrapped); } /** * @deprecated since 1.2, use {@link #XmlFriendlyMapper(Mapper)} */ public XmlFriendlyMapper(ClassMapper wrapped) { this((Mapper)wrapped); } public String serializedClass(Class type) { return escapeClassName(super.serializedClass(type)); } public Class realClass(String elementName) { return super.realClass(unescapeClassName(elementName)); } public String serializedMember(Class type, String memberName) { return escapeFieldName(super.serializedMember(type, memberName)); } public String realMember(Class type, String serialized) { return unescapeFieldName(super.realMember(type, serialized)); } public String mapNameToXML(String javaName) { return escapeFieldName(javaName); } public String mapNameFromXML(String xmlName) { return unescapeFieldName(xmlName); } } package com.xunlei.analytics.config; public class AnalyticsReportConfigurationBuilder { int batchUploadCount; long deleteExpirationDayTime; boolean isWifiOnly; long reportCheckInterval; int reportRetryCount; int reportRule; long sessionContinueMillis; public AnalyticsReportConfigurationBuilder() { this.reportRule = 0; this.batchUploadCount = 10; this.reportCheckInterval = 180000; this.deleteExpirationDayTime = 604800000; this.isWifiOnly = false; this.reportRetryCount = 3; this.sessionContinueMillis = 5000; } public AnalyticsReportConfigurationBuilder batchUploadCount(int i) { this.batchUploadCount = i; return this; } public AnalyticsReportConfiguration build() { return new AnalyticsReportConfiguration(this); } public AnalyticsReportConfigurationBuilder deleteExpirationDayTime(int i) { this.deleteExpirationDayTime = (long) i; return this; } public AnalyticsReportConfigurationBuilder reportCheckInterval(long j) { this.reportCheckInterval = j; return this; } public AnalyticsReportConfigurationBuilder reportRetryCount(int i) { this.reportRetryCount = i; return this; } public AnalyticsReportConfigurationBuilder reportRule(int i) { this.reportRule = i; return this; } public AnalyticsReportConfigurationBuilder sessionContinueMillis(long j) { this.sessionContinueMillis = j; return this; } public AnalyticsReportConfigurationBuilder uploadInWifiOnly(boolean z) { this.isWifiOnly = z; return this; } } chqu1012/JRegis package de.dc.spring.fx.ui.jregis.metro.ui.gen.calendar.appointment.filter; import org.apache.commons.lang.builder.ToStringBuilder; public class XAppointmentSearchContent { private String name; private String value; private XAppointmentSearchType type; public XAppointmentSearchContent(String name, String value, XAppointmentSearchType type) { this.name = name; this.value = value; this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public XAppointmentSearchType getType() { return type; } public void setType(XAppointmentSearchType type) { this.type = type; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } } /* * 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.calcite.rel.rules; import org.apache.calcite.plan.RelOptRuleCall; import org.apache.calcite.plan.RelOptUtil; import org.apache.calcite.plan.RelRule; import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Join; import org.apache.calcite.rel.core.Project; import org.apache.calcite.rel.logical.LogicalJoin; import org.apache.calcite.rel.logical.LogicalProject; import org.apache.calcite.rel.type.RelDataTypeField; import org.apache.calcite.rex.RexCall; import org.apache.calcite.rex.RexNode; import org.apache.calcite.rex.RexOver; import org.apache.calcite.rex.RexShuttle; import org.apache.calcite.tools.RelBuilderFactory; import org.apache.calcite.util.ImmutableBeans; import org.immutables.value.Value; import java.util.ArrayList; import java.util.List; import static java.util.Objects.requireNonNull; /** * Planner rule that pushes a {@link org.apache.calcite.rel.core.Project} * past a {@link org.apache.calcite.rel.core.Join} * by splitting the projection into a projection on top of each child of * the join. * * @see CoreRules#PROJECT_JOIN_TRANSPOSE */ @Value.Enclosing public class ProjectJoinTransposeRule extends RelRule implements TransformationRule { /** Creates a ProjectJoinTransposeRule. */ protected ProjectJoinTransposeRule(Config config) { super(config); } @Deprecated // to be removed before 2.0 public ProjectJoinTransposeRule( Class projectClass, Class joinClass, PushProjector.ExprCondition preserveExprCondition, RelBuilderFactory relBuilderFactory) { this(Config.DEFAULT .withRelBuilderFactory(relBuilderFactory) .as(Config.class) .withOperandFor(projectClass, joinClass) .withPreserveExprCondition(preserveExprCondition)); } //~ Methods ---------------------------------------------------------------- @Override public void onMatch(RelOptRuleCall call) { final Project origProject = call.rel(0); final Join join = call.rel(1); // Normalize the join condition so we don't end up misidentified expanded // form of IS NOT DISTINCT FROM as PushProject also visit the filter condition // and push down expressions. RexNode joinFilter = join.getCondition().accept(new RexShuttle() { @Override public RexNode visitCall(RexCall rexCall) { final RexNode node = super.visitCall(rexCall); if (!(node instanceof RexCall)) { return node; } return RelOptUtil.collapseExpandedIsNotDistinctFromExpr((RexCall) node, call.builder().getRexBuilder()); } }); // locate all fields referenced in the projection and join condition; // determine which inputs are referenced in the projection and // join condition; if all fields are being referenced and there are no // special expressions, no point in proceeding any further final PushProjector pushProjector = new PushProjector( origProject, joinFilter, join, config.preserveExprCondition(), call.builder()); if (pushProjector.locateAllRefs()) { return; } // create left and right projections, projecting only those // fields referenced on each side final RelNode leftProject = pushProjector.createProjectRefsAndExprs( join.getLeft(), true, false); final RelNode rightProject = pushProjector.createProjectRefsAndExprs( join.getRight(), true, true); // convert the join condition to reference the projected columns RexNode newJoinFilter = null; int[] adjustments = pushProjector.getAdjustments(); if (joinFilter != null) { List projectJoinFieldList = new ArrayList<>(); projectJoinFieldList.addAll( join.getSystemFieldList()); projectJoinFieldList.addAll( leftProject.getRowType().getFieldList()); projectJoinFieldList.addAll( rightProject.getRowType().getFieldList()); newJoinFilter = pushProjector.convertRefsAndExprs( joinFilter, projectJoinFieldList, adjustments); } // create a new join with the projected children final Join newJoin = join.copy( join.getTraitSet(), requireNonNull(newJoinFilter, "newJoinFilter must not be null"), leftProject, rightProject, join.getJoinType(), join.isSemiJoinDone()); // put the original project on top of the join, converting it to // reference the modified projection list final RelNode topProject = pushProjector.createNewProject(newJoin, adjustments); call.transformTo(topProject); } /** Rule configuration. */ @Value.Immutable(singleton = false) public interface Config extends RelRule.Config { Config DEFAULT = ImmutableProjectJoinTransposeRule.Config.builder() .withPreserveExprCondition(expr -> !(expr instanceof RexOver)) .build() .withOperandFor(LogicalProject.class, LogicalJoin.class); @Override default ProjectJoinTransposeRule toRule() { return new ProjectJoinTransposeRule(this); } /** Defines when an expression should not be pushed. */ @SuppressWarnings("deprecation") @ImmutableBeans.Property PushProjector.ExprCondition preserveExprCondition(); /** Sets {@link #preserveExprCondition()}. */ Config withPreserveExprCondition(PushProjector.ExprCondition condition); /** Defines an operand tree for the given classes. */ default Config withOperandFor(Class projectClass, Class joinClass) { return withOperandSupplier(b0 -> b0.operand(projectClass).oneInput(b1 -> b1.operand(joinClass).anyInputs())) .as(Config.class); } } } 1-10 package com.google.common.cache; enum CacheBuilder$NullListener implements RemovalListener { INSTANCE; public void onRemoval(RemovalNotification removalNotification) { } } package umleditor; public class Statics { public static class BUTTON{ public static final int SELECT = 0; public static final int ASSOCIATION_LINE = 1; public static final int GENERALIZATION_LINE = 2; public static final int COMPOSITION_LINE = 3; public static final int UML_CLASS = 4; public static final int USE_CASE = 5; } public static class MENUITEMS{ public static final int GROUP = 0; public static final int UNGROUP = 1; public static final int RENAME = 2; public static final int LOAD = 3; public static final int SAVE = 4; public static final int EXIT = 5; } public static class UMLOBJECT{ public static final int CLASS = 0; public static final int USE_CASE = 1; public static final int ASSOCIATION_LINE = 2; public static final int GENERALIZATION_LINE = 3; public static final int COMPOSITION_LINE = 4; public static final int SELECT_SQUARE = 5; public static final int COMPOSITE = 6; } public static class MODE{ public static final int OBJECT = 0; public static final int LINE = 1; public static final int SELECT = 2; } public static class UMLOBJECT_TYPE{ public static final int SHAPE = 0; public static final int LINE = 1; } public static class PORT{ public static final int TOP = 0; public static final int LEFT = 1; public static final int RIGHT = 2; public static final int BOTTOM = 3; } } package controllers; import apimodels.DefaultCrumbIssuer; import play.mvc.Controller; import play.mvc.Result; import play.mvc.Http; import java.util.List; import java.util.Map; import java.util.ArrayList; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.JsonNode; import com.google.inject.Inject; import java.io.File; import openapitools.OpenAPIUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; import play.Configuration; import openapitools.OpenAPIUtils.ApiAction; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen", date = "2019-04-10T03:54:21.169Z[GMT]") public class BaseRemoteAccessApiController extends Controller { private final BaseRemoteAccessApiControllerImpInterface imp; private final ObjectMapper mapper; private final Configuration configuration; @Inject private BaseRemoteAccessApiController(Configuration configuration, BaseRemoteAccessApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); this.configuration = configuration; } @ApiAction public Result getCrumb() throws Exception { DefaultCrumbIssuer obj = imp.getCrumb(); if (configuration.getBoolean("useOutputBeanValidation")) { OpenAPIUtils.validate(obj); } JsonNode result = mapper.valueToTree(obj); return ok(result); } } /* ************************************************************************* * The contents of this file are subject to the Openbravo Public License * Version 1.1 (the "License"), being the Mozilla Public License * Version 1.1 with a permitted attribution clause; you may not use this * file except in compliance with the License. You may obtain a copy of * the License at http://www.openbravo.com/legal/license.html * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations * under the License. * The Original Code is Openbravo ERP. * The Initial Developer of the Original Code is Openbravo SLU * All portions are Copyright (C) 2001-2017 Openbravo SLU * All Rights Reserved. * Contributor(s): ______________________________________. ************************************************************************ */ package org.openbravo.erpCommon.utility; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.ScrollMode; import org.hibernate.ScrollableResults; import org.hibernate.criterion.Restrictions; import org.openbravo.base.secureApp.HttpSecureAppServlet; import org.openbravo.base.secureApp.VariablesSecureApp; import org.openbravo.base.structure.BaseOBObject; import org.openbravo.client.application.GlobalMenu; import org.openbravo.dal.core.OBContext; import org.openbravo.dal.service.OBCriteria; import org.openbravo.dal.service.OBDal; import org.openbravo.dal.service.OBQuery; import org.openbravo.data.Sqlc; import org.openbravo.database.ConnectionProvider; import org.openbravo.model.ad.datamodel.Table; import org.openbravo.model.ad.ui.Tab; import org.openbravo.model.ad.utility.Tree; import org.openbravo.utils.Replace; import org.openbravo.xmlEngine.XmlDocument; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver; /** * @author * * Manage the composition of the tree data for the tree window types. */ public class WindowTree extends HttpSecureAppServlet { private static final long serialVersionUID = 1L; private static final String CHILD_SHEETS = "frameWindowTreeF3"; private static List nodeIdList = new ArrayList<>(); @Inject GlobalMenu menu; public void init(ServletConfig config) { super.init(config); boolHist = false; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { VariablesSecureApp vars = new VariablesSecureApp(request); // Checking the window invoking the tree is accessible if (!hasGeneralAccess(vars, "W", vars.getStringParameter("inpTabId"))) { bdErrorGeneralPopUp(request, response, Utility.messageBD(this, "Error", vars.getLanguage()), Utility.messageBD(this, "AccessTableNoView", vars.getLanguage())); } if (vars.commandIn("DEFAULT", "TAB")) { String strTabId = vars.getGlobalVariable("inpTabId", "WindowTree|tabId"); ADTreeData treeData = new ADTreeData(strTabId); treeData.initializeData(vars, this); if (treeData.treeId == null) { advisePopUp(request, response, "ERROR", Utility.messageBD(this, "Error", vars.getLanguage()), Utility.messageBD(this, "AccessTableNoView", vars.getLanguage())); } else { printPageDataSheet(response, vars, treeData); } } else if (vars.commandIn("ASSIGN")) { String strTabId = vars.getRequiredStringParameter("inpTabId"); String strTop = vars.getRequiredStringParameter("inpTop"); String strLink = vars.getRequiredStringParameter("inpLink"); String strChild = vars.getStringParameter("inpChild", "N"); String strResult = WindowTreeChecks.checkChanges(this, vars, strTabId, strTop, strLink, strChild.equals("Y")); if (strResult.equals("")) { changeNode(vars, strTabId, strTop, strLink, strChild); } else { vars.setSessionValue("WindowTree|message", strResult); } vars.setSessionValue("WindowTree|tabId", strTabId); PrintWriter out = response.getWriter(); if (strResult != "") { // create OBError and serialize it using JSON OBError error = new OBError(); error.setType("Error"); error.setTitle("Error"); error.setMessage(strResult); XStream xs = new XStream(new JettisonMappedXmlDriver()); xs.alias("OBError", OBError.class); strResult = xs.toXML(error); } out.print(strResult); out.close(); } else { throw new ServletException(); } } /** * Main method to build the html for the tree. * * @param vars * Handler for the session info. * @param key * key column name. * @param editable * is editable? * @param strTabId * id of the tab. * @return String html with the tree. * @throws ServletException */ private String loadNodes(VariablesSecureApp vars, ADTreeData treeData, boolean editable) throws ServletException { if (treeData.treeId == null) { log4j.error("WindowTree.loadNodes() - Unknown TreeNode: TreeType " + treeData.treeType + " - TreeKey " + treeData.key); throw new ServletException("WindowTree.loadNodes() - Unknown TreeNode"); } StringBuilder nodesMenu = new StringBuilder(); if (log4j.isDebugEnabled()) log4j.debug("WindowTree.loadNodes() - TreeType: " + treeData.treeType + " || TreeID: " + treeData.treeId); nodesMenu.append("\n
    \n"); nodesMenu.append(WindowTreeUtility.addNodeElement(treeData.treeName, treeData.treeDescription, CHILD_SHEETS, true, "", strDireccion, "clickItem(0, '" + Replace.replace(treeData.treeName, "'", "\\'") + "', 'N');", "dblClickItem(0);", true, "0", "")); WindowTreeData[] wtd = WindowTreeUtility.getTree(this, vars, treeData.treeType, treeData.treeId, editable, "", "", treeData.tabId); Map> wtdTree = buildTree(wtd); nodesMenu.append(generateTree(wtd, wtdTree, strDireccion, "0", true, treeData.tabId)); nodesMenu.append("\n
\n"); nodeIdList = null; return nodesMenu.toString(); } /** * Generates the tree for the html. * * @param data * Array with the tree elements. * @param direccion * String with the path for the urls. * @param indice * String with the index. * @param isFirst * Indicates if is the first or not. * @return String html with the tree. */ private String generateTree(WindowTreeData[] data, Map> wtdTree, String direccion, String indice, boolean isFirst, String strTabId) { boolean localIsFirst = isFirst; String localIndice = indice; if (data == null || data.length == 0) return ""; if (log4j.isDebugEnabled()) log4j.debug("WindowTree.generateTree() - data: " + data.length); if (localIndice == null) localIndice = "0"; boolean hayDatos = false; StringBuilder strResultado = new StringBuilder(); strResultado.append("
    "); localIsFirst = false; List subList = wtdTree.get(localIndice); if (subList != null) { List filteredSubList = applyWhereClause(subList, strTabId); for (WindowTreeData elem : subList) { hayDatos = true; String strHijos = generateTree(data, wtdTree, direccion, elem.nodeId, localIsFirst, strTabId); // if elem is present in filtered sublist click action is allowed, else disabled if (filteredSubList.contains(elem)) { strResultado.append(WindowTreeUtility.addNodeElement(elem.name, elem.description, CHILD_SHEETS, elem.issummary.equals("Y"), WindowTreeUtility.windowType(elem.action), direccion, "clickItem('" + elem.nodeId + "', '" + Replace.replace(elem.name, "'", "\\'") + "', '" + elem.issummary + "');", "dblClickItem('" + elem.nodeId + "');", !strHijos.equals(""), elem.nodeId, elem.action)); } else { strResultado.append(WindowTreeUtility.addNodeElement(elem.name, elem.description, CHILD_SHEETS, elem.issummary.equals("Y"), WindowTreeUtility.windowType(elem.action), direccion, null, null, !strHijos.equals(""), elem.nodeId, elem.action)); } strResultado.append(strHijos); } } strResultado.append("
"); return (hayDatos ? strResultado.toString() : ""); } /* * Retrieves the tab level hqlWhereClause and applies them to the current TreeData list and * returns the filtered list. sqlWhereClause is not applied in the tab, so not applied here. Uses * a global static list nodeIdList to fetch it only once though the method is called recursively. */ private List applyWhereClause(List subList, String strTabId) { String entityName = null, hqlWhereClause = null; try { OBContext.setAdminMode(); Tab tabData = OBDal.getInstance().get(org.openbravo.model.ad.ui.Tab.class, strTabId); if (tabData != null) { entityName = tabData.getTable().getName(); hqlWhereClause = tabData.getHqlwhereclause(); } } catch (Exception e) { log4j.error("Exception while retrieving hqlWhereClause " + e); } finally { OBContext.restorePreviousMode(); } List newSubList = new ArrayList(); if (hqlWhereClause != null && !hqlWhereClause.trim().isEmpty()) { hqlWhereClause = hqlWhereClause.replaceAll("\\be.", ""); OBQuery entityResults = OBDal.getInstance().createQuery("" + entityName + "", hqlWhereClause); if (nodeIdList == null) { nodeIdList = new ArrayList<>(); } if (nodeIdList.isEmpty() && nodeIdList.size() != entityResults.count()) { ScrollableResults entityData = entityResults.scroll(ScrollMode.FORWARD_ONLY); int clearEachLoops = 100; int i = 0; try { while (entityData.next()) { i++; BaseOBObject entity = (BaseOBObject) entityData.get()[0]; if (entity.getId() != null) { nodeIdList.add(entity.getId().toString()); } if (i % clearEachLoops == 0) { OBDal.getInstance().getSession().clear(); } } } finally { entityData.close(); } } for (WindowTreeData elem : subList) { if (nodeIdList.contains(elem.nodeId)) { newSubList.add(elem); } } } else { newSubList = subList; } return newSubList; } private static Map> buildTree(WindowTreeData[] input) { Map> resMap = new HashMap<>(); for (WindowTreeData elem : input) { List list = resMap.get(elem.parentId); if (list == null) { list = new ArrayList<>(); } list.add(elem); resMap.put(elem.parentId, list); } return resMap; } /** * Prints the tree page. * * @param response * Handler to the response. * @param vars * Handler for the session info. * @param TabId * Tab id. * @throws IOException * @throws ServletException */ private void printPageDataSheet(HttpServletResponse response, VariablesSecureApp vars, ADTreeData treeData) throws IOException, ServletException { if (log4j.isDebugEnabled()) log4j.debug("Output: Tree's screen for the tab: " + treeData.tabId); OBError defaultInfo = new OBError(); defaultInfo.setType("INFO"); defaultInfo.setTitle(Utility.messageBD(this, "Info", vars.getLanguage())); defaultInfo.setMessage(Utility.messageBD(this, "TreeInfo", vars.getLanguage())); vars.setMessage("WindowTree", defaultInfo); XmlDocument xmlDocument = xmlEngine.readXmlTemplate( "org/openbravo/erpCommon/utility/WindowTree").createXmlDocument(); xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";"); xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n"); xmlDocument.setParameter("theme", vars.getTheme()); WindowTreeData[] data = WindowTreeData.selectTabName(this, treeData.tabId); xmlDocument.setParameter("description", data[0].name); xmlDocument.setParameter("page", Utility.getTabURL(treeData.tabId, "E", true)); xmlDocument.setParameter("menu", loadNodes(vars, treeData, WindowTreeData.selectEditable(this, treeData.tabId).equals("Y"))); xmlDocument.setParameter("treeID", treeData.treeId); xmlDocument.setParameter("tabID", treeData.tabId); String key = "inp" + Sqlc.TransformaNombreColumna(treeData.key); xmlDocument.setParameter("keyField", key); xmlDocument.setParameter("keyFieldScript", "function getKeyField() {\n return document.frmMain." + key + ";\n}\n"); try { OBError myMessage = vars.getMessage("WindowTree"); vars.removeMessage("WindowTree"); if (myMessage != null) { xmlDocument.setParameter("messageType", myMessage.getType()); xmlDocument.setParameter("messageTitle", myMessage.getTitle()); xmlDocument.setParameter("messageMessage", myMessage.getMessage()); } } catch (Exception ex) { log4j.error(ex.getMessage(), ex); } response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); out.println(xmlDocument.print()); out.close(); } /** * Makes the change of position of the elements in the tree. * * It positions the node and moves down all the nodes after this one. * * For menu tree it looks whether the current node and the ones after that are within a module in * development. It searchs the first node after the current one that is not in development and * modifies the seqno for the current one (regardless it is in development or not) and the ones * bellow it that are in development. * * @param vars * Handler for the session info. * @param strTabId * Tab id. * @param strTop * Parent node id. * @param strLink * Id of the node to change. * @param strChild * String indicating if is a child or not of the parent node (Y|N). * @throws ServletException */ private void changeNode(VariablesSecureApp vars, String strTabId, String strTop, String strLink, String strChild) throws ServletException { String key = WindowTreeData.selectKey(this, strTabId); String TreeType = WindowTreeUtility.getTreeType(key); String TreeID = ""; String strParent = strTop; boolean editable = WindowTreeData.selectEditable(this, strTabId).equals("Y"); if ("MM".equals(TreeType)) { // Editing Application Menu tree, invalidate menu cache manually as this update is not // captured by Listener because it is not done though DAL menu.invalidateCache(); } // Calculating the TreeID try { OBContext.setAdminMode(true); Tab tab = OBDal.getInstance().get(Tab.class, strTabId); Table table = tab.getTable(); OBCriteria adTreeCriteria = OBDal.getInstance().createCriteria(Tree.class); adTreeCriteria.add(Restrictions.eq(Tree.PROPERTY_TABLE, table)); adTreeCriteria.add(Restrictions.eq(Tree.PROPERTY_CLIENT, OBContext.getOBContext() .getCurrentClient())); adTreeCriteria.setFilterOnReadableOrganization(false); Tree adTree = (Tree) adTreeCriteria.uniqueResult(); if (adTree != null) { TreeID = adTree.getId(); TreeType = adTree.getTable().getTreeType(); } else { WindowTreeData[] data = WindowTreeData.selectTreeID(this, Utility.getContext(this, vars, "#User_Client", ""), TreeType); if (data == null || data.length == 0) { log4j.error("WindowTree.loadNodes() - Unknown TreeNode"); throw new ServletException("WindowTree.loadNodes() - Unknown TreeNode"); } else { TreeID = data[0].id; } } } finally { OBContext.restorePreviousMode(); } // Calculating the parent if (!strTop.equals("0")) { WindowTreeData[] data = WindowTreeUtility.getTree(this, vars, TreeType, TreeID, editable, "", strTop, strTabId); if (data == null || data.length == 0) { log4j.error("WindowTree.loadNodes() - Unknown Top Node"); throw new ServletException("WindowTree.loadNodes() - Unknown Top Node"); } if (!data[0].issummary.equals("Y") || !strChild.equals("Y")) { strParent = data[0].parentId; } } else strParent = strTop; WindowTreeData[] data = WindowTreeUtility.getTree(this, vars, TreeType, TreeID, editable, strParent, "", strTabId); int seqNo = 0; int add = 10; try { if (data == null || data.length == 0) { WindowTreeUtility.setNode(this, vars, TreeType, TreeID, strParent, strLink, Integer.toString(seqNo)); } else { boolean updated = false; boolean finish = false; if (strParent.equals(strTop)) { seqNo += add; WindowTreeUtility.setNode(this, vars, TreeType, TreeID, strParent, strLink, Integer.toString(seqNo)); updated = true; } for (int i = 0; !finish && i < data.length; i++) { if (!data[i].nodeId.equals(strLink)) { if (updated && !finish) { // update only elements after // the current one if (data[i].isindevelopment == null || data[i].isindevelopment.equals("") || data[i].isindevelopment.equals("Y")) { seqNo += add; WindowTreeUtility.setNode(this, vars, TreeType, TreeID, data[i].parentId, data[i].nodeId, Integer.toString(seqNo)); } else { finish = true; // update elements till one is // not in developement, then // finish } } if (!updated && data[i].nodeId.equals(strTop)) { // Calculate the addition for the range of modules // in development int j = 0; for (j = i + 1; j < data.length && (data[j].isindevelopment == null || data[j].isindevelopment.equals("") || data[j].isindevelopment .equals("Y")); j++) ; if (j == data.length) add = 10; // it is at the end it can be expanded // without problem else add = new Float( ((new Integer(data[j].seqno) - new Integer(data[i].seqno)) / (j - i + 1))) .intValue(); // Set the current node in its posisiton if (i == 0) seqNo = 10; else seqNo = new Integer(data[i].seqno).intValue() + add; WindowTreeUtility.setNode(this, vars, TreeType, TreeID, strParent, strLink, Integer.toString(seqNo)); updated = true; } } } if (!updated) WindowTreeUtility.setNode(this, vars, TreeType, TreeID, strParent, strLink, Integer.toString(seqNo)); } } catch (ServletException e) { log4j.error("WindowTree.changeNode() - Couldn't change the node: " + strLink); log4j.error("WindowTree.setNode() - error: " + e); throw new ServletException(e); } } public String getServletInfo() { return "Servlet that presents the tree of a TreeNode windo windoww"; } // end of getServletInfo() method private class ADTreeData { private String tabId; private String treeId; private String treeName; private String treeType; private String treeDescription; private String key; private ADTreeData(String tabId) { this.tabId = tabId; } private void initializeData(VariablesSecureApp vars, ConnectionProvider connectionProvider) throws ServletException { initFromADTree(); if (treeId == null) { key = WindowTreeData.selectKey(connectionProvider, tabId); treeType = WindowTreeUtility.getTreeType(key); WindowTreeData[] data = WindowTreeData.selectTreeID(connectionProvider, Utility.getContext(connectionProvider, vars, "#User_Client", ""), treeType); if (data != null && data.length > 0) { treeId = data[0].id; treeName = data[0].name; treeDescription = data[0].description; } } } private void initFromADTree() { try { OBContext.setAdminMode(true); Tab tab = OBDal.getInstance().get(Tab.class, tabId); Table table = tab.getTable(); OBCriteria adTreeCriteria = OBDal.getInstance().createCriteria(Tree.class); adTreeCriteria.add(Restrictions.eq(Tree.PROPERTY_TABLE, table)); adTreeCriteria.add(Restrictions.eq(Tree.PROPERTY_CLIENT, OBContext.getOBContext() .getCurrentClient())); adTreeCriteria.setFilterOnReadableOrganization(false); Tree adTree = (Tree) adTreeCriteria.uniqueResult(); if (adTree == null) { return; } treeId = adTree.getId(); treeName = adTree.getName(); treeDescription = adTree.getDescription(); treeType = adTree.getTypeArea(); key = ""; } finally { OBContext.restorePreviousMode(); } } } } package com.jeesite.modules.util; import java.security.MessageDigest; public class MD5Util { private static final String[] hexDigits = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"}; public MD5Util() { } private static String byteArrayToHexString(byte[] b) { StringBuffer resultSb = new StringBuffer(); for(int i = 0; i < b.length; ++i) { resultSb.append(byteToHexString(b[i])); } return resultSb.toString(); } private static String byteToHexString(byte b) { int n = b; if (b < 0) { n = b + 256; } int d1 = n / 16; int d2 = n % 16; return hexDigits[d1] + hexDigits[d2]; } public static String MD5Encode(String origin) { char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; try { byte[] btInput = origin.getBytes("UTF-8"); MessageDigest mdInst = MessageDigest.getInstance("MD5"); mdInst.update(btInput); byte[] md = mdInst.digest(); int j = md.length; char[] str = new char[j * 2]; int k = 0; for(int i = 0; i < j; ++i) { byte byte0 = md[i]; str[k++] = hexDigits[byte0 >>> 4 & 15]; str[k++] = hexDigits[byte0 & 15]; } return new String(str); } catch (Exception var10) { var10.printStackTrace(); return null; } } }acoresoft/jeeplat package com.acoreful.jeeplat.components.demo; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; import org.springframework.core.type.AnnotationMetadata; import lombok.extern.slf4j.Slf4j; @Slf4j public class AcfDemoApiRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { Map map = importingClassMetadata.getAnnotationAttributes(EnableAcfDemo.class.getName()); String basePackages = StringUtils.join((String[]) map.get("basePackages"), ","); log.info("[AcfDemoApi]basePackages:{}", basePackages); BeanDefinition beanDefinition = BeanDefinitionBuilder .genericBeanDefinition(AcfDemoAnnotationBeanFactoryPostProcessor.class) .addPropertyValue("basePackages", basePackages).getBeanDefinition(); registry.registerBeanDefinition("acfDemoAnnotationBeanFactoryPostProcessor", beanDefinition); } } package com.vinaymaneti.codernyt.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.AppCompatImageView; import android.support.v7.widget.AppCompatTextView; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import com.bumptech.glide.Glide; import com.vinaymaneti.codernyt.R; import com.vinaymaneti.codernyt.model.Article; import com.vinaymaneti.codernyt.model.Multimedia; import com.vinaymaneti.codernyt.util.UiUtils; import butterknife.BindView; import butterknife.ButterKnife; public class DetailArticleActivity extends AppCompatActivity { Article article; @BindView(R.id.coverImageView) AppCompatImageView coverImageView; @BindView(R.id.textSnippet) AppCompatTextView textSnippet; @BindView(R.id.pbloading) ProgressBar progressBarLoading; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail_article); ButterKnife.bind(this); Bundle bundle = getIntent().getExtras(); if (bundle != null) { article = bundle.getParcelable("article"); if (article.getMultimedia().size() > 0 && article.getMultimedia() != null) { Multimedia multimedia = article.getMultimedia().get(0); if (multimedia.getHeight() != null) { ViewGroup.LayoutParams layoutParams = coverImageView.getLayoutParams(); layoutParams.height = (int) UiUtils.convertDpTOPixel(multimedia.getHeight(), this); coverImageView.setLayoutParams(layoutParams); } coverImageView.setVisibility(View.VISIBLE); Glide.with(this) .load(multimedia.getUrl()) .into(coverImageView); } else { coverImageView.setVisibility(View.GONE); progressBarLoading.setVisibility(View.GONE); } textSnippet.setText(article.getSnippet()); } } } timoles/codeql public class InsecureLdapEndpoint2 { public Hashtable createConnectionEnv() { Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldaps://ad.your-server.com:636"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, "username"); env.put(Context.SECURITY_CREDENTIALS, "secpassword"); // GOOD - No configuration to disable SSL endpoint check since it is enabled by default. { } return env; } } ja-ko/StillAlive package dev.jko; import org.junit.Assert; import org.junit.Test; public class StillAliveTest { private boolean called = false; @Test public void checkConsumerCalled() throws Exception { StillAlive.setExecutionCallback(this::logLine); Thread.sleep(1000); Assert.assertTrue(called); } private void logLine(String line) { called = true; } } Jen-Lopez/voting_rights_rys_2020 package com.example.voting_rights_rys; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import com.google.android.material.bottomnavigation.BottomNavigationView; public class Resources extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_resources); //Initialize bottom nav bar and select "Resources" BottomNavigationView bottomNavView = findViewById(R.id.bot_nav); bottomNavView.setSelectedItemId(R.id.resources); //Start a new activity when a nav bar item is selected bottomNavView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()){ case R.id.home: startActivity(new Intent(getApplicationContext(), MainActivity.class)); overridePendingTransition(0,0); return true; case R.id.elections: startActivity(new Intent(getApplicationContext(), Elections.class)); overridePendingTransition(0,0); return true; case R.id.resources: return true; case R.id.settings: startActivity(new Intent(getApplicationContext(), Settings.class)); overridePendingTransition(0,0); return true; } return false; } }); } }android-client-generated/src/main/java/io/swagger/client/model/InlineResponse20020.java /** * Whats App API * Whats App API * * OpenAPI spec version: 1.0.0 * Contact: * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.model; import io.swagger.client.model.InlineResponse20020MediaArray; import java.util.*; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; @ApiModel(description = "") public class InlineResponse20020 { @SerializedName("success") private Boolean success = null; @SerializedName("mediaArray") private List mediaArray = null; /** **/ @ApiModelProperty(value = "") public Boolean getSuccess() { return success; } public void setSuccess(Boolean success) { this.success = success; } /** **/ @ApiModelProperty(value = "") public List getMediaArray() { return mediaArray; } public void setMediaArray(List mediaArray) { this.mediaArray = mediaArray; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InlineResponse20020 inlineResponse20020 = (InlineResponse20020) o; return (this.success == null ? inlineResponse20020.success == null : this.success.equals(inlineResponse20020.success)) && (this.mediaArray == null ? inlineResponse20020.mediaArray == null : this.mediaArray.equals(inlineResponse20020.mediaArray)); } @Override public int hashCode() { int result = 17; result = 31 * result + (this.success == null ? 0: this.success.hashCode()); result = 31 * result + (this.mediaArray == null ? 0: this.mediaArray.hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InlineResponse20020 {\n"); sb.append(" success: ").append(success).append("\n"); sb.append(" mediaArray: ").append(mediaArray).append("\n"); sb.append("}\n"); return sb.toString(); } } 10-100 package com.github.thorbenkuck.netcom2.network.server; import com.github.thorbenkuck.keller.datatypes.interfaces.Value; import com.github.thorbenkuck.netcom2.exceptions.ClientConnectionFailedException; import com.github.thorbenkuck.netcom2.exceptions.StartFailedException; import com.github.thorbenkuck.netcom2.logging.Logging; import com.github.thorbenkuck.netcom2.network.shared.clients.Client; import com.github.thorbenkuck.netcom2.network.shared.connections.*; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; final class NativeTCPConnectorCore extends AbstractConnectorCore { private final Value connected = Value.synchronize(false); private final Value serverSocketValue = Value.emptySynchronized(); private final Logging logging = Logging.unified(); NativeTCPConnectorCore(ClientFactory clientFactory) { super(clientFactory); logging.instantiated(this); } private void registerConnected(final Socket socket) throws IOException { final Connection connection = Connection.tcp(socket); // Assume the DefaultConnection // This will not always be true. // However, the chain of // initial messages will fix this connection.setIdentifier(DefaultConnection.class); final Client client = createClient(); connection.hook(ConnectionContext.combine(client, connection)); logging.trace("Registering Connection to EventLoop"); getCurrentEventLoop().register(connection); } protected final EventLoop createEventLoop() { logging.debug("Creating new EventLoop"); logging.trace("Opening new NIOEventLoop .."); return EventLoop.openBlocking(); } @Override protected final void close() throws IOException { final ServerSocket serverSocket = serverSocketValue.get(); if (serverSocket != null) { serverSocket.close(); } } @Override public final void clear() { if (!serverSocketValue.isEmpty()) { serverSocketValue.clear(); } } @Override public final void establishConnection(final SocketAddress socketAddress) throws StartFailedException { try { final ServerSocket serverSocket = new ServerSocket(); serverSocket.bind(socketAddress); serverSocketValue.set(serverSocket); connected.set(true); } catch (final IOException e) { throw new StartFailedException(e); } } @Override public final void handleNext() throws ClientConnectionFailedException { if (serverSocketValue.isEmpty()) { throw new ClientConnectionFailedException("Not yet launched"); } final ServerSocket serverSocket = serverSocketValue.get(); try { final Socket socket = serverSocket.accept(); registerConnected(socket); } catch (final IOException e) { throw new ClientConnectionFailedException(e); } } } Langsdorf/BlackBird10-100 package com.github.langsdorf.blackbird.user; import java.util.List; import java.util.Map; import com.github.langsdorf.blackbird.user.misc.Relationships; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class User { private long userId; private String name; private String screenName; private String location; private String description; private String profileWebsite; private boolean protectedProfile; private int followers; private int following; private String createdAt; private int favouritesCount; private String timeZone; private boolean verified; private int tweetsCount; private String language; private String profileColor; private String profileBannerUrl; private String profileImageUrl; private List followersList; private List followingList; private List blockList; private List muteList; private Map> relationships; public User(String screenName) { setScreenName(screenName); } public User(long userId) { setUserId(userId); } }springlink/springlink-mybatissrc/main/java/com/github/springlink/mybatis/registry/SqlContext.java /* * Copyright 2019 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 * * https://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.github.springlink.mybatis.registry; import java.util.Map; import org.apache.ibatis.type.TypeAliasRegistry; import com.google.common.base.Strings; import com.google.common.collect.Maps; import com.github.springlink.mybatis.metadata.SqlEntityMetadata; import com.github.springlink.mybatis.metadata.SqlMetadata; import com.github.springlink.mybatis.metadata.SqlPropertyMetadata; import com.github.springlink.mybatis.sql.SqlCriterion; import com.github.springlink.mybatis.sql.SqlOrderBy; import com.github.springlink.mybatis.sql.SqlProjections; import com.github.springlink.mybatis.sql.SqlReference; import com.github.springlink.mybatis.sql.SqlUpdate; import com.github.springlink.mybatis.util.Asserts; public final class SqlContext { public static final String DEFAULT_PATH = "ctx"; private final Map entityInfoMap = Maps.newHashMap(); private final Map propertyInfoMap = Maps.newHashMap(); private final Map objectMap = Maps.newHashMap(); private final SqlDialect dialect; private final TypeAliasRegistry typeAliasRegistry; private final String rootPath; public SqlContext(SqlDialect dialect, TypeAliasRegistry typeAliasRegistry) { this(dialect, typeAliasRegistry, DEFAULT_PATH); } public SqlContext(SqlDialect dialect, TypeAliasRegistry typeAliasRegistry, String rootPath) { Asserts.notNull(dialect, "dialect"); Asserts.notNull(typeAliasRegistry, "typeAliasRegistry"); Asserts.notEmpty(rootPath, "rootPath"); this.dialect = dialect; this.typeAliasRegistry = typeAliasRegistry; this.rootPath = rootPath; } public void bind(String expression) { Asserts.notEmpty(expression, "expression"); for (String element : expression.split(";")) { String[] parts = element.split(":", 2); if (parts.length == 0) { throw new IllegalArgumentException("Invalid bind expression: " + element); } String name = (parts.length == 2 ? Strings.emptyToNull(parts[0].trim()) : null); String[] defs = (parts.length == 2 ? parts[1] : parts[0]).split("#"); if (defs.length == 0) { throw new IllegalArgumentException("Invalid bind expression: " + element); } String typeAlias = defs[0].trim(); String alias = defs.length == 2 ? Strings.emptyToNull(defs[1].trim()) : null; if (typeAlias.isEmpty()) { throw new IllegalArgumentException("Invalid bind expression: " + element); } putEntity(name, typeAlias, alias); } } public String sql(String name) { Asserts.notEmpty(name, "name"); Object obj = getObject(name); if (obj == null) { return ""; } String path = getObjectPath(name); if (obj instanceof SqlCriterion) { return dialect.getCriterionSql(this, path, (SqlCriterion) obj); } else if (obj instanceof SqlOrderBy) { return dialect.getOrderBySql(this, path, (SqlOrderBy) obj); } else if (obj instanceof SqlUpdate) { return dialect.getUpdateSql(this, path, (SqlUpdate) obj); } else if (obj instanceof SqlProjections) { return dialect.getProjectionsSql(this, path, (SqlProjections) obj); } else { throw new IllegalArgumentException("Illegal object type " + obj.getClass().getName() + ": [" + name + "]"); } } public SqlContext putEntity(String typeAlias, String alias) { Asserts.notEmpty(typeAlias, "typeAlias"); return putEntity(null, typeAlias, alias); } public SqlContext putEntity(String name, String typeAlias, String alias) { Asserts.notEmpty(typeAlias, "typeAlias"); return putEntity(name, typeAliasRegistry.resolveAlias(typeAlias), alias); } public SqlContext putEntity(Class entityType, String alias) { Asserts.notNull(entityType, "entityType"); return putEntity(null, entityType, alias); } public SqlContext putEntity(String name, Class entityType, String alias) { Asserts.notNull(entityType, "entityType"); entityInfoMap.put(Strings.nullToEmpty(name), new EntityInfo(SqlMetadata.forEntityType(entityType), alias)); return this; } public SqlContext putObject(String name, Object obj) { Asserts.notEmpty(name, "name"); objectMap.put(name, obj); return this; } public SqlContext putObjects(Map objs) { objectMap.putAll(objs); return this; } public String getObjectPath(String name) { Asserts.notEmpty(name, "name"); return rootPath + ".objects." + name; } public Object getObject(String name) { Asserts.notEmpty(name, "name"); return objectMap.get(name); } public Map getObjects() { return objectMap; } public SqlDialect getDialect() { return dialect; } public TypeAliasRegistry getTypeAliasRegistry() { return typeAliasRegistry; } public String getRootPath() { return rootPath; } public SqlEntityMetadata getEntity() { return getEntity(null); } public SqlEntityMetadata getEntity(String name) { return getEntityInfo(name).entity; } public String getTableAlias() { return getTableAlias(null); } public String getTableAlias(String name) { return getEntityInfo(name).alias; } public SqlPropertyMetadata getProperty(String property) { Asserts.notEmpty(property, "property"); return getPropertyInfo(property).property; } public SqlEntityMetadata getPropertyEntity(String property) { Asserts.notEmpty(property, "property"); return getPropertyInfo(property).entity; } public String getColumnAlias(String property) { Asserts.notEmpty(property, "property"); return getPropertyInfo(property).alias; } private EntityInfo getEntityInfo(String name) { String key = Strings.nullToEmpty(name); EntityInfo info = entityInfoMap.get(key); if (info == null) { if (key.isEmpty()) { throw new IllegalArgumentException("No default entity specified"); } else { throw new IllegalArgumentException("No such entity specified: " + name); } } return info; } private PropertyInfo getPropertyInfo(String property) { PropertyInfo info = propertyInfoMap.computeIfAbsent(property, p -> { SqlReference ref = SqlReference.of(property); SqlPropertyMetadata pm = null; String name = ""; EntityInfo er = getEntityInfo(null); while (ref != null && ref.getName() == null) { pm = er.entity.getProperty(ref.getProperty()); ref = pm.getReference() != null ? SqlReference.of(pm.getReference()) : null; } if (ref != null) { name = ref.getName(); er = getEntityInfo(name); while (ref != null && ref.getName().equals(name)) { pm = er.entity.getProperty(ref.getProperty()); ref = pm.getReference() != null ? SqlReference.of(pm.getReference()) : null; } } return ref == null ? new PropertyInfo(er.entity, er.alias, pm) : null; }); if (info == null) { throw new IllegalArgumentException("Unresolvable property: " + property); } return info; } private static class EntityInfo { final SqlEntityMetadata entity; final String alias; private EntityInfo(SqlEntityMetadata entity, String alias) { this.entity = entity; this.alias = alias; } } private static class PropertyInfo extends EntityInfo { final SqlPropertyMetadata property; private PropertyInfo(SqlEntityMetadata entity, String alias, SqlPropertyMetadata property) { super(entity, alias); this.property = property; } } } xchange-cryptonit/src/main/java/org/knowm/xchange/cryptonit2/service/CryptonitTradeService.java package org.knowm.xchange.cryptonit2.service; import static org.knowm.xchange.dto.Order.OrderType.BID; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.knowm.xchange.Exchange; import org.knowm.xchange.cryptonit2.CryptonitAdapters; import org.knowm.xchange.cryptonit2.CryptonitAuthenticatedV2; import org.knowm.xchange.cryptonit2.CryptonitUtils; import org.knowm.xchange.cryptonit2.dto.CryptonitException; import org.knowm.xchange.cryptonit2.dto.trade.CryptonitOrder; import org.knowm.xchange.cryptonit2.dto.trade.CryptonitUserTransaction; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.dto.trade.MarketOrder; import org.knowm.xchange.dto.trade.OpenOrders; import org.knowm.xchange.dto.trade.UserTrades; import org.knowm.xchange.exceptions.ExchangeException; import org.knowm.xchange.service.trade.TradeService; import org.knowm.xchange.service.trade.params.*; import org.knowm.xchange.service.trade.params.orders.DefaultOpenOrdersParamCurrencyPair; import org.knowm.xchange.service.trade.params.orders.OpenOrdersParams; /** @author */ public class CryptonitTradeService extends CryptonitTradeServiceRaw implements TradeService { public CryptonitTradeService(Exchange exchange) { super(exchange); } @Override public OpenOrders getOpenOrders() throws IOException, CryptonitException { return getOpenOrders(createOpenOrdersParams()); } @Override public OpenOrders getOpenOrders(OpenOrdersParams params) throws ExchangeException, IOException { Collection pairs = DefaultOpenOrdersParamCurrencyPair.getPairs(params, exchange); List limitOrders = new ArrayList<>(); for (CurrencyPair pair : pairs) { CryptonitOrder[] openOrders = getCryptonitOpenOrders(pair); for (CryptonitOrder CryptonitOrder : openOrders) { OrderType orderType = CryptonitOrder.getType() == 0 ? OrderType.BID : OrderType.ASK; String id = Integer.toString(CryptonitOrder.getId()); BigDecimal price = CryptonitOrder.getPrice(); limitOrders.add( new LimitOrder( orderType, CryptonitOrder.getAmount(), pair, id, CryptonitOrder.getDatetime(), price)); } } return new OpenOrders(limitOrders); } @Override public String placeMarketOrder(MarketOrder order) throws IOException, CryptonitException { CryptonitAuthenticatedV2.Side side = order.getType().equals(BID) ? CryptonitAuthenticatedV2.Side.buy : CryptonitAuthenticatedV2.Side.sell; CryptonitOrder CryptonitOrder = placeCryptonitMarketOrder(order.getCurrencyPair(), side, order.getOriginalAmount()); if (CryptonitOrder.getErrorMessage() != null) { throw new ExchangeException(CryptonitOrder.getErrorMessage()); } return Integer.toString(CryptonitOrder.getId()); } @Override public String placeLimitOrder(LimitOrder order) throws IOException, CryptonitException { CryptonitAuthenticatedV2.Side side = order.getType().equals(BID) ? CryptonitAuthenticatedV2.Side.buy : CryptonitAuthenticatedV2.Side.sell; CryptonitOrder CryptonitOrder = placeCryptonitOrder( order.getCurrencyPair(), side, order.getOriginalAmount(), order.getLimitPrice()); if (CryptonitOrder.getErrorMessage() != null) { throw new ExchangeException(CryptonitOrder.getErrorMessage()); } return Integer.toString(CryptonitOrder.getId()); } @Override public boolean cancelOrder(String orderId) throws IOException, CryptonitException { return cancelCryptonitOrder(Integer.parseInt(orderId)); } @Override public boolean cancelOrder(CancelOrderParams orderParams) throws IOException { if (orderParams instanceof CancelOrderByIdParams) { return cancelOrder(((CancelOrderByIdParams) orderParams).getOrderId()); } else { return false; } } /** Required parameter types: {@link TradeHistoryParamPaging#getPageLength()} */ @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { Long limit = null; CurrencyPair currencyPair = null; Long offset = null; TradeHistoryParamsSorted.Order sort = null; if (params instanceof TradeHistoryParamPaging) { limit = Long.valueOf(((TradeHistoryParamPaging) params).getPageLength()); } if (params instanceof TradeHistoryParamCurrencyPair) { currencyPair = ((TradeHistoryParamCurrencyPair) params).getCurrencyPair(); } if (params instanceof TradeHistoryParamOffset) { offset = ((TradeHistoryParamOffset) params).getOffset(); } if (params instanceof TradeHistoryParamsSorted) { sort = ((TradeHistoryParamsSorted) params).getOrder(); } CryptonitUserTransaction[] txs = getCryptonitUserTransactions( limit, currencyPair, offset, sort == null ? null : sort.toString()); return CryptonitAdapters.adaptTradeHistory(txs); } @Override public TradeHistoryParams createTradeHistoryParams() { return new CryptonitTradeHistoryParams(null, CryptonitUtils.MAX_TRANSACTIONS_PER_QUERY); } @Override public OpenOrdersParams createOpenOrdersParams() { return new DefaultOpenOrdersParamCurrencyPair(); } @Override public Collection getOrder(String... orderIds) throws IOException { Collection orders = new ArrayList<>(orderIds.length); for (String orderId : orderIds) { orders.add( CryptonitAdapters.adaptOrder(orderId, super.getCryptonitOrder(Long.parseLong(orderId)))); } return orders; } } src/org/open2jam/util/DJMaxDBLoader.java package org.open2jam.util; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; public class DJMaxDBLoader { private static String db_path = "/resources/DJMAX_ONLINE.csv"; private static HashMap> database; private static HashMap> readDB() throws IOException { return readDB(db_path); } /** Read the cvs file and return the result */ private static HashMap> readDB(String path) throws IOException { db_path = path; URL url = DJMaxDBLoader.class.getResource(db_path); BufferedReader r = null; if(url == null) { File file = new File(db_path); if(!file.exists()) return null; r = new BufferedReader(new InputStreamReader(new FileInputStream(file))); } else { r = new BufferedReader(new InputStreamReader(url.openStream())); } if(r == null) return null; database = new HashMap>(); String line; r.readLine(); //we don't need the header while((line = r.readLine()) != null) { line = line.replace("\"", ""); ArrayList al = new ArrayList(); for(String s : line.split("(?=;)")) { if(s.equals(";")) s = "99"; al.add(s.replace(";", "").trim()); } database.put(al.remove(0), al); } return database; } public static HashMap> getDB() throws IOException { if(database == null) return readDB(); else return database; } } package ie.gmit.sw.ai.cloud; public class WordFrequency { private String word; private int frequency; private int fontSize = 0; public WordFrequency(String word, int frequency) { this.word = word; this.frequency = frequency; } public String getWord() { return this.word; } public void setWord(String word) { this.word = word; } public int getFrequency() { return this.frequency; } public void setFrequency(int frequency) { this.frequency = frequency; } public int getFontSize() { return this.fontSize; } public void setFontSize(int size) { this.fontSize = size; } public String toString() { return "Word: " + getWord() + "\tFreq: " + getFrequency() + "\tFont Size: " + getFontSize(); } }SharplEr/HprofCrawler1-10 package org.sharpler.hprofcrawler.parser; import java.util.Arrays; import java.util.List; public enum Type { OBJ("Object", 4), BOOL("boolean", 1), CHAR("char", 2), FLOAT("float", 4), DOUBLE("double", 8), BYTE("byte", 1), SHORT("short", 2), INT("int", 4), LONG("long", 8); public static final List VALUES = Arrays.asList(values()); private final String name; private final int sizeInBytes; private Type(String name, int sizeInBytes) { this.name = name; this.sizeInBytes = sizeInBytes; } public int sizeInBytes() { return sizeInBytes; } public static Type hprofTypeToEnum(byte type) { switch (type) { case 2: return OBJ; case 4: return BOOL; case 5: return CHAR; case 6: return FLOAT; case 7: return DOUBLE; case 8: return BYTE; case 9: return SHORT; case 10: return INT; case 11: return LONG; default: throw new IllegalArgumentException("Unexpected type in heap dump: " + type); } } @Override public String toString() { return name; } } 0 package com.google.cloud.bigquery.connector.common; import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.bigquery.Field; import com.google.cloud.bigquery.Schema; import com.google.cloud.bigquery.StandardSQLTypeName; import com.google.cloud.bigquery.StandardTableDefinition; import com.google.cloud.bigquery.TableId; import com.google.cloud.bigquery.TableInfo; import com.google.cloud.bigquery.storage.v1.BigQueryReadClient; import com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest; import com.google.cloud.bigquery.storage.v1.ReadSession; import com.google.cloud.bigquery.storage.v1.ReadSession.TableReadOptions; import com.google.cloud.bigquery.storage.v1.stub.EnhancedBigQueryReadStub; import com.google.common.collect.ImmutableList; import java.util.Optional; import org.junit.Test; import org.mockito.ArgumentCaptor; public class ReadSessionCreatorTest { EnhancedBigQueryReadStub stub = mock(EnhancedBigQueryReadStub.class); BigQueryClient bigQueryClient = mock(BigQueryClient.class); UnaryCallable createReadSessionCall = mock(UnaryCallable.class); BigQueryReadClient readClient = BigQueryReadClient.create(stub); BigQueryClientFactory bigQueryReadClientFactory = mock(BigQueryClientFactory.class); TableInfo table = TableInfo.newBuilder( TableId.of("a", "b"), StandardTableDefinition.newBuilder() .setSchema(Schema.of(Field.of("name", StandardSQLTypeName.BOOL))) .setNumBytes(1L) .build()) .build(); @Test public void testSerializedInstanceIsPropagated() throws Exception { TableReadOptions tableReadOptions = TableReadOptions.newBuilder().build(); ReadSession readSession = ReadSession.newBuilder().setName("abc").setReadOptions(tableReadOptions).build(); CreateReadSessionRequest request = CreateReadSessionRequest.newBuilder().setReadSession(readSession).build(); Optional encodedBase = Optional.of(java.util.Base64.getEncoder().encodeToString(request.toByteArray())); ReadSessionCreatorConfig config = new ReadSessionCreatorConfigBuilder().setRequestEncodedBase(encodedBase).build(); ReadSessionCreator creator = new ReadSessionCreator(config, bigQueryClient, bigQueryReadClientFactory); when(bigQueryReadClientFactory.createBigQueryReadClient(eq(Optional.empty()))) .thenReturn(readClient); when(bigQueryClient.getTable(any())).thenReturn(table); when(stub.createReadSessionCallable()).thenReturn(createReadSessionCall); creator .create(TableId.of("dataset", "table"), ImmutableList.of("col1", "col2"), Optional.empty()) .getReadSession(); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(CreateReadSessionRequest.class); verify(createReadSessionCall, times(1)).call(requestCaptor.capture()); ReadSession actual = requestCaptor.getValue().getReadSession(); assertThat(actual.getName()).isEqualTo("abc"); assertThat(actual.getReadOptions().getSelectedFieldsList()).containsExactly("col1", "col2"); } } package com.easy.restful.sys.dao; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.easy.restful.sys.model.SysFile; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 文件 * * @author 系统管理员 * @date 2021-02-21 */ public interface SysFileMapper extends BaseMapper { /** * 获取列表数据 * * @param queryWrapper 查询条件 * @return List */ List select(@Param("ew") QueryWrapper queryWrapper); }src/main/migrations/org/mamute/migration/all/M015CreateBlockedIpTable.java package org.mamute.migration.all; import org.mamute.migration.MigrationOperation; import org.mamute.migration.RawSQLOperation; import org.mamute.migration.SchemaMigration; import javax.enterprise.context.ApplicationScoped; import java.util.List; @ApplicationScoped public class M015CreateBlockedIpTable implements SchemaMigration { @Override public List up() { String q1 = " create table BlockedIp (\n" + " id bigint not null auto_increment,\n" + " createdAt datetime,\n" + " ip varchar(255),\n" + " primary key (id)\n" + " ) ENGINE=InnoDB"; return RawSQLOperation.forSqls(q1); } @Override public List down() { return RawSQLOperation.forSqls(); } } sunshower-io/sunshower-base package io.sunshower.persist; import java.time.Clock; public interface TimeBased { Clock getClock(); } package com.example.myapplication; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import android.util.Log; public class MainActivity extends AppCompatActivity { public static final String TAG="myMessage"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.i(TAG,"inside onCreate"); Toast mytoast=Toast.makeText(getApplicationContext(),"I'm inside onCreate()",Toast.LENGTH_SHORT); mytoast.show(); } @Override protected void onStart() { super.onStart(); Log.i(TAG,"inside onStart"); Toast mytoast=Toast.makeText(getApplicationContext(),"I'm inside onStart()",Toast.LENGTH_SHORT); mytoast.show(); } @Override protected void onStop() { super.onStop(); Log.i(TAG,"inside onStop"); Toast mytoast=Toast.makeText(getApplicationContext(),"I'm inside onStop()",Toast.LENGTH_SHORT); mytoast.show(); } @Override protected void onDestroy() { super.onDestroy(); Log.i(TAG,"inside onDestroy"); Toast mytoast=Toast.makeText(getApplicationContext(),"I'm inside onDestroy()",Toast.LENGTH_SHORT); mytoast.show(); } @Override protected void onPause() { super.onPause(); Toast mytoast=Toast.makeText(getApplicationContext(),"I'm inside onPause()",Toast.LENGTH_SHORT); mytoast.show(); } //@Override /*protected void onResume() { super.onResume(); Log.i(TAG,"inside onResume"); Toast mytoast=Toast.makeText(getApplicationContext(),"I'm inside onResume()",Toast.LENGTH_SHORT); mytoast.show(); } */ @Override protected void onRestart() { super.onRestart(); Log.i(TAG,"inside onRestart"); Toast mytoast=Toast.makeText(getApplicationContext(),"I'm inside onRestart()",Toast.LENGTH_SHORT); mytoast.show(); } } sra/src/main/java/org/apache/syncope/sra/security/cas/CASAuthenticationToken.java /* * 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.syncope.sra.security.cas; import org.apache.commons.lang3.StringUtils; import org.jasig.cas.client.validation.Assertion; import org.springframework.security.authentication.AbstractAuthenticationToken; public class CASAuthenticationToken extends AbstractAuthenticationToken { private static final long serialVersionUID = 6333776590644298469L; private final Assertion assertion; public CASAuthenticationToken(final Assertion assertion) { super(null); this.assertion = assertion; this.setAuthenticated(true); } @Override public Object getCredentials() { return StringUtils.EMPTY; } @Override public Assertion getPrincipal() { return assertion; } } /* * MIT License * * Copyright (c) 2018 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package fko.FrankyEngine.Franky; import fko.UCI.IUCIProtocolHandler; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Duration; import java.time.Instant; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Attempt at a proper Unit Test for Evaluation */ public class EvaluationTest { private static final Logger LOG = LoggerFactory.getLogger(EvaluationTest.class); private String fenStandard; private Position position; private Evaluation evaluation; @BeforeEach public void setUp() { fenStandard = IUCIProtocolHandler.START_FEN; position = new Position(fenStandard); evaluation = new Evaluation(); } @Test void evaluate() { // standard position should be 0 // change if next player gets a bonus position = new Position(fenStandard); int value = evaluation.evaluate(position); assertEquals(10, value, "Start Position should be 10 from TEMPO"); // Mirrored position - should be equal position = new Position("k6n/7p/6P1/7K/8/8/8/8 w - - 0 1"); int value1 = evaluation.evaluate(position); LOG.info(evaluation.toString()); position = new Position("8/8/8/8/k7/1p6/P7/N6K b - - 0 1"); int value2 = evaluation.evaluate(position); LOG.info(evaluation.toString()); assertEquals(value1, value2, "Mirrored Position should be equal"); } @Test void material() { // Start position position = new Position(fenStandard); int value = evaluation.material(position); assertEquals(0, value); // other positions String fen = "k6n/7p/6P1/7K/8/8/8/8 w - - 0 1"; // white position = new Position(fen); value = evaluation.material(position); // System.out.println(value); assertEquals(-320, value); fen = "8/8/8/8/k7/1p6/P7/N6K b - - 0 1"; // black position = new Position(fen); value = evaluation.material(position); // System.out.println(value); assertEquals(-320, value); } @Test void mobility() { // Start position position = new Position(fenStandard); int value = evaluation.mobility(position); //System.out.println(value); assertEquals(0, value); // other positions String fen = "r3k2r/1ppn3p/2q1q1n1/8/2q1Pp2/6R1/p1p2PPP/1R4K1 b kq e3 0 113"; position = new Position(fen); value = evaluation.mobility(position); //System.out.println(value); assertEquals(52, value); fen = "k6n/7p/6P1/7K/8/8/8/8 w - - 0 1"; // white position = new Position(fen); value = evaluation.mobility(position); //System.out.println(value); assertEquals(-4, value); fen = "8/8/8/8/k7/1p6/P7/N6K b - - 0 1"; // black position = new Position(fen); value = evaluation.mobility(position); //System.out.println(value); assertEquals(-4, value); } @Test void position() { int value; // Start Position position = new Position(); value = evaluation.position(this.position); assertEquals(0, value); this.position.makeMove(Move.fromUCINotation(this.position, "e2e4")); value = evaluation.position(this.position); assertEquals(-55, value); this.position.makeMove(Move.fromUCINotation(this.position, "e7e5")); value = evaluation.position(this.position); assertEquals(0, value); this.position.makeMove(Move.fromUCINotation(this.position, "g1f3")); value = evaluation.position(this.position); assertEquals(-50, value); // All White pieces no Black pieces but King this.position = new Position("4k3/8/8/8/8/8/PPPPPPPP/RNBQKBNR w KQ - 0 1"); assertEquals(-117, evaluation.position(this.position)); // All Black pieces no White pieces but King this.position = new Position("rnbqkbnr/pppppppp/8/8/8/8/8/4K3 w kq - 0 1"); assertEquals(117, evaluation.position(this.position)); } @Test public final void testNeutralPosition() { position = new Position("7k/7p/8/8/8/8/P7/K7 w - - 0 1"); int mat = evaluation.material(position); int mob = evaluation.mobility(position); System.out.println("Material: " + mat); System.out.println("Mobility: " + mob); position = new Position("7k/7p/8/8/8/8/P7/K7 b - - 0 1"); mat = evaluation.material(position); mob = evaluation.mobility(position); System.out.println("Material: " + mat); System.out.println("Mobility: " + mob); assertEquals(0, mat); assertEquals(0, mob); } @Test public final void testCheckPosition() { // no in check position = new Position("r6k/6R1/p4p1p/2p2P1P/1pq1PN2/6P1/1PP5/2KR4 w - - 0 1"); assertEquals(191, evaluation.evaluate(position)); LOG.info(evaluation.toString()); // white gives check to black position = new Position("r2R3k/6R1/p4p1p/2p2P1P/1pq1PN2/6P1/1PP5/2K5 b - - 0 1"); assertEquals(-234, evaluation.evaluate(position)); LOG.info(evaluation.toString()); // black gives check to white position = new Position("r6k/6R1/p4p1p/2p2P1P/1p1qPN2/6P1/1PPK4/3R4 w - - 0 2"); assertEquals(135, evaluation.evaluate(position)); LOG.info(evaluation.toString()); } @Test public final void testSinglePieces() { // king values position = new Position("8/4k3/8/8/8/8/8/4K3 w - -"); assertEquals(0, evaluation.evaluate(position)); LOG.info(evaluation.toString()); position = new Position("8/4k3/8/8/8/8/8/4K3 b - -"); assertEquals(0, evaluation.evaluate(position)); } @Test public final void testKingSafety() { position = new Position("rnbq1rk1/pppp1ppp/5n2/2b1p3/2B1P3/5N2/PPPP1PPP/RNBQ1RK1 w - -"); assertEquals(0, evaluation.kingSafety(position)); LOG.info(evaluation.toString()); position = new Position("2kr1bnr/pppq1ppp/2np4/4p3/2B1P1b1/2NP1N2/PPP2PPP/R1BQ1RK1 w - -"); assertEquals(10, evaluation.kingSafety(position)); LOG.info(evaluation.toString()); position = new Position("rnbq1rk1/pppp1ppp/5n2/2b1p3/2B1P3/5N2/PPPP1PPP/RNBQ1RK1 b - -"); assertEquals(0, evaluation.kingSafety(position)); LOG.info(evaluation.toString()); position = new Position("2kr1bnr/pppq1ppp/2np4/4p3/2B1P1b1/2NP1N2/PPP2PPP/R1BQ1RK1 b - -"); assertEquals(-10, evaluation.kingSafety(position)); LOG.info(evaluation.toString()); } @Test public void testPositionValue() { position = new Position(); int move; move = Move.fromSANNotation(position, "e4"); assertEquals(25, Evaluation.getPositionValue(position, move)); move = Move.fromSANNotation(position, "c3"); assertEquals(-10, Evaluation.getPositionValue(position, move)); move = Move.fromSANNotation(position, "Na3"); assertEquals(-30, Evaluation.getPositionValue(position, move)); position = new Position("r1bqkbnr/pppp1ppp/2n5/1B2p3/4P3/5N2/PPPP1PPP/RNBQK2R b KQkq -"); move = Move.fromSANNotation(position, "a6"); assertEquals(5, Evaluation.getPositionValue(position, move)); move = Move.fromSANNotation(position, "Qh4"); assertEquals(-5, Evaluation.getPositionValue(position, move)); move = Move.fromSANNotation(position, "Ke7"); assertEquals(-20, Evaluation.getPositionValue(position, move)); } @Test @Disabled public final void testNewEvals() { position = new Position("r1bq1rk1/pp1p1ppp/2n2b2/2p1p3/4P3/2NP1NP1/PPP1KPBP/R2Q3R b - - 1 1"); evaluation.evaluate(position); } @Test @Disabled public void testTiming() { int ROUNDS = 5; int DURATION = 2; int ITERATIONS = 0; Instant start; System.out.println("Running Timing Test"); String fen = "r3k2r/1ppn3p/2q1q1n1/8/2q1Pp2/6R1/p1p2PPP/1R4K1 b kq e3 0 113"; position = new Position(fen); for (int j = 0; j < ROUNDS; j++) { System.gc(); start = Instant.now(); ITERATIONS = 0; do { ITERATIONS++; // ### TEST CODE testCode(); // ### /TEST CODE } while (Duration.between(start, Instant.now()).getSeconds() < DURATION); System.out.println(String.format("Timing: %,7d runs/s", ITERATIONS / DURATION)); } } private void testCode() { evaluation.evaluate(position); } } package com.castrodev.reddit.detail; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.support.annotation.VisibleForTesting; import android.support.customtabs.CustomTabsIntent; import android.support.test.espresso.IdlingResource; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.castrodev.reddit.R; import com.castrodev.reddit.model.RedditObject; import com.castrodev.reddit.model.RedditParcelableObject; import com.castrodev.reddit.util.EspressoIdlingResource; import com.castrodev.reddit.util.NetworkUtils; import com.squareup.picasso.Picasso; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.castrodev.reddit.main.MainActivity.KEY; public class DetailActivity extends AppCompatActivity implements DetailView { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.rv_comments) RecyclerView rvComments; @BindView(R.id.progress) ProgressBar progressBar; @BindView(R.id.iv_detail_post) ImageView ivDetailPost; @BindView(R.id.tv_author) TextView tvAuthor; @BindView(R.id.tv_comment_count) TextView tvCommentCount; @BindView(R.id.tv_error) TextView tvError; @BindView(R.id.error_view) View errorView; private DetailPresenter presenter; private RedditParcelableObject redditParcelableObject; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); ButterKnife.bind(this); getParcelableObject(); presenter = new DetailPresenterImpl(this, redditParcelableObject.getPermalink()); setupView(); } private void getParcelableObject() { if (getIntent().hasExtra(KEY)) { redditParcelableObject = getIntent().getParcelableExtra(KEY); } } private void setupView() { toolbar.setTitle(redditParcelableObject.getTitle()); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Resources res = getResources(); tvAuthor.setText( String.format(res.getString(R.string.author_name) , redditParcelableObject.getAuthor())); tvCommentCount.setText( String.format(res.getString(R.string.comments_count) , redditParcelableObject.getNumComments())); Picasso.with(this) .load(redditParcelableObject.getThumbnail()) .error(R.drawable.ic_error_image) .into(ivDetailPost); } @Override protected void onResume() { super.onResume(); presenter.onResume(); } @Override public void showProgress() { progressBar.setVisibility(View.VISIBLE); rvComments.setVisibility(View.INVISIBLE); } @Override public void hideProgress() { progressBar.setVisibility(View.INVISIBLE); rvComments.setVisibility(View.VISIBLE); } @Override public void setItems(List redditObjectList) { errorView.setVisibility(View.GONE); RedditObject objectWithComments = redditObjectList.get(1); rvComments.setLayoutManager(new LinearLayoutManager(this)); rvComments.setAdapter(new DetailAdapter(objectWithComments, presenter)); } @Override public void openPostLink(String url) { int colorInt = ContextCompat.getColor(this, R.color.colorPrimary); CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder(); builder.setToolbarColor(colorInt); CustomTabsIntent customTabsIntent = builder.build(); customTabsIntent.launchUrl(this, Uri.parse(url)); } @Override public void showError(int message) { rvComments.setVisibility(View.GONE); errorView.setVisibility(View.VISIBLE); tvError.setText(message); } @Override public boolean isConnected() { return NetworkUtils.isConnected(this); } @OnClick(R.id.fabNavigate) public void onFabClicked(View v) { presenter.showUrl(redditParcelableObject.getUrl()); } @VisibleForTesting public IdlingResource getCountingIdlingResource() { return EspressoIdlingResource.getIdlingResource(); } @OnClick(R.id.bt_try_again) public void tryAgain(View v){ presenter.onResume(); } } begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|activemq operator|. name|transport operator|. name|failover package|; end_package begin_class specifier|public class|class name|TwoBrokerFailoverClusterTest extends|extends name|FailoverClusterTestSupport block|{ specifier|private specifier|static specifier|final name|String name|BROKER_A_CLIENT_TC_ADDRESS init|= literal|"tcp://127.0.0.1:61616" decl_stmt|; specifier|private specifier|static specifier|final name|String name|BROKER_B_CLIENT_TC_ADDRESS init|= literal|"tcp://127.0.0.1:61617" decl_stmt|; specifier|private specifier|static specifier|final name|String name|BROKER_A_NOB_TC_ADDRESS init|= literal|"tcp://127.0.0.1:61626" decl_stmt|; specifier|private specifier|static specifier|final name|String name|BROKER_B_NOB_TC_ADDRESS init|= literal|"tcp://127.0.0.1:61627" decl_stmt|; specifier|private specifier|static specifier|final name|String name|BROKER_A_NAME init|= literal|"BROKERA" decl_stmt|; specifier|private specifier|static specifier|final name|String name|BROKER_B_NAME init|= literal|"BROKERB" decl_stmt|; specifier|public name|void name|testTwoBrokersRestart parameter_list|() throws|throws name|Exception block|{ name|createBrokerA argument_list|( literal|false argument_list|, literal|"" argument_list|, literal|null argument_list|, literal|null argument_list|) expr_stmt|; name|createBrokerB argument_list|( literal|false argument_list|, literal|"" argument_list|, literal|null argument_list|, literal|null argument_list|) expr_stmt|; name|getBroker argument_list|( name|BROKER_B_NAME argument_list|) operator|. name|waitUntilStarted argument_list|() expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|2000 argument_list|) expr_stmt|; name|setClientUrl argument_list|( literal|"failover://(" operator|+ name|BROKER_A_CLIENT_TC_ADDRESS operator|+ literal|"," operator|+ name|BROKER_B_CLIENT_TC_ADDRESS operator|+ literal|")?randomize=false&jms.watchTopicAdvisories=false" argument_list|) expr_stmt|; name|createClients argument_list|() expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|5000 argument_list|) expr_stmt|; name|assertClientsConnectedToTwoBrokers argument_list|() expr_stmt|; name|assertClientsConnectionsEvenlyDistributed argument_list|( literal|.35 argument_list|) expr_stmt|; name|getBroker argument_list|( name|BROKER_A_NAME argument_list|) operator|. name|stop argument_list|() expr_stmt|; name|getBroker argument_list|( name|BROKER_A_NAME argument_list|) operator|. name|waitUntilStopped argument_list|() expr_stmt|; name|removeBroker argument_list|( name|BROKER_A_NAME argument_list|) expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|1000 argument_list|) expr_stmt|; name|assertAllConnected argument_list|( name|NUMBER_OF_CLIENTS argument_list|) expr_stmt|; name|assertAllConnectedTo argument_list|( name|BROKER_B_CLIENT_TC_ADDRESS argument_list|) expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|5000 argument_list|) expr_stmt|; name|logger operator|. name|info argument_list|( literal|"Restarting A" argument_list|) expr_stmt|; name|createBrokerA argument_list|( literal|false argument_list|, literal|"" argument_list|, literal|null argument_list|, literal|null argument_list|) expr_stmt|; name|getBroker argument_list|( name|BROKER_A_NAME argument_list|) operator|. name|waitUntilStarted argument_list|() expr_stmt|; name|Thread operator|. name|sleep argument_list|( literal|5000 argument_list|) expr_stmt|; name|assertAllConnected argument_list|( name|NUMBER_OF_CLIENTS argument_list|) expr_stmt|; name|assertClientsConnectedToTwoBrokers argument_list|() expr_stmt|; name|assertClientsConnectionsEvenlyDistributed argument_list|( literal|.35 argument_list|) expr_stmt|; block|} specifier|private name|void name|createBrokerA parameter_list|( name|boolean name|multi parameter_list|, name|String name|params parameter_list|, name|String name|clusterFilter parameter_list|, name|String name|destinationFilter parameter_list|) throws|throws name|Exception block|{ specifier|final name|String name|tcParams init|= operator|( name|params operator|== literal|null operator|) condition|? literal|"" else|: name|params decl_stmt|; if|if condition|( name|getBroker argument_list|( name|BROKER_A_NAME argument_list|) operator|== literal|null condition|) block|{ name|addBroker argument_list|( name|BROKER_A_NAME argument_list|, name|createBroker argument_list|( name|BROKER_A_NAME argument_list|) argument_list|) expr_stmt|; name|addTransportConnector argument_list|( name|getBroker argument_list|( name|BROKER_A_NAME argument_list|) argument_list|, literal|"openwire" argument_list|, name|BROKER_A_CLIENT_TC_ADDRESS operator|+ name|tcParams argument_list|, literal|true argument_list|) expr_stmt|; if|if condition|( name|multi condition|) block|{ name|addTransportConnector argument_list|( name|getBroker argument_list|( name|BROKER_A_NAME argument_list|) argument_list|, literal|"network" argument_list|, name|BROKER_A_NOB_TC_ADDRESS operator|+ name|tcParams argument_list|, literal|false argument_list|) expr_stmt|; name|addNetworkBridge argument_list|( name|getBroker argument_list|( name|BROKER_A_NAME argument_list|) argument_list|, literal|"A_2_B_Bridge" argument_list|, literal|"static://(" operator|+ name|BROKER_B_NOB_TC_ADDRESS operator|+ literal|")?useExponentialBackOff=false" argument_list|, literal|false argument_list|, name|clusterFilter argument_list|) expr_stmt|; block|} else|else block|{ name|addNetworkBridge argument_list|( name|getBroker argument_list|( name|BROKER_A_NAME argument_list|) argument_list|, literal|"A_2_B_Bridge" argument_list|, literal|"static://(" operator|+ name|BROKER_B_CLIENT_TC_ADDRESS operator|+ literal|")?useExponentialBackOff=false" argument_list|, literal|false argument_list|, name|clusterFilter argument_list|) expr_stmt|; block|} name|getBroker argument_list|( name|BROKER_A_NAME argument_list|) operator|. name|start argument_list|() expr_stmt|; block|} block|} specifier|private name|void name|createBrokerB parameter_list|( name|boolean name|multi parameter_list|, name|String name|params parameter_list|, name|String name|clusterFilter parameter_list|, name|String name|destinationFilter parameter_list|) throws|throws name|Exception block|{ specifier|final name|String name|tcParams init|= operator|( name|params operator|== literal|null operator|) condition|? literal|"" else|: name|params decl_stmt|; if|if condition|( name|getBroker argument_list|( name|BROKER_B_NAME argument_list|) operator|== literal|null condition|) block|{ name|addBroker argument_list|( name|BROKER_B_NAME argument_list|, name|createBroker argument_list|( name|BROKER_B_NAME argument_list|) argument_list|) expr_stmt|; name|addTransportConnector argument_list|( name|getBroker argument_list|( name|BROKER_B_NAME argument_list|) argument_list|, literal|"openwire" argument_list|, name|BROKER_B_CLIENT_TC_ADDRESS operator|+ name|tcParams argument_list|, literal|true argument_list|) expr_stmt|; if|if condition|( name|multi condition|) block|{ name|addTransportConnector argument_list|( name|getBroker argument_list|( name|BROKER_B_NAME argument_list|) argument_list|, literal|"network" argument_list|, name|BROKER_B_NOB_TC_ADDRESS operator|+ name|tcParams argument_list|, literal|false argument_list|) expr_stmt|; name|addNetworkBridge argument_list|( name|getBroker argument_list|( name|BROKER_B_NAME argument_list|) argument_list|, literal|"B_2_A_Bridge" argument_list|, literal|"static://(" operator|+ name|BROKER_A_NOB_TC_ADDRESS operator|+ literal|")?useExponentialBackOff=false" argument_list|, literal|false argument_list|, name|clusterFilter argument_list|) expr_stmt|; block|} else|else block|{ name|addNetworkBridge argument_list|( name|getBroker argument_list|( name|BROKER_B_NAME argument_list|) argument_list|, literal|"B_2_A_Bridge" argument_list|, literal|"static://(" operator|+ name|BROKER_A_CLIENT_TC_ADDRESS operator|+ literal|")?useExponentialBackOff=false" argument_list|, literal|false argument_list|, name|clusterFilter argument_list|) expr_stmt|; block|} name|getBroker argument_list|( name|BROKER_B_NAME argument_list|) operator|. name|start argument_list|() expr_stmt|; block|} block|} block|} end_class end_unit IMCG/MapReduce /** * 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.hadoop.hive.ql; import java.io.File; import java.io.DataInput; import java.io.IOException; import java.io.FileNotFoundException; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.util.StringUtils; import java.util.Random; public class Context { private Path resFile; private Path resDir; private FileSystem fs; static final private Log LOG = LogFactory.getLog("hive.ql.Context"); private Path[] resDirPaths; private int resDirFilesNum; boolean initialized; private String scratchDir; private HiveConf conf; public Context(HiveConf conf) { try { this.conf = conf; fs = FileSystem.get(conf); initialized = false; resDir = null; resFile = null; } catch (IOException e) { LOG.info("Context creation error: " + StringUtils.stringifyException(e)); } } public void makeScratchDir() throws Exception { Random rand = new Random(); int randomid = Math.abs(rand.nextInt()%rand.nextInt()); scratchDir = conf.getVar(HiveConf.ConfVars.SCRATCHDIR) + File.separator + randomid; Path tmpdir = new Path(scratchDir); fs.mkdirs(tmpdir); } public String getScratchDir() { return scratchDir; } public void removeScratchDir() throws Exception { Path tmpdir = new Path(scratchDir); fs.delete(tmpdir, true); } /** * @return the resFile */ public Path getResFile() { return resFile; } /** * @param resFile the resFile to set */ public void setResFile(Path resFile) { this.resFile = resFile; resDir = null; resDirPaths = null; resDirFilesNum = 0; } /** * @return the resDir */ public Path getResDir() { return resDir; } /** * @param resDir the resDir to set */ public void setResDir(Path resDir) { this.resDir = resDir; resFile = null; resDirFilesNum = 0; resDirPaths = null; } public void clear() { initialized = false; if (resDir != null) { try { fs.delete(resDir, true); } catch (IOException e) { LOG.info("Context clear error: " + StringUtils.stringifyException(e)); } } if (resFile != null) { try { fs.delete(resFile, false); } catch (IOException e) { LOG.info("Context clear error: " + StringUtils.stringifyException(e)); } } resDir = null; resFile = null; resDirFilesNum = 0; resDirPaths = null; } public DataInput getStream() { try { if (!initialized) { initialized = true; if ((resFile == null) && (resDir == null)) return null; if (resFile != null) return (DataInput)fs.open(resFile); FileStatus status = fs.getFileStatus(resDir); assert status.isDir(); FileStatus[] resDirFS = fs.globStatus(new Path(resDir + "/*")); resDirPaths = new Path[resDirFS.length]; int pos = 0; for (FileStatus resFS: resDirFS) if (!resFS.isDir()) resDirPaths[pos++] = resFS.getPath(); if (pos == 0) return null; return (DataInput)fs.open(resDirPaths[resDirFilesNum++]); } else { return getNextStream(); } } catch (FileNotFoundException e) { LOG.info("getStream error: " + StringUtils.stringifyException(e)); return null; } catch (IOException e) { LOG.info("getStream error: " + StringUtils.stringifyException(e)); return null; } } private DataInput getNextStream() { try { if (resDir != null && resDirFilesNum < resDirPaths.length && (resDirPaths[resDirFilesNum] != null)) return (DataInput)fs.open(resDirPaths[resDirFilesNum++]); } catch (FileNotFoundException e) { LOG.info("getNextStream error: " + StringUtils.stringifyException(e)); return null; } catch (IOException e) { LOG.info("getNextStream error: " + StringUtils.stringifyException(e)); return null; } return null; } } /* * Copyright (C) 2000-2013 * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. 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 eu.javaspecialists.tjsn.concurrency.util; /** * A class maintaining a single reference variable serving as the result * of an operation. The result cannot be accessed until it has been set. *

* It is based on Doug Lea's EDU.oswego.cs.dl.util.concurrent.FutureResult. * * @author , Dr */ final public class FutureResult { private V value; private boolean ready; public synchronized V get() throws InterruptedException { while (!ready) { wait(100); } return value; } public synchronized void set(V newValue) { value = newValue; ready = true; notifyAll(); } public synchronized boolean isReady() { return ready; } }package com.github.jolice.gui.multipage; import org.junit.Test; import com.github.jolice.gui.multipage.player.PlayerPages; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.UUID; import static org.junit.Assert.*; public class PlayerPagesTest { @Test public void hasSession() { PlayerPages playerPages = new PlayerPages(); UUID first = UUID.randomUUID(); UUID second = UUID.randomUUID(); playerPages.setPlayerPage(first, 1); assertTrue(playerPages.hasSession(first)); assertFalse(playerPages.hasSession(second)); } @Test public void clear() { PlayerPages playerPages = new PlayerPages(); UUID first = UUID.randomUUID(); playerPages.setPlayerPage(first, 1); playerPages.clear(); assertTrue(playerPages.getActiveSessions().isEmpty()); assertNull(playerPages.getPlayerPage(first)); } @Test public void getActiveSessions() { PlayerPages playerPages = new PlayerPages(); UUID first, second; do { first = UUID.randomUUID(); second = UUID.randomUUID(); } while (first.equals(second)); playerPages.setPlayerPage(first, 2); playerPages.setPlayerPage(second, 3); assertEquals(new HashSet<>(Arrays.asList(first, second)), playerPages.getActiveSessions()); } @Test public void rearrangeAfterRemoval() { PlayerPages playerPages = new PlayerPages(); UUID a = UUID.randomUUID(); UUID b = UUID.randomUUID(); UUID c = UUID.randomUUID(); UUID d = UUID.randomUUID(); playerPages.setPlayerPage(a, 1); playerPages.setPlayerPage(b, 2); playerPages.setPlayerPage(c, 2); playerPages.setPlayerPage(d, 3); Set currentlyLookingAtPage = playerPages.rearrangeAfterRemoval(2); assertEquals(new HashSet<>(Arrays.asList(b, c)), currentlyLookingAtPage); assertEquals(2, playerPages.getPlayerPage(d)); assertEquals(1, playerPages.getPlayerPage(a)); assertNull(playerPages.getPlayerPage(b)); assertNull(playerPages.getPlayerPage(c)); } @Test public void switchPage() { PlayerPages playerPages = new PlayerPages(); UUID uuid = UUID.randomUUID(); playerPages.setPlayerPage(uuid, 2); playerPages.switchPage(uuid, operand -> operand + 1); assertEquals(3, playerPages.getPlayerPage(uuid)); playerPages.switchPage(uuid, operand -> operand - 1); assertEquals(2, playerPages.getPlayerPage(uuid)); } @Test public void removePlayer() { PlayerPages playerPages = new PlayerPages(); UUID uuid = UUID.randomUUID(); playerPages.setPlayerPage(uuid, 1); assertEquals(1, playerPages.getPlayerPage(uuid)); playerPages.removePlayer(uuid); assertNull(playerPages.getPlayerPage(uuid)); } }package com.vaadin.demo.component.progressbar; import com.vaadin.demo.DemoExporter; // hidden-full-source-line import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.progressbar.ProgressBar; import com.vaadin.flow.component.progressbar.ProgressBarVariant; import com.vaadin.flow.router.Route; @Route("progress-bar-theme-variants") public class ProgressBarThemeVariants extends VerticalLayout { public ProgressBarThemeVariants() { setPadding(false); getStyle().set("font-family", "var(--lumo-font-family)").set("color", "var(--lumo-secondary-text-color)"); // Contrast // tag::snippet[] ProgressBar progressBarContrast = new ProgressBar(); progressBarContrast.addThemeVariants(ProgressBarVariant.LUMO_CONTRAST); // end::snippet[] progressBarContrast.setValue(0.5); Div progressBarContrastLabel = new Div(); progressBarContrastLabel.setText("Transferring files... (60/120)"); Div progressBarContrastWrapper = new Div(progressBarContrastLabel, progressBarContrast); progressBarContrastWrapper.setWidthFull(); add(progressBarContrastWrapper); // Success ProgressBar progressBarSuccess = new ProgressBar(); progressBarSuccess.addThemeVariants(ProgressBarVariant.LUMO_SUCCESS); progressBarSuccess.setValue(0.75); Div progressBarSuccessLabel = new Div(); progressBarSuccessLabel.setText("Tasks (15/20)"); Div progressBarSuccessWrapper = new Div(progressBarSuccessLabel,progressBarSuccess); progressBarSuccessWrapper.setWidthFull(); add(progressBarSuccessWrapper); // Error ProgressBar progressBarError = new ProgressBar(); progressBarError.addThemeVariants(ProgressBarVariant.LUMO_ERROR); progressBarError.setValue(0.2); Div progressBarErrorLabel = new Div(); progressBarErrorLabel.setText("Tasks (4/20)"); Div progressBarErrorWrapper = new Div(progressBarErrorLabel, progressBarError); progressBarErrorWrapper.setWidthFull(); add(progressBarErrorWrapper); } public static class Exporter extends DemoExporter { // hidden-full-source-line } // hidden-full-source-line } package com.michelin.ns4kafka.services; import com.michelin.ns4kafka.models.AccessControlEntry; import com.michelin.ns4kafka.models.ConsumerGroupResetOffsets; import com.michelin.ns4kafka.models.ConsumerGroupResetOffsets.ResetOffsetsMethod; import com.michelin.ns4kafka.models.Namespace; import com.michelin.ns4kafka.services.executors.ConsumerGroupAsyncExecutor; import io.micronaut.context.ApplicationContext; import io.micronaut.inject.qualifiers.Qualifiers; import org.apache.kafka.common.TopicPartition; import javax.inject.Inject; import javax.inject.Singleton; import java.time.Duration; import java.time.Instant; import java.time.OffsetDateTime; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.regex.Pattern; import java.util.stream.Collectors; @Singleton public class ConsumerGroupService { @Inject ApplicationContext applicationContext; @Inject AccessControlEntryService accessControlEntryService; public boolean isNamespaceOwnerOfConsumerGroup(String namespace, String groupId) { return accessControlEntryService.isNamespaceOwnerOfResource(namespace, AccessControlEntry.ResourceType.GROUP, groupId); } public List validateResetOffsets(ConsumerGroupResetOffsets consumerGroupResetOffsets) { List validationErrors = new ArrayList<>(); // validate topic // allowed : *, , Pattern validTopicValue = Pattern.compile("^(\\*|[a-zA-Z0-9-_.]+(:[0-9]+)?)$"); if (!validTopicValue.matcher(consumerGroupResetOffsets.getSpec().getTopic()).matches()) { validationErrors.add("Invalid value " + consumerGroupResetOffsets.getSpec().getTopic() + " for topic : Value must match" + " [*, , ]"); } String options = consumerGroupResetOffsets.getSpec().getOptions(); switch (consumerGroupResetOffsets.getSpec().getMethod()) { case SHIFT_BY: try { Integer.parseInt(options); } catch (NumberFormatException e) { validationErrors.add("Invalid value " + options + " for options : Value must be an Integer"); } break; case BY_DURATION: try { Duration.parse(options); } catch (NullPointerException | DateTimeParseException e) { validationErrors.add("Invalid value " + options + " for options : Value must be an ISO 8601 Duration [ PnDTnHnMnS ]"); } break; case TO_DATETIME: // OffsetDateTime is of format iso6801 with time zone try { OffsetDateTime.parse(options); } catch (Exception e) { validationErrors.add("Invalid value " + options + " for options : Value must be an ISO 8601 DateTime with Time zone [ yyyy-MM-dd'T'HH:mm:ss.SSSXXX ]"); } break; case TO_LATEST: case TO_EARLIEST: default: // Nothing to do break; } return validationErrors; } public String getConsumerGroupStatus(Namespace namespace, String groupId) throws ExecutionException, InterruptedException { ConsumerGroupAsyncExecutor consumerGroupAsyncExecutor = applicationContext.getBean(ConsumerGroupAsyncExecutor.class, Qualifiers.byName(namespace.getMetadata().getCluster())); return consumerGroupAsyncExecutor.describeConsumerGroups(List.of(groupId)).get(groupId).state().toString(); } public List getPartitionsToReset(Namespace namespace, String groupId, String topic) throws InterruptedException, ExecutionException { ConsumerGroupAsyncExecutor consumerGroupAsyncExecutor = applicationContext.getBean(ConsumerGroupAsyncExecutor.class, Qualifiers.byName(namespace.getMetadata().getCluster())); //List result; //get partitions for a topic if (topic.equals("*")) { return new ArrayList<>(consumerGroupAsyncExecutor.getCommittedOffsets(groupId).keySet()); } else if (topic.contains(":")) { String[] splitResult = topic.split(":"); return List.of(new TopicPartition(splitResult[0], Integer.parseInt(splitResult[1]))); } else { return consumerGroupAsyncExecutor.getCommittedOffsets(groupId) .keySet() .stream() .filter((topicPartition) -> topicPartition.topic().equals(topic)) .collect(Collectors.toList()); } } public Map prepareOffsetsToReset(Namespace namespace, String groupId, String options, List partitionsToReset, ResetOffsetsMethod method) throws InterruptedException, ExecutionException { ConsumerGroupAsyncExecutor consumerGroupAsyncExecutor = applicationContext.getBean(ConsumerGroupAsyncExecutor.class, Qualifiers.byName(namespace.getMetadata().getCluster())); switch (method) { case SHIFT_BY: int shiftBy = Integer.parseInt(options); Map currentCommittedOffsets = consumerGroupAsyncExecutor.getCommittedOffsets(groupId); Map requestedOffsets = partitionsToReset.stream() .map(e -> { if (currentCommittedOffsets.containsKey(e)) { return Map.entry(e, currentCommittedOffsets.get(e) + shiftBy); } throw new IllegalArgumentException("Cannot shift offset for partition " + e.toString() + " since there is no current committed offset"); }) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return consumerGroupAsyncExecutor.checkOffsetsRange(groupId, requestedOffsets); case BY_DURATION: Duration duration = Duration.parse(options); return consumerGroupAsyncExecutor.getLogTimestampOffsets(groupId, partitionsToReset, Instant.now().minus(duration).toEpochMilli()); case TO_DATETIME: OffsetDateTime dateTime = OffsetDateTime.parse(options); return consumerGroupAsyncExecutor.getLogTimestampOffsets(groupId, partitionsToReset, dateTime.toInstant().toEpochMilli()); case TO_LATEST: return consumerGroupAsyncExecutor.getLogEndOffsets(groupId, partitionsToReset); case TO_EARLIEST: return consumerGroupAsyncExecutor.getLogStartOffsets(groupId, partitionsToReset); default: throw new IllegalArgumentException("Unreachable code"); } } public void alterConsumerGroupOffsets(Namespace namespace, String consumerGroupId, Map preparedOffsets) throws InterruptedException, ExecutionException { ConsumerGroupAsyncExecutor consumerGroupAsyncExecutor = applicationContext.getBean(ConsumerGroupAsyncExecutor.class, Qualifiers.byName(namespace.getMetadata().getCluster())); consumerGroupAsyncExecutor.alterConsumerGroupOffsets(consumerGroupId, preparedOffsets); } } package model; import exceptions.CentreAlreadyAddedException; import exceptions.CentreDoesNotExistException; import org.json.JSONArray; import org.json.JSONObject; import persistence.Writable; import java.util.ArrayList; import java.util.List; // Represents a list of the users favourited collection centres that can be referenced later // Data persistence methods adapted from WorkRoom class in JsonSterilizationDemo public class FavouritesList implements Writable { public String name; private final List centres; // EFFECTS: constructs a Favourites List with given name and an empty list of collection centres public FavouritesList(String name) { this.name = name; centres = new ArrayList<>(); } // getters public String getName() { return name; } // EFFECTS: returns an unmodifiable list of centres in this favourites list public List getCentres() { return centres; } // MODIFIES: this // EFFECTS: adds collection centre to list throws CentreAlreadyAddedException if CollectionCentre is already in // FavouritesList public void addCollectionCentre(CollectionCentre c) throws CentreAlreadyAddedException { if (centres.contains(c)) { throw new CentreAlreadyAddedException("Collection Centre already added"); } else { centres.add(c); } } // MODIFIES: this // EFFECTS: removes collection centre from list throws CentreDoesNotExistException if CollectionCentre is not in // FavouritesList public void removeCollectionCentre(CollectionCentre c) throws CentreDoesNotExistException { if (!centres.contains(c)) { throw new CentreDoesNotExistException("Collection Centre not in Favourites"); } else { centres.remove(c); } } // EFFECTS: produces a message indicating size of list // Empty: "There are no collection centres in your list" // 1: "There is 1 collection centre in your list" // >1: "There are x collection centres in your list" public String sizeMessage() { if (centres.isEmpty()) { return "There are no collection centres in your favourites list."; } else { if (centres.size() == 1) { return "There is 1 collection centre in your favourites list."; } else { return "There are " + centres.size() + " collection centres in your favourites list."; } } } // EFFECTS: returns the size of the favourites list public int length() { return centres.size(); } @Override public JSONObject toJson() { JSONObject json = new JSONObject(); json.put("centres", collectionCentresToJson()); return json; } // EFFECTS: returns collection centres in this favourites list as a JSON array private JSONArray collectionCentresToJson() { JSONArray jsonArray = new JSONArray(); for (CollectionCentre c : centres) { jsonArray.put(c.toJson()); } return jsonArray; } } /* * Copyright 2018 * * 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 no.priv.bang.handlereg.services; import static org.junit.jupiter.api.Assertions.*; import java.sql.SQLException; import org.junit.jupiter.api.Test; class HandleregExceptionTest { @Test void testCreate() { String message1 = "just a message"; HandleregException exception1 = new HandleregException(message1); assertEquals(message1, exception1.getMessage()); assertNull(exception1.getCause()); String message2 = "message with cause"; Exception cause2 = new SQLException(); HandleregException exception2 = new HandleregException(message2, cause2); assertEquals(message2, exception2.getMessage()); assertEquals(cause2, exception2.getCause()); HandleregException exception3 = new HandleregException(message2, cause2, true, true); assertEquals(message2, exception3.getMessage()); assertEquals(cause2, exception3.getCause()); HandleregException exception4 = new HandleregException(cause2); assertEquals(cause2.getClass().getName(), exception4.getMessage()); assertEquals(cause2, exception4.getCause()); } } jpraus/Chars /* * Copyright (c) 2013 */ package com.praus.chars.clock; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author <> */ public class RoundClock { private static final Logger logger = LoggerFactory.getLogger(RoundClock.class); private final static long ROUND_MILLIS = 200; private final List listeners = new LinkedList(); public Thread thread = null; public boolean running = false; public synchronized void start() { if (!running) { if (!listeners.isEmpty()) { startThread(); } running = true; } } public synchronized void stop() { if (running) { running = false; } } public synchronized void register(RoundClockListener listener) { if (running) { if (!listeners.contains(listener)) { listeners.add(listener); startThread(); } } } public synchronized void unregister(RoundClockListener listener) { listeners.remove(listener); } private synchronized void startThread() { if (running && thread == null) { thread = new Thread(new Runnable() { public void run() { while (running) { try { Thread.sleep(ROUND_MILLIS); } catch (InterruptedException ex) { } if (running) { for (RoundClockListener listener : listeners) { listener.onRoundTick(); } //logger.debug("Round tick performed"); } } } }); thread.start(); } } } 1-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.xml.security.stax.impl.transformer; import org.apache.xml.security.exceptions.XMLSecurityException; import org.apache.xml.security.stax.ext.Transformer; import org.apache.xml.security.stax.ext.XMLSecurityConstants; import org.apache.xml.security.stax.ext.XMLSecurityUtils; import org.apache.xml.security.stax.ext.stax.XMLSecEvent; import org.apache.xml.security.stax.impl.processor.input.XMLEventReaderInputProcessor; import org.apache.xml.security.utils.UnsyncByteArrayInputStream; import org.apache.xml.security.utils.UnsyncByteArrayOutputStream; import javax.xml.stream.*; import java.io.*; import java.util.Map; /** */ public class TransformIdentity implements Transformer { private static XMLOutputFactory xmlOutputFactory; private static XMLInputFactory xmlInputFactory; private OutputStream outputStream; private XMLEventWriter xmlEventWriterForOutputStream; private Transformer transformer; private ChildOutputMethod childOutputMethod; protected static XMLOutputFactory getXmlOutputFactory() { synchronized(TransformIdentity.class) { if (xmlOutputFactory == null) { xmlOutputFactory = XMLOutputFactory.newInstance(); } } return xmlOutputFactory; } public static XMLInputFactory getXmlInputFactory() { synchronized(TransformIdentity.class) { if (xmlInputFactory == null) { xmlInputFactory = XMLInputFactory.newInstance(); } } return xmlInputFactory; } @Override public void setOutputStream(OutputStream outputStream) throws XMLSecurityException { this.outputStream = outputStream; } protected OutputStream getOutputStream() { return this.outputStream; } protected XMLEventWriter getXmlEventWriterForOutputStream() throws XMLStreamException { if (this.xmlEventWriterForOutputStream != null) { return this.xmlEventWriterForOutputStream; } if (this.outputStream != null) { return this.xmlEventWriterForOutputStream = getXmlOutputFactory().createXMLEventWriter(new FilterOutputStream(outputStream) { @Override public void close() throws IOException { //do not close the parent output stream! super.flush(); } }); } return null; } @Override public void setTransformer(Transformer transformer) throws XMLSecurityException { this.transformer = transformer; } protected Transformer getTransformer() { return transformer; } @Override public void setProperties(Map properties) throws XMLSecurityException { throw new UnsupportedOperationException("no properties supported"); } @Override public XMLSecurityConstants.TransformMethod getPreferredTransformMethod(XMLSecurityConstants.TransformMethod forInput) { switch (forInput) { case XMLSecEvent: return XMLSecurityConstants.TransformMethod.XMLSecEvent; case InputStream: return XMLSecurityConstants.TransformMethod.InputStream; default: throw new IllegalArgumentException("Unsupported class " + forInput.name()); } } @Override public void transform(XMLSecEvent xmlSecEvent) throws XMLStreamException { if (getXmlEventWriterForOutputStream() != null) { //we have an output stream getXmlEventWriterForOutputStream().add(xmlSecEvent); } else { //we have a child transformer if (childOutputMethod == null) { final XMLSecurityConstants.TransformMethod preferredChildTransformMethod = getTransformer().getPreferredTransformMethod(XMLSecurityConstants.TransformMethod.XMLSecEvent); if (preferredChildTransformMethod == XMLSecurityConstants.TransformMethod.XMLSecEvent) { childOutputMethod = new ChildOutputMethod() { @Override public void transform(Object object) throws XMLStreamException { getTransformer().transform((XMLSecEvent) object); } @Override public void doFinal() throws XMLStreamException { getTransformer().doFinal(); } }; } else if (preferredChildTransformMethod == XMLSecurityConstants.TransformMethod.InputStream) { childOutputMethod = new ChildOutputMethod() { private UnsyncByteArrayOutputStream baos; private XMLEventWriter xmlEventWriter; @Override public void transform(Object object) throws XMLStreamException { if (xmlEventWriter == null) { baos = new UnsyncByteArrayOutputStream(); xmlEventWriter = getXmlOutputFactory().createXMLEventWriter(baos); } xmlEventWriter.add((XMLSecEvent) object); } @Override public void doFinal() throws XMLStreamException { xmlEventWriter.close(); try (InputStream is = new UnsyncByteArrayInputStream(baos.toByteArray())) { getTransformer().transform(is); getTransformer().doFinal(); } catch (IOException ex) { throw new XMLStreamException(ex); } } }; } } if (childOutputMethod != null) { childOutputMethod.transform(xmlSecEvent); } } } @Override public void transform(final InputStream inputStream) throws XMLStreamException { if (getOutputStream() != null) { //we have an output stream try { XMLSecurityUtils.copy(inputStream, getOutputStream()); } catch (IOException e) { throw new XMLStreamException(e); } } else { //we have a child transformer if (childOutputMethod == null) { final XMLSecurityConstants.TransformMethod preferredChildTransformMethod = getTransformer().getPreferredTransformMethod(XMLSecurityConstants.TransformMethod.InputStream); if (preferredChildTransformMethod == XMLSecurityConstants.TransformMethod.XMLSecEvent) { childOutputMethod = new ChildOutputMethod() { private XMLEventReaderInputProcessor xmlEventReaderInputProcessor; @Override public void transform(Object object) throws XMLStreamException { if (xmlEventReaderInputProcessor == null) { xmlEventReaderInputProcessor = new XMLEventReaderInputProcessor( null, getXmlInputFactory().createXMLStreamReader(inputStream) ); } try { XMLSecEvent xmlSecEvent; do { xmlSecEvent = xmlEventReaderInputProcessor.processNextEvent(null); getTransformer().transform(xmlSecEvent); } while (xmlSecEvent.getEventType() != XMLStreamConstants.END_DOCUMENT); } catch (XMLSecurityException e) { throw new XMLStreamException(e); } } @Override public void doFinal() throws XMLStreamException { getTransformer().doFinal(); } }; } else if (preferredChildTransformMethod == XMLSecurityConstants.TransformMethod.InputStream) { childOutputMethod = new ChildOutputMethod() { @Override public void transform(Object object) throws XMLStreamException { getTransformer().transform(inputStream); } @Override public void doFinal() throws XMLStreamException { getTransformer().doFinal(); } }; } } if (childOutputMethod != null) { childOutputMethod.transform(inputStream); } } } @Override public void doFinal() throws XMLStreamException { if (xmlEventWriterForOutputStream != null) { xmlEventWriterForOutputStream.close(); } if (childOutputMethod != null) { childOutputMethod.doFinal(); } else if (transformer != null) { transformer.doFinal(); } } interface ChildOutputMethod { void transform(Object object) throws XMLStreamException; void doFinal() throws XMLStreamException; } } app/src/main/java/me/aaronchan/androidapiguidedemos/BlankFragment1.java package me.aaronchan.androidapiguidedemos; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.View; import android.view.ViewGroup; /** * A simple {@link Fragment} subclass. */ public class BlankFragment1 extends Fragment { private static final String TAG = BlankFragment1.class.getSimpleName(); public BlankFragment1() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate"); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_blank_fragment1, container, false); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_fragment1, menu); } } package org.mitre.svmp.performance; import java.util.Date; /** * @author * Stores information about a set of performance data */ public class MeasurementInfo { private Date startDate; // primary key private int connectionID; // foreign key private int measureInterval; private int pingInterval; public MeasurementInfo(Date startDate, int connectionID, int measureInterval, int pingInterval) { this.startDate = startDate; this.connectionID = connectionID; this.measureInterval = measureInterval; this.pingInterval = pingInterval; } public Date getStartDate() { return startDate; } public int getConnectionID() { return connectionID; } public int getMeasureInterval() { return measureInterval; } public int getPingInterval() { return pingInterval; } } huruiyi/Java201808spring-beans/src/main/java/com/apress/prospring4/ch2/_ConstructionInjection/ResolvingAmbiguity/EmployeeService.java package com.apress.prospring4.ch2._ConstructionInjection.ResolvingAmbiguity; public class EmployeeService { private String employeeName; private int employeeAge; private String employeeId; EmployeeService(String employeeName, int employeeAge, String employeeId) { this.employeeName = employeeName; this.employeeAge = employeeAge; this.employeeId = employeeId; } EmployeeService(String employeeName, String employeeId, int employeeAge) { this.employeeName = employeeName; this.employeeAge = employeeAge; this.employeeId = employeeId; } @Override public String toString() { return "Employee Name: " + employeeName + " Age: " + employeeAge + " EmployeeId: " + employeeId; } } /* * Decompiled with CFR 0.150. * * Could not load the following classes: * com.google.common.collect.AbstractIterator */ package net.minecraft.util; import com.google.common.collect.AbstractIterator; import java.util.Iterator; import net.minecraft.entity.Entity; import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.util.Vec3; import net.minecraft.util.Vec3i; import skizzle.util.Timer; public class BlockPos extends Vec3i { public static final BlockPos ORIGIN = new BlockPos(0, 0, 0); private static final int field_177990_b; private static final int field_177991_c; private static final int field_177989_d; private static final int field_177987_f; private static final int field_177988_g; private static final long field_177994_h; private static final long field_177995_i; private static final long field_177993_j; private static final String __OBFID = "CL_00002334"; public static Timer autoChestTimer; static { field_177991_c = field_177990_b = 1 + MathHelper.calculateLogBaseTwo(MathHelper.roundUpToPowerOfTwo(30000000)); field_177989_d = 64 - field_177990_b - field_177991_c; field_177987_f = 0 + field_177991_c; field_177988_g = field_177987_f + field_177989_d; field_177994_h = (1L << field_177990_b) - 1L; field_177995_i = (1L << field_177989_d) - 1L; field_177993_j = (1L << field_177991_c) - 1L; autoChestTimer = new Timer(); } public BlockPos(int x, int y, int z) { super(x, y, z); } public BlockPos(double x, double y, double z) { super(x, y, z); } public BlockPos(Entity p_i46032_1_) { this(p_i46032_1_.posX, p_i46032_1_.posY, p_i46032_1_.posZ); } public BlockPos(Vec3 p_i46033_1_) { this(p_i46033_1_.xCoord, p_i46033_1_.yCoord, p_i46033_1_.zCoord); } public BlockPos(Vec3i p_i46034_1_) { this(p_i46034_1_.getX(), p_i46034_1_.getY(), p_i46034_1_.getZ()); } public BlockPos add(double x, double y, double z) { return new BlockPos((double)this.getX() + x, (double)this.getY() + y, (double)this.getZ() + z); } public BlockPos add(int x, int y, int z) { return new BlockPos(this.getX() + x, this.getY() + y, this.getZ() + z); } public BlockPos add(Vec3i vec) { return new BlockPos(this.getX() + vec.getX(), this.getY() + vec.getY(), this.getZ() + vec.getZ()); } public BlockPos subtract(Vec3i vec) { return new BlockPos(this.getX() - vec.getX(), this.getY() - vec.getY(), this.getZ() - vec.getZ()); } public BlockPos multiply(int factor) { return new BlockPos(this.getX() * factor, this.getY() * factor, this.getZ() * factor); } public BlockPos offsetUp() { return this.offsetUp(1); } public BlockPos offsetUp(int n) { return this.offset(EnumFacing.UP, n); } public BlockPos offsetDown() { return this.offsetDown(1); } public BlockPos offsetDown(int n) { return this.offset(EnumFacing.DOWN, n); } public BlockPos offsetNorth() { return this.offsetNorth(1); } public BlockPos offsetNorth(int n) { return this.offset(EnumFacing.NORTH, n); } public BlockPos offsetSouth() { return this.offsetSouth(1); } public BlockPos offsetSouth(int n) { return this.offset(EnumFacing.SOUTH, n); } public BlockPos offsetWest() { return this.offsetWest(1); } public BlockPos offsetWest(int n) { return this.offset(EnumFacing.WEST, n); } public BlockPos offsetEast() { return this.offsetEast(1); } public BlockPos offsetEast(int n) { return this.offset(EnumFacing.EAST, n); } public BlockPos offset(EnumFacing facing) { return this.offset(facing, 1); } public BlockPos offset(EnumFacing facing, int n) { return new BlockPos(this.getX() + facing.getFrontOffsetX() * n, this.getY() + facing.getFrontOffsetY() * n, this.getZ() + facing.getFrontOffsetZ() * n); } public BlockPos crossProductBP(Vec3i vec) { return new BlockPos(this.getY() * vec.getZ() - this.getZ() * vec.getY(), this.getZ() * vec.getX() - this.getX() * vec.getZ(), this.getX() * vec.getY() - this.getY() * vec.getX()); } public long toLong() { return ((long)this.getX() & field_177994_h) << field_177988_g | ((long)this.getY() & field_177995_i) << field_177987_f | ((long)this.getZ() & field_177993_j) << 0; } public static BlockPos fromLong(long serialized) { int var2 = (int)(serialized << 64 - field_177988_g - field_177990_b >> 64 - field_177990_b); int var3 = (int)(serialized << 64 - field_177987_f - field_177989_d >> 64 - field_177989_d); int var4 = (int)(serialized << 64 - field_177991_c >> 64 - field_177991_c); return new BlockPos(var2, var3, var4); } public static Iterable getAllInBox(BlockPos from, BlockPos to) { final BlockPos var2 = new BlockPos(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()), Math.min(from.getZ(), to.getZ())); final BlockPos var3 = new BlockPos(Math.max(from.getX(), to.getX()), Math.max(from.getY(), to.getY()), Math.max(from.getZ(), to.getZ())); return new Iterable(){ private static final String __OBFID = "CL_00002333"; public Iterator iterator() { return new AbstractIterator(){ private BlockPos lastReturned = null; private static final String __OBFID = "CL_00002332"; protected BlockPos computeNext0() { if (this.lastReturned == null) { this.lastReturned = var2; return this.lastReturned; } if (this.lastReturned.equals(var3)) { return (BlockPos)this.endOfData(); } int var1 = this.lastReturned.getX(); int var2x = this.lastReturned.getY(); int var3x = this.lastReturned.getZ(); if (var1 < var3.getX()) { ++var1; } else if (var2x < var3.getY()) { var1 = var2.getX(); ++var2x; } else if (var3x < var3.getZ()) { var1 = var2.getX(); var2x = var2.getY(); ++var3x; } this.lastReturned = new BlockPos(var1, var2x, var3x); return this.lastReturned; } protected Object computeNext() { return this.computeNext0(); } }; } }; } public static Iterable getAllInBoxMutable(BlockPos from, BlockPos to) { final BlockPos var2 = new BlockPos(Math.min(from.getX(), to.getX()), Math.min(from.getY(), to.getY()), Math.min(from.getZ(), to.getZ())); final BlockPos var3 = new BlockPos(Math.max(from.getX(), to.getX()), Math.max(from.getY(), to.getY()), Math.max(from.getZ(), to.getZ())); return new Iterable(){ private static final String __OBFID = "CL_00002331"; public Iterator iterator() { return new AbstractIterator(){ private MutableBlockPos theBlockPos = null; private static final String __OBFID = "CL_00002330"; protected MutableBlockPos computeNext0() { if (this.theBlockPos == null) { this.theBlockPos = new MutableBlockPos(var2.getX(), var2.getY(), var2.getZ(), null); return this.theBlockPos; } if (this.theBlockPos.equals(var3)) { return (MutableBlockPos)this.endOfData(); } int var1 = this.theBlockPos.getX(); int var2xx = this.theBlockPos.getY(); int var3x = this.theBlockPos.getZ(); if (var1 < var3.getX()) { ++var1; } else if (var2xx < var3.getY()) { var1 = var2.getX(); ++var2xx; } else if (var3x < var3.getZ()) { var1 = var2.getX(); var2xx = var2.getY(); ++var3x; } this.theBlockPos.x = var1; this.theBlockPos.y = var2xx; this.theBlockPos.z = var3x; return this.theBlockPos; } protected Object computeNext() { return this.computeNext0(); } }; } }; } @Override public Vec3i crossProduct(Vec3i vec) { return this.crossProductBP(vec); } public static final class MutableBlockPos extends BlockPos { public int x; public int y; public int z; private static final String __OBFID = "CL_00002329"; private MutableBlockPos(int x_, int y_, int z_) { super(0, 0, 0); this.x = x_; this.y = y_; this.z = z_; } @Override public int getX() { return this.x; } @Override public int getY() { return this.y; } @Override public int getZ() { return this.z; } @Override public Vec3i crossProduct(Vec3i vec) { return super.crossProductBP(vec); } MutableBlockPos(int p_i46025_1_, int p_i46025_2_, int p_i46025_3_, Object p_i46025_4_) { this(p_i46025_1_, p_i46025_2_, p_i46025_3_); } } } src/main/java/alipsa/sieparser/SieDimension.java1-10 /* MIT License Copyright (c) 2015 Modifications by Copyright (c) 2016 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package alipsa.sieparser; import java.util.HashMap; import java.util.HashSet; public class SieDimension { public boolean isDefault; public HashSet subDim = new HashSet(); public HashMap objects = new HashMap(); private String number; private String name; private SieDimension parent = null; public SieDimension(String num, String aName, boolean defaultVal) { number = num; name = aName; isDefault = defaultVal; } public SieDimension(String num, String aName) { number = num; name = aName; isDefault = false; } public SieDimension(String number) { this(number, ""); } public String getNumber() { return number; } public void setNumber(String value) { number = value; } public String getName() { return name; } public void setName(String value) { name = value; } public SieDimension getSuperDim() throws Exception { return parent; } public void setSuperDim(SieDimension value) throws Exception { parent = value; parent.subDim.add(this); } } package io.scalecube.security.tokens.jwt; import io.scalecube.security.tokens.jwt.jsonwebtoken.JsonwebtokenParserFactory; import java.security.Key; import java.time.Duration; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; public final class JwtTokenResolverImpl implements JwtTokenResolver { private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenResolver.class); private KeyProvider keyProvider; private JwtTokenParserFactory tokenParserFactory = new JsonwebtokenParserFactory(); private Scheduler scheduler = Schedulers.boundedElastic(); private Duration cleanupInterval = Duration.ofSeconds(60); private final Map> keyResolutions = new ConcurrentHashMap<>(); public JwtTokenResolverImpl() {} private JwtTokenResolverImpl(JwtTokenResolverImpl other) { this.keyProvider = other.keyProvider; this.tokenParserFactory = other.tokenParserFactory; this.scheduler = other.scheduler; this.cleanupInterval = other.cleanupInterval; } /** * Setter for keyProvider. * * @param keyProvider keyProvider * @return new instance with applied setting */ public JwtTokenResolverImpl keyProvider(KeyProvider keyProvider) { final JwtTokenResolverImpl c = copy(); c.keyProvider = keyProvider; return c; } /** * Setter for tokenParserFactory. * * @param tokenParserFactory tokenParserFactory * @return new instance with applied setting */ public JwtTokenResolverImpl tokenParserFactory(JwtTokenParserFactory tokenParserFactory) { final JwtTokenResolverImpl c = copy(); c.tokenParserFactory = tokenParserFactory; return c; } /** * Setter for scheduler. * * @param scheduler scheduler * @return new instance with applied setting */ public JwtTokenResolverImpl scheduler(Scheduler scheduler) { final JwtTokenResolverImpl c = copy(); c.scheduler = scheduler; return c; } /** * Setter for cleanupInterval. * * @param cleanupInterval cleanupInterval * @return new instance with applied setting */ public JwtTokenResolverImpl cleanupInterval(Duration cleanupInterval) { final JwtTokenResolverImpl c = copy(); c.cleanupInterval = cleanupInterval; return c; } @Override public Mono> resolve(String token) { return Mono.defer( () -> { JwtTokenParser tokenParser = tokenParserFactory.newParser(token); JwtToken jwtToken = tokenParser.parseToken(); Map header = jwtToken.header(); String kid = (String) header.get("kid"); Objects.requireNonNull(kid, "kid is missing"); Map body = jwtToken.body(); String aud = (String) body.get("aud"); // optional LOGGER.debug("[resolveToken][aud:{}][kid:{}] Resolving token {}", aud, kid, mask(token)); // workaround to remove safely on errors AtomicReference> computedValueHolder = new AtomicReference<>(); return findKey(kid, computedValueHolder) .map(key -> tokenParser.verifyToken(key).body()) .doOnError(throwable -> cleanup(kid, computedValueHolder)) .doOnError( throwable -> LOGGER.error( "[resolveToken][aud:{}][kid:{}][{}] Exception occurred: {}", aud, kid, mask(token), throwable.toString())) .doOnSuccess( s -> LOGGER.debug( "[resolveToken][aud:{}][kid:{}] Resolved token {}", aud, kid, mask(token))); }); } private Mono findKey(String kid, AtomicReference> computedValueHolder) { return keyResolutions.computeIfAbsent( kid, (kid1) -> { Mono result = computedValueHolder.updateAndGet( mono -> Mono.defer(() -> keyProvider.findKey(kid1)) .cache() .doOnError(ex -> keyResolutions.remove(kid1))); scheduleCleanup(kid, computedValueHolder); return result; }); } private void scheduleCleanup(String kid, AtomicReference> computedValueHolder) { scheduler.schedule( () -> cleanup(kid, computedValueHolder), cleanupInterval.toMillis(), TimeUnit.MILLISECONDS); } private void cleanup(String kid, AtomicReference> computedValueHolder) { if (computedValueHolder.get() != null) { keyResolutions.remove(kid, computedValueHolder.get()); } } private static String mask(String data) { if (data == null || data.isEmpty() || data.length() < 5) { return "*****"; } return data.replace(data.substring(2, data.length() - 2), "***"); } private JwtTokenResolverImpl copy() { return new JwtTokenResolverImpl(this); } } /* * 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.androidmanagement.v1.model; /** * Information about device hardware. The fields related to temperature thresholds are only * available if hardwareStatusEnabled is true in the device's policy. * *

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 Android Management 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 HardwareInfo extends com.google.api.client.json.GenericJson { /** * Battery shutdown temperature thresholds in Celsius for each battery on the device. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List batteryShutdownTemperatures; /** * Battery throttling temperature thresholds in Celsius for each battery on the device. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List batteryThrottlingTemperatures; /** * Brand of the device. For example, Google. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String brand; /** * CPU shutdown temperature thresholds in Celsius for each CPU on the device. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List cpuShutdownTemperatures; /** * CPU throttling temperature thresholds in Celsius for each CPU on the device. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List cpuThrottlingTemperatures; /** * Baseband version. For example, MDM9625_104662.22.05.34p. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String deviceBasebandVersion; /** * GPU shutdown temperature thresholds in Celsius for each GPU on the device. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List gpuShutdownTemperatures; /** * GPU throttling temperature thresholds in Celsius for each GPU on the device. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List gpuThrottlingTemperatures; /** * Name of the hardware. For example, Angler. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String hardware; /** * Manufacturer. For example, Motorola. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String manufacturer; /** * The model of the device. For example, Asus Nexus 7. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String model; /** * The device serial number. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String serialNumber; /** * Device skin shutdown temperature thresholds in Celsius. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List skinShutdownTemperatures; /** * Device skin throttling temperature thresholds in Celsius. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List skinThrottlingTemperatures; /** * Battery shutdown temperature thresholds in Celsius for each battery on the device. * @return value or {@code null} for none */ public java.util.List getBatteryShutdownTemperatures() { return batteryShutdownTemperatures; } /** * Battery shutdown temperature thresholds in Celsius for each battery on the device. * @param batteryShutdownTemperatures batteryShutdownTemperatures or {@code null} for none */ public HardwareInfo setBatteryShutdownTemperatures(java.util.List batteryShutdownTemperatures) { this.batteryShutdownTemperatures = batteryShutdownTemperatures; return this; } /** * Battery throttling temperature thresholds in Celsius for each battery on the device. * @return value or {@code null} for none */ public java.util.List getBatteryThrottlingTemperatures() { return batteryThrottlingTemperatures; } /** * Battery throttling temperature thresholds in Celsius for each battery on the device. * @param batteryThrottlingTemperatures batteryThrottlingTemperatures or {@code null} for none */ public HardwareInfo setBatteryThrottlingTemperatures(java.util.List batteryThrottlingTemperatures) { this.batteryThrottlingTemperatures = batteryThrottlingTemperatures; return this; } /** * Brand of the device. For example, Google. * @return value or {@code null} for none */ public java.lang.String getBrand() { return brand; } /** * Brand of the device. For example, Google. * @param brand brand or {@code null} for none */ public HardwareInfo setBrand(java.lang.String brand) { this.brand = brand; return this; } /** * CPU shutdown temperature thresholds in Celsius for each CPU on the device. * @return value or {@code null} for none */ public java.util.List getCpuShutdownTemperatures() { return cpuShutdownTemperatures; } /** * CPU shutdown temperature thresholds in Celsius for each CPU on the device. * @param cpuShutdownTemperatures cpuShutdownTemperatures or {@code null} for none */ public HardwareInfo setCpuShutdownTemperatures(java.util.List cpuShutdownTemperatures) { this.cpuShutdownTemperatures = cpuShutdownTemperatures; return this; } /** * CPU throttling temperature thresholds in Celsius for each CPU on the device. * @return value or {@code null} for none */ public java.util.List getCpuThrottlingTemperatures() { return cpuThrottlingTemperatures; } /** * CPU throttling temperature thresholds in Celsius for each CPU on the device. * @param cpuThrottlingTemperatures cpuThrottlingTemperatures or {@code null} for none */ public HardwareInfo setCpuThrottlingTemperatures(java.util.List cpuThrottlingTemperatures) { this.cpuThrottlingTemperatures = cpuThrottlingTemperatures; return this; } /** * Baseband version. For example, MDM9625_104662.22.05.34p. * @return value or {@code null} for none */ public java.lang.String getDeviceBasebandVersion() { return deviceBasebandVersion; } /** * Baseband version. For example, MDM9625_104662.22.05.34p. * @param deviceBasebandVersion deviceBasebandVersion or {@code null} for none */ public HardwareInfo setDeviceBasebandVersion(java.lang.String deviceBasebandVersion) { this.deviceBasebandVersion = deviceBasebandVersion; return this; } /** * GPU shutdown temperature thresholds in Celsius for each GPU on the device. * @return value or {@code null} for none */ public java.util.List getGpuShutdownTemperatures() { return gpuShutdownTemperatures; } /** * GPU shutdown temperature thresholds in Celsius for each GPU on the device. * @param gpuShutdownTemperatures gpuShutdownTemperatures or {@code null} for none */ public HardwareInfo setGpuShutdownTemperatures(java.util.List gpuShutdownTemperatures) { this.gpuShutdownTemperatures = gpuShutdownTemperatures; return this; } /** * GPU throttling temperature thresholds in Celsius for each GPU on the device. * @return value or {@code null} for none */ public java.util.List getGpuThrottlingTemperatures() { return gpuThrottlingTemperatures; } /** * GPU throttling temperature thresholds in Celsius for each GPU on the device. * @param gpuThrottlingTemperatures gpuThrottlingTemperatures or {@code null} for none */ public HardwareInfo setGpuThrottlingTemperatures(java.util.List gpuThrottlingTemperatures) { this.gpuThrottlingTemperatures = gpuThrottlingTemperatures; return this; } /** * Name of the hardware. For example, Angler. * @return value or {@code null} for none */ public java.lang.String getHardware() { return hardware; } /** * Name of the hardware. For example, Angler. * @param hardware hardware or {@code null} for none */ public HardwareInfo setHardware(java.lang.String hardware) { this.hardware = hardware; return this; } /** * Manufacturer. For example, Motorola. * @return value or {@code null} for none */ public java.lang.String getManufacturer() { return manufacturer; } /** * Manufacturer. For example, Motorola. * @param manufacturer manufacturer or {@code null} for none */ public HardwareInfo setManufacturer(java.lang.String manufacturer) { this.manufacturer = manufacturer; return this; } /** * The model of the device. For example, Asus Nexus 7. * @return value or {@code null} for none */ public java.lang.String getModel() { return model; } /** * The model of the device. For example, Asus Nexus 7. * @param model model or {@code null} for none */ public HardwareInfo setModel(java.lang.String model) { this.model = model; return this; } /** * The device serial number. * @return value or {@code null} for none */ public java.lang.String getSerialNumber() { return serialNumber; } /** * The device serial number. * @param serialNumber serialNumber or {@code null} for none */ public HardwareInfo setSerialNumber(java.lang.String serialNumber) { this.serialNumber = serialNumber; return this; } /** * Device skin shutdown temperature thresholds in Celsius. * @return value or {@code null} for none */ public java.util.List getSkinShutdownTemperatures() { return skinShutdownTemperatures; } /** * Device skin shutdown temperature thresholds in Celsius. * @param skinShutdownTemperatures skinShutdownTemperatures or {@code null} for none */ public HardwareInfo setSkinShutdownTemperatures(java.util.List skinShutdownTemperatures) { this.skinShutdownTemperatures = skinShutdownTemperatures; return this; } /** * Device skin throttling temperature thresholds in Celsius. * @return value or {@code null} for none */ public java.util.List getSkinThrottlingTemperatures() { return skinThrottlingTemperatures; } /** * Device skin throttling temperature thresholds in Celsius. * @param skinThrottlingTemperatures skinThrottlingTemperatures or {@code null} for none */ public HardwareInfo setSkinThrottlingTemperatures(java.util.List skinThrottlingTemperatures) { this.skinThrottlingTemperatures = skinThrottlingTemperatures; return this; } @Override public HardwareInfo set(String fieldName, Object value) { return (HardwareInfo) super.set(fieldName, value); } @Override public HardwareInfo clone() { return (HardwareInfo) super.clone(); } } bonitoo-io/flux-java /* * The MIT License * Copyright © 2018 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package io.bonitoo.platform.impl; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import io.bonitoo.AbstractRestClient; import io.bonitoo.core.Preconditions; import io.bonitoo.platform.BucketClient; import io.bonitoo.platform.dto.Bucket; import io.bonitoo.platform.dto.Buckets; import io.bonitoo.platform.dto.Organization; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import retrofit2.Call; /** * @author () (13/09/2018 10:47) */ final class BucketClientImpl extends AbstractRestClient implements BucketClient { private static final Logger LOG = Logger.getLogger(BucketClientImpl.class.getName()); private final PlatformService platformService; private final JsonAdapter adapter; BucketClientImpl(@Nonnull final PlatformService platformService, @Nonnull final Moshi moshi) { this.platformService = platformService; this.adapter = moshi.adapter(Bucket.class); } @Nullable @Override public Bucket findBucketByID(@Nonnull final String bucketID) { Preconditions.checkNonEmptyString(bucketID, "Bucket ID"); Call bucket = platformService.findBucketByID(bucketID); return execute(bucket, "bucket not found"); } @Nonnull @Override public List findBuckets() { return findBucketsByOrganizationName(null); } @Nonnull public List findBucketsByOrganization(@Nonnull final Organization organization) { Objects.requireNonNull(organization, "Organization is required"); return findBucketsByOrganizationName(organization.getName()); } @Nonnull @Override public List findBucketsByOrganizationName(@Nullable final String organizationName) { Call bucketsCall = platformService.findBuckets(organizationName); Buckets buckets = execute(bucketsCall); LOG.log(Level.FINEST, "findBucketsByOrganizationName found: {0}", buckets); return buckets.getBuckets(); } @Nonnull @Override public Bucket createBucket(@Nonnull final String name, @Nonnull final String retentionPeriod, @Nonnull final Organization organization) { Objects.requireNonNull(organization, "Organization is required"); return createBucket(name, retentionPeriod, organization.getName()); } @Nonnull @Override public Bucket createBucket(@Nonnull final String name, @Nonnull final String retentionPeriod, @Nonnull final String organizationName) { Preconditions.checkNonEmptyString(name, "Bucket name"); Preconditions.checkNonEmptyString(organizationName, "Organization name"); Preconditions.checkDuration(retentionPeriod, "Bucket.retentionPeriod"); Bucket bucket = new Bucket(); bucket.setName(name); bucket.setRetentionPeriod(retentionPeriod); bucket.setOrganizationName(organizationName); return createBucket(bucket); } @Nonnull @Override public Bucket createBucket(@Nonnull final Bucket bucket) { Objects.requireNonNull(bucket, "Bucket is required"); Preconditions.checkNonEmptyString(bucket.getName(), "Bucket name"); Preconditions.checkNonEmptyString(bucket.getOrganizationName(), "Organization name"); Preconditions.checkDuration(bucket.getRetentionPeriod(), "Bucket.retentionPeriod"); Call call = platformService.createBucket(createBody(adapter.toJson(bucket))); return execute(call); } @Nonnull @Override public Bucket updateBucket(@Nonnull final Bucket bucket) { Objects.requireNonNull(bucket, "Bucket is required"); Preconditions.checkDuration(bucket.getRetentionPeriod(), "Bucket.retentionPeriod"); String json = adapter.toJson(bucket); Call bucketCall = platformService.updateBucket(bucket.getId(), createBody(json)); return execute(bucketCall); } @Override public void deleteBucket(@Nonnull final Bucket bucket) { Objects.requireNonNull(bucket, "Bucket is required"); deleteBucket(bucket.getId()); } @Override public void deleteBucket(@Nonnull final String bucketID) { Preconditions.checkNonEmptyString(bucketID, "bucketID"); Call call = platformService.deleteBucket(bucketID); execute(call); } }bundle/src/main/java/com/brandonmaynard/restful/utils/ResponseUtils.java package com.brandonmaynard.restful.utils; import com.brandonmaynard.restful.exceptions.RestClientException; import com.brandonmaynard.restful.models.Response; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpStatus; import org.apache.sling.commons.json.JSONException; import org.apache.sling.commons.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * {@link Response} utility methods. * @see aem-rest-api GitHub repository for more information. * @author - https://www.linkedin.com/in/brandonmaynard/ */ public final class ResponseUtils { private static final Logger LOG = LoggerFactory.getLogger(ResponseUtils.class); /** * Private constructor. */ private ResponseUtils() { // Do Nothing. } /** * Get the supplied Response's body JSON. * @param response Response * @return JSONObject */ public static JSONObject getResponseBodyJson(final Response response) { try { return new JSONObject(response.getBody()); } catch (JSONException e) { LOG.error("Unable to get body JSON. Raw response:\n{}", response.getBody(), e); } return new JSONObject(); } /** * Get the access token from the authentication response body's JSON. * @param valueName value's name * @param authenticationJson Authentication response body's JSON * @return String */ public static String getValueFromJson(final String valueName, final JSONObject authenticationJson) { try { return authenticationJson.getString(valueName); } catch (JSONException e) { LOG.error("Unable to grab value from supplied JSON. Full JSON output:\n{}", authenticationJson.toString(), e); } return StringUtils.EMPTY; } /** * Validate that response is ok and log if response is problematic. * @param response Response * @param url String * @throws RestClientException exception */ public static void validate(final Response response, final String url) throws RestClientException { validate(response, url, getResponseBodyJson(response)); } /** * Validate that response is ok and log if response is problematic. * @param response Response * @param url String * @param responseJson JSON of authentication response body * @throws RestClientException exception */ private static void validate(final Response response, final String url, final JSONObject responseJson) throws RestClientException { try { boolean hasError = responseJson.has("error") && responseJson.getString("error").equalsIgnoreCase("true"); if ((response.getStatusCode() != HttpStatus.SC_OK && response.getStatusCode() != HttpStatus.SC_CREATED) || hasError) { final String message = "Unable to authenticating with"; throw new RestClientException(buildResponseMessage(response.getStatusCode(), message, url, response.getBody())); } } catch (JSONException e) { final String message = "Unable to validate response JSON"; LOG.error(buildResponseMessage(response.getStatusCode(), message, url, response.getBody()), e); } } /** * Build the response message for the exception that is thrown. * @param statusCode response status code * @param message custom message to display in logs * @param url url used for webservice call * @param body response body * @return String */ private static String buildResponseMessage(final int statusCode, final String message, final String url, final String body) { return "Status Code " .concat(String.valueOf(statusCode)) .concat(": ") .concat(message) .concat(" ") .concat(StringUtils.isBlank(url) ? StringUtils.EMPTY : url) .concat("\nRaw response:\n") .concat(body); } } 0 package org.erhmutlu.algrthms.traversal; import org.erhmutlu.algrthms.TreeHelper; import org.junit.Test; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; public class IterativeTreeTraversalTest { private IterativeTreeTraversal iterativeTreeTraversal = new IterativeTreeTraversal(); @Test public void should_pre_order_traverse_tree() { //given Node rootNode = TreeHelper.prepareTree(); //when List values = iterativeTreeTraversal.preOrderTraverse(rootNode); //then assertThat(values).isEqualTo(new LinkedList<>(Arrays.asList(100, 50, 25, 75, 150, 125, 110, 175))); } }package net.devaction.mylocation.lastknownlocationcore.clusteredclient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.devaction.mylocation.lastknownlocationapi.protobuf.LastKnownLocationRequest; /** * @author * * since December 2018 */ public class LastKnownLocationRequestProvider01{ private static final Logger log = LoggerFactory.getLogger(LastKnownLocationRequestProvider01.class); public static LastKnownLocationRequest provide(){ LastKnownLocationRequest.Builder requestBuilder = LastKnownLocationRequest.newBuilder(); requestBuilder.setTimestamp(System.currentTimeMillis() / 1000); LastKnownLocationRequest request = requestBuilder.build(); log.info("Test request:\n" + request); return request; } } //------------------------------------------------------------------------ // @(#)ParameterData.java // HashParameter型のデータの保管のみを行う(描画は行わない) // Copyright (c) MiraiDesign 2010 All Rights Reserved. //------------------------------------------------------------------------ package com.miraidesign.renderer.item; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import com.miraidesign.session.SessionObject; import com.miraidesign.util.CharArray; import com.miraidesign.util.CharArrayQueue; import com.miraidesign.util.HashParameter; import com.miraidesign.util.QueueTable; /** HashParameter型のデータの保管のみを行う(描画は行わない)*/ public class ParameterData extends ItemData { private HashParameter parameter = new HashParameter(); // データ保存エリア { type = PARAMETER; } //--------------------------------------------------------------------- // constructor //--------------------------------------------------------------------- public ParameterData() {} public ParameterData(ParameterData from, SessionObject session) { this.sessionObject = session; copy(from); } public ParameterData(HashParameter parameter) { setParameter(parameter); } //--------------------------------------------------------------------- // データ設定 //--------------------------------------------------------------------- /** データをクリアする */ public void clear() { parameter.clear(); } /** サイズを返す @return parameterサイズ */ public int size() { return parameter.size();} /** 要素の新設定(既存データはクリア) @param key キー値 @param value 新しい値 */ public void set(String key, String value) { parameter.set(key, value); } public void set(CharArray key, String value) { parameter.set(key, value); } public void set(String key, CharArray value) { parameter.set(key, value); } public void set(CharArray key, CharArray value) { parameter.set(key, value); } public void set(String key, int value) { parameter.set(key, value); } public void set(CharArray key, int value) { parameter.set(key, value); } public void set(String key, long value) {parameter.set(key, value);} public void set(CharArray key, long value) {parameter.set(key, value);} public void set(String key, double value) {parameter.set(key, value);} public void set(CharArray key, double value) {parameter.set(key, value);} public void set(String key, boolean value) {parameter.set(key, value);} public void set(CharArray key, boolean value) {parameter.set(key, value);} /** Queueテーブルの先頭行を設定する */ public void set(QueueTable table) { parameter.set(table,0);} /** Queueテーブルの指定行を設定する */ public void set(QueueTable table, int row) { parameter.set(table, row);} /** 文字列からまとめて設定する @param str 文字列 @param sep セパレータ (= 等) @param connect 接続文字 (, 等) */ public void set(CharArray str, String sep, String connect) { parameter.set(str, sep, connect); } public void set(String str, String sep, String connect) { parameter.set(str, sep, connect); } /** 要素の追加 (同一キーが存在した場合は後のものが削除される) @param key 追加するキー値 @param value 追加する要素 */ public void add(String key, String value) { parameter.add(key,value); } public void add(CharArray key, String value) { parameter.add(key,value); } public void add(String key, CharArray value) { parameter.add(key,value); } public void add(CharArray key, CharArray value) { parameter.add(key,value); } public void add(String key, int value) { parameter.add(key,value); } public void add(CharArray key, int value) { parameter.add(key,value); } public void add(String key, long value) { parameter.add(key,value); } public void add(CharArray key, long value) { parameter.add(key,value); } public void add(String key, double value) { parameter.add(key,value); } public void add(CharArray key, double value) { parameter.add(key,value); } public void add(String key, boolean value) { parameter.add(key,value); } public void add(CharArray key, boolean value) { parameter.add(key,value); } /** Queueテーブルの先頭行を追加する */ public void add(QueueTable table) { parameter.add(table,0); } /** Queueテーブルの指定行を追加する */ public void add(QueueTable table, int row) { parameter.add(table,row); } /** 文字列からまとめて追加する @param str 文字列 @param sep セパレータ (= 等) @param connect 接続文字(, 等) */ public void add(CharArray str, String sep, String connect) { parameter.add(str, sep, connect); } public void add(String str, String sep, String connect) { parameter.add(str, sep, connect); } /** キー値をパラメータ形式で取得する **/ public CharArrayQueue getKeyParameter() { return parameter.getKeyParameter();} /** データをパラメータ形式で取得する **/ public CharArrayQueue getDataParameter() { return parameter.getParameter();} /** 要素の取得 @param index 取得する場所(0- @return 取得した値 */ public CharArray get(int index) { return parameter.get(index); } public CharArray getCharArray(int index) { return parameter.getCharArray(index); } public int getInt(int index) { return parameter.getInt(index); } public long getLong(int index) { return parameter.getLong(index); } public double getDouble(int index) { return parameter.getDouble(index); } public boolean getBoolean(int index) { return parameter.getBoolean(index); } /** 要素の取得 @param key キーワード @return 取得した値 */ public CharArray get(String key) { return parameter.get(key); } public CharArray get(CharArray key) { return parameter.get(key); } public CharArray getCharArray(String key) { return parameter.getCharArray(key); } public CharArray getCharArray(CharArray key) { return parameter.getCharArray(key); } public int getInt(String key) { return parameter.getInt(key); } public int getInt(CharArray key) { return parameter.getInt(key); } public long getLong(String key) { return parameter.getLong(key); } public long getLong(CharArray key) { return parameter.getLong(key); } public boolean getBoolean(String key) { return parameter.getBoolean(key); } public boolean getBoolean(CharArray key) { return parameter.getBoolean(key); } public double getDouble(String key) { return parameter.getDouble(key); } public double getDouble(CharArray key) { return parameter.getDouble(key); } //--------------------------------------------------------------------- // setter //--------------------------------------------------------------------- public void setValue(String[] values) { caQueue.clear(); for (int i = 0; i < values.length; i++) { caQueue.enqueue(new CharArray(values[i])); // うーん、、 } } /** HashParameter を設定する */ public boolean setParameter(HashParameter parameter) { this.parameter = parameter; return (parameter != null); } //--------------------------------------------------------------------- // getter //--------------------------------------------------------------------- public CharArrayQueue getValue() { return caQueue; } /** HashParameter を取得する */ public HashParameter getParameter() { return parameter; } //--------------------------------------------------------------------- // copy / clone //--------------------------------------------------------------------- public void copy(ParameterData from) { // 元オブジェクトより全データをコピー super.copy(from); parameter.copy(from.parameter); } //--------------------------------------------------------------------- // draw //--------------------------------------------------------------------- /** レンダリングする(何もしません) @param session SessionObject @return 出力先 */ public CharArray draw(SessionObject session) { if (visible) { // do nothing } return session.getBuffer(); } //---------------------------------------- // シリアライズ用 //---------------------------------------- public void writeObject(DataOutput out) throws IOException { super.writeObject(out); if (out != null) { parameter.writeObject(out); } } public void readObject(DataInput in) throws IOException { super.readObject(in); if (in != null) { parameter.readObject(in); } } } // // [end of ParameterData.java] // package com.xxyp.xxyp.main.bean; import com.xxyp.xxyp.common.bean.BaseBean; import java.util.List; /** * Description : 约拍bean * Created by sunpengfei on 2017/8/10. * Person in charge : sunpengfei */ public class ShotBean extends BaseBean { /* 约拍id */ private String datingShotId; /* 发布约拍用户id */ private String userId; /* 用户名称 */ private String userName; /* 用户头像 */ private String userImage; /* 约拍地址 */ private String datingShotAddress; /* 约拍目的 摄影师 模特 */ private String purpose; /* 付款方式 */ private String paymentMethod; /* 约拍信息 */ private String datingShotIntroduction; /* 约拍描述 */ private String description; /* 接受约拍userId */ private String datingUserId; /* 约拍图片 */ private List datingShotImages; private long releaseTime; /* 状态 * 0 失效 1 创建 2 进行中 3 完成 * */ private int status; public String getDatingShotId() { return datingShotId; } public void setDatingShotId(String datingShotId) { this.datingShotId = datingShotId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserImage() { return userImage; } public void setUserImage(String userImage) { this.userImage = userImage; } public String getDatingShotAddress() { return datingShotAddress; } public void setDatingShotAddress(String datingShotAddress) { this.datingShotAddress = datingShotAddress; } public String getPurpose() { return purpose; } public void setPurpose(String purpose) { this.purpose = purpose; } public String getPaymentMethod() { return paymentMethod; } public void setPaymentMethod(String paymentMethod) { this.paymentMethod = paymentMethod; } public String getDatingShotIntroduction() { return datingShotIntroduction; } public void setDatingShotIntroduction(String datingShotIntroduction) { this.datingShotIntroduction = datingShotIntroduction; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDatingUserId() { return datingUserId; } public void setDatingUserId(String datingUserId) { this.datingUserId = datingUserId; } public List getDatingShotImages() { return datingShotImages; } public void setDatingShotImages(List datingShotImages) { this.datingShotImages = datingShotImages; } public long getReleaseTime() { return releaseTime; } public void setReleaseTime(long releaseTime) { this.releaseTime = releaseTime; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } } 1-10 /* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.psi.stubsHierarchy.impl; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class StubHierarchyConnector { private final StubResolver myResolve; protected StubHierarchyConnector(Symbols symbols) { myResolve = new StubResolver(symbols, this); } void connect(Symbol sym) { Symbol.ClassSymbol c = (Symbol.ClassSymbol) sym; if (c.myOwner instanceof Symbol.ClassSymbol) { ((Symbol.ClassSymbol)c.myOwner).connect(this); } Object supers = c.mySuperClasses; if (supers == null) { c.setSupers(Collections.emptySet()); return; } // Determine supertype. Set supertypes = new HashSet<>(); try { if (supers instanceof QualifiedName[]) { for (QualifiedName name : (QualifiedName[])supers) { name.resolveCandidates(myResolve, c, supertypes); } } else { ((QualifiedName)supers).resolveCandidates(myResolve, c, supertypes); } } catch (IncompleteHierarchyException ignore) { c.markHierarchyIncomplete(); return; } for (Iterator iterator = supertypes.iterator(); iterator.hasNext();) { if (isJavaLangObject(iterator.next())) { iterator.remove(); } } c.setSupers(supertypes); } private static boolean isJavaLangObject(Symbol s) { return s.myShortName == NameEnvironment.OBJECT_NAME && s.myOwner instanceof Symbol.PackageSymbol && ((Symbol.PackageSymbol)s.myOwner).myQualifiedName == NameEnvironment.java_lang; } } package org.fortytwo.c64.cpu; import org.fortytwo.c64.memory.Memory; // basically LSR then EOR // TODO: refactor back to being based on ASL public class LSE_Instruction extends Instruction { LSE_Instruction(AddressingMode mode){ super(mode, "LSE"); switch (mode){ case ZeroPageAbsolute: cycles = 5; break; case ZeroPageIndexedX: cycles = 6; break; case Absolute: cycles = 6; break; case IndexedX: cycles = 7; break; case IndexedY: cycles = 7; break; case PreIndexedIndirect: cycles = 8; break; case PostIndexedIndirect: cycles = 8; break; default: throw new IllegalArgumentException("AddressMode not supported: " + mode); } } public int execute(int[] operands, Memory memory, CPU cpu){ int val= 0xFF & memory.read(toInt(operands)); cpu.setCarryFlag(((val & 0x01) != 0)); val = val >> 1; cpu.setZeroFlag((val & 0xFF) == 0); memory.write(toInt(operands), val & 0xFF); int accum = 0xFF & cpu.readRegister(RegisterType.accumulator); accum = accum ^ (0xFF & val); cpu.writeRegister(RegisterType.accumulator, accum); cpu.setZeroFlag((accum & 0xFF) == 0); cpu.setSignFlag((accum & 0x80) != 0); return cycles; } } dream-tool-core/src/main/java/com/wy/io/output/ByteArrayOutputStream.java package com.wy.io.output; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * 安全同步的字节数组实现类{@link java.io.ByteArrayOutputStream} FIXME * * @author 飞花梦影 * @date 2021-02-19 08:58:36 * @git {@link https://github.com/dreamFlyingFlower} */ public class ByteArrayOutputStream extends AbstractByteArrayOutputStream { /** * 创建一个默认大小的字节数组 */ public ByteArrayOutputStream() { this(DEFAULT_SIZE); } /** * 创建一个指定大小的字节数组输出流,size不能小于0 * * @param size 初始字节大小,不能小于0 */ public ByteArrayOutputStream(final int size) { if (size < 0) { throw new IllegalArgumentException("Negative initial size: " + size); } synchronized (this) { grow(size); } } /** * @see java.io.ByteArrayOutputStream#reset() */ @Override public synchronized void reset() { super.reset(); } @Override public synchronized int size() { return super.size(); } @Override public synchronized byte[] toByteArray() { return super.toByteArray(); } @Override public synchronized void write(final int b) { super.write(b); } @Override public synchronized int write(final InputStream in) throws IOException { return super.write(in); } @Override public void write(final byte[] b, final int off, final int len) { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } synchronized (this) { super.write(b, off, len); } } @Override public synchronized void writeTo(final OutputStream out) throws IOException { super.writeTo(out); } }FIRST-Team-2472/SparkMaxsrc/main/java/frc/robot/Robot.java // This program is used to demonstrate the setting of PID parameters // using the Spark Max and a small NEO motor. // Shuffleboard allows adjustment of kF, kP, kI, and kD // Shuffleboard displays joystick value, set (desired) speed, // and actual speed. // Also displayed is the actual percent difference between // set speed and actual speed. A boolean box turns green // when the 2 values are within 2 percent of each other // // The joystick can be used to adjust the speed of the motor // to try out new parameters for kF, kP, kI and kD. // The trigger on the joystick (button 1) instantly doubles // the current set speed. A timer then displays the time // it takes to see the motor at within 2% of the new // set speed. This feature allows for tuning of the // various parameters. // Most sources say to leave kD at 0 for velocity PIDs. // Suggest: // 1. Set all parameters to 0 and see that motor does not run. // 2. Adjust kF and see how close you can get to good tracking // 3. Next, adjust kP to achieve better tracking and response. // 4. If you see that the error is consistently centered on // a non-zero value, kI may be set to correct the error // toward 0. This is mainly for obsessive individuals. d // // Note: The "setClosedLoopRampRate" parameter is useful to // avoid scaring the crap out of you if your parameters are // too large - PID algorithms are notorious for very dramatic, // noisy and possibly destructive behavior if the parameters // are too large. Always start with VERY SMALL parameter values // and work up. /*----------------------------------------------------------------------------*/ /* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ // URL for downloading/installing the REV Spark Max Libraries // https://www.revrobotics.com/content/sw/max/sdk/REVRobotics.json package frc.robot; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.math.filter.MedianFilter; import edu.wpi.first.wpilibj.TimedRobot; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import com.revrobotics.CANSparkMax; import com.revrobotics.RelativeEncoder; import com.revrobotics.SparkMaxPIDController; import com.revrobotics.CANSparkMax.ControlType; import com.revrobotics.CANSparkMaxLowLevel.MotorType; /** * This is a demo program showing the use of the RobotDrive class, specifically * it contains the code necessary to operate a robot with tank drive. */ public class Robot extends TimedRobot { private Joystick m_stick; private boolean measuring = false; private long startMS = 0; private double joyYAdjusted; private double setPoint; private static final int deviceID = 40; private CANSparkMax m_motor; private SparkMaxPIDController m_pidController; private RelativeEncoder m_encoder; public double kP, kI, kD, kIz, kFF, kMaxOutput, kMinOutput, maxRPM; private double baseY; private int UltraPort = 0; private int PhotoPort = 0; MedianFilter m_filter = new MedianFilter(10); private AnalogInput distance = new AnalogInput(UltraPort); private DigitalInput photocell = new DigitalInput(PhotoPort); @Override public void robotInit() { m_stick = new Joystick(0); // initialize motor m_motor = new CANSparkMax(deviceID, MotorType.kBrushless); /** * The RestoreFactoryDefaults method can be used to reset the configuration parameters * in the SPARK MAX to their factory default state. If no argument is passed, these * parameters will not persist between power cycles */ m_motor.restoreFactoryDefaults(); // the ramp rate is the limit on how fast the controller // can change the speed of the motor - leaving this off // or setting it too low can stress the gearbox, belts, // or mechanisms. ".3" is 0 to full speed in 300MS m_motor.setClosedLoopRampRate(.3); /** * In order to use PID functionality for a controller, a CANPIDController object * is constructed by calling the getPIDController() method on an existing * CANSparkMax object */ m_pidController = m_motor.getPIDController(); // Encoder object created to display position values m_encoder = m_motor.getEncoder(); // PID coefficients //kP = 6e-5; kP = .0001; kI = 0; kD = 0; kIz = 0; // kFF = 0.000015; kFF = .0001; kMaxOutput = 1; kMinOutput = -1; maxRPM = 5700; // set PID coefficients m_pidController.setP(kP); m_pidController.setI(kI); m_pidController.setD(kD); m_pidController.setIZone(kIz); m_pidController.setFF(kFF); m_pidController.setOutputRange(kMinOutput, kMaxOutput); // display PID coefficients on SmartDashboard SmartDashboard.putNumber("P Gain", kP); SmartDashboard.putNumber("I Gain", kI); SmartDashboard.putNumber("D Gain", kD); SmartDashboard.putNumber("Feed Forward", kFF); baseY = m_stick.getY(); // set neutral joystick } @Override public void teleopInit() { // TODO Auto-generated method stub super.teleopInit(); // PID coefficients kP = .0001; kI = 0; kD = 0; kIz = 0; kFF = .0001; kMaxOutput = 1; kMinOutput = -1; maxRPM = 5700; // set PID coefficients m_pidController.setP(kP); m_pidController.setI(kI); m_pidController.setD(kD); m_pidController.setFF(kFF); m_pidController.setOutputRange(kMinOutput, kMaxOutput); // display PID coefficients on SmartDashboard SmartDashboard.putNumber("P Gain", kP); SmartDashboard.putNumber("I Gain", kI); SmartDashboard.putNumber("D Gain", kD); SmartDashboard.putNumber("Feed Forward", kFF); baseY = m_stick.getY(); // set neutral joystick } @Override public void teleopPeriodic() { double percentError = 0; double distancevalue = 0; boolean photovalue = false; // read PID coefficients from SmartDashboard double p = SmartDashboard.getNumber("P Gain", 0); double i = SmartDashboard.getNumber("I Gain", 0); double d = SmartDashboard.getNumber("D Gain", 0); double ff = SmartDashboard.getNumber("Feed Forward", 0); // if PID coefficients on SmartDashboard have changed, write new values to controller if((p != kP)) { m_pidController.setP(p); kP = p; } if((i != kI)) { m_pidController.setI(i / 1000000.0); kI = i; } if((d != kD)) { m_pidController.setD(d / 1000000.0); kD = d; } if((ff != kFF)) { m_pidController.setFF(ff); kFF = ff; } /** * PIDController objects are commanded to a set point using the * SetReference() method. * * The first parameter is the value of the set point, whose units vary * depending on the control type set in the second parameter. * * The second parameter is the control type can be set to one of four * parameters: * com.revrobotics.ControlType.kDutyCycle * com.revrobotics.ControlType.kPosition * com.revrobotics.ControlType.kVelocity * com.revrobotics.ControlType.kVoltage */ percentError = Math.abs((setPoint - m_encoder.getVelocity())/setPoint); joyYAdjusted = m_stick.getY() - baseY; if (m_stick.getRawButton(1)) { if(measuring) { if ((percentError < .02) && (startMS != 0)) { SmartDashboard.putNumber("React MS", System.currentTimeMillis() - startMS); startMS = 0; } } else { measuring = true; startMS = System.currentTimeMillis(); setPoint = joyYAdjusted * maxRPM; m_pidController.setReference(setPoint, ControlType.kVelocity); double newY = joyYAdjusted * 2.0; if (newY > .8) newY = .8; if (newY < -.8) newY = -.8; setPoint = newY * maxRPM; m_pidController.setReference(setPoint, ControlType.kVelocity); } } // If joystick button is not down, use the joystick position as // the setPoint. else { measuring = false; startMS = 0; setPoint = joyYAdjusted * maxRPM; m_pidController.setReference(setPoint, ControlType.kVelocity); } SmartDashboard.putNumber("Joy Y", m_stick.getY() - baseY); SmartDashboard.putNumber("Target Speed", setPoint); SmartDashboard.putNumber("Actual Speed", m_encoder.getVelocity()); SmartDashboard.putNumber("Graph", m_encoder.getVelocity()); double speederrorpercent = 0; if (setPoint != 0) speederrorpercent = (setPoint - m_encoder.getVelocity())/setPoint * 100.0; SmartDashboard.putNumber("Speed Error", speederrorpercent); if (Math.abs((setPoint - m_encoder.getVelocity())/setPoint) <.02) SmartDashboard.putBoolean("Tracking", true); else SmartDashboard.putBoolean("Tracking", false); distancevalue = m_filter.calculate(distance.getVoltage()); photovalue = photocell.get(); SmartDashboard.putNumber("distance", distancevalue); SmartDashboard.putBoolean("Photo", photovalue); } } 0 package org.infinispan.persistence.jdbc.common.impl; import static org.infinispan.persistence.jdbc.common.logging.Log.PERSISTENCE; import java.sql.Connection; import java.sql.SQLException; import java.util.EnumSet; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Predicate; import javax.transaction.Transaction; import org.infinispan.commons.util.IntSet; import org.infinispan.persistence.jdbc.common.TableOperations; import org.infinispan.persistence.jdbc.common.configuration.AbstractJdbcStoreConfiguration; import org.infinispan.persistence.jdbc.common.connectionfactory.ConnectionFactory; import org.infinispan.persistence.jdbc.common.logging.Log; import org.infinispan.persistence.spi.InitializationContext; import org.infinispan.persistence.spi.MarshallableEntry; import org.infinispan.persistence.spi.NonBlockingStore; import org.infinispan.persistence.spi.PersistenceException; import org.infinispan.util.concurrent.BlockingManager; import org.infinispan.util.logging.LogFactory; import org.reactivestreams.Publisher; import io.reactivex.rxjava3.core.Flowable; import io.reactivex.rxjava3.internal.functions.Functions; public abstract class BaseJdbcStore implements NonBlockingStore { protected static final Log log = LogFactory.getLog(BaseJdbcStore.class, Log.class); protected ConnectionFactory connectionFactory; protected BlockingManager blockingManager; protected C config; protected TableOperations tableOperations; protected final Map transactionConnectionMap = new ConcurrentHashMap<>(); @Override public Set characteristics() { return EnumSet.of(Characteristic.BULK_READ, Characteristic.TRANSACTIONAL, Characteristic.SHAREABLE); } Object keyIdentifier(Object key) { return key; } /** * Extension point to allow for initializing and creating a table operations object. All variables in the {@link * BaseJdbcStore} will be initialized except for {@link #tableOperations} when this is invoked. * * @param ctx store context * @param config configuration of the store * @return the table operations to use for future calls * @throws SQLException if any database exception occurs during creation */ abstract protected TableOperations createTableOperations(InitializationContext ctx, C config) throws SQLException; @Override public CompletionStage start(InitializationContext ctx) { this.config = ctx.getConfiguration(); blockingManager = ctx.getBlockingManager(); return blockingManager.runBlocking(() -> { try { ConnectionFactory factory = ConnectionFactory.getConnectionFactory(config.connectionFactory().connectionFactoryClass()); factory.start(config.connectionFactory(), factory.getClass().getClassLoader()); this.connectionFactory = factory; tableOperations = createTableOperations(ctx, config); } catch (SQLException e) { throw new PersistenceException(e); } }, "jdbcstore-start"); } /** * Method to extend to add additional steps when the store is shutting down. This is invoked before the {@link * #connectionFactory} is shut down and should not do so. */ protected void extraStopSteps() { } @Override public CompletionStage stop() { return blockingManager.runBlocking(() -> { extraStopSteps(); try { log.tracef("Stopping connection factory: %s", connectionFactory); if (connectionFactory != null) { connectionFactory.stop(); } } catch (Throwable t) { log.debug("Exception while stopping", t); } }, "jdbcstore-stop"); } @Override public CompletionStage isAvailable() { return blockingManager.supplyBlocking(() -> { if (connectionFactory == null) return false; Connection connection = null; try { connection = connectionFactory.getConnection(); return connection != null && connection.isValid(10); } catch (SQLException e) { return false; } finally { connectionFactory.releaseConnection(connection); } }, "jdbcstore-available"); } @Override public CompletionStage> load(int segment, Object key) { return blockingManager.supplyBlocking(() -> { Connection conn = null; try { conn = connectionFactory.getConnection(); return tableOperations.loadEntry(conn, segment, key); } catch (SQLException e) { Object keyIdentifier = keyIdentifier(key); PERSISTENCE.sqlFailureReadingKey(key, keyIdentifier, e); throw new PersistenceException(String.format( "SQL error while fetching stored entry with key: %s, lockingKey: %s", key, keyIdentifier), e); } finally { connectionFactory.releaseConnection(conn); } }, "jdbcstore-load"); } @Override public CompletionStage write(int segment, MarshallableEntry entry) { return blockingManager.runBlocking(() -> { Connection connection = null; try { connection = connectionFactory.getConnection(); tableOperations.upsertEntry(connection, segment, entry); } catch (SQLException ex) { PERSISTENCE.sqlFailureStoringKey(entry.getKey(), ex); throw new PersistenceException(String.format("Error while storing string key to database; key: '%s'", entry.getKey()), ex); } finally { connectionFactory.releaseConnection(connection); } }, "jdbcstore-write"); } @Override public CompletionStage delete(int segment, Object key) { return blockingManager.supplyBlocking(() -> { Connection connection = null; try { connection = connectionFactory.getConnection(); return tableOperations.deleteEntry(connection, segment, key); } catch (SQLException ex) { PERSISTENCE.sqlFailureRemovingKeys(ex); throw new PersistenceException(String.format("Error while removing key %s from database", key), ex); } finally { connectionFactory.releaseConnection(connection); } }, "jdbcstore-delete"); } @Override public CompletionStage clear() { return blockingManager.runBlocking(() -> { Connection connection = null; try { connection = connectionFactory.getConnection(); tableOperations.deleteAllRows(connection); } catch (SQLException ex) { PERSISTENCE.failedClearingJdbcCacheStore(ex); throw new PersistenceException("Failed clearing cache store", ex); } finally { connectionFactory.releaseConnection(connection); } }, "jdbcstore-delete"); } @Override public CompletionStage batch(int publisherCount, Publisher> removePublisher, Publisher>> writePublisher) { return blockingManager.runBlocking(() -> { Connection connection = null; try { connection = connectionFactory.getConnection(); tableOperations.batchUpdates(connection, publisherCount, Flowable.fromPublisher(removePublisher) .flatMap(Functions.identity()), writePublisher); } catch (SQLException e) { throw PERSISTENCE.sqlFailureWritingBatch(e); } finally { connectionFactory.releaseConnection(connection); } }, "jdbcstore-batch"); } @Override public CompletionStage prepareWithModifications(Transaction tx, int publisherCount, Publisher> removePublisher, Publisher>> writePublisher) { return blockingManager.runBlocking(() -> { try { Connection connection = getTxConnection(tx); connection.setAutoCommit(false); tableOperations.batchUpdates(connection, publisherCount, Flowable.fromPublisher(removePublisher) .flatMap(Functions.identity()), writePublisher); // We do not call connection.close() in the event of an exception, as close() on active Tx behaviour is implementation // dependent. See https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html#close-- } catch (SQLException e) { throw PERSISTENCE.prepareTxFailure(e); } }, "jdbcstore-prepare"); } @Override public CompletionStage commit(Transaction tx) { return blockingManager.runBlocking(() -> { Connection connection; try { connection = getTxConnection(tx); connection.commit(); } catch (SQLException e) { PERSISTENCE.sqlFailureTxCommit(e); throw new PersistenceException(String.format("Error during commit of JDBC transaction (%s)", tx), e); } finally { destroyTxConnection(tx); } }, "jdbcstore-commit"); } @Override public CompletionStage rollback(Transaction tx) { return blockingManager.runBlocking(() -> { Connection connection; try { connection = getTxConnection(tx); connection.rollback(); } catch (SQLException e) { PERSISTENCE.sqlFailureTxRollback(e); throw new PersistenceException(String.format("Error during rollback of JDBC transaction (%s)", tx), e); } finally { destroyTxConnection(tx); } }, "jdbcstore-rollback"); } protected Connection getTxConnection(Transaction tx) { Connection connection = transactionConnectionMap.get(tx); if (connection == null) { connection = connectionFactory.getConnection(); transactionConnectionMap.put(tx, connection); } return connection; } protected void destroyTxConnection(Transaction tx) { Connection connection = transactionConnectionMap.remove(tx); if (connection != null) connectionFactory.releaseConnection(connection); } @Override public Publisher> publishEntries(IntSet segments, Predicate filter, boolean includeValues) { return blockingManager.blockingPublisher(tableOperations.publishEntries(connectionFactory::getConnection, connectionFactory::releaseConnection, segments, filter, includeValues)); } @Override public Publisher publishKeys(IntSet segments, Predicate filter) { return blockingManager.blockingPublisher(tableOperations.publishKeys(connectionFactory::getConnection, connectionFactory::releaseConnection, segments, filter)); } @Override public CompletionStage size(IntSet segments) { return blockingManager.supplyBlocking(() -> { Connection conn = null; try { conn = connectionFactory.getConnection(); return tableOperations.size(conn); } catch (SQLException e) { PERSISTENCE.sqlFailureSize(e); throw new PersistenceException("SQL failure while retrieving size", e); } finally { connectionFactory.releaseConnection(conn); } }, "jdbcstore-size"); } @Override public CompletionStage approximateSize(IntSet segments) { return size(segments); } } package com.josonprog.jcondition.support.sql.interpret; public final class NotInterpreter extends LeftUnitaryOperatorInterpreter { public NotInterpreter() { super("NOT", 5); } } package uk.gov.hmcts.ccd.definition.store.domain.datetime; public class InvalidDateTimeFormatException extends Exception { private String dateTimeFormat; public InvalidDateTimeFormatException(String dateTimeFormat) { this.dateTimeFormat = dateTimeFormat; } public String getDateTimeFormat() { return this.dateTimeFormat; } } weltam/idylfin /** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.maths.lowlevelapi.functions.iss; import org.apache.commons.lang.Validate; /** * Tries to detect NaNs, where they are, and provides some potentially useful tools to do things like mask off NaNs. */ public class IsNaN { /** * Walks through a vector looking for NaN's if one is found the routine returns TRUE. * @param v the vector (with possible NaN entries) * @return a boolean, TRUE if a NaN is found in v, FALSE otherwise */ public static boolean any(double[] v) { Validate.notNull(v); boolean logical = false; final int len = v.length; for (int i = 0; i < len; i++) { if (v[i] != v[i]) { logical = true; return logical; } } return logical; } /** * Walks through a vector looking for NaN's and sets the index of a corresponding boolean vector to TRUE if a NaN is found. * @param v the vector (with possible NaN entries) * @return a boolean vector, true or false depending on whether a NaN is found in the input vector (true = NaN found at position). */ public static boolean[] getBooleans(double[] v) { Validate.notNull(v); final int len = v.length; boolean[] logical = new boolean[len]; for (int i = 0; i < len; i++) { if (v[i] != v[i]) { logical[i] = true; } } return logical; } /** * Walks through a vector looking for NaN's if one is found the routine returns TRUE. * @param v the vector (with possible NaN entries) * @return a boolean, TRUE if a NaN is found in v, FALSE otherwise */ public static boolean any(float[] v) { Validate.notNull(v); boolean logical = false; final int len = v.length; for (int i = 0; i < len; i++) { if (v[i] != v[i]) { logical = true; return logical; } } return logical; } /** * Walks through a vector looking for NaN's and sets the index of a corresponding boolean vector to TRUE if a NaN is found. * @param v the vector (with possible NaN entries) * @return a boolean vector, true or false depending on whether a NaN is found in the input vector (true = NaN found at position). */ public static boolean[] getBooleans(float[] v) { Validate.notNull(v); final int len = v.length; boolean[] logical = new boolean[len]; for (int i = 0; i < len; i++) { if (v[i] != v[i]) { logical[i] = true; } } return logical; } } 10-100 //Not clear on who the original author(s) of this code is/are //I may have modified is slightly, but am not the original author //I believe it to be public domain. Please contact me if I should //change the attributions or remove from the repository. //Thanks, tvelliott package jPCBSim; // General Imports import java.awt.*; import java.io.*; // JOGL Imports import javax.media.opengl.GL2; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLEventListener; import javax.media.opengl.awt.GLCanvas; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.*; import com.jogamp.opengl.util.FPSAnimator; import static javax.media.opengl.GL.*; // GL constants import static javax.media.opengl.GL2.*; // GL2 constants import com.jogamp.opengl.util.*; import com.jogamp.opengl.util.gl2.*; /** * Renderer Class * * @version $Id: Renderer.java 813 2008-06-03 16:31:35Z mzaczek $ * @since CTS 1.0 */ public class Renderer implements GLEventListener { /** GLU object. */ private GLU glu = new GLU(); private pcb_model pcbmodel; private boolean is_ortho=false; private boolean do_mesh=true; private boolean do_pml=false; private boolean do_airbox=true; /** * GLUquadric instance of a star sphere used for displaying a sphere textured * with stars to represent the star field. */ private GLUquadric starSphere; private double zoom_ortho=1.0; /** Ambient light array. */ private float lightAmbient[] = {0.38f, 0.38f, 0.38f, 0.0f}; /** Diffuse light array. */ private float lightDiffuse[] = {1.0f, 1.0f, 1.0f, 0.0f}; /** Specular light array. */ //private float lightSpecular[] = {0.15f, 0.15f, 0.15f, 0.0f}; private float lightSpecular[] = {0.0f, 0.0f, 0.0f, 0.0f}; /** Ambient/Diffuse array. */ private float lightAmbientDiffuse[] = {0.65f, 0.65f, 0.65f, 0.0f}; /** Position of the light. */ private float lightPosition[] = {1.0f, 1.0f, 1.0f, 1.0f}; private float lightPosition1[] = {1.0f, 1.0f, 1.0f, 1.0f}; /** Near plane clipping distance. */ public double nearPlane = 0.0001; //public double nearPlane = 1.0; /** Far plane clipping distance. */ public double farPlane = 200000000.0; /** Zoom factor based on distance of eye to object. */ public double zoomFactor = 0.01; /** Width. */ private int _width; /** Height. */ private int _height; private Simulation simulation; private PCBSimClient client; /** Reset flag that when true will ask the display method to perform a reshape. */ public boolean reset = false; public Vector3d vEye = new Vector3d(1.0, 1.0, 1.0); public Vector3d vLook = new Vector3d(-0.05, -0.05, -0.05); public Vector3d vUp = new Vector3d(0.0, 1.0, 0.0); public Vector3d vRight = new Vector3d(1.0, 0.0, 0.0); public Point lastMousePoint = new Point(); public Point currentMousePoint = new Point(); public Camera camera = new Camera(); /** * Renderer constructor that initializes the rotation strings and sets the * width/height. * * @param width The width. * @param height The height. */ Renderer(int width, int height) { this._width = width; this._height = height; camera.setEye(new Vector3d(0, 0, 100)); camera.lookAt(new Vector3d(0, 0, 0), new Vector3d(1, 0, 0)); camera.rotateAroundLookVector(90.0); camera.moveBack(0.5); } public void setPCBModel(pcb_model model) { this.pcbmodel = model; } public void setSimulation(Simulation sim) { this.simulation = sim; } public void setClient(PCBSimClient client) { this.client = client; } public void meshApplySettings() { try { client.updateFromSimFields(simulation); simulation.writeConfig(); pcbmodel.updateMesh(simulation); } catch(Exception e) { e.printStackTrace(); } } public void abortSimulation() { try { simulation.abort(); } catch(Exception e) { e.printStackTrace(); } } public void runSimulation() { openEMSWriter writer = new openEMSWriter(simulation); try { this.is_ortho = false; this.do_mesh = true; this.do_pml = false; this.do_airbox = true; reset=true; client.updateFromSimFields(simulation); simulation.writeConfig(); pcbmodel.updateMesh(simulation); writer.writeOpenEMSConfig(pcbmodel); } catch(Exception e) { e.printStackTrace(); } } public void readEMSConfig() { openEMSWriter writer = new openEMSWriter(simulation); try { writer.readOpenEMSConfig(pcbmodel); } catch(Exception e) { e.printStackTrace(); } } public void setMesh(boolean b) { this.do_mesh = b; reset=true; } public void setAirBox(boolean b) { this.do_airbox = b; reset=true; } public void setPML(boolean b) { this.do_pml = b; reset=true; } public void toggleOrtho() { this.is_ortho = !this.is_ortho; reset=true; } public void toggleMesh() { this.do_mesh = !this.do_mesh; reset=true; } public void togglePML() { this.do_pml = !this.do_pml; reset=true; } public void toggleAirBox() { this.do_airbox = !this.do_airbox; reset=true; } public boolean isOrtho() { return is_ortho; } public void zoomOrtho(double val) { if( val < 0.0 ) { if( zoom_ortho >= 0.05 ) zoom_ortho-=0.05; } else { zoom_ortho+=0.05; } camera.doUpdate(); reset=true; } public double getZoomOrtho() { return zoom_ortho; } /** * The initialization function that configures the view, defines the lights, * loads the star and sun textures, and initializes the system and its * children. * * @param drawable A GLAutoDrawable instance. */ public void init(GLAutoDrawable drawable) { final GL2 gl = drawable.getGL().getGL2(); gl.setSwapInterval(1); // // View Settings // gl.glViewport(0, 0, 320, 240); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); // Set the Field-of-View, Aspect Ratio, Near & Far clipping planes glu.gluPerspective(65.0, 320.0 / 240.0, nearPlane, farPlane); gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadIdentity(); //scale meters to display units gl.glTranslated(254.0,254.0,254.0); // // Lighting // // Enable Smooth Shading gl.glShadeModel(GL2.GL_SMOOTH); gl.glMaterialfv(gl.GL_FRONT_AND_BACK, gl.GL_SPECULAR, lightSpecular, 0); gl.glMaterialfv(gl.GL_FRONT_AND_BACK, GL2.GL_AMBIENT_AND_DIFFUSE, lightAmbientDiffuse, 0); // Background - black gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Depth Buffer Setup gl.glClearDepth(1.0f); // Clear The Stencil Buffer To 0 gl.glClearStencil(0); // Enables Depth Testing gl.glEnable(GL2.GL_DEPTH_TEST); // Really Nice Perspective Calculations gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST); // Set The Ambient Lighting For Light0 gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_AMBIENT, lightAmbient, 0); // Set The Diffuse Lighting For Light0 gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_DIFFUSE, lightDiffuse, 0); // Set The Position For Light0 gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, lightPosition, 0); gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_SPECULAR, lightSpecular, 0); gl.glLightf(GL2.GL_LIGHT0, GL2.GL_CONSTANT_ATTENUATION, 1.0f); gl.glLightf(GL2.GL_LIGHT0, GL2.GL_LINEAR_ATTENUATION, 0.0f); gl.glLightf(GL2.GL_LIGHT0, GL2.GL_QUADRATIC_ATTENUATION, 0.0f); // Set The Ambient Lighting For Light0 gl.glLightfv(GL2.GL_LIGHT1, GL2.GL_AMBIENT, lightAmbient, 0); // Set The Diffuse Lighting For Light0 gl.glLightfv(GL2.GL_LIGHT1, GL2.GL_DIFFUSE, lightDiffuse, 0); // Set The Position For Light0 gl.glLightfv(GL2.GL_LIGHT1, GL2.GL_POSITION, lightPosition, 0); gl.glLightfv(GL2.GL_LIGHT1, GL2.GL_SPECULAR, lightSpecular, 0); gl.glLightf(GL2.GL_LIGHT1, GL2.GL_CONSTANT_ATTENUATION, 1.0f); gl.glLightf(GL2.GL_LIGHT1, GL2.GL_LINEAR_ATTENUATION, 0.0f); gl.glLightf(GL2.GL_LIGHT1, GL2.GL_QUADRATIC_ATTENUATION, 0.0f); //gl.glLightModeli(GL2.GL_LIGHT_MODEL_LOCAL_VIEWER, GL2.GL_FALSE); //gl.glLightModelfv(gl.GL_LIGHT_MODEL_AMBIENT, lightAmbient, 0); gl.glLightModelfv(gl.GL_LIGHT_MODEL_TWO_SIDE, lightAmbient, 0); // Enable Lighting gl.glEnable(GL2.GL_LIGHTING); // Enable Light 0 gl.glEnable(GL2.GL_LIGHT0); gl.glEnable(GL2.GL_LIGHT1); gl.glDisable(GL2.GL_CULL_FACE); gl.glEnable(GL2.GL_NORMALIZE); gl.glLightModelf(GL2.GL_LIGHT_MODEL_COLOR_CONTROL, GL2.GL_SEPARATE_SPECULAR_COLOR); // Enable lighting on both side...especially needed for certain models // where the normal calculations would give the wrong face. // Note that this failed for some models being loaded...test again. //gl.glLightModeli(GL2.GL_LIGHT_MODEL_TWO_SIDE,1); } /** * The primary display function that is called by JOGL to draw the defined * scene - it is called for every frame. It first clears the background of * the previous scene. Next the rotation parameters are corrected/updated. * The star background is then displayed, which is then followed by the * display of the planets and models attached to the system. And finally, * the sun texture is drawn and pointed at the user. * * @param drawable A GLAutoDrawable instance. */ public void display(GLAutoDrawable drawable) { GL2 gl = drawable.getGL().getGL2(); if (reset) { if(!this.is_ortho) { int width = _width; int height = _height; gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); // Set the Field-of-View, Aspect Ratio, Near & Far clipping planes glu.gluPerspective(65.0, width / height, nearPlane, farPlane); } else { gl.glMatrixMode(GL_PROJECTION); gl.glLoadIdentity(); gl.glOrtho(pcbmodel.getZoomOrtho()*-1.2*pcbmodel.max_x,pcbmodel.getZoomOrtho()*1.2*pcbmodel.max_x, pcbmodel.getZoomOrtho()*-1.2*pcbmodel.max_x, pcbmodel.getZoomOrtho()*1.2*pcbmodel.max_x,-1, 1); } gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadIdentity(); reset = false; } // Clear Screen And Depth Buffer gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT); gl.glLoadIdentity(); updateView(gl); // Update light position // 0 in the last component causes jagged terminator on planets, 1 results // in a smooth terminator but the location of the sunlight is no longer // correct...not sure why. Old code used a 0 (zero) very successfully, // what changed?! gl.glLightfv(GL2.GL_LIGHT0, GL2.GL_POSITION, lightPosition, 0); gl.glLightfv(GL2.GL_LIGHT1, GL2.GL_POSITION, lightPosition1, 0); GLUT glut = new GLUT(); gl.glEnable(GL2.GL_LIGHTING); gl.glEnable(GL2.GL_COLOR_MATERIAL); /* //draw the grid int x = 0; gl.glPushMatrix(); gl.glPushAttrib(GL_ALL_ATTRIB_BITS); gl.glDisable(GL2.GL_LIGHTING); gl.glLineWidth(1.0f); gl.glColor3f(0.1f, 0.1f, 0.1f); double offset = -100.0; for(x=-4990;x<5000;x+=10) { gl.glBegin(gl.GL_LINES); gl.glVertex3d(x, offset, -5000); gl.glVertex3d(x, offset, 5000); gl.glVertex3d(-5000, offset, x); gl.glVertex3d(5000, offset, x); gl.glEnd(); } gl.glPopAttrib(); gl.glPopMatrix(); */ //draw the pcb model if(pcbmodel!=null) { pcbmodel.render(gl); } //draw the mesh model if(pcbmodel!=null) { pcbmodel.setOrtho(this.is_ortho, this.zoom_ortho); if(do_mesh) pcbmodel.renderMesh(gl, do_pml, do_airbox); } gl.glPushMatrix(); gl.glPushAttrib(GL_ALL_ATTRIB_BITS); gl.glEnable (GL_LINE_SMOOTH); gl.glEnable(GL2.GL_POLYGON_SMOOTH); gl.glEnable(GL2.GL_BLEND); gl.glHint(GL2.GL_POLYGON_SMOOTH_HINT, GL2.GL_NICEST); gl.glHint(GL2.GL_LINE_SMOOTH_HINT, GL2.GL_NICEST); gl.glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //draw origin gl.glLineWidth(1.0f); gl.glBegin(gl.GL_LINES); gl.glColor4f(0.5f, 0.0f, 0.0f, 0.5f); gl.glVertex3d(-5000, 0, 0); gl.glVertex3d(5000, 0, 0); gl.glColor4f(0.0f, 0.5f, 0.0f, 0.5f); gl.glVertex3d(0, -0500, 0); gl.glVertex3d(0, 5000, 0); gl.glColor4f(0.0f, 0.0f, 0.5f, 0.5f); gl.glVertex3d(0, 0, -5000); gl.glVertex3d(0, 0, 5000); gl.glEnd(); gl.glPopAttrib(); gl.glPopMatrix(); // Flush The GL Rendering Pipeline gl.glFlush(); } /** * This method affects the display if the window is reshaped. * * @param drawable A GLAutoDrawable instance. * @param x The x coordinate of the top-left corner of the window. * @param y The y coordinate of the top-left corner of the window. * @param width The width of the window. * @param height The height of the window. */ public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { GL2 gl = drawable.getGL().getGL2(); // Prevent division by 0 in aspect ratio if (height <= 0) { height = 1; } this._width = width; this._height = height; if(!this.is_ortho) { gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL2.GL_PROJECTION); gl.glLoadIdentity(); // Set the Field-of-View, Aspect Ratio, Near & Far clipping planes glu.gluPerspective(65.0, width / height, nearPlane, farPlane); } else { gl.glMatrixMode(GL_PROJECTION); gl.glLoadIdentity(); gl.glOrtho(pcbmodel.getZoomOrtho()*-1.2*pcbmodel.max_x,pcbmodel.getZoomOrtho()*1.2*pcbmodel.max_x, pcbmodel.getZoomOrtho()*-1.2*pcbmodel.max_x, pcbmodel.getZoomOrtho()*1.2*pcbmodel.max_x,-1, 1); } gl.glMatrixMode(GL2.GL_MODELVIEW); gl.glLoadIdentity(); } /** * This method is not completed in the current JOGL specification (1.1.0) * but is is required because of the implementation specification. * * @param drawable A GLAutoDrawable instance. * @param modeChanged Flag for mode change. * @param deviceChanged Flag for device change (ie if window is moved to another * screen, etc). */ public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { // Nothing } private void updateView(GL2 gl) { gl.glMultMatrixd(camera.getView(), 0); } /** * Builds a view matrix. * * The final view matrix will take the form of: *
   *  |   rx    ry    rz   -(r.e)  |
   *  |   ux    uy    uz   -(u.e)  |
   *  |  -lx   -ly   -lz    (l.e)  |
   *  |    0     0     0       1   |
   *
   * Where r = Right vector
   *       u = Up vector
   *       l = Look vector
   *       e = Eye position in world space
   *       . = Dot-Product operation
   * 
* */ private void updateViewMatrix(GL2 gl) { double view[] = {1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; vLook.normalize(); Vector3d.cross(vRight, vLook, vUp); vRight.normalize(); Vector3d.cross(vUp, vRight, vLook); vUp.normalize(); view[0] = vRight.x; view[1] = vUp.x; view[2] = -vLook.x; view[3] = 0.0; view[4] = vRight.y; view[5] = vUp.y; view[6] = -vLook.y; view[7] = 0.0; view[8] = vRight.z; view[9] = vUp.z; view[10] = -vLook.z; view[11] = 0.0; view[12] = -Vector3d.dot(vRight, vEye); view[13] = -Vector3d.dot(vUp, vEye); view[14] = Vector3d.dot(vLook, vEye); view[15] = 1.0; // System.out.println(" vEye: " + vEye); // System.out.println(" vLook: " + vLook); // System.out.println(" vUp: " + vUp); // System.out.println("vRight: " + vRight); gl.glMultMatrixd(view, 0); } public double[] matRotate(double mat[], double angle, Vector3d axis) { double s = Math.sin(angle * Math.PI / 180.0); double c = Math.cos(angle * Math.PI / 180.0); axis.normalize(); mat[0] = c + (1 - c) * axis.x; mat[1] = (1 - c) * axis.x * axis.y + s * axis.z; mat[2] = (1 - c) * axis.x * axis.z - s * axis.y; mat[3] = 0.0; mat[4] = (1 - c) * axis.y * axis.x - s * axis.z; mat[5] = c + (1 - c) * Math.pow(axis.y, 2); mat[6] = (1 - c) * axis.y * axis.z + s * axis.x; mat[7] = 0.0; mat[8] = (1 - c) * axis.z * axis.x + s * axis.y; mat[9] = (1 - c) * axis.z * axis.z - s * axis.x; mat[10] = c + (1 - c) * Math.pow(axis.z, 2); mat[11] = 0.0; mat[12] = 0.0; mat[13] = 0.0; mat[14] = 0.0; mat[15] = 1.0; return mat; } public Vector3d transformVector(double mat[], Vector3d vec) { double x = vec.x; double y = vec.y; double z = vec.z; vec.x = x * mat[0] + y * mat[4] + z * mat[8]; vec.y = x * mat[1] + y * mat[5] + z * mat[9]; vec.z = x * mat[2] + y * mat[6] + z * mat[10]; return vec; } /** * Source: http://local.wasp.uwa.edu.au/~pbourke/geometry/rotate/ * s * @param angle */ public void rotateLookVector( double angle ) { double a = angle * Math.PI/180.0; Quat4f q1 = new Quat4f((float)vUp.x, (float)vUp.y, (float)vUp.z, 0.0f); Quat4f q2 = new Quat4f((float)(vLook.x * Math.sin(a/2.0)), (float)(vLook.y * Math.sin(a/2.0)), (float)(vLook.z * Math.sin(a/2.0)), (float)(Math.cos(a/2))); Quat4f q3 = new Quat4f(); q3 = Quat4f.mult(q2, Quat4f.mult(q1, Quat4f.conjugate(q2))); // System.out.println("--------------angle: " + a + " ---------------------"); // System.out.println(" vUp: " + vUp); // System.out.println(" q3: " + q3); vUp.x = q3.x; vUp.y = q3.y; vUp.z = q3.z; } public void dispose(GLAutoDrawable arg0) { } } echosvg-css/src/main/java/io/sf/carte/echosvg/css/engine/value/svg/EnableBackgroundManager.java /* See the NOTICE file distributed with this work for additional information regarding copyright ownership. 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 io.sf.carte.echosvg.css.engine.value.svg; import org.w3c.dom.DOMException; import org.w3c.dom.css.CSSPrimitiveValue; import org.w3c.dom.css.CSSValue; import io.sf.carte.doc.style.css.nsac.LexicalUnit; import io.sf.carte.echosvg.css.engine.CSSEngine; import io.sf.carte.echosvg.css.engine.CSSStylableElement; import io.sf.carte.echosvg.css.engine.StyleMap; import io.sf.carte.echosvg.css.engine.value.LengthManager; import io.sf.carte.echosvg.css.engine.value.ListValue; import io.sf.carte.echosvg.css.engine.value.Value; import io.sf.carte.echosvg.css.engine.value.ValueConstants; import io.sf.carte.echosvg.css.engine.value.ValueManager; import io.sf.carte.echosvg.util.CSSConstants; import io.sf.carte.echosvg.util.SVGTypes; /** * This class provides a manager for the 'enable-background' property values. * * @author * @author For later modifications, see Git history. * @version $Id$ */ public class EnableBackgroundManager extends LengthManager { /** * The length orientation. */ protected int orientation; /** * Implements {@link ValueManager#isInheritedProperty()}. */ @Override public boolean isInheritedProperty() { return false; } /** * Implements {@link ValueManager#isAnimatableProperty()}. */ @Override public boolean isAnimatableProperty() { return false; } /** * Implements {@link ValueManager#isAdditiveProperty()}. */ @Override public boolean isAdditiveProperty() { return false; } /** * Implements {@link ValueManager#getPropertyType()}. */ @Override public int getPropertyType() { return SVGTypes.TYPE_ENABLE_BACKGROUND_VALUE; } /** * Implements {@link ValueManager#getPropertyName()}. */ @Override public String getPropertyName() { return CSSConstants.CSS_ENABLE_BACKGROUND_PROPERTY; } /** * Implements {@link ValueManager#getDefaultValue()}. */ @Override public Value getDefaultValue() { return SVGValueConstants.ACCUMULATE_VALUE; } /** * Implements {@link ValueManager#createValue(LexicalUnit,CSSEngine)}. */ @Override public Value createValue(LexicalUnit lu, CSSEngine engine) throws DOMException { switch (lu.getLexicalUnitType()) { case INHERIT: return ValueConstants.INHERIT_VALUE; default: throw createInvalidLexicalUnitDOMException(lu.getLexicalUnitType()); case IDENT: String id = lu.getStringValue().toLowerCase().intern(); if (id == CSSConstants.CSS_ACCUMULATE_VALUE) { return SVGValueConstants.ACCUMULATE_VALUE; } if (id != CSSConstants.CSS_NEW_VALUE) { throw createInvalidIdentifierDOMException(id); } ListValue result = new ListValue(' '); result.append(SVGValueConstants.NEW_VALUE); lu = lu.getNextLexicalUnit(); if (lu == null) { return result; } result.append(super.createValue(lu, engine)); for (int i = 1; i < 4; i++) { lu = lu.getNextLexicalUnit(); if (lu == null) { throw createMalformedLexicalUnitDOMException(); } result.append(super.createValue(lu, engine)); } return result; } } /** * Implements {@link ValueManager#createStringValue(short,String,CSSEngine)}. */ @Override public Value createStringValue(short type, String value, CSSEngine engine) { if (type != CSSPrimitiveValue.CSS_IDENT) { throw createInvalidStringTypeDOMException(type); } if (!value.equalsIgnoreCase(CSSConstants.CSS_ACCUMULATE_VALUE)) { throw createInvalidIdentifierDOMException(value); } return SVGValueConstants.ACCUMULATE_VALUE; } /** * Implements {@link ValueManager#createFloatValue(short,float)}. */ @Override public Value createFloatValue(short unitType, float floatValue) throws DOMException { throw createDOMException(); } /** * Implements * {@link ValueManager#computeValue(CSSStylableElement,String,CSSEngine,int,StyleMap,Value)}. */ @Override public Value computeValue(CSSStylableElement elt, String pseudo, CSSEngine engine, int idx, StyleMap sm, Value value) { if (value.getCssValueType() == CSSValue.CSS_VALUE_LIST) { ListValue lv = (ListValue) value; if (lv.getLength() == 5) { Value lv1 = lv.item(1); orientation = HORIZONTAL_ORIENTATION; Value v1 = super.computeValue(elt, pseudo, engine, idx, sm, lv1); Value lv2 = lv.item(2); orientation = VERTICAL_ORIENTATION; Value v2 = super.computeValue(elt, pseudo, engine, idx, sm, lv2); Value lv3 = lv.item(3); orientation = HORIZONTAL_ORIENTATION; Value v3 = super.computeValue(elt, pseudo, engine, idx, sm, lv3); Value lv4 = lv.item(4); orientation = VERTICAL_ORIENTATION; Value v4 = super.computeValue(elt, pseudo, engine, idx, sm, lv4); if (lv1 != v1 || lv2 != v2 || lv3 != v3 || lv4 != v4) { ListValue result = new ListValue(' '); result.append(lv.item(0)); result.append(v1); result.append(v2); result.append(v3); result.append(v4); return result; } } } return value; } /** * Indicates the orientation of the property associated with this manager. */ @Override protected int getOrientation() { return orientation; } } package com.py.py.api; import java.security.Principal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; 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 com.py.py.constants.APIUrls; import com.py.py.constants.ResponseCodes; import com.py.py.dto.APIResponse; import com.py.py.dto.DTO; import com.py.py.dto.in.SubmitFeedbackDTO; import com.py.py.service.FeedbackService; import com.py.py.service.constants.PermissionNames; import com.py.py.validation.SubmitFeedbackValidator; @Controller public class FeedbackController extends BaseController { @Autowired protected FeedbackService feedbackService; @InitBinder protected void initBinder(WebDataBinder binder) { binder.setValidator(new SubmitFeedbackValidator()); } @PreAuthorize("hasAuthority('" + PermissionNames.FEEDBACK_SUBMIT + "')") @ResponseBody @RequestMapping(value = APIUrls.FEEDBACKS, method = RequestMethod.POST) public APIResponse bug(Principal p, @RequestBody @Validated SubmitFeedbackDTO dto) throws Exception{ feedbackService.createFeedback(getUser(p), dto); return Success(ResponseCodes.CREATED); } } src/main/java/org/asciidoctor/ant/AsciidoctorAntTask.java /* * Copyright 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 org.asciidoctor.ant; import org.apache.commons.io.FileUtils; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; import org.asciidoctor.*; import org.asciidoctor.internal.JRubyRuntimeContext; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class AsciidoctorAntTask extends Task { private File sourceDirectory; private File outputDirectory; private boolean preserveDirectories = false; private String sourceDocumentName; private String backend = "docbook"; private String imagesDir = "images"; private String doctype = "article"; private boolean compact = false; private boolean headerFooter = true; private String sourceHighlighter; private boolean embedAssets = false; private String eruby = ""; private String templateDir; private String templateEngine; private String baseDir; private boolean relativeBaseDir = false; private String extensions; private SafeMode safe = SafeMode.SAFE; private List resources = new ArrayList(); private List attributes = new ArrayList(); private List preProcessors = new ArrayList(); private List treeProcessors = new ArrayList(); private List postProcessors = new ArrayList(); private List blockProcessors = new ArrayList(); private List blockMacroProcessors = new ArrayList(); private List inlineMacroProcessors = new ArrayList(); private List includeProcessors = new ArrayList(); private List requires = new ArrayList(); private String gemPaths; @Override public void execute() throws BuildException { checkMandatoryParameter("sourceDirectory", sourceDirectory); checkMandatoryParameter("outputDirectory", outputDirectory); ensureOutputExists(outputDirectory); Asciidoctor asciidoctor = createAsciidoctor(gemPaths); registerAdditionalRubyLibraries(asciidoctor); registerExtensions(asciidoctor); AttributesBuilder attributesBuilder = buildAttributes(); OptionsBuilder optionsBuilder = buildOptions(); optionsBuilder.attributes(attributesBuilder.get()); if (sourceDocumentName == null) { log("Render asciidoc files from " + sourceDirectory + " to " + outputDirectory + " with backend=" + backend); for (File file : scanSourceFiles()) { setDestinationPaths(optionsBuilder, file); asciidoctor.renderFile(file, optionsBuilder.get()); } } else { log("Render " + sourceDocumentName + " from " + sourceDirectory + " to " + outputDirectory + " with backend=" + backend); File file = new File(sourceDirectory, sourceDocumentName); setDestinationPaths(optionsBuilder, file); asciidoctor.renderFile(file, optionsBuilder.get()); } try { for (FileSet resource : resources) { File resourceDir = resource.getDir(); String destPath = resourceDir.getCanonicalPath().substring(sourceDirectory.getCanonicalPath().length()); File destResourceDir = new File(outputDirectory, destPath); destResourceDir.mkdirs(); String[] includedFiles = resource.getDirectoryScanner(getProject()).getIncludedFiles(); FileUtils.copyDirectory(resourceDir, destResourceDir, new ResourceFileFilter(includedFiles), false); } } catch (IOException e) { throw new BuildException("Error copying resources", e); } } private void registerAdditionalRubyLibraries(Asciidoctor asciidoctor) { for (RubyLibrary require : requires) { asciidoctor.rubyExtensionRegistry().requireLibrary(require.getName()); } } private void registerExtensions(Asciidoctor asciidoctor) { try { asciidoctor.rubyExtensionRegistry().requireLibrary("asciidoctor-diagram"); } catch (RuntimeException e) { log("asciidoctor-diagram is not available", Project.MSG_WARN); } for (Extension preProcessor : preProcessors) { asciidoctor.javaExtensionRegistry().preprocessor(preProcessor.getClassName()); } for (Extension treeProcessor : treeProcessors) { asciidoctor.javaExtensionRegistry().treeprocessor(treeProcessor.getClassName()); } for (Extension postProcessor : postProcessors) { asciidoctor.javaExtensionRegistry().postprocessor(postProcessor.getClassName()); } for (Extension blockProcessor : blockProcessors) { asciidoctor.javaExtensionRegistry().block(blockProcessor.getBlockName(), blockProcessor.getClassName()); } for (Extension blockMacroProcessor : blockMacroProcessors) { asciidoctor.javaExtensionRegistry().blockMacro(blockMacroProcessor.getBlockName(), blockMacroProcessor.getClassName()); } for (Extension inlineMacroProcessor : inlineMacroProcessors) { asciidoctor.javaExtensionRegistry().inlineMacro(inlineMacroProcessor.getBlockName(), inlineMacroProcessor.getClassName()); } for (Extension includeProcessor : includeProcessors) { asciidoctor.javaExtensionRegistry().includeProcessor(includeProcessor.getClassName()); } } private Asciidoctor createAsciidoctor(String gemPath) { ClassLoader oldTCCL = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); return getAsciidoctorInstance(gemPath); } finally { Thread.currentThread().setContextClassLoader(oldTCCL); } } private Asciidoctor getAsciidoctorInstance(String gemPath) { Asciidoctor asciidoctor; if (gemPath == null) { asciidoctor = Asciidoctor.Factory.create(); } else { // Replace Windows path separator to avoid paths with mixed \ and /. // This happens for instance when setting: ${project.build.directory}/gems-provided // because the project's path is converted to string. String normalizedGemPath = (File.separatorChar == '\\') ? gemPath.replaceAll("\\\\", "/") : gemPath; asciidoctor = Asciidoctor.Factory.create(normalizedGemPath); } String gemHome = JRubyRuntimeContext.get(asciidoctor).evalScriptlet("ENV['GEM_HOME']").toString(); String gemHomeExpected = (gemPath == null || "".equals(gemPath)) ? "" : gemPath.split(java.io.File.pathSeparator)[0]; if (!"".equals(gemHome) && !gemHomeExpected.equals(gemHome)) { log("Using inherited external environment to resolve gems (" + gemHome + "), i.e. build is platform dependent!"); } return asciidoctor; } private OptionsBuilder buildOptions() { OptionsBuilder optionsBuilder = OptionsBuilder.options(); optionsBuilder.safe(safe).eruby(eruby).backend(backend).docType(doctype).compact(compact).headerFooter(headerFooter).mkDirs(true); if (templateEngine != null) { optionsBuilder.templateEngine(templateEngine); } if (templateDir != null) { optionsBuilder.templateDir(new File(templateDir)); } return optionsBuilder; } private void setDestinationPaths(OptionsBuilder optionsBuilder, final File sourceFile) { optionsBuilder.baseDir(computeBaseDir(sourceFile)); try { if (preserveDirectories) { String proposalPath = sourceFile.getParentFile().getCanonicalPath().substring(sourceDirectory.getCanonicalPath().length()); File relativePath = new File(outputDirectory, proposalPath); relativePath.mkdirs(); optionsBuilder.toDir(relativePath).destinationDir(relativePath); } else { File destinationDir = outputDirectory; optionsBuilder.toDir(destinationDir).destinationDir(destinationDir); } } catch (IOException e) { throw new BuildException("Unable to locate output directory", e); } } private File computeBaseDir(File sourceFile) { File baseDirFile; if (baseDir != null) { baseDirFile = new File(baseDir); } else { // when preserveDirectories == false, parent and sourceDirectory are the same if (relativeBaseDir) { baseDirFile = sourceFile.getParentFile(); } else { baseDirFile = getProject().getBaseDir(); } } return baseDirFile; } private AttributesBuilder buildAttributes() { AttributesBuilder attributesBuilder = AttributesBuilder.attributes(); attributesBuilder.imagesDir(imagesDir); if (sourceHighlighter != null) { attributesBuilder.sourceHighlighter(sourceHighlighter); } if (embedAssets) { attributesBuilder.linkCss(false); attributesBuilder.dataUri(true); } attributesBuilder.copyCss(false); // TODO Figure out how to reliably set other values (like boolean values, dates, times, etc) for (Attribute attribute : attributes) { if ("true".equals(attribute.getValue()) || "false".equals(attribute.getValue())) { attributesBuilder.attribute(attribute.getKey(), Attributes.toAsciidoctorFlag(Boolean.valueOf(attribute.getValue()))); continue; } // Can't do anything about dates and times because all that logic is private in Attributes attributesBuilder.attribute(attribute.getKey(), attribute.getValue()); } return attributesBuilder; } private void checkMandatoryParameter(String name, Object value) { if (value == null) { throw new BuildException(name + " is mandatory"); } } private void ensureOutputExists(File outputFile) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { log("Can't create " + outputFile.getPath(), Project.MSG_ERR); } } } private List scanSourceFiles() { final List asciidoctorFiles; String absoluteSourceDirectory = sourceDirectory.getAbsolutePath(); if (extensions == null || extensions.isEmpty()) { final DirectoryWalker directoryWalker = new AsciiDocDirectoryWalker(absoluteSourceDirectory); asciidoctorFiles = directoryWalker.scan(); } else { final DirectoryWalker directoryWalker = new CustomExtensionDirectoryWalker(absoluteSourceDirectory, Arrays.asList(extensions.split(","))); asciidoctorFiles = directoryWalker.scan(); } for (Iterator iter = asciidoctorFiles.iterator(); iter.hasNext();) { File f = iter.next(); do { // stop when we hit the source directory root if (absoluteSourceDirectory.equals(f.getAbsolutePath())) { break; } // skip if the filename or directory begins with _ if (f.getName().startsWith("_")) { iter.remove(); break; } } while ((f = f.getParentFile()) != null); } return asciidoctorFiles; } private static class CustomExtensionDirectoryWalker extends AbstractDirectoryWalker { private final List extensions; public CustomExtensionDirectoryWalker(final String absolutePath, final List extensions) { super(absolutePath); this.extensions = extensions; } @Override protected boolean isAcceptedFile(final File filename) { final String name = filename.getName(); for (final String extension : extensions) { if (name.endsWith(extension)) { return true; } } return false; } } // Setters for Ant Task @SuppressWarnings("UnusedDeclaration") public void setSourceDirectory(File sourceDirectory) { this.sourceDirectory = sourceDirectory; } @SuppressWarnings("UnusedDeclaration") public void setOutputDirectory(File outputDirectory) { this.outputDirectory = outputDirectory; } @SuppressWarnings("UnusedDeclaration") public void setSourceDocumentName(String sourceDocumentName) { this.sourceDocumentName = sourceDocumentName; } @SuppressWarnings("UnusedDeclaration") public void setBackend(String backend) { this.backend = backend; } @SuppressWarnings("UnusedDeclaration") public void setImagesDir(String imagesDir) { this.imagesDir = imagesDir; } @SuppressWarnings("UnusedDeclaration") public void setDoctype(String doctype) { this.doctype = doctype; } @SuppressWarnings("UnusedDeclaration") public void setCompact(boolean compact) { this.compact = compact; } @SuppressWarnings("UnusedDeclaration") public void setHeaderFooter(boolean headerFooter) { this.headerFooter = headerFooter; } @SuppressWarnings("UnusedDeclaration") public void setSourceHighlighter(String sourceHighlighter) { this.sourceHighlighter = sourceHighlighter; } @SuppressWarnings("UnusedDeclaration") public void setEmbedAssets(boolean embedAssets) { this.embedAssets = embedAssets; } @SuppressWarnings("UnusedDeclaration") public void setEruby(String eruby) { this.eruby = eruby; } @SuppressWarnings("UnusedDeclaration") public void setTemplateDir(String templateDir) { this.templateDir = templateDir; } @SuppressWarnings("UnusedDeclaration") public void setTemplateEngine(String templateEngine) { this.templateEngine = templateEngine; } @SuppressWarnings("UnusedDeclaration") public void setBaseDir(String baseDir) { this.baseDir = baseDir; } @SuppressWarnings("UnusedDeclaration") public void setRelativeBaseDir(boolean relativeBaseDir) { this.relativeBaseDir = relativeBaseDir; } @SuppressWarnings("UnusedDeclaration") public void setExtensions(String extensions) { this.extensions = extensions; } @SuppressWarnings("UnusedDeclaration") public void setPreserveDirectories(boolean preserveDirectories) { this.preserveDirectories = preserveDirectories; } @SuppressWarnings("UnusedDeclaration") public void addResource(FileSet fileSet) { resources.add(fileSet); } @SuppressWarnings("UnusedDeclaration") public Attribute createAttribute() { Attribute attribute = new Attribute(); attributes.add(attribute); return attribute; } public class Attribute { private String key; private String value; public String getKey() { return key; } public String getValue() { return value; } @SuppressWarnings("UnusedDeclaration") public void setKey(String key) { this.key = key; } @SuppressWarnings("UnusedDeclaration") public void setValue(String value) { this.value = value; } } private static class ResourceFileFilter implements FileFilter { private final List includedFiles; public ResourceFileFilter(String[] includedFiles) { this.includedFiles = Arrays.asList(includedFiles); } @Override public boolean accept(File pathname) { return includedFiles.contains(pathname.getName()); } } /** * Safemode can be UNSAFE, SAFE, SERVER, SECURE. * * @param s New value of safe. Case is ignored. Not required-default is SAFE. */ public void setSafemode(String s) { safe = SafeMode.valueOf(s.toUpperCase()); } @SuppressWarnings("UnusedDeclaration") public Extension createPreProcessor() { Extension extension = new Extension(); preProcessors.add(extension); return extension; } @SuppressWarnings("UnusedDeclaration") public Extension createTreeProcessor() { Extension extension = new Extension(); treeProcessors.add(extension); return extension; } @SuppressWarnings("UnusedDeclaration") public Extension createPostProcessor() { Extension extension = new Extension(); postProcessors.add(extension); return extension; } @SuppressWarnings("UnusedDeclaration") public Extension createBlockProcessor() { Extension extension = new Extension(); blockProcessors.add(extension); return extension; } @SuppressWarnings("UnusedDeclaration") public Extension createBlockMacroProcessor() { Extension extension = new Extension(); blockMacroProcessors.add(extension); return extension; } @SuppressWarnings("UnusedDeclaration") public Extension createInlineMacroProcessor() { Extension extension = new Extension(); inlineMacroProcessors.add(extension); return extension; } @SuppressWarnings("UnusedDeclaration") public Extension createIncludeProcessor() { Extension extension = new Extension(); includeProcessors.add(extension); return extension; } public class Extension { private String className; private String blockName; public String getClassName() { return className; } public String getBlockName() { return blockName; } @SuppressWarnings("UnusedDeclaration") public void setClassName(String className) { this.className = className; } @SuppressWarnings("UnusedDeclaration") public void setBlockName(String blockName) { this.blockName = blockName; } } @SuppressWarnings("UnusedDeclaration") public void setGemPaths(String gemPaths) { this.gemPaths = gemPaths; } @SuppressWarnings("UnusedDeclaration") public RubyLibrary createRequire() { RubyLibrary rubyLibrary = new RubyLibrary(); requires.add(rubyLibrary); return rubyLibrary; } public class RubyLibrary { private String name; public String getName() { return name; } @SuppressWarnings("UnusedDeclaration") public void setName(String name) { this.name = name; } } } package com.wylarel.simplebackpacks.listeners; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.ProjectileLaunchEvent; import com.wylarel.simplebackpacks.Main; public class ExampleListener implements Listener { @SuppressWarnings("unused") private Main main; public ExampleListener(Main main) { this.main = main; } @EventHandler public void ProjectileLaunchEvent(ProjectileLaunchEvent e) { } } 0 package com.kosmo88.logistics_erp.util.elastic; import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class esConfig { private String hostName = "www.dulgi.xyz"; // private String hostName = "http://www.dulgi.xyz"; private Integer port = 9200; private String alterHostName = "www.dulgi.xyz"; private Integer alterPort = 9300; @Bean public RestHighLevelClient getClient() { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost(hostName, port, "http"), new HttpHost(alterHostName, alterPort, "http"))); return client; } } 0 package CategoryServiceClient; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.http.*; import org.springframework.stereotype.Controller; import org.springframework.web.client.RestTemplate; import java.util.HashMap; import java.util.Map; @Controller public class CategoryServiceClient { private String baseUrl; private Map cache = new HashMap<>(); @LoadBalanced @Bean RestTemplate restTemplate() { return new RestTemplate(); } @Autowired private RestTemplate restTemplate; public CategoryServiceClient(){ this.baseUrl = "http://" + "category-service" + "/"; } public CategoryServiceClient(String baseUrl){ this.baseUrl = baseUrl; } public Category postCategory(String name) throws ApiException { ResponseEntity response = restTemplate.postForEntity(baseUrl + "categories", name, Category.class); handle(response); return response.getBody(); } public Category[] getCategories() throws ApiException { return getCategories(""); } @HystrixCommand(fallbackMethod = "getCategoriesCache", ignoreExceptions=ApiException.class) public Category[] getCategories(String query) throws ApiException { HttpHeaders headers = new HttpHeaders(); headers.set("query", query); ResponseEntity response = restTemplate.exchange(baseUrl + "categories", HttpMethod.GET, new HttpEntity(headers), Category[].class); handle(response); Category[] categories = response.getBody(); for(Category category : categories) { cache.put(category.getId(), category); } return categories; } @HystrixCommand(fallbackMethod = "getCategoriesByIdCache", ignoreExceptions=ApiException.class) public Category getCategoryById(int id) throws ApiException { ResponseEntity response = restTemplate.getForEntity(baseUrl + "categories/" + id, Category.class); handle(response); Category category = response.getBody(); if(category != null) cache.put(category.getId(), category); return category; } public void deleteCategoryById(int id) throws ApiException { ResponseEntity response = restTemplate.exchange(baseUrl + "categories/" + id, HttpMethod.DELETE, new HttpEntity(new HttpHeaders()), Category.class); handle(response); } private void handle(ResponseEntity response) throws ApiException { if(response.getStatusCode() != HttpStatus.OK) throw new ApiException(response.getStatusCode().value(), response.getStatusCode().getReasonPhrase()); } public Category[] getCategoriesCache(String query) { return cache.values() .stream() .filter(c -> c.getName().contains(query)) .toArray(Category[]::new); } public Category getCategoriesByIdCache(int id) throws ApiException { Category category = cache.getOrDefault((long) id, null); if(category == null) throw new ApiException(HttpStatus.NOT_FOUND.value(), "Category not found"); return category; } } /* * Copyright 2017-2022 original 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 * * https://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 io.micronaut.serde.adhoc.pojo; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.micronaut.serde.annotation.Serdeable; /** * */ @Serdeable public class Account { private String name; private long accountNumber; private double balance; @JsonProperty("isActive") private boolean isActive; private OtherAccount[] favoriteAccounts; @JsonCreator public Account(String name, long accountNumber, double balance, boolean isActive, OtherAccount[] favoriteAccounts) { this.name = name; this.accountNumber = accountNumber; this.balance = balance; this.isActive = isActive; this.favoriteAccounts = favoriteAccounts; } /** * * @return name property */ public String getName() { return name; } /** * * @return account property */ public long getAccountNumber() { return accountNumber; } /** * * @return balance property */ public double getBalance() { return balance; } /** * * @return isActive property */ public boolean isActive() { return isActive; } /** * * @return favoriteAccounts property */ public OtherAccount[] getFavoriteAccounts() { return favoriteAccounts; } /** * * @return String representation of the class */ @Override public String toString() { return "{\n" + String.format("\"name\": \"%s\",\n", name) + String.format("\"accountNumber\": %d,\n", accountNumber) + String.format("\"balance\": %f,\n", balance) + String.format("\"isActive\": %s,\n", isActive) + String.format("\"favoriteAccounts\": [%s,%s,%s]\n", favoriteAccounts[0], favoriteAccounts[1], favoriteAccounts[2]) + "}\n"; } }package com.swime.domain; import lombok.Data; @Data public class StudyAnswerVO { private long sn; private long stdSn; private String userId; private long questionSn; // 중복컬럼 <- StudySurvey에서 가져와서 넣기 private String question; // 중복컬럼 private String answer; } package com.github.jenya705.mcapi.server.application; import com.google.inject.Provider; import com.google.inject.util.Providers; /** * @author Jenya705 */ public abstract class AbstractApplicationModule implements BaseCommon { private final Provider application; public AbstractApplicationModule(ServerApplication application) { this(Providers.of(application)); } public AbstractApplicationModule(Provider provider) { this.application = provider; } @Override public ServerApplication app() { return application.get(); } public Provider appProvider() { return application; } } balarj/rmend-commons package com.brajagopal.rmend.data.beans; import org.apache.commons.collections4.MapUtils; import org.apache.commons.lang3.StringUtils; import java.util.Map; /** * @author */ public class EntitiesBean extends BaseContent { private double relevance; public EntitiesBean() { this(ContentType.ENTITIES); } private EntitiesBean(ContentType _contentType) { super(_contentType); } @Override public void process(Map _value) { this.type = MapUtils.getString(_value, "_type", MapUtils.getString(_value, "type", null)); this.forEndUserDisplay = MapUtils.getBoolean(_value, "forenduserdisplay", MapUtils.getBoolean(_value, "forEndUserDisplay", false)); this.relevance = MapUtils.getDouble(_value, "relevance", 0.0); this.name = MapUtils.getString(_value, "name", null); this.name = ((name.length() > 50)?StringUtils.substringBeforeLast(StringUtils.left(name, 50), "_"):this.name); } @Override public BaseContent getInstance() { return new EntitiesBean(); } @Override public String toString() { return "EntitiesBean {" + "contentType=" + getContentType() + ", type='" + getType() + '\'' + ", forEndUserDisplay=" + isForEndUserDisplay() + ", name='" + getName() + '\'' + ", score=" + getScore() + '}'; } public double getRelevance() { return relevance; } @Override public double getScore() { return getRelevance(); } } package cn.edu.gzmu.authserver.model.constant; /** * . * * @author EchoCow * @date 2020/1/2 下午8:07 */ public interface AuthConstant { /** * 客户端信息. */ String CLIENT_DETAILS = "clientDetails"; /** * 学期. */ String SEMESTER = "semester"; /** * 学生. */ String STUDENT = "student"; /** * 教师. */ String TEACHER = "teacher"; /** * 数据. */ String SYS_DATA = "sysData"; /** * 资源. */ String SYS_RES = "sysRes"; /** * 角色. */ String SYS_ROLE = "sysRole"; /** * 用户. */ String SYS_USER = "sysUser"; } 1-10 /******************************************************************************* * Copyright (C) 2005-2012 Alfresco Software Limited. * * This file is part of the Alfresco Mobile SDK. * * 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.api.model.impl; import java.util.Map; import org.alfresco.mobile.android.api.constants.CloudConstant; import org.alfresco.mobile.android.api.model.Tag; import org.apache.chemistry.opencmis.commons.impl.JSONConverter; /** * TagImpl. * * @author */ public class TagImpl implements Tag { private static final long serialVersionUID = 1L; /** Unique identifier to a specific tag. */ private String identifier; /** Value of the tag. */ private String value; /** * Instantiates a new tag impl. */ public TagImpl() { } /** * Instantiates a new tag impl. * * @param value the value of the tag */ public TagImpl (String value) { this.identifier = null; if (value.startsWith("\"") && value.endsWith("\"")){ this.value = value.replaceAll("\"", ""); } else { this.value = value; } } /** * Parse Json Response from Alfresco Public API to create a Site. * * @param jo the jo * @return Tag object that contains essential information about it. */ public static Tag parsePublicAPIJson(Map jo) { TagImpl tagItem = new TagImpl(); tagItem.identifier = JSONConverter.getString(jo, CloudConstant.ID_VALUE); tagItem.value = JSONConverter.getString(jo, CloudConstant.TAG_VALUE); return tagItem; } /** {@inheritDoc} */ public String getIdentifier() { return identifier; } /** {@inheritDoc} */ public String getValue() { return value; } } package it.polimi.eftaios.controller.socket; import java.io.IOException; import java.io.Serializable; import java.net.Socket; /** * Consente a un client di connettersi a un server remoto dato il suo ip e la * sua porta. * * @author * */ public class SocketClient implements Serializable { private static final long serialVersionUID = 1L; private String ip; private int port; private transient Socket socket; private SocketCommunicator server; public SocketCommunicator getServer() { return server; } public SocketClient(String ip, int port) { this.ip = ip; this.port = port; } public void startClient() { try { socket = new Socket(ip, port); System.out.println("Connection established"); } catch (IOException e) { throw new AssertionError("Fail to connect server", e); } server = new SocketCommunicator(socket); } public void closeClient() { server.close(); } } /* * Copyright 2016 LinkedIn Corp. * * 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.linkedin.drelephant.exceptions.azkaban; import com.linkedin.drelephant.exceptions.JobState; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; public class AzkabanJobLogAnalyzerTest { private String succeededAzkabanJobLog = "24-06-2016 03:12:53 PDT extractCrawlCompanyIndustryClassificationFlow_extractionFinalizer INFO - Starting job sample_sample at 1466763173873\n" + "24-06-2016 03:12:53 PDT extractCrawlCompanyIndustryClassificationFlow_extractionFinalizer INFO - job JVM args: -Dazkaban.flowid=sampleFlow -Dazkaban.execid=557260 -Dazkaban.jobid=sample_jobr\n" + "24-06-2016 03:12:55 PDT extractCrawlCompanyIndustryClassificationFlow_extractionFinalizer INFO - Finishing job sample_job attempt: 0 at 1466763175040 with status SUCCEEDED"; private String killedAzkabanJobLog = "28-06-2016 16:58:20 PDT feature-exploration_create-index-map INFO - Starting job sample at 1467158300703\n" + "28-06-2016 17:58:05 PDT feature-exploration_create-index-map ERROR - Kill has been called.\n" + "28-06-2016 17:58:05 PDT feature-exploration_create-index-map INFO - 16/06/29 00:58:05 INFO util.Utils: Shutdown hook called\n" + "28-06-2016 17:58:06 PDT feature-exploration_create-index-map ERROR - caught error running the job\n" + "28-06-2016 17:58:06 PDT feature-exploration_create-index-map INFO - Token service: :8032\n" + "28-06-2016 17:58:06 PDT feature-exploration_create-index-map INFO - Cancelling mr job tracker token \n" + "28-06-2016 17:58:06 PDT feature-exploration_create-index-map ERROR - Job run failed!\n" + "28-06-2016 17:58:06 PDT feature-exploration_create-index-map ERROR - java.lang.RuntimeException: azkaban.jobExecutor.utils.process.ProcessFailureException cause: java.lang.RuntimeException: azkaban.jobExecutor.utils.process.ProcessFailureException\n" + "28-06-2016 17:58:06 PDT feature-exploration_create-index-map INFO - Finishing job feature-exploration_create-index-map attempt: 0 at 1467161886022 with status KILLED\n" + "28-06-2016 17:58:06 PDT feature-exploration_create-index-map INFO - applicationIds to kill: [application_1466048666726_642278]\n" + "28-06-2016 17:58:06 PDT feature-exploration_create-index-map INFO - start klling application: application_1466048666726_642278\n" + "28-06-2016 17:58:06 PDT feature-exploration_create-index-map INFO - successfully killed application: application_1466048666726_642278"; private String mrLevelFailedAzkabanJobLog = "24-06-2016 03:12:19 PDT help_center_sessions INFO - Starting job help_center_sessions at 1466763139993\n" + "24-06-2016 03:12:25 PDT help_center_sessions INFO - INFO Kind: HDFS_DELEGATION_TOKEN, Service: sample-localhostnn01.grid.linkedin.com:9000, Ident: (HDFS_DELEGATION_TOKEN token for username)\n" + "24-06-2016 03:12:26 PDT help_center_sessions INFO - INFO Submitted application application_1466048666726_410150\n" + "24-06-2016 03:12:26 PDT help_center_sessions INFO - INFO Running job: job_1466048666726_410150\n" + "24-06-2016 03:12:33 PDT help_center_sessions INFO - INFO Job job_1466048666726_410150 running in uber mode : false\n" + "24-06-2016 03:12:40 PDT help_center_sessions INFO - Error: java.io.FileNotFoundException: Path is not a file: /data/databases/sample/Sample/1466675602538-PT-472724050\n" + "24-06-2016 03:12:40 PDT help_center_sessions INFO - \tat org.apache.hadoop.hdfs.server.namenode.INodeFile.valueOf(INodeFile.java:70)\n" + "24-06-2016 03:12:40 PDT help_center_sessions INFO - \tat org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1671)\n" + "24-06-2016 03:12:40 PDT help_center_sessions INFO - \tat org.apache.hadoop.ipc.Server$Handler.run(Server.java:2038\n" + "24-06-2016 03:13:00 PDT help_center_sessions ERROR - Job run failed!\n" + "24-06-2016 03:13:00 PDT help_center_sessions ERROR - java.lang.RuntimeException: azkaban.jobExecutor.utils.process.ProcessFailureException cause: java.lang.RuntimeException: azkaban.jobExecutor.utils.process.ProcessFailureException\n" + "24-06-2016 03:13:00 PDT help_center_sessions INFO - Finishing job help_center_sessions attempt: 0 at 1466763180242 with status FAILED"; private String scriptLevelFailedAzkabanJobLog="28-06-2016 16:23:10 PDT job_search_trigger INFO - Starting job job_search_trigger at 1467156190329\n" + "28-06-2016 16:23:12 PDT job_search_trigger INFO - INFO Last attempt: false\n" + "28-06-2016 16:23:12 PDT job_search_trigger INFO - Exception in thread \"main\" java.lang.reflect.UndeclaredThrowableException\n" + "28-06-2016 16:23:12 PDT job_search_trigger INFO - \tat org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1686)\n" + "28-06-2016 16:23:12 PDT job_search_trigger INFO - \t... 3 more\n" + "28-06-2016 16:23:12 PDT job_search_trigger INFO - Caused by: java.lang.RuntimeException: Backfill requires start and end date\n" + "28-06-2016 16:23:12 PDT job_search_trigger INFO - \tat com.linkedin.metrics.feeder.TriggerJob.generateDaily(TriggerJob.java:143)\n" + "28-06-2016 16:23:12 PDT job_search_trigger INFO - \tat com.linkedin.metrics.feeder.TriggerJob.run(TriggerJob.java:135)\n" + "28-06-2016 16:23:12 PDT job_search_trigger INFO - \t... 14 more\n" + "28-06-2016 16:23:12 PDT job_search_trigger INFO - Process completed unsuccessfully in 1 seconds.\n" + "28-06-2016 16:23:12 PDT job_search_trigger ERROR - Job run failed!\n" + "28-06-2016 16:23:12 PDT job_search_trigger ERROR - java.lang.RuntimeException: azkaban.jobExecutor.utils.process.ProcessFailureException cause: java.lang.RuntimeException: azkaban.jobExecutor.utils.process.ProcessFailureException\n" + "28-06-2016 16:23:12 PDT job_search_trigger INFO - Finishing job job_search_trigger attempt: 0 at 1467156192215 with status FAILED"; private String azkabanLevelFailedAzkabanJobLog = "28-06-2016 13:45:27 PDT feature-exploration_create-index-map INFO - Starting job feature-exploration_create-index-map at 1467146727699\n" + "28-06-2016 13:45:27 PDT feature-exploration_create-index-map INFO - job JVM args: -Dazkaban.flowid=feature-exploration -Dazkaban.execid=593197 -Dazkaban.jobid=feature-exploration_create-index-map\n" + "28-06-2016 13:45:27 PDT feature-exploration_create-index-map INFO - Building spark job executor. \n" + "28-06-2016 13:45:27 PDT feature-exploration_create-index-map ERROR - Failed to build job executor for job feature-exploration_create-index-mapCould not find variable substitution for variable(s) [global.jvm.args->user.to.proxy]\n" + "28-06-2016 13:45:27 PDT feature-exploration_create-index-map ERROR - Failed to build job type\n" + "azkaban.jobtype.JobTypeManagerException: Failed to build job executor for job feature-exploration_create-index-map\n" + "28-06-2016 13:45:27 PDT feature-exploration_create-index-map ERROR - Job run failed preparing the job.\n" + "28-06-2016 13:45:27 PDT feature-exploration_create-index-map INFO - Finishing job feature-exploration_create-index-map attempt: 0 at 1467146727702 with status FAILED"; private AzkabanJobLogAnalyzer analyzedSucceededLog; private AzkabanJobLogAnalyzer analyzedKilledLog; private AzkabanJobLogAnalyzer analyzedMRLevelFailedLog; private AzkabanJobLogAnalyzer analyzedScriptLevelFailedLog; private AzkabanJobLogAnalyzer analyzedAzkabanLevelFailedLog; public AzkabanJobLogAnalyzerTest(){ analyzedSucceededLog = new AzkabanJobLogAnalyzer(succeededAzkabanJobLog); analyzedKilledLog = new AzkabanJobLogAnalyzer(killedAzkabanJobLog); analyzedMRLevelFailedLog = new AzkabanJobLogAnalyzer(mrLevelFailedAzkabanJobLog); analyzedScriptLevelFailedLog = new AzkabanJobLogAnalyzer(scriptLevelFailedAzkabanJobLog); analyzedAzkabanLevelFailedLog = new AzkabanJobLogAnalyzer(azkabanLevelFailedAzkabanJobLog); } @Test public void getStateTest(){ assertTrue(analyzedSucceededLog.getState() == JobState.SUCCEEDED); assertTrue(analyzedKilledLog.getState() == JobState.KILLED); assertTrue(analyzedMRLevelFailedLog.getState() == JobState.MRFAIL); assertTrue(analyzedScriptLevelFailedLog.getState() == JobState.SCRIPTFAIL); assertTrue(analyzedAzkabanLevelFailedLog.getState() == JobState.SCHEDULERFAIL); } @Test public void getSubEventsTest(){ assertTrue("Succeeded sub events test failed",analyzedSucceededLog.getSubEvents().isEmpty()); assertTrue("Script level failed sub events test failed",analyzedScriptLevelFailedLog.getSubEvents().isEmpty()); assertTrue("Azkaban level failed sub events test failed",analyzedAzkabanLevelFailedLog.getSubEvents().isEmpty()); assertTrue(analyzedMRLevelFailedLog.getSubEvents().size() == 1); assertTrue(analyzedMRLevelFailedLog.getSubEvents().iterator().next().equals("job_1466048666726_410150")); assertTrue("Killed sub events test failed",analyzedKilledLog.getSubEvents().isEmpty()); } @Test public void getExceptionsTest(){ assertTrue(analyzedSucceededLog.getException() == null); assertTrue(analyzedKilledLog.getException() == null); } }0 package co.net.parking.entities; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the alianzas_parqueaderos database table. * */ @Entity @Table(name = "alianzas_parqueaderos") @NamedQuery(name = "AlianzasParqueadero.findAll", query = "SELECT a FROM AlianzasParqueadero a Where a.codPark=:codPark and a.estado = 1") public class AlianzasParqueadero implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "AlianzaParkId") private short alianzaParkId; @Column(name = "cod_park") private String codPark; private short alianzaId; private short estado; private String nombreAlianza; private String urlAlianza; public String getUrlAlianza() { return urlAlianza; } public void setUrlAlianza(String urlAlianza) { this.urlAlianza = urlAlianza; } public AlianzasParqueadero() { } public short getAlianzaId() { return this.alianzaId; } public void setAlianzaId(short alianzaId) { this.alianzaId = alianzaId; } public short getAlianzaParkId() { return this.alianzaParkId; } public void setAlianzaParkId(short alianzaParkId) { this.alianzaParkId = alianzaParkId; } public String getCodPark() { return this.codPark; } public void setCodPark(String codPark) { this.codPark = codPark; } public short getEstado() { return this.estado; } public void setEstado(short estado) { this.estado = estado; } public String getNombreAlianza() { return this.nombreAlianza; } public void setNombreAlianza(String nombreAlianza) { this.nombreAlianza = nombreAlianza; } }package com.zhangyu.raft.node; /** * The methods from user to post, delete, get, update data */ public interface Node { public String get(String key); public boolean add(String key, String value); public boolean del(String key); public boolean update(String key, String value); public void start(); } 0 package figurefix.prac.test.report; import java.util.Iterator; import figurefix.prac.util.DataMap; import figurefix.prac.util.DataSet; public class SampleList implements Iterator { private String title = null; private int size = 0; private String[] dsname = null; public SampleList(String title, int size, String ... dsname) { this.title = title; this.size = size; this.dsname = dsname; } @Override public boolean hasNext() { return size>0; } @Override public DataMap next() { if(size>0) { size--; DataSet m = new DataSet(); for(int i=0; ij1046697411/AndroidCommonFramework package org.jzl.android.recyclerview.manager.layout; import androidx.annotation.LayoutRes; import androidx.recyclerview.widget.RecyclerView; import org.jzl.android.recyclerview.core.factory.ItemViewFactory; import org.jzl.android.recyclerview.core.vh.DataBinder; import org.jzl.android.recyclerview.manager.Manager; public interface EmptyLayoutManager extends Manager { int TYPE_EMPTY_LAYOUT = -1; T getEmptyData(); EmptyLayoutManager setEmptyData(T data); int getItemType(); boolean isEnable(); EmptyLayoutManager createItemView(ItemViewFactory itemViewFactory); EmptyLayoutManager createItemView(@LayoutRes int layoutResId); EmptyLayoutManager dataBinding(DataBinder dataBinder); EmptyLayoutManager enable(); EmptyLayoutManager disable(); EmptyLayoutManager setEmptyItemType(int itemType); EmptyLayoutManager addEmptyLayoutCallback(EmptyLayoutCallback emptyLayoutCallback); EmptyLayoutManager removeEmptyLayoutCallback(EmptyLayoutCallback emptyLayoutCallback); interface EmptyLayoutCallback { void onEmptyLayoutStateChanged(boolean isEmpty); } } /** * Copyright 2014 SAP AG * * 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.spotter.eclipse.ui.providers; import org.eclipse.swt.graphics.Image; import org.spotter.eclipse.ui.Activator; import org.spotter.eclipse.ui.model.ExtensionItem; import org.spotter.shared.hierarchy.model.XPerformanceProblem; import org.spotter.shared.result.model.ResultsContainer; import org.spotter.shared.result.model.SpotterResult; /** * An image provider for extension items displayed in the results view. * * @author * */ public class ResultExtensionsImageProvider extends SpotterExtensionsImageProvider { private static final Image IMG_NO_LOOKUP = Activator.getImage("icons/exclamation.png"); private static final Image IMG_DETECTED = Activator.getImage("icons/flag-red.png"); private static final Image IMG_NOT_DETECTED = Activator.getImage("icons/flag-green.png"); private ResultsContainer resultsContainer; /** * Set the results container. * * @param resultsContainer * The results container to set */ public void setResultsContainer(ResultsContainer resultsContainer) { this.resultsContainer = resultsContainer; } @Override public Image getImage(ExtensionItem item) { Object xmlModel = item.getModelWrapper().getXMLModel(); if (resultsContainer == null || !(xmlModel instanceof XPerformanceProblem)) { return null; } XPerformanceProblem problem = (XPerformanceProblem) xmlModel; String id = problem.getUniqueId(); SpotterResult spotterResult = resultsContainer.getResultsMap().get(id); if (spotterResult == null) { return IMG_NO_LOOKUP; } else { return spotterResult.isDetected() ? IMG_DETECTED : IMG_NOT_DETECTED; } } } protocols/snmp/ctl/src/main/java/org/onosproject/snmp/ctl/DefaultSnmpv3Device.java /* * Copyright 2021-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.onosproject.snmp.ctl; import com.google.common.base.MoreObjects; import org.apache.commons.lang.StringUtils; import org.onosproject.snmp.Snmpv3Device; import org.onosproject.snmp.SnmpDeviceConfig; import java.util.Objects; import static com.google.common.base.Preconditions.checkState; /** * This is a logical representation of actual SNMPv3 device. * carrying all the necessary information to connect and execute * SNMPv3 operations. */ public class DefaultSnmpv3Device extends DefaultSnmpDevice implements Snmpv3Device { private final String securityLevel; private final String securityName; private final String authProtocol; private final String authPassword; private final String privProtocol; private final String privPassword; private final String contextName; /** * Create a new DefaultSnmpv3Device. * * @param config snmp device config */ public DefaultSnmpv3Device(SnmpDeviceConfig config) { super(config); checkState(!StringUtils.isEmpty(config.securityLevel()), "SNMPv3 security level cannot be null or empty"); checkState(!StringUtils.isEmpty(config.securityName()), "SNMPv3 security name cannot be null or empty"); this.securityLevel = config.securityLevel(); this.securityName = config.securityName(); this.authProtocol = config.authProtocol(); this.authPassword = config.authPassword(); this.privProtocol = config.privacyProtocol(); this.privPassword = config.privacyPassword(); this.contextName = config.contextName(); } /** * Retrieves the security name of SNMPv3 device. * * @return security name */ @Override public String getSecurityName() { return securityName; } /** * Retrieves the security level of SNMPv3 device. * * @return security level */ @Override public String getSecurityLevel() { return securityLevel; } /** * Retrieves the authentication protocol of SNMPv3 device. * * @return authentication protocol */ @Override public String getAuthProtocol() { return authProtocol; } /** * Retrieves the authentication password of SNMPv3 device. * * @return authentication password */ @Override public String getAuthPassword() { return authPassword; } /** * Retrieves the privacy protocol of SNMPv3 device. * * @return privacy protocol */ @Override public String getPrivProtocol() { return privProtocol; } /** * Retrieves the privacy password of SNMPv3 device. * * @return privacy password */ @Override public String getPrivPassword() { return privPassword; } /** * Retrieves the context name of SNMPv3 device. * * @return context name */ @Override public String getContextName() { return contextName; } /** * Convert the Snmpv3 device to string. */ @Override public String toString() { return MoreObjects.toStringHelper(getClass()) .add("hostName", getSnmpHost()) .add("securityLevel", securityLevel) .add("securityName", securityName) .add("authProtocol", authProtocol) .add("authPassword", authPassword) .add("privProtocol", privProtocol) .add("privPassword", privPassword) .add("contextName", contextName) .toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } DefaultSnmpv3Device otherv3Device = (DefaultSnmpv3Device) obj; return Objects.equals(securityLevel, otherv3Device.securityLevel) && Objects.equals(securityName, otherv3Device.securityName) && Objects.equals(getSnmpHost(), otherv3Device.getSnmpHost()); } @Override public int hashCode() { return Objects.hash(securityLevel, securityName, getSnmpHost()); } } /** * This file is part of choco-solver, http://choco-solver.org/ * * Copyright (c) 2017, IMT Atlantique. All rights reserved. * * Licensed under the BSD 4-clause license. * See LICENSE file in the project root for full license information. */ package org.chocosolver.solver; /** * An interface to provide an identity to object, using a positive int to caracterize the object. * It allows definition of , 2 147 483 647 different objects. *
* * @author * @since 14/12/11 */ public interface Identity { int getId(); } tanmaylaud/Leet-Coding-Challenge1-10 class Solution { public boolean isHappy(int n) { if (n <= 0) return false; if (n == 1) return true; int fastSum = sumOfSquares(sumOfSquares(n)); int slowSum = sumOfSquares(n); do { fastSum = sumOfSquares(sumOfSquares(fastSum)); slowSum = sumOfSquares(slowSum); if (slowSum == 1 || fastSum == 1) return true; } while (slowSum != fastSum); return false; } public int sumOfSquares(int n) { int temp = n; int sum = 0; while (temp != 0) { sum += (temp % 10) * (temp % 10); temp = temp / 10; } return sum; } }package com.wrq.vo; import lombok.Data; import java.util.Date; /** * Created by wangqian on 2019/5/1. */ @Data public class ScoreListVo { private Integer id; private String title; private Integer shareId; private Integer integral; private String createTime; private String fileNewName; private String ownerName; private String fileTypeImg; } package com.v0rt3x.genericrecyclerview.util; import android.graphics.Color; import android.graphics.PorterDuff; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.v0rt3x.genericrecyclerview.R; import com.v0rt3x.simplerecyclerview.BaseViewHolder; import com.v0rt3x.simplerecyclerview.Constants; import com.v0rt3x.simplerecyclerview.OnItemClickListener; import com.v0rt3x.simplerecyclerview.RecyclerViewViewHolderAdapter; /** * Created by on 9/1/16. * View holder for the Base Tile. It provides a method to populate the tile based on the supplied Base Tile. */ public class ExampleViewHolder extends BaseViewHolder { private ImageView iconBGView, iconImageView, actionImageView; private TextView iconNumberTextView, titleTextView, messageTextView; ExampleViewHolder() { super(); } ExampleViewHolder(Constants.LayoutType layoutType) { super(layoutType); } @Override public RecyclerViewViewHolderAdapter createViewHolder(ViewGroup viewGroup, OnItemClickListener listener) { View view = createItemView(viewGroup); setSpringListener(view); iconBGView = (ImageView) view.findViewById(R.id.view_icon_bg); iconImageView = (ImageView) view.findViewById(R.id.image_icon); iconNumberTextView = (TextView) view.findViewById(R.id.text_icon_number); titleTextView = (TextView) view.findViewById(R.id.text_title); messageTextView = (TextView) view.findViewById(R.id.text_message); actionImageView = (ImageView) view.findViewById(R.id.image_action); return new RecyclerViewViewHolderAdapter<>(this, view, listener); } /** * Populates the tile based on the supplied Base Tile. * @param mData - the data model used to populate the item view */ public void configureViewHolder(Example mData) { this.mData = mData; iconBGView.setColorFilter(Color.parseColor(mData.getImageBackgroundColor()), PorterDuff.Mode.SRC_ATOP); iconImageView.setImageResource(mData.getImage()); String numberHits = mData.getNumberHits(); if (numberHits != null && !numberHits.isEmpty()) { iconNumberTextView.setVisibility(View.VISIBLE); iconNumberTextView.setText(mData.getNumberHits()); } titleTextView.setText(mData.getTitle()); messageTextView.setText(mData.getMessage()); int actionImage = mData.getActionImage(); if (actionImageView != null && actionImage != 0) { actionImageView.setImageResource(mData.getActionImage()); actionImageView.setVisibility(View.VISIBLE); } } @Override public int getLayoutId() { switch (layoutType) { case LINEAR: return R.layout.card_example; case GRID: case STAGGERED: return R.layout.card_grid_example; default: return R.layout.card_example; } } } package sg.atom.corex.entity; import com.simsilica.es.EntityId; /** * Simple Entity interface * * @author cuong.nguyen */ public interface ComposableEntity { EntityId getId(); long getIid(); void compose(Object... components); void persist(); } package br.com.zupacademy.rodrigo.proposta.cartao; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import br.com.zupacademy.rodrigo.proposta.cartao.biometria.Biometria; @Entity public class Cartao { @Id private String id; private String emitidoEm; private String titular; private BigDecimal limite; private String idProposta; @OneToMany(cascade = CascadeType.ALL) private List bloqueios = new ArrayList(); @OneToMany(cascade = CascadeType.ALL) private List avisos = new ArrayList(); @OneToMany(cascade = CascadeType.ALL) private List carteiras = new ArrayList(); @OneToOne(cascade = CascadeType.ALL) private Renegociacao renegociacao; @OneToOne(cascade = CascadeType.ALL) private Vencimento vencimento; @Enumerated(EnumType.STRING) private EstadoCartao estadoCartao; @OneToMany private List biometrias = new ArrayList<>(); @Deprecated public Cartao() { } public Cartao(String id, String emitidoEm, String titular, BigDecimal limite, String idProposta, List bloqueios, List avisos, List carteiras, Renegociacao renegociacao, Vencimento vencimento) { this.id = id; this.emitidoEm = emitidoEm; this.titular = titular; this.limite = limite; this.idProposta = idProposta; this.bloqueios = bloqueios; this.avisos = avisos; this.carteiras = carteiras; this.renegociacao = renegociacao; this.vencimento = vencimento; this.estadoCartao = EstadoCartao.NAO_BLOQUEADO; } public String getId() { return id; } public String getEmitidoEm() { return emitidoEm; } public String getTitular() { return titular; } public BigDecimal getLimite() { return limite; } public String getIdProposta() { return idProposta; } public List getBloqueios() { return bloqueios; } public List getAvisos() { return avisos; } public List getCarteiras() { return carteiras; } public Renegociacao getRenegociacao() { return renegociacao; } public Vencimento getVencimento() { return vencimento; } public void addBiometria(Biometria biometria){ this.biometrias.add(biometria); } public void addAviso(Aviso aviso){ this.avisos.add(aviso); } public void addBloqueio(Bloqueio bloqueio){ this.bloqueios.add(bloqueio); } public boolean isBloqueado() { if(this.estadoCartao == EstadoCartao.BLOQUEADO) { return true; } return false; } public EstadoCartao getEstadoCartao() { return estadoCartao; } public void setEstadoCartao(EstadoCartao estadoCartao) { this.estadoCartao = estadoCartao; } } 0 package person.alexp.halva.examples; import io.soabase.halva.caseclass.CaseClass; import io.soabase.halva.container.TypeContainer; /** * Created by Alex on 6/28/2016. */ @TypeContainer(unsuffix="_" , renameContained = true) public interface LensExampleTypes_ { @CaseClass(unsuffix = "_") interface Point_ { double x(); double y(); } @CaseClass(unsuffix = "_") interface Color_ { byte r(); byte g(); byte b(); } @CaseClass(unsuffix = "_") interface Turtle_ { Point_ position(); double heading(); Color_ color(); } } YiLian/src/main/java/com/yilian/mall/ui/mvp/model/LocationModelImpl.java package com.yilian.mall.ui.mvp.model; import android.content.Context; import com.yilian.mall.utils.PreferenceUtils; import com.yilian.mylibrary.Constants; import com.yilian.networkingmodule.retrofitutil.RetrofitUtils3; import rx.Observer; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * @author Created by on 2018/1/16. */ public class LocationModelImpl implements ILocationModel { @SuppressWarnings("unchecked") @Override public Subscription getAddressList(Context context, Observer observer) { return RetrofitUtils3.getRetrofitService(context).getRegion("getRegion") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(observer); } @SuppressWarnings("unchecked") @Override public Subscription getLocation(Context context, Observer observer) { return RetrofitUtils3.getRetrofitService(context) .getLocation("location/setLocation", PreferenceUtils.readStrConfig(Constants.SELF_LOCATION_LAT, context) , PreferenceUtils.readStrConfig(Constants.SELF_LOCATION_LNG, context)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(observer) ; } } 0 package br.com.mercadoLivre.controller.Mailer; import br.com.mercadoLivre.model.PerguntaUsuarioProduto; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.validation.Valid; import javax.validation.constraints.NotNull; @Component public class CarteiroManager { @Autowired private CarteiroFake carteiro; public void novaPergunta ( @NotNull @Valid PerguntaUsuarioProduto pergunta ) { var to = pergunta.getUsuario().getLogin(); carteiro.envia("html" , "question" , "" , to ); } } package com.sha.serverside.service; import com.sha.serverside.model.Module; import com.sha.serverside.repository.ModuleRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service @Transactional public class ModuleServiceImpl implements ModuleService { @Autowired private ModuleRepository moduleRepository; @Override public Module updateModule(Module module) { return moduleRepository.save(module); } @Override public void deleteModule(Long moduleId) { moduleRepository.deleteById(moduleId); } @Override public List findAllModules() { return moduleRepository.findAll(); } @Override public List findAllModulesOfCourse(Long courseId) { return moduleRepository.findByCourseId(courseId); } } /* * Copyright 2017 The Mifos Initiative. * * 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 io.mifos.accounting.api.v1; @SuppressWarnings({"unused"}) public interface EventConstants { String DESTINATION = "accounting-v1"; String SELECTOR_NAME = "action"; // system events String INITIALIZE = "initialize"; String SELECTOR_INITIALIZE = SELECTOR_NAME + " = '" + INITIALIZE + "'"; // ledger events String POST_LEDGER = "post-ledger"; String PUT_LEDGER = "put-ledger"; String DELETE_LEDGER = "delete-ledger"; String POST_SUB_LEDGER = "post-sub-ledger"; String SELECTOR_POST_LEDGER = SELECTOR_NAME + " = '" + POST_LEDGER + "'"; String SELECTOR_PUT_LEDGER = SELECTOR_NAME + " = '" + PUT_LEDGER + "'"; String SELECTOR_DELETE_LEDGER = SELECTOR_NAME + " = '" + DELETE_LEDGER + "'"; String SELECTOR_POST_SUB_LEDGER = SELECTOR_NAME + " = '" + POST_SUB_LEDGER + "'"; // account events String POST_ACCOUNT = "post-account"; String PUT_ACCOUNT = "put-account"; String DELETE_ACCOUNT = "delete-account"; String LOCK_ACCOUNT = "lock-account"; String UNLOCK_ACCOUNT = "unlock-account"; String CLOSE_ACCOUNT = "close-account"; String REOPEN_ACCOUNT = "reopen-account"; String SELECTOR_POST_ACCOUNT = SELECTOR_NAME + " = '" + POST_ACCOUNT + "'"; String SELECTOR_PUT_ACCOUNT = SELECTOR_NAME + " = '" + PUT_ACCOUNT + "'"; String SELECTOR_DELETE_ACCOUNT = SELECTOR_NAME + " = '" + DELETE_ACCOUNT + "'"; String SELECTOR_LOCK_ACCOUNT = SELECTOR_NAME + " = '" + LOCK_ACCOUNT + "'"; String SELECTOR_UNLOCK_ACCOUNT = SELECTOR_NAME + " = '" + UNLOCK_ACCOUNT + "'"; String SELECTOR_CLOSE_ACCOUNT = SELECTOR_NAME + " = '" + CLOSE_ACCOUNT + "'"; String SELECTOR_REOPEN_ACCOUNT = SELECTOR_NAME + " = '" + REOPEN_ACCOUNT + "'"; // journal events String POST_JOURNAL_ENTRY = "post-journal-entry"; String RELEASE_JOURNAL_ENTRY = "release-journal-entry"; String SELECTOR_POST_JOURNAL_ENTRY = SELECTOR_NAME + " = '" + POST_JOURNAL_ENTRY + "'"; String SELECTOR_RELEASE_JOURNAL_ENTRY = SELECTOR_NAME + " = '" + RELEASE_JOURNAL_ENTRY + "'"; String POST_TX_TYPE = "post-tx-type"; String SELECTOR_POST_TX_TYPE = SELECTOR_NAME + " = '" + POST_TX_TYPE + "'"; String PUT_TX_TYPE = "put-tx-type"; String SELECTOR_PUT_TX_TYPE = SELECTOR_NAME + " = '" + PUT_TX_TYPE + "'"; } architect/code/Full-text-Search/solr/src/main/java/com/kkb/solr/controller/IndexController.java0 package com.kkb.solr.controller; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.kkb.solr.service.IndexService; import javax.annotation.Resource; @Controller public class IndexController { @Resource private IndexService service; @RequestMapping(value="indexImport",produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8") @ResponseBody public String indexImport() throws Exception { return service.importIndex(); } } arnosthavelka/lambdas-poc0 package com.github.aha.poc.lambdas.factory; import java.util.function.Supplier; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FactoryPatternDemo { /** Logger. */ private static final Logger LOG = LoggerFactory.getLogger(FactoryPatternDemo.class); public static void main(String[] args) { Supplier shapeFactory = MathFactory::new; Integer addValue = shapeFactory.get().getShape(MathEnum.ADD).calc(1, 2, 3); LOG.info("1 + 2 + 3 = {}", addValue); Integer multiplyValue = shapeFactory.get().getShape(MathEnum.MULTIPLY).calc(2, 3); LOG.info("2 * 3 = {}", multiplyValue); } }src/main/java/WayofTime/bloodmagic/client/render/entity/RenderCorruptedSpider.java package WayofTime.bloodmagic.client.render.entity; import WayofTime.bloodmagic.client.render.entity.layer.LayerCorruptedSpiderEyes; import WayofTime.bloodmagic.client.render.entity.layer.LayerWill; import WayofTime.bloodmagic.client.render.model.ModelCorruptedSpider; import WayofTime.bloodmagic.entity.mob.EntityCorruptedSpider; import net.minecraft.client.model.ModelSpider; import net.minecraft.client.renderer.entity.RenderLiving; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class RenderCorruptedSpider extends RenderLiving { private static final ResourceLocation SPIDER_TEXTURES = new ResourceLocation("textures/entity/spider/spider.png"); public RenderCorruptedSpider(RenderManager renderManagerIn) { super(renderManagerIn, new ModelSpider(), 1.0F); this.addLayer(new LayerCorruptedSpiderEyes(this)); this.addLayer(new LayerWill<>(this, new ModelCorruptedSpider(1.1f))); } protected float getDeathMaxRotation(EntityCorruptedSpider entityLivingBaseIn) { return 180.0F; } /** * Returns the location of an entity's texture. Doesn't seem to be called * unless you call Render.bindEntityTexture. */ protected ResourceLocation getEntityTexture(EntityCorruptedSpider entity) { return SPIDER_TEXTURES; } }package com.salesmanager.shop.model.catalog.category; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class ReadableCategory extends CategoryEntity { /** * */ private static final long serialVersionUID = 1L; private CategoryDescription description;//one category based on language private int productCount; private String store; private List children = new ArrayList<>() { private static final long serialVersionUID = 2L; @Override public boolean add(ReadableCategory x) { int index = Collections.binarySearch(this, x, new Comparator<>() { public int compare(ReadableCategory u1, ReadableCategory u2) { return u1.getSortOrder()>u2.getSortOrder()?1:-1; } }); if (index < 0) index = ~index; super.add(index, x); return true; } }; public void setDescription(CategoryDescription description) { this.description = description; } public CategoryDescription getDescription() { return description; } public int getProductCount() { return productCount; } public void setProductCount(int productCount) { this.productCount = productCount; } public List getChildren() { return children; } public void setChildren(List children) { this.children = children; } public String getStore() { return store; } public void setStore(String store) { this.store = store; } } 0 /* * The MIT License * * Copyright 2020 . * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.logging.Level; import java.util.logging.Logger; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLServerSocket; public class SSLSocketServer { final Object lock = new Object(); SSLServerSocketFactory serverSocketFactory; String[] protocols; String[] ciphers; SSLServerSocket serverSocket; Thread serverThread; String host = "localhost"; int port = 0; boolean shutdownOutput = false; public SSLSocketServer( SSLServerSocketFactory serverSocketFactory, String[] protocols, String[] ciphers) { this.ciphers = ciphers; this.protocols = protocols; this.serverSocketFactory = serverSocketFactory; } public void start() throws IOException { synchronized (lock) { if (serverSocket == null) { serverSocket = (SSLServerSocket) serverSocketFactory.createServerSocket(); serverSocket.setEnabledProtocols(protocols); serverSocket.setEnabledCipherSuites(ciphers); InetSocketAddress serverAddress = new InetSocketAddress(host, port); serverSocket.bind(serverAddress); port = serverSocket.getLocalPort(); Runnable runnable = new Runnable() { @Override public void run() { try { serverLoop(); } catch (SocketException ignored) { // this exception is expected // on serverSocket close } catch (Exception ex) { if (!SSLSocketTester.isOkException(ex)) { Logger.getLogger( SSLSocketServer.class.getName()) .log(Level.SEVERE, null, ex); } } } }; serverThread = new Thread(runnable); serverThread.start(); } } } public String getHost() { synchronized (lock) { return host; } } public int getPort() { synchronized (lock) { return port; } } public void stop() throws IOException { synchronized (lock) { if (serverSocket != null) { try { serverSocket.close(); } finally { try { if (serverThread != null) { serverThread.join(); } } catch (InterruptedException ex) { Logger.getLogger(SSLSocketServer.class.getName()).log(Level.SEVERE, null, ex); } port = 0; serverThread = null; serverSocket = null; } } } } public void serverLoop() throws IOException { for (;;) { try (Socket socket = serverSocket.accept()) { OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); int readByte; while ((readByte = is.read()) >= 0) { os.write(readByte); } // see: https://bugzilla.redhat.com/show_bug.cgi?id=1918473 if (shutdownOutput) { try { socket.shutdownOutput(); } catch (UnsupportedOperationException ex) { // ignored } } } } } } /* * Copyright (c) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ package tests.integration.com.microsoft.azure.sdk.iot.iothub.twin; import com.google.gson.JsonParser; import com.microsoft.azure.sdk.iot.device.DeviceTwin.Pair; import com.microsoft.azure.sdk.iot.device.DeviceTwin.Property; import com.microsoft.azure.sdk.iot.device.DeviceTwin.TwinPropertyCallBack; import com.microsoft.azure.sdk.iot.device.IotHubClientProtocol; import com.microsoft.azure.sdk.iot.device.exceptions.ModuleClientException; import com.microsoft.azure.sdk.iot.service.auth.AuthenticationType; import com.microsoft.azure.sdk.iot.service.exceptions.IotHubException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import tests.integration.com.microsoft.azure.sdk.iot.helpers.*; import tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.ContinuousIntegrationTest; import tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.IotHubTest; import tests.integration.com.microsoft.azure.sdk.iot.helpers.annotations.StandardTierHubOnlyTest; import tests.integration.com.microsoft.azure.sdk.iot.iothub.setup.DeviceTwinCommon; import java.io.IOException; import java.net.URISyntaxException; import java.security.GeneralSecurityException; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; /** * Test class containing all non error injection tests to be run on JVM and android pertaining to DesiredProperties. */ @IotHubTest @RunWith(Parameterized.class) public class DesiredPropertiesTests extends DeviceTwinCommon { private JsonParser jsonParser = new JsonParser(); public DesiredPropertiesTests(IotHubClientProtocol protocol, AuthenticationType authenticationType, ClientType clientType, String publicKeyCert, String privateKey, String x509Thumbprint) { super(protocol, authenticationType, clientType, publicKeyCert, privateKey, x509Thumbprint); jsonParser = new JsonParser(); } @Before public void setUpNewDeviceAndModule() throws IOException, IotHubException, URISyntaxException, InterruptedException, ModuleClientException, GeneralSecurityException { super.setUpNewDeviceAndModule(); } @Test @StandardTierHubOnlyTest public void testSubscribeToDesiredProperties() throws IOException, InterruptedException, IotHubException { subscribeToDesiredPropertiesAndVerify( MAX_PROPERTIES_TO_TEST, PROPERTY_VALUE, PROPERTY_VALUE_UPDATE, PROPERTY_VALUE_UPDATE); } @Test @StandardTierHubOnlyTest public void testSubscribeToDesiredArrayProperties() throws IOException, InterruptedException, IotHubException { subscribeToDesiredPropertiesAndVerify( MAX_PROPERTIES_TO_TEST, jsonParser.parse(PROPERTY_VALUE_ARRAY), jsonParser.parse(PROPERTY_VALUE_UPDATE_ARRAY), PROPERTY_VALUE_UPDATE_ARRAY_PREFIX); } @Test @StandardTierHubOnlyTest @ContinuousIntegrationTest public void testSubscribeToDesiredArrayPropertiesWithVersion() throws IOException, InterruptedException, IotHubException { // arrange testSubscribeToDesiredPropertiesWithVersionFlow( jsonParser.parse(PROPERTY_VALUE_ARRAY), jsonParser.parse(PROPERTY_VALUE_UPDATE_ARRAY), PROPERTY_VALUE_UPDATE_ARRAY_PREFIX); } @Test @StandardTierHubOnlyTest public void testSubscribeToDesiredPropertiesWithVersion() throws IOException, InterruptedException, IotHubException { testSubscribeToDesiredPropertiesWithVersionFlow( PROPERTY_VALUE, PROPERTY_VALUE_UPDATE, PROPERTY_VALUE_UPDATE); } public void testSubscribeToDesiredPropertiesWithVersionFlow(Object propertyValue, Object updatePropertyValue, String updatePropertyPrefix) throws IOException, InterruptedException, IotHubException { // arrange deviceUnderTest.sCDeviceForTwin.clearTwin(); deviceUnderTest.dCDeviceForTwin.getDesiredProp().clear(); Map> desiredPropertiesCB = new HashMap<>(); for (int i = 0; i < MAX_PROPERTIES_TO_TEST; i++) { PropertyState propertyState = new PropertyState(); propertyState.callBackTriggered = false; propertyState.propertyNewVersion = -1; propertyState.property = new Property(PROPERTY_KEY + i, propertyValue); deviceUnderTest.dCDeviceForTwin.propertyStateList[i] = propertyState; desiredPropertiesCB.put(propertyState.property, new com.microsoft.azure.sdk.iot.device.DeviceTwin.Pair(deviceUnderTest.dCOnProperty, propertyState)); } // act internalClient.subscribeToTwinDesiredProperties(desiredPropertiesCB); Thread.sleep(DELAY_BETWEEN_OPERATIONS); Set desiredProperties = new HashSet<>(); for (int i = 0; i < MAX_PROPERTIES_TO_TEST; i++) { desiredProperties.add(new com.microsoft.azure.sdk.iot.service.devicetwin.Pair(PROPERTY_KEY + i, updatePropertyValue)); } deviceUnderTest.sCDeviceForTwin.setDesiredProperties(desiredProperties); sCDeviceTwin.updateTwin(deviceUnderTest.sCDeviceForTwin); // assert waitAndVerifyTwinStatusBecomesSuccess(); waitAndVerifyDesiredPropertyCallback(updatePropertyPrefix, true); } @Test @StandardTierHubOnlyTest @ContinuousIntegrationTest public void testSubscribeToDesiredPropertiesMultiThreaded() throws IOException, InterruptedException, IotHubException { testSubscribeToDesiredPropertiesMultiThreadedFlow(PROPERTY_VALUE, PROPERTY_VALUE_UPDATE, PROPERTY_VALUE_UPDATE); } @Test @StandardTierHubOnlyTest @ContinuousIntegrationTest public void testSubscribeToDesiredArrayPropertiesMultiThreaded() throws IOException, InterruptedException, IotHubException { testSubscribeToDesiredPropertiesMultiThreadedFlow(jsonParser.parse(PROPERTY_VALUE_ARRAY), jsonParser.parse(PROPERTY_VALUE_UPDATE_ARRAY), PROPERTY_VALUE_UPDATE_ARRAY_PREFIX); } public void testSubscribeToDesiredPropertiesMultiThreadedFlow(Object propertyValue, Object updatePropertyValue, String updatePropertyPrefix) throws IOException, InterruptedException, IotHubException { // arrange ExecutorService executor = Executors.newFixedThreadPool(MAX_PROPERTIES_TO_TEST); deviceUnderTest.dCDeviceForTwin.getDesiredProp().clear(); deviceUnderTest.sCDeviceForTwin.clearTwin(); for (int i = 0; i < MAX_PROPERTIES_TO_TEST; i++) { PropertyState propertyState = new PropertyState(); propertyState.callBackTriggered = false; propertyState.property = new Property(PROPERTY_KEY + i, propertyValue); deviceUnderTest.dCDeviceForTwin.propertyStateList[i] = propertyState; deviceUnderTest.dCDeviceForTwin.setDesiredPropertyCallback(propertyState.property, deviceUnderTest.dCDeviceForTwin, propertyState); } // act internalClient.subscribeToDesiredProperties(deviceUnderTest.dCDeviceForTwin.getDesiredProp()); Thread.sleep(DELAY_BETWEEN_OPERATIONS); //Setting desired properties in different threads leads to a race condition Object desiredPropertiesUpdateLock = new Object(); for (int i = 0; i < MAX_PROPERTIES_TO_TEST; i++) { final int index = i; executor.submit(new Runnable() { @Override public void run() { try { Set desiredProperties = new HashSet<>(); desiredProperties.add(new com.microsoft.azure.sdk.iot.service.devicetwin.Pair(PROPERTY_KEY + index, updatePropertyValue)); synchronized (desiredPropertiesUpdateLock) { Set currentDesiredProperties = deviceUnderTest.sCDeviceForTwin.getDesiredProperties(); desiredProperties.addAll(currentDesiredProperties); deviceUnderTest.sCDeviceForTwin.setDesiredProperties(desiredProperties); sCDeviceTwin.updateTwin(deviceUnderTest.sCDeviceForTwin); } } catch (IotHubException | IOException e) { fail(e.getMessage()); } } }); Thread.sleep(DELAY_BETWEEN_OPERATIONS); } executor.shutdown(); if (!executor.awaitTermination(1, TimeUnit.MINUTES)) { executor.shutdownNow(); } // assert waitAndVerifyTwinStatusBecomesSuccess(); waitAndVerifyDesiredPropertyCallback(updatePropertyPrefix, false); } @Test @StandardTierHubOnlyTest public void testSubscribeToDesiredPropertiesSequentially() throws IOException, InterruptedException, IotHubException { testSubscribeToDesiredPropertiesSequentiallyFlow(PROPERTY_VALUE, PROPERTY_VALUE_UPDATE, PROPERTY_VALUE_UPDATE); } @Test @StandardTierHubOnlyTest @ContinuousIntegrationTest public void testSubscribeToDesiredArrayPropertiesSequentially() throws IOException, InterruptedException, IotHubException { testSubscribeToDesiredPropertiesSequentiallyFlow( jsonParser.parse(PROPERTY_VALUE_ARRAY), jsonParser.parse(PROPERTY_VALUE_UPDATE_ARRAY), PROPERTY_VALUE_UPDATE_ARRAY_PREFIX); } public void testSubscribeToDesiredPropertiesSequentiallyFlow( Object propertyValue, Object updatePropertyValue, String updatePropertyPrefix) throws IOException, InterruptedException, IotHubException { // arrange deviceUnderTest.sCDeviceForTwin.clearTwin(); deviceUnderTest.dCDeviceForTwin.getDesiredProp().clear(); for (int i = 0; i < MAX_PROPERTIES_TO_TEST; i++) { PropertyState propertyState = new PropertyState(); propertyState.callBackTriggered = false; propertyState.property = new Property(PROPERTY_KEY + i, propertyValue); deviceUnderTest.dCDeviceForTwin.propertyStateList[i] = propertyState; deviceUnderTest.dCDeviceForTwin.setDesiredPropertyCallback(propertyState.property, deviceUnderTest.dCDeviceForTwin, propertyState); } // act internalClient.subscribeToDesiredProperties(deviceUnderTest.dCDeviceForTwin.getDesiredProp()); Thread.sleep(DELAY_BETWEEN_OPERATIONS); for (int i = 0; i < MAX_PROPERTIES_TO_TEST; i++) { Set desiredProperties = new HashSet<>(); desiredProperties.add(new com.microsoft.azure.sdk.iot.service.devicetwin.Pair(PROPERTY_KEY + i, updatePropertyValue)); deviceUnderTest.sCDeviceForTwin.setDesiredProperties(desiredProperties); sCDeviceTwin.updateTwin(deviceUnderTest.sCDeviceForTwin); Thread.sleep(DELAY_BETWEEN_OPERATIONS); } // assert waitAndVerifyTwinStatusBecomesSuccess(); waitAndVerifyDesiredPropertyCallback(updatePropertyPrefix, false); } @Test @StandardTierHubOnlyTest public void testUpdateDesiredProperties() throws IOException, InterruptedException, IotHubException, GeneralSecurityException, URISyntaxException, ModuleClientException { addMultipleDevices(MAX_DEVICES); // Add desired properties for multiple devices deviceUnderTest.sCDeviceForTwin.clearTwin(); deviceUnderTest.dCDeviceForTwin.getDesiredProp().clear(); for (int i = 0; i < MAX_DEVICES; i++) { Set desiredProperties = new HashSet<>(); desiredProperties.add(new com.microsoft.azure.sdk.iot.service.devicetwin.Pair(PROPERTY_KEY + i, PROPERTY_VALUE + i)); devicesUnderTest[i].sCDeviceForTwin.setDesiredProperties(desiredProperties); sCDeviceTwin.updateTwin(devicesUnderTest[i].sCDeviceForTwin); devicesUnderTest[i].sCDeviceForTwin.clearTwin(); } // Update desired properties on multiple devices for (int i = 0; i < MAX_DEVICES; i++) { sCDeviceTwin.getTwin(devicesUnderTest[i].sCDeviceForTwin); Set desiredProperties = devicesUnderTest[i].sCDeviceForTwin.getDesiredProperties(); for (com.microsoft.azure.sdk.iot.service.devicetwin.Pair dp : desiredProperties) { dp.setValue(PROPERTY_VALUE_UPDATE + i); } devicesUnderTest[i].sCDeviceForTwin.setDesiredProperties(desiredProperties); sCDeviceTwin.updateTwin(devicesUnderTest[i].sCDeviceForTwin); devicesUnderTest[i].sCDeviceForTwin.clearTwin(); } // Read updates on multiple devices for (int i = 0; i < MAX_DEVICES; i++) { sCDeviceTwin.getTwin(devicesUnderTest[i].sCDeviceForTwin); for (com.microsoft.azure.sdk.iot.service.devicetwin.Pair dp : devicesUnderTest[i].sCDeviceForTwin.getDesiredProperties()) { Assert.assertEquals(CorrelationDetailsLoggingAssert.buildExceptionMessage("Unexpected desired property key, expected " + PROPERTY_KEY + i + " but was " + dp.getKey(), internalClient), PROPERTY_KEY + i, dp.getKey()); Assert.assertEquals(CorrelationDetailsLoggingAssert.buildExceptionMessage("Unexpected desired property value, expected " + PROPERTY_VALUE_UPDATE + i + " but was " + dp.getValue(), internalClient), PROPERTY_VALUE_UPDATE + i, dp.getValue()); } Integer version = devicesUnderTest[i].sCDeviceForTwin.getDesiredPropertiesVersion(); assertNotNull(CorrelationDetailsLoggingAssert.buildExceptionMessage("Version was null", internalClient), version); } // Remove desired properties for (int i = 0; i < MAX_DEVICES; i++) { sCDeviceTwin.getTwin(devicesUnderTest[i].sCDeviceForTwin); Set desiredProperties = devicesUnderTest[i].sCDeviceForTwin.getDesiredProperties(); for (com.microsoft.azure.sdk.iot.service.devicetwin.Pair dp : desiredProperties) { dp.setValue(null); } devicesUnderTest[i].sCDeviceForTwin.setDesiredProperties(desiredProperties); sCDeviceTwin.updateTwin(devicesUnderTest[i].sCDeviceForTwin); devicesUnderTest[i].sCDeviceForTwin.clearTwin(); } // Read updates for (int i = 0; i < MAX_DEVICES; i++) { sCDeviceTwin.getTwin(devicesUnderTest[i].sCDeviceForTwin); Assert.assertEquals(CorrelationDetailsLoggingAssert.buildExceptionMessage("Desired properties were not deleted by setting to null", internalClient), 0, devicesUnderTest[i].sCDeviceForTwin.getDesiredProperties().size()); } removeMultipleDevices(MAX_DEVICES); } } package net.earthcomputer.multiconnect.protocols.v1_13_2.mixin; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.RemovalListener; import net.earthcomputer.multiconnect.api.Protocols; import net.earthcomputer.multiconnect.impl.ConnectionInfo; import net.earthcomputer.multiconnect.impl.Constants; import net.earthcomputer.multiconnect.impl.Utils; import net.earthcomputer.multiconnect.protocols.v1_13_2.*; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.entity.EntityType; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketByteBuf; import net.minecraft.network.packet.s2c.play.*; import net.minecraft.util.Identifier; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.Vec3d; import net.minecraft.village.TradeOffer; import net.minecraft.village.TradeOfferList; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Unique; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; @Mixin(ClientPlayNetworkHandler.class) public abstract class MixinClientPlayNetworkHandler { @Shadow public abstract void onOpenWrittenBook(OpenWrittenBookS2CPacket packet); @Shadow public abstract void onDifficulty(DifficultyS2CPacket packet); @Shadow public abstract void onSetTradeOffers(SetTradeOffersS2CPacket packet); @Shadow public abstract void onVelocityUpdate(EntityVelocityUpdateS2CPacket entityVelocityUpdateS2CPacket_1); @Shadow public abstract void onChunkLoadDistance(ChunkLoadDistanceS2CPacket packet); @Shadow public abstract void onChunkData(ChunkDataS2CPacket packet); @Unique private static final Logger MULTICONNECT_LOGGER = LogManager.getLogger("multiconnect"); // Handle reordering of the (synthetic) render distance center packet, to allow the chunk data to arrive beforehand and queue it @Unique private boolean hasReceivedServerPosition; @Unique private int centerChunkX; @Unique private int centerChunkZ; @Unique private int viewDistance = 12; @Unique private static final int MAX_VIEW_DISTANCE = 32; @Unique private final Cache> waitingChunkDataPackets = CacheBuilder.newBuilder() .expireAfterWrite(Constants.PACKET_QUEUE_DROP_TIMEOUT, TimeUnit.SECONDS) .removalListener((RemovalListener>) notification -> { if (notification.wasEvicted()) { MULTICONNECT_LOGGER.warn("Dropping chunk packet(s) at {}, {} because it was too far away from the render distance center {}, {}", notification.getKey().x, notification.getKey().z, centerChunkX, centerChunkZ); } }) .build(); @Inject(method = "", at = @At("RETURN")) private void onConstruct(CallbackInfo ci) { Utils.autoCleanUp(waitingChunkDataPackets, Constants.PACKET_QUEUE_DROP_TIMEOUT, TimeUnit.SECONDS); } @Inject(method = "onChunkData", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/NetworkThreadUtils;forceMainThread(Lnet/minecraft/network/Packet;Lnet/minecraft/network/listener/PacketListener;Lnet/minecraft/util/thread/ThreadExecutor;)V", shift = At.Shift.AFTER), cancellable = true) private void onOnChunkData(ChunkDataS2CPacket packet, CallbackInfo ci) { if (ConnectionInfo.protocolVersion <= Protocols.V1_13_2) { if (!isInRange(packet.getX(), packet.getZ())) { waitingChunkDataPackets.asMap().computeIfAbsent(new ChunkPos(packet.getX(), packet.getZ()), k -> new ArrayList<>()).add(packet); ci.cancel(); } } } @Inject(method = "onChunkLoadDistance", at = @At("RETURN")) private void onOnChunkLoadDistance(ChunkLoadDistanceS2CPacket packet, CallbackInfo ci) { if (ConnectionInfo.protocolVersion <= Protocols.V1_13_2) { viewDistance = packet.getDistance(); } } @Inject(method = "onChunkRenderDistanceCenter", at = @At("RETURN")) private void onOnRenderDistanceCenter(ChunkRenderDistanceCenterS2CPacket packet, CallbackInfo ci) { if (ConnectionInfo.protocolVersion <= Protocols.V1_13_2 && hasReceivedServerPosition) { centerChunkX = packet.getChunkX(); centerChunkZ = packet.getChunkZ(); // Increase radius if necessary, up to a limit of MAX_VIEW_DISTANCE int newViewDistance = waitingChunkDataPackets.asMap().keySet().stream() .mapToInt(pos -> getRequiredRange(pos.x, pos.z)) .filter(distance -> distance <= MAX_VIEW_DISTANCE) .max().orElse(0); if (newViewDistance > viewDistance) { onChunkLoadDistance(new ChunkLoadDistanceS2CPacket(newViewDistance)); } // Process queued packets for (int dx = centerChunkX - viewDistance; dx <= centerChunkX + viewDistance; dx++) { for (int dz = centerChunkZ - viewDistance; dz <= centerChunkZ + viewDistance; dz++) { List chunkDataPackets = waitingChunkDataPackets.asMap().remove(new ChunkPos(dx, dz)); if (chunkDataPackets != null) { for (ChunkDataS2CPacket chunkDataPacket : chunkDataPackets) { onChunkData(chunkDataPacket); } } } } } } @Unique private boolean isInRange(int chunkX, int chunkZ) { return getRequiredRange(chunkX, chunkZ) <= viewDistance; } @Unique private int getRequiredRange(int chunkX, int chunkZ) { return Math.max(Math.abs(chunkX - centerChunkX), Math.abs(chunkZ - centerChunkZ)); } @Inject(method = "onCustomPayload", at = @At(value = "INVOKE", target = "Lnet/minecraft/network/NetworkThreadUtils;forceMainThread(Lnet/minecraft/network/Packet;Lnet/minecraft/network/listener/PacketListener;Lnet/minecraft/util/thread/ThreadExecutor;)V", shift = At.Shift.AFTER), cancellable = true) private void onOnCustomPayload(CustomPayloadS2CPacket packet, CallbackInfo ci) { if (ConnectionInfo.protocolVersion <= Protocols.V1_13_2) { Identifier channel = packet.getChannel(); if (Protocol_1_13_2.CUSTOM_PAYLOAD_TRADE_LIST.equals(channel)) { PacketByteBuf buf = packet.getData(); int syncId = buf.readInt(); TradeOfferList trades = new TradeOfferList(); int tradeCount = buf.readUnsignedByte(); for (int i = 0; i < tradeCount; i++) { ItemStack buy = buf.readItemStack(); ItemStack sell = buf.readItemStack(); boolean hasSecondItem = buf.readBoolean(); ItemStack secondBuy = hasSecondItem ? buf.readItemStack() : ItemStack.EMPTY; boolean locked = buf.readBoolean(); int tradeUses = buf.readInt(); int maxTradeUses = buf.readInt(); TradeOffer trade = new TradeOffer(buy, secondBuy, sell, tradeUses, maxTradeUses, 0, 1); if (locked) trade.disable(); trades.add(trade); } onSetTradeOffers(new SetTradeOffersS2CPacket(syncId, trades, 5, 0, false, false)); ci.cancel(); } else if (Protocol_1_13_2.CUSTOM_PAYLOAD_OPEN_BOOK.equals(channel)) { OpenWrittenBookS2CPacket openBookPacket = new OpenWrittenBookS2CPacket(packet.getData()); onOpenWrittenBook(openBookPacket); ci.cancel(); } } } @Inject(method = "onGameJoin", at = @At("TAIL")) private void onOnGameJoin(GameJoinS2CPacket packet, CallbackInfo ci) { if (ConnectionInfo.protocolVersion <= Protocols.V1_13_2) { onDifficulty(new DifficultyS2CPacket(PendingDifficulty.getPendingDifficulty(), false)); } } @Inject(method = "onPlayerRespawn", at = @At("TAIL")) private void onOnPlayerRespawn(PlayerRespawnS2CPacket packet, CallbackInfo ci) { if (ConnectionInfo.protocolVersion <= Protocols.V1_13_2) { hasReceivedServerPosition = false; onDifficulty(new DifficultyS2CPacket(PendingDifficulty.getPendingDifficulty(), false)); } } @Inject(method = "onEntitySpawn", at = @At("TAIL")) private void onOnEntitySpawn(EntitySpawnS2CPacket packet, CallbackInfo ci) { if (ConnectionInfo.protocolVersion <= Protocols.V1_13_2) { if (packet.getEntityTypeId() == EntityType.ITEM || packet.getEntityTypeId() == EntityType.ARROW || packet.getEntityTypeId() == EntityType.SPECTRAL_ARROW || packet.getEntityTypeId() == EntityType.TRIDENT) { onVelocityUpdate(new EntityVelocityUpdateS2CPacket(packet.getId(), new Vec3d(packet.getVelocityX(), packet.getVelocityY(), packet.getVelocityZ()))); } } } @Inject(method = "onPlayerPositionLook", at = @At("TAIL")) private void onOnPlayerPositionLook(PlayerPositionLookS2CPacket packet, CallbackInfo ci) { if (ConnectionInfo.protocolVersion <= Protocols.V1_13_2) { hasReceivedServerPosition = true; Protocol_1_13_2.updateCameraPosition(); } } } nqiu/lunar-java package test; import com.nlf.calendar.SolarWeek; import com.nlf.calendar.util.SolarUtil; import org.junit.Assert; import org.junit.Test; /** * 周测试 * * @author 6tail */ public class WeekTest { @Test public void testFromMonday(){ //一周的开始从星期一开始计 int start = 1; SolarWeek week = new SolarWeek(2019,5,1,start); Assert.assertEquals("2019.5.1",week.toString()); Assert.assertEquals("2019年5月第1周",week.toFullString()); //当月共几周 Assert.assertEquals(5,SolarUtil.getWeeksOfMonth(week.getYear(),week.getMonth(),start)); //当周第一天 Assert.assertEquals("2019-04-29",week.getFirstDay().toString()); //当周第一天(本月) Assert.assertEquals("2019-05-01",week.getFirstDayInMonth().toString()); } @Test public void testFromSunday(){ //一周的开始从星期日开始计 int start = 0; SolarWeek week = new SolarWeek(2019,5,1,start); Assert.assertEquals("2019.5.1",week.toString()); Assert.assertEquals("2019年5月第1周",week.toFullString()); //当月共几周 Assert.assertEquals(5,SolarUtil.getWeeksOfMonth(week.getYear(),week.getMonth(),start)); //当周第一天 Assert.assertEquals("2019-04-28",week.getFirstDay().toString()); //当周第一天(本月) Assert.assertEquals("2019-05-01",week.getFirstDayInMonth().toString()); } } package bolum06; public class Cozum_06_02 { public static void main(String[] args) { long sayi = 234; System.out.println("Sayinin rakamlari toplami : " + toplamRakamlar(sayi)); } public static int toplamRakamlar(long n) { int toplam = 0; while (n != 0) { toplam += n % 10; n /= 10; } return toplam; } } java/examples/com/mxgraph/examples/web/EmbedImage.java package com.mxgraph.examples.web; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.StringWriter; import java.io.Writer; import java.net.URL; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.zip.GZIPOutputStream; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.mxgraph.util.mxBase64; import com.mxgraph.util.mxUtils; /** * */ public class EmbedImage extends HttpServlet { /** * */ private static final long serialVersionUID = -4951624126588618796L; /** * */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream out = response.getOutputStream(); String encoding = request.getHeader("Accept-Encoding"); // Supports GZIP content encoding if (encoding != null && encoding.indexOf("gzip") >= 0) { response.setHeader("Content-Encoding", "gzip"); out = new GZIPOutputStream(out); } PrintWriter writer = new PrintWriter(out); writer.println(""); writer.println(""); writer.println(""); writer.println(""); writer.println(""); writer.println(""); writer.println(""); writer.flush(); writer.close(); } /** * */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream out = response.getOutputStream(); String encoding = request.getHeader("Accept-Encoding"); // Supports GZIP content encoding if (encoding != null && encoding.indexOf("gzip") >= 0) { response.setHeader("Content-Encoding", "gzip"); out = new GZIPOutputStream(out); } PrintWriter writer = new PrintWriter(out); String url = request.getParameter("url"); if (url != null) { // Enables caching of this response response.setHeader("Content-Type", "text/plain"); response.setHeader("Cache-Control", "private"); response.setHeader("Expires", "Thu, 15 Apr 2030 20:00:00 GMT"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(ImageIO.read(new URL(url)), "png", bos); writer.print("\n"); } else if (request.getSession(false) != null) { response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); response.setHeader("Content-Type", "text/plain"); // Gets the image from the session and destroys the session and the cookie writer.print(request.getSession().getAttribute("image")); request.getSession().invalidate(); Cookie cookie = new Cookie("JSESSIONID", ""); cookie.setMaxAge(0); cookie.setPath("/"); response.addCookie(cookie); } else { // Makes sure there is no caching on the client side response.setHeader("Cache-Control", "no-store"); response.setHeader("Expires", "0"); response.setStatus(HttpServletResponse.SC_OK); // Loads the static HTML page with the placeholder from the template String page = mxUtils.readFile(Roundtrip.class.getResource( "/com/mxgraph/examples/web/resources/embedimage.html") .getPath()); String userAgent = request.getHeader("User-Agent"); boolean dataUrl = userAgent.indexOf("MSIE 6") < 0 && userAgent.indexOf("MSIE 7") < 0; // In a real-world environment the following would be done for each entry // of the image bundle in an XML file for a diagram. String name = "myImage"; String data = ""; String mhtml = (dataUrl) ? "" : "\n" + mhtml(name, data); String bundle = "bundle.putImage('myImage', 'data:image/png," + data + "=', 'mhtml:' + window.location.href + '!" + name + "');"; // Replaces the placeholder in the template with the XML data // which is then parsed into the graph model on the client. // In a production environment you should use a template engine. page = page.replaceAll("%mhtml%", mhtml); page = page.replaceAll("%dataUrl%", (dataUrl) ? "true" : "false"); page = page.replaceAll("%bundle%", bundle); writer.println(page); } writer.flush(); writer.close(); } /** * Creates a MHTML entry for the given resource name and base64 encoded data. */ protected String mhtml(String name, String data) { return "Content-Type: multipart/related; boundary=\"----\"\n" + "\n" + "------\n" + "Content-Location:" + name + "\n" + "Content-Transfer-Encoding:base64\n" + "\n" + data + "=\n" + "------\n"; } // // Handling of multipart/form-data *** NOT FOR PRODUCTION USE!! *** // /** * Encoding for the multipart/form-data. */ protected static final String ENCODING = "ISO-8859-1"; /** * Parses the given multipart/form-data request into a map that maps from * names to values. Note that this implementation ignores the file type and * filename and does only return the actual data as the value for the name * of the file input in the form. Returns an empty map if the form does not * contain any multipart/form-data. */ protected Map parseMultipartRequest( HttpServletRequest request) throws IOException { Map result = new Hashtable(); String contentType = request.getHeader("Content-Type"); // Checks if the form is of the correct content type if (contentType != null && contentType.indexOf("multipart/form-data") == 0) { // Extracts the boundary from the header int boundaryIndex = contentType.indexOf("boundary="); String boundary = "--" + contentType.substring(boundaryIndex + 9).trim(); // Splits the multipart/form-data into its different parts Iterator it = splitFormData( readStream(request.getInputStream()), boundary).iterator(); while (it.hasNext()) { parsePart(it.next(), result); } } return result; } /** * Parses the values in the given form-data part into the given map. The * value of the name attribute will be used as the name for the data. The * filename will be stored under filename in the given map and the * content-type is ignored in this implementation. */ protected void parsePart(String part, Map into) { String[] lines = part.split("\r\n"); if (lines.length > 1) { // First line contains content-disposition in the following format: // form-data; name="upfile"; filename="avatar.jpg" String[] tokens = lines[1].split(";"); // Stores the value of the name attribute for the form-data String name = null; for (int i = 0; i < tokens.length; i++) { String tmp = tokens[i]; int index = tmp.indexOf("="); // Checks if the token contains a key=value pair if (index >= 0) { String key = tmp.substring(0, index).trim(); String value = tmp.substring(index + 2, tmp.length() - 1); if (key.equals("name")) { name = value; } else { into.put(key, value); } } } // Last line contains the actual data if (name != null) { into.put(name, lines[lines.length - 1]); } } } /** * Returns the parts of the given multipart/form-data. */ protected List splitFormData(String formData, String boundary) { List result = new LinkedList(); int nextBoundary = formData.indexOf(boundary); while (nextBoundary >= 0) { if (nextBoundary > 0) { result.add(formData.substring(0, nextBoundary)); } formData = formData.substring(nextBoundary + boundary.length()); nextBoundary = formData.indexOf(boundary); } return result; } /** * Reads the complete stream into memory as a String. */ protected String readStream(InputStream is) throws IOException { if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[1024]; try { Reader reader = new BufferedReader(new InputStreamReader(is, ENCODING)); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } finally { is.close(); } return writer.toString(); } else { return ""; } } } common/src/main/java/de/unistuttgart/ipvs/as/mmp/common/domain/ModelGroup.java package de.unistuttgart.ipvs.as.mmp.common.domain; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import org.hibernate.search.annotations.Field; import org.hibernate.search.annotations.Fields; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "model_group") @EqualsAndHashCode(callSuper = true) @Data @Builder @AllArgsConstructor @NoArgsConstructor public class ModelGroup extends BaseEntity{ @Fields({ @Field(), @Field(name = "ALL") }) @Column(updatable = false) private String modelGroupName; } com.zutubi.tove/src/java/com/zutubi/tove/type/PrimitiveType.java /* Copyright 2017 Zutubi Pty Ltd * * 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.zutubi.tove.type; import com.zutubi.tove.squeezer.SqueezeException; import com.zutubi.tove.squeezer.Squeezers; import com.zutubi.tove.squeezer.TypeSqueezer; import com.zutubi.util.CollectionUtils; import java.util.HashMap; import java.util.Map; /** * Manages basic numerical, boolean and string values. */ public class PrimitiveType extends SimpleType implements Type { private static final Class[] XML_RPC_SUPPORTED_TYPES = { Boolean.class, Double.class, Integer.class, String.class }; private static final Map PRIMITIVE_CLASSES_MAP; private static final Map NULL_VALUES_MAP; static { PRIMITIVE_CLASSES_MAP = new HashMap(8); PRIMITIVE_CLASSES_MAP.put(boolean.class, Boolean.class); PRIMITIVE_CLASSES_MAP.put(byte.class, Byte.class); PRIMITIVE_CLASSES_MAP.put(char.class, Character.class); PRIMITIVE_CLASSES_MAP.put(double.class, Double.class); PRIMITIVE_CLASSES_MAP.put(int.class, Integer.class); PRIMITIVE_CLASSES_MAP.put(float.class, Float.class); PRIMITIVE_CLASSES_MAP.put(long.class, Long.class); PRIMITIVE_CLASSES_MAP.put(short.class, Short.class); NULL_VALUES_MAP = new HashMap(7); NULL_VALUES_MAP.put(byte.class, Byte.MIN_VALUE); NULL_VALUES_MAP.put(char.class, Character.MIN_VALUE); NULL_VALUES_MAP.put(double.class, Double.MIN_VALUE); NULL_VALUES_MAP.put(int.class, Integer.MIN_VALUE); NULL_VALUES_MAP.put(float.class, Float.MIN_VALUE); NULL_VALUES_MAP.put(long.class, Long.MIN_VALUE); NULL_VALUES_MAP.put(short.class, Short.MIN_VALUE); } private TypeSqueezer squeezer; public PrimitiveType(Class type) { this(type, null); } public PrimitiveType(Class type, String symbolicName) { super(type, symbolicName); squeezer = Squeezers.findSqueezer(type); if (squeezer == null) { throw new IllegalArgumentException("Unsupported primitive type: " + type); } } public Object instantiate(Object data, Instantiator instantiator) throws TypeException { try { if (data instanceof String[]) { return squeezer.unsqueeze(((String[]) data)[0]); } else if (data instanceof String) { return squeezer.unsqueeze((String) data); } return data; } catch (SqueezeException e) { throw new TypeConversionException(e.getMessage()); } } public String unstantiate(Object instance, String templateOwnerPath) throws TypeException { if (instance == null) { return null; } try { return squeezer.squeeze(instance); } catch (SqueezeException e) { throw new TypeException(e); } } public Object toXmlRpc(String templateOwnerPath, Object data) throws TypeException { if (data == null) { return null; } // XML-RPC only supports limited types, in their direct form. Class clazz = getClazz(); if(PRIMITIVE_CLASSES_MAP.containsKey(clazz)) { clazz = PRIMITIVE_CLASSES_MAP.get(clazz); } String s = (String) data; if(CollectionUtils.contains(XML_RPC_SUPPORTED_TYPES, clazz)) { return instantiate(s, null); } else if(clazz == Byte.class) { // Convert up to int return Byte.valueOf(s).intValue(); } else if(clazz == Float.class) { // Convert up to double return Float.valueOf(s).doubleValue(); } else if(clazz == Short.class) { // Convert up to int return Short.valueOf(s).intValue(); } else { // Leave as a string. This includes characters, and unfortunately // longs as well (XML-RPC has no direct way to specify a 64 bit // int). return s; } } public String fromXmlRpc(String templateOwnerPath, Object data, boolean applyDefaults) throws TypeException { Class clazz = getClazz(); if(PRIMITIVE_CLASSES_MAP.containsKey(clazz)) { clazz = PRIMITIVE_CLASSES_MAP.get(clazz); } if(CollectionUtils.contains(XML_RPC_SUPPORTED_TYPES, clazz)) { typeCheck(data, clazz); return unstantiate(data, templateOwnerPath); } else if(clazz == Byte.class) { typeCheck(data, Integer.class); return Byte.toString(((Integer)data).byteValue()); } else if(clazz == Float.class) { typeCheck(data, Double.class); return Float.toString(((Double)data).floatValue()); } else if(clazz == Short.class) { typeCheck(data, Integer.class); return Short.toString(((Integer)data).shortValue()); } else { typeCheck(data, String.class); return (String) data; } } public Object getNullValue() { return NULL_VALUES_MAP.get(getClazz()); } } Sheldan/abstractoabstracto-application/core/core-impl/src/main/java/dev/sheldan/abstracto/core/command/service/CommandCoolDownRuntimeStorage.java package dev.sheldan.abstracto.core.command.service; import lombok.Builder; import lombok.Getter; import lombok.Setter; import org.springframework.stereotype.Component; import java.time.Instant; import java.util.HashMap; import java.util.Map; @Component @Getter public class CommandCoolDownRuntimeStorage { // maps server ID to command name to time at which the command can be executed again private Map serverCoolDowns = new HashMap<>(); // maps server ID to channel group ID to command name to time at which the command can be executed again private Map> channelGroupCoolDowns = new HashMap<>(); // maps server ID to member ID to command name to time at which the command can be executed again private Map> memberCoolDowns = new HashMap<>(); } @Getter @Setter @Builder class CommandReUseMap { private Map reUseTimes; }/* * Copyright 2014 * * 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.thatjoemoore.utils.annotations; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; /** * Created by adm.jmooreoa on 12/31/14. */ public abstract class AbstractWriter implements AnalyzeAndWriteProcessor.Writer { private ProcessingEnvironment processingEnv; private RoundEnvironment roundEnv; private Logger logger; @Override public void init(ProcessingEnvironment processingEnv, RoundEnvironment roundEnv, Logger logger) { this.processingEnv = processingEnv; this.roundEnv = roundEnv; this.logger = logger; } protected ProcessingEnvironment processingEnv() { return processingEnv; } protected RoundEnvironment roundEnv() { return roundEnv; } protected Logger logger() { return logger; } protected final Types types() { return processingEnv.getTypeUtils(); } protected final Elements elements() { return processingEnv.getElementUtils(); } protected final Messager messager() { return processingEnv.getMessager(); } protected final Filer filer() { return processingEnv.getFiler(); } } /* * Copyright 2014 Red Hat, Inc. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.web.handler; import io.vertx.core.Vertx; import io.vertx.core.http.HttpMethod; import io.vertx.ext.auth.authentication.AuthenticationProvider; import io.vertx.ext.auth.authentication.UsernamePasswordCredentials; import io.vertx.ext.auth.authorization.Authorization; import io.vertx.ext.auth.authorization.AuthorizationProvider; import io.vertx.ext.auth.authorization.PermissionBasedAuthorization; import io.vertx.ext.auth.properties.PropertyFileAuthentication; import io.vertx.ext.auth.properties.PropertyFileAuthorization; import io.vertx.ext.web.WebTestBase; import io.vertx.ext.web.sstore.LocalSessionStore; import io.vertx.ext.web.sstore.SessionStore; import org.junit.AfterClass; import org.junit.Test; /** * @author */ public abstract class AuthHandlerTestBase extends WebTestBase { @AfterClass public static void oneTimeTearDown() { Vertx vertx = Vertx.vertx(); if (vertx.fileSystem().existsBlocking(BodyHandler.DEFAULT_UPLOADS_DIRECTORY)) { vertx.fileSystem().deleteRecursiveBlocking(BodyHandler.DEFAULT_UPLOADS_DIRECTORY, true); } } @Test public void testAuthAuthorities() throws Exception { testAuthorization("tim", false, PermissionBasedAuthorization.create("dance")); } @Test public void testAuthAuthoritiesFail() throws Exception { testAuthorization("tim", true, PermissionBasedAuthorization.create("knitter")); } protected abstract AuthenticationHandler createAuthHandler(AuthenticationProvider authProvider); protected boolean requiresSession() { return false; } protected SessionStore getSessionStore() { return LocalSessionStore.create(vertx); } protected void testAuthorization(String username, boolean fail, Authorization authority) throws Exception { if (requiresSession()) { router.route().handler(BodyHandler.create()); SessionStore store = getSessionStore(); router.route().handler(SessionHandler.create(store)); } AuthenticationProvider authNProvider = PropertyFileAuthentication.create(vertx, "login/loginusers.properties"); AuthorizationProvider authZProvider = PropertyFileAuthorization.create(vertx, "login/loginusers.properties"); AuthenticationHandler authNHandler = createAuthHandler(authNProvider); router.route().handler(rc -> { // we need to be logged in if (rc.user() == null) { UsernamePasswordCredentials authInfo = new UsernamePasswordCredentials(username, ""); authNProvider.authenticate(authInfo, res -> { if (res.succeeded()) { rc.setUser(res.result()); rc.next(); } else { rc.fail(res.cause()); } }); } }); router.route().handler(authNHandler); if (authority != null) { router.route().handler(AuthorizationHandler.create(authority).addAuthorizationProvider(authZProvider)); } router.route().handler(rc -> rc.response().end()); testRequest(HttpMethod.GET, "/", fail ? 403: 200, fail? "Forbidden": "OK"); } } 0 package com.platform.service.impl; import com.platform.dao.GoodsSpecificationDao; import com.platform.entity.GoodsSpecificationEntity; import com.platform.utils.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Map; import com.platform.dao.GoodsCrashDao; import com.platform.entity.GoodsCrashEntity; import com.platform.service.GoodsCrashService; /** * 商品搭配减Service实现类 * * @author qins * @email * @date 2017-08-30 18:35:41 */ @Service("goodsCrashService") public class GoodsCrashServiceImpl implements GoodsCrashService { @Autowired private GoodsCrashDao goodsCrashDao; @Autowired private GoodsSpecificationDao goodsSpecificationDao; @Override public GoodsCrashEntity queryObject(Integer id) { return goodsCrashDao.queryObject(id); } @Override public List queryList(Map map) { List list = goodsCrashDao.queryList(map); List result = new ArrayList<>(); //翻译产品规格 if (null != list && list.size() > 0) { for (GoodsCrashEntity item : list) { String specificationIds = item.getGoodsSpecificationIds(); String specificationValue = ""; if (!StringUtils.isNullOrEmpty(specificationIds)) { String[] arr = specificationIds.split("_"); for (String goodsSpecificationId : arr) { GoodsSpecificationEntity entity = goodsSpecificationDao.queryObject(goodsSpecificationId); if (null != entity) { specificationValue += entity.getValue() + ";"; } } } item.setGoodsSpecificationValue(specificationValue); result.add(item); } } return result; } @Override public int queryTotal(Map map) { return goodsCrashDao.queryTotal(map); } @Override public int save(GoodsCrashEntity goodsCrash) { return goodsCrashDao.save(goodsCrash); } @Override public int update(GoodsCrashEntity goodsCrash) { return goodsCrashDao.update(goodsCrash); } @Override public int delete(Integer id) { return goodsCrashDao.delete(id); } @Override public int deleteBatch(Integer[] ids) { return goodsCrashDao.deleteBatch(ids); } } rapodaca/Terasology /* * Copyright 2011 <>. * * 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.terasology.logic.world; /** * Basic interface for anything providing chunks. * * @author <> */ public interface IChunkProvider { /** * Returns the chunk at the given position. * * @param x The chunk position on the x-axis * @param z The chunk position on the z-axis * @return The chunk */ public Chunk loadOrCreateChunk(int x, int z); /** * Frees obsolete chunks. */ public void flushCache(); /** * Disposes all chunks managed by this chunk provider. */ public void dispose(); /** * Returns the amount of chunks managed by this chunk provider. * * @return The amount of managed chunks */ public int size(); } YTG1234/make-every-biome-spawnable-lolsrc/main/java/esb/MakeEveryBiomeSpawnable.java package esb; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; import net.fabricmc.fabric.api.biome.v1.BiomeModifications; import net.fabricmc.fabric.api.biome.v1.BiomeSelectionContext; import net.fabricmc.fabric.api.biome.v1.ModificationPhase; import net.fabricmc.fabric.impl.biome.modification.BiomeSelectionContextImpl; import net.minecraft.util.Identifier; import net.minecraft.util.registry.BuiltinRegistries; import net.minecraft.util.registry.RegistryKey; import net.minecraft.world.biome.Biome; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.Path; import java.util.function.Predicate; public class MakeEveryBiomeSpawnable implements ModInitializer { public static Gson GSON = new GsonBuilder() .registerTypeAdapter(Identifier.class, new IdentifierTypeAdapter()) .setPrettyPrinting().create(); public static Config CONFIG = new Config(); public static final Path CONFIG_LOCATION = FabricLoader.getInstance().getConfigDir().resolve("spawnable_biomes.json"); public static final String MOD_ID = "make-every-biome-spawnable-lol"; @Override public void onInitialize() { readConfig(); Predicate NORMAL_SPAWNS = b -> b.getBiome().getSpawnSettings().isPlayerSpawnFriendly(); Predicate VALID_BIOMES = b -> { Identifier id = b.getBiomeKey().getValue(); for (Identifier i : CONFIG.biomes) { if (i.equals(id)) { return CONFIG.isWhitelist; } } return !CONFIG.isWhitelist; }; BiomeModifications.create(new Identifier(MOD_ID, "disable_spawns")).add(ModificationPhase.POST_PROCESSING, NORMAL_SPAWNS, s -> { s.getSpawnSettings().setPlayerSpawnFriendly(false); }); BiomeModifications.create(new Identifier(MOD_ID, "spawns")).add(ModificationPhase.POST_PROCESSING, VALID_BIOMES, s -> { s.getSpawnSettings().setPlayerSpawnFriendly(true); }); } private void readConfig() { File cfgFile = CONFIG_LOCATION.toFile(); if (cfgFile.exists()) { try(FileReader fileReader = new FileReader(cfgFile)) { try(JsonReader reader = new JsonReader(fileReader)) { // We use try-with-resources in order to close the readers automatically CONFIG = GSON.fromJson(reader, Config.class); } } catch(IOException e) { e.printStackTrace(); } } else { try { String cfgOut = GSON.toJson(CONFIG); Files.write(CONFIG_LOCATION, cfgOut.getBytes()); } catch(IOException e) { e.printStackTrace(); } } } public static class Config { public boolean isWhitelist = false; public Identifier[] biomes = {}; } public static class IdentifierTypeAdapter extends TypeAdapter { @Override public void write(JsonWriter out, Identifier value) throws IOException { out.value(value.toString()); } @Override public Identifier read(JsonReader in) throws IOException { return new Identifier(in.nextString()); } } } 0 package jp.co.trattoria.chapter2_1; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; public class WordCounterEx implements Runnable{ static final AtomicInteger totalCount = new AtomicInteger(0); static List words = null; private static int threshold = -1; private static int threadCount = -1; private int id; /** * 1トランザクション毎に検索範囲を設定して、スレッドに割り当てて並列処理する。 * ・捜査対象を登録する機能 * ・レンジを設定する機能 * ・カウントする機能 */ public static void setPreSetting(List words, int threshold){ WordCounterEx.words = words; WordCounterEx.threshold = threshold; } public static void startCount(int threadCount){ if(WordCounterEx.words == null || WordCounterEx.threshold < 0 || threadCount < 0){ throw new IllegalArgumentException("引数がなんかダメ"); } WordCounterEx.threadCount = threadCount; for(int i = 0; i WordCounterEx.threshold){ count++; } } totalCount.addAndGet(count); } public static void main(String[] args) throws IOException { String contents = new String(Files.readAllBytes(Paths.get("src\\jp\\co\\trattoria\\capter2_1\\rfc793_1.txt")), StandardCharsets.UTF_8); List words = Arrays.asList(contents.split("[\\P{L}]+")); WordCounterEx.setPreSetting(words, 8); WordCounterEx.startCount(100); // 同時に生成するスレッド上限を指定する System.out.println("counter:" + WordCounterEx.totalCount.get()); } } package com.cloud.vertx.jdbc.impl; import com.cloud.vertx.jdbc.BaseRepository; import io.vertx.core.*; import io.vertx.core.json.JsonObject; import io.vertx.ext.jdbc.JDBCClient; import io.vertx.ext.sql.SQLConnection; /** * jdbc基础操作统一接口实现类。 * * @author zhoudingyun */ public class BaseRepositoryImpl implements BaseRepository { protected JDBCClient client; protected Vertx vertx; protected JsonObject config; /** * 构造方法。 * * @param vertx vertx * @param config config */ public BaseRepositoryImpl(Vertx vertx, JsonObject config) { client = JDBCClient.create(vertx, config); this.vertx = vertx; this.config = config; } /** * A helper methods that generates async handler for SQLConnection * * @return generated handler */ public Handler> connHandler(Handler> h1, Handler h2) { return conn -> { if (conn.succeeded()) { final SQLConnection connection = conn.result(); h2.handle(connection); } else { h1.handle(Future.failedFuture(conn.cause())); } }; } /** * 获取数据库连接。 * * @return Future */ @Override public Future getConnection() { Promise promise = Promise.promise(); client.getConnection(conn -> { if (conn.succeeded()) { final SQLConnection connection = conn.result(); promise.complete(connection); } else { promise.fail(conn.cause()); } }); return promise.future(); } } src/main/java/com/agricraft/agricore/plant/particle/AgriFertilizerParticle.java package com.agricraft.agricore.plant.particle; import com.agricraft.agricore.core.AgriCore; import java.util.Arrays; public class AgriFertilizerParticle extends AgriParticle { private final int amount; private final String[] when; public AgriFertilizerParticle() { super(); this.amount = 2; this.when = new String[0]; } public AgriFertilizerParticle(String particle, double deltaX, double deltaY, double deltaZ, int amount, String[] when) { super(particle, deltaX, deltaY, deltaZ); this.amount = amount; this.when = when; } public boolean shouldSpawn(String type) { return Arrays.asList(when).contains(type); } public int getAmount() { return this.amount; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("\nAgriFertilizerParticle:"); sb.append("\n\t- Particle: ").append(particle); sb.append("\n\t- DeltaX: ").append(delta_x); sb.append("\n\t- DeltaY: ").append(delta_y); sb.append("\n\t- DeltaZ: ").append(delta_z); sb.append("\n\t- Amount: ").append(amount); sb.append("\n\t- When: ").append(Arrays.toString(when)); return sb.toString(); } @Override public boolean validate() { if (!AgriCore.getValidator().isValidResource(this.particle)) { AgriCore.getCoreLogger().info("Invalid AgriFertilizerParticle! Invalid Particle Resource: \"{0}\"!", this.particle); return false; } return true; } } mjlomeli/FoodieFriend package com.interview.androidlib; /** * @author * @version Feburary, 2020 * * This program provides a way to upload images onto the ImageView * using a URL address as a String. Special thanks to "Android developer" * on StackOverflow who strongly influenced the code: * https://stackoverflow.com/questions/2471935/how-to-load-an-imageview-by-url-in-android */ import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.widget.ImageView; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; // Downloads the image from the url public class DownloadImage extends AsyncTask { ImageView bitMap; public DownloadImage(ImageView bitMap){ this.bitMap = bitMap; } @Override protected Bitmap doInBackground(String... urls) { String urls_to_display = urls[0]; Bitmap connect = null; URI uri = null; try { uri = new URI(urls_to_display); } catch (URISyntaxException e) { e.printStackTrace(); } try{ if (uri != null) { InputStream in = new java.net.URL(uri.toString()).openStream(); connect = BitmapFactory.decodeStream(in); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return connect; } protected void onPostExecute(Bitmap map){ if (map != null) bitMap.setImageBitmap(map); } }jonfryd/ImageClustering package dk.impact.imageprocessing.core; import java.io.FileInputStream; import java.io.IOException; import java.util.Vector; import java.io.File; public abstract class FeatureLoaderAbstract implements IFeatureLoader { Vector results; boolean fileLoaded; protected FeatureLoaderAbstract() { results = new Vector(); } public final boolean load(String filename) { FileInputStream fis; File file = new File(filename); results.clear(); fileLoaded = false; try { fis = new FileInputStream(file); fileLoaded = doLoading(fis); fis.close(); } catch (IOException e) { System.out.println(e); return false; } return fileLoaded; } abstract protected boolean doLoading(FileInputStream fis) throws IOException; public Vector getResult() { return results; } public String getSource() { return getClass().getSimpleName(); } } package com.faforever.client.replay; import com.faforever.client.api.dto.Game; import com.faforever.client.api.dto.GamePlayerStats; import com.faforever.client.api.dto.Validity; import com.faforever.client.map.MapBean; import com.faforever.client.mod.FeaturedMod; import com.faforever.client.vault.review.Review; import javafx.beans.Observable; import javafx.beans.property.IntegerProperty; import javafx.beans.property.ListProperty; import javafx.beans.property.MapProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleListProperty; import javafx.beans.property.SimpleMapProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.ObservableMap; import lombok.Data; import org.apache.commons.lang3.StringEscapeUtils; import org.jetbrains.annotations.Nullable; import java.nio.file.Path; import java.time.Duration; import java.time.temporal.Temporal; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static com.faforever.client.util.TimeUtil.fromPythonTime; public class Replay { private final IntegerProperty id; private final StringProperty title; private final MapProperty> teams; private final MapProperty> teamPlayerStats; private final ObjectProperty startTime; private final ObjectProperty endTime; private final ObjectProperty featuredMod; private final ObjectProperty map; private final ObjectProperty replayFile; private final IntegerProperty views; private final ListProperty chatMessages; private final ListProperty gameOptions; private final ListProperty reviews; private final ObjectProperty validity; public Replay(String title) { this(); this.title.set(title); } public Replay() { id = new SimpleIntegerProperty(); title = new SimpleStringProperty(); teams = new SimpleMapProperty<>(FXCollections.observableHashMap()); teamPlayerStats = new SimpleMapProperty<>(FXCollections.observableHashMap()); startTime = new SimpleObjectProperty<>(); endTime = new SimpleObjectProperty<>(); featuredMod = new SimpleObjectProperty<>(); map = new SimpleObjectProperty<>(); replayFile = new SimpleObjectProperty<>(); views = new SimpleIntegerProperty(); chatMessages = new SimpleListProperty<>(FXCollections.observableArrayList()); gameOptions = new SimpleListProperty<>(FXCollections.observableArrayList()); reviews = new SimpleListProperty<>(FXCollections.observableArrayList(param -> new Observable[]{param.scoreProperty(), param.textProperty()})); validity = new SimpleObjectProperty<>(); } public Replay(LocalReplayInfo replayInfo, Path replayFile, FeaturedMod featuredMod, MapBean mapBean) { this(); id.set(replayInfo.getUid()); title.set(StringEscapeUtils.unescapeHtml4(replayInfo.getTitle())); startTime.set(fromPythonTime(replayInfo.getGameTime() > 0 ? replayInfo.getGameTime() : replayInfo.getLaunchedAt())); endTime.set(fromPythonTime(replayInfo.getGameEnd())); this.featuredMod.set(featuredMod); map.set(mapBean); this.replayFile.set(replayFile); if (replayInfo.getTeams() != null) { teams.putAll(replayInfo.getTeams()); } } public static Replay fromDto(Game dto) { Replay replay = new Replay(); replay.setId(Integer.parseInt(dto.getId())); replay.setFeaturedMod(FeaturedMod.fromFeaturedMod(dto.getFeaturedMod())); replay.setTitle(dto.getName()); replay.setStartTime(dto.getStartTime()); Optional.ofNullable(dto.getEndTime()).ifPresent(replay::setEndTime); Optional.ofNullable(dto.getMapVersion()).ifPresent(mapVersion -> replay.setMap(MapBean.fromMapVersionDto(dto.getMapVersion()))); // replay.setViews(dto.getViews()); replay.setTeams(teams(dto)); replay.setTeamPlayerStats(teamPlayerStats(dto)); replay.getReviews().setAll(reviews(dto)); replay.setValidity(dto.getValidity()); return replay; } private static ObservableList reviews(Game dto) { return FXCollections.observableList(dto.getReviews().stream() .map(Review::fromDto) .collect(Collectors.toList())); } private static ObservableMap> teams(Game dto) { ObservableMap> teams = FXCollections.observableHashMap(); dto.getPlayerStats() .forEach(gamePlayerStats -> teams.computeIfAbsent( String.valueOf(gamePlayerStats.getTeam()), s -> new LinkedList<>() ).add(gamePlayerStats.getPlayer().getLogin())); return teams; } private static ObservableMap> teamPlayerStats(Game dto) { ObservableMap> teams = FXCollections.observableHashMap(); dto.getPlayerStats() .forEach(gamePlayerStats -> teams.computeIfAbsent( String.valueOf(gamePlayerStats.getTeam()), s -> new LinkedList<>() ).add(PlayerStats.fromDto(gamePlayerStats))); return teams; } public static String getReplayUrl(int replayId, String baseUrlFormat) { return String.format(baseUrlFormat, replayId); } public Validity getValidity() { return validity.get(); } public void setValidity(Validity validity) { this.validity.set(validity); } public ObjectProperty validityProperty() { return validity; } public Path getReplayFile() { return replayFile.get(); } public void setReplayFile(Path replayFile) { this.replayFile.set(replayFile); } public ObjectProperty replayFileProperty() { return replayFile; } public String getTitle() { return title.get(); } public void setTitle(String title) { this.title.set(title); } public StringProperty titleProperty() { return title; } public ObservableMap> getTeams() { return teams.get(); } public void setTeams(ObservableMap> teams) { this.teams.set(teams); } public MapProperty> teamsProperty() { return teams; } public int getId() { return id.get(); } public void setId(int id) { this.id.set(id); } public IntegerProperty idProperty() { return id; } public Temporal getStartTime() { return startTime.get(); } public void setStartTime(Temporal startTime) { this.startTime.set(startTime); } public ObjectProperty startTimeProperty() { return startTime; } @Nullable public Temporal getEndTime() { return endTime.get(); } public void setEndTime(Temporal endTime) { this.endTime.set(endTime); } public ObjectProperty endTimeProperty() { return endTime; } public FeaturedMod getFeaturedMod() { return featuredMod.get(); } public void setFeaturedMod(FeaturedMod featuredMod) { this.featuredMod.set(featuredMod); } public ObjectProperty featuredModProperty() { return featuredMod; } @Nullable public MapBean getMap() { return map.get(); } public void setMap(MapBean map) { this.map.set(map); } public ObjectProperty mapProperty() { return map; } public int getViews() { return views.get(); } public void setViews(int views) { this.views.set(views); } public IntegerProperty viewsProperty() { return views; } public ObservableList getChatMessages() { return chatMessages.get(); } public void setChatMessages(ObservableList chatMessages) { this.chatMessages.set(chatMessages); } public ListProperty chatMessagesProperty() { return chatMessages; } public ObservableList getGameOptions() { return gameOptions.get(); } public void setGameOptions(ObservableList gameOptions) { this.gameOptions.set(gameOptions); } public ListProperty gameOptionsProperty() { return gameOptions; } public ObservableMap> getTeamPlayerStats() { return teamPlayerStats.get(); } public void setTeamPlayerStats(ObservableMap> teamPlayerStats) { this.teamPlayerStats.set(teamPlayerStats); } public MapProperty> teamPlayerStatsProperty() { return teamPlayerStats; } public ObservableList getReviews() { return reviews.get(); } public static class ChatMessage { private final ObjectProperty time; private final StringProperty sender; private final StringProperty message; public ChatMessage(Duration time, String sender, String message) { this.time = new SimpleObjectProperty<>(time); this.sender = new SimpleStringProperty(sender); this.message = new SimpleStringProperty(message); } public Duration getTime() { return time.get(); } public void setTime(Duration time) { this.time.set(time); } public ObjectProperty timeProperty() { return time; } public String getSender() { return sender.get(); } public void setSender(String sender) { this.sender.set(sender); } public StringProperty senderProperty() { return sender; } public String getMessage() { return message.get(); } public void setMessage(String message) { this.message.set(message); } public StringProperty messageProperty() { return message; } } public static class GameOption { private final StringProperty key; private final StringProperty value; public GameOption(String key, Object value) { this.key = new SimpleStringProperty(key); this.value = new SimpleStringProperty(String.valueOf(value)); } public String getKey() { return key.get(); } public void setKey(String key) { this.key.set(key); } public StringProperty keyProperty() { return key; } public String getValue() { return value.get(); } public void setValue(String value) { this.value.set(value); } public StringProperty valueProperty() { return value; } } @Data public static class PlayerStats { private final int playerId; private final double beforeMean; private final double beforeDeviation; private final Double afterMean; private final Double afterDeviation; private final int score; public static PlayerStats fromDto(GamePlayerStats gamePlayerStats) { return new PlayerStats( Integer.valueOf(gamePlayerStats.getPlayer().getId()), gamePlayerStats.getBeforeMean(), gamePlayerStats.getBeforeDeviation(), gamePlayerStats.getAfterMean() == null ? null : Double.valueOf(gamePlayerStats.getAfterMean()), gamePlayerStats.getAfterDeviation() == null ? null : Double.valueOf(gamePlayerStats.getAfterDeviation()), gamePlayerStats.getScore() ); } } } /** * Copyright (c) 2011, The University of Southampton and the individual contributors. * 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 the University of Southampton 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 OWNER 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.openimaj.image.objectdetection.hog; import java.util.ArrayList; import java.util.List; import org.openimaj.image.FImage; import org.openimaj.image.objectdetection.AbstractMultiScaleObjectDetector; import org.openimaj.math.geometry.shape.Rectangle; public class HOGDetector extends AbstractMultiScaleObjectDetector { protected float scaleFactor = 1.2f; protected HOGClassifier classifier; double threshold = 0.5; public HOGDetector(HOGClassifier classifier, float scaleFactor) { this.classifier = classifier; this.scaleFactor = scaleFactor; } public HOGDetector(HOGClassifier classifier) { this.classifier = classifier; } @Override public List detect(FImage image) { final List results = new ArrayList(); final int imageWidth = image.getWidth(); final int imageHeight = image.getHeight(); classifier.prepare(image); // compute the number of scales to test and the starting factor int nFactors = 0; int startFactor = 0; for (float factor = 1; factor * classifier.width < imageWidth && factor * classifier.height < imageHeight; factor *= scaleFactor) { final float width = factor * classifier.width; final float height = factor * classifier.height; if (width < minSize || height < minSize) { startFactor++; } if (maxSize > 0 && (width > maxSize || height > maxSize)) { break; } nFactors++; } // run the detection at each scale float factor = (float) Math.pow(scaleFactor, startFactor); for (int scaleStep = startFactor; scaleStep < nFactors; factor *= scaleFactor, scaleStep++) { final float ystep = 8 * factor; final int windowWidth = (int) (factor * classifier.width); final int windowHeight = (int) (factor * classifier.height); // determine the spatial range, taking into account any ROI. final int startX = (int) (roi == null ? 0 : Math.max(0, roi.x)); final int startY = (int) (roi == null ? 0 : Math.max(0, roi.y)); final int stopX = Math.round( (roi == null ? imageWidth : Math.min(imageWidth, roi.x + roi.width)) - windowWidth); final int stopY = Math.round((((roi == null ? imageHeight : Math.min(imageHeight, roi.y + roi.height)) - windowHeight))); detectAtScale(startX, stopX, startY, stopY, ystep, windowWidth, windowHeight, results); } return results; } /** * Perform detection at a single scale. Subclasses may override this to * customise the spatial search. The given starting and stopping coordinates * take into account any region of interest set on this detector. * * @param startX * the starting x-ordinate * @param stopX * the stopping x-ordinate * @param startY * the starting y-ordinate * @param stopY * the stopping y-ordinate * @param ystep * the amount to step * @param windowWidth * the window width at the current scale * @param windowHeight * the window height at the current scale * @param results * the list to store detection results in */ protected void detectAtScale(final int startX, final int stopX, final int startY, final int stopY, final float ystep, final int windowWidth, final int windowHeight, final List results) { final Rectangle current = new Rectangle(); for (int iy = startY; iy < stopY; iy += ystep) { for (int ix = startX; ix < stopX; ix += ystep) { current.x = ix; current.y = iy; current.width = windowWidth; current.height = windowHeight; if (classifier.classify(current) > threshold) { results.add(current.clone()); } } } } } maxzuraw/cbn-server-atlas-hackaton package pl.krejnstudio.smarttools.coldbedroomnotifier.domain.repositories; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import pl.krejnstudio.smarttools.coldbedroomnotifier.domain.TempMeasurement; public interface TempMeasurementRepository extends MongoRepository { @Query(value="{'sensor': ?0}") Page findBySensorName(String sensor, Pageable pageable); TempMeasurement findTopBySensorOrderByCreatedOnDesc(String sensor); } QiChen2014/SpringMVCDemo2 package com.springapp.mvc.model; public class Tuser { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_user.id * * @mbggenerated Tue Mar 15 17:28:25 CST 2016 */ private Integer id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_user.name * * @mbggenerated Tue Mar 15 17:28:25 CST 2016 */ private String name; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column t_user.pwd * * @mbggenerated Tue Mar 15 17:28:25 CST 2016 */ private String pwd; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table t_user * * @mbggenerated Tue Mar 15 17:28:25 CST 2016 */ public Tuser(Integer id, String name, String pwd) { this.id = id; this.name = name; this.pwd = ; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table t_user * * @mbggenerated Tue Mar 15 17:28:25 CST 2016 */ public Tuser() { super(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_user.id * * @return the value of t_user.id * * @mbggenerated Tue Mar 15 17:28:25 CST 2016 */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_user.id * * @param id the value for t_user.id * * @mbggenerated Tue Mar 15 17:28:25 CST 2016 */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_user.name * * @return the value of t_user.name * * @mbggenerated Tue Mar 15 17:28:25 CST 2016 */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_user.name * * @param name the value for t_user.name * * @mbggenerated Tue Mar 15 17:28:25 CST 2016 */ public void setName(String name) { this.name = name == null ? null : name.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column t_user.pwd * * @return the value of t_user.pwd * * @mbggenerated Tue Mar 15 17:28:25 CST 2016 */ public String getPwd() { return pwd; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column t_user.pwd * * @param pwd the value for t_user.pwd * * @mbggenerated Tue Mar 15 17:28:25 CST 2016 */ public void setPwd(String pwd) { this.pwd = pwd == null ? null : pwd.trim(); } }package de.bischinger.validation.business; import de.bischinger.validation.model.MyPojo; import org.assertj.core.api.SoftAssertionError; import org.junit.BeforeClass; import org.junit.Test; import static de.bischinger.validation.business.ValidationStrategy.ALWAYS_EQUAL; import static de.bischinger.validation.business.ValidationStrategy.BY_OFFSETMAPPING; public class ValidationStrategyTest { private static MyPojo actual; @BeforeClass public static void before() { actual = new MyPojo(1, 2, 3, 4); } @Test public void should_pass_EqualsStrategy_when_everything_is_equal() throws Exception { ALWAYS_EQUAL.validate(actual, actual, null); } @Test(expected = SoftAssertionError.class) public void should_fail_EqualsStrategy_with_non_equal() throws Exception { ALWAYS_EQUAL.validate(actual, new MyPojo(1, 2, 0, 3), null); } @Test public void should_pass_OffsetStrategy_when_everything_is_equal() throws Exception { BY_OFFSETMAPPING.validate(actual, actual, 0, 0, 0, 0); } @Test public void should_pass_OffsetStrategy_when_everything_is_closeTo() throws Exception { BY_OFFSETMAPPING.validate(actual, new MyPojo(0, 3, 2, 5), 1, 1, 1, 1); } @Test(expected = SoftAssertionError.class) public void should_fail_OffsetStrategy_when_something_is_not_closeTo() throws Exception { BY_OFFSETMAPPING.validate(actual, new MyPojo(0, -5, 2, 10), 1, 1, 1, 1); } }package com.service.serviceImpl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.mmall.dao2.OrderItemMapper2; import com.mmall.pojo.OrderItem; import com.service.IOrderItemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service(value = "iOrderItemServiceImpl2") public class OrderItemServiceImpl2 implements IOrderItemService { @Autowired private OrderItemMapper2 orderItemMapper2; @Override public OrderItem getOrderItemByID(Integer id) { return orderItemMapper2.selectByPrimaryKey(id); } @Override public List getOrderItemList(Integer pageNum, Integer pageSize) { // 设置分页 PageHelper.startPage(pageNum, pageSize); //紧跟着的第一个select方法会被分页(一次性消费),【记住:必须在mapper接口中的方法执行之前设置该分页信息】 //由输出的SQL语句可知,是在原语句后面加了LIMIT List list = orderItemMapper2.selectList(); //分页时,实际返回的结果list类型是Page extends ArrayList。 // 如果想获取更多分页信息,需要强制转换为Page,或用PageInfo对结果进行包装,PageInfo包含了非常全面的分页属性 PageInfo pageInfo = new PageInfo<>(list); // return pageInfo.getList(); return list; } } package com.freud.opc.utgard.cases; import java.net.UnknownHostException; import java.util.concurrent.Executors; import org.jinterop.dcom.common.JIException; import org.openscada.opc.lib.da.Server; import org.openscada.opc.lib.da.browser.Branch; import org.openscada.opc.lib.da.browser.FlatBrowser; import org.openscada.opc.lib.da.browser.Leaf; import com.freud.opc.utgard.BaseConfiguration; /** * * According the clsid get the connection and print all the group and item * information * * @author Freud * */ public class OPCTest2 { public static void main(String[] args) throws Exception { Server server = new Server( BaseConfiguration.getCLSIDConnectionInfomation(), Executors.newSingleThreadScheduledExecutor()); server.connect(); /** 获得OPC连接下所有的Group和Item */ dumpTree(server.getTreeBrowser().browse(), 0); /** 获得OPC下所有的Item */ dumpFlat(server.getFlatBrowser()); server.disconnect(); } /** * 遍历Flat结构的所有Item值 * * @param browser * @throws IllegalArgumentException * @throws UnknownHostException * @throws JIException */ private static void dumpFlat(final FlatBrowser browser) throws IllegalArgumentException, UnknownHostException, JIException { for (String name : browser.browse()) { System.out.println(name); } } /** * 遍历Tree结构 * * @param branch * @param level */ private static void dumpTree(final Branch branch, final int level) { for (final Leaf leaf : branch.getLeaves()) { dumpLeaf(leaf, level); } for (final Branch subBranch : branch.getBranches()) { dumpBranch(subBranch, level); dumpTree(subBranch, level + 1); } } private static String printTab(int level) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < level; i++) { sb.append("\t"); } return sb.toString(); } /** * 打印Item * * @param leaf */ private static void dumpLeaf(final Leaf leaf, final int level) { System.out.println(printTab(level) + "Leaf: " + leaf.getName() + ":" + leaf.getItemId()); } /** * 打印Group * * @param branch */ private static void dumpBranch(final Branch branch, final int level) { System.out.println(printTab(level) + "Branch: " + branch.getName()); } } src/test/java/com/github/rinde/logistics/pdptw/mas/comm/RtSolverBidderTest.java /* * Copyright (C) 2013-2016 , iMinds-DistriNet, KU Leuven * * 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.github.rinde.logistics.pdptw.mas.comm; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import javax.measure.unit.NonSI; import javax.measure.unit.SI; import org.junit.Before; import org.junit.Test; import org.mockito.Matchers; import com.github.rinde.logistics.pdptw.mas.Truck; import com.github.rinde.logistics.pdptw.mas.comm.RtSolverBidder.BidFunctions; import com.github.rinde.logistics.pdptw.mas.route.RoutePlanner; import com.github.rinde.rinsim.central.GlobalStateObject; import com.github.rinde.rinsim.central.Solver; import com.github.rinde.rinsim.central.rt.RealtimeSolver; import com.github.rinde.rinsim.central.rt.RtSimSolverBuilder; import com.github.rinde.rinsim.central.rt.RtSolverModel; import com.github.rinde.rinsim.central.rt.RtStAdapters; import com.github.rinde.rinsim.core.model.DependencyProvider; import com.github.rinde.rinsim.core.model.FakeDependencyProvider; import com.github.rinde.rinsim.core.model.pdp.PDPModel; import com.github.rinde.rinsim.core.model.pdp.PDPModel.ParcelState; import com.github.rinde.rinsim.core.model.pdp.PDPModel.VehicleParcelActionInfo; import com.github.rinde.rinsim.core.model.pdp.PDPModel.VehicleState; import com.github.rinde.rinsim.core.model.pdp.Parcel; import com.github.rinde.rinsim.core.model.pdp.VehicleDTO; import com.github.rinde.rinsim.core.model.time.RealtimeClockController; import com.github.rinde.rinsim.core.model.time.TimeModel; import com.github.rinde.rinsim.event.EventAPI; import com.github.rinde.rinsim.geom.Point; import com.github.rinde.rinsim.pdptw.common.ObjectiveFunction; import com.github.rinde.rinsim.pdptw.common.PDPRoadModel; import com.github.rinde.rinsim.pdptw.common.RouteFollowingVehicle.RouteAdjuster; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /** * * @author */ public class RtSolverBidderTest { @SuppressWarnings("null") RtSolverModel model; @SuppressWarnings("null") DependencyProvider dependencyProvider; @SuppressWarnings("null") RealtimeClockController clock; PDPRoadModel rm; PDPModel pm; @Before public void setUp() { clock = spy((RealtimeClockController) TimeModel.builder() .withRealTime() .build(FakeDependencyProvider.empty())); doNothing().when(clock).switchToRealTime(); doNothing().when(clock).switchToSimulatedTime(); rm = mock(PDPRoadModel.class); when(rm.getSpeedUnit()).thenReturn(NonSI.KILOMETERS_PER_HOUR); when(rm.getDistanceUnit()).thenReturn(SI.KILOMETER); pm = mock(PDPModel.class); when(pm.getEventAPI()).thenReturn(mock(EventAPI.class)); dependencyProvider = FakeDependencyProvider.builder() .add(clock, RealtimeClockController.class) .add(rm, PDPRoadModel.class) .add(pm, PDPModel.class) .build(); model = RtSolverModel.builder().build(dependencyProvider); ((TimeModel) clock).register(model); } // test for cancelling a bid computation. // 1. callForBids // 2. endOfAuction (while computation is still going on) @Test public void test() throws InterruptedException { final RealtimeSolver solver = RtStAdapters.toRealtime(new Solver() { @Override public ImmutableList> solve(GlobalStateObject state) throws InterruptedException { while (true) { System.out.println("computing"); Thread.sleep(100); } } }); final RtSolverBidder bidder = new RtSolverBidder(mock(ObjectiveFunction.class), solver, BidFunctions.PLAIN, -1, true); final RoutePlanner rp = mock(RoutePlanner.class); when(rp.getEventAPI()).thenReturn(mock(EventAPI.class)); final Truck truck = new Truck(VehicleDTO.builder().build(), rp, bidder, mock(RouteAdjuster.class), true); when(rm.getPosition(truck)).thenReturn(new Point(0, 0)); final Parcel a = mock(Parcel.class); when(pm.getContents(truck)).thenReturn(ImmutableSet.of()); final VehicleParcelActionInfo info = mock(VehicleParcelActionInfo.class); when(info.getParcel()).thenReturn(a); when(pm.getVehicleState(truck)).thenReturn(VehicleState.IDLE); when(pm.getVehicleActionInfo(truck)).thenReturn(info); when(pm.getParcelState(a)).thenReturn(ParcelState.AVAILABLE); bidder.init(rm, pm, truck); bidder.setSolverProvider(model.get(RtSimSolverBuilder.class)); final Auctioneer auctioneer = mock(Auctioneer.class); bidder.callForBids(auctioneer, a, 0); assertThat(bidder.cfbQueue).hasSize(1); assertThat(bidder.computing.get()).isTrue(); // give a little time to the solver to start computing Thread.sleep(100); assertThat(bidder.solverHandle.get().isComputing()).isTrue(); assertThat(bidder.computing.get()).isTrue(); // wait a bit more, then announce end of auction Thread.sleep(100); bidder.endOfAuction(auctioneer, a, 0); assertThat(bidder.cfbQueue).isEmpty(); assertThat(bidder.computing.get()).isFalse(); verify(auctioneer, never()).submit(Matchers.any(DoubleBid.class)); } } 0 package fr.polytech.myrpg.characters.items.edible; import fr.polytech.myrpg.characters.Characteristic; /** * This class represents an effect. * * @author * @since 1.0.0 */ public class Effect { /** * The characteristic on which the effect will act. */ private final Characteristic characteristic; /** * The value which will affect the characteristic. */ private final int value; /** * Create an effect. * * @param characteristic * The characteristic on which the effect will act. * @param value * The value which will affect the characteristic. */ public Effect(Characteristic characteristic, int value) { this.characteristic = characteristic; this.value = value; } /** * Get the characteristic. * * @return The characteristic. */ public Characteristic getCharacteristic() { return this.characteristic; } /** * Get the value. * * @return The value. */ public int getValue() { return this.value; } /** * @see java.lang.Object#toString() */ @Override public String toString() { final StringBuilder stringRepresentation = new StringBuilder(); stringRepresentation.append("Effect [characteristic="); stringRepresentation.append(this.characteristic); stringRepresentation.append(", value="); stringRepresentation.append(this.value); stringRepresentation.append("]"); return stringRepresentation.toString(); } } package com.javachat.model; import java.util.ArrayList; import java.util.Collection; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import lombok.Getter; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Table; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Transient; import javax.validation.constraints.Email; @Entity @Table(name = "users") @Getter @Setter public class User implements UserDetails { private static final long serialVersionUID = 5978279130943396080L; @Id @JsonIgnore @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String name; @Email private String email; @ManyToOne private Role role; @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.EAGER) @JsonIgnore private List userImages; private String password; @Transient private UserImage userMainImage; private ZonedDateTime updated; private ZonedDateTime created; @Transient private String passwordConfirm; @Column(name="is_deleted") private boolean isDeleted; @Column(name="fail_times") private int failTimes; @Column(name="is_verified") private boolean isVerified; @Column(name="is_banned") private boolean isBanned; @Transient private boolean agreesTerm = false; @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.LAZY) @JsonIgnore private List boardResponses; @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.LAZY) @JsonIgnore private List boards; @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.LAZY) @JsonIgnore private List userConfirmations; @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.LAZY) @JsonIgnore private List userForgotemails; @Transient private Collection authorities; public String getUsernameNonEmail() { if (this.isDeleted) { return "Deleted user"; } else if (this.isBanned) { return "Banned user"; } return this.name; } public void setUsernameNonEmail(String name) { this.name = name; } @Override public String getUsername() { return this.email; } public void setUsername(String email) { this.email = email; } @Override public String getPassword() { return this.password; } public String getUSStringUpdated() { ZonedDateTime time = this.updated.withZoneSameInstant(ZoneId.of("America/Chicago")); String stringTime = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(time); return stringTime; } public String getUSStringCreated() { ZonedDateTime time = this.created.withZoneSameInstant(ZoneId.of("America/Chicago")); String stringTime = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(time); return stringTime; } public UserImage getUserMainImage() { if (this.userMainImage == null) { this.userMainImage = new UserImage(); } else { for (UserImage image : userImages) { if (image.isMain()) { this.userMainImage = image; break; } } } return this.userMainImage; }; @Override public Collection getAuthorities() { List authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(this.role.getName())); return authorities; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }100-1000 package com.ewolff.microservice.shipping; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable public class Customer { @Column(nullable = false) private Long customerId; @Column(nullable = false) private String name; @Column(nullable = false) private String firstname; public Customer() { super(); customerId = 0l; } public Customer(long customerId, String firstname, String name) { super(); this.customerId = customerId; this.name = name; this.firstname = firstname; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public Long getCustomerId() { return customerId; } public void setCustomerId(Long id) { this.customerId = id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((customerId == null) ? 0 : customerId.hashCode()); result = prime * result + ((firstname == null) ? 0 : firstname.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Customer other = (Customer) obj; if (customerId == null) { if (other.customerId != null) return false; } else if (!customerId.equals(other.customerId)) return false; if (firstname == null) { if (other.firstname != null) return false; } else if (!firstname.equals(other.firstname)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Customer [customerId=" + customerId + ", name=" + name + ", firstname=" + firstname + "]"; } } cagey-config-spi/src/main/java/com/xpcagey/config/spi/IllegalPathException.java package com.xpcagey.config.spi; /** * IllegalPathException should be thrown by a ConfigServiceProvider if a requested path is malformed or unreachable. If * a resource is missing from the indicated path but the path itself is available, the ConfigServiceProvider should * return Optional.empty() instead of throwing an exception. */ public class IllegalPathException extends Exception { public final String path; public final String loader; public IllegalPathException(String loader, String path, Throwable cause) { super("Path ["+path+"] is not supported for loader ["+loader+"]", cause); this.loader = loader; this.path = path; } }package com.g2forge.gearbox.browser.selenium; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import com.g2forge.gearbox.browser.IForm; import com.g2forge.gearbox.browser.ISelect; import com.g2forge.gearbox.browser.ISelect.IOptionSelector; import com.g2forge.gearbox.browser.operation.IOperationBuilder; class Form extends Element implements IForm { public Form(WebElement element, SeleniumBrowser browser) { super(element, browser); assertTag(element, "form"); } @Override public boolean getBoolean(By by) { final WebElement input = element.findElement(by); assertInput(input, "checkbox"); return input.isSelected(); } @Override public List getOptions(By by) { final Select select = new Select(element.findElement(by), browser); return select.getOptions(ISelect.bySelected(true)); } @Override public String getText(By by) { final WebElement input = element.findElement(by); if (!"textarea".equals(input.getTagName().toLowerCase())) assertInput(input, "email", "number", "text", "password", "file"); return input.getAttribute("value"); } @Override public IOperationBuilder operation() { return new OperationBuilder<>(this); } @Override public IForm select(By by, IOptionSelector... selectors) { final Select select = new Select(element.findElement(by), browser); for (IOptionSelector selector : selectors) { select.getOption(selector).setSelected(true); } return this; } @Override public IForm set(By by, boolean selected) { final WebElement input = element.findElement(by); assertInput(input, "checkbox"); if (input.isSelected() != selected) input.click(); return this; } @Override public IForm set(By by, String text) { final WebElement input = element.findElement(by); if (!"textarea".equals(input.getTagName().toLowerCase())) assertInput(input, "email", "number", "text", "password", "file"); input.clear(); input.sendKeys(text); return this; } @Override public IForm submit() { element.submit(); return this; } } package com.java8.nashorn; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; /** * Bind java objects to custom javascript objects. * * @author */ public class Nashorn5 { public static void main(String[] args) throws Exception { ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); engine.eval("load('res/nashorn5.js')"); Invocable invocable = (Invocable) engine; Product product = new Product(); product.setName("Rubber"); product.setPrice(1.99); product.setStock(1037); Object result = invocable.invokeFunction("getValueOfGoods", product); System.out.println(result); } }package org.nem.core.model.observers; import org.nem.core.model.Account; /** * A notification that represents the announcement of a potentially new account. */ public class AccountNotification extends Notification { private final Account account; /** * Creates a new account notification. * * @param account The account. */ public AccountNotification(final Account account) { super(NotificationType.Account); this.account = account; } /** * Gets the potentially new account. * * @return The potentially new account. */ public Account getAccount() { return this.account; } } 1-10 package de.unipaderborn.visuflow.model; /** * This class maintains the edge between instances of two {@link de.unipaderborn.visuflow.model.VFMethod} nodes. * @author * */ public class VFMethodEdge { int id; VFMethod sourceMethod; VFMethod destMethod; public VFMethodEdge(int id, VFMethod sourceMethod, VFMethod destinationMethod) { this.id = id; this.sourceMethod = sourceMethod; this.destMethod = destinationMethod; } public int getId() { return id; } public void setId(int id) { this.id = id; } public VFMethod getSourceMethod() { return sourceMethod; } public void setSourceMethod(VFMethod sourceMethod) { this.sourceMethod = sourceMethod; } public VFMethod getDestMethod() { return destMethod; } public void setDestMethod(VFMethod destMethod) { this.destMethod = destMethod; } public String toString(){ return "Source: " + sourceMethod + " | Destination: " + destMethod; } } /** * Licensed to the zk1931 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 com.github.zk1931.jzab; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import java.util.Iterator; import java.util.HashSet; import java.util.Map; import java.util.Random; import java.util.Set; import org.junit.Assert; import org.junit.Test; import org.slf4j.LoggerFactory; import org.slf4j.Logger; class SnapshotStateMachine implements StateMachine { private static final Logger LOG = LoggerFactory.getLogger(SnapshotStateMachine.class); ConcurrentHashMap state = new ConcurrentHashMap(); CountDownLatch txnsCount; Semaphore semMembership = new Semaphore(0); Semaphore semSnapshot = new Semaphore(0); SnapshotStateMachine(int nTxns) { txnsCount = new CountDownLatch(nTxns); } @Override public ByteBuffer preprocess(Zxid zxid, ByteBuffer message) { return message; } @Override public void deliver(Zxid zxid, ByteBuffer stateUpdate, String clientId, Object ctx) { byte[] buffer = new byte[stateUpdate.remaining()]; stateUpdate.get(buffer); String key = new String(buffer); LOG.debug("Delivering {}", key); this.state.put(key, "value"); txnsCount.countDown(); } @Override public void flushed(Zxid zxid, ByteBuffer flushReq, Object ctx) {} @Override public void save(FileOutputStream fos) { LOG.debug("SAVE is called."); try { ObjectOutputStream out = new ObjectOutputStream(fos); out.writeObject(state); } catch (IOException e) { LOG.error("Caught exception", e); } } @Override public void snapshotDone(String filePath, Object ctx) { LOG.debug("Snapshot is stored at {}", filePath); semSnapshot.release(); } @Override public void restore(FileInputStream fis) { LOG.debug("RESTORE is called."); try { ObjectInputStream oin = new ObjectInputStream(fis); ConcurrentHashMap map = (ConcurrentHashMap)oin.readObject(); state = new ConcurrentHashMap(); Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); state.put((String)pairs.getKey(), (String)pairs.getValue()); } LOG.debug("The size of map after recovery from snapshot file is {}", state.size()); } catch (Exception e) { LOG.error("Caught exception", e); } } @Override public void removed(String serverId, Object ctx) { } @Override public void recovering(PendingRequests pendings) {} @Override public void leading(Set followers, Set members) { semMembership.release(); } @Override public void following(String ld, Set members) { semMembership.release(); } void waitMemberChanged() throws InterruptedException { semMembership.acquire(); } void waitSnapshot() throws InterruptedException { semSnapshot.acquire(); } } /** * Tests for Snapshot. */ public class SnapshotTest extends TestBase { private static final Logger LOG = LoggerFactory.getLogger(SnapshotTest.class); @Test(timeout=10000) public void testSnapshotSingleServer() throws Exception { final int nTxns = 20; QuorumTestCallback cb1 = new QuorumTestCallback(); SnapshotStateMachine st1 = new SnapshotStateMachine(nTxns); String server = getUniqueHostPort(); ZabConfig config = new ZabConfig(); // For testing purpose, set the threshold to 32 bytes.. config.setLogDir(getDirectory().getPath()); Zab zab = new Zab(st1, config, server, server); st1.waitMemberChanged(); for (int i = 0; i < nTxns; ++i) { zab.send(ByteBuffer.wrap(("txns" + i).getBytes()), null); } st1.txnsCount.await(); // Take the snapshot after all transaction gets delivered. zab.takeSnapshot(null); st1.waitSnapshot(); Thread.sleep(1000); zab.shutdown(); SnapshotStateMachine stNew = new SnapshotStateMachine(nTxns); zab = new Zab(stNew, config); stNew.waitMemberChanged(); // Make sure restored state is consistent. Assert.assertEquals(st1.state, stNew.state); zab.shutdown(); } @Test(timeout=20000) public void testSnapshotCluster() throws Exception { final int nTxns = 20; QuorumTestCallback cb1 = new QuorumTestCallback(); SnapshotStateMachine st1 = new SnapshotStateMachine(nTxns); QuorumTestCallback cb2 = new QuorumTestCallback(); SnapshotStateMachine st2 = new SnapshotStateMachine(nTxns); String server1 = getUniqueHostPort(); String server2 = getUniqueHostPort(); ZabConfig config1 = new ZabConfig(); ZabConfig config2 = new ZabConfig(); config1.setLogDir(getDirectory().getPath() + File.separator + server1); config2.setLogDir(getDirectory().getPath() + File.separator + server2); Zab zab1 = new Zab(st1, config1, server1, server1); st1.waitMemberChanged(); Zab zab2 = new Zab(st2, config2, server2, server1); st2.waitMemberChanged(); int snapIdx = new Random().nextInt(nTxns); for (int i = 0; i < nTxns; ++i) { zab1.send(ByteBuffer.wrap(("txns" + i).getBytes()), null); Thread.sleep(5); if (i == snapIdx) { zab1.takeSnapshot(null); zab2.takeSnapshot(null); st1.waitSnapshot(); st2.waitSnapshot(); } } st1.txnsCount.await(); st2.txnsCount.await(); // Shutdown both servers. zab1.shutdown(); zab2.shutdown(); // Restarts them. SnapshotStateMachine stNew1 = new SnapshotStateMachine(nTxns); SnapshotStateMachine stNew2 = new SnapshotStateMachine(nTxns); zab1 = new Zab(stNew1, config1); zab2 = new Zab(stNew2, config2); stNew1.waitMemberChanged(); stNew2.waitMemberChanged(); // Make sure the states are consistent. Assert.assertEquals(st1.state, stNew1.state); Assert.assertEquals(st2.state, stNew2.state); Assert.assertEquals(stNew1.state, stNew2.state); zab1.shutdown(); zab2.shutdown(); } @Test(timeout=20000) public void testSnapshotSynchronizationCase1() throws Exception { // Starts server1, sends transactions txn1,txn2 ... txnn. // Starts server2 joins server1, the snapshot will be used to synchronize // server2. In the end, we verify the two state machines have the same state final int nTxns = 50; QuorumTestCallback cb1 = new QuorumTestCallback(); SnapshotStateMachine st1 = new SnapshotStateMachine(nTxns); QuorumTestCallback cb2 = new QuorumTestCallback(); SnapshotStateMachine st2 = new SnapshotStateMachine(nTxns); String server1 = getUniqueHostPort(); String server2 = getUniqueHostPort(); ZabConfig config1 = new ZabConfig(); config1.setLogDir(getDirectory().getPath() + File.separator + server1); ZabConfig config2 = new ZabConfig(); config2.setLogDir(getDirectory().getPath() + File.separator + server2); Zab zab1 = new Zab(st1, config1, server1, server1); st1.waitMemberChanged(); int snapIdx = new Random().nextInt(nTxns); for (int i = 0; i < nTxns; ++i) { zab1.send(ByteBuffer.wrap(("txns" + i).getBytes()), null); // Sleep a while to avoid all the transactions batch together. Thread.sleep(5); if (i == snapIdx) { zab1.takeSnapshot(null); st1.waitSnapshot(); } } st1.txnsCount.await(); // Server2 joins in. Zab zab2 = new Zab(st2, config2, server2, server1); st2.waitMemberChanged(); Assert.assertEquals(st1.state, st2.state); zab2.shutdown(); st2 = new SnapshotStateMachine(nTxns); // zab2 recovers. zab2 = new Zab(st2, config2); st2.waitMemberChanged(); // After recovery, we verify they still have same states. Assert.assertEquals(st1.state, st2.state); zab2.shutdown(); zab1.shutdown(); } @Test(timeout=20000) public void testSnapshotSynchronizationCase2() throws Exception { QuorumTestCallback cb1 = new QuorumTestCallback(); QuorumTestCallback cb2 = new QuorumTestCallback(); SnapshotStateMachine st1 = new SnapshotStateMachine(0); SnapshotStateMachine st2 = new SnapshotStateMachine(0); String server1 = getUniqueHostPort(); String server2 = getUniqueHostPort(); String server3 = getUniqueHostPort(); Set peers = new HashSet<>(); peers.add(server1); peers.add(server2); peers.add(server3); PersistentState state1 = makeInitialState(server1, 5); state1.setAckEpoch(0); PersistentState state2 = makeInitialState(server2, 1); state2.setAckEpoch(0); ZabConfig config1 = new ZabConfig(); ZabConfig config2 = new ZabConfig(); Zab zab1 = new Zab(st1, config1, server1, peers, state1, cb1, null); Zab zab2 = new Zab(st2, config2, server2, peers, state2, cb2, null); cb1.waitBroadcasting(); cb2.waitBroadcasting(); Assert.assertEquals(cb1.initialHistory.size(), 5); Assert.assertEquals(cb1.initialHistory.get(0).getZxid(), new Zxid(0, 0)); Assert.assertTrue(cb2.initialHistory.size() == 5); Assert.assertEquals(cb2.initialHistory.get(0).getZxid(), new Zxid(0, 0)); // server1 gonna take snapshot. zab1.takeSnapshot(null); st1.waitSnapshot(); // Make sure server1 does take snapshot. Assert.assertEquals(new Zxid(0, 4), state1.getSnapshotZxid()); // Shutdown zab2. zab2.shutdown(); // Mannuly truncate all the logs of server2. state2.getLog().truncate(Zxid.ZXID_NOT_EXIST); st2 = new SnapshotStateMachine(0); cb2 = new QuorumTestCallback(); // Restarts server2. zab2 = new Zab(st2, config2, state2, cb2, null); cb2.waitBroadcasting(); // server2 should get snapshot file synchronized from server1. Assert.assertEquals(new Zxid(0, 4), state2.getSnapshotZxid()); // Eventually they will have same state. Assert.assertEquals(st2.state, st1.state); zab1.shutdown(); zab2.shutdown(); } @Test(timeout=20000) public void testSnapshotSynchronizationCase3() throws Exception { QuorumTestCallback cb1 = new QuorumTestCallback(); QuorumTestCallback cb2 = new QuorumTestCallback(); SnapshotStateMachine st1 = new SnapshotStateMachine(0); SnapshotStateMachine st2 = new SnapshotStateMachine(0); String server1 = getUniqueHostPort(); String server2 = getUniqueHostPort(); String server3 = getUniqueHostPort(); Set peers = new HashSet<>(); peers.add(server1); peers.add(server2); peers.add(server3); PersistentState state1 = makeInitialState(server1, 5); state1.setProposedEpoch(2); state1.setAckEpoch(2); PersistentState state2 = makeInitialState(server2, 1); state2.setAckEpoch(0); ZabConfig config1 = new ZabConfig(); ZabConfig config2 = new ZabConfig(); Zab zab1 = new Zab(st1, config1, server1, peers, state1, cb1, null); Zab zab2 = new Zab(st2, config2, server2, peers, state2, cb2, null); cb1.waitBroadcasting(); cb2.waitBroadcasting(); Assert.assertEquals(cb1.initialHistory.size(), 5); Assert.assertEquals(cb1.initialHistory.get(0).getZxid(), new Zxid(0, 0)); Assert.assertTrue(cb2.initialHistory.size() == 5); Assert.assertEquals(cb2.initialHistory.get(0).getZxid(), new Zxid(0, 0)); // server1 takes snapshot. zab1.takeSnapshot(null); st1.waitSnapshot(); // Make sure server1 did take snapshot. Assert.assertEquals(new Zxid(0, 4), state1.getSnapshotZxid()); // Shutdown zab2. zab2.shutdown(); // Add one more transaction to make server1 and server2 have different // epochs. appendTxns(state2.getLog(), new Zxid(1, 0), 1); // Reset epoch number to make sure server1 becomes leader. state2.setProposedEpoch(0); state2.setAckEpoch(0); st2 = new SnapshotStateMachine(0); cb2 = new QuorumTestCallback(); // Restarts server2. zab2 = new Zab(st2, config2, state2, cb2, null); cb2.waitBroadcasting(); // server2 should get snapshot file synchronized from server1. Assert.assertEquals(new Zxid(0, 4), state2.getSnapshotZxid()); // Eventuall they will have same state. Assert.assertEquals(st2.state, st1.state); zab1.shutdown(); zab2.shutdown(); } } src/cellsociety/cellstate/CellState.java package cellsociety.cellstate; import javafx.scene.paint.Paint; public interface CellState { Paint getColor(); } package nl.alowaniak.runelite.musicreplacer; import com.google.gson.reflect.TypeToken; import lombok.extern.slf4j.Slf4j; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import static net.runelite.http.api.RuneLiteAPI.GSON; import static nl.alowaniak.runelite.musicreplacer.MusicReplacerPlugin.MUSIC_REPLACER_API; @Slf4j @Singleton class YouTubeSearcher { @Inject private OkHttpClient http; @Inject @Named(MusicReplacerPlugin.MUSIC_REPLACER_EXECUTOR) private ExecutorService executor; /** * @param term the {@code term} to search for. * @param resultCollector will be called with the found results. */ public void search(String term, Consumer> resultCollector) { executor.submit(() -> resultCollector.accept(getSearchResults(term))); } private List getSearchResults(String term) { try (Response res = getSearchResponse(term)) { if (!res.isSuccessful()) throw new IOException(res.code() + ": " + res.message() + " " + res.body().string()); return GSON.fromJson(res.body().string(), new TypeToken>(){}.getType()); } catch (IOException e) { log.warn("Something went wrong when searching for " + term, e); return Collections.emptyList(); } } private Response getSearchResponse(String term) throws IOException { return http.newBuilder().readTimeout(1, TimeUnit.MINUTES) .build() .newCall(new Request.Builder() .url(MUSIC_REPLACER_API + "search/" + URLEncoder.encode(term, StandardCharsets.UTF_8.toString())) .build() ).execute(); } } /* * Copyright 2020 IBM Corp. 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 com.ibm.watson.data.client.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Objects; /** * AssetFileMetadata */ public class AssetFileMetadata { private String path; private String etag; private Integer size; private String type; private String mimeType; private String lastModifed; public AssetFileMetadata path(String path) { this.path = path; return this; } /** * The path of the file. * @return path **/ @javax.annotation.Nullable @JsonProperty("path") @JsonInclude(value = JsonInclude.Include.NON_NULL) public String getPath() { return path; } public void setPath(String path) { this.path = path; } public AssetFileMetadata etag(String etag) { this.etag = etag; return this; } /** * ETAG for the resource. * @return etag **/ @javax.annotation.Nullable @JsonProperty("etag") @JsonInclude(value = JsonInclude.Include.NON_NULL) public String getEtag() { return etag; } public void setEtag(String etag) { this.etag = etag; } public AssetFileMetadata size(Integer size) { this.size = size; return this; } /** * The size in bytes for files. The number of resource for folders. * @return size **/ @javax.annotation.Nullable @JsonProperty("size") @JsonInclude(value = JsonInclude.Include.NON_NULL) public Integer getSize() { return size; } public void setSize(Integer size) { this.size = size; } public AssetFileMetadata type(String type) { this.type = type; return this; } /** * Either folder or file. * @return type **/ @javax.annotation.Nullable @JsonProperty("type") @JsonInclude(value = JsonInclude.Include.NON_NULL) public String getType() { return type; } public void setType(String type) { this.type = type; } public AssetFileMetadata mimeType(String mimeType) { this.mimeType = mimeType; return this; } /** * If the resource is a file this will be the mime type of the file. * @return mimeType **/ @javax.annotation.Nullable @JsonProperty("mime_type") @JsonInclude(value = JsonInclude.Include.NON_NULL) public String getMimeType() { return mimeType; } public void setMimeType(String mimeType) { this.mimeType = mimeType; } public AssetFileMetadata lastModifed(String lastModifed) { this.lastModifed = lastModifed; return this; } /** * Time when the asset was last modified, defaults to create date. Returned in * json timestamp format. (Yes, this is spelled wrong, as it is spelled wrong in the API itself.) * @return lastModifed **/ @javax.annotation.Nullable @JsonProperty("last_modifed") @JsonInclude(value = JsonInclude.Include.NON_NULL) public String getLastModifed() { return lastModifed; } public void setLastModifed(String lastModifed) { this.lastModifed = lastModifed; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AssetFileMetadata assetFileMetadata = (AssetFileMetadata)o; return Objects.equals(this.path, assetFileMetadata.path) && Objects.equals(this.etag, assetFileMetadata.etag) && Objects.equals(this.size, assetFileMetadata.size) && Objects.equals(this.type, assetFileMetadata.type) && Objects.equals(this.mimeType, assetFileMetadata.mimeType) && Objects.equals(this.lastModifed, assetFileMetadata.lastModifed); } @Override public int hashCode() { return Objects.hash(path, etag, size, type, mimeType, lastModifed); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AssetFileMetadata {\n"); sb.append(" path: ").append(toIndentedString(path)).append("\n"); sb.append(" etag: ").append(toIndentedString(etag)).append("\n"); sb.append(" size: ").append(toIndentedString(size)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" mimeType: ").append(toIndentedString(mimeType)).append("\n"); sb.append(" lastModifed: ").append(toIndentedString(lastModifed)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } 0 // Generated by OABuilder package com.cdi.model; import java.util.logging.*; import com.viaoa.object.*; import com.viaoa.annotation.*; import com.viaoa.datasource.*; import com.viaoa.hub.*; import com.viaoa.util.*; import com.viaoa.util.filter.*; import com.cdi.model.oa.*; import com.cdi.model.oa.propertypath.*; import com.cdi.model.oa.search.*; import com.cdi.model.oa.filter.*; import com.cdi.model.search.*; import com.cdi.model.filter.*; import com.cdi.delegate.ModelDelegate; import com.cdi.resource.Resource; public class ItemModel extends OAObjectModel { private static Logger LOG = Logger.getLogger(ItemModel.class.getName()); // Hubs protected Hub hub; // selected items protected Hub hubMultiSelect; // detail hubs protected Hub hubFileInfo; protected Hub hubImageStore; protected Hub hubItemCategory; protected Hub hubMold; protected Hub hubProductionArea; protected Hub hubOpenOrderItems; protected Hub hubWebItems; // ObjectModels protected FileInfoModel modelFileInfo; protected ImageStoreModel modelImageStore; protected ItemCategoryModel modelItemCategory; protected MoldModel modelMold; protected ProductionAreaModel modelProductionArea; protected OrderItemModel modelOpenOrderItems; protected WebItemModel modelWebItems; // SearchModels used for references protected ItemCategorySearchModel modelItemCategorySearch; protected MoldSearchModel modelMoldSearch; protected WebItemSearchModel modelWebItemsSearch; public ItemModel() { setDisplayName("Item"); setPluralDisplayName("Items"); } public ItemModel(Hub hubItem) { this(); if (hubItem != null) HubDelegate.setObjectClass(hubItem, Item.class); this.hub = hubItem; } public ItemModel(Item item) { this(); getHub().add(item); getHub().setPos(0); } public Hub getOriginalHub() { return getHub(); } public Hub getFileInfoHub() { if (hubFileInfo != null) return hubFileInfo; hubFileInfo = getHub().getDetailHub(Item.P_FileInfo); return hubFileInfo; } public Hub getImageStoreHub() { if (hubImageStore != null) return hubImageStore; hubImageStore = getHub().getDetailHub(Item.P_ImageStore); return hubImageStore; } protected HubhubRootItemCategory; public Hub getRootItemCategoryHub() { if (hubRootItemCategory != null) return hubRootItemCategory; hubRootItemCategory = ModelDelegate.getItemCategories().createSharedHub(); return hubRootItemCategory; } public Hub getItemCategoryHub() { if (hubItemCategory != null) return hubItemCategory; hubItemCategory = new Hub<>(ItemCategory.class); hubItemCategory.setSharedHub(getRootItemCategoryHub()); hubItemCategory.setLinkHub(getHub(), Item.P_ItemCategory); return hubItemCategory; } public Hub getMoldHub() { if (hubMold != null) return hubMold; hubMold = getHub().getDetailHub(Item.P_Mold); return hubMold; } public Hub getProductionAreaHub() { if (hubProductionArea != null) return hubProductionArea; hubProductionArea = new Hub<>(ProductionArea.class); Hub hub = ModelDelegate.getProductionAreas(); HubCopy hc = new HubCopy<>(hub, hubProductionArea, false); hubProductionArea.setLinkHub(getHub(), Item.P_ProductionArea); return hubProductionArea; } public Hub getOpenOrderItems() { if (hubOpenOrderItems == null) { hubOpenOrderItems = getHub().getDetailHub(Item.P_OpenOrderItems); } return hubOpenOrderItems; } public Hub getWebItems() { if (hubWebItems == null) { hubWebItems = getHub().getDetailHub(Item.P_WebItems); } return hubWebItems; } public Item getItem() { return getHub().getAO(); } public Hub getHub() { if (hub == null) { hub = new Hub(Item.class); } return hub; } public Hub getMultiSelectHub() { if (hubMultiSelect == null) { hubMultiSelect = new Hub(Item.class); } return hubMultiSelect; } public FileInfoModel getFileInfoModel() { if (modelFileInfo != null) return modelFileInfo; modelFileInfo = new FileInfoModel(getFileInfoHub()); modelFileInfo.setDisplayName("File Info"); modelFileInfo.setPluralDisplayName("File Infos"); modelFileInfo.setForJfc(getForJfc()); modelFileInfo.setAllowNew(true); modelFileInfo.setAllowSave(true); modelFileInfo.setAllowAdd(false); modelFileInfo.setAllowRemove(false); modelFileInfo.setAllowClear(false); modelFileInfo.setAllowDelete(true); modelFileInfo.setAllowSearch(false); modelFileInfo.setAllowHubSearch(true); modelFileInfo.setAllowGotoEdit(true); modelFileInfo.setViewOnly(getViewOnly()); // call Item.onEditQueryFileInfo(FileInfoModel) to be able to customize this model OAObjectCallbackDelegate.onObjectCallbackModel(Item.class, Item.P_FileInfo, modelFileInfo); return modelFileInfo; } public ImageStoreModel getImageStoreModel() { if (modelImageStore != null) return modelImageStore; modelImageStore = new ImageStoreModel(getImageStoreHub()); modelImageStore.setDisplayName("Image Store"); modelImageStore.setPluralDisplayName("Images"); modelImageStore.setForJfc(getForJfc()); modelImageStore.setAllowNew(false); modelImageStore.setAllowSave(true); modelImageStore.setAllowAdd(false); modelImageStore.setAllowRemove(false); modelImageStore.setAllowClear(false); modelImageStore.setAllowDelete(false); modelImageStore.setAllowSearch(false); modelImageStore.setAllowHubSearch(true); modelImageStore.setAllowGotoEdit(true); modelImageStore.setViewOnly(getViewOnly()); // call Item.onEditQueryImageStore(ImageStoreModel) to be able to customize this model OAObjectCallbackDelegate.onObjectCallbackModel(Item.class, Item.P_ImageStore, modelImageStore); return modelImageStore; } public ItemCategoryModel getItemCategoryModel() { if (modelItemCategory != null) return modelItemCategory; modelItemCategory = new ItemCategoryModel(getRootItemCategoryHub(), getItemCategoryHub()); modelItemCategory.setDisplayName("Item Category"); modelItemCategory.setPluralDisplayName("Item Categories"); modelItemCategory.setForJfc(getForJfc()); modelItemCategory.setAllowNew(false); modelItemCategory.setAllowSave(true); modelItemCategory.setAllowAdd(false); modelItemCategory.setAllowRemove(true); modelItemCategory.setAllowClear(true); modelItemCategory.setAllowDelete(false); modelItemCategory.setAllowSearch(true); modelItemCategory.setAllowHubSearch(true); modelItemCategory.setAllowGotoEdit(false); OALinkInfo li = HubDetailDelegate.getLinkInfoFromDetailToMaster(getOriginalHub()); modelItemCategory.setCreateUI(li == null || !Item.P_ItemCategory.equals(li.getName()) ); modelItemCategory.setViewOnly(true); // call Item.onEditQueryItemCategory(ItemCategoryModel) to be able to customize this model OAObjectCallbackDelegate.onObjectCallbackModel(Item.class, Item.P_ItemCategory, modelItemCategory); return modelItemCategory; } public MoldModel getMoldModel() { if (modelMold != null) return modelMold; modelMold = new MoldModel(getMoldHub()); modelMold.setDisplayName("Mold"); modelMold.setPluralDisplayName("Molds"); modelMold.setForJfc(getForJfc()); modelMold.setAllowNew(true); modelMold.setAllowSave(true); modelMold.setAllowAdd(false); modelMold.setAllowRemove(true); modelMold.setAllowClear(true); modelMold.setAllowDelete(false); modelMold.setAllowSearch(true); modelMold.setAllowHubSearch(true); modelMold.setAllowGotoEdit(true); OALinkInfo li = HubDetailDelegate.getLinkInfoFromDetailToMaster(getOriginalHub()); modelMold.setCreateUI(li == null || !Item.P_Mold.equals(li.getName()) ); modelMold.setViewOnly(getViewOnly()); // call Item.onEditQueryMold(MoldModel) to be able to customize this model OAObjectCallbackDelegate.onObjectCallbackModel(Item.class, Item.P_Mold, modelMold); return modelMold; } public ProductionAreaModel getProductionAreaModel() { if (modelProductionArea != null) return modelProductionArea; modelProductionArea = new ProductionAreaModel(getProductionAreaHub()); modelProductionArea.setDisplayName("Production Area"); modelProductionArea.setPluralDisplayName("Production Areas"); modelProductionArea.setForJfc(getForJfc()); modelProductionArea.setAllowNew(false); modelProductionArea.setAllowSave(true); modelProductionArea.setAllowAdd(false); modelProductionArea.setAllowRemove(false); modelProductionArea.setAllowClear(false); modelProductionArea.setAllowDelete(false); modelProductionArea.setAllowSearch(false); modelProductionArea.setAllowHubSearch(true); modelProductionArea.setAllowGotoEdit(false); OALinkInfo li = HubDetailDelegate.getLinkInfoFromDetailToMaster(getOriginalHub()); modelProductionArea.setCreateUI(li == null || !Item.P_ProductionArea.equals(li.getName()) ); modelProductionArea.setViewOnly(true); // call Item.onEditQueryProductionArea(ProductionAreaModel) to be able to customize this model OAObjectCallbackDelegate.onObjectCallbackModel(Item.class, Item.P_ProductionArea, modelProductionArea); return modelProductionArea; } public OrderItemModel getOpenOrderItemsModel() { if (modelOpenOrderItems != null) return modelOpenOrderItems; modelOpenOrderItems = new OrderItemModel(getOpenOrderItems()); modelOpenOrderItems.setDisplayName("Order Item"); modelOpenOrderItems.setPluralDisplayName("Order Items"); if (HubDetailDelegate.getLinkInfoFromMasterToDetail(getOriginalHub().getMasterHub()) == HubDetailDelegate.getLinkInfoFromMasterToDetail(getOpenOrderItems())) { modelOpenOrderItems.setCreateUI(false); } modelOpenOrderItems.setForJfc(getForJfc()); modelOpenOrderItems.setAllowNew(false); modelOpenOrderItems.setAllowSave(false); modelOpenOrderItems.setAllowAdd(false); modelOpenOrderItems.setAllowMove(false); modelOpenOrderItems.setAllowRemove(false); modelOpenOrderItems.setAllowDelete(false); modelOpenOrderItems.setAllowSearch(false); modelOpenOrderItems.setAllowHubSearch(true); modelOpenOrderItems.setAllowGotoEdit(true); modelOpenOrderItems.setViewOnly(getViewOnly()); modelOpenOrderItems.setAllowTableFilter(true); modelOpenOrderItems.setAllowTableSorting(true); // default is always false for these, can be turned by custom code in editQuery call (below) modelOpenOrderItems.setAllowMultiSelect(false); modelOpenOrderItems.setAllowCopy(false); modelOpenOrderItems.setAllowCut(false); modelOpenOrderItems.setAllowPaste(false); // call Item.onEditQueryOpenOrderItems(OrderItemModel) to be able to customize this model OAObjectCallbackDelegate.onObjectCallbackModel(Item.class, Item.P_OpenOrderItems, modelOpenOrderItems); return modelOpenOrderItems; } public WebItemModel getWebItemsModel() { if (modelWebItems != null) return modelWebItems; modelWebItems = new WebItemModel(getWebItems()); modelWebItems.setDisplayName("Web Item"); modelWebItems.setPluralDisplayName("Web Items"); if (HubDetailDelegate.getLinkInfoFromMasterToDetail(getOriginalHub().getMasterHub()) == HubDetailDelegate.getLinkInfoFromMasterToDetail(getWebItems())) { modelWebItems.setCreateUI(false); } modelWebItems.setForJfc(getForJfc()); modelWebItems.setAllowNew(false); modelWebItems.setAllowSave(true); modelWebItems.setAllowAdd(true); modelWebItems.setAllowMove(false); modelWebItems.setAllowRemove(true); modelWebItems.setAllowDelete(false); modelWebItems.setAllowSearch(false); modelWebItems.setAllowHubSearch(true); modelWebItems.setAllowGotoEdit(true); modelWebItems.setViewOnly(getViewOnly()); modelWebItems.setAllowTableFilter(true); modelWebItems.setAllowTableSorting(true); // default is always false for these, can be turned by custom code in editQuery call (below) modelWebItems.setAllowMultiSelect(false); modelWebItems.setAllowCopy(false); modelWebItems.setAllowCut(false); modelWebItems.setAllowPaste(false); // call Item.onEditQueryWebItems(WebItemModel) to be able to customize this model OAObjectCallbackDelegate.onObjectCallbackModel(Item.class, Item.P_WebItems, modelWebItems); return modelWebItems; } public ItemCategorySearchModel getItemCategorySearchModel() { if (modelItemCategorySearch != null) return modelItemCategorySearch; modelItemCategorySearch = new ItemCategorySearchModel(); return modelItemCategorySearch; } public MoldSearchModel getMoldSearchModel() { if (modelMoldSearch != null) return modelMoldSearch; modelMoldSearch = new MoldSearchModel(); return modelMoldSearch; } public WebItemSearchModel getWebItemsSearchModel() { if (modelWebItemsSearch != null) return modelWebItemsSearch; modelWebItemsSearch = new WebItemSearchModel(); return modelWebItemsSearch; } public HubCopy createHubCopy() { Hub hubItemx = new Hub<>(Item.class); HubCopy hc = new HubCopy<>(getHub(), hubItemx, true); return hc; } public ItemModel createCopy() { ItemModel mod = new ItemModel(createHubCopy().getHub()); return mod; } } package examples.async; import com.vtence.molecule.WebServer; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.net.http.HttpClient; import java.net.http.HttpRequest; import static com.vtence.molecule.testing.http.HttpResponseAssert.assertThat; import static java.net.http.HttpResponse.BodyHandlers.ofString; public class AsyncTest { AsyncExample example = new AsyncExample(); WebServer server = WebServer.create(9999); HttpClient client = HttpClient.newHttpClient(); HttpRequest.Builder request = HttpRequest.newBuilder(server.uri()); @Before public void startServer() throws IOException { example.run(server); } @After public void stopServer() throws IOException { server.stop(); } @Test public void servingContentFromADifferentThreadAfterALongRunningOperation() throws Exception { var response = client.send(request.build(), ofString()); assertThat(response).hasBody("After waiting for a long time..."); } }google-play-game-services/src/org/robovm/bindings/gpgs/GPGAchievementMetadataBlock.java package org.robovm.bindings.gpgs; import org.robovm.apple.foundation.NSError; public interface GPGAchievementMetadataBlock { /** Runs this block. */ void invoke (GPGAchievementMetadata metadata, NSError error); } tacsio/jornada-dev-eficiente1-10 package io.tacsio.country.dto; import io.tacsio.country.Pais; import lombok.Getter; @Getter public class PaisResponse { private Long id; private String nome; public PaisResponse(Pais pais) { this.id = pais.getId(); this.nome = pais.getNome(); } @Override public String toString() { return "PaísResponse [nome=" + nome + "]"; } }src/main/java/irismod/service/Tx.java // Generated by the protocol buffer compiler. DO NOT EDIT! // source: service/tx.proto package irismod.service; public final class Tx { private Tx() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } public interface MsgDefineServiceOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgDefineService) com.google.protobuf.MessageOrBuilder { /** * string name = 1; * @return The name. */ java.lang.String getName(); /** * string name = 1; * @return The bytes for name. */ com.google.protobuf.ByteString getNameBytes(); /** * string description = 2; * @return The description. */ java.lang.String getDescription(); /** * string description = 2; * @return The bytes for description. */ com.google.protobuf.ByteString getDescriptionBytes(); /** * repeated string tags = 3; * @return A list containing the tags. */ java.util.List getTagsList(); /** * repeated string tags = 3; * @return The count of tags. */ int getTagsCount(); /** * repeated string tags = 3; * @param index The index of the element to return. * @return The tags at the given index. */ java.lang.String getTags(int index); /** * repeated string tags = 3; * @param index The index of the value to return. * @return The bytes of the tags at the given index. */ com.google.protobuf.ByteString getTagsBytes(int index); /** * string author = 4; * @return The author. */ java.lang.String getAuthor(); /** * string author = 4; * @return The bytes for author. */ com.google.protobuf.ByteString getAuthorBytes(); /** * string author_description = 5 [(.gogoproto.moretags) = "yaml:\"author_description\""]; * @return The authorDescription. */ java.lang.String getAuthorDescription(); /** * string author_description = 5 [(.gogoproto.moretags) = "yaml:\"author_description\""]; * @return The bytes for authorDescription. */ com.google.protobuf.ByteString getAuthorDescriptionBytes(); /** * string schemas = 6; * @return The schemas. */ java.lang.String getSchemas(); /** * string schemas = 6; * @return The bytes for schemas. */ com.google.protobuf.ByteString getSchemasBytes(); } /** *
   * MsgDefineService defines an SDK message for defining a new service.
   * 
* * Protobuf type {@code irismod.service.MsgDefineService} */ public static final class MsgDefineService extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgDefineService) MsgDefineServiceOrBuilder { private static final long serialVersionUID = 0L; // Use MsgDefineService.newBuilder() to construct. private MsgDefineService(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgDefineService() { name_ = ""; description_ = ""; tags_ = com.google.protobuf.LazyStringArrayList.EMPTY; author_ = ""; authorDescription_ = ""; schemas_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgDefineService(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgDefineService( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); name_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); description_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000001) != 0)) { tags_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000001; } tags_.add(s); break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); author_ = s; break; } case 42: { java.lang.String s = input.readStringRequireUtf8(); authorDescription_ = s; break; } case 50: { java.lang.String s = input.readStringRequireUtf8(); schemas_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { tags_ = tags_.getUnmodifiableView(); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgDefineService_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgDefineService_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgDefineService.class, irismod.service.Tx.MsgDefineService.Builder.class); } public static final int NAME_FIELD_NUMBER = 1; private volatile java.lang.Object name_; /** * string name = 1; * @return The name. */ @java.lang.Override public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } } /** * string name = 1; * @return The bytes for name. */ @java.lang.Override public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DESCRIPTION_FIELD_NUMBER = 2; private volatile java.lang.Object description_; /** * string description = 2; * @return The description. */ @java.lang.Override public java.lang.String getDescription() { java.lang.Object ref = description_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); description_ = s; return s; } } /** * string description = 2; * @return The bytes for description. */ @java.lang.Override public com.google.protobuf.ByteString getDescriptionBytes() { java.lang.Object ref = description_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); description_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TAGS_FIELD_NUMBER = 3; private com.google.protobuf.LazyStringList tags_; /** * repeated string tags = 3; * @return A list containing the tags. */ public com.google.protobuf.ProtocolStringList getTagsList() { return tags_; } /** * repeated string tags = 3; * @return The count of tags. */ public int getTagsCount() { return tags_.size(); } /** * repeated string tags = 3; * @param index The index of the element to return. * @return The tags at the given index. */ public java.lang.String getTags(int index) { return tags_.get(index); } /** * repeated string tags = 3; * @param index The index of the value to return. * @return The bytes of the tags at the given index. */ public com.google.protobuf.ByteString getTagsBytes(int index) { return tags_.getByteString(index); } public static final int AUTHOR_FIELD_NUMBER = 4; private volatile java.lang.Object author_; /** * string author = 4; * @return The author. */ @java.lang.Override public java.lang.String getAuthor() { java.lang.Object ref = author_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); author_ = s; return s; } } /** * string author = 4; * @return The bytes for author. */ @java.lang.Override public com.google.protobuf.ByteString getAuthorBytes() { java.lang.Object ref = author_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); author_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int AUTHOR_DESCRIPTION_FIELD_NUMBER = 5; private volatile java.lang.Object authorDescription_; /** * string author_description = 5 [(.gogoproto.moretags) = "yaml:\"author_description\""]; * @return The authorDescription. */ @java.lang.Override public java.lang.String getAuthorDescription() { java.lang.Object ref = authorDescription_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); authorDescription_ = s; return s; } } /** * string author_description = 5 [(.gogoproto.moretags) = "yaml:\"author_description\""]; * @return The bytes for authorDescription. */ @java.lang.Override public com.google.protobuf.ByteString getAuthorDescriptionBytes() { java.lang.Object ref = authorDescription_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); authorDescription_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SCHEMAS_FIELD_NUMBER = 6; private volatile java.lang.Object schemas_; /** * string schemas = 6; * @return The schemas. */ @java.lang.Override public java.lang.String getSchemas() { java.lang.Object ref = schemas_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); schemas_ = s; return s; } } /** * string schemas = 6; * @return The bytes for schemas. */ @java.lang.Override public com.google.protobuf.ByteString getSchemasBytes() { java.lang.Object ref = schemas_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); schemas_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_); } if (!getDescriptionBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, description_); } for (int i = 0; i < tags_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, tags_.getRaw(i)); } if (!getAuthorBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, author_); } if (!getAuthorDescriptionBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 5, authorDescription_); } if (!getSchemasBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, schemas_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_); } if (!getDescriptionBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, description_); } { int dataSize = 0; for (int i = 0; i < tags_.size(); i++) { dataSize += computeStringSizeNoTag(tags_.getRaw(i)); } size += dataSize; size += 1 * getTagsList().size(); } if (!getAuthorBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, author_); } if (!getAuthorDescriptionBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, authorDescription_); } if (!getSchemasBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, schemas_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgDefineService)) { return super.equals(obj); } irismod.service.Tx.MsgDefineService other = (irismod.service.Tx.MsgDefineService) obj; if (!getName() .equals(other.getName())) return false; if (!getDescription() .equals(other.getDescription())) return false; if (!getTagsList() .equals(other.getTagsList())) return false; if (!getAuthor() .equals(other.getAuthor())) return false; if (!getAuthorDescription() .equals(other.getAuthorDescription())) return false; if (!getSchemas() .equals(other.getSchemas())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + NAME_FIELD_NUMBER; hash = (53 * hash) + getName().hashCode(); hash = (37 * hash) + DESCRIPTION_FIELD_NUMBER; hash = (53 * hash) + getDescription().hashCode(); if (getTagsCount() > 0) { hash = (37 * hash) + TAGS_FIELD_NUMBER; hash = (53 * hash) + getTagsList().hashCode(); } hash = (37 * hash) + AUTHOR_FIELD_NUMBER; hash = (53 * hash) + getAuthor().hashCode(); hash = (37 * hash) + AUTHOR_DESCRIPTION_FIELD_NUMBER; hash = (53 * hash) + getAuthorDescription().hashCode(); hash = (37 * hash) + SCHEMAS_FIELD_NUMBER; hash = (53 * hash) + getSchemas().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgDefineService parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDefineService parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDefineService parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDefineService parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDefineService parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDefineService parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDefineService parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDefineService parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgDefineService parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDefineService parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgDefineService parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDefineService parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgDefineService prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgDefineService defines an SDK message for defining a new service.
     * 
* * Protobuf type {@code irismod.service.MsgDefineService} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgDefineService) irismod.service.Tx.MsgDefineServiceOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgDefineService_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgDefineService_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgDefineService.class, irismod.service.Tx.MsgDefineService.Builder.class); } // Construct using irismod.service.Tx.MsgDefineService.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); name_ = ""; description_ = ""; tags_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); author_ = ""; authorDescription_ = ""; schemas_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgDefineService_descriptor; } @java.lang.Override public irismod.service.Tx.MsgDefineService getDefaultInstanceForType() { return irismod.service.Tx.MsgDefineService.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgDefineService build() { irismod.service.Tx.MsgDefineService result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgDefineService buildPartial() { irismod.service.Tx.MsgDefineService result = new irismod.service.Tx.MsgDefineService(this); int from_bitField0_ = bitField0_; result.name_ = name_; result.description_ = description_; if (((bitField0_ & 0x00000001) != 0)) { tags_ = tags_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000001); } result.tags_ = tags_; result.author_ = author_; result.authorDescription_ = authorDescription_; result.schemas_ = schemas_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgDefineService) { return mergeFrom((irismod.service.Tx.MsgDefineService)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgDefineService other) { if (other == irismod.service.Tx.MsgDefineService.getDefaultInstance()) return this; if (!other.getName().isEmpty()) { name_ = other.name_; onChanged(); } if (!other.getDescription().isEmpty()) { description_ = other.description_; onChanged(); } if (!other.tags_.isEmpty()) { if (tags_.isEmpty()) { tags_ = other.tags_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureTagsIsMutable(); tags_.addAll(other.tags_); } onChanged(); } if (!other.getAuthor().isEmpty()) { author_ = other.author_; onChanged(); } if (!other.getAuthorDescription().isEmpty()) { authorDescription_ = other.authorDescription_; onChanged(); } if (!other.getSchemas().isEmpty()) { schemas_ = other.schemas_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgDefineService parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgDefineService) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * string name = 1; * @return The name. */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); name_ = s; return s; } else { return (java.lang.String) ref; } } /** * string name = 1; * @return The bytes for name. */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string name = 1; * @param value The name to set. * @return This builder for chaining. */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } name_ = value; onChanged(); return this; } /** * string name = 1; * @return This builder for chaining. */ public Builder clearName() { name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * string name = 1; * @param value The bytes for name to set. * @return This builder for chaining. */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); name_ = value; onChanged(); return this; } private java.lang.Object description_ = ""; /** * string description = 2; * @return The description. */ public java.lang.String getDescription() { java.lang.Object ref = description_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); description_ = s; return s; } else { return (java.lang.String) ref; } } /** * string description = 2; * @return The bytes for description. */ public com.google.protobuf.ByteString getDescriptionBytes() { java.lang.Object ref = description_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); description_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string description = 2; * @param value The description to set. * @return This builder for chaining. */ public Builder setDescription( java.lang.String value) { if (value == null) { throw new NullPointerException(); } description_ = value; onChanged(); return this; } /** * string description = 2; * @return This builder for chaining. */ public Builder clearDescription() { description_ = getDefaultInstance().getDescription(); onChanged(); return this; } /** * string description = 2; * @param value The bytes for description to set. * @return This builder for chaining. */ public Builder setDescriptionBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); description_ = value; onChanged(); return this; } private com.google.protobuf.LazyStringList tags_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureTagsIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { tags_ = new com.google.protobuf.LazyStringArrayList(tags_); bitField0_ |= 0x00000001; } } /** * repeated string tags = 3; * @return A list containing the tags. */ public com.google.protobuf.ProtocolStringList getTagsList() { return tags_.getUnmodifiableView(); } /** * repeated string tags = 3; * @return The count of tags. */ public int getTagsCount() { return tags_.size(); } /** * repeated string tags = 3; * @param index The index of the element to return. * @return The tags at the given index. */ public java.lang.String getTags(int index) { return tags_.get(index); } /** * repeated string tags = 3; * @param index The index of the value to return. * @return The bytes of the tags at the given index. */ public com.google.protobuf.ByteString getTagsBytes(int index) { return tags_.getByteString(index); } /** * repeated string tags = 3; * @param index The index to set the value at. * @param value The tags to set. * @return This builder for chaining. */ public Builder setTags( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureTagsIsMutable(); tags_.set(index, value); onChanged(); return this; } /** * repeated string tags = 3; * @param value The tags to add. * @return This builder for chaining. */ public Builder addTags( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureTagsIsMutable(); tags_.add(value); onChanged(); return this; } /** * repeated string tags = 3; * @param values The tags to add. * @return This builder for chaining. */ public Builder addAllTags( java.lang.Iterable values) { ensureTagsIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, tags_); onChanged(); return this; } /** * repeated string tags = 3; * @return This builder for chaining. */ public Builder clearTags() { tags_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * repeated string tags = 3; * @param value The bytes of the tags to add. * @return This builder for chaining. */ public Builder addTagsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureTagsIsMutable(); tags_.add(value); onChanged(); return this; } private java.lang.Object author_ = ""; /** * string author = 4; * @return The author. */ public java.lang.String getAuthor() { java.lang.Object ref = author_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); author_ = s; return s; } else { return (java.lang.String) ref; } } /** * string author = 4; * @return The bytes for author. */ public com.google.protobuf.ByteString getAuthorBytes() { java.lang.Object ref = author_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); author_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string author = 4; * @param value The author to set. * @return This builder for chaining. */ public Builder setAuthor( java.lang.String value) { if (value == null) { throw new NullPointerException(); } author_ = value; onChanged(); return this; } /** * string author = 4; * @return This builder for chaining. */ public Builder clearAuthor() { author_ = getDefaultInstance().getAuthor(); onChanged(); return this; } /** * string author = 4; * @param value The bytes for author to set. * @return This builder for chaining. */ public Builder setAuthorBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); author_ = value; onChanged(); return this; } private java.lang.Object authorDescription_ = ""; /** * string author_description = 5 [(.gogoproto.moretags) = "yaml:\"author_description\""]; * @return The authorDescription. */ public java.lang.String getAuthorDescription() { java.lang.Object ref = authorDescription_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); authorDescription_ = s; return s; } else { return (java.lang.String) ref; } } /** * string author_description = 5 [(.gogoproto.moretags) = "yaml:\"author_description\""]; * @return The bytes for authorDescription. */ public com.google.protobuf.ByteString getAuthorDescriptionBytes() { java.lang.Object ref = authorDescription_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); authorDescription_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string author_description = 5 [(.gogoproto.moretags) = "yaml:\"author_description\""]; * @param value The authorDescription to set. * @return This builder for chaining. */ public Builder setAuthorDescription( java.lang.String value) { if (value == null) { throw new NullPointerException(); } authorDescription_ = value; onChanged(); return this; } /** * string author_description = 5 [(.gogoproto.moretags) = "yaml:\"author_description\""]; * @return This builder for chaining. */ public Builder clearAuthorDescription() { authorDescription_ = getDefaultInstance().getAuthorDescription(); onChanged(); return this; } /** * string author_description = 5 [(.gogoproto.moretags) = "yaml:\"author_description\""]; * @param value The bytes for authorDescription to set. * @return This builder for chaining. */ public Builder setAuthorDescriptionBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); authorDescription_ = value; onChanged(); return this; } private java.lang.Object schemas_ = ""; /** * string schemas = 6; * @return The schemas. */ public java.lang.String getSchemas() { java.lang.Object ref = schemas_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); schemas_ = s; return s; } else { return (java.lang.String) ref; } } /** * string schemas = 6; * @return The bytes for schemas. */ public com.google.protobuf.ByteString getSchemasBytes() { java.lang.Object ref = schemas_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); schemas_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string schemas = 6; * @param value The schemas to set. * @return This builder for chaining. */ public Builder setSchemas( java.lang.String value) { if (value == null) { throw new NullPointerException(); } schemas_ = value; onChanged(); return this; } /** * string schemas = 6; * @return This builder for chaining. */ public Builder clearSchemas() { schemas_ = getDefaultInstance().getSchemas(); onChanged(); return this; } /** * string schemas = 6; * @param value The bytes for schemas to set. * @return This builder for chaining. */ public Builder setSchemasBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); schemas_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgDefineService) } // @@protoc_insertion_point(class_scope:irismod.service.MsgDefineService) private static final irismod.service.Tx.MsgDefineService DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgDefineService(); } public static irismod.service.Tx.MsgDefineService getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgDefineService parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgDefineService(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgDefineService getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgDefineServiceResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgDefineServiceResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgDefineServiceResponse defines the Msg/DefineService response type.
   * 
* * Protobuf type {@code irismod.service.MsgDefineServiceResponse} */ public static final class MsgDefineServiceResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgDefineServiceResponse) MsgDefineServiceResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgDefineServiceResponse.newBuilder() to construct. private MsgDefineServiceResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgDefineServiceResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgDefineServiceResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgDefineServiceResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgDefineServiceResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgDefineServiceResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgDefineServiceResponse.class, irismod.service.Tx.MsgDefineServiceResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgDefineServiceResponse)) { return super.equals(obj); } irismod.service.Tx.MsgDefineServiceResponse other = (irismod.service.Tx.MsgDefineServiceResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgDefineServiceResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDefineServiceResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDefineServiceResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDefineServiceResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDefineServiceResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDefineServiceResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDefineServiceResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDefineServiceResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgDefineServiceResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDefineServiceResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgDefineServiceResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDefineServiceResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgDefineServiceResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgDefineServiceResponse defines the Msg/DefineService response type.
     * 
* * Protobuf type {@code irismod.service.MsgDefineServiceResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgDefineServiceResponse) irismod.service.Tx.MsgDefineServiceResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgDefineServiceResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgDefineServiceResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgDefineServiceResponse.class, irismod.service.Tx.MsgDefineServiceResponse.Builder.class); } // Construct using irismod.service.Tx.MsgDefineServiceResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgDefineServiceResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgDefineServiceResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgDefineServiceResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgDefineServiceResponse build() { irismod.service.Tx.MsgDefineServiceResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgDefineServiceResponse buildPartial() { irismod.service.Tx.MsgDefineServiceResponse result = new irismod.service.Tx.MsgDefineServiceResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgDefineServiceResponse) { return mergeFrom((irismod.service.Tx.MsgDefineServiceResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgDefineServiceResponse other) { if (other == irismod.service.Tx.MsgDefineServiceResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgDefineServiceResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgDefineServiceResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgDefineServiceResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgDefineServiceResponse) private static final irismod.service.Tx.MsgDefineServiceResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgDefineServiceResponse(); } public static irismod.service.Tx.MsgDefineServiceResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgDefineServiceResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgDefineServiceResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgDefineServiceResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgBindServiceOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgBindService) com.google.protobuf.MessageOrBuilder { /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ java.lang.String getServiceName(); /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ com.google.protobuf.ByteString getServiceNameBytes(); /** * string provider = 2; * @return The provider. */ java.lang.String getProvider(); /** * string provider = 2; * @return The bytes for provider. */ com.google.protobuf.ByteString getProviderBytes(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ java.util.List getDepositList(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ cosmos.base.v1beta1.CoinOuterClass.Coin getDeposit(int index); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ int getDepositCount(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ java.util.List getDepositOrBuilderList(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getDepositOrBuilder( int index); /** * string pricing = 4; * @return The pricing. */ java.lang.String getPricing(); /** * string pricing = 4; * @return The bytes for pricing. */ com.google.protobuf.ByteString getPricingBytes(); /** * uint64 qos = 5 [(.gogoproto.customname) = "QoS"]; * @return The qos. */ long getQos(); /** * string options = 6; * @return The options. */ java.lang.String getOptions(); /** * string options = 6; * @return The bytes for options. */ com.google.protobuf.ByteString getOptionsBytes(); /** * string owner = 7; * @return The owner. */ java.lang.String getOwner(); /** * string owner = 7; * @return The bytes for owner. */ com.google.protobuf.ByteString getOwnerBytes(); } /** *
   * MsgBindService defines an SDK message for binding to an existing service.
   * 
* * Protobuf type {@code irismod.service.MsgBindService} */ public static final class MsgBindService extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgBindService) MsgBindServiceOrBuilder { private static final long serialVersionUID = 0L; // Use MsgBindService.newBuilder() to construct. private MsgBindService(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgBindService() { serviceName_ = ""; provider_ = ""; deposit_ = java.util.Collections.emptyList(); pricing_ = ""; options_ = ""; owner_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgBindService(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgBindService( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); serviceName_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); provider_ = s; break; } case 26: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { deposit_ = new java.util.ArrayList(); mutable_bitField0_ |= 0x00000001; } deposit_.add( input.readMessage(cosmos.base.v1beta1.CoinOuterClass.Coin.parser(), extensionRegistry)); break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); pricing_ = s; break; } case 40: { qos_ = input.readUInt64(); break; } case 50: { java.lang.String s = input.readStringRequireUtf8(); options_ = s; break; } case 58: { java.lang.String s = input.readStringRequireUtf8(); owner_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { deposit_ = java.util.Collections.unmodifiableList(deposit_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgBindService_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgBindService_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgBindService.class, irismod.service.Tx.MsgBindService.Builder.class); } public static final int SERVICE_NAME_FIELD_NUMBER = 1; private volatile java.lang.Object serviceName_; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ @java.lang.Override public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ @java.lang.Override public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROVIDER_FIELD_NUMBER = 2; private volatile java.lang.Object provider_; /** * string provider = 2; * @return The provider. */ @java.lang.Override public java.lang.String getProvider() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } } /** * string provider = 2; * @return The bytes for provider. */ @java.lang.Override public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DEPOSIT_FIELD_NUMBER = 3; private java.util.List deposit_; /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public java.util.List getDepositList() { return deposit_; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public java.util.List getDepositOrBuilderList() { return deposit_; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public int getDepositCount() { return deposit_.size(); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public cosmos.base.v1beta1.CoinOuterClass.Coin getDeposit(int index) { return deposit_.get(index); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getDepositOrBuilder( int index) { return deposit_.get(index); } public static final int PRICING_FIELD_NUMBER = 4; private volatile java.lang.Object pricing_; /** * string pricing = 4; * @return The pricing. */ @java.lang.Override public java.lang.String getPricing() { java.lang.Object ref = pricing_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pricing_ = s; return s; } } /** * string pricing = 4; * @return The bytes for pricing. */ @java.lang.Override public com.google.protobuf.ByteString getPricingBytes() { java.lang.Object ref = pricing_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); pricing_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int QOS_FIELD_NUMBER = 5; private long qos_; /** * uint64 qos = 5 [(.gogoproto.customname) = "QoS"]; * @return The qos. */ @java.lang.Override public long getQos() { return qos_; } public static final int OPTIONS_FIELD_NUMBER = 6; private volatile java.lang.Object options_; /** * string options = 6; * @return The options. */ @java.lang.Override public java.lang.String getOptions() { java.lang.Object ref = options_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); options_ = s; return s; } } /** * string options = 6; * @return The bytes for options. */ @java.lang.Override public com.google.protobuf.ByteString getOptionsBytes() { java.lang.Object ref = options_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); options_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int OWNER_FIELD_NUMBER = 7; private volatile java.lang.Object owner_; /** * string owner = 7; * @return The owner. */ @java.lang.Override public java.lang.String getOwner() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } } /** * string owner = 7; * @return The bytes for owner. */ @java.lang.Override public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getServiceNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, serviceName_); } if (!getProviderBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, provider_); } for (int i = 0; i < deposit_.size(); i++) { output.writeMessage(3, deposit_.get(i)); } if (!getPricingBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, pricing_); } if (qos_ != 0L) { output.writeUInt64(5, qos_); } if (!getOptionsBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, options_); } if (!getOwnerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 7, owner_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getServiceNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, serviceName_); } if (!getProviderBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, provider_); } for (int i = 0; i < deposit_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, deposit_.get(i)); } if (!getPricingBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, pricing_); } if (qos_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(5, qos_); } if (!getOptionsBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, options_); } if (!getOwnerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, owner_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgBindService)) { return super.equals(obj); } irismod.service.Tx.MsgBindService other = (irismod.service.Tx.MsgBindService) obj; if (!getServiceName() .equals(other.getServiceName())) return false; if (!getProvider() .equals(other.getProvider())) return false; if (!getDepositList() .equals(other.getDepositList())) return false; if (!getPricing() .equals(other.getPricing())) return false; if (getQos() != other.getQos()) return false; if (!getOptions() .equals(other.getOptions())) return false; if (!getOwner() .equals(other.getOwner())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SERVICE_NAME_FIELD_NUMBER; hash = (53 * hash) + getServiceName().hashCode(); hash = (37 * hash) + PROVIDER_FIELD_NUMBER; hash = (53 * hash) + getProvider().hashCode(); if (getDepositCount() > 0) { hash = (37 * hash) + DEPOSIT_FIELD_NUMBER; hash = (53 * hash) + getDepositList().hashCode(); } hash = (37 * hash) + PRICING_FIELD_NUMBER; hash = (53 * hash) + getPricing().hashCode(); hash = (37 * hash) + QOS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getQos()); hash = (37 * hash) + OPTIONS_FIELD_NUMBER; hash = (53 * hash) + getOptions().hashCode(); hash = (37 * hash) + OWNER_FIELD_NUMBER; hash = (53 * hash) + getOwner().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgBindService parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgBindService parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgBindService parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgBindService parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgBindService parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgBindService parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgBindService parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgBindService parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgBindService parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgBindService parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgBindService parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgBindService parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgBindService prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgBindService defines an SDK message for binding to an existing service.
     * 
* * Protobuf type {@code irismod.service.MsgBindService} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgBindService) irismod.service.Tx.MsgBindServiceOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgBindService_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgBindService_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgBindService.class, irismod.service.Tx.MsgBindService.Builder.class); } // Construct using irismod.service.Tx.MsgBindService.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getDepositFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); serviceName_ = ""; provider_ = ""; if (depositBuilder_ == null) { deposit_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { depositBuilder_.clear(); } pricing_ = ""; qos_ = 0L; options_ = ""; owner_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgBindService_descriptor; } @java.lang.Override public irismod.service.Tx.MsgBindService getDefaultInstanceForType() { return irismod.service.Tx.MsgBindService.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgBindService build() { irismod.service.Tx.MsgBindService result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgBindService buildPartial() { irismod.service.Tx.MsgBindService result = new irismod.service.Tx.MsgBindService(this); int from_bitField0_ = bitField0_; result.serviceName_ = serviceName_; result.provider_ = provider_; if (depositBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { deposit_ = java.util.Collections.unmodifiableList(deposit_); bitField0_ = (bitField0_ & ~0x00000001); } result.deposit_ = deposit_; } else { result.deposit_ = depositBuilder_.build(); } result.pricing_ = pricing_; result.qos_ = qos_; result.options_ = options_; result.owner_ = owner_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgBindService) { return mergeFrom((irismod.service.Tx.MsgBindService)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgBindService other) { if (other == irismod.service.Tx.MsgBindService.getDefaultInstance()) return this; if (!other.getServiceName().isEmpty()) { serviceName_ = other.serviceName_; onChanged(); } if (!other.getProvider().isEmpty()) { provider_ = other.provider_; onChanged(); } if (depositBuilder_ == null) { if (!other.deposit_.isEmpty()) { if (deposit_.isEmpty()) { deposit_ = other.deposit_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDepositIsMutable(); deposit_.addAll(other.deposit_); } onChanged(); } } else { if (!other.deposit_.isEmpty()) { if (depositBuilder_.isEmpty()) { depositBuilder_.dispose(); depositBuilder_ = null; deposit_ = other.deposit_; bitField0_ = (bitField0_ & ~0x00000001); depositBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDepositFieldBuilder() : null; } else { depositBuilder_.addAllMessages(other.deposit_); } } } if (!other.getPricing().isEmpty()) { pricing_ = other.pricing_; onChanged(); } if (other.getQos() != 0L) { setQos(other.getQos()); } if (!other.getOptions().isEmpty()) { options_ = other.options_; onChanged(); } if (!other.getOwner().isEmpty()) { owner_ = other.owner_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgBindService parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgBindService) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object serviceName_ = ""; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The serviceName to set. * @return This builder for chaining. */ public Builder setServiceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } serviceName_ = value; onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return This builder for chaining. */ public Builder clearServiceName() { serviceName_ = getDefaultInstance().getServiceName(); onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The bytes for serviceName to set. * @return This builder for chaining. */ public Builder setServiceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); serviceName_ = value; onChanged(); return this; } private java.lang.Object provider_ = ""; /** * string provider = 2; * @return The provider. */ public java.lang.String getProvider() { java.lang.Object ref = provider_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } else { return (java.lang.String) ref; } } /** * string provider = 2; * @return The bytes for provider. */ public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string provider = 2; * @param value The provider to set. * @return This builder for chaining. */ public Builder setProvider( java.lang.String value) { if (value == null) { throw new NullPointerException(); } provider_ = value; onChanged(); return this; } /** * string provider = 2; * @return This builder for chaining. */ public Builder clearProvider() { provider_ = getDefaultInstance().getProvider(); onChanged(); return this; } /** * string provider = 2; * @param value The bytes for provider to set. * @return This builder for chaining. */ public Builder setProviderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); provider_ = value; onChanged(); return this; } private java.util.List deposit_ = java.util.Collections.emptyList(); private void ensureDepositIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { deposit_ = new java.util.ArrayList(deposit_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder> depositBuilder_; /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getDepositList() { if (depositBuilder_ == null) { return java.util.Collections.unmodifiableList(deposit_); } else { return depositBuilder_.getMessageList(); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public int getDepositCount() { if (depositBuilder_ == null) { return deposit_.size(); } else { return depositBuilder_.getCount(); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin getDeposit(int index) { if (depositBuilder_ == null) { return deposit_.get(index); } else { return depositBuilder_.getMessage(index); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder setDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (depositBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDepositIsMutable(); deposit_.set(index, value); onChanged(); } else { depositBuilder_.setMessage(index, value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder setDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.set(index, builderForValue.build()); onChanged(); } else { depositBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit(cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (depositBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDepositIsMutable(); deposit_.add(value); onChanged(); } else { depositBuilder_.addMessage(value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (depositBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDepositIsMutable(); deposit_.add(index, value); onChanged(); } else { depositBuilder_.addMessage(index, value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit( cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.add(builderForValue.build()); onChanged(); } else { depositBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.add(index, builderForValue.build()); onChanged(); } else { depositBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addAllDeposit( java.lang.Iterable values) { if (depositBuilder_ == null) { ensureDepositIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, deposit_); onChanged(); } else { depositBuilder_.addAllMessages(values); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder clearDeposit() { if (depositBuilder_ == null) { deposit_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { depositBuilder_.clear(); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder removeDeposit(int index) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.remove(index); onChanged(); } else { depositBuilder_.remove(index); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder getDepositBuilder( int index) { return getDepositFieldBuilder().getBuilder(index); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getDepositOrBuilder( int index) { if (depositBuilder_ == null) { return deposit_.get(index); } else { return depositBuilder_.getMessageOrBuilder(index); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getDepositOrBuilderList() { if (depositBuilder_ != null) { return depositBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(deposit_); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder addDepositBuilder() { return getDepositFieldBuilder().addBuilder( cosmos.base.v1beta1.CoinOuterClass.Coin.getDefaultInstance()); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder addDepositBuilder( int index) { return getDepositFieldBuilder().addBuilder( index, cosmos.base.v1beta1.CoinOuterClass.Coin.getDefaultInstance()); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getDepositBuilderList() { return getDepositFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder> getDepositFieldBuilder() { if (depositBuilder_ == null) { depositBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder>( deposit_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); deposit_ = null; } return depositBuilder_; } private java.lang.Object pricing_ = ""; /** * string pricing = 4; * @return The pricing. */ public java.lang.String getPricing() { java.lang.Object ref = pricing_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pricing_ = s; return s; } else { return (java.lang.String) ref; } } /** * string pricing = 4; * @return The bytes for pricing. */ public com.google.protobuf.ByteString getPricingBytes() { java.lang.Object ref = pricing_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); pricing_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string pricing = 4; * @param value The pricing to set. * @return This builder for chaining. */ public Builder setPricing( java.lang.String value) { if (value == null) { throw new NullPointerException(); } pricing_ = value; onChanged(); return this; } /** * string pricing = 4; * @return This builder for chaining. */ public Builder clearPricing() { pricing_ = getDefaultInstance().getPricing(); onChanged(); return this; } /** * string pricing = 4; * @param value The bytes for pricing to set. * @return This builder for chaining. */ public Builder setPricingBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pricing_ = value; onChanged(); return this; } private long qos_ ; /** * uint64 qos = 5 [(.gogoproto.customname) = "QoS"]; * @return The qos. */ @java.lang.Override public long getQos() { return qos_; } /** * uint64 qos = 5 [(.gogoproto.customname) = "QoS"]; * @param value The qos to set. * @return This builder for chaining. */ public Builder setQos(long value) { qos_ = value; onChanged(); return this; } /** * uint64 qos = 5 [(.gogoproto.customname) = "QoS"]; * @return This builder for chaining. */ public Builder clearQos() { qos_ = 0L; onChanged(); return this; } private java.lang.Object options_ = ""; /** * string options = 6; * @return The options. */ public java.lang.String getOptions() { java.lang.Object ref = options_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); options_ = s; return s; } else { return (java.lang.String) ref; } } /** * string options = 6; * @return The bytes for options. */ public com.google.protobuf.ByteString getOptionsBytes() { java.lang.Object ref = options_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); options_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string options = 6; * @param value The options to set. * @return This builder for chaining. */ public Builder setOptions( java.lang.String value) { if (value == null) { throw new NullPointerException(); } options_ = value; onChanged(); return this; } /** * string options = 6; * @return This builder for chaining. */ public Builder clearOptions() { options_ = getDefaultInstance().getOptions(); onChanged(); return this; } /** * string options = 6; * @param value The bytes for options to set. * @return This builder for chaining. */ public Builder setOptionsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); options_ = value; onChanged(); return this; } private java.lang.Object owner_ = ""; /** * string owner = 7; * @return The owner. */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } else { return (java.lang.String) ref; } } /** * string owner = 7; * @return The bytes for owner. */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string owner = 7; * @param value The owner to set. * @return This builder for chaining. */ public Builder setOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } owner_ = value; onChanged(); return this; } /** * string owner = 7; * @return This builder for chaining. */ public Builder clearOwner() { owner_ = getDefaultInstance().getOwner(); onChanged(); return this; } /** * string owner = 7; * @param value The bytes for owner to set. * @return This builder for chaining. */ public Builder setOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); owner_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgBindService) } // @@protoc_insertion_point(class_scope:irismod.service.MsgBindService) private static final irismod.service.Tx.MsgBindService DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgBindService(); } public static irismod.service.Tx.MsgBindService getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgBindService parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgBindService(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgBindService getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgBindServiceResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgBindServiceResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgBindServiceResponse defines the Msg/BindService response type.
   * 
* * Protobuf type {@code irismod.service.MsgBindServiceResponse} */ public static final class MsgBindServiceResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgBindServiceResponse) MsgBindServiceResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgBindServiceResponse.newBuilder() to construct. private MsgBindServiceResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgBindServiceResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgBindServiceResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgBindServiceResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgBindServiceResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgBindServiceResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgBindServiceResponse.class, irismod.service.Tx.MsgBindServiceResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgBindServiceResponse)) { return super.equals(obj); } irismod.service.Tx.MsgBindServiceResponse other = (irismod.service.Tx.MsgBindServiceResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgBindServiceResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgBindServiceResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgBindServiceResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgBindServiceResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgBindServiceResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgBindServiceResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgBindServiceResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgBindServiceResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgBindServiceResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgBindServiceResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgBindServiceResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgBindServiceResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgBindServiceResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgBindServiceResponse defines the Msg/BindService response type.
     * 
* * Protobuf type {@code irismod.service.MsgBindServiceResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgBindServiceResponse) irismod.service.Tx.MsgBindServiceResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgBindServiceResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgBindServiceResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgBindServiceResponse.class, irismod.service.Tx.MsgBindServiceResponse.Builder.class); } // Construct using irismod.service.Tx.MsgBindServiceResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgBindServiceResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgBindServiceResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgBindServiceResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgBindServiceResponse build() { irismod.service.Tx.MsgBindServiceResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgBindServiceResponse buildPartial() { irismod.service.Tx.MsgBindServiceResponse result = new irismod.service.Tx.MsgBindServiceResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgBindServiceResponse) { return mergeFrom((irismod.service.Tx.MsgBindServiceResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgBindServiceResponse other) { if (other == irismod.service.Tx.MsgBindServiceResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgBindServiceResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgBindServiceResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgBindServiceResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgBindServiceResponse) private static final irismod.service.Tx.MsgBindServiceResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgBindServiceResponse(); } public static irismod.service.Tx.MsgBindServiceResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgBindServiceResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgBindServiceResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgBindServiceResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgUpdateServiceBindingOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgUpdateServiceBinding) com.google.protobuf.MessageOrBuilder { /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ java.lang.String getServiceName(); /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ com.google.protobuf.ByteString getServiceNameBytes(); /** * string provider = 2; * @return The provider. */ java.lang.String getProvider(); /** * string provider = 2; * @return The bytes for provider. */ com.google.protobuf.ByteString getProviderBytes(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ java.util.List getDepositList(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ cosmos.base.v1beta1.CoinOuterClass.Coin getDeposit(int index); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ int getDepositCount(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ java.util.List getDepositOrBuilderList(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getDepositOrBuilder( int index); /** * string pricing = 4; * @return The pricing. */ java.lang.String getPricing(); /** * string pricing = 4; * @return The bytes for pricing. */ com.google.protobuf.ByteString getPricingBytes(); /** * uint64 qos = 5 [(.gogoproto.customname) = "QoS"]; * @return The qos. */ long getQos(); /** * string options = 6; * @return The options. */ java.lang.String getOptions(); /** * string options = 6; * @return The bytes for options. */ com.google.protobuf.ByteString getOptionsBytes(); /** * string owner = 7; * @return The owner. */ java.lang.String getOwner(); /** * string owner = 7; * @return The bytes for owner. */ com.google.protobuf.ByteString getOwnerBytes(); } /** *
   * MsgUpdateServiceBinding defines an SDK message for updating an existing service binding.
   * 
* * Protobuf type {@code irismod.service.MsgUpdateServiceBinding} */ public static final class MsgUpdateServiceBinding extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgUpdateServiceBinding) MsgUpdateServiceBindingOrBuilder { private static final long serialVersionUID = 0L; // Use MsgUpdateServiceBinding.newBuilder() to construct. private MsgUpdateServiceBinding(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgUpdateServiceBinding() { serviceName_ = ""; provider_ = ""; deposit_ = java.util.Collections.emptyList(); pricing_ = ""; options_ = ""; owner_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgUpdateServiceBinding(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgUpdateServiceBinding( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); serviceName_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); provider_ = s; break; } case 26: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { deposit_ = new java.util.ArrayList(); mutable_bitField0_ |= 0x00000001; } deposit_.add( input.readMessage(cosmos.base.v1beta1.CoinOuterClass.Coin.parser(), extensionRegistry)); break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); pricing_ = s; break; } case 40: { qos_ = input.readUInt64(); break; } case 50: { java.lang.String s = input.readStringRequireUtf8(); options_ = s; break; } case 58: { java.lang.String s = input.readStringRequireUtf8(); owner_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { deposit_ = java.util.Collections.unmodifiableList(deposit_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateServiceBinding_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateServiceBinding_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgUpdateServiceBinding.class, irismod.service.Tx.MsgUpdateServiceBinding.Builder.class); } public static final int SERVICE_NAME_FIELD_NUMBER = 1; private volatile java.lang.Object serviceName_; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ @java.lang.Override public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ @java.lang.Override public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROVIDER_FIELD_NUMBER = 2; private volatile java.lang.Object provider_; /** * string provider = 2; * @return The provider. */ @java.lang.Override public java.lang.String getProvider() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } } /** * string provider = 2; * @return The bytes for provider. */ @java.lang.Override public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DEPOSIT_FIELD_NUMBER = 3; private java.util.List deposit_; /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public java.util.List getDepositList() { return deposit_; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public java.util.List getDepositOrBuilderList() { return deposit_; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public int getDepositCount() { return deposit_.size(); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public cosmos.base.v1beta1.CoinOuterClass.Coin getDeposit(int index) { return deposit_.get(index); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getDepositOrBuilder( int index) { return deposit_.get(index); } public static final int PRICING_FIELD_NUMBER = 4; private volatile java.lang.Object pricing_; /** * string pricing = 4; * @return The pricing. */ @java.lang.Override public java.lang.String getPricing() { java.lang.Object ref = pricing_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pricing_ = s; return s; } } /** * string pricing = 4; * @return The bytes for pricing. */ @java.lang.Override public com.google.protobuf.ByteString getPricingBytes() { java.lang.Object ref = pricing_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); pricing_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int QOS_FIELD_NUMBER = 5; private long qos_; /** * uint64 qos = 5 [(.gogoproto.customname) = "QoS"]; * @return The qos. */ @java.lang.Override public long getQos() { return qos_; } public static final int OPTIONS_FIELD_NUMBER = 6; private volatile java.lang.Object options_; /** * string options = 6; * @return The options. */ @java.lang.Override public java.lang.String getOptions() { java.lang.Object ref = options_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); options_ = s; return s; } } /** * string options = 6; * @return The bytes for options. */ @java.lang.Override public com.google.protobuf.ByteString getOptionsBytes() { java.lang.Object ref = options_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); options_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int OWNER_FIELD_NUMBER = 7; private volatile java.lang.Object owner_; /** * string owner = 7; * @return The owner. */ @java.lang.Override public java.lang.String getOwner() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } } /** * string owner = 7; * @return The bytes for owner. */ @java.lang.Override public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getServiceNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, serviceName_); } if (!getProviderBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, provider_); } for (int i = 0; i < deposit_.size(); i++) { output.writeMessage(3, deposit_.get(i)); } if (!getPricingBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, pricing_); } if (qos_ != 0L) { output.writeUInt64(5, qos_); } if (!getOptionsBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 6, options_); } if (!getOwnerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 7, owner_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getServiceNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, serviceName_); } if (!getProviderBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, provider_); } for (int i = 0; i < deposit_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, deposit_.get(i)); } if (!getPricingBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, pricing_); } if (qos_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(5, qos_); } if (!getOptionsBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, options_); } if (!getOwnerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, owner_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgUpdateServiceBinding)) { return super.equals(obj); } irismod.service.Tx.MsgUpdateServiceBinding other = (irismod.service.Tx.MsgUpdateServiceBinding) obj; if (!getServiceName() .equals(other.getServiceName())) return false; if (!getProvider() .equals(other.getProvider())) return false; if (!getDepositList() .equals(other.getDepositList())) return false; if (!getPricing() .equals(other.getPricing())) return false; if (getQos() != other.getQos()) return false; if (!getOptions() .equals(other.getOptions())) return false; if (!getOwner() .equals(other.getOwner())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SERVICE_NAME_FIELD_NUMBER; hash = (53 * hash) + getServiceName().hashCode(); hash = (37 * hash) + PROVIDER_FIELD_NUMBER; hash = (53 * hash) + getProvider().hashCode(); if (getDepositCount() > 0) { hash = (37 * hash) + DEPOSIT_FIELD_NUMBER; hash = (53 * hash) + getDepositList().hashCode(); } hash = (37 * hash) + PRICING_FIELD_NUMBER; hash = (53 * hash) + getPricing().hashCode(); hash = (37 * hash) + QOS_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getQos()); hash = (37 * hash) + OPTIONS_FIELD_NUMBER; hash = (53 * hash) + getOptions().hashCode(); hash = (37 * hash) + OWNER_FIELD_NUMBER; hash = (53 * hash) + getOwner().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgUpdateServiceBinding parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateServiceBinding parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateServiceBinding parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateServiceBinding parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateServiceBinding parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateServiceBinding parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateServiceBinding parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateServiceBinding parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgUpdateServiceBinding parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateServiceBinding parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgUpdateServiceBinding parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateServiceBinding parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgUpdateServiceBinding prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgUpdateServiceBinding defines an SDK message for updating an existing service binding.
     * 
* * Protobuf type {@code irismod.service.MsgUpdateServiceBinding} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgUpdateServiceBinding) irismod.service.Tx.MsgUpdateServiceBindingOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateServiceBinding_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateServiceBinding_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgUpdateServiceBinding.class, irismod.service.Tx.MsgUpdateServiceBinding.Builder.class); } // Construct using irismod.service.Tx.MsgUpdateServiceBinding.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getDepositFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); serviceName_ = ""; provider_ = ""; if (depositBuilder_ == null) { deposit_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { depositBuilder_.clear(); } pricing_ = ""; qos_ = 0L; options_ = ""; owner_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateServiceBinding_descriptor; } @java.lang.Override public irismod.service.Tx.MsgUpdateServiceBinding getDefaultInstanceForType() { return irismod.service.Tx.MsgUpdateServiceBinding.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgUpdateServiceBinding build() { irismod.service.Tx.MsgUpdateServiceBinding result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgUpdateServiceBinding buildPartial() { irismod.service.Tx.MsgUpdateServiceBinding result = new irismod.service.Tx.MsgUpdateServiceBinding(this); int from_bitField0_ = bitField0_; result.serviceName_ = serviceName_; result.provider_ = provider_; if (depositBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { deposit_ = java.util.Collections.unmodifiableList(deposit_); bitField0_ = (bitField0_ & ~0x00000001); } result.deposit_ = deposit_; } else { result.deposit_ = depositBuilder_.build(); } result.pricing_ = pricing_; result.qos_ = qos_; result.options_ = options_; result.owner_ = owner_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgUpdateServiceBinding) { return mergeFrom((irismod.service.Tx.MsgUpdateServiceBinding)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgUpdateServiceBinding other) { if (other == irismod.service.Tx.MsgUpdateServiceBinding.getDefaultInstance()) return this; if (!other.getServiceName().isEmpty()) { serviceName_ = other.serviceName_; onChanged(); } if (!other.getProvider().isEmpty()) { provider_ = other.provider_; onChanged(); } if (depositBuilder_ == null) { if (!other.deposit_.isEmpty()) { if (deposit_.isEmpty()) { deposit_ = other.deposit_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDepositIsMutable(); deposit_.addAll(other.deposit_); } onChanged(); } } else { if (!other.deposit_.isEmpty()) { if (depositBuilder_.isEmpty()) { depositBuilder_.dispose(); depositBuilder_ = null; deposit_ = other.deposit_; bitField0_ = (bitField0_ & ~0x00000001); depositBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDepositFieldBuilder() : null; } else { depositBuilder_.addAllMessages(other.deposit_); } } } if (!other.getPricing().isEmpty()) { pricing_ = other.pricing_; onChanged(); } if (other.getQos() != 0L) { setQos(other.getQos()); } if (!other.getOptions().isEmpty()) { options_ = other.options_; onChanged(); } if (!other.getOwner().isEmpty()) { owner_ = other.owner_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgUpdateServiceBinding parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgUpdateServiceBinding) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object serviceName_ = ""; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The serviceName to set. * @return This builder for chaining. */ public Builder setServiceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } serviceName_ = value; onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return This builder for chaining. */ public Builder clearServiceName() { serviceName_ = getDefaultInstance().getServiceName(); onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The bytes for serviceName to set. * @return This builder for chaining. */ public Builder setServiceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); serviceName_ = value; onChanged(); return this; } private java.lang.Object provider_ = ""; /** * string provider = 2; * @return The provider. */ public java.lang.String getProvider() { java.lang.Object ref = provider_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } else { return (java.lang.String) ref; } } /** * string provider = 2; * @return The bytes for provider. */ public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string provider = 2; * @param value The provider to set. * @return This builder for chaining. */ public Builder setProvider( java.lang.String value) { if (value == null) { throw new NullPointerException(); } provider_ = value; onChanged(); return this; } /** * string provider = 2; * @return This builder for chaining. */ public Builder clearProvider() { provider_ = getDefaultInstance().getProvider(); onChanged(); return this; } /** * string provider = 2; * @param value The bytes for provider to set. * @return This builder for chaining. */ public Builder setProviderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); provider_ = value; onChanged(); return this; } private java.util.List deposit_ = java.util.Collections.emptyList(); private void ensureDepositIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { deposit_ = new java.util.ArrayList(deposit_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder> depositBuilder_; /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getDepositList() { if (depositBuilder_ == null) { return java.util.Collections.unmodifiableList(deposit_); } else { return depositBuilder_.getMessageList(); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public int getDepositCount() { if (depositBuilder_ == null) { return deposit_.size(); } else { return depositBuilder_.getCount(); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin getDeposit(int index) { if (depositBuilder_ == null) { return deposit_.get(index); } else { return depositBuilder_.getMessage(index); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder setDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (depositBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDepositIsMutable(); deposit_.set(index, value); onChanged(); } else { depositBuilder_.setMessage(index, value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder setDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.set(index, builderForValue.build()); onChanged(); } else { depositBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit(cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (depositBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDepositIsMutable(); deposit_.add(value); onChanged(); } else { depositBuilder_.addMessage(value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (depositBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDepositIsMutable(); deposit_.add(index, value); onChanged(); } else { depositBuilder_.addMessage(index, value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit( cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.add(builderForValue.build()); onChanged(); } else { depositBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.add(index, builderForValue.build()); onChanged(); } else { depositBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addAllDeposit( java.lang.Iterable values) { if (depositBuilder_ == null) { ensureDepositIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, deposit_); onChanged(); } else { depositBuilder_.addAllMessages(values); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder clearDeposit() { if (depositBuilder_ == null) { deposit_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { depositBuilder_.clear(); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder removeDeposit(int index) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.remove(index); onChanged(); } else { depositBuilder_.remove(index); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder getDepositBuilder( int index) { return getDepositFieldBuilder().getBuilder(index); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getDepositOrBuilder( int index) { if (depositBuilder_ == null) { return deposit_.get(index); } else { return depositBuilder_.getMessageOrBuilder(index); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getDepositOrBuilderList() { if (depositBuilder_ != null) { return depositBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(deposit_); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder addDepositBuilder() { return getDepositFieldBuilder().addBuilder( cosmos.base.v1beta1.CoinOuterClass.Coin.getDefaultInstance()); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder addDepositBuilder( int index) { return getDepositFieldBuilder().addBuilder( index, cosmos.base.v1beta1.CoinOuterClass.Coin.getDefaultInstance()); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getDepositBuilderList() { return getDepositFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder> getDepositFieldBuilder() { if (depositBuilder_ == null) { depositBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder>( deposit_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); deposit_ = null; } return depositBuilder_; } private java.lang.Object pricing_ = ""; /** * string pricing = 4; * @return The pricing. */ public java.lang.String getPricing() { java.lang.Object ref = pricing_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); pricing_ = s; return s; } else { return (java.lang.String) ref; } } /** * string pricing = 4; * @return The bytes for pricing. */ public com.google.protobuf.ByteString getPricingBytes() { java.lang.Object ref = pricing_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); pricing_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string pricing = 4; * @param value The pricing to set. * @return This builder for chaining. */ public Builder setPricing( java.lang.String value) { if (value == null) { throw new NullPointerException(); } pricing_ = value; onChanged(); return this; } /** * string pricing = 4; * @return This builder for chaining. */ public Builder clearPricing() { pricing_ = getDefaultInstance().getPricing(); onChanged(); return this; } /** * string pricing = 4; * @param value The bytes for pricing to set. * @return This builder for chaining. */ public Builder setPricingBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); pricing_ = value; onChanged(); return this; } private long qos_ ; /** * uint64 qos = 5 [(.gogoproto.customname) = "QoS"]; * @return The qos. */ @java.lang.Override public long getQos() { return qos_; } /** * uint64 qos = 5 [(.gogoproto.customname) = "QoS"]; * @param value The qos to set. * @return This builder for chaining. */ public Builder setQos(long value) { qos_ = value; onChanged(); return this; } /** * uint64 qos = 5 [(.gogoproto.customname) = "QoS"]; * @return This builder for chaining. */ public Builder clearQos() { qos_ = 0L; onChanged(); return this; } private java.lang.Object options_ = ""; /** * string options = 6; * @return The options. */ public java.lang.String getOptions() { java.lang.Object ref = options_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); options_ = s; return s; } else { return (java.lang.String) ref; } } /** * string options = 6; * @return The bytes for options. */ public com.google.protobuf.ByteString getOptionsBytes() { java.lang.Object ref = options_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); options_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string options = 6; * @param value The options to set. * @return This builder for chaining. */ public Builder setOptions( java.lang.String value) { if (value == null) { throw new NullPointerException(); } options_ = value; onChanged(); return this; } /** * string options = 6; * @return This builder for chaining. */ public Builder clearOptions() { options_ = getDefaultInstance().getOptions(); onChanged(); return this; } /** * string options = 6; * @param value The bytes for options to set. * @return This builder for chaining. */ public Builder setOptionsBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); options_ = value; onChanged(); return this; } private java.lang.Object owner_ = ""; /** * string owner = 7; * @return The owner. */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } else { return (java.lang.String) ref; } } /** * string owner = 7; * @return The bytes for owner. */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string owner = 7; * @param value The owner to set. * @return This builder for chaining. */ public Builder setOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } owner_ = value; onChanged(); return this; } /** * string owner = 7; * @return This builder for chaining. */ public Builder clearOwner() { owner_ = getDefaultInstance().getOwner(); onChanged(); return this; } /** * string owner = 7; * @param value The bytes for owner to set. * @return This builder for chaining. */ public Builder setOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); owner_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgUpdateServiceBinding) } // @@protoc_insertion_point(class_scope:irismod.service.MsgUpdateServiceBinding) private static final irismod.service.Tx.MsgUpdateServiceBinding DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgUpdateServiceBinding(); } public static irismod.service.Tx.MsgUpdateServiceBinding getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgUpdateServiceBinding parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgUpdateServiceBinding(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgUpdateServiceBinding getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgUpdateServiceBindingResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgUpdateServiceBindingResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgUpdateServiceBindingResponse defines the Msg/UpdateServiceBinding response type.
   * 
* * Protobuf type {@code irismod.service.MsgUpdateServiceBindingResponse} */ public static final class MsgUpdateServiceBindingResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgUpdateServiceBindingResponse) MsgUpdateServiceBindingResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgUpdateServiceBindingResponse.newBuilder() to construct. private MsgUpdateServiceBindingResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgUpdateServiceBindingResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgUpdateServiceBindingResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgUpdateServiceBindingResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateServiceBindingResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateServiceBindingResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgUpdateServiceBindingResponse.class, irismod.service.Tx.MsgUpdateServiceBindingResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgUpdateServiceBindingResponse)) { return super.equals(obj); } irismod.service.Tx.MsgUpdateServiceBindingResponse other = (irismod.service.Tx.MsgUpdateServiceBindingResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgUpdateServiceBindingResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgUpdateServiceBindingResponse defines the Msg/UpdateServiceBinding response type.
     * 
* * Protobuf type {@code irismod.service.MsgUpdateServiceBindingResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgUpdateServiceBindingResponse) irismod.service.Tx.MsgUpdateServiceBindingResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateServiceBindingResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateServiceBindingResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgUpdateServiceBindingResponse.class, irismod.service.Tx.MsgUpdateServiceBindingResponse.Builder.class); } // Construct using irismod.service.Tx.MsgUpdateServiceBindingResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateServiceBindingResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgUpdateServiceBindingResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgUpdateServiceBindingResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgUpdateServiceBindingResponse build() { irismod.service.Tx.MsgUpdateServiceBindingResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgUpdateServiceBindingResponse buildPartial() { irismod.service.Tx.MsgUpdateServiceBindingResponse result = new irismod.service.Tx.MsgUpdateServiceBindingResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgUpdateServiceBindingResponse) { return mergeFrom((irismod.service.Tx.MsgUpdateServiceBindingResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgUpdateServiceBindingResponse other) { if (other == irismod.service.Tx.MsgUpdateServiceBindingResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgUpdateServiceBindingResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgUpdateServiceBindingResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgUpdateServiceBindingResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgUpdateServiceBindingResponse) private static final irismod.service.Tx.MsgUpdateServiceBindingResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgUpdateServiceBindingResponse(); } public static irismod.service.Tx.MsgUpdateServiceBindingResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgUpdateServiceBindingResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgUpdateServiceBindingResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgUpdateServiceBindingResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgSetWithdrawAddressOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgSetWithdrawAddress) com.google.protobuf.MessageOrBuilder { /** * string owner = 1; * @return The owner. */ java.lang.String getOwner(); /** * string owner = 1; * @return The bytes for owner. */ com.google.protobuf.ByteString getOwnerBytes(); /** * string withdraw_address = 2 [(.gogoproto.moretags) = "yaml:\"withdraw_address\""]; * @return The withdrawAddress. */ java.lang.String getWithdrawAddress(); /** * string withdraw_address = 2 [(.gogoproto.moretags) = "yaml:\"withdraw_address\""]; * @return The bytes for withdrawAddress. */ com.google.protobuf.ByteString getWithdrawAddressBytes(); } /** *
   * MsgSetWithdrawAddress defines an SDK message to set the withdrawal address for a provider.
   * 
* * Protobuf type {@code irismod.service.MsgSetWithdrawAddress} */ public static final class MsgSetWithdrawAddress extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgSetWithdrawAddress) MsgSetWithdrawAddressOrBuilder { private static final long serialVersionUID = 0L; // Use MsgSetWithdrawAddress.newBuilder() to construct. private MsgSetWithdrawAddress(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgSetWithdrawAddress() { owner_ = ""; withdrawAddress_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgSetWithdrawAddress(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgSetWithdrawAddress( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); owner_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); withdrawAddress_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgSetWithdrawAddress_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgSetWithdrawAddress_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgSetWithdrawAddress.class, irismod.service.Tx.MsgSetWithdrawAddress.Builder.class); } public static final int OWNER_FIELD_NUMBER = 1; private volatile java.lang.Object owner_; /** * string owner = 1; * @return The owner. */ @java.lang.Override public java.lang.String getOwner() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } } /** * string owner = 1; * @return The bytes for owner. */ @java.lang.Override public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int WITHDRAW_ADDRESS_FIELD_NUMBER = 2; private volatile java.lang.Object withdrawAddress_; /** * string withdraw_address = 2 [(.gogoproto.moretags) = "yaml:\"withdraw_address\""]; * @return The withdrawAddress. */ @java.lang.Override public java.lang.String getWithdrawAddress() { java.lang.Object ref = withdrawAddress_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); withdrawAddress_ = s; return s; } } /** * string withdraw_address = 2 [(.gogoproto.moretags) = "yaml:\"withdraw_address\""]; * @return The bytes for withdrawAddress. */ @java.lang.Override public com.google.protobuf.ByteString getWithdrawAddressBytes() { java.lang.Object ref = withdrawAddress_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); withdrawAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getOwnerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, owner_); } if (!getWithdrawAddressBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, withdrawAddress_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getOwnerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, owner_); } if (!getWithdrawAddressBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, withdrawAddress_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgSetWithdrawAddress)) { return super.equals(obj); } irismod.service.Tx.MsgSetWithdrawAddress other = (irismod.service.Tx.MsgSetWithdrawAddress) obj; if (!getOwner() .equals(other.getOwner())) return false; if (!getWithdrawAddress() .equals(other.getWithdrawAddress())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + OWNER_FIELD_NUMBER; hash = (53 * hash) + getOwner().hashCode(); hash = (37 * hash) + WITHDRAW_ADDRESS_FIELD_NUMBER; hash = (53 * hash) + getWithdrawAddress().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgSetWithdrawAddress parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgSetWithdrawAddress parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgSetWithdrawAddress parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgSetWithdrawAddress parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgSetWithdrawAddress parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgSetWithdrawAddress parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgSetWithdrawAddress parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgSetWithdrawAddress parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgSetWithdrawAddress parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgSetWithdrawAddress parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgSetWithdrawAddress parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgSetWithdrawAddress parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgSetWithdrawAddress prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgSetWithdrawAddress defines an SDK message to set the withdrawal address for a provider.
     * 
* * Protobuf type {@code irismod.service.MsgSetWithdrawAddress} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgSetWithdrawAddress) irismod.service.Tx.MsgSetWithdrawAddressOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgSetWithdrawAddress_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgSetWithdrawAddress_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgSetWithdrawAddress.class, irismod.service.Tx.MsgSetWithdrawAddress.Builder.class); } // Construct using irismod.service.Tx.MsgSetWithdrawAddress.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); owner_ = ""; withdrawAddress_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgSetWithdrawAddress_descriptor; } @java.lang.Override public irismod.service.Tx.MsgSetWithdrawAddress getDefaultInstanceForType() { return irismod.service.Tx.MsgSetWithdrawAddress.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgSetWithdrawAddress build() { irismod.service.Tx.MsgSetWithdrawAddress result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgSetWithdrawAddress buildPartial() { irismod.service.Tx.MsgSetWithdrawAddress result = new irismod.service.Tx.MsgSetWithdrawAddress(this); result.owner_ = owner_; result.withdrawAddress_ = withdrawAddress_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgSetWithdrawAddress) { return mergeFrom((irismod.service.Tx.MsgSetWithdrawAddress)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgSetWithdrawAddress other) { if (other == irismod.service.Tx.MsgSetWithdrawAddress.getDefaultInstance()) return this; if (!other.getOwner().isEmpty()) { owner_ = other.owner_; onChanged(); } if (!other.getWithdrawAddress().isEmpty()) { withdrawAddress_ = other.withdrawAddress_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgSetWithdrawAddress parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgSetWithdrawAddress) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object owner_ = ""; /** * string owner = 1; * @return The owner. */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } else { return (java.lang.String) ref; } } /** * string owner = 1; * @return The bytes for owner. */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string owner = 1; * @param value The owner to set. * @return This builder for chaining. */ public Builder setOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } owner_ = value; onChanged(); return this; } /** * string owner = 1; * @return This builder for chaining. */ public Builder clearOwner() { owner_ = getDefaultInstance().getOwner(); onChanged(); return this; } /** * string owner = 1; * @param value The bytes for owner to set. * @return This builder for chaining. */ public Builder setOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); owner_ = value; onChanged(); return this; } private java.lang.Object withdrawAddress_ = ""; /** * string withdraw_address = 2 [(.gogoproto.moretags) = "yaml:\"withdraw_address\""]; * @return The withdrawAddress. */ public java.lang.String getWithdrawAddress() { java.lang.Object ref = withdrawAddress_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); withdrawAddress_ = s; return s; } else { return (java.lang.String) ref; } } /** * string withdraw_address = 2 [(.gogoproto.moretags) = "yaml:\"withdraw_address\""]; * @return The bytes for withdrawAddress. */ public com.google.protobuf.ByteString getWithdrawAddressBytes() { java.lang.Object ref = withdrawAddress_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); withdrawAddress_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string withdraw_address = 2 [(.gogoproto.moretags) = "yaml:\"withdraw_address\""]; * @param value The withdrawAddress to set. * @return This builder for chaining. */ public Builder setWithdrawAddress( java.lang.String value) { if (value == null) { throw new NullPointerException(); } withdrawAddress_ = value; onChanged(); return this; } /** * string withdraw_address = 2 [(.gogoproto.moretags) = "yaml:\"withdraw_address\""]; * @return This builder for chaining. */ public Builder clearWithdrawAddress() { withdrawAddress_ = getDefaultInstance().getWithdrawAddress(); onChanged(); return this; } /** * string withdraw_address = 2 [(.gogoproto.moretags) = "yaml:\"withdraw_address\""]; * @param value The bytes for withdrawAddress to set. * @return This builder for chaining. */ public Builder setWithdrawAddressBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); withdrawAddress_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgSetWithdrawAddress) } // @@protoc_insertion_point(class_scope:irismod.service.MsgSetWithdrawAddress) private static final irismod.service.Tx.MsgSetWithdrawAddress DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgSetWithdrawAddress(); } public static irismod.service.Tx.MsgSetWithdrawAddress getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgSetWithdrawAddress parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgSetWithdrawAddress(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgSetWithdrawAddress getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgSetWithdrawAddressResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgSetWithdrawAddressResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgSetWithdrawAddressResponse defines the Msg/SetWithdrawAddress response type.
   * 
* * Protobuf type {@code irismod.service.MsgSetWithdrawAddressResponse} */ public static final class MsgSetWithdrawAddressResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgSetWithdrawAddressResponse) MsgSetWithdrawAddressResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgSetWithdrawAddressResponse.newBuilder() to construct. private MsgSetWithdrawAddressResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgSetWithdrawAddressResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgSetWithdrawAddressResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgSetWithdrawAddressResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgSetWithdrawAddressResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgSetWithdrawAddressResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgSetWithdrawAddressResponse.class, irismod.service.Tx.MsgSetWithdrawAddressResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgSetWithdrawAddressResponse)) { return super.equals(obj); } irismod.service.Tx.MsgSetWithdrawAddressResponse other = (irismod.service.Tx.MsgSetWithdrawAddressResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgSetWithdrawAddressResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgSetWithdrawAddressResponse defines the Msg/SetWithdrawAddress response type.
     * 
* * Protobuf type {@code irismod.service.MsgSetWithdrawAddressResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgSetWithdrawAddressResponse) irismod.service.Tx.MsgSetWithdrawAddressResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgSetWithdrawAddressResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgSetWithdrawAddressResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgSetWithdrawAddressResponse.class, irismod.service.Tx.MsgSetWithdrawAddressResponse.Builder.class); } // Construct using irismod.service.Tx.MsgSetWithdrawAddressResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgSetWithdrawAddressResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgSetWithdrawAddressResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgSetWithdrawAddressResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgSetWithdrawAddressResponse build() { irismod.service.Tx.MsgSetWithdrawAddressResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgSetWithdrawAddressResponse buildPartial() { irismod.service.Tx.MsgSetWithdrawAddressResponse result = new irismod.service.Tx.MsgSetWithdrawAddressResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgSetWithdrawAddressResponse) { return mergeFrom((irismod.service.Tx.MsgSetWithdrawAddressResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgSetWithdrawAddressResponse other) { if (other == irismod.service.Tx.MsgSetWithdrawAddressResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgSetWithdrawAddressResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgSetWithdrawAddressResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgSetWithdrawAddressResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgSetWithdrawAddressResponse) private static final irismod.service.Tx.MsgSetWithdrawAddressResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgSetWithdrawAddressResponse(); } public static irismod.service.Tx.MsgSetWithdrawAddressResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgSetWithdrawAddressResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgSetWithdrawAddressResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgSetWithdrawAddressResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgDisableServiceBindingOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgDisableServiceBinding) com.google.protobuf.MessageOrBuilder { /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ java.lang.String getServiceName(); /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ com.google.protobuf.ByteString getServiceNameBytes(); /** * string provider = 2; * @return The provider. */ java.lang.String getProvider(); /** * string provider = 2; * @return The bytes for provider. */ com.google.protobuf.ByteString getProviderBytes(); /** * string owner = 3; * @return The owner. */ java.lang.String getOwner(); /** * string owner = 3; * @return The bytes for owner. */ com.google.protobuf.ByteString getOwnerBytes(); } /** *
   * MsgDisableServiceBinding defines an SDK message to disable a service binding.
   * 
* * Protobuf type {@code irismod.service.MsgDisableServiceBinding} */ public static final class MsgDisableServiceBinding extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgDisableServiceBinding) MsgDisableServiceBindingOrBuilder { private static final long serialVersionUID = 0L; // Use MsgDisableServiceBinding.newBuilder() to construct. private MsgDisableServiceBinding(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgDisableServiceBinding() { serviceName_ = ""; provider_ = ""; owner_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgDisableServiceBinding(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgDisableServiceBinding( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); serviceName_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); provider_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); owner_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgDisableServiceBinding_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgDisableServiceBinding_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgDisableServiceBinding.class, irismod.service.Tx.MsgDisableServiceBinding.Builder.class); } public static final int SERVICE_NAME_FIELD_NUMBER = 1; private volatile java.lang.Object serviceName_; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ @java.lang.Override public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ @java.lang.Override public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROVIDER_FIELD_NUMBER = 2; private volatile java.lang.Object provider_; /** * string provider = 2; * @return The provider. */ @java.lang.Override public java.lang.String getProvider() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } } /** * string provider = 2; * @return The bytes for provider. */ @java.lang.Override public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int OWNER_FIELD_NUMBER = 3; private volatile java.lang.Object owner_; /** * string owner = 3; * @return The owner. */ @java.lang.Override public java.lang.String getOwner() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } } /** * string owner = 3; * @return The bytes for owner. */ @java.lang.Override public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getServiceNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, serviceName_); } if (!getProviderBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, provider_); } if (!getOwnerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, owner_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getServiceNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, serviceName_); } if (!getProviderBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, provider_); } if (!getOwnerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, owner_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgDisableServiceBinding)) { return super.equals(obj); } irismod.service.Tx.MsgDisableServiceBinding other = (irismod.service.Tx.MsgDisableServiceBinding) obj; if (!getServiceName() .equals(other.getServiceName())) return false; if (!getProvider() .equals(other.getProvider())) return false; if (!getOwner() .equals(other.getOwner())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SERVICE_NAME_FIELD_NUMBER; hash = (53 * hash) + getServiceName().hashCode(); hash = (37 * hash) + PROVIDER_FIELD_NUMBER; hash = (53 * hash) + getProvider().hashCode(); hash = (37 * hash) + OWNER_FIELD_NUMBER; hash = (53 * hash) + getOwner().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgDisableServiceBinding parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDisableServiceBinding parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDisableServiceBinding parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDisableServiceBinding parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDisableServiceBinding parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDisableServiceBinding parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDisableServiceBinding parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDisableServiceBinding parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgDisableServiceBinding parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDisableServiceBinding parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgDisableServiceBinding parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDisableServiceBinding parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgDisableServiceBinding prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgDisableServiceBinding defines an SDK message to disable a service binding.
     * 
* * Protobuf type {@code irismod.service.MsgDisableServiceBinding} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgDisableServiceBinding) irismod.service.Tx.MsgDisableServiceBindingOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgDisableServiceBinding_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgDisableServiceBinding_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgDisableServiceBinding.class, irismod.service.Tx.MsgDisableServiceBinding.Builder.class); } // Construct using irismod.service.Tx.MsgDisableServiceBinding.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); serviceName_ = ""; provider_ = ""; owner_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgDisableServiceBinding_descriptor; } @java.lang.Override public irismod.service.Tx.MsgDisableServiceBinding getDefaultInstanceForType() { return irismod.service.Tx.MsgDisableServiceBinding.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgDisableServiceBinding build() { irismod.service.Tx.MsgDisableServiceBinding result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgDisableServiceBinding buildPartial() { irismod.service.Tx.MsgDisableServiceBinding result = new irismod.service.Tx.MsgDisableServiceBinding(this); result.serviceName_ = serviceName_; result.provider_ = provider_; result.owner_ = owner_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgDisableServiceBinding) { return mergeFrom((irismod.service.Tx.MsgDisableServiceBinding)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgDisableServiceBinding other) { if (other == irismod.service.Tx.MsgDisableServiceBinding.getDefaultInstance()) return this; if (!other.getServiceName().isEmpty()) { serviceName_ = other.serviceName_; onChanged(); } if (!other.getProvider().isEmpty()) { provider_ = other.provider_; onChanged(); } if (!other.getOwner().isEmpty()) { owner_ = other.owner_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgDisableServiceBinding parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgDisableServiceBinding) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object serviceName_ = ""; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The serviceName to set. * @return This builder for chaining. */ public Builder setServiceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } serviceName_ = value; onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return This builder for chaining. */ public Builder clearServiceName() { serviceName_ = getDefaultInstance().getServiceName(); onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The bytes for serviceName to set. * @return This builder for chaining. */ public Builder setServiceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); serviceName_ = value; onChanged(); return this; } private java.lang.Object provider_ = ""; /** * string provider = 2; * @return The provider. */ public java.lang.String getProvider() { java.lang.Object ref = provider_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } else { return (java.lang.String) ref; } } /** * string provider = 2; * @return The bytes for provider. */ public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string provider = 2; * @param value The provider to set. * @return This builder for chaining. */ public Builder setProvider( java.lang.String value) { if (value == null) { throw new NullPointerException(); } provider_ = value; onChanged(); return this; } /** * string provider = 2; * @return This builder for chaining. */ public Builder clearProvider() { provider_ = getDefaultInstance().getProvider(); onChanged(); return this; } /** * string provider = 2; * @param value The bytes for provider to set. * @return This builder for chaining. */ public Builder setProviderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); provider_ = value; onChanged(); return this; } private java.lang.Object owner_ = ""; /** * string owner = 3; * @return The owner. */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } else { return (java.lang.String) ref; } } /** * string owner = 3; * @return The bytes for owner. */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string owner = 3; * @param value The owner to set. * @return This builder for chaining. */ public Builder setOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } owner_ = value; onChanged(); return this; } /** * string owner = 3; * @return This builder for chaining. */ public Builder clearOwner() { owner_ = getDefaultInstance().getOwner(); onChanged(); return this; } /** * string owner = 3; * @param value The bytes for owner to set. * @return This builder for chaining. */ public Builder setOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); owner_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgDisableServiceBinding) } // @@protoc_insertion_point(class_scope:irismod.service.MsgDisableServiceBinding) private static final irismod.service.Tx.MsgDisableServiceBinding DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgDisableServiceBinding(); } public static irismod.service.Tx.MsgDisableServiceBinding getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgDisableServiceBinding parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgDisableServiceBinding(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgDisableServiceBinding getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgDisableServiceBindingResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgDisableServiceBindingResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgDisableServiceBindingResponse defines the Msg/DisableServiceBinding response type.
   * 
* * Protobuf type {@code irismod.service.MsgDisableServiceBindingResponse} */ public static final class MsgDisableServiceBindingResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgDisableServiceBindingResponse) MsgDisableServiceBindingResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgDisableServiceBindingResponse.newBuilder() to construct. private MsgDisableServiceBindingResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgDisableServiceBindingResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgDisableServiceBindingResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgDisableServiceBindingResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgDisableServiceBindingResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgDisableServiceBindingResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgDisableServiceBindingResponse.class, irismod.service.Tx.MsgDisableServiceBindingResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgDisableServiceBindingResponse)) { return super.equals(obj); } irismod.service.Tx.MsgDisableServiceBindingResponse other = (irismod.service.Tx.MsgDisableServiceBindingResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgDisableServiceBindingResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgDisableServiceBindingResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgDisableServiceBindingResponse defines the Msg/DisableServiceBinding response type.
     * 
* * Protobuf type {@code irismod.service.MsgDisableServiceBindingResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgDisableServiceBindingResponse) irismod.service.Tx.MsgDisableServiceBindingResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgDisableServiceBindingResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgDisableServiceBindingResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgDisableServiceBindingResponse.class, irismod.service.Tx.MsgDisableServiceBindingResponse.Builder.class); } // Construct using irismod.service.Tx.MsgDisableServiceBindingResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgDisableServiceBindingResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgDisableServiceBindingResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgDisableServiceBindingResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgDisableServiceBindingResponse build() { irismod.service.Tx.MsgDisableServiceBindingResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgDisableServiceBindingResponse buildPartial() { irismod.service.Tx.MsgDisableServiceBindingResponse result = new irismod.service.Tx.MsgDisableServiceBindingResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgDisableServiceBindingResponse) { return mergeFrom((irismod.service.Tx.MsgDisableServiceBindingResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgDisableServiceBindingResponse other) { if (other == irismod.service.Tx.MsgDisableServiceBindingResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgDisableServiceBindingResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgDisableServiceBindingResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgDisableServiceBindingResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgDisableServiceBindingResponse) private static final irismod.service.Tx.MsgDisableServiceBindingResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgDisableServiceBindingResponse(); } public static irismod.service.Tx.MsgDisableServiceBindingResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgDisableServiceBindingResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgDisableServiceBindingResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgDisableServiceBindingResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgEnableServiceBindingOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgEnableServiceBinding) com.google.protobuf.MessageOrBuilder { /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ java.lang.String getServiceName(); /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ com.google.protobuf.ByteString getServiceNameBytes(); /** * string provider = 2; * @return The provider. */ java.lang.String getProvider(); /** * string provider = 2; * @return The bytes for provider. */ com.google.protobuf.ByteString getProviderBytes(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ java.util.List getDepositList(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ cosmos.base.v1beta1.CoinOuterClass.Coin getDeposit(int index); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ int getDepositCount(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ java.util.List getDepositOrBuilderList(); /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getDepositOrBuilder( int index); /** * string owner = 4; * @return The owner. */ java.lang.String getOwner(); /** * string owner = 4; * @return The bytes for owner. */ com.google.protobuf.ByteString getOwnerBytes(); } /** *
   * MsgEnableServiceBinding defines an SDK message to enable a service binding.
   * 
* * Protobuf type {@code irismod.service.MsgEnableServiceBinding} */ public static final class MsgEnableServiceBinding extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgEnableServiceBinding) MsgEnableServiceBindingOrBuilder { private static final long serialVersionUID = 0L; // Use MsgEnableServiceBinding.newBuilder() to construct. private MsgEnableServiceBinding(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgEnableServiceBinding() { serviceName_ = ""; provider_ = ""; deposit_ = java.util.Collections.emptyList(); owner_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgEnableServiceBinding(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgEnableServiceBinding( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); serviceName_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); provider_ = s; break; } case 26: { if (!((mutable_bitField0_ & 0x00000001) != 0)) { deposit_ = new java.util.ArrayList(); mutable_bitField0_ |= 0x00000001; } deposit_.add( input.readMessage(cosmos.base.v1beta1.CoinOuterClass.Coin.parser(), extensionRegistry)); break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); owner_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { deposit_ = java.util.Collections.unmodifiableList(deposit_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgEnableServiceBinding_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgEnableServiceBinding_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgEnableServiceBinding.class, irismod.service.Tx.MsgEnableServiceBinding.Builder.class); } public static final int SERVICE_NAME_FIELD_NUMBER = 1; private volatile java.lang.Object serviceName_; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ @java.lang.Override public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ @java.lang.Override public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROVIDER_FIELD_NUMBER = 2; private volatile java.lang.Object provider_; /** * string provider = 2; * @return The provider. */ @java.lang.Override public java.lang.String getProvider() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } } /** * string provider = 2; * @return The bytes for provider. */ @java.lang.Override public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DEPOSIT_FIELD_NUMBER = 3; private java.util.List deposit_; /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public java.util.List getDepositList() { return deposit_; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public java.util.List getDepositOrBuilderList() { return deposit_; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public int getDepositCount() { return deposit_.size(); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public cosmos.base.v1beta1.CoinOuterClass.Coin getDeposit(int index) { return deposit_.get(index); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getDepositOrBuilder( int index) { return deposit_.get(index); } public static final int OWNER_FIELD_NUMBER = 4; private volatile java.lang.Object owner_; /** * string owner = 4; * @return The owner. */ @java.lang.Override public java.lang.String getOwner() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } } /** * string owner = 4; * @return The bytes for owner. */ @java.lang.Override public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getServiceNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, serviceName_); } if (!getProviderBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, provider_); } for (int i = 0; i < deposit_.size(); i++) { output.writeMessage(3, deposit_.get(i)); } if (!getOwnerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, owner_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getServiceNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, serviceName_); } if (!getProviderBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, provider_); } for (int i = 0; i < deposit_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, deposit_.get(i)); } if (!getOwnerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, owner_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgEnableServiceBinding)) { return super.equals(obj); } irismod.service.Tx.MsgEnableServiceBinding other = (irismod.service.Tx.MsgEnableServiceBinding) obj; if (!getServiceName() .equals(other.getServiceName())) return false; if (!getProvider() .equals(other.getProvider())) return false; if (!getDepositList() .equals(other.getDepositList())) return false; if (!getOwner() .equals(other.getOwner())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SERVICE_NAME_FIELD_NUMBER; hash = (53 * hash) + getServiceName().hashCode(); hash = (37 * hash) + PROVIDER_FIELD_NUMBER; hash = (53 * hash) + getProvider().hashCode(); if (getDepositCount() > 0) { hash = (37 * hash) + DEPOSIT_FIELD_NUMBER; hash = (53 * hash) + getDepositList().hashCode(); } hash = (37 * hash) + OWNER_FIELD_NUMBER; hash = (53 * hash) + getOwner().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgEnableServiceBinding parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgEnableServiceBinding parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgEnableServiceBinding parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgEnableServiceBinding parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgEnableServiceBinding parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgEnableServiceBinding parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgEnableServiceBinding parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgEnableServiceBinding parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgEnableServiceBinding parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgEnableServiceBinding parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgEnableServiceBinding parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgEnableServiceBinding parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgEnableServiceBinding prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgEnableServiceBinding defines an SDK message to enable a service binding.
     * 
* * Protobuf type {@code irismod.service.MsgEnableServiceBinding} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgEnableServiceBinding) irismod.service.Tx.MsgEnableServiceBindingOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgEnableServiceBinding_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgEnableServiceBinding_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgEnableServiceBinding.class, irismod.service.Tx.MsgEnableServiceBinding.Builder.class); } // Construct using irismod.service.Tx.MsgEnableServiceBinding.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getDepositFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); serviceName_ = ""; provider_ = ""; if (depositBuilder_ == null) { deposit_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { depositBuilder_.clear(); } owner_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgEnableServiceBinding_descriptor; } @java.lang.Override public irismod.service.Tx.MsgEnableServiceBinding getDefaultInstanceForType() { return irismod.service.Tx.MsgEnableServiceBinding.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgEnableServiceBinding build() { irismod.service.Tx.MsgEnableServiceBinding result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgEnableServiceBinding buildPartial() { irismod.service.Tx.MsgEnableServiceBinding result = new irismod.service.Tx.MsgEnableServiceBinding(this); int from_bitField0_ = bitField0_; result.serviceName_ = serviceName_; result.provider_ = provider_; if (depositBuilder_ == null) { if (((bitField0_ & 0x00000001) != 0)) { deposit_ = java.util.Collections.unmodifiableList(deposit_); bitField0_ = (bitField0_ & ~0x00000001); } result.deposit_ = deposit_; } else { result.deposit_ = depositBuilder_.build(); } result.owner_ = owner_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgEnableServiceBinding) { return mergeFrom((irismod.service.Tx.MsgEnableServiceBinding)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgEnableServiceBinding other) { if (other == irismod.service.Tx.MsgEnableServiceBinding.getDefaultInstance()) return this; if (!other.getServiceName().isEmpty()) { serviceName_ = other.serviceName_; onChanged(); } if (!other.getProvider().isEmpty()) { provider_ = other.provider_; onChanged(); } if (depositBuilder_ == null) { if (!other.deposit_.isEmpty()) { if (deposit_.isEmpty()) { deposit_ = other.deposit_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureDepositIsMutable(); deposit_.addAll(other.deposit_); } onChanged(); } } else { if (!other.deposit_.isEmpty()) { if (depositBuilder_.isEmpty()) { depositBuilder_.dispose(); depositBuilder_ = null; deposit_ = other.deposit_; bitField0_ = (bitField0_ & ~0x00000001); depositBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDepositFieldBuilder() : null; } else { depositBuilder_.addAllMessages(other.deposit_); } } } if (!other.getOwner().isEmpty()) { owner_ = other.owner_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgEnableServiceBinding parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgEnableServiceBinding) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object serviceName_ = ""; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The serviceName to set. * @return This builder for chaining. */ public Builder setServiceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } serviceName_ = value; onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return This builder for chaining. */ public Builder clearServiceName() { serviceName_ = getDefaultInstance().getServiceName(); onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The bytes for serviceName to set. * @return This builder for chaining. */ public Builder setServiceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); serviceName_ = value; onChanged(); return this; } private java.lang.Object provider_ = ""; /** * string provider = 2; * @return The provider. */ public java.lang.String getProvider() { java.lang.Object ref = provider_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } else { return (java.lang.String) ref; } } /** * string provider = 2; * @return The bytes for provider. */ public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string provider = 2; * @param value The provider to set. * @return This builder for chaining. */ public Builder setProvider( java.lang.String value) { if (value == null) { throw new NullPointerException(); } provider_ = value; onChanged(); return this; } /** * string provider = 2; * @return This builder for chaining. */ public Builder clearProvider() { provider_ = getDefaultInstance().getProvider(); onChanged(); return this; } /** * string provider = 2; * @param value The bytes for provider to set. * @return This builder for chaining. */ public Builder setProviderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); provider_ = value; onChanged(); return this; } private java.util.List deposit_ = java.util.Collections.emptyList(); private void ensureDepositIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { deposit_ = new java.util.ArrayList(deposit_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder> depositBuilder_; /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getDepositList() { if (depositBuilder_ == null) { return java.util.Collections.unmodifiableList(deposit_); } else { return depositBuilder_.getMessageList(); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public int getDepositCount() { if (depositBuilder_ == null) { return deposit_.size(); } else { return depositBuilder_.getCount(); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin getDeposit(int index) { if (depositBuilder_ == null) { return deposit_.get(index); } else { return depositBuilder_.getMessage(index); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder setDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (depositBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDepositIsMutable(); deposit_.set(index, value); onChanged(); } else { depositBuilder_.setMessage(index, value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder setDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.set(index, builderForValue.build()); onChanged(); } else { depositBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit(cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (depositBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDepositIsMutable(); deposit_.add(value); onChanged(); } else { depositBuilder_.addMessage(value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (depositBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureDepositIsMutable(); deposit_.add(index, value); onChanged(); } else { depositBuilder_.addMessage(index, value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit( cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.add(builderForValue.build()); onChanged(); } else { depositBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addDeposit( int index, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.add(index, builderForValue.build()); onChanged(); } else { depositBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addAllDeposit( java.lang.Iterable values) { if (depositBuilder_ == null) { ensureDepositIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, deposit_); onChanged(); } else { depositBuilder_.addAllMessages(values); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder clearDeposit() { if (depositBuilder_ == null) { deposit_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { depositBuilder_.clear(); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder removeDeposit(int index) { if (depositBuilder_ == null) { ensureDepositIsMutable(); deposit_.remove(index); onChanged(); } else { depositBuilder_.remove(index); } return this; } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder getDepositBuilder( int index) { return getDepositFieldBuilder().getBuilder(index); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getDepositOrBuilder( int index) { if (depositBuilder_ == null) { return deposit_.get(index); } else { return depositBuilder_.getMessageOrBuilder(index); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getDepositOrBuilderList() { if (depositBuilder_ != null) { return depositBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(deposit_); } } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder addDepositBuilder() { return getDepositFieldBuilder().addBuilder( cosmos.base.v1beta1.CoinOuterClass.Coin.getDefaultInstance()); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder addDepositBuilder( int index) { return getDepositFieldBuilder().addBuilder( index, cosmos.base.v1beta1.CoinOuterClass.Coin.getDefaultInstance()); } /** * repeated .cosmos.base.v1beta1.Coin deposit = 3 [(.gogoproto.nullable) = false, (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getDepositBuilderList() { return getDepositFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder> getDepositFieldBuilder() { if (depositBuilder_ == null) { depositBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder>( deposit_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean()); deposit_ = null; } return depositBuilder_; } private java.lang.Object owner_ = ""; /** * string owner = 4; * @return The owner. */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } else { return (java.lang.String) ref; } } /** * string owner = 4; * @return The bytes for owner. */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string owner = 4; * @param value The owner to set. * @return This builder for chaining. */ public Builder setOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } owner_ = value; onChanged(); return this; } /** * string owner = 4; * @return This builder for chaining. */ public Builder clearOwner() { owner_ = getDefaultInstance().getOwner(); onChanged(); return this; } /** * string owner = 4; * @param value The bytes for owner to set. * @return This builder for chaining. */ public Builder setOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); owner_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgEnableServiceBinding) } // @@protoc_insertion_point(class_scope:irismod.service.MsgEnableServiceBinding) private static final irismod.service.Tx.MsgEnableServiceBinding DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgEnableServiceBinding(); } public static irismod.service.Tx.MsgEnableServiceBinding getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgEnableServiceBinding parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgEnableServiceBinding(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgEnableServiceBinding getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgEnableServiceBindingResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgEnableServiceBindingResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgEnableServiceBindingResponse defines the Msg/EnableServiceBinding response type.
   * 
* * Protobuf type {@code irismod.service.MsgEnableServiceBindingResponse} */ public static final class MsgEnableServiceBindingResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgEnableServiceBindingResponse) MsgEnableServiceBindingResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgEnableServiceBindingResponse.newBuilder() to construct. private MsgEnableServiceBindingResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgEnableServiceBindingResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgEnableServiceBindingResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgEnableServiceBindingResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgEnableServiceBindingResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgEnableServiceBindingResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgEnableServiceBindingResponse.class, irismod.service.Tx.MsgEnableServiceBindingResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgEnableServiceBindingResponse)) { return super.equals(obj); } irismod.service.Tx.MsgEnableServiceBindingResponse other = (irismod.service.Tx.MsgEnableServiceBindingResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgEnableServiceBindingResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgEnableServiceBindingResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgEnableServiceBindingResponse defines the Msg/EnableServiceBinding response type.
     * 
* * Protobuf type {@code irismod.service.MsgEnableServiceBindingResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgEnableServiceBindingResponse) irismod.service.Tx.MsgEnableServiceBindingResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgEnableServiceBindingResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgEnableServiceBindingResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgEnableServiceBindingResponse.class, irismod.service.Tx.MsgEnableServiceBindingResponse.Builder.class); } // Construct using irismod.service.Tx.MsgEnableServiceBindingResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgEnableServiceBindingResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgEnableServiceBindingResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgEnableServiceBindingResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgEnableServiceBindingResponse build() { irismod.service.Tx.MsgEnableServiceBindingResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgEnableServiceBindingResponse buildPartial() { irismod.service.Tx.MsgEnableServiceBindingResponse result = new irismod.service.Tx.MsgEnableServiceBindingResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgEnableServiceBindingResponse) { return mergeFrom((irismod.service.Tx.MsgEnableServiceBindingResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgEnableServiceBindingResponse other) { if (other == irismod.service.Tx.MsgEnableServiceBindingResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgEnableServiceBindingResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgEnableServiceBindingResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgEnableServiceBindingResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgEnableServiceBindingResponse) private static final irismod.service.Tx.MsgEnableServiceBindingResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgEnableServiceBindingResponse(); } public static irismod.service.Tx.MsgEnableServiceBindingResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgEnableServiceBindingResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgEnableServiceBindingResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgEnableServiceBindingResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgRefundServiceDepositOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgRefundServiceDeposit) com.google.protobuf.MessageOrBuilder { /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ java.lang.String getServiceName(); /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ com.google.protobuf.ByteString getServiceNameBytes(); /** * string provider = 2; * @return The provider. */ java.lang.String getProvider(); /** * string provider = 2; * @return The bytes for provider. */ com.google.protobuf.ByteString getProviderBytes(); /** * string owner = 3; * @return The owner. */ java.lang.String getOwner(); /** * string owner = 3; * @return The bytes for owner. */ com.google.protobuf.ByteString getOwnerBytes(); } /** *
   * MsgRefundServiceDeposit defines an SDK message to refund deposit from a service binding.
   * 
* * Protobuf type {@code irismod.service.MsgRefundServiceDeposit} */ public static final class MsgRefundServiceDeposit extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgRefundServiceDeposit) MsgRefundServiceDepositOrBuilder { private static final long serialVersionUID = 0L; // Use MsgRefundServiceDeposit.newBuilder() to construct. private MsgRefundServiceDeposit(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgRefundServiceDeposit() { serviceName_ = ""; provider_ = ""; owner_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgRefundServiceDeposit(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgRefundServiceDeposit( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); serviceName_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); provider_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); owner_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgRefundServiceDeposit_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgRefundServiceDeposit_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgRefundServiceDeposit.class, irismod.service.Tx.MsgRefundServiceDeposit.Builder.class); } public static final int SERVICE_NAME_FIELD_NUMBER = 1; private volatile java.lang.Object serviceName_; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ @java.lang.Override public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ @java.lang.Override public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROVIDER_FIELD_NUMBER = 2; private volatile java.lang.Object provider_; /** * string provider = 2; * @return The provider. */ @java.lang.Override public java.lang.String getProvider() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } } /** * string provider = 2; * @return The bytes for provider. */ @java.lang.Override public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int OWNER_FIELD_NUMBER = 3; private volatile java.lang.Object owner_; /** * string owner = 3; * @return The owner. */ @java.lang.Override public java.lang.String getOwner() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } } /** * string owner = 3; * @return The bytes for owner. */ @java.lang.Override public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getServiceNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, serviceName_); } if (!getProviderBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, provider_); } if (!getOwnerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, owner_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getServiceNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, serviceName_); } if (!getProviderBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, provider_); } if (!getOwnerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, owner_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgRefundServiceDeposit)) { return super.equals(obj); } irismod.service.Tx.MsgRefundServiceDeposit other = (irismod.service.Tx.MsgRefundServiceDeposit) obj; if (!getServiceName() .equals(other.getServiceName())) return false; if (!getProvider() .equals(other.getProvider())) return false; if (!getOwner() .equals(other.getOwner())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SERVICE_NAME_FIELD_NUMBER; hash = (53 * hash) + getServiceName().hashCode(); hash = (37 * hash) + PROVIDER_FIELD_NUMBER; hash = (53 * hash) + getProvider().hashCode(); hash = (37 * hash) + OWNER_FIELD_NUMBER; hash = (53 * hash) + getOwner().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgRefundServiceDeposit parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRefundServiceDeposit parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRefundServiceDeposit parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRefundServiceDeposit parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRefundServiceDeposit parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRefundServiceDeposit parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRefundServiceDeposit parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRefundServiceDeposit parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgRefundServiceDeposit parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRefundServiceDeposit parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgRefundServiceDeposit parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRefundServiceDeposit parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgRefundServiceDeposit prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgRefundServiceDeposit defines an SDK message to refund deposit from a service binding.
     * 
* * Protobuf type {@code irismod.service.MsgRefundServiceDeposit} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgRefundServiceDeposit) irismod.service.Tx.MsgRefundServiceDepositOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgRefundServiceDeposit_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgRefundServiceDeposit_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgRefundServiceDeposit.class, irismod.service.Tx.MsgRefundServiceDeposit.Builder.class); } // Construct using irismod.service.Tx.MsgRefundServiceDeposit.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); serviceName_ = ""; provider_ = ""; owner_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgRefundServiceDeposit_descriptor; } @java.lang.Override public irismod.service.Tx.MsgRefundServiceDeposit getDefaultInstanceForType() { return irismod.service.Tx.MsgRefundServiceDeposit.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgRefundServiceDeposit build() { irismod.service.Tx.MsgRefundServiceDeposit result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgRefundServiceDeposit buildPartial() { irismod.service.Tx.MsgRefundServiceDeposit result = new irismod.service.Tx.MsgRefundServiceDeposit(this); result.serviceName_ = serviceName_; result.provider_ = provider_; result.owner_ = owner_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgRefundServiceDeposit) { return mergeFrom((irismod.service.Tx.MsgRefundServiceDeposit)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgRefundServiceDeposit other) { if (other == irismod.service.Tx.MsgRefundServiceDeposit.getDefaultInstance()) return this; if (!other.getServiceName().isEmpty()) { serviceName_ = other.serviceName_; onChanged(); } if (!other.getProvider().isEmpty()) { provider_ = other.provider_; onChanged(); } if (!other.getOwner().isEmpty()) { owner_ = other.owner_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgRefundServiceDeposit parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgRefundServiceDeposit) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object serviceName_ = ""; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The serviceName to set. * @return This builder for chaining. */ public Builder setServiceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } serviceName_ = value; onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return This builder for chaining. */ public Builder clearServiceName() { serviceName_ = getDefaultInstance().getServiceName(); onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The bytes for serviceName to set. * @return This builder for chaining. */ public Builder setServiceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); serviceName_ = value; onChanged(); return this; } private java.lang.Object provider_ = ""; /** * string provider = 2; * @return The provider. */ public java.lang.String getProvider() { java.lang.Object ref = provider_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } else { return (java.lang.String) ref; } } /** * string provider = 2; * @return The bytes for provider. */ public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string provider = 2; * @param value The provider to set. * @return This builder for chaining. */ public Builder setProvider( java.lang.String value) { if (value == null) { throw new NullPointerException(); } provider_ = value; onChanged(); return this; } /** * string provider = 2; * @return This builder for chaining. */ public Builder clearProvider() { provider_ = getDefaultInstance().getProvider(); onChanged(); return this; } /** * string provider = 2; * @param value The bytes for provider to set. * @return This builder for chaining. */ public Builder setProviderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); provider_ = value; onChanged(); return this; } private java.lang.Object owner_ = ""; /** * string owner = 3; * @return The owner. */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } else { return (java.lang.String) ref; } } /** * string owner = 3; * @return The bytes for owner. */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string owner = 3; * @param value The owner to set. * @return This builder for chaining. */ public Builder setOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } owner_ = value; onChanged(); return this; } /** * string owner = 3; * @return This builder for chaining. */ public Builder clearOwner() { owner_ = getDefaultInstance().getOwner(); onChanged(); return this; } /** * string owner = 3; * @param value The bytes for owner to set. * @return This builder for chaining. */ public Builder setOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); owner_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgRefundServiceDeposit) } // @@protoc_insertion_point(class_scope:irismod.service.MsgRefundServiceDeposit) private static final irismod.service.Tx.MsgRefundServiceDeposit DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgRefundServiceDeposit(); } public static irismod.service.Tx.MsgRefundServiceDeposit getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgRefundServiceDeposit parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgRefundServiceDeposit(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgRefundServiceDeposit getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgRefundServiceDepositResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgRefundServiceDepositResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgRefundServiceDepositResponse defines the Msg/RefundServiceDeposit response type.
   * 
* * Protobuf type {@code irismod.service.MsgRefundServiceDepositResponse} */ public static final class MsgRefundServiceDepositResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgRefundServiceDepositResponse) MsgRefundServiceDepositResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgRefundServiceDepositResponse.newBuilder() to construct. private MsgRefundServiceDepositResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgRefundServiceDepositResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgRefundServiceDepositResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgRefundServiceDepositResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgRefundServiceDepositResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgRefundServiceDepositResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgRefundServiceDepositResponse.class, irismod.service.Tx.MsgRefundServiceDepositResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgRefundServiceDepositResponse)) { return super.equals(obj); } irismod.service.Tx.MsgRefundServiceDepositResponse other = (irismod.service.Tx.MsgRefundServiceDepositResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRefundServiceDepositResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgRefundServiceDepositResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgRefundServiceDepositResponse defines the Msg/RefundServiceDeposit response type.
     * 
* * Protobuf type {@code irismod.service.MsgRefundServiceDepositResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgRefundServiceDepositResponse) irismod.service.Tx.MsgRefundServiceDepositResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgRefundServiceDepositResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgRefundServiceDepositResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgRefundServiceDepositResponse.class, irismod.service.Tx.MsgRefundServiceDepositResponse.Builder.class); } // Construct using irismod.service.Tx.MsgRefundServiceDepositResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgRefundServiceDepositResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgRefundServiceDepositResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgRefundServiceDepositResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgRefundServiceDepositResponse build() { irismod.service.Tx.MsgRefundServiceDepositResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgRefundServiceDepositResponse buildPartial() { irismod.service.Tx.MsgRefundServiceDepositResponse result = new irismod.service.Tx.MsgRefundServiceDepositResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgRefundServiceDepositResponse) { return mergeFrom((irismod.service.Tx.MsgRefundServiceDepositResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgRefundServiceDepositResponse other) { if (other == irismod.service.Tx.MsgRefundServiceDepositResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgRefundServiceDepositResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgRefundServiceDepositResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgRefundServiceDepositResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgRefundServiceDepositResponse) private static final irismod.service.Tx.MsgRefundServiceDepositResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgRefundServiceDepositResponse(); } public static irismod.service.Tx.MsgRefundServiceDepositResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgRefundServiceDepositResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgRefundServiceDepositResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgRefundServiceDepositResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgCallServiceOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgCallService) com.google.protobuf.MessageOrBuilder { /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ java.lang.String getServiceName(); /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ com.google.protobuf.ByteString getServiceNameBytes(); /** * repeated string providers = 2; * @return A list containing the providers. */ java.util.List getProvidersList(); /** * repeated string providers = 2; * @return The count of providers. */ int getProvidersCount(); /** * repeated string providers = 2; * @param index The index of the element to return. * @return The providers at the given index. */ java.lang.String getProviders(int index); /** * repeated string providers = 2; * @param index The index of the value to return. * @return The bytes of the providers at the given index. */ com.google.protobuf.ByteString getProvidersBytes(int index); /** * string consumer = 3; * @return The consumer. */ java.lang.String getConsumer(); /** * string consumer = 3; * @return The bytes for consumer. */ com.google.protobuf.ByteString getConsumerBytes(); /** * string input = 4; * @return The input. */ java.lang.String getInput(); /** * string input = 4; * @return The bytes for input. */ com.google.protobuf.ByteString getInputBytes(); /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ java.util.List getServiceFeeCapList(); /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ cosmos.base.v1beta1.CoinOuterClass.Coin getServiceFeeCap(int index); /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ int getServiceFeeCapCount(); /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ java.util.List getServiceFeeCapOrBuilderList(); /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getServiceFeeCapOrBuilder( int index); /** * int64 timeout = 6; * @return The timeout. */ long getTimeout(); /** * bool super_mode = 7 [(.gogoproto.moretags) = "yaml:\"super_mode\""]; * @return The superMode. */ boolean getSuperMode(); /** * bool repeated = 8; * @return The repeated. */ boolean getRepeated(); /** * uint64 repeated_frequency = 9 [(.gogoproto.moretags) = "yaml:\"repeated_frequency\""]; * @return The repeatedFrequency. */ long getRepeatedFrequency(); /** * int64 repeated_total = 10 [(.gogoproto.moretags) = "yaml:\"repeated_total\""]; * @return The repeatedTotal. */ long getRepeatedTotal(); } /** *
   * MsgCallService defines an SDK message to initiate a service request context.
   * 
* * Protobuf type {@code irismod.service.MsgCallService} */ public static final class MsgCallService extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgCallService) MsgCallServiceOrBuilder { private static final long serialVersionUID = 0L; // Use MsgCallService.newBuilder() to construct. private MsgCallService(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgCallService() { serviceName_ = ""; providers_ = com.google.protobuf.LazyStringArrayList.EMPTY; consumer_ = ""; input_ = ""; serviceFeeCap_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgCallService(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgCallService( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); serviceName_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000001) != 0)) { providers_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000001; } providers_.add(s); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); consumer_ = s; break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); input_ = s; break; } case 42: { if (!((mutable_bitField0_ & 0x00000002) != 0)) { serviceFeeCap_ = new java.util.ArrayList(); mutable_bitField0_ |= 0x00000002; } serviceFeeCap_.add( input.readMessage(cosmos.base.v1beta1.CoinOuterClass.Coin.parser(), extensionRegistry)); break; } case 48: { timeout_ = input.readInt64(); break; } case 56: { superMode_ = input.readBool(); break; } case 64: { repeated_ = input.readBool(); break; } case 72: { repeatedFrequency_ = input.readUInt64(); break; } case 80: { repeatedTotal_ = input.readInt64(); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { providers_ = providers_.getUnmodifiableView(); } if (((mutable_bitField0_ & 0x00000002) != 0)) { serviceFeeCap_ = java.util.Collections.unmodifiableList(serviceFeeCap_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgCallService_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgCallService_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgCallService.class, irismod.service.Tx.MsgCallService.Builder.class); } public static final int SERVICE_NAME_FIELD_NUMBER = 1; private volatile java.lang.Object serviceName_; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ @java.lang.Override public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ @java.lang.Override public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROVIDERS_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList providers_; /** * repeated string providers = 2; * @return A list containing the providers. */ public com.google.protobuf.ProtocolStringList getProvidersList() { return providers_; } /** * repeated string providers = 2; * @return The count of providers. */ public int getProvidersCount() { return providers_.size(); } /** * repeated string providers = 2; * @param index The index of the element to return. * @return The providers at the given index. */ public java.lang.String getProviders(int index) { return providers_.get(index); } /** * repeated string providers = 2; * @param index The index of the value to return. * @return The bytes of the providers at the given index. */ public com.google.protobuf.ByteString getProvidersBytes(int index) { return providers_.getByteString(index); } public static final int CONSUMER_FIELD_NUMBER = 3; private volatile java.lang.Object consumer_; /** * string consumer = 3; * @return The consumer. */ @java.lang.Override public java.lang.String getConsumer() { java.lang.Object ref = consumer_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); consumer_ = s; return s; } } /** * string consumer = 3; * @return The bytes for consumer. */ @java.lang.Override public com.google.protobuf.ByteString getConsumerBytes() { java.lang.Object ref = consumer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); consumer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int INPUT_FIELD_NUMBER = 4; private volatile java.lang.Object input_; /** * string input = 4; * @return The input. */ @java.lang.Override public java.lang.String getInput() { java.lang.Object ref = input_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); input_ = s; return s; } } /** * string input = 4; * @return The bytes for input. */ @java.lang.Override public com.google.protobuf.ByteString getInputBytes() { java.lang.Object ref = input_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); input_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SERVICE_FEE_CAP_FIELD_NUMBER = 5; private java.util.List serviceFeeCap_; /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public java.util.List getServiceFeeCapList() { return serviceFeeCap_; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public java.util.List getServiceFeeCapOrBuilderList() { return serviceFeeCap_; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public int getServiceFeeCapCount() { return serviceFeeCap_.size(); } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public cosmos.base.v1beta1.CoinOuterClass.Coin getServiceFeeCap(int index) { return serviceFeeCap_.get(index); } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getServiceFeeCapOrBuilder( int index) { return serviceFeeCap_.get(index); } public static final int TIMEOUT_FIELD_NUMBER = 6; private long timeout_; /** * int64 timeout = 6; * @return The timeout. */ @java.lang.Override public long getTimeout() { return timeout_; } public static final int SUPER_MODE_FIELD_NUMBER = 7; private boolean superMode_; /** * bool super_mode = 7 [(.gogoproto.moretags) = "yaml:\"super_mode\""]; * @return The superMode. */ @java.lang.Override public boolean getSuperMode() { return superMode_; } public static final int REPEATED_FIELD_NUMBER = 8; private boolean repeated_; /** * bool repeated = 8; * @return The repeated. */ @java.lang.Override public boolean getRepeated() { return repeated_; } public static final int REPEATED_FREQUENCY_FIELD_NUMBER = 9; private long repeatedFrequency_; /** * uint64 repeated_frequency = 9 [(.gogoproto.moretags) = "yaml:\"repeated_frequency\""]; * @return The repeatedFrequency. */ @java.lang.Override public long getRepeatedFrequency() { return repeatedFrequency_; } public static final int REPEATED_TOTAL_FIELD_NUMBER = 10; private long repeatedTotal_; /** * int64 repeated_total = 10 [(.gogoproto.moretags) = "yaml:\"repeated_total\""]; * @return The repeatedTotal. */ @java.lang.Override public long getRepeatedTotal() { return repeatedTotal_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getServiceNameBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, serviceName_); } for (int i = 0; i < providers_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, providers_.getRaw(i)); } if (!getConsumerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, consumer_); } if (!getInputBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, input_); } for (int i = 0; i < serviceFeeCap_.size(); i++) { output.writeMessage(5, serviceFeeCap_.get(i)); } if (timeout_ != 0L) { output.writeInt64(6, timeout_); } if (superMode_ != false) { output.writeBool(7, superMode_); } if (repeated_ != false) { output.writeBool(8, repeated_); } if (repeatedFrequency_ != 0L) { output.writeUInt64(9, repeatedFrequency_); } if (repeatedTotal_ != 0L) { output.writeInt64(10, repeatedTotal_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getServiceNameBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, serviceName_); } { int dataSize = 0; for (int i = 0; i < providers_.size(); i++) { dataSize += computeStringSizeNoTag(providers_.getRaw(i)); } size += dataSize; size += 1 * getProvidersList().size(); } if (!getConsumerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, consumer_); } if (!getInputBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, input_); } for (int i = 0; i < serviceFeeCap_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, serviceFeeCap_.get(i)); } if (timeout_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(6, timeout_); } if (superMode_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(7, superMode_); } if (repeated_ != false) { size += com.google.protobuf.CodedOutputStream .computeBoolSize(8, repeated_); } if (repeatedFrequency_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(9, repeatedFrequency_); } if (repeatedTotal_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(10, repeatedTotal_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgCallService)) { return super.equals(obj); } irismod.service.Tx.MsgCallService other = (irismod.service.Tx.MsgCallService) obj; if (!getServiceName() .equals(other.getServiceName())) return false; if (!getProvidersList() .equals(other.getProvidersList())) return false; if (!getConsumer() .equals(other.getConsumer())) return false; if (!getInput() .equals(other.getInput())) return false; if (!getServiceFeeCapList() .equals(other.getServiceFeeCapList())) return false; if (getTimeout() != other.getTimeout()) return false; if (getSuperMode() != other.getSuperMode()) return false; if (getRepeated() != other.getRepeated()) return false; if (getRepeatedFrequency() != other.getRepeatedFrequency()) return false; if (getRepeatedTotal() != other.getRepeatedTotal()) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + SERVICE_NAME_FIELD_NUMBER; hash = (53 * hash) + getServiceName().hashCode(); if (getProvidersCount() > 0) { hash = (37 * hash) + PROVIDERS_FIELD_NUMBER; hash = (53 * hash) + getProvidersList().hashCode(); } hash = (37 * hash) + CONSUMER_FIELD_NUMBER; hash = (53 * hash) + getConsumer().hashCode(); hash = (37 * hash) + INPUT_FIELD_NUMBER; hash = (53 * hash) + getInput().hashCode(); if (getServiceFeeCapCount() > 0) { hash = (37 * hash) + SERVICE_FEE_CAP_FIELD_NUMBER; hash = (53 * hash) + getServiceFeeCapList().hashCode(); } hash = (37 * hash) + TIMEOUT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTimeout()); hash = (37 * hash) + SUPER_MODE_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getSuperMode()); hash = (37 * hash) + REPEATED_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( getRepeated()); hash = (37 * hash) + REPEATED_FREQUENCY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getRepeatedFrequency()); hash = (37 * hash) + REPEATED_TOTAL_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getRepeatedTotal()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgCallService parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgCallService parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgCallService parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgCallService parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgCallService parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgCallService parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgCallService parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgCallService parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgCallService parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgCallService parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgCallService parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgCallService parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgCallService prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgCallService defines an SDK message to initiate a service request context.
     * 
* * Protobuf type {@code irismod.service.MsgCallService} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgCallService) irismod.service.Tx.MsgCallServiceOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgCallService_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgCallService_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgCallService.class, irismod.service.Tx.MsgCallService.Builder.class); } // Construct using irismod.service.Tx.MsgCallService.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getServiceFeeCapFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); serviceName_ = ""; providers_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); consumer_ = ""; input_ = ""; if (serviceFeeCapBuilder_ == null) { serviceFeeCap_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); } else { serviceFeeCapBuilder_.clear(); } timeout_ = 0L; superMode_ = false; repeated_ = false; repeatedFrequency_ = 0L; repeatedTotal_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgCallService_descriptor; } @java.lang.Override public irismod.service.Tx.MsgCallService getDefaultInstanceForType() { return irismod.service.Tx.MsgCallService.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgCallService build() { irismod.service.Tx.MsgCallService result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgCallService buildPartial() { irismod.service.Tx.MsgCallService result = new irismod.service.Tx.MsgCallService(this); int from_bitField0_ = bitField0_; result.serviceName_ = serviceName_; if (((bitField0_ & 0x00000001) != 0)) { providers_ = providers_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000001); } result.providers_ = providers_; result.consumer_ = consumer_; result.input_ = input_; if (serviceFeeCapBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { serviceFeeCap_ = java.util.Collections.unmodifiableList(serviceFeeCap_); bitField0_ = (bitField0_ & ~0x00000002); } result.serviceFeeCap_ = serviceFeeCap_; } else { result.serviceFeeCap_ = serviceFeeCapBuilder_.build(); } result.timeout_ = timeout_; result.superMode_ = superMode_; result.repeated_ = repeated_; result.repeatedFrequency_ = repeatedFrequency_; result.repeatedTotal_ = repeatedTotal_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgCallService) { return mergeFrom((irismod.service.Tx.MsgCallService)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgCallService other) { if (other == irismod.service.Tx.MsgCallService.getDefaultInstance()) return this; if (!other.getServiceName().isEmpty()) { serviceName_ = other.serviceName_; onChanged(); } if (!other.providers_.isEmpty()) { if (providers_.isEmpty()) { providers_ = other.providers_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureProvidersIsMutable(); providers_.addAll(other.providers_); } onChanged(); } if (!other.getConsumer().isEmpty()) { consumer_ = other.consumer_; onChanged(); } if (!other.getInput().isEmpty()) { input_ = other.input_; onChanged(); } if (serviceFeeCapBuilder_ == null) { if (!other.serviceFeeCap_.isEmpty()) { if (serviceFeeCap_.isEmpty()) { serviceFeeCap_ = other.serviceFeeCap_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureServiceFeeCapIsMutable(); serviceFeeCap_.addAll(other.serviceFeeCap_); } onChanged(); } } else { if (!other.serviceFeeCap_.isEmpty()) { if (serviceFeeCapBuilder_.isEmpty()) { serviceFeeCapBuilder_.dispose(); serviceFeeCapBuilder_ = null; serviceFeeCap_ = other.serviceFeeCap_; bitField0_ = (bitField0_ & ~0x00000002); serviceFeeCapBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getServiceFeeCapFieldBuilder() : null; } else { serviceFeeCapBuilder_.addAllMessages(other.serviceFeeCap_); } } } if (other.getTimeout() != 0L) { setTimeout(other.getTimeout()); } if (other.getSuperMode() != false) { setSuperMode(other.getSuperMode()); } if (other.getRepeated() != false) { setRepeated(other.getRepeated()); } if (other.getRepeatedFrequency() != 0L) { setRepeatedFrequency(other.getRepeatedFrequency()); } if (other.getRepeatedTotal() != 0L) { setRepeatedTotal(other.getRepeatedTotal()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgCallService parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgCallService) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object serviceName_ = ""; /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The serviceName. */ public java.lang.String getServiceName() { java.lang.Object ref = serviceName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); serviceName_ = s; return s; } else { return (java.lang.String) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return The bytes for serviceName. */ public com.google.protobuf.ByteString getServiceNameBytes() { java.lang.Object ref = serviceName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); serviceName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The serviceName to set. * @return This builder for chaining. */ public Builder setServiceName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } serviceName_ = value; onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @return This builder for chaining. */ public Builder clearServiceName() { serviceName_ = getDefaultInstance().getServiceName(); onChanged(); return this; } /** * string service_name = 1 [(.gogoproto.moretags) = "yaml:\"service_name\""]; * @param value The bytes for serviceName to set. * @return This builder for chaining. */ public Builder setServiceNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); serviceName_ = value; onChanged(); return this; } private com.google.protobuf.LazyStringList providers_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureProvidersIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { providers_ = new com.google.protobuf.LazyStringArrayList(providers_); bitField0_ |= 0x00000001; } } /** * repeated string providers = 2; * @return A list containing the providers. */ public com.google.protobuf.ProtocolStringList getProvidersList() { return providers_.getUnmodifiableView(); } /** * repeated string providers = 2; * @return The count of providers. */ public int getProvidersCount() { return providers_.size(); } /** * repeated string providers = 2; * @param index The index of the element to return. * @return The providers at the given index. */ public java.lang.String getProviders(int index) { return providers_.get(index); } /** * repeated string providers = 2; * @param index The index of the value to return. * @return The bytes of the providers at the given index. */ public com.google.protobuf.ByteString getProvidersBytes(int index) { return providers_.getByteString(index); } /** * repeated string providers = 2; * @param index The index to set the value at. * @param value The providers to set. * @return This builder for chaining. */ public Builder setProviders( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureProvidersIsMutable(); providers_.set(index, value); onChanged(); return this; } /** * repeated string providers = 2; * @param value The providers to add. * @return This builder for chaining. */ public Builder addProviders( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureProvidersIsMutable(); providers_.add(value); onChanged(); return this; } /** * repeated string providers = 2; * @param values The providers to add. * @return This builder for chaining. */ public Builder addAllProviders( java.lang.Iterable values) { ensureProvidersIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, providers_); onChanged(); return this; } /** * repeated string providers = 2; * @return This builder for chaining. */ public Builder clearProviders() { providers_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * repeated string providers = 2; * @param value The bytes of the providers to add. * @return This builder for chaining. */ public Builder addProvidersBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureProvidersIsMutable(); providers_.add(value); onChanged(); return this; } private java.lang.Object consumer_ = ""; /** * string consumer = 3; * @return The consumer. */ public java.lang.String getConsumer() { java.lang.Object ref = consumer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); consumer_ = s; return s; } else { return (java.lang.String) ref; } } /** * string consumer = 3; * @return The bytes for consumer. */ public com.google.protobuf.ByteString getConsumerBytes() { java.lang.Object ref = consumer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); consumer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string consumer = 3; * @param value The consumer to set. * @return This builder for chaining. */ public Builder setConsumer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } consumer_ = value; onChanged(); return this; } /** * string consumer = 3; * @return This builder for chaining. */ public Builder clearConsumer() { consumer_ = getDefaultInstance().getConsumer(); onChanged(); return this; } /** * string consumer = 3; * @param value The bytes for consumer to set. * @return This builder for chaining. */ public Builder setConsumerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); consumer_ = value; onChanged(); return this; } private java.lang.Object input_ = ""; /** * string input = 4; * @return The input. */ public java.lang.String getInput() { java.lang.Object ref = input_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); input_ = s; return s; } else { return (java.lang.String) ref; } } /** * string input = 4; * @return The bytes for input. */ public com.google.protobuf.ByteString getInputBytes() { java.lang.Object ref = input_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); input_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string input = 4; * @param value The input to set. * @return This builder for chaining. */ public Builder setInput( java.lang.String value) { if (value == null) { throw new NullPointerException(); } input_ = value; onChanged(); return this; } /** * string input = 4; * @return This builder for chaining. */ public Builder clearInput() { input_ = getDefaultInstance().getInput(); onChanged(); return this; } /** * string input = 4; * @param value The bytes for input to set. * @return This builder for chaining. */ public Builder setInputBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); input_ = value; onChanged(); return this; } private java.util.List serviceFeeCap_ = java.util.Collections.emptyList(); private void ensureServiceFeeCapIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { serviceFeeCap_ = new java.util.ArrayList(serviceFeeCap_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder> serviceFeeCapBuilder_; /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getServiceFeeCapList() { if (serviceFeeCapBuilder_ == null) { return java.util.Collections.unmodifiableList(serviceFeeCap_); } else { return serviceFeeCapBuilder_.getMessageList(); } } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public int getServiceFeeCapCount() { if (serviceFeeCapBuilder_ == null) { return serviceFeeCap_.size(); } else { return serviceFeeCapBuilder_.getCount(); } } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin getServiceFeeCap(int index) { if (serviceFeeCapBuilder_ == null) { return serviceFeeCap_.get(index); } else { return serviceFeeCapBuilder_.getMessage(index); } } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder setServiceFeeCap( int index, cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (serviceFeeCapBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServiceFeeCapIsMutable(); serviceFeeCap_.set(index, value); onChanged(); } else { serviceFeeCapBuilder_.setMessage(index, value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder setServiceFeeCap( int index, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (serviceFeeCapBuilder_ == null) { ensureServiceFeeCapIsMutable(); serviceFeeCap_.set(index, builderForValue.build()); onChanged(); } else { serviceFeeCapBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addServiceFeeCap(cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (serviceFeeCapBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServiceFeeCapIsMutable(); serviceFeeCap_.add(value); onChanged(); } else { serviceFeeCapBuilder_.addMessage(value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addServiceFeeCap( int index, cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (serviceFeeCapBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServiceFeeCapIsMutable(); serviceFeeCap_.add(index, value); onChanged(); } else { serviceFeeCapBuilder_.addMessage(index, value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addServiceFeeCap( cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (serviceFeeCapBuilder_ == null) { ensureServiceFeeCapIsMutable(); serviceFeeCap_.add(builderForValue.build()); onChanged(); } else { serviceFeeCapBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addServiceFeeCap( int index, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (serviceFeeCapBuilder_ == null) { ensureServiceFeeCapIsMutable(); serviceFeeCap_.add(index, builderForValue.build()); onChanged(); } else { serviceFeeCapBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addAllServiceFeeCap( java.lang.Iterable values) { if (serviceFeeCapBuilder_ == null) { ensureServiceFeeCapIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, serviceFeeCap_); onChanged(); } else { serviceFeeCapBuilder_.addAllMessages(values); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder clearServiceFeeCap() { if (serviceFeeCapBuilder_ == null) { serviceFeeCap_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { serviceFeeCapBuilder_.clear(); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder removeServiceFeeCap(int index) { if (serviceFeeCapBuilder_ == null) { ensureServiceFeeCapIsMutable(); serviceFeeCap_.remove(index); onChanged(); } else { serviceFeeCapBuilder_.remove(index); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder getServiceFeeCapBuilder( int index) { return getServiceFeeCapFieldBuilder().getBuilder(index); } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getServiceFeeCapOrBuilder( int index) { if (serviceFeeCapBuilder_ == null) { return serviceFeeCap_.get(index); } else { return serviceFeeCapBuilder_.getMessageOrBuilder(index); } } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getServiceFeeCapOrBuilderList() { if (serviceFeeCapBuilder_ != null) { return serviceFeeCapBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(serviceFeeCap_); } } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder addServiceFeeCapBuilder() { return getServiceFeeCapFieldBuilder().addBuilder( cosmos.base.v1beta1.CoinOuterClass.Coin.getDefaultInstance()); } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder addServiceFeeCapBuilder( int index) { return getServiceFeeCapFieldBuilder().addBuilder( index, cosmos.base.v1beta1.CoinOuterClass.Coin.getDefaultInstance()); } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 5 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getServiceFeeCapBuilderList() { return getServiceFeeCapFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder> getServiceFeeCapFieldBuilder() { if (serviceFeeCapBuilder_ == null) { serviceFeeCapBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder>( serviceFeeCap_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); serviceFeeCap_ = null; } return serviceFeeCapBuilder_; } private long timeout_ ; /** * int64 timeout = 6; * @return The timeout. */ @java.lang.Override public long getTimeout() { return timeout_; } /** * int64 timeout = 6; * @param value The timeout to set. * @return This builder for chaining. */ public Builder setTimeout(long value) { timeout_ = value; onChanged(); return this; } /** * int64 timeout = 6; * @return This builder for chaining. */ public Builder clearTimeout() { timeout_ = 0L; onChanged(); return this; } private boolean superMode_ ; /** * bool super_mode = 7 [(.gogoproto.moretags) = "yaml:\"super_mode\""]; * @return The superMode. */ @java.lang.Override public boolean getSuperMode() { return superMode_; } /** * bool super_mode = 7 [(.gogoproto.moretags) = "yaml:\"super_mode\""]; * @param value The superMode to set. * @return This builder for chaining. */ public Builder setSuperMode(boolean value) { superMode_ = value; onChanged(); return this; } /** * bool super_mode = 7 [(.gogoproto.moretags) = "yaml:\"super_mode\""]; * @return This builder for chaining. */ public Builder clearSuperMode() { superMode_ = false; onChanged(); return this; } private boolean repeated_ ; /** * bool repeated = 8; * @return The repeated. */ @java.lang.Override public boolean getRepeated() { return repeated_; } /** * bool repeated = 8; * @param value The repeated to set. * @return This builder for chaining. */ public Builder setRepeated(boolean value) { repeated_ = value; onChanged(); return this; } /** * bool repeated = 8; * @return This builder for chaining. */ public Builder clearRepeated() { repeated_ = false; onChanged(); return this; } private long repeatedFrequency_ ; /** * uint64 repeated_frequency = 9 [(.gogoproto.moretags) = "yaml:\"repeated_frequency\""]; * @return The repeatedFrequency. */ @java.lang.Override public long getRepeatedFrequency() { return repeatedFrequency_; } /** * uint64 repeated_frequency = 9 [(.gogoproto.moretags) = "yaml:\"repeated_frequency\""]; * @param value The repeatedFrequency to set. * @return This builder for chaining. */ public Builder setRepeatedFrequency(long value) { repeatedFrequency_ = value; onChanged(); return this; } /** * uint64 repeated_frequency = 9 [(.gogoproto.moretags) = "yaml:\"repeated_frequency\""]; * @return This builder for chaining. */ public Builder clearRepeatedFrequency() { repeatedFrequency_ = 0L; onChanged(); return this; } private long repeatedTotal_ ; /** * int64 repeated_total = 10 [(.gogoproto.moretags) = "yaml:\"repeated_total\""]; * @return The repeatedTotal. */ @java.lang.Override public long getRepeatedTotal() { return repeatedTotal_; } /** * int64 repeated_total = 10 [(.gogoproto.moretags) = "yaml:\"repeated_total\""]; * @param value The repeatedTotal to set. * @return This builder for chaining. */ public Builder setRepeatedTotal(long value) { repeatedTotal_ = value; onChanged(); return this; } /** * int64 repeated_total = 10 [(.gogoproto.moretags) = "yaml:\"repeated_total\""]; * @return This builder for chaining. */ public Builder clearRepeatedTotal() { repeatedTotal_ = 0L; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgCallService) } // @@protoc_insertion_point(class_scope:irismod.service.MsgCallService) private static final irismod.service.Tx.MsgCallService DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgCallService(); } public static irismod.service.Tx.MsgCallService getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgCallService parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgCallService(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgCallService getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgCallServiceResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgCallServiceResponse) com.google.protobuf.MessageOrBuilder { /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ java.lang.String getRequestContextId(); /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ com.google.protobuf.ByteString getRequestContextIdBytes(); } /** *
   * MsgCallServiceResponse defines the Msg/CallService response type.
   * 
* * Protobuf type {@code irismod.service.MsgCallServiceResponse} */ public static final class MsgCallServiceResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgCallServiceResponse) MsgCallServiceResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgCallServiceResponse.newBuilder() to construct. private MsgCallServiceResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgCallServiceResponse() { requestContextId_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgCallServiceResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgCallServiceResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); requestContextId_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgCallServiceResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgCallServiceResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgCallServiceResponse.class, irismod.service.Tx.MsgCallServiceResponse.Builder.class); } public static final int REQUEST_CONTEXT_ID_FIELD_NUMBER = 1; private volatile java.lang.Object requestContextId_; /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ @java.lang.Override public java.lang.String getRequestContextId() { java.lang.Object ref = requestContextId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestContextId_ = s; return s; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ @java.lang.Override public com.google.protobuf.ByteString getRequestContextIdBytes() { java.lang.Object ref = requestContextId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestContextId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getRequestContextIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, requestContextId_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getRequestContextIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, requestContextId_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgCallServiceResponse)) { return super.equals(obj); } irismod.service.Tx.MsgCallServiceResponse other = (irismod.service.Tx.MsgCallServiceResponse) obj; if (!getRequestContextId() .equals(other.getRequestContextId())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + REQUEST_CONTEXT_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestContextId().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgCallServiceResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgCallServiceResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgCallServiceResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgCallServiceResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgCallServiceResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgCallServiceResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgCallServiceResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgCallServiceResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgCallServiceResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgCallServiceResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgCallServiceResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgCallServiceResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgCallServiceResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgCallServiceResponse defines the Msg/CallService response type.
     * 
* * Protobuf type {@code irismod.service.MsgCallServiceResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgCallServiceResponse) irismod.service.Tx.MsgCallServiceResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgCallServiceResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgCallServiceResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgCallServiceResponse.class, irismod.service.Tx.MsgCallServiceResponse.Builder.class); } // Construct using irismod.service.Tx.MsgCallServiceResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); requestContextId_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgCallServiceResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgCallServiceResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgCallServiceResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgCallServiceResponse build() { irismod.service.Tx.MsgCallServiceResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgCallServiceResponse buildPartial() { irismod.service.Tx.MsgCallServiceResponse result = new irismod.service.Tx.MsgCallServiceResponse(this); result.requestContextId_ = requestContextId_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgCallServiceResponse) { return mergeFrom((irismod.service.Tx.MsgCallServiceResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgCallServiceResponse other) { if (other == irismod.service.Tx.MsgCallServiceResponse.getDefaultInstance()) return this; if (!other.getRequestContextId().isEmpty()) { requestContextId_ = other.requestContextId_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgCallServiceResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgCallServiceResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object requestContextId_ = ""; /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ public java.lang.String getRequestContextId() { java.lang.Object ref = requestContextId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestContextId_ = s; return s; } else { return (java.lang.String) ref; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ public com.google.protobuf.ByteString getRequestContextIdBytes() { java.lang.Object ref = requestContextId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestContextId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @param value The requestContextId to set. * @return This builder for chaining. */ public Builder setRequestContextId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } requestContextId_ = value; onChanged(); return this; } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return This builder for chaining. */ public Builder clearRequestContextId() { requestContextId_ = getDefaultInstance().getRequestContextId(); onChanged(); return this; } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @param value The bytes for requestContextId to set. * @return This builder for chaining. */ public Builder setRequestContextIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requestContextId_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgCallServiceResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgCallServiceResponse) private static final irismod.service.Tx.MsgCallServiceResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgCallServiceResponse(); } public static irismod.service.Tx.MsgCallServiceResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgCallServiceResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgCallServiceResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgCallServiceResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgRespondServiceOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgRespondService) com.google.protobuf.MessageOrBuilder { /** * string request_id = 1 [(.gogoproto.moretags) = "yaml:\"request_id\""]; * @return The requestId. */ java.lang.String getRequestId(); /** * string request_id = 1 [(.gogoproto.moretags) = "yaml:\"request_id\""]; * @return The bytes for requestId. */ com.google.protobuf.ByteString getRequestIdBytes(); /** * string provider = 2; * @return The provider. */ java.lang.String getProvider(); /** * string provider = 2; * @return The bytes for provider. */ com.google.protobuf.ByteString getProviderBytes(); /** * string result = 3; * @return The result. */ java.lang.String getResult(); /** * string result = 3; * @return The bytes for result. */ com.google.protobuf.ByteString getResultBytes(); /** * string output = 4; * @return The output. */ java.lang.String getOutput(); /** * string output = 4; * @return The bytes for output. */ com.google.protobuf.ByteString getOutputBytes(); } /** *
   * MsgRespondService defines an SDK message to respond a service request.
   * 
* * Protobuf type {@code irismod.service.MsgRespondService} */ public static final class MsgRespondService extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgRespondService) MsgRespondServiceOrBuilder { private static final long serialVersionUID = 0L; // Use MsgRespondService.newBuilder() to construct. private MsgRespondService(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgRespondService() { requestId_ = ""; provider_ = ""; result_ = ""; output_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgRespondService(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgRespondService( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); requestId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); provider_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); result_ = s; break; } case 34: { java.lang.String s = input.readStringRequireUtf8(); output_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgRespondService_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgRespondService_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgRespondService.class, irismod.service.Tx.MsgRespondService.Builder.class); } public static final int REQUEST_ID_FIELD_NUMBER = 1; private volatile java.lang.Object requestId_; /** * string request_id = 1 [(.gogoproto.moretags) = "yaml:\"request_id\""]; * @return The requestId. */ @java.lang.Override public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } } /** * string request_id = 1 [(.gogoproto.moretags) = "yaml:\"request_id\""]; * @return The bytes for requestId. */ @java.lang.Override public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROVIDER_FIELD_NUMBER = 2; private volatile java.lang.Object provider_; /** * string provider = 2; * @return The provider. */ @java.lang.Override public java.lang.String getProvider() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } } /** * string provider = 2; * @return The bytes for provider. */ @java.lang.Override public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int RESULT_FIELD_NUMBER = 3; private volatile java.lang.Object result_; /** * string result = 3; * @return The result. */ @java.lang.Override public java.lang.String getResult() { java.lang.Object ref = result_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); result_ = s; return s; } } /** * string result = 3; * @return The bytes for result. */ @java.lang.Override public com.google.protobuf.ByteString getResultBytes() { java.lang.Object ref = result_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); result_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int OUTPUT_FIELD_NUMBER = 4; private volatile java.lang.Object output_; /** * string output = 4; * @return The output. */ @java.lang.Override public java.lang.String getOutput() { java.lang.Object ref = output_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); output_ = s; return s; } } /** * string output = 4; * @return The bytes for output. */ @java.lang.Override public com.google.protobuf.ByteString getOutputBytes() { java.lang.Object ref = output_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); output_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getRequestIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, requestId_); } if (!getProviderBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, provider_); } if (!getResultBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, result_); } if (!getOutputBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 4, output_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getRequestIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, requestId_); } if (!getProviderBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, provider_); } if (!getResultBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, result_); } if (!getOutputBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, output_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgRespondService)) { return super.equals(obj); } irismod.service.Tx.MsgRespondService other = (irismod.service.Tx.MsgRespondService) obj; if (!getRequestId() .equals(other.getRequestId())) return false; if (!getProvider() .equals(other.getProvider())) return false; if (!getResult() .equals(other.getResult())) return false; if (!getOutput() .equals(other.getOutput())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + REQUEST_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestId().hashCode(); hash = (37 * hash) + PROVIDER_FIELD_NUMBER; hash = (53 * hash) + getProvider().hashCode(); hash = (37 * hash) + RESULT_FIELD_NUMBER; hash = (53 * hash) + getResult().hashCode(); hash = (37 * hash) + OUTPUT_FIELD_NUMBER; hash = (53 * hash) + getOutput().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgRespondService parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRespondService parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRespondService parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRespondService parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRespondService parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRespondService parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRespondService parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRespondService parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgRespondService parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRespondService parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgRespondService parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRespondService parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgRespondService prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgRespondService defines an SDK message to respond a service request.
     * 
* * Protobuf type {@code irismod.service.MsgRespondService} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgRespondService) irismod.service.Tx.MsgRespondServiceOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgRespondService_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgRespondService_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgRespondService.class, irismod.service.Tx.MsgRespondService.Builder.class); } // Construct using irismod.service.Tx.MsgRespondService.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); requestId_ = ""; provider_ = ""; result_ = ""; output_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgRespondService_descriptor; } @java.lang.Override public irismod.service.Tx.MsgRespondService getDefaultInstanceForType() { return irismod.service.Tx.MsgRespondService.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgRespondService build() { irismod.service.Tx.MsgRespondService result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgRespondService buildPartial() { irismod.service.Tx.MsgRespondService result = new irismod.service.Tx.MsgRespondService(this); result.requestId_ = requestId_; result.provider_ = provider_; result.result_ = result_; result.output_ = output_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgRespondService) { return mergeFrom((irismod.service.Tx.MsgRespondService)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgRespondService other) { if (other == irismod.service.Tx.MsgRespondService.getDefaultInstance()) return this; if (!other.getRequestId().isEmpty()) { requestId_ = other.requestId_; onChanged(); } if (!other.getProvider().isEmpty()) { provider_ = other.provider_; onChanged(); } if (!other.getResult().isEmpty()) { result_ = other.result_; onChanged(); } if (!other.getOutput().isEmpty()) { output_ = other.output_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgRespondService parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgRespondService) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object requestId_ = ""; /** * string request_id = 1 [(.gogoproto.moretags) = "yaml:\"request_id\""]; * @return The requestId. */ public java.lang.String getRequestId() { java.lang.Object ref = requestId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestId_ = s; return s; } else { return (java.lang.String) ref; } } /** * string request_id = 1 [(.gogoproto.moretags) = "yaml:\"request_id\""]; * @return The bytes for requestId. */ public com.google.protobuf.ByteString getRequestIdBytes() { java.lang.Object ref = requestId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string request_id = 1 [(.gogoproto.moretags) = "yaml:\"request_id\""]; * @param value The requestId to set. * @return This builder for chaining. */ public Builder setRequestId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } requestId_ = value; onChanged(); return this; } /** * string request_id = 1 [(.gogoproto.moretags) = "yaml:\"request_id\""]; * @return This builder for chaining. */ public Builder clearRequestId() { requestId_ = getDefaultInstance().getRequestId(); onChanged(); return this; } /** * string request_id = 1 [(.gogoproto.moretags) = "yaml:\"request_id\""]; * @param value The bytes for requestId to set. * @return This builder for chaining. */ public Builder setRequestIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requestId_ = value; onChanged(); return this; } private java.lang.Object provider_ = ""; /** * string provider = 2; * @return The provider. */ public java.lang.String getProvider() { java.lang.Object ref = provider_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } else { return (java.lang.String) ref; } } /** * string provider = 2; * @return The bytes for provider. */ public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string provider = 2; * @param value The provider to set. * @return This builder for chaining. */ public Builder setProvider( java.lang.String value) { if (value == null) { throw new NullPointerException(); } provider_ = value; onChanged(); return this; } /** * string provider = 2; * @return This builder for chaining. */ public Builder clearProvider() { provider_ = getDefaultInstance().getProvider(); onChanged(); return this; } /** * string provider = 2; * @param value The bytes for provider to set. * @return This builder for chaining. */ public Builder setProviderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); provider_ = value; onChanged(); return this; } private java.lang.Object result_ = ""; /** * string result = 3; * @return The result. */ public java.lang.String getResult() { java.lang.Object ref = result_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); result_ = s; return s; } else { return (java.lang.String) ref; } } /** * string result = 3; * @return The bytes for result. */ public com.google.protobuf.ByteString getResultBytes() { java.lang.Object ref = result_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); result_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string result = 3; * @param value The result to set. * @return This builder for chaining. */ public Builder setResult( java.lang.String value) { if (value == null) { throw new NullPointerException(); } result_ = value; onChanged(); return this; } /** * string result = 3; * @return This builder for chaining. */ public Builder clearResult() { result_ = getDefaultInstance().getResult(); onChanged(); return this; } /** * string result = 3; * @param value The bytes for result to set. * @return This builder for chaining. */ public Builder setResultBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); result_ = value; onChanged(); return this; } private java.lang.Object output_ = ""; /** * string output = 4; * @return The output. */ public java.lang.String getOutput() { java.lang.Object ref = output_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); output_ = s; return s; } else { return (java.lang.String) ref; } } /** * string output = 4; * @return The bytes for output. */ public com.google.protobuf.ByteString getOutputBytes() { java.lang.Object ref = output_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); output_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string output = 4; * @param value The output to set. * @return This builder for chaining. */ public Builder setOutput( java.lang.String value) { if (value == null) { throw new NullPointerException(); } output_ = value; onChanged(); return this; } /** * string output = 4; * @return This builder for chaining. */ public Builder clearOutput() { output_ = getDefaultInstance().getOutput(); onChanged(); return this; } /** * string output = 4; * @param value The bytes for output to set. * @return This builder for chaining. */ public Builder setOutputBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); output_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgRespondService) } // @@protoc_insertion_point(class_scope:irismod.service.MsgRespondService) private static final irismod.service.Tx.MsgRespondService DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgRespondService(); } public static irismod.service.Tx.MsgRespondService getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgRespondService parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgRespondService(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgRespondService getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgRespondServiceResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgRespondServiceResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgRespondService defines the Msg/RespondService response type.
   * 
* * Protobuf type {@code irismod.service.MsgRespondServiceResponse} */ public static final class MsgRespondServiceResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgRespondServiceResponse) MsgRespondServiceResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgRespondServiceResponse.newBuilder() to construct. private MsgRespondServiceResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgRespondServiceResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgRespondServiceResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgRespondServiceResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgRespondServiceResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgRespondServiceResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgRespondServiceResponse.class, irismod.service.Tx.MsgRespondServiceResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgRespondServiceResponse)) { return super.equals(obj); } irismod.service.Tx.MsgRespondServiceResponse other = (irismod.service.Tx.MsgRespondServiceResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgRespondServiceResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRespondServiceResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRespondServiceResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRespondServiceResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRespondServiceResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgRespondServiceResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgRespondServiceResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRespondServiceResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgRespondServiceResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRespondServiceResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgRespondServiceResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgRespondServiceResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgRespondServiceResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgRespondService defines the Msg/RespondService response type.
     * 
* * Protobuf type {@code irismod.service.MsgRespondServiceResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgRespondServiceResponse) irismod.service.Tx.MsgRespondServiceResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgRespondServiceResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgRespondServiceResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgRespondServiceResponse.class, irismod.service.Tx.MsgRespondServiceResponse.Builder.class); } // Construct using irismod.service.Tx.MsgRespondServiceResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgRespondServiceResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgRespondServiceResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgRespondServiceResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgRespondServiceResponse build() { irismod.service.Tx.MsgRespondServiceResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgRespondServiceResponse buildPartial() { irismod.service.Tx.MsgRespondServiceResponse result = new irismod.service.Tx.MsgRespondServiceResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgRespondServiceResponse) { return mergeFrom((irismod.service.Tx.MsgRespondServiceResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgRespondServiceResponse other) { if (other == irismod.service.Tx.MsgRespondServiceResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgRespondServiceResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgRespondServiceResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgRespondServiceResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgRespondServiceResponse) private static final irismod.service.Tx.MsgRespondServiceResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgRespondServiceResponse(); } public static irismod.service.Tx.MsgRespondServiceResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgRespondServiceResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgRespondServiceResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgRespondServiceResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgPauseRequestContextOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgPauseRequestContext) com.google.protobuf.MessageOrBuilder { /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ java.lang.String getRequestContextId(); /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ com.google.protobuf.ByteString getRequestContextIdBytes(); /** * string consumer = 2; * @return The consumer. */ java.lang.String getConsumer(); /** * string consumer = 2; * @return The bytes for consumer. */ com.google.protobuf.ByteString getConsumerBytes(); } /** *
   * MsgPauseRequestContext defines an SDK message to pause a service request.
   * 
* * Protobuf type {@code irismod.service.MsgPauseRequestContext} */ public static final class MsgPauseRequestContext extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgPauseRequestContext) MsgPauseRequestContextOrBuilder { private static final long serialVersionUID = 0L; // Use MsgPauseRequestContext.newBuilder() to construct. private MsgPauseRequestContext(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgPauseRequestContext() { requestContextId_ = ""; consumer_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgPauseRequestContext(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgPauseRequestContext( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); requestContextId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); consumer_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgPauseRequestContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgPauseRequestContext_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgPauseRequestContext.class, irismod.service.Tx.MsgPauseRequestContext.Builder.class); } public static final int REQUEST_CONTEXT_ID_FIELD_NUMBER = 1; private volatile java.lang.Object requestContextId_; /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ @java.lang.Override public java.lang.String getRequestContextId() { java.lang.Object ref = requestContextId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestContextId_ = s; return s; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ @java.lang.Override public com.google.protobuf.ByteString getRequestContextIdBytes() { java.lang.Object ref = requestContextId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestContextId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONSUMER_FIELD_NUMBER = 2; private volatile java.lang.Object consumer_; /** * string consumer = 2; * @return The consumer. */ @java.lang.Override public java.lang.String getConsumer() { java.lang.Object ref = consumer_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); consumer_ = s; return s; } } /** * string consumer = 2; * @return The bytes for consumer. */ @java.lang.Override public com.google.protobuf.ByteString getConsumerBytes() { java.lang.Object ref = consumer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); consumer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getRequestContextIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, requestContextId_); } if (!getConsumerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, consumer_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getRequestContextIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, requestContextId_); } if (!getConsumerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, consumer_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgPauseRequestContext)) { return super.equals(obj); } irismod.service.Tx.MsgPauseRequestContext other = (irismod.service.Tx.MsgPauseRequestContext) obj; if (!getRequestContextId() .equals(other.getRequestContextId())) return false; if (!getConsumer() .equals(other.getConsumer())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + REQUEST_CONTEXT_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestContextId().hashCode(); hash = (37 * hash) + CONSUMER_FIELD_NUMBER; hash = (53 * hash) + getConsumer().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgPauseRequestContext parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgPauseRequestContext parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgPauseRequestContext parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgPauseRequestContext parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgPauseRequestContext parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgPauseRequestContext parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgPauseRequestContext parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgPauseRequestContext parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgPauseRequestContext parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgPauseRequestContext parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgPauseRequestContext parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgPauseRequestContext parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgPauseRequestContext prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgPauseRequestContext defines an SDK message to pause a service request.
     * 
* * Protobuf type {@code irismod.service.MsgPauseRequestContext} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgPauseRequestContext) irismod.service.Tx.MsgPauseRequestContextOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgPauseRequestContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgPauseRequestContext_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgPauseRequestContext.class, irismod.service.Tx.MsgPauseRequestContext.Builder.class); } // Construct using irismod.service.Tx.MsgPauseRequestContext.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); requestContextId_ = ""; consumer_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgPauseRequestContext_descriptor; } @java.lang.Override public irismod.service.Tx.MsgPauseRequestContext getDefaultInstanceForType() { return irismod.service.Tx.MsgPauseRequestContext.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgPauseRequestContext build() { irismod.service.Tx.MsgPauseRequestContext result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgPauseRequestContext buildPartial() { irismod.service.Tx.MsgPauseRequestContext result = new irismod.service.Tx.MsgPauseRequestContext(this); result.requestContextId_ = requestContextId_; result.consumer_ = consumer_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgPauseRequestContext) { return mergeFrom((irismod.service.Tx.MsgPauseRequestContext)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgPauseRequestContext other) { if (other == irismod.service.Tx.MsgPauseRequestContext.getDefaultInstance()) return this; if (!other.getRequestContextId().isEmpty()) { requestContextId_ = other.requestContextId_; onChanged(); } if (!other.getConsumer().isEmpty()) { consumer_ = other.consumer_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgPauseRequestContext parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgPauseRequestContext) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object requestContextId_ = ""; /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ public java.lang.String getRequestContextId() { java.lang.Object ref = requestContextId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestContextId_ = s; return s; } else { return (java.lang.String) ref; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ public com.google.protobuf.ByteString getRequestContextIdBytes() { java.lang.Object ref = requestContextId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestContextId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @param value The requestContextId to set. * @return This builder for chaining. */ public Builder setRequestContextId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } requestContextId_ = value; onChanged(); return this; } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return This builder for chaining. */ public Builder clearRequestContextId() { requestContextId_ = getDefaultInstance().getRequestContextId(); onChanged(); return this; } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @param value The bytes for requestContextId to set. * @return This builder for chaining. */ public Builder setRequestContextIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requestContextId_ = value; onChanged(); return this; } private java.lang.Object consumer_ = ""; /** * string consumer = 2; * @return The consumer. */ public java.lang.String getConsumer() { java.lang.Object ref = consumer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); consumer_ = s; return s; } else { return (java.lang.String) ref; } } /** * string consumer = 2; * @return The bytes for consumer. */ public com.google.protobuf.ByteString getConsumerBytes() { java.lang.Object ref = consumer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); consumer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string consumer = 2; * @param value The consumer to set. * @return This builder for chaining. */ public Builder setConsumer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } consumer_ = value; onChanged(); return this; } /** * string consumer = 2; * @return This builder for chaining. */ public Builder clearConsumer() { consumer_ = getDefaultInstance().getConsumer(); onChanged(); return this; } /** * string consumer = 2; * @param value The bytes for consumer to set. * @return This builder for chaining. */ public Builder setConsumerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); consumer_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgPauseRequestContext) } // @@protoc_insertion_point(class_scope:irismod.service.MsgPauseRequestContext) private static final irismod.service.Tx.MsgPauseRequestContext DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgPauseRequestContext(); } public static irismod.service.Tx.MsgPauseRequestContext getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgPauseRequestContext parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgPauseRequestContext(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgPauseRequestContext getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgPauseRequestContextResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgPauseRequestContextResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgPauseRequestContextResponse defines the Msg/PauseRequestContext response type.
   * 
* * Protobuf type {@code irismod.service.MsgPauseRequestContextResponse} */ public static final class MsgPauseRequestContextResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgPauseRequestContextResponse) MsgPauseRequestContextResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgPauseRequestContextResponse.newBuilder() to construct. private MsgPauseRequestContextResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgPauseRequestContextResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgPauseRequestContextResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgPauseRequestContextResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgPauseRequestContextResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgPauseRequestContextResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgPauseRequestContextResponse.class, irismod.service.Tx.MsgPauseRequestContextResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgPauseRequestContextResponse)) { return super.equals(obj); } irismod.service.Tx.MsgPauseRequestContextResponse other = (irismod.service.Tx.MsgPauseRequestContextResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgPauseRequestContextResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgPauseRequestContextResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgPauseRequestContextResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgPauseRequestContextResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgPauseRequestContextResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgPauseRequestContextResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgPauseRequestContextResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgPauseRequestContextResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgPauseRequestContextResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgPauseRequestContextResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgPauseRequestContextResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgPauseRequestContextResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgPauseRequestContextResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgPauseRequestContextResponse defines the Msg/PauseRequestContext response type.
     * 
* * Protobuf type {@code irismod.service.MsgPauseRequestContextResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgPauseRequestContextResponse) irismod.service.Tx.MsgPauseRequestContextResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgPauseRequestContextResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgPauseRequestContextResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgPauseRequestContextResponse.class, irismod.service.Tx.MsgPauseRequestContextResponse.Builder.class); } // Construct using irismod.service.Tx.MsgPauseRequestContextResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgPauseRequestContextResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgPauseRequestContextResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgPauseRequestContextResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgPauseRequestContextResponse build() { irismod.service.Tx.MsgPauseRequestContextResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgPauseRequestContextResponse buildPartial() { irismod.service.Tx.MsgPauseRequestContextResponse result = new irismod.service.Tx.MsgPauseRequestContextResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgPauseRequestContextResponse) { return mergeFrom((irismod.service.Tx.MsgPauseRequestContextResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgPauseRequestContextResponse other) { if (other == irismod.service.Tx.MsgPauseRequestContextResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgPauseRequestContextResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgPauseRequestContextResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgPauseRequestContextResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgPauseRequestContextResponse) private static final irismod.service.Tx.MsgPauseRequestContextResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgPauseRequestContextResponse(); } public static irismod.service.Tx.MsgPauseRequestContextResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgPauseRequestContextResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgPauseRequestContextResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgPauseRequestContextResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgStartRequestContextOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgStartRequestContext) com.google.protobuf.MessageOrBuilder { /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ java.lang.String getRequestContextId(); /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ com.google.protobuf.ByteString getRequestContextIdBytes(); /** * string consumer = 2; * @return The consumer. */ java.lang.String getConsumer(); /** * string consumer = 2; * @return The bytes for consumer. */ com.google.protobuf.ByteString getConsumerBytes(); } /** *
   * MsgStartRequestContext defines an SDK message to resume a service request.
   * 
* * Protobuf type {@code irismod.service.MsgStartRequestContext} */ public static final class MsgStartRequestContext extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgStartRequestContext) MsgStartRequestContextOrBuilder { private static final long serialVersionUID = 0L; // Use MsgStartRequestContext.newBuilder() to construct. private MsgStartRequestContext(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgStartRequestContext() { requestContextId_ = ""; consumer_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgStartRequestContext(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgStartRequestContext( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); requestContextId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); consumer_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgStartRequestContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgStartRequestContext_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgStartRequestContext.class, irismod.service.Tx.MsgStartRequestContext.Builder.class); } public static final int REQUEST_CONTEXT_ID_FIELD_NUMBER = 1; private volatile java.lang.Object requestContextId_; /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ @java.lang.Override public java.lang.String getRequestContextId() { java.lang.Object ref = requestContextId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestContextId_ = s; return s; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ @java.lang.Override public com.google.protobuf.ByteString getRequestContextIdBytes() { java.lang.Object ref = requestContextId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestContextId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONSUMER_FIELD_NUMBER = 2; private volatile java.lang.Object consumer_; /** * string consumer = 2; * @return The consumer. */ @java.lang.Override public java.lang.String getConsumer() { java.lang.Object ref = consumer_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); consumer_ = s; return s; } } /** * string consumer = 2; * @return The bytes for consumer. */ @java.lang.Override public com.google.protobuf.ByteString getConsumerBytes() { java.lang.Object ref = consumer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); consumer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getRequestContextIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, requestContextId_); } if (!getConsumerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, consumer_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getRequestContextIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, requestContextId_); } if (!getConsumerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, consumer_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgStartRequestContext)) { return super.equals(obj); } irismod.service.Tx.MsgStartRequestContext other = (irismod.service.Tx.MsgStartRequestContext) obj; if (!getRequestContextId() .equals(other.getRequestContextId())) return false; if (!getConsumer() .equals(other.getConsumer())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + REQUEST_CONTEXT_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestContextId().hashCode(); hash = (37 * hash) + CONSUMER_FIELD_NUMBER; hash = (53 * hash) + getConsumer().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgStartRequestContext parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgStartRequestContext parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgStartRequestContext parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgStartRequestContext parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgStartRequestContext parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgStartRequestContext parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgStartRequestContext parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgStartRequestContext parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgStartRequestContext parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgStartRequestContext parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgStartRequestContext parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgStartRequestContext parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgStartRequestContext prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgStartRequestContext defines an SDK message to resume a service request.
     * 
* * Protobuf type {@code irismod.service.MsgStartRequestContext} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgStartRequestContext) irismod.service.Tx.MsgStartRequestContextOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgStartRequestContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgStartRequestContext_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgStartRequestContext.class, irismod.service.Tx.MsgStartRequestContext.Builder.class); } // Construct using irismod.service.Tx.MsgStartRequestContext.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); requestContextId_ = ""; consumer_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgStartRequestContext_descriptor; } @java.lang.Override public irismod.service.Tx.MsgStartRequestContext getDefaultInstanceForType() { return irismod.service.Tx.MsgStartRequestContext.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgStartRequestContext build() { irismod.service.Tx.MsgStartRequestContext result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgStartRequestContext buildPartial() { irismod.service.Tx.MsgStartRequestContext result = new irismod.service.Tx.MsgStartRequestContext(this); result.requestContextId_ = requestContextId_; result.consumer_ = consumer_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgStartRequestContext) { return mergeFrom((irismod.service.Tx.MsgStartRequestContext)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgStartRequestContext other) { if (other == irismod.service.Tx.MsgStartRequestContext.getDefaultInstance()) return this; if (!other.getRequestContextId().isEmpty()) { requestContextId_ = other.requestContextId_; onChanged(); } if (!other.getConsumer().isEmpty()) { consumer_ = other.consumer_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgStartRequestContext parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgStartRequestContext) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object requestContextId_ = ""; /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ public java.lang.String getRequestContextId() { java.lang.Object ref = requestContextId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestContextId_ = s; return s; } else { return (java.lang.String) ref; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ public com.google.protobuf.ByteString getRequestContextIdBytes() { java.lang.Object ref = requestContextId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestContextId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @param value The requestContextId to set. * @return This builder for chaining. */ public Builder setRequestContextId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } requestContextId_ = value; onChanged(); return this; } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return This builder for chaining. */ public Builder clearRequestContextId() { requestContextId_ = getDefaultInstance().getRequestContextId(); onChanged(); return this; } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @param value The bytes for requestContextId to set. * @return This builder for chaining. */ public Builder setRequestContextIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requestContextId_ = value; onChanged(); return this; } private java.lang.Object consumer_ = ""; /** * string consumer = 2; * @return The consumer. */ public java.lang.String getConsumer() { java.lang.Object ref = consumer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); consumer_ = s; return s; } else { return (java.lang.String) ref; } } /** * string consumer = 2; * @return The bytes for consumer. */ public com.google.protobuf.ByteString getConsumerBytes() { java.lang.Object ref = consumer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); consumer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string consumer = 2; * @param value The consumer to set. * @return This builder for chaining. */ public Builder setConsumer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } consumer_ = value; onChanged(); return this; } /** * string consumer = 2; * @return This builder for chaining. */ public Builder clearConsumer() { consumer_ = getDefaultInstance().getConsumer(); onChanged(); return this; } /** * string consumer = 2; * @param value The bytes for consumer to set. * @return This builder for chaining. */ public Builder setConsumerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); consumer_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgStartRequestContext) } // @@protoc_insertion_point(class_scope:irismod.service.MsgStartRequestContext) private static final irismod.service.Tx.MsgStartRequestContext DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgStartRequestContext(); } public static irismod.service.Tx.MsgStartRequestContext getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgStartRequestContext parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgStartRequestContext(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgStartRequestContext getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgStartRequestContextResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgStartRequestContextResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgStartRequestContextResponse defines the Msg/StartRequestContext response type.
   * 
* * Protobuf type {@code irismod.service.MsgStartRequestContextResponse} */ public static final class MsgStartRequestContextResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgStartRequestContextResponse) MsgStartRequestContextResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgStartRequestContextResponse.newBuilder() to construct. private MsgStartRequestContextResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgStartRequestContextResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgStartRequestContextResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgStartRequestContextResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgStartRequestContextResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgStartRequestContextResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgStartRequestContextResponse.class, irismod.service.Tx.MsgStartRequestContextResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgStartRequestContextResponse)) { return super.equals(obj); } irismod.service.Tx.MsgStartRequestContextResponse other = (irismod.service.Tx.MsgStartRequestContextResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgStartRequestContextResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgStartRequestContextResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgStartRequestContextResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgStartRequestContextResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgStartRequestContextResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgStartRequestContextResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgStartRequestContextResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgStartRequestContextResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgStartRequestContextResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgStartRequestContextResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgStartRequestContextResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgStartRequestContextResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgStartRequestContextResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgStartRequestContextResponse defines the Msg/StartRequestContext response type.
     * 
* * Protobuf type {@code irismod.service.MsgStartRequestContextResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgStartRequestContextResponse) irismod.service.Tx.MsgStartRequestContextResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgStartRequestContextResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgStartRequestContextResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgStartRequestContextResponse.class, irismod.service.Tx.MsgStartRequestContextResponse.Builder.class); } // Construct using irismod.service.Tx.MsgStartRequestContextResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgStartRequestContextResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgStartRequestContextResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgStartRequestContextResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgStartRequestContextResponse build() { irismod.service.Tx.MsgStartRequestContextResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgStartRequestContextResponse buildPartial() { irismod.service.Tx.MsgStartRequestContextResponse result = new irismod.service.Tx.MsgStartRequestContextResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgStartRequestContextResponse) { return mergeFrom((irismod.service.Tx.MsgStartRequestContextResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgStartRequestContextResponse other) { if (other == irismod.service.Tx.MsgStartRequestContextResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgStartRequestContextResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgStartRequestContextResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgStartRequestContextResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgStartRequestContextResponse) private static final irismod.service.Tx.MsgStartRequestContextResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgStartRequestContextResponse(); } public static irismod.service.Tx.MsgStartRequestContextResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgStartRequestContextResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgStartRequestContextResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgStartRequestContextResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgKillRequestContextOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgKillRequestContext) com.google.protobuf.MessageOrBuilder { /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ java.lang.String getRequestContextId(); /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ com.google.protobuf.ByteString getRequestContextIdBytes(); /** * string consumer = 2; * @return The consumer. */ java.lang.String getConsumer(); /** * string consumer = 2; * @return The bytes for consumer. */ com.google.protobuf.ByteString getConsumerBytes(); } /** *
   * MsgKillRequestContext defines an SDK message to terminate a service request.
   * 
* * Protobuf type {@code irismod.service.MsgKillRequestContext} */ public static final class MsgKillRequestContext extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgKillRequestContext) MsgKillRequestContextOrBuilder { private static final long serialVersionUID = 0L; // Use MsgKillRequestContext.newBuilder() to construct. private MsgKillRequestContext(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgKillRequestContext() { requestContextId_ = ""; consumer_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgKillRequestContext(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgKillRequestContext( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); requestContextId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); consumer_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgKillRequestContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgKillRequestContext_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgKillRequestContext.class, irismod.service.Tx.MsgKillRequestContext.Builder.class); } public static final int REQUEST_CONTEXT_ID_FIELD_NUMBER = 1; private volatile java.lang.Object requestContextId_; /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ @java.lang.Override public java.lang.String getRequestContextId() { java.lang.Object ref = requestContextId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestContextId_ = s; return s; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ @java.lang.Override public com.google.protobuf.ByteString getRequestContextIdBytes() { java.lang.Object ref = requestContextId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestContextId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CONSUMER_FIELD_NUMBER = 2; private volatile java.lang.Object consumer_; /** * string consumer = 2; * @return The consumer. */ @java.lang.Override public java.lang.String getConsumer() { java.lang.Object ref = consumer_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); consumer_ = s; return s; } } /** * string consumer = 2; * @return The bytes for consumer. */ @java.lang.Override public com.google.protobuf.ByteString getConsumerBytes() { java.lang.Object ref = consumer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); consumer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getRequestContextIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, requestContextId_); } if (!getConsumerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, consumer_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getRequestContextIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, requestContextId_); } if (!getConsumerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, consumer_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgKillRequestContext)) { return super.equals(obj); } irismod.service.Tx.MsgKillRequestContext other = (irismod.service.Tx.MsgKillRequestContext) obj; if (!getRequestContextId() .equals(other.getRequestContextId())) return false; if (!getConsumer() .equals(other.getConsumer())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + REQUEST_CONTEXT_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestContextId().hashCode(); hash = (37 * hash) + CONSUMER_FIELD_NUMBER; hash = (53 * hash) + getConsumer().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgKillRequestContext parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgKillRequestContext parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgKillRequestContext parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgKillRequestContext parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgKillRequestContext parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgKillRequestContext parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgKillRequestContext parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgKillRequestContext parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgKillRequestContext parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgKillRequestContext parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgKillRequestContext parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgKillRequestContext parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgKillRequestContext prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgKillRequestContext defines an SDK message to terminate a service request.
     * 
* * Protobuf type {@code irismod.service.MsgKillRequestContext} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgKillRequestContext) irismod.service.Tx.MsgKillRequestContextOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgKillRequestContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgKillRequestContext_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgKillRequestContext.class, irismod.service.Tx.MsgKillRequestContext.Builder.class); } // Construct using irismod.service.Tx.MsgKillRequestContext.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); requestContextId_ = ""; consumer_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgKillRequestContext_descriptor; } @java.lang.Override public irismod.service.Tx.MsgKillRequestContext getDefaultInstanceForType() { return irismod.service.Tx.MsgKillRequestContext.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgKillRequestContext build() { irismod.service.Tx.MsgKillRequestContext result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgKillRequestContext buildPartial() { irismod.service.Tx.MsgKillRequestContext result = new irismod.service.Tx.MsgKillRequestContext(this); result.requestContextId_ = requestContextId_; result.consumer_ = consumer_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgKillRequestContext) { return mergeFrom((irismod.service.Tx.MsgKillRequestContext)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgKillRequestContext other) { if (other == irismod.service.Tx.MsgKillRequestContext.getDefaultInstance()) return this; if (!other.getRequestContextId().isEmpty()) { requestContextId_ = other.requestContextId_; onChanged(); } if (!other.getConsumer().isEmpty()) { consumer_ = other.consumer_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgKillRequestContext parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgKillRequestContext) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object requestContextId_ = ""; /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ public java.lang.String getRequestContextId() { java.lang.Object ref = requestContextId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestContextId_ = s; return s; } else { return (java.lang.String) ref; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ public com.google.protobuf.ByteString getRequestContextIdBytes() { java.lang.Object ref = requestContextId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestContextId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @param value The requestContextId to set. * @return This builder for chaining. */ public Builder setRequestContextId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } requestContextId_ = value; onChanged(); return this; } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return This builder for chaining. */ public Builder clearRequestContextId() { requestContextId_ = getDefaultInstance().getRequestContextId(); onChanged(); return this; } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @param value The bytes for requestContextId to set. * @return This builder for chaining. */ public Builder setRequestContextIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requestContextId_ = value; onChanged(); return this; } private java.lang.Object consumer_ = ""; /** * string consumer = 2; * @return The consumer. */ public java.lang.String getConsumer() { java.lang.Object ref = consumer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); consumer_ = s; return s; } else { return (java.lang.String) ref; } } /** * string consumer = 2; * @return The bytes for consumer. */ public com.google.protobuf.ByteString getConsumerBytes() { java.lang.Object ref = consumer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); consumer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string consumer = 2; * @param value The consumer to set. * @return This builder for chaining. */ public Builder setConsumer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } consumer_ = value; onChanged(); return this; } /** * string consumer = 2; * @return This builder for chaining. */ public Builder clearConsumer() { consumer_ = getDefaultInstance().getConsumer(); onChanged(); return this; } /** * string consumer = 2; * @param value The bytes for consumer to set. * @return This builder for chaining. */ public Builder setConsumerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); consumer_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgKillRequestContext) } // @@protoc_insertion_point(class_scope:irismod.service.MsgKillRequestContext) private static final irismod.service.Tx.MsgKillRequestContext DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgKillRequestContext(); } public static irismod.service.Tx.MsgKillRequestContext getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgKillRequestContext parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgKillRequestContext(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgKillRequestContext getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgKillRequestContextResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgKillRequestContextResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgKillRequestContextResponse defines the Msg/KillRequestContext response type.
   * 
* * Protobuf type {@code irismod.service.MsgKillRequestContextResponse} */ public static final class MsgKillRequestContextResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgKillRequestContextResponse) MsgKillRequestContextResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgKillRequestContextResponse.newBuilder() to construct. private MsgKillRequestContextResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgKillRequestContextResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgKillRequestContextResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgKillRequestContextResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgKillRequestContextResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgKillRequestContextResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgKillRequestContextResponse.class, irismod.service.Tx.MsgKillRequestContextResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgKillRequestContextResponse)) { return super.equals(obj); } irismod.service.Tx.MsgKillRequestContextResponse other = (irismod.service.Tx.MsgKillRequestContextResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgKillRequestContextResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgKillRequestContextResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgKillRequestContextResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgKillRequestContextResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgKillRequestContextResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgKillRequestContextResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgKillRequestContextResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgKillRequestContextResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgKillRequestContextResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgKillRequestContextResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgKillRequestContextResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgKillRequestContextResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgKillRequestContextResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgKillRequestContextResponse defines the Msg/KillRequestContext response type.
     * 
* * Protobuf type {@code irismod.service.MsgKillRequestContextResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgKillRequestContextResponse) irismod.service.Tx.MsgKillRequestContextResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgKillRequestContextResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgKillRequestContextResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgKillRequestContextResponse.class, irismod.service.Tx.MsgKillRequestContextResponse.Builder.class); } // Construct using irismod.service.Tx.MsgKillRequestContextResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgKillRequestContextResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgKillRequestContextResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgKillRequestContextResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgKillRequestContextResponse build() { irismod.service.Tx.MsgKillRequestContextResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgKillRequestContextResponse buildPartial() { irismod.service.Tx.MsgKillRequestContextResponse result = new irismod.service.Tx.MsgKillRequestContextResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgKillRequestContextResponse) { return mergeFrom((irismod.service.Tx.MsgKillRequestContextResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgKillRequestContextResponse other) { if (other == irismod.service.Tx.MsgKillRequestContextResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgKillRequestContextResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgKillRequestContextResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgKillRequestContextResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgKillRequestContextResponse) private static final irismod.service.Tx.MsgKillRequestContextResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgKillRequestContextResponse(); } public static irismod.service.Tx.MsgKillRequestContextResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgKillRequestContextResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgKillRequestContextResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgKillRequestContextResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgUpdateRequestContextOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgUpdateRequestContext) com.google.protobuf.MessageOrBuilder { /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ java.lang.String getRequestContextId(); /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ com.google.protobuf.ByteString getRequestContextIdBytes(); /** * repeated string providers = 2; * @return A list containing the providers. */ java.util.List getProvidersList(); /** * repeated string providers = 2; * @return The count of providers. */ int getProvidersCount(); /** * repeated string providers = 2; * @param index The index of the element to return. * @return The providers at the given index. */ java.lang.String getProviders(int index); /** * repeated string providers = 2; * @param index The index of the value to return. * @return The bytes of the providers at the given index. */ com.google.protobuf.ByteString getProvidersBytes(int index); /** * string consumer = 3; * @return The consumer. */ java.lang.String getConsumer(); /** * string consumer = 3; * @return The bytes for consumer. */ com.google.protobuf.ByteString getConsumerBytes(); /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ java.util.List getServiceFeeCapList(); /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ cosmos.base.v1beta1.CoinOuterClass.Coin getServiceFeeCap(int index); /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ int getServiceFeeCapCount(); /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ java.util.List getServiceFeeCapOrBuilderList(); /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getServiceFeeCapOrBuilder( int index); /** * int64 timeout = 5; * @return The timeout. */ long getTimeout(); /** * uint64 repeated_frequency = 6 [(.gogoproto.moretags) = "yaml:\"repeated_frequency\""]; * @return The repeatedFrequency. */ long getRepeatedFrequency(); /** * int64 repeated_total = 7 [(.gogoproto.moretags) = "yaml:\"repeated_total\""]; * @return The repeatedTotal. */ long getRepeatedTotal(); } /** *
   * MsgUpdateRequestContext defines an SDK message to update a service request context.
   * 
* * Protobuf type {@code irismod.service.MsgUpdateRequestContext} */ public static final class MsgUpdateRequestContext extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgUpdateRequestContext) MsgUpdateRequestContextOrBuilder { private static final long serialVersionUID = 0L; // Use MsgUpdateRequestContext.newBuilder() to construct. private MsgUpdateRequestContext(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgUpdateRequestContext() { requestContextId_ = ""; providers_ = com.google.protobuf.LazyStringArrayList.EMPTY; consumer_ = ""; serviceFeeCap_ = java.util.Collections.emptyList(); } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgUpdateRequestContext(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgUpdateRequestContext( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); requestContextId_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000001) != 0)) { providers_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000001; } providers_.add(s); break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); consumer_ = s; break; } case 34: { if (!((mutable_bitField0_ & 0x00000002) != 0)) { serviceFeeCap_ = new java.util.ArrayList(); mutable_bitField0_ |= 0x00000002; } serviceFeeCap_.add( input.readMessage(cosmos.base.v1beta1.CoinOuterClass.Coin.parser(), extensionRegistry)); break; } case 40: { timeout_ = input.readInt64(); break; } case 48: { repeatedFrequency_ = input.readUInt64(); break; } case 56: { repeatedTotal_ = input.readInt64(); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { providers_ = providers_.getUnmodifiableView(); } if (((mutable_bitField0_ & 0x00000002) != 0)) { serviceFeeCap_ = java.util.Collections.unmodifiableList(serviceFeeCap_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateRequestContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateRequestContext_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgUpdateRequestContext.class, irismod.service.Tx.MsgUpdateRequestContext.Builder.class); } public static final int REQUEST_CONTEXT_ID_FIELD_NUMBER = 1; private volatile java.lang.Object requestContextId_; /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ @java.lang.Override public java.lang.String getRequestContextId() { java.lang.Object ref = requestContextId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestContextId_ = s; return s; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ @java.lang.Override public com.google.protobuf.ByteString getRequestContextIdBytes() { java.lang.Object ref = requestContextId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestContextId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROVIDERS_FIELD_NUMBER = 2; private com.google.protobuf.LazyStringList providers_; /** * repeated string providers = 2; * @return A list containing the providers. */ public com.google.protobuf.ProtocolStringList getProvidersList() { return providers_; } /** * repeated string providers = 2; * @return The count of providers. */ public int getProvidersCount() { return providers_.size(); } /** * repeated string providers = 2; * @param index The index of the element to return. * @return The providers at the given index. */ public java.lang.String getProviders(int index) { return providers_.get(index); } /** * repeated string providers = 2; * @param index The index of the value to return. * @return The bytes of the providers at the given index. */ public com.google.protobuf.ByteString getProvidersBytes(int index) { return providers_.getByteString(index); } public static final int CONSUMER_FIELD_NUMBER = 3; private volatile java.lang.Object consumer_; /** * string consumer = 3; * @return The consumer. */ @java.lang.Override public java.lang.String getConsumer() { java.lang.Object ref = consumer_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); consumer_ = s; return s; } } /** * string consumer = 3; * @return The bytes for consumer. */ @java.lang.Override public com.google.protobuf.ByteString getConsumerBytes() { java.lang.Object ref = consumer_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); consumer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int SERVICE_FEE_CAP_FIELD_NUMBER = 4; private java.util.List serviceFeeCap_; /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public java.util.List getServiceFeeCapList() { return serviceFeeCap_; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public java.util.List getServiceFeeCapOrBuilderList() { return serviceFeeCap_; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public int getServiceFeeCapCount() { return serviceFeeCap_.size(); } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public cosmos.base.v1beta1.CoinOuterClass.Coin getServiceFeeCap(int index) { return serviceFeeCap_.get(index); } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ @java.lang.Override public cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getServiceFeeCapOrBuilder( int index) { return serviceFeeCap_.get(index); } public static final int TIMEOUT_FIELD_NUMBER = 5; private long timeout_; /** * int64 timeout = 5; * @return The timeout. */ @java.lang.Override public long getTimeout() { return timeout_; } public static final int REPEATED_FREQUENCY_FIELD_NUMBER = 6; private long repeatedFrequency_; /** * uint64 repeated_frequency = 6 [(.gogoproto.moretags) = "yaml:\"repeated_frequency\""]; * @return The repeatedFrequency. */ @java.lang.Override public long getRepeatedFrequency() { return repeatedFrequency_; } public static final int REPEATED_TOTAL_FIELD_NUMBER = 7; private long repeatedTotal_; /** * int64 repeated_total = 7 [(.gogoproto.moretags) = "yaml:\"repeated_total\""]; * @return The repeatedTotal. */ @java.lang.Override public long getRepeatedTotal() { return repeatedTotal_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getRequestContextIdBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, requestContextId_); } for (int i = 0; i < providers_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, providers_.getRaw(i)); } if (!getConsumerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, consumer_); } for (int i = 0; i < serviceFeeCap_.size(); i++) { output.writeMessage(4, serviceFeeCap_.get(i)); } if (timeout_ != 0L) { output.writeInt64(5, timeout_); } if (repeatedFrequency_ != 0L) { output.writeUInt64(6, repeatedFrequency_); } if (repeatedTotal_ != 0L) { output.writeInt64(7, repeatedTotal_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getRequestContextIdBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, requestContextId_); } { int dataSize = 0; for (int i = 0; i < providers_.size(); i++) { dataSize += computeStringSizeNoTag(providers_.getRaw(i)); } size += dataSize; size += 1 * getProvidersList().size(); } if (!getConsumerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, consumer_); } for (int i = 0; i < serviceFeeCap_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, serviceFeeCap_.get(i)); } if (timeout_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(5, timeout_); } if (repeatedFrequency_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(6, repeatedFrequency_); } if (repeatedTotal_ != 0L) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(7, repeatedTotal_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgUpdateRequestContext)) { return super.equals(obj); } irismod.service.Tx.MsgUpdateRequestContext other = (irismod.service.Tx.MsgUpdateRequestContext) obj; if (!getRequestContextId() .equals(other.getRequestContextId())) return false; if (!getProvidersList() .equals(other.getProvidersList())) return false; if (!getConsumer() .equals(other.getConsumer())) return false; if (!getServiceFeeCapList() .equals(other.getServiceFeeCapList())) return false; if (getTimeout() != other.getTimeout()) return false; if (getRepeatedFrequency() != other.getRepeatedFrequency()) return false; if (getRepeatedTotal() != other.getRepeatedTotal()) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + REQUEST_CONTEXT_ID_FIELD_NUMBER; hash = (53 * hash) + getRequestContextId().hashCode(); if (getProvidersCount() > 0) { hash = (37 * hash) + PROVIDERS_FIELD_NUMBER; hash = (53 * hash) + getProvidersList().hashCode(); } hash = (37 * hash) + CONSUMER_FIELD_NUMBER; hash = (53 * hash) + getConsumer().hashCode(); if (getServiceFeeCapCount() > 0) { hash = (37 * hash) + SERVICE_FEE_CAP_FIELD_NUMBER; hash = (53 * hash) + getServiceFeeCapList().hashCode(); } hash = (37 * hash) + TIMEOUT_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getTimeout()); hash = (37 * hash) + REPEATED_FREQUENCY_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getRepeatedFrequency()); hash = (37 * hash) + REPEATED_TOTAL_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashLong( getRepeatedTotal()); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgUpdateRequestContext parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateRequestContext parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateRequestContext parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateRequestContext parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateRequestContext parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateRequestContext parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateRequestContext parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateRequestContext parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgUpdateRequestContext parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateRequestContext parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgUpdateRequestContext parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateRequestContext parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgUpdateRequestContext prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgUpdateRequestContext defines an SDK message to update a service request context.
     * 
* * Protobuf type {@code irismod.service.MsgUpdateRequestContext} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgUpdateRequestContext) irismod.service.Tx.MsgUpdateRequestContextOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateRequestContext_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateRequestContext_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgUpdateRequestContext.class, irismod.service.Tx.MsgUpdateRequestContext.Builder.class); } // Construct using irismod.service.Tx.MsgUpdateRequestContext.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { getServiceFeeCapFieldBuilder(); } } @java.lang.Override public Builder clear() { super.clear(); requestContextId_ = ""; providers_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); consumer_ = ""; if (serviceFeeCapBuilder_ == null) { serviceFeeCap_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); } else { serviceFeeCapBuilder_.clear(); } timeout_ = 0L; repeatedFrequency_ = 0L; repeatedTotal_ = 0L; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateRequestContext_descriptor; } @java.lang.Override public irismod.service.Tx.MsgUpdateRequestContext getDefaultInstanceForType() { return irismod.service.Tx.MsgUpdateRequestContext.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgUpdateRequestContext build() { irismod.service.Tx.MsgUpdateRequestContext result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgUpdateRequestContext buildPartial() { irismod.service.Tx.MsgUpdateRequestContext result = new irismod.service.Tx.MsgUpdateRequestContext(this); int from_bitField0_ = bitField0_; result.requestContextId_ = requestContextId_; if (((bitField0_ & 0x00000001) != 0)) { providers_ = providers_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000001); } result.providers_ = providers_; result.consumer_ = consumer_; if (serviceFeeCapBuilder_ == null) { if (((bitField0_ & 0x00000002) != 0)) { serviceFeeCap_ = java.util.Collections.unmodifiableList(serviceFeeCap_); bitField0_ = (bitField0_ & ~0x00000002); } result.serviceFeeCap_ = serviceFeeCap_; } else { result.serviceFeeCap_ = serviceFeeCapBuilder_.build(); } result.timeout_ = timeout_; result.repeatedFrequency_ = repeatedFrequency_; result.repeatedTotal_ = repeatedTotal_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgUpdateRequestContext) { return mergeFrom((irismod.service.Tx.MsgUpdateRequestContext)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgUpdateRequestContext other) { if (other == irismod.service.Tx.MsgUpdateRequestContext.getDefaultInstance()) return this; if (!other.getRequestContextId().isEmpty()) { requestContextId_ = other.requestContextId_; onChanged(); } if (!other.providers_.isEmpty()) { if (providers_.isEmpty()) { providers_ = other.providers_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureProvidersIsMutable(); providers_.addAll(other.providers_); } onChanged(); } if (!other.getConsumer().isEmpty()) { consumer_ = other.consumer_; onChanged(); } if (serviceFeeCapBuilder_ == null) { if (!other.serviceFeeCap_.isEmpty()) { if (serviceFeeCap_.isEmpty()) { serviceFeeCap_ = other.serviceFeeCap_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureServiceFeeCapIsMutable(); serviceFeeCap_.addAll(other.serviceFeeCap_); } onChanged(); } } else { if (!other.serviceFeeCap_.isEmpty()) { if (serviceFeeCapBuilder_.isEmpty()) { serviceFeeCapBuilder_.dispose(); serviceFeeCapBuilder_ = null; serviceFeeCap_ = other.serviceFeeCap_; bitField0_ = (bitField0_ & ~0x00000002); serviceFeeCapBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getServiceFeeCapFieldBuilder() : null; } else { serviceFeeCapBuilder_.addAllMessages(other.serviceFeeCap_); } } } if (other.getTimeout() != 0L) { setTimeout(other.getTimeout()); } if (other.getRepeatedFrequency() != 0L) { setRepeatedFrequency(other.getRepeatedFrequency()); } if (other.getRepeatedTotal() != 0L) { setRepeatedTotal(other.getRepeatedTotal()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgUpdateRequestContext parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgUpdateRequestContext) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object requestContextId_ = ""; /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The requestContextId. */ public java.lang.String getRequestContextId() { java.lang.Object ref = requestContextId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); requestContextId_ = s; return s; } else { return (java.lang.String) ref; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return The bytes for requestContextId. */ public com.google.protobuf.ByteString getRequestContextIdBytes() { java.lang.Object ref = requestContextId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); requestContextId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @param value The requestContextId to set. * @return This builder for chaining. */ public Builder setRequestContextId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } requestContextId_ = value; onChanged(); return this; } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @return This builder for chaining. */ public Builder clearRequestContextId() { requestContextId_ = getDefaultInstance().getRequestContextId(); onChanged(); return this; } /** * string request_context_id = 1 [(.gogoproto.moretags) = "yaml:\"request_context_id\""]; * @param value The bytes for requestContextId to set. * @return This builder for chaining. */ public Builder setRequestContextIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); requestContextId_ = value; onChanged(); return this; } private com.google.protobuf.LazyStringList providers_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureProvidersIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { providers_ = new com.google.protobuf.LazyStringArrayList(providers_); bitField0_ |= 0x00000001; } } /** * repeated string providers = 2; * @return A list containing the providers. */ public com.google.protobuf.ProtocolStringList getProvidersList() { return providers_.getUnmodifiableView(); } /** * repeated string providers = 2; * @return The count of providers. */ public int getProvidersCount() { return providers_.size(); } /** * repeated string providers = 2; * @param index The index of the element to return. * @return The providers at the given index. */ public java.lang.String getProviders(int index) { return providers_.get(index); } /** * repeated string providers = 2; * @param index The index of the value to return. * @return The bytes of the providers at the given index. */ public com.google.protobuf.ByteString getProvidersBytes(int index) { return providers_.getByteString(index); } /** * repeated string providers = 2; * @param index The index to set the value at. * @param value The providers to set. * @return This builder for chaining. */ public Builder setProviders( int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureProvidersIsMutable(); providers_.set(index, value); onChanged(); return this; } /** * repeated string providers = 2; * @param value The providers to add. * @return This builder for chaining. */ public Builder addProviders( java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureProvidersIsMutable(); providers_.add(value); onChanged(); return this; } /** * repeated string providers = 2; * @param values The providers to add. * @return This builder for chaining. */ public Builder addAllProviders( java.lang.Iterable values) { ensureProvidersIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, providers_); onChanged(); return this; } /** * repeated string providers = 2; * @return This builder for chaining. */ public Builder clearProviders() { providers_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * repeated string providers = 2; * @param value The bytes of the providers to add. * @return This builder for chaining. */ public Builder addProvidersBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureProvidersIsMutable(); providers_.add(value); onChanged(); return this; } private java.lang.Object consumer_ = ""; /** * string consumer = 3; * @return The consumer. */ public java.lang.String getConsumer() { java.lang.Object ref = consumer_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); consumer_ = s; return s; } else { return (java.lang.String) ref; } } /** * string consumer = 3; * @return The bytes for consumer. */ public com.google.protobuf.ByteString getConsumerBytes() { java.lang.Object ref = consumer_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); consumer_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string consumer = 3; * @param value The consumer to set. * @return This builder for chaining. */ public Builder setConsumer( java.lang.String value) { if (value == null) { throw new NullPointerException(); } consumer_ = value; onChanged(); return this; } /** * string consumer = 3; * @return This builder for chaining. */ public Builder clearConsumer() { consumer_ = getDefaultInstance().getConsumer(); onChanged(); return this; } /** * string consumer = 3; * @param value The bytes for consumer to set. * @return This builder for chaining. */ public Builder setConsumerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); consumer_ = value; onChanged(); return this; } private java.util.List serviceFeeCap_ = java.util.Collections.emptyList(); private void ensureServiceFeeCapIsMutable() { if (!((bitField0_ & 0x00000002) != 0)) { serviceFeeCap_ = new java.util.ArrayList(serviceFeeCap_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder> serviceFeeCapBuilder_; /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getServiceFeeCapList() { if (serviceFeeCapBuilder_ == null) { return java.util.Collections.unmodifiableList(serviceFeeCap_); } else { return serviceFeeCapBuilder_.getMessageList(); } } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public int getServiceFeeCapCount() { if (serviceFeeCapBuilder_ == null) { return serviceFeeCap_.size(); } else { return serviceFeeCapBuilder_.getCount(); } } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin getServiceFeeCap(int index) { if (serviceFeeCapBuilder_ == null) { return serviceFeeCap_.get(index); } else { return serviceFeeCapBuilder_.getMessage(index); } } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder setServiceFeeCap( int index, cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (serviceFeeCapBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServiceFeeCapIsMutable(); serviceFeeCap_.set(index, value); onChanged(); } else { serviceFeeCapBuilder_.setMessage(index, value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder setServiceFeeCap( int index, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (serviceFeeCapBuilder_ == null) { ensureServiceFeeCapIsMutable(); serviceFeeCap_.set(index, builderForValue.build()); onChanged(); } else { serviceFeeCapBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addServiceFeeCap(cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (serviceFeeCapBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServiceFeeCapIsMutable(); serviceFeeCap_.add(value); onChanged(); } else { serviceFeeCapBuilder_.addMessage(value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addServiceFeeCap( int index, cosmos.base.v1beta1.CoinOuterClass.Coin value) { if (serviceFeeCapBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureServiceFeeCapIsMutable(); serviceFeeCap_.add(index, value); onChanged(); } else { serviceFeeCapBuilder_.addMessage(index, value); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addServiceFeeCap( cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (serviceFeeCapBuilder_ == null) { ensureServiceFeeCapIsMutable(); serviceFeeCap_.add(builderForValue.build()); onChanged(); } else { serviceFeeCapBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addServiceFeeCap( int index, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder builderForValue) { if (serviceFeeCapBuilder_ == null) { ensureServiceFeeCapIsMutable(); serviceFeeCap_.add(index, builderForValue.build()); onChanged(); } else { serviceFeeCapBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder addAllServiceFeeCap( java.lang.Iterable values) { if (serviceFeeCapBuilder_ == null) { ensureServiceFeeCapIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, serviceFeeCap_); onChanged(); } else { serviceFeeCapBuilder_.addAllMessages(values); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder clearServiceFeeCap() { if (serviceFeeCapBuilder_ == null) { serviceFeeCap_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { serviceFeeCapBuilder_.clear(); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public Builder removeServiceFeeCap(int index) { if (serviceFeeCapBuilder_ == null) { ensureServiceFeeCapIsMutable(); serviceFeeCap_.remove(index); onChanged(); } else { serviceFeeCapBuilder_.remove(index); } return this; } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder getServiceFeeCapBuilder( int index) { return getServiceFeeCapFieldBuilder().getBuilder(index); } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder getServiceFeeCapOrBuilder( int index) { if (serviceFeeCapBuilder_ == null) { return serviceFeeCap_.get(index); } else { return serviceFeeCapBuilder_.getMessageOrBuilder(index); } } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getServiceFeeCapOrBuilderList() { if (serviceFeeCapBuilder_ != null) { return serviceFeeCapBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(serviceFeeCap_); } } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder addServiceFeeCapBuilder() { return getServiceFeeCapFieldBuilder().addBuilder( cosmos.base.v1beta1.CoinOuterClass.Coin.getDefaultInstance()); } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public cosmos.base.v1beta1.CoinOuterClass.Coin.Builder addServiceFeeCapBuilder( int index) { return getServiceFeeCapFieldBuilder().addBuilder( index, cosmos.base.v1beta1.CoinOuterClass.Coin.getDefaultInstance()); } /** * repeated .cosmos.base.v1beta1.Coin service_fee_cap = 4 [(.gogoproto.nullable) = false, (.gogoproto.moretags) = "yaml:\"service_fee_cap\"", (.gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; */ public java.util.List getServiceFeeCapBuilderList() { return getServiceFeeCapFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder> getServiceFeeCapFieldBuilder() { if (serviceFeeCapBuilder_ == null) { serviceFeeCapBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< cosmos.base.v1beta1.CoinOuterClass.Coin, cosmos.base.v1beta1.CoinOuterClass.Coin.Builder, cosmos.base.v1beta1.CoinOuterClass.CoinOrBuilder>( serviceFeeCap_, ((bitField0_ & 0x00000002) != 0), getParentForChildren(), isClean()); serviceFeeCap_ = null; } return serviceFeeCapBuilder_; } private long timeout_ ; /** * int64 timeout = 5; * @return The timeout. */ @java.lang.Override public long getTimeout() { return timeout_; } /** * int64 timeout = 5; * @param value The timeout to set. * @return This builder for chaining. */ public Builder setTimeout(long value) { timeout_ = value; onChanged(); return this; } /** * int64 timeout = 5; * @return This builder for chaining. */ public Builder clearTimeout() { timeout_ = 0L; onChanged(); return this; } private long repeatedFrequency_ ; /** * uint64 repeated_frequency = 6 [(.gogoproto.moretags) = "yaml:\"repeated_frequency\""]; * @return The repeatedFrequency. */ @java.lang.Override public long getRepeatedFrequency() { return repeatedFrequency_; } /** * uint64 repeated_frequency = 6 [(.gogoproto.moretags) = "yaml:\"repeated_frequency\""]; * @param value The repeatedFrequency to set. * @return This builder for chaining. */ public Builder setRepeatedFrequency(long value) { repeatedFrequency_ = value; onChanged(); return this; } /** * uint64 repeated_frequency = 6 [(.gogoproto.moretags) = "yaml:\"repeated_frequency\""]; * @return This builder for chaining. */ public Builder clearRepeatedFrequency() { repeatedFrequency_ = 0L; onChanged(); return this; } private long repeatedTotal_ ; /** * int64 repeated_total = 7 [(.gogoproto.moretags) = "yaml:\"repeated_total\""]; * @return The repeatedTotal. */ @java.lang.Override public long getRepeatedTotal() { return repeatedTotal_; } /** * int64 repeated_total = 7 [(.gogoproto.moretags) = "yaml:\"repeated_total\""]; * @param value The repeatedTotal to set. * @return This builder for chaining. */ public Builder setRepeatedTotal(long value) { repeatedTotal_ = value; onChanged(); return this; } /** * int64 repeated_total = 7 [(.gogoproto.moretags) = "yaml:\"repeated_total\""]; * @return This builder for chaining. */ public Builder clearRepeatedTotal() { repeatedTotal_ = 0L; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgUpdateRequestContext) } // @@protoc_insertion_point(class_scope:irismod.service.MsgUpdateRequestContext) private static final irismod.service.Tx.MsgUpdateRequestContext DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgUpdateRequestContext(); } public static irismod.service.Tx.MsgUpdateRequestContext getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgUpdateRequestContext parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgUpdateRequestContext(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgUpdateRequestContext getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgUpdateRequestContextResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgUpdateRequestContextResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgUpdateRequestContextResponse defines the Msg/UpdateRequestContext response type.
   * 
* * Protobuf type {@code irismod.service.MsgUpdateRequestContextResponse} */ public static final class MsgUpdateRequestContextResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgUpdateRequestContextResponse) MsgUpdateRequestContextResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgUpdateRequestContextResponse.newBuilder() to construct. private MsgUpdateRequestContextResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgUpdateRequestContextResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgUpdateRequestContextResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgUpdateRequestContextResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateRequestContextResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateRequestContextResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgUpdateRequestContextResponse.class, irismod.service.Tx.MsgUpdateRequestContextResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgUpdateRequestContextResponse)) { return super.equals(obj); } irismod.service.Tx.MsgUpdateRequestContextResponse other = (irismod.service.Tx.MsgUpdateRequestContextResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgUpdateRequestContextResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgUpdateRequestContextResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgUpdateRequestContextResponse defines the Msg/UpdateRequestContext response type.
     * 
* * Protobuf type {@code irismod.service.MsgUpdateRequestContextResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgUpdateRequestContextResponse) irismod.service.Tx.MsgUpdateRequestContextResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateRequestContextResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateRequestContextResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgUpdateRequestContextResponse.class, irismod.service.Tx.MsgUpdateRequestContextResponse.Builder.class); } // Construct using irismod.service.Tx.MsgUpdateRequestContextResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgUpdateRequestContextResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgUpdateRequestContextResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgUpdateRequestContextResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgUpdateRequestContextResponse build() { irismod.service.Tx.MsgUpdateRequestContextResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgUpdateRequestContextResponse buildPartial() { irismod.service.Tx.MsgUpdateRequestContextResponse result = new irismod.service.Tx.MsgUpdateRequestContextResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgUpdateRequestContextResponse) { return mergeFrom((irismod.service.Tx.MsgUpdateRequestContextResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgUpdateRequestContextResponse other) { if (other == irismod.service.Tx.MsgUpdateRequestContextResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgUpdateRequestContextResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgUpdateRequestContextResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgUpdateRequestContextResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgUpdateRequestContextResponse) private static final irismod.service.Tx.MsgUpdateRequestContextResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgUpdateRequestContextResponse(); } public static irismod.service.Tx.MsgUpdateRequestContextResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgUpdateRequestContextResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgUpdateRequestContextResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgUpdateRequestContextResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgWithdrawEarnedFeesOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgWithdrawEarnedFees) com.google.protobuf.MessageOrBuilder { /** * string owner = 1; * @return The owner. */ java.lang.String getOwner(); /** * string owner = 1; * @return The bytes for owner. */ com.google.protobuf.ByteString getOwnerBytes(); /** * string provider = 2; * @return The provider. */ java.lang.String getProvider(); /** * string provider = 2; * @return The bytes for provider. */ com.google.protobuf.ByteString getProviderBytes(); } /** *
   * MsgWithdrawEarnedFees defines an SDK message to withdraw the fees earned by the provider or owner.
   * 
* * Protobuf type {@code irismod.service.MsgWithdrawEarnedFees} */ public static final class MsgWithdrawEarnedFees extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgWithdrawEarnedFees) MsgWithdrawEarnedFeesOrBuilder { private static final long serialVersionUID = 0L; // Use MsgWithdrawEarnedFees.newBuilder() to construct. private MsgWithdrawEarnedFees(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgWithdrawEarnedFees() { owner_ = ""; provider_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgWithdrawEarnedFees(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgWithdrawEarnedFees( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); owner_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); provider_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgWithdrawEarnedFees_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgWithdrawEarnedFees_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgWithdrawEarnedFees.class, irismod.service.Tx.MsgWithdrawEarnedFees.Builder.class); } public static final int OWNER_FIELD_NUMBER = 1; private volatile java.lang.Object owner_; /** * string owner = 1; * @return The owner. */ @java.lang.Override public java.lang.String getOwner() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } } /** * string owner = 1; * @return The bytes for owner. */ @java.lang.Override public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int PROVIDER_FIELD_NUMBER = 2; private volatile java.lang.Object provider_; /** * string provider = 2; * @return The provider. */ @java.lang.Override public java.lang.String getProvider() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } } /** * string provider = 2; * @return The bytes for provider. */ @java.lang.Override public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!getOwnerBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, owner_); } if (!getProviderBytes().isEmpty()) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, provider_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!getOwnerBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, owner_); } if (!getProviderBytes().isEmpty()) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, provider_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgWithdrawEarnedFees)) { return super.equals(obj); } irismod.service.Tx.MsgWithdrawEarnedFees other = (irismod.service.Tx.MsgWithdrawEarnedFees) obj; if (!getOwner() .equals(other.getOwner())) return false; if (!getProvider() .equals(other.getProvider())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + OWNER_FIELD_NUMBER; hash = (53 * hash) + getOwner().hashCode(); hash = (37 * hash) + PROVIDER_FIELD_NUMBER; hash = (53 * hash) + getProvider().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgWithdrawEarnedFees parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgWithdrawEarnedFees parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgWithdrawEarnedFees parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgWithdrawEarnedFees parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgWithdrawEarnedFees parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgWithdrawEarnedFees parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgWithdrawEarnedFees parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgWithdrawEarnedFees parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgWithdrawEarnedFees parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgWithdrawEarnedFees parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgWithdrawEarnedFees parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgWithdrawEarnedFees parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgWithdrawEarnedFees prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgWithdrawEarnedFees defines an SDK message to withdraw the fees earned by the provider or owner.
     * 
* * Protobuf type {@code irismod.service.MsgWithdrawEarnedFees} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgWithdrawEarnedFees) irismod.service.Tx.MsgWithdrawEarnedFeesOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgWithdrawEarnedFees_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgWithdrawEarnedFees_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgWithdrawEarnedFees.class, irismod.service.Tx.MsgWithdrawEarnedFees.Builder.class); } // Construct using irismod.service.Tx.MsgWithdrawEarnedFees.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); owner_ = ""; provider_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgWithdrawEarnedFees_descriptor; } @java.lang.Override public irismod.service.Tx.MsgWithdrawEarnedFees getDefaultInstanceForType() { return irismod.service.Tx.MsgWithdrawEarnedFees.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgWithdrawEarnedFees build() { irismod.service.Tx.MsgWithdrawEarnedFees result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgWithdrawEarnedFees buildPartial() { irismod.service.Tx.MsgWithdrawEarnedFees result = new irismod.service.Tx.MsgWithdrawEarnedFees(this); result.owner_ = owner_; result.provider_ = provider_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgWithdrawEarnedFees) { return mergeFrom((irismod.service.Tx.MsgWithdrawEarnedFees)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgWithdrawEarnedFees other) { if (other == irismod.service.Tx.MsgWithdrawEarnedFees.getDefaultInstance()) return this; if (!other.getOwner().isEmpty()) { owner_ = other.owner_; onChanged(); } if (!other.getProvider().isEmpty()) { provider_ = other.provider_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgWithdrawEarnedFees parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgWithdrawEarnedFees) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object owner_ = ""; /** * string owner = 1; * @return The owner. */ public java.lang.String getOwner() { java.lang.Object ref = owner_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); owner_ = s; return s; } else { return (java.lang.String) ref; } } /** * string owner = 1; * @return The bytes for owner. */ public com.google.protobuf.ByteString getOwnerBytes() { java.lang.Object ref = owner_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); owner_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string owner = 1; * @param value The owner to set. * @return This builder for chaining. */ public Builder setOwner( java.lang.String value) { if (value == null) { throw new NullPointerException(); } owner_ = value; onChanged(); return this; } /** * string owner = 1; * @return This builder for chaining. */ public Builder clearOwner() { owner_ = getDefaultInstance().getOwner(); onChanged(); return this; } /** * string owner = 1; * @param value The bytes for owner to set. * @return This builder for chaining. */ public Builder setOwnerBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); owner_ = value; onChanged(); return this; } private java.lang.Object provider_ = ""; /** * string provider = 2; * @return The provider. */ public java.lang.String getProvider() { java.lang.Object ref = provider_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); provider_ = s; return s; } else { return (java.lang.String) ref; } } /** * string provider = 2; * @return The bytes for provider. */ public com.google.protobuf.ByteString getProviderBytes() { java.lang.Object ref = provider_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); provider_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * string provider = 2; * @param value The provider to set. * @return This builder for chaining. */ public Builder setProvider( java.lang.String value) { if (value == null) { throw new NullPointerException(); } provider_ = value; onChanged(); return this; } /** * string provider = 2; * @return This builder for chaining. */ public Builder clearProvider() { provider_ = getDefaultInstance().getProvider(); onChanged(); return this; } /** * string provider = 2; * @param value The bytes for provider to set. * @return This builder for chaining. */ public Builder setProviderBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); provider_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgWithdrawEarnedFees) } // @@protoc_insertion_point(class_scope:irismod.service.MsgWithdrawEarnedFees) private static final irismod.service.Tx.MsgWithdrawEarnedFees DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgWithdrawEarnedFees(); } public static irismod.service.Tx.MsgWithdrawEarnedFees getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgWithdrawEarnedFees parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgWithdrawEarnedFees(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgWithdrawEarnedFees getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } public interface MsgWithdrawEarnedFeesResponseOrBuilder extends // @@protoc_insertion_point(interface_extends:irismod.service.MsgWithdrawEarnedFeesResponse) com.google.protobuf.MessageOrBuilder { } /** *
   * MsgWithdrawEarnedFeesResponse defines the Msg/WithdrawEarnedFees response type.
   * 
* * Protobuf type {@code irismod.service.MsgWithdrawEarnedFeesResponse} */ public static final class MsgWithdrawEarnedFeesResponse extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:irismod.service.MsgWithdrawEarnedFeesResponse) MsgWithdrawEarnedFeesResponseOrBuilder { private static final long serialVersionUID = 0L; // Use MsgWithdrawEarnedFeesResponse.newBuilder() to construct. private MsgWithdrawEarnedFeesResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { super(builder); } private MsgWithdrawEarnedFeesResponse() { } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new MsgWithdrawEarnedFeesResponse(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MsgWithdrawEarnedFeesResponse( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgWithdrawEarnedFeesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgWithdrawEarnedFeesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgWithdrawEarnedFeesResponse.class, irismod.service.Tx.MsgWithdrawEarnedFeesResponse.Builder.class); } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof irismod.service.Tx.MsgWithdrawEarnedFeesResponse)) { return super.equals(obj); } irismod.service.Tx.MsgWithdrawEarnedFeesResponse other = (irismod.service.Tx.MsgWithdrawEarnedFeesResponse) obj; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(irismod.service.Tx.MsgWithdrawEarnedFeesResponse prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** *
     * MsgWithdrawEarnedFeesResponse defines the Msg/WithdrawEarnedFees response type.
     * 
* * Protobuf type {@code irismod.service.MsgWithdrawEarnedFeesResponse} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements // @@protoc_insertion_point(builder_implements:irismod.service.MsgWithdrawEarnedFeesResponse) irismod.service.Tx.MsgWithdrawEarnedFeesResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return irismod.service.Tx.internal_static_irismod_service_MsgWithdrawEarnedFeesResponse_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return irismod.service.Tx.internal_static_irismod_service_MsgWithdrawEarnedFeesResponse_fieldAccessorTable .ensureFieldAccessorsInitialized( irismod.service.Tx.MsgWithdrawEarnedFeesResponse.class, irismod.service.Tx.MsgWithdrawEarnedFeesResponse.Builder.class); } // Construct using irismod.service.Tx.MsgWithdrawEarnedFeesResponse.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return irismod.service.Tx.internal_static_irismod_service_MsgWithdrawEarnedFeesResponse_descriptor; } @java.lang.Override public irismod.service.Tx.MsgWithdrawEarnedFeesResponse getDefaultInstanceForType() { return irismod.service.Tx.MsgWithdrawEarnedFeesResponse.getDefaultInstance(); } @java.lang.Override public irismod.service.Tx.MsgWithdrawEarnedFeesResponse build() { irismod.service.Tx.MsgWithdrawEarnedFeesResponse result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public irismod.service.Tx.MsgWithdrawEarnedFeesResponse buildPartial() { irismod.service.Tx.MsgWithdrawEarnedFeesResponse result = new irismod.service.Tx.MsgWithdrawEarnedFeesResponse(this); onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof irismod.service.Tx.MsgWithdrawEarnedFeesResponse) { return mergeFrom((irismod.service.Tx.MsgWithdrawEarnedFeesResponse)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(irismod.service.Tx.MsgWithdrawEarnedFeesResponse other) { if (other == irismod.service.Tx.MsgWithdrawEarnedFeesResponse.getDefaultInstance()) return this; this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { irismod.service.Tx.MsgWithdrawEarnedFeesResponse parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (irismod.service.Tx.MsgWithdrawEarnedFeesResponse) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:irismod.service.MsgWithdrawEarnedFeesResponse) } // @@protoc_insertion_point(class_scope:irismod.service.MsgWithdrawEarnedFeesResponse) private static final irismod.service.Tx.MsgWithdrawEarnedFeesResponse DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new irismod.service.Tx.MsgWithdrawEarnedFeesResponse(); } public static irismod.service.Tx.MsgWithdrawEarnedFeesResponse getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { @java.lang.Override public MsgWithdrawEarnedFeesResponse parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MsgWithdrawEarnedFeesResponse(input, extensionRegistry); } }; public static com.google.protobuf.Parser parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } @java.lang.Override public irismod.service.Tx.MsgWithdrawEarnedFeesResponse getDefaultInstanceForType() { return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgDefineService_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgDefineService_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgDefineServiceResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgDefineServiceResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgBindService_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgBindService_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgBindServiceResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgBindServiceResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgUpdateServiceBinding_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgUpdateServiceBinding_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgUpdateServiceBindingResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgUpdateServiceBindingResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgSetWithdrawAddress_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgSetWithdrawAddress_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgSetWithdrawAddressResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgSetWithdrawAddressResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgDisableServiceBinding_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgDisableServiceBinding_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgDisableServiceBindingResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgDisableServiceBindingResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgEnableServiceBinding_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgEnableServiceBinding_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgEnableServiceBindingResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgEnableServiceBindingResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgRefundServiceDeposit_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgRefundServiceDeposit_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgRefundServiceDepositResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgRefundServiceDepositResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgCallService_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgCallService_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgCallServiceResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgCallServiceResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgRespondService_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgRespondService_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgRespondServiceResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgRespondServiceResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgPauseRequestContext_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgPauseRequestContext_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgPauseRequestContextResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgPauseRequestContextResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgStartRequestContext_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgStartRequestContext_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgStartRequestContextResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgStartRequestContextResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgKillRequestContext_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgKillRequestContext_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgKillRequestContextResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgKillRequestContextResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgUpdateRequestContext_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgUpdateRequestContext_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgUpdateRequestContextResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgUpdateRequestContextResponse_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgWithdrawEarnedFees_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgWithdrawEarnedFees_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_irismod_service_MsgWithdrawEarnedFeesResponse_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_irismod_service_MsgWithdrawEarnedFeesResponse_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\020service/tx.proto\022\017irismod.service\032\036cos" + "mos/base/v1beta1/coin.proto\032\024gogoproto/g" + "ogo.proto\"\237\001\n\020MsgDefineService\022\014\n\004name\030\001" + " \001(\t\022\023\n\013description\030\002 \001(\t\022\014\n\004tags\030\003 \003(\t\022" + "\016\n\006author\030\004 \001(\t\0229\n\022author_description\030\005 " + "\001(\tB\035\362\336\037\031yaml:\"author_description\"\022\017\n\007sc" + "hemas\030\006 \001(\t\"\032\n\030MsgDefineServiceResponse\"" + "\366\001\n\016MsgBindService\022-\n\014service_name\030\001 \001(\t" + "B\027\362\336\037\023yaml:\"service_name\"\022\020\n\010provider\030\002 " + "\001(\t\022\\\n\007deposit\030\003 \003(\0132\031.cosmos.base.v1bet" + "a1.CoinB0\310\336\037\000\252\337\037(github.com/cosmos/cosmo" + "s-sdk/types.Coins\022\017\n\007pricing\030\004 \001(\t\022\024\n\003qo" + "s\030\005 \001(\004B\007\342\336\037\003QoS\022\017\n\007options\030\006 \001(\t\022\r\n\005own" + "er\030\007 \001(\t\"\030\n\026MsgBindServiceResponse\"\377\001\n\027M" + "sgUpdateServiceBinding\022-\n\014service_name\030\001" + " \001(\tB\027\362\336\037\023yaml:\"service_name\"\022\020\n\010provide" + "r\030\002 \001(\t\022\\\n\007deposit\030\003 \003(\0132\031.cosmos.base.v" + "1beta1.CoinB0\310\336\037\000\252\337\037(github.com/cosmos/c" + "osmos-sdk/types.Coins\022\017\n\007pricing\030\004 \001(\t\022\024" + "\n\003qos\030\005 \001(\004B\007\342\336\037\003QoS\022\017\n\007options\030\006 \001(\t\022\r\n" + "\005owner\030\007 \001(\t\"!\n\037MsgUpdateServiceBindingR" + "esponse\"]\n\025MsgSetWithdrawAddress\022\r\n\005owne" + "r\030\001 \001(\t\0225\n\020withdraw_address\030\002 \001(\tB\033\362\336\037\027y" + "aml:\"withdraw_address\"\"\037\n\035MsgSetWithdraw" + "AddressResponse\"j\n\030MsgDisableServiceBind" + "ing\022-\n\014service_name\030\001 \001(\tB\027\362\336\037\023yaml:\"ser" + "vice_name\"\022\020\n\010provider\030\002 \001(\t\022\r\n\005owner\030\003 " + "\001(\t\"\"\n MsgDisableServiceBindingResponse\"" + "\307\001\n\027MsgEnableServiceBinding\022-\n\014service_n" + "ame\030\001 \001(\tB\027\362\336\037\023yaml:\"service_name\"\022\020\n\010pr" + "ovider\030\002 \001(\t\022\\\n\007deposit\030\003 \003(\0132\031.cosmos.b" + "ase.v1beta1.CoinB0\310\336\037\000\252\337\037(github.com/cos" + "mos/cosmos-sdk/types.Coins\022\r\n\005owner\030\004 \001(" + "\t\"!\n\037MsgEnableServiceBindingResponse\"i\n\027" + "MsgRefundServiceDeposit\022-\n\014service_name\030" + "\001 \001(\tB\027\362\336\037\023yaml:\"service_name\"\022\020\n\010provid" + "er\030\002 \001(\t\022\r\n\005owner\030\003 \001(\t\"!\n\037MsgRefundServ" + "iceDepositResponse\"\257\003\n\016MsgCallService\022-\n" + "\014service_name\030\001 \001(\tB\027\362\336\037\023yaml:\"service_n" + "ame\"\022\021\n\tproviders\030\002 \003(\t\022\020\n\010consumer\030\003 \001(" + "\t\022\r\n\005input\030\004 \001(\t\022~\n\017service_fee_cap\030\005 \003(" + "\0132\031.cosmos.base.v1beta1.CoinBJ\310\336\037\000\252\337\037(gi" + "thub.com/cosmos/cosmos-sdk/types.Coins\362\336" + "\037\026yaml:\"service_fee_cap\"\022\017\n\007timeout\030\006 \001(" + "\003\022)\n\nsuper_mode\030\007 \001(\010B\025\362\336\037\021yaml:\"super_m" + "ode\"\022\020\n\010repeated\030\010 \001(\010\0229\n\022repeated_frequ" + "ency\030\t \001(\004B\035\362\336\037\031yaml:\"repeated_frequency" + "\"\0221\n\016repeated_total\030\n \001(\003B\031\362\336\037\025yaml:\"rep" + "eated_total\"\"S\n\026MsgCallServiceResponse\0229" + "\n\022request_context_id\030\001 \001(\tB\035\362\336\037\031yaml:\"re" + "quest_context_id\"\"p\n\021MsgRespondService\022)" + "\n\nrequest_id\030\001 \001(\tB\025\362\336\037\021yaml:\"request_id" + "\"\022\020\n\010provider\030\002 \001(\t\022\016\n\006result\030\003 \001(\t\022\016\n\006o" + "utput\030\004 \001(\t\"\033\n\031MsgRespondServiceResponse" + "\"e\n\026MsgPauseRequestContext\0229\n\022request_co" + "ntext_id\030\001 \001(\tB\035\362\336\037\031yaml:\"request_contex" + "t_id\"\022\020\n\010consumer\030\002 \001(\t\" \n\036MsgPauseReque" + "stContextResponse\"e\n\026MsgStartRequestCont" + "ext\0229\n\022request_context_id\030\001 \001(\tB\035\362\336\037\031yam" + "l:\"request_context_id\"\022\020\n\010consumer\030\002 \001(\t" + "\" \n\036MsgStartRequestContextResponse\"d\n\025Ms" + "gKillRequestContext\0229\n\022request_context_i" + "d\030\001 \001(\tB\035\362\336\037\031yaml:\"request_context_id\"\022\020" + "\n\010consumer\030\002 \001(\t\"\037\n\035MsgKillRequestContex" + "tResponse\"\370\002\n\027MsgUpdateRequestContext\0229\n" + "\022request_context_id\030\001 \001(\tB\035\362\336\037\031yaml:\"req" + "uest_context_id\"\022\021\n\tproviders\030\002 \003(\t\022\020\n\010c" + "onsumer\030\003 \001(\t\022~\n\017service_fee_cap\030\004 \003(\0132\031" + ".cosmos.base.v1beta1.CoinBJ\310\336\037\000\252\337\037(githu" + "b.com/cosmos/cosmos-sdk/types.Coins\362\336\037\026y" + "aml:\"service_fee_cap\"\022\017\n\007timeout\030\005 \001(\003\0229" + "\n\022repeated_frequency\030\006 \001(\004B\035\362\336\037\031yaml:\"re" + "peated_frequency\"\0221\n\016repeated_total\030\007 \001(" + "\003B\031\362\336\037\025yaml:\"repeated_total\"\"!\n\037MsgUpdat" + "eRequestContextResponse\"8\n\025MsgWithdrawEa" + "rnedFees\022\r\n\005owner\030\001 \001(\t\022\020\n\010provider\030\002 \001(" + "\t\"\037\n\035MsgWithdrawEarnedFeesResponse2\353\013\n\003M" + "sg\022]\n\rDefineService\022!.irismod.service.Ms" + "gDefineService\032).irismod.service.MsgDefi" + "neServiceResponse\022W\n\013BindService\022\037.irism" + "od.service.MsgBindService\032\'.irismod.serv" + "ice.MsgBindServiceResponse\022r\n\024UpdateServ" + "iceBinding\022(.irismod.service.MsgUpdateSe" + "rviceBinding\0320.irismod.service.MsgUpdate" + "ServiceBindingResponse\022l\n\022SetWithdrawAdd" + "ress\022&.irismod.service.MsgSetWithdrawAdd" + "ress\032..irismod.service.MsgSetWithdrawAdd" + "ressResponse\022r\n\024EnableServiceBinding\022(.i" + "rismod.service.MsgEnableServiceBinding\0320" + ".irismod.service.MsgEnableServiceBinding" + "Response\022u\n\025DisableServiceBinding\022).iris" + "mod.service.MsgDisableServiceBinding\0321.i" + "rismod.service.MsgDisableServiceBindingR" + "esponse\022r\n\024RefundServiceDeposit\022(.irismo" + "d.service.MsgRefundServiceDeposit\0320.iris" + "mod.service.MsgRefundServiceDepositRespo" + "nse\022W\n\013CallService\022\037.irismod.service.Msg" + "CallService\032\'.irismod.service.MsgCallSer" + "viceResponse\022`\n\016RespondService\022\".irismod" + ".service.MsgRespondService\032*.irismod.ser" + "vice.MsgRespondServiceResponse\022o\n\023PauseR" + "equestContext\022\'.irismod.service.MsgPause" + "RequestContext\032/.irismod.service.MsgPaus" + "eRequestContextResponse\022o\n\023StartRequestC" + "ontext\022\'.irismod.service.MsgStartRequest" + "Context\032/.irismod.service.MsgStartReques" + "tContextResponse\022l\n\022KillRequestContext\022&" + ".irismod.service.MsgKillRequestContext\032." + ".irismod.service.MsgKillRequestContextRe" + "sponse\022r\n\024UpdateRequestContext\022(.irismod" + ".service.MsgUpdateRequestContext\0320.irism" + "od.service.MsgUpdateRequestContextRespon" + "se\022l\n\022WithdrawEarnedFees\022&.irismod.servi" + "ce.MsgWithdrawEarnedFees\032..irismod.servi" + "ce.MsgWithdrawEarnedFeesResponseB6Z0gith" + "ub.com/irisnet/irismod/modules/service/t" + "ypes\310\341\036\000b\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { cosmos.base.v1beta1.CoinOuterClass.getDescriptor(), com.google.protobuf.GoGoProtos.getDescriptor(), }); internal_static_irismod_service_MsgDefineService_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_irismod_service_MsgDefineService_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgDefineService_descriptor, new java.lang.String[] { "Name", "Description", "Tags", "Author", "AuthorDescription", "Schemas", }); internal_static_irismod_service_MsgDefineServiceResponse_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_irismod_service_MsgDefineServiceResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgDefineServiceResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgBindService_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_irismod_service_MsgBindService_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgBindService_descriptor, new java.lang.String[] { "ServiceName", "Provider", "Deposit", "Pricing", "Qos", "Options", "Owner", }); internal_static_irismod_service_MsgBindServiceResponse_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_irismod_service_MsgBindServiceResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgBindServiceResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgUpdateServiceBinding_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_irismod_service_MsgUpdateServiceBinding_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgUpdateServiceBinding_descriptor, new java.lang.String[] { "ServiceName", "Provider", "Deposit", "Pricing", "Qos", "Options", "Owner", }); internal_static_irismod_service_MsgUpdateServiceBindingResponse_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_irismod_service_MsgUpdateServiceBindingResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgUpdateServiceBindingResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgSetWithdrawAddress_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_irismod_service_MsgSetWithdrawAddress_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgSetWithdrawAddress_descriptor, new java.lang.String[] { "Owner", "WithdrawAddress", }); internal_static_irismod_service_MsgSetWithdrawAddressResponse_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_irismod_service_MsgSetWithdrawAddressResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgSetWithdrawAddressResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgDisableServiceBinding_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_irismod_service_MsgDisableServiceBinding_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgDisableServiceBinding_descriptor, new java.lang.String[] { "ServiceName", "Provider", "Owner", }); internal_static_irismod_service_MsgDisableServiceBindingResponse_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_irismod_service_MsgDisableServiceBindingResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgDisableServiceBindingResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgEnableServiceBinding_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_irismod_service_MsgEnableServiceBinding_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgEnableServiceBinding_descriptor, new java.lang.String[] { "ServiceName", "Provider", "Deposit", "Owner", }); internal_static_irismod_service_MsgEnableServiceBindingResponse_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_irismod_service_MsgEnableServiceBindingResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgEnableServiceBindingResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgRefundServiceDeposit_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_irismod_service_MsgRefundServiceDeposit_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgRefundServiceDeposit_descriptor, new java.lang.String[] { "ServiceName", "Provider", "Owner", }); internal_static_irismod_service_MsgRefundServiceDepositResponse_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_irismod_service_MsgRefundServiceDepositResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgRefundServiceDepositResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgCallService_descriptor = getDescriptor().getMessageTypes().get(14); internal_static_irismod_service_MsgCallService_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgCallService_descriptor, new java.lang.String[] { "ServiceName", "Providers", "Consumer", "Input", "ServiceFeeCap", "Timeout", "SuperMode", "Repeated", "RepeatedFrequency", "RepeatedTotal", }); internal_static_irismod_service_MsgCallServiceResponse_descriptor = getDescriptor().getMessageTypes().get(15); internal_static_irismod_service_MsgCallServiceResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgCallServiceResponse_descriptor, new java.lang.String[] { "RequestContextId", }); internal_static_irismod_service_MsgRespondService_descriptor = getDescriptor().getMessageTypes().get(16); internal_static_irismod_service_MsgRespondService_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgRespondService_descriptor, new java.lang.String[] { "RequestId", "Provider", "Result", "Output", }); internal_static_irismod_service_MsgRespondServiceResponse_descriptor = getDescriptor().getMessageTypes().get(17); internal_static_irismod_service_MsgRespondServiceResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgRespondServiceResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgPauseRequestContext_descriptor = getDescriptor().getMessageTypes().get(18); internal_static_irismod_service_MsgPauseRequestContext_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgPauseRequestContext_descriptor, new java.lang.String[] { "RequestContextId", "Consumer", }); internal_static_irismod_service_MsgPauseRequestContextResponse_descriptor = getDescriptor().getMessageTypes().get(19); internal_static_irismod_service_MsgPauseRequestContextResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgPauseRequestContextResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgStartRequestContext_descriptor = getDescriptor().getMessageTypes().get(20); internal_static_irismod_service_MsgStartRequestContext_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgStartRequestContext_descriptor, new java.lang.String[] { "RequestContextId", "Consumer", }); internal_static_irismod_service_MsgStartRequestContextResponse_descriptor = getDescriptor().getMessageTypes().get(21); internal_static_irismod_service_MsgStartRequestContextResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgStartRequestContextResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgKillRequestContext_descriptor = getDescriptor().getMessageTypes().get(22); internal_static_irismod_service_MsgKillRequestContext_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgKillRequestContext_descriptor, new java.lang.String[] { "RequestContextId", "Consumer", }); internal_static_irismod_service_MsgKillRequestContextResponse_descriptor = getDescriptor().getMessageTypes().get(23); internal_static_irismod_service_MsgKillRequestContextResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgKillRequestContextResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgUpdateRequestContext_descriptor = getDescriptor().getMessageTypes().get(24); internal_static_irismod_service_MsgUpdateRequestContext_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgUpdateRequestContext_descriptor, new java.lang.String[] { "RequestContextId", "Providers", "Consumer", "ServiceFeeCap", "Timeout", "RepeatedFrequency", "RepeatedTotal", }); internal_static_irismod_service_MsgUpdateRequestContextResponse_descriptor = getDescriptor().getMessageTypes().get(25); internal_static_irismod_service_MsgUpdateRequestContextResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgUpdateRequestContextResponse_descriptor, new java.lang.String[] { }); internal_static_irismod_service_MsgWithdrawEarnedFees_descriptor = getDescriptor().getMessageTypes().get(26); internal_static_irismod_service_MsgWithdrawEarnedFees_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgWithdrawEarnedFees_descriptor, new java.lang.String[] { "Owner", "Provider", }); internal_static_irismod_service_MsgWithdrawEarnedFeesResponse_descriptor = getDescriptor().getMessageTypes().get(27); internal_static_irismod_service_MsgWithdrawEarnedFeesResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_irismod_service_MsgWithdrawEarnedFeesResponse_descriptor, new java.lang.String[] { }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.protobuf.GoGoProtos.castrepeated); registry.add(com.google.protobuf.GoGoProtos.customname); registry.add(com.google.protobuf.GoGoProtos.goprotoGettersAll); registry.add(com.google.protobuf.GoGoProtos.moretags); registry.add(com.google.protobuf.GoGoProtos.nullable); com.google.protobuf.Descriptors.FileDescriptor .internalUpdateFileDescriptor(descriptor, registry); cosmos.base.v1beta1.CoinOuterClass.getDescriptor(); com.google.protobuf.GoGoProtos.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) } package me.anisimoff.editor.Command; import me.anisimoff.editor.Model.Model; import me.anisimoff.editor.Model.State; import me.anisimoff.editor.Route; public class CommandSaveRoute extends Command { private Route dbBackup; public CommandSaveRoute(Model model) { super(model); } @Override public boolean execute() { State state = model.getState(); if(model.isNone()) { return false; } backup = model.getState(); dbBackup = model.loadRouteByID(model.getRoute().getId()); boolean result = model.updateRoute(); if (result) { state.setNotModified(); } return result; } @Override public void undo() { model.setState(State.ModifiedRoute(dbBackup)); model.updateRoute(); model.setState(backup); } } package shvyn22.flexingnotes.presentation.addedit; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; import shvyn22.flexingnotes.data.local.model.Todo; import shvyn22.flexingnotes.databinding.ItemTodoBinding; public class TodoAdapter extends RecyclerView.Adapter { private final ArrayList todos = new ArrayList<>(); @NonNull @Override public TodoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new TodoViewHolder( ItemTodoBinding.inflate( LayoutInflater.from(parent.getContext()), parent, false ) ); } @Override public void onBindViewHolder(@NonNull TodoViewHolder holder, int position) { holder.bind(todos.get(position)); } @Override public int getItemCount() { return todos.size(); } @Override public int getItemViewType(int position) { return position; } @Override public long getItemId(int position) { return position; } public void updateAndNotify(ArrayList todos) { this.todos.clear(); this.todos.addAll(todos); notifyDataSetChanged(); } static class TodoViewHolder extends RecyclerView.ViewHolder { private final ItemTodoBinding binding; public TodoViewHolder(ItemTodoBinding binding) { super(binding.getRoot()); this.binding = binding; } public void bind(Todo item) { binding.cbComplete.setChecked(item.isCompleted); binding.etTodo.setText(item.text); binding.cbComplete.setOnCheckedChangeListener((compoundButton, isChecked) -> item.isCompleted = isChecked ); binding.etTodo.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { item.text = charSequence.toString(); } @Override public void afterTextChanged(Editable editable) { } }); } } } package com.steveq.app.persistence.dao; import com.steveq.app.persistence.model.Authority; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Set; @Repository public interface AuthoritiesRepository extends CrudRepository{ Set findAuthoritiesByNameIn(List names); } package fr.xephi.authme.datasource.columnshandler; import fr.xephi.authme.settings.Settings; import java.util.HashMap; import java.util.Map; /** * Context for resolving the properties of {@link AuthMeColumns} entries. */ public class ColumnContext { private final Settings settings; private final Map, String> columnNames = new HashMap<>(); private final boolean hasDefaultSupport; /** * Constructor. * * @param settings plugin settings * @param hasDefaultSupport whether or not the underlying database has support for the {@code DEFAULT} keyword */ public ColumnContext(Settings settings, boolean hasDefaultSupport) { this.settings = settings; this.hasDefaultSupport = hasDefaultSupport; } public String getName(DataSourceColumn column) { return columnNames.computeIfAbsent(column, k -> settings.getProperty(k.getNameProperty())); } public boolean hasDefaultSupport() { return hasDefaultSupport; } } android-clean-architecture-sample/src/main/java/co/develoop/androidcleanarchitecturesample/screen/list/infinite/adapter/injection/RandomUserInfiniteListAdapterComponent.java package co.develoop.androidcleanarchitecturesample.screen.list.infinite.adapter.injection; import co.develoop.androidcleanarchitecturesample.injection.AppComponent; import co.develoop.androidcleanarchitecturesample.screen.list.infinite.adapter.RandomUserInfiniteListRecyclerViewAdapter; import dagger.Component; @RandomUserInfiniteListAdapterScope @Component(dependencies = {AppComponent.class}, modules = {RandomUserInfiniteListAdapterModule.class}) public interface RandomUserInfiniteListAdapterComponent { void inject(RandomUserInfiniteListRecyclerViewAdapter randomUserInfiniteListAdapter); }core/src/main/java/com/strategicgains/crossroads/I18nConfig.java /* Copyright 2014, Strategic Gains, 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 com.strategicgains.crossroads; import java.util.Properties; import java.util.ResourceBundle; /** * Provides accessing methods for properties values, baseName and bundlePath, * which are used in the Singleton instance of I18n. * * @author toddf * @since Jun 10, 2014 * @see I18n */ public class I18nConfig { private final static String RESOURCE_BUNDLE_BASE_NAME_KEY = "i18n.baseName"; private final static String RESOURCE_BUNDLE_PATH_KEY = "i18n.bundlePath"; private final static String RESOURCE_BUNDLE_BASE_NAME_DEFAULT = "I18n"; private String baseName; private String bundlePath; /** * Construct a new I18nConfig instance, using the configuration values from a Properties instance. * * @param p configuration values. */ public I18nConfig(Properties p) { super(); initialize(p); } /** * Set the configuration values from a Properties instance. * * @param p configuration values. */ protected void initialize(Properties p) { baseName = p.getProperty(RESOURCE_BUNDLE_BASE_NAME_KEY, RESOURCE_BUNDLE_BASE_NAME_DEFAULT); bundlePath = p.getProperty(RESOURCE_BUNDLE_PATH_KEY); } /** * Get the ResourceBundle base name. * * @return the baseName for the resource bundles. * @see ResourceBundle */ public String getBaseName() { return baseName; } /** * Answer whether the configuration has a bundlePath property. * * @return true if the bundlePath property is set, otherwise false. */ public boolean hasBundlePath() { return (bundlePath != null); } /** * Typically, {@link ResourceBundle}s are loaded from the ClassPath. However, many * applications prefer to load {@link ResourceBundle}s from the file system so * they can be deployed and updated separately from the application. *

* By setting a bundlePath, the directory in which {@link ResourceBundle}s live, * I18n will load resource bundles from that file location instead of from the classpath. *

* @return the value of the bundlePath setting. Possibly null. */ public String getBundlePath() { return bundlePath; } } package mantra.errors; /** Defines behavior of object able to handle error messages from Mantra including * both tool errors like "can't write file" and grammar ambiguity warnings. * To avoid having to change tools that use Mantra (like GUIs), I am * wrapping error data in Message objects and passing them to the listener. * In this way, users of this interface are less sensitive to changes in * the info I need for error messages. */ public interface MantraToolListener { public void info(String msg); public void error(MantraMessage msg); public void warning(MantraMessage msg); } src/test/java/cdzero2hero/test/api/FriendsPage.java package cdzero2hero.test.api; import com.gargoylesoftware.htmlunit.html.HtmlAnchor; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput; import com.gargoylesoftware.htmlunit.html.HtmlTextInput; import java.io.IOException; public class FriendsPage { private final HtmlPage htmlPage; public FriendsPage(HtmlPage htmlPage) { this.htmlPage = htmlPage; } public boolean isLoaded() { return "friends".equals(htmlPage.getBody().getId()); } public String getName() { return htmlPage.getElementById("name").asText(); } public LoginPage logout() throws IOException { HtmlAnchor logout = htmlPage.getAnchorByHref("/logout"); HtmlPage newPage = logout.click(); return new LoginPage(newPage); } public int getFriendsCount() { return htmlPage.getByXPath("//tr[@class='friend']").size(); } public FriendsPage addFriend(String firstName, String lastName) throws IOException { HtmlTextInput firstNameInput = htmlPage.getElementByName("firstName"); firstNameInput.setValueAttribute(firstName); HtmlTextInput lastNameInputInput = htmlPage.getElementByName("lastName"); lastNameInputInput.setValueAttribute(lastName); HtmlSubmitInput submitButton = htmlPage.getElementByName("submit"); HtmlPage newPage = submitButton.click(); return new FriendsPage(newPage); } } app/src/main/java/com/alorma/github/gcm/GitskariosGcmListenerService.java package com.alorma.github.gcm; import android.accounts.Account; import android.accounts.AccountManager; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.support.v4.content.ContextCompat; import android.support.v7.app.NotificationCompat; import com.alorma.github.R; import com.alorma.github.account.GetNotificationsService; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import core.User; import core.issues.Issue; import core.repositories.Repo; public class GitskariosGcmListenerService extends FirebaseMessagingService { private static final String TAG = "MyGcmListenerService"; /** * Called when message is received. * * For Set of keys use data.keySet(). */ // [START receive_message] @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); if (remoteMessage.getFrom().startsWith("/topics/")) { defaultNotifications(); /* if (remoteMessage.getData() != null) { String action = remoteMessage.getData().get("action"); if (action != null) { Gson gson = new Gson(); Repo repo = gson.fromJson(remoteMessage.getData().get("repository"), Repo.class); Issue issue = gson.fromJson(remoteMessage.getData().get("issue"), Issue.class); User sender = gson.fromJson(remoteMessage.getData().get("sender"), User.class); summaryNotification(repo); if (action.equals("opened")) { openIssueNotification(repo, issue, sender); } else if (action.equals("closed")) { closeIssueNotification(repo, issue, sender); } } else { defaultNotifications(); } } */ } } private void summaryNotification(Repo repo) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentTitle(repo.getFullName()); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setColor(ContextCompat.getColor(this, R.color.primary)).setGroup(repo.getFullName()).setGroupSummary(true); NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify((int) repo.getId(), builder.build()); } private void openIssueNotification(Repo repo, Issue issue, User sender) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentTitle("Issue opened"); builder.setContentText(sender.getLogin() + " opened issue " + issue.getTitle() + " on " + repo.getFullName()); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setColor(ContextCompat.getColor(this, R.color.primary)).setGroup(repo.getFullName()); NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify((int) issue.getId(), builder.build()); } private void closeIssueNotification(Repo repo, Issue issue, User sender) { NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentTitle("Issue closed"); builder.setContentText(sender.getLogin() + " closed issue " + issue.getTitle() + " on " + repo.getFullName()); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setColor(ContextCompat.getColor(this, R.color.primary)).setGroup(repo.getFullName()); NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nm.notify((int) issue.getId(), builder.build()); } private void defaultNotifications() { Account[] accounts = AccountManager.get(this).getAccountsByType(getString(R.string.account_type)); for (Account account : accounts) { String name = account.name; String token = AccountManager.get(this).getUserData(account, AccountManager.KEY_AUTHTOKEN); Intent intent = new Intent(this, GetNotificationsService.class); intent.putExtra(GetNotificationsService.ACCOUNT_NAME, name); intent.putExtra(GetNotificationsService.ACCOUNT_TOKEN, token); this.startService(intent); } } } 10-100 package info.novatec.testit.webtester.api.callbacks; import info.novatec.testit.webtester.api.browser.Browser; /** * A {@link CallbackWithReturnValue callback with return value} specialized for * {@link Browser browser} input type. * * @param the return type of the callback * @since 0.9.0 */ public interface BrowserCallbackWithReturnValue extends CallbackWithReturnValue { // nothing special - just simplifying the API } demo/src/main/java/me/yokeyword/sample/app/presenter/home/HomeDetailPresenter.java package me.yokeyword.sample.app.presenter.home; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.LineData; import com.github.mikephil.charting.data.LineDataSet; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieEntry; import com.github.mikephil.charting.formatter.IValueFormatter; import com.github.mikephil.charting.utils.ColorTemplate; import com.github.mikephil.charting.utils.ViewPortHandler; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import cn.bmob.v3.BmobUser; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.SaveListener; import me.yokeyword.sample.app.model.entity.DataInfo; import me.yokeyword.sample.app.model.entity.DetailInfo; import me.yokeyword.sample.app.model.entity.ShareInfo; import me.yokeyword.sample.app.presenter.BasePresenter; import me.yokeyword.sample.app.ui.view.home.HomeDetailView; import me.yokeyword.sample.app.util.Logger; /** * Created by xu on 2017/6/19. */ public class HomeDetailPresenter extends BasePresenter { private HomeDetailView view; public HomeDetailPresenter(HomeDetailView view) { this.view = view; } public void setBarData(List infoList) { if (infoList.isEmpty()) return; List yVals = new ArrayList<>(); for (int i = 0; i < infoList.size(); i++) { DetailInfo info = infoList.get(i); yVals.add(new BarEntry(i, info.getValues())); } BarDataSet dataSet = new BarDataSet(yVals, ""); dataSet.setColors(ColorTemplate.MATERIAL_COLORS); dataSet.setValueTextSize(7); BarData data = new BarData(dataSet); view.setBarData(data); } public void setLineData(List infoList) { if (infoList.isEmpty()) return; List yVals = new ArrayList<>(); for (int i = 0; i < infoList.size(); i++) { DetailInfo info = infoList.get(i); yVals.add(new Entry(i, info.getValues())); } LineDataSet dataSet = new LineDataSet(yVals, ""); dataSet.setValueTextSize(12); dataSet.setValueTextColors(ColorTemplate.createColors(ColorTemplate.MATERIAL_COLORS)); dataSet.setColors(ColorTemplate.MATERIAL_COLORS); dataSet.setDrawCircleHole(false); LineData data = new LineData(dataSet); view.setLineData(data); } public void setPieData(List infoList) { if (infoList.isEmpty()) return; List yVals = new ArrayList<>(); for (int i = 0; i < infoList.size(); i++) { DetailInfo info = infoList.get(i); yVals.add(new PieEntry(i, info.getValues())); } PieDataSet dataSet = new PieDataSet(yVals, ""); dataSet.setColors(ColorTemplate.VORDIPLOM_COLORS); dataSet.setValueTextSize(9); dataSet.setDrawValues(false); dataSet.setValueFormatter(new IValueFormatter() { @Override public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) { return decimalFormat.format(value) + "%\t" + (int) entry.getY(); } }); PieData data = new PieData(dataSet); view.setPieData(data); } private DecimalFormat decimalFormat = new DecimalFormat("###,###,###,##0.0"); public void share(List infoList) { BmobUser user = BmobUser.getCurrentUser(); ShareInfo info = new ShareInfo(); info.setUserName(user.getUsername()); info.setData(infoList); info.save(new SaveListener() { @Override public void done(String s, BmobException e) { if (e == null) { view.showToast("分享成功"); } else { view.showToast("分享失败"); Logger.e("BmobException", e.toString()); } } }); } } /* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template */ package View; /** * * @author felipe.guerrera */ public class FormMenu extends javax.swing.JFrame { /** * Creates new form FormMenu */ public FormMenu() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // //GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); bt_cadastrarprod = new javax.swing.JButton(); bt_verprod = new javax.swing.JButton(); bt_novoserv = new javax.swing.JButton(); vt_verservico = new javax.swing.JButton(); bt_cadastrarcliente = new javax.swing.JButton(); bt_cadastrarpet = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); bt_cadastrarcargo = new javax.swing.JButton(); bt_agendamento = new javax.swing.JButton(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(0, 0, 255)); jLabel1.setFont(new java.awt.Font("Ravie", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 0)); jLabel1.setText("Menu Funcionários"); jLabel2.setFont(new java.awt.Font("Ravie", 1, 24)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 0)); jLabel2.setText("Pet Shop Bicho Sacana"); bt_cadastrarprod.setBackground(new java.awt.Color(0, 0, 255)); bt_cadastrarprod.setFont(new java.awt.Font("Ravie", 1, 14)); // NOI18N bt_cadastrarprod.setForeground(new java.awt.Color(255, 255, 0)); bt_cadastrarprod.setText("Cadastrar Produtos"); bt_cadastrarprod.setBorder(null); bt_cadastrarprod.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bt_cadastrarprodActionPerformed(evt); } }); bt_verprod.setBackground(new java.awt.Color(0, 0, 255)); bt_verprod.setFont(new java.awt.Font("Ravie", 1, 14)); // NOI18N bt_verprod.setForeground(new java.awt.Color(255, 255, 0)); bt_verprod.setText("Ver Produtos"); bt_verprod.setBorder(null); bt_verprod.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bt_verprodActionPerformed(evt); } }); bt_novoserv.setBackground(new java.awt.Color(0, 0, 255)); bt_novoserv.setFont(new java.awt.Font("Ravie", 1, 14)); // NOI18N bt_novoserv.setForeground(new java.awt.Color(255, 255, 0)); bt_novoserv.setText("Novo Serviço"); bt_novoserv.setBorder(null); bt_novoserv.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bt_novoservActionPerformed(evt); } }); vt_verservico.setBackground(new java.awt.Color(0, 0, 255)); vt_verservico.setFont(new java.awt.Font("Ravie", 1, 14)); // NOI18N vt_verservico.setForeground(new java.awt.Color(255, 255, 0)); vt_verservico.setText("Ver Serviços"); vt_verservico.setBorder(null); vt_verservico.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { vt_verservicoActionPerformed(evt); } }); bt_cadastrarcliente.setBackground(new java.awt.Color(0, 0, 255)); bt_cadastrarcliente.setFont(new java.awt.Font("Ravie", 1, 14)); // NOI18N bt_cadastrarcliente.setForeground(new java.awt.Color(255, 255, 0)); bt_cadastrarcliente.setText("Cadastrar Clientes"); bt_cadastrarcliente.setBorder(null); bt_cadastrarcliente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bt_cadastrarclienteActionPerformed(evt); } }); bt_cadastrarpet.setBackground(new java.awt.Color(0, 0, 255)); bt_cadastrarpet.setFont(new java.awt.Font("Ravie", 1, 14)); // NOI18N bt_cadastrarpet.setForeground(new java.awt.Color(255, 255, 0)); bt_cadastrarpet.setText("Cadastrar Pet"); bt_cadastrarpet.setBorder(null); bt_cadastrarpet.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bt_cadastrarpetActionPerformed(evt); } }); jButton7.setBackground(new java.awt.Color(0, 0, 255)); jButton7.setFont(new java.awt.Font("Ravie", 1, 14)); // NOI18N jButton7.setForeground(new java.awt.Color(255, 255, 0)); jButton7.setText("Sair"); jButton7.setBorder(null); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); bt_cadastrarcargo.setBackground(new java.awt.Color(0, 0, 255)); bt_cadastrarcargo.setFont(new java.awt.Font("Ravie", 1, 14)); // NOI18N bt_cadastrarcargo.setForeground(new java.awt.Color(255, 255, 0)); bt_cadastrarcargo.setText("Cadastrar Novo Cargo"); bt_cadastrarcargo.setBorder(null); bt_cadastrarcargo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bt_cadastrarcargoActionPerformed(evt); } }); bt_agendamento.setBackground(new java.awt.Color(0, 0, 255)); bt_agendamento.setFont(new java.awt.Font("Ravie", 1, 14)); // NOI18N bt_agendamento.setForeground(new java.awt.Color(255, 255, 0)); bt_agendamento.setText("Agendamento"); bt_agendamento.setBorder(null); bt_agendamento.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { bt_agendamentoActionPerformed(evt); } }); jButton1.setBackground(new java.awt.Color(0, 0, 255)); jButton1.setFont(new java.awt.Font("Ravie", 1, 14)); // NOI18N jButton1.setForeground(new java.awt.Color(255, 255, 0)); jButton1.setText("Cadastrar Funcionário"); jButton1.setBorder(null); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(60, 60, 60) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(jLabel1)) .addComponent(jLabel2))) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton7)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(127, 127, 127) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(9, 9, 9) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(bt_novoserv, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bt_verprod, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bt_cadastrarpet, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bt_cadastrarcliente, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(vt_verservico, javax.swing.GroupLayout.PREFERRED_SIZE, 203, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(bt_cadastrarprod))) .addComponent(bt_cadastrarcargo) .addComponent(jButton1))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(164, 164, 164) .addComponent(bt_agendamento))) .addContainerGap(69, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bt_cadastrarprod) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bt_verprod) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bt_novoserv) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bt_cadastrarpet) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bt_cadastrarcliente) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(vt_verservico) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bt_cadastrarcargo) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bt_agendamento) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton7) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// //GEN-END:initComponents private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed this.dispose(); }//GEN-LAST:event_jButton7ActionPerformed private void bt_cadastrarprodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_cadastrarprodActionPerformed FormCadastrarprod fun = new FormCadastrarprod(); fun.setVisible(true); this.dispose(); }//GEN-LAST:event_bt_cadastrarprodActionPerformed private void bt_verprodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_verprodActionPerformed FormVerprod fun = new FormVerprod(); fun.setVisible(true); this.dispose(); }//GEN-LAST:event_bt_verprodActionPerformed private void vt_verservicoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vt_verservicoActionPerformed FormVerserv fun = new FormVerserv(); fun.setVisible(true); this.dispose(); }//GEN-LAST:event_vt_verservicoActionPerformed private void bt_cadastrarclienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_cadastrarclienteActionPerformed FormCadastrarcliente fun = new FormCadastrarcliente(); fun.setVisible(true); this.dispose(); }//GEN-LAST:event_bt_cadastrarclienteActionPerformed private void bt_cadastrarpetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_cadastrarpetActionPerformed FormCadastrarpet fun = new FormCadastrarpet(); fun.setVisible(true); this.dispose(); }//GEN-LAST:event_bt_cadastrarpetActionPerformed private void bt_novoservActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_novoservActionPerformed FormCadastrarserv fun = new FormCadastrarserv(); fun.setVisible(true); this.dispose(); }//GEN-LAST:event_bt_novoservActionPerformed private void bt_cadastrarcargoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_cadastrarcargoActionPerformed FormCadastrarcargo fun = new FormCadastrarcargo(); fun.setVisible(true); this.dispose(); }//GEN-LAST:event_bt_cadastrarcargoActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed FormCadastrofunc fun = new FormCadastrofunc(); fun.setVisible(true); this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed private void bt_agendamentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_agendamentoActionPerformed FormAgendamento fun = new FormAgendamento(); fun.setVisible(true); this.dispose(); }//GEN-LAST:event_bt_agendamentoActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FormMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FormMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FormMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FormMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } // /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FormMenu().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton bt_agendamento; private javax.swing.JButton bt_cadastrarcargo; private javax.swing.JButton bt_cadastrarcliente; private javax.swing.JButton bt_cadastrarpet; private javax.swing.JButton bt_cadastrarprod; private javax.swing.JButton bt_novoserv; private javax.swing.JButton bt_verprod; private javax.swing.JButton jButton1; private javax.swing.JButton jButton7; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JButton vt_verservico; // End of variables declaration//GEN-END:variables } Chapter11/MeasurableMin/Person.java //Chapter11 - Exercise P11.4 public class Person implements Measureble { private double num; private String name; public Person (double aNum, String aName) { num = aNum; name = aName; } public String getName() { return name; } public double getMax() { return num; } public double getMin() { return num; } }package com.github.anansii.tenebrae.items; import com.github.anansii.tenebrae.TenebraeMod; import com.github.anansii.tenebrae.reference.Reference; import net.minecraft.item.ItemHoe; public class ItemTenebriumHoe extends ItemHoe { public ItemTenebriumHoe() { super(ItemMaterials.tenebriumToolMaterial); final String internalName = ItemNames.tenebriumHoe; setUnlocalizedName(Reference.MOD_ID + "." + internalName); setTextureName(Reference.MOD_ID + ":" + internalName); setCreativeTab(TenebraeMod.creativeTab); } } fapo85/openstack4jcore-test/src/main/java/org/openstack4j/api/network/PortForwardingTests.java package org.openstack4j.api.network; import java.io.IOException; import java.util.List; import org.openstack4j.api.AbstractTest; import org.openstack4j.api.Builders; import org.openstack4j.model.common.ActionResponse; import org.openstack4j.model.network.ext.PortForwarding; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; /** * @author zjluo */ @Test(suiteName = "Network/FloatingIp/portForwarding") public class PortForwardingTests extends AbstractTest { private static final String JSON_RESPONSE_CREATE = "/network/portforwarding/create.json"; private static final String JSON_RESPONSE_GET = "/network/portforwarding/get.json"; private static final String JSON_RESPONSE_LIST = "/network/portforwarding/list.json"; private static final String FLOATINGIP_ID = "2f245a7b-796b-4f26-9cf9-9e82d248fda7"; @Override protected Service service() { return Service.NETWORK; } public void testCreate() throws IOException, InterruptedException { respondWithCodeAndResource(201, JSON_RESPONSE_CREATE); String protocol = "tcp"; String internalPortId = "1238be08-a2a8-4b8d-addf-fb5e2250e480"; String internalIp = "10.0.0.11"; int internalPort = 25; int externalPort = 2230; String description = "Some description"; PortForwarding portForwarding = osv3().networking().floatingip().portForwarding().create(FLOATINGIP_ID, Builders.portForwarding() .protocol(protocol) .internalPortId(internalPortId) .internalIpAddress(internalIp) .internalPort(internalPort) .externalPort(externalPort) .description(description) .build()); assertEquals(internalPortId, portForwarding.getInternalPortId()); assertEquals(protocol, portForwarding.getProtocol()); assertEquals(internalIp, portForwarding.getInternalIpAddress()); assertEquals(internalPort, portForwarding.getInternalPort()); assertEquals(externalPort, portForwarding.getExternalPort()); assertEquals(description, portForwarding.getDescription()); } public void testGet() throws IOException { respondWithCodeAndResource(200, JSON_RESPONSE_GET); String id = "725ade3c-9760-4880-8080-8fc2dbab9acc"; PortForwarding portForwarding = osv3().networking().floatingip().portForwarding().get(FLOATINGIP_ID, id); assertNotNull(portForwarding); assertEquals(portForwarding.getId(), id); } public void testList() throws IOException { respondWithCodeAndResource(200, JSON_RESPONSE_LIST); List portForwardings = osv3().networking().floatingip().portForwarding().list(FLOATINGIP_ID); assertNotNull(portForwardings); assertEquals(portForwardings.size(), 2); } public void testDelete() { respondWith(204); String id = "725ade3c-9760-4880-8080-8fc2dbab9acc"; ActionResponse response = osv3().networking().floatingip().portForwarding().delete(FLOATINGIP_ID, id); assertTrue(response.isSuccess()); } } package com.larryhsiao.clotho.color; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test for {@link GreenInt} */ public class GreenIntTest { /** * Normal case */ @Test void normalCase() { assertEquals( 160, new GreenInt(0xFFA0FF).value() ); } } package com.github.lunatrius.schematica.nbt; import net.minecraft.tileentity.TileEntity; public class TileEntityException extends Exception { public TileEntityException(TileEntity tileEntity, Throwable cause) { super(String.valueOf(tileEntity), cause); } } x-pack/qa/security-example-spi-extension/src/main/java/org/elasticsearch/example/realm/CustomRoleMappingRealm.java /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.example.realm; import org.elasticsearch.action.ActionListener; import org.elasticsearch.common.cache.Cache; import org.elasticsearch.common.cache.CacheBuilder; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.xpack.core.security.authc.AuthenticationResult; import org.elasticsearch.xpack.core.security.authc.AuthenticationToken; import org.elasticsearch.xpack.core.security.authc.Realm; import org.elasticsearch.xpack.core.security.authc.RealmConfig; import org.elasticsearch.xpack.core.security.authc.support.CachingRealm; import org.elasticsearch.xpack.core.security.authc.support.UserRoleMapper; import org.elasticsearch.xpack.core.security.authc.support.UsernamePasswordToken; import org.elasticsearch.xpack.core.security.user.User; import java.util.List; import java.util.Map; /** * An example realm with specific behaviours: * (1) It only supports lookup (that is, "run-as" and "authorization_realms") but not authentication * (2) It performs role mapping to determine the roles for the looked-up user * (3) It caches the looked-up User objects */ public class CustomRoleMappingRealm extends Realm implements CachingRealm { public static final String TYPE = "custom_role_mapping"; static final String USERNAME = "role_mapped_user"; static final String USER_GROUP = "user_group"; private final Cache cache; private final UserRoleMapper roleMapper; public CustomRoleMappingRealm(RealmConfig config, UserRoleMapper roleMapper) { super(config); this.cache = CacheBuilder.builder().build(); this.roleMapper = roleMapper; this.roleMapper.refreshRealmOnChange(this); } @Override public boolean supports(AuthenticationToken token) { return false; } @Override public UsernamePasswordToken token(ThreadContext threadContext) { return null; } @Override public void authenticate(AuthenticationToken authToken, ActionListener> listener) { listener.onResponse(AuthenticationResult.notHandled()); } @Override public void lookupUser(String username, ActionListener listener) { final User user = cache.get(username); if (user != null) { listener.onResponse(user); return; } if (USERNAME.equals(username)) { buildUser( username, ActionListener.wrap(u -> listener.onResponse(cache.computeIfAbsent(username, k -> u)), listener::onFailure) ); } else { listener.onResponse(null); } } private void buildUser(String username, ActionListener listener) { final UserRoleMapper.UserData data = new UserRoleMapper.UserData(username, null, List.of(USER_GROUP), Map.of(), super.config); roleMapper.resolveRoles( data, ActionListener.wrap(roles -> listener.onResponse(new User(username, roles.toArray(String[]::new))), listener::onFailure) ); } @Override public void expire(String username) { this.cache.invalidate(username); } @Override public void expireAll() { this.cache.invalidateAll(); } } onnoA/springboot-sample package com.onnoa.security.jwt.login.config.security; import com.onnoa.security.jwt.login.config.security.service.UserDetailsServiceImpl; import com.onnoa.security.jwt.login.service.UmsAdminService; import com.onnoa.security.jwt.login.service.UmsPermissionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; /** * @Description: SpringSecurity的配置 * 相关依赖及方法说明 *

* configure(HttpSecurity httpSecurity):用于配置需要拦截的url路径、jwt过滤器及出异常后的处理器; * configure(AuthenticationManagerBuilder auth):用于配置UserDetailsService及PasswordEncoder; * RestfulAccessDeniedHandler:当用户没有访问权限时的处理器,用于返回JSON格式的处理结果; * RestAuthenticationEntryPoint:当未登录或token失效时,返回JSON格式的结果; * UserDetailsService:SpringSecurity定义的核心接口,用于根据用户名获取用户信息,需要自行实现; * UserDetails:SpringSecurity定义用于封装用户信息的类(主要是用户信息和权限),需要自行实现; * PasswordEncoder:SpringSecurity定义的用于对密码进行编码及比对的接口,目前使用的是BCryptPasswordEncoder; * JwtAuthenticationTokenFilter:在用户名和密码校验前添加的过滤器,如果有jwt的token,会自行根据token信息进行登录。 * @Author: onnoA * @Date: 2019/12/4 15:15 */ @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UmsAdminService adminService; @Autowired private UmsPermissionService permissionService; @Autowired private UserDetailsServiceImpl userDetailsService; @Autowired private RestfulAccessDeniedHandler restfulAccessDeniedHandler; @Autowired private RestAuthenticationEntryPoint restAuthenticationEntryPoint; @Bean public UserDetailsService userDetailsService() { return username -> { return userDetailsService.loadUserByUsername(username); }; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } // JwtAuthenticationTokenFilter作为拦截器拦截请求 @Bean public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() { return new JwtAuthenticationTokenFilter(); } @Bean @Override // AuthenticationManager进行认证 public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity http) throws Exception { http //post请求默认的都开启了csrf的模式,所有post请求都必须带有token之类的验证信息才可以进入登陆页面,这边是禁用csrf模式 // 由于使用的是JWT,我们这里不需要csrf .csrf() .disable() // 基于token,不用session .sessionManagement() // Session 创建策略 // ALWAYS 总是创建 HttpSession // IF_REQUIRED Spring Security 只会在需要时创建一个 HttpSession // NEVER Spring Security 不会创建 HttpSession,但如果它已经存在,将可以使用 HttpSession // STATELESS Spring Security 永远不会创建 HttpSession,它不会使用 HttpSession 来获取 SecurityContext .sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() //表示以下配置的所有的get请求都不需要权限认证 .authorizeRequests() .antMatchers(HttpMethod.GET, "/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css", "/**/*.js" ) .permitAll() // 对登录注册允许无权限访问 .antMatchers("/admin/login", "/admin/register","/admin/test","/admin/captche","/admin/push","/admin/mybatis") .permitAll() // 除上面的请求外,所有的请求均需验证 .anyRequest() .authenticated(); // 禁用缓存 http.headers().cacheControl(); // 添加jwt filter http.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class); http.exceptionHandling() // 当访问接口没有权限时,自定义的返回结果 .accessDeniedHandler(restfulAccessDeniedHandler) // 当未登录或token失效时,返回JSON格式的结果; .authenticationEntryPoint(restAuthenticationEntryPoint); } // 对登录用户进行认证 其实就是获取用户信息,以及对密码进行校验 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(userDetailsService()) // 密码加密方式 .passwordEncoder(passwordEncoder()); } } package se.arbetsformedlingen.venice.log; import org.apache.http.client.fluent.Executor; import org.apache.http.client.fluent.Request; import java.util.List; import java.util.ArrayList; import java.time.LocalDate; import java.io.IOException; import org.json.JSONArray; import org.json.JSONObject; import org.json.JSONException; public class MonitorClient { private String format; private String[] hosts; private int port; private String[] versions; public MonitorClient(String format, String[] hosts, int port, String[] versions) { this.format = format; this.hosts = hosts; this.port = port; this.versions = versions; } public MonitorResult fetch() throws IOException { Executor executor = Executor.newInstance(); List entries = new ArrayList<>(); for (String host : hosts) { for (String version : versions) { String url = format.replaceAll("\\$\\{host\\}", host) .replaceAll("\\$\\{port\\}", String.valueOf(port)) .replaceAll("\\$\\{version\\}", version); Request request = Request.Get(url); String rawJson = executor .execute(request) .returnContent() .asString(); JSONArray arr = new JSONArray(rawJson); entries.addAll(jsonArrayToLogEntries(host, version, arr)); } } return new MonitorResult(entries); } public List jsonArrayToLogEntries(String host, String version, JSONArray arr) { List entries = new ArrayList<>(); for (int i = 0; i < arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); String service = obj.getString("service"); String method = obj.has("method") ? obj.getString("method") : ""; String applicationId = obj.getString("applicationId"); int count = obj.getInt("count"); double avg = obj.getDouble("avg"); double max = obj.getDouble("max"); double p95 = obj.getDouble("p95"); double p99 = obj.getDouble("p99"); JSONArray buckets = obj.getJSONArray("buckets"); List hours = jsonArrayToCallsPerHour(buckets); entries.add(new LogEntry(host, version, service, method, applicationId, count, avg, max, p95, p99, hours)); } return entries; } public List jsonArrayToCallsPerHour(JSONArray arr) { List hours = new ArrayList<>(); for (int i = 0; i < arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); String rawDate = obj.getString("date"); LocalDate date = LocalDate.parse(rawDate); if (obj.getInt("hour") == 24) { date = date.plusDays(1); } int hour = obj.getInt("hour") % 24; int calls = obj.getInt("value"); hours.add(new CallsPerHour(date, hour, calls)); } return hours; } } /* MIT License Copyright (c) 2019 Gleethos Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ _____ _ _ _ _ ______ |_ _| | | | | | | (_) | ____| | | _ __ ___ _ __ | | ___ _ __ ___ ___ _ __ | |_ __ _| |_ _ ___ _ __ | |__ ___ _ __ | | | '_ ` _ \| '_ \| |/ _ \ '_ ` _ \ / _ \ '_ \| __/ _` | __| |/ _ \| '_ \| __/ _ \| '__| _| |_| | | | | | |_) | | __/ | | | | | __/ | | | || (_| | |_| | (_) | | | | | | (_) | | |_____|_| |_| |_| .__/|_|\___|_| |_| |_|\___|_| |_|\__\__,_|\__|_|\___/|_| |_|_| \___/|_| | | |_| ------------------------------------------------------------------------------------------------------------------------ */ package neureka.backend.api; import neureka.Tsr; import neureka.devices.Device; /** * Generally speaking, this interface describes the functionality of an implementation * of an execution procedure tailored to a specific {@link Device} (interface) instance * and {@link Algorithm} (interface) instance! * Instances of implementations of the {@link ImplementationFor} interface are components * of instances of implementations of the {@link Algorithm} interface, * which themselves are components of {@link Operation} implementation instances. * * * @param The Device type for which an implementation of this interface has been made. */ @FunctionalInterface public interface ImplementationFor< TargetDevice extends Device > { /** * This method is the entrypoint for a concrete implementation * of the algorithm to which instances of this interface * belong and the device on which this is implemented. * One has to keep in mind that the implementation details * with respect to the target device are specific to the * methods of the "TargetDevice" type on which this call should run... * * @param call The call which ought to be executed on this implementation. */ void run( ExecutionCall call ); default Tsr runAndGetFirstTensor(ExecutionCall call ) { this.run( call ); return call.getTensors()[0]; } } 10-100 /* Copyright 2017 Alfa Financial Software * * 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.alfasoftware.morf.jdbc; import static org.junit.Assert.assertEquals; import java.sql.SQLException; import java.sql.SQLTimeoutException; import org.junit.Test; /** * All tests of {@link DatabaseExceptionHelper} * * @author Copyright (c) Alfa Financial Software 2017 */ public class TestDatabaseExceptionHelper { private final DatabaseExceptionHelper databaseExceptionHelper = new DatabaseExceptionHelper(); /** * Test if detection works for throwables which have * {@link SQLTimeoutException} in the causes. */ @Test public void testIsCausedByTimeoutForSQLTimeoutException() { // when then assertEquals(true, databaseExceptionHelper.isCausedByTimeoutException(new ExtendsSQLTimeoutException())); } /** * Test if detection works for special cases of MySQL timeout exceptions which * do not extend {@link SQLTimeoutException} (but only {@link SQLException}). */ @Test public void testIsCausedByTimeoutForMySQLTimeoutException() { // when then assertEquals(true, databaseExceptionHelper.isCausedByTimeoutException(new MySQLTimeoutException())); } /** * Test only generic exception which extends {@link SQLTimeoutException} * * @author Copyright (c) Alfa Financial Software 2017 */ private static class ExtendsSQLTimeoutException extends SQLTimeoutException { } /** * Test only exception which pretends to be one of the MySQL timeout realted * exception (simple name matches). * * @author Copyright (c) Alfa Financial Software 2017 */ private static class MySQLTimeoutException extends SQLException { } } // Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.hosted.controller.application; import org.junit.Assert; import org.junit.Test; /** * @author smorgrav */ public class ClusterUtilizationTest { private static final double delta = Double.MIN_NORMAL; @Test public void getMaxUtilization() { ClusterUtilization resources = new ClusterUtilization(0.3, 0.1, 0.4, 0.5); Assert.assertEquals(0.5, resources.getMaxUtilization(), delta); resources = new ClusterUtilization(0.3, 0.1, 0.4, 0.0); Assert.assertEquals(0.4, resources.getMaxUtilization(), delta); resources = new ClusterUtilization(0.4, 0.3, 0.3, 0.0); Assert.assertEquals(0.4, resources.getMaxUtilization(), delta); resources = new ClusterUtilization(0.1, 0.3, 0.3, 0.0); Assert.assertEquals(0.3, resources.getMaxUtilization(), delta); } } /*************************************************************************** * Copyright (c) 2015 VMware, Inc. 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 com.vmware.bdd.placement.util; import com.vmware.bdd.placement.Container; import com.vmware.bdd.placement.entity.AbstractDatacenter; /** * Created by xiaoliangl on 8/18/15. */ public class ContainerToStringHelper { public static String convertToString(Container container) { AbstractDatacenter dc = container.getDc(); StringBuilder sb = new StringBuilder(dc.getName()).append('\n'); int clusterIndent = 2; for(AbstractDatacenter.AbstractCluster cluster : dc.getClusters()) { for(int i = 0; i < clusterIndent; i ++) { sb.append('>'); } sb.append(cluster.getName()); sb.append('\n'); int hostIndent = 4; if (cluster.getHosts() != null) { for(AbstractDatacenter.AbstractHost host : cluster.getHosts()) { for(int i = 0; i < hostIndent; i ++) { sb.append('>'); } sb.append(host.getName()); sb.append('\n'); int datastoreIndent = 6; if (host.getDatastores() != null) { for(AbstractDatacenter.AbstractDatastore datastore : host.getDatastores()) { for(int i = 0; i < datastoreIndent; i ++) { sb.append('>'); } sb.append(datastore.getName()).append(':').append(datastore.getFreeSpace()).append("GB"); sb.append('\n'); } } } } } return sb.toString(); } } package io.sitoolkit.cv.plugin.gradle; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import org.apache.commons.lang3.StringUtils; import org.gradle.api.file.FileCollection; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.JavaExec; import org.gradle.api.tasks.Optional; import org.gradle.api.tasks.options.Option; public class RunTask extends JavaExec { public static final String ANALYZE_SQL_OPTION = "analyze-sql"; public static final String ANALYZE_SQL_DESCRIPTION = "Run tests and analyze SQL logs to generate a CRUD matrix"; private static final String OPEN_BROWSER_OPTION = "open"; private String stopKey = "x"; private String cvArgs; private boolean analyzeSql; private String openBrowser; @Input @Optional public String getCvArgs() { return cvArgs; } @Option(option = "cvArgs", description = "Project directory path to generate report") public void setCvArgs(String cvArgs) { this.cvArgs = cvArgs; } @Option(option = ANALYZE_SQL_OPTION, description = ANALYZE_SQL_DESCRIPTION) public void setAnalyzeSql(boolean analyzeSql) { this.analyzeSql = analyzeSql; } @Option(option = OPEN_BROWSER_OPTION, description = "Set false to not open the browser at startup") public void setOpenBrowser(String openBrowser) { this.openBrowser = openBrowser; } private List getCvArgsAsList() { List args = new ArrayList<>(); if (StringUtils.isNotEmpty(cvArgs)) { args.addAll(Arrays.asList(cvArgs.split(" "))); } if (analyzeSql) { args.add("--cv." + ANALYZE_SQL_OPTION); } if (!StringUtils.isEmpty(openBrowser) && openBrowser.equals("false")) { args.add("--cv." + OPEN_BROWSER_OPTION + "=false"); } return args; } @Override public void exec() { setArgs(getCvArgsAsList()); super.exec(); } public void configure() { setMain("io.sitoolkit.cv.app.SitCvApplication"); FileCollection classpath = getProject().getBuildscript().getConfigurations() .findByName("classpath"); setClasspath(classpath); getConventionMapping().map("jvmArgs", new Callable>() { @SuppressWarnings("unchecked") @Override public Iterable call() throws Exception { if (getProject().hasProperty("applicationDefaultJvmArgs")) { return (Iterable) getProject().property("applicationDefaultJvmArgs"); } return Collections.emptyList(); } }); } } /* * Copyright (c) 2010-2018 Evolveum * * 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.evolveum.midpoint.certification.impl; import com.evolveum.midpoint.prism.delta.ItemDelta; import java.util.*; import java.util.stream.Collectors; /** * Modifications to execute on an object (mostly on a campaign). * * Because there can be lots of modifications that could take literally hours to execute (sometimes blocking DB as described * e.g. in MID-4611), they are divided into smaller batches. * * @author mederly */ public class ModificationsToExecute { private static final int BATCH_SIZE = 50; final List>> batches = new ArrayList<>(); private List> getLastBatch() { return batches.get(batches.size() - 1); } public boolean isEmpty() { return batches.isEmpty(); } public void add(ItemDelta... deltas) { add(Arrays.asList(deltas)); } public void add(Collection> deltas) { if (deltas.isEmpty()) { return; } if (isEmpty() || getLastBatch().size() + deltas.size() > BATCH_SIZE) { createNewBatch(); } getLastBatch().addAll(deltas); } void createNewBatch() { batches.add(new ArrayList<>()); } int getTotalDeltasCount() { int rv = 0; for (List> batch : batches) { rv += batch.size(); } return rv; } List> getAllDeltas() { return batches.stream().flatMap(Collection::stream).collect(Collectors.toList()); } } package mage.cards.d; import java.util.UUID; import mage.abilities.effects.common.discard.DiscardTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.target.common.TargetOpponent; /** * * @author fireshoes */ public final class Deception extends CardImpl { public Deception(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.SORCERY},"{2}{B}"); // Target opponent discards two cards. this.getSpellAbility().addTarget(new TargetOpponent()); this.getSpellAbility().addEffect(new DiscardTargetEffect(2)); } public Deception(final Deception card) { super(card); } @Override public Deception copy() { return new Deception(this); } } sathiscode/azure-tables-hive package com.microsoft.hadoop.azure; import java.util.*; import org.apache.hadoop.conf.Configuration; import com.microsoft.azure.storage.StorageException; import com.microsoft.azure.storage.table.*; public interface AzureTablePartitioner { public void configure(Configuration config); public List getSplits(CloudTable table) throws StorageException; } 0 package net.zuz.cwm.item.trinkets.items; import dev.emi.trinkets.api.SlotReference; import dev.emi.trinkets.api.TrinketItem; import dev.emi.trinkets.api.client.TrinketRenderer; import net.minecraft.client.render.OverlayTexture; import net.minecraft.client.render.VertexConsumer; import net.minecraft.client.render.VertexConsumerProvider; import net.minecraft.client.render.entity.model.BipedEntityModel; import net.minecraft.client.render.entity.model.EntityModel; import net.minecraft.client.util.math.MatrixStack; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.effect.StatusEffectInstance; import net.minecraft.entity.effect.StatusEffects; import net.minecraft.item.ItemStack; import net.minecraft.util.Identifier; import net.zuz.cwm.entity.trinkets.WarmSocksEntity; public class WarmSocks extends TrinketItem implements TrinketRenderer { public WarmSocks(Settings settings) { super(settings); } @Override public void tick(ItemStack stack, SlotReference slot, LivingEntity entity) { entity.addStatusEffect(new StatusEffectInstance(StatusEffects.SATURATION,400,1, true, false)); } private static final Identifier TEXTURE = new Identifier("cwm", "textures/item/trinkets/amethyst_belt_model.png"); private BipedEntityModel model; @Override public void render(ItemStack stack, SlotReference slotReference, EntityModel contextModel, MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, LivingEntity entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) { BipedEntityModel model = this.getModel(); model.setAngles(entity, limbAngle, limbDistance, animationProgress, animationProgress, headPitch); TrinketRenderer.followBodyRotations(entity, model); VertexConsumer vertexConsumer = vertexConsumers.getBuffer(model.getLayer(TEXTURE)); matrices.scale(0.8F, 0.8F, 0.8F); matrices.translate(0F, 0.8, -0.15); model.render(matrices, vertexConsumer, light, OverlayTexture.DEFAULT_UV, 1, 1, 1, 1); } private BipedEntityModel getModel() { if (this.model == null) { this.model = new WarmSocksEntity(WarmSocksEntity.getTexturedModelData().createModel()); } return this.model; } } 0 // This is a generated file. Not intended for manual editing. package com.intellij.plugins.thrift.lang.psi.impl; import java.util.List; import org.jetbrains.annotations.*; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import static com.intellij.plugins.thrift.lang.lexer.ThriftTokenTypes.*; import com.intellij.plugins.thrift.lang.psi.*; import com.intellij.plugins.thrift.util.ThriftPsiUtil; public class ThriftDefinitionNameImpl extends ThriftPsiCompositeElementImpl implements ThriftDefinitionName { public ThriftDefinitionNameImpl(ASTNode node) { super(node); } public void accept(@NotNull PsiElementVisitor visitor) { if (visitor instanceof ThriftVisitor) ((ThriftVisitor)visitor).visitDefinitionName(this); else super.accept(visitor); } @Override @NotNull public PsiElement getIdentifier() { return findNotNullChildByType(IDENTIFIER); } @NotNull public PsiElement setName(String name) { return ThriftPsiUtil.setName(this, name); } @Nullable @NonNls public String getName() { return ThriftPsiUtil.getName(this); } @NotNull public PsiElement getNameIdentifier() { return ThriftPsiUtil.getNameIdentifier(this); } } jldelarbre/lectureNotes package lectureNotes.lesson2.organizations; public interface IMyComponent { void doSomething(); interface IFactory { IMyComponent build(); } } hzn6426/search-mybatis-plus0 /** * Copyright (c) 2021-2021, zening (). *

* 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.baomibing.query.mybatis; import java.util.Collection; import com.baomibing.query.LimitOffset; import com.baomibing.query.SQLDelete; import com.baomibing.query.SQLQuery; import com.baomibing.query.SQLUpdate; import com.baomibing.query.condition.ACondition; import com.baomibing.query.condition.AND; import com.baomibing.query.condition.BETWEEN; import com.baomibing.query.condition.CTMCondition; import com.baomibing.query.condition.EQ; import com.baomibing.query.condition.EXISTS; import com.baomibing.query.condition.FalseCondition; import com.baomibing.query.condition.GT; import com.baomibing.query.condition.GTE; import com.baomibing.query.condition.IN; import com.baomibing.query.condition.IS_NULL; import com.baomibing.query.condition.LIKE; import com.baomibing.query.condition.LLIKE; import com.baomibing.query.condition.LT; import com.baomibing.query.condition.LTE; import com.baomibing.query.condition.NOT_EQ; import com.baomibing.query.condition.NOT_EXISTS; import com.baomibing.query.condition.NOT_IN; import com.baomibing.query.condition.NOT_NULL; import com.baomibing.query.condition.OR; import com.baomibing.query.condition.RLIKE; import com.baomibing.query.condition.TrueCondition; import com.baomibing.query.expression.ADD; import com.baomibing.query.expression.DIVISION; import com.baomibing.query.expression.Expression; import com.baomibing.query.expression.MOD; import com.baomibing.query.expression.MULTIPL; import com.baomibing.query.expression.POW; import com.baomibing.query.expression.SUBTRACT; import com.baomibing.query.select.AS; import com.baomibing.query.select.AVG; import com.baomibing.query.select.Alias; import com.baomibing.query.select.CASE_WHEN; import com.baomibing.query.select.COUNT; import com.baomibing.query.select.CTMFunction; import com.baomibing.query.select.DISTINCT; import com.baomibing.query.select.Field; import com.baomibing.query.select.FieldPart; import com.baomibing.query.select.MAX; import com.baomibing.query.select.MIN; import com.baomibing.query.select.SQLFunction; import com.baomibing.query.select.SUM; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; /** * An interface which can be implements in service. * It contains the common static condition methods. * * @author zening * @since 1.0.0 */ public interface SQLQueryService { default SQLQuery sqlQuery() {return new SQLQuery();} default SQLUpdate sqlUpdate(Class clazz) {return new SQLUpdate(clazz);} default SQLDelete sqlDelete() {return new SQLDelete();} default Alias alias(Class table, String aliasName) { return new Alias(table, aliasName); } default AND and(ACondition... conditions) { return new AND(conditions); } default OR or(ACondition... conditions) { return new OR(conditions); } default AND and(boolean beTrue, ACondition... conditions) { return new AND(beTrue, conditions); } default OR or(boolean beTrue, ACondition... conditions) { return new OR(beTrue, conditions); } default Field field(String column) {return new Field<>(column);} default LIKE like(FieldPart field, String value) {return new LIKE(field, value);} default LIKE like(boolean beTrue, FieldPart field, String value) {return new LIKE(beTrue, field, value);} default LIKE like(SFunction propertyFunction, String value) { return new LIKE(propertyFunction, value); } default LIKE like(SFunction propertyFunction, SQLFunction sqlFunction) { return new LIKE(propertyFunction, sqlFunction); } default LIKE like(boolean beTrue, SFunction propertyFunction, String value) { return new LIKE(beTrue, propertyFunction, value); } default LIKE like(boolean beTrue, SFunction propertyFunction, SQLFunction sqlFunction) { return new LIKE(beTrue, propertyFunction, sqlFunction); } default LIKE like(Alias alias, String value) { return new LIKE(alias, value); } default LIKE like(Alias alias1, Alias alias2) { return new LIKE(alias1, alias2); } default LIKE like(boolean beTrue, Alias alias, String value) { return new LIKE(beTrue, alias, value); } default LIKE like(boolean beTrue, Alias alias1, Alias alias2) { return new LIKE(beTrue, alias1, alias2); } default LLIKE llike(SFunction propertyFunction, SQLFunction sqlFunction) { return new LLIKE(propertyFunction, sqlFunction); } default LLIKE llike(boolean beTrue, SFunction propertyFunction, SQLFunction sqlFunction) { return new LLIKE(beTrue, propertyFunction, sqlFunction); } default LLIKE llike(FieldPart field, String value) { return new LLIKE(field, value); } default LLIKE llike(boolean beTrue, FieldPart field, String value) { return new LLIKE(beTrue, field, value); } default LLIKE llike(SFunction propertyFunction, String value) { return new LLIKE(propertyFunction, value); } default LLIKE llike(boolean beTrue, SFunction propertyFunction, String value) { return new LLIKE(beTrue, propertyFunction, value); } default LLIKE llike(Alias alias, String value) { return new LLIKE(alias, value); } default LLIKE llike(Alias alias1, Alias alias2) { return new LLIKE(alias1, alias2); } default LLIKE llike(boolean beTrue, Alias alias, String value) { return new LLIKE(beTrue, alias, value); } default LLIKE llike(boolean beTrue, Alias alias1, Alias alias2) { return new LLIKE(beTrue, alias1, alias2); } default RLIKE rlike(SFunction propertyFunction, SQLFunction sqlFunction) { return new RLIKE(propertyFunction, sqlFunction); } default RLIKE rlike(boolean beTrue, SFunction propertyFunction, SQLFunction sqlFunction) { return new RLIKE(beTrue, propertyFunction, sqlFunction); } default RLIKE rlike(FieldPart field, String value) { return new RLIKE(field, value); } default RLIKE rlike(boolean beTrue, SFunction propertyFunction, String value) { return new RLIKE(beTrue, propertyFunction, value); } default RLIKE rlike(boolean beTrue, FieldPart field, String value) { return new RLIKE(beTrue, field, value); } default RLIKE rlike(SFunction propertyFunction, String value) { return new RLIKE(propertyFunction, value); } default RLIKE rlike(Alias alias, String value) { return new RLIKE(alias, value); } default RLIKE rlike(Alias alias1, Alias alias2) { return new RLIKE(alias1, alias2); } default RLIKE rlike(boolean beTrue, Alias alias, String value) { return new RLIKE(beTrue, alias, value); } default RLIKE rlike(boolean beTrue, Alias alias1, Alias alias2) { return new RLIKE(beTrue, alias1, alias2); } default EQ eq(FieldPart field, Object value) { return new EQ(field, value); } default EQ eq(boolean beTrue, FieldPart field, Object value) { return new EQ(beTrue, field, value); } default EQ eq(SFunction propertyFunction, Object value) { return new EQ(propertyFunction, value); } default EQ eq(SFunction propertyFunction, SFunction valueFunction) { return new EQ(propertyFunction, valueFunction); } default EQ eq(SQLFunction sqlFunction, Object value) { return new EQ(sqlFunction, value); } default EQ eq(SQLFunction sqlFunction, SFunction valueFunction) { return new EQ(sqlFunction, valueFunction); } default EQ eq(SFunction propertyFunction, Expression expression) { return new EQ(propertyFunction, expression); } default EQ eq(Alias alias1, Alias alias2) { return new EQ(alias1, alias2); } default EQ eq (Alias alias, Object value) { return new EQ(alias, value); } default EQ eq (Alias alias, Expression expression) { return new EQ(alias, expression); } default EQ eq (boolean beTrue, Alias alias1, Alias alias2) { return new EQ(beTrue, alias1, alias2); } default EQ eq (boolean beTrue, Alias alias, Object value) { return new EQ(beTrue, alias, value); } default EQ eq (boolean beTrue, Alias alias, Expression expression) { return new EQ(beTrue, alias, expression); } default EQ eq(boolean beTrue, SFunction propertyFunction, Object value) { return new EQ(beTrue, propertyFunction, value); } default EQ eq(boolean beTrue, SFunction propertyFunction, SFunction valueFunction) { return new EQ(beTrue, propertyFunction, valueFunction); } default EQ eq(SFunction propertyFunction, SQLFunction sqlFunction) { return new EQ(propertyFunction, sqlFunction); } default EQ eq(boolean beTrue, SFunction propertyFunction, SQLFunction sqlFunction) { return new EQ(beTrue, propertyFunction, sqlFunction); } default EQ eq(boolean beTrue, SQLFunction sqlFunction, Object value) { return new EQ(beTrue, sqlFunction, value); } default EQ eq(boolean beTrue, SQLFunction sqlFunction, SFunction valueFunction) { return new EQ(beTrue, sqlFunction, valueFunction); } default EQ eq(boolean beTrue, SFunction propertyFunction, Expression expression) { return new EQ(beTrue, propertyFunction, expression); } default NOT_EQ not_eq(FieldPart field, Object value) { return new NOT_EQ(field, value); } default NOT_EQ not_eq(boolean beTrue, FieldPart field, Object value) { return new NOT_EQ(beTrue, field, value); } default NOT_EQ not_eq(SFunction propertyFunction, Object value) { return new NOT_EQ(propertyFunction, value); } default NOT_EQ not_eq(SFunction propertyFunction, SFunction valueFunction) { return new NOT_EQ(propertyFunction, valueFunction); } default NOT_EQ not_eq(SFunction propertyFunction, SQLFunction sqlFunction) { return new NOT_EQ(propertyFunction, sqlFunction); } default NOT_EQ not_eq(SQLFunction sqlFunction, Object value) { return new NOT_EQ(sqlFunction, value); } default NOT_EQ not_eq(SQLFunction sqlFunction, SFunction valueFunction) { return new NOT_EQ(sqlFunction, valueFunction); } default NOT_EQ not_eq(SFunction propertyFunction, Expression expression) { return new NOT_EQ(propertyFunction, expression); } default NOT_EQ not_eq(boolean beTrue, SFunction propertyFunction, Object value) { return new NOT_EQ(beTrue, propertyFunction, value); } default NOT_EQ not_eq(boolean beTrue, SFunction propertyFunction, SFunction valueFunction) { return new NOT_EQ(beTrue, propertyFunction, valueFunction); } default NOT_EQ not_eq(boolean beTrue, SQLFunction sqlFunction, Object value) { return new NOT_EQ(beTrue, sqlFunction, value); } default NOT_EQ not_eq(boolean beTrue, SQLFunction sqlFunction, SFunction valueFunction) { return new NOT_EQ(beTrue, sqlFunction, valueFunction); } default NOT_EQ not_eq(boolean beTrue, SFunction propertyFunction, SQLFunction sqlFunction) { return new NOT_EQ(beTrue, propertyFunction, sqlFunction); } default NOT_EQ not_eq(boolean beTrue, SFunction propertyFunction, Expression expression) { return new NOT_EQ(beTrue, propertyFunction, expression); } default NOT_EQ not_eq(Alias alias1, Alias alias2) { return new NOT_EQ(alias1, alias2); } default NOT_EQ not_eq (Alias alias, Object value) { return new NOT_EQ(alias, value); } default NOT_EQ not_eq (Alias alias, Expression expression) { return new NOT_EQ(alias, expression); } default NOT_EQ not_eq (boolean beTrue, Alias alias1, Alias alias2) { return new NOT_EQ(beTrue, alias1, alias2); } default NOT_EQ not_eq (boolean beTrue, Alias alias, Object value) { return new NOT_EQ(beTrue, alias, value); } default NOT_EQ not_eq (boolean beTrue, Alias alias, Expression expression) { return new NOT_EQ(beTrue, alias, expression); } default GT gt(FieldPart field, Object value) { return new GT(field, value); } default GT gt(boolean beTrue, FieldPart field, Object value) { return new GT(beTrue, field, value); } default GT gt(SFunction propertyFunction, Object value) { return new GT(propertyFunction, value); } default GT gt(SFunction propertyFunction, SFunction valueFunction) { return new GT(propertyFunction, valueFunction); } default GT gt(SFunction propertyFunction, SQLFunction sqlFunction) { return new GT(propertyFunction, sqlFunction); } default GT gt(SQLFunction sqlFunction, Object value) { return new GT(sqlFunction, value); } default GT gt(SQLFunction sqlFunction, SFunction valueFunction) { return new GT(sqlFunction, valueFunction); } default GT gt(SFunction propertyFunction, Expression expression) { return new GT(propertyFunction, expression); } default GT gt(boolean beTrue, SFunction propertyFunction, Object value) { return new GT(beTrue, propertyFunction, value); } default GT gt(boolean beTrue, SFunction propertyFunction, SFunction valueFunction) { return new GT(beTrue, propertyFunction, valueFunction); } default GT gt(boolean beTrue, SQLFunction sqlFunction, Object value) { return new GT(beTrue, sqlFunction, value); } default GT gt(boolean beTrue, SQLFunction sqlFunction, SFunction valueFunction) { return new GT(beTrue, sqlFunction, valueFunction); } default GT gt(boolean beTrue, SFunction propertyFunction, SQLFunction sqlFunction) { return new GT(beTrue, propertyFunction, sqlFunction); } default GT gt(boolean beTrue, SFunction propertyFunction, Expression expression) { return new GT(beTrue, propertyFunction, expression); } default GT gt(Alias alias1, Alias alias2) { return new GT(alias1, alias2); } default GT gt (Alias alias, Object value) { return new GT(alias, value); } default GT gt (Alias alias, Expression expression) { return new GT(alias, expression); } default GT gt (boolean beTrue, Alias alias1, Alias alias2) { return new GT(beTrue, alias1, alias2); } default GT gt (boolean beTrue, Alias alias, Object value) { return new GT(beTrue, alias, value); } default GT gt (boolean beTrue, Alias alias, Expression expression) { return new GT(beTrue, alias, expression); } default GTE gte(FieldPart field, Object value) { return new GTE(field, value); } default GTE gte(boolean beTrue, FieldPart field, Object value) { return new GTE(beTrue, field, value); } default GTE gte(SFunction propertyFunction, Object value) { return new GTE(propertyFunction, value); } default GTE gte(SFunction propertyFunction, SFunction valueFunction) { return new GTE(propertyFunction, valueFunction); } default GTE gte(SFunction propertyFunction, SQLFunction sqlFunction) { return new GTE(propertyFunction, sqlFunction); } default GTE gte(SQLFunction sqlFunction, Object value) { return new GTE(sqlFunction, value); } default GTE gte(SQLFunction sqlFunction, SFunction valueFunction) { return new GTE(sqlFunction, valueFunction); } default GTE gte(SFunction propertyFunction, Expression expression) { return new GTE(propertyFunction, expression); } default GTE gte(boolean beTrue, SFunction propertyFunction, Object value) { return new GTE(beTrue, propertyFunction, value); } default GTE gte(boolean beTrue, SFunction propertyFunction, SFunction valueFunction) { return new GTE(beTrue, propertyFunction, valueFunction); } default GTE gte(boolean beTrue, SQLFunction sqlFunction, Object value) { return new GTE(beTrue, sqlFunction, value); } default GTE gte(boolean beTrue, SQLFunction sqlFunction, SFunction valueFunction) { return new GTE(beTrue, sqlFunction, valueFunction); } default GTE gte(boolean beTrue, SFunction propertyFunction, SQLFunction sqlFunction) { return new GTE(beTrue, propertyFunction, sqlFunction); } default GTE gte(boolean beTrue, SFunction propertyFunction, Expression expression) { return new GTE(beTrue, propertyFunction, expression); } default GTE gte(Alias alias1, Alias alias2) { return new GTE(alias1, alias2); } default GTE gte (Alias alias, Object value) { return new GTE(alias, value); } default GTE gte (Alias alias, Expression expression) { return new GTE(alias, expression); } default GTE gte (boolean beTrue, Alias alias1, Alias alias2) { return new GTE(beTrue, alias1, alias2); } default GTE gte (boolean beTrue, Alias alias, Object value) { return new GTE(beTrue, alias, value); } default GTE gte (boolean beTrue, Alias alias, Expression expression) { return new GTE(beTrue, alias, expression); } default LTE lte(FieldPart field, Object value) { return new LTE(field, value); } default LTE lte(boolean beTrue, FieldPart field, Object value) { return new LTE(beTrue, field, value); } default LTE lte(SFunction propertyFunction, Object value) { return new LTE(propertyFunction, value); } default LTE lte(SFunction propertyFunction, SFunction valueFunction) { return new LTE(propertyFunction, valueFunction); } default LTE lte(SFunction propertyFunction, SQLFunction sqlFunction) { return new LTE(propertyFunction, sqlFunction); } default LTE lte(SQLFunction sqlFunction, Object value) { return new LTE(sqlFunction, value); } default LTE lte(SQLFunction sqlFunction, SFunction valueFunction) { return new LTE(sqlFunction, valueFunction); } default LTE lte(SFunction propertyFunction, Expression expression) { return new LTE(propertyFunction, expression); } default LTE lte(boolean beTrue, SFunction propertyFunction, Object value) { return new LTE(beTrue, propertyFunction, value); } default LTE lte(boolean beTrue, SFunction propertyFunction, SFunction valueFunction) { return new LTE(beTrue, propertyFunction, valueFunction); } default LTE lte(boolean beTrue, SQLFunction sqlFunction, Object value) { return new LTE(beTrue, sqlFunction, value); } default LTE lte(boolean beTrue, SQLFunction sqlFunction, SFunction valueFunction) { return new LTE(beTrue, sqlFunction, valueFunction); } default LTE lte(boolean beTrue, SFunction propertyFunction, SQLFunction sqlFunction) { return new LTE(beTrue, propertyFunction, sqlFunction); } default LTE lte(boolean beTrue, SFunction propertyFunction, Expression expression) { return new LTE(beTrue, propertyFunction, expression); } default LTE lte(Alias alias1, Alias alias2) { return new LTE(alias1, alias2); } default LTE lte (Alias alias, Object value) { return new LTE(alias, value); } default LTE lte (Alias alias, Expression expression) { return new LTE(alias, expression); } default LTE lte (boolean beTrue, Alias alias1, Alias alias2) { return new LTE(beTrue, alias1, alias2); } default LTE lte (boolean beTrue, Alias alias, Object value) { return new LTE(beTrue, alias, value); } default LTE lte (boolean beTrue, Alias alias, Expression expression) { return new LTE(beTrue, alias, expression); } default LT lt(FieldPart field, Object value) { return new LT(field, value); } default LT lt(boolean beTrue, FieldPart field, Object value) { return new LT(beTrue, field, value); } default LT lt(SFunction propertyFunction, Object value) { return new LT(propertyFunction, value); } default LT lt(SFunction propertyFunction, SFunction valueFunction) { return new LT(propertyFunction, valueFunction); } default LT lt(SFunction propertyFunction, SQLFunction sqlFunction) { return new LT(propertyFunction, sqlFunction); } default LT lt(SQLFunction sqlFunction, Object value) { return new LT(sqlFunction, value); } default LT lt(SQLFunction sqlFunction, SFunction valueFunction) { return new LT(sqlFunction, valueFunction); } default LT lt(SFunction propertyFunction, Expression expression) { return new LT(propertyFunction, expression); } default LT lt(boolean beTrue, SFunction propertyFunction, Object value) { return new LT(beTrue, propertyFunction, value); } default LT lt(boolean beTrue, SFunction propertyFunction, SFunction valueFunction) { return new LT(beTrue, propertyFunction, valueFunction); } default LT lt(boolean beTrue, SQLFunction sqlFunction, Object value) { return new LT(beTrue, sqlFunction, value); } default LT lt(boolean beTrue, SQLFunction sqlFunction, SFunction valueFunction) { return new LT(beTrue, sqlFunction, valueFunction); } default LT lt(boolean beTrue, SFunction propertyFunction, SQLFunction sqlFunction) { return new LT(beTrue, propertyFunction, sqlFunction); } default LT lt(boolean beTrue, SFunction propertyFunction, Expression expression) { return new LT(beTrue, propertyFunction, expression); } default LT lt(Alias alias1, Alias alias2) { return new LT(alias1, alias2); } default LT lt (Alias alias, Object value) { return new LT(alias, value); } default LT lt (Alias alias, Expression expression) { return new LT(alias, expression); } default LT lt (boolean beTrue, Alias alias1, Alias alias2) { return new LT(beTrue, alias1, alias2); } default LT lt (boolean beTrue, Alias alias, Object value) { return new LT(beTrue, alias, value); } default LT lt (boolean beTrue, Alias alias, Expression expression) { return new LT(beTrue, alias, expression); } default TrueCondition trueCondition() { return new TrueCondition(); } default FalseCondition falseCondition() { return new FalseCondition(); } default BETWEEN between(FieldPart field, Object value1, Object value2) { return new BETWEEN(field, value1, value2); } default BETWEEN between(boolean beTrue, FieldPart field, Object value1, Object value2) { return new BETWEEN(beTrue, field, value1, value2); } default BETWEEN between(SFunction propertyFunction, Object value1, Object value2) { return new BETWEEN(propertyFunction, value1, value2); } default BETWEEN between(boolean beTrue, SFunction propertyFunction, Object value1, Object value2) { return new BETWEEN(beTrue, propertyFunction, value1, value2); } default BETWEEN between(Alias alias, Object value1, Object value2) { return new BETWEEN(alias, value1, value2); } default BETWEEN between(boolean beTrue, Alias alias, Object value1, Object value2) { return new BETWEEN(beTrue, alias, value1, value2); } default IN in(FieldPart field, Collection value) { return new IN(field, value); } default IN in(boolean beTrue, FieldPart field, Collection value) { return new IN(beTrue, field, value); } default IN in(SFunction propertyFunction, Collection value) { return new IN(propertyFunction, value); } default IN in(SFunction propertyFunction, SQLQuery query) { return new IN(propertyFunction, query); } default NOT_IN not_in(FieldPart field, Collection value) { return new NOT_IN(field, value); } default NOT_IN not_in(boolean beTrue, FieldPart field, Collection value) { return new NOT_IN(beTrue, field, value); } default NOT_IN not_in(SFunction propertyFunction, Collection value) { return new NOT_IN(propertyFunction, value); } default NOT_IN not_in(SFunction propertyFunction, SQLQuery query) { return new NOT_IN(propertyFunction, query); } default IN in(boolean beTrue, SFunction propertyFunction, Collection value) { return new IN(beTrue, propertyFunction, value); } default IN in(boolean beTrue, SFunction propertyFunction, SQLQuery query) { return new IN(beTrue, propertyFunction, query); } default NOT_IN not_in(boolean beTrue, SFunction propertyFunction, Collection value) { return new NOT_IN(beTrue, propertyFunction, value); } default NOT_IN not_in(boolean beTrue, SFunction propertyFunction, SQLQuery query) { return new NOT_IN(beTrue, propertyFunction, query); } default IN in(Alias alias, Collection value) { return new IN( alias, value); } default IN in( Alias alias, SQLQuery query) { return new IN(alias, query); } default IN in(boolean beTrue, Alias alias, Collection value) { return new IN(beTrue, alias, value); } default IN in(boolean beTrue, Alias alias, SQLQuery query) { return new IN(beTrue, alias, query); } default NOT_IN not_in(Alias alias, Collection value) { return new NOT_IN( alias, value); } default NOT_IN not_in( Alias alias, SQLQuery query) { return new NOT_IN(alias, query); } default NOT_IN not_in(boolean beTrue, Alias alias, Collection value) { return new NOT_IN(beTrue, alias, value); } default NOT_IN not_in(boolean beTrue, Alias alias, SQLQuery query) { return new NOT_IN(beTrue, alias, query); } default IS_NULL is_null(FieldPart field) { return new IS_NULL(field); } default IS_NULL is_null(boolean beTrue, FieldPart field) { return new IS_NULL(beTrue, field); } default IS_NULL is_null(SFunction propertyFunction) { return new IS_NULL(propertyFunction); } default NOT_NULL not_null(SFunction propertyFunction) { return new NOT_NULL(propertyFunction); } default IS_NULL is_null(Alias alias) { return new IS_NULL(alias); } default IS_NULL is_null(boolean beTrue, Alias alias) { return new IS_NULL(beTrue, alias); } default NOT_NULL not_null(FieldPart field) { return new NOT_NULL(field); } default NOT_NULL not_null(boolean beTrue, FieldPart field) { return new NOT_NULL(beTrue, field); } default NOT_NULL not_null(Alias alias) { return new NOT_NULL(alias); } default NOT_NULL not_null(boolean beTrue, Alias alias) { return new NOT_NULL(beTrue, alias); } default IS_NULL is_null(boolean beTrue, SFunction propertyFunction) { return new IS_NULL(beTrue, propertyFunction); } default NOT_NULL not_null(boolean beTrue, SFunction propertyFunction) { return new NOT_NULL(beTrue, propertyFunction); } default EXISTS exists(SQLQuery queryer) { return new EXISTS(queryer); } default NOT_EXISTS not_exists(SQLQuery queryer) { return new NOT_EXISTS(queryer); } default EXISTS exists(boolean beTrue, SQLQuery queryer) { return new EXISTS(beTrue, queryer); } default NOT_EXISTS not_exists(boolean beTrue, SQLQuery queryer) { return new NOT_EXISTS(beTrue, queryer); } default CTMCondition condition(Alias alias, String sql, Object... args) { return new CTMCondition(alias, sql, args); } default CTMCondition condition(String sql, Alias alias, Object... args) { return new CTMCondition(sql, alias, args); } default CTMCondition condition(boolean beTrue, Alias alias, String sql, Object... args) { return new CTMCondition(beTrue, alias, sql, args); } default CTMCondition condition(boolean beTrue, String sql, Alias alias, Object... args) { return new CTMCondition(beTrue, sql, alias, args); } default CTMCondition condition(SFunction propertyFunction, String sql, Object... args) { return new CTMCondition(propertyFunction, sql, args); } default CTMCondition condition(String sql, Object... args) { return new CTMCondition(sql, args); } default CTMCondition condition(String sql, SFunction propertyFunction, Object... args) { return new CTMCondition(sql, propertyFunction, args); } default CTMCondition condition(boolean beTrue, SFunction propertyFunction, String sql, Object... args) { return new CTMCondition(beTrue, propertyFunction, sql, args); } default CTMCondition condition(boolean beTrue, String sql, Object... args) { return new CTMCondition(beTrue, sql, args); } default CTMCondition condition(boolean beTrue, String sql, SFunction propertyFunction, Object... args) { return new CTMCondition(beTrue, sql, propertyFunction, args); } default ADD add(SFunction propertyFunction, Number value) { return new ADD(propertyFunction, value); } default DIVISION divide(SFunction propertyFunction, Number value) { return new DIVISION(propertyFunction, value); } default MULTIPL multiply(SFunction propertyFunction, Number value) { return new MULTIPL(propertyFunction, value); } default SUBTRACT subtract(SFunction propertyFunction, Number value) { return new SUBTRACT(propertyFunction, value); } default ADD add(Alias alias, Number value) { return new ADD(alias, value); } default DIVISION divide(Alias alias, Number value) { return new DIVISION(alias, value); } default MULTIPL multiply(Alias alias, Number value) { return new MULTIPL(alias, value); } default SUBTRACT subtract(Alias alias, Number value) { return new SUBTRACT(alias, value); } default MOD mod(Alias alias, Number value) { return new MOD(alias, value); } default POW pow(Alias alias, Number value) { return new POW(alias, value); } default MOD mod(SFunction propertyFunction, Number value) { return new MOD(propertyFunction, value); } default POW pow(SFunction propertyFunction, Number value) { return new POW(propertyFunction, value); } default AS as(SQLFunction fun, String alias) { return new AS(fun, alias); } default AS as(FieldPart field, String alias) { return new AS(field, alias); } default AS as(SFunction fun, String alias) { return new AS(fun, alias); } default AVG avg(SFunction fun) { return new AVG(fun); } default AVG avg(String sql) { return new AVG(sql); } default CASE_WHEN case_when() { return new CASE_WHEN(); } default COUNT count(SFunction fun) { return new COUNT(fun); } default COUNT count() { return new COUNT(); } default COUNT count(String sql) { return new COUNT(sql); } default COUNT count(DISTINCT distinct) { return new COUNT(distinct); } default LimitOffset limitOffset(int pageNo, int pageSize) { return new LimitOffset(pageNo, pageSize); } default CTMFunction sql_fun(String fun, Object... args) { return new CTMFunction(fun, args); } default MAX max(SFunction fun) { return new MAX(fun); } default MAX max(String sql) { return new MAX(sql); } default MIN min(SFunction fun) { return new MIN(fun); } default MIN min(String sql) { return new MIN(sql); } default SUM sum(DISTINCT distinct) { return new SUM(distinct); } default SUM sum(SFunction fun) { return new SUM(fun); } default SUM sum(SFunction fun1, SFunction fun2) { return new SUM(fun1, fun2); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3) { return new SUM(fun1, fun2, fun3); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4) { return new SUM(fun1, fun2, fun3, fun4); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5) { return new SUM(fun1, fun2, fun3, fun4, fun5); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17, SFunction fun18) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17, fun18); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17, SFunction fun18, SFunction fun19) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17, fun18, fun19); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17, SFunction fun18, SFunction fun19, SFunction fun20) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17, fun18, fun19, fun20); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17, SFunction fun18, SFunction fun19, SFunction fun20, SFunction fun21) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17, fun18, fun19, fun20, fun21); } default SUM sum(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17, SFunction fun18, SFunction fun19, SFunction fun20, SFunction fun21, SFunction fun22) { return new SUM(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17, fun18, fun19, fun20, fun21, fun22); } default DISTINCT distinct(Alias... aliases) { return new DISTINCT(aliases); } default DISTINCT distinct(SFunction fun) { return new DISTINCT(fun); } default DISTINCT distinct(SFunction fun1, SFunction fun2) { return new DISTINCT(fun1, fun2); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3) { return new DISTINCT(fun1, fun2, fun3); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4) { return new DISTINCT(fun1, fun2, fun3, fun4); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17, SFunction fun18) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17, fun18); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17, SFunction fun18, SFunction fun19) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17, fun18, fun19); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17, SFunction fun18, SFunction fun19, SFunction fun20) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17, fun18, fun19, fun20); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17, SFunction fun18, SFunction fun19, SFunction fun20, SFunction fun21) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17, fun18, fun19, fun20, fun21); } default DISTINCT distinct(SFunction fun1, SFunction fun2, SFunction fun3, SFunction fun4, SFunction fun5, SFunction fun6, SFunction fun7, SFunction fun8, SFunction fun9, SFunction fun10, SFunction fun11, SFunction fun12, SFunction fun13, SFunction fun14, SFunction fun15, SFunction fun16, SFunction fun17, SFunction fun18, SFunction fun19, SFunction fun20, SFunction fun21, SFunction fun22) { return new DISTINCT(fun1, fun2, fun3, fun4, fun5, fun6, fun7, fun8, fun9, fun10, fun11, fun12, fun13, fun14, fun15, fun16, fun17, fun18, fun19, fun20, fun21, fun22); } } 1-10 package org.nineml.coffeegrinder.gll; import org.nineml.coffeegrinder.parser.State; public class MCall extends MStatement { public final State slot; public MCall(State slot) { this.slot = slot; } protected void execute(GllParser gllParser) { gllParser.call(slot, gllParser.c_U, gllParser.c_I); } @Override public String toString() { return "\t\tcall(" + slot + ", c_U, c_I)"; } } /** * 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.hama.examples; import java.io.IOException; import java.util.ArrayList; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hama.HamaConfiguration; import org.apache.hama.bsp.HashPartitioner; import org.apache.hama.bsp.TextInputFormat; import org.apache.hama.bsp.TextOutputFormat; import org.apache.hama.graph.Edge; import org.apache.hama.graph.GraphJob; import org.apache.hama.graph.GraphJobRunner.GraphJobCounter; import org.apache.hama.graph.Vertex; import org.apache.hama.graph.VertexInputReader; /** * NOTE: Graph modification APIs can be used only with {@link MapVerticesInfo}. * * This is an example of how to manipulate Graphs dynamically. The input of this * example is a number in each row. We assume that the is a vertex with ID:1 * which is responsible to create a sum vertex that will aggregate the values of * the other vertices. During the aggregation, sum vertex will delete all other * vertices. * * Input example: 1 2 3 4 * * Output example: sum 10 */ public class DynamicGraph { private static enum DYNAMIC_GRAPH_COUNTER { ADDED_VERTEX } public static class GraphTextReader extends VertexInputReader { @Override public boolean parseVertex(LongWritable key, Text value, Vertex vertex) throws Exception { vertex.setVertexID(value); vertex.setValue(new IntWritable(Integer.parseInt(value.toString()))); return true; } } public static class GraphVertex extends Vertex { private void createSumVertex() throws IOException { if (this.getVertexID().toString().equals("1")) { Text new_id = new Text("sum"); this.addVertex(new_id, new ArrayList>(), new IntWritable(0)); this.getCounter(DYNAMIC_GRAPH_COUNTER.ADDED_VERTEX).increment(1);; } } private void sendAllValuesToSumAndRemove() throws IOException { if (!this.getVertexID().toString().equals("sum")) { this.sendMessage(new Text("sum"), this.getValue()); this.remove(); } } // this must run only on "sum" vertex private void calculateSum(Iterable msgs) throws IOException { if (this.getVertexID().toString().equals("sum")) { int s = 0; for (IntWritable i : msgs) { s += i.get(); } s += this.getPeer().getCounter(GraphJobCounter.INPUT_VERTICES) .getCounter(); this.setValue(new IntWritable(this.getValue().get() + s)); } else { throw new UnsupportedOperationException( "We have more vertecies than we expected: " + this.getVertexID() + " " + this.getValue()); } } @Override public void compute(Iterable msgs) throws IOException { if (this.getSuperstepCount() == 0) { createSumVertex(); } else if (this.getSuperstepCount() == 1) { sendAllValuesToSumAndRemove(); } else if (this.getSuperstepCount() == 2) { calculateSum(msgs); } else if (this.getSuperstepCount() == 3) { this.voteToHalt(); } } } public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { if (args.length != 2) { printUsage(); } HamaConfiguration conf = new HamaConfiguration(new Configuration()); GraphJob graphJob = createJob(args, conf); long startTime = System.currentTimeMillis(); if (graphJob.waitForCompletion(true)) { System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds"); } } private static void printUsage() { System.out.println("Usage: "); System.exit(-1); } private static GraphJob createJob(String[] args, HamaConfiguration conf) throws IOException { GraphJob graphJob = new GraphJob(conf, DynamicGraph.class); graphJob.setJobName("Dynamic Graph"); graphJob.setVertexClass(GraphVertex.class); graphJob.setInputPath(new Path(args[0])); graphJob.setOutputPath(new Path(args[1])); graphJob.setVertexIDClass(Text.class); graphJob.setVertexValueClass(IntWritable.class); graphJob.setEdgeValueClass(NullWritable.class); graphJob.setInputFormat(TextInputFormat.class); graphJob.setVertexInputReaderClass(GraphTextReader.class); graphJob.setPartitioner(HashPartitioner.class); graphJob.setOutputFormat(TextOutputFormat.class); graphJob.setOutputKeyClass(Text.class); graphJob.setOutputValueClass(IntWritable.class); return graphJob; } } src/main/java/com/recoders/escapelog/dto/MapAreaDto.java package com.recoders.escapelog.dto; import com.recoders.escapelog.domain.AreaGroup; import lombok.Getter; @Getter public class MapAreaDto { String areaGroup; String areaKrName; int areaThemeNum; int visitNum; int successNum; int stampLevel; int requiredNum; double visitNumPercent; double successNumPercent; public MapAreaDto(AreaGroup areaGroup, int areaThemeNum,int visitNum, int successNum){ this.areaGroup = areaGroup.name(); this.areaKrName = areaGroup.getKrName(); this.areaThemeNum = areaThemeNum; this.visitNum = visitNum; this.successNum = successNum; this.visitNumPercent = visitNum*areaThemeNum !=0 ? calculatePercentage(visitNum,areaThemeNum) : 0; this.successNumPercent = successNum*areaThemeNum !=0 ? calculatePercentage(successNum,areaThemeNum) : 0; setAreaStampLevel(this.visitNumPercent); } public void setAreaStampLevel(double visitNumPercent){ if (visitNumPercent>=70){ this.stampLevel = 3; }else if(visitNumPercent>=50){ this.stampLevel = 2; this.requiredNum = (int) Math.ceil((0.7*areaThemeNum)-visitNum); }else if(visitNumPercent>=20){ this.requiredNum = (int) Math.ceil((0.5*areaThemeNum)-visitNum); this.stampLevel = 1; }else{ this.requiredNum = (int) Math.ceil((0.2*areaThemeNum)-visitNum); this.stampLevel = 0; } } public double calculatePercentage(int numerator, int denominator){ double result = Double.parseDouble(String.format("%.2f",(double)numerator/denominator*100)); return result; } } bloodhound-annotations/src/main/java/com/jvanderwee/bloodhound/TrackScreen.java package com.jvanderwee.bloodhound; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.METHOD; @Retention(RetentionPolicy.RUNTIME) @Target({METHOD}) public @interface TrackScreen { String value(); } package com.elastic.operations.admin; import org.elasticsearch.client.Client; import org.elasticsearch.client.ClusterAdminClient; import org.elasticsearch.client.IndicesAdminClient; import org.springframework.beans.factory.annotation.Autowired; /** * @Date: 2019/12/23 16:16 **/ public class PublicAdmin { @Autowired Client client; public IndicesAdminClient indicesAdminClient = client.admin().indices(); public ClusterAdminClient clusterAdminClient = client.admin().cluster(); } package nu.postnummeruppror.insamlingsappen; import nu.postnummeruppror.insamlingsappen.domain.Account; import nu.postnummeruppror.insamlingsappen.domain.LocationSample; import nu.postnummeruppror.insamlingsappen.domain.Root; import org.json.JSONArray; import org.json.JSONObject; import org.prevayler.Query; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; /** * @author kalle * @since 2017-12-05 */ public class ProduceTimeLineStatistics { public static void main (String[] args) throws Exception { Insamlingsappen.getInstance().open(); try { Writer out = new OutputStreamWriter(new FileOutputStream(new File("src/main/webapp/nightly/stats.json")), "UTF8"); JSONArray stats = new ProduceTimeLineStatistics().execute(); stats.write(out); out.close(); } finally { Insamlingsappen.getInstance().close(); } } private static class Item { private String date; private int totalSampleCount = 0; private int totalPostalCodeCount = 0; private int totalPostalTownCount = 0; private List newSamples = new ArrayList<>(); private List newAccounts = new ArrayList<>(); private int totalAccountsCount =0; private Set newPostalCodes = new HashSet<>(); private Set newPostalTowns = new HashSet<>(); } public JSONArray execute() throws Exception { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Map items = new HashMap<>(); Set postalCodes = new HashSet<>(); Set postalTowns = new HashSet<>(); // add accounts List accounts = Insamlingsappen.getInstance().getPrevayler().execute(new Query>() { @Override public List query(Root root, Date date) throws Exception { return new ArrayList<>(root.getAccounts().values()); } }); for (Account account : accounts) { String date = dateFormat.format(new Date(account.getTimestampCreated())); Item item = items.get(date); if (item == null) { item = new Item(); item.date = date; items.put(date, item); } item.newAccounts.add(account); } // add samples List locationSamples = Insamlingsappen.getInstance().getPrevayler().execute(new Query>() { @Override public List query(Root root, Date date) throws Exception { return new ArrayList(root.getLocationSamples().values()); } }); for (LocationSample locationSample : locationSamples) { String date = dateFormat.format(new Date(locationSample.getTimestamp())); Item item = items.get(date); if (item == null) { item = new Item(); item.date = date; items.put(date, item); } item.newSamples.add(locationSample); String postalCode = locationSample.getTag("addr:postcode"); if (postalCode != null) { postalCode = postalCode.replaceAll("\\D+", ""); if (postalCode.length() == 5 && postalCodes.add(postalCode)) { item.newPostalCodes.add(postalCode); } } String postalTown = locationSample.getTag("addr:city"); if (postalTown != null) { postalTown = postalTown.toUpperCase(); postalTown = postalTown.replaceAll("\\s+", ""); postalTown = postalTown.replaceAll("\\p{Punct}+", ""); if (!postalTown.isEmpty() && postalTowns.add(postalTown)) { item.newPostalTowns.add(locationSample.getTag("addr:city")); } } } // set total counts in all items List itemsByDate = new ArrayList<>(items.values()); Collections.sort(itemsByDate, new Comparator() { @Override public int compare(Item o1, Item o2) { return o1.date.compareTo(o2.date); } }); int totalSampleCount = 0; int totalPostalCodeCount = 0; int totalPostalTownCount = 0; int totalAcccountsCount = 0; for (Item item : itemsByDate) { totalSampleCount += item.newSamples.size(); item.totalSampleCount = totalSampleCount; totalPostalCodeCount += item.newPostalCodes.size(); item.totalPostalCodeCount = totalPostalCodeCount; totalPostalTownCount += item.newPostalTowns.size(); item.totalPostalTownCount = totalPostalTownCount; totalAcccountsCount += item.newAccounts.size(); item.totalAccountsCount = totalAcccountsCount; } JSONArray response = new JSONArray(); for (Item item : itemsByDate) { JSONArray newPostalCodes = new JSONArray(); for (String postalCode : item.newPostalCodes) { newPostalCodes.put(postalCode); } JSONArray newPostalTowns = new JSONArray(); for (String postalTown : item.newPostalTowns) { newPostalTowns.put(postalTown); } JSONObject jsonItem = new JSONObject(new LinkedHashMap<>()); jsonItem.put("date", item.date); jsonItem.put("newSamplesCount", item.newSamples.size()); jsonItem.put("totalSampleCount", item.totalSampleCount); jsonItem.put("newPostalCodes", newPostalCodes); jsonItem.put("totalPostalCodeCount", item.totalPostalCodeCount); jsonItem.put("newPostalTowns", newPostalTowns); jsonItem.put("totalPostalTownCount", item.totalPostalTownCount); jsonItem.put("newAccountsCount", item.newAccounts.size()); jsonItem.put("totalAccountsCount", item.totalAccountsCount); response.put(jsonItem); } return response; } } package se.uu.it.cs.recsys.persistence.entity; /* * #%L * CourseRecommenderPersistence * %% * Copyright (C) 2015 < > * %% * 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. * #L% */ import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author <> */ @Entity @Table(name = "course") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Course.findAll", query = "SELECT c FROM Course c"), @NamedQuery(name = "Course.findAllDistinctAutoGenId", query = "SELECT DISTINCT(c.autoGenId) FROM Course c"), @NamedQuery(name = "Course.findByAutoGenId", query = "SELECT c FROM Course c WHERE c.autoGenId = :autoGenId"), @NamedQuery(name = "Course.findByAutoGenIds", query = "SELECT c FROM Course c WHERE c.autoGenId in :autoGenIds"), @NamedQuery(name = "Course.findByCode", query = "SELECT c FROM Course c " + "LEFT JOIN FETCH c.courseDomainRelevanceCollection WHERE c.code = :code"), @NamedQuery(name = "Course.findByName", query = "SELECT c FROM Course c WHERE c.name = :name"), @NamedQuery(name = "Course.findByLevel", query = "SELECT c FROM Course c WHERE c.level = :level"), @NamedQuery(name = "Course.findByCredit", query = "SELECT c FROM Course c WHERE c.credit = :credit"), @NamedQuery(name = "Course.findByTaughtYear", query = "SELECT c FROM Course c WHERE c.taughtYear = :taughtYear"), @NamedQuery(name = "Course.findByStartPeriod", query = "SELECT c FROM Course c WHERE c.startPeriod = :startPeriod"), @NamedQuery(name = "Course.findByEndPeriod", query = "SELECT c FROM Course c WHERE c.endPeriod = :endPeriod"), @NamedQuery(name = "Course.findByTaughtYearAndStartPeriod", query = "SELECT c FROM Course c " + "WHERE c.taughtYear = :taughtYear and c.startPeriod = :startPeriod"), @NamedQuery(name = "Course.findByCodeAndTaughtYearAndStartPeriod", query = "SELECT c FROM Course c " + "WHERE c.code = :code and c.taughtYear = :taughtYear and c.startPeriod = :startPeriod")}) public class Course implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "auto_gen_id") private Integer autoGenId; @Column(name = "code") private String code; @Column(name = "name") private String name; @Column(name = "taught_year") private Short taughtYear; @Column(name = "start_period") private Short startPeriod; @Column(name = "end_period") private Short endPeriod; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "course") private Collection courseDomainRelevanceCollection; @JoinColumn(name = "credit", referencedColumnName = "credit") @ManyToOne private SupportedCourseCredit credit; @JoinColumn(name = "level", referencedColumnName = "level") @ManyToOne private SupportedCourseLevel level; @OneToMany(cascade = CascadeType.ALL, mappedBy = "course") private Collection courseSelectionNormalizedCollection; @OneToMany(cascade = CascadeType.ALL, mappedBy = "course") private Collection courseSelectionOriginalCollection; public Course() { } public Course(Integer autoGenId) { this.autoGenId = autoGenId; } public Integer getAutoGenId() { return autoGenId; } public void setAutoGenId(Integer autoGenId) { this.autoGenId = autoGenId; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Short getTaughtYear() { return taughtYear; } public void setTaughtYear(Short taughtYear) { this.taughtYear = taughtYear; } public Short getStartPeriod() { return startPeriod; } public void setStartPeriod(Short startPeriod) { this.startPeriod = startPeriod; } public Short getEndPeriod() { return endPeriod; } public void setEndPeriod(Short endPeriod) { this.endPeriod = endPeriod; } @XmlTransient public Collection getCourseDomainRelevanceCollection() { return courseDomainRelevanceCollection; } public void setCourseDomainRelevanceCollection(Collection courseDomainRelevanceCollection) { this.courseDomainRelevanceCollection = courseDomainRelevanceCollection; } public SupportedCourseCredit getCredit() { return credit; } public void setCredit(SupportedCourseCredit credit) { this.credit = credit; } public SupportedCourseLevel getLevel() { return level; } public void setLevel(SupportedCourseLevel level) { this.level = level; } @XmlTransient public Collection getCourseSelectionNormalizedCollection() { return courseSelectionNormalizedCollection; } public void setCourseSelectionNormalizedCollection(Collection courseSelectionNormalizedCollection) { this.courseSelectionNormalizedCollection = courseSelectionNormalizedCollection; } @XmlTransient public Collection getCourseSelectionOriginalCollection() { return courseSelectionOriginalCollection; } public void setCourseSelectionOriginalCollection(Collection courseSelectionOriginalCollection) { this.courseSelectionOriginalCollection = courseSelectionOriginalCollection; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((autoGenId == null) ? 0 : autoGenId.hashCode()); result = prime * result + ((code == null) ? 0 : code.hashCode()); result = prime * result + ((courseDomainRelevanceCollection == null) ? 0 : courseDomainRelevanceCollection.hashCode()); result = prime * result + ((courseSelectionNormalizedCollection == null) ? 0 : courseSelectionNormalizedCollection.hashCode()); result = prime * result + ((courseSelectionOriginalCollection == null) ? 0 : courseSelectionOriginalCollection.hashCode()); result = prime * result + ((credit == null) ? 0 : credit.hashCode()); result = prime * result + ((endPeriod == null) ? 0 : endPeriod.hashCode()); result = prime * result + ((level == null) ? 0 : level.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((startPeriod == null) ? 0 : startPeriod.hashCode()); result = prime * result + ((taughtYear == null) ? 0 : taughtYear.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Course other = (Course) obj; if (autoGenId == null) { if (other.autoGenId != null) { return false; } } else if (!autoGenId.equals(other.autoGenId)) { return false; } if (code == null) { if (other.code != null) { return false; } } else if (!code.equals(other.code)) { return false; } if (courseDomainRelevanceCollection == null) { if (other.courseDomainRelevanceCollection != null) { return false; } } else if (!courseDomainRelevanceCollection .equals(other.courseDomainRelevanceCollection)) { return false; } if (courseSelectionNormalizedCollection == null) { if (other.courseSelectionNormalizedCollection != null) { return false; } } else if (!courseSelectionNormalizedCollection .equals(other.courseSelectionNormalizedCollection)) { return false; } if (courseSelectionOriginalCollection == null) { if (other.courseSelectionOriginalCollection != null) { return false; } } else if (!courseSelectionOriginalCollection .equals(other.courseSelectionOriginalCollection)) { return false; } if (credit == null) { if (other.credit != null) { return false; } } else if (!credit.equals(other.credit)) { return false; } if (endPeriod == null) { if (other.endPeriod != null) { return false; } } else if (!endPeriod.equals(other.endPeriod)) { return false; } if (level == null) { if (other.level != null) { return false; } } else if (!level.equals(other.level)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (startPeriod == null) { if (other.startPeriod != null) { return false; } } else if (!startPeriod.equals(other.startPeriod)) { return false; } if (taughtYear == null) { if (other.taughtYear != null) { return false; } } else if (!taughtYear.equals(other.taughtYear)) { return false; } return true; } @Override public String toString() { return "se.uu.it.cs.recsys.persistence.entity.Course[ autoGenId=" + autoGenId + " ]"; } } jiwopene/BobBall /* Copyright (c) 2012 . All rights reserved. Licensed under the terms of the BSD License, see LICENSE.txt */ package org.bobstuff.bobball; import android.graphics.Color; import android.os.Parcel; import android.os.Parcelable; import org.bobstuff.bobball.GameLogic.Bar; public class Player implements Parcelable { private int score; public Bar bar; private int lives; public int level; private int playerId; public Player(int playerId) { this.score = 0; this.bar = null; this.lives = 0; this.level = 0; this.playerId = playerId; } public Player(Player other) { this.score = other.score; if (other.bar != null) this.bar = new Bar(other.bar); this.lives = other.lives; this.level = other.level; this.playerId = other.playerId; } public int getPlayerId() { return playerId; } public int getLives() { return lives; } public void setLives(int lives) { this.lives = lives; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } //implement parcelable public int describeContents() { return 0; } public int getColor() { float hue = playerId * 36; return Color.HSVToColor(new float[]{hue, 1, 1}); } protected Player(Parcel in) { ClassLoader classLoader = getClass().getClassLoader(); playerId = in.readInt(); level = in.readInt(); score = in.readInt(); bar = in.readParcelable(classLoader); lives = in.readInt(); } public void writeToParcel(Parcel dest, int flags) { dest.writeInt(playerId); dest.writeInt(level); dest.writeInt(score); dest.writeParcelable(bar, flags); dest.writeInt(lives); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public Player createFromParcel(Parcel in) { return new Player(in); } public Player[] newArray(int size) { return new Player[size]; } }; } NoFaceGoose/TabletopGames package games.blackjack.gui; import core.components.Deck; import core.components.FrenchCard; import core.components.PartialObservableDeck; import gui.views.CardView; import gui.views.ComponentView; import utilities.ImageIO; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import static games.blackjack.gui.BlackjackGUIManager.*; public class BlackjackDeckView extends ComponentView { Image backOfCard; String dataPath; int minimumCardOffset = 5; Rectangle[] rects; int cardHighlight = -1; boolean highlighting; public BlackjackDeckView(Deck d, String dataPath){ super(d, playerWidth, cardHeight); backOfCard = ImageIO.GetInstance().getImage(dataPath + "gray_back.png"); this.dataPath = dataPath; addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ALT){ highlighting = true; } } @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ALT){ highlighting = false; cardHighlight = -1; } } }); addMouseMotionListener(new MouseAdapter() { @Override public void mouseMoved(MouseEvent e) { if (highlighting){ for (int i = 0; i< rects.length; i++){ if (rects[i].contains(e.getPoint())){ cardHighlight = i; break; } } } } }); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() ==1){ for (int i = 0; i< rects.length; i++){ if (rects[i].contains(e.getPoint())){ cardHighlight = i; break; } } } else{ cardHighlight = -1; } } }); } @Override protected void paintComponent(Graphics g) { drawDeck((Graphics2D)g, new Rectangle(0, 0, width, cardHeight)); } public void drawDeck(Graphics2D g, Rectangle rect){ int size = g.getFont().getSize(); @SuppressWarnings("Unchecked") PartialObservableDeck deck = (PartialObservableDeck) component; if (deck != null){ int offset = Math.max((rect.width-cardWidth) / deck.getSize(), minimumCardOffset); rects = new Rectangle[deck.getSize()]; for (int i = 0; i < deck.getSize(); i++){ FrenchCard card = deck.get(i); Image cardFace = getCardImage(card); Rectangle r = new Rectangle(rect.x + offset * i, rect.y, cardWidth, cardHeight); rects[i] = r; CardView.drawCard(g, r.x, r.y, r.width, r.height, card, cardFace, backOfCard, deck.isComponentVisible(i, 0)); g.drawRoundRect(r.x, r.y, r.width, r.height, 15, 15); } if (cardHighlight != -1){ FrenchCard card = deck.get(cardHighlight); Image cardFace = getCardImage(card); Rectangle r = rects[cardHighlight]; CardView.drawCard(g, r.x, r.y, r.width, r.height, card, cardFace, backOfCard, deck.isComponentVisible(cardHighlight, 0)); g.drawRoundRect(r.x, r.y, r.width, r.height, 15, 15); } g.drawString(""+deck.getSize(), rect.x+10, rect.y+cardHeight - size); } } @Override public Dimension getPreferredSize(){ return new Dimension(width, height); } private Image getCardImage(FrenchCard card){ Image img = null; //String coloName = card. switch(card.type){ case Number: img = ImageIO.GetInstance().getImage(dataPath + card.number + card.suite + ".png"); break; case Jack: case Queen: case King: case Ace: img = ImageIO.GetInstance().getImage(dataPath + card.type + card.suite + ".png"); break; } return img; } public int getCardHighlight(){return cardHighlight;} public void setCardHighlight(int cardHighlight) { this.cardHighlight = cardHighlight; } public Rectangle[] getRects() { return rects; } } /* * 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.isis.persistence.jpa.eclipselink.inject; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.util.Collections; import java.util.Set; import javax.enterprise.context.spi.Contextual; import javax.enterprise.context.spi.CreationalContext; import javax.enterprise.inject.spi.AnnotatedConstructor; import javax.enterprise.inject.spi.AnnotatedField; import javax.enterprise.inject.spi.AnnotatedMethod; import javax.enterprise.inject.spi.AnnotatedType; import javax.enterprise.inject.spi.InjectionPoint; import javax.enterprise.inject.spi.InjectionTarget; import javax.inject.Provider; import org.apache.isis.applib.services.inject.ServiceInjector; import org.apache.isis.commons.internal.exceptions._Exceptions; import lombok.SneakyThrows; final class _Util { static CreationalContext createCreationalContext(Contextual contextual) { return new CreationalContext() { @Override public void push(T incompleteInstance) { // silently ignore } @Override public void release() { // silently ignore } }; } static AnnotatedType createAnnotatedType(Class type) { return new AnnotatedType() { @Override public Class getJavaClass() { return type; } @Override public Type getBaseType() { _Exceptions.throwNotImplemented(); return null; } @Override public Set getTypeClosure() { _Exceptions.throwNotImplemented(); return null; } @Override public X getAnnotation(Class annotationType) { _Exceptions.throwNotImplemented(); return null; } @Override public Set getAnnotations() { _Exceptions.throwNotImplemented(); return null; } @Override public boolean isAnnotationPresent(Class annotationType) { _Exceptions.throwNotImplemented(); return false; } @Override public Set> getConstructors() { _Exceptions.throwNotImplemented(); return null; } @Override public Set> getMethods() { _Exceptions.throwNotImplemented(); return null; } @Override public Set> getFields() { _Exceptions.throwNotImplemented(); return null; } }; } static InjectionTarget createInjectionTarget( final AnnotatedType type, final Provider serviceInjectorProvider) { return new InjectionTarget() { @Override @SneakyThrows public T produce(CreationalContext ctx) { return type.getJavaClass().newInstance(); } @Override public void inject(T instance, CreationalContext ctx) { serviceInjectorProvider.get().injectServicesInto(instance); } @Override public void dispose(T instance) { // silently ignore } @Override public Set getInjectionPoints() { // silently ignore return Collections.emptySet(); } @Override public void postConstruct(T instance) { // silently ignore } @Override public void preDestroy(T instance) { // silently ignore } }; } } package prueba1; import java.util.ArrayList; import java.util.List; public class Datos { //atributos private List listaCar; //constructores public Datos(List listaCar) { super(); this.listaCar = listaCar; } //Constructor personalizado public Datos() { super(); this.listaCar = new ArrayList (); listaCar.add(new Coche ("Toyota","Celica",143,"Azul")); listaCar.add(new Coche ("Renault","Megane",90,"Rojo")); listaCar.add(new Coche ("Seat","Leon",110,"Rojo")); listaCar.add(new Coche ("Seat","Leon",150,"Verde")); listaCar.add(new Coche ("Seat","Ibiza",105,"Gris")); listaCar.add(new Coche ("BMW", "325",190,"Negro")); } //getters and setters public List getListaCar() { return listaCar; } public void setListaCar(List listaCar) { this.listaCar = listaCar; } //toString @Override public String toString() { return "Datos [listaCar=" + listaCar + "]"; } } package model.entity; import lombok.Data; /** * Created by louxiu */ @Data public class B extends A { private int b; private Object a; @Override public int getA() { return (Integer) a; } } 0 package org.harry.security.util; import iaik.asn1.ObjectID; import iaik.asn1.structures.AlgorithmID; import iaik.asn1.structures.Attribute; import iaik.asn1.structures.GeneralName; import iaik.asn1.structures.Name; import iaik.security.provider.IAIKMD; import iaik.utils.RFC2253NameParser; import iaik.utils.Util; import iaik.x509.X509Certificate; import iaik.x509.attr.AttributeCertificate; import iaik.x509.attr.Holder; import iaik.x509.attr.V2Form; import iaik.x509.attr.attributes.Role; import iaik.x509.attr.extensions.NoRevAvail; import iaik.x509.ocsp.OCSPResponse; import iaik.x509.ocsp.ReqCert; import iaik.xml.crypto.XSecProvider; import iaik.xml.crypto.XmldsigMore; import iaik.xml.crypto.utils.KeySelectorImpl; import iaik.xml.crypto.utils.URIDereferencerImpl; import iaik.xml.crypto.xades.*; import iaik.xml.crypto.xades.dom.DOMExtensionContext; import iaik.xml.crypto.xades.impl.dom.XAdESSignatureFactory; import iaik.xml.crypto.xades.timestamp.TimeStampProcessor; import org.harry.security.util.bean.SigningBean; import org.harry.security.util.ocsp.HttpOCSPClient; import org.harry.security.util.trustlist.TrustListManager; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.xml.crypto.Data; import javax.xml.crypto.KeySelector; import javax.xml.crypto.MarshalException; import javax.xml.crypto.OctetStreamData; import javax.xml.crypto.dsig.*; import javax.xml.crypto.dsig.dom.DOMSignContext; import javax.xml.crypto.dsig.dom.DOMValidateContext; import javax.xml.crypto.dsig.keyinfo.*; import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.*; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URI; import java.security.*; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.util.*; import static java.util.Arrays.asList; import static java.util.Collections.nCopies; import static org.harry.security.CommonConst.*; public class SignXAdESUtil { private PrivateKey privateKey; private Certificate[] certChain; private XAdESSignatureFactory sfac; private QualifyingPropertiesFactory qfac; private KeyInfoFactory kif; private XAdESSignature signature; private Document doc; private DOMSignContext context; private XAdESParams params = new XAdESParams(); private String signedPropsId; private XMLExtendContext exContext; private List walker; public SignXAdESUtil(PrivateKey key, Certificate[] certChain, boolean pkcs11) throws Exception { this.privateKey = key; this.certChain = certChain; walker = ConfigReader.loadAllTrusts(); Provider xSecProvider = null; if ( !pkcs11) { IAIKMD.addAsProvider(); xSecProvider = new XSecProvider(); Security.insertProviderAt(xSecProvider, 3); //move other XMLDsig provider to the end Provider otherXMLDsigProvider = Security.getProvider("XMLDSig"); if (otherXMLDsigProvider != null) { Security.removeProvider(otherXMLDsigProvider.getName()); Security.addProvider(otherXMLDsigProvider); } } else { } sfac = (XAdESSignatureFactory) XAdESSignatureFactory.getInstance("DOM", xSecProvider); qfac = QualifyingPropertiesFactory.getInstance("DOM", xSecProvider); kif = KeyInfoFactory.getInstance("DOM", xSecProvider); } /** * method for prepare signing with all requested parameteers TODO pack the parameters into a sign parameter class * @param sourceXML the inpput xml stream * @param params the parameter object for building a signature * * @throws Exception error case */ public void prepareSigning(InputStream sourceXML, XAdESParams params) throws Exception { String sigBaseId = UUID.randomUUID().toString(); signedPropsId = "SignedProperties-" + sigBaseId; String signatureId = "Signature-" + sigBaseId; loadXMLDoc(sourceXML); X509Certificate [] signerChain = new X509Certificate[certChain.length]; int index = 0; for (Certificate cert: certChain) { signerChain[index] = new X509Certificate(cert.getEncoded()); index++; } this.params = params; // reference to the signed properties Reference spRef = sfac.newReference( "#" + signedPropsId, sfac.newDigestMethod(params.getDigestAlg(), null), asList(sfac.newTransform(params.getCanonMethod(), (TransformParameterSpec) null)), SignedProperties.REFERENCE_TYPE, "SignedProperties-Reference-" + sigBaseId); // reference to the data itself (enveloped) Reference ref = sfac.newReference( "", sfac.newDigestMethod(params.getDigestAlg(), null), Collections.singletonList (sfac.newTransform (Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); CanonicalizationMethod canonicalizationMethod = sfac.newCanonicalizationMethod( params.getCanonMethod(), (C14NMethodParameterSpec) null); SignatureMethod signatureMethod = sfac.newSignatureMethod( params.getSignatureAlg(), null); SignedInfo si = sfac.newSignedInfo( canonicalizationMethod, signatureMethod, asList( ref, spRef), "SignedInfo-" + sigBaseId); CertIDV2 certID = qfac.newCertIDV2(null, signerChain[0], sfac.newDigestMethod(params.getDigestAlg(), null),true); SigningCertificateV2 sc = qfac.newSigningCertificateV2(Collections.singletonList(certID)); SigningTime st = null; st = qfac.newSigningTime(); SignatureProductionPlaceV2 prodPlace = null; if (params.getProductionPlace() != null) { VerificationResults.ProdPlace place = params.getProductionPlace(); prodPlace = qfac.newSignatureProductionPlaceV2(place.getCity(), place.getStreet(), place.getRegion(), place.getZipCode(), place.getCountry()); } SignerRoleV2 theRole = null; if (params.getSignerRole().isPresent()) { theRole = getSignerRoleV2(params); } List counterSigs = new ArrayList<>(); if (params.getCounterSigKeys().isPresent()) { Tuple keys = params.getCounterSigKeys().get(); CounterSignature cs = createCounterSignature(keys); counterSigs = Collections.nCopies(1, cs); } SignaturePolicyIdentifier spiden = null; if (params.isGenPolicy()) { spiden = generatePolicy(); } SignedSignatureProperties ssp = qfac.newSignedSignatureProperties(st, sc, spiden, prodPlace, theRole, null); // Create SignedProperties SignedDataObjectProperties sdp = null; if (params.isSetContentTimeStamp()) { sdp = setAllDataObjTSP(params.getCanonMethod()); } SignedProperties sp = qfac.newSignedProperties(ssp, sdp, signedPropsId); // Create QualifyingProperties UnsignedProperties up = qfac.newUnsignedProperties(qfac.newUnsignedSignatureProperties(counterSigs, null) , null, null); QualifyingProperties qp = qfac.newQualifyingProperties(sp, up, "#" + signatureId, null); XMLObject qpObj = sfac.newXMLObject(nCopies(1, qp), null, null, null); X509Data x509data = kif.newX509Data( Arrays.asList(signerChain)); KeyInfo ki = kif.newKeyInfo(Collections.nCopies(1, x509data)); signature = (XAdESSignature) sfac.newXMLSignature(si, ki, Arrays.asList(qpObj), signatureId, "SignatureValue-" + sigBaseId); context = new DOMSignContext(privateKey, doc.getDocumentElement()); context.setURIDereferencer(new URIDereferencerImpl()); context.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); context.putNamespacePrefix(XMLSignature.XMLNS, "ds"); context.putNamespacePrefix(XAdESSignature.XMLNS_1_4_1, "xades"); if (params.isSetContentTimeStamp()) { TimeStampProcessor processor = new SimpleTimeStampProcessor(params.getTSA_URL()); context.put(TimeStampProcessor.PROPERTY, processor); } } private SignaturePolicyIdentifier generatePolicy() throws FileNotFoundException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { // Create the SignaturePolicyIdentifier qualifying property InputStream policyStream = SignXAdESUtil.class.getResourceAsStream("/signatures/UnichornPolicy.xml"); Data spis = new OctetStreamData( new BufferedInputStream(policyStream), "/signatures/UnichornPolicy.xml", "text/xml"); ObjectIdentifier oi = qfac.newObjectIdentifier("http://www.unichorn.de/policy/all", null, "Harrys Policy", null); List spqualifiers = new ArrayList(); List spuris = new ArrayList(); spuris.add(qfac.newSPURI("/resources/signatures/UnichornPolicy.xml")); spqualifiers.add(qfac.newSigPolicyQualifier(spuris)); List spusernotices = new ArrayList(); spusernotices.add(qfac.newSPUserNotice("This is a default signature only.", null)); spqualifiers.add(qfac.newSigPolicyQualifier(spusernotices)); SignaturePolicyId spid = qfac.newSignaturePolicyId(oi, null, sfac.newDigestMethod(params.getDigestAlg(), null), spis, spqualifiers); return qfac.newSignaturePolicyIdentifier(spid); } private SignerRoleV2 getSignerRoleV2(XAdESParams params) throws CertificateEncodingException { SignerRoleV2 theRole; X509AttributeCertificate cert = qfac.newX509AttributeCertificate(params.getSignerRole().get().getEncoded(), null, null); CertifiedRoleV2 role = qfac.newCertifiedRoleV2(cert); theRole = qfac.newSignerRoleV2(null, Arrays.asList(role), null); return theRole; } private void loadXMLDoc(InputStream sourceXML) throws ParserConfigurationException, SAXException, IOException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); dbf.setIgnoringElementContentWhitespace(true); dbf.setExpandEntityReferences(false); DocumentBuilder documentBuilder = dbf.newDocumentBuilder(); doc = documentBuilder.parse(sourceXML); } private SignedDataObjectProperties setAllDataObjTSP(String canonMethod) throws Exception { // add an AllDataObjectsTimeStamp AllDataObjectsTimeStamp allDataObjectsTimeStamp = qfac.newAllDataObjectsTimeStamp( sfac.newCanonicalizationMethod(canonMethod, (C14NMethodParameterSpec) null), "AllDataObjectsTimeStamp-1", null); List dataObjectTimeStamps = new ArrayList<>(); dataObjectTimeStamps.add(allDataObjectsTimeStamp); SignedDataObjectProperties sdp = qfac.newSignedDataObjectProperties(null, null, dataObjectTimeStamps, null, null); return sdp; } private void setSignatureTimeStamp(DOMValidateContext valContext) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MalformedURLException, MarshalException, XMLSignatureException { NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); exContext = new DOMExtensionContext(valContext); SignatureTimeStamp tsp = this.qfac.newSignatureTimeStamp(sfac.newCanonicalizationMethod(params.getCanonMethod(), (C14NMethodParameterSpec) null), "timeStampID" + UUID.randomUUID().toString(), null); TimeStampProcessor processor = new SimpleTimeStampProcessor(params.getTSA_URL()); exContext.put(TimeStampProcessor.PROPERTY, processor); signature.appendSignatureTimeStamp(tsp, exContext); } public CounterSignature createCounterSignature(Tuple keys) throws Exception { // Create a Reference to the orignal signature Reference csRef = sfac.newReference("#" + signedPropsId, sfac.newDigestMethod(params.getDigestAlg(), null), null, CounterSignature.REFERENCE_TYPE, null); // Create corresponding SignedInfo SignedInfo csSI = sfac.newSignedInfo(sfac.newCanonicalizationMethod( params.getCanonMethod(), (C14NMethodParameterSpec) null), sfac .newSignatureMethod(params.getSignatureAlg(), null), Collections .nCopies(1, csRef)); // Create a KeyValue containing the RSA PublicKey that was generated KeyInfoFactory kif = sfac.getKeyInfoFactory(); X509Data x509data = kif.newX509Data( Arrays.asList(keys.getSecond())); KeyInfo cski = kif.newKeyInfo(Collections.nCopies(1, x509data)); // Create counter signature CertIDV2 certID = qfac.newCertIDV2(null, keys.getSecond()[0], sfac.newDigestMethod(params.getDigestAlg(), null),true); SigningCertificateV2 sc = qfac.newSigningCertificateV2(Collections.singletonList(certID)); SignedSignatureProperties ssp = qfac.newSignedSignatureProperties(null, sc, null, null, null, null); SignedProperties sp = qfac.newSignedProperties(ssp, null, UUID.randomUUID().toString()); QualifyingProperties qp = qfac.newQualifyingProperties(sp, null, "#" + UUID.randomUUID().toString(), null); XMLObject qpObj = sfac.newXMLObject(nCopies(1, qp), null, null, null); XMLSignature cs = sfac.newXMLSignature(csSI, cski, Arrays.asList(qpObj), UUID.randomUUID().toString(), "SignatureValue-" + UUID.randomUUID().toString()); // Create the XAdES CounterSignature property CounterSignature counterSignature = qfac.newCounterSignature(cs, KeySelector.singletonKeySelector(keys.getFirst())); return counterSignature; } public void sign(OutputStream targetXML) throws Exception { signature.sign(context); DOMValidateContext valContext = switchToDomValidateContext(); valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE); if (params.isSetSigTimeStamp()) { setSignatureTimeStamp(valContext); } if (params.isAppendOCSPValues()) { appendOCSPResults(); } processTransformWrite(targetXML); return; } private DOMValidateContext switchToDomValidateContext() throws Exception { ByteArrayOutputStream signedOut = new ByteArrayOutputStream(); processTransformWrite(signedOut); ByteArrayInputStream xmlIN = new ByteArrayInputStream(signedOut.toByteArray()); loadXMLDoc(xmlIN); NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); DOMValidateContext valContext = new DOMValidateContext(new KeySelectorImpl(), nl.item(0)); // unmarshal the XMLSignature signature = (XAdESSignature)sfac.unmarshalXMLSignature(valContext); boolean coreValidity = signature.validate(valContext); return valContext; } private void appendOCSPResults() throws Exception { // Get SigningCertificate and RevocationInformation // And create the CompleteCertificateRefs and CompleteRevocationRefs properties CertIDV2 sigCert = null; QualifyingProperties qp = ((XAdESSignature) signature).getQualifyingProperties(); SignedProperties sp = qp.getSignedProperties(); if (sp != null) { SignedSignatureProperties ssp = sp.getSignedSignatureProperties(); if (ssp != null) { SigningCertificateV2 sigCerts = ssp.getSigningCertificateV2(); if (sigCerts != null) { List certs = sigCerts.getCertIDs(); if (!certs.isEmpty()) { sigCert = (CertIDV2) certs.get(0); } } } } IssuerSerialV2 sigCertIssSer = sigCert.getIssuerSerialV2(); String issuerName = sigCertIssSer.getIssuerName(); RFC2253NameParser parser = new RFC2253NameParser(issuerName); Name name = parser.parse(); String cn = name.getRDN(ObjectID.commonName); List certRefs = new ArrayList(); List ocspRefs = new ArrayList(); SigningBean bean = new SigningBean().setCheckPathOcsp(true); AlgorithmPathChecker checker = new AlgorithmPathChecker(walker, bean); VerificationResults.SignerInfoCheckResults results = new VerificationResults.SignerInfoCheckResults(); X509Certificate[] realChain = checker.detectChain(Util.convertCertificate(this.certChain[0]), null, results); for(int index = 0;index < realChain.length; index++) { if (( index + 1) < realChain.length) { X509Certificate cert = realChain[index]; X509Certificate [] checkChain= new X509Certificate[2]; checkChain[0] = cert; checkChain[1] = realChain[index + 1]; BigInteger serial = cert.getSerialNumber(); CertIDV2 certId = qfac.newCertIDV2("https://localhost/" + serial, cert, sfac.newDigestMethod(params.getDigestAlg(), null), false); certRefs.add(certId); OCSPResponse response = HttpOCSPClient.sendOCSPRequest(OCSP_URL, null, null, checkChain, ReqCert.certID, false, true); String ocspFile = APP_DIR_WORKING + File.separator + cn + ".ocs"; File ocspOutFile = new File(ocspFile); URI uri = ocspOutFile.toURI(); OutputStream ocspOut = new FileOutputStream(ocspOutFile); response.writeTo(ocspOut); ocspOut.flush(); ocspOut.close(); ocspRefs.add(qfac.newOCSPRef(response.getEncoded(), sfac.newDigestMethod(DigestMethod.SHA1, null), uri.toString())); } } CompleteCertificateRefsV2 compCertRefs = qfac.newCompleteCertificateRefsV2(certRefs, "CompleteCertificateRefs"); CompleteRevocationRefs compRevRefs; compRevRefs = qfac.newCompleteRevocationRefs(null, ocspRefs, null, "CompleteRevocationRefs"); //register unmarshalled ID attributes with the new Context // for (Iterator iter = valContext.iterator(); iter.hasNext();) { // Map.Entry idElementEntry = (Map.Entry) iter.next(); // Element e = (Element) idElementEntry.getValue(); // extensionContext.setIdAttributeNS(e,null,"Id"); // } // Append validation references ((XAdESSignature) signature).appendValidationRefsV2(compCertRefs, compRevRefs, null, null, exContext); } private void processTransformWrite(OutputStream outputStream) throws TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(doc), new StreamResult(outputStream)); } public void createAttributeCert(OutputStream certOut) throws Exception { AttributeCertificate attributeCertificate = new AttributeCertificate(); // issuer V2Form v2Form = new V2Form((iaik.asn1.structures.Name) new X509Certificate(this.certChain[0].getEncoded()).getSubjectDN()); attributeCertificate.setIssuer(v2Form); // holder (from base certificate) Holder holder = new Holder(); holder.setBaseCertificateID(new X509Certificate(this.certChain[0].getEncoded())); attributeCertificate.setHolder(holder); // serial number attributeCertificate.setSerialNumber(BigInteger.valueOf(1563556764)); // validity GregorianCalendar c = new GregorianCalendar(); Date notBeforeTime = c.getTime(); c.add(Calendar.YEAR, 3); Date notAfterTime = c.getTime(); attributeCertificate.setNotBeforeTime(notBeforeTime); attributeCertificate.setNotAfterTime(notAfterTime); // add any attributes (e.g. Role): GeneralName roleName = new GeneralName(GeneralName.uniformResourceIdentifier, "urn:productManager"); Role role = new Role(roleName); attributeCertificate.addAttribute(new Attribute(role)); // add any extensions (e.g. No Revocation Info Available): NoRevAvail noRevAvail = new NoRevAvail(); attributeCertificate.addExtension(noRevAvail); // sign attribute certificate attributeCertificate.sign(AlgorithmID.sha512WithRSAEncryption, privateKey); // DER encode the certificate attributeCertificate.writeTo(certOut); } public XAdESParams newParams() { return new XAdESParams(); } public class XAdESParams { private boolean setSigTimeStamp = false; private boolean setContentTimeStamp = false; private boolean setArchiveTimeStamp = false; private Optional signerRole = Optional.empty(); private String canonMethod = CanonicalizationMethod.EXCLUSIVE; private String signatureAlg = XmldsigMore.SIGNATURE_RSA_SHA256; private String digestAlg = DigestMethod.SHA256; private String TSA_URL = TSP_URL; private Optional> counterSigKeys = Optional.empty(); private VerificationResults.ProdPlace productionPlace = null; private boolean genPolicy = false; private boolean appendOCSPValues = false; public boolean isSetSigTimeStamp() { return setSigTimeStamp; } public XAdESParams setSetSigTimeStamp(boolean setSigTimeStamp) { this.setSigTimeStamp = setSigTimeStamp; return this; } public boolean isSetContentTimeStamp() { return setContentTimeStamp; } public XAdESParams setSetContentTimeStamp(boolean setContentTimeStamp) { this.setContentTimeStamp = setContentTimeStamp; return this; } public boolean isSetArchiveTimeStamp() { return setArchiveTimeStamp; } public XAdESParams setSetArchiveTimeStamp(boolean setArchiveTimeStamp) { this.setArchiveTimeStamp = setArchiveTimeStamp; return this; } public Optional getSignerRole() { return signerRole; } public XAdESParams setSignerRole(Optional signerRole) { this.signerRole = signerRole; return this; } public String getCanonMethod() { return canonMethod; } public XAdESParams setCanonMethod(String canonMethod) { this.canonMethod = canonMethod; return this; } public String getSignatureAlg() { return signatureAlg; } public XAdESParams setSignatureAlg(String signatureAlg) { this.signatureAlg = signatureAlg; return this; } public String getDigestAlg() { return digestAlg; } public XAdESParams setDigestAlg(String digestAlg) { this.digestAlg = digestAlg; return this; } public String getTSA_URL() { return TSA_URL; } public XAdESParams setTSA_URL(String TSA_URL) { this.TSA_URL = TSA_URL; return this; } public Optional> getCounterSigKeys() { return counterSigKeys; } public XAdESParams setCounterSigKeys(Tuple input) { this.counterSigKeys = Optional.of(input); return this; } public VerificationResults.ProdPlace getProductionPlace() { return productionPlace; } public XAdESParams setProductionPlace(VerificationResults.ProdPlace productionPlace) { this.productionPlace = productionPlace; return this; } public boolean isGenPolicy() { return genPolicy; } public XAdESParams setGenPolicy(boolean genPolicy) { this.genPolicy = genPolicy; return this; } public boolean isAppendOCSPValues() { return appendOCSPValues; } public XAdESParams setAppendOCSPValues(boolean appendOCSPValues) { this.appendOCSPValues = appendOCSPValues; return this; } } } android/src/main/java/ru/krista/io/asn1/core/Asn1Tag.java package ru.krista.io.asn1.core; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value = {ElementType.TYPE, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Asn1Tag { /** * Маска, определяющая специальный набор тэгов использующихся только как маркеры в алгоритме обработки DER структур. * Никакие структуры не могут быть записаны или прочитаны из DER потока с этими тэгами. */ int SYNTETIC_MASK = 0xFF00; /* Тэг не определен */ int TAG_UNSPECIFIED = 0xFFFF; /* Объект может иметь любой тэг, явное значение которого указано в контейнере, частью которого объект является */ int TAG_ANY = 0xFFFE; /** * Значение тэга опрелеляется полимофым типом. */ int TAG_EXPLICIT_CONSTRUCT = 0xFFFD; int value() default TAG_UNSPECIFIED; Tag.TagClass cls() default Tag.TagClass.UNIVERSAL; Tag.TagType type() default Tag.TagType.PRIMITIVE; } package de.saarland.trie; import java.util.*; /** * @author almer * 7/6/13, 11:36 AM */ public class Node { // Children of this node. // private final Node children[]; private final Map children; // Values to store on the leaf nodes private final Set values; // Pointer to a heavy child private Character heavyChildPointer; // Number of children in the subtree // including itself. private int weight; /** * Constructor */ public Node() { this.children = new HashMap<>(); this.values = new HashSet<>(); this.weight = 1; } public void addChild(Character c, Node node) { if (children.containsKey(c)) System.out.println(String.format("Node already contains character %c", c)); children.put(c, node); } public Node getChild(Character c) { if (children.containsKey(c)) return children.get(c); return null; } public Set getValues() { return values; } /** * Returns children array with, * possibly with null values inside. * * @return children of this node */ public Map getChildren() { return children; } public Node getHeavyChild() { return children.get(heavyChildPointer); } // public Character getHeavyChildPointer() { // return heavyChildPointer; // } public void setHeavyChildPointer(Character pointer) { this.heavyChildPointer = pointer; } public List getLightChildren() { List lightChildren = new ArrayList<>(); for (Character ch : children.keySet()) { if (!ch.equals(heavyChildPointer)) lightChildren.add(children.get(ch)); } return lightChildren; } public boolean isLeaf() { return weight == 1; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } /** * Creates a deep copy of itself * * @return a deep copy of itself */ public Node deepCopy() { Node result = new Node(); for (Character key : children.keySet()) { Node child = children.get(key).deepCopy(); result.addChild(key, child); } result.getValues().addAll(values); return result; } } package com.intkr.saas.module.screen.admin.shop.json; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * * @author beidenhuang * @datetime 2011-11-3 下午03:49:42 * @version 1.0 */ public class HasLogin { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); public void execute(HttpServletRequest request, HttpServletResponse response) { request.setAttribute("msg", "yes"); } } kmall-search/src/main/java/xyz/klenkiven/kmall/search/service/impl/MallSearchServiceImpl.java package xyz.klenkiven.kmall.search.service.impl; import com.fasterxml.jackson.core.JsonEncoding; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.io.JsonStringEncoder; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.json.JsonMapper; import lombok.RequiredArgsConstructor; import org.apache.commons.lang.StringUtils; import org.apache.lucene.search.join.ScoreMode; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.*; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.aggregations.AggregationBuilders; import org.elasticsearch.search.aggregations.Aggregations; import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation; import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder; import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested; import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms; import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms; import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder; import org.elasticsearch.search.fetch.subphase.highlight.HighlightField; import org.elasticsearch.search.sort.SortOrder; import org.springframework.stereotype.Service; import xyz.klenkiven.kmall.common.to.elasticsearch.SkuESModel; import xyz.klenkiven.kmall.common.utils.R; import xyz.klenkiven.kmall.common.utils.Result; import xyz.klenkiven.kmall.search.ESConstant; import xyz.klenkiven.kmall.search.config.KmallElasticSearchConfig; import xyz.klenkiven.kmall.search.feign.ProductFeignService; import xyz.klenkiven.kmall.search.service.MallSearchService; import xyz.klenkiven.kmall.search.vo.AttrResponseVO; import xyz.klenkiven.kmall.search.vo.BrandVO; import xyz.klenkiven.kmall.search.vo.SearchParam; import xyz.klenkiven.kmall.search.vo.SearchResult; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Mall Search Service Impl * @author klenkiven */ @Service("mallSearchService") @RequiredArgsConstructor public class MallSearchServiceImpl implements MallSearchService { private final RestHighLevelClient esClient; private final ProductFeignService productFeignService; @Override public SearchResult search(SearchParam searchParam) { SearchResult result = null; // Construct search condition SearchRequest searchRequest = buildSearchRequest(searchParam); try { // Execute the search request SearchResponse search = esClient.search(searchRequest, KmallElasticSearchConfig.COMMON_OPTIONS); result = buildResult(search, searchParam); } catch (IOException e) { e.printStackTrace(); } return result; } /** * Build Search Request * 模糊匹配,过滤(按照分类,品牌,属性,库存,价格区间),排序,分页,高亮 * 聚合分析 * @param searchParam search Parameter * @return request */ private SearchRequest buildSearchRequest(SearchParam searchParam) { SearchRequest searchRequest = new SearchRequest(ESConstant.PRODUCT_INDEX); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); // ======================================模糊匹配 + 过滤========================================= BoolQueryBuilder boolQuery = new BoolQueryBuilder(); // 模糊匹配 if (!StringUtils.isEmpty(searchParam.getKeyword())) { boolQuery.must(new MatchQueryBuilder("skuTitle", searchParam.getKeyword())); } // 过滤(按照分类,品牌,属性,库存,价格区间) // 分类 if (searchParam.getCatalog3Id() != null) { boolQuery.filter(new TermQueryBuilder("catalogId", searchParam.getCatalog3Id())); } // 品牌 if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0) { boolQuery.filter(new TermsQueryBuilder("brandId", searchParam.getBrandId())); } // 属性 if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) { for (String attr : searchParam.getAttrs()) { BoolQueryBuilder nestBoolQuery = new BoolQueryBuilder(); // attrs = 2_5寸 String[] s = attr.split("_"); String attrId = ""; String[] attrValues = new String[]{}; if (s.length == 2) { attrId = s[0]; nestBoolQuery.must(new TermQueryBuilder("attrs.attrId", attrId)); attrValues = s[1].split(":"); nestBoolQuery.must(new TermsQueryBuilder("attrs.attrValue", attrValues)); } NestedQueryBuilder nestedQuery = new NestedQueryBuilder("attrs", nestBoolQuery, ScoreMode.None); boolQuery.filter(nestedQuery); } } // 库存 if (searchParam.getHasStock() != null) { boolQuery.filter(new TermQueryBuilder("hasStock", searchParam.getHasStock() == 1)); } // 价格区间 if (!StringUtils.isEmpty(searchParam.getSkuPrice())) { // 0_500/500_/_500 String[] priceRange = searchParam.getSkuPrice().split("_"); RangeQueryBuilder rangeQuery = new RangeQueryBuilder("skuPrice"); if (!StringUtils.isEmpty(priceRange[0])) { rangeQuery.gte(priceRange[0]); } if (!StringUtils.isEmpty(priceRange[1])) { rangeQuery.lte(priceRange[1]); } boolQuery.filter(rangeQuery); } searchSourceBuilder.query(boolQuery); // ======================================模糊匹配 + 过滤========================================= // ===========================================排序============================================== // saleCount_asc if (!StringUtils.isEmpty(searchParam.getSort())) { String[] sort = searchParam.getSort().split("_"); if (sort.length >= 2) { SortOrder order = sort[1].equalsIgnoreCase("asc")? SortOrder.ASC : SortOrder.DESC; searchSourceBuilder.sort(sort[0], order); } } // ===========================================排序============================================== // ===========================================page============================================== searchSourceBuilder.from((searchParam.getPageNum() - 1) * ESConstant.SEARCH_PAGE_SIZE); searchSourceBuilder.size(ESConstant.SEARCH_PAGE_SIZE); // ===========================================page============================================== // ===========================================高亮============================================== if (!StringUtils.isEmpty(searchParam.getKeyword())) { HighlightBuilder highlightBuilder = new HighlightBuilder(); highlightBuilder.field("skuTitle"); highlightBuilder.preTags(""); highlightBuilder.postTags(""); searchSourceBuilder.highlighter(highlightBuilder); } // ===========================================高亮============================================== // ==========================================聚合分析=========================================== // BrandAgg TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg"); brandAgg.field("brandId").size(50); TermsAggregationBuilder brandNameAgg = AggregationBuilders.terms("brand_name_agg"); brandNameAgg.field("brandName").size(1); TermsAggregationBuilder brandImgAgg = AggregationBuilders.terms("brand_img_agg"); brandImgAgg.field("brandImg").size(1); brandAgg.subAggregation(brandNameAgg); brandAgg.subAggregation(brandImgAgg); searchSourceBuilder.aggregation(brandAgg); // CatalogAgg TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg"); catalogAgg.field("catalogId").size(20); TermsAggregationBuilder catalogNameAgg = AggregationBuilders.terms("catalog_name_agg"); catalogNameAgg.field("catalogName").size(1); catalogAgg.subAggregation(catalogNameAgg); searchSourceBuilder.aggregation(catalogAgg); // AttrsAgg NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs"); TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg"); attrIdAgg.field("attrs.attrId"); TermsAggregationBuilder attrNameAgg = AggregationBuilders.terms("attr_name_agg"); attrNameAgg.field("attrs.attrName").size(1); TermsAggregationBuilder attrValueAgg = AggregationBuilders.terms("attr_value_agg"); attrValueAgg.field("attrs.attrValue").size(50); attrIdAgg.subAggregation(attrNameAgg); attrIdAgg.subAggregation(attrValueAgg); attrAgg.subAggregation(attrIdAgg); searchSourceBuilder.aggregation(attrAgg); // ==========================================聚合分析=========================================== searchRequest.source(searchSourceBuilder); System.out.println(searchRequest.source()); return searchRequest; } /** * Build Search Result * @param search search Response * @param param Request Param * @return result */ private SearchResult buildResult(SearchResponse search, SearchParam param) { ObjectMapper mapper = new ObjectMapper(); SearchResult searchResult = new SearchResult(); SearchHits hits = search.getHits(); // 1. Product Info List products = new ArrayList<>(); for (SearchHit hit : hits.getHits()) { SkuESModel skuESModel = new SkuESModel(); try { skuESModel = mapper.readValue(hit.getSourceAsString(), SkuESModel.class); // If has keyword, highlight it. if (!StringUtils.isEmpty(param.getKeyword())) { HighlightField skuTitle = hit.getHighlightFields().get("skuTitle"); String content = skuTitle.getFragments()[0].string(); skuESModel.setSkuTitle(content); } } catch (JsonProcessingException e) { e.printStackTrace(); } products.add(skuESModel); } searchResult.setProducts(products); // 2. Paging Info // 2.1 Total Hits Records long total = hits.getTotalHits().value; searchResult.setTotal(total); // 2.2 Total Page long totalPage = (total / ESConstant.SEARCH_PAGE_SIZE) + (total % ESConstant.SEARCH_PAGE_SIZE == 0 ? 0 : 1); searchResult.setTotalPages((int) totalPage); // 2.3 Current Page searchResult.setPageNum(param.getPageNum()); // 2.4 Navigation Pages List navPages = new ArrayList<>(); for (int i = 1; i <= totalPage; i++) { navPages.add(i); } searchResult.setPageNavs(navPages); Aggregations aggregations = search.getAggregations(); // 3. Brands Info List brands = new ArrayList<>(); ParsedLongTerms brandAgg = aggregations.get("brand_agg"); for (Terms.Bucket bucket : brandAgg.getBuckets()) { Long brandId = (Long) bucket.getKey(); ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg"); String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString(); ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg"); String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString(); var brand = new SearchResult.BrandVo(); brand.setBrandId(brandId); brand.setBrandImg(brandImg); brand.setBrandName(brandName); brands.add(brand); } searchResult.setBrands(brands); // Category Info List catalogs = new ArrayList<>(); ParsedLongTerms catalogAgg = aggregations.get("catalog_agg"); for (Terms.Bucket bucket : catalogAgg.getBuckets()) { Long catalogId = (Long) bucket.getKey(); ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg"); String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString(); var catalog = new SearchResult.CatalogVo(); catalog.setCatalogId(catalogId); catalog.setCatalogName(catalogName); catalogs.add(catalog); } searchResult.setCatalogs(catalogs); // Attrs Info List attrs = new ArrayList<>(); ParsedNested attrAgg = aggregations.get("attr_agg"); ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg"); for (Terms.Bucket bucket : attrIdAgg.getBuckets()) { Long attrId = (Long) bucket.getKey(); ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg"); String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString(); ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg"); List attrValue = attrValueAgg.getBuckets().stream() .map(MultiBucketsAggregation.Bucket::getKeyAsString) .collect(Collectors.toList()); SearchResult.AttrVo attr = new SearchResult.AttrVo(); attr.setAttrId(attrId); attr.setAttrName(attrName); attr.setAttrValue(attrValue); attrs.add(attr); } searchResult.setAttrs(attrs); // Bread Navigation if (param.getAttrs() != null && param.getAttrs().size() > 0) { List navs = param.getAttrs().stream().map((attr -> { SearchResult.NavVo nav = new SearchResult.NavVo(); String[] s = attr.split("_"); // attrs=1_白色:蓝色 nav.setNavValue(s[1]); if (!StringUtils.isEmpty(s[0])) { Long attrId = Long.parseLong(s[0]); R r = productFeignService.attrInfo(attrId); searchResult.getAttrIds().add(attrId); if (r.getCode() == 0) { AttrResponseVO responseVO = getData(r.get("attr"), new TypeReference() { }); nav.setNavName(responseVO.getAttrName()); } else { nav.setNavName(s[0]); } } String replace = replaceQueryString(param, attr, "attrs"); nav.setLink("http://search.kmall.com/list.html?" + replace); return nav; })).collect(Collectors.toList()); searchResult.setNavs(navs); } // 品牌、分类 if (param.getBrandId() != null && param.getBrandId().size() > 0) { List navs = searchResult.getNavs(); SearchResult.NavVo navVo = new SearchResult.NavVo(); navVo.setNavName("品牌"); // TODO 远程查询所有品牌 Result> r = productFeignService.brandsInfo(param.getBrandId()); if (r.getCode() == 0) { List brand = r.getData(); StringBuilder sb = new StringBuilder(); String replace = ""; for (BrandVO brandVo : brand) { sb.append(brandVo.getName()).append(";"); replace = replaceQueryString(param, brandVo.getBrandId()+"", "brandId"); } navVo.setNavValue(sb.toString()); navVo.setLink("http://search.kmall.com/list.html?" + replace); } navs.add(navVo); } return searchResult; } /** * Get Object By JSON */ private T getData(Object data, TypeReference typeReference) { JsonMapper jsonMapper = new JsonMapper(); ObjectMapper objectMapper = new ObjectMapper(); String json = ""; T result = null; try { json = jsonMapper.writeValueAsString(data); result = objectMapper.readValue(json, typeReference); } catch (JsonProcessingException e) { e.printStackTrace(); } return result; } /** * Replace Query String */ private String replaceQueryString(SearchParam param, String value, String key) { String encode = null; encode = URLEncoder.encode(value, StandardCharsets.UTF_8); encode = encode.replace("+", "%20"); //浏览器对空格的编码和Java不一样,差异化处理 // 就是点了X之后,应该跳转的地址 // 这里要判断一下,attrs是不是第一个参数,因为第一个参数 没有&符号 // TODO BUG,第一个参数不带& return param.get_queryString().replace("&"+ key + "=" + encode, ""); } } package org.benetech.servicenet.web.rest; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.UUID; import org.benetech.servicenet.MockedSmsConfiguration; import org.benetech.servicenet.MockedUserTestConfiguration; import org.benetech.servicenet.ServiceNetApp; import org.benetech.servicenet.ZeroCodeSpringJUnit5Extension; import org.benetech.servicenet.domain.Beneficiary; import org.benetech.servicenet.domain.Location; import org.benetech.servicenet.domain.Organization; import org.benetech.servicenet.domain.Referral; import org.benetech.servicenet.mother.OrganizationMother; import org.benetech.servicenet.repository.BeneficiaryRepository; import org.benetech.servicenet.repository.ReferralRepository; import org.benetech.servicenet.service.dto.BeneficiaryDTO; import org.benetech.servicenet.service.dto.CheckInDTO; import org.benetech.servicenet.service.mapper.BeneficiaryMapper; import org.benetech.servicenet.util.IdentifierUtils; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Integration tests for the {@link BeneficiaryResource} REST controller. */ @ExtendWith({ SpringExtension.class, ZeroCodeSpringJUnit5Extension.class }) @SpringBootTest(classes = {ServiceNetApp.class, MockedUserTestConfiguration.class, MockedSmsConfiguration.class}) @WithMockUser(username = "admin", roles = {"ADMIN"}) @AutoConfigureMockMvc public class BeneficiaryResourceIT { private static final String DEFAULT_PHONE_NUMBER = "AAAAAAAAAA"; private static final String UPDATED_PHONE_NUMBER = "BBBBBBBBBB"; @Autowired private BeneficiaryRepository beneficiaryRepository; @Autowired private ReferralRepository referralRepository; @Autowired private BeneficiaryMapper beneficiaryMapper; @Autowired private EntityManager em; @Autowired private MockMvc restBeneficiaryMockMvc; private Beneficiary beneficiary; UUID id = UUID.randomUUID(); /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Beneficiary createEntity(EntityManager em) { Beneficiary beneficiary = new Beneficiary() .phoneNumber(DEFAULT_PHONE_NUMBER); return beneficiary; } /** * Create an updated entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Beneficiary createUpdatedEntity(EntityManager em) { Beneficiary beneficiary = new Beneficiary() .phoneNumber(UPDATED_PHONE_NUMBER); return beneficiary; } @BeforeEach public void initTest() { beneficiary = createEntity(em); } @Test @Transactional public void createBeneficiary() throws Exception { int databaseSizeBeforeCreate = beneficiaryRepository.findAll().size(); // Create the Beneficiary BeneficiaryDTO beneficiaryDTO = beneficiaryMapper.toDto(beneficiary); restBeneficiaryMockMvc.perform(post("/api/beneficiaries").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(beneficiaryDTO))) .andExpect(status().isCreated()); // Validate the Beneficiary in the database List beneficiaryList = beneficiaryRepository.findAll(); assertThat(beneficiaryList).hasSize(databaseSizeBeforeCreate + 1); Beneficiary testBeneficiary = beneficiaryList.get(beneficiaryList.size() - 1); assertThat(testBeneficiary.getPhoneNumber()).isEqualTo(DEFAULT_PHONE_NUMBER); } @Test @Transactional public void createBeneficiaryWithExistingId() throws Exception { int databaseSizeBeforeCreate = beneficiaryRepository.findAll().size(); // Create the Beneficiary with an existing ID beneficiary.setId(id); BeneficiaryDTO beneficiaryDTO = beneficiaryMapper.toDto(beneficiary); // An entity with an existing ID cannot be created, so this API call must fail restBeneficiaryMockMvc.perform(post("/api/beneficiaries").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(beneficiaryDTO))) .andExpect(status().isBadRequest()); // Validate the Beneficiary in the database List beneficiaryList = beneficiaryRepository.findAll(); assertThat(beneficiaryList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void getAllBeneficiaries() throws Exception { // Initialize the database beneficiaryRepository.saveAndFlush(beneficiary); // Get all the beneficiaryList restBeneficiaryMockMvc.perform(get("/api/beneficiaries?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(beneficiary.getId().toString()))) .andExpect(jsonPath("$.[*].phoneNumber").value(hasItem(DEFAULT_PHONE_NUMBER))); } @Test @Transactional public void getBeneficiary() throws Exception { // Initialize the database beneficiaryRepository.saveAndFlush(beneficiary); // Get the beneficiary restBeneficiaryMockMvc.perform(get("/api/beneficiaries/{id}", beneficiary.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.id").value(beneficiary.getId().toString())) .andExpect(jsonPath("$.phoneNumber").value(DEFAULT_PHONE_NUMBER)); } @Test @Transactional public void getNonExistingBeneficiary() throws Exception { // Get the beneficiary restBeneficiaryMockMvc.perform(get("/api/beneficiaries/{id}", UUID.randomUUID())) .andExpect(status().isNotFound()); } @Test @Transactional public void updateBeneficiary() throws Exception { // Initialize the database beneficiaryRepository.saveAndFlush(beneficiary); int databaseSizeBeforeUpdate = beneficiaryRepository.findAll().size(); // Update the beneficiary Beneficiary updatedBeneficiary = beneficiaryRepository.findById(beneficiary.getId()).get(); // Disconnect from session so that the updates on updatedBeneficiary are not directly saved in db em.detach(updatedBeneficiary); updatedBeneficiary .phoneNumber(UPDATED_PHONE_NUMBER); BeneficiaryDTO beneficiaryDTO = beneficiaryMapper.toDto(updatedBeneficiary); restBeneficiaryMockMvc.perform(put("/api/beneficiaries").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(beneficiaryDTO))) .andExpect(status().isOk()); // Validate the Beneficiary in the database List beneficiaryList = beneficiaryRepository.findAll(); assertThat(beneficiaryList).hasSize(databaseSizeBeforeUpdate); Beneficiary testBeneficiary = beneficiaryList.get(beneficiaryList.size() - 1); assertThat(testBeneficiary.getPhoneNumber()).isEqualTo(UPDATED_PHONE_NUMBER); } @Test @Transactional public void updateNonExistingBeneficiary() throws Exception { int databaseSizeBeforeUpdate = beneficiaryRepository.findAll().size(); // Create the Beneficiary BeneficiaryDTO beneficiaryDTO = beneficiaryMapper.toDto(beneficiary); // If the entity doesn't have an ID, it will throw BadRequestAlertException restBeneficiaryMockMvc.perform(put("/api/beneficiaries").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(beneficiaryDTO))) .andExpect(status().isBadRequest()); // Validate the Beneficiary in the database List beneficiaryList = beneficiaryRepository.findAll(); assertThat(beneficiaryList).hasSize(databaseSizeBeforeUpdate); } @Test @Transactional public void deleteBeneficiary() throws Exception { // Initialize the database beneficiaryRepository.saveAndFlush(beneficiary); int databaseSizeBeforeDelete = beneficiaryRepository.findAll().size(); // Delete the beneficiary restBeneficiaryMockMvc.perform(delete("/api/beneficiaries/{id}", beneficiary.getId()).with(csrf()) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNoContent()); // Validate the database contains one less item List beneficiaryList = beneficiaryRepository.findAll(); assertThat(beneficiaryList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void checkIn() throws Exception { // Initialize the database beneficiaryRepository.saveAndFlush(beneficiary); Organization org = OrganizationMother.createDefaultWithAllRelationsAndPersist(em); Location loc = org.getLocations().stream().findFirst().get(); assertThat(referralRepository.findAll()).hasSize(0); // Check in the beneficiary CheckInDTO checkInDTO = new CheckInDTO(); checkInDTO.setPhoneNumber(beneficiary.getPhoneNumber()); checkInDTO.setCboId(org.getId()); checkInDTO.setLocationId(loc.getId()); restBeneficiaryMockMvc.perform(post("/api/beneficiaries/check-in").with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(checkInDTO))) .andExpect(status().isOk()); // Validate the Check in in the database List referrals = referralRepository.findAll(); assertThat(referrals).hasSize(1); Referral referral = referrals.get(0); assertThat(referral.getBeneficiary()).isEqualTo(beneficiary); assertThat(referral.getFrom()).isEqualTo(org); assertThat(referral.getFromLocation()).isEqualTo(loc); assertThat(referral.getTo()).isEqualTo(org); assertThat(referral.getToLocation()).isNull(); assertThat(referral.getSentAt()).isNotNull(); assertThat(referral.getFulfilledAt()).isNotNull(); assertThat(referral.getShortcode()).isNull(); } @Test @Transactional public void refer() throws Exception { // Initialize the database beneficiaryRepository.saveAndFlush(beneficiary); Organization org = OrganizationMother.createDefaultWithAllRelationsAndPersist(em); Organization anotherOrg = OrganizationMother.createForServiceProviderAndPersist(em); Organization yetAnotherOrg = OrganizationMother.createAnotherForServiceProviderAndPersist(em); Location loc = org.getLocations().stream().findFirst().get(); Location anotherLoc = anotherOrg.getLocations().stream().findFirst().get(); Location yetAnotherLoc = yetAnotherOrg.getLocations().stream().findFirst().get(); assertThat(referralRepository.findAll()).hasSize(0); // Refer the beneficiary Map organizationLocs = new HashMap<>(); String referringOrganizationId = org.getId().toString(); String referringLocationId = loc.getId().toString(); String beneficiaryId = IdentifierUtils.toBase36(beneficiary.getIdentifier()); organizationLocs.put(anotherOrg.getId(), anotherLoc.getId()); organizationLocs.put(yetAnotherOrg.getId(), yetAnotherLoc.getId()); restBeneficiaryMockMvc.perform(post("/api/beneficiaries/refer" + "?referringOrganizationId=" + referringOrganizationId + "&referringLocationId=" + referringLocationId + "&beneficiaryId=" + beneficiaryId ).with(csrf()) .contentType(MediaType.APPLICATION_JSON) .content(TestUtil.convertObjectToJsonBytes(organizationLocs))) .andExpect(status().isOk()); // Validate Referrals in the database List referrals = referralRepository.findAll(); assertThat(referrals).hasSize(2); Optional referralOptional = referrals.stream().filter(ref -> ref.getTo().equals(anotherOrg)).findFirst(); assertThat(referralOptional.isPresent()).isTrue(); Referral referral = referralOptional.get(); assertThat(referral.getBeneficiary()).isEqualTo(beneficiary); assertThat(referral.getFrom()).isEqualTo(org); assertThat(referral.getFromLocation()).isEqualTo(loc); assertThat(referral.getTo()).isEqualTo(anotherOrg); assertThat(referral.getToLocation()).isEqualTo(anotherLoc); assertThat(referral.getSentAt()).isNotNull(); assertThat(referral.getFulfilledAt()).isNull(); assertThat(referral.getShortcode()).isNull(); Optional anotherReferralOptional = referrals.stream().filter(ref -> ref.getTo().equals(yetAnotherOrg)).findFirst(); assertThat(anotherReferralOptional.isPresent()).isTrue(); Referral anotherReferral = anotherReferralOptional.get(); assertThat(anotherReferral.getBeneficiary()).isEqualTo(beneficiary); assertThat(anotherReferral.getFrom()).isEqualTo(org); assertThat(anotherReferral.getFromLocation()).isEqualTo(loc); assertThat(anotherReferral.getTo()).isEqualTo(yetAnotherOrg); assertThat(anotherReferral.getToLocation()).isEqualTo(yetAnotherLoc); assertThat(anotherReferral.getSentAt()).isNotNull(); assertThat(anotherReferral.getFulfilledAt()).isNull(); assertThat(anotherReferral.getShortcode()).isNull(); } } NDPH-ARTS/mts-services1-10 package uk.ac.ox.ndph.mts.practitioner_service.validation; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.converter.ConvertWith; import org.junit.jupiter.params.provider.CsvSource; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.HttpHeaders; import uk.ac.ox.ndph.mts.practitioner_service.NullableConverter; import uk.ac.ox.ndph.mts.practitioner_service.exception.RestException; import uk.ac.ox.ndph.mts.practitioner_service.model.RoleAssignment; import uk.ac.ox.ndph.mts.roleserviceclient.RoleServiceClient; import uk.ac.ox.ndph.mts.security.authentication.SecurityContextUtil; import uk.ac.ox.ndph.mts.siteserviceclient.SiteServiceClient; import java.util.function.Consumer; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class RoleAssignmentValidationTests { @Captor ArgumentCaptor roleIdCaptor; @Captor ArgumentCaptor siteIdCaptor; @Mock private RoleServiceClient roleServiceClient; @Mock private SiteServiceClient siteServiceClient; private RoleAssignmentValidation validator; @Mock private SecurityContextUtil securityContextUtil; @BeforeEach void setup() { this.validator = new RoleAssignmentValidation(roleServiceClient, siteServiceClient, securityContextUtil); } @ParameterizedTest @CsvSource({",,,practitionerId", ",siteId,roleId,practitionerId", "null,siteId,roleId,practitionerId", "practitionerId,,roleId,siteId", "practitionerId,null,roleId,siteId", "practitionerId,siteId,,roleId", "practitionerId,siteId,null,roleId", }) void TestRoleAssignmentValidation_WhenFieldsAreEmptyOrNull_ThrowsValidationException( @ConvertWith(NullableConverter.class) String practitionerId, @ConvertWith(NullableConverter.class) String siteId, @ConvertWith(NullableConverter.class) String roleId, String expectedField) { // Arrange RoleAssignment roleAssignment = new RoleAssignment(practitionerId, siteId, roleId); // Act + Assert var result = validator.validate(roleAssignment); assertThat(result.isValid(), is(false)); assertThat(result.getErrorMessage(), containsString(expectedField)); } @Test void TestRoleAssignmentValidation_WhenValidRole_ReturnsValidResponse() { // Arrange final var roleId = "testRoleId"; when(roleServiceClient.entityIdExists(anyString(), any(Consumer.class))).thenReturn(true); when(siteServiceClient.entityIdExists(anyString(), any(Consumer.class))).thenReturn(true); final var roleAssignment = new RoleAssignment("practitionerId", "siteId", roleId); // Act final var result = validator.validate(roleAssignment); // Assert assertThat(result.isValid(), is(true)); Mockito.verify(roleServiceClient).entityIdExists(roleIdCaptor.capture(), any(Consumer.class)); assertThat(roleId, equalTo(roleIdCaptor.getValue())); } @Test void TestRoleAssignmentValidation_WhenInvalidRole_ReturnsInvalidResponse() { // Arrange var roleId = "missingRoleId"; when(roleServiceClient.entityIdExists(eq(roleId), any(Consumer.class))).thenReturn(false); final RoleAssignment roleAssignment = new RoleAssignment("practitionerId", "siteId", roleId); // Act var result = validator.validate(roleAssignment); // Assert assertThat(result.isValid(), is(false)); assertThat(result.getErrorMessage(), containsString("roleId")); Mockito.verify(roleServiceClient).entityIdExists(roleIdCaptor.capture(), any(Consumer.class)); var value = roleIdCaptor.getValue(); assertThat(roleId, equalTo(value)); } @Test void TestRoleAssignmentValidation_WhenServiceFails_ThrowsException() { // Arrange var roleId = "testRoleId"; when(roleServiceClient.entityIdExists(eq(roleId), any(Consumer.class))).thenThrow(new RestException("mock")); final RoleAssignment roleAssignment = new RoleAssignment("practitionerId", "siteId", roleId); // Act // Assert assertThrows(RestException.class, () -> validator.validate(roleAssignment)); Mockito.verify(roleServiceClient).entityIdExists(roleIdCaptor.capture(), any(Consumer.class)); assertThat(roleId, equalTo(roleIdCaptor.getValue())); } @Test void TestRoleAssignmentValidation_WhenValidSite_ReturnsValidResponse() { // Arrange final var siteId = "testSiteId"; when(roleServiceClient.entityIdExists(anyString(), any(Consumer.class))).thenReturn(true); when(siteServiceClient.entityIdExists(anyString(), any(Consumer.class))).thenReturn(true); final var roleAssignment = new RoleAssignment("practitionerId", siteId, "roleId"); // Act final var result = validator.validate(roleAssignment); // Assert assertThat(result.isValid(), is(true)); Mockito.verify(siteServiceClient).entityIdExists(siteIdCaptor.capture(), any(Consumer.class)); var value = siteIdCaptor.getValue(); assertThat(siteId, equalTo(value)); } @Test void TestRoleAssignmentValidation_WhenInvalidSite_ReturnsInvalidResponse() { // Arrange final var siteId = "missingSiteId"; when(roleServiceClient.entityIdExists(anyString(), any(Consumer.class))).thenReturn(true); when(siteServiceClient.entityIdExists(anyString(), any(Consumer.class))).thenReturn(false); final var roleAssignment = new RoleAssignment("practitionerId", siteId, "roleId"); // Act var result = validator.validate(roleAssignment); // Assert assertThat(result.isValid(), is(false)); assertThat(result.getErrorMessage(), containsString("siteId")); Mockito.verify(siteServiceClient).entityIdExists(siteIdCaptor.capture(), any(Consumer.class)); var value = siteIdCaptor.getValue(); assertThat(siteId, equalTo(value)); } @Test void TestRoleAssignmentValidation_WhenSiteServiceFails_ThrowsException() { // Arrange final var siteId = "testSiteId"; when(roleServiceClient.entityIdExists(anyString(), any(Consumer.class))).thenReturn(true); when(siteServiceClient.entityIdExists(anyString(), any(Consumer.class))).thenThrow(new RestException("mock")); final RoleAssignment roleAssignment = new RoleAssignment("practitionerId", siteId, "roleId"); // Act // Assert assertThrows(RestException.class, () -> validator.validate(roleAssignment)); Mockito.verify(siteServiceClient).entityIdExists(siteIdCaptor.capture(), any(Consumer.class)); } } package com.bplow.netconn.aom.dao.impl; import java.sql.SQLException; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.bplow.netconn.aom.dao.TbWebServerDAO; import com.bplow.netconn.aom.dao.entity.TbWebServer; import com.bplow.netconn.aom.dao.entity.TbWebServerExample; import com.bplow.netconn.base.dao.BaseIbatisDaoSupport; import com.bplow.netconn.base.dao.pagination.IPagination; import com.ibatis.sqlmap.client.SqlMapClient; @Service("tbWebServerDAOImpl") public class TbWebServerDAOImpl extends BaseIbatisDaoSupport implements TbWebServerDAO { public TbWebServerDAOImpl() { super(); } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ public TbWebServerDAOImpl(SqlMapClient sqlMapClient) { super(); this.sqlMapClient = sqlMapClient; } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ public int countByExample(TbWebServerExample example) throws SQLException { Integer count = (Integer) sqlMapClient.queryForObject( "tb_web_server.countByExample", example); return count; } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ public int deleteByExample(TbWebServerExample example) throws SQLException { int rows = sqlMapClient .delete("tb_web_server.deleteByExample", example); return rows; } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ public int deleteByPrimaryKey(String id) throws SQLException { TbWebServer _key = new TbWebServer(); _key.setId(id); int rows = sqlMapClient .delete("tb_web_server.deleteByPrimaryKey", _key); return rows; } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ public void insert(TbWebServer record) throws SQLException { sqlMapClient.insert("tb_web_server.insert", record); } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ public void insertSelective(TbWebServer record) throws SQLException { sqlMapClient.insert("tb_web_server.insertSelective", record); } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ @SuppressWarnings("unchecked") public List selectByExample(TbWebServerExample example) throws SQLException { List list = sqlMapClient.queryForList( "tb_web_server.selectByExample", example); return list; } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ public TbWebServer selectByPrimaryKey(String id) throws SQLException { TbWebServer _key = new TbWebServer(); _key.setId(id); TbWebServer record = (TbWebServer) sqlMapClient.queryForObject( "tb_web_server.selectByPrimaryKey", _key); return record; } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ public int updateByExampleSelective(TbWebServer record, TbWebServerExample example) throws SQLException { UpdateByExampleParms parms = new UpdateByExampleParms(record, example); int rows = sqlMapClient.update( "tb_web_server.updateByExampleSelective", parms); return rows; } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ public int updateByExample(TbWebServer record, TbWebServerExample example) throws SQLException { UpdateByExampleParms parms = new UpdateByExampleParms(record, example); int rows = sqlMapClient.update("tb_web_server.updateByExample", parms); return rows; } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ public int updateByPrimaryKeySelective(TbWebServer record) throws SQLException { int rows = sqlMapClient.update( "tb_web_server.updateByPrimaryKeySelective", record); return rows; } /** * This method was generated by MyBatis Generator. This method corresponds * to the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ public int updateByPrimaryKey(TbWebServer record) throws SQLException { int rows = sqlMapClient.update("tb_web_server.updateByPrimaryKey", record); return rows; } /** * This class was generated by MyBatis Generator. This class corresponds to * the database table tb_web_server * * @mbggenerated Sat Apr 23 12:36:53 CST 2016 */ protected static class UpdateByExampleParms extends TbWebServerExample { private Object record; public UpdateByExampleParms(Object record, TbWebServerExample example) { super(example); this.record = record; } public Object getRecord() { return record; } } /* * (non-Javadoc) * * @see * com.bplow.netconn.aom.dao.TbWebServerDAO#queryWebServerForpage(com.bplow * .netconn.aom.dao.entity.TbWebServer) */ @Override public IPagination queryWebServerForpage(TbWebServer record) throws SQLException { IPagination page = this.queryForPagenation( "tb_web_server.countForPage", "tb_web_server.selectForPage", record,record.getPageNum(),record.getMaxRowNums()); return page; } }package com.mercury.app.activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.Fragment; import android.telephony.PhoneStateListener; import android.telephony.SmsManager; import android.telephony.TelephonyManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import com.mercury.app.R; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import cz.msebera.android.httpclient.Header; import org.json.JSONException; import org.json.JSONObject; public class HelpLocationFragment extends Fragment { ImageView btnGPSShowLocation; String result; String link; Button bookOla; private PopupWindow pw; private View popupView; private LayoutInflater popupLay; private PopupWindow intervalWin; private View intervalView; private LayoutInflater intervalLay; //public static final String apiURL = "http://sandbox-t.olacabs.com/v1/bookings/create?pickup_lat=12.950072&pickup_lng=77.642 684&pickup_mode=NOW&category=sedan"; ConnectCustomerToFlow connectCustomer; /*//JSON node names private static final String TAG_NAME = "driver_name"; private static final String TAG_MOBILE = "driver_number"; // contacts JSONArray JSONArray contacts = null;*/ // Hashmap for ListView //ArrayList> contactList; //TextView firstContactNumber; AppLocationService appLocationService; //AddContactsFragment addContactsFragment; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.activity_info,container,false); appLocationService = new AppLocationService(getActivity()); /*firstContactNumber = (TextView)v.findViewById(R.id.frstCntct); String myTag = getTag(); ((SliderActivity)getActivity()).setLocFragB(myTag); addContactsFragment = new AddContactsFragment();*/ bookOla = (Button)v.findViewById(R.id.olaCab); bookOla.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getActivity(),"You are safe with Thea Assist!", Toast.LENGTH_SHORT).show(); } }); btnGPSShowLocation = (ImageView)v.findViewById(R.id.sosBtn1); btnGPSShowLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Location gpsLocation = appLocationService.getLocation(LocationManager.GPS_PROVIDER); if (gpsLocation != null) { double latitude = gpsLocation.getLatitude(); double longitude = gpsLocation.getLongitude(); result = "Lat:" + latitude + " Longi:" + longitude; link = "http://maps.google.com/maps?q=loc:" + String.format("%f,%f", latitude, longitude); Log.d("Location:", result); Log.d("MapsLink:", link); sendMessage(); Toast.makeText(getActivity(), "Help on the way!", Toast.LENGTH_SHORT).show(); } else { showSettingsAlert(); } } }); return v; } /*@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); contactList = new ArrayList>(); ListView lv = (ListView)getActivity().findViewById(R.id.driverList); }*/ /*public void updateText(String t){ firstContactNumber.setText(t); }*/ private void sendMessage() { //Send help message StringBuilder sosMsg = new StringBuilder(); sosMsg.append("I'm in danger.Please help..\n"); //TO DO: send this result to google maps sosMsg.append(link); //Log.d("FirstContact", addContactsFragment.fContact); //change this to the numbers the user specified emergency contacts String[] numbers = new String[]{"+919591200619"}; for(int i = 0; i < numbers.length; i++){ SmsManager sosHelpMsg = SmsManager.getDefault(); //TO DO: Set the phone number to list of numbers based on nearest located people available sosHelpMsg.sendTextMessage(numbers[i], null, sosMsg.toString(), null, null); } // add PhoneStateListener for monitoring MyPhoneListener phoneListener = new MyPhoneListener(); //call try{ TelephonyManager telephonyManager = (TelephonyManager) appLocationService.getSystemService(Context.TELEPHONY_SERVICE); // receive notifications of telephony state changes telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE); String helpline = "+918030853000"; //change this to the user selected contact Intent callIntent= new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + helpline)); startActivity(callIntent); }catch (Exception e){ Toast.makeText(getActivity(), "Call Failed", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } private class MyPhoneListener extends PhoneStateListener { private boolean onCall = false; @Override public void onCallStateChanged(int state, String incomingNumber){ switch (state){ case TelephonyManager.CALL_STATE_RINGING: //phone ringing Toast.makeText(getActivity(), incomingNumber + " calls you", Toast.LENGTH_LONG).show(); break; case TelephonyManager.CALL_STATE_OFFHOOK: // one call exists that is dialing, active, or on hold Toast.makeText(getActivity(), "on call...", Toast.LENGTH_LONG).show(); //because user answers the incoming call onCall = true; break; case TelephonyManager.CALL_STATE_IDLE: // in initialization of the class and at the end of phone call // detect flag from CALL_STATE_OFFHOOK if (onCall == true) { Toast.makeText(getActivity(), "restart app after call", Toast.LENGTH_LONG).show(); // restart our application Intent restart = getActivity().getPackageManager(). getLaunchIntentForPackage(getActivity().getPackageName()); restart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(restart); onCall = false; } break; default: break; } } } public void showSettingsAlert(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity()); alertDialog.setTitle("Settings"); alertDialog.setMessage("Enable Location provider.Go to Settings menu?"); alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); getActivity().startActivity(intent); } }); alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.cancel(); } }); alertDialog.show(); } /*public void CallToOla(){ //Make restful webservice call AsyncHttpClient client = new AsyncHttpClient(); client.get(apiURL, null, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try{ //TO-DO OLA booking final String jsonStr = "{\n" + " \"crn\": \"1630\",\n" + " \"driver_name\": \"Phonenix D253\",\n" + " \"driver_number\": \"4567894253\",\n" + " \"cab_type\": \"sedan\",\n" + " \"cab_number\": \"KA 25 3\",\n" + " \"car_model\": \"Toyota Corolla\",\n" + " \"eta\": 2,\n" + " \"driver_lat\": 12.950074,\n" + " \"driver_lng\": 77.641727\n" + "}"; JSONObject jsonResponse = new JSONObject(jsonStr); int crn = Integer.parseInt(jsonResponse.optString("crn").toString()); String driverName = jsonResponse.optString("driver_name").toString(); String driverNumber = jsonResponse.optString("driver_number").toString(); Log.d("DriverName", driverName); Log.d("DriverNumber", driverNumber); StringBuilder cabMsg = new StringBuilder(); cabMsg.append("Say Ola to your driver" + driverName + "\ncontact number" + driverNumber); SmsManager olaMsg = SmsManager.getDefault(); olaMsg.sendTextMessage("+919591200619", null, cabMsg.toString(),null, null ); //sms user that cab is booked //JSON Object JSONObject obj = new JSONObject(response); // When the JSON response has status boolean value assigned with true if(obj.getBoolean("status")){ Toast.makeText(getActivity(), "Successfull", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getActivity(),"Failure", Toast.LENGTH_SHORT).show(); } }catch(JSONException e){ Toast.makeText(getActivity(), "Error occured", Toast.LENGTH_SHORT).show(); e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { // When Http response code is '404' if(statusCode == 404){ Toast.makeText(getActivity(), "Requested resource not found", Toast.LENGTH_LONG).show(); } // When Http response code is '500' else if(statusCode == 500){ Toast.makeText(getActivity(), "Something went wrong at server end", Toast.LENGTH_LONG).show(); } // When Http response code other than 404, 500 else{ Toast.makeText(getActivity(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show(); } } }); } */ /* private class GetDrivers extends AsyncTask{ @Override protected Void doInBackground(Void... voids) { // Creating service handler class instance ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(apiURL, ServiceHandler.GET); Log.d("Response: ", "> " + jsonStr); if(jsonStr != null){ try{ JSONObject jsonObj = new JSONObject(jsonStr); // looping through All Contacts String name = jsonObj.getString(TAG_NAME); String mobile = jsonObj.getString(TAG_MOBILE); // tmp hashmap for single contact HashMap contact = new HashMap(); // adding each child node to HashMap key => value contact.put(TAG_NAME, name); contact.put(TAG_MOBILE, mobile) // adding contact to contact list contactList.add(contact); }catch (JSONException e){ e.printStackTrace(); } }else{ Log.e("ServiceHandler", "Couldn't get any data from the url"); } return null; } @Override protected void onPostExecute(Void result){ ListAdapter adapter = new SimpleAdapter( getActivity(), contactList, R.layout.activity_info, new String[] { TAG_NAME, TAG_MOBILE }, new int[] { R.id.name, R.id.mobile }); lv.setListAdapter(adapter); } } */ } deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/conf/constraint/MaxNormConstraint.java /* * ****************************************************************************** * * Copyright (c) 2021 Deeplearning4j Contributors * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.deeplearning4j.nn.conf.constraint; import lombok.Data; import lombok.EqualsAndHashCode; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Broadcast; import org.nd4j.linalg.indexing.BooleanIndexing; import org.nd4j.linalg.indexing.conditions.Conditions; import java.util.Collections; import java.util.Set; /** * Constrain the maximum L2 norm of the incoming weights for each unit to be less than or equal to the specified value. * If the L2 norm exceeds the specified value, the weights will be scaled down to satisfy the constraint. * * @author */ @Data @EqualsAndHashCode(callSuper = true) public class MaxNormConstraint extends BaseConstraint { private double maxNorm; private MaxNormConstraint(){ //No arg for json ser/de } /** * @param maxNorm Maximum L2 value * @param paramNames Which parameter names to apply constraint to * @param dimensions Dimensions to apply to. For DenseLayer, OutputLayer, RnnOutputLayer, LSTM, etc: this should * be dimension 1. For CNNs, this should be dimensions [1,2,3] corresponding to last 3 of * parameters which have order [depthOut, depthIn, kH, kW] */ public MaxNormConstraint(double maxNorm, Set paramNames, int... dimensions){ super(paramNames, DEFAULT_EPSILON, dimensions); this.maxNorm = maxNorm; } /** * Apply to weights but not biases by default * * @param maxNorm Maximum L2 value * @param dimensions Dimensions to apply to. For DenseLayer, OutputLayer, RnnOutputLayer, LSTM, etc: this should * be dimension 1. For CNNs, this should be dimensions [1,2,3] corresponding to last 3 of * parameters which have order [depthOut, depthIn, kH, kW] */ public MaxNormConstraint(double maxNorm, int... dimensions) { this(maxNorm, Collections.emptySet(), dimensions); } @Override public void apply(INDArray param){ INDArray norm = param.norm2(dimensions); INDArray clipped = norm.unsafeDuplication(); BooleanIndexing.replaceWhere(clipped, maxNorm, Conditions.greaterThan(maxNorm)); norm.addi(epsilon); clipped.divi(norm); Broadcast.mul(param, clipped, param, getBroadcastDims(dimensions, param.rank()) ); } @Override public MaxNormConstraint clone() { return new MaxNormConstraint(maxNorm, params, dimensions); } } Creational/factory_method/src/main/java/com/pmareke/factory/MarketingManager.java package com.pmareke.factory; import com.pmareke.interfaces.IInterviewer; import com.pmareke.models.CommunityExecutive; public class MarketingManager extends HiringManager { @Override protected IInterviewer MakeInterviewer() { return new CommunityExecutive(); } } /* * Copyright 2020 Valtech GmbH * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, publish, distribute, * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package de.valtech.avs.core.history; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import org.apache.commons.lang3.StringUtils; import org.apache.jackrabbit.JcrConstants; import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants; import org.apache.sling.api.resource.ModifiableValueMap; import org.apache.sling.api.resource.PersistenceException; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceUtil; import org.apache.sling.api.resource.ResourceUtil.BatchResourceRemover; import org.apache.sling.api.resource.ValueMap; import org.apache.sling.jcr.resource.api.JcrResourceConstants; import org.osgi.service.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import de.valtech.avs.api.history.HistoryEntry; import de.valtech.avs.api.service.AvsException; import de.valtech.avs.api.service.scanner.ScanResult; /** * Reads and writes history entries. * * @author */ @Component(service = HistoryService.class) public class HistoryService { private static final Logger LOG = LoggerFactory.getLogger(HistoryService.class); /** * Base node for history entries */ public static final String HISTORY_BASE = "/var/avs/history"; protected static final String ATTR_TIME = "time"; protected static final String ATTR_CLEAN = "clean"; protected static final String ATTR_OUTPUT = "output"; protected static final String ATTR_PATH = "path"; protected static final String ATTR_USER_ID = "userId"; private static final String NAME_INDEX = "oak:index"; private Random random = new Random(); /** * Creates a new history entry. * * @param resolver resource resolver * @param result scan result * @throws AvsException error setting up entry */ public void createHistoryEntry(ResourceResolver resolver, ScanResult result) throws AvsException { Calendar now = new GregorianCalendar(); String basePath = HISTORY_BASE + "/" + now.get(Calendar.YEAR) + "/" + (now.get(Calendar.MONTH) + 1) + "/" + now.get(Calendar.DAY_OF_MONTH); String nodeName = generateHistoryNodeName(); String nodePath = basePath + "/" + nodeName; createPath(basePath, resolver, JcrResourceConstants.NT_SLING_ORDERED_FOLDER); createPath(nodePath, resolver, JcrConstants.NT_UNSTRUCTURED); Resource resource = resolver.getResource(nodePath); ModifiableValueMap values = resource.adaptTo(ModifiableValueMap.class); values.put(ATTR_TIME, now); values.put(ATTR_OUTPUT, result.getOutput()); values.put(ATTR_CLEAN, result.isClean()); values.put(ATTR_PATH, result.getPath()); values.put(ATTR_USER_ID, result.getUserId()); try { resolver.commit(); } catch (PersistenceException e) { throw new AvsException("Unable to story history entry", e); } } /** * Returns the last history entries. The search starts at the newest entry. * * @param startIndex start reading at this index (first is 0) * @param count number of entries to read * @param resolver resource resolver * @return history entries (newest first) */ public List getHistory(int startIndex, int count, ResourceResolver resolver) { List entries = new ArrayList<>(); if (count == 0) { return entries; } Resource base = resolver.getResource(HISTORY_BASE); Resource current = getLatestHistoryEntry(base); if (current == null) { return entries; } // skip up to start index for (int i = 0; i < startIndex; i++) { current = getPreviousHistoryEntry(current); } for (int i = 0; i < count; i++) { if (current == null) { break; } entries.add(readHistoryEntry(current)); current = getPreviousHistoryEntry(current); } return entries; } /** * Returns the run before the given one. * * @param current current run * @return previous run */ private Resource getPreviousHistoryEntry(Resource current) { // check if the parent has a sibling before the current node Resource previous = getPreviousSibling(current); if (previous != null) { return previous; } // go down till we find an earlier sibling Resource base = descendToPreviousSiblingInHistory(current.getParent()); // go back up the folders return ascendToLastRun(base); } /** * Gos up the folders to last run. * * @param resource current node * @return last run */ private Resource ascendToLastRun(Resource resource) { if (resource == null) { return null; } Resource last = getLastChild(resource); if (last == null) { // stop if there is no child at all return null; } ValueMap values = last.adaptTo(ValueMap.class); if (JcrResourceConstants.NT_SLING_ORDERED_FOLDER.equals(values.get(JcrConstants.JCR_PRIMARYTYPE, String.class))) { return ascendToLastRun(last); } return last; } /** * Descends in history till a previous sibling is found. Descending stops at history base level * * @param current current resource * @return previous sibling */ private Resource descendToPreviousSiblingInHistory(Resource current) { if ((current == null) || HISTORY_BASE.equals(current.getPath())) { return null; } Resource previous = getPreviousSibling(current); if (previous != null) { return previous; } previous = descendToPreviousSiblingInHistory(current.getParent()); return previous; } /** * Returns the previous sibling of the given node. * * @param resource current node * @return last sibling or null */ private Resource getPreviousSibling(Resource resource) { Iterator siblings = resource.getParent().listChildren(); Resource previous = null; while (siblings.hasNext()) { Resource sibling = siblings.next(); if (sibling.getName().equals(resource.getName())) { break; } if (!sibling.getName().equals(AccessControlConstants.REP_POLICY) && !sibling.getName().equals(NAME_INDEX)) { previous = sibling; } } return previous; } /** * Returns the latest history entry. * * @param base base resource * @return latest run resource */ private Resource getLatestHistoryEntry(Resource base) { if (base == null) { return null; } return ascendToLastRun(base); } /** * Returns the last child of the given resource. * * @param resource resource * @return last child */ private Resource getLastChild(Resource resource) { if (resource == null) { return null; } Resource last = null; Iterator lastIterator = resource.listChildren(); while (lastIterator.hasNext()) { Resource candidate = lastIterator.next(); if (!AccessControlConstants.REP_POLICY.equals(candidate.getName()) && !NAME_INDEX.equals(candidate.getName())) { last = candidate; } } return last; } /** * Reads a history entry from JCR. * * @param resource history resource * @return history entry */ private HistoryEntry readHistoryEntry(Resource resource) { ValueMap values = resource.adaptTo(ValueMap.class); boolean clean = values.get(ATTR_CLEAN, false); String output = values.get(ATTR_OUTPUT, ""); String path = values.get(ATTR_PATH, ""); String userId = values.get(ATTR_USER_ID, ""); Calendar date = values.get(ATTR_TIME, Calendar.class); return new HistoryEntryImpl(date.getTime(), output, clean, path, resource.getPath(), userId); } /** * Creates the folder at the given path if not yet existing. * * @param path path * @param resolver resource resolver * @param primaryType primary type * @throws AvsException error creating folder */ protected void createPath(String path, ResourceResolver resolver, String primaryType) throws AvsException { Resource folder = resolver.getResource(path); if (folder == null) { String parent = path.substring(0, path.lastIndexOf('/')); String name = path.substring(path.lastIndexOf('/') + 1); if (resolver.getResource(parent) == null) { createPath(parent, resolver, primaryType); } Map properties = new HashMap<>(); properties.put(JcrConstants.JCR_PRIMARYTYPE, primaryType); try { resolver.create(resolver.getResource(parent), name, properties); } catch (PersistenceException e) { throw new AvsException("Unable to create " + path, e); } } } /** * Generates the node name for a history entry. * * @return name */ private String generateHistoryNodeName() { return System.currentTimeMillis() + "" + random.nextInt(100000); } /** * Purges the history by keeping only entries within the set number of days. * * @param resolver resource resolver * @param daysToKeep number of days to keep * @throws PersistenceException error deleting node */ public void purgeHistory(ResourceResolver resolver, int daysToKeep) throws PersistenceException { Resource base = resolver.getResource(HISTORY_BASE); Calendar calendar = new GregorianCalendar(); calendar.add(Calendar.DAY_OF_MONTH, -daysToKeep); LOG.debug("Starting purge with limit {}", calendar.getTime()); deleteRecursive(base.listChildren(), calendar, new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH}); } /** * Deletes the year resources that are too old. * * @param resources resources * @param calendar time limit * @param fields calendar fields * @throws PersistenceException error deleting node */ private void deleteRecursive(Iterator resources, Calendar calendar, int[] fields) throws PersistenceException { int currentField = fields[0]; while (resources.hasNext()) { Resource resource = resources.next(); String name = resource.getName(); // skip extra nodes such as ACLs if (!StringUtils.isNumeric(name)) { LOG.debug("Skipping purge of other node: {}", resource.getPath()); continue; } int nodeValue = Integer.parseInt(name); int limit = calendar.get(currentField); if (currentField == Calendar.MONTH) { // months start with 0 but are stored beginning with 1 in CRX limit++; } if (nodeValue > limit) { LOG.debug("Skipping purge of too young node: {}", resource.getPath()); } else if (nodeValue == limit) { LOG.debug("Skipping purge of too young node: {}", resource.getPath()); // check next level if (fields.length == 1) { return; } int[] fieldsNew = new int[fields.length - 1]; System.arraycopy(fields, 1, fieldsNew, 0, fieldsNew.length); deleteRecursive(resource.listChildren(), calendar, fieldsNew); } else { LOG.debug("Purging node: {}", resource.getPath()); BatchResourceRemover remover = ResourceUtil.getBatchResourceRemover(1000); remover.delete(resource); } } } /** * Self test of history. Checks if the history node exists. * * @param resolver resource resolver * @throws AvsException check failed */ public void selfCheck(ResourceResolver resolver) throws AvsException { Resource base = resolver.getResource(HISTORY_BASE); if (base == null) { throw new AvsException(HISTORY_BASE + " does not exist or is not accessible."); } } } josher93/Android_MVP package io.jpotts18.android_mvp.domain.repos; /** * Created by jpotts18 on 5/11/15. */ public interface IRepoListPresenter { public void loadCommits(String username); } 1-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.qpid.jms.integration; import static org.apache.qpid.jms.provider.amqp.AmqpSupport.ANONYMOUS_RELAY; import static org.hamcrest.Matchers.arrayContaining; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.fail; import javax.jms.Connection; import javax.jms.Destination; import javax.jms.Message; import javax.jms.MessageProducer; import javax.jms.Queue; import javax.jms.Session; import javax.jms.TemporaryQueue; import javax.jms.TemporaryTopic; import javax.jms.Topic; import org.apache.qpid.jms.test.QpidJmsTestCase; import org.apache.qpid.jms.test.testpeer.ListDescribedType; import org.apache.qpid.jms.test.testpeer.TestAmqpPeer; import org.apache.qpid.jms.test.testpeer.describedtypes.Accepted; import org.apache.qpid.jms.test.testpeer.describedtypes.TransactionalState; import org.apache.qpid.jms.test.testpeer.matchers.CoordinatorMatcher; import org.apache.qpid.jms.test.testpeer.matchers.TransactionalStateMatcher; import org.apache.qpid.jms.test.testpeer.matchers.sections.MessageAnnotationsSectionMatcher; import org.apache.qpid.jms.test.testpeer.matchers.sections.MessageHeaderSectionMatcher; import org.apache.qpid.jms.test.testpeer.matchers.sections.TransferPayloadCompositeMatcher; import org.apache.qpid.proton.amqp.Binary; import org.apache.qpid.proton.amqp.Symbol; import org.apache.qpid.proton.amqp.transaction.TxnCapability; import org.hamcrest.Matcher; import org.junit.Test; /** * Test MessageProducers created using various configuration of the presettle options */ public class PresettledProducerIntegrationTest extends QpidJmsTestCase { private final IntegrationTestFixture testFixture = new IntegrationTestFixture(); private final Symbol[] serverCapabilities = new Symbol[] { ANONYMOUS_RELAY }; //----- Test the jms.presettleAll option ---------------------------------// @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleAllSendToTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleAll=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, Topic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleAllSendToQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleAll=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, Queue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleAllSendToTempTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleAll=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, TemporaryTopic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleAllSendToTempQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleAll=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, TemporaryQueue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleAllAnonymousSendToTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleAll=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, true, true, Topic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleAllAnonymousSendToQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleAll=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, true, true, Queue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleAllAnonymousSendToTempTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleAll=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, true, true, TemporaryTopic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleAllAnonymousSendToTempQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleAll=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, true, true, TemporaryQueue.class); } //----- Test the jms.presettleProducers option ---------------------------------// @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleProducersTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, Topic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleProducersQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, Queue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleProducersTempTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, TemporaryTopic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleProducersTempQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, TemporaryQueue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleProducersAnonymousTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, true, true, Topic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleProducersAnonymousQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, true, true, Queue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleProducersAnonymousTempTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, true, true, TemporaryTopic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleProducersAnonymousTempQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, true, true, TemporaryQueue.class); } //----- Test the jms.presettleTopicProducers option ---------------------------------// @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTopicProducersTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTopicProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, Topic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTopicProducersQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTopicProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, false, false, Queue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTopicProducersTempTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTopicProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, TemporaryTopic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTopicProducersTempQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTopicProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, false, false, TemporaryQueue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTopicProducersAnonymousTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTopicProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, false, true, Topic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTopicProducersAnonymousQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTopicProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, false, false, Queue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTopicProducersAnonymousTempTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTopicProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, false, true, TemporaryTopic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTopicProducersAnonymousTempQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTopicProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, false, false, TemporaryQueue.class); } //----- Test the jms.presettleQueueProducers option ---------------------------------// @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleQueueProducersTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleQueueProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, false, false, Topic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleQueueProducersQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleQueueProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, Queue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleQueueProducersTempTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleQueueProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, false, false, TemporaryTopic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleQueueProducersTempQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleQueueProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, true, true, TemporaryQueue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleQueueProducersAnonymousTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleQueueProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, false, false, Topic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleQueueProducersAnonymousQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleQueueProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, false, true, Queue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleQueueProducersAnonymousTempTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleQueueProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, false, false, TemporaryTopic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleQueueProducersAnonymousTempQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleQueueProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, true, false, true, TemporaryQueue.class); } //----- Test the jms.presettleTransactedProducers option ---------------------------------// @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTransactedProducersTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTransactedProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, true, false, true, true, Topic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTransactedProducersQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTransactedProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, true, false, true, true, Queue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTransactedProducersTempTopic() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTransactedProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, true, false, true, true, TemporaryTopic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTransactedProducersTempQueue() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTransactedProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, true, false, true, true, TemporaryQueue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTransactedProducersTopicNoTX() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTransactedProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, false, false, Topic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTransactedProducersQueueNoTX() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTransactedProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, false, false, Queue.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTransactedProducersTempTopicNoTX() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTransactedProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, false, false, TemporaryTopic.class); } @Test(timeout = 20000) public void testJmsPresettlePolicyPresettleTransactedProducersTempQueueNoTX() throws Exception { String presettleConfig = "?jms.presettlePolicy.presettleTransactedProducers=true"; doTestProducerWithPresettleOptions(presettleConfig, false, false, false, false, TemporaryQueue.class); } //----- Test Method implementation ---------------------------------------// private void doTestProducerWithPresettleOptions(String uriOptions, boolean transacted, boolean anonymous, boolean senderSettled, boolean transferSettled, Class destType) throws Exception { doTestProducerWithPresettleOptions(uriOptions, transacted, anonymous, true, senderSettled, transferSettled, destType); } private void doTestProducerWithPresettleOptions(String uriOptions, boolean transacted, boolean anonymous, boolean relaySupported, boolean senderSettled, boolean transferSettled, Class destType) throws Exception { try (TestAmqpPeer testPeer = new TestAmqpPeer();) { Connection connection = testFixture.establishConnecton(testPeer, uriOptions, relaySupported ? serverCapabilities : null, null); testPeer.expectBegin(); Session session = null; Binary txnId = null; if (transacted) { // Expect the session, with an immediate link to the transaction coordinator // using a target with the expected capabilities only. CoordinatorMatcher txCoordinatorMatcher = new CoordinatorMatcher(); txCoordinatorMatcher.withCapabilities(arrayContaining(TxnCapability.LOCAL_TXN)); testPeer.expectSenderAttach(txCoordinatorMatcher, false, false); // First expect an unsettled 'declare' transfer to the txn coordinator, and // reply with a declared disposition state containing the txnId. txnId = new Binary(new byte[]{ (byte) 1, (byte) 2, (byte) 3, (byte) 4}); testPeer.expectDeclare(txnId); session = connection.createSession(true, Session.SESSION_TRANSACTED); } else { session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); } Destination destination = null; if (destType == Queue.class) { destination = session.createQueue("MyQueue"); } else if (destType == Topic.class) { destination = session.createTopic("MyTopis"); } else if (destType == TemporaryQueue.class) { String dynamicAddress = "myTempQueueAddress"; testPeer.expectTempQueueCreationAttach(dynamicAddress); destination = session.createTemporaryQueue(); } else if (destType == TemporaryTopic.class) { String dynamicAddress = "myTempTopicAddress"; testPeer.expectTempTopicCreationAttach(dynamicAddress); destination = session.createTemporaryTopic(); } else { fail("unexpected type"); } if (senderSettled) { testPeer.expectSettledSenderAttach(); } else { testPeer.expectSenderAttach(); } MessageProducer producer = null; if (anonymous) { producer = session.createProducer(null); } else { producer = session.createProducer(destination); } // Create and transfer a new message MessageHeaderSectionMatcher headersMatcher = new MessageHeaderSectionMatcher(true); headersMatcher.withDurable(equalTo(true)); MessageAnnotationsSectionMatcher msgAnnotationsMatcher = new MessageAnnotationsSectionMatcher(true); TransferPayloadCompositeMatcher messageMatcher = new TransferPayloadCompositeMatcher(); messageMatcher.setHeadersMatcher(headersMatcher); messageMatcher.setMessageAnnotationsMatcher(msgAnnotationsMatcher); Matcher stateMatcher = nullValue(); if (transacted) { stateMatcher = new TransactionalStateMatcher(); ((TransactionalStateMatcher) stateMatcher).withTxnId(equalTo(txnId)); ((TransactionalStateMatcher) stateMatcher).withOutcome(nullValue()); } ListDescribedType responseState = new Accepted(); if (transacted) { TransactionalState txState = new TransactionalState(); txState.setTxnId(txnId); txState.setOutcome(new Accepted()); } if (transferSettled) { testPeer.expectTransfer(messageMatcher, stateMatcher, true, false, responseState, false); } else { testPeer.expectTransfer(messageMatcher, stateMatcher, false, true, responseState, true); } if (anonymous && !relaySupported) { testPeer.expectDetach(true, true, true); } Message message = session.createTextMessage(); if (anonymous) { producer.send(destination, message); } else { producer.send(message); } if (transacted) { testPeer.expectDischarge(txnId, true); } testPeer.expectClose(); connection.close(); testPeer.waitForAllHandlersToComplete(1000); } } } package com.ipiecoles.java.java220; import org.joda.time.LocalDate; import java.util.Objects; public class Commercial extends Employe{ //region Attributs private Double caAnnuel = 0d; private Integer performance = 10; //endregion //region Constructeur public Commercial(){} public Commercial(String nom,String prenom,String matricule, LocalDate dateEmbauche,Double salaire, Double caAnnuel){ super(nom,prenom,matricule,dateEmbauche,salaire); this.caAnnuel = caAnnuel; } public Commercial(String nom,String prenom,String matricule, LocalDate dateEmbauche,Double salaire, Double caAnnuel, Integer performance){ super(nom,prenom,matricule,dateEmbauche,salaire); this.caAnnuel = caAnnuel; this.performance = performance; } //endregion //region Getters Setters public Double getCaAnnuel() { return caAnnuel; } public void setCaAnnuel(Double caAnnuel) { this.caAnnuel = caAnnuel; } public Integer getPerformance() { return performance; } public void setPerformance(Integer performance) { performance = performance; } //endregion //region Méthodes public Double getPrimeAnnuelle(){ if(this.caAnnuel != null) { caAnnuel = Math.max(Math.ceil(this.caAnnuel * 0.05), 500.0d); } return 500.0d; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; Commercial that = (Commercial) o; return Objects.equals(caAnnuel, that.caAnnuel); } @Override public int hashCode() { return Objects.hash(super.hashCode(), caAnnuel); } public boolean performanceEgale(Integer unePerformance) { return getPerformance().equals(unePerformance); } public enum equivalenceNote{INSUFFISANT, PASSABLE, BIEN, TRES_BIEN, NULL} { } //endregion } package org.jeecg.ThreadTeast4; import java.math.BigDecimal; public class Tortoise extends Animal{ public Tortoise() { setName("乌龟");// Thread的方法,给线程赋值名字 } @Override public void runing() { // 重写running方法,编写乌龟的奔跑操作 // 跑的距离 BigDecimal dis=new BigDecimal("0.1"); //剩余的距离 len=len.subtract(dis); while (len.compareTo(new BigDecimal("0"))<=0) { length = 0; System.out.println("乌龟获得了胜利"); if (callBack != null) { callBack.Win(); } this.stop(); // 让兔子不要在跑了 } System.out.println("乌龟跑了" + dis + "米,距离终点还有" + len + "米"); try { this.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } package io.github.noeppi_noeppi.mods.intturtle.engine; public class IntCodeException extends Exception { public final long at; public IntCodeException(String message) { this(message, Long.MIN_VALUE); } public IntCodeException(IntCodeException parent, long at) { super(parent.getMessage(), parent); this.at = at; } public IntCodeException(String message, long at) { super(message); this.at = at; } } /* * Copyright 2022 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 * * https://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.instancio.util; import org.instancio.exception.InstancioApiException; import org.instancio.test.support.pojo.basic.StringHolder; import org.instancio.test.support.pojo.person.Gender; import org.instancio.test.support.pojo.person.Person; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.lang.reflect.Field; import java.util.AbstractList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; class ReflectionUtilsTest { @ValueSource(classes = {String.class, String[].class, List[].class}) @ParameterizedTest void isArrayOrConcreteTrue(final Class klass) { assertThat(ReflectionUtils.isArrayOrConcrete(klass)).isTrue(); } @ValueSource(classes = {List.class, AbstractList.class}) @ParameterizedTest void isArrayOrConcreteFalse(final Class klass) { assertThat(ReflectionUtils.isArrayOrConcrete(klass)).isFalse(); } @Test void getEnumValues() { final Gender[] enumValues = ReflectionUtils.getEnumValues(Gender.class); assertThat(enumValues).containsExactly(Gender.values()); } @Test void getField() { assertThat(ReflectionUtils.getField(Person.class, "name")) .isNotNull() .extracting(Field::getName) .isEqualTo("name"); assertThatThrownBy(() -> ReflectionUtils.getField(Person.class, null)) .isInstanceOf(NullPointerException.class) .hasMessage("null field name"); assertThatThrownBy(() -> ReflectionUtils.getField(Person.class, "foo")) .isInstanceOf(InstancioApiException.class) .hasMessage("Invalid field 'foo' for class org.instancio.test.support.pojo.person.Person"); } @Test void getAnnotatedFields() { final List fields = ReflectionUtils.getAnnotatedFields(WithAnnotatedField.class, Nullable.class); assertThat(fields).hasSize(2) .extracting(Field::getName) .contains("foo", "bar"); } @Test void getAnnotatedFieldsReturnsEmptyList() { assertThat(ReflectionUtils.getAnnotatedFields(StringHolder.class, Nullable.class)).isEmpty(); } @SuppressWarnings({"unused", "NotNullFieldNotInitialized", "NullableProblems"}) private static class WithAnnotatedField { @Nullable private String foo; @Nullable private Integer bar; @Nonnull private Integer baz; } } package com.dynatrace.diagnostics.plugins.jmx.variableholder; public class ServletStats { public ServletStats() { super(); } public String getserverName() { return serverName; } public void setserverName(String serverName) { this.serverName = serverName; } public String getAverageAvgStatistic() { return AverageAvgStatistic; } public void setAverageAvgStatistic(String AverageAvgStatistic) { this.AverageAvgStatistic = AverageAvgStatistic; } public String getAverageAvgMin() { return AverageAvgMin; } public void setAverageAvgMin(String AverageAvgMin) { this.AverageAvgMin = AverageAvgMin; } public String getAverageAvgMax() { return AverageAvgMax; } public void setAverageAvgMax(String AverageAvgMax) { this.AverageAvgMax = AverageAvgMax; } public String getAverageAvgTotal() { return AverageAvgTotal; } public void setAverageAvgTotal(String AverageAvgTotal) { this.AverageAvgTotal = AverageAvgTotal; } public String getAverageAvgCount() { return AverageAvgCount; } public void setAverageAvgCount(String AverageAvgCount) { this.AverageAvgCount = AverageAvgCount; } public String getAverageAvgSumSq() { return AverageAvgSumSq; } public void setAverageAvgSumSq(String AverageAvgSumSq) { this.AverageAvgSumSq = AverageAvgSumSq; } public String getTimeAvgStatistic() { return TimeAvgStatistic; } public void setTimeAvgStatistic(String TimeAvgStatistic) { this.TimeAvgStatistic = TimeAvgStatistic; } public String getTimeAvgMin() { return TimeAvgMin; } public void setTimeAvgMin(String TimeAvgMin) { this.TimeAvgMin = TimeAvgMin; } public String getTimeAvgMax() { return TimeAvgMax; } public void setTimeAvgMax(String TimeAvgMax) { this.TimeAvgMax = TimeAvgMax; } public String getTimeAvgTotal() { return TimeAvgTotal; } public void setTimeAvgTotal(String TimeAvgTotal) { this.TimeAvgTotal = TimeAvgTotal; } public String getTimeAvgCount() { return TimeAvgCount; } public void setTimeAvgCount(String TimeAvgCount) { this.TimeAvgCount = TimeAvgCount; } public String getTimeAvgSumSq() { return TimeAvgSumSq; } public void setTimeAvgSumSq(String TimeAvgSumSq) { this.TimeAvgSumSq = TimeAvgSumSq; } public String getservletName() { return servletName; } public void setservletName(String servletName) { this.servletName = servletName; } public String getEnviro() { return Enviro; } public void setEnviro(String Enviro) { this.Enviro = Enviro; } public String getTotalRequest() { return TotalRequest; } public void setTotalRequest(String TotalRequest) { this.TotalRequest = TotalRequest; } String serverName = null; String Enviro; String AverageAvgStatistic; String AverageAvgMin; String AverageAvgMax; String AverageAvgTotal; String AverageAvgCount; String AverageAvgSumSq; String TimeAvgStatistic; String TimeAvgMin; String TimeAvgMax; String TimeAvgTotal; String TimeAvgCount; String TimeAvgSumSq; String TotalRequest; String servletName; } package org.firstinspires.ftc.teamcode.tests; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import org.firstinspires.ftc.teamcode.AutonomousOpMode; import org.firstinspires.ftc.teamcode.old.OldHolonomicDrivebase; import org.firstinspires.ftc.teamcode.subsystems.Hanging; /** * Created by xiax on 4/23/2018. */ @TeleOp(name = "Drive Test", group = "test") public class DriveTest extends AutonomousOpMode { @Override public void runOpMode() { initializeAutonomous(); waitForStart(); while (opModeIsActive()) { if (gamepad1.a) { MoveUntilEncoder(10, 0, .5); } if (gamepad1.b) { MoveUntilEncoder(20, 0, .5); } if (gamepad1.y) { MoveUntilEncoder(40, 0, .5); } if (gamepad1.x) { MoveUntilEncoder(80, 0, .5); } if (gamepad2.a) { MoveUntilEncoder(10, 180, .5); } if (gamepad2.b) { MoveUntilEncoder(20, 180, .5); } if (gamepad2.y) { MoveUntilEncoder(40, 180, .5); } if (gamepad2.x) { MoveUntilEncoder(80, 180, .5); } } } } /* * Copyright 2009-2017 Aconex * * 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 io.pcp.parfait.jmx; import static org.junit.Assert.assertEquals; import java.util.Collections; import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularData; import io.pcp.parfait.MonitorableRegistry; import io.pcp.parfait.timing.EventTimer; import io.pcp.parfait.timing.InProgressSnapshot; import io.pcp.parfait.timing.LoggerSink; import io.pcp.parfait.timing.StepMeasurementSink; import io.pcp.parfait.timing.ThreadContext; import io.pcp.parfait.timing.ThreadMetricSuite; import io.pcp.parfait.timing.Timeable; import org.junit.Test; public class JmxInProgressMonitorTest { @Test public void testValuesConvertedToStringsForExport() { ThreadContext context = new ThreadContext(); context.put("stringvalue", "floop"); context.put("intvalue", 99); Timeable t = new Timeable() { @Override public void setEventTimer(EventTimer timer) { } }; EventTimer timer = new EventTimer("foo", new MonitorableRegistry(), ThreadMetricSuite.blank(), false, false, Collections.singletonList(new LoggerSink())); timer.registerTimeable(t, "foo"); timer.getCollector().startTiming(t, "stuff"); InProgressSnapshot snapshot = InProgressSnapshot.capture(timer, context); TabularData data = JmxInProgressMonitor.TO_TABULAR_DATA.apply(snapshot); assertEquals(SimpleType.STRING, data.getTabularType().getRowType().getType("stringvalue")); assertEquals(SimpleType.STRING, data.getTabularType().getRowType().getType("intvalue")); } } lipstick-console/src/main/java/com/netflix/lipstick/model/P2jSampleOutput.java100-1000 /** * Copyright 2013 Netflix, 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 com.netflix.lipstick.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; /** * Container for sample output of a store operation in a map/reduce job. * * @author jmagnusson * */ @Entity public class P2jSampleOutput { private long id; private String schemaString; private String sampleOutput; @Id @GeneratedValue public long getId() { return id; } public void setId(long id) { this.id = id; } @Lob public String getSchemaString() { return schemaString; } public void setSchemaString(String schemaString) { this.schemaString = schemaString; } @Lob public String getSampleOutput() { return sampleOutput; } public void setSampleOutput(String sampleOutput) { this.sampleOutput = sampleOutput; } } /** * This package provides some utilities like the {@link io.github.bakedlibs.dough.data.persistent.PersistentDataAPI}, * this api allows you to interact with {@link org.bukkit.persistence.PersistentDataContainer}s. * We also provide a few {@link org.bukkit.persistence.PersistentDataType} implementations ourselves. */ package io.github.bakedlibs.dough.data.persistent;JoHeinem/flowing-retailkafka/java/payment/src/main/java/io/flowing/retail/payment/engine/dto/engine/AuthorizationDto.java0 /* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. Licensed under a commercial license. * You may not use this file except in compliance with the commercial license. */ package io.flowing.retail.payment.engine.dto.engine; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @NoArgsConstructor @AllArgsConstructor @Data public class AuthorizationDto { protected String id; protected Integer type; protected List permissions; protected String userId; protected String groupId; protected Integer resourceType; protected String resourceId; } package kr.hs.entrydsm.rollsroyce.domain.application.service; import kr.hs.entrydsm.rollsroyce.domain.application.presentation.dto.request.ChangeIntroduceRequest; import kr.hs.entrydsm.rollsroyce.domain.user.domain.User; import kr.hs.entrydsm.rollsroyce.domain.user.facade.UserFacade; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @RequiredArgsConstructor @Service public class ChangeIntroduceService { private final UserFacade userFacade; @Transactional public void execute(ChangeIntroduceRequest request) { User user = userFacade.getCurrentUser(); user.updateSelfIntroduce(request.getContent()); } } src/main/java/com/logpresso/client/http/impl/TrapReceiver.java /* * Copyright 2013 Eediom 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 com.logpresso.client.http.impl; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.SocketException; import java.net.SocketTimeoutException; import java.net.URL; import java.util.concurrent.CopyOnWriteArraySet; import org.json.JSONArray; import org.json.JSONTokener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.logpresso.client.Message; /** * 로그프레소 서버에서 전송되는 비동기적 트랩 전문을 수신합니다. * * @author * */ public class TrapReceiver extends Thread { private final Logger logger = LoggerFactory.getLogger(TrapReceiver.class); private boolean doStop; private String host; private int port; private String cookie; private CopyOnWriteArraySet listeners; private HttpURLConnection con; public TrapReceiver(String host, String cookie) { this(host, 80, cookie); } public TrapReceiver(String host, int port, String cookie) { this.host = host; this.port = port; this.cookie = cookie; this.listeners = new CopyOnWriteArraySet(); } @Override public void run() { try { logger.trace("logdb client: trap thread started"); while (!doStop) { receiveTrap(); } } catch (SocketException e) { if (e.getMessage().equalsIgnoreCase("socket closed")) return; } catch (Throwable t) { logger.error("logdb client: trap receiver error", t); } finally { logger.trace("logdb client: trap thread stopped"); } } private void receiveTrap() throws SocketException { InputStream is = null; try { con = (HttpURLConnection) new URL("http://" + host + ":" + port + "/msgbus/trap").openConnection(); con.setRequestProperty("Content-Type", "text/json"); con.setRequestProperty("Cookie", cookie); con.setConnectTimeout(5000); con.setReadTimeout(5000); is = con.getInputStream(); ByteArrayOutputStream bos = null; if (con.getContentLength() > 0) bos = new ByteArrayOutputStream(con.getContentLength()); else bos = new ByteArrayOutputStream(); byte[] b = new byte[8096]; while (true) { int read = is.read(b); if (read < 0) break; bos.write(b, 0, read); } String text = new String(bos.toByteArray(), "utf-8"); if (text.isEmpty()) return; JSONTokener tokenizer = new JSONTokener(new StringReader(text)); JSONArray container = (JSONArray) tokenizer.nextValue(); for (int i = 0; i < container.length(); i++) { JSONArray obj = container.getJSONArray(i); Message msg = MessageCodec.decode(obj.toString()); invokeTrapCallbacks(msg); } } catch (SocketTimeoutException e) { logger.debug("logdb client: socket timeout"); } catch (ConnectException e) { throw e; } catch (SocketException e) { if (e.getMessage().equalsIgnoreCase("socket closed")) throw e; logger.error("logdb client: cannot fetch trap", e); } catch (Throwable t) { logger.error("logdb client: cannot fetch trap", t); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } if (con != null) { con.disconnect(); con = null; } } } private void invokeTrapCallbacks(Message msg) { for (TrapListener listener : listeners) { try { listener.onTrap(msg); } catch (Throwable t) { logger.error("logdb client: listener should not throw any exception", t); } } } public void addListener(TrapListener listener) { listeners.add(listener); } public void removeListener(TrapListener listener) { listeners.remove(listener); } public void close() { try { doStop = true; if (con != null) con.disconnect(); interrupt(); join(); } catch (InterruptedException e) { } } } src/org/jocl/struct/__attribute__.java /* * JOCL - Java bindings for OpenCL * * Copyright 2009 - http://www.jocl.org/ * * * This file is part of JOCL. * * JOCL is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JOCL 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with JOCL. If not, see . */ package org.jocl.struct; import java.lang.annotation.*; /** * This annotation is an emulation of the __attribute__ * annotation of OpenCL. * * TODO: This is highly experimental, and not yet made * public */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.TYPE}) @interface __attribute__ { int align() default 0; boolean packed() default false; } package com.dyvak.crm.service.impl; import com.dyvak.crm.service.LeadService; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; @Service @AllArgsConstructor public class LeadServiceImpl implements LeadService { } package com.properties.providers; import java.io.IOException; import java.io.InputStream; import java.net.URI; public class FileProvider extends PropertyProvider { @Override protected InputStream openResource(URI uri) throws IOException { return uri.toURL().openStream(); } }package org.zmsoft.framework.support; import javax.servlet.http.HttpServletRequest; import org.zmsoft.framework.constants.ICFrameworkConstants; import org.zmsoft.framework.utils.EmptyHelper; /** * 请求头参数获取 * */ public class MyHttpRequestHelper implements ICFrameworkConstants{ public static String loadJobId(HttpServletRequest request) { // 获得参数里面的Token String jobId = request.getHeader(CONSTANT_USER_JOBID);// 头部 if (EmptyHelper.isEmpty(jobId)) { jobId = request.getParameter(CONSTANT_USER_JOBID);// 参数列表 } return jobId; } public static String loadToken(HttpServletRequest request) { // 获得参数里面的Token String token = request.getHeader(CONSTANT_USER_TOKEN);// 头部 if (EmptyHelper.isEmpty(token)) { token = request.getParameter(CONSTANT_USER_TOKEN);// 参数列表 } return token; } } package examples.adventure; import java.util.List; /** This very simple text adventure game uses Lists and Maps to store information about the world. */ public class RuralTravels extends Game { public static void main(String[] args) { new RuralTravels().play(); } public RuralTravels() { var pigKnockOverEvent = new Event(0.4f, "A friendly pig knocks you over", -10); var oinkEvent = new Event(1, "Your lovely pig oinks and greets you.", 10); pigKnockOverEvent.addElseEvents(oinkEvent); var farm = new Place("Farm", "an old farm with animals", List.of(pigKnockOverEvent)); var town = new Place("Town", "a small town in the middle of nowhere"); var airport = new Place("Airport", "a one-runway airport, mostly used by crop dusters", List.of(new Event(0.6f, "An experimental plane flies overhead", 0))); location = farm; farm.addTransitions(town); town.addTransitions(farm, airport); airport.addTransitions(town); } } src/main/java/io/clickhandler/web/camber/client/Camber.java package io.clickhandler.web.camber.client; import com.google.gwt.core.client.ScriptInjector; import io.clickhandler.web.camber.resources.CamberResourceBundle; import io.clickhandler.web.reactGwt.client.ReactGwt; public class Camber { public static void init() { ScriptInjector.fromString(CamberResourceBundle.INSTANCE.camberWebpack().getText()).setWindow(ScriptInjector.TOP_WINDOW).inject(); } } package br.com.danilo.oo; public class Quadrado implements AreaCalculavel { private int lado; public Quadrado(int lado) { this.lado = lado; } @Override public double calculeArea() { return this.lado * this.lado; } } addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/GroupAdderssTests.java package ru.stqa.pft.addressbook; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.*; public class GroupAdderssTests { FirefoxDriver wd; @BeforeMethod public void setUp() throws Exception { wd = new FirefoxDriver(); wd.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); login("admin", "secret"); } private void login(String username, String password) { wd.get("http://localhost/addressbook/index.php"); wd.findElement(By.name("pass")).click(); wd.findElement(By.name("pass")).sendKeys("\\undefined"); wd.findElement(By.name("user")).click(); wd.findElement(By.name("user")).clear(); wd.findElement(By.name("user")).sendKeys(username); wd.findElement(By.id("content")).click(); wd.findElement(By.name("pass")).click(); wd.findElement(By.name("pass")).clear(); wd.findElement(By.name("pass")).sendKeys(password); wd.findElement(By.id("LoginForm")).click(); wd.findElement(By.xpath("//form[@id='LoginForm']/input[3]")).click(); } @Test public void GroupAdderssTests() { gotoAdders(); fillcontact(new GroupContsct("Alena", "Kob", "this address", "+71111111111", "")); returnToAddres(); } private void fillcontact(GroupContsct groupContsct) { wd.findElement(By.name("firstname")).click(); wd.findElement(By.name("firstname")).clear(); wd.findElement(By.name("firstname")).sendKeys(groupContsct.getName()); wd.findElement(By.name("middlename")).click(); wd.findElement(By.name("lastname")).click(); wd.findElement(By.name("lastname")).clear(); wd.findElement(By.name("lastname")).sendKeys(groupContsct.getLastname()); wd.findElement(By.name("address")).click(); wd.findElement(By.name("address")).clear(); wd.findElement(By.name("address")).sendKeys(groupContsct.getAddress()); wd.findElement(By.name("home")).click(); wd.findElement(By.name("home")).clear(); wd.findElement(By.name("home")).sendKeys(groupContsct.getTel()); wd.findElement(By.name("email")).click(); wd.findElement(By.name("email")).clear(); wd.findElement(By.name("email")).sendKeys(groupContsct.getEmail()); } private void returnToAddres() { wd.findElement(By.xpath("//div[@id='content']/form/input[21]")).click(); } private void gotoAdders() { wd.findElement(By.linkText("add new")).click(); } @AfterMethod public void tearDown() { wd.quit(); } public static boolean isAlertPresent(FirefoxDriver wd) { try { wd.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } } 10-100 package com.miotech.kun.workflow.executor.kubernetes; import com.google.inject.Inject; import com.google.inject.Singleton; import com.miotech.kun.workflow.core.Executor; import com.miotech.kun.workflow.core.model.resource.ResourceQueue; import com.miotech.kun.workflow.core.model.taskrun.TaskAttempt; import com.miotech.kun.workflow.executor.AbstractQueueManager; import com.miotech.kun.workflow.executor.WorkerLifeCycleManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Singleton public class KubernetesExecutor implements Executor { private final Logger logger = LoggerFactory.getLogger(KubernetesExecutor.class); private final WorkerLifeCycleManager podLifeCycleManager;//pod生命周期管理 private final AbstractQueueManager kubernetesResourceManager;//管理kubernetes资源配额 @Inject public KubernetesExecutor(WorkerLifeCycleManager podLifeCycleManager, KubernetesResourceManager kubernetesResourceManager) { this.podLifeCycleManager = podLifeCycleManager; this.kubernetesResourceManager = kubernetesResourceManager; } public boolean submit(TaskAttempt taskAttempt) { logger.info("submit taskAttemptId = {} to executor", taskAttempt.getId()); podLifeCycleManager.start(taskAttempt); return true; } @Override public boolean reset() { logger.info("kubernetes going to reset"); podLifeCycleManager.reset(); return true; } @Override public boolean recover() { logger.info("kubernetes going to recover"); podLifeCycleManager.recover(); return true; } @Override public String workerLog(Long taskAttemptId, Integer tailLines) { return podLifeCycleManager.getLog(taskAttemptId, tailLines); } @Override public boolean cancel(Long taskAttemptId) { podLifeCycleManager.stop(taskAttemptId); return true; } @Override public void changePriority(long taskAttemptId, String queueName, Integer priority) { kubernetesResourceManager.changePriority(taskAttemptId, queueName, priority); } @Override public ResourceQueue createResourceQueue(ResourceQueue resourceQueue) { return kubernetesResourceManager.createResourceQueue(resourceQueue); } public ResourceQueue updateResourceQueue(ResourceQueue resourceQueue) { return kubernetesResourceManager.updateResourceQueue(resourceQueue); } } 0 // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.search.documents.indexes; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.HttpPipeline; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import com.azure.search.documents.SearchServiceVersion; import com.azure.search.documents.implementation.converters.SearchIndexerConverter; import com.azure.search.documents.implementation.converters.SearchIndexerDataSourceConverter; import com.azure.search.documents.implementation.converters.SearchIndexerSkillsetConverter; import com.azure.search.documents.implementation.util.MappingUtils; import com.azure.search.documents.indexes.implementation.SearchServiceClientImpl; import com.azure.search.documents.indexes.implementation.SearchServiceClientImplBuilder; import com.azure.search.documents.indexes.implementation.models.ListDataSourcesResult; import com.azure.search.documents.indexes.implementation.models.ListIndexersResult; import com.azure.search.documents.indexes.implementation.models.ListSkillsetsResult; import com.azure.search.documents.indexes.models.SearchIndexer; import com.azure.search.documents.indexes.models.SearchIndexerDataSourceConnection; import com.azure.search.documents.indexes.models.SearchIndexerSkillset; import com.azure.search.documents.indexes.models.SearchIndexerStatus; import reactor.core.publisher.Mono; import java.util.Objects; import java.util.function.Function; import static com.azure.core.util.FluxUtil.monoError; import static com.azure.core.util.FluxUtil.pagedFluxError; import static com.azure.core.util.FluxUtil.withContext; /** * Asynchronous Client to manage and query indexers, as well as manage other resources, on a Cognitive Search service */ public class SearchIndexerAsyncClient { /** * Search REST API Version */ private final SearchServiceVersion serviceVersion; /** * The endpoint for the Azure Cognitive Search service. */ private final String endpoint; /** * The logger to be used */ private final ClientLogger logger = new ClientLogger(SearchIndexerAsyncClient.class); /** * The underlying AutoRest client used to interact with the Search service */ private final SearchServiceClientImpl restClient; /** * The pipeline that powers this client. */ private final HttpPipeline httpPipeline; SearchIndexerAsyncClient(String endpoint, SearchServiceVersion serviceVersion, HttpPipeline httpPipeline) { this.endpoint = endpoint; this.serviceVersion = serviceVersion; this.httpPipeline = httpPipeline; this.restClient = new SearchServiceClientImplBuilder() .endpoint(endpoint) // .apiVersion(serviceVersion.getVersion()) .pipeline(httpPipeline) .buildClient(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return the pipeline. */ HttpPipeline getHttpPipeline() { return this.httpPipeline; } /** * Gets the endpoint for the Azure Cognitive Search service. * * @return the endpoint value. */ public String getEndpoint() { return this.endpoint; } /** * Creates a new Azure Cognitive Search data source or updates a data source if it already exists. * *

Code Sample

* *

Create or update search indexer data source connection named "dataSource".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnection#SearchIndexerDataSourceConnection} * * @param dataSource The definition of the {@link SearchIndexerDataSourceConnection} to create or update. * @return the data source that was created or updated. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono createOrUpdateDataSourceConnection( SearchIndexerDataSourceConnection dataSource) { return createOrUpdateDataSourceConnectionWithResponse(dataSource, false).map(Response::getValue); } /** * Creates a new Azure Cognitive Search data source or updates a data source if it already exists. * *

Code Sample

* *

Create or update search indexer data source connection named "dataSource".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean} * * @param dataSource The definition of the {@link SearchIndexerDataSourceConnection} to create or update. * @param onlyIfUnchanged {@code true} to update if the {@code dataSource} is the same as the current service value. * {@code false} to always update existing value. * @return a data source response. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createOrUpdateDataSourceConnectionWithResponse( SearchIndexerDataSourceConnection dataSource, boolean onlyIfUnchanged) { return withContext(context -> createOrUpdateDataSourceConnectionWithResponse(dataSource, onlyIfUnchanged, context)); } Mono> createOrUpdateDataSourceConnectionWithResponse( SearchIndexerDataSourceConnection dataSource, boolean onlyIfUnchanged, Context context) { Objects.requireNonNull(dataSource, "'DataSource' cannot be null."); String ifMatch = onlyIfUnchanged ? dataSource.getETag() : null; if (dataSource.getConnectionString() == null) { dataSource.setConnectionString(""); } try { return restClient .getDataSources() .createOrUpdateWithResponseAsync(dataSource.getName(), SearchIndexerDataSourceConverter.map(dataSource), ifMatch, null, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(MappingUtils::mappingExternalDataSource); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Azure Cognitive Search data source * *

Code Sample

* *

Create search indexer data source connection named "dataSource".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateDataSourceConnection#SearchIndexerDataSourceConnection} * * @param dataSource The definition of the dataSource to create. * @return a Mono which performs the network request upon subscription. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono createDataSourceConnection( SearchIndexerDataSourceConnection dataSource) { return createDataSourceConnectionWithResponse(dataSource).map(Response::getValue); } /** * Creates a new Azure Cognitive Search data source * *

Code Sample

* *

Create search indexer data source connection named "dataSource".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection} * * @param dataSource The definition of the {@link SearchIndexerDataSourceConnection} to create. * @return a Mono which performs the network request upon subscription. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createDataSourceConnectionWithResponse( SearchIndexerDataSourceConnection dataSource) { return withContext(context -> this.createDataSourceConnectionWithResponse(dataSource, context)); } Mono> createDataSourceConnectionWithResponse( SearchIndexerDataSourceConnection dataSource, Context context) { try { return restClient.getDataSources() .createWithResponseAsync(SearchIndexerDataSourceConverter.map(dataSource), null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(MappingUtils::mappingExternalDataSource); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Retrieves a DataSource from an Azure Cognitive Search service. * *

Code Sample

* *

Get search indexer data source connection named "dataSource".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnection#String} * * @param dataSourceName the name of the {@link SearchIndexerDataSourceConnection} to retrieve. * @return the DataSource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono getDataSourceConnection(String dataSourceName) { return getDataSourceConnectionWithResponse(dataSourceName).map(Response::getValue); } /** * Retrieves a DataSource from an Azure Cognitive Search service. * *

Code Sample

* *

Get search indexer data source connection named "dataSource".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.getDataSourceConnectionWithResponse#String} * * @param dataSourceName the name of the {@link SearchIndexerDataSourceConnection} to retrieve. * @return a response containing the DataSource. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getDataSourceConnectionWithResponse( String dataSourceName) { return withContext(context -> getDataSourceConnectionWithResponse(dataSourceName, context)); } @ServiceMethod(returns = ReturnType.SINGLE) Mono> getDataSourceConnectionWithResponse(String dataSourceName, Context context) { try { return restClient.getDataSources() .getWithResponseAsync(dataSourceName, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(MappingUtils::mappingExternalDataSource); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * List all DataSources from an Azure Cognitive Search service. * *

Code Sample

* *

List all search indexer data source connections.

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.listDataSourceConnections} * * @return a list of DataSources */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listDataSourceConnections() { try { return new PagedFlux<>(() -> withContext(context -> this.listDataSourceConnectionsWithResponse(null, context)) .map(MappingUtils::mappingPagingDataSource)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } PagedFlux listDataSourceConnections(Context context) { try { return new PagedFlux<>(() -> this.listDataSourceConnectionsWithResponse(null, context) .map(MappingUtils::mappingPagingDataSource)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } /** * List all DataSource names from an Azure Cognitive Search service. * *

Code Sample

* *

List all search indexer data source connection names.

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.listDataSourceConnectionNames} * * @return a list of DataSource names */ public PagedFlux listDataSourceConnectionNames() { try { return new PagedFlux<>(() -> withContext(context -> this.listDataSourceConnectionsWithResponse("name", context)) .map(MappingUtils::mappingPagingDataSourceNames)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } PagedFlux listDataSourceConnectionNames(Context context) { try { return new PagedFlux<>(() -> this.listDataSourceConnectionsWithResponse("name", context) .map(MappingUtils::mappingPagingDataSourceNames)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } private Mono> listDataSourceConnectionsWithResponse(String select, Context context) { return restClient.getDataSources() .listWithResponseAsync(select, null, context) .onErrorMap(MappingUtils::exceptionMapper); } /** * Delete a DataSource * *

Code Sample

* *

Delete the search indexer data source connection named "dataSource".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnection#String} * * @param dataSourceName the name of the {@link SearchIndexerDataSourceConnection} for deletion * @return a void Mono */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono deleteDataSourceConnection(String dataSourceName) { return withContext(context -> deleteDataSourceConnectionWithResponse(dataSourceName, null, context).flatMap(FluxUtil::toMono)); } /** * Deletes an Azure Cognitive Search data source. * *

Code Sample

* *

Delete the search indexer data source connection named "dataSource".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteDataSourceConnectionWithResponse#SearchIndexerDataSourceConnection-boolean} * * @param dataSource The {@link SearchIndexerDataSourceConnection} to delete. * @param onlyIfUnchanged {@code true} to delete if the {@code dataSource} is the same as the current service value. * {@code false} to always delete existing value. * @return a mono response */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteDataSourceConnectionWithResponse(SearchIndexerDataSourceConnection dataSource, boolean onlyIfUnchanged) { Objects.requireNonNull(dataSource, "'DataSource' cannot be null"); String etag = onlyIfUnchanged ? dataSource.getETag() : null; return withContext(context -> deleteDataSourceConnectionWithResponse(dataSource.getName(), etag, context)); } Mono> deleteDataSourceConnectionWithResponse(String dataSourceName, String etag, Context context) { try { return restClient.getDataSources() .deleteWithResponseAsync( dataSourceName, etag, null, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Azure Cognitive Search indexer. * *

Code Sample

* *

Create search indexer named "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexer#SearchIndexer} * * @param indexer definition of the indexer to create. * @return the created Indexer. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono createIndexer(SearchIndexer indexer) { return createIndexerWithResponse(indexer).map(Response::getValue); } /** * Creates a new Azure Cognitive Search indexer. * *

Code Sample

* *

Create search indexer named "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createIndexerWithResponse#SearchIndexer} * * @param indexer definition of the indexer to create * @return a response containing the created Indexer. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createIndexerWithResponse(SearchIndexer indexer) { return withContext(context -> createIndexerWithResponse(indexer, context)); } Mono> createIndexerWithResponse(SearchIndexer indexer, Context context) { try { return restClient.getIndexers() .createWithResponseAsync(SearchIndexerConverter.map(indexer), null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(MappingUtils::mappingExternalSearchIndexer); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new Azure Cognitive Search indexer or updates an indexer if it already exists. * *

Code Sample

* *

Create or update search indexer named "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexer#SearchIndexer} * * @param indexer The definition of the indexer to create or update. * @return a response containing the created Indexer. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono createOrUpdateIndexer(SearchIndexer indexer) { return createOrUpdateIndexerWithResponse(indexer, false).map(Response::getValue); } /** * Creates a new Azure Cognitive Search indexer or updates an indexer if it already exists. * *

Code Sample

* *

Create or update search indexer named "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexerWithResponse#SearchIndexer-boolean} * * @param indexer the definition of the {@link SearchIndexer} to create or update * @param onlyIfUnchanged {@code true} to update if the {@code indexer} is the same as the current service value. * {@code false} to always update existing value. * @return a response containing the created Indexer. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createOrUpdateIndexerWithResponse(SearchIndexer indexer, boolean onlyIfUnchanged) { return withContext(context -> createOrUpdateIndexerWithResponse(indexer, onlyIfUnchanged, context)); } Mono> createOrUpdateIndexerWithResponse(SearchIndexer indexer, boolean onlyIfUnchanged, Context context) { Objects.requireNonNull(indexer, "'Indexer' cannot be 'null'"); String ifMatch = onlyIfUnchanged ? indexer.getETag() : null; try { return restClient.getIndexers() .createOrUpdateWithResponseAsync(indexer.getName(), SearchIndexerConverter.map(indexer), ifMatch, null, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(MappingUtils::mappingExternalSearchIndexer); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Retrieves an indexer definition. * *

Code Sample

* *

Get search indexer with name "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexer#String} * * @param indexerName the name of the indexer to retrieve * @return the indexer. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono getIndexer(String indexerName) { return getIndexerWithResponse(indexerName).map(Response::getValue); } /** * Retrieves an indexer definition. * *

Code Sample

* *

Get search indexer with name "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerWithResponse#String} * * @param indexerName the name of the indexer to retrieve * @return a response containing the indexer. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getIndexerWithResponse(String indexerName) { return withContext(context -> getIndexerWithResponse(indexerName, context)); } Mono> getIndexerWithResponse(String indexerName, Context context) { try { return restClient.getIndexers() .getWithResponseAsync(indexerName, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(MappingUtils::mappingExternalSearchIndexer); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists all indexers available for an Azure Cognitive Search service. * *

Code Sample

* *

List all search indexers.

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.listIndexers} * * @return a response containing all Indexers from the Search service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listIndexers() { try { return new PagedFlux<>(() -> withContext(context -> this.listIndexersWithResponse(null, context)) .map(MappingUtils::mappingPagingSearchIndexer)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } PagedFlux listIndexers(Context context) { try { return new PagedFlux<>(() -> this.listIndexersWithResponse(null, context) .map(MappingUtils::mappingPagingSearchIndexer)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } /** * Lists all indexers available for an Azure Cognitive Search service. * *

Code Sample

* *

List all search indexer names.

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.listIndexerNames} * * @return a response containing all Indexers from the Search service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listIndexerNames() { try { return new PagedFlux<>(() -> withContext(context -> this.listIndexersWithResponse("name", context)) .map(MappingUtils::mappingPagingSearchIndexerNames)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } PagedFlux listIndexerNames(Context context) { try { return new PagedFlux<>(() -> this.listIndexersWithResponse("name", context) .map(MappingUtils::mappingPagingSearchIndexerNames)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } private Mono> listIndexersWithResponse(String select, Context context) { return restClient.getIndexers() .listWithResponseAsync(select, null, context) .onErrorMap(MappingUtils::exceptionMapper); } /** * Deletes an Azure Cognitive Search indexer. * *

Code Sample

* *

Delete search indexer named "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexer#String} * * @param indexerName the name of the indexer to delete * @return a response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono deleteIndexer(String indexerName) { return withContext(context -> deleteIndexerWithResponse(indexerName, null, context) .flatMap(FluxUtil::toMono)); } /** * Deletes an Azure Cognitive Search indexer. * *

Code Sample

* *

Delete search indexer named "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteIndexerWithResponse#SearchIndexer-boolean} * * @param indexer the {@link SearchIndexer} to delete * @param onlyIfUnchanged {@code true} to delete if the {@code indexer} is the same as the current service value. * {@code false} to always delete existing value. * @return a response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteIndexerWithResponse(SearchIndexer indexer, boolean onlyIfUnchanged) { Objects.requireNonNull(indexer, "'Indexer' cannot be null"); String etag = onlyIfUnchanged ? indexer.getETag() : null; return withContext(context -> deleteIndexerWithResponse(indexer.getName(), etag, context)); } /** * Deletes an Azure Cognitive Search indexer. * * @param indexerName the name of the indexer to delete * @param etag Optional. The etag to match. * @param context the context * @return a response signalling completion. */ Mono> deleteIndexerWithResponse(String indexerName, String etag, Context context) { try { return restClient.getIndexers() .deleteWithResponseAsync(indexerName, etag, null, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Resets the change tracking state associated with an indexer. * *

Code Sample

* *

Reset search indexer named "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexer#String} * * @param indexerName the name of the indexer to reset * @return a response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono resetIndexer(String indexerName) { return resetIndexerWithResponse(indexerName).flatMap(FluxUtil::toMono); } /** * Resets the change tracking state associated with an indexer. * *

Code Sample

* *

Reset search indexer named "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.resetIndexerWithResponse#String} * * @param indexerName the name of the indexer to reset * @return a response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> resetIndexerWithResponse(String indexerName) { return withContext(context -> resetIndexerWithResponse(indexerName, context)); } Mono> resetIndexerWithResponse(String indexerName, Context context) { try { return restClient.getIndexers() .resetWithResponseAsync(indexerName, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Runs an indexer on-demand. * *

Code Sample

* *

Run search indexer named "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexer#String} * * @param indexerName the name of the indexer to run * @return a response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono runIndexer(String indexerName) { return runIndexerWithResponse(indexerName).flatMap(FluxUtil::toMono); } /** * Runs an indexer on-demand. * *

Code Sample

* *

Run search indexer named "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.runIndexerWithResponse#String} * * @param indexerName the name of the indexer to run * @return a response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> runIndexerWithResponse(String indexerName) { return withContext(context -> runIndexerWithResponse(indexerName, context)); } Mono> runIndexerWithResponse(String indexerName, Context context) { try { return restClient.getIndexers().runWithResponseAsync(indexerName, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Returns the current status and execution history of an indexer. * *

Code Sample

* *

Get status for search indexer "searchIndexer".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatus#String} * * @param indexerName the name of the indexer for which to retrieve status * @return the indexer execution info. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono getIndexerStatus(String indexerName) { return getIndexerStatusWithResponse(indexerName).map(Response::getValue); } /** * Returns the current status and execution history of an indexer. * *

Code Sample

* *

Get search indexer status.

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.getIndexerStatusWithResponse#String} * * @param indexerName the name of the indexer for which to retrieve status * @return a response with the indexer execution info. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getIndexerStatusWithResponse(String indexerName) { return withContext(context -> getIndexerStatusWithResponse(indexerName, context)); } Mono> getIndexerStatusWithResponse(String indexerName, Context context) { try { return restClient.getIndexers() .getStatusWithResponseAsync(indexerName, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(MappingUtils::mappingIndexerStatus); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Creates a new skillset in an Azure Cognitive Search service. * *

Code Sample

* *

Create search indexer skillset "searchIndexerSkillset".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillset#SearchIndexerSkillset} * * @param skillset definition of the skillset containing one or more cognitive skills * @return the created Skillset. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono createSkillset(SearchIndexerSkillset skillset) { return createSkillsetWithResponse(skillset).map(Response::getValue); } /** * Creates a new skillset in an Azure Cognitive Search service. * *

Code Sample

* *

Create search indexer skillset "searchIndexerSkillset".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createSkillsetWithResponse#SearchIndexerSkillset} * * @param skillset definition of the skillset containing one or more cognitive skills * @return a response containing the created Skillset. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createSkillsetWithResponse(SearchIndexerSkillset skillset) { return withContext(context -> createSkillsetWithResponse(skillset, context)); } Mono> createSkillsetWithResponse(SearchIndexerSkillset skillset, Context context) { Objects.requireNonNull(skillset, "'Skillset' cannot be null."); try { return restClient.getSkillsets() .createWithResponseAsync(SearchIndexerSkillsetConverter.map(skillset), null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(MappingUtils::mappingExternalSkillset); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Retrieves a skillset definition. * *

Code Sample

* *

Get search indexer skillset "searchIndexerSkillset".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSearchIndexerSkillset#String} * * @param skillsetName the name of the skillset to retrieve * @return the Skillset. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono getSkillset(String skillsetName) { return getSkillsetWithResponse(skillsetName).map(Response::getValue); } /** * Retrieves a skillset definition. * *

Code Sample

* *

Get search indexer skillset "searchIndexerSkillset".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.getSkillsetWithResponse#String} * * @param skillsetName the name of the skillset to retrieve * @return a response containing the Skillset. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getSkillsetWithResponse(String skillsetName) { return withContext(context -> getSkillsetWithResponse(skillsetName, context)); } Mono> getSkillsetWithResponse(String skillsetName, Context context) { try { return this.restClient.getSkillsets() .getWithResponseAsync(skillsetName, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(MappingUtils::mappingExternalSkillset); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Lists all skillsets available for an Azure Cognitive Search service. * *

Code Sample

* *

List all search indexer skillsets.

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.listSkillsets} * * @return a reactive response emitting the list of skillsets. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listSkillsets() { try { return new PagedFlux<>(() -> withContext(context -> listSkillsetsWithResponse(null, context)) .map(MappingUtils::mappingPagingSkillset)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } PagedFlux listSkillsets(Context context) { try { return new PagedFlux<>(() -> listSkillsetsWithResponse(null, context) .map(MappingUtils::mappingPagingSkillset)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } /** * Lists all skillset names for an Azure Cognitive Search service. * *

Code Sample

* *

List all search indexer skillset names.

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.listSkillsetNames} * * @return a reactive response emitting the list of skillset names. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux listSkillsetNames() { try { return new PagedFlux<>(() -> withContext(context -> listSkillsetsWithResponse("name", context)) .map(MappingUtils::mappingPagingSkillsetNames)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } PagedFlux listSkillsetNames(Context context) { try { return new PagedFlux<>(() -> listSkillsetsWithResponse("name", context) .map(MappingUtils::mappingPagingSkillsetNames)); } catch (RuntimeException ex) { return pagedFluxError(logger, ex); } } private Mono> listSkillsetsWithResponse(String select, Context context) { return this.restClient.getSkillsets() .listWithResponseAsync(select, null, context) .onErrorMap(MappingUtils::exceptionMapper); } /** * Creates a new Azure Cognitive Search skillset or updates a skillset if it already exists. * *

Code Sample

* *

Create or update search indexer skillset "searchIndexerSkillset".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateIndexerSkillset#SearchIndexerSkillset} * * @param skillset the definition of the skillset to create or update * @return the skillset that was created or updated. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono createOrUpdateSkillset(SearchIndexerSkillset skillset) { return createOrUpdateSkillsetWithResponse(skillset, false).map(Response::getValue); } /** * Creates a new Azure Cognitive Search skillset or updates a skillset if it already exists. * *

Code Sample

* *

Create or update search indexer skillset "searchIndexerSkillset".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.createOrUpdateSkillsetWithResponse#SearchIndexerSkillset-boolean} * * @param skillset the definition of the skillset to create or update * @param onlyIfUnchanged {@code true} to update if the {@code skillset} is the same as the current service value. * {@code false} to always update existing value. * @return a response containing the skillset that was created or updated. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, boolean onlyIfUnchanged) { return withContext(context -> createOrUpdateSkillsetWithResponse(skillset, onlyIfUnchanged, context)); } Mono> createOrUpdateSkillsetWithResponse(SearchIndexerSkillset skillset, boolean onlyIfUnchanged, Context context) { Objects.requireNonNull(skillset, "'Skillset' cannot be null."); String ifMatch = onlyIfUnchanged ? skillset.getETag() : null; try { return restClient.getSkillsets() .createOrUpdateWithResponseAsync(skillset.getName(), SearchIndexerSkillsetConverter.map(skillset), ifMatch, null, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(MappingUtils::mappingExternalSkillset); } catch (RuntimeException ex) { return monoError(logger, ex); } } /** * Deletes a cognitive skillset in an Azure Cognitive Search service. * *

Code Sample

* *

Delete search indexer skillset "searchIndexerSkillset".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillset#String} * * @param skillsetName the name of the skillset to delete * @return a response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono deleteSkillset(String skillsetName) { return withContext(context -> deleteSkillsetWithResponse(skillsetName, null, context) .flatMap(FluxUtil::toMono)); } /** * Deletes a cognitive skillset in an Azure Cognitive Search service. * *

Code Sample

* *

Delete search indexer skillset "searchIndexerSkillset".

* * {@codesnippet com.azure.search.documents.indexes.SearchIndexerAsyncClient.deleteSkillsetWithResponse#SearchIndexerSkillset-boolean} * * @param skillset the {@link SearchIndexerSkillset} to delete. * @param onlyIfUnchanged {@code true} to delete if the {@code skillset} is the same as the current service value. * {@code false} to always delete existing value. * @return a response signalling completion. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteSkillsetWithResponse(SearchIndexerSkillset skillset, boolean onlyIfUnchanged) { Objects.requireNonNull(skillset, "'Skillset' cannot be null."); String etag = onlyIfUnchanged ? skillset.getETag() : null; return withContext(context -> deleteSkillsetWithResponse(skillset.getName(), etag, context)); } Mono> deleteSkillsetWithResponse(String skillsetName, String etag, Context context) { try { return restClient.getSkillsets() .deleteWithResponseAsync(skillsetName, etag, null, null, context) .onErrorMap(MappingUtils::exceptionMapper) .map(Function.identity()); } catch (RuntimeException ex) { return monoError(logger, ex); } } } rockysims/fortressplugin package me.newyith.fortress.util; public class AuthToken extends BaseUUID { //just an object with a UUID } /** * Copyright 2015-2017 * * 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 squash.booking.lambdas.core; import squash.booking.lambdas.core.ILifecycleManager.LifecycleState; import squash.deployment.lambdas.utils.ExceptionUtils; import squash.deployment.lambdas.utils.FileUtils; import squash.deployment.lambdas.utils.IS3TransferManager; import squash.deployment.lambdas.utils.S3TransferManager; import squash.deployment.lambdas.utils.TransferUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.model.CannedAccessControlList; import com.amazonaws.services.s3.model.CopyObjectRequest; import com.amazonaws.services.s3.model.DeleteObjectRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.sns.AmazonSNS; import com.amazonaws.services.sns.AmazonSNSClientBuilder; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Lists; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Optional; import java.util.Properties; import java.util.TimeZone; import java.util.UUID; /** * Manages all interactions with the website pages in the S3 bucket. * *

This manages all modifications to the website pages - which are currently * served from an S3 bucket. * * @author () */ public class PageManager implements IPageManager { private String websiteBucketName; private Region region; private String adminSnsTopicArn; private IBookingManager bookingManager; private ILifecycleManager lifecycleManager; private LambdaLogger logger; private Boolean initialised = false; @Override public void initialise(IBookingManager bookingManager, ILifecycleManager lifecycleManager, LambdaLogger logger) throws Exception { this.logger = logger; websiteBucketName = getEnvironmentVariable("WebsiteBucket"); adminSnsTopicArn = getEnvironmentVariable("AdminSNSTopicArn"); region = Region.getRegion(Regions.fromName(getEnvironmentVariable("AWS_REGION"))); this.bookingManager = bookingManager; this.lifecycleManager = lifecycleManager; initialised = true; } @Override public String refreshPage(String date, List validDates, String apiGatewayBaseUrl, Boolean createDuplicate, List bookings, String revvingSuffix) throws Exception { if (!initialised) { throw new IllegalStateException("The page manager has not been initialised"); } // To workaround S3 ReadAfterUpdate and ReadAfterDelete being only // eventually-consistent, we save new booking page and also a duplicate // with a unique name - and we redirect to this duplicate - which _will_ // have ReadAfterWrite consistency, since it is a new key. String pageGuid = UUID.randomUUID().toString(); logger.log("About to create booking page with guid: " + pageGuid); String newPage = createBookingPage(date, validDates, apiGatewayBaseUrl + "/reservationform", apiGatewayBaseUrl + "/cancellationform", "http://" + websiteBucketName + ".s3-website-" + region + ".amazonaws.com", bookings, pageGuid, revvingSuffix); logger.log("Created booking page with guid: " + pageGuid); logger.log("About to copy booking page to S3"); copyUpdatedBookingPageToS3(date, newPage, createDuplicate ? pageGuid : "", true); logger.log("Copied booking page to S3"); // Create cached booking data as JSON for the Angularjs app to use logger.log("About to create and upload cached booking data to S3"); copyJsonDataToS3("NoScript/" + date, createCachedBookingData(date, validDates, bookings)); logger.log("Uploaded cached booking data to S3"); return pageGuid; } @Override public void refreshAllPages(List validDates, String apiGatewayBaseUrl, String revvingSuffix) throws Exception { if (!initialised) { throw new IllegalStateException("The page manager has not been initialised"); } try { // Upload all bookings pages, cached booking data, famous players data, // and the index page to the S3 bucket. N.B. This should upload for the // most-future date first to ensure all links are valid during the several // seconds the update takes to complete. logger.log("About to refresh S3 website"); logger.log("Using valid dates: " + validDates); logger.log("Using ApigatewayBaseUrl: " + apiGatewayBaseUrl); // Log time to sanity check it does occur at midnight. (_Think_ this // accounts for BST?). N.B. Manual executions may be at other times. logger.log("Current London time is: " + Calendar.getInstance().getTime().toInstant() .atZone(TimeZone.getTimeZone("Europe/London").toZoneId()) .format(DateTimeFormatter.ofPattern("h:mm a"))); ImmutablePair> lifecycleState = lifecycleManager .getLifecycleState(); uploadBookingsPagesToS3(validDates, apiGatewayBaseUrl, revvingSuffix, lifecycleState); logger.log("Uploaded new set of bookings pages to S3"); // Save the valid dates in JSON form logger.log("About to create and upload cached valid dates data to S3"); copyJsonDataToS3("NoScript/validdates", createValidDatesData(validDates)); logger.log("Uploaded cached valid dates data to S3"); logger.log("About to upload famous players data to S3"); uploadFamousPlayers(); logger.log("Uploaded famous players data to S3"); // Remove the now-previous day's bookings page and cached data from S3. // (If this page does not exist then this is a no-op.) String yesterdaysDate = getCurrentLocalDate().minusDays(1).format( DateTimeFormatter.ofPattern("yyyy-MM-dd")); logger.log("About to remove yesterday's booking page and cached data from S3 bucket: " + websiteBucketName + " and key: " + yesterdaysDate + ".html"); IS3TransferManager transferManager = getS3TransferManager(); DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(websiteBucketName, yesterdaysDate + ".html"); AmazonS3 client = transferManager.getAmazonS3Client(); client.deleteObject(deleteObjectRequest); deleteObjectRequest = new DeleteObjectRequest(websiteBucketName, yesterdaysDate + ".json"); client.deleteObject(deleteObjectRequest); logger.log("Removed yesterday's booking page and cached data successfully from S3"); } catch (Exception exception) { logger.log("Exception caught while refreshing S3 booking pages - so notifying sns topic"); getSNSClient() .publish( adminSnsTopicArn, "Apologies - but there was an error refreshing the booking pages in S3. Please refresh the pages manually instead from the Lambda console. The error message was: " + exception.getMessage(), "Sqawsh booking pages in S3 failed to refresh"); // Rethrow throw exception; } } @Override public void uploadFamousPlayers() throws Exception { if (!initialised) { throw new IllegalStateException("The page manager has not been initialised"); } String famousPlayers; try { famousPlayers = IOUtils.toString(PageManager.class .getResourceAsStream("/squash/booking/lambdas/core/FamousPlayers.json")); } catch (IOException e) { logger.log("Exception caught reading FamousPlayers.json file: " + e.getMessage()); throw new Exception("Exception caught reading FamousPlayers.json file"); } logger.log("Uploading famousplayers.json to S3"); copyJsonDataToS3("famousplayers", famousPlayers); logger.log("Uploaded famousplayers.json to S3 successfully"); } /** * Creates and returns the website's booking page for a specified date. * *

This is not private only so that it can be unit-tested. * * @param date the date in YYYY-MM-DD format. * @param validDates the dates for which bookings can be made, in YYYY-MM-DD format. * @param reservationFormGetUrl the Url from which to get a reservation form * @param cancellationFormGetUrl the Url from which to get a cancellation form. * @param s3WebsiteUrl the base Url of the bookings website bucket. * @param bookings the bookings for the specified date. * @param pageGuid the guid to embed within the page - used by AATs. * @param revvingSuffix the suffix to use for the linked css file, used for cache rev-ing. * @throws Exception */ protected String createBookingPage(String date, List validDates, String reservationFormGetUrl, String cancellationFormGetUrl, String s3WebsiteUrl, List bookings, String pageGuid, String revvingSuffix) throws Exception { ImmutablePair> lifecycleState = lifecycleManager .getLifecycleState(); // N.B. we assume that the date is known to be a valid date logger.log("About to create booking page"); logger.log("Lifecycle state is: " + lifecycleState.left.name()); if (lifecycleState.left.equals(LifecycleState.RETIRED)) { logger.log("Lifecycle state forwarding url is: " + lifecycleState.right.get()); } Integer numCourts = 5; // Get dates in longhand format for display on the dropdown DateTimeFormatter longFormatter = DateTimeFormatter.ofPattern("EE, d MMM, yyyy"); DateTimeFormatter shortFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); List validDatesLong = new ArrayList<>(); validDates.stream().forEach((validDate) -> { LocalDate localDate = java.time.LocalDate.parse(validDate, shortFormatter); validDatesLong.add(localDate.format(longFormatter)); }); // In order to merge the day's bookings with our velocity template, we need // to create an object with bookings on a grid corresponding to the html // table. For each grid cell, we need to know whether the cell is booked, // and if it is, the name of the booking, and, if it's a block booking, the // span of the block and whether this cell is interior to the block. logger.log("About to set up velocity context"); List> bookedState = new ArrayList<>(); List> rowSpan = new ArrayList<>(); List> colSpan = new ArrayList<>(); List> isBlockInterior = new ArrayList<>(); List> names = new ArrayList<>(); // First set up default arrays for case of no bookings for (int slot = 1; slot <= 16; slot++) { bookedState.add(new ArrayList<>()); rowSpan.add(new ArrayList<>()); colSpan.add(new ArrayList<>()); isBlockInterior.add(new ArrayList<>()); names.add(new ArrayList<>()); for (int court = 1; court <= numCourts; court++) { bookedState.get(slot - 1).add(false); rowSpan.get(slot - 1).add(1); colSpan.get(slot - 1).add(1); isBlockInterior.get(slot - 1).add(true); names.get(slot - 1).add(""); } } // Mutate cells which are in fact booked for (Booking booking : bookings) { for (int court = booking.getCourt(); court < booking.getCourt() + booking.getCourtSpan(); court++) { for (int slot = booking.getSlot(); slot < booking.getSlot() + booking.getSlotSpan(); slot++) { bookedState.get(slot - 1).set(court - 1, true); rowSpan.get(slot - 1).set(court - 1, booking.getSlotSpan()); colSpan.get(slot - 1).set(court - 1, booking.getCourtSpan()); isBlockInterior.get(slot - 1).set(court - 1, ((court == booking.getCourt()) && (slot == booking.getSlot())) ? false : true); names.get(slot - 1).set(court - 1, booking.getName()); } } } // Create the page by merging the data with the page template VelocityEngine engine = new VelocityEngine(); // Use the classpath loader so Velocity finds our template Properties properties = new Properties(); properties.setProperty("resource.loader", "class"); properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); engine.init(properties); VelocityContext context = new VelocityContext(); context.put("pageGuid", pageGuid); context.put("s3WebsiteUrl", s3WebsiteUrl); context.put("reservationFormGetUrl", reservationFormGetUrl); context.put("cancellationFormGetUrl", cancellationFormGetUrl); context.put("pagesDate", date); context.put("validDates", validDates); context.put("validDatesLong", validDatesLong); context.put("numCourts", numCourts); context.put("timeSlots", getTimeSlotLabels()); context.put("bookedState", bookedState); context.put("rowSpan", rowSpan); context.put("colSpan", colSpan); context.put("isBlockInterior", isBlockInterior); context.put("names", names); context.put("revvingSuffix", revvingSuffix); context.put("lifecycleState", lifecycleState.left.name()); context .put("forwardingUrl", lifecycleState.right.isPresent() ? lifecycleState.right.get() : ""); logger.log("Set up velocity context"); // TODO assert some sensible invariants on data sizes? // Render the page logger.log("About to render booking page"); StringWriter writer = new StringWriter(); Template template = engine.getTemplate("squash/booking/lambdas/BookingPage.vm", "utf-8"); template.merge(context, writer); logger.log("Rendered booking page: " + writer); return writer.toString(); } /** * Returns JSON-encoded booking data for a specified date. * *

This is not private only so that it can be unit-tested. * * @param date the date in YYYY-MM-DD format. * @param validDates the dates for which bookings can be made, in YYYY-MM-DD format. * @param bookings the bookings for the specified date. * @throws Exception */ protected String createCachedBookingData(String date, List validDates, List bookings) throws Exception { ImmutablePair> lifecycleState = lifecycleManager .getLifecycleState(); // N.B. we assume that the date is known to be a valid date logger.log("About to create cached booking data"); logger.log("Lifecycle state is: " + lifecycleState.left.name()); if (lifecycleState.left.equals(LifecycleState.RETIRED)) { logger.log("Lifecycle state forwarding url is: " + lifecycleState.right.get()); } // Encode bookings as JSON // Create the node factory that gives us nodes. JsonNodeFactory factory = new JsonNodeFactory(false); // Create a json factory to write the treenode as json. JsonFactory jsonFactory = new JsonFactory(); ObjectNode rootNode = factory.objectNode(); rootNode.put("date", date); ArrayNode validDatesNode = rootNode.putArray("validdates"); for (int i = 0; i < validDates.size(); i++) { validDatesNode.add(validDates.get(i)); } ArrayNode bookingsNode = rootNode.putArray("bookings"); for (int i = 0; i < bookings.size(); i++) { Booking booking = bookings.get(i); ObjectNode bookingNode = factory.objectNode(); bookingNode.put("court", booking.getCourt()); bookingNode.put("courtSpan", booking.getCourtSpan()); bookingNode.put("slot", booking.getSlot()); bookingNode.put("slotSpan", booking.getSlotSpan()); bookingNode.put("name", booking.getName()); bookingsNode.add(bookingNode); } // This gives the Angularjs app access to the lifecycle state. ObjectNode lifecycleStateNode = rootNode.putObject("lifecycleState"); lifecycleStateNode.put("state", lifecycleState.left.name()); lifecycleStateNode.put("url", lifecycleState.right.isPresent() ? lifecycleState.right.get() : ""); ByteArrayOutputStream bookingDataStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(bookingDataStream); try (JsonGenerator generator = jsonFactory.createGenerator(printStream)) { ObjectMapper mapper = new ObjectMapper(); mapper.writeTree(generator, rootNode); } String bookingData = bookingDataStream.toString(StandardCharsets.UTF_8.name()); logger.log("Created cached booking data: " + bookingData); return bookingData; } /** * Returns JSON-encoded valid-dates data for a specified date. * *

This is not private only so that it can be unit-tested. * * @param validDates the dates for which bookings can be made, in YYYY-MM-DD format. * @throws IOException */ protected String createValidDatesData(List validDates) throws IllegalArgumentException, IOException { // N.B. we assume that the date is known to be a valid date logger.log("About to create cached valid dates data"); // Encode valid dates as JSON // Create the node factory that gives us nodes. JsonNodeFactory factory = new JsonNodeFactory(false); // Create a json factory to write the treenode as json. JsonFactory jsonFactory = new JsonFactory(); ObjectNode rootNode = factory.objectNode(); ArrayNode validDatesNode = rootNode.putArray("dates"); for (int i = 0; i < validDates.size(); i++) { validDatesNode.add(validDates.get(i)); } ByteArrayOutputStream validDatesStream = new ByteArrayOutputStream(); PrintStream printStream = new PrintStream(validDatesStream); try (JsonGenerator generator = jsonFactory.createGenerator(printStream)) { ObjectMapper mapper = new ObjectMapper(); mapper.writeTree(generator, rootNode); } String validDatesString = validDatesStream.toString(StandardCharsets.UTF_8.name()); logger.log("Created cached valid dates data : " + validDatesString); return validDatesString; } private List getTimeSlotLabels() { // First time slot of the day is 10am... // ...so initialise to one time slot (i.e. 45 minutes) earlier logger.log("About to get time slot labels"); LocalTime time = LocalTime.of(9, 15); List timeSlots = new ArrayList<>(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("h:mm a"); for (int slots = 1; slots <= 16; slots++) { time = time.plusMinutes(45); timeSlots.add(time.format(formatter)); } logger.log("Got slot labels: " + timeSlots); return timeSlots; } private void copyJsonDataToS3(String keyName, String jsonToCopy) throws Exception { logger.log("About to copy cached json data to S3"); try { logger.log("Uploading json data to S3 bucket: " + websiteBucketName + " and key: " + keyName + ".json"); byte[] jsonAsBytes = jsonToCopy.getBytes(StandardCharsets.UTF_8); ByteArrayInputStream jsonAsStream = new ByteArrayInputStream(jsonAsBytes); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(jsonAsBytes.length); metadata.setContentType("application/json"); // Direct caches not to satisfy future requests with this data without // revalidation. if (keyName.contains("famousplayers")) { // Famousplayers list is good for a year metadata.setCacheControl("max-age=31536000"); } else { metadata.setCacheControl("no-cache, must-revalidate"); } PutObjectRequest putObjectRequest = new PutObjectRequest(websiteBucketName, keyName + ".json", jsonAsStream, metadata); // Data must be public so it can be served from the website putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead); IS3TransferManager transferManager = getS3TransferManager(); TransferUtils.waitForS3Transfer(transferManager.upload(putObjectRequest), logger); logger.log("Uploaded cached json data to S3 bucket"); } catch (AmazonServiceException ase) { ExceptionUtils.logAmazonServiceException(ase, logger); throw new Exception("Exception caught while copying json data to S3"); } catch (AmazonClientException ace) { ExceptionUtils.logAmazonClientException(ace, logger); throw new Exception("Exception caught while copying json data to S3"); } catch (InterruptedException e) { logger.log("Caught interrupted exception: "); logger.log("Error Message: " + e.getMessage()); throw new Exception("Exception caught while copying json data to S3"); } } private void copyUpdatedBookingPageToS3(String pageBaseName, String page, String uidSuffix, boolean usePrefix) throws Exception { logger.log("About to copy booking page to S3"); String pageBaseNameWithPrefix = usePrefix ? "NoScript/" + pageBaseName : pageBaseName; try { logger.log("Uploading booking page to S3 bucket: " + websiteBucketName + "s3websitebucketname" + " and key: " + pageBaseNameWithPrefix + uidSuffix + ".html"); byte[] pageAsGzippedBytes = FileUtils.gzip(page.getBytes(StandardCharsets.UTF_8), logger); ByteArrayInputStream pageAsStream = new ByteArrayInputStream(pageAsGzippedBytes); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentLength(pageAsGzippedBytes.length); metadata.setContentEncoding("gzip"); metadata.setContentType("text/html"); // Direct caches not to satisfy future requests with this data without // revalidation. metadata.setCacheControl("no-cache, must-revalidate"); PutObjectRequest putObjectRequest = new PutObjectRequest(websiteBucketName, pageBaseNameWithPrefix + uidSuffix + ".html", pageAsStream, metadata); // Page must be public so it can be served from the website putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead); IS3TransferManager transferManager = getS3TransferManager(); TransferUtils.waitForS3Transfer(transferManager.upload(putObjectRequest), logger); logger.log("Uploaded booking page to S3 bucket"); if (uidSuffix.equals("")) { // Nothing to copy - so return logger.log("UidSuffix is empty - so not creating duplicate page"); return; } // N.B. We copy from hashed key to non-hashed (and not vice versa) // to ensure consistency logger.log("Copying booking page in S3 bucket: " + websiteBucketName + " and key: " + pageBaseNameWithPrefix + ".html"); CopyObjectRequest copyObjectRequest = new CopyObjectRequest(websiteBucketName, pageBaseNameWithPrefix + uidSuffix + ".html", websiteBucketName, pageBaseNameWithPrefix + ".html"); copyObjectRequest.setCannedAccessControlList(CannedAccessControlList.PublicRead); // N.B. Copied object will get same metadata as the source (e.g. the // cache-control header etc.) TransferUtils.waitForS3Transfer(transferManager.copy(copyObjectRequest), logger); logger.log("Copied booking page successfully in S3"); } catch (AmazonServiceException ase) { ExceptionUtils.logAmazonServiceException(ase, logger); throw new Exception("Exception caught while copying booking page to S3"); } catch (AmazonClientException ace) { ExceptionUtils.logAmazonClientException(ace, logger); throw new Exception("Exception caught while copying booking page to S3"); } catch (InterruptedException e) { logger.log("Caught interrupted exception: "); logger.log("Error Message: " + e.getMessage()); throw new Exception("Exception caught while copying booking page to S3"); } } private void uploadBookingsPagesToS3(List validDates, String apiGatewayBaseUrl, String revvingSuffix, ImmutablePair> lifecycleState) throws Exception { logger.log("About to upload booking page for each valid date"); logger.log("Lifecycle state is: " + lifecycleState.left.name()); if (lifecycleState.left.equals(LifecycleState.RETIRED)) { logger.log("Lifecycle state forwarding url is: " + lifecycleState.right.get()); } String currentDate = validDates.get(0); logger.log("About to refresh index pages for: " + currentDate); refreshIndexPages(currentDate); logger.log("Refreshed index pages"); // Dates will be in time order. We want to iterate in reverse time order to // ensure that we refresh the most-future page first, which ensures all // links remain valid during the update process. List bookings; for (String validDate : Lists.reverse(validDates)) { logger.log("About to upload booking page for: " + validDate); bookings = bookingManager.getBookings(validDate, false); refreshPage(validDate, validDates, // Still in forward time order apiGatewayBaseUrl, false, bookings, revvingSuffix); } logger.log("Uploaded booking page for each valid date"); } private void refreshIndexPages(String currentDate) throws Exception { // These 2 pages will redirect to the current day's page. Today.html is // there to handle case where a javascript-disabled client has a booking // page open which has a link to an earlier page that has now expired (which // means at least one midnight must have passed since they fetched the // page). It also handles other generally-messed-up urls for // javascript-disabled clients. Noscript.html is there for the AngularApp // to redirect to when javascript is disabled. It differs from Today.html // only by not showing a momentary redirect message. logger.log("About to refresh index pages"); String todayIndexPage = createIndexPage("http://" + websiteBucketName + ".s3-website-" + region + ".amazonaws.com?selectedDate=" + currentDate + ".html", true); String noscriptIndexPage = createIndexPage("http://" + websiteBucketName + ".s3-website-" + region + ".amazonaws.com?selectedDate=" + currentDate + ".html", false); logger.log("About to upload index pages"); copyUpdatedBookingPageToS3("today", todayIndexPage, "", true); // Also copy to root of bucket - as error and index page must be there. copyUpdatedBookingPageToS3("today", todayIndexPage, "", false); copyUpdatedBookingPageToS3("noscript", noscriptIndexPage, "", true); logger.log("Uploaded index pages"); logger.log("Refreshed index pages"); } /** * Creates and returns the website's index page. * *

This is not private only so that it can be unit-tested. * * @param redirectUrl the Url of the booking page for the current date. * @param showRedirectMessage whether to show a redirect error message to the user */ protected String createIndexPage(String redirectUrl, Boolean showRedirectMessage) { logger.log("About to create the index page"); // Create the page by merging the data with the page template VelocityEngine engine = new VelocityEngine(); // Use the classpath loader so Velocity finds our template Properties properties = new Properties(); properties.setProperty("resource.loader", "class"); properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); engine.init(properties); VelocityContext context = new VelocityContext(); context.put("redirectUrl", redirectUrl); context.put("showRedirectMessage", showRedirectMessage); // Render the page StringWriter writer = new StringWriter(); Template template = engine.getTemplate("squash/booking/lambdas/IndexPage.vm", "utf-8"); template.merge(context, writer); logger.log("Rendered index page: " + writer); return writer.toString(); } /** * Returns an SNS client. * *

This method is provided so unit tests can mock out SNS. */ protected AmazonSNS getSNSClient() { // Use a getter here so unit tests can substitute a mock client AmazonSNS client = AmazonSNSClientBuilder.standard().withRegion(region.getName()).build(); return client; } /** * Returns a named environment variable. * @throws Exception */ protected String getEnvironmentVariable(String variableName) throws Exception { // Use a getter here so unit tests can substitute a mock value. // We get the value from an environment variable so that CloudFormation can // set the actual value when the stack is created. String environmentVariable = System.getenv(variableName); if (environmentVariable == null) { logger.log("Environment variable: " + variableName + " is not defined, so throwing."); throw new Exception("Environment variable: " + variableName + " should be defined."); } return environmentVariable; } /** * Returns an IS3TransferManager. * *

This method is provided so unit tests can mock out S3. */ protected IS3TransferManager getS3TransferManager() { // Use a getter here so unit tests can substitute a mock transfermanager return new S3TransferManager(); } /** * Returns the current London local date. */ protected LocalDate getCurrentLocalDate() { // Use a getter here so unit tests can substitute a different date. // This gets the correct local date no matter what the user's device // system time may say it is, and no matter where in AWS we run. return BookingsUtilities.getCurrentLocalDate(); } }src/main/java/de/tetris/controller/gui/InfodialogController.java package de.tetris.controller.gui; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import lombok.extern.slf4j.Slf4j; import java.net.URL; import java.util.ResourceBundle; /** * @author (msg systems ag) 2017 */ @Slf4j public class InfodialogController implements Initializable { @Override public void initialize(URL location, ResourceBundle resources) { } @FXML public void closeDialog(ActionEvent actionEvent) { log.debug("Close Infodialog"); ((Node)(actionEvent.getSource())).getScene().getWindow().hide(); } } package net.termat.gtfsviewer.gtfs.model; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import java.util.List; @Dao public interface GFareAttributeDao { @Query("select * from gfareattribute") List findAll(); @Insert void insert(GFareAttribute a); @Insert(onConflict = OnConflictStrategy.IGNORE) void insertAll(List a); @Query("DELETE FROM gfareattribute") public void deleteAll(); @Delete void delete(List list); @Query("select * from gfareattribute where data_id=:data_id") List getDataAtDataId(String data_id); } /** * */ /** * @author coolkids * */ package org.trurlex.strategy;halu5071/edwards1-10 package io.moatwel.crypto.eddsa.ed25519; import io.moatwel.crypto.eddsa.Coordinate; import io.moatwel.crypto.eddsa.EncodedCoordinate; import io.moatwel.util.HexEncoder; import org.junit.Test; import java.math.BigInteger; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class EncodedCoordinateEd25519Test { @Test public void success_Decode_1() { EncodedCoordinate encoded = new EncodedCoordinateEd25519(HexEncoder.getBytes("762115b81aae8ab7a87e5d205ee64173ffc2666721b9bed118c4af49a2928601")); Coordinate coordinate = encoded.decode(); assertThat(coordinate.getInteger(), is(new BigInteger("690082385501664621091624779109445751481919948714921317484605800924977635702"))); } @Test public void success_Decode_2() { EncodedCoordinate encoded = new EncodedCoordinateEd25519(HexEncoder.getBytes("f29829ffdb3b229fd05dc7f83c1de7ab041cbbeb4156d7442f3e23de19c80701")); Coordinate coordinate = encoded.decode(); assertThat(coordinate.getInteger(), is(new BigInteger("466061824698566712370651010976869652622695944005000025458774533499639142642"))); } @Test public void success_Decode_3() { EncodedCoordinate encoded = new EncodedCoordinateEd25519(HexEncoder.getBytes("f193d7d58eb5ba3482c54b4dad4f9685726b2957cdf363fd4c6ed5a85e98750c")); Coordinate coordinate = encoded.decode(); assertThat(coordinate.getInteger(), is(new BigInteger("5635526907038231869349643959556202269054548263441123979990494297630113764337"))); } @Test public void success_Decode_4() { EncodedCoordinate encoded = new EncodedCoordinateEd25519(HexEncoder.getBytes("6e89e4b5973ab73a1538714746c77fd09f33aeeebdf11daffd94d6ba940ae108")); Coordinate coordinate = encoded.decode(); assertThat(coordinate.getInteger(), is(new BigInteger("4016116405453202388474865418908325977025123430952466464539276325205466974574"))); } @Test public void success_Decode_5() { EncodedCoordinate encoded = new EncodedCoordinateEd25519(HexEncoder.getBytes("df2780568c569c6713ed48bc7d96e04a93fdda45237bfc34afe40518b2635f02")); Coordinate coordinate = encoded.decode(); assertThat(coordinate.getInteger(), is(new BigInteger("1073164242609237669094038971348660945523306704071742924708751717996060223455"))); } } package ai.labs.backupservice; import io.swagger.annotations.Api; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ResponseHeader; import javax.ws.rs.*; import javax.ws.rs.core.Response; import java.io.InputStream; import java.net.URI; /** * @author ginccc */ @Api(value = "backup") @Path("/backup/export") public interface IRestExportService { @GET @Produces("application/zip") @Path("{botFilename}") @ApiResponse(code = 200, response = InputStream.class, message = "returns bot zip file as application/zip") Response getBotZipArchive(@PathParam("botFilename") String botFilename); @POST @Path("{botId}") @ApiResponse(code = 200, responseHeaders = { @ResponseHeader(name = "location", response = URI.class) }, message = "returns location of the exported ZIP file to be downloaded") Response exportBot(@PathParam("botId") String botId, @ApiParam(name = "botVersion", required = true, format = "integer", example = "1") @QueryParam("botVersion") @DefaultValue("1") Integer botVersion); } auniverseaway/adobe-dx-1bundles/testing-extensions/src/test/java/com/adobe/dx/testing/extensions/ResponsiveContextTest.java /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ Copyright 2020 Adobe ~ ~ 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.adobe.dx.testing.extensions; import static org.junit.jupiter.api.Assertions.assertEquals; import com.adobe.dx.inlinestyle.InlineStyleWorker; import com.adobe.dx.responsive.Breakpoint; import com.adobe.dx.testing.AbstractInlineStyleWorkerTest; import org.apache.sling.api.SlingHttpServletRequest; import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.Test; public class ResponsiveContextTest extends AbstractInlineStyleWorkerTest { @Override protected InlineStyleWorker getWorker() { return WORKER_TO_TEST; } @Test protected void testBasics() { assertEquals("checkThis", getWorker().getKey()); assertEquals("FOO", getDeclaration("mobile")); assertEquals("BAR", getRule("BAR", "id")); } final static InlineStyleWorker WORKER_TO_TEST = new InlineStyleWorker() { @Override public String getKey() { return "checkThis"; } @Override public @Nullable String getDeclaration(Breakpoint breakpoint, SlingHttpServletRequest request) { return "FOO"; } @Override public @Nullable String getRule(@Nullable Breakpoint breakpoint, @Nullable String id, SlingHttpServletRequest request) { return "BAR"; } }; } 1-10 /*- * ============LICENSE_START========================================== * OPENECOMP - DCAE * =================================================================== * Copyright (c) 2017 AT&T Intellectual Property. 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. * ============LICENSE_END============================================ */ package org.openecomp.ncomp.sirius.manager; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.HashMap; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.eclipse.jetty.http.ssl.SslContextFactory; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.server.ssl.SslSelectChannelConnector; import org.eclipse.jetty.util.B64Code; import org.eclipse.jetty.util.StringUtil; import org.json.JSONArray; import org.json.JSONObject; import org.openecomp.entity.EcompSubComponentInstance; import org.openecomp.logger.EcompException; import org.openecomp.logger.EcompMessageEnum; import org.openecomp.logger.StatusCodeEnum; import com.att.eelf.i18n.EELFResourceManager; import org.openecomp.ncomp.sirius.manager.logging.ManagementServerMessageEnum; import org.openecomp.ncomp.sirius.manager.logging.NcompLogger; import org.openecomp.ncomp.utils.PropertyUtil; import org.openecomp.ncomp.webservice.utils.JsonUtils; public class Jetty8Server { public static final Logger logger = Logger.getLogger(Jetty8Server.class); static final NcompLogger ecomplogger = NcompLogger.getNcompLogger(); Server server; private SelectChannelConnector conn1; private int actualport; HashMap handlerMap = new HashMap(); ServerThread thread; private Properties props; class Jetty8ServerHandler extends AbstractHandler { private HashMap method2action = new HashMap(); { method2action.put("POST", "CREATE"); method2action.put("PUT", "UPDATE"); method2action.put("GET", "LIST"); method2action.put("DELETE", "DELETE"); } @Override public void handle(String contextPath, Request jRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (request.getMethod().equals("OPTIONS")) { setResponseHeaders(response); response.setHeader("Allow", "HEAD,GET,PUT,DELETE,OPTIONS"); response.setStatus(200); jRequest.setHandled(true); return; } String userName = checkAuth(contextPath,jRequest); if (userName == null) { setResponseHeaders(response); response.setStatus(403); jRequest.setHandled(true); logger.info("Authorization not valid"); return; } if (request.getRemoteHost() != null) ecomplogger.setRemoteHost(request.getRemoteHost()); if (userName != null) ecomplogger.setPartnerName(userName); ecomplogger.startUnknownAuditEvent(contextPath); String requestId = request.getHeader("X-ECOMP-RequestID"); if (requestId == null) { ecomplogger.newRequestId(); ecomplogger.missingRequestId(request); } else { ecomplogger.setRequestId(requestId); } String clientVersion = request.getHeader("X-ECOMP-Client-Version"); if (clientVersion == null) clientVersion = "UNKNOWN"; ecomplogger.setInstanceId(EcompSubComponentInstance.getServerName() + ":" + props.getProperty("server.port") + contextPath); String action = request.getHeader("action"); if (action == null) { String method = request.getMethod(); action = method2action.get(method); } logger.debug("new request:" + contextPath + " " + request.getMethod() + " " + action); Object res = null; String contextPath1 = null; IRequestHandler handler = null; for (String prefix : handlerMap.keySet()) { if (contextPath.equals(prefix) || contextPath.startsWith(prefix + "/")) { contextPath1 = contextPath.substring(prefix.length()); handler = handlerMap.get(prefix); } } if (handler == null) { logger.warn("request with no handler: " + contextPath); handleError(jRequest,response,ManagementServerMessageEnum.MANAGEMENT_SERVER_WEB_REQUEST_WITHOUT_HANDLER,contextPath); return; } try { if ("application/json".equals(jRequest.getContentType()) || jRequest.getContentType() == null) { // ByteArrayOutputStream s = new ByteArrayOutputStream(); // FileUtils.copyStream(request.getInputStream(), s); // System.err.println(s); // JSONObject json = new JSONObject(new String(s.toByteArray())); JSONObject json = JsonUtils.stream2json(request.getInputStream()); res = handler.handleJson(userName, action, contextPath1, json, req2context(contextPath, jRequest, userName), clientVersion); } else { handleError(jRequest,response,ManagementServerMessageEnum.MANAGEMENT_SERVER_WEB_REQUEST_UNSUPPORTED_CONTENT_TYPE,jRequest.getContentType()); return; } } catch (EcompException e) { handleError(jRequest, response, e.msgEnum, e.args); return; } catch (Exception e) { handleError(jRequest,response,ManagementServerMessageEnum.MANAGEMENT_SERVER_WEB_REQUEST_UNKNOWN_EXCEPTION,e.getMessage()); return; } if (res != null) { setResponseHeaders(response); if (res instanceof JSONObject) { JSONObject json1 = (JSONObject) res; PrintWriter w = response.getWriter(); w.append(json1.toString(2)); w.close(); } else if (res instanceof JSONArray) { JSONArray json1 = (JSONArray) res; PrintWriter w = response.getWriter(); w.append(json1.toString(2)); w.close(); } else { handleError(jRequest,response,ManagementServerMessageEnum.MANAGEMENT_SERVER_WEB_REQUEST_UNKNOWN_RETURN_CLASS,res.getClass().getName()); return; } } response.setStatus(HttpServletResponse.SC_OK); jRequest.setHandled(true); ecomplogger.recordAuditEventEnd(); } private void setResponseHeaders(HttpServletResponse response) { for (Object k : props.keySet()) { if (k instanceof String) { String s = (String) k; if (! s.startsWith("server.header")) continue; response.setHeader(s.substring(14), props.getProperty(s)); } } } private void handleError(Request jRequest, HttpServletResponse response, EcompMessageEnum msg, String... args) throws IOException { try { ecomplogger.warn(msg, args); ecomplogger.recordAuditEventEnd(StatusCodeEnum.ERROR, msg, args); String s = EELFResourceManager.getIdentifier(msg); // Assume s ends in something like 4015W int httpErrorCode = 501; try { String error = s.substring(s.length()-5,s.length()-2); httpErrorCode = Integer.parseInt(error); } catch (Exception e) { } response.sendError(httpErrorCode, EELFResourceManager.format(msg,args)); } catch (Exception e) { ManagementServerUtils.printStackTrace(e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,e.getMessage()); } jRequest.setHandled(true); } private JSONObject req2context(String contextPath, Request jRequest, String user) { JSONObject c = new JSONObject(); c.put("remoteIp", jRequest.getRemoteAddr()); c.put("user", user); JSONObject p = new JSONObject(); for (Object k : jRequest.getParameterMap().keySet()) { if (k instanceof String) { String kk = (String) k; p.put(kk, jRequest.getParameter(kk)); } } c.put("parameters", p); c.put("path", contextPath); return c; } } public Jetty8Server(String propertyFileName) { try { props = PropertyUtil.getPropertiesFromClasspath(propertyFileName); String portString = props.getProperty("server.port"); if (portString == null) return; int port = Integer.parseInt(portString); server = new Server(); if (props.containsKey("server.keyStore")) { @SuppressWarnings("deprecation") SslContextFactory f = new SslContextFactory(props.getProperty("server.keyStore")); f.setKeyStorePassword(props.getProperty("server.keyStorePassword")); f.setKeyManagerPassword(props.getProperty("server.keyManagerPassword")); f.setTrustStore(props.getProperty("server.trustStore")); f.setTrustStorePassword(props.getProperty("server.trustStorePassword")); logger.info("HTTPS excluded protocols: " + Arrays.asList(f.getExcludeProtocols())); f.addExcludeProtocols("SSLv1", "SSLv2", "SSLv3"); logger.info("HTTPS excluded protocols after fix: " + Arrays.asList(f.getExcludeProtocols())); SslSelectChannelConnector c = new SslSelectChannelConnector(f); c.setPort(port); c.setMaxIdleTime(30000); server.addConnector(c); conn1 = c; logger.info("Adding HTTPS on port: " + port); } else { SelectChannelConnector c = new SelectChannelConnector(); c.setPort(port); server.addConnector(c); conn1 = c; logger.info("Adding HTTP on port: " + port); } server.setHandler(new Jetty8ServerHandler()); // secondary port (assume HTTP) portString = props.getProperty("server.port2"); if (portString != null) { port = Integer.parseInt(portString); SelectChannelConnector c = new SelectChannelConnector(); c.setPort(port); server.addConnector(c); logger.info("Adding HTTP on secondary port: " + port); } } catch (Exception e) { ManagementServerUtils.printStackTrace(e); } } /** * In unit testing, we want to start on an operating system selected port * number, so we configure a port number of 0, and then use this to find out * the real port number */ public int getPort() { return (actualport); } /** * In unit testing, we want to shut down the server */ public void stop() { try { server.stop(); } catch (Exception e) { } } public void start() { thread = new ServerThread(); } public void join() { try { if (server == null) { logger.warn("Ignore Join: server is NULL"); return; } server.start(); actualport = conn1.getLocalPort(); server.join(); } catch (Exception e) { ManagementServerUtils.printStackTrace(e); } } public static void main(String[] args) { new Jetty8Server("server.properties"); } public void add(String prefix, IRequestHandler h) { handlerMap.put(prefix, h); } class DummyRequestHandler implements IRequestHandler { @Override public Object handleJson(String userName, String action, String resourcePath, JSONObject json, JSONObject context, String clientVersion) { logger.debug("handleJson: user=" + userName + " action=" + action + " path=" + resourcePath + " json=" + json); return null; } @Override public Object handleBinary(String userName, String action, String resourcePath, InputStream in) { logger.info("handleBinary: user=" + userName + " action=" + action + " path=" + resourcePath); return null; } } private class ServerThread implements Runnable { public ServerThread() { Thread t = new Thread(this, "jetty server"); t.setDaemon(true); t.start(); } @Override public void run() { try { server.start(); actualport = conn1.getLocalPort(); server.join(); } catch (Exception e) { ManagementServerUtils.printStackTrace(e); } } } private String checkAuth(String contextPath, Request r) { if (props.containsKey("server.noauth."+ contextPath)) return "none"; String s = r.getHeader("Authorization"); if (s == null) { logger.warn("Authorization failed: No header"); return null; } String a[] = s.split(" "); if (a.length != 2) { logger.warn("Authorization failed: Bad header"); return null; } String s1 = null; try { s1 = B64Code.decode(a[1], StringUtil.__ISO_8859_1); } catch (UnsupportedEncodingException e) { logger.warn("Authorization failed: Bad header:" + e); return null; } int i = s1.indexOf(":"); if (i == -1) { logger.warn("Authorization failed: Bad header"); return null; } String user = s1.substring(0, i); String pw = s1.substring(i + 1); String pw2 = props.getProperty("server.user." + user); boolean valid = pw.equals(JavaHttpClient.decryptPassword(pw2)); if (!valid) logger.warn("Authorization: bad PW: " + user + "@" + r.getRemoteAddr() + " " + pw.substring(0, 2)); return valid ? user : null; } } /* * 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. */ /** * * @author luisf */ package game; import java.awt.Dimension; import javax.swing.*; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiSystem; import javax.sound.midi.MidiUnavailableException; import javax.sound.midi.Sequencer; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; public class Main { public static void main(String[] args) throws MidiUnavailableException, FileNotFoundException, IOException, InvalidMidiDataException, UnsupportedAudioFileException, LineUnavailableException { Sequencer sequencer = MidiSystem.getSequencer(); sequencer.open(); InputStream music = new BufferedInputStream(new FileInputStream(new File("images/Music.mid"))); sequencer.setSequence(music); sequencer.start(); Map map = new Map("Tank Game"); map.setPreferredSize(new Dimension(1280, 950)); map.setMaximumSize(new Dimension(1280, 950)); map.setMinimumSize(new Dimension(1280, 950)); //map.pack(); map.setResizable(false); map.run(); map.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } 1-10 package ru.job4j.calculate; /** * Calculate. * It prints string to console. * * @author */ public class Calculate { /** * Method main. * The point of enter to program. * * @param args - array String. */ public static void main(final String[] args) { System.out.println("Hello World"); } /** * Method echo. * * @param name Your name. * @return Echo plus your name. */ public final String echo(final String name) { return "Echo, echo, echo : " + name; } } /* * Zynaptic Reaction - An asynchronous programming framework for Java. * * Copyright (c) 2009-2019, Zynaptic Limited. * * 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. * * Please visit www.zynaptic.com or contact if you need * additional information or have any questions. */ package com.zynaptic.reaction.test.core; import com.zynaptic.reaction.Deferred; import com.zynaptic.reaction.Reactor; import com.zynaptic.reaction.Signal; import com.zynaptic.reaction.Signalable; import com.zynaptic.reaction.Timeable; import com.zynaptic.reaction.SignalContextException; /** * This aggregation class encapsulates all the tests which are required to * verify correct functioning of the reactor signal code. * * @author */ public class SignalTests { // Interval between test 'tick' callbacks in milliseconds. private static final int TICK_INTERVAL = 250; /** * Test single signal subscription, generation and unsubscription. Legacy test * harness does not include strong generic type checking. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static class SingleSignalCallback implements Timeable, Signalable { private Reactor reactor; private Deferred deferredDone; private int i = 0; private int callbackCount = 0; private String magicData1 = "Test data 1"; private Signal testSignal; /* * Timer tick method - used to start up test and generate signal events. */ public void onTick(Object data) { // On first call, register for signal callbacks and then generate // signal. if (i == 0) { System.out.println("Reactor : Testing single signal callbacks."); Object[] params = (Object[]) data; reactor = (Reactor) params[0]; deferredDone = (Deferred) params[1]; testSignal = reactor.newSignal(); try { reactor.runTimerOneShot(this, TICK_INTERVAL, null); testSignal.subscribe(this); testSignal.signal(magicData1); } catch (Exception error) { deferredDone.errback(error); } } // On second callback, check that the signal has fired once then try // to re-subscribe to the same signal. else if (i == 1) { if (callbackCount != 1) { deferredDone.errback(new Exception("Incorrect number of signal callbacks detected.")); } else { try { reactor.runTimerOneShot(this, TICK_INTERVAL, null); testSignal.subscribe(this); testSignal.signal(magicData1); } catch (Exception error) { deferredDone.errback(error); } } } // On third callback, check that the signal has fired once then // unsubscribe from the signal. else if (i == 2) { if (callbackCount != 2) { deferredDone.errback(new Exception("Incorrect number of signal callbacks detected.")); } else { try { reactor.runTimerOneShot(this, TICK_INTERVAL, null); testSignal.unsubscribe(this); testSignal.signal(magicData1); } catch (Exception error) { deferredDone.errback(error); } } } // On fourth callback, check that the signal did not fire and // attempt to // unsubscribe again. else if (i == 3) { if (callbackCount != 2) { deferredDone.errback(new Exception("Incorrect number of signal callbacks detected.")); } else { try { reactor.runTimerOneShot(this, TICK_INTERVAL, null); testSignal.unsubscribe(this); testSignal.signal(magicData1); } catch (Exception error) { deferredDone.errback(error); } } } // On final callback, check that the signal did not fire and exit to // the // test fixture. else { if (callbackCount != 2) { deferredDone.errback(new Exception("Incorrect number of signal callbacks detected.")); } else { deferredDone.callback(null); } } i++; } /* * Signal callback method. This checks for valid callback data and ups the * callback counter. */ public void onSignal(Signal signalId, Object data) { if (!(signalId.equals(testSignal))) { deferredDone.errback(new Exception("Signal callback with incorrect signal ID.")); } else if (data != magicData1) { deferredDone.errback(new Exception("Signal callback with invalid data.")); } else { callbackCount++; System.out.println(" Valid signal callback : " + callbackCount); } } } /** * Test exception generation for invalid operations. Legacy test harness does * not include strong generic type checking. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static class InvalidOperationExceptions implements Timeable, Signalable { private Reactor reactor; private Deferred deferredDone; private int i = 0; private int callbackCount = 0; private String magicData1 = "Test data 1"; private String magicData2 = "Test data 2"; private Signal testSignal1; private Signal testSignal2; /* * Timer tick method - used to start up test and generate signal events. */ public void onTick(Object data) { // On first call, register for signal callbacks and then generate // signal. if (i == 0) { System.out.println("Reactor : Testing signal exceptions for invalid operations."); Object[] params = (Object[]) data; reactor = (Reactor) params[0]; deferredDone = (Deferred) params[1]; testSignal1 = reactor.newSignal(); testSignal2 = reactor.newSignal(); // Add a signal callback so that we can test signal context // exceptions. try { reactor.runTimerOneShot(this, TICK_INTERVAL, null); testSignal1.subscribe(this); testSignal2.subscribe(this); testSignal1.signal(magicData1); } catch (Exception error) { deferredDone.errback(error); } } // On second callback test has completed. Notify test harness. else { if (callbackCount != 2) { deferredDone.errback(new Exception("Incorrect number of signal callbacks detected.")); } else { deferredDone.callback(null); } } i++; } /* * Signal callback method. This attempts to subscribe and unsubscribe the * signalable and fire a new signal from the signal callback context. */ public void onSignal(Signal signalId, Object data) { // First signal callback should be for signal 1. if (i == 1) { if (!(signalId.equals(testSignal1))) { deferredDone.errback(new Exception("Signal callback with incorrect signal ID.")); } else if (data != magicData1) { deferredDone.errback(new Exception("Signal callback with invalid data.")); } else { callbackCount++; System.out.println(" Valid signal callback : " + callbackCount); // We should not be able to call the subscribeSignalable // method in // this // context. try { testSignal1.subscribe(this); deferredDone.errback(new Exception("Expected SignalContextException in signal callback.")); } catch (SignalContextException error) { // This is expected. } catch (Exception error) { deferredDone.errback(new Exception("Unexpected exception in signal callback.")); } // We should not be able to call the unsubscribeSignalable // method in // this context. try { testSignal1.unsubscribe(this); deferredDone.errback(new Exception("Expected SignalContextException in signal callback.")); } catch (SignalContextException error) { // This is expected. } catch (Exception error) { deferredDone.errback(new Exception("Unexpected exception in signal callback.")); } // We should be able to fire a new signal in this context. try { testSignal2.signal(magicData2); } catch (Exception error) { deferredDone.errback(new Exception("Unexpected exception in signal callback.")); } } } // Second signal callback should be for signal 2. else { if (!(signalId.equals(testSignal2))) { deferredDone.errback(new Exception("Signal callback with incorrect signal ID.")); } else if (data != magicData2) { deferredDone.errback(new Exception("Signal callback with invalid data.")); } else { callbackCount++; System.out.println(" Valid signal callback : " + callbackCount); } } i++; } } /** * Test final signal operation. Legacy test harness does not include strong * generic type checking. */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static class FinalSignalCallback implements Timeable, Signalable { private Reactor reactor; private Deferred deferredDone; private int i = 0; private int callbackCount = 0; private String magicData1 = "Test data 1"; private Signal testSignal; /* * Timer tick method - used to start up test and generate signal events. */ public void onTick(Object data) { // On first call, register for signal callbacks and then generate // signal. if (i == 0) { System.out.println("Reactor : Testing final signal callbacks."); Object[] params = (Object[]) data; reactor = (Reactor) params[0]; deferredDone = (Deferred) params[1]; testSignal = reactor.newSignal(); try { reactor.runTimerOneShot(this, TICK_INTERVAL, null); testSignal.subscribe(this); testSignal.signal(magicData1); } catch (Exception error) { deferredDone.errback(error); } } // On second callback, check that the signal has fired once then // perform a // final signal callback. else if (i == 1) { if (callbackCount != 1) { deferredDone.errback(new Exception("Incorrect number of signal callbacks detected.")); } else { try { reactor.runTimerOneShot(this, TICK_INTERVAL, null); testSignal.signalFinalize(magicData1); } catch (Exception error) { deferredDone.errback(error); } } } // On third callback, check that the signal has fired once then // attempt to // signal again. else if (i == 2) { if (callbackCount != 2) { deferredDone.errback(new Exception("Incorrect number of signal callbacks detected.")); } else { try { reactor.runTimerOneShot(this, TICK_INTERVAL, null); testSignal.signal(magicData1); } catch (Exception error) { deferredDone.errback(error); } } } // On final callback, check that the signal did not fire and exit to // the // test fixture. else { if (callbackCount != 2) { deferredDone.errback(new Exception("Incorrect number of signal callbacks detected.")); } else { deferredDone.callback(null); } } i++; } /* * Signal callback method. This checks for valid callback data and ups the * callback counter. */ public void onSignal(Signal signalId, Object data) { if (!(signalId.equals(testSignal))) { deferredDone.errback(new Exception("Signal callback with incorrect signal ID.")); } else if (data != magicData1) { deferredDone.errback(new Exception("Signal callback with invalid data.")); } else { callbackCount++; System.out.println(" Valid signal callback : " + callbackCount); } } } } cliff363825/TwentyFour package com.onevgo.j2se.nio.nonblocking; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.charset.StandardCharsets; import java.util.Scanner; public class UDPClient { public static void main(String[] args) throws IOException { DatagramChannel dc = DatagramChannel.open(); dc.configureBlocking(false); ByteBuffer buf = ByteBuffer.allocate(1024); Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String s = scanner.next(); buf.put(s.getBytes(StandardCharsets.UTF_8)); buf.flip(); dc.send(buf, new InetSocketAddress("127.0.0.1", 9898)); buf.clear(); } dc.close(); } } package edu.vanderbilt.accre.laurelin.root_proxy; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.util.concurrent.Future; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.tukaani.xz.SeekableXZInputStream; import edu.vanderbilt.accre.laurelin.root_proxy.io.FileInterface; public class XZDecompressionWrapper implements FileInterface { private static final Logger logger = LogManager.getLogger(); private class BackingFd extends org.tukaani.xz.SeekableInputStream { private RandomAccessFile fd; protected BackingFd(String path) throws FileNotFoundException { fd = new RandomAccessFile(path, "r"); } @Override public long length() throws IOException { return fd.length(); } @Override public long position() throws IOException { return fd.getFilePointer(); } @Override public void seek(long pos) throws IOException { fd.seek(pos); } @Override public int read() throws IOException { return fd.read(); } @Override public int read(byte b[], int off, int len) throws IOException { return fd.read(b, off, len); } } private SeekableXZInputStream fd; private RandomAccessFile truthFD; synchronized ByteBuffer backingRead(long offset, int len) throws IOException { // the XZInput Stream isn't thread-safe, so synchronize all reads byte[] byteBuf = new byte[len]; fd.seek(offset); fd.read(byteBuf, 0, len); if (truthFD != null) { byte[] truthByteBuf = new byte[len]; truthFD.seek(offset); truthFD.read(truthByteBuf, 0, len); /* * Compare the pristine with the minified. Since the minified has * a lot of zero'd out bytes, we need to go one-by-one to exclude * those from the comparison. */ for (int i = 0; i < len; i += 1) { byte m = byteBuf[i]; byte p = truthByteBuf[i]; boolean minifiedIsZero = (m == '\0'); boolean pristineIsZero = (p == '\0'); boolean minifiedMatchesPristine = (m == p); if (!minifiedIsZero && !minifiedMatchesPristine) { // if ( (m != '\0') && (m != p)) { String truthStr = new String(); String xzStr = new String(); final int CONTEXT = 10; int j = (i > CONTEXT) ? (i - CONTEXT) : 0; for (int k = j; k <= i; k += 1) { truthStr += Byte.toString(truthByteBuf[k]) + " "; xzStr += Byte.toString(byteBuf[k]) + " "; } logger.fatal("Mismatching pristine and minified reads at off " + (offset + i)); logger.fatal(" pristine: " + truthStr); logger.fatal(" minified: " + xzStr); throw new RuntimeException("Pristine and minified don't match"); } } } return ByteBuffer.wrap(byteBuf); } public XZDecompressionWrapper(String path) throws IOException { String truthPath = path.replace("testdata/minified", "testdata/pristine").replace(".xz", ""); File inFile = new File(truthPath); if (inFile.isFile()) { truthFD = new RandomAccessFile(truthPath, "r"); } else { truthFD = null; } fd = new SeekableXZInputStream(new BackingFd(path)); } @Override public ByteBuffer read(long offset, long len) throws IOException { assert len == (int) len; return backingRead(offset, (int) len); } @Override public ByteBuffer[] readv(int[] offsets, int[] lens) throws IOException { return null; } @Override public Future readAsync(int offset, int len) throws IOException { return null; } @Override public Future[] readvAsync(int[] offsets, int[] lens) throws IOException { return null; } @Override public void close() throws IOException { fd.close(); } @Override public long getLimit() throws IOException { return fd.length(); } } package Stream; import java.util.ArrayList; import java.util.List; /** * @program: my-design-patterns * @description: * @author: Rui.Zhou * @create: 2019-07-03 16:50 **/ public class Demo01List { public static void main(String[] args) { //创建一个List储存姓名 List list = new ArrayList<>(); list.add("张三"); list.add("张二娃"); list.add("张五娃"); list.add("李四"); list.add("李三贵"); list.add("周志伟"); //对List中的元素进行过滤,只要以张开头的存储到一个集合中 ArrayList zhang = new ArrayList<>(); for (String s : list) { if(s.startsWith("张")){ zhang.add(s); } } //对zhang进行过滤,只要姓名长度为3的人 ArrayList three = new ArrayList<>(); for (String s : zhang) { if(s.length() == 3){ three.add(s); } } //遍历three打印 for (String s : three) { System.out.println(s); } } } debra888/qpp-conversion-tool package gov.cms.qpp.conversion.model.error; import static com.google.common.truth.Truth.assertWithMessage; import java.util.Collections; import org.junit.jupiter.api.Test; import com.google.common.truth.StringSubject; class ErrorTest { @Test void testValidationErrorInit() { Error objectUnderTest = new Error(); assertWithMessage("The validation errors should have been empty at first") .that(objectUnderTest.getDetails()).isEmpty(); } @Test void testAddValidationError() { Error objectUnderTest = new Error(); objectUnderTest.addValidationError(new Detail()); objectUnderTest.addValidationError(new Detail()); assertWithMessage("The list should have two items") .that(objectUnderTest.getDetails()).hasSize(2); } @Test void testInitializesDetailsWhenNull() { Error objectUnderTest = new Error(); objectUnderTest.setDetails(null); objectUnderTest.addValidationError(new Detail()); assertWithMessage("The list should have zero items") .that(objectUnderTest.getDetails()).hasSize(1); } @Test void testMutability() { Error objectUnderTest = new Error(); objectUnderTest.setSourceIdentifier("meep"); objectUnderTest.setDetails(Collections.singletonList(new Detail())); assertWithMessage("The list should be one") .that(objectUnderTest.getDetails()).hasSize(1); assertWithMessage("The source identifier should be set") .that(objectUnderTest.getSourceIdentifier()).isEqualTo("meep"); } @Test void testToString() { Error objectUnderTest = new Error(); objectUnderTest.setSourceIdentifier("sourceID"); objectUnderTest.setDetails(Collections.singletonList(Detail.forProblemCode(ProblemCode.UNEXPECTED_ERROR))); objectUnderTest.setType("aType"); objectUnderTest.setMessage("coolMessage"); StringSubject subject = assertWithMessage("Must contain formatted string") .that(objectUnderTest.toString()); subject.contains(String.valueOf(objectUnderTest.getSourceIdentifier())); subject.contains(String.valueOf(objectUnderTest.getDetails())); subject.contains(String.valueOf(objectUnderTest.getType())); subject.contains(String.valueOf(objectUnderTest.getMessage())); } }package com.hardsoftstudio.real.textview.utils; import android.content.Context; import android.graphics.Point; import com.hardsoftstudio.real.textview.exceptions.RealHtmlTextViewException; /** * Created by Marcel on 07/10/2014. */ public class SizeUtils { public static float getDensity(Context context){ float scale = context.getResources().getDisplayMetrics().density; return scale; } public static int convertDiptoPix(Context c, int dip){ if (dip==0) return 0; float scale = getDensity(c); return (int) (dip * scale + 0.5f); } public static int convertPixtoDip(Context c, int pixel){ if (pixel==0) return 0; float scale = getDensity(c); return (int)((pixel - 0.5f)/scale); } public static Point getSizeFromString(String source) throws RealHtmlTextViewException, NumberFormatException { if (source==null || source.isEmpty()) return new Point(0,0); int index = source.lastIndexOf("width"); if (index<0) throw new RealHtmlTextViewException("No width tag found for remote image"); String sizeTag = source.substring(index,source.length()); int end = sizeTag.indexOf("&"); if (end<0) throw new RealHtmlTextViewException("Missing & in size tag"); String width = sizeTag.substring(index+6,end); String height = sizeTag.substring(end+8,sizeTag.length()); return new Point(Integer.parseInt(width),Integer.parseInt(height)); } public static String removeSizeTag(String source) { return source.substring(0,source.lastIndexOf("width")-1); } } tcrct/dagger4j package com.dagger4j.mvc.core; import com.dagger4j.mvc.annotation.Bean; import com.dagger4j.exception.MvcException; import com.dagger4j.exception.ValidatorException; import com.dagger4j.kit.ToolsKit; import com.dagger4j.mvc.http.IRequest; import com.dagger4j.mvc.http.enums.ConstEnums; import com.dagger4j.utils.DataType; import com.dagger4j.vtor.annotation.VtorKit; import com.dagger4j.vtor.core.VtorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.List; import java.util.Map; /** * 参数注入到方法体, 先根据参数名取出请求对象里的值后,再判断是否存在验证注解,如果有验证注解,则验证 * 验证不通过,则抛出异常中止流程 * * @author Created by laotang * @date createed in 2018/6/28. */ public class ParameterInvokeMethod { private static final Logger logger = LoggerFactory.getLogger(ParameterInvokeMethod.class); /** * 将请求参数转换为Object[], 注入到Method里 * * @param controller 执行的控制器 * @param method 执行的方法 * @param paramNameArray 执行方法里的参数变量名 * @return */ public static Object[] getParameterValues(BaseController controller, Method method, String[] paramNameArray) { Parameter[] methodParams = method.getParameters(); if (ToolsKit.isEmpty(methodParams)) { return null; } Object[] requestParamValueObj = null; if (methodParams.length != paramNameArray.length) { throw new MvcException("参数长度不一致!"); } IRequest request = controller.getRequest(); requestParamValueObj = new Object[methodParams.length]; for (int i = 0; i < methodParams.length; i++) { Class parameterType = methodParams[i].getType(); Annotation[] annotations = methodParams[i].getAnnotations(); String paramValue = request.getParameter(paramNameArray[i]); if (DataType.isString(parameterType)) { requestParamValueObj[i] = paramValue; } else if (DataType.isInteger(parameterType) || DataType.isIntegerObject(parameterType)) { requestParamValueObj[i] = Integer.parseInt(paramValue); } else if (DataType.isLong(parameterType) || DataType.isLongObject(parameterType)) { requestParamValueObj[i] = Long.parseLong(paramValue); } else if (DataType.isDouble(parameterType) || DataType.isDoubleObject(parameterType)) { requestParamValueObj[i] = Double.parseDouble(paramValue); } else if (DataType.isDate(parameterType)) { requestParamValueObj[i] = ToolsKit.parseDate(paramValue, ConstEnums.DEFAULT_DATE_FORMAT_VALUE.getValue()); } else if (DataType.isTimestamp(parameterType)) { requestParamValueObj[i] = ToolsKit.parseDate(paramValue, ConstEnums.DEFAULT_DATE_FORMAT_VALUE.getValue()); } else if(DataType.isListType(parameterType) || DataType.isSetType(parameterType) || DataType.isQueueType(parameterType)) { requestParamValueObj[i] = invokeCollention(request, parameterType); } else if(DataType.isMapType(parameterType) ) { requestParamValueObj[i] = invokeMap(request); } else{ requestParamValueObj[i] = invokeBean(request, parameterType, annotations, i); } //返回前,根据验证注解,进行参数数据验证 if (ToolsKit.isNotEmpty(annotations)) { try { // 有可能会有多个注解,所以要遍历一下 for (Annotation annotation : annotations) { // System.out.println(annotation.annotationType() + " " + parameterType.getName() + " " + paramNameArray[i] + " " + paramValue); VtorFactory.validator(annotation, parameterType, paramNameArray[i], paramValue); } } catch (Exception e) { throw new ValidatorException(e.getMessage(), e); } } } return requestParamValueObj; } /** * List, Set, Queue类型验证 * @param request * @param parameterType * @return */ private static Object invokeCollention(IRequest request, Class parameterType) { String json = request.getParameter(ConstEnums.INPUTSTREAM_STR_NAME.getValue()); List entityList = ToolsKit.jsonParseArray(json, parameterType); try { VtorKit.validate(entityList); } catch (Exception e) { throw new ValidatorException(e.getMessage(), e); } return entityList; } /** * Map类型验证 * @param request * @return */ private static Object invokeMap(IRequest request) { String json = request.getParameter(ConstEnums.INPUTSTREAM_STR_NAME.getValue()); Map entityMap = ToolsKit.jsonParseObject(json, Map.class); try { VtorKit.validate(entityMap); } catch (Exception e) { throw new ValidatorException(e.getMessage(), e); } return entityMap; } /** * Bean类型验证 * @param request 请求对象 * @param parameterType 参数类型 * @param annotation 注解对象 * @param index 索引位置 * @return */ private static Object invokeBean(IRequest request, Class parameterType, Annotation[] annotation, int index) { // 如果是继承了IdEntity或对象有设置Bean注解或在参数前设置了Bean注解, 则认为是要转换为Bean对象并验证 String json = request.getParameter(ConstEnums.INPUTSTREAM_STR_NAME.getValue()); Object entity = ToolsKit.jsonParseObject(json, parameterType); if(ToolsKit.isEmpty(entity)) { logger.warn("json字符串转换为Object时出错,返回null退出..."); return null; } boolean isBean = DataType.isIdEntityType(parameterType) || entity instanceof Serializable || parameterType.isAnnotationPresent(Bean.class) || (ToolsKit.isNotEmpty(annotation) && Bean.class.equals(annotation[index].annotationType())); if(!isBean) { logger.warn("请注意对象或集合元素是否实现[ java.io.Serializable ]接口及设置了[ @Bean ]注解"); return null; } // 如果Bean的话,无需在参数添加注解,遍历bean里的field进行判断是否需要验证 try { if(isBean&& ToolsKit.isNotEmpty(entity)) {VtorKit.validate(entity);} } catch (Exception e) { throw new ValidatorException(e.getMessage(), e); } return entity; } } package scratch.kevin.simCompare; import java.awt.Color; import java.awt.Font; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.math3.stat.StatUtils; import org.apache.commons.math3.stat.descriptive.moment.Mean; import org.apache.commons.math3.stat.descriptive.moment.Variance; import org.apache.commons.math3.util.MathArrays; import org.jfree.chart.annotations.XYAnnotation; import org.jfree.chart.annotations.XYTextAnnotation; import org.jfree.chart.plot.DatasetRenderingOrder; import org.jfree.data.Range; import org.jfree.chart.ui.TextAnchor; import org.opensha.commons.data.Site; import org.opensha.commons.data.function.DefaultXY_DataSet; import org.opensha.commons.data.function.DiscretizedFunc; import org.opensha.commons.data.function.EvenlyDiscretizedFunc; import org.opensha.commons.data.function.HistogramFunction; import org.opensha.commons.data.function.XY_DataSet; import org.opensha.commons.gui.plot.HeadlessGraphPanel; import org.opensha.commons.gui.plot.PlotCurveCharacterstics; import org.opensha.commons.gui.plot.PlotLineType; import org.opensha.commons.gui.plot.PlotSpec; import org.opensha.commons.mapping.gmt.elements.GMT_CPT_Files; import org.opensha.commons.util.cpt.CPT; import org.opensha.sha.imr.AttenRelRef; import com.google.common.base.Preconditions; import com.google.common.collect.Table; import com.google.common.primitives.Doubles; public class ZScoreHistPlot { private static final boolean rate_weighted = true; public static class ZScoreResult { public final double mean; public final double stdDevFract; public final HistogramFunction hist; public final Map sourceHists; private ZScoreResult(double mean, double stdDevFract, HistogramFunction hist, Map sourceHists) { super(); this.mean = mean; this.stdDevFract = stdDevFract; this.hist = hist; this.sourceHists = sourceHists; } } public static ZScoreResult[] calcZScores(SimulationRotDProvider simProv, Collection> eventComps, List sites, IMT[] imts, RuptureComparisonFilter filter) throws IOException { return calcZScores(simProv, eventComps, sites, imts, filter, null); } public static ZScoreResult[] calcZScores(SimulationRotDProvider simProv, Collection> eventComps, List sites, IMT[] imts, RuptureComparisonFilter filter, Table sourceRupContribFracts) throws IOException { int numComputed = 0; int numMatches = 0; for (Site site : sites) { for (RuptureComparison comp : eventComps) { if (!comp.isComputed(site, imts[0])) continue; numComputed++; if ((filter != null && !filter.matches(comp, site))) continue; numMatches += simProv.getNumSimulations(site, comp.getRupture()); } } System.out.println(numMatches+" matches (of "+numComputed+" computed)"); int numBins; if (numMatches < 100) numBins = 10; else if (numMatches < 500) numBins = 40; else numBins = 100; System.out.println("Binning with "+numBins+" bins"); ZScoreResult[] ret = new ZScoreResult[imts.length]; for (int p=0; p sourceHists = sourceRupContribFracts == null ? null : new HashMap<>(); List allVals = new ArrayList<>(); List allWeights = rate_weighted ? new ArrayList<>() : null; int count = 0; for (Site site : sites) { for (RuptureComparison comp : eventComps) { if (!comp.hasSite(site)) continue; Preconditions.checkState(comp.isComputed(site, imt), "Computed for %s but not %s", imts[0], imt); if ((filter != null && !filter.matches(comp, site))) continue; double gmpeVal = comp.getLogMean(site, imt); Map sourceFracts = sourceHists == null ? null : sourceRupContribFracts.column(comp.getRupture()); List simVals = simProv.getValues(site, comp.getRupture(), imt); double rateEach = comp.getAnnualRate()/(double)simVals.size(); for (double simVal : simVals) { // in log space simVal = Math.log(simVal); double val = (simVal - gmpeVal)/comp.getStdDev(site, imt); int ind = hist.getClosestXIndex(val); if (sourceFracts != null) { double sum = 0d; for (String sourceName : sourceFracts.keySet()) { HistogramFunction sourceHist = sourceHists.get(sourceName); if (sourceHist == null) { sourceHist = new HistogramFunction(hist.getMinX(), hist.getMaxX(), hist.size()); sourceHist.setName(sourceName); sourceHists.put(sourceName, sourceHist); } double fract = sourceFracts.get(sourceName); sourceHist.add(ind, rateEach*fract); sum += fract; } Preconditions.checkState((float)sum == 1f, "Bad sum of contribution fracts: %s", sum); } hist.add(ind, rateEach); allVals.add(val); if (rate_weighted) allWeights.add(rateEach); count++; } } } if (count == 0) return null; double[] valsArray = Doubles.toArray(allVals); double mean, stdDev; if (rate_weighted) { double[] weightsArray = Doubles.toArray(allWeights); weightsArray = MathArrays.normalizeArray(weightsArray, weightsArray.length); mean = new Mean().evaluate(valsArray, weightsArray); double var = new Variance().evaluate(valsArray, weightsArray, mean); stdDev = Math.sqrt(var); System.out.println(imt.getDisplayName()+" mean="+(float)mean +"\tvar="+(float)var+"\tsd="+(float)stdDev); } else { mean = new Mean().evaluate(valsArray); stdDev = Math.sqrt(new Variance().evaluate(valsArray, mean)); } double area = calcArea(hist); hist.scale(1d/area); if (sourceHists != null) for (HistogramFunction sourceHist : sourceHists.values()) sourceHist.scale(1d/area); ret[p] = new ZScoreResult(mean, stdDev, hist, sourceHists); } return ret; } public static boolean plotStandardNormal(SimulationRotDProvider simProv, Collection> eventComps, List sites, IMT[] imts, AttenRelRef gmpe, RuptureComparisonFilter filter, List binDescriptions, File outputDir, String prefix) throws IOException { return plotStandardNormal(simProv, eventComps, sites, imts, gmpe, filter, binDescriptions, outputDir, prefix, null, 0, false); } private static final double maxY = 0.7d; private static final double numStdDev = 3.75; public static boolean plotStandardNormal(SimulationRotDProvider simProv, Collection> eventComps, List sites, IMT[] imts, AttenRelRef gmpe, RuptureComparisonFilter filter, List binDescriptions, File outputDir, String prefix, Table sourceRupContribFracts, int maxNumSourceContribs, boolean pub) throws IOException { List specs = new ArrayList<>(); List xRanges = new ArrayList<>(); xRanges.add(new Range(-numStdDev, numStdDev)); List means = new ArrayList<>(); List stdDevs = new ArrayList<>(); Color stdDevColor = new Color(0, 150, 0); DatasetRenderingOrder order = DatasetRenderingOrder.FORWARD; ZScoreResult[] scores = calcZScores(simProv, eventComps, sites, imts, filter, sourceRupContribFracts); if (scores == null) return false; for (int p=0; p funcs = new ArrayList<>(); List chars = new ArrayList<>(); EvenlyDiscretizedFunc stdNormal = new EvenlyDiscretizedFunc(score.hist.getMinX(), score.hist.getMaxX(), 1000); double scalar = 1d/Math.sqrt(2d*Math.PI); for (int i=0; i sourceHistList = new ArrayList<>(); for (String sourceName : score.sourceHists.keySet()) sourceHistList.add(score.sourceHists.get(sourceName)); // sort by area, decreasing Collections.sort(sourceHistList, histComparator); if (sourceHistList.size() > maxNumSourceContribs) { HistogramFunction otherHist = new HistogramFunction( score.hist.getMinX(), score.hist.getMaxX(), score.hist.size()); otherHist.setName("Other"); for (int i=maxNumSourceContribs-1; i "+cptVal); funcs.add(clone); chars.add(new PlotCurveCharacterstics(PlotLineType.HISTOGRAM, 1f, colorCPT.getColor(cptVal))); } funcs.add(score.hist); chars.add(new PlotCurveCharacterstics(PlotLineType.HISTOGRAM, 1f, Color.GRAY)); } else { funcs.add(score.hist); chars.add(new PlotCurveCharacterstics(PlotLineType.HISTOGRAM, 1f, Color.GRAY)); funcs.add(stdNormal); chars.add(new PlotCurveCharacterstics(PlotLineType.SOLID, 2f, Color.BLACK)); funcs.add(meanLine); chars.add(new PlotCurveCharacterstics(PlotLineType.DASHED, 3f, pub ? Color.BLACK : Color.BLUE)); } for (double sigma=Math.ceil(-numStdDev); !pub && sigma<=numStdDev; sigma++) { DefaultXY_DataSet sigmaLine = new DefaultXY_DataSet(); sigmaLine.set(sigma, 0); sigmaLine.set(sigma, maxY-0.075); funcs.add(sigmaLine); chars.add(new PlotCurveCharacterstics(PlotLineType.DOTTED, 1f, stdDevColor)); } String title = pub ? " " : gmpe.getShortName()+" Log-Normal Comparision"; String xAxisLabel = "z-score (Standard Deviations)"; String yAxisLabel = "Density"; PlotSpec spec = new PlotSpec(funcs, chars, title, xAxisLabel, yAxisLabel); spec.setLegendVisible(imt == imts[imts.length-1]); specs.add(spec); } DecimalFormat twoSigFig = new DecimalFormat("0.00"); List yRanges = new ArrayList<>(); for (int i=0; i labels = new ArrayList<>(binDescriptions); if (!pub) labels.add(0, imts[i].getShortName()); double yEach = maxY/8d; double x = -numStdDev + 0.2; double y = maxY; if (pub) y -= 0.2*yEach; else y -= 1.2*yEach; Font bigFont = new Font(Font.SANS_SERIF, Font.BOLD, 24); Font smallFont = new Font(Font.SANS_SERIF, Font.BOLD, 20); List anns = new ArrayList<>(); XYTextAnnotation meanAnn = new XYTextAnnotation( "Mean: "+twoSigFig.format(means.get(i)), -x, y); meanAnn.setTextAnchor(TextAnchor.TOP_RIGHT); meanAnn.setFont(bigFont); anns.add(meanAnn); XYTextAnnotation stdDevAnn = new XYTextAnnotation( "σ-fract: "+twoSigFig.format(stdDevs.get(i)), -x, y-yEach); stdDevAnn.setTextAnchor(TextAnchor.TOP_RIGHT); stdDevAnn.setFont(bigFont); anns.add(stdDevAnn); for (int j=0; j 1) { width = 800; height = 200 + 300*specs.size(); } else { width = 600; height = 450; } gp.getChartPanel().setSize(width, height); gp.saveAsPNG(file.getAbsolutePath()+".png"); gp.saveAsPDF(file.getAbsolutePath()+".pdf"); return true; } private static double calcArea(HistogramFunction hist) { double area = 0d; for (Point2D pt : hist) area += hist.getDelta()*pt.getY(); return area; } private static final Comparator histComparator = new Comparator() { @Override public int compare(HistogramFunction o1, HistogramFunction o2) { double a1 = calcArea(o1); double a2 = calcArea(o2); return -Double.compare(a1, a2); } }; } src/main/java/com/ruoyi/project/smt/ledger/vo/ShipExportVO.java package com.ruoyi.project.smt.ledger.vo; import lombok.Data; import lombok.EqualsAndHashCode; /** * @Description * @Author Administrator * @Date 2019/12/9 22:52 * @Version 1.0 **/ @Data @EqualsAndHashCode(callSuper = false) public class ShipExportVO { //客户编码 private String cusCode; //电子料名称 private String dzlName; //出货日期 private String shipTime; //订单号 private String orderNo; //FPC名称 private String bomName; //FPC出货数量 private Integer fpcShipQty; //用量 private Integer dzlNumber; //电子料出货 private Integer shipQty; //备品 private Integer bak; } package pl.itcraft.appstract.admin.order.fulfillment; import pl.itcraft.appstract.admin.utils.AdminAppModuleConfig; import pl.itcraft.appstract.core.entities.UploadedFile; public class TitleSearchDocumentDto { private String fileName; private String url; public TitleSearchDocumentDto(UploadedFile file, AdminAppModuleConfig config) { this.fileName = file.getSourceFileName(); this.url = config.getAbsoluteFileUrl(file.getPath()); } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } } package semanticAnalyzer.SymbolTable; public enum EntryKind { FUNCTION, CLASS, VARIABLE, PARAMETER, INHERIT } /** * WebViewCloseButton.java * Chilli Source * Created by on 16/12/2011. * * The MIT License (MIT) * * Copyright (c) 2011 Tag Games Limited * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.chilliworks.chillisource.web; import com.chilliworks.chillisource.core.R; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RelativeLayout; public class WebViewCloseButton extends Button { final private int mudwIndex; //--------------------------------------------------------------------- /// CCloseButton /// /// Constructor for CCloseButton - sets layout and size of button. /// Override on click listener to remove views /// /// @param Context /// @param index of webview that this will be associated with /// //--------------------------------------------------------------------- public WebViewCloseButton(Context context, int inudwIndex, float infSize) { super(context); mudwIndex = inudwIndex; if (R.doesExist(R.Type.DRAWABLE, "com_chillisource_close_button") == true) { setBackgroundResource(R.getId(R.Type.DRAWABLE, "com_chillisource_close_button")); } else { setText("X"); } RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams((int)infSize, (int)infSize); params.addRule(RelativeLayout.ALIGN_RIGHT, mudwIndex); params.addRule(RelativeLayout.ALIGN_TOP, mudwIndex); setLayoutParams(params); setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ViewGroup vg = (ViewGroup)(v.getParent()); vg.removeView(v); WebViewNativeInterface.Dismiss(mudwIndex); } }); } //--------------------------------------------------------------------- /// Get Index /// /// Get Index of webview associated with button /// /// @returns int of index /// //--------------------------------------------------------------------- public int GetIndex() { return mudwIndex; } }ccampo133/authbert-web1-10 package com.authid.web.controller; import org.jetbrains.annotations.NotNull; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Optional; /** * @author */ @RestController public class VersionController { public static final String DEFAULT_VERSION = "0.0.0.dev"; private final String version; public VersionController() { this.version = Optional.ofNullable(getClass().getPackage().getImplementationVersion()).orElse(DEFAULT_VERSION); } @NotNull @RequestMapping("/version") public String getVersion() { return version; } }package com.goyourfly.weather_library.net.yahoo_obj; /** * Created by gaoyf on 14/12/29. */ public class NetCentroid { public float latitude; public float longitude; } /* * 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.addthis.hydra.data.query.op.merge; import com.addthis.bundle.util.ValueUtil; import com.addthis.bundle.value.ValueArray; import com.addthis.bundle.value.ValueFactory; import com.addthis.bundle.value.ValueObject; import com.addthis.hydra.data.query.op.MergedRow; import com.google.common.base.Joiner; public class JoinedValue extends AbstractMergedValue { private static final Joiner DEFAULT_JOINER = Joiner.on(','); private final Joiner joiner; public JoinedValue(Joiner joiner) { this.joiner = joiner; } public JoinedValue(String seperator) { this(Joiner.on(seperator)); } public JoinedValue() { this(DEFAULT_JOINER); } @Override protected ValueObject doMerge(ValueObject nextValue, ValueObject value) { ValueArray values = ValueUtil.asArray(value); values.add(nextValue); return values; } @Override protected ValueObject convert(ValueObject nextValue) { if (nextValue.getObjectType() != ValueObject.TYPE.ARRAY) { return nextValue.asString(); } else { return nextValue; } } @Override protected ValueObject doEmit(ValueObject value, MergedRow mergedRow) { ValueArray values = ValueUtil.asArray(value); return ValueFactory.create(joiner.join(values)); } } import java.util.Random; import java.util.HashMap; import java.util.Arrays; import java.util.ArrayList; import java.lang.*; import static spark.Spark.*; import spark.ModelAndView; import spark.template.velocity.VelocityTemplateEngine; import java.util.Map; public class App { public static void main(String[] args) { String layout = "templates/layout.vtl"; staticFileLocation("/public"); get("/", (request, response) -> { HashMap model = new HashMap(); request.session().attribute("pet", null); model.put("template", "templates/home.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); post("/pet", (request, response) -> { HashMap model = new HashMap(); Tamagotchi pet = request.session().attribute("pet"); if (pet == null) { String petName = request.queryParams("name"); pet = new Tamagotchi(petName); request.session().attribute("pet", pet); model.put("pet", request.session().attribute("pet")); } String feed = request.queryParams("feed"); if (Boolean.parseBoolean(feed)) { pet = pet.feed(); model.put("pet", request.session().attribute("pet")); } String doNothing = request.queryParams("doNothing"); if (Boolean.parseBoolean(doNothing)) { pet = pet.timePasses(); model.put("pet", request.session().attribute("pet")); } String nap = request.queryParams("nap"); if (Boolean.parseBoolean(nap)) { pet = pet.nap(); model.put("pet", request.session().attribute("pet")); } String play = request.queryParams("play"); if (Boolean.parseBoolean(play)) { pet = pet.play(); model.put("pet", request.session().attribute("pet")); } model.put("template", "templates/pet.vtl"); return new ModelAndView(model, layout); }, new VelocityTemplateEngine()); } } package com.alaskalany.todoly.cli; import java.util.ArrayList; import java.util.Scanner; public abstract class Menu { private final String title; private final ArrayList options; private final String prompt; protected Menu(String title) { options = new ArrayList<>(); this.title = title; prompt = setPrompt(); setOptions(options); } protected abstract void setOptions(ArrayList options); public void display() { System.out.println(); displayTitle(); System.out.println(); displayOptions(); System.out.println(); displayBody(); System.out.println(); displayPrompt(); getInput(); } protected abstract void displayBody(); private void displayPrompt() { System.out.print(prompt); System.out.print(":> "); } private void displayOptions() { options.forEach(option -> { System.out.print(1 + options.indexOf(option)); System.out.print("- "); System.out.print(option); System.out.println(); }); } private void displayTitle() { System.out.println(title); } protected abstract String setPrompt(); private void getInput() { Scanner scanner = new Scanner(System.in); onInput(scanner.nextLine()); } protected abstract void onInput(String string); protected void displayMenu(Menu menu) { menu.display(); } } package ca.ulaval.glo4002.billing.domain.invoices; import ca.ulaval.glo4002.billing.domain.clients.ClientId; public interface InvoiceRepository { Invoice find(InvoiceId invoiceId); InvoiceId insert(Invoice invoice); Invoice findLast(ClientId clientId); void delete(Invoice invoice); } src/main/java/gunging/ootilities/gunging_ootilities_plugin/misc/OptiFineGlint.java package gunging.ootilities.gunging_ootilities_plugin.misc; import gunging.ootilities.gunging_ootilities_plugin.Gunging_Ootilities_Plugin; import gunging.ootilities.gunging_ootilities_plugin.OotilityCeption; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Map; public class OptiFineGlint { // Internal Overall Storage public static ArrayList loadedGlints = new ArrayList(); // Reload Config public static void ReloadGlints(OotilityCeption oots) { // Starts Fresh loadedGlints = new ArrayList(); // If there were no parsing errors if (Gunging_Ootilities_Plugin.theMain.optiFineGlintPair != null) { // Read the file yeet FileConfigPair ofgPair = Gunging_Ootilities_Plugin.theMain.optiFineGlintPair; // Get the latest version of the storage ofgPair = Gunging_Ootilities_Plugin.theMain.GetLatest(ofgPair); // Modify Storage YamlConfiguration ofgStorage = ofgPair.getStorage(); // Log da shit for(Map.Entry val : (ofgStorage.getValues(false)).entrySet()){ // Get Glint Name String tName = val.getKey(); // Get Enchantment Value Enchantment tEnchant = null; if (ofgStorage.contains(tName + ".Enchantment")) { tEnchant = oots.GetEnchantmentByName(ofgStorage.getString(tName + ".Enchantment")); } // Get Enchantment Level Integer tLevel = null; Boolean igLevel = true; if (ofgStorage.contains(tName + ".Level")) { // Something is in there so we're not ignoring level igLevel = false; // Does it parse bruh if (oots.IntTryParse(ofgStorage.getString(tName + ".Level"))) { // Set tLevel = ofgStorage.getInt(tName + ".Level"); } } // Get Lore Line String tLore = null; if (ofgStorage.contains(tName + ".LoreLine")) { tLore = ofgStorage.getString(tName + ".LoreLine"); } //oots.CPLog("Loaded \u00a7e" + tName + " \u00a77 for enchantment \u00a73" + tEnchant + " " + tLevel); // Create and add glint loadedGlints.add(new OptiFineGlint(tName, tEnchant, tLevel, tLore, igLevel)); } // Failed to parse } else { // Empty but not null loadedGlints = new ArrayList(); } } // Check for Contain public static OptiFineGlint IsGlintLoaded(String glintName, RefSimulator logger) { // Check every loaded Glint for (OptiFineGlint glnt : loadedGlints) { // Is it the one we searching four? if (glnt.getGlintName().equals(glintName)) { // Enchantment and Level may suck ngl Boolean enchSuccess, levelSuccess; // Success if non-null enchSuccess = (glnt.getEnchant() != null); // Success if non-null or level disabled levelSuccess = (glnt.ignoresLevel() || glnt.getLevel() != null); // Check for short bounds if (levelSuccess && !glnt.ignoresLevel()) { // Will become false if out of bounds levelSuccess = (glnt.getLevel() < 32767 && glnt.getLevel() > -32768); } // Log Any error if (!enchSuccess && levelSuccess) { // Invalid Enchantment OotilityCeption.Log4Success(logger, !Gunging_Ootilities_Plugin.blockImportantErrorFeedback, "The \u00a7eenchantment \u00a77associated with glint '\u00a73 " + glintName + "\u00a77' is \u00a7cinvalid\u00a77."); // Nope return null; } // Log Any error if (!levelSuccess && enchSuccess) { // Invalid Level OotilityCeption.Log4Success(logger, !Gunging_Ootilities_Plugin.blockImportantErrorFeedback, "The \u00a7eenchantment level \u00a77associated with glint '\u00a73 " + glintName + "\u00a77' is \u00a7cinvalid\u00a77."); // Nope return null; } // Log Double Error if (!levelSuccess && !enchSuccess) { // Invalid Everything lol OotilityCeption.Log4Success(logger, !Gunging_Ootilities_Plugin.blockImportantErrorFeedback, "The \u00a7eenchantment and \u00a7eenchantment levels \u00a77associated with glint '\u00a73 " + glintName + "\u00a77' are \u00a7cinvalid\u00a77."); // Nope return null; } // If both succeeded if (levelSuccess && enchSuccess) { // Found enchantment return glnt; } } } // Log Return OotilityCeption.Log4Success(logger, !Gunging_Ootilities_Plugin.blockImportantErrorFeedback, "No optiFine glint of name '\u00a73 " + glintName + "\u00a77' is currently loaded."); // Nope return null; } // Apply Glint public static ItemStack ApplyGlint(ItemStack iSource, OptiFineGlint tGlint, RefSimulator logger) { OotilityCeption oots = new OotilityCeption(); // Make sure the glint fucking exists if (tGlint != null) { // Make sure its non-null if (iSource != null) { // Make sure its not air if (!OotilityCeption.IsAir(iSource.getType())) { // Product yeet ItemStack iProduct = iSource; // Make sure the item meets enchantment-level requirements if (tGlint.getLevel() != null) { // Level Exists. Is the level serendipitously the correct already? if (iSource.getEnchantmentLevel(tGlint.getEnchant()) == tGlint.getLevel()) { // Yes. Wow. // No. Lets add the next useless enchant ;D } else { // Add the next useless enchant to the item iProduct = OotilityCeption.AddUselessEnchantmentOfLevel(iSource, tGlint.getLevel()); } } // The level stuff is now setup. Add the enchantment if it wasn't serendipitously added yet. if (!OotilityCeption.TestForEnchantment(iProduct, tGlint.getEnchant(), null, null)) { // Enchantment at least power iProduct.addUnsafeEnchantment(tGlint.getEnchant(), 1); } // Add Lore, if defined if (tGlint.getLoreLine() != null) { // Jus' Append it at the end iProduct = OotilityCeption.AppendLoreLine(iProduct, tGlint.getLoreLine(), null, null); } // Log I suppose OotilityCeption.Log4Success(logger, Gunging_Ootilities_Plugin.sendGooPSuccessFeedback, "Successfully applied \u00a73" + tGlint.getGlintName() + "\u00a77 to " + OotilityCeption.GetItemName(iProduct)); // Finish return iProduct; // Item Stack is AIR } else { //Log OotilityCeption.Log4Success(logger, Gunging_Ootilities_Plugin.sendGooPFailFeedback, "There is no item in there!"); } // Item Stack is Null } else { //Log OotilityCeption.Log4Success(logger, Gunging_Ootilities_Plugin.sendGooPFailFeedback, "There is no item in that slot!"); } // Glint Doesnt Exist } else { //Log OotilityCeption.Log4Success(logger, !Gunging_Ootilities_Plugin.blockImportantErrorFeedback, "That glint doesnt exist!"); } // Null - ew return null; } // Define Glint public static OptiFineGlint DefineGlint(String glintName, Enchantment enchant, Integer enchantLevel, String loreLine, RefSimulator logger) { // Define in YML if there were no parsing errors if (Gunging_Ootilities_Plugin.theMain.optiFineGlintPair != null) { // Read the file yeet FileConfigPair ofgPair = Gunging_Ootilities_Plugin.theMain.optiFineGlintPair; // Get the latest version of the storage ofgPair = Gunging_Ootilities_Plugin.theMain.GetLatest(ofgPair); // Modify Storage YamlConfiguration ofgStorage = ofgPair.getStorage(); // Set Enchantment ofgStorage.set(glintName + ".Enchantment", enchant.getKey().getKey()); // Set Level if (enchantLevel != null) { ofgStorage.set(glintName + ".Level", enchantLevel); } // Set lore Line if (loreLine != null) { ofgStorage.set(glintName + ".LoreLine", loreLine); } // Save Gunging_Ootilities_Plugin.theMain.SaveFile(ofgPair); // Log OotilityCeption.Log4Success(logger, Gunging_Ootilities_Plugin.sendGooPSuccessFeedback, "Successfuly defined new glint: \u00a73" + glintName); } else { // Log OotilityCeption.Log4Success(logger, !Gunging_Ootilities_Plugin.blockImportantErrorFeedback, "\u00a7cCan't save new glint due to \u00a7eopti-fine-glints.yml\u00a7c parsing errors. \u00a77It will be useable until next reload though."); } // Load and Return OptiFineGlint ret = new OptiFineGlint(glintName, enchant, enchantLevel, loreLine, enchantLevel == null); loadedGlints.add(ret); return ret; } // The Basics Stuff String eName; Enchantment tEnchant; Integer tLevel; String tLoreLine; // Lore line WITH color codes Boolean noLevel; Boolean noLore; public OptiFineGlint(String glintName, Enchantment enchant, Integer enchantLevel, String loreLine, Boolean ignoreLevel) { eName = glintName; tEnchant = enchant; tLevel = enchantLevel; tLoreLine = loreLine; noLevel = ignoreLevel; noLore = (loreLine == null); } public String getGlintName() { return eName; } public Enchantment getEnchant() { return tEnchant; } public Integer getLevel() { if (noLevel) { return null; } else { return tLevel; } } public String getLoreLine() { if (noLore) { return null; } else { return tLoreLine; } } public Boolean ignoresLevel() { return noLevel; } } pedrodaniel10/SD package org.binas.ws; public class BinasApp { public static void main(String[] args) throws Exception { String wsName; String wsURL; String uddiURL; int replics; BinasEndpointManager endpoint; if (args.length == 4){ uddiURL = args[0]; wsName = args[1]; wsURL = args[2]; replics = Integer.parseInt(args[3]); if(replics < 3){ System.out.println("Number of Replics should be greater or equals to 3."); return; } endpoint = new BinasEndpointManager(uddiURL, wsName, wsURL, replics); System.out.println("{wsName = " + wsName + ", wsURL = " + wsURL + ", uddiURL = " + uddiURL + ", replics = " + replics + "}"); } else{ System.err.println("Argument(s) missing!"); System.err.println("Usage: java Binas uddiURL wsName wsURL"); return; } try { endpoint.start(); endpoint.awaitConnections(); } finally { endpoint.stop(); } } } cyberstormdotmu/em-stitching-api package uk.gov.hmcts.reform.em.stitching.conversion; import java.io.File; import java.io.IOException; import java.util.List; public interface FileToPDFConverter { List accepts(); File convert(File file) throws IOException; } // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See License.txt in the project root. package com.microsoft.alm.plugin.idea.tfvc.ui.servertree; import com.intellij.ide.util.treeView.AbstractTreeBuilder; import com.intellij.ide.util.treeView.AbstractTreeStructure; import com.intellij.ide.util.treeView.NodeDescriptor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.ui.treeStructure.SimpleTreeStructure; import org.jetbrains.annotations.NotNull; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import java.util.Comparator; public class TfsTreeBuilder extends AbstractTreeBuilder { private static final Logger LOG = Logger.getInstance(TfsTreeBuilder.class.getName()); private static final Comparator COMPARATOR = new Comparator() { public int compare(NodeDescriptor o1, NodeDescriptor o2) { if (o1 instanceof TfsErrorTreeNode) { return o2 instanceof TfsErrorTreeNode ? ((TfsErrorTreeNode) o1).getMessage().compareTo(((TfsErrorTreeNode) o2).getMessage()) : -1; } else if (o2 instanceof TfsErrorTreeNode) { return 1; } final TfsTreeNode n1 = (TfsTreeNode) o1; final TfsTreeNode n2 = (TfsTreeNode) o2; if (n1.isDirectory() && !n2.isDirectory()) { return -1; } else if (!n1.isDirectory() && n2.isDirectory()) { return 1; } return n1.getFileName().compareToIgnoreCase(n2.getFileName()); } }; public static TfsTreeBuilder createInstance(@NotNull final TfsTreeNode root, @NotNull final JTree tree) { final DefaultTreeModel treeModel = new DefaultTreeModel(new DefaultMutableTreeNode(root)); tree.setModel(treeModel); return new TfsTreeBuilder(tree, treeModel, new SimpleTreeStructure.Impl(root) { @Override public boolean isToBuildChildrenInBackground(Object element) { return true; } @Override public boolean isAlwaysLeaf(Object element) { if (element instanceof TfsTreeNode) { return !((TfsTreeNode) element).isDirectory(); } else { LOG.assertTrue(element instanceof TfsErrorTreeNode); return true; } } }); } public TfsTreeBuilder(final JTree tree, final DefaultTreeModel treeModel, final AbstractTreeStructure treeStructure) { super(tree, treeModel, treeStructure, COMPARATOR); } @Override protected void runBackgroundLoading(@NotNull final Runnable runnable) { if (isDisposed()) return; runnable.run(); } @Override protected boolean isAutoExpandNode(final NodeDescriptor nodeDescriptor) { if (nodeDescriptor instanceof TfsErrorTreeNode) { return true; } if (nodeDescriptor instanceof TfsTreeNode) { return !((TfsTreeNode) nodeDescriptor).isDirectory() || ((TfsTreeNode) nodeDescriptor).isRoot(); } return false; } @Override protected boolean isAlwaysShowPlus(final NodeDescriptor descriptor) { if (descriptor instanceof TfsTreeNode) { return ((TfsTreeNode) descriptor).isDirectory(); } else { LOG.assertTrue(descriptor instanceof TfsErrorTreeNode); return false; } } } package ratismal.drivebackup.util; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.temporal.TemporalAccessor; import java.util.List; import org.bukkit.Bukkit; public class SchedulerUtil { private static final int TICKS_PER_SECOND = 20; /** * Cancels the specified tasks * @param taskList an List of the IDs of the tasks */ public static void cancelTasks(List taskList) { for (int task : taskList) { Bukkit.getScheduler().cancelTask(task); } taskList.clear(); } /** * Converts the specified number of seconds to game ticks * @param seconds the number of seconds * @return the number of game ticks */ public static long sToTicks(long seconds) { return seconds * TICKS_PER_SECOND; } /** * Parses the time * @param time the time, as a String * @return the parsed time */ public static TemporalAccessor parseTime(String time) throws IllegalArgumentException { DateTimeFormatter formatter = new DateTimeFormatterBuilder() .appendOptional(DateTimeFormatter.ofPattern("kk:mm")) .appendOptional(DateTimeFormatter.ofPattern("k:mm")) .toFormatter(); return formatter.parse(time); } } JayaniSumudini/JavaTraining package com.company.designPatterns.factoryPattern; enum ShapeType { Circle, Rectangle } LEODPEN/OOAD_Projectsprojects/src/proA/game/PositionInfo.java package proA.game; /** * @author onion * @date 2019/9/11 -12:13 下午 */ public class PositionInfo { private int currentPosition; private int direction; private int time; public PositionInfo(int currentPosition, int direction, int time) { this.currentPosition = currentPosition; this.direction = direction; this.time = time; } public int getCurrentPosition() { return currentPosition; } public int getDirection() { return direction; } public int getTime() { return time; } @Override public String toString(){ return time + "s:" + currentPosition; } } package com.telecominfraproject.wlan.status.network.models; import java.util.Objects; import com.telecominfraproject.wlan.core.model.entity.MinMaxAvgValueInt; import com.telecominfraproject.wlan.core.model.json.BaseJsonModel; /** * @author dtop * */ public class ChannelUtilizationPerRadioDetails extends BaseJsonModel { private static final long serialVersionUID = -4773437330014768087L; private MinMaxAvgValueInt channelUtilization; private int numGoodEquipment; private int numWarnEquipment; private int numBadEquipment; public MinMaxAvgValueInt getChannelUtilization() { return channelUtilization; } public void setChannelUtilization(MinMaxAvgValueInt channelUtilization) { this.channelUtilization = channelUtilization; } public int getNumGoodEquipment() { return numGoodEquipment; } public void setNumGoodEquipment(int numGoodEquipment) { this.numGoodEquipment = numGoodEquipment; } public int getNumWarnEquipment() { return numWarnEquipment; } public void setNumWarnEquipment(int numWarnEquipment) { this.numWarnEquipment = numWarnEquipment; } public int getNumBadEquipment() { return numBadEquipment; } public void setNumBadEquipment(int numBadEquipment) { this.numBadEquipment = numBadEquipment; } @Override public ChannelUtilizationPerRadioDetails clone() { ChannelUtilizationPerRadioDetails ret = (ChannelUtilizationPerRadioDetails) super.clone(); if(this.channelUtilization!=null){ ret.channelUtilization = this.channelUtilization.clone(); } return ret; } /** * @param other * @return this object, merged with other */ public ChannelUtilizationPerRadioDetails combineWith(ChannelUtilizationPerRadioDetails other) { if(other == null){ return this; } if(this.channelUtilization !=null){ this.channelUtilization.combineWith(other.channelUtilization); } else { this.channelUtilization = other.channelUtilization; } if(this.numGoodEquipment == 0){ this.numGoodEquipment = other.numGoodEquipment; } if(this.numWarnEquipment == 0){ this.numWarnEquipment = other.numWarnEquipment; } if(this.numBadEquipment == 0){ this.numBadEquipment = other.numBadEquipment; } return this; } @Override public int hashCode() { return Objects.hash(channelUtilization, numBadEquipment, numGoodEquipment, numWarnEquipment); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ChannelUtilizationPerRadioDetails)) { return false; } ChannelUtilizationPerRadioDetails other = (ChannelUtilizationPerRadioDetails) obj; return Objects.equals(channelUtilization, other.channelUtilization) && numBadEquipment == other.numBadEquipment && numGoodEquipment == other.numGoodEquipment && numWarnEquipment == other.numWarnEquipment; } } package com.tibco.as.spacebar.ui.wizards.transfer.csv; import org.eclipse.swt.widgets.Listener; import com.tibco.as.spacebar.ui.wizards.transfer.AbstractImportWizardPage; public class DelimitedImportMainPage extends AbstractImportWizardPage implements Listener { private final static String[] EXTENSIONS = { "", "csv", "txt" }; public DelimitedImportMainPage() { super("DelimitedImportMainPage", "Import spaces from CSV files", EXTENSIONS); setDescription("Select the CSV files to import."); } } package mage.cards.q; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.DrawCardControllerTriggeredAbility; import mage.abilities.effects.common.GainLifeEffect; import mage.abilities.effects.common.LoseLifeTargetEffect; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.SuperType; import mage.target.common.TargetOpponent; import java.util.UUID; /** * @author TheElk801 */ public final class QuezaAugurOfAgonies extends CardImpl { public QuezaAugurOfAgonies(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{W}{U}{B}"); this.addSuperType(SuperType.LEGENDARY); this.subtype.add(SubType.CEPHALID); this.subtype.add(SubType.ADVISOR); this.power = new MageInt(3); this.toughness = new MageInt(4); // Whenever you draw a card, target opponent loses 1 life and you gain 1 life. Ability ability = new DrawCardControllerTriggeredAbility(new LoseLifeTargetEffect(1), false); ability.addEffect(new GainLifeEffect(1).concatBy("and")); ability.addTarget(new TargetOpponent()); this.addAbility(ability); } private QuezaAugurOfAgonies(final QuezaAugurOfAgonies card) { super(card); } @Override public QuezaAugurOfAgonies copy() { return new QuezaAugurOfAgonies(this); } } /* * Copyright 2018 (Panzer1119) * * 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 de.codemakers.mcfp; import com.google.gson.*; import de.codemakers.io.file.AdvancedFile; import de.codemakers.mcfp.entities.FileOverride; import de.codemakers.mcfp.entities.Overrides; import de.codemakers.mcfp.util.Util; public class GeneratorTest { public static final void main(String[] args) throws Exception { final AdvancedFile advancedFile_minecraft_original = new AdvancedFile(args[0]); final AdvancedFile advancedFile_minecraft_modified = new AdvancedFile(args[1]); final AdvancedFile advancedFile_overrides_json = new AdvancedFile(args[2]); final boolean includeData = args.length > 3 ? Boolean.parseBoolean(args[3]) : false; final Overrides overrides = Util.generateOverrides(advancedFile_minecraft_original, advancedFile_minecraft_modified, false, includeData); System.out.println(overrides); System.out.println(); System.out.println(); System.out.println(); System.out.println(); final Gson gson = new GsonBuilder().create(); final GsonBuilder gsonBuilder = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting(); final JsonSerializer jsonSerializer = (src, typeOfSrc, context) -> { final JsonElement jsonElement = gson.toJsonTree(src, typeOfSrc); final JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.has("source") && src.getSourceType() != null) { jsonObject.addProperty("source", src.getSourceType().getType() + ":" + src.getSource()); } return jsonObject; }; gsonBuilder.registerTypeAdapter(FileOverride.class, jsonSerializer); final String json = gsonBuilder.create().toJson(overrides); //System.out.println(json); advancedFile_overrides_json.writeBytesWithoutException(json.getBytes()); } } l2lisp/BuiltInFunctions.java // H22.8/18, H30.4/8 (鈴) package l2lisp; import java.io.*; import java.util.*; import java.math.BigInteger; import java.lang.reflect.Field; /** 組込み Lisp 関数の集合体. * 若干のユーティリティも含む。 */ public class BuiltInFunctions { /** このクラスはインスタンスを作らない。*/ private BuiltInFunctions () {} /** 組込み Lisp 関数からなる配列 */ public static final Callable[] FUNCTIONS = new Callable[] { new Callable ("car", 1) { { doc = "(car '(a b c)) => a; (car nil) => nil"; } public Object call(Object[] a) { return (a[0] == null) ? null : ((Cell) a[0]).car; } }, new Callable ("cdr", 1) { { doc = "(cdr '(a b c)) => (b c); (cdr nil) => nil"; } public Object call(Object[] a) { return (a[0] == null) ? null : ((Cell) a[0]).cdr; } }, new Callable ("cons", 2, Callable.Option.IS_LAZY) { { doc = "(cons 'a '(b c)) => (a b c)"; } public Object call(Object[] a) { return new Cell (a[0], a[1]); } }, new Callable ("atom", 1) { { doc = "(atom x) => x が Cell のインスタンスならば偽"; } public Object call(Object[] a) { return (a[0] instanceof Cell) ? null : LL.S_T; } }, new Callable ("eq", 2) { { doc = "(eq x y) => x と y が同じ参照か?"; } public Object call(Object[] a) { return (a[0] == a[1]) ? LL.S_T : null; } }, new Callable ("stringp", 1) { { doc = "(stringp x) => x が文字列 (String) か?"; } public Object call(Object[] a) { return (a[0] instanceof String) ? LL.S_T : null; } }, new Callable ("integerp", 1) { { doc = "(integerp x) => x が整数 (Integer か BigInteger) か?"; } public Object call(Object[] a) { Object x = a[0]; return (x instanceof Integer || x instanceof BigInteger) ? LL.S_T : null; } }, new Callable ("floatp", 1) { { doc = "(floatp x) => x が浮動小数点数 (Double) か?"; } public Object call(Object[] a) { return (a[0] instanceof Double) ? LL.S_T : null; } }, new Callable ("symbolp", 1) { { doc = "(symbolp x) => x がシンボル (Symbol または null) か?"; } public Object call(Object[] a) { Object x = a[0]; return (x == null || x instanceof Symbol) ? LL.S_T : null; } }, new Callable ("keywordp", 1) { { doc = "(keywordp x) => x がキーワードか?"; } public Object call(Object[] a) { return (a[0] instanceof Symbol.Keyword) ? LL.S_T : null; } }, new Callable ("vectorp", 1) { { doc = "(vectorp x) => x がベクトル (Object[]) か?"; } public Object call(Object[] a) { return (a[0] instanceof Object[]) ? LL.S_T : null; } }, new Callable ("eql", 2) { { doc = "(eql x y) => x と y が同じ整数,実数,または参照か?"; } public Object call(Object[] a) { return eql(a[0], a[1]) ? LL.S_T : null; } }, new Callable ("string=", 2) { { doc = "(string= s1 s2) => s1 と s2 が同じ文字列か?"; } public Object call(Object[] a) { String s1 = asString(a[0]); String s2 = asString(a[1]); return s1.equals(s2) ? LL.S_T : null; } }, new Callable ("list", 1, Callable.Option.HAS_REST, Callable.Option.IS_LAZY) { { doc = "(list ...)"; } public Object call(Object[] a) { return a[0]; } }, new Callable ("vector", 1, Callable.Option.HAS_REST, Callable.Option.IS_LAZY) { { doc = "(vector ...) => 引数を要素とするベクトル"; } public Object call(Object[] a) { ArrayList x = new ArrayList (); if (a[0] != null) for (Object e: (Cell) a[0]) x.add(e); return x.toArray(); } }, new Callable ("make-vector", 2, Callable.Option.IS_LAZY) { { doc = "(make-vector L E) => 長さ L 各要素 E のベクトル"; } public Object call(Object[] a) { int length = (Integer) LL.force(a[0]); Object element = a[1]; Object[] x = new Object[length]; for (int i = 0; i < length; i++) x[i] = element; return x; } }, new Callable ("prin1", 1) { { doc = "(prin1 x): x を印字する (文字列は引用符付き)"; } public Object call(Object[] a, IInterp interp, Cell env) { PrintWriter pw = interp.getWriter(); pw.print(LL.str(a[0], true)); pw.flush(); // (terpri) に任せるべきかもしれないが… return a[0]; } }, new Callable ("princ", 1) { { doc = "(princ x): x を印字する (文字列は引用符なし)"; } public Object call(Object[] a, IInterp interp, Cell env) { PrintWriter pw = interp.getWriter(); pw.print(LL.str(a[0], false)); pw.flush(); // (terpri) に任せるべきかもしれないが… return a[0]; } }, new Callable ("terpri", 0) { { doc = "(terpri): 印字改行する"; } public Object call(Object[] a, IInterp interp, Cell env) { PrintWriter pw = interp.getWriter(); pw.println(); return true; } }, new Callable ("read", 0) { { doc = "(read) => 入力から読み取った式"; } public Object call(Object[] a, IInterp interp, Cell env) throws IOException { LispReader lr = interp.getReader(); return lr.read(); } }, new Callable ("+", 1, Callable.Option.HAS_REST) { { doc = "算術加算 (+ ...); (+ 2 3) => 5; (+) => 0"; } public Object call(Object[] a) { Number x = (Integer) 0; for (Cell j = (Cell) a[0]; j != null; j = j.getCdrCell()) { Number y = (Number) j.car; if (x instanceof Integer && y instanceof Integer) { x = reg(x.longValue() + y.longValue()); } else if (x instanceof Double || y instanceof Double) { x = x.doubleValue() + y.doubleValue(); } else { if (x instanceof Integer) x = BigInteger.valueOf(x.longValue()); else if (y instanceof Integer) y = BigInteger.valueOf(y.longValue()); x = reg(((BigInteger) x).add((BigInteger) y)); } } return x; } }, new Callable ("*", 1, Callable.Option.HAS_REST) { { doc = "算術乗算 (* ...); (* 2 3) => 6; (*) => 1"; } public Object call(Object[] a) { Number x = (Integer) 1; for (Cell j = (Cell) a[0]; j != null; j = j.getCdrCell()) { Number y = (Number) j.car; if (x instanceof Integer && y instanceof Integer) { x = reg(x.longValue() * y.longValue()); } else if (x instanceof Double || y instanceof Double) { x = x.doubleValue() * y.doubleValue(); } else { if (x instanceof Integer) x = BigInteger.valueOf(x.longValue()); else if (y instanceof Integer) y = BigInteger.valueOf(y.longValue()); x = reg(((BigInteger) x).multiply((BigInteger) y)); } } return x; } }, new Callable ("/", 3, Callable.Option.HAS_REST) { { doc = "算術除算 (/ x y ...); (/ 6 5) => 1; (/ 6 5.0) => 1.2"; } public Object call(Object[] a) { Number x = (Number) a[0]; Cell yy = new Cell (a[1], a[2]); for (Cell j = yy; j != null; j = j.getCdrCell()) { Number y = (Number) j.car; if (x instanceof Integer && y instanceof Integer) { x = reg(x.longValue() / y.longValue()); // 注: 8bit演算で -128 / -1 は? } else if (x instanceof Double || y instanceof Double) { x = x.doubleValue() / y.doubleValue(); } else { if (x instanceof Integer) x = BigInteger.valueOf(x.longValue()); else if (y instanceof Integer) y = BigInteger.valueOf(y.longValue()); x = reg(((BigInteger) x).divide((BigInteger) y)); } } return x; } }, new Callable ("-", 2, Callable.Option.HAS_REST) { { doc = "算術減算 (- x ...); (- 10) => -10; (- 10 2) => 8"; } public Object call(Object[] a) { Number x = (Number) a[0]; Cell yy = (Cell) a[1]; if (yy == null) { if (x instanceof Integer) return reg(- x.longValue()); else if (x instanceof Double) return - x.doubleValue(); else return reg(((BigInteger) x).negate()); } else { for (Cell j = yy; j != null; j = j.getCdrCell()) { Number y = (Number) j.car; if (x instanceof Integer && y instanceof Integer) { x = reg(x.longValue() - y.longValue()); } else if (x instanceof Double || y instanceof Double) { x = x.doubleValue() - y.doubleValue(); } else { if (x instanceof Integer) x = BigInteger.valueOf(x.longValue()); else if (y instanceof Integer) y = BigInteger.valueOf(y.longValue()); x = reg(((BigInteger) x).subtract((BigInteger) y)); } } return x; } } }, new Callable ("%", 2) { { doc = "算術剰余 (% a b); (% 5 7) => 5"; } public Object call(Object[] a) { Number x = (Number) a[0]; Number y = (Number) a[1]; if (x instanceof Integer && y instanceof Integer) { x = x.intValue() % y.intValue(); } else if (x instanceof Double || y instanceof Double) { x = x.doubleValue() % y.doubleValue(); } else { if (x instanceof Integer) x = BigInteger.valueOf(x.longValue()); else if (x instanceof Integer) x = BigInteger.valueOf(y.longValue()); x = reg(((BigInteger) x).remainder((BigInteger) y)); } return x; } }, new Callable ("=", 2) { { doc = "算術比較 (= a b): a と b が数として等しいか?"; } public Object call(Object[] a) { Number x = (Number) a[0]; Number y = (Number) a[1]; if (x instanceof Integer && y instanceof Integer) { return (x.intValue() == y.intValue()) ? LL.S_T : null; } else if (x instanceof Double || y instanceof Double) { return (x.doubleValue() == y.doubleValue()) ? LL.S_T : null; } else { if (x instanceof Integer) x = BigInteger.valueOf(x.longValue()); else if (y instanceof Integer) y = BigInteger.valueOf(y.longValue()); return (((BigInteger) x).compareTo((BigInteger) y) == 0) ? LL.S_T : null; } } }, new Callable ("<", 2) { { doc = "算術比較 (< a b): a < b か?"; } public Object call(Object[] a) { Number x = (Number) a[0]; Number y = (Number) a[1]; if (x instanceof Integer && y instanceof Integer) { return (x.intValue() < y.intValue()) ? LL.S_T : null; } else if (x instanceof Double || y instanceof Double) { return (x.doubleValue() < y.doubleValue()) ? LL.S_T : null; } else { if (x instanceof Integer) x = BigInteger.valueOf(x.longValue()); else if (y instanceof Integer) y = BigInteger.valueOf(y.longValue()); return (((BigInteger) x).compareTo((BigInteger) y) < 0) ? LL.S_T : null; } } }, new Callable ("float", 1) { { doc = "(float 数) => 数を浮動小数点数にした値"; } public Object call(Object[] a) { Number x = (Number) a[0]; return x.doubleValue(); } }, new Callable ("truncate", 1) { { doc = "(truncate 数) => 数をゼロの方向へ丸めた整数"; } public Object call(Object[] a) { Number x = (Number) a[0]; if (x instanceof Integer || x instanceof BigInteger) { return x; } else { long i = x.longValue(); double f = x.doubleValue(); double delta = f - i; if (-1.0 < delta && delta < 1.0) // 検算 return reg(i); else throw new ArithmeticException ("out of range: " + x); } } }, new Callable ("load", 1) { { doc = "(load file-name): Lisp スクリプトファイルを実行する"; } public Object call(Object[] a, IInterp interp, Cell env) throws IOException { String fileName = (String) a[0]; InputStream stream = new FileInputStream (fileName); IInput script = new LinesFromInputStream (stream); return interp.run(script, null); } }, new Callable ("eval", 1) { { doc = "(eval x) => x を大域的な環境で評価した値"; } public Object call(Object[] a, IInterp interp, Cell env) { return interp.eval(a[0], null); } }, new Callable ("apply", 2) { { doc = "(apply fn (...)) => fn を引数のリストに適用した値"; } public Object call(Object[] a, IInterp interp, Cell env) { Function fn = (Function) a[0]; Cell arg = (Cell) a[1]; return fn.apply(arg, interp, env); } }, new Callable ("force", 1) { { doc = "(force x) => x ただし x が約束ならばそれをかなえる"; } public Object call(Object[] a) { return a[0]; // 引数渡しの時にもうかなえられている } }, new Callable ("rplaca", 2, Callable.Option.IS_LAZY) { { doc = "(rplaca x y): x の car を y で置き換える"; } public Object call(Object[] a) { Object x = LL.force(a[0]); ((Cell) x).car = a[1]; return a[1]; // 結果は約束のままかもしれない } }, new Callable ("rplacd", 2, Callable.Option.IS_LAZY) { { doc = "(rplacd x y): x の cdr を y で置き換える"; } public Object call(Object[] a) { Object x = LL.force(a[0]); ((Cell) x).cdr = a[1]; return a[1]; // 結果は約束のままかもしれない } }, new Callable ("throw", 2, Callable.Option.IS_LAZY) { { doc = "(throw tag value): tag を付けて value を送出する"; } public Object call(Object[] a) { Object x = LL.force(a[0]); throw new LispThrowException (x, a[1]); } // value は約束のままかもしれない }, new Callable ("aref", 2) { { doc = "(aref array index)"; } public Object call(Object[] a) { Object x = a[0]; int i = (Integer) a[1]; if (x instanceof Object[]) return ((Object[]) x)[i]; else return (int) ((String) x).charAt(i); } }, new Callable ("aset", 3, Callable.Option.IS_LAZY) { // Emacs Lisp と異なり,要素への代入はベクトルに限る。 { doc = "(aset vector index value): vector[index] := value"; } public Object call(Object[] a) { Object x = LL.force(a[0]); int i = (Integer) LL.force(a[1]); Object value = a[2]; ((Object[]) x)[i] = value; return value; // value は約束のままかもしれない } }, new Callable ("mapcar", 2) { { doc = "(mapcar fn (...)) => 各要素に fn を適用したリスト"; } public Object call(Object[] a, final IInterp interp, final Cell env) { final Function f = (Function) a[0]; Iterable list = toIterable(a[1]); LL.IUnary fn = new LL.IUnary () { public Object apply(Object e) { return f.apply(new Cell (e, null), interp, env); } }; return LL.mapcar(list, fn); } }, new Callable ("mapc", 2) { { doc = "(mapc fn (...)): 各要素に fn を順に適用する"; } public Object call(Object[] a, final IInterp interp, final Cell env) { Function f = (Function) a[0]; Object x = a[1]; if (x != null) for (Object e: toIterable(x)) f.apply(new Cell (e, null), interp, env); return x; } }, new Callable ("length", 1) { { doc = "(length x): 要素数"; } public Object call(Object[] a) { Object x = a[0]; if (x == null) { return 0; } else if (x instanceof Object[]) { return ((Object[]) x).length; } else if (x instanceof String) { return ((String) x).length(); } else { int i = 0; for (Object e: toIterable(x)) i++; return i; } } }, new Callable ("string-to-char", 1) { { doc = "(string-to-char \"ABC\") => 65"; } public Object call(Object[] a) { String s = (String) a[0]; if (s.length() == 0) return 0; else return (int) s.charAt(0); } }, new Callable ("number-to-string", 1) { { doc = "(number-to-string -23) => \"-23\""; } public Object call(Object[] a) { Number x = (Number) a[0]; return x.toString(); } }, new Callable ("string-to-number", 1) { // Emacs Lisp と異なり,Lisp 式の数の読み取りと一致させる。 { doc = "(string-to-number \" 444.3622 \") => 444.3622"; } public Object call(Object[] a) throws IOException { IInput input = new LinesFromString ((String) a[0]); LispReader reader = new LispReader (input); try { Object x = reader.read(); if (x instanceof Number) return x; } catch (EvalException ex) { ; // 不正な式は 0 として扱う } // LinesFromString は close() をしなくてもよい return 0; } }, new Callable ("_string+", 2) { { doc = "(_string+ str1 str2) => str1 + str2"; } public Object call(Object[] a) { return (String) a[0] + (String) a[1]; } }, new Callable ("_sequence-to-string", 1) { { doc = "(_sequence-to-string '(1 2 3)) => \"\\x01\\x02\\x03\""; } public Object call(Object[] a) { Object x = a[0]; if (x == null) { return ""; } else if (x instanceof String) { return x; } else { StringBuilder sb = new StringBuilder (); for (Object e: toIterable(x)) { Number n = (Number) e; char ch = (char) n.intValue(); sb.append(ch); } return sb.toString(); } } }, new Callable ("_vector+", 2) { { doc = "(_vector+ [1 2] [3 4]) => [1 2 3 4]"; } public Object call(Object[] a) { Object[] x = (Object[]) a[0]; Object[] y = (Object[]) a[1]; Object[] z = new Object[x.length + y.length]; for (int i = 0; i < x.length; i++) z[i] = x[i]; for (int i = 0; i < y.length; i++) z[i + x.length] = y[i]; return z; } }, new Callable ("_sequence-to-vector", 1) { { doc = "(_sequence-to-vector \"abc\") => [97 98 99]"; } public Object call(Object[] a) { ArrayList x = new ArrayList (); if (a[0] != null) for (Object e: toIterable(a[0])) x.add(e); return x.toArray(); } }, new Callable ("_list+", 2) { { doc = "(_list+ '(a b) '(c d)) => (a b c d)"; } public Object call(Object[] a) { Cell list = (Cell) a[0]; Object tail = a[1]; Object z = null; Cell y = null; if (list != null) for (Object e: list) { Cell x = new Cell (e, null); if (z == null) z = x; else y.cdr = x; y = x; } if (z == null) z = tail; else y.cdr = tail; return z; } }, new Callable ("_sequence-to-list", 1) { { doc = "(_sequence-to-list \"abc\") => (97 98 99)"; } public Object call(Object[] a) { Object x = a[0]; if (x == null || x instanceof Cell) return x; else return LL.mapcar(toIterable(x), null); } }, new Callable ("dump", 0) { { doc = "(dump) => (大域的に定義されたシンボルの集合 環境)"; } public Object call(Object[] a, IInterp interp, Cell env) { Map map = interp.getSymbolTable(); Set keys = map.keySet(); Object[] symbols = keys.toArray(); Arrays.sort(symbols); return LL.list(symbols, env); } }, new Callable ("java-load", 2) { { doc = "(java-load クラス名 静的公開フィールド名): " + "フィールド値を Callable[] として関数を取り込む"; } public Object call(Object[] a, IInterp interp, Cell env) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { String className = (String) a[0]; String fieldName = (String) a[1]; Class klass = Class.forName(className); Field field = klass.getField(fieldName); Callable[] fs = (Callable[]) field.get(null); interp.load(fs); return fs; } }, new Callable ("help", 1) { { doc = "(help callable): callable を説明する"; } public Object call(Object[] a, IInterp interp, Cell env) { if (a[0] instanceof Callable) { Callable c = (Callable) a[0]; if (c.doc != null) { PrintWriter pw = interp.getWriter(); pw.println(c.doc); } } return a[0]; } }, new Callable ("prelude", 0) { { doc = "(prelude): 初期化スクリプトの内容を印字する"; } public Object call(Object[] a, IInterp interp, Cell env) throws IOException { return printResource(LL.class, LL.PRELUDE, interp); } }, new Callable ("copyright", 0) { { doc = "(copyright): 著作権を表示する"; } public Object call(Object[] a, IInterp interp, Cell env) throws IOException { return printResource(LL.class, LL.COPYRIGHT, interp); } } }; /** 二つの引数が同じ整数,実数,または参照か? * @param a 任意の Lisp 値 * @param b 任意の Lisp 値 * @return Lisp の eql 関数としての比較結果 */ public static boolean eql(Object a, Object b) { if (a == b) { // 同じ参照または nil か? return true; } else if (a instanceof Number && b instanceof Number) { // 数か? Number x = (Number) a; Number y = (Number) b; if (x instanceof Double) { return (y instanceof Double && x.doubleValue() == y.doubleValue()); } else if (y instanceof Double) { return false; } else { // x と y は整数 (Integer か BigInteger) if (x instanceof Integer) if (y instanceof Integer) return x.intValue() == y.intValue(); else x = BigInteger.valueOf(x.longValue()); else if (y instanceof Integer) y = BigInteger.valueOf(y.longValue()); return ((BigInteger) x).compareTo((BigInteger) y) == 0; } } else { return false; } } /** null, シンボル,文字列に対する文字列値 * @param x Lisp 値,ただし nil かシンボルか文字列 * @return 引数の Lisp 値としての文字列表現 */ public static String asString(Object x) { if (x == null || x instanceof Symbol || x instanceof String) return LL.str(x, false); else throw new EvalException ("string or symbol expected", x); } /** map 系ユーティリティ. * 引数が null, Iterable ならばそのまま返す。 * Object[] ならば List にラップして返す。 * String ならば,対応する文字コードの Integer 値の並びを * 返す Iterable を作成して,それを返す。 * @param x null, Iterable, Object[] または String * @return 引数の各要素を順に与える Iterable 値 */ public static Iterable toIterable(Object x) { if (x == null || x instanceof Iterable) { return (Iterable) x; } else if (x instanceof Object[]) { return Arrays.asList((Object[]) x); } else { final String s = (String) x; return new Iterable () { public Iterator iterator() { return new Iterator () { int n = s.length(); int i = 0; public boolean hasNext() { return i < n; } public Integer next() { if (i < n) { int ch = (int) s.charAt(i); i++; return ch; } else { throw new NoSuchElementException (); } } public void remove() { throw new UnsupportedOperationException (); } }; } }; } } /** 算術ユーティリティ. * long 値をできれば int 値に,できなければ BigInteger 値にする。 * @param x 正規化したい数値 * @return 引数に等しい Integer または BigInteger のオブジェクト */ public static Number reg(long x) { int i = (int) x; return (i == x) ? i : BigInteger.valueOf(x); } /** 算術ユーティリティ. * BigInteger 値をできれば int 値に,できなければそのままにする。 * @param x 正規化したい数値 * @return 引数に等しい Integer または BigInteger のオブジェクト */ public static Number reg(BigInteger x) { return (x.bitLength() < 32) ? x.intValue() : x; } /** クラスのリソースをテキストとして印字し,その行数を返す。 * @param klass 対象とするクラス * @param name 対象とするリソース名 * @param interp ここから印字に用いる PrintWriter を得る。 * @return 印字行数 * @throws IOException リソースの入出力に関して発生した例外 */ public static int printResource(Class klass, String name, IInterp interp) throws IOException { PrintWriter pw = interp.getWriter(); IInput input = new LinesFromInputStream (klass.getResourceAsStream(name)); try { int count = 0; for (;;) { String line = input.readLine(false); if (line == null) break; pw.println(line); count++; } return count; } finally { input.close(); } } } // BuiltInFunctions package com.jimmy.model; import java.math.BigDecimal; public class LineChartPluginEntity extends BaseChartPluginEntity { // private String lineChartX; //x轴数据,表示折线图名称 private BigDecimal lineChartY; //y轴数据,表示折线图值 private String lineGroupName; //分类名称 private String color; // public String getLineChartX() { return lineChartX; } public void setLineChartX(String lineChartX) { this.lineChartX = lineChartX; } public BigDecimal getLineChartY() { return lineChartY; } public void setLineChartY(BigDecimal lineChartY) { this.lineChartY = lineChartY; } public String getLineGroupName() { return lineGroupName; } public void setLineGroupName(String lineGroupName) { this.lineGroupName = lineGroupName; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } } costinm/dmesh package com.github.costinm.dmesh.lm3; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.net.NetworkCapabilities; import android.net.NetworkRequest; import android.net.NetworkSpecifier; import android.net.wifi.aware.AttachCallback; import android.net.wifi.aware.DiscoverySessionCallback; import android.net.wifi.aware.IdentityChangedListener; import android.net.wifi.aware.PeerHandle; import android.net.wifi.aware.PublishConfig; import android.net.wifi.aware.PublishDiscoverySession; import android.net.wifi.aware.SubscribeConfig; import android.net.wifi.aware.SubscribeDiscoverySession; import android.net.wifi.aware.WifiAwareManager; import android.net.wifi.aware.WifiAwareNetworkSpecifier; import android.net.wifi.aware.WifiAwareSession; import android.os.Build; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import android.widget.Toast; import androidx.annotation.RequiresApi; import com.github.costinm.dmesh.android.msg.MsgMux; import com.github.costinm.dmesh.android.util.Hex; import java.util.HashMap; import java.util.List; import java.util.Map; @TargetApi(Build.VERSION_CODES.O) public class Nan { private static final String TAG = "DM/wifi/nan"; static Map devices = new HashMap<>(); public WifiAwareManager nanMgr; public String nanId; Context ctx; Wifi wifi; WifiAwareSession nanSession; // Not null if publish session active and nan active PublishDiscoverySession pubSession; // Not null if sub session active SubscribeDiscoverySession subSession; // Intended status of NAN subscription. subType indicates the type. boolean nanSub; int subType = SubscribeConfig.SUBSCRIBE_TYPE_ACTIVE; // Intended status of NAN publishing. boolean nanPub; int pubType = PublishConfig.PUBLISH_TYPE_SOLICITED; // Intended status of NAN radio, based on command/setting. // If true, when possible radio will be started. boolean nanActive; byte[] nanMac; String pubServiceName = "dmesh"; byte[] pubServiceInfo; // called when mgr reports 'isAvailable'. NAN may be turned off when P2P is enabled or in // many other cases. When it returns, if we sub or adv attach will be called again. int msgId; public Nan(Wifi wifi) { this.wifi = wifi; this.ctx = wifi.ctx; nanMgr = ctx.getSystemService(WifiAwareManager.class); if (nanMgr == null) { return; } if (nanMgr.getCharacteristics() != null) { Log.d(TAG, "/NAN/Char" + nanMgr.getCharacteristics().getMaxServiceNameLength() + "/" + nanMgr.getCharacteristics().getMaxServiceSpecificInfoLength() + " " + nanMgr.isAvailable()); } else { Log.d(TAG, "/NAN/Avail" + nanMgr.isAvailable()); } } boolean isAvailable() { return nanMac != null && nanMgr != null && nanMgr.isAvailable(); } /** * Start the NAN radio, and after that possibly publish or subscribe, if the mode is enabled. * Once attach succeeds the radio will send discovery beacons and participate in NAN master. */ @RequiresApi(api = Build.VERSION_CODES.O) private void startNanRadio() { if (nanMgr == null) { return; } nanActive = true; if (!nanMgr.isAvailable()) { return; } Log.d(TAG, "/NAN/ATTACH"); try { nanMgr.attach(new AttachCallback() { @Override public void onAttached(WifiAwareSession session) { super.onAttached(session); nanSession = session; if (nanPub) { publish(); } if (nanSub) { startNanSub(); } MsgMux.get(ctx).publish("/net/NAN/Attach"); } @Override public void onAttachFailed() { super.onAttachFailed(); MsgMux.get(ctx).publish("/net/NAN/AttachError"); } }, new IdentityChangedListener() { @Override public void onIdentityChanged(byte[] mac) { super.onIdentityChanged(mac); nanMac = mac; nanId = new String(Hex.encode(mac)); MsgMux.get(ctx).publish("/net/NAN/MAC/" + nanId); wifi.sendWifiDiscoveryStatus("/nan/id", ""); } }, null); } catch (Throwable t) { Log.d(TAG, "/NAN/ " + t); MsgMux.get(ctx).publish("/net/NAN/AttachError", "err", t.getMessage()); } } /** * Set nan radio desired state. *

* If on - will attempt to attach, and if not possible will attach when it it becomes so. *

* If off, close the NAN session, will stop sending discovery beacons - and not start again. */ public void nanRadio(boolean on) { nanActive = on; if (on) { startNanRadio(); } else { nanActive = false; // TODO: for now auto-starts if available. if (nanSession == null) { return; } nanSession.close(); nanSession = null; nanId = null; // will be reset on next start. } } void onDiscovered(PeerHandle peerHandle, byte[] serviceSpecificInfo, boolean byPublisher) { Device bd = new Device(peerHandle, serviceSpecificInfo); Device old = devices.get(bd.id); if (old == null) { onDiscovery(bd, bd.id, true); } else { // See BLE - it keeps discovering device in range. if (SystemClock.elapsedRealtime() - old.lastScan > 120000) { onDiscovery(bd, bd.id, false); } } devices.put(bd.id, bd); String info = new String(serviceSpecificInfo); // for debugging if (byPublisher) { // Used with active sub and passive pub MsgMux.get(ctx).publish("/net/NAN/PubServiceDiscovered/" + info + "/" + peerHandle); bd.nanSession = pubSession; } else { // Used with active pub and passive sub MsgMux.get(ctx).publish("/net/NAN/SubServiceDiscovered/" + info + "/" + peerHandle); bd.nanSession = subSession; } send(bd.id, "FOUND"); //conNan(bd.id); } private void onDiscovery(Device bd, String id, boolean b) { wifi.sendWifiDiscoveryStatus("nan", ""); } @RequiresApi(api = Build.VERSION_CODES.O) private void publish() { PublishConfig pub = new PublishConfig.Builder().setServiceName(pubServiceName) .setPublishType(pubType) // silent, but respond to active requests .setTerminateNotificationEnabled(true) .setServiceSpecificInfo(wifi.adv.getBytes()) .build(); nanSession.publish(pub, new MyNanCallback(true) { @Override public void onPublishStarted(PublishDiscoverySession session) { super.onPublishStarted(session); Log.d(TAG, "/NAN/PubStart"); MsgMux.get(ctx).publish("/net/NAN/PubStart"); pubSession = session; } @Override public void onSessionTerminated() { super.onSessionTerminated(); pubSession = null; MsgMux.get(ctx).publish("/net/NAN/PubStop", "dev", "" + devices); } @Override public void onMessageReceived(PeerHandle peerHandle, byte[] message) { super.onMessageReceived(peerHandle, message); String msg = new String(message); if (msg.startsWith("PING")) { pubSession.sendMessage(peerHandle, 1, "PONGP".getBytes()); Toast.makeText(wifi.ctx, "PINGP " + msg, Toast.LENGTH_SHORT); } else if (msg.equals("CON")) { NetworkSpecifier ns; if (Build.VERSION.SDK_INT >= 29) { ns = new WifiAwareNetworkSpecifier.Builder(pubSession, peerHandle).build(); } else { ns = pubSession.createNetworkSpecifierOpen(peerHandle); } NetworkRequest nr = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI_AWARE) .setNetworkSpecifier(ns).build(); wifi.cm.requestNetwork(nr, new Wifi.ConnectivityCallback(wifi), 10000); pubSession.sendMessage(peerHandle, 1, "CONS".getBytes()); } else { Toast.makeText(wifi.ctx, "NAN: " + msg, Toast.LENGTH_SHORT); } MsgMux.get(ctx).publish("/net/NAN/TXT/" + msg + "/" + peerHandle); } }, null); } public void onWifiAwareStateChanged(Intent i) { i.getBooleanExtra("foo", true); Log.d("NAN", "State changed " + i.getAction() + " " + i.getExtras()); if (isAvailable()) { if (nanActive) { startNanRadio(); } } else { nanSession = null; MsgMux.get(ctx).publish("/net/NAN/STOP"); } } public void pub(boolean active) { nanPub = true; pubType = active ? PublishConfig.PUBLISH_TYPE_UNSOLICITED : PublishConfig.PUBLISH_TYPE_SOLICITED; if (!isAvailable()) { nanRadio(true); return; } if (pubSession == null) { if (nanSession == null) { startNanRadio(); // will use nanAnnActive to activate publish when attached } else { publish(); } } } public void stopPub() { nanPub = false; if (pubSession != null) { pubSession.close(); pubSession = null; } } public void sub(Handler h, boolean active) { subType = active ? SubscribeConfig.SUBSCRIBE_TYPE_ACTIVE : SubscribeConfig.SUBSCRIBE_TYPE_PASSIVE; nanSub = active; if (nanSession == null) { nanRadio(true); // will set sub session } else { startNanSub(); } } public void stopSub() { nanSub = false; if (subSession == null) { return; } subSession.close(); subSession = null; } /** * Start a subscribe discovery session. *

* Will stay active until 'stop' is called. */ private void startNanSub() { SubscribeConfig cfg = new SubscribeConfig.Builder() .setServiceName("dmesh") .setServiceSpecificInfo(wifi.adv.getBytes()) .setSubscribeType(subType) .setTerminateNotificationEnabled(true) .build(); Log.d(TAG, "/NAN/Subscribe"); nanSession.subscribe(cfg, new MyNanCallback(false) { @Override public void onSubscribeStarted(SubscribeDiscoverySession session) { super.onSubscribeStarted(session); Log.d(TAG, "/NAN/SubStart" + session); MsgMux.get(ctx).publish("/net/NAN/SubStart"); subSession = session; } @Override public void onSessionTerminated() { super.onSessionTerminated(); subSession = null; MsgMux.get(ctx).publish("/net/NAN/SubStop", "dev", "" + devices); } @Override public void onMessageReceived(final PeerHandle peerHandle, byte[] message) { super.onMessageReceived(peerHandle, message); String msg = new String(message); if (msg.equals("CONS")) { wifi.delayHandler.postDelayed(new Runnable() { @Override public void run() { NetworkSpecifier ns; if (Build.VERSION.SDK_INT >= 29) { ns = new WifiAwareNetworkSpecifier.Builder(subSession, peerHandle).build(); } else { ns = subSession.createNetworkSpecifierOpen(peerHandle); } NetworkRequest nr = new NetworkRequest.Builder() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI_AWARE) .setNetworkSpecifier(ns).build(); wifi.cm.requestNetwork(nr, new Wifi.ConnectivityCallback(wifi), 10000); } }, 3000); } else { Toast.makeText(wifi.ctx, "NAN: " + msg, Toast.LENGTH_SHORT); } MsgMux.get(ctx).publish("/net/NAN/TXT/" + msg + "/" + peerHandle); Log.d(TAG, "NAN received: " + msg + " " + peerHandle); } }, null); } /** * Connect to a NAN device. * * @param id - the primary ID, from the pub announce. */ @RequiresApi(api = Build.VERSION_CODES.O) public void conNan(String id) { if ("0".equals(id) || "*".equals(id)) { for (Device d : devices.values()) { subSession.sendMessage(d.nan, msgId++, "CON".getBytes()); if ("0".equals(id)) { return; } } return; } Device d = devices.get(id); if (d == null || subSession == null) { return; } if (d.nan != null) { subSession.sendMessage(d.nan, msgId++, "CON".getBytes()); } } @RequiresApi(api = Build.VERSION_CODES.O) public void sendAll(String id) { if (subSession != null) { for (Device d : devices.values()) { if (d.nan != null && d.nanSession == subSession) { // May log: DiscoverySession: called on terminated session Log.d(TAG, "NAN send " + d.id + " " + d.nan + " " + msgId); subSession.sendMessage(d.nan, msgId++, id.getBytes()); } } } if (pubSession != null) { for (Device d : devices.values()) { if (d.nan != null && d.nanSession == pubSession) { // May log: DiscoverySession: called on terminated session Log.d(TAG, "NAN send pub " + d.id + " " + d.nan + " " + msgId); pubSession.sendMessage(d.nan, msgId++, id.getBytes()); } } } } @RequiresApi(api = Build.VERSION_CODES.O) public void send(String id, String msg) { Device d = devices.get(id); if (d != null && d.nan != null && d.nanSession != null) { d.nanSession.sendMessage(d.nan, msgId++, msg.getBytes()); } } @RequiresApi(api = Build.VERSION_CODES.O) class MyNanCallback extends DiscoverySessionCallback { private final boolean pub; public MyNanCallback(boolean pub) { this.pub = pub; } @Override public void onSessionTerminated() { devices.clear(); // TODO: only devices of given type super.onSessionTerminated(); } /** * It appears only subscriber discovers the publisher, not the other way around. *

* For both ends to know, we need to send a message (further discovery). * * @param peerHandle * @param serviceSpecificInfo * @param matchFilter */ @Override public void onServiceDiscovered(PeerHandle peerHandle, byte[] serviceSpecificInfo, List matchFilter) { Log.d(TAG, "/NAN/ServiceDiscovered " + (pub ? "pub" : "sub")); super.onServiceDiscovered(peerHandle, serviceSpecificInfo, matchFilter); onDiscovered(peerHandle, serviceSpecificInfo, pub); } @Override public void onSessionConfigUpdated() { super.onSessionConfigUpdated(); Log.d(TAG, "/NAN/PubSessionConfigUpdated"); } @Override public void onSessionConfigFailed() { super.onSessionConfigFailed(); MsgMux.get(ctx).publish("/net/NAN/PubSessionConfigFailed"); } @Override public void onServiceDiscoveredWithinRange(PeerHandle peerHandle, byte[] serviceSpecificInfo, List matchFilter, int distanceMm) { onServiceDiscovered(peerHandle, serviceSpecificInfo, matchFilter); } @Override public void onMessageSendSucceeded(int messageId) { super.onMessageSendSucceeded(messageId); Log.d(TAG, "/NAN/SENT/" + messageId); } @Override public void onMessageSendFailed(int messageId) { super.onMessageSendFailed(messageId); MsgMux.get(ctx).publish("/net/NAN/MSGERR", "id", Integer.toString(messageId)); } } } cryptpa/Ex_H package org.openpredict.exchange.beans; import lombok.Getter; @Getter public enum OrderType { LIMIT(0), MARKET(1); private final byte code; OrderType(int code) { this.code = (byte) code; } public static OrderType valueOf(long v) { return v == 0 ? LIMIT : MARKET; } } sgholamian/log-aware-clone-detectionLACCPlus/ActiveMQ/2086_2.java //,temp,ServerSessionImplTest.java,415,427,temp,AMQ4441Test.java,69,83 //,3 public class xxx { @Override public void run() { while (!done.get() && latch.getCount() > 0) { try { final PooledConnection pooledConnection = (PooledConnection) pooled.createConnection(); if (pooledConnection.getConnection() == null) { LOG.info("Found broken connection."); latch.countDown(); } pooledConnection.close(); } catch (JMSException e) { LOG.warn("Caught Exception", e); } } } };package messageutils; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import play.Play; /** * Class for saving and loading the messages data. *

* Default implementation uses files. To override this you should extend this * class and configure the class with the messages.resource property in the * application.conf. * * @author huljas */ public abstract class MessagesResource { /** * The default language without a language code. Localizations with this * language will be saved to the file "messages". */ public final static String DEFAULT_LANGUAGE = "default"; private static MessagesResource instance; /** * The singleton instance. * * @return The singleton instance. */ public static synchronized MessagesResource instance() { if (instance == null) { try { String resourceClass = MessagesUtil.getConfig( "messages.resource", null); if (StringUtils.isBlank(resourceClass)) { resourceClass = DefaultMessagesResource.class.getName(); } Class clazz = Class.forName(resourceClass, true, Play .application().classloader()); instance = (MessagesResource) clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } return instance; } /** * Loads the keys in the keep list. * * @return List of keys to keep. */ public abstract List loadKeepList(); /** * Loads the keys in the ignore list. * * @return List of keys to ignore. */ public abstract List loadIgnoreList(); /** * Loads messages for given language. * * @param language * The language to load values and keys for. * @return Mapping of key to value. */ public abstract Map loadMessages(String language); /** * Saves new value for given key. * * @param language * The language of the value. * @param key * The key to save. * @param value * The value for the key in the given language. */ public abstract void save(String language, String key, String value); /** * Adds key to keep list. * * @param key * The key to keep. */ public abstract void keep(String key); /** * Removes key from keep list. * * @param key * The key to remove. */ public abstract void removeKeep(String key); /** * Removes given keys. * * @param language * The language, where the keys will be removed from. * @param keys * The keys to remove. */ public abstract void removeAll(String language, List keys); /** * Ignores given keys. * * @param keys * The keys to ignore. */ public abstract void ignoreAll(List keys); /** * Unignores given keys. * * @param keys * The keys to unignore. */ public abstract void unignoreAll(List keys); } /* * Copyright 2009 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.openehealth.ipf.platform.camel.ihe.atna.util; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.HashMap; import org.apache.camel.CamelContext; import org.apache.camel.ProducerTemplate; import org.openhealthtools.ihe.atna.auditor.events.AuditEventMessage; import org.openhealthtools.ihe.atna.auditor.sender.AuditMessageSender; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; /** * An audit message sender that sends audit messages to a configured Camel * endpoint. When configured in a Spring application context, it is attempted to * auto-wire the required Camel context. * * @author */ public class CamelEndpointSender implements AuditMessageSender, InitializingBean, DisposableBean { public static final String HEADER_NAMESPACE = "org.openehealth.ipf.platform.camel.ihe.atna"; @Autowired(required=false) private CamelContext camelContext; private ProducerTemplate producerTemplate; private String endpointUriString; private URI endpointUriObject; /** * Sets the Camel context that contains the endpoint to send audit messages * to. This method needs only be used for setting the Camel context if * auto-wiring is not possible (e.g. in certain test environments). * * @param camelContext */ public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } /** * The endpoint URI to send audit messages to. * * @param endpointUri * @throws URISyntaxException */ public void setEndpointUri(String endpointUri) throws URISyntaxException { endpointUriString = endpointUri; endpointUriObject = new URI(endpointUri); } @Override public void afterPropertiesSet() throws Exception { producerTemplate = camelContext.createProducerTemplate(); producerTemplate.start(); } @Override public void destroy() throws Exception { producerTemplate.stop(); } @Override public void sendAuditEvent(AuditEventMessage[] msg) throws Exception { sendAuditEvent(msg, null, 0); } /** * Sends audit event messages to the configured endpoint URI. * * @param msg audit event message array. * @param addr ignored * @param port ignored */ @Override public void sendAuditEvent(AuditEventMessage[] msg, InetAddress addr, int port) throws Exception { for (AuditEventMessage m : msg) { m.setDestinationAddress(getDestinationAddress()); m.setDestinationPort(getDestinationPort()); HashMap headers = new HashMap(); headers.put(HEADER_NAMESPACE + ".destination.address", m.getDestinationAddress().getHostAddress()); headers.put(HEADER_NAMESPACE + ".destination.port", m.getDestinationPort()); headers.put(HEADER_NAMESPACE + ".datetime", m.getDateTime()); producerTemplate.sendBodyAndHeaders(endpointUriString, m.getAuditMessage().toString(), headers); } } private int getDestinationPort() { return endpointUriObject.getPort(); } private InetAddress getDestinationAddress() throws UnknownHostException { String host = endpointUriObject.getHost(); return InetAddress.getByName(host == null ? "0.0.0.0" : host); } } package br.com.mobiclub.quantoprima.ui.common; /** * */ public interface MobiClubActivity { public int getLayout(); } package de.siphalor.tweed.config.annotated; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface AConfigConstraint { Class value(); String param() default ""; } /* * Copyright 2017 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package org.skia.skqp; import android.content.Context; import android.content.res.AssetManager; import android.util.Log; import java.io.File; import java.io.IOException; public class SkQP { protected native void nInit(AssetManager assetManager, String dataDir, boolean experimentalMode); protected native float nExecuteGM(int gm, int backend) throws SkQPException; protected native String[] nExecuteUnitTest(int test); protected native void nMakeReport(); protected String[] mGMs; protected String[] mBackends; protected String[] mUnitTests; protected static final String kSkiaGM = "skqp_"; protected static final String kSkiaUnitTests = "skqp_unitTest"; protected static final String LOG_PREFIX = "org.skia.skqp"; static { System.loadLibrary("skqp_app"); } protected void runTests(Context context, String outputDirPath) { Log.i(LOG_PREFIX, "Output Dir: " + outputDirPath); File outputDir = new File(outputDirPath); try { ensureEmtpyDirectory(outputDir); } catch (IOException e) { Log.e(LOG_PREFIX, "ensureEmtpyDirectory:" + e.getMessage()); } // Note: nInit will initialize the mGMs, mBackends and mUnitTests fields. AssetManager assetManager = context.getResources().getAssets(); this.nInit(assetManager, outputDirPath, true); for (int backend = 0; backend < mBackends.length; backend++) { String classname = kSkiaGM + mBackends[backend]; for (int gm = 0; gm < mGMs.length; gm++) { String testName = kSkiaGM + mBackends[backend] + "_" +mGMs[gm]; float value = java.lang.Float.MAX_VALUE; String error = null; Log.w(LOG_PREFIX, "Running: " + testName); try { value = this.nExecuteGM(gm, backend); } catch (SkQPException exept) { error = exept.getMessage(); } if (error != null) { // Record error message and carry on. } else if (value != 0) { // Record failure and carry on. // SkQPRunner.Fail(desc, notifier, String.format( // "Image mismatch: error metric = %f", value)); } else { // Record success for this test. } } } for (int unitTest = 0; unitTest < mUnitTests.length; unitTest++) { String testName = kSkiaUnitTests + "_" + mUnitTests[unitTest]; Log.w(LOG_PREFIX, "Running: " + testName); String[] errors = this.nExecuteUnitTest(unitTest); if (errors != null && errors.length > 0) { for (String error : errors) { Log.w(LOG_PREFIX, "Error running " + testName + ":" + error); } } else { Log.i(LOG_PREFIX, "Test: " + testName + " finished successfully."); } } Log.i(LOG_PREFIX, "Finished running all tests."); nMakeReport(); } protected static void ensureEmtpyDirectory(File f) throws IOException { if (f.exists()) { delete(f); } if (!f.mkdirs()) { throw new IOException("Unable to create directory:" + f.getAbsolutePath()); } } protected static void delete(File f) throws IOException { if (f.isDirectory()) { for (File s : f.listFiles()) { delete(s); } } if (!f.delete()) { throw new IOException("Unable to delete:" + f.getAbsolutePath()); } } } /*-------------------------------------------------------------------------------------------------------------------*\ | Copyright (C) 2014 PayPal | | | | 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.paypal.selion.platform.web; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.yaml.snakeyaml.TypeDescription; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.Constructor; /** * A simple factory of {@link Page} objects */ public final class PageFactory { private PageFactory() { // Utility class. So hide the constructor } /** * Creates a instance of a {@link Page}. * * @param in * input stream of the Yaml File * @return an instance of the Page object * @throws IOException * if unable to read from the {@link InputStream}. Does not close the {@link InputStream} when this * occurs. */ public static Page getPage(InputStream in) throws IOException { Constructor constructor = new Constructor(Page.class); TypeDescription typeDesc = new TypeDescription(Page.class); typeDesc.putListPropertyType("pageValidators", String.class); typeDesc.putMapPropertyType("elements", String.class, GUIElement.class); constructor.addTypeDescription(typeDesc); Yaml yamlFile = new Yaml(constructor); Page page = (Page) yamlFile.load(new BufferedReader(new InputStreamReader(in, "UTF-8"))); try { in.close(); } catch (IOException e) { // NOSONAR Do Nothing } return page; } } training-base/src/main/java/com/winfred/training/juc/lock/StampedLockTest.java package com.winfred.training.juc.lock; import com.winfred.training.juc.concurrent.pool.ThreadPoolUtil; import java.util.concurrent.locks.StampedLock; /** * @author kevin */ public class StampedLockTest { private StampedLock stampedLock = new StampedLock(); private CacheTest cache = null; public static void main(String[] args) { StampedLockTest stampedLockTest = new StampedLockTest(); int max = 100; // for (int i = 0; i < max; i++) { // ThreadPoolUtil.doExecutor(() -> { // CacheTest test = stampedLockTest.getOrCreateCache(); // if (null != test) { // System.out.println("缓存获取成功: " + test.getKey()); // } // }); // } for (int i = 0; i < max; i++) { ThreadPoolUtil.doExecutor(() -> { CacheTest test = stampedLockTest.getOrCreateCacheWithLockV1(); if (null != test) { System.out.println("缓存获取成功: " + test.getKey()); } }); } // for (int i = 0; i < max; i++) { // ThreadPoolUtil.doExecutor(() -> { // CacheTest test = stampedLockTest.getOrCreateCacheWithLockV2(); // if (null != test) { // System.out.println("缓存获取成功: " + test.getKey()); // } // }); // } ThreadPoolUtil.destroy(); } public CacheTest getCache() { return cache; } public CacheTest createCache() { CacheTest cacheTest = new CacheTest(); try { System.out.println("------------> 开始创建缓存"); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } if (cache != null) { System.out.println("缓存已经存在"); throw new RuntimeException("缓存已经存在"); } cacheTest.setKey("ttt"); cacheTest.setField("fff"); cacheTest.setValue("vvv"); cache = cacheTest; return cache; } public CacheTest getOrCreateCache() { CacheTest cache = getCache(); if (cache != null) { return cache; } return createCache(); } public CacheTest getOrCreateCacheWithLockV1() { // 乐观读 long lockKey = stampedLock.tryOptimisticRead(); CacheTest cache; try { cache = getCache(); if (cache != null) { return cache; } if (lockKey == 0) { // 无锁, 加写锁 lockKey = stampedLock.writeLock(); } else { // 有读锁, 读锁升级写锁 long writeLockKey = stampedLock.tryConvertToWriteLock(lockKey); if (0 == writeLockKey) { // 读锁升级失败 stampedLock.unlockRead(lockKey); lockKey = stampedLock.writeLock(); } else { // 读锁升级写锁成功 lockKey = writeLockKey; } } cache = getCache(); if (cache != null) { return cache; } cache = createCache(); } finally { if (0 != lockKey) { stampedLock.unlock(lockKey); } } return cache; } public CacheTest getOrCreateCacheWithLockV2() { CacheTest cache; cache = getCache(); if (cache != null) { return cache; } long lockKey = stampedLock.tryWriteLock(); try { if (0L == lockKey) { lockKey = stampedLock.writeLock(); } cache = getCache(); if (cache != null) { return cache; } cache = createCache(); } finally { stampedLock.unlockWrite(lockKey); } return cache; } class CacheTest { private String key; private String field; private String value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getField() { return field; } public void setField(String field) { this.field = field; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } } 10-100 package edu.columbia.main.bing.phpBBScraper; import edu.columbia.main.LogDB; import edu.columbia.main.collection.BabelJob; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.log4j.Logger; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.List; /** * Created by Gideon on 4/24/15. */ public class BBJob extends BabelJob { private String threadNumber; private String forumNumber; private String origData; Logger log = Logger.getLogger(BBJob.class); public BBJob(String url, String lang, LogDB logDb) { super(url, lang, logDb, null); origData = data; setURL(); } public void setURL(){ String retValue = ""; try { URL tmp = new URL(this.data); retValue = tmp.getHost() + tmp.getPath(); } catch (MalformedURLException e) { log.error(e); } List params = null; try { params = URLEncodedUtils.parse(new URI(this.data), "UTF-8"); } catch (URISyntaxException e) { log.error(e); } for (org.apache.http.NameValuePair param : params) { if(param.getName().equals("f")) { retValue += "?f=" + param.getValue(); forumNumber = param.getValue(); } if(param.getName().equals("t")) threadNumber = param.getValue(); } this.data = retValue; } public String getURL() { return data; } public String getThreadNumber() { return threadNumber; } public boolean isValid(){ if(threadNumber != null && !threadNumber.isEmpty() && forumNumber !=null && !forumNumber.isEmpty()) return true; else return false; } @Override public String toString() { return this.origData; } public String getForumNumber() { return forumNumber; } } app/src/main/java/com/example/finalproject/SQLiteHelperConection.java package com.example.finalproject; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; import com.example.finalproject.utilidades.Utilidades; public class SQLiteHelperConection extends SQLiteOpenHelper { public SQLiteHelperConection(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(Utilidades.CREATE_USER_TABLE); db.execSQL(Utilidades.CREATE_BOOK_TABLE); db.execSQL(Utilidades.CREATE_GAME_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(Utilidades.DELETE_USER_TABLE); db.execSQL(Utilidades.DELETE_BOOK_TABLE); db.execSQL(Utilidades.DELETE_GAME_TABLE); onCreate(db); } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); if (!db.isReadOnly()) { db.execSQL("PRAGMA foreign_keys=ON;"); } } } 1-10 package org.qpython.qpy.plugin.model; import com.quseit.common.updater.updatepkg.UpdatePackage; import org.qpython.qpy.plugin.CloudPluginManager; import java.io.File; import io.realm.RealmObject; import io.realm.annotations.Ignore; import io.realm.annotations.PrimaryKey; public class CloudPluginBean extends RealmObject implements UpdatePackage { @PrimaryKey private String name; private String title; private String src; private int versionCode; private String versionDescription; private String description; private String path; @Ignore private String url; public CloudPluginBean() { } public CloudPluginBean(String name, String title, String src, int versionCode, String versionDescription, String description, String path, String url) { this.name = name; this.title = title; this.src = src; this.versionCode = versionCode; this.versionDescription = versionDescription; this.path = path; this.url = url; this.description = description; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSrc() { return src; } public void setSrc(String src) { this.src = src; } public int getVersionCode() { return versionCode; } public void setVersionCode(int versionCode) { this.versionCode = versionCode; } public void setVersionDescription(String versionDescription) { this.versionDescription = versionDescription; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @Override public String getVersion() { return String.valueOf(versionCode); } public String getVersionDescription() { return versionDescription; } @Override public String getDownloadUrl() { return url; } @Override public boolean checkVersion() { return CloudPluginManager.checkUpdate(this); } @Override public void install(File file) { CloudPluginManager.install(this, file, false); } } package com.showka.MyBatisDemo.kubun; import com.showka.MyBatisDemo.kubun.i.Kubun; import lombok.AllArgsConstructor; import lombok.Getter; @AllArgsConstructor @Getter public enum JigyoKubun implements Kubun { 販売("01"), レンタル("02"), 兼業("10"), EMPTY(""); private String code; } package com.skplanet.sascm.service; import java.util.List; import java.util.Map; public interface AraStrService { public Map selectStoreInfo(Map param) throws Exception; public List> giveCouponList(Map param) throws Exception; public List> listCouponList(Map param) throws Exception; public List> listPaymentList(Map param) throws Exception; public List> listCalculateList(Map param) throws Exception; public Map selectCampId(Map param) throws Exception; public int insertAraCamp(Map param) throws Exception; public int insertAraCampInfo(Map param) throws Exception; public int insertAraCampOff(Map param) throws Exception; public int insertAraCampChl(Map param) throws Exception; public int insertAraOffCpn(Map param) throws Exception; public int insertAraChlSms(Map param) throws Exception; public int insertApprReq(Map param) throws Exception; public List> selectApprReqList(Map param) throws Exception; public List> selectApprResList(Map param) throws Exception; public List> selectAllCpnList(Map param) throws Exception; public List> selectCouponList(Map param) throws Exception; public int giveCpnList(Map param) throws Exception; public List> selectPayCpnList(Map param) throws Exception; public List> selectNoPayCpnList(Map param) throws Exception; public List> selectTempCalcList(Map param) throws Exception; } // RobotBuilder Version: 0.0.2 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in th future. package org.usfirst.frc319.BobBAE2013.subsystems; import org.usfirst.frc319.BobBAE2013.RobotMap; import org.usfirst.frc319.BobBAE2013.commands.*; import edu.wpi.first.wpilibj.*; import edu.wpi.first.wpilibj.command.Subsystem; /** * */ public class DriveTrain extends Subsystem { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS SpeedController leftSpeedController = RobotMap.driveTrainLeftSpeedController; SpeedController rightSpeedController = RobotMap.driveTrainRightSpeedController; RobotDrive tankDrive = RobotMap.driveTrainTankDrive; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS // Put methods for controlling this subsystem // here. Call these from Commands. public void initDefaultCommand() { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND setDefaultCommand(new TankDrive()); // Set the default command for a subsystem here. //setDefaultCommand(new MySpecialCommand()); } public void TankDrive(Joystick stick){ double leftscale = 1; double rightscale = -1; tankDrive.tankDrive(stick.getRawAxis(5)*rightscale, stick.getRawAxis(2)*leftscale); } public void DriveBack(){ double leftscale = .7; double rightscale = .7; tankDrive.tankDrive(-1*leftscale, -1*rightscale); } public void TurnAround(){ double leftscale = .7; double rightscale = .7; tankDrive.tankDrive(1*leftscale, -1*rightscale); } public void Stop(){ tankDrive.tankDrive(0, 0); } } src/main/java/com/webank/webase/chain/mgr/deploy/req/ReqDeploy.java10-100 package com.webank.webase.chain.mgr.deploy.req; import java.util.List; import javax.validation.constraints.*; import com.webank.webase.chain.mgr.base.enums.DockerImageTypeEnum; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.NoArgsConstructor; /** * */ @Data @NoArgsConstructor @ApiModel(description = "部署链请求") public class ReqDeploy { @ApiModelProperty(value = "Chain id,由 WebServer 生成", example = "10", required = true) // @NotNull(message = "chain id error.") private int chainId; @ApiModelProperty(value = "Docker 镜像版本", example = "v2.5.0", required = true) @NotBlank(message = "Image tag version error.") private String version; @ApiModelProperty(value = "部署的主机信息列表,最少两台", required = true) @Size(min = 1, message = "At least 1 host.") private List deployHostList; @ApiModelProperty(value = "加密方式:0,非过密;1,国密", example = "0") @Min(0) @Max(1) private int encryptType; @ApiModelProperty(value = "镜像拉取方式, 0 : 手动拉取, 1: 官方自动拉取。默认 0", example = "0") private byte dockerImageType = DockerImageTypeEnum.PULL_OFFICIAL.getId(); @ApiModelProperty(value = "共识机制", example = "pbft") private String consensusType = "pbft"; @ApiModelProperty(value = "存储方式", example = "rocksdb") private String storageType = "rocksdb"; @ApiModelProperty(value = "链描述", example = "测试链") private String description; @ApiModelProperty(value = "链名称,默认等于 chain ID", example = "10") private String chainName; @Data @NoArgsConstructor public static class DeployHost { @ApiModelProperty(value = "主机所属公司 ID", example = "10", required = true) @Positive(message = "External company id error.") private int extCompanyId; @ApiModelProperty(value = "主机所属组织 ID", example = "10", required = true) @Positive(message = "External agency id error.") private int extOrgId; @ApiModelProperty(value = "主机在 WebServer 中的 ID", example = "10", required = true) @Positive(message = "External host id error.") private int extHostId; @ApiModelProperty(value = "主机 IP", example = "127.0.0.2", required = true) @NotBlank(message = "IP blank error.") private String ip; @ApiModelProperty(value = "主机 SSH 免密账号,默认 root", example = "root") private String sshUser = "root"; @ApiModelProperty(value = "主机 SSH 端口,默认 22", example = "22") private int sshPort = 22; @ApiModelProperty(value = "Docker daemon 端口,默认 2375,暂不使用", example = "2375") private int dockerDemonPort = 2375; @ApiModelProperty(value = "主机部署节点数量", example = "1") private int num = 1; @ApiModelProperty(value = "主机存放节点数据目录", example = "1") private String rootDirOnHost = "/root/fisco"; @ApiModelProperty(value = "默认的 JSON-RPC 端口", example = "8545") private int jsonrpcPort = 8545; @ApiModelProperty(value = "默认的 P2P 端口 ", example = "30300") private int p2pPort = 30300; @ApiModelProperty(value = "默认的 Channel 端口", example = "20200") private int channelPort = 20200; @ApiModelProperty(value = "默认的 Front 端口", example = "5002") private int frontPort = 5002; } } /* * 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.camel.component.workday.producer; import java.util.Map; import java.util.stream.Collectors; import org.apache.camel.component.workday.WorkdayConfiguration; import org.apache.camel.component.workday.WorkdayEndpoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The Workday Report producer. */ public class WorkdayReportProducer extends WorkdayDefaultProducer { public static final String WORKDAY_RASS_URL_TEMPLATE = "https://%s/ccx/service/customreport2/%s%s"; private static final Logger LOG = LoggerFactory.getLogger(WorkdayReportProducer.class); public WorkdayReportProducer(WorkdayEndpoint endpoint) { super(endpoint); } @Override public String prepareUri(WorkdayConfiguration configuration) { Map parameters = configuration.getParameters(); StringBuilder stringBuilder = new StringBuilder(configuration.getPath()); stringBuilder.append("?"); if (parameters.size() > 0) { String params = parameters.keySet().stream().map(k -> k + "=" + parameters.get(k)).collect(Collectors.joining("&")); stringBuilder.append(params); stringBuilder.append("&"); } stringBuilder.append("format="); stringBuilder.append(configuration.getReportFormat()); String uriString = String.format(WORKDAY_RASS_URL_TEMPLATE, configuration.getHost(), configuration.getTenant(), stringBuilder.toString()); return uriString; } }wienerri/plsql-formatter-settings package com.trivadis.plsql.formatter.settings; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import java.util.logging.LogManager; import org.junit.Assert; import oracle.dbtools.app.Format; import oracle.dbtools.app.Persist2XML; public abstract class ConfiguredTestFormatter { private final Format formatter; public ConfiguredTestFormatter() { super(); loadLoggingConf(); formatter = new Format(); configureFormatter(); } private void loadLoggingConf() { LogManager manager = LogManager.getLogManager(); try { manager.readConfiguration(Thread.currentThread().getContextClassLoader().getResourceAsStream("logging.conf")); } catch (SecurityException | IOException e) { e.printStackTrace(); } } private Map getOptions() { Map map; try { URL advancedFormat = Thread.currentThread().getContextClassLoader().getResource("trivadis_advanced_format.xml"); // symbolic link map = Persist2XML.read(advancedFormat); } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return map; } private String getArboriFileName() { URL customFormat = Thread.currentThread().getContextClassLoader().getResource("trivadis_custom_format.arbori"); // symbolic link return customFormat.getFile(); } private void configureFormatter() { Map map = getOptions(); for (String key : map.keySet()) { formatter.options.put(key, map.get(key)); } formatter.options.put(formatter.formatProgramURL, getArboriFileName()); } public Format getFormatter() { return formatter; } public void resetOptions() { configureFormatter(); } public void formatAndAssert(CharSequence expected) { formatAndAssert(expected, false); } public void formatAndAssert(CharSequence expected, boolean resetOptions) { try { String expectedTrimmed = expected.toString().trim(); String actual = formatter.format(expectedTrimmed); Assert.assertEquals(expectedTrimmed, actual); } catch (IOException e) { throw new RuntimeException(e); } finally { if (resetOptions) { resetOptions(); } } } } 1-10 /** * @author Nannf * @date 2020/11/18 8:57 * @description 实现 pow(x, n) ,即计算 x 的 n 次幂函数。 *

* 输入: 2.00000, 10 * 输出: 1024.00000 *

* 输入: 2.10000, 3 * 输出: 9.26100 *

* 输入: 2.00000, -2 * 输出: 0.25000 * 解释: 2-2 = 1/22 = 1/4 = 0.25 *

* -100.0 < x < 100.0 * n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。 */ public class Solution_50 { public static void main(String[] args) { System.out.println(new Solution_50().myPow(3, 5)); } public double myPow(double x, int n) { if (n > 0) { return dfs(x, n); } else { long b = -n; return 1 / dfs(x, b); } } // 栈溢出 private double dfs(double x, long n) { if (n == 0) { return 1; } long b = n / 2; if (n % 2 != 0) { return x * dfs(x * x, b); } else { return dfs(x * x, b); } } } 0 /* * 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 Stacks_and_Queues; /** * * @author Bansari */ //we will keep four information //1.Top index of first stack //2.Top index of second stack //3.Base of middle stack //4.Top index of middle stack public class ThreeStacksInOneArray { private int array[]; private int size; private int topleft; private int topright; private int topmiddle; private int basemiddle; public ThreeStacksInOneArray(int size){ if(size < 2) System.out.println("Could not initialize, Size should be greater than 2"); else{ this.size = size; topleft = -1; topright = size; basemiddle = size/2; topmiddle = basemiddle - 1; array = new int[size]; } } public void push(int stackId, int data){ if(stackId == 1){ if(topleft+1 == basemiddle){ if(stack3RightShiftable()){ shiftStack3Right(); array[++topleft] = data; }else return; }else{ array[++topleft] = data; } }else if(stackId == 2){ if(topright-1 == topmiddle){ if(stack3LeftShiftable()){ shiftStack3Left(); array[--topright] = data; }else return; }else{ array[--topright] = data; } }else if(stackId == 3){ if(topmiddle == topright - 1){ if(stack3LeftShiftable()){ shiftStack3Left(); array[++topmiddle] = data; }else return; }else{ array[++topmiddle] = data; } }else return; } public int pop(int stackId, int data){ if(stackId == 1){ if(topleft == -1) return 0; int num = array[this.topleft]; this.topleft = this.topleft - 1; return num; }else if(stackId == 2){ if(topright == -1) return 0; int num = array[this.topright]; this.topright = this.topright + 1; return num; }else if(stackId == 3){ if(topmiddle == basemiddle) return 0; int num = array[topmiddle]; if(topmiddle>basemiddle) topmiddle = topmiddle -1; } return 0; } public int top(int stackId){ if(stackId == 1){ if(topleft == -1) return 0; return array[topleft]; }else if(stackId == 2){ if(topright == this.size) return 0; return array[topright]; }else{ if(topmiddle == basemiddle){ return 0; } return array[topmiddle]; } } public void display(){ int i = this.topleft; int j = this.topright; int k = this.basemiddle+1; System.out.println("Printing left array elements"); while(i != -1){ System.out.println(this.array[i]); i--; } System.out.println("Printing right array elements"); while(j != (array.length)){ System.out.println(this.array[j]); j++; } System.out.println("Printing middle array elements"); while(k=basemiddle;i--){ array[i] = array[i-1]; } topmiddle++; basemiddle++; } public static void main(String args[]){ ThreeStacksInOneArray s = new ThreeStacksInOneArray(10); s.push(1,2); s.push(1,3); s.push(1, 4); s.push(2, 12); s.push(2, 13); s.push(2,14); s.push(3, 22); s.push(3, 23); s.push(3,24); s.display(); } } src/io/tmoore/treap/Treap.java package io.tmoore.treap; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.PriorityQueue; import java.util.Queue; import java.util.Spliterator; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class Treap> implements Collection { private TreapNode root = null; // CONSTRUCTORS @SuppressWarnings("WeakerAccess") public Treap() { } @SuppressWarnings("WeakerAccess") public Treap(Collection fromCollection) { addAll(fromCollection); } Treap(TreapNode root) { this.root = root; } TreapNode getRoot() { return root; } @SuppressWarnings("WeakerAccess") public List asList() { ArrayList collector = new ArrayList<>(); root.addContentsToList(collector); return collector; } @Override public int size() { return root == null ? 0 : root.size(); } @Override public boolean isEmpty() { return root == null; } @Override public boolean contains(Object o) { if (o == null || root == null || root.getValue() == null || root.getValue().getClass() != o.getClass()) { return false; } @SuppressWarnings("unchecked") T item = (T)o; return root.contains(item); } /** * Traverses {@link Treap} elements in natural ascending order. * * {@inheritDoc} */ @Override public Iterator iterator() { return new TreapIterator(); } @Override public Spliterator spliterator() { return new TreapSpliterator(); } @Override public Stream stream() { return StreamSupport.stream(this::spliterator, TreapSpliterator.CHARACTERISTICS, false); } @Override public Stream parallelStream() { return StreamSupport.stream(this::spliterator, TreapSpliterator.CHARACTERISTICS, true); } @Override public Object[] toArray() { return root == null ? new Object[0] : asList().toArray(); } @Override public T1[] toArray(T1[] a) { Objects.requireNonNull(a); //noinspection SuspiciousToArrayCall return root == null ? a : asList().toArray(a); } boolean add(T newItem, int priority) { Objects.requireNonNull(newItem); return add(new TreapNode<>(newItem, priority)); } private boolean add(TreapNode newNode) { if (root == null) { root = newNode; } if (root.add(newNode)) { TreapNode newRoot = root.balance(); if (newRoot != root) { root = newRoot; } return true; } return false; } @Override public boolean add(T newItem) { Objects.requireNonNull(newItem); return add(new TreapNode<>(newItem)); } @Override public boolean remove(Object o) { if (o == null || root == null || root.getValue() == null || root.getValue().getClass() != o.getClass()) { return false; } @SuppressWarnings("unchecked") T item = (T) o; if (root.remove(item)) { TreapNode newRoot = root.balance(); if (newRoot != root) { root = newRoot; } if (root.getPriority() == Integer.MIN_VALUE) { root = null; } return true; } return false; } @Override public boolean containsAll(Collection c) { for (Object item : c) { if (!contains(item)) { return false; } } return true; } @Override public boolean addAll(Collection c) { boolean changed = false; for (T item : Objects.requireNonNull(c)) { changed |= add(item); } return changed; } @Override public boolean removeAll(Collection c) { boolean changed = false; for (Object item : Objects.requireNonNull(c)) { changed |= remove(item); } return changed; } @Override public boolean retainAll(Collection c) { Objects.requireNonNull(c); boolean changed = false; for (T item : this) { if (!c.contains(item)) { changed |= this.remove(item); } } return changed; } @Override public void clear() { root = null; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getName()); sb.append(System.lineSeparator()); if (root == null) { sb.append(TreapNode.NULL_NODE_STRING); } else { root.toStringRecursive(sb, 0); } return sb.toString(); } /** * A left, depth-first tree iterator which iterates over the elements of the parent {@link Treap} * in natural ascending order. */ private class TreapIterator implements Iterator { Deque> stack = new ArrayDeque<>(size()); T lastReturned = null; private TreapIterator() { if (Treap.this.root != null) { stack.push(Treap.this.root); } } @Override public boolean hasNext() { return !stack.isEmpty(); } @Override public T next() { if (stack.isEmpty()) { throw new NoSuchElementException("The Iterator is empty."); } TreapNode next = stack.pop(); if (next.getRight() != null) { stack.push(next.getRight()); } if (next.getLeft() != null) { stack.push(next.getLeft()); } lastReturned = next.getValue(); return next.getValue(); } @Override public void remove() { if (lastReturned == null) { throw new IllegalStateException("remove called twice or before next was ever called"); } Treap.this.remove(lastReturned); lastReturned = null; } } /** * {@link Spliterator} for parallel BFS traversal of a {@link TreapNode} and its children. */ private class TreapSpliterator implements Spliterator { private static final int CHARACTERISTICS = DISTINCT | NONNULL | SIZED | SUBSIZED; private final Queue> queue = new PriorityQueue<>(); /** * Implementation Note: * * {@link TreapSpliterator} runs into trouble when {@link #trySplit()} is called but the * {@link #queue} only contains the root node. If it creates a new {@link TreapSpliterator} * with one of root's children, but keeps this {@link TreapSpliterator} as-is, then it will * iterate over the chosen child (and all of its children) twice. If it sets this * {@link TreapSpliterator} on, say, the left child, and a new {@link TreapSpliterator} on the * right child, then it will never iterate over root's value. This serves as a marker for when * this {@link TreapSpliterator} has split but the parent value still has not been processed. */ private T unprocessedParent = null; TreapSpliterator(TreapNode root) { if (root != null) { queue.add(root); } } TreapSpliterator() { this(Treap.this.root); } @Override public boolean tryAdvance(Consumer action) { if (unprocessedParent != null) { action.accept(unprocessedParent); unprocessedParent = null; return true; } if (queue.isEmpty()) { return false; } TreapNode next = queue.remove(); if (next.getRight() != null) { queue.add(next.getRight()); } if (next.getLeft() != null) { queue.add(next.getLeft()); } action.accept(next.getValue()); return true; } @Override public Spliterator trySplit() { if (queue.size() == 0) { return null; } if (queue.size() == 1) { TreapNode current = queue.remove(); unprocessedParent = current.getValue(); if (current.getRight() != null) { queue.add(current.getRight()); } if (current.getLeft() != null) { queue.add(current.getLeft()); } } return new TreapSpliterator(queue.remove()); } @Override public long estimateSize() { return getExactSizeIfKnown(); } @Override public long getExactSizeIfKnown() { return (unprocessedParent == null ? 0 : 1) + (queue.isEmpty() ? 0 : queue.peek().size()); } @Override public Comparator getComparator() { return null; } @Override public int characteristics() { return CHARACTERISTICS; } } } pulsar-client/src/test/java/org/apache/pulsar/client/impl/schema/StringSchemaTest.java /** * 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.pulsar.client.impl.schema; import static java.nio.charset.StandardCharsets.US_ASCII; import static java.nio.charset.StandardCharsets.UTF_8; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertTrue; import static org.testng.internal.junit.ArrayAsserts.assertArrayEquals; import java.nio.charset.Charset; import java.util.Collections; import java.util.HashMap; import java.util.Map; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import org.apache.pulsar.common.schema.SchemaInfo; import org.apache.pulsar.common.schema.SchemaType; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; /** * Unit test {@link StringSchema}. */ public class StringSchemaTest { @Test public void testUtf8Charset() { StringSchema schema = new StringSchema(); SchemaInfo si = schema.getSchemaInfo(); assertFalse(si.getProperties().containsKey(StringSchema.CHARSET_KEY)); String myString = "my string for test"; byte[] data = schema.encode(myString); assertArrayEquals(data, myString.getBytes(UTF_8)); String decodedString = schema.decode(data); assertEquals(decodedString, myString); ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(data.length); byteBuf.writeBytes(data); assertEquals(schema.decode(byteBuf), myString); } @Test public void testAsciiCharset() { StringSchema schema = new StringSchema(US_ASCII); SchemaInfo si = schema.getSchemaInfo(); assertTrue(si.getProperties().containsKey(StringSchema.CHARSET_KEY)); assertEquals( si.getProperties().get(StringSchema.CHARSET_KEY), US_ASCII.name() ); String myString = "my string for test"; byte[] data = schema.encode(myString); assertArrayEquals(data, myString.getBytes(US_ASCII)); String decodedString = schema.decode(data); assertEquals(decodedString, myString); ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(data.length); byteBuf.writeBytes(data); assertEquals(schema.decode(byteBuf), myString); } @Test public void testSchemaInfoWithoutCharset() { SchemaInfo si = new SchemaInfo() .setName("test-schema-info-without-charset") .setType(SchemaType.STRING) .setSchema(new byte[0]) .setProperties(Collections.emptyMap()); StringSchema schema = StringSchema.fromSchemaInfo(si); String myString = "my string for test"; byte[] data = schema.encode(myString); assertArrayEquals(data, myString.getBytes(UTF_8)); String decodedString = schema.decode(data); assertEquals(decodedString, myString); ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(data.length); byteBuf.writeBytes(data); assertEquals(schema.decode(byteBuf), myString); } @DataProvider(name = "charsets") public Object[][] charsets() { return new Object[][] { { UTF_8 }, { US_ASCII } }; } @Test(dataProvider = "charsets") public void testSchemaInfoWithCharset(Charset charset) { Map properties = new HashMap<>(); properties.put(StringSchema.CHARSET_KEY, charset.name()); SchemaInfo si = new SchemaInfo() .setName("test-schema-info-without-charset") .setType(SchemaType.STRING) .setSchema(new byte[0]) .setProperties(properties); StringSchema schema = StringSchema.fromSchemaInfo(si); String myString = "my string for test"; byte[] data = schema.encode(myString); assertArrayEquals(data, myString.getBytes(charset)); String decodedString = schema.decode(data); assertEquals(decodedString, myString); ByteBuf byteBuf = ByteBufAllocator.DEFAULT.buffer(data.length); byteBuf.writeBytes(data); assertEquals(schema.decode(byteBuf), myString); } } package org.terifan.raccoon.io.physical; import org.terifan.raccoon.io.managed.ManagedBlockDevice; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; import org.testng.annotations.Test; import static org.testng.Assert.*; public class FileBlockDeviceNGTest { @Test public void testSomeMethod() throws IOException { File file = File.createTempFile("blkdev","tmp"); Random rnd = new Random(1); int s = 512; HashMap blocks = new HashMap<>(); ArrayList offsets = new ArrayList<>(); for (int k = 0; k < 5; k++) { try (ManagedBlockDevice dev = new ManagedBlockDevice(new FileBlockDevice(file, s, false))) { for (int j = 0; j < 10; j++) { for (int i = 0; i < 50; i++) { long pos = dev.allocBlock(1); byte[] buf = new byte[s]; rnd.nextBytes(buf); blocks.put(pos, buf); dev.writeBlock(pos, buf, 0, s, new long[2]); offsets.add(pos); } for (int i = 0; i < 25; i++) { long pos = offsets.remove(rnd.nextInt(offsets.size())); byte[] buf = new byte[s]; dev.readBlock(pos, buf, 0, s, new long[2]); assertEquals(blocks.remove(pos), buf); dev.freeBlock(pos, 1); } dev.commit(); } } } file.delete(); } } 0 package com.apoem.mmxx.eventtracking.infrastructure.biz; import lombok.ToString; import java.util.List; /** * Please check `classpath:bizCity.json` for more details. */ @ToString public class JsonCommunityInfo { private String city; private List list; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public List getList() { return list; } public void setList(List list) { this.list = list; } } package net.futureclient.asm.internal; import com.google.common.collect.Streams; import net.futureclient.asm.config.ConfigManager; import net.futureclient.asm.config.Config; import net.futureclient.asm.obfuscation.MappingType; import net.futureclient.asm.obfuscation.RuntimeState; import net.futureclient.asm.transformer.annotation.Inject; import net.futureclient.asm.transformer.annotation.Transformer; import net.futureclient.asm.transformer.util.AnnotationInfo; import net.futureclient.asm.transformer.util.ObfUtils; import net.minecraft.launchwrapper.IClassTransformer; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Handle; import org.objectweb.asm.Type; import org.objectweb.asm.tree.*; import java.lang.annotation.Annotation; import java.util.*; import java.util.stream.Collectors; import static org.objectweb.asm.Opcodes.*; /** * Created by Babbaj on 5/20/2018. *

* This class is responsible for processing the bytecode of transformers */ public final class TransformerPreProcessor implements IClassTransformer { @Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (configContainsClass(transformedName)) { ClassNode cn = new ClassNode(); ClassReader cr = new ClassReader(basicClass); cr.accept(cn, 0); if (!hasAnnotation(cn, Transformer.class)) { AsmLib.LOGGER.error("Transformer Class {} is missing @{} annotation", transformedName, Transformer.class.getSimpleName()); return basicClass; } processClass(cn); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES); cn.accept(cw); return cw.toByteArray(); } return basicClass; } private boolean configContainsClass(String className) { return ConfigManager.INSTANCE .getConfigs().stream() .map(Config::getTransformerClassNames) .flatMap(Collection::stream) .anyMatch(className::equals); } private boolean hasAnnotation(ClassNode cn, Class clazz) { return cn.visibleAnnotations.stream() .anyMatch(node -> node.desc.equals(Type.getDescriptor(clazz))); } private void processClass(ClassNode clazz) { clazz.methods.forEach(node -> injectAtLambdas(clazz, node)); modifyAllLambdas(clazz); // TODO: only apply to lambda methods clazz.methods.stream() .filter(method -> (method.access & ACC_SYNTHETIC) != 0) .forEach(method -> { method.access &= ~ACC_PRIVATE; method.access |= ACC_PUBLIC; }); clazz.visibleAnnotations.stream() .filter(node -> node.desc.equals(Type.getDescriptor(Transformer.class))) .findFirst() .ifPresent(this::processTransformer); clazz.methods.stream() .map(node -> node.visibleAnnotations) .filter(Objects::nonNull) .flatMap(List::stream) .filter(node -> node.desc.equals(Type.getDescriptor(Inject.class))) .forEach(this::processInject); final Class wrapperClass = TransformerDelegate.createDelegateClass(clazz, Type.getObjectType(clazz.name)); TransformerDelegate.DELEGATES.put(clazz.name, wrapperClass); } // process @Transformer annotation @SuppressWarnings("unchecked") private void processTransformer(AnnotationNode node) { AnnotationInfo info = AnnotationInfo.fromAsm(node); if (info.getValue("target") == null) { node.values.add(0, "target"); String newTarget = Optional.of(info.getValue("value")) .map(Type::getInternalName) .map(this::mcpClassName) .get(); node.values.add(1, newTarget); } final int i = node.values.indexOf("value"); if (i != -1) { node.values.remove(i + 1); node.values.remove(i); } } // process @Inject annotation private void processInject(final AnnotationNode node) { AnnotationInfo info = AnnotationInfo.fromAsm(node); if (info.getValue("target") == null) { final String name = info.getValue("name"); if (name == null) throw new IllegalArgumentException("Failed to supply method name"); final String ret = Optional.ofNullable(info.getValue("ret")) .map(this::mcpClassType) .orElse(Type.VOID_TYPE) .getDescriptor(); final String args = Optional.ofNullable(info.>getValue("args")) .map(list -> list.stream() .map(this::mcpClassType) .map(Type::getDescriptor) .collect(Collectors.joining())) .orElse(""); final String fullDesc = String.format("%s(%s)%s", name, args, ret); int i = node.values.indexOf("target"); if (i == -1) { node.values.add(0, "target"); node.values.add(1, fullDesc); } else { node.values.set(i + 1, fullDesc); } } // target value is set, remove the old annotation values because theyre unnecessary and cause problems String[] oldValueNames = {"name", "args", "ret"}; for (String valueName : oldValueNames) { final int index = node.values.indexOf(valueName); if (index != -1) { node.values.remove(index + 1); node.values.remove(index); } } } // replace all lambbda method references with untyped wrapper methods to avoid premature class loading private void modifyAllLambdas(ClassNode clazz) { List wrapperMethods = clazz.methods.stream() .map(method -> method.instructions) .flatMap(insnList -> Streams.stream(insnList.iterator())) .filter(InvokeDynamicInsnNode.class::isInstance).map(InvokeDynamicInsnNode.class::cast) .map(lambdaNode -> replaceLambdaMethodReference(clazz, lambdaNode)) .collect(Collectors.toList()); clazz.methods.addAll(wrapperMethods); } private MethodNode replaceLambdaMethodReference(ClassNode thisClass, InvokeDynamicInsnNode node) { final Handle methodRef = (Handle)node.bsmArgs[1]; final Type refDesc = (Type)node.bsmArgs[2]; final MethodNode wrapperMethod = AsmUtil.createWrapperFunction(methodRef.getName() + "#wrapper", methodRef.getOwner(), methodRef.getName(), methodRef.getDesc(), methodRef.getTag()); node.bsmArgs[1] = new Handle(H_INVOKESTATIC, thisClass.name, wrapperMethod.name, wrapperMethod.desc); node.bsmArgs[0] = AsmUtil.toRawTypeDescriptor((Type)node.bsmArgs[0]); node.bsmArgs[2] = AsmUtil.toRawTypeDescriptor((Type)node.bsmArgs[2]); node.desc = AsmUtil.descriptorWithRawTypeArgs(Type.getMethodType(node.desc)).getDescriptor(); return wrapperMethod; } // TODO: make sure we have java lambdas private void injectAtLambdas(ClassNode clazz, MethodNode method) { Streams.stream(method.instructions.iterator()) .filter(InvokeDynamicInsnNode.class::isInstance) .map(InvokeDynamicInsnNode.class::cast) .forEach(node -> { lambdaHook(clazz, method, node); }); } private void lambdaHook(ClassNode clazz, MethodNode method, InvokeDynamicInsnNode node) { Handle methodRef = (Handle)node.bsmArgs[1]; Type realType = (Type)node.bsmArgs[2]; // MethodType InsnList list = new InsnList(); list.add(new InsnNode(DUP)); // method reference list.add(new LdcInsnNode(methodRef.getOwner())); list.add(new LdcInsnNode(methodRef.getName())); list.add(new LdcInsnNode(methodRef.getDesc())); list.add(new LdcInsnNode(methodRef.getTag())); // instantiatedMethodType list.add(new LdcInsnNode(realType.getInternalName())); // InvokeDynamicInsnNode desc list.add(new LdcInsnNode(node.desc)); list.add(new MethodInsnNode(INVOKESTATIC, Type.getInternalName(LambdaInfo.class), "addLambda", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;Ljava/lang/String;)V")); method.instructions.insert(node, list); } // if we we are compiled to notch we need to remap class literals back to mcp private String mcpClassName(String clazz) { if (RuntimeState.getRuntimeMappingType() == MappingType.NOTCH) { return ObfUtils.remapClassToMcp(clazz); // notch -> mcp } // already mcp return clazz; } private Type mcpClassType(Type t) { // TODO: fix if (RuntimeState.getRuntimeMappingType() == MappingType.NOTCH) { if (t.getSort() != Type.OBJECT && t.getSort() != Type.ARRAY) return t; // primitive final String clazz = t.getInternalName(); return Type.getObjectType(ObfUtils.remapClassToMcp(clazz)); // notch -> mcp } return t; } } howcroft/keycloak package org.keycloak.testsuite.console.page.roles; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.keycloak.representations.idm.RoleRepresentation.Composites; import org.keycloak.testsuite.page.Form; import static org.keycloak.testsuite.util.WaitUtils.waitUntilElement; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.Select; /** * * @author fkiss * @author tkyjovsk */ public class RoleCompositeRoles extends Form { @FindBy(id = "available") protected Select availableRealmRolesSelect; @FindBy(id = "assigned") protected Select assignedRealmRolesSelect; @FindBy(id = "clients") protected Select clientSelect; @FindBy(id = "available-client") protected Select availableClientRolesSelect; @FindBy(id = "assigned-client") protected Select assignedClientRolesSelect; @FindBy(css = "button[ng-click*='addRealm']") protected WebElement addSelectedRealmRolesButton; @FindBy(css = "button[ng-click*='addClient']") protected WebElement addSelectedClientRolesButton; @FindBy(css = "button[ng-click*='deleteRealm']") protected WebElement removeSelectedRealmRolesButton; @FindBy(css = "button[ng-click*='deleteClient']") protected WebElement removeSelectedClientRolesButton; public Composites getComposites() { Composites composites = new Composites(); // realm roles composites.setRealm(getSelectValues(assignedRealmRolesSelect)); // client roles Map> clientRoles = new HashMap<>(); for (String client : getSelectValues(clientSelect)) { clientSelect.selectByVisibleText(client); clientRoles.put(client, new ArrayList<>(getSelectValues(assignedClientRolesSelect))); } composites.setClient(clientRoles); return composites; } public void setComposites(Composites composites) { if (composites != null) { setRealmRoles(composites.getRealm()); for (String client : composites.getClient().keySet()) { clientSelect.selectByVisibleText(client); setClientRoles(composites.getClient().get(client)); } } } private void setRealmRoles(Collection roles) { removeRedundantRoles(assignedRealmRolesSelect, removeSelectedRealmRolesButton, roles); addMissingRoles(availableRealmRolesSelect, addSelectedRealmRolesButton, roles); } private void setClientRoles(Collection roles) { removeRedundantRoles(assignedClientRolesSelect, removeSelectedClientRolesButton, roles); addMissingRoles(availableClientRolesSelect, addSelectedClientRolesButton, roles); } private void removeRedundantRoles(Select select, WebElement button, Collection roles) { select.deselectAll(); for (String role : getSelectValues(select)) { if (roles == null // if roles not provided, remove all || !roles.contains(role)) { // if roles provided, remove only the redundant select.selectByVisibleText(role); } } button.click(); } public void addRealmRole(String role) { addMissingRoles(availableRealmRolesSelect, addSelectedRealmRolesButton, Arrays.asList(role)); } public void addClientRole(String role) { addMissingRoles(availableClientRolesSelect, addSelectedClientRolesButton, Arrays.asList(role)); } protected void addMissingRoles(Select select, WebElement button, Collection roles) { select.deselectAll(); if (roles != null) { // if roles not provided, don't add any for (String role : getSelectValues(select)) { if (roles.contains(role)) { // if roles provided, add only the missing select.selectByVisibleText(role); } } button.click(); } } public static Set getSelectValues(Select select) { Set roles = new HashSet<>(); for (WebElement option : select.getOptions()) { roles.add(option.getText()); } return roles; } // *** public Set getAvailableRealmRoles() { return getSelectValues(availableRealmRolesSelect); } public Set getAvailableClientRoles(String client) { return getSelectValues(availableClientRolesSelect); } public Set getAssignedRealmRoles() { return getSelectValues(assignedRealmRolesSelect); } public Set getAssignedClientRoles() { return getSelectValues(assignedClientRolesSelect); } // *** original methods *** public void addAvailableRole(String... roles) { waitUntilElement(By.id("available")).is().present(); for (String role : roles) { availableRealmRolesSelect.selectByVisibleText(role); addSelectedRealmRolesButton.click(); } } public void removeAssignedRole(String role) { waitUntilElement(By.id("assigned")).is().present(); assignedRealmRolesSelect.selectByVisibleText(role); removeSelectedRealmRolesButton.click(); } public boolean isAssignedRole(String role) { waitUntilElement(By.id("assigned")).is().present(); try { assignedRealmRolesSelect.selectByVisibleText(role); } catch (Exception ex) { return false; } return true; } public boolean isAssignedClientRole(String role) { waitUntilElement(By.id("assigned")).is().present(); try { assignedClientRolesSelect.selectByVisibleText(role); } catch (Exception ex) { return false; } return true; } public void selectClientRole(String client) { waitUntilElement(By.id("clients")).is().present(); clientSelect.selectByVisibleText(client); } public void addAvailableClientRole(String... roles) { waitUntilElement(By.id("available-client")).is().present(); for (String role : roles) { availableClientRolesSelect.selectByVisibleText(role); addSelectedClientRolesButton.click(); } } public void removeAssignedClientRole(String client) { waitUntilElement(By.id("assigned-client")).is().present(); assignedClientRolesSelect.selectByVisibleText(client); removeSelectedClientRolesButton.click(); } } import org.hibernate.SessionFactory; public abstract class FooBean6 { public FooBean6(SessionFactory aaa) { } //must be included public void destroy_1(){} protected void destroy_2(){} private void destroy_3() {} void destroy_4(){} public void destroy_5(boolean b) {} // not included public void destroy_6(String b) {} public void destroy_7(String b, String b2){} public abstract void destroy_8(){} //must be included public void init_1() {} protected void init_2() {} private void init_3(){} //not included private void init_4(boolean b) {} }package leetCode; public class LeetCode1448 { public int goodNodes(TreeNode root) { return 0; } } package com.zopa.calculation; import com.zopa.error.LenderRetrievalError; import com.zopa.model.LoanQuote; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import java.util.Arrays; import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertThrows; public class QuoteCalculationTest { public List loanQuoteList; @BeforeEach public void init() { LoanQuote loanQuote1 = new LoanQuote(); loanQuote1.setLenderRate(new BigDecimal("0.7")); loanQuote1.setLenderAmountAvailable(new BigDecimal(1000)); LoanQuote loanQuote2 = new LoanQuote(); loanQuote2.setLenderRate(new BigDecimal("0.8")); loanQuote2.setLenderAmountAvailable(new BigDecimal(500)); LoanQuote loanQuote3 = new LoanQuote(); loanQuote3.setLenderRate(new BigDecimal("0.5")); loanQuote3.setLenderAmountAvailable(new BigDecimal(320)); LoanQuote loanQuote4 = new LoanQuote(); loanQuote4.setLenderRate(new BigDecimal("0.2")); loanQuote4.setLenderAmountAvailable(new BigDecimal(550)); LoanQuote loanQuote5 = new LoanQuote(); loanQuote5.setLenderRate(new BigDecimal("0.7")); loanQuote5.setLenderAmountAvailable(new BigDecimal(800)); LoanQuote loanQuote6 = new LoanQuote(); loanQuote6.setLenderRate(new BigDecimal("0.8")); loanQuote6.setLenderAmountAvailable(new BigDecimal(14000)); loanQuoteList = Arrays.asList(loanQuote1, loanQuote2, loanQuote3, loanQuote4, loanQuote5, loanQuote6); } @Test public void quoteCalculationThrowsWhenLoanAmountCannotBeFulfilled() { QuoteCalculation quoteCalculation = new QuoteCalculation(1010); assertThrows(LenderRetrievalError.class, () -> quoteCalculation.calculateMonthlyAndTotalRepayment(loanQuoteList)); } @Test public void calculateQuoteMax() { QuoteCalculation quoteCalculation = new QuoteCalculation(15000); LoanQuote loanQuote = quoteCalculation.calculateMonthlyAndTotalRepayment(loanQuoteList); assertThat(loanQuote.getMonthlyRepayment(), equalTo(new BigDecimal("1550.14"))); assertThat(loanQuote.getTotalRepayment(), equalTo(new BigDecimal("55805.04"))); assertThat(loanQuote.getLenderRate(), equalTo(new BigDecimal("0.8"))); assertThat(loanQuote.getLoanAmount(), equalTo(15000)); } @Test public void calculateQuoteMin() { QuoteCalculation quoteCalculation = new QuoteCalculation(1000); LoanQuote loanQuote = quoteCalculation.calculateMonthlyAndTotalRepayment(loanQuoteList); assertThat(loanQuote.getMonthlyRepayment(), equalTo(new BigDecimal("103.34"))); assertThat(loanQuote.getTotalRepayment(), equalTo(new BigDecimal("3720.24"))); assertThat(loanQuote.getLenderRate(), equalTo(new BigDecimal("0.7"))); assertThat(loanQuote.getLoanAmount(), equalTo(1000)); } } /* * Copyright [2019] [恒宇少年 - 于起宇] * * 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.minbox.framework.api.boot.autoconfigure.enhance; import org.apache.ibatis.io.VFS; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * @author:恒宇少年 - 于起宇 *

* DateTime:2019-04-25 15:16 * Blog:http://blog.yuqiyu.com * WebSite:http://www.jianshu.com/u/092df3f77bca * Gitee:https://gitee.com/hengboy * GitHub:https://github.com/hengboy */ public class SpringBootVFS extends VFS { private final ResourcePatternResolver resourceResolver; public SpringBootVFS() { this.resourceResolver = new PathMatchingResourcePatternResolver(getClass().getClassLoader()); } @Override public boolean isValid() { return true; } @Override protected List list(URL url, String path) throws IOException { Resource[] resources = resourceResolver.getResources("classpath*:" + path + "/**/*.class"); List resourcePaths = new ArrayList(); for (Resource resource : resources) { resourcePaths.add(preserveSubpackageName(resource.getURI(), path)); } return resourcePaths; } private static String preserveSubpackageName(final URI uri, final String rootPath) { final String uriStr = uri.toString(); final int start = uriStr.indexOf(rootPath); return uriStr.substring(start); } } /* * Copyright (C) 2020 Temporal Technologies, Inc. All Rights Reserved. * * Copyright 2012-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Modifications copyright (C) 2017 Uber Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not * use this file except in compliance with the License. A copy of the License is * located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 io.temporal.serviceclient.rpcretry; import io.temporal.serviceclient.RpcRetryOptions; import java.time.Duration; /** Default rpc retry options for long polls like waiting for the workflow finishing and result. */ public class DefaultStubLongPollRpcRetryOptions { public static final Duration INITIAL_INTERVAL = Duration.ofMillis(1); public static final Duration MAXIMUM_INTERVAL = Duration.ofMinutes(1); public static final double BACKOFF = 1.2; public static RpcRetryOptions.Builder getBuilder() { RpcRetryOptions.Builder roBuilder = RpcRetryOptions.newBuilder() .setInitialInterval(INITIAL_INTERVAL) .setBackoffCoefficient(BACKOFF) .setMaximumInterval(MAXIMUM_INTERVAL); DefaultStubServiceOperationRpcRetryOptions.TEMPORAL_SERVER_DEFAULT_NON_RETRY.forEach( roBuilder::addDoNotRetry); return roBuilder; } } client/java/client/src/com/bj58/spat/gaea/client/proxy/builder/MethodCaller.java /* * Copyright Beijing 58 Information Technology Co.,Ltd. * * 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 com.bj58.spat.gaea.client.proxy.builder; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import com.bj58.spat.gaea.client.proxy.ServiceProxy; import com.bj58.spat.gaea.client.proxy.ServiceProxy.InvokeResult; import com.bj58.spat.gaea.client.utility.logger.ILog; import com.bj58.spat.gaea.client.utility.logger.LogFactory; import com.bj58.spat.gaea.server.contract.annotation.AnnotationUtil; import com.bj58.spat.gaea.server.contract.annotation.OperationContract; import com.bj58.spat.gaea.server.contract.entity.Out; /** * MethodCaller * * @author Service Platform Architecture Team () */ public class MethodCaller { private static final ILog logger = LogFactory.getLogger(MethodCaller.class); private String serviceName; private String lookup; public MethodCaller(String serviceName, String lookup) { this.serviceName = serviceName; this.lookup = lookup; } public Object doMethodCall(Object[] args, Method methodInfo) throws Exception, Throwable { Type[] typeAry = methodInfo.getGenericParameterTypes(); Class[] clsAry = methodInfo.getParameterTypes(); if (args == null) { args = new Object[0]; } if (args.length != typeAry.length) { throw new Exception("argument count error!"); } ServiceProxy proxy = ServiceProxy.getProxy(serviceName); Parameter[] paras = new Parameter[args.length]; List outParas = new ArrayList(); if (typeAry != null) { for (int i = 0; i < typeAry.length; i++) { if (args[i] instanceof Out) { paras[i] = new Parameter(args[i], clsAry[i], typeAry[i], ParaType.Out); outParas.add(i); } else { paras[i] = new Parameter(args[i], clsAry[i], typeAry[i], ParaType.In); } } } Parameter returnPara = new Parameter(null, methodInfo.getReturnType(), methodInfo.getGenericReturnType()); String methodName = methodInfo.getName(); OperationContract ann = methodInfo.getAnnotation(OperationContract.class); if (ann != null) { if (!ann.methodName().equals(AnnotationUtil.DEFAULT_VALUE)) { methodName = "$" + ann.methodName(); } } InvokeResult result = proxy.invoke(returnPara, lookup, methodName, paras); if (result != null && result.getOutPara() != null) { for (int i = 0; i < outParas.size() && i < result.getOutPara().length; i++) { Object op = args[outParas.get(i)]; if(op instanceof Out){ ((Out)op).setOutPara(result.getOutPara()[i]); } } } return result.getResult(); } } package androidx.core.app; import android.annotation.SuppressLint; import android.app.job.JobServiceEngine; /** * Improved version of {@link JobIntentService} which also explicitly stops de-queuing work if the * service is to be destroyed. *

* Potential fix for {@link SecurityException} when de-queuing work, assuming they are caused by * the processor trying to dequeue work after the service is destroyed by the system. *

* https://issuetracker.google.com/issues/63622293 */ public abstract class SafeJobIntentService extends JobIntentService { @SuppressLint("NewApi") @Override public void onDestroy() { super.onDestroy(); // stop de-queuing work if the service is to be destroyed if (this.mJobImpl != null) { ((JobServiceEngine) mJobImpl).onStopJob(null); } } } /* * Licensed to GraphHopper and under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper 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 com.graphhopper.storage.index; import com.graphhopper.routing.util.EncodingManager; import com.graphhopper.storage.Graph; import org.junit.*; import static org.junit.Assert.*; /** * * @author */ public class Location2IDFullIndexTest extends AbstractLocationIndexTester { @Override public LocationIndex createIndex( Graph g, int resolution ) { return new Location2IDFullIndex(g); } @Override public void testGrid() { // do not test against itself } @Test public void testFullIndex() { LocationIndex idx = new Location2IDFullIndex(createSampleGraph(new EncodingManager("CAR"))); assertEquals(5, idx.findID(2, 3)); assertEquals(10, idx.findID(4, 1)); assertEquals(10, idx.findID(3.6, 1.4)); } } package ru.job4j.simplelinkedlist; import java.util.NoSuchElementException; /** * Class simple queue. * * @since 22/08/2017 * @version 1 */ public class Queue { /** * Container for queue. */ private SimpleLinkedList container = new SimpleLinkedList(); /** * Adds new element to this queue. * @param e - new element to add */ public void add(E e) { container.add(e); } /** * Retrieves and removes the head of this queue. * @return the head of this queue * @throws NoSuchElementException if this queue is empty */ public E poll() { return container.remove(0); } /** * Retrieves, but does not remove, the head of this queue. * @return the head of this queue * @throws NoSuchElementException if this queue is empty */ public E element() { try { return container.get(0); } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException(); } } /** * Tests is this queue is empty. * @return result of test */ public boolean isEmpty() { return container.size() == 0; } } jeecg-boot/jeecg-boot-module-system/src/main/java/org/jeecg/modules/eth_hub/entity/Payout.java package org.jeecg.modules.eth_hub.entity; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @NoArgsConstructor @Data public class Payout { private String status; private DataDTO data; @NoArgsConstructor @Data public static class DataDTO { private List rounds; private List payouts; private Object miningStart; private PendingPayoutDTO pendingPayout; private EstimatesDTO estimates; @NoArgsConstructor @Data public static class PendingPayoutDTO { private Integer gasPrice; private String time; } @NoArgsConstructor @Data public static class EstimatesDTO { private Double averageHashrate; private Double coinsPerMin; private Double usdPerMin; private Double btcPerMin; } @NoArgsConstructor @Data public static class RoundsDTO { private Integer block; private Long amount; } @NoArgsConstructor @Data public static class PayoutsDTO { private Integer start; private Integer end; private String amount; private String txHash; private Long txCost; private Integer paidOn; } } } package com.foxpower.flchatofandroid.ui.fragment; import android.widget.TextView; import com.foxpower.flchatofandroid.R; import com.foxpower.flchatofandroid.common.BaseFragment; import com.foxpower.flchatofandroid.enums.SocketConnectStatus; import com.foxpower.flchatofandroid.util.manager.ChatManager; import com.foxpower.flchatofandroid.util.manager.ClientManager; import com.foxpower.flchatofandroid.util.manager.SocketManager; import org.greenrobot.eventbus.EventBus; import butterknife.BindView; import butterknife.OnClick; /** * Created by fengli on 2018/2/7. */ public class HomeMeFragment extends BaseFragment { @BindView(R.id.me_current_user) TextView currentUserView; @BindView(R.id.me_connect_status) TextView connectStatusView; @OnClick(R.id.me_exit_login) void exitLogin() { // SocketManager.socket.disconnect(); } @Override protected int getLayoutId() { return R.layout.fragment_home_me; } @Override protected void initView() { super.initView(); currentUserView.setText("登录用户:" + ClientManager.currentUserId); connectStatusView.setText(connectStatusDes(SocketManager.connectStatus)); } private String connectStatusDes(SocketConnectStatus status) { String des = ""; switch (status){ case SocketConnected: des = "连接成功"; break; case SocketConnecting: des = "连接中"; break; case SocketConnectError: des = "连接失败"; break; case SocketDisconnected: des = "连接断开"; break; } return "连接状态:" + des; } @Override protected void initData() { super.initData(); // EventBus.getDefault().register(this); } @Override public void onDestroy() { super.onDestroy(); // EventBus.getDefault().unregister(this); } } package query; import java.util.ArrayList; // TODO: Auto-generated Javadoc /** * Interface of ranking algorithm. */ public interface RankInterface { /** * Rank. * * @param urls the urls * @param keywords the keywords * @return the array list */ public ArrayList rank(ArrayList urls, ArrayList keywords); /** * Weigh. * * @param url the url * @param keywords the keywords * @return the double */ public double weigh(String url, ArrayList keywords); } aculver28/ksql package io.confluent.ksql.execution.testutil; import io.confluent.ksql.execution.expression.tree.Expression; import io.confluent.ksql.execution.expression.tree.IntegerLiteral; import io.confluent.ksql.execution.expression.tree.UnqualifiedColumnReferenceExp; import io.confluent.ksql.name.ColumnName; import io.confluent.ksql.schema.ksql.LogicalSchema; import io.confluent.ksql.schema.ksql.SystemColumns; import io.confluent.ksql.schema.ksql.types.SqlStruct; import io.confluent.ksql.schema.ksql.types.SqlTypes; public final class TestExpressions { private TestExpressions() { } private final static SqlStruct ADDRESS_SCHEMA = SqlTypes.struct() .field("NUMBER", SqlTypes.BIGINT) .field("STREET", SqlTypes.STRING) .field("CITY", SqlTypes.STRING) .field("STATE", SqlTypes.STRING) .field("ZIPCODE", SqlTypes.BIGINT) .build(); public final static LogicalSchema SCHEMA = LogicalSchema.builder() .keyColumn(SystemColumns.ROWKEY_NAME, SqlTypes.STRING) .valueColumn(ColumnName.of("COL0"), SqlTypes.BIGINT) .valueColumn(ColumnName.of("COL1"), SqlTypes.STRING) .valueColumn(ColumnName.of("COL2"), SqlTypes.STRING) .valueColumn(ColumnName.of("COL3"), SqlTypes.DOUBLE) .valueColumn(ColumnName.of("COL4"), SqlTypes.array(SqlTypes.DOUBLE)) .valueColumn(ColumnName.of("COL5"), SqlTypes.map(SqlTypes.DOUBLE)) .valueColumn(ColumnName.of("COL6"), ADDRESS_SCHEMA) .valueColumn(ColumnName.of("COL7"), SqlTypes.INTEGER) .valueColumn(ColumnName.of("COL8"), SqlTypes.decimal(2, 1)) .valueColumn(ColumnName.of("COL9"), SqlTypes.decimal(2, 1)) .build(); public static final UnqualifiedColumnReferenceExp COL0 = columnRef("COL0"); public static final UnqualifiedColumnReferenceExp COL1 = columnRef("COL1"); public static final UnqualifiedColumnReferenceExp COL2 = columnRef("COL2"); public static final UnqualifiedColumnReferenceExp COL3 = columnRef("COL3"); public static final UnqualifiedColumnReferenceExp ADDRESS = columnRef("COL6"); public static final UnqualifiedColumnReferenceExp ARRAYCOL = columnRef("COL4"); public static final UnqualifiedColumnReferenceExp MAPCOL = columnRef("COL5"); public static final UnqualifiedColumnReferenceExp COL7 = columnRef("COL7"); private static UnqualifiedColumnReferenceExp columnRef(final String name) { return new UnqualifiedColumnReferenceExp(ColumnName.of(name)); } public static Expression literal(final int value) { return new IntegerLiteral(value); } } /* * Copyright 2019 Haulmont. * * 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.haulmont.cuba.gui.components; import com.haulmont.cuba.gui.data.Datasource; import io.jmix.ui.component.ComboBox; import java.util.function.Consumer; import java.util.function.Function; /** * Component compatible with {@link Datasource}. * * @param type of options and value * @deprecated Use {@link ComboBox} instead */ @Deprecated public interface LookupField extends OptionsField, ComboBox { String NAME = "lookupField"; /** * @deprecated Use {@link #getNullSelectionCaption()} instead */ @Deprecated V getNullOption(); /** * @deprecated Use {@link #setNullSelectionCaption(String)} instead */ @Deprecated void setNullOption(V nullOption); /** * @return true if the component handles new options entered by user. * @see #setNewOptionHandler(Consumer) */ @Deprecated boolean isNewOptionAllowed(); /** * Makes the component handle new options entered by user. * * @see #setNewOptionHandler(Consumer) * @deprecated setting the new option handler enables new options */ @Deprecated void setNewOptionAllowed(boolean newOptionAllowed); /** * Set the icon provider for LookupField. * * @param optionClass class of the option * @param optionIconProvider provider which provides icons for options * * @deprecated Use {@link #setOptionIconProvider(Function)} */ @Deprecated void setOptionIconProvider(Class optionClass, Function optionIconProvider); /** * Interface to be implemented if {@link #setNewOptionAllowed(boolean)} is set to true. */ @Deprecated interface NewOptionHandler extends Consumer { @Override default void accept(String caption) { addNewOption(caption); } /** * Called when user enters a value which is not in the options list, and presses Enter. * @param caption value entered by user */ void addNewOption(String caption); } /** * Allows to set icons for particular elements in the options list. */ @Deprecated interface OptionIconProvider extends Function { @Override default String apply(T item) { return getItemIcon(item); } /** * Called when component paints its content. * * @param item item from options list, options map or enum options * @return icon name or null to show no icon */ String getItemIcon(T item); } } mds-generator/src/main/java/xyz/codemeans/mybatis/generator/GeneratorRunner.java package xyz.codemeans.mybatis.generator; import com.google.common.collect.Lists; import java.io.IOException; import java.util.List; import lombok.extern.slf4j.Slf4j; import xyz.codemeans.mybatis.generator.config.GenerationDef; import xyz.codemeans.mybatis.generator.core.MdsGenerator; import xyz.codemeans.mybatis.generator.core.TypeGeneration; import xyz.codemeans.mybatis.generator.core.TypeMapping; import xyz.codemeans.mybatis.generator.core.TypeProcessor; /** * an example * * @author yuanwq */ @Slf4j public class GeneratorRunner { private final GeneratorProperties properties; public GeneratorRunner(GeneratorProperties properties) { this.properties = properties; } public List run() throws IOException { TypeMapping typeMapping = new TypeMapping(properties.getTypes()); TypeProcessor typeProcessor = new TypeProcessor(typeMapping); MdsGenerator generator = new MdsGenerator(typeProcessor); List allGenerations = Lists.newArrayList(); for (GenerationDef def : properties.getGenerations()) { List generations = generator.generate(def); log.info("models in {} generated: {}", def.getInputPackage(), Lists.transform(generations, TypeGeneration::getOutfile)); allGenerations.addAll(generations); } return allGenerations; } } commons/src/main/java/virtuozo/infra/FormatValidator.java1-10 package virtuozo.infra; public class FormatValidator extends Validator, String> { private Format format; public FormatValidator(Format format) { super(); this.format = format; } @Override protected boolean delegateValidation(String value) { try { this.format.unformat(value); return true; } catch (IllegalArgumentException e) { return false; } } } 1-10 /* * Copyright (C) 2018 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.tools.build.bundletool.device; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import com.android.bundle.Devices.DeviceSpec; import com.android.tools.build.bundletool.TestData; import com.android.tools.build.bundletool.model.exceptions.ValidationException; import java.nio.file.Paths; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class DeviceSpecParserTest { @Test public void parsesCorrectDeviceSpecFile() throws Exception { DeviceSpec deviceSpec = DeviceSpecParser.parseDeviceSpec(TestData.openReader("testdata/device/pixel2_spec.json")); assertThat(deviceSpec.getSupportedAbisList()) .containsExactly("arm64-v8a", "armeabi-v7a", "armeabi"); assertThat(deviceSpec.getScreenDensity()).isEqualTo(560); assertThat(deviceSpec.getSdkVersion()).isEqualTo(26); assertThat(deviceSpec.getSupportedLocalesList()).containsExactly("en-GB"); } @Test public void parsesCorrectDeviceSpecFile_parsePartialDeviceSpec_Succeeds() throws Exception { DeviceSpec deviceSpec = DeviceSpecParser.parsePartialDeviceSpec( TestData.openReader("testdata/device/pixel2_spec.json")); assertThat(deviceSpec.getSupportedAbisList()) .containsExactly("arm64-v8a", "armeabi-v7a", "armeabi"); assertThat(deviceSpec.getScreenDensity()).isEqualTo(560); assertThat(deviceSpec.getSdkVersion()).isEqualTo(26); assertThat(deviceSpec.getSupportedLocalesList()).containsExactly("en-GB"); } @Test public void wrongFileExtension_throws() throws Exception { Throwable exception = assertThrows( ValidationException.class, () -> DeviceSpecParser.parseDeviceSpec(Paths.get("device_spec.wrong_extension"))); assertThat(exception) .hasMessageThat() .contains("Expected .json extension for the device spec file"); } @Test public void rejectsNegativeDensity() throws Exception { Throwable exception = assertThrows( ValidationException.class, () -> DeviceSpecParser.parseDeviceSpec( TestData.openReader("testdata/device/invalid_spec_density_negative.json"))); assertThat(exception).hasMessageThat().contains("Device spec screen density (-1)"); } @Test public void rejectsSdkLevelZero() throws Exception { Throwable exception = assertThrows( ValidationException.class, () -> DeviceSpecParser.parseDeviceSpec( TestData.openReader("testdata/device/invalid_spec_sdk_zero.json"))); assertThat(exception).hasMessageThat().contains("Device spec SDK version (0)"); } @Test public void rejectsEmptyLocaleList() throws Exception { Throwable exception = assertThrows( ValidationException.class, () -> DeviceSpecParser.parseDeviceSpec( TestData.openReader("testdata/device/invalid_spec_locales_empty.json"))); assertThat(exception).hasMessageThat().contains("Device spec supported locales list is empty"); } @Test public void parsePartialDeviceSpec_acceptEmptyAbi() throws Exception { DeviceSpec deviceSpec = DeviceSpecParser.parsePartialDeviceSpec( TestData.openReader("testdata/device/invalid_spec_abi_empty.json")); assertThat(deviceSpec.getSupportedAbisList()).isEmpty(); assertThat(deviceSpec.getScreenDensity()).isEqualTo(411); assertThat(deviceSpec.getSdkVersion()).isEqualTo(1); assertThat(deviceSpec.getSupportedLocalesList()).containsExactly("en-US", "es-US"); } @Test public void parsePartialDeviceSpec_acceptEmptyLocaleList() throws Exception { DeviceSpec deviceSpec = DeviceSpecParser.parsePartialDeviceSpec( TestData.openReader("testdata/device/invalid_spec_locales_empty.json")); assertThat(deviceSpec.getSupportedAbisList()).containsExactly("armeabi-v7a"); assertThat(deviceSpec.getScreenDensity()).isEqualTo(411); assertThat(deviceSpec.getSdkVersion()).isEqualTo(24); assertThat(deviceSpec.getSupportedLocalesList()).isEmpty(); } @Test public void parsePartialDeviceSpec_acceptZeroSdk() throws Exception { DeviceSpec deviceSpec = DeviceSpecParser.parsePartialDeviceSpec( TestData.openReader("testdata/device/invalid_spec_sdk_zero.json")); assertThat(deviceSpec.getSupportedAbisList()).containsExactly("armeabi-v7a"); assertThat(deviceSpec.getScreenDensity()).isEqualTo(411); assertThat(deviceSpec.getSdkVersion()).isEqualTo(0); assertThat(deviceSpec.getSupportedLocalesList()).containsExactly("en-US", "es-US"); } @Test public void parsePartialDeviceSpec_acceptZeroDensity() throws Exception { DeviceSpec deviceSpec = DeviceSpecParser.parsePartialDeviceSpec( TestData.openReader("testdata/device/invalid_spec_density_zero.json")); assertThat(deviceSpec.getSupportedAbisList()).containsExactly("armeabi-v7a"); assertThat(deviceSpec.getScreenDensity()).isEqualTo(0); assertThat(deviceSpec.getSdkVersion()).isEqualTo(23); assertThat(deviceSpec.getSupportedLocalesList()).containsExactly("en-US", "es-US"); } @Test public void parsePartialDeviceSpec_rejectsNegativeDensity() throws Exception { Throwable exception = assertThrows( ValidationException.class, () -> DeviceSpecParser.parsePartialDeviceSpec( TestData.openReader("testdata/device/invalid_spec_density_negative.json"))); assertThat(exception).hasMessageThat().contains("Device spec screen density (-1)"); } } package seedu.address.commons.core; /** * Container for user visible messages. */ public class Messages { public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command"; public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s"; public static final String MESSAGE_INVALID_PERSON_DISPLAYED_INDEX = "The person index provided is invalid"; public static final String MESSAGE_INDEX_LIST_MISMATCH = "The index cannot be used for current list. "; public static final String MESSAGE_INVALID_TUTORIAL_DISPLAYED_INDEX = "The tutorial index provided is invalid"; public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d persons listed!"; public static final String MESSAGE_INVALID_TUTORIAL_WEEKS = "Invalid Week Number! Tutorial only has %s weeks"; public static final String MESSAGE_TUTORIAL_NOT_FOUND = "There is no class with the given name in camNUS"; public static final String MESSAGE_ASSESSMENT_NOT_FOUND = "An assessment with the given name " + "does not exist in camNUS"; } app/src/main/java/app/debata/com/debata/Chats/ChatViewHolders.java0 package app.debata.com.debata.Chats; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import app.debata.com.debata.R; /** * ImgObject will contain the profile image url. * * @author * @since 1.0 */ public class ChatViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener { public TextView mMessage; public LinearLayout mContainer; public ChatViewHolders(View itemView) { super(itemView); itemView.setOnClickListener(this); // message is the actual text mMessage = itemView.findViewById(R.id.chat_message); // container is the background of the message mContainer = itemView.findViewById(R.id.container); } @Override public void onClick(View view) { } } uyaki-cloud-db/uyaki-cloud-db-postgresql/src/main/java/com/uyaki/cloud/db/postgresql/typehandler/UUIDArrayTypeHandler.java package com.uyaki.cloud.db.postgresql.typehandler; import com.uyaki.cloud.common.core.enums.MathSymbolEnum; import com.uyaki.cloud.db.postgresql.contanst.PatternContansts; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedJdbcTypes; import java.sql.*; import java.util.UUID; import java.util.regex.Matcher; /** * @author uyaki * @date 2019-09-09 08:56 */ @MappedJdbcTypes(JdbcType.ARRAY) public class UUIDArrayTypeHandler extends BaseTypeHandler { @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, UUID[] uuids, JdbcType jdbcType) throws SQLException { Connection connection = preparedStatement.getConnection(); Array array = connection.createArrayOf("uuid", uuids); preparedStatement.setArray(i, array); } @Override public UUID[] getNullableResult(ResultSet resultSet, String s) throws SQLException { String columnValue = resultSet.getString(s); return getUUIDArray(columnValue); } @Override public UUID[] getNullableResult(ResultSet resultSet, int i) throws SQLException { String columnValue = resultSet.getString(i); return getUUIDArray(columnValue); } @Override public UUID[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException { String columnValue = callableStatement.getString(i); return getUUIDArray(columnValue); } private UUID[] getUUIDArray(String columnValue) { if (null == columnValue) { return null; } Matcher m = PatternContansts.ARRAY_CONVERSION_PATTERN.matcher(columnValue); columnValue = m.replaceAll("").trim(); if (columnValue.isEmpty()) { return null; } String[] stringArray = columnValue.split(MathSymbolEnum.COMMA.symbol()); UUID[] uuidArray = new UUID[stringArray.length]; for (int i = 0; i < stringArray.length; i++) { uuidArray[i] = UUID.fromString(stringArray[i]); } return uuidArray; } } package mitsk.gui; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; public class GUI extends JFrame { private Integer clients = 0; private JTextField clientsTextField = new JTextField(clients.toString()); private Integer impatient = 0; private JTextField impatientTextField = new JTextField(impatient.toString()); private Integer inQueue = 0; private JTextField inQueueTextField = new JTextField(inQueue.toString()); GUI() { setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setLocationRelativeTo(null); setTitle("Restaurant Federation"); { clientsTextField.setEditable(false); clientsTextField.setHorizontalAlignment(JTextField.CENTER); JLabel clientsLabel = new JLabel("Clients"); clientsLabel.setLabelFor(clientsTextField); clientsLabel.setVerticalTextPosition(JLabel.CENTER); clientsLabel.setHorizontalTextPosition(JLabel.CENTER); JPanel clientsPanel = new JPanel(new GridLayout(2, 1)); clientsPanel.add(clientsLabel); clientsPanel.add(clientsTextField); clientsPanel.setBorder(new EmptyBorder(16, 16, 16, 16)); add(clientsPanel); } { impatientTextField.setEditable(false); impatientTextField.setHorizontalAlignment(JTextField.CENTER); JLabel impatientLabel = new JLabel("Impatient Clients"); impatientLabel.setLabelFor(impatientTextField); impatientLabel.setVerticalTextPosition(JLabel.CENTER); impatientLabel.setHorizontalTextPosition(JLabel.CENTER); JPanel impatientPanel = new JPanel(new GridLayout(2, 1)); impatientPanel.add(impatientLabel); impatientPanel.add(impatientTextField); impatientPanel.setBorder(new EmptyBorder(16, 16, 16, 16)); add(impatientPanel); } { inQueueTextField.setEditable(false); inQueueTextField.setHorizontalAlignment(JTextField.CENTER); JLabel inQueueLabel = new JLabel("Queue"); inQueueLabel.setLabelFor(inQueueTextField); inQueueLabel.setVerticalTextPosition(JLabel.CENTER); inQueueLabel.setHorizontalTextPosition(JLabel.CENTER); JPanel inQueuePanel = new JPanel(new GridLayout(2, 1)); inQueuePanel.add(inQueueLabel); inQueuePanel.add(inQueueTextField); inQueuePanel.setBorder(new EmptyBorder(16, 16, 16, 16)); add(inQueuePanel); } setLayout(new GridLayout(1, 3)); } void addClient() { ++clients; updateAll(); } void addImpatientClient() { removeClient(); removeFromQueue(); ++impatient; updateAll(); } void addToQueue() { ++inQueue; updateAll(); } void removeClient() { --clients; updateAll(); } void removeFromQueue() { --inQueue; updateAll(); } public void run() { pack(); setVisible(true); } private void updateAll() { clientsTextField.setText(clients.toString()); impatientTextField.setText(impatient.toString()); inQueueTextField.setText(inQueue.toString()); validate(); repaint(); pack(); } } 1-10 /* * Decompiled with CFR 0_119. */ package script.patterns; import script.patterns.PatternTransformer; public class NullTransformer implements PatternTransformer { @Override public String transform(String input) { return input; } } package com.skey.myserver.server; import com.skey.myserver.utils.IOUtils; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * MyServer 服务 * * @author ALion * @version 2018/8/3 23:27 */ public class Server { private static ServerSocket server; private boolean isShutdown = false; public void start() { start(8888); } public void start(int port) { try { server = new ServerSocket(port); WebApp.init();//触发静态代码块初始化,XML解析 this.receive(); } catch (IOException e) { e.printStackTrace(); stop(); } } private void receive() { try { while (!isShutdown) { Socket client = server.accept(); new Thread(new Dispatcher(client)).start(); } } catch (IOException e) { // e.printStackTrace(); stop(); } } public void stop() { isShutdown = true; IOUtils.close(server); } } /* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.ballerinalang.util.codegen; import org.ballerinalang.model.types.BType; import java.util.HashMap; import java.util.Map; /** * {@code CallableUnitInfo} contains common metadata of a Ballerina function/resource/action in the program file. * * @since 0.87 */ public class CallableUnitInfo { protected String pkgPath; protected String name; protected boolean isNative; // Index to the PackageCPEntry protected int pkgCPIndex; protected int nameCPIndex; protected BType[] paramTypes; protected BType[] retParamTypes; protected CodeAttributeInfo codeAttributeInfo; protected Map attributeInfoMap = new HashMap<>(); // protected Map workerInfoMap = new HashMap<>(); private PackageInfo packageInfo; protected WorkerInfo defaultWorkerInfo; protected Map workerInfoMap = new HashMap<>(); public String getName() { return name; } public String getPkgPath() { return pkgPath; } public void setName(String name) { this.name = name; } public int getPackageCPIndex() { return pkgCPIndex; } public PackageInfo getPackageInfo() { return packageInfo; } public int getNameCPIndex() { return nameCPIndex; } public void setNameCPIndex(int nameCPIndex) { this.nameCPIndex = nameCPIndex; } public void setPackageInfo(PackageInfo packageInfo) { this.packageInfo = packageInfo; } public boolean isNative() { return isNative; } public void setNative(boolean aNative) { isNative = aNative; } public BType[] getParamTypes() { return paramTypes; } public void setParamTypes(BType[] paramTypes) { this.paramTypes = paramTypes; } public BType[] getRetParamTypes() { return retParamTypes; } public void setRetParamTypes(BType[] retParamType) { this.retParamTypes = retParamType; } public WorkerInfo getDefaultWorkerInfo() { return defaultWorkerInfo; } public void setDefaultWorkerInfo(WorkerInfo defaultWorkerInfo) { this.defaultWorkerInfo = defaultWorkerInfo; } public WorkerInfo getWorkerInfo(String workerName) { return workerInfoMap.get(workerName); } public void addWorkerInfo(String attributeName, WorkerInfo workerInfo) { workerInfoMap.put(attributeName, workerInfo); } public Map getWorkerInfoMap() { return workerInfoMap; } public CodeAttributeInfo getCodeAttributeInfo() { return codeAttributeInfo; } public AttributeInfo getAttributeInfo(String attributeName) { return attributeInfoMap.get(attributeName); } public void addAttributeInfo(String attributeName, AttributeInfo attributeInfo) { attributeInfoMap.put(attributeName, attributeInfo); } // public WorkerInfo getWorkerInfo(String workerName) { // return workerInfoMap.get(workerName); // } // // public void addWorkerInfo(String attributeName, WorkerInfo workerInfo) { // workerInfoMap.put(attributeName, workerInfo); // } public AnnotationAttachmentInfo getAnnotationAttachmentInfo(String packageName, String annotationName) { AnnotationAttributeInfo attributeInfo = (AnnotationAttributeInfo) getAttributeInfo( AttributeInfo.ANNOTATIONS_ATTRIBUTE); if (attributeInfo == null || packageName == null || annotationName == null) { return null; } for (AnnotationAttachmentInfo annotationInfo : attributeInfo.getAnnotationAttachmentInfo()) { if (packageName.equals(annotationInfo.getPkgPath()) && annotationName.equals(annotationInfo.getName())) { return annotationInfo; } } return null; } } Submission/src/student_player/TranspositionState.java package student_player; import boardgame.Move; import pentago_twist.PentagoBoardState; import java.util.Arrays; public class TranspositionState{ PentagoBoardState currentBoardState; int utility; int visitCount; double pWinScore; Move nextBestMove; public TranspositionState(PentagoBoardState pState, int pUtility){ currentBoardState = (PentagoBoardState) pState.clone(); utility = pUtility; //visitCount = } public int getUtility(){ return utility; } public static int KeysGenerator(PentagoBoardState currentBoard){ PentagoBoardState.Piece[][] board = currentBoard.getBoard(); return Arrays.deepHashCode(board); /*int[] black_x = new int[6]; int[] white_x = new int[6]; int[] black_y = new int[6]; int[] white_y = new int[6]; for(int i = 0; i< 6; i++){ black_x[i] = 00; //heng white_x[i] = 00; black_y[i] = 00; //shu white_y[i] = 00; } for(int i = 0; i < 6; i++){ for(int j = 0; j < 6; j++){ if(board[i][j] == PentagoBoardState.Piece.BLACK){ black_x[i]++; }else if(board[i][j] == PentagoBoardState.Piece.WHITE){ white_x[i]++; } if(board[j][i] == PentagoBoardState.Piece.BLACK){ black_y[i]++; }else if(board[j][i] == PentagoBoardState.Piece.WHITE){ white_y[i]++; } } } int bx = 00; int wx = 00; int by = 00; int wy = 00; for(int i = 0; i < 6; i++){ bx = bx*8 +black_x[i]; wx = wx*8 +white_x[i]; by = by*8 + black_y[i]; wy = wy*8 + white_y[i]; } return (long) (bx*Math.pow(8, 18) + wx*Math.pow(8, 12) + by*Math.pow(8, 6)+ wy)*/ /*long white_key = 0b0; long black_key = 0b0; long key = 0; for(int i = 0; i < 6; i++){ for(int j = 0; j < 6; j++){ if(board[i][j] == PentagoBoardState.Piece.BLACK){ key = key*10 +2; }else if(board[i][j] == PentagoBoardState.Piece.WHITE){ key = key*10 +1; } else{ key = key*10 + 0; } } } return key;*/ } }/* * 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 macromedia.asc.parser; import macromedia.asc.util.*; import macromedia.asc.semantics.*; /** * Node */ public class TryStatementNode extends Node { public StatementListNode tryblock; public StatementListNode catchlist; public FinallyClauseNode finallyblock; public boolean finallyInserted; public int loop_index; public TryStatementNode(StatementListNode tryblock, StatementListNode catchlist, FinallyClauseNode finallyblock) { this.tryblock = tryblock; this.catchlist = catchlist; this.finallyblock = finallyblock; this.finallyInserted = false; } public Value evaluate(Context cx, Evaluator evaluator) { if (evaluator.checkFeature(cx, this)) { return evaluator.evaluate(cx, this); } else { return null; } } public int countVars() { return (tryblock != null ? tryblock.countVars() : 0) + (catchlist != null ? catchlist.countVars() : 0) + (finallyblock != null ? finallyblock.countVars() : 0); } public boolean isBranch() { return true; } public String toString() { return "TryStatement"; } private boolean skip = false; public void skipNode(boolean b) { skip = b; } public boolean skip() { return skip; } } package au.aurin.org.svc; public class appData { private long app_id; private String appname; public long getApp_id() { return app_id; } public void setApp_id(final long app_id) { this.app_id = app_id; } public String getAppname() { return appname; } public void setAppname(final String appname) { this.appname = appname; } } TruthOriginem/Insight package com.originem.insight.blocks; import com.originem.insight.blockentities.BlockEntityObsidianReactor; import com.originem.insight.blocks.base.AbstractBlockAutomationWithDirection; import com.originem.insight.registry.BlockEntitiesRegistry; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.fabricmc.yarn.constants.MiningLevels; import net.minecraft.block.BlockState; import net.minecraft.block.Blocks; import net.minecraft.block.entity.BlockEntity; import net.minecraft.block.entity.BlockEntityTicker; import net.minecraft.block.entity.BlockEntityType; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.Direction; import net.minecraft.world.World; import org.jetbrains.annotations.Nullable; import java.util.Random; public class BlockObsidianReactor extends AbstractBlockAutomationWithDirection { public BlockObsidianReactor(Settings settings) { super(settings); } public BlockObsidianReactor() { this(FabricBlockSettings.copyOf(Blocks.OBSIDIAN) .requiresTool().breakByTool(FabricToolTags.PICKAXES, MiningLevels.DIAMOND)); this.setDefaultState(getStateManager().getDefaultState().with(WORKING, false).with(FACING, Direction.NORTH)); } @Environment(EnvType.CLIENT) public void randomDisplayTick(BlockState state, World world, BlockPos pos, Random random) { if (state.get(WORKING)) { if (random.nextInt(200) == 0) world.playSound(pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, SoundEvents.BLOCK_LAVA_AMBIENT, SoundCategory.BLOCKS, 0.2F + random.nextFloat() * 0.2F, 0.9F + random.nextFloat() * 0.15F, false); } } @Nullable @Override public BlockEntity createBlockEntity(BlockPos pos, BlockState state) { return new BlockEntityObsidianReactor(pos, state); } @Nullable @Override public BlockEntityTicker getTicker(World world, BlockState state, BlockEntityType type) { return world.isClient ? null : checkType(type, BlockEntitiesRegistry.BLOCK_ENTITY_OBSIDIAN_REACTOR, BlockEntityObsidianReactor::serverTick); } } rpatil524/datacollector /** * Copyright 2015 StreamSets Inc. * * Licensed under 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 com.streamsets.datacollector.base; import com.streamsets.datacollector.MiniSDC; import com.streamsets.datacollector.MiniSDCTestingUtility; import com.streamsets.datacollector.util.VerifyUtils; import org.junit.After; import org.junit.Before; import org.junit.Test; import javax.ws.rs.core.Response; import java.io.IOException; import java.net.URI; import java.util.Map; import static org.junit.Assert.assertEquals; public abstract class PipelineRunStandaloneIT { protected abstract String getPipelineJson() throws Exception; protected abstract int getRecordsInOrigin(); protected abstract int getRecordsInTarget() throws IOException; protected abstract String getPipelineName(); protected abstract String getPipelineRev(); private MiniSDCTestingUtility miniSDCTestingUtility; @Before public void setUp() throws Exception { miniSDCTestingUtility = new MiniSDCTestingUtility(); } @After public void tearDown() throws Exception { } @Test public void testPipelineRun() throws Exception { System.setProperty("sdc.testing-mode", "true"); try { MiniSDC miniSDC = miniSDCTestingUtility.createMiniSDC(MiniSDC.ExecutionMode.STANDALONE); miniSDC.startSDC(); URI serverURI = miniSDC.getServerURI(); miniSDC.createAndStartPipeline(getPipelineJson()); //FIXME: Do we need to wait for 5 seconds? Thread.sleep(5000); Map> countersMap = VerifyUtils.getCountersFromMetrics(serverURI, getPipelineName(), getPipelineRev()); int recordsInTarget = getRecordsInTarget(); int recordsInOrigin = getRecordsInOrigin(); assertEquals("Output records counter for source should be equal to " + recordsInOrigin, recordsInOrigin, VerifyUtils.getSourceOutputRecords(countersMap)); assertEquals("Output records counter for target should be equal to " + recordsInTarget, recordsInTarget, VerifyUtils.getTargetOutputRecords(countersMap)); assertEquals("Records output by Origin should be same as Records in Destination", recordsInOrigin, recordsInTarget); } finally { miniSDCTestingUtility.stopMiniSDC(); } } private static void checkResponse(Response response, Response.Status expectedStatus) { if(response.getStatusInfo().getStatusCode() != expectedStatus.getStatusCode()) { throw new RuntimeException("Request Failed with Error code : " + response.getStatusInfo() + ". Error details: " + response.getStatusInfo().getReasonPhrase()); } } } 1-10 package io.toolisticon.byoct.jpa.mapkeyjoincolumnprocessor.testmethod; import javax.persistence.MapKeyJoinColumn; public class TestcaseValidUsage { @MapKeyJoinColumn() String method( String parameter) { return null; } }pasdfasdf/voogasalad0 package newengine.events.input; import bus.BusEvent; import bus.BusEventType; import newengine.player.Player; import newengine.utils.ActionMode; import newengine.utils.Target; public class GameWorldMouseEvent extends BusEvent { public static final BusEventType CONFIRM_SKILL = new BusEventType<>("CONFIRM_SKILL"); public static final BusEventType CANCEL_SKILL_AND_MOVE_SPRITE = new BusEventType<>("CANCEL_SKILL_AND_MOVE_SPRITE"); public static final BusEventType SELECT_SPRITE = new BusEventType<>("SELECT_SPRITE"); private Target target; private ActionMode actionMode; private Player player; public GameWorldMouseEvent(BusEventType busEventType, Target target, ActionMode actionMode, Player player) { super(busEventType); this.target = target; this.actionMode = actionMode; this.player = player; } public Target getTarget() { return target; } public ActionMode getActionMode() { return actionMode; } public Player getPlayer() { return player; } } package org.iclub.repository; import java.util.List; import java.util.Optional; import org.iclub.model.BinaryFile; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface BinaryFileRepository extends JpaRepository { Optional findBinaryFileByLogo(Boolean logo); List findByScroller(Boolean scroller); List findByResource(Boolean resource); } /* * Copyright (c) 2005-2013 * and Washington University in St. Louis * * 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. * */ /* * File: NodeMonitor.java * Author: * Email: * Organization: Washington University * * Derived from: none * * Date Created: 10/23/2003 * * Description: * * Modification History: * */ import java.util.Vector; import java.util.*; import javax.swing.*; import javax.swing.event.*; import java.awt.Font; import java.awt.event.*; import java.net.*; public abstract class NodeMonitor implements NCCPConnection.ConnectionListener, ONLComponent.ONLMonitorable { protected Vector daemons = null; protected MonitorManager monitorManager = null; protected Vector monitorEntries = null; protected ONLComponent onlComponent = null; public NodeMonitor(Vector d, ONLComponent c, MonitorManager w) { this(c,w); //ExpCoordinator.printer.print("NodeMonitor::NodeMonitor (int, NodeMonitor.ID, MonitorManager)"); initializeDaemons(d); } public NodeMonitor(ONLComponent c, MonitorManager w) { daemons = new Vector(); onlComponent = c; monitorManager = w; } protected void initializeDaemons(Vector mds) { int max = mds.size(); for (int i = 0; i < max; ++i) { addDaemon((MonitorDaemon)mds.elementAt(i)); } } //CHANGE to get specific daemon public MonitorDaemon getDaemon(int tp) { int max = daemons.size(); MonitorDaemon elem; ExpCoordinator.printer.print(new String("NodeMonitor.getDaemon looking for " + tp + " daemons:" + max), ExperimentXML.TEST_XML); for (int i = 0; i < max; ++i) { elem = (MonitorDaemon)daemons.elementAt(i); if (elem.isType(tp)) return elem; } ExpCoordinator.printer.print(new String("NodeMonitor.getDaemon looking for " + tp + " didn't find"), 1); return null; } public void addDaemon(MonitorDaemon md) { if (!daemons.contains(md)) { ExpCoordinator.print(new String("NodeMonitor(" + onlComponent.getLabel() + ").addDaemon " + md.toString()), 5); daemons.add(md); md.addConnectionListener(this); } } public void removeDaemon(MonitorDaemon md) { daemons.remove(md);} public MonitorManager getMonitorManager() { return monitorManager;} public void setMonitorManager(MonitorManager w) { monitorManager = w;} //NCCPConnection.ConnectionListener public void connectionFailed(NCCPConnection.ConnectionEvent e) { //removeDaemon((MonitorDaemon)(e.getSource())); } public void connectionClosed(NCCPConnection.ConnectionEvent e){} public void connectionOpened(NCCPConnection.ConnectionEvent e){} //end interface NCCPConnection.ConnectionListener public abstract Monitor addMonitor(MonitorDataType.Base dt); public Monitor addMonitor(Monitor m) { ExpCoordinator.printer.print(new String("NodeMonitor.addMonitor(Monitor)"), 1); MonitorDaemon md = getDaemon(m.getDataType().getDaemonType()); if (md != null) return (md.addMonitor(m)); else ExpCoordinator.printer.print("NodeMonitor.addMonitor(Monitor) daemon is null"); return null; } public void removeMonitor(Monitor m) { MonitorDaemon md = getDaemon(m.getDataType().getDaemonType()); if (md != null) md.removeMonitor(m); } public ONLComponent getONLComponent() { return onlComponent;} public void clear() { int max = daemons.size(); MonitorDaemon elem; for (int i = 0; i < max; ++i) { elem = (MonitorDaemon)daemons.elementAt(i); elem.clear(); } } public void addActions(ONLComponent.CfgMonMenu menu) {} } java-programming/src/main/java/com/github/akarazhev/jacademy/jprog/collections/linkedlist/v2/LinkedListDemo.java package com.github.akarazhev.jacademy.jprog.collections.linkedlist.v2; import java.util.LinkedList; public class LinkedListDemo { public static void main(String[] args) { LinkedList linkedList = new LinkedList<>(); linkedList.add(1); linkedList.add(2); linkedList.add(3); linkedList.add(4); linkedList.add(2); linkedList.add(4); linkedList.add(5); System.out.println("LinkedList before removing any element " + linkedList); linkedList.remove(); //Removes the first element. System.out.println("LinkedList after removing first element " + linkedList); linkedList.removeLast(); //Removes the last element. System.out.println("LinkedList after removing last element " + linkedList); linkedList.remove(new Integer(2)); //Removes the first occurrence of 2. System.out.println("LinkedList after removing first occurrence of 2. " + linkedList); linkedList.removeLastOccurrence(new Integer(4)); //Removes the last occurrence of 4. System.out.println("LinkedList after removing the last occurrence of 4. " + linkedList); } } 825245794/JavaCodeExerciseOnClass2015-20190 package myPackage; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport{ /** * */ private static final long serialVersionUID = 1L; private String username; private String info; public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } // public String execute(){ // return SUCCESS; // } public String add()throws Exception{ info="添加用户信息"; return "add"; } public String update()throws Exception{ info="更新用户信息"; return "update"; } } js-lib-com/rest-clientsrc/main/java/js/rest/client/RestClientFactory.java package js.rest.client; import java.lang.reflect.Proxy; import js.rmi.RemoteFactory; import js.rmi.UnsupportedProtocolException; import js.util.Params; public class RestClientFactory implements RemoteFactory { @SuppressWarnings("unchecked") public I getRemoteInstance(String implementationURL, Class interfaceClass) throws UnsupportedProtocolException { Params.notNull(implementationURL, "Implementation URL"); Params.notNull(interfaceClass, "Interface class"); // at this point we know that interface class is a super of returned instance class so is safe to suppress warning return (I) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[] { interfaceClass }, new RestTransactionHandler(implementationURL)); } } package com.langdashu.flexible.uid.core.constant; /** * 环境标识 * *

更多内容参看浪大叔 * @author 浪大叔 */ public enum Env { LOCAL("local"), DEV("dev"), TEST("test"), STG("stg"), SIT("sit"), PRD("prd"), NONE("none"); private String code; Env(String code) { this.code = code; } public String getCode() { return code; } } thefirstwind/tech_core package com.thefirstwind; import java.util.concurrent.TimeUnit; public class Case018_Synchronized { synchronized void m(){ System.out.println("m start"); try{ TimeUnit.SECONDS.sleep(1); } catch(InterruptedException e){ e.printStackTrace(); } System.out.println("m end"); } public static void main(String[] args){ Case018_Synchronized_Child child = new Case018_Synchronized_Child(); child.m(); } } class Case018_Synchronized_Child extends Case018_Synchronized{ @Override synchronized void m(){ System.out.println("child m start"); super.m(); System.out.println("child m end"); } } package iams.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import iams.dao.HallDao; /** * Servlet implementation class DeleteHallServelet */ @WebServlet("/DeleteHallServelet") public class DeleteHallServelet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public DeleteHallServelet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String id = request.getParameter("btn_delete"); System.out.println(id); HallDao hall = new HallDao(); hall.deleteHall(id); response.sendRedirect("Halls.jsp"); } } /* * Copyright (c) 2020-2021 . * * 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.thepavel.jpqlbuilder.functions; import org.junit.Test; import org.thepavel.jpqlbuilder.DummyObject; import org.thepavel.jpqlbuilder.proxy.EntityProxyFactory; import org.thepavel.jpqlbuilder.model.Company; import org.thepavel.jpqlbuilder.model.Status; import java.time.LocalDate; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import static org.junit.Assert.assertEquals; import static org.thepavel.jpqlbuilder.DummyFunction.dummy; import static org.thepavel.jpqlbuilder.DummyJpqlStringWriter.asString; public class FunctionsTest { @Test public void lower() { assertEquals("lower(A)", asString(new Lower("A"))); } @Test public void upper() { assertEquals("upper(A)", asString(new Upper("A"))); } @Test public void upperLower() { assertEquals("upper(lower(A))", asString(new Upper(new Lower("A")))); } @Test public void lowerUpper() { assertEquals("lower(upper(A))", asString(new Lower(new Upper("A")))); } @Test public void trim() { assertEquals("trim(A)", asString(new Trim("A"))); } @Test public void trimWithChar() { assertEquals("trim(x from A)", asString(new Trim("A", 'x'))); } @Test public void nestedTrim() { assertEquals("trim(lower(A))", asString(new Trim(new Lower("A")))); } @Test public void nestedTrimWithChar() { assertEquals("trim(x from lower(A))", asString(new Trim(new Lower("A"), 'x'))); } @Test public void leftTrim() { assertEquals("trim(leading from A)", asString(new LeftTrim("A"))); } @Test public void leftTrimWithChar() { assertEquals("trim(leading x from A)", asString(new LeftTrim("A", 'x'))); } @Test public void nestedLeftTrim() { assertEquals("trim(leading from lower(A))", asString(new LeftTrim(new Lower("A")))); } @Test public void nestedLeftTrimWithChar() { assertEquals("trim(leading x from lower(A))", asString(new LeftTrim(new Lower("A"), 'x'))); } @Test public void rightTrim() { assertEquals("trim(trailing from A)", asString(new RightTrim("A"))); } @Test public void rightTrimWithChar() { assertEquals("trim(trailing x from A)", asString(new RightTrim("A", 'x'))); } @Test public void nestedRightTrim() { assertEquals("trim(trailing from lower(A))", asString(new RightTrim(new Lower("A")))); } @Test public void nestedRightTrimWithChar() { assertEquals("trim(trailing x from lower(A))", asString(new RightTrim(new Lower("A"), 'x'))); } @Test public void concatSingle() { assertEquals("concat(A)", asString(new Concat("A"))); } @Test public void concatSingleNested() { assertEquals("concat(lower(A))", asString(new Concat(new Lower("A")))); } @Test public void concatMulti() { assertEquals("concat(A, B, C)", asString(new Concat("A", "B", "C"))); } @Test public void concatMultiNested() { assertEquals("concat(lower(A), upper(B))", asString(new Concat(new Lower("A"), new Upper("B")))); } @Test public void substringNoLength() { assertEquals("substring(A, 1)", asString(new Substring("A", 1))); } @Test public void substringNoLengthNested() { assertEquals("substring(lower(A), 1)", asString(new Substring(new Lower("A"), 1))); assertEquals("substring(A, dummy(1))", asString(new Substring("A", dummy(1)))); assertEquals("substring(lower(A), dummy(1))", asString(new Substring(new Lower("A"), dummy(1)))); } @Test public void substring() { assertEquals("substring(A, 1, 2)", asString(new Substring("A", 1, 2))); } @Test public void substringNested() { assertEquals("substring(A, dummy(1), 2)", asString(new Substring("A", dummy(1), 2))); assertEquals("substring(A, 1, dummy(2))", asString(new Substring("A", 1, dummy(2)))); assertEquals("substring(A, dummy(1), dummy(2))", asString(new Substring("A", dummy(1), dummy(2)))); assertEquals("substring(lower(A), 1, 2)", asString(new Substring(new Lower("A"), 1, 2))); assertEquals("substring(lower(A), dummy(1), 2)", asString(new Substring(new Lower("A"), dummy(1), 2))); assertEquals("substring(lower(A), 1, dummy(2))", asString(new Substring(new Lower("A"), 1, dummy(2)))); assertEquals("substring(lower(A), dummy(1), dummy(2))", asString(new Substring(new Lower("A"), dummy(1), dummy(2)))); } @Test public void length() { assertEquals("length(A)", asString(new Length("A"))); } @Test public void lengthNested() { assertEquals("length(lower(A))", asString(new Length(new Lower("A")))); } @Test public void locateNoPosition() { assertEquals("locate(A, B)", asString(new Locate("A", "B"))); } @Test public void locateNoPositionNested() { assertEquals("locate(lower(A), B)", asString(new Locate(new Lower("A"), "B"))); assertEquals("locate(A, lower(B))", asString(new Locate("A", new Lower("B")))); assertEquals("locate(lower(A), lower(B))", asString(new Locate(new Lower("A"), new Lower("B")))); } @Test public void locate() { assertEquals("locate(A, B, 1)", asString(new Locate("A", "B", 1))); } @Test public void locateNested() { assertEquals("locate(A, lower(B), 1)", asString(new Locate("A", new Lower("B"), 1))); assertEquals("locate(A, B, dummy(1))", asString(new Locate("A", "B", dummy(1)))); assertEquals("locate(A, lower(B), dummy(1))", asString(new Locate("A", new Lower("B"), dummy(1)))); assertEquals("locate(lower(A), B, 1)", asString(new Locate(new Lower("A"), "B", 1))); assertEquals("locate(lower(A), lower(B), 1)", asString(new Locate(new Lower("A"), new Lower("B"), 1))); assertEquals("locate(lower(A), B, dummy(1))", asString(new Locate(new Lower("A"), "B", dummy(1)))); assertEquals("locate(lower(A), lower(B), dummy(1))", asString(new Locate(new Lower("A"), new Lower("B"), dummy(1)))); } @Test public void add() { assertEquals("1 + 2", asString(new Add<>(1, 2))); assertEquals("1 + 2", asString(new Add<>(1, 2L))); assertEquals("1 + 2.3", asString(new Add<>(1, 2.3))); } @Test public void addNested() { assertEquals("length(A) + 2", asString(new Add<>(new Length("A"), 2))); assertEquals("1.2 + length(B)", asString(new Add<>(1.2, new Length("B")))); assertEquals("1 + 2 + 3 + 4", asString(new Add<>(new Add<>(1, 2), new Add<>(3, 4)))); assertEquals("1 + 2 + 3 - 4", asString(new Add<>(new Add<>(1, 2), new Sub<>(3, 4)))); assertEquals("1 + 2 + 3 * 4", asString(new Add<>(new Add<>(1, 2), new Multi<>(3, 4)))); assertEquals("1 + 2 + 3 / 4", asString(new Add<>(new Add<>(1, 2), new Div<>(3, 4)))); } @Test public void sub() { assertEquals("1 - 2", asString(new Sub<>(1, 2))); assertEquals("1 - 2", asString(new Sub<>(1, 2L))); assertEquals("1 - 2.3", asString(new Sub<>(1, 2.3))); } @Test public void subNested() { assertEquals("length(A) - 2", asString(new Sub<>(new Length("A"), 2))); assertEquals("1.2 - length(B)", asString(new Sub<>(1.2, new Length("B")))); assertEquals("1 + 2 - (3 + 4)", asString(new Sub<>(new Add<>(1, 2), new Add<>(3, 4)))); assertEquals("1 + 2 - (3 - 4)", asString(new Sub<>(new Add<>(1, 2), new Sub<>(3, 4)))); assertEquals("1 + 2 - 3 * 4", asString(new Sub<>(new Add<>(1, 2), new Multi<>(3, 4)))); assertEquals("1 + 2 - 3 / 4", asString(new Sub<>(new Add<>(1, 2), new Div<>(3, 4)))); } @Test public void multi() { assertEquals("1 * 2", asString(new Multi<>(1, 2))); assertEquals("1 * 2", asString(new Multi<>(1, 2L))); assertEquals("1 * 2.3", asString(new Multi<>(1, 2.3))); } @Test public void multiNested() { assertEquals("length(A) * 2", asString(new Multi<>(new Length("A"), 2))); assertEquals("1.2 * length(B)", asString(new Multi<>(1.2, new Length("B")))); assertEquals("(1 + 2) * (3 - 4)", asString(new Multi<>(new Add<>(1, 2), new Sub<>(3, 4)))); assertEquals("1 * 2 * (3 / 4)", asString(new Multi<>(new Multi<>(1, 2), new Div<>(3, 4)))); assertEquals("1 * 2 * 3 * 4", asString(new Multi<>(new Multi<>(1, 2), new Multi<>(3, 4)))); } @Test public void div() { assertEquals("1 / 2", asString(new Div<>(1, 2))); assertEquals("1 / 2", asString(new Div<>(1, 2L))); assertEquals("1 / 2.3", asString(new Div<>(1, 2.3))); } @Test public void divNested() { assertEquals("length(A) / 2", asString(new Div<>(new Length("A"), 2))); assertEquals("1.2 / length(B)", asString(new Div<>(1.2, new Length("B")))); assertEquals("(1 + 2) / (3 - 4)", asString(new Div<>(new Add<>(1, 2), new Sub<>(3, 4)))); assertEquals("(1 / 2) / (3 * 4)", asString(new Div<>(new Div<>(1, 2), new Multi<>(3, 4)))); } @Test public void abs() { assertEquals("abs(1)", asString(new Abs<>(1))); } @Test public void absNested() { assertEquals("abs(1 - 2)", asString(new Abs<>(new Sub<>(1, 2)))); } @Test public void mod() { assertEquals("mod(10 / 20)", asString(new Mod<>(new Div<>(10, 20)))); } @Test public void sqrt() { assertEquals("sqrt(1)", asString(new Sqrt<>(1))); } @Test public void sqrtNested() { assertEquals("sqrt(1 + 2)", asString(new Sqrt<>(new Add<>(1, 2)))); } @Test public void currentDate() { assertEquals("current_date", asString(new CurrentDate())); } @Test public void currentTime() { assertEquals("current_time", asString(new CurrentTime())); } @Test public void currentTimestamp() { assertEquals("current_timestamp", asString(new CurrentTimestamp())); } @Test public void caseTest() { assertEquals( "case 1 when 2 then 3 when 4 then 5 else 6 end", asString(new Case<>(1).when(2).then(3).when(4).then(5).orElse(6)) ); } @Test public void caseNestedTest() { assertEquals( "case 1 + 2 when 1 + 2 then 3 + 4 when 5 + 6 then 7 + 8 else 9 + 10 end", asString(new Case<>(new Add<>(1, 2)).when(new Add<>(1, 2)).then(new Add<>(3, 4)).when(new Add<>(5, 6)).then(new Add<>(7, 8)).orElse(new Add<>(9, 10))) ); } @Test public void casePredicate() { assertEquals( "case when 1 = 2 then 3 when 4 = 5 then 6 else 7 end", asString(new CasePredicate().when(1).is(2).then(3).when(4).is(5).then(6).orElse(7)) ); } @Test public void casePredicateNested() { assertEquals( "case when 1 + 2 = 3 then 4 + 5 when 6 + 7 = 8 then 9 + 10 else 11 + 12 end", asString(new CasePredicate().when(new Add<>(1, 2)).is(3).then(new Add<>(4, 5)).when(new Add<>(6, 7)).is(8).then(new Add<>(9, 10)).orElse(new Add<>(11, 12))) ); } @Test public void casePredicateCollection() { List list = new ArrayList<>(); assertEquals( "case when [] is empty then 1 when [] is not empty then 2 else 0 end", asString(new CasePredicate().when(list).isEmpty().then(1).when(list).isNotEmpty().then(2).orElse(0)) ); } @Test public void coalesceSingle() { assertEquals("coalesce(A)", asString(new Coalesce<>("A"))); } @Test public void coalesceSingleNested() { assertEquals("coalesce(lower(A))", asString(new Coalesce<>(new Lower("A")))); } @Test public void coalesceMulti() { assertEquals("coalesce(A, B)", asString(new Coalesce<>("A", "B"))); } @Test public void coalesceMultiNested() { assertEquals("coalesce(lower(A), lower(B))", asString(new Coalesce<>(new Lower("A"), new Lower("B")))); } @Test public void coalesceMixed() { assertEquals("coalesce(A, lower(B))", asString(new Coalesce<>("A").coalesce(new Lower("B")))); assertEquals("coalesce(lower(A), B)", asString(new Coalesce<>(new Lower("A")).coalesce("B"))); } @Test public void nullif() { assertEquals("nullif(A, B)", asString(new Nullif<>("A", "B"))); } @Test public void nullifNested() { assertEquals("nullif(lower(A), lower(B))", asString(new Nullif<>(new Lower("A"), new Lower("B")))); } @Test public void cast() { assertEquals("cast(A byte)", asString(new Cast<>("A", Cast.Type.BYTE))); assertEquals("cast(A short)", asString(new Cast<>("A", Cast.Type.SHORT))); assertEquals("cast(A integer)", asString(new Cast<>("A", Cast.Type.INTEGER))); assertEquals("cast(A long)", asString(new Cast<>("A", Cast.Type.LONG))); assertEquals("cast(A float)", asString(new Cast<>("A", Cast.Type.FLOAT))); assertEquals("cast(A double)", asString(new Cast<>("A", Cast.Type.DOUBLE))); assertEquals("cast(A character)", asString(new Cast<>("A", Cast.Type.CHAR))); assertEquals("cast(A boolean)", asString(new Cast<>("A", Cast.Type.BOOLEAN))); assertEquals("cast(A yes_no)", asString(new Cast<>("A", Cast.Type.YES_NO))); assertEquals("cast(A true_false)", asString(new Cast<>("A", Cast.Type.TRUE_FALSE))); assertEquals("cast(A string)", asString(new Cast<>("A", Cast.Type.STRING))); assertEquals("cast(A date)", asString(new Cast<>("A", Cast.Type.DATE))); assertEquals("cast(A time)", asString(new Cast<>("A", Cast.Type.TIME))); assertEquals("cast(A timestamp)", asString(new Cast<>("A", Cast.Type.TIMESTAMP))); assertEquals("cast(A calendar)", asString(new Cast<>("A", Cast.Type.CALENDAR))); assertEquals("cast(A calendar_date)", asString(new Cast<>("A", Cast.Type.CALENDAR_DATE))); assertEquals("cast(A big_decimal)", asString(new Cast<>("A", Cast.Type.BIG_DECIMAL))); assertEquals("cast(A big_integer)", asString(new Cast<>("A", Cast.Type.BIG_INTEGER))); assertEquals("cast(A locale)", asString(new Cast<>("A", Cast.Type.LOCALE))); assertEquals("cast(A timezone)", asString(new Cast<>("A", Cast.Type.TIME_ZONE))); assertEquals("cast(A currency)", asString(new Cast<>("A", Cast.Type.CURRENCY))); assertEquals("cast(A class)", asString(new Cast<>("A", Cast.Type.CLASS))); assertEquals("cast(A binary)", asString(new Cast<>("A", Cast.Type.BINARY))); assertEquals("cast(A text)", asString(new Cast<>("A", Cast.Type.TEXT))); assertEquals("cast(A serializable)", asString(new Cast<>("A", Cast.Type.SERIALIZABLE))); assertEquals("cast(A clob)", asString(new Cast<>("A", Cast.Type.CLOB))); assertEquals("cast(A blob)", asString(new Cast<>("A", Cast.Type.BLOB))); assertEquals("cast(A imm_date)", asString(new Cast<>("A", Cast.Type.IMM_DATE))); assertEquals("cast(A imm_time)", asString(new Cast<>("A", Cast.Type.IMM_TIME))); assertEquals("cast(A imm_timestamp)", asString(new Cast<>("A", Cast.Type.IMM_TIMESTAMP))); assertEquals("cast(A imm_calendar)", asString(new Cast<>("A", Cast.Type.IMM_CALENDAR))); assertEquals("cast(A imm_calendar_date)", asString(new Cast<>("A", Cast.Type.IMM_CALENDAR_DATE))); assertEquals("cast(A imm_serializable)", asString(new Cast<>("A", Cast.Type.IMM_SERIALIZABLE))); assertEquals("cast(A imm_binary)", asString(new Cast<>("A", Cast.Type.IMM_BINARY))); } @Test public void castNested() { assertEquals("cast(lower(A) text)", asString(new Cast<>(new Lower("A"), Cast.Type.TEXT))); } @Test public void extract() { Date date = Date.from(LocalDate.of(2020, 1, 1).atStartOfDay(ZoneOffset.UTC).toInstant()); assertEquals("extract(YEAR from 2020-01-01)", asString(new Extract(date, Extract.Part.YEAR))); assertEquals("extract(MONTH from 2020-01-01)", asString(new Extract(date, Extract.Part.MONTH))); assertEquals("extract(DAY from 2020-01-01)", asString(new Extract(date, Extract.Part.DAY))); assertEquals("extract(HOUR from 2020-01-01)", asString(new Extract(date, Extract.Part.HOUR))); assertEquals("extract(MINUTE from 2020-01-01)", asString(new Extract(date, Extract.Part.MINUTE))); assertEquals("extract(SECOND from 2020-01-01)", asString(new Extract(date, Extract.Part.SECOND))); } @Test public void extractNested() { assertEquals("extract(YEAR from current_date)", asString(new Extract(new CurrentDate(), Extract.Part.YEAR))); } @Test public void regexp() { assertEquals("A regexp B", asString(new RegExp("A", "B"))); } @Test public void regexpNested() { assertEquals("lower(A) regexp B", asString(new RegExp(new Lower("A"), "B"))); } @Test public void index() { Company company = EntityProxyFactory.createProxy(Company.class, null); assertEquals("index(Company)", asString(new Index(company))); } @Test(expected = IllegalArgumentException.class) public void indexNonProxy() { assertEquals("index(Company)", asString(new Index(new Company()))); } @Test(expected = IllegalArgumentException.class) public void indexNonEntity() { TestEntity testEntity = EntityProxyFactory.createProxy(TestEntity.class, null); assertEquals("index(TestEntity)", asString(new Index(testEntity))); } @Test public void key() { assertEquals("key({})", asString(new Key<>(new HashMap<>()))); } @Test public void size() { assertEquals("size([])", asString(new Size(new ArrayList<>()))); } @Test public void type() { Company company = EntityProxyFactory.createProxy(Company.class, null); assertEquals("type(Company)", asString(new Type(company))); } @Test(expected = IllegalArgumentException.class) public void typeNonProxy() { assertEquals("type(Company)", asString(new Type(new Company()))); } @Test(expected = IllegalArgumentException.class) public void typeNonEntity() { TestEntity testEntity = EntityProxyFactory.createProxy(TestEntity.class, null); assertEquals("type(TestEntity)", asString(new Type(testEntity))); } @Test public void function() { List arguments = Arrays.asList("A", "B"); assertEquals("function('dummy', A, B)", asString(new Function<>("dummy", arguments))); } @Test public void functionNested() { List arguments = Arrays.asList(dummy("A"), dummy("B")); assertEquals("function('dummy', dummy(A), dummy(B))", asString(new Function<>("dummy", arguments))); } @Test public void functionNoArgs() { List arguments = Collections.emptyList(); assertEquals("function('dummy')", asString(new Function<>("dummy", arguments))); } @Test(expected = NullPointerException.class) public void functionNullArgs() { new Function<>("dummy", null); } @Test(expected = NullPointerException.class) public void functionNullName() { new Function<>(null, Collections.emptyList()); } @Test(expected = IllegalArgumentException.class) public void functionBadName() { new Function<>("'dummy", Collections.emptyList()); } @Test public void func() { List arguments = Arrays.asList("A", "B"); assertEquals("func('dummy', A, B)", asString(new Func<>("dummy", arguments))); } @Test public void funcNested() { List arguments = Arrays.asList(dummy("A"), dummy("B")); assertEquals("func('dummy', dummy(A), dummy(B))", asString(new Func<>("dummy", arguments))); } @Test public void funcNoArgs() { List arguments = Collections.emptyList(); assertEquals("func('dummy')", asString(new Func<>("dummy", arguments))); } @Test(expected = NullPointerException.class) public void funcNullArgs() { new Func<>("dummy", null); } @Test(expected = NullPointerException.class) public void funcNullName() { new Func<>(null, Collections.emptyList()); } @Test(expected = IllegalArgumentException.class) public void funcBadName() { new Func<>("'dummy", Collections.emptyList()); } @Test public void sql() { List arguments = Arrays.asList("A", "B"); assertEquals("sql('dummy', A, B)", asString(new Sql<>("dummy", arguments))); } @Test public void sqlNested() { List arguments = Arrays.asList(dummy("A"), dummy("B")); assertEquals("sql('dummy', dummy(A), dummy(B))", asString(new Sql<>("dummy", arguments))); } @Test public void sqlNoArgs() { List arguments = Collections.emptyList(); assertEquals("sql('(select sysdate from dual)')", asString(new Sql<>("(select sysdate from dual)", arguments))); } @Test(expected = NullPointerException.class) public void sqlNullArgs() { new Sql<>("dummy", null); } @Test(expected = NullPointerException.class) public void sqlNullName() { new Sql<>(null, Collections.emptyList()); } @Test(expected = IllegalArgumentException.class) public void sqlBadCode() { new Sql<>("'dummy", Collections.emptyList()); } @Test public void column() { Company company = EntityProxyFactory.createProxy(Company.class, null); assertEquals("column('dummy', Company)", asString(new Column<>("dummy", company))); } @Test(expected = NullPointerException.class) public void columnNullName() { new Column<>(null, new Company()); } @Test(expected = NullPointerException.class) public void columnNullEntity() { new Column<>("dummy", null); } @Test(expected = IllegalArgumentException.class) public void columnBadName() { Company company = EntityProxyFactory.createProxy(Company.class, null); assertEquals("column('dummy', Company)", asString(new Column<>("'dummy", company))); } @Test(expected = IllegalArgumentException.class) public void columnNonEntity() { TestEntity testEntity = EntityProxyFactory.createProxy(TestEntity.class, null); assertEquals("column('dummy', Company)", asString(new Column<>("'dummy", testEntity))); } @Test(expected = IllegalArgumentException.class) public void columnNonProxy() { assertEquals("column('dummy', Company)", asString(new Column<>("'dummy", new Company()))); } @Test public void count() { assertEquals("count(A)", asString(new Count<>("A"))); } @Test public void min() { assertEquals("min(A)", asString(new Min<>("A"))); } @Test public void max() { assertEquals("max(A)", asString(new Max<>("A"))); } @Test public void avg() { assertEquals("avg(A)", asString(new Avg<>("A"))); } @Test public void sum() { assertEquals("sum(A)", asString(new Sum<>("A"))); } @Test public void newTest() { assertEquals("new org.thepavel.jpqlbuilder.DummyObject(A, 1)", asString(new New(DummyObject.class, "A", 1))); } @Test(expected = IllegalArgumentException.class) public void newPrimitive() { assertEquals("new int(1)", asString(new New(int.class, 1))); } @Test(expected = IllegalArgumentException.class) public void newArray() { assertEquals("new org.thepavel.jpqlbuilder.DummyObject[1]", asString(new New(DummyObject[].class, 1))); } @Test(expected = IllegalArgumentException.class) public void newEnum() { assertEquals("new org.thepavel.jpqlbuilder.model.Status()", asString(new New(Status.class))); } public static class TestEntity { } } package org.rapidpm.vaadin.helloworld.server; import io.undertow.Undertow; import io.undertow.util.Headers; import java.util.Optional; /** * */ public class HelloWorldMain { private HelloWorldMain() { } public static void start() { main(new String[0]); } public static void shutdown() { undertowOptional.ifPresent(Undertow::stop); } private static Optional undertowOptional; public static void main(String[] args) { Undertow server = Undertow .builder() .addHttpListener(8080, "localhost") .setHandler(exchange -> { exchange.getResponseHeaders() .put(Headers.CONTENT_TYPE, "text/plain"); exchange.getResponseSender() .send("Hello World"); }) .build(); server.start(); undertowOptional = Optional.of(server); server.getListenerInfo().forEach(System.out::println); } } 10-100 package fi.evident.apina.spring.testclasses; @SuppressWarnings({"unused", "CanBeFinal"}) public final class TypeWithOverlappingFieldAndGetter { public String foo; public String getFoo() { return foo; } } package be.rubengerits.buildstatus.presenter; import android.database.Cursor; import android.support.annotation.NonNull; import com.squareup.sqlbrite.SqlBrite; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.inject.Inject; import be.rubengerits.buildstatus.api.global.Repositories; import be.rubengerits.buildstatus.api.global.Repository; import be.rubengerits.buildstatus.model.data.Account; import be.rubengerits.buildstatus.model.database.DataBaseHelper; import be.rubengerits.buildstatus.model.network.BuildStatusService; import be.rubengerits.buildstatus.view.OverviewView; import rx.Observable; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class OverviewPresenterImpl implements OverviewPresenter { @Inject BuildStatusService buildStatusService; @Inject DataBaseHelper dataBaseHelper; private OverviewView view; public OverviewPresenterImpl(OverviewView view) { this.view = view; } public void updateRepositories() { view.startLoading(); final Set repositoryList = new TreeSet<>(); if (dataBaseHelper.hasAccounts()) { dataBaseHelper.getAccounts() .flatMap(this::loadAccounts) .flatMap(buildStatusService::getRepositories) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnCompleted(view::stopLoading) .doOnError(view::showError) .onErrorReturn(e -> new Repositories()) .doOnNext(repositories -> { if (repositories.getRepositories() != null) { repositoryList.addAll(repositories.getRepositories()); } view.showContent(repositoryList); view.stopLoading(); }) .subscribe(); } else { view.showNoAccounts(); } } @NonNull private Observable loadAccounts(SqlBrite.Query query) { List accounts = new ArrayList<>(); if (query != null) { try (Cursor run = query.run()) { if (run.getCount() > 0) { run.moveToFirst(); do { Account account = new Account(); account.setId(run.getInt(run.getColumnIndex("id"))); account.setUsername(run.getString(run.getColumnIndex("username"))); account.setToken(run.getString(run.getColumnIndex("token"))); accounts.add(account); } while (run.moveToNext()); } } } return Observable.from(accounts); } public Observable isAuthenticated() { return Observable.from(new Boolean[]{Boolean.TRUE}); } } package fusion.comerger.algorithm.partitioner.hierClust; /* * Please refer to https://github.com/fusion-jena/OAPT * Algergawy, Alsayed, , , and . "SeeCOnt: A new seeding-based clustering approach for ontology matching." In East European Conference on Advances in Databases and Information Systems, pp. 245-258. Springer, Cham, 2015. * 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 java.util.*; import org.semanticweb.owlapi.model.OWLClass; //import opt.general.model.impl.NodeImpl; public class Cluster { private int cid; private ArrayList elements; private double intraSim; private HashMap interSim; // Empty cluster with no elements. public Cluster() { init(-1); } public Cluster(int id) { init(id); } public Cluster(int id, OWLClass e) { init(id); add(e); } public Cluster(int id, Collection elements) { init(id); for(OWLClass e : elements) { add(e); } } // New cluster that contains all elements from provided clusters. public Cluster( Cluster c1, Cluster c2) { init(-1); add(c1); add(c2); } public Cluster(Collection elements) { init(-1); for(OWLClass e : elements) { add(e); } } public Cluster(OWLClass element) { init(-1); add(element); } private void init(int label) { this.cid = label; elements = new ArrayList(); intraSim=0; interSim=new HashMap(); } public int getLabel() { return cid; } public int size() { return elements.size(); } public Cluster copy() { Cluster copy = new Cluster(); for(OWLClass e : this.getElements()) { // DataPoint is immutable. No need to create a copy. copy.add(e); } return copy; } /** * Modifies existing cluster by adding all elements from provided cluster. * * @param c */ public void add(Cluster c) { for(OWLClass e : c.getElements() ) { elements.add(e); } } /** * Modifies existing cluster by adding a new element. * * @param e */ public void add(OWLClass e) { elements.add(e); } public boolean contains(Cluster c) { boolean result = true; for(OWLClass e : c.getElements()) { if( !contains(e) ) { result = false; break; } } return result; } public boolean contains(OWLClass e) { return elements.contains(e); } public ArrayList getElements() { return new ArrayList(elements); } public String getElementsAsString() { StringBuffer buf = new StringBuffer(); for(OWLClass e : elements) { if( buf.length() > 0 ) { buf.append(",\n"); } buf.append(e.toString().substring(e.toString().lastIndexOf("#")+1)); } // buf.append(":"+intraSim); return "{" + buf.toString() + "}"; } // this method used through similar cluster finding public String getElementsAsStringSim() { StringBuffer buf = new StringBuffer(); for(OWLClass e : elements) { if( buf.length() > 0 ) { buf.append(" "); } buf.append(e.toString().substring(e.toString().lastIndexOf("#")+1)); } return "{" + buf.toString() + "}"; } @Override public String toString() { return getElementsAsString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((elements == null) ? 0 : elements.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Cluster other = (Cluster) obj; if (elements == null) { if (other.elements != null) return false; } else if (!elements.equals(other.elements)) return false; return true; } // methods to adapt the intrasimilarity feature public void setIntraSim(double sim) { this.intraSim=sim; } public double getIntraSim() { return intraSim; } public double getInterSim(int id) { return (Double)interSim.get(id); } public HashMap getInterSim() { return interSim; } public void setInterSim(int id, double sim) { this.interSim.put(id,sim); } } lucida/questionanswering/OpenEphyra/src/info/ephyra/answerselection/filters/AnswerPatternFilter.java1000+ package info.ephyra.answerselection.filters; import info.ephyra.answerselection.AnswerPattern; import info.ephyra.io.MsgPrinter; import info.ephyra.nlp.NETagger; import info.ephyra.nlp.OpenNLP; import info.ephyra.querygeneration.Query; import info.ephyra.questionanalysis.QuestionInterpretation; import info.ephyra.search.Result; import info.ephyra.util.FileUtils; import info.ephyra.util.RegexConverter; import info.ephyra.util.StringUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Hashtable; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** *

The AnswerPatternFilter uses answer patterns to extract * factoid answers from text passages and to rank them. It is only applied if * the question could be interpreted, i.e. a QuestionInterpretation * is available.

* *

In addition, this Filter provides methods to add, load, save * and assess the answer patterns.

* *

This class extends the class Filter.

* * @author * @version 2007-04-18 */ public class AnswerPatternFilter extends Filter { /** Identifier for the pattern learning and matching approach. */ public static final String ID = "Pattern learning and matching"; /** For each PROPERTY the answer patterns that are used to extract it. */ private static Hashtable> props = new Hashtable>(); /** * For each PROPERTY the number of text passages used to assess the answer * patterns. */ private static Hashtable nOfPassages = new Hashtable(); /** Maps tags in PROPERTY objects back to the original strings. */ private static Hashtable reverseMap = new Hashtable(); /** PROPERTY objects extracted from a Result. */ private static ArrayList extr; /** For each PROPERTY object the NE types. */ private static ArrayList types; /** For each PROPERTY object the sentence it was extracted from. */ private static ArrayList sents; /** For each PROPERTY object the answer pattern used to extract it. */ private static ArrayList aps; /** * Replaces all TARGET objects in the sentence. The reverse mappings are * stored in reverseMap. * * @param sentence input sentence * @param to the TARGET object of the question * @param nes the NEs in the sentence * @return sentence with TARGET tags or null, if the sentence * does not contain the TARGET */ private static String replaceTarget(String sentence, String to, String[][] nes) { HashSet reps = new HashSet(); String tag, result = sentence; int id = 1; for (String[] neType : nes) for (String ne : neType) if (StringUtils.equalsCommonNorm(ne, to)) reps.add(ne); to = "(?i)" + RegexConverter.strToRegexWithBounds(to); Matcher m = Pattern.compile(to).matcher(result); while (m.find()) reps.add(m.group(0)); // get proper case // sort expressions by length String[] sorted = reps.toArray(new String[reps.size()]); StringUtils.sortByLengthDesc(sorted); for (String rep : sorted) { tag = ""; // add unique tag ID reverseMap.put(tag, rep); // remember reverse mapping rep = RegexConverter.strToRegexWithBounds(rep); result = result.replaceAll(rep, tag); } return (result.equals(sentence)) ? null : result; } /** * Replaces all CONTEXT objects in the sentence. The reverse mappings are * stored in reverseMap. * * @param sentence input sentence * @param cos the CONTEXT objects of the question * @param nes the NEs in the sentence * @return sentence with CONTEXT tags */ private static String replaceContext(String sentence, String[] cos, String[][] nes) { HashSet reps = new HashSet(); String tag; int id = 1; for (String[] neType : nes) for (String ne : neType) for (String co : cos) if (StringUtils.equalsCommonNorm(ne, co)) reps.add(ne); for (String co : cos) { co = "(?i)" + RegexConverter.strToRegexWithBounds(co); Matcher m = Pattern.compile(co).matcher(sentence); while (m.find()) reps.add(m.group(0)); // get proper case } // sort expressions by length String[] sorted = reps.toArray(new String[reps.size()]); StringUtils.sortByLengthDesc(sorted); for (String rep : sorted) { tag = ""; // add unique tag ID reverseMap.put(tag, rep); // remember reverse mapping rep = RegexConverter.strToRegexWithBounds(rep); sentence = sentence.replaceAll(rep, tag); } return sentence; } /** * Replaces all NEs in the sentence. The reverse mappings are stored in * reverseMap. * * @param sentence input sentence * @param nes the NEs in the sentence * @return sentence with NE tags */ private static String replaceNes(String sentence, String[][] nes) { Hashtable reps = new Hashtable(); String neType, tag; int id = 1; for (int i = 0; i < nes.length; i++) { neType = NETagger.getNeType(i); for (String ne : nes[i]) { tag = reps.get(ne); if (tag == null) tag = "<" + neType; else if (!tag.contains(neType)) tag += "_" + neType; reps.put(ne, tag); } } // sort expressions by length String[] sorted = reps.keySet().toArray(new String[reps.size()]); StringUtils.sortByLengthDesc(sorted); for (String rep : sorted) { tag = reps.get(rep) + "_" + id++ + ">"; // add unique tag ID reverseMap.put(tag, rep); // remember reverse mapping rep = RegexConverter.strToRegexWithBounds(rep); sentence = sentence.replaceAll(rep, tag); } return sentence; } /** * Prepares a sentence for answer extraction. * * @param sentence input sentence * @param to the TARGET object of the question * @param cos the CONTEXT objects of the question * @param nes the NEs in the sentence * @return sentence ready for answer extraction or null, if * there is no TARGET object in the input sentence */ private static String prepSentence(String sentence, String to, String[] cos, String[][] nes) { // initialize reverse map reverseMap = new Hashtable(); // replace TARGET and CONTEXT objects and NEs sentence = replaceTarget(sentence, to, nes); if (sentence == null) return null; sentence = replaceContext(sentence, cos, nes); sentence = replaceNes(sentence, nes); // add '#' at beginning and end of sentence sentence = "# " + sentence + " #"; return sentence; } /** * Gets the NE types that a PROPERTY object has in common with the answer * pattern used to extract it. * * @param pos PROPERTY object * @param pattern answer pattern used to extract it * @return NE types or null if the answer pattern does not * expect specific types */ private static String[] getNeTypes(String pos, AnswerPattern pattern) { ArrayList neTypes = new ArrayList(); String[] propertyTypes = pattern.getPropertyTypes(); if (propertyTypes == null) return null; for (String propertyType : propertyTypes) if (pos.contains(propertyType)) neTypes.add(propertyType); return neTypes.toArray(new String[neTypes.size()]); } /** * Replaces tags in an extracted PROPERTY object with the original strings * stored in reverseMap. * * @param po PROPERTY object * @return PROPERTY object without tags */ private static String replaceTags(String po) { Pattern p = Pattern.compile("<(TO|CO|NE).*?>"); Matcher m = p.matcher(po); while (m.find()) { String tag = m.group(0); String rep = reverseMap.get(tag); // look up replacement if (rep != null) po = po.replace(tag, rep); } return po; } /** * Applies the answer patterns to the answer string of the * Result object to extract PROPERTY objects. * * @param result a Result object */ private static void extractPos(Result result) { extr = new ArrayList(); types = new ArrayList(); sents = new ArrayList(); aps = new ArrayList(); // get interpretation and answer string QuestionInterpretation qi = result.getQuery().getInterpretation(); String to = qi.getTarget(); // String[] cos = qi.getContext(); String[] cos = new String[0]; // CONTEXT objects are ignored String prop = qi.getProperty(); String answer = result.getAnswer(); // get answer patterns HashSet patterns = props.get(prop); if (patterns == null) return; // tokenize interpretation to = NETagger.tokenizeWithSpaces(to); for (int i = 0; i < cos.length; i++) cos[i] = NETagger.tokenizeWithSpaces(cos[i]); // split answer string into sentences and tokenize sentences String[] originalSentences = OpenNLP.sentDetect(answer); String[][] tokens = new String[originalSentences.length][]; String[] sentences = new String[originalSentences.length]; for (int i = 0; i < originalSentences.length; i++) { tokens[i] = NETagger.tokenize(originalSentences[i]); sentences[i] = StringUtils.concatWithSpaces(tokens[i]); } /* PrintWriter pw = null; try { pw = new PrintWriter(new FileOutputStream(new File("netagger_data.txt"),true)); } catch (FileNotFoundException ex) { System.out.println("File not found exception!!"); }*/ // extract named entities String[][][] nes = NETagger.extractNes(tokens); // pw.printf("%s ----- %s\n", tokens.toString(), nes.toString()); /*PrintWriter pw2 = null; try { pw2 = new PrintWriter(new FileOutputStream(new File("regex_data.txt"),true)); } catch (FileNotFoundException ex) { System.out.println("File not found exception!!"); }*/ for (int i = 0; i < sentences.length; i++) { // prepare sentence for answer extraction sentences[i] = prepSentence(sentences[i], to, cos, nes[i]); if (sentences[i] == null) continue; for (AnswerPattern pattern : patterns) { // apply answer pattern String[] pos = pattern.apply(sentences[i]); // pw2.printf("%s ----- %s ----- %s\n", pattern.getDesc(), sentences[i], pos); // get NE types of PROPERTY objects String[][] neTypes = new String[pos.length][]; for (int j = 0; j < pos.length; j++) neTypes[j] = getNeTypes(pos[j], pattern); // replace tags and untokenize PROPERTY objects for (int j = 0; j < pos.length; j++) { pos[j] = replaceTags(pos[j]); pos[j] = OpenNLP.untokenize(pos[j], originalSentences[i]); } // store the PROPERTY objects, the sentences they were extracted // from, the patterns used to extract them and the NE types for (int j = 0; j < pos.length; j++) { extr.add(pos[j]); types.add(neTypes[j]); sents.add(originalSentences[i]); aps.add(pattern); } } } // pw.close(); // pw2.close(); } /** * Adds an answer pattern for a specific PROPERTY. * * @param expr pattern descriptor * @param prop PROPERTY that the pattern extracts * @return true, iff a new pattern was added */ public static boolean addPattern(String expr, String prop) { // get the answer patterns for the specified PROPERTY HashSet patterns = props.get(prop); if (patterns == null) { // new PROPERTY patterns = new HashSet(); props.put(prop, patterns); nOfPassages.put(prop, 0); } // if the pattern is not in the set, add it boolean added = patterns.add(new AnswerPattern(expr, prop)); // print out new patterns if (added) MsgPrinter.printStatusMsg(prop + ": " + expr); return added; } /** * Loads the answer patterns from a directory of PROPERTY files. The first * line of each file is the total number of passages used to assess the * patterns. It is followed by a list of pattern descriptors, along with * their number of correct and wrong applications. The format of the * descriptors is described in the documentation of the class * AnswerPattern. * * @param dir directory of the answer patterns * @return true, iff the answer patterns were loaded successfully */ public static boolean loadPatterns(String dir) { File[] files = FileUtils.getFiles(dir); try { BufferedReader in; String prop, expr; int passages, correct, wrong; HashSet patterns; for (File file : files) { MsgPrinter.printStatusMsg(" ...for " + file.getName()); prop = file.getName(); in = new BufferedReader(new FileReader(file)); // total number of passages used to assess the patterns passages = Integer.parseInt(in.readLine().split(" ")[1]); nOfPassages.put(prop, passages); patterns = new HashSet(); while (in.ready()) { in.readLine(); // pattern descriptor expr = in.readLine(); // number of correct applications correct = Integer.parseInt(in.readLine().split(" ")[1]); // number of wrong applications wrong = Integer.parseInt(in.readLine().split(" ")[1]); try { patterns.add(new AnswerPattern(expr, prop, correct, wrong)); } catch (PatternSyntaxException pse) { MsgPrinter.printErrorMsg("Problem loading pattern:\n" + prop + " " + expr); MsgPrinter.printErrorMsg(pse.getMessage()); } } props.put(prop, patterns); in.close(); } MsgPrinter.printStatusMsg(" ...done"); } catch (IOException e) { return false; } return true; } /** * Saves the answer patterns to resource files. A separate file is created * for each PROPERTY. The first line is the total number of passages used to * assess the answer patterns. It is followed by a list of pattern * descriptors along with their number of correct and wrong applications. * * @param dir directory of the answer patterns * @return true, iff the answer patterns were saved successfully */ public static boolean savePatterns(String dir) { File file; PrintWriter out; try { for (String prop : props.keySet()) { // sort answer patterns HashSet ps = props.get(prop); AnswerPattern[] patterns = ps.toArray(new AnswerPattern[ps.size()]); Arrays.sort(patterns); file = new File(dir + "/" + prop); out = new PrintWriter(file, "UTF-8"); // total number of passages used to assess the patterns out.println("#passages: " + nOfPassages.get(prop)); for (int i = patterns.length - 1; i >= 0; i--) { out.println(); // pattern descriptor out.println(patterns[i].getDesc()); // number of correct applications out.println("#correct: " + patterns[i].getCorrect()); // number of wrong applications out.println("#incorrect: " + patterns[i].getWrong()); } out.close(); } } catch (IOException e) { return false; } return true; } /** * Assesses the answer patterns by applying them to the answer string of the * Result object and comparing the extracted answers to the * regular expression regex. * * @param result Result object * @param regex regular expression that describes a correct answer */ public static void assessPatterns(Result result, String regex) { // increment the number of passages used to assess the patterns String prop = result.getQuery().getInterpretation().getProperty(); int n = (nOfPassages.get(prop) == null) ? 1 : nOfPassages.get(prop) + 1; nOfPassages.put(prop, n); // extract PROPERTY objects extractPos(result); // use the regular expression regex to assess the PROPERTY objects for (int i = 0; i < extr.size(); i++) { String po = extr.get(i); AnswerPattern ap = aps.get(i); if (po.matches("(?i)" + regex)) ap.incCorrect(); else ap.incWrong(); } } /** * Drops answer patterns that have a support of supportThresh * or less. * * @param supportThresh the support threshold */ public static void dropLowSupport(float supportThresh) { // for each PROPERTY for (String prop : props.keySet()) { HashSet patterns = props.get(prop); int n = nOfPassages.get(prop); HashSet remaining = new HashSet(); // check the threshold for each answer pattern for (AnswerPattern pattern : patterns) if ((pattern.getCorrect() / (float) n) >= supportThresh) remaining.add(pattern); props.put(prop, remaining); } } /** * Drops answer patterns that have a confidence of * confidenceThresh or less. * * @param confidenceThresh the confidence threshold */ public static void dropLowConfidence(float confidenceThresh) { // for each PROPERTY for (String prop : props.keySet()) { HashSet patterns = props.get(prop); HashSet remaining = new HashSet(); // check the threshold for each answer pattern for (AnswerPattern pattern : patterns) if (pattern.getConfidence() >= confidenceThresh) remaining.add(pattern); props.put(prop, remaining); } } /** * Applies the answer patterns to the answer strings of the * Result objects and creates a new Result for * each extracted unique answer. * * @param results array of Result objects * @return extended array of Result objects */ public Result[] apply(Result[] results) { // extracted factoid answers and corresponding results Hashtable factoids = new Hashtable(); for (Result result : results) { // only apply this filter to results for the pattern matching // approach Query query = result.getQuery(); QuestionInterpretation qi = query.getInterpretation(); if (!query.extractWith(ID) || qi == null || result.getScore() > Float.NEGATIVE_INFINITY) continue; // extract PROPERTY objects extractPos(result); // create new result for each unique normalized PROPERTY object for (int i = 0; i < extr.size(); i++) { String po = extr.get(i); String[] neTypes = types.get(i); String norm = StringUtils.normalize(po); String sentence = sents.get(i); float conf = aps.get(i).getConfidence(); Result factoid = factoids.get(norm); if (factoid == null) { // new answer // query, doc ID and sentence can be ambiguous factoid = new Result(po, result.getQuery(), result.getDocID()); factoid.setSentence(sentence); factoid.addExtractionTechnique(ID); factoids.put(norm, factoid); } if (neTypes != null) for (String neType : neTypes) factoid.addNeType(neType); factoid.incScore(conf); } } // keep old results Result[] newResults = factoids.values().toArray(new Result[factoids.size()]); Result[] allResults = new Result[results.length + newResults.length]; for (int i = 0; i < results.length; i++) allResults[i] = results[i]; for (int i = 0; i < newResults.length; i++) allResults[results.length + i] = newResults[i]; return allResults; } } /* Copyright 2009 - 2010 The Stajistics 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 org.stajistics.configuration.xml.binding; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.stajistics.AbstractStajisticsTestCase; /** * @author The Stajistics Project */ public class XMLConfigBindingManagerTest extends AbstractStajisticsTestCase { private static final String TEST_CONFIG_XML_FILE = "/org/stajistics/configuration/xml/testConfig.xml"; private XMLConfigBindingManager manager; @Before public void setUp() { manager = new XMLConfigBindingManager(); } protected InputStream getTestConfigFile() { InputStream in = getClass().getResourceAsStream(TEST_CONFIG_XML_FILE); if (in == null) { throw new RuntimeException("Resource not found: " + TEST_CONFIG_XML_FILE); } return in; } @Test public void testUnmarshalGetProperties() { // Disabled for now as XML configuration is not yet a fully fleshed out feature /*InputStream in = getTestConfigFile(); XMLConfigDocument doc = manager.unmarshal(in); Map props = doc.getProperties(); assertTrue(props.containsKey("name1")); assertEquals("value1", props.get("name1")); assertTrue(props.containsKey("name2")); assertEquals("value2", props.get("name2"));*/ } } package mage.cards.h; import java.util.UUID; import mage.MageInt; import mage.abilities.Ability; import mage.abilities.common.BeginningOfUpkeepTriggeredAbility; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.effects.Effect; import mage.abilities.effects.common.LoseLifeSourceControllerEffect; import mage.abilities.effects.common.continuous.BoostEnchantedEffect; import mage.abilities.effects.common.continuous.GainAbilityAttachedEffect; import mage.abilities.keyword.BestowAbility; import mage.abilities.keyword.FlyingAbility; import mage.cards.CardImpl; import mage.cards.CardSetInfo; import mage.constants.AttachmentType; import mage.constants.CardType; import mage.constants.SubType; import mage.constants.TargetController; import mage.constants.Zone; /** * * @author Quercitron */ public final class HeraldOfTorment extends CardImpl { public HeraldOfTorment(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.ENCHANTMENT,CardType.CREATURE},"{1}{B}{B}"); this.subtype.add(SubType.DEMON); this.power = new MageInt(3); this.toughness = new MageInt(3); // Bestow {3}{B}{B} this.addAbility(new BestowAbility(this, "{3}{B}{B}")); // Flying this.addAbility(FlyingAbility.getInstance()); // At the beginning of your upkeep, you lose 1 life. this.addAbility(new BeginningOfUpkeepTriggeredAbility(new LoseLifeSourceControllerEffect(1), TargetController.YOU, false)); // Enchanted creature gets +3/+3 and has flying. Ability ability = new SimpleStaticAbility(Zone.BATTLEFIELD, new BoostEnchantedEffect(3, 3)); Effect effect = new GainAbilityAttachedEffect(FlyingAbility.getInstance(), AttachmentType.AURA); effect.setText("and has flying"); ability.addEffect(effect); this.addAbility(ability); } public HeraldOfTorment(final HeraldOfTorment card) { super(card); } @Override public HeraldOfTorment copy() { return new HeraldOfTorment(this); } } /** * Copyright © 2012-2014 JeeSite All rights reserved. */ package com.thinkgem.jeesite.modules.wx.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.thinkgem.jeesite.common.config.Global; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.web.BaseController; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.modules.sys.entity.User; import com.thinkgem.jeesite.modules.sys.utils.UserUtils; import com.thinkgem.jeesite.modules.wx.entity.WxInterfaceInfo; import com.thinkgem.jeesite.modules.wx.service.WxInterfaceInfoService; /** * 接口验证信息Controller * @author shenzb.fnst * @version 2015-07-27 */ @Controller @RequestMapping(value = "${adminPath}/wx/wxInterfaceInfo") public class WxInterfaceInfoController extends BaseController { @Autowired private WxInterfaceInfoService wxInterfaceInfoService; @ModelAttribute public WxInterfaceInfo get(@RequestParam(required=false) String id) { WxInterfaceInfo entity = null; if (StringUtils.isNotBlank(id)){ entity = wxInterfaceInfoService.get(id); } if (entity == null){ entity = new WxInterfaceInfo(); } return entity; } @RequiresPermissions("wx:wxInterfaceInfo:view") @RequestMapping(value = {"list", ""}) public String list(WxInterfaceInfo wxInterfaceInfo, HttpServletRequest request, HttpServletResponse response, Model model) { Page page = wxInterfaceInfoService.findPage(new Page(request, response), wxInterfaceInfo); model.addAttribute("page", page); return "modules/wx/wxInterfaceInfoList"; } @RequiresPermissions("wx:wxInterfaceInfo:view") @RequestMapping(value = "form") public String form(WxInterfaceInfo wxInterfaceInfo, Model model) { wxInterfaceInfo.setOffice(UserUtils.getUser().getCompany()); model.addAttribute("wxInterfaceInfo", wxInterfaceInfo); return "modules/wx/wxInterfaceInfoForm"; } @RequiresPermissions("wx:wxInterfaceInfo:edit") @RequestMapping(value = "save") public String save(WxInterfaceInfo wxInterfaceInfo, Model model, RedirectAttributes redirectAttributes) { wxInterfaceInfo.setOffice(UserUtils.getUser().getCompany()); if (!beanValidator(model, wxInterfaceInfo)){ return form(wxInterfaceInfo, model); } wxInterfaceInfoService.save(wxInterfaceInfo); addMessage(redirectAttributes, "保存接口验证信息成功"); return "redirect:"+Global.getAdminPath()+"/wx/wxInterfaceInfo/?repage"; } @RequiresPermissions("wx:wxInterfaceInfo:edit") @RequestMapping(value = "delete") public String delete(WxInterfaceInfo wxInterfaceInfo, RedirectAttributes redirectAttributes) { wxInterfaceInfoService.delete(wxInterfaceInfo); addMessage(redirectAttributes, "删除接口验证信息成功"); return "redirect:"+Global.getAdminPath()+"/wx/wxInterfaceInfo/?repage"; } /** * 接口信息显示 * @param user * @param model * @return */ @RequiresPermissions("wx:wxInterfaceInfo:view") @RequestMapping(value = "info") public String info(WxInterfaceInfo wxInterfaceInfo, HttpServletResponse response, Model model) { User currentUser = UserUtils.getUser(); WxInterfaceInfo currentWxInterfaceInfo = wxInterfaceInfoService.getWxInterfaceInfoByCompanyId(currentUser.getCompany().getId()); // if (StringUtils.isNotBlank(wxInterfaceInfo.getCorpid())){ // if(Global.isDemoMode()){ // model.addAttribute("message", "演示模式,不允许操作!"); // return "modules/sys/userInfo"; // } // if (currentWxInterfaceInfo == null) { // currentWxInterfaceInfo = new WxInterfaceInfo(); // } // currentWxInterfaceInfo.setOffice(wxInterfaceInfo.getOffice()); // currentWxInterfaceInfo.setCorpid(wxInterfaceInfo.getCorpid()); // currentWxInterfaceInfo.setProviderSecret(wxInterfaceInfo.getProviderSecret()); // wxInterfaceInfoService.save(currentWxInterfaceInfo); // model.addAttribute("message", "保存信息成功"); // model.addAttribute("wxInterfaceInfo", currentWxInterfaceInfo); // } else { // model.addAttribute("wxInterfaceInfo", new WxInterfaceInfo()); // } model.addAttribute("wxInterfaceInfo", currentWxInterfaceInfo == null ? new WxInterfaceInfo() : currentWxInterfaceInfo); //model.addAttribute("user", currentUser); model.addAttribute("Global", new Global()); return "modules/wx/wxInterfaceInfo"; } }package college.com.collegenetwork.models; /** * Created by Krypto on 28-08-2017. */ public class ApprovalVO { String studentName; String timing; String subject; String stream; public ApprovalVO(String studentName, String timing,String subject,String stream) { this.studentName = studentName; this.timing = timing; this.subject = subject; this.stream = stream; } public String getStudentName() { return studentName; } public String getTiming() { return timing; } public String getSubject() { return subject; } public String getStream() { return stream; } } dependencymanager/org.apache.felix.dependencymanager.lambda/src/org/apache/felix/dm/lambda/callbacks/InstanceCbRefServiceRefServiceComponent.java /* * 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.felix.dm.lambda.callbacks; import java.util.Objects; import org.apache.felix.dm.Component; import org.osgi.framework.ServiceReference; /** * Represents a swap callback(ServiceReference, Service, ServiceReference, Service, Component) on an Object instance. * * @author Felix Project Team */ @FunctionalInterface public interface InstanceCbRefServiceRefServiceComponent { /** * Handles the given arguments * @param oldRef an old swapped service reference * @param old an old swapped service * @param replaceRef the new service reference * @param replace the new service * @param c a Component */ void accept(ServiceReference oldRef, S old, ServiceReference replaceRef, S replace, Component c); default InstanceCbRefServiceRefServiceComponent andThen(InstanceCbRefServiceRefServiceComponent after) { Objects.requireNonNull(after); return (ServiceReference oldRef, S old, ServiceReference replaceRef, S replace, Component c) -> { accept(oldRef, old, replaceRef, replace, c); after.accept(oldRef, old, replaceRef, replace, c); }; } } package org.sagebionetworks.web.unitclient.widget.table.v2.schema; import org.sagebionetworks.web.client.widget.table.v2.schema.ColumnModelTableRowViewer; /** * Stub for ColumnModelTableRowViewer * * @author jmhill * */ public class ColumnModelTableRowViewerStub extends ColumnModelTableRowStub implements ColumnModelTableRowViewer { boolean isSelectable; @Override public void setSelectable(boolean isSelectable) { this.isSelectable = isSelectable; } } package yichen.extraalchemy.recipes; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import yichen.extraalchemy.api.ExtraAlchemyAPI; import yichen.extraalchemy.api.RecipeTransmute; public class ModTransmuteRecipes { public static RecipeTransmute ironIngotRecipe; public static RecipeTransmute clayball; public static RecipeTransmute coal; public static RecipeTransmute ingotAlubrass; public static void init() { //输出-输入-时间(tick) ironIngotRecipe = ExtraAlchemyAPI.registerTransmuteRecipe(new ItemStack(Items.IRON_INGOT), new ItemStack(Items.GOLD_INGOT), 100); clayball = ExtraAlchemyAPI.registerTransmuteRecipe(new ItemStack(Items.CLAY_BALL), new ItemStack(Blocks.DIRT), 100); coal = ExtraAlchemyAPI.registerTransmuteRecipe(new ItemStack(Items.COAL, 1, 1), "logWood", 800); ingotAlubrass = ExtraAlchemyAPI.registerTransmuteRecipe("ingotCopper", "ingotAlubrass", 100); } } /** * 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 io.streamnative.pulsar.handlers.kop; import java.util.function.Predicate; import org.apache.pulsar.common.naming.NamespaceName; import org.apache.pulsar.common.naming.TopicName; /** * Listener that is triggered when a topic's ownership changed via load or unload. */ public interface TopicOwnershipListener extends Predicate { /** * It's triggered when the topic is loaded by a broker. * * @param topicName */ void whenLoad(TopicName topicName); /** * It's triggered when the topic is unloaded by a broker. * * @param topicName */ void whenUnload(TopicName topicName); /** Returns the name of the listener. */ String name(); default boolean test(NamespaceName namespaceName) { return true; } } romaj4/job4jchapter_008/src/main/java/ru/job4j/tdd/SimpleGenerate.java package ru.job4j.tdd; import java.util.Map; import java.util.NoSuchElementException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author () * @version $Id$ * @since 0.1 */ public class SimpleGenerate implements Template { private static final Pattern KEYS = Pattern.compile("\\$\\{\\w*}"); /** * Parses the string by pattern and returns the modified string. * * @param template template. * @param keysMap map of keys - value. * @return modified string. */ @Override public String generate(String template, Map keysMap) { Matcher matcher = this.KEYS.matcher(template); while (matcher.find()) { String expression = matcher.group(); String key = expression.substring(2, expression.length() - 1); if (!keysMap.containsKey(key)) { throw new NoSuchElementException("No such key"); } template = template.replace(expression, keysMap.get(key)); keysMap.remove(key); matcher = this.KEYS.matcher(template); } if (keysMap.size() > 0) { throw new IllegalStateException("There are extra keys in map"); } return template; } } server/src/main/java/com/google/floody/controller/CronTasksController.java /* * Copyright 2021 Google LLC * * 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 * * https://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.floody.controller; import com.google.common.flogger.GoogleLogger; import com.google.floody.exceptions.UnauthorizedUserException; import com.google.floody.model.FloodyProperties; import com.google.floody.protobuf.FileOperations.FileOperationResultList; import java.io.IOException; import java.time.ZoneOffset; import java.time.ZonedDateTime; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** Provides end-points for all cron tasks. */ @RestController @RequestMapping("/crontasks") public final class CronTasksController extends FloodyBaseController { private static GoogleLogger logger = GoogleLogger.forEnclosingClass(); @Autowired private FloodyProperties floodyProperties; @GetMapping(value = "/removeOldFiles") public FileOperationResultList deleteOlderFiles( @RequestParam(required = false, defaultValue = "false") boolean dryRun, HttpServletRequest request) throws IOException, InterruptedException { verifyCaller(request); var cutOffDate = ZonedDateTime.now(ZoneOffset.UTC).minusDays(floodyProperties.getGeneratedFileTtlDays()); return robotServicesFactory().buildFileDeletor(dryRun).deleteFilesLastAccessed(cutOffDate); } private void verifyCaller(HttpServletRequest request) { if (!"true".equals(request.getHeader("X-Appengine-Cron"))) { throw new UnauthorizedUserException("Unknown caller for secured endpoint"); } } } /* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by and Contributors. * * This program and the accompanying materials are dual-licensed under * either * * (a) the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation, or (at your option) any * later version. * * or (per the licensee's choosing) * * (b) the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation. */ /* ----------------- * PushRelabelMaximumFlow.java * ----------------- * (C) Copyright 2015-2015, by and Contributors. * * Original Author: * Contributor(s): * * $Id$ * * Changes * ------- */ package org.jgrapht.alg.flow; import java.util.*; import org.jgrapht.*; import org.jgrapht.alg.util.*; import org.jgrapht.alg.util.Extension.*; /** *

* Push-relabel maximum flow algorithm designed by and * . Current implementation complexity upper-bound is O(V^3). For * more details see: "A new approach to the maximum flow problem" by * and STOC '86: Proceedings of the * eighteenth annual ACM symposium on Theory of computing

* * @author */ public class PushRelabelMaximumFlow extends MaximumFlowAlgorithmBase { // Diagnostic private static final boolean DIAGNOSTIC_ENABLED = false; private DirectedGraph network; private final ExtensionFactory vertexExtensionsFactory; private final ExtensionFactory edgeExtensionsFactory; // Label pruning helpers private Map labeling; boolean flowBack; private PushRelabelDiagnostic diagnostic; public PushRelabelMaximumFlow(DirectedGraph network) { this.network = network; this.vertexExtensionsFactory = new ExtensionFactory() { @Override public VertexExtension create() { return PushRelabelMaximumFlow.this.new VertexExtension(); } }; this.edgeExtensionsFactory = new ExtensionFactory() { @Override public EdgeExtension create() { return PushRelabelMaximumFlow.this.new EdgeExtension(); } }; if (DIAGNOSTIC_ENABLED) { this.diagnostic = new PushRelabelDiagnostic(); } } void init() { super.init(vertexExtensionsFactory, edgeExtensionsFactory); this.labeling = new HashMap(); this.flowBack = false; } @Override DirectedGraph getNetwork() { return network; } public void initialize( VertexExtension source, VertexExtension sink, Queue active) { source.label = network.vertexSet().size(); source.excess = Double.POSITIVE_INFINITY; label(source, sink); for (EdgeExtension ex : source.getOutgoing()) { pushFlowThrough(ex, ex.capacity); if (ex.getTarget().prototype != sink.prototype) { active.offer(ex.getTarget()); } } } private void label(VertexExtension source, VertexExtension sink) { Set seen = new HashSet(); Queue q = new ArrayDeque(); q.offer(sink); sink.label = 0; seen.add(sink); seen.add(source); while (!q.isEmpty()) { VertexExtension ux = q.poll(); for (EdgeExtension ex : ux.getOutgoing()) { VertexExtension vx = ex.getTarget(); if (!seen.contains(vx)) { seen.add(vx); vx.label = ux.label + 1; q.add(vx); // NOTA BENE: // This is part of label-pruning mechanic which // targets to diminish all 'useless' relabels during // "flow-back" phase of the algorithm pushing excess // flow back to the source if (!labeling.containsKey(vx.label)) { labeling.put(vx.label, 1); } else { labeling.put(vx.label, labeling.get(vx.label) + 1); } } } } if (DIAGNOSTIC_ENABLED) { System.out.println("INIT LABELING " + labeling); } } @Override public MaximumFlow buildMaximumFlow(V source, V sink) { init(); Queue active = new ArrayDeque(); initialize(extendedVertex(source), extendedVertex(sink), active); while (!active.isEmpty()) { VertexExtension ux = active.poll(); for (;;) { for (EdgeExtension ex : ux.getOutgoing()) { if (isAdmissible(ex)) { if ((ex.getTarget().prototype != sink) && (ex.getTarget().prototype != source)) { active.offer(ex.getTarget()); } // Check whether we're rip off the excess if (discharge(ex)) { break; } } } if (ux.hasExcess()) { relabel(ux); } else { break; } // Check whether we still have any vertices with the label '1' if (!flowBack && !labeling.containsKey(0) && !labeling.containsKey(1)) { // This supposed to drastically improve performance cutting // off the necessity to drive labels of all vertices up to // value 'N' one-by-one not entailing eny effective // discharge -- at this point there is no vertex with the // label <= 1 in the network & therefore no // 'discharging-path' to the _sink_ also signalling that // we're in the flow-back stage of the algorithm extendedVertex(source).label = Collections.max(labeling.keySet()) + 1; flowBack = true; } } } Map maxFlow = composeFlow(); double maxFlowValue = 0.0; for (E e : network.incomingEdgesOf(sink)) { maxFlowValue += maxFlow.get(e); } if (DIAGNOSTIC_ENABLED) { diagnostic.dump(); } return new MaximumFlowImpl(maxFlowValue, maxFlow); } private void relabel(VertexExtension vx) { assert (vx.hasExcess()); int min = Integer.MAX_VALUE; for (EdgeExtension ex : vx.getOutgoing()) { if (ex.hasCapacity()) { VertexExtension ux = ex.getTarget(); if (min > ux.label) { min = ux.label; } } } if (DIAGNOSTIC_ENABLED) { diagnostic.incrementRelabels(vx.label, min + 1); } assert (labeling.get(vx.label) > 0); updateLabeling(vx, min + 1); // Sanity if (min != Integer.MAX_VALUE) { vx.label = min + 1; } } private void updateLabeling(VertexExtension vx, int l) { if (labeling.get(vx.label) == 1) { labeling.remove(vx.label); } else { labeling.put(vx.label, labeling.get(vx.label) - 1); } if (!labeling.containsKey(l)) { labeling.put(l, 1); } else { labeling.put(l, labeling.get(l) + 1); } } private boolean discharge(EdgeExtension ex) { VertexExtension ux = ex.getSource(); if (DIAGNOSTIC_ENABLED) { diagnostic.incrementDischarges(ex); } pushFlowThrough(ex, Math.min(ux.excess, ex.capacity - ex.flow)); return !ux.hasExcess(); } protected void pushFlowThrough(EdgeExtension ex, double f) { ex.getSource().excess -= f; ex.getTarget().excess += f; assert ((ex.getSource().excess >= 0.0) && (ex.getTarget().excess >= 0)); super.pushFlowThrough(ex, f); } private boolean isAdmissible(EdgeExtension e) { return e.hasCapacity() && (e.getSource().label == (e.getTarget().label + 1)); } private EdgeExtension extendedEdge(E e) { return this.edgeExtended(e); } private VertexExtension extendedVertex(V v) { return this.vertexExtended(v); } private class PushRelabelDiagnostic { // Discharges Map, Integer> discharges = new HashMap, Integer>(); long dischargesCounter = 0; // Relabels Map, Integer> relabels = new HashMap, Integer>(); long relabelsCounter = 0; private void incrementDischarges(EdgeExtension ex) { Pair p = Pair.of(ex.getSource().prototype, ex.getTarget().prototype); if (!discharges.containsKey(p)) { discharges.put(p, 0); } discharges.put(p, discharges.get(p) + 1); dischargesCounter++; } private void incrementRelabels(int from, int to) { Pair p = Pair.of(from, to); if (!relabels.containsKey(p)) { relabels.put(p, 0); } relabels.put(p, relabels.get(p) + 1); relabelsCounter++; } void dump() { Map labels = new HashMap(); for (V v : network.vertexSet()) { VertexExtension vx = extendedVertex(v); if (!labels.containsKey(vx.label)) { labels.put(vx.label, 0); } labels.put(vx.label, labels.get(vx.label) + 1); } System.out.println("LABELS "); System.out.println("------ "); System.out.println(labels); List, Integer>> relabelsSorted = new ArrayList, Integer>>( relabels.entrySet()); Collections.sort( relabelsSorted, new Comparator, Integer>>() { @Override public int compare( Map.Entry, Integer> o1, Map.Entry, Integer> o2) { return -(o1.getValue() - o2.getValue()); } }); System.out.println("RELABELS "); System.out.println("-------- "); System.out.println(" Count: " + relabelsCounter); System.out.println(" " + relabelsSorted); List, Integer>> dischargesSorted = new ArrayList, Integer>>( discharges.entrySet()); Collections.sort( dischargesSorted, new Comparator, Integer>>() { @Override public int compare( Map.Entry, Integer> one, Map.Entry, Integer> other) { return -(one.getValue() - other.getValue()); } }); System.out.println("DISCHARGES "); System.out.println("---------- "); System.out.println(" Count: " + dischargesCounter); System.out.println(" " + dischargesSorted); } } public class VertexExtension extends VertexExtensionBase { private int label; private boolean hasExcess() { return excess > 0; } @Override public String toString() { return prototype.toString() + String.format(" { LBL: %d } ", label); } } public class EdgeExtension extends EdgeExtensionBase { private boolean hasCapacity() { return compareFlowTo(capacity, flow) > 0; } @Override public String toString() { return prototype.toString() + String.format(" { F/CAP: %f / %f } ", flow, capacity); } } } // End PushRelabelMaximumFlow.java devsunny/app-galleries package com.asksunny.batch.graph; import java.util.List; import javax.script.Compilable; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; public class Scrapebook { public Scrapebook() { // TODO Auto-generated constructor stub } public static void main(String[] args) { System.setProperty("python.console.encoding", "UTF-8"); ScriptEngineManager manager = new ScriptEngineManager(); List sefs = manager.getEngineFactories(); for (ScriptEngineFactory scriptEngineFactory : sefs) { System.out.println(scriptEngineFactory.getEngineName()); } ScriptEngine engine = manager.getEngineByName("Nashorn"); System.out.println(engine instanceof Compilable); engine = manager.getEngineByName("groovy"); System.out.println(engine instanceof Compilable); engine = manager.getEngineByName("ruby"); System.out.println(engine instanceof Compilable); engine = manager.getEngineByName("python"); System.out.println(engine instanceof Compilable); } } 0 package com.vojtechcahlik.spaceintact.weapons; import com.vojtechcahlik.spaceintact.PhysicalSprite; import com.vojtechcahlik.spaceintact.Game; import com.vojtechcahlik.spaceintact.MovableSprite; /** * A basic enemy weapon. */ public class LameThrower extends Weapon { public LameThrower(MovableSprite wielder) { super(wielder, "/lame_thrower_blast.png"); } @Override protected void fire() { PhysicalSprite blast = new PhysicalSprite(0, 0, -1 * blastSpeed, blastDamage, blastHitPoints, blastIconPath); blast.positionX = wielder.positionX; blast.positionY = wielder.positionY + (wielder.sizeY - blast.sizeY) / 2; Game.ENEMY_SPRITES.add(blast); } }sgholamian/log-aware-clone-detectionLACCPlus/ActiveMQ/1193_2.java //,temp,AMQ3120Test.java,48,71,temp,AMQ4323Test.java,51,74 //,2 public class xxx { protected void startBroker(boolean delete) throws Exception { broker = new BrokerService(); //Start with a clean directory kahaDbDir = new File(broker.getBrokerDataDirectory(), "KahaDB"); deleteDir(kahaDbDir); broker.setSchedulerSupport(false); broker.setDeleteAllMessagesOnStartup(delete); broker.setPersistent(true); broker.setUseJmx(false); broker.addConnector("tcp://localhost:0"); PolicyMap map = new PolicyMap(); PolicyEntry entry = new PolicyEntry(); entry.setUseCache(false); map.setDefaultEntry(entry); broker.setDestinationPolicy(map); configurePersistence(broker, delete); broker.start(); LOG.info("Starting broker.."); } };joaosorio23/LAPR3 package lapr.project.model; import lapr.project.data.AddressDB; import lapr.project.data.DataHandler; import lapr.project.data.PharmacyDB; import lapr.project.data.ScooterDB; import lapr.project.utils.authorization.model.User; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.util.Properties; /** * The type Scooter Test. */ public class ScooterTest { /** * The Pharmacy. */ private final Pharmacy pharmacy; /** * The Address. */ private final Address address; /** * The Scooter. */ private Scooter scooter; /** * Instantiates a new Scooter Test. */ public ScooterTest() { try { Properties properties = new Properties(System.getProperties()); InputStream input = new FileInputStream("target/classes/application.properties"); properties.load(input); input.close(); System.setProperties(properties); } catch (IOException e) { e.printStackTrace(); } //Initial Database Setup new DataHandler(); this.address = new Address("04040404.04,04040404.04", "Rua ISEP", "4460-123", 123, "São João", 37); this.pharmacy = new Pharmacy("", this.address, "Pharmacy Teste"); this.scooter = new Scooter("10.0", "134.0", "35.0", "20.0"); this.scooter = new Scooter(1, 10.0, 134.0, 35.0, 100, 20.0); } /** * Save Test. * * @throws SQLException the sql exception */ @Test public void save() throws SQLException { System.out.println("Scooter save() Test"); new PharmacyDB().removePharmacy(this.pharmacy.getEmail()); new AddressDB().removeAddress(this.address.getGPSCoordinates()); new AddressDB().addAddress(this.address); new PharmacyDB().addPharmacy(this.pharmacy); int size = new ScooterDB().getAllScooters(this.pharmacy.getEmail()).size(); this.scooter.save(this.pharmacy.getEmail()); Assertions.assertEquals(size + 1, new ScooterDB().getAllScooters(this.pharmacy.getEmail()).size()); new ScooterDB().removeScooter(new ScooterDB().getAllScooters(this.pharmacy.getEmail()).get(0).getId()); new PharmacyDB().removePharmacy(this.pharmacy.getEmail()); new AddressDB().removeAddress(this.address.getGPSCoordinates()); } /** * Remove Test. * * @throws SQLException the sql exception */ @Test public void remove() throws SQLException { System.out.println("Scooter remove() Test"); new PharmacyDB().removePharmacy(this.pharmacy.getEmail()); new AddressDB().removeAddress(this.address.getGPSCoordinates()); new AddressDB().addAddress(this.address); new PharmacyDB().addPharmacy(this.pharmacy); this.scooter.save(this.pharmacy.getEmail()); int size = new ScooterDB().getAllScooters(this.pharmacy.getEmail()).size(); Scooter s = new ScooterDB().getAllScooters(this.pharmacy.getEmail()).get(0); s.remove(); Assertions.assertEquals(size - 1, new ScooterDB().getAllScooters(this.pharmacy.getEmail()).size()); try { s.remove(); } catch (IllegalArgumentException ia) { Assertions.assertEquals(size, new ScooterDB().getAllScooters(this.pharmacy.getEmail()).size()); } new PharmacyDB().removePharmacy(this.pharmacy.getEmail()); new AddressDB().removeAddress(this.address.getGPSCoordinates()); } /** * Update Test. * * @throws SQLException the sql exception */ @Test public void update() throws SQLException { System.out.println("Scooter update() Test"); new PharmacyDB().removePharmacy(this.pharmacy.getEmail()); new AddressDB().removeAddress(this.address.getGPSCoordinates()); new AddressDB().addAddress(this.address); new PharmacyDB().addPharmacy(this.pharmacy); this.scooter.save(this.pharmacy.getEmail()); Scooter s = new ScooterDB().getAllScooters(this.pharmacy.getEmail()).get(0); s.setCapacity("100"); s.update(); Assertions.assertEquals(s.getCapacity(), new ScooterDB().getAllScooters(this.pharmacy.getEmail()).get(0).getCapacity()); new ScooterDB().removeScooter(s.getId()); new PharmacyDB().removePharmacy(this.pharmacy.getEmail()); new AddressDB().removeAddress(this.address.getGPSCoordinates()); } /** * Equals Test. */ @Test public void equals() { System.out.println("Scooter equals() Test"); User u = new User("jose", "", "jose123"); Scooter s1 = new Scooter(2, 10.0, 134.0, 35.0, 100, 20.0); Scooter s2 = new Scooter(1, 134.0, 154.0, 135.0, 2, 20.0); //objetos iguais Assertions.assertEquals(this.scooter, this.scooter); //objetos classes diferentes Assertions.assertNotEquals(this.scooter, u); //objetos da mesma classe ids diferentes Assertions.assertNotEquals(this.scooter, s1); //objetos da mesma classe ids iguais Assertions.assertEquals(this.scooter, s2); } /** * Hash Code Test. */ @Test public void HashCodeTest() { System.out.println("Scooter hashCode() Test"); Scooter s1 = new Scooter(1, 10.0, 134.0, 35.0, 100, 20.0); Scooter s2 = new Scooter(2, 134.0, 154.0, 135.0, 2, 20.0); Assertions.assertEquals(this.scooter.hashCode(), s1.hashCode()); Assertions.assertNotEquals(this.scooter.hashCode(), s2.hashCode()); } }fr0609/SeriesGuide /* * Copyright 2014 * * 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.battlelancer.seriesguide.provider; import android.annotation.SuppressLint; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.OperationApplicationException; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.preference.PreferenceManager; import com.battlelancer.seriesguide.provider.SeriesGuideContract.EpisodeSearch; import com.battlelancer.seriesguide.provider.SeriesGuideContract.Episodes; import com.battlelancer.seriesguide.provider.SeriesGuideContract.ListItems; import com.battlelancer.seriesguide.provider.SeriesGuideContract.Lists; import com.battlelancer.seriesguide.provider.SeriesGuideContract.Movies; import com.battlelancer.seriesguide.provider.SeriesGuideContract.Seasons; import com.battlelancer.seriesguide.provider.SeriesGuideContract.Shows; import com.battlelancer.seriesguide.provider.SeriesGuideDatabase.Tables; import com.battlelancer.seriesguide.ui.SeriesGuidePreferences; import com.battlelancer.seriesguide.util.SelectionBuilder; import java.util.ArrayList; import java.util.Arrays; import timber.log.Timber; public class SeriesGuideProvider extends ContentProvider { public static final boolean LOGV = false; private static UriMatcher sUriMatcher; private static final int SHOWS = 100; private static final int SHOWS_ID = 101; private static final int SHOWS_FILTERED = 102; private static final int SHOWS_WITH_LAST_EPISODE = 103; private static final int SHOWS_WITH_NEXT_EPISODE = 104; private static final int EPISODES = 200; private static final int EPISODES_ID = 201; private static final int EPISODES_OFSHOW = 202; private static final int EPISODES_OFSEASON = 203; private static final int EPISODES_OFSEASON_WITHSHOW = 204; private static final int EPISODES_WITHSHOW = 205; private static final int EPISODES_ID_WITHSHOW = 206; private static final int SEASONS = 300; private static final int SEASONS_ID = 301; private static final int SEASONS_OFSHOW = 302; private static final int EPISODESEARCH = 400; private static final int EPISODESEARCH_ID = 401; private static final int LISTS = 500; private static final int LISTS_ID = 501; private static final int LISTS_WITH_LIST_ITEM_ID = 502; private static final int LIST_ITEMS = 600; private static final int LIST_ITEMS_ID = 601; private static final int LIST_ITEMS_WITH_DETAILS = 602; private static final int MOVIES = 700; private static final int MOVIES_ID = 701; private static final int SEARCH_SUGGEST = 800; private static final int RENEW_FTSTABLE = 900; /** * Build and return a {@link UriMatcher} that catches all {@link Uri} variations supported by * this {@link ContentProvider}. */ private static UriMatcher buildUriMatcher(Context context) { final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); final String authority = context.getPackageName() + ".provider"; // Shows matcher.addURI(authority, SeriesGuideContract.PATH_SHOWS, SHOWS); matcher.addURI(authority, SeriesGuideContract.PATH_SHOWS + "/" + SeriesGuideContract.PATH_FILTER + "/*", SHOWS_FILTERED); matcher.addURI(authority, SeriesGuideContract.PATH_SHOWS + "/" + SeriesGuideContract.PATH_WITH_LAST_EPISODE, SHOWS_WITH_LAST_EPISODE); matcher.addURI(authority, SeriesGuideContract.PATH_SHOWS + "/" + SeriesGuideContract.PATH_WITH_NEXT_EPISODE, SHOWS_WITH_NEXT_EPISODE); matcher.addURI(authority, SeriesGuideContract.PATH_SHOWS + "/*", SHOWS_ID); // Episodes matcher.addURI(authority, SeriesGuideContract.PATH_EPISODES, EPISODES); matcher.addURI(authority, SeriesGuideContract.PATH_EPISODES + "/" + SeriesGuideContract.PATH_OFSEASON + "/" + SeriesGuideContract.PATH_WITHSHOW + "/*", EPISODES_OFSEASON_WITHSHOW); matcher.addURI(authority, SeriesGuideContract.PATH_EPISODES + "/" + SeriesGuideContract.PATH_OFSEASON + "/*", EPISODES_OFSEASON); matcher.addURI(authority, SeriesGuideContract.PATH_EPISODES + "/" + SeriesGuideContract.PATH_OFSHOW + "/*", EPISODES_OFSHOW); matcher.addURI(authority, SeriesGuideContract.PATH_EPISODES + "/" + SeriesGuideContract.PATH_WITHSHOW, EPISODES_WITHSHOW); matcher.addURI(authority, SeriesGuideContract.PATH_EPISODES + "/" + SeriesGuideContract.PATH_WITHSHOW + "/*", EPISODES_ID_WITHSHOW); matcher.addURI(authority, SeriesGuideContract.PATH_EPISODES + "/*", EPISODES_ID); // Seasons matcher.addURI(authority, SeriesGuideContract.PATH_SEASONS, SEASONS); matcher.addURI(authority, SeriesGuideContract.PATH_SEASONS + "/" + SeriesGuideContract.PATH_OFSHOW + "/*", SEASONS_OFSHOW); matcher.addURI(authority, SeriesGuideContract.PATH_SEASONS + "/*", SEASONS_ID); // Lists matcher.addURI(authority, SeriesGuideContract.PATH_LISTS, LISTS); matcher.addURI(authority, SeriesGuideContract.PATH_LISTS + "/" + SeriesGuideContract.PATH_WITH_LIST_ITEM_ID + "/*", LISTS_WITH_LIST_ITEM_ID); matcher.addURI(authority, SeriesGuideContract.PATH_LISTS + "/*", LISTS_ID); // List items matcher.addURI(authority, SeriesGuideContract.PATH_LIST_ITEMS, LIST_ITEMS); matcher.addURI(authority, SeriesGuideContract.PATH_LIST_ITEMS + "/" + SeriesGuideContract.PATH_WITH_DETAILS, LIST_ITEMS_WITH_DETAILS); matcher.addURI(authority, SeriesGuideContract.PATH_LIST_ITEMS + "/*", LIST_ITEMS_ID); // Movies matcher.addURI(authority, SeriesGuideContract.PATH_MOVIES, MOVIES); matcher.addURI(authority, SeriesGuideContract.PATH_MOVIES + "/*", MOVIES_ID); // Search matcher.addURI(authority, SeriesGuideContract.PATH_EPISODESEARCH + "/" + SeriesGuideContract.PATH_SEARCH, EPISODESEARCH); matcher.addURI(authority, SeriesGuideContract.PATH_EPISODESEARCH + "/*", EPISODESEARCH_ID); // Suggestions matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST); matcher.addURI(authority, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST); // Ops matcher.addURI(authority, SeriesGuideContract.PATH_RENEWFTSTABLE, RENEW_FTSTABLE); return matcher; } private final ThreadLocal mApplyingBatch = new ThreadLocal(); private SeriesGuideDatabase mDbHelper; protected SQLiteDatabase mDb; @Override public void shutdown() { /** * If we ever do unit-testing, nice to have this already (no bug-hunt). */ if (mDbHelper != null) { mDbHelper.close(); mDbHelper = null; mDb = null; } } @Override public boolean onCreate() { Context context = getContext(); sUriMatcher = buildUriMatcher(context); mDbHelper = new SeriesGuideDatabase(context); PreferenceManager.getDefaultSharedPreferences(context) .registerOnSharedPreferenceChangeListener(mImportListener); return true; } final OnSharedPreferenceChangeListener mImportListener = new OnSharedPreferenceChangeListener() { @SuppressLint("CommitPrefEdits") public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equalsIgnoreCase(SeriesGuidePreferences.KEY_DATABASEIMPORTED)) { if (sharedPreferences .getBoolean(SeriesGuidePreferences.KEY_DATABASEIMPORTED, false)) { mDbHelper.close(); sharedPreferences.edit() .putBoolean(SeriesGuidePreferences.KEY_DATABASEIMPORTED, false) .commit(); } } } }; @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (LOGV) { Timber.v("query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")"); } final SQLiteDatabase db = mDbHelper.getReadableDatabase(); final int match = sUriMatcher.match(uri); switch (match) { case RENEW_FTSTABLE: { SeriesGuideDatabase.rebuildFtsTableImpl(db); return null; } case EPISODESEARCH: { if (selectionArgs == null) { throw new IllegalArgumentException( "selectionArgs must be provided for the Uri: " + uri); } return SeriesGuideDatabase.search(selection, selectionArgs, db); } case SEARCH_SUGGEST: { if (selectionArgs == null) { throw new IllegalArgumentException( "selectionArgs must be provided for the Uri: " + uri); } return SeriesGuideDatabase.getSuggestions(selectionArgs[0], db); } default: { // Most cases are handled with simple SelectionBuilder final SelectionBuilder builder = buildSelection(uri, match); Cursor query = builder .where(selection, selectionArgs) .query(db, projection, sortOrder); if (query != null) { query.setNotificationUri(getContext().getContentResolver(), uri); } return query; } } } @Override public String getType(Uri uri) { final int match = sUriMatcher.match(uri); switch (match) { case SHOWS: case SHOWS_FILTERED: case SHOWS_WITH_LAST_EPISODE: case SHOWS_WITH_NEXT_EPISODE: return Shows.CONTENT_TYPE; case SHOWS_ID: return Shows.CONTENT_ITEM_TYPE; case EPISODES: case EPISODES_OFSHOW: case EPISODES_OFSEASON: case EPISODES_OFSEASON_WITHSHOW: case EPISODES_WITHSHOW: return Episodes.CONTENT_TYPE; case EPISODES_ID: case EPISODES_ID_WITHSHOW: return Episodes.CONTENT_ITEM_TYPE; case SEASONS: case SEASONS_OFSHOW: return Seasons.CONTENT_TYPE; case SEASONS_ID: return Seasons.CONTENT_ITEM_TYPE; case LISTS: case LISTS_WITH_LIST_ITEM_ID: return Lists.CONTENT_TYPE; case LISTS_ID: return Lists.CONTENT_ITEM_TYPE; case LIST_ITEMS: case LIST_ITEMS_WITH_DETAILS: return ListItems.CONTENT_TYPE; case LIST_ITEMS_ID: return ListItems.CONTENT_ITEM_TYPE; case MOVIES: return Movies.CONTENT_TYPE; case MOVIES_ID: return Movies.CONTENT_ITEM_TYPE; case SEARCH_SUGGEST: return SearchManager.SUGGEST_MIME_TYPE; case RENEW_FTSTABLE: return Episodes.CONTENT_TYPE; // however there is nothing returned default: throw new UnsupportedOperationException("Unknown uri: " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { Uri newItemUri; if (!applyingBatch()) { final SQLiteDatabase db = mDbHelper.getWritableDatabase(); db.beginTransaction(); try { newItemUri = insertInTransaction(uri, values); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } else { newItemUri = insertInTransaction(uri, values); } if (newItemUri != null) { getContext().getContentResolver().notifyChange(uri, null); } return newItemUri; } @Override public int bulkInsert(Uri uri, ContentValues[] values) { int numValues = values.length; boolean notifyChange = false; final SQLiteDatabase db = mDbHelper.getWritableDatabase(); db.beginTransaction(); try { for (int i = 0; i < numValues; i++) { Uri result = insertInTransaction(uri, values[i]); if (result != null) { notifyChange = true; } db.yieldIfContendedSafely(); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } if (notifyChange) { getContext().getContentResolver().notifyChange(uri, null); } return numValues; } private Uri insertInTransaction(Uri uri, ContentValues values) { if (LOGV) { Timber.v("insert(uri=" + uri + ", values=" + values.toString() + ")"); } Uri notifyUri = null; final int match = sUriMatcher.match(uri); switch (match) { case SHOWS: { long id = mDbHelper.insertShows(values); if (id < 0) { break; } notifyUri = Shows.buildShowUri(values.getAsString(Shows._ID)); break; } case SEASONS: { long id = mDbHelper.insertSeasons(values); if (id < 0) { break; } notifyUri = Seasons.buildSeasonUri(values.getAsString(Seasons._ID)); break; } case EPISODES: { long id = mDbHelper.insertEpisodes(values); if (id < 0) { break; } notifyUri = Episodes.buildEpisodeUri(values.getAsString(Episodes._ID)); break; } case LISTS: { long id = mDbHelper.insertLists(values); if (id < 0) { break; } notifyUri = Lists.buildListUri(values.getAsString(Lists.LIST_ID)); break; } case LIST_ITEMS: { long id = mDbHelper.insertListItems(values); if (id < 0) { break; } notifyUri = ListItems.buildListItemUri(values.getAsString(ListItems.LIST_ITEM_ID)); break; } case MOVIES: { long id = mDbHelper.insertMovies(values); if (id < 0) { break; } notifyUri = Movies.buildMovieUri(values.getAsInteger(Movies.TMDB_ID)); break; } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } return notifyUri; } /** * {@inheritDoc} */ @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (LOGV) { Timber.v("update(uri=" + uri + ", values=" + values.toString() + ")"); } int count = 0; if (!applyingBatch()) { final SQLiteDatabase db = mDbHelper.getWritableDatabase(); db.beginTransaction(); try { count = buildSelection(uri, sUriMatcher.match(uri)) .where(selection, selectionArgs) .update(db, values); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } else { mDb = mDbHelper.getWritableDatabase(); count = buildSelection(uri, sUriMatcher.match(uri)) .where(selection, selectionArgs) .update(mDb, values); } if (count > 0) { getContext().getContentResolver().notifyChange(uri, null); } return count; } /** * {@inheritDoc} */ @Override public int delete(Uri uri, String selection, String[] selectionArgs) { if (LOGV) { Timber.v("delete(uri=" + uri + ")"); } int count = 0; if (!applyingBatch()) { final SQLiteDatabase db = mDbHelper.getWritableDatabase(); db.beginTransaction(); try { count = buildSelection(uri, sUriMatcher.match(uri)) .where(selection, selectionArgs) .delete(db); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } else { mDb = mDbHelper.getWritableDatabase(); count = buildSelection(uri, sUriMatcher.match(uri)) .where(selection, selectionArgs) .delete(mDb); } if (count > 0) { getContext().getContentResolver().notifyChange(uri, null); } return count; } /** * Apply the given set of {@link ContentProviderOperation}, executing inside a {@link * SQLiteDatabase} transaction. All changes will be rolled back if any single one fails. */ @Override public ContentProviderResult[] applyBatch(ArrayList operations) throws OperationApplicationException { final int numOperations = operations.size(); if (numOperations == 0) { return new ContentProviderResult[0]; } mDb = mDbHelper.getWritableDatabase(); mDb.beginTransaction(); try { mApplyingBatch.set(true); final ContentProviderResult[] results = new ContentProviderResult[numOperations]; for (int i = 0; i < numOperations; i++) { final ContentProviderOperation operation = operations.get(i); if (i > 0 && operation.isYieldAllowed()) { mDb.yieldIfContendedSafely(); } results[i] = operation.apply(this, results, i); } mDb.setTransactionSuccessful(); return results; } finally { mApplyingBatch.set(false); mDb.endTransaction(); } } private boolean applyingBatch() { return mApplyingBatch.get() != null && mApplyingBatch.get(); } /** * Builds selection using a {@link SelectionBuilder} to match the requested {@link Uri}. */ private static SelectionBuilder buildSelection(Uri uri, int match) { final SelectionBuilder builder = new SelectionBuilder(); switch (match) { case SHOWS: { return builder.table(Tables.SHOWS); } case SHOWS_ID: { final String showId = Shows.getShowId(uri); return builder.table(Tables.SHOWS).where(Shows._ID + "=?", showId); } case SHOWS_FILTERED: { final String filter = uri.getLastPathSegment(); return builder.table(Tables.SHOWS).where(Shows.TITLE + " LIKE ?", "%" + filter + "%"); } case SHOWS_WITH_LAST_EPISODE: { return builder.table(Tables.SHOWS_JOIN_EPISODES_ON_LAST_EPISODE) .mapToTable(Shows._ID, Tables.SHOWS) .mapToTable(Shows.RATING, Tables.SHOWS); } case SHOWS_WITH_NEXT_EPISODE: { return builder.table(Tables.SHOWS_JOIN_EPISODES_ON_NEXT_EPISODE) .mapToTable(Shows._ID, Tables.SHOWS) .mapToTable(Shows.RATING, Tables.SHOWS); } case EPISODES: { return builder.table(Tables.EPISODES); } case EPISODES_ID: { final String episodeId = Episodes.getEpisodeId(uri); return builder.table(Tables.EPISODES).where(Episodes._ID + "=?", episodeId); } case EPISODES_OFSHOW: { final String showId = uri.getPathSegments().get(2); return builder.table(Tables.EPISODES).where(Shows.REF_SHOW_ID + "=?", showId); } case EPISODES_OFSEASON: { final String seasonId = uri.getPathSegments().get(2); return builder.table(Tables.EPISODES).where(Seasons.REF_SEASON_ID + "=?", seasonId); } case EPISODES_OFSEASON_WITHSHOW: { final String seasonId = uri.getPathSegments().get(3); return builder.table(Tables.EPISODES_JOIN_SHOWS) .mapToTable(Episodes._ID, Tables.EPISODES) .mapToTable(Episodes.RATING, Tables.EPISODES) .where(Seasons.REF_SEASON_ID + "=?", seasonId); } case EPISODES_WITHSHOW: { return builder.table(Tables.EPISODES_JOIN_SHOWS) .mapToTable(Episodes._ID, Tables.EPISODES) .mapToTable(Episodes.RATING, Tables.EPISODES); } case EPISODES_ID_WITHSHOW: { final String episodeId = Episodes.getEpisodeId(uri); return builder.table(Tables.EPISODES_JOIN_SHOWS) .mapToTable(Episodes._ID, Tables.EPISODES) .mapToTable(Episodes.RATING, Tables.EPISODES) .where(Qualified.EPISODES_EPISODE_ID + "=?", episodeId); } case SEASONS: { return builder.table(Tables.SEASONS); } case SEASONS_ID: { final String seasonId = Seasons.getSeasonId(uri); return builder.table(Tables.SEASONS).where(Seasons._ID + "=?", seasonId); } case SEASONS_OFSHOW: { final String showId = uri.getPathSegments().get(2); return builder.table(Tables.SEASONS).where(Shows.REF_SHOW_ID + "=?", showId); } case EPISODESEARCH_ID: { final String rowid = EpisodeSearch.getDocId(uri); return builder.table(Tables.EPISODES_SEARCH).where(EpisodeSearch._DOCID + "=?", rowid); } case LISTS: { return builder.table(Tables.LISTS); } case LISTS_ID: { final String listId = Lists.getId(uri); return builder.table(Tables.LISTS).where(Lists.LIST_ID + "=?", listId); } case LISTS_WITH_LIST_ITEM_ID: { final String itemId = uri.getPathSegments().get(2); return builder .table(Tables.LISTS + " LEFT OUTER JOIN (" + SubQuery.LISTS_LIST_ITEM_ID + "'" + itemId + "%') AS " + Tables.LIST_ITEMS + " ON " + Qualified.LISTS_LIST_ID + "=" + Qualified.LIST_ITEMS_LIST_ID) .mapToTable(Lists._ID, Tables.LISTS); } case LIST_ITEMS: { return builder.table(Tables.LIST_ITEMS); } case LIST_ITEMS_ID: { final String list_item_id = ListItems.getId(uri); return builder.table(Tables.LIST_ITEMS).where(ListItems.LIST_ITEM_ID + "=?", list_item_id); } case LIST_ITEMS_WITH_DETAILS: { return builder.table(Tables.LIST_ITEMS_WITH_DETAILS); } case MOVIES: { return builder.table(Tables.MOVIES); } case MOVIES_ID: { final String movieId = Movies.getId(uri); return builder.table(Tables.MOVIES).where(Movies.TMDB_ID + "=?", movieId); } default: { throw new UnsupportedOperationException("Unknown uri: " + uri); } } } private interface SubQuery { String LISTS_LIST_ITEM_ID = "SELECT * FROM " + Tables.LIST_ITEMS + " WHERE " + ListItems.LIST_ITEM_ID + " LIKE "; } /** * {@link SeriesGuideContract} fields that are fully qualified with a specific parent {@link * Tables}. Used when needed to work around SQL ambiguity. */ private interface Qualified { String EPISODES_EPISODE_ID = Tables.EPISODES + "." + Episodes._ID; String LISTS_LIST_ID = Tables.LISTS + "." + Lists.LIST_ID; String LIST_ITEMS_LIST_ID = Tables.LIST_ITEMS + "." + Lists.LIST_ID; } } package org.sage.common.events; import java.io.Serializable; public interface SageCompleteEvent extends SageEvent { public boolean isSuccessful(); } package com.github.arisan.adapter; import android.view.ViewGroup; import android.widget.Toast; import com.github.arisan.FormConfig; import com.github.arisan.helper.ChildUtils; import com.github.arisan.model.FormModel; import java.util.ArrayList; import java.util.List; public class OneToManyAdapter { private List> mList; private FormConfig config; private ViewGroup parent_view; private List listForm = new ArrayList<>(); private String parent_field_name; public OneToManyAdapter(ViewGroup parent_view) { this.parent_view = parent_view; } public void init(){ } public FormConfig convertToChildConfig(FormConfig config){ FormConfig childConfig = config; childConfig.submitText = "DELETE"; childConfig.useTitle = false; childConfig.isChild = true; return childConfig; } public void processData(){ for(final List models : mList){ final FormAdapter adapter = new FormAdapter(parent_view.getContext()); adapter.setParent_field_name(parent_field_name); adapter.setOnSubmitListener(new FormAdapter.OnSubmitListener() { @Override public void onSubmit(String result) { int idx = mList.indexOf(models); if(mList.size()!=1) { listForm.remove(adapter); mList.remove(idx); adapter.explode(); reindex(); }else{ Toast.makeText(adapter.getContext(), "Cannot Remove all", Toast.LENGTH_SHORT).show(); } } }); adapter.setConfig(convertToChildConfig(config)); adapter.getConfig().index_child = mList.indexOf(models); adapter.setFieldModels(models); adapter.setParent_view(parent_view); adapter.processData(); listForm.add(adapter); } } public void addNewData(){ final List new_data = ChildUtils.listValueRemover(mList); mList.add(new_data); //Add form to parent final FormAdapter new_adapter = new FormAdapter(parent_view.getContext()); new_adapter.setParent_field_name(parent_field_name); new_adapter.setOnSubmitListener(new FormAdapter.OnSubmitListener() { @Override public void onSubmit(String result) { int idx = mList.indexOf(new_data); if(mList.size()!=1) { listForm.remove(new_adapter); mList.remove(idx); new_adapter.explode(); reindex(); }else{ Toast.makeText(new_adapter.getContext(), "Cannot Remove all", Toast.LENGTH_SHORT).show(); } } }); new_adapter.setConfig(convertToChildConfig(config)); new_adapter.getConfig().index_child = mList.indexOf(new_data); new_adapter.setFieldModels(new_data); new_adapter.setParent_view(parent_view); new_adapter.processData(); listForm.add(new_adapter); } void reindex(){ for(FormAdapter form:listForm){ form.getConfig().index_child = listForm.indexOf(form); } } //=======SETTER GETTER============// public ViewGroup getParent_view() { return parent_view; } public void setParent_view(ViewGroup parent_view) { this.parent_view = parent_view; } public List> getList() { return mList; } public void setList(List> mList) { this.mList = mList; } public FormConfig getConfig() { return config; } public void setConfig(FormConfig config) { this.config = config.renew(); } public List getListForm() { return listForm; } public void setListForm(List listForm) { this.listForm = listForm; } public String getParent_field_name() { return parent_field_name; } public void setParent_field_name(String parent_field_name) { this.parent_field_name = parent_field_name; } } package hst; import static com.mongodb.client.model.Filters.eq; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import org.bson.Document; import org.bson.types.ObjectId; import com.mongodb.Block; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.MongoDatabase; import com.mongodb.client.gridfs.GridFSBucket; import com.mongodb.client.gridfs.GridFSBuckets; import com.mongodb.client.gridfs.GridFSFindIterable; import com.mongodb.client.gridfs.model.GridFSFile; public class EmployeDetailFind { // db esthablishment and creation Logger mongoLogger = Logger.getLogger("org.mongodb.driver"); // mongoLogger.setLevel(Level.SEVERE); MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017")); MongoDatabase database = mongoClient.getDatabase("HST"); GridFSBucket gridBucket = GridFSBuckets.create(database, "EmployeeDetails"); protected String FileName; protected ObjectId ObjectId; protected Document Metadata; protected Date UploadDate; protected String Out; // search procedure by visa type public Object VisaTypeFind(String VisaType) { mongoLogger.setLevel(Level.SEVERE); System.out.println("details of VisaType collection"); gridBucket.find(eq("metadata.VisaType", VisaType)).forEach(new Block() { public void apply(final GridFSFile gridFSFile) { FileName = gridFSFile.getFilename(); ObjectId = gridFSFile.getObjectId(); Metadata = gridFSFile.getMetadata(); UploadDate = gridFSFile.getUploadDate(); System.out.println("Employee name :" + FileName); System.out.println("ObjectId :" + ObjectId); System.out.println("Employee Details :" + Metadata); System.out.println("UploadDate :" + UploadDate); Out += "
Employee name :" + FileName + "
ObjectId :" + ObjectId + "
Employee Details :" + Metadata + "
UploadDate :" + UploadDate + "

"; } }); return "Search Results :" + Out; } // search procedure by MailAddress public Object MailAddress(String MailAddress) { mongoLogger.setLevel(Level.SEVERE); System.out.println("details of MailAddress collections "); gridBucket.find(eq("metadata.MailAddress", MailAddress)).forEach(new Block() { public void apply(final GridFSFile gridFSFile) { String FileName = gridFSFile.getFilename(); ObjectId ObjectId = gridFSFile.getObjectId(); Document Metadata = gridFSFile.getMetadata(); Date UploadDate = gridFSFile.getUploadDate(); System.out.println("Employee name :" + FileName); System.out.println("ObjectId :" + ObjectId); System.out.println("Employee Details :" + Metadata); System.out.println("UploadDate :" + UploadDate); Out += "
Employee name :" + FileName + "
ObjectId :" + ObjectId + "
Employee Details :" + Metadata + "
UploadDate :" + UploadDate + "

"; } }); return "Search Results :" + Out; } // search procedure by contact num1 public Object ContactNum1(String ContactNum1) { mongoLogger.setLevel(Level.SEVERE); System.out.println("details of ContactNum collections "); gridBucket.find(eq("metadata.ContactNum1", ContactNum1)).forEach(new Block() { public void apply(final GridFSFile gridFSFile) { String FileName = gridFSFile.getFilename(); ObjectId ObjectId = gridFSFile.getObjectId(); Document Metadata = gridFSFile.getMetadata(); Date UploadDate = gridFSFile.getUploadDate(); System.out.println("Employee name :" + FileName); System.out.println("ObjectId :" + ObjectId); System.out.println("Employee Details :" + Metadata); System.out.println("UploadDate :" + UploadDate); Out += "
Employee name :" + FileName + "
ObjectId :" + ObjectId + "
Employee Details :" + Metadata + "
UploadDate :" + UploadDate + "

"; } }); return "Search Results :" + Out; } // Search procedure by contatct num 2 public Object ContactNum2(String ContactNum2) { mongoLogger.setLevel(Level.SEVERE); System.out.println("details of ContactNum collections "); gridBucket.find(eq("metadata.ContactNum2", ContactNum2)).forEach(new Block() { public void apply(final GridFSFile gridFSFile) { String FileName = gridFSFile.getFilename(); ObjectId ObjectId = gridFSFile.getObjectId(); Document Metadata = gridFSFile.getMetadata(); Date UploadDate = gridFSFile.getUploadDate(); System.out.println("Employee name :" + FileName); System.out.println("ObjectId :" + ObjectId); System.out.println("Employee Details :" + Metadata); System.out.println("UploadDate :" + UploadDate); Out += "
Employee name :" + FileName + "
ObjectId :" + ObjectId + "
Employee Details :" + Metadata + "
UploadDate :" + UploadDate + "

"; } }); return "Search Results :" + Out; } // search procedure by Filename public Object AttachmentName(String AttachmentName) { mongoLogger.setLevel(Level.SEVERE); System.out.println("details of AttachmentName collections "); gridBucket.find(eq("filename", AttachmentName)).forEach(new Block() { public void apply(final GridFSFile gridFSFile) { String FileName = gridFSFile.getFilename(); ObjectId ObjectId = gridFSFile.getObjectId(); Document Metadata = gridFSFile.getMetadata(); Date UploadDate = gridFSFile.getUploadDate(); System.out.println("Employee name :" + FileName); System.out.println("ObjectId :" + ObjectId); System.out.println("Employee Details :" + Metadata); System.out.println("UploadDate :" + UploadDate); Out += "
Employee name :" + FileName + "
ObjectId :" + ObjectId + "
Employee Details :" + Metadata + "
UploadDate :" + UploadDate + "

"; } }); GridFSFindIterable testItemsCursor = gridBucket.find(eq("filename", AttachmentName)); gridBucket.find(eq("filename","xxxxx")); //1.search document 2.get metdata and object id ,filename 3.set the new atthacment return "Search Results :" + Out; } // search procedure by ObjectId public Object FileId(ObjectId FileId) { mongoLogger.setLevel(Level.SEVERE); System.out.println("details of ObjectId collections "); gridBucket.find(eq("_id", FileId)).forEach(new Block() { public void apply(final GridFSFile gridFSFile) { String FileName = gridFSFile.getFilename(); ObjectId ObjectId = gridFSFile.getObjectId(); Document Metadata = gridFSFile.getMetadata(); Date UploadDate = gridFSFile.getUploadDate(); System.out.println("Employee name :" + FileName); System.out.println("ObjectId :" + ObjectId); System.out.println("Employee Details :" + Metadata); System.out.println("UploadDate :" + UploadDate); Out += "
Employee name :" + FileName + "
ObjectId :" + ObjectId + "
Employee Details :" + Metadata + "
UploadDate :" + UploadDate + "

"; } }); return "Search Results :" + Out; } public Object Findall() { System.out.println("details of all collections "); mongoLogger.setLevel(Level.SEVERE); // database.getCollection("sai.vardhan.Boda.files").find(); gridBucket.find().forEach(new Block() { public void apply(final GridFSFile gridFSFile) { String FileName = gridFSFile.getFilename(); ObjectId ObjectId = gridFSFile.getObjectId(); Document Metadata = gridFSFile.getMetadata(); Date UploadDate = gridFSFile.getUploadDate(); System.out.println("Employee name :" + FileName); System.out.println("ObjectId :" + ObjectId); System.out.println("Employee Details :" + Metadata); System.out.println("UploadDate :" + UploadDate); Out += "
Employee name :" + FileName + "
ObjectId :" + ObjectId + "
Employee Details :" + Metadata + "
UploadDate :" + UploadDate + "

"; } }); return "Search Results :" + Out; } public void close() { mongoClient.close(); } } package org.jboss.resteasy.test.resource.param; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import jakarta.ws.rs.client.ClientBuilder; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.container.test.api.RunAsClient; import org.jboss.arquillian.junit.Arquillian; import org.jboss.resteasy.client.jaxrs.ResteasyClient; import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget; import org.jboss.resteasy.client.jaxrs.internal.ClientConfiguration; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterConstructorClass; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterCookieResource; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterCookieResourceIntf; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterFromStringClass; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterHeaderDelegate; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterHeaderDelegateClass; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterHeaderResource; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterHeaderResourceIntf; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterMatrixResource; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterMatrixResourceIntf; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterMiscResource; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterMiscResourceIntf; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterParamConverter; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterParamConverterClass; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterParamConverterProvider; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterPathResource; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterPathResourceIntf; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterQueryResource; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterQueryResourceIntf; import org.jboss.resteasy.test.resource.param.resource.MultiValuedParamDefaultParamConverterValueOfClass; import org.jboss.resteasy.utils.PortProviderUtil; import org.jboss.resteasy.utils.TestUtil; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; /** * @tpSubChapter Parameters * @tpChapter Integration tests * @tpTestCaseDetails Test for RESTEasy extended support for multivalue @*Param (RESTEASY-1966) * org.jboss.resteasy.plugins.providers.MultiValuedArrayParamConverter and * org.jboss.resteasy.plugins.providers.MultiValuedCollectionParamConverter are used * @tpSince RESTEasy 4.0.0 */ @RunWith(Arquillian.class) @RunAsClient public class MultiValuedParamDefaultParamConverterProxyTest { private static ResteasyClient client; private static MultiValuedParamDefaultParamConverterCookieResourceIntf cookieProxy; private static MultiValuedParamDefaultParamConverterHeaderResourceIntf headerProxy; private static MultiValuedParamDefaultParamConverterMatrixResourceIntf matrixProxy; private static MultiValuedParamDefaultParamConverterMiscResourceIntf miscProxy; private static MultiValuedParamDefaultParamConverterPathResourceIntf pathProxy; private static MultiValuedParamDefaultParamConverterQueryResourceIntf queryProxy; private static List list_constructor = new ArrayList(); private static Set set_constructor = new HashSet(); private static SortedSet sortedSet_constructor = new TreeSet(); private static MultiValuedParamDefaultParamConverterConstructorClass[] array_constructor = new MultiValuedParamDefaultParamConverterConstructorClass[2]; private static List list_valueOf = new ArrayList(); private static Set set_valueOf = new HashSet(); private static SortedSet sortedSet_valueOf = new TreeSet(); private static MultiValuedParamDefaultParamConverterValueOfClass[] array_valueOf = new MultiValuedParamDefaultParamConverterValueOfClass[2]; private static List list_fromString = new ArrayList(); private static Set set_fromString = new HashSet(); private static SortedSet sortedSet_fromString = new TreeSet(); private static MultiValuedParamDefaultParamConverterFromStringClass[] array_fromString = new MultiValuedParamDefaultParamConverterFromStringClass[2]; private static List list_headerDelegate = new ArrayList(); private static Set set_headerDelegate = new HashSet(); private static SortedSet sortedSet_headerDelegate = new TreeSet(); private static MultiValuedParamDefaultParamConverterHeaderDelegateClass[] array_headerDelegate = new MultiValuedParamDefaultParamConverterHeaderDelegateClass[2]; private static List list_paramConverter = new ArrayList(); private static Set set_paramConverter = new HashSet(); private static SortedSet sortedSet_paramConverter = new TreeSet(); private static MultiValuedParamDefaultParamConverterParamConverterClass[] array_paramConverter = new MultiValuedParamDefaultParamConverterParamConverterClass[2]; private static boolean[] booleanArray = new boolean[2]; private static byte[] byteArray = new byte[2]; private static char[] charArray = new char[2]; private static short[] shortArray = new short[2]; private static int[] intArray = new int[2]; private static long[] longArray = new long[2]; private static float[] floatArray = new float[2]; private static double[] doubleArray = new double[2]; @Deployment public static Archive deploy() { WebArchive war = TestUtil.prepareArchive(MultiValuedParamDefaultParamConverterProxyTest.class.getSimpleName()); war.addClass(MultiValuedParamDefaultParamConverterConstructorClass.class); war.addClass(MultiValuedParamDefaultParamConverterFromStringClass.class); war.addClass(MultiValuedParamDefaultParamConverterParamConverterClass.class); war.addClass(MultiValuedParamDefaultParamConverterValueOfClass.class); war.addClass(MultiValuedParamDefaultParamConverterParamConverter.class); war.addClass(MultiValuedParamDefaultParamConverterCookieResourceIntf.class); war.addClass(MultiValuedParamDefaultParamConverterHeaderResourceIntf.class); war.addClass(MultiValuedParamDefaultParamConverterMatrixResourceIntf.class); war.addClass(MultiValuedParamDefaultParamConverterMiscResourceIntf.class); war.addClass(MultiValuedParamDefaultParamConverterPathResourceIntf.class); war.addClass(MultiValuedParamDefaultParamConverterQueryResourceIntf.class); war.addClass(MultiValuedParamDefaultParamConverterHeaderDelegateClass.class); war.addClass(MultiValuedParamDefaultParamConverterHeaderDelegate.class); return TestUtil.finishContainerPrepare(war, null, MultiValuedParamDefaultParamConverterParamConverterProvider.class, MultiValuedParamDefaultParamConverterCookieResource.class, MultiValuedParamDefaultParamConverterHeaderResource.class, MultiValuedParamDefaultParamConverterMatrixResource.class, MultiValuedParamDefaultParamConverterMiscResource.class, MultiValuedParamDefaultParamConverterPathResource.class, MultiValuedParamDefaultParamConverterQueryResource.class); } private static String generateURL(String path) { return PortProviderUtil.generateURL(path, MultiValuedParamDefaultParamConverterProxyTest.class.getSimpleName()); } @BeforeClass public static void beforeClass() throws Exception { client = (ResteasyClient) ClientBuilder.newClient(); client.register(MultiValuedParamDefaultParamConverterParamConverterProvider.class); ClientConfiguration config = ((ClientConfiguration)client.getConfiguration()); config.addHeaderDelegate(MultiValuedParamDefaultParamConverterHeaderDelegateClass.class, new MultiValuedParamDefaultParamConverterHeaderDelegate()); ResteasyWebTarget target = client.target(generateURL("")); cookieProxy = target.proxy(MultiValuedParamDefaultParamConverterCookieResourceIntf.class); headerProxy = target.proxy(MultiValuedParamDefaultParamConverterHeaderResourceIntf.class); matrixProxy = target.proxy(MultiValuedParamDefaultParamConverterMatrixResourceIntf.class); miscProxy = target.proxy(MultiValuedParamDefaultParamConverterMiscResourceIntf.class); pathProxy = target.proxy(MultiValuedParamDefaultParamConverterPathResourceIntf.class); queryProxy = target.proxy(MultiValuedParamDefaultParamConverterQueryResourceIntf.class); MultiValuedParamDefaultParamConverterConstructorClass c1_constructor = new MultiValuedParamDefaultParamConverterConstructorClass("c1"); MultiValuedParamDefaultParamConverterConstructorClass c2_constructor = new MultiValuedParamDefaultParamConverterConstructorClass("c2"); list_constructor.add(c1_constructor); list_constructor.add(c2_constructor); set_constructor.add(c1_constructor); set_constructor.add(c2_constructor); sortedSet_constructor.add(c1_constructor); sortedSet_constructor.add(c2_constructor); array_constructor[0] = c1_constructor; array_constructor[1] = c2_constructor; MultiValuedParamDefaultParamConverterValueOfClass c1_valueOf = MultiValuedParamDefaultParamConverterValueOfClass.valueOf("c1"); MultiValuedParamDefaultParamConverterValueOfClass c2_valueOf = MultiValuedParamDefaultParamConverterValueOfClass.valueOf("c2"); list_valueOf.add(c1_valueOf); list_valueOf.add(c2_valueOf); set_valueOf.add(c1_valueOf); set_valueOf.add(c2_valueOf); sortedSet_valueOf.add(c1_valueOf); sortedSet_valueOf.add(c2_valueOf); array_valueOf[0] = c1_valueOf; array_valueOf[1] = c2_valueOf; MultiValuedParamDefaultParamConverterFromStringClass c1_fromString = MultiValuedParamDefaultParamConverterFromStringClass.fromString("c1"); MultiValuedParamDefaultParamConverterFromStringClass c2_fromString = MultiValuedParamDefaultParamConverterFromStringClass.fromString("c2"); list_fromString.add(c1_fromString); list_fromString.add(c2_fromString); set_fromString.add(c1_fromString); set_fromString.add(c2_fromString); sortedSet_fromString.add(c1_fromString); sortedSet_fromString.add(c2_fromString); array_fromString[0] = c1_fromString; array_fromString[1] = c2_fromString; MultiValuedParamDefaultParamConverterHeaderDelegateClass c1_headerDelegate = new MultiValuedParamDefaultParamConverterHeaderDelegateClass(); c1_headerDelegate.setS("c1"); MultiValuedParamDefaultParamConverterHeaderDelegateClass c2_headerDelegate = new MultiValuedParamDefaultParamConverterHeaderDelegateClass(); c2_headerDelegate.setS("c2"); list_headerDelegate.add(c1_headerDelegate); list_headerDelegate.add(c2_headerDelegate); set_headerDelegate.add(c1_headerDelegate); set_headerDelegate.add(c2_headerDelegate); sortedSet_headerDelegate.add(c1_headerDelegate); sortedSet_headerDelegate.add(c2_headerDelegate); array_headerDelegate[0] = c1_headerDelegate; array_headerDelegate[1] = c2_headerDelegate; MultiValuedParamDefaultParamConverterParamConverterClass c1_paramConverter = new MultiValuedParamDefaultParamConverterParamConverterClass(); c1_paramConverter.setS("c1"); MultiValuedParamDefaultParamConverterParamConverterClass c2_paramConverter = new MultiValuedParamDefaultParamConverterParamConverterClass(); c2_paramConverter.setS("c2"); list_paramConverter.add(c1_paramConverter); list_paramConverter.add(c2_paramConverter); set_paramConverter.add(c1_paramConverter); set_paramConverter.add(c2_paramConverter); sortedSet_paramConverter.add(c1_paramConverter); sortedSet_paramConverter.add(c2_paramConverter); array_paramConverter[0] = c1_paramConverter; array_paramConverter[1] = c2_paramConverter; booleanArray[0] = false; booleanArray[1] = true; byteArray[0] = 0; byteArray[1] = 1; charArray[0] = 'a'; charArray[1] = 'z'; shortArray[0] = 3; shortArray[1] = 7; intArray[0] = 11; intArray[1] = 13; longArray[0] = 17; longArray[1] = 19; floatArray[0] = 23.0f; floatArray[1] = 29.0f; doubleArray[0] = 31.0d; doubleArray[1] = 37.0d; } @AfterClass public static void afterClass() throws Exception { client.close(); } ///////////////////////////////////////////////////////////////////////////////////////////// /** * @tpTestDetails CookieParam test * @tpSince RESTEasy 4.0.0 */ @Test public void testCookie() { Assert.assertEquals("cscc1|cscc2|", cookieProxy.cookieConstructorSeparatorList(list_constructor)); Assert.assertEquals("cscc1|cscc2|", cookieProxy.cookieConstructorSeparatorSet(set_constructor)); Assert.assertEquals("cscc1|cscc2|", cookieProxy.cookieConstructorSeparatorSortedSet(sortedSet_constructor)); Assert.assertEquals("cscc1|cscc2|", cookieProxy.cookieConstructorSeparatorArray(array_constructor)); Assert.assertEquals("cscc1|cscc2|", cookieProxy.cookieConstructorDefaultList(list_constructor)); Assert.assertEquals("cscc1|cscc2|", cookieProxy.cookieConstructorDefaultSet(set_constructor)); Assert.assertEquals("cscc1|cscc2|", cookieProxy.cookieConstructorDefaultSortedSet(sortedSet_constructor)); Assert.assertEquals("cscc1|cscc2|", cookieProxy.cookieConstructorDefaultArray(array_constructor)); Assert.assertEquals("vsvc1|vsvc2|", cookieProxy.cookieValueOfSeparatorList(list_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", cookieProxy.cookieValueOfSeparatorSet(set_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", cookieProxy.cookieValueOfSeparatorSortedSet(sortedSet_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", cookieProxy.cookieValueOfSeparatorArray(array_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", cookieProxy.cookieValueOfDefaultList(list_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", cookieProxy.cookieValueOfDefaultSet(set_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", cookieProxy.cookieValueOfDefaultSortedSet(sortedSet_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", cookieProxy.cookieValueOfDefaultArray(array_valueOf)); Assert.assertEquals("fsfc1|fsfc2|", cookieProxy.cookieFromStringSeparatorList(list_fromString)); Assert.assertEquals("fsfc1|fsfc2|", cookieProxy.cookieFromStringSeparatorSet(set_fromString)); Assert.assertEquals("fsfc1|fsfc2|", cookieProxy.cookieFromStringSeparatorSortedSet(sortedSet_fromString)); Assert.assertEquals("fsfc1|fsfc2|", cookieProxy.cookieFromStringSeparatorArray(array_fromString)); Assert.assertEquals("fsfc1|fsfc2|", cookieProxy.cookieFromStringDefaultList(list_fromString)); Assert.assertEquals("fsfc1|fsfc2|", cookieProxy.cookieFromStringDefaultSet(set_fromString)); Assert.assertEquals("fsfc1|fsfc2|", cookieProxy.cookieFromStringDefaultSortedSet(sortedSet_fromString)); Assert.assertEquals("fsfc1|fsfc2|", cookieProxy.cookieFromStringDefaultArray(array_fromString)); Assert.assertEquals("ppc1|ppc2|", cookieProxy.cookieParamConverterSeparatorList(list_paramConverter)); Assert.assertEquals("ppc1|ppc2|", cookieProxy.cookieParamConverterSeparatorSet(set_paramConverter)); Assert.assertEquals("ppc1|ppc2|", cookieProxy.cookieParamConverterSeparatorSortedSet(sortedSet_paramConverter)); Assert.assertEquals("ppc1|ppc2|", cookieProxy.cookieParamConverterSeparatorArray(array_paramConverter)); Assert.assertEquals("ppc1|ppc2|", cookieProxy.cookieParamConverterDefaultList(list_paramConverter)); Assert.assertEquals("ppc1|ppc2|", cookieProxy.cookieParamConverterDefaultSet(set_paramConverter)); Assert.assertEquals("ppc1|ppc2|", cookieProxy.cookieParamConverterDefaultSortedSet(sortedSet_paramConverter)); Assert.assertEquals("ppc1|ppc2|", cookieProxy.cookieParamConverterDefaultArray(array_paramConverter)); Assert.assertEquals("false|true|", cookieProxy.cookieBoolean(booleanArray)); Assert.assertEquals("0|1|", cookieProxy.cookieByte(byteArray)); Assert.assertEquals("a|z|", cookieProxy.cookieChar(charArray)); Assert.assertEquals("3|7|", cookieProxy.cookieShort(shortArray)); Assert.assertEquals("11|13|", cookieProxy.cookieInt(intArray)); Assert.assertEquals("17|19|", cookieProxy.cookieLong(longArray)); Assert.assertEquals("23.0|29.0|", cookieProxy.cookieFloat(floatArray)); Assert.assertEquals("31.0|37.0|", cookieProxy.cookieDouble(doubleArray)); } /** * @tpTestDetails HeaderParam test * @tpSince RESTEasy 4.0.0 */ @Test public void testHeader() { Assert.assertEquals("cscc1|cscc2|", headerProxy.headerConstructorSeparatorList(list_constructor)); Assert.assertEquals("cscc1|cscc2|", headerProxy.headerConstructorSeparatorSet(set_constructor)); Assert.assertEquals("cscc1|cscc2|", headerProxy.headerConstructorSeparatorSortedSet(sortedSet_constructor)); Assert.assertEquals("cscc1|cscc2|", headerProxy.headerConstructorSeparatorArray(array_constructor)); Assert.assertEquals("cscc1|cscc2|", headerProxy.headerConstructorDefaultList(list_constructor)); Assert.assertEquals("cscc1|cscc2|", headerProxy.headerConstructorDefaultSet(set_constructor)); Assert.assertEquals("cscc1|cscc2|", headerProxy.headerConstructorDefaultSortedSet(sortedSet_constructor)); Assert.assertEquals("cscc1|cscc2|", headerProxy.headerConstructorDefaultArray(array_constructor)); Assert.assertEquals("vsvc1|vsvc2|", headerProxy.headerValueOfSeparatorList(list_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", headerProxy.headerValueOfSeparatorSet(set_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", headerProxy.headerValueOfSeparatorSortedSet(sortedSet_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", headerProxy.headerValueOfSeparatorArray(array_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", headerProxy.headerValueOfDefaultList(list_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", headerProxy.headerValueOfDefaultSet(set_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", headerProxy.headerValueOfDefaultSortedSet(sortedSet_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", headerProxy.headerValueOfDefaultArray(array_valueOf)); Assert.assertEquals("fsfc1|fsfc2|", headerProxy.headerFromStringSeparatorList(list_fromString)); Assert.assertEquals("fsfc1|fsfc2|", headerProxy.headerFromStringSeparatorSet(set_fromString)); Assert.assertEquals("fsfc1|fsfc2|", headerProxy.headerFromStringSeparatorSortedSet(sortedSet_fromString)); Assert.assertEquals("fsfc1|fsfc2|", headerProxy.headerFromStringSeparatorArray(array_fromString)); Assert.assertEquals("fsfc1|fsfc2|", headerProxy.headerFromStringDefaultList(list_fromString)); Assert.assertEquals("fsfc1|fsfc2|", headerProxy.headerFromStringDefaultSet(set_fromString)); Assert.assertEquals("fsfc1|fsfc2|", headerProxy.headerFromStringDefaultSortedSet(sortedSet_fromString)); Assert.assertEquals("fsfc1|fsfc2|", headerProxy.headerFromStringDefaultArray(array_fromString)); Assert.assertEquals("hhc1|hhc2|", headerProxy.headerHeaderDelegateSeparatorList(list_headerDelegate)); Assert.assertEquals("hhc1|hhc2|", headerProxy.headerHeaderDelegateSeparatorSet(set_headerDelegate)); Assert.assertEquals("hhc1|hhc2|", headerProxy.headerHeaderDelegateSeparatorSortedSet(sortedSet_headerDelegate)); Assert.assertEquals("hhc1|hhc2|", headerProxy.headerHeaderDelegateSeparatorArray(array_headerDelegate)); Assert.assertEquals("hhc1|hhc2|", headerProxy.headerHeaderDelegateDefaultList(list_headerDelegate)); Assert.assertEquals("hhc1|hhc2|", headerProxy.headerHeaderDelegateDefaultSet(set_headerDelegate)); Assert.assertEquals("hhc1|hhc2|", headerProxy.headerHeaderDelegateDefaultSortedSet(sortedSet_headerDelegate)); Assert.assertEquals("hhc1|hhc2|", headerProxy.headerHeaderDelegateDefaultArray(array_headerDelegate)); Assert.assertEquals("ppc1|ppc2|", headerProxy.headerParamConverterSeparatorList(list_paramConverter)); Assert.assertEquals("ppc1|ppc2|", headerProxy.headerParamConverterSeparatorSet(set_paramConverter)); Assert.assertEquals("ppc1|ppc2|", headerProxy.headerParamConverterSeparatorSortedSet(sortedSet_paramConverter)); Assert.assertEquals("ppc1|ppc2|", headerProxy.headerParamConverterSeparatorArray(array_paramConverter)); Assert.assertEquals("ppc1|ppc2|", headerProxy.headerParamConverterDefaultList(list_paramConverter)); Assert.assertEquals("ppc1|ppc2|", headerProxy.headerParamConverterDefaultSet(set_paramConverter)); Assert.assertEquals("ppc1|ppc2|", headerProxy.headerParamConverterDefaultSortedSet(sortedSet_paramConverter)); Assert.assertEquals("ppc1|ppc2|", headerProxy.headerParamConverterDefaultArray(array_paramConverter)); Assert.assertEquals("false|true|", headerProxy.headerBoolean(booleanArray)); Assert.assertEquals("0|1|", headerProxy.headerByte(byteArray)); Assert.assertEquals("a|z|", headerProxy.headerChar(charArray)); Assert.assertEquals("3|7|", headerProxy.headerShort(shortArray)); Assert.assertEquals("11|13|", headerProxy.headerInt(intArray)); Assert.assertEquals("17|19|", headerProxy.headerLong(longArray)); Assert.assertEquals("23.0|29.0|", headerProxy.headerFloat(floatArray)); Assert.assertEquals("31.0|37.0|", headerProxy.headerDouble(doubleArray)); } /** * @tpTestDetails MatrixParam test * @tpSince RESTEasy 4.0.0 */ @Test public void testMatrix() { Assert.assertEquals("cscc1|cscc2|", matrixProxy.matrixConstructorSeparatorList(list_constructor)); Assert.assertEquals("cscc1|cscc2|", matrixProxy.matrixConstructorSeparatorSet(set_constructor)); Assert.assertEquals("cscc1|cscc2|", matrixProxy.matrixConstructorSeparatorSortedSet(sortedSet_constructor)); Assert.assertEquals("cscc1|cscc2|", matrixProxy.matrixConstructorSeparatorArray(array_constructor)); Assert.assertEquals("cscc1|cscc2|", matrixProxy.matrixConstructorDefaultList(list_constructor)); Assert.assertEquals("cscc1|cscc2|", matrixProxy.matrixConstructorDefaultSet(set_constructor)); Assert.assertEquals("cscc1|cscc2|", matrixProxy.matrixConstructorDefaultSortedSet(sortedSet_constructor)); Assert.assertEquals("cscc1|cscc2|", matrixProxy.matrixConstructorDefaultArray(array_constructor)); Assert.assertEquals("vsvc1|vsvc2|", matrixProxy.matrixValueOfSeparatorList(list_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", matrixProxy.matrixValueOfSeparatorSet(set_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", matrixProxy.matrixValueOfSeparatorSortedSet(sortedSet_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", matrixProxy.matrixValueOfSeparatorArray(array_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", matrixProxy.matrixValueOfDefaultList(list_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", matrixProxy.matrixValueOfDefaultSet(set_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", matrixProxy.matrixValueOfDefaultSortedSet(sortedSet_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", matrixProxy.matrixValueOfDefaultArray(array_valueOf)); Assert.assertEquals("fsfc1|fsfc2|", matrixProxy.matrixFromStringSeparatorList(list_fromString)); Assert.assertEquals("fsfc1|fsfc2|", matrixProxy.matrixFromStringSeparatorSet(set_fromString)); Assert.assertEquals("fsfc1|fsfc2|", matrixProxy.matrixFromStringSeparatorSortedSet(sortedSet_fromString)); Assert.assertEquals("fsfc1|fsfc2|", matrixProxy.matrixFromStringSeparatorArray(array_fromString)); Assert.assertEquals("fsfc1|fsfc2|", matrixProxy.matrixFromStringDefaultList(list_fromString)); Assert.assertEquals("fsfc1|fsfc2|", matrixProxy.matrixFromStringDefaultSet(set_fromString)); Assert.assertEquals("fsfc1|fsfc2|", matrixProxy.matrixFromStringDefaultSortedSet(sortedSet_fromString)); Assert.assertEquals("fsfc1|fsfc2|", matrixProxy.matrixFromStringDefaultArray(array_fromString)); Assert.assertEquals("ppc1|ppc2|", matrixProxy.matrixParamConverterSeparatorList(list_paramConverter)); Assert.assertEquals("ppc1|ppc2|", matrixProxy.matrixParamConverterSeparatorSet(set_paramConverter)); Assert.assertEquals("ppc1|ppc2|", matrixProxy.matrixParamConverterSeparatorSortedSet(sortedSet_paramConverter)); Assert.assertEquals("ppc1|ppc2|", matrixProxy.matrixParamConverterSeparatorArray(array_paramConverter)); Assert.assertEquals("ppc1|ppc2|", matrixProxy.matrixParamConverterDefaultList(list_paramConverter)); Assert.assertEquals("ppc1|ppc2|", matrixProxy.matrixParamConverterDefaultSet(set_paramConverter)); Assert.assertEquals("ppc1|ppc2|", matrixProxy.matrixParamConverterDefaultSortedSet(sortedSet_paramConverter)); Assert.assertEquals("ppc1|ppc2|", matrixProxy.matrixParamConverterDefaultArray(array_paramConverter)); Assert.assertEquals("false|true|", matrixProxy.matrixBoolean(booleanArray)); Assert.assertEquals("0|1|", matrixProxy.matrixByte(byteArray)); Assert.assertEquals("a|z|", matrixProxy.matrixChar(charArray)); Assert.assertEquals("3|7|", matrixProxy.matrixShort(shortArray)); Assert.assertEquals("11|13|", matrixProxy.matrixInt(intArray)); Assert.assertEquals("17|19|", matrixProxy.matrixLong(longArray)); Assert.assertEquals("23.0|29.0|", matrixProxy.matrixFloat(floatArray)); Assert.assertEquals("31.0|37.0|", matrixProxy.matrixDouble(doubleArray)); } /** * @tpTestDetails PathParam test * @tpSince RESTEasy 4.0.0 */ @Test public void testPath() { Assert.assertEquals("cscc1|cscc2|", pathProxy.pathConstructorSeparatorList(list_constructor)); Assert.assertEquals("cscc1|cscc2|", pathProxy.pathConstructorSeparatorSet(set_constructor)); Assert.assertEquals("cscc1|cscc2|", pathProxy.pathConstructorSeparatorSortedSet(sortedSet_constructor)); Assert.assertEquals("cscc1|cscc2|", pathProxy.pathConstructorSeparatorArray(array_constructor)); Assert.assertEquals("cscc1|cscc2|", pathProxy.pathConstructorDefaultList(list_constructor)); Assert.assertEquals("cscc1|cscc2|", pathProxy.pathConstructorDefaultSet(set_constructor)); Assert.assertEquals("cscc1|cscc2|", pathProxy.pathConstructorDefaultSortedSet(sortedSet_constructor)); Assert.assertEquals("cscc1|cscc2|", pathProxy.pathConstructorDefaultArray(array_constructor)); Assert.assertEquals("vsvc1|vsvc2|", pathProxy.pathValueOfSeparatorList(list_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", pathProxy.pathValueOfSeparatorSet(set_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", pathProxy.pathValueOfSeparatorSortedSet(sortedSet_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", pathProxy.pathValueOfSeparatorArray(array_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", pathProxy.pathValueOfDefaultList(list_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", pathProxy.pathValueOfDefaultSet(set_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", pathProxy.pathValueOfDefaultSortedSet(sortedSet_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", pathProxy.pathValueOfDefaultArray(array_valueOf)); Assert.assertEquals("fsfc1|fsfc2|", pathProxy.pathFromStringSeparatorList(list_fromString)); Assert.assertEquals("fsfc1|fsfc2|", pathProxy.pathFromStringSeparatorSet(set_fromString)); Assert.assertEquals("fsfc1|fsfc2|", pathProxy.pathFromStringSeparatorSortedSet(sortedSet_fromString)); Assert.assertEquals("fsfc1|fsfc2|", pathProxy.pathFromStringSeparatorArray(array_fromString)); Assert.assertEquals("fsfc1|fsfc2|", pathProxy.pathFromStringDefaultList(list_fromString)); Assert.assertEquals("fsfc1|fsfc2|", pathProxy.pathFromStringDefaultSet(set_fromString)); Assert.assertEquals("fsfc1|fsfc2|", pathProxy.pathFromStringDefaultSortedSet(sortedSet_fromString)); Assert.assertEquals("fsfc1|fsfc2|", pathProxy.pathFromStringDefaultArray(array_fromString)); Assert.assertEquals("ppc1|ppc2|", pathProxy.pathParamConverterSeparatorList(list_paramConverter)); Assert.assertEquals("ppc1|ppc2|", pathProxy.pathParamConverterSeparatorSet(set_paramConverter)); Assert.assertEquals("ppc1|ppc2|", pathProxy.pathParamConverterSeparatorSortedSet(sortedSet_paramConverter)); Assert.assertEquals("ppc1|ppc2|", pathProxy.pathParamConverterSeparatorArray(array_paramConverter)); Assert.assertEquals("ppc1|ppc2|", pathProxy.pathParamConverterDefaultList(list_paramConverter)); Assert.assertEquals("ppc1|ppc2|", pathProxy.pathParamConverterDefaultSet(set_paramConverter)); Assert.assertEquals("ppc1|ppc2|", pathProxy.pathParamConverterDefaultSortedSet(sortedSet_paramConverter)); Assert.assertEquals("ppc1|ppc2|", pathProxy.pathParamConverterDefaultArray(array_paramConverter)); Assert.assertEquals("false|true|", pathProxy.pathBoolean(booleanArray)); Assert.assertEquals("0|1|", pathProxy.pathByte(byteArray)); Assert.assertEquals("a|z|", pathProxy.pathChar(charArray)); Assert.assertEquals("3|7|", pathProxy.pathShort(shortArray)); Assert.assertEquals("11|13|", pathProxy.pathInt(intArray)); Assert.assertEquals("17|19|", pathProxy.pathLong(longArray)); Assert.assertEquals("23.0|29.0|", pathProxy.pathFloat(floatArray)); Assert.assertEquals("31.0|37.0|", pathProxy.pathDouble(doubleArray)); } /** * @tpTestDetails QueryParam test * @tpSince RESTEasy 4.0.0 */ @Test public void testQuery() { Assert.assertEquals("cscc1|cscc2|", queryProxy.queryConstructorSeparatorList(list_constructor)); Assert.assertEquals("cscc1|cscc2|", queryProxy.queryConstructorSeparatorSet(set_constructor)); Assert.assertEquals("cscc1|cscc2|", queryProxy.queryConstructorSeparatorSortedSet(sortedSet_constructor)); Assert.assertEquals("cscc1|cscc2|", queryProxy.queryConstructorSeparatorArray(array_constructor)); Assert.assertEquals("cscc1|cscc2|", queryProxy.queryConstructorDefaultList(list_constructor)); Assert.assertEquals("cscc1|cscc2|", queryProxy.queryConstructorDefaultSet(set_constructor)); Assert.assertEquals("cscc1|cscc2|", queryProxy.queryConstructorDefaultSortedSet(sortedSet_constructor)); Assert.assertEquals("cscc1|cscc2|", queryProxy.queryConstructorDefaultArray(array_constructor)); Assert.assertEquals("vsvc1|vsvc2|", queryProxy.queryValueOfSeparatorList(list_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", queryProxy.queryValueOfSeparatorSet(set_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", queryProxy.queryValueOfSeparatorSortedSet(sortedSet_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", queryProxy.queryValueOfSeparatorArray(array_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", queryProxy.queryValueOfDefaultList(list_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", queryProxy.queryValueOfDefaultSet(set_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", queryProxy.queryValueOfDefaultSortedSet(sortedSet_valueOf)); Assert.assertEquals("vsvc1|vsvc2|", queryProxy.queryValueOfDefaultArray(array_valueOf)); Assert.assertEquals("fsfc1|fsfc2|", queryProxy.queryFromStringSeparatorList(list_fromString)); Assert.assertEquals("fsfc1|fsfc2|", queryProxy.queryFromStringSeparatorSet(set_fromString)); Assert.assertEquals("fsfc1|fsfc2|", queryProxy.queryFromStringSeparatorSortedSet(sortedSet_fromString)); Assert.assertEquals("fsfc1|fsfc2|", queryProxy.queryFromStringSeparatorArray(array_fromString)); Assert.assertEquals("fsfc1|fsfc2|", queryProxy.queryFromStringDefaultList(list_fromString)); Assert.assertEquals("fsfc1|fsfc2|", queryProxy.queryFromStringDefaultSet(set_fromString)); Assert.assertEquals("fsfc1|fsfc2|", queryProxy.queryFromStringDefaultSortedSet(sortedSet_fromString)); Assert.assertEquals("fsfc1|fsfc2|", queryProxy.queryFromStringDefaultArray(array_fromString)); Assert.assertEquals("ppc1|ppc2|", queryProxy.queryParamConverterSeparatorList(list_paramConverter)); Assert.assertEquals("ppc1|ppc2|", queryProxy.queryParamConverterSeparatorSet(set_paramConverter)); Assert.assertEquals("ppc1|ppc2|", queryProxy.queryParamConverterSeparatorSortedSet(sortedSet_paramConverter)); Assert.assertEquals("ppc1|ppc2|", queryProxy.queryParamConverterSeparatorArray(array_paramConverter)); Assert.assertEquals("ppc1|ppc2|", queryProxy.queryParamConverterDefaultList(list_paramConverter)); Assert.assertEquals("ppc1|ppc2|", queryProxy.queryParamConverterDefaultSet(set_paramConverter)); Assert.assertEquals("ppc1|ppc2|", queryProxy.queryParamConverterDefaultSortedSet(sortedSet_paramConverter)); Assert.assertEquals("ppc1|ppc2|", queryProxy.queryParamConverterDefaultArray(array_paramConverter)); Assert.assertEquals("false|true|", queryProxy.queryBoolean(booleanArray)); Assert.assertEquals("0|1|", queryProxy.queryByte(byteArray)); Assert.assertEquals("a|z|", queryProxy.queryChar(charArray)); Assert.assertEquals("3|7|", queryProxy.queryShort(shortArray)); Assert.assertEquals("11|13|", queryProxy.queryInt(intArray)); Assert.assertEquals("17|19|", queryProxy.queryLong(longArray)); Assert.assertEquals("23.0|29.0|", queryProxy.queryFloat(floatArray)); Assert.assertEquals("31.0|37.0|", queryProxy.queryDouble(doubleArray)); } /** * @tpTestDetails * @tpSince RESTEasy 4.0.0 * @tpTestCaseDetails This test verifies that MultiValuedParamConverterProvider does not engage on the * client side if @Separator has an inappropriate value. */ @Test public void testMiscellaneous() { Set set = new HashSet(); set.add("p1"); set.add("p2"); Assert.assertTrue(miscProxy.regexClientCookie(set).contains("[p1, p2]")); Assert.assertTrue(miscProxy.regexClientHeader(set).contains("p1,p2")); Assert.assertTrue(miscProxy.regexClientMatrix(set).contains("p=p1;p=p2")); Assert.assertTrue(miscProxy.regexClientPath(set).contains("%5Bp1,%20p2%5D")); Assert.assertTrue(miscProxy.regexClientQuery(set).contains("p=p1&p=p2")); } } polarnik/gatling /* * Copyright 2011-2019 GatlingCorp (https://gatling.io) * * 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 io.gatling.http.client.body.multipart.impl; import static io.gatling.http.client.util.MiscUtils.*; import io.gatling.http.client.Param; import io.gatling.http.client.body.multipart.Part; import io.gatling.http.client.body.multipart.impl.PartVisitor.*; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import java.io.Closeable; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.GatheringByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.util.List; import static java.nio.charset.StandardCharsets.US_ASCII; public abstract class PartImpl implements Closeable { /** * Content disposition as a byte */ static final byte QUOTE_BYTE = '\"'; /** * Carriage return/linefeed as a byte array */ static final byte[] CRLF_BYTES = "\r\n".getBytes(US_ASCII); /** * Extra characters as a byte array */ static final byte[] EXTRA_BYTES = "--".getBytes(US_ASCII); /** * Content disposition as a byte array */ private static final byte[] CONTENT_DISPOSITION_BYTES = "Content-Disposition: ".getBytes(US_ASCII); /** * form-data as a byte array */ private static final byte[] FORM_DATA_DISPOSITION_TYPE_BYTES = "form-data".getBytes(US_ASCII); /** * name as a byte array */ private static final byte[] NAME_BYTES = "; name=".getBytes(US_ASCII); /** * Content type header as a byte array */ private static final byte[] CONTENT_TYPE_BYTES = "Content-Type: ".getBytes(US_ASCII); /** * Content charset as a byte array */ private static final byte[] CHARSET_BYTES = "; charset=".getBytes(US_ASCII); /** * Content type header as a byte array */ private static final byte[] CONTENT_TRANSFER_ENCODING_BYTES = "Content-Transfer-Encoding: ".getBytes(US_ASCII); /** * Content type header as a byte array */ private static final byte[] HEADER_NAME_VALUE_SEPARATOR_BYTES = ": ".getBytes(US_ASCII); /** * Content type header as a byte array */ private static final byte[] CONTENT_ID_BYTES = "Content-ID: ".getBytes(US_ASCII); protected final Part part; protected final byte[] boundary; private final int preContentLength; private final int postContentLength; protected PartImplState state; boolean slowTarget; // lazy private ByteBuf preContentBuffer; private ByteBuf postContentBuffer; PartImpl(Part part, byte[] boundary) { this.part = part; this.boundary = boundary; preContentLength = computePreContentLength(); postContentLength = computePostContentLength(); state = PartImplState.PRE_CONTENT; } public long length() { return preContentLength + postContentLength + getContentLength(); } public PartImplState getState() { return state; } boolean isTargetSlow() { return slowTarget; } public void copyInto(ByteBuf target) throws IOException { switch (state) { case DONE: return; case PRE_CONTENT: copyInto(lazyLoadPreContentBuffer(), target, PartImplState.CONTENT); return; case CONTENT: copyContentInto(target); return; case POST_CONTENT: copyInto(lazyLoadPostContentBuffer(), target, PartImplState.DONE); return; default: throw new IllegalStateException("Unknown state " + state); } } public long transferTo(WritableByteChannel target) throws IOException { slowTarget = false; switch (state) { case DONE: return 0L; case PRE_CONTENT: return transferTo(lazyLoadPreContentBuffer(), target, PartImplState.CONTENT); case CONTENT: return transferContentTo(target); case POST_CONTENT: return transferTo(lazyLoadPostContentBuffer(), target, PartImplState.DONE); default: throw new IllegalStateException("Unknown state " + state); } } private ByteBuf lazyLoadPreContentBuffer() { if (preContentBuffer == null) preContentBuffer = computePreContentBytes(preContentLength); return preContentBuffer; } private ByteBuf lazyLoadPostContentBuffer() { if (postContentBuffer == null) postContentBuffer = computePostContentBytes(postContentLength); return postContentBuffer; } @Override public void close() { if (preContentBuffer != null) { preContentBuffer.release(); } if (postContentBuffer != null) { postContentBuffer.release(); } } protected abstract long getContentLength(); protected abstract void copyContentInto(ByteBuf target) throws IOException; protected abstract long transferContentTo(WritableByteChannel target) throws IOException; void copyInto(ByteBuf source, ByteBuf target, PartImplState sourceFullyWrittenState) { int sourceRemaining = source.readableBytes(); int targetRemaining = target.writableBytes(); if (sourceRemaining <= targetRemaining) { target.writeBytes(source); state = sourceFullyWrittenState; } else { target.writeBytes(source, targetRemaining); } } long transferTo(ByteBuf source, WritableByteChannel target, PartImplState sourceFullyWrittenState) throws IOException { int transferred = 0; if (target instanceof GatheringByteChannel) { transferred = source.readBytes((GatheringByteChannel) target, source.readableBytes()); } else { for (ByteBuffer byteBuffer : source.nioBuffers()) { int len = byteBuffer.remaining(); int written = target.write(byteBuffer); transferred += written; if (written != len) { // couldn't write full buffer, exit loop break; } } // assume this is a basic single ByteBuf source.readerIndex(source.readerIndex() + transferred); } if (source.isReadable()) { slowTarget = true; } else { state = sourceFullyWrittenState; } return transferred; } protected int computePreContentLength() { CounterPartVisitor counterVisitor = new CounterPartVisitor(); visitPreContent(counterVisitor); return counterVisitor.getCount(); } protected ByteBuf computePreContentBytes(int preContentLength) { ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(preContentLength); ByteBufVisitor bytesVisitor = new ByteBufVisitor(buffer); visitPreContent(bytesVisitor); return buffer; } protected int computePostContentLength() { CounterPartVisitor counterVisitor = new CounterPartVisitor(); visitPostContent(counterVisitor); return counterVisitor.getCount(); } protected ByteBuf computePostContentBytes(int postContentLength) { ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer(postContentLength); ByteBufVisitor bytesVisitor = new ByteBufVisitor(buffer); visitPostContent(bytesVisitor); return buffer; } private void visitStart(PartVisitor visitor) { visitor.withBytes(EXTRA_BYTES); visitor.withBytes(boundary); } protected void visitContentDispositionHeader(PartVisitor visitor) { visitor.withBytes(CRLF_BYTES); visitor.withBytes(CONTENT_DISPOSITION_BYTES); visitor.withBytes(part.getDispositionType() != null ? part.getDispositionType().getBytes(US_ASCII) : FORM_DATA_DISPOSITION_TYPE_BYTES); if (part.getName() != null) { visitor.withBytes(NAME_BYTES); visitor.withByte(QUOTE_BYTE); visitor.withBytes(part.getName().getBytes(US_ASCII)); visitor.withByte(QUOTE_BYTE); } } private void visitContentTypeHeader(PartVisitor visitor) { String contentType = part.getContentType(); if (contentType != null) { visitor.withBytes(CRLF_BYTES); visitor.withBytes(CONTENT_TYPE_BYTES); visitor.withBytes(contentType.getBytes(US_ASCII)); Charset charSet = part.getCharset(); if (charSet != null) { visitor.withBytes(CHARSET_BYTES); visitor.withBytes(part.getCharset().name().getBytes(US_ASCII)); } } } private void visitTransferEncodingHeader(PartVisitor visitor) { String transferEncoding = part.getTransferEncoding(); if (transferEncoding != null) { visitor.withBytes(CRLF_BYTES); visitor.withBytes(CONTENT_TRANSFER_ENCODING_BYTES); visitor.withBytes(transferEncoding.getBytes(US_ASCII)); } } private void visitContentIdHeader(PartVisitor visitor) { String contentId = part.getContentId(); if (contentId != null) { visitor.withBytes(CRLF_BYTES); visitor.withBytes(CONTENT_ID_BYTES); visitor.withBytes(contentId.getBytes(US_ASCII)); } } private void visitCustomHeaders(PartVisitor visitor) { if (isNonEmpty(part.getCustomHeaders())) { List customHeaders = part.getCustomHeaders(); for (Param param : customHeaders) { visitor.withBytes(CRLF_BYTES); visitor.withBytes(param.getName().getBytes(US_ASCII)); visitor.withBytes(HEADER_NAME_VALUE_SEPARATOR_BYTES); visitor.withBytes(param.getValue().getBytes(US_ASCII)); } } } private void visitEndOfHeaders(PartVisitor visitor) { visitor.withBytes(CRLF_BYTES); visitor.withBytes(CRLF_BYTES); } private void visitPreContent(PartVisitor visitor) { visitStart(visitor); visitContentDispositionHeader(visitor); visitContentTypeHeader(visitor); visitTransferEncodingHeader(visitor); visitContentIdHeader(visitor); visitCustomHeaders(visitor); visitEndOfHeaders(visitor); } private void visitPostContent(PartVisitor visitor) { visitor.withBytes(CRLF_BYTES); } } package gov.healthit.chpl.changerequest.validation; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import gov.healthit.chpl.changerequest.domain.ChangeRequest; import gov.healthit.chpl.changerequest.domain.ChangeRequestAttestation; import gov.healthit.chpl.changerequest.domain.ChangeRequestStatus; import gov.healthit.chpl.changerequest.domain.ChangeRequestStatusType; import gov.healthit.chpl.changerequest.domain.ChangeRequestType; import gov.healthit.chpl.domain.Developer; public class ChangeRequestModificationValidationTest { private ChangeRequestModificationValidation validator; @Before public void setup() { validator = Mockito.spy(ChangeRequestModificationValidation.class); } @Test public void isValid_NewStatusAdded_ReturnTrueWithNoErrors() { ChangeRequestValidationContext context = ChangeRequestValidationContext.builder() .origChangeRequest(ChangeRequest.builder() .id(1L) .changeRequestType(ChangeRequestType.builder() .id(3L) .name("Developer Attestation Change Request") .build()) .developer(new Developer()) .currentStatus(ChangeRequestStatus.builder() .changeRequestStatusType(ChangeRequestStatusType.builder() .id(1L) .name("Pending ONC-ACB Action") .build()) .build()) .details(ChangeRequestAttestation.builder() .attestation("TEST_ATTESTATION") .build()) .build()) .newChangeRequest(ChangeRequest.builder() .id(1L) .changeRequestType(ChangeRequestType.builder() .id(3L) .name("Developer Attestation Change Request") .build()) .developer(new Developer()) .currentStatus(ChangeRequestStatus.builder() .changeRequestStatusType(ChangeRequestStatusType.builder() .id(3L) .name("Accepted") .build()) .build()) .details(ChangeRequestAttestation.builder() .attestation("TEST_ATTESTATION_UPDATED") .build()) .build()) .build(); Boolean isValid = validator.isValid(context); assertEquals(true, isValid); assertEquals(0, validator.getMessages().size()); } @Test public void isValid_ChangeRequestDetailsUpdated_ReturnTrueWithNoErrors() { ChangeRequestValidationContext context = ChangeRequestValidationContext.builder() .origChangeRequest(ChangeRequest.builder() .id(1L) .changeRequestType(ChangeRequestType.builder() .id(3L) .name("Developer Attestation Change Request") .build()) .developer(new Developer()) .currentStatus(ChangeRequestStatus.builder() .changeRequestStatusType(ChangeRequestStatusType.builder() .id(1L) .name("Pending ONC-ACB Action") .build()) .build()) .details(ChangeRequestAttestation.builder() .attestation("TEST_ATTESTATION") .build()) .build()) .newChangeRequest(ChangeRequest.builder() .id(1L) .changeRequestType(ChangeRequestType.builder() .id(3L) .name("Developer Attestation Change Request") .build()) .developer(new Developer()) .currentStatus(ChangeRequestStatus.builder() .changeRequestStatusType(ChangeRequestStatusType.builder() .id(1L) .name("Pending ONC-ACB Action") .build()) .build()) .details(ChangeRequestAttestation.builder() .attestation("TEST_ATTESTATION_UPDATED") .build()) .build()) .build(); Boolean isValid = validator.isValid(context); assertEquals(true, isValid); assertEquals(0, validator.getMessages().size()); } @Test public void isValid_ChangeRequestDetailsNoChanged_ReturnFalseWith1Error() { ChangeRequestValidationContext context = ChangeRequestValidationContext.builder() .origChangeRequest(ChangeRequest.builder() .id(1L) .changeRequestType(ChangeRequestType.builder() .id(3L) .name("Developer Attestation Change Request") .build()) .developer(new Developer()) .currentStatus(ChangeRequestStatus.builder() .changeRequestStatusType(ChangeRequestStatusType.builder() .id(1L) .name("Pending ONC-ACB Action") .build()) .build()) .details(ChangeRequestAttestation.builder() .attestation("TEST_ATTESTATION") .build()) .build()) .newChangeRequest(ChangeRequest.builder() .id(1L) .changeRequestType(ChangeRequestType.builder() .id(3L) .name("Developer Attestation Change Request") .build()) .developer(new Developer()) .currentStatus(ChangeRequestStatus.builder() .changeRequestStatusType(ChangeRequestStatusType.builder() .id(1L) .name("Pending ONC-ACB Action") .build()) .build()) .details(ChangeRequestAttestation.builder() .attestation("TEST_ATTESTATION") .build()) .build()) .build(); Boolean isValid = validator.isValid(context); assertEquals(false, isValid); assertEquals(1, validator.getMessages().size()); } } nintha/vproxy package vproxyapp.controller; import java.util.ArrayList; import java.util.List; import java.util.Map; public interface DockerNetworkDriver { void createNetwork(CreateNetworkRequest req) throws Exception; void deleteNetwork(String networkId) throws Exception; CreateEndpointResponse createEndpoint(CreateEndpointRequest req) throws Exception; void deleteEndpoint(String networkId, String endpointId) throws Exception; JoinResponse join(String networkId, String endpointId, String sandboxKey) throws Exception; void leave(String networkId, String endpointId) throws Exception; class CreateNetworkRequest { public String networkId; public List ipv4Data; public List ipv6Data; @Override public String toString() { return "CreateNetworkRequest{" + "networkId='" + networkId + '\'' + ", ipv4Data=" + ipv4Data + ", ipv6Data=" + ipv6Data + '}'; } } class IPData { public String addressSpace; public String pool; public String gateway; public Map auxAddresses; // nullable String __transformedGateway; @Override public String toString() { return "IPData{" + "addressSpace='" + addressSpace + '\'' + ", pool='" + pool + '\'' + ", gateway='" + gateway + '\'' + ", auxAddresses=" + auxAddresses + '}'; } } class CreateEndpointRequest { public String networkId; public String endpointId; public NetInterface netInterface; // nullable @Override public String toString() { return "CreateEndpointRequest{" + "networkId='" + networkId + '\'' + ", endpointId='" + endpointId + '\'' + ", netInterface=" + netInterface + '}'; } } class NetInterface { public String address; public String addressIPV6; public String macAddress; @Override public String toString() { return "NetInterface{" + "address='" + address + '\'' + ", addressIPV6='" + addressIPV6 + '\'' + ", macAddress='" + macAddress + '\'' + '}'; } } class CreateEndpointResponse { public NetInterface netInterface; // nullable @Override public String toString() { return "CreateEndpointResponse{" + "netInterface=" + netInterface + '}'; } } class JoinResponse { public InterfaceName interfaceName = new InterfaceName(); public String gateway; public String gatewayIPv6; public List staticRoutes = new ArrayList<>(); @Override public String toString() { return "JoinResponse{" + "interfaceName=" + interfaceName + ", gateway='" + gateway + '\'' + ", gatewayIPv6='" + gatewayIPv6 + '\'' + ", staticRoutes=" + staticRoutes + '}'; } } class InterfaceName { public String srcName; public String dstPrefix; @Override public String toString() { return "InterfaceName{" + "srcName='" + srcName + '\'' + ", dstPrefix='" + dstPrefix + '\'' + '}'; } } class StaticRoute { public String destination; public int routeType; // 0: nextHop, 1: connected(no value for nextHop) public String nextHop; @Override public String toString() { return "StaticRoute{" + "destination='" + destination + '\'' + ", routeType=" + routeType + ", nextHop='" + nextHop + '\'' + '}'; } } } 1-10 package controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import pojo.Page; import pojo.User; import service.UserService; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.List; @Controller public class Query { @Autowired private UserService userService; //页面跳转功能,同时可以刷新 @RequestMapping(value = "/onpage", method = RequestMethod.GET) public ModelAndView onpage(Integer pageNo){ ModelAndView one = new ModelAndView(); if (pageNo != null && pageNo > 0){ int pageSize = 20;//每页20行数据 int Start = (pageNo - 1) * 20; List dd = userService.selectAll(Start,pageSize);//返回数据库中的数据 one.addObject("dd", dd); one.setViewName("second"); return one; } return new ModelAndView("second"); } @RequestMapping(value = "/increase", method = RequestMethod.GET)//用户增加界面 public ModelAndView insert(User user) { long timeStamp = System.currentTimeMillis(); //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据) SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");//这个是你要转成后的时间的格式 String sd = sdf.format(new Date(timeStamp)); // 时间戳转换成时间 // System.out.println(sd);//打印出你要的时间 user.setCreateat(sd); user.setUpdateat(sd); ModelAndView anm = new ModelAndView(); System.out.printf(String.valueOf(user)); User ll = userService.insert(user); anm.setViewName("second");//返回操作界面 return anm; } } 0 package com.qcy.userservice.entity; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.Date; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** *

* *

* * @author CodeHunter_qcy * @since 2020-06-20 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @ApiModel(value="Orders对象", description="") public class Orders implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "oid", type = IdType.ID_WORKER_STR) private String oid; @TableField(fill = FieldFill.INSERT_UPDATE) private LocalDateTime time; private String bid; private BigDecimal total; private Integer state; private String tel; private String address; } package io.github.strikerrocker.vt.tweaks.silkspawner; import io.github.strikerrocker.vt.VanillaTweaks; import io.github.strikerrocker.vt.base.Feature; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Items; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.Enchantments; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.block.SpawnerBlock; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.SpawnerBlockEntity; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.ForgeConfigSpec; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; public class SilkSpawner extends Feature { private static final String SPAWNER_TAG = "SilkSpawnerData"; private ForgeConfigSpec.BooleanValue enableSilkSpawner; @Override public void setupConfig(ForgeConfigSpec.Builder builder) { enableSilkSpawner = builder .translation("config.vanillatweaks:enableSilkSpawner") .comment("Want the ability to move spawners with silk touch?") .define("enableSilkSpawner", true); } @Override public boolean usesEvents() { return true; } /** * Handles spawner block entity placement */ @SubscribeEvent public void onBlockPlaced(BlockEvent.EntityPlaceEvent event) { if (event.getEntity() instanceof Player player) { ItemStack stack = player.getItemInHand(player.getUsedItemHand()); if (enableSilkSpawner.get() && !stack.isEmpty() && stack.hasTag() && stack.getItem() == Items.SPAWNER) { CompoundTag spawnerDataNBT = stack.getOrCreateTag().getCompound(SPAWNER_TAG); if (!spawnerDataNBT.isEmpty()) { BlockEntity tile = event.getWorld().getBlockEntity(event.getPos()); if (tile instanceof SpawnerBlockEntity spawnerBlockEntity) { spawnerBlockEntity.getSpawner().load(player.level, event.getPos(), spawnerDataNBT); } } } } } /** * Handles Spawner break logic */ @SubscribeEvent(priority = EventPriority.HIGHEST) public void onBreak(BlockEvent.BreakEvent event) { Level level = event.getPlayer().level; BlockEntity blockEntity = level.getBlockEntity(event.getPos()); int lvl = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, event.getPlayer().getMainHandItem()); if (event.getState().getBlock() instanceof SpawnerBlock && !level.isClientSide() && blockEntity instanceof SpawnerBlockEntity && enableSilkSpawner.get() && lvl >= 1) { event.setExpToDrop(0); ItemStack drop = new ItemStack(Blocks.SPAWNER); CompoundTag spawnerData = ((SpawnerBlockEntity) blockEntity).getSpawner().save(blockEntity.getLevel(), event.getPos(), new CompoundTag()); CompoundTag stackTag = new CompoundTag(); spawnerData.remove("Delay"); stackTag.put(SPAWNER_TAG, spawnerData); drop.setTag(stackTag); Block.popResource(event.getPlayer().level, event.getPos(), drop); level.removeBlockEntity(blockEntity.getBlockPos()); level.destroyBlock(event.getPos(), false); event.setCanceled(true); } } @Mod.EventBusSubscriber(modid = VanillaTweaks.MOD_ID, value = Dist.CLIENT) public static class ClientEvents { /** * Shows the name of the mob in tooltip */ @SubscribeEvent public static void onToolTipEvent(ItemTooltipEvent event) { ItemStack stack = event.getItemStack(); if (stack.hasTag()) { CompoundTag spawnerDataNBT = stack.getOrCreateTag().getCompound(SPAWNER_TAG); if (!spawnerDataNBT.isEmpty()) { DummySpawnerLogic.DUMMY_SPAWNER_LOGIC.load(event.getEntity().level, BlockPos.ZERO, spawnerDataNBT); Entity ent = DummySpawnerLogic.DUMMY_SPAWNER_LOGIC.getOrCreateDisplayEntity(event.getEntity().level); if (ent != null) { event.getToolTip().add(ent.getDisplayName()); } } } } } }school-engagements/pikatersrc/org/pikater/core/options/computing/ZeroRCA_Box.java package org.pikater.core.options.computing; import org.pikater.core.agents.experiment.computing.Agent_ZeroRCA; import org.pikater.core.ontology.subtrees.agentinfo.AgentInfo; import org.pikater.core.ontology.subtrees.batchdescription.ComputingAgent; import org.pikater.core.options.OptionsHelper; import org.pikater.core.options.SlotsHelper; public class ZeroRCA_Box { public static AgentInfo get() { AgentInfo agentInfo = new AgentInfo(); agentInfo.importAgentClass(Agent_ZeroRCA.class); agentInfo.importOntologyClass(ComputingAgent.class); agentInfo.setName("ZeroR"); agentInfo.setDescription("Zero R Method"); agentInfo.addOptions(OptionsHelper.getCAOptions()); // Slots Definition agentInfo.setInputSlots(SlotsHelper.getInputSlots_CA()); agentInfo.setOutputSlots(SlotsHelper.getOutputSlots_CA()); return agentInfo; } } // https://leetcode.com/problems/length-of-last-word class Solution { public int lengthOfLastWord(String s) { int lastWordLength = 0; if (!s.isEmpty() && !s.contains(" ")) { lastWordLength = s.length(); return lastWordLength; } String[] words = s.split(" "); for (int i = words.length-1; i >= 0; --i) { String word = words[i]; if (!word.contains(" ")) { lastWordLength = word.length(); break; } } return lastWordLength; } } 0 package io.quarkus.elytron.security.runtime; import java.util.Map; import io.quarkus.runtime.annotations.ConfigGroup; import io.quarkus.runtime.annotations.ConfigItem; /** * Configuration information used to populate a {@linkplain org.wildfly.security.auth.realm.SimpleMapBackedSecurityRealm} * } */ @ConfigGroup public class MPRealmConfig { /** * The authentication mechanism */ @ConfigItem(defaultValue = "Quarkus") public String realmName; /** * If the embedded store is enabled. */ @ConfigItem public boolean enabled; /** The realm users user1=password\nuser2=password2... mapping */ @ConfigItem public Map users; /** The realm roles user1=role1,role2,...\nuser2=role1,role2,... mapping */ @ConfigItem public Map roles; public String getRealmName() { return realmName; } public void setRealmName(String realmName) { this.realmName = realmName; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Map getUsers() { return users; } public void setUsers(Map users) { this.users = users; } public Map getRoles() { return roles; } public void setRoles(Map roles) { this.roles = roles; } @Override public String toString() { return "MPRealmConfig{" + ", realmName='" + realmName + '\'' + ", enabled=" + enabled + ", users=" + users + ", roles=" + roles + '}'; } } package blue.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import blue.model.Cliente; import blue.repository.helper.ClientesQueries; public interface Clientes extends JpaRepository, ClientesQueries { public Optional findByCpfOuCnpj(String cpfOuCnpj); } package nextstep.subway.section; import io.restassured.RestAssured; import io.restassured.response.ExtractableResponse; import io.restassured.response.Response; import nextstep.subway.AcceptanceTest; import nextstep.subway.line.LineAcceptanceTest; import nextstep.subway.line.dto.LineResponse; import nextstep.subway.station.StationAcceptanceTest; import nextstep.subway.station.dto.StationResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; import static org.assertj.core.api.Assertions.assertThat; @DisplayName("지하철 노선 구간 관련 기능") public class SectionAcceptanceTest extends AcceptanceTest { private StationResponse 상행역; private StationResponse 강남역; private StationResponse 양재역; private StationResponse 정자역; private StationResponse 미금역; private StationResponse 광교역; private StationResponse 하행역; private LineResponse 신분당선; @BeforeEach public void setUp() { super.setUp(); 상행역 = StationAcceptanceTest.지하철역_등록되어_있음("상행역").as(StationResponse.class); 강남역 = StationAcceptanceTest.지하철역_등록되어_있음("강남역").as(StationResponse.class); 양재역 = StationAcceptanceTest.지하철역_등록되어_있음("양재역").as(StationResponse.class); 정자역 = StationAcceptanceTest.지하철역_등록되어_있음("정자역").as(StationResponse.class); 미금역 = StationAcceptanceTest.지하철역_등록되어_있음("미금역").as(StationResponse.class); 광교역 = StationAcceptanceTest.지하철역_등록되어_있음("광교역").as(StationResponse.class); 하행역 = StationAcceptanceTest.지하철역_등록되어_있음("하행역").as(StationResponse.class); Map createParams = LineAcceptanceTest.지하철_노선_더미_데이터_신분상선(강남역.getId(), 광교역.getId(), 10); 신분당선 = LineAcceptanceTest.지하철_노선_등록되어_있음(createParams).as(LineResponse.class); } @DisplayName("노선에 구간을 등록한다.") @Test void addSection() { // when // 지하철_노선에_지하철역_등록_요청 ExtractableResponse registerSectionResponse1 = 지하철_노선에_지하철역_등록_요청(신분당선.getId(), 상행역.getId(), 강남역.getId(), 10); ExtractableResponse registerSectionResponse2 = 지하철_노선에_지하철역_등록_요청(신분당선.getId(), 강남역.getId(), 정자역.getId(), 7); ExtractableResponse registerSectionResponse3 = 지하철_노선에_지하철역_등록_요청(신분당선.getId(), 미금역.getId(), 광교역.getId(), 2); ExtractableResponse registerSectionResponse4 = 지하철_노선에_지하철역_등록_요청(신분당선.getId(), 강남역.getId(), 양재역.getId(), 2); // 지하철_노선에_조회 ExtractableResponse lineResponse = LineAcceptanceTest.지하철_노선_조회(registerSectionResponse2.header("Location")); // then // 지하철_노선에_지하철역_등록됨 Stream.of(registerSectionResponse1, registerSectionResponse2, registerSectionResponse3, registerSectionResponse4) .forEach(i -> 상태코드_확인(i, HttpStatus.CREATED.value())); assertThat(lineResponse.statusCode()).isEqualTo(HttpStatus.OK.value()); 라인에_역들이_순서대로_나오는지_확인(lineResponse, 상행역.getName(), 강남역.getName(), 양재역.getName(), 정자역.getName(), 미금역.getName(), 광교역.getName()); } @DisplayName("노선에 구간을 등록한다. - 새로운 역을 상행 종점으로 등록") @Test void addSection_새로운_역을_상행_종점으로_등록() { // when // 지하철_노선에_지하철역_등록_요청 ExtractableResponse registerSectionResponse = 지하철_노선에_지하철역_등록_요청(신분당선.getId(), 상행역.getId(), 강남역.getId(), 10); // 지하철_노선에_조회 ExtractableResponse lineResponse = LineAcceptanceTest.지하철_노선_조회(registerSectionResponse.header("Location")); // then // 지하철_노선에_지하철역_등록됨 assertThat(registerSectionResponse.statusCode()).isEqualTo(HttpStatus.CREATED.value()); assertThat(lineResponse.statusCode()).isEqualTo(HttpStatus.OK.value()); assertThat(lineResponse.jsonPath().getList("stations", StationResponse.class).get(0).getName()).isEqualTo(상행역.getName()); assertThat(lineResponse.jsonPath().getList("stations", StationResponse.class).get(1).getName()).isEqualTo(강남역.getName()); assertThat(lineResponse.jsonPath().getList("stations", StationResponse.class).get(2).getName()).isEqualTo(광교역.getName()); } @DisplayName("노선에 구간을 등록한다. - 새로운 역을 하행 종점으로 등록할 경우") @Test void addSection_새로운_역을_하행_종점으로_등록() { // when // 지하철_노선에_지하철역_등록_요청 ExtractableResponse registerSectionResponse = 지하철_노선에_지하철역_등록_요청(신분당선.getId(), 광교역.getId(), 하행역.getId(), 10); // 지하철_노선에_조회 ExtractableResponse lineResponse = LineAcceptanceTest.지하철_노선_조회(registerSectionResponse.header("Location")); // then // 지하철_노선에_지하철역_등록됨 assertThat(registerSectionResponse.statusCode()).isEqualTo(HttpStatus.CREATED.value()); assertThat(lineResponse.statusCode()).isEqualTo(HttpStatus.OK.value()); assertThat(lineResponse.jsonPath().getList("stations", StationResponse.class).get(0).getName()).isEqualTo(강남역.getName()); assertThat(lineResponse.jsonPath().getList("stations", StationResponse.class).get(1).getName()).isEqualTo(광교역.getName()); assertThat(lineResponse.jsonPath().getList("stations", StationResponse.class).get(2).getName()).isEqualTo(하행역.getName()); } @DisplayName("노선에 구간을 등록한다. - 역 사이에 새로운 역을 등록할 경우 기존 역 사이 길이보다 크거나 같으면 등록을 할 수 없음") @Test void addSectionException_역_사이_길이보다_크거나_같은_경우() { // when // 지하철_노선에_지하철역_등록_요청 ExtractableResponse response = 지하철_노선에_지하철역_등록_요청(신분당선.getId(), 강남역.getId(), 정자역.getId(), 10); // then // 지하철_노선에_지하철역_등록됨 assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value()); } @DisplayName("노선에 구간을 등록한다. - 상행역과 하행역이 이미 노선에 모두 등록되어 있다면 추가할 수 없음") @Test void addSectionException_이미_노선에_모두_등록되어_있는_경우() { // when // 지하철_노선에_지하철역_등록_요청 ExtractableResponse response = 지하철_노선에_지하철역_등록_요청(신분당선.getId(), 강남역.getId(), 광교역.getId(), 10); // then // 지하철_노선에_지하철역_등록됨 assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value()); } @DisplayName("노선에 구간을 등록한다. - 상행역과 하행역 둘 중 하나도 포함되어있지 않으면 추가할 수 없음") @Test void addSectionException_상행역과_하행역_둘_중_하나도_포함되어있지_않은_경우() { // when // 지하철_노선에_지하철역_등록_요청 ExtractableResponse response = 지하철_노선에_지하철역_등록_요청(신분당선.getId(), 정자역.getId(), 미금역.getId(), 10); // then // 지하철_노선에_지하철역_등록됨 assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST.value()); } public static ExtractableResponse 지하철_노선에_지하철역_등록_요청(Long lineId, Long upStationId, Long downStationId, Integer distance) { Map params = new HashMap<>(); params.put("upStationId", upStationId + ""); params.put("downStationId", downStationId + ""); params.put("distance", distance + ""); return RestAssured.given().log().all() .body(params) .contentType(MediaType.APPLICATION_JSON_VALUE) .when() .post("/lines/" + lineId + "/sections") .then().log().all() .extract(); } private void 라인에_역들이_순서대로_나오는지_확인(ExtractableResponse lineResponse, String... 역이름) { for (int i = 0; i < 역이름.length; i++) { assertThat(lineResponse.jsonPath().getList("stations", StationResponse.class).get(i).getName()).isEqualTo(역이름[i]); } } private void 상태코드_확인(ExtractableResponse response, int httpStatusValue) { assertThat(response.statusCode()).isEqualTo(httpStatusValue); } } mzhg/PostProcessingWork package jet.opengl.renderer.Unreal4.distancefield; import org.lwjgl.util.vector.Vector4f; import jet.opengl.renderer.Unreal4.TextureBuffer; import jet.opengl.postprocessing.common.GLenum; public class FDistanceFieldCulledObjectBuffers { public static int ObjectDataStride; public static int ObjectBoxBoundsStride; public boolean bWantBoxBounds; public int MaxObjects; public final TextureBuffer ObjectIndirectArguments = new TextureBuffer(); public final TextureBuffer ObjectIndirectDispatch = new TextureBuffer(); public final TextureBuffer Bounds = new TextureBuffer(); public final TextureBuffer Data = new TextureBuffer(); public final TextureBuffer BoxBounds = new TextureBuffer(); public FDistanceFieldCulledObjectBuffers() { MaxObjects = 0; bWantBoxBounds = false; } void Initialize() { if (MaxObjects > 0) { final int FastVRamFlag = 0 ;//GFastVRamConfig.DistanceFieldCulledObjectBuffers | ( IsTransientResourceBufferAliasingEnabled() ? BUF_Transient : BUF_None ); final int PF_R32_UINT = GLenum.GL_R32UI; ObjectIndirectArguments.Initialize(/*sizeof(uint32)*/4, 5, PF_R32_UINT, 0/*BUF_Static | BUF_DrawIndirect*/); ObjectIndirectDispatch.Initialize(/*sizeof(uint32)*/4, 3, PF_R32_UINT, 0/*BUF_Static | BUF_DrawIndirect*/); Bounds.Initialize(/*sizeof(FVector4)*/Vector4f.SIZE, MaxObjects, GLenum.GL_RGBA32F/*BUF_Static | FastVRamFlag, TEXT("FDistanceFieldCulledObjectBuffers::Bounds")*/); Data.Initialize(/*sizeof(FVector4)*/Vector4f.SIZE, MaxObjects * ObjectDataStride,GLenum.GL_RGBA32F/* BUF_Static | FastVRamFlag, TEXT("FDistanceFieldCulledObjectBuffers::Data")*/); if (bWantBoxBounds) { BoxBounds.Initialize(/*sizeof(FVector4)*/Vector4f.SIZE, MaxObjects * ObjectBoxBoundsStride, GLenum.GL_RGBA32F/*BUF_Static | FastVRamFlag, TEXT("FDistanceFieldCulledObjectBuffers::BoxBounds")*/); } } } /*void AcquireTransientResource() { Bounds.AcquireTransientResource(); Data.AcquireTransientResource(); if (bWantBoxBounds) { BoxBounds.AcquireTransientResource(); } } void DiscardTransientResource() { Bounds.DiscardTransientResource(); Data.DiscardTransientResource(); if (bWantBoxBounds) { BoxBounds.DiscardTransientResource(); } }*/ public void Release() { ObjectIndirectArguments.Release(); ObjectIndirectDispatch.Release(); Bounds.Release(); Data.Release(); BoxBounds.Release(); } public int GetSizeBytes() { return ObjectIndirectArguments.NumBytes + ObjectIndirectDispatch.NumBytes + Bounds.NumBytes + Data.NumBytes + BoxBounds.NumBytes; } } src/main/java/com/comlib/server/service/CommunityService.java package com.comlib.server.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.comlib.server.dao.CommunityDao; import com.comlib.server.entity.Community; @Service public class CommunityService { @Autowired CommunityDao communityDao; public CommunityService() { super(); } private static final Logger log = LoggerFactory.getLogger(CommunityService.class); public void addNewCommunity() { log.info("Inside add new community"); Community community = new Community("Aparna Cyberlife", "Nallagandla", "Hyderabad", "500019", ""); communityDao.add(community); } } /* * (c) Copyright , Germany. All rights reserved. Contact: . * * Created on 06.05.2014 */ package net.finmath.experiments.concurrency; import java.util.stream.IntStream; /** * This is a test of Java 8 parallel streams. * * We are testing nested parallel forEach loops, which appear to * have unexpected poor performance in Java 1.8.0u5. * * We have a nested stream.parallel().forEach(): * * The inner loop is independent (stateless, no interference, etc. - except of the use of a common pool) * and consumes 1 second in total in the worst case, namely if processed sequential. * Half of the tasks of the outer loop consume 10 seconds prior that loop. * Half consume 10 seconds after that loop. * We have a boolean which allows to switch the inner loop from parallel() to sequential(). * Hence every thread consumes 11 seconds (worst case) in total. * Now: submitting 24 outer-loop-tasks to a pool of 8 we would expect 24/8 * 11 = 33 seconds at best (on an 8 core or better machine). * * The result is: * - With inner sequential loop: 33 seconds. * - With inner parallel loop: >80 seconds (I had 92 seconds). * * Now, there is a funny workaround. The method * wraps every operation in its own thread. Use this to wrap the inner loop in its * own thread via * {@code * wrapInThread( () -> * IntStream.range(0,numberOfTasksInInnerLoop).parallel().forEach(j -> { * burnTime(10); * })); * } * And the performance issue is gone. Note that this does not introduce any new * parallelism and that the inner loop tasks are still submitted to the same * common fork-join pool. * * The reason, why this fix works, is because the inner loop is started form a Thread * and not from possible ForkJoinWorkerThread of the outer loop. In the latter case * the ForkJoinTask by mistake assumes that the starting thread is a worker of itself * and issues a join, effectively joining inner loop tasks with outer loop tasks. * * @author */ public class NestedParallelForEachTest { // The program uses 33 sec with this boolean to false and around 80+ with this boolean true: private final boolean isInnerStreamParallel = true; // Setup: Inner loop task 0.01 sec in worse case. Outer loop task: 10 sec + inner loop. This setup: (100 * 0.01 sec + 10 sec) * 24/8 = 33 sec. private final int numberOfTasksInOuterLoop = 24; // In real applications this can be a large number (e.g. > 1000). private final int numberOfTasksInInnerLoop = 100; // In real applications this can be a large number (e.g. > 1000). private final int concurrentExecutionsLimitForStreams = 8; // java.util.concurrent.ForkJoinPool.common.parallelism // For those, who do not trust the use of Thread.sleep(). private final boolean isCPUTimeBurned = false; // Set to true, if you like a true loop, and not Thread.sleep() private final long cpuTimeBurningCountPerMillis = 800000; // You might need to calibrate this for your machine public static void main(String[] args) { (new NestedParallelForEachTest()).testNestedLoops(); } public void testNestedLoops() { final long start = System.currentTimeMillis(); System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism",Integer.toString(concurrentExecutionsLimitForStreams)); System.out.println("java.util.concurrent.ForkJoinPool.common.parallelism = " + System.getProperty("java.util.concurrent.ForkJoinPool.common.parallelism")); // Outer loop IntStream.range(0,numberOfTasksInOuterLoop).parallel().forEach(i -> { try { if(i < 10) { burnTime(10 * 1000); } System.out.println(i + "\t" + Thread.currentThread()); if(isInnerStreamParallel) { // Inner loop as parallel: worst case (sequential) it takes 10 * numberOfTasksInInnerLoop millis IntStream.range(0,numberOfTasksInInnerLoop).parallel().forEach(j -> { burnTime(10); }); } else { // Inner loop as sequential IntStream.range(0,numberOfTasksInInnerLoop).sequential().forEach(j -> { burnTime(10); }); } if(i >= 10) { burnTime(10 * 1000); } } catch (final Exception e) { e.printStackTrace(); } }); final long end = System.currentTimeMillis(); System.out.println("Done in " + (end-start)/1000 + " sec."); } private double burnTime(long millis) { if(isCPUTimeBurned) { double x = 0; for(long i=0; iocharv/sopra-fs19-group13-serversrc/main/java/ch/uzh/ifi/seal/soprafs19/repository/UserRepository.java package ch.uzh.ifi.seal.soprafs19.repository; import ch.uzh.ifi.seal.soprafs19.entity.User; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository("userRepository") public interface UserRepository extends CrudRepository { //javacode that gets translated into sql queries User findByUsername(String username); User findByToken(String token); } package org.twak.tweed.gen; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.vecmath.Matrix4d; import javax.vecmath.Point2d; import javax.vecmath.Point3d; import javax.vecmath.Vector2d; import javax.vecmath.Vector3d; import org.apache.commons.math3.ml.clustering.Cluster; import org.apache.commons.math3.ml.clustering.Clusterable; import org.apache.commons.math3.ml.clustering.DBSCANClusterer; import org.twak.tweed.Tweed; import org.twak.tweed.TweedSettings; import org.twak.utils.Cache; import org.twak.utils.Line; import org.twak.utils.Mathz; import org.twak.utils.PaintThing; import org.twak.utils.PaintThing.ICanPaintU; import org.twak.utils.Pair; import org.twak.utils.PanMouseAdaptor; import org.twak.utils.collections.Arrayz; import org.twak.utils.collections.ConsecutiveItPairs; import org.twak.utils.collections.ConsecutivePairs; import org.twak.utils.geom.Line3d; import org.twak.utils.geom.LinearForm; import org.twak.utils.geom.LinearForm3D; import org.twak.utils.geom.ObjRead; import org.twak.utils.streams.InAxDoubleArray; import org.twak.utils.ui.Rainbow; import org.twak.viewTrace.Bin; import org.twak.viewTrace.FindLines; import org.twak.viewTrace.ObjSlice; import org.twak.viewTrace.SliceParameters; import org.twak.viewTrace.SuperLine; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.scene.Geometry; import com.jme3.scene.Mesh; import com.jme3.scene.Node; import com.jme3.scene.VertexBuffer; public class Prof extends ArrayList { private final static Vector3d UP = new Vector3d( 0, 1, 0 ); Matrix4d toFlat, to3d; Vector3d dir; double finalStart = Double.MAX_VALUE; double finalAngle = Double.MAX_VALUE; private Prof clean; static { PaintThing.lookup.put( Prof.class, new ICanPaintU() { @Override public void paint( Object o, Graphics2D g, PanMouseAdaptor ma ) { Prof p = (Prof) o; for ( Pair line : new ConsecutivePairs<>( p, false ) ) { // g.setColor( Color.black ); g.drawLine( ma.toX( line.first().x ), ma.toY( -line.first().y ), ma.toX( line.second().x ), ma.toY( -line.second().y ) ); PaintThing.setBounds( line.first() ); // g.setColor( Color.red ); // for ( Point2d s : new Point2d[] { line.first(), line.second() } ) { // g.fillOval( ma.toX( s.x ) - 4, ma.toY( -s.y ) - 4, 8, 8 ); // } } } } ); } public Prof() { Matrix4d i = new Matrix4d(); i.setIdentity(); this.toFlat = this.to3d = i; this.dir = new Vector3d( 1, 0, 0 ); } public Prof( Matrix4d toFlat, Vector3d dir3 ) { this.toFlat = toFlat; this.to3d = new Matrix4d(); to3d.invert( toFlat ); this.dir = dir3; } public Prof( Prof p ) { super( p ); // shallow copy! this.toFlat = new Matrix4d( p.toFlat ); this.to3d = new Matrix4d( p.to3d ); this.dir = new Vector3d( p.dir ); } public static Prof buildProfile( ObjRead mesh, Line3d oLine, Point3d cen, double minH, double maxH, double minD, double maxD, Tweed tweed, Node dbg ) { Prof monotonic = buildProfile( oLine, cen ); Vector3d dir = oLine.dir(); dir.normalize(); Vector3d sliceNormal = new Vector3d( dir.x, 0, dir.z ); LinearForm3D lf = new LinearForm3D( sliceNormal, cen ); List lines = ObjSlice.sliceTri( mesh, lf, 0.5, new Vector3d( -dir.z, 0, dir.x ), Math.PI / 2 + 0.1 ); // dbg.attachChild( Jme3z.lines( tweed, lines, ColorRGBA.Blue, 2 ) ); Line3d first = null; double closestStart = Double.MAX_VALUE; for ( Line3d l : lines ) { if ( l.start.y > l.end.y ) l.reverse(); double dist = l.distanceSquared( cen ); if ( dist < closestStart ) { closestStart = dist; first = l; } } if ( first == null ) { return null; // lines.clear(); // monotonic.add( cen ); // monotonic.add( new Point3d( cen.x, cen.y - 500, cen.z ) ); } else { climb( lines, first, monotonic, maxH, true ); climb( lines, first, monotonic, minH, false ); } { double tol = 0.2; minD -= tol; maxD += tol; LinearForm min = new LinearForm( Mathz.UP ).findC( new Point2d( minD, 0 ) ); LinearForm max = new LinearForm( Mathz.UP ).findC( new Point2d( maxD, 0 ) ); for ( int i = 0; i < monotonic.size() - 1; i++ ) { Point2d a = monotonic.get( i ), b = monotonic.get( i + 1 ); if ( a.x < minD && b.x < minD ) { monotonic.remove( i ); i--; } else if ( a.x < minD ) { monotonic.set( i, new LinearForm( new Line( a, b ) ).intersect( min ) ); } else if ( b.x < minD ) { monotonic.set( i + 1, new LinearForm( new Line( a, b ) ).intersect( min ) ); b.x = minD + Math.ulp( minD ); } if ( a.x > maxD && b.x > maxD ) { monotonic.remove( i ); i--; } else if ( a.x > maxD ) { monotonic.set( i, new LinearForm( new Line( a, b ) ).intersect( max ) ); } else if ( b.x > maxD ) { monotonic.set( i + 1, new LinearForm( new Line( a, b ) ).intersect( max ) ); b.x = maxD - Math.ulp( maxD ); } } } return monotonic; } public static Prof buildProfile( Line3d oLine, Point3d cen ) { Matrix4d to2D = new Matrix4d(); Vector3d c2 = oLine.dir(), c3 = new Vector3d(); c2.normalize(); c3.cross( c2, UP ); to2D.setIdentity(); to2D.setRow( 0, c3.x, c3.y, c3.z, 0 ); to2D.setRow( 1, UP.x, UP.y, UP.z, 0 ); to2D.setRow( 2, c2.x, c2.y, c2.z, 0 ); { Point3d start = new Point3d( cen.x, 0, cen.z ); to2D.transform( start ); to2D.m03 = -start.x; to2D.m13 = -start.y; to2D.m23 = -start.z; to2D.m33 = 1; } Prof monotonic = new Prof( to2D, c2 ); return monotonic; } public static Prof retarget( Prof p, SuperLine profileLine ) { Line3d l = new Line3d( Pointz.to3( profileLine ) ); Prof out = buildProfile( new Line3d( Pointz.to3( profileLine ) ), l.closestPointOn( p.to3d( p.get( 0 ) ), false ) ); for ( Point2d p2 : p ) out.add( p.to3d( p2 ) ); return out; } interface BetterThan { public boolean betterThan( double h1, double h2 ); public boolean betterThanOrEqualTo( double h1, double h2 ); } private static void climb( List lines, Line3d first, Prof monotonic, double max, boolean isUp ) { Point3d end = isUp ? highestEnd( first ) : lowestEnd( first ), extrema = end; monotonic.add( isUp ? monotonic.size() : 0, end ); Map ends = new IdentityHashMap(); BetterThan bt = new BetterThan() { @Override public boolean betterThan( double h1, double h2 ) { return isUp ? h1 > h2 : h1 < h2; } @Override public boolean betterThanOrEqualTo( double h1, double h2 ) { return isUp ? h1 >= h2 : h1 <= h2; } }; Line3d next = null; boolean worseThanExtrema = false; double BIG_JUMP = TweedSettings.settings.meshHoleJumpSize; do { double bestDist = 1; int startOrEnd = -1; next = null; for ( Line3d l : lines ) { if ( ( bt.betterThan( l.end.y, extrema.y ) || bt.betterThan( l.start.y, extrema.y ) ) && !ends.containsKey( l ) ) { for ( int i = 0; i < 2; i++ ) { double dist = l.points()[ i ].distance( worseThanExtrema ? extrema : end ); if ( dist < bestDist ) { bestDist = dist; startOrEnd = i; next = l; } } } } if ( next == null ) { bestDist = BIG_JUMP; // nothing strictly montonic, try near...limit search to near extrema (balcony width) for ( Line3d l : lines ) { if ( !ends.containsKey( l ) ) { for ( int i = 0; i < 2; i++ ) { double dist = l.points()[ i ].distance( extrema ); if ( dist < bestDist ) { // bestDist = dist; startOrEnd = i; next = l; } } } } } if ( next != null ) { ends.put( next, next ); end = next.points()[ 1 - startOrEnd ]; if ( bt.betterThanOrEqualTo( end.y, extrema.y ) ) { if ( worseThanExtrema ) { // add intermediate point double angle = next.angle( UP ); if ( angle < Math.PI / 2 - 0.2 || angle > Math.PI / 2 + 0.2 ) { // intersecting with horizontal lines is messy. Point3d pt = new LinearForm3D( UP, extrema ).collide( end, next.dir(), next.length() ); if ( bt.betterThan( max, pt.y ) ) monotonic.add( isUp ? monotonic.size() : 0, pt ); } } extrema = end; Point3d toAdd = end; if ( bt.betterThan( end.y, max ) ) { // trim to max toAdd = new LinearForm3D( UP, new Vector3d( 0, max, 0 ) ).collide( next.points()[ startOrEnd ], next.dir(), next.length() ); if (toAdd == null) continue; if ( toAdd.getClass() != Point3d.class && bt.betterThan( max, toAdd.y ) ) // intersection failed toAdd = new Point3d( end.x, max, end.z ); else toAdd = null; next = null; } if ( toAdd != null ) monotonic.add( isUp ? monotonic.size() : 0, toAdd ); worseThanExtrema = false; } else worseThanExtrema = true; } } while ( next != null ); } private static Point3d highestEnd( Line3d c ) { return c.start.y > c.end.y ? c.start : c.end; } private static Point3d lowestEnd( Line3d c ) { return c.start.y < c.end.y ? c.start : c.end; } public boolean add( Point3d pt ) { return super.add( to2d( pt ) ); } public void add( int pos, Point3d pt ) { super.add( pos, to2d( pt ) ); } public Point2d to2d( Point3d pt ) { Point3d tmp = new Point3d(); toFlat.transform( pt, tmp ); return new Point2d( tmp.x, tmp.y ); } public Point3d to3d( Point2d pt ) { Point3d out = new Point3d( pt.x, pt.y, 0 ); to3d.transform( out ); return out; } public List get3D() { return this.stream().map( x -> to3d( x ) ).collect( Collectors.toList() ); } public double distance( Prof other, boolean union, // union or just range of other boolean extendThis, boolean extendOther ) // do we extend or penalize when out of range? { double meanFit = 0; int norm = 0; int t = 0, o = 0; if ( size() < 2 || other.size() < 2 ) throw new Error(); double h = union ? Math.min( other.get( 0 ).y, this.get( 0 ).y ) : other.get( 0 ).y, delta = 0.1; h = Math.max( 0, h ); double penalty = 10 * 10; if ( get( 0 ).y > other.get( other.size() - 1 ).y || get( size() - 1 ).y < other.get( 0 ).y ) return penalty; boolean overT = false, overO = false; while ( true ) { while ( h > get( t + 1 ).y ) { t++; if ( t >= size() - 1 ) { overT = true; t = size() - 2; break; } } while ( h > other.get( o + 1 ).y ) { o++; if ( o >= other.size() - 1 ) { overO = true; o = other.size() - 2; break; } } if ( !union && overO || overT && overO ) break; if ( !extendOther && overO || !extendThis && overT ) meanFit += penalty; else { Line tl = new Line( get( t ), get( t + 1 ) ), ol = new Line( other.get( o ), other.get( o + 1 ) ); double tx = tl.xAtY( h ), ox = ol.xAtY( h ); tx = Math.min( 0, tx ); ox = Math.min( 0, ox ); meanFit += ( Math.pow( tl.absAngle( ol ) * 2, 2 ) + Math.pow( tx - ox, 2 ) ) * delta * ( 1 / tl.aTan2() ); } norm++; h += delta; } return norm == 0 ? penalty : meanFit / norm; } public Prof parameterize() { // find and subtract vertical lines Set lines = new HashSet<>(); for ( int i = 1; i < size(); i++ ) lines.add( new Line( get( i - 1 ), get( i ) ) ); double avgMinY = get( 0 ).y; SliceParameters P = new SliceParameters( 5 ); P.FL_REGRESS = false; P.FL_BINS = 20; double A = 0.4; // simple = 0.4 double B = 1; // simple = 1; lines = new FindLines( lines, P ) { protected double nextAngle( Set remaining, int iteration ) { double delta = Math.PI / P.FL_BINS; Bin aBin = new Bin( -Math.PI - delta, Math.PI + delta, P.FL_BINS * 2, true ); // angle bin for ( Line l : remaining ) { double len = l.length(); double angle = l.aTan2(); aBin.add( angle, len, l ); } // if (iteration < 1) // return MUtils.PI2; if ( iteration < 1 && aBin.getWeight( Mathz.PI2 ) >= 5 ) return Mathz.PI2; int aBinI = aBin.maxI(); return aBin.val( aBinI ); } protected double getTolNearLine( Point2d p ) { return P.FL_NEAR_LINE * ( p.y < avgMinY + 5 ? 5 : B ); }; protected double getTolNearLine2( Point2d p ) { return P.FL_NEAR_LINE_2 * ( p.y < avgMinY + 5 ? 10 : B ); }; }.result.all; clean = new Prof( this ); clean.clear(); if ( lines.isEmpty() ) { clean.add( new Point2d( 0, 0 ) ); clean.add( new Point2d( 0, 1 ) ); return clean; } List llines = new ArrayList( lines ); llines.stream().filter( l -> l.start.y > l.end.y ).forEach( l -> l.reverseLocal() ); Collections.sort( llines, new Comparator() { public int compare( Line o1, Line o2 ) { return Double.compare( o1.start.y + o1.end.y, o2.start.y + o2.end.y ); }; } ); for ( int i = 0; i < llines.size(); i++ ) { Line l = llines.get( i ); double angle = l.aTan2(); if ( angle < Mathz.PI2 + 0.1 && angle > Mathz.PI2 - 0.4 ) llines.set( i, FindLines.rotateToAngle( l, l.fromPPram( 0.5 ), Mathz.PI2 ) ); } Line bottomLine = llines.get( 0 ); llines.add( 0, new Line( new Point2d( bottomLine.start.x, get( 0 ).y ), new Point2d( bottomLine.start.x, get( 0 ).y ) ) ); double lastY = -Double.MAX_VALUE, lastX = Double.MAX_VALUE; for ( Line l : llines ) { boolean startAbove = l.start.y >= lastY && l.start.x <= lastX, endAbove = l.end.y >= lastY && l.end.x <= lastX; if ( startAbove && endAbove ) { clean.add( l.start ); clean.add( l.end ); } else if ( !startAbove && endAbove ) {// || (startAbove && !endAbove) ) { if ( l.start.y < lastY ) { Point2d sec = new LinearForm( new Vector2d( 1, 0 ) ).findC( new Point2d( 0, lastY ) ).intersect( new LinearForm( l ) ); if ( sec != null ) l.start = sec; } if ( l.start.x > lastX ) { Point2d sec = new LinearForm( new Vector2d( 0, 1 ) ).findC( new Point2d( lastX, 0 ) ).intersect( new LinearForm( l ) ); if ( sec != null ) l.start = sec; } if ( l.end.distanceSquared( l.start ) < 100 ) clean.add( l.start ); clean.add( l.end ); } else { Vector2d dir = l.dir(); if ( Math.abs( dir.x ) > Math.abs( dir.y ) ) { LinearForm x = new LinearForm( new Vector2d( 1, 0 ) ).findC( new Point2d( 0, lastY ) ); l.start = x.project( l.start ); l.end = x.project( l.end ); l.start.x = Math.min( l.start.x, lastX ); l.end.x = Math.min( l.end.x, lastX ); } else { LinearForm y = new LinearForm( new Vector2d( 0, 1 ) ).findC( new Point2d( lastX, 0 ) ); l.start = y.project( l.start ); l.end = y.project( l.end ); l.start.y = Math.max( l.start.y, lastY ); l.end.y = Math.max( l.end.y, lastY ); } clean.add( l.start ); clean.add( l.end ); } lastY = l.end.y; lastX = l.end.x; } clean.clean( 0.2 ); return clean; } public static Prof parameterize( List in // all profs from a single profile-edge are in the same 2D space, with strange x-origin ) { // double toProfileEdge; // { // Prof eg = in.iterator().next(); // Point3d p = Pointz.to3( profileEdge.start ); // toProfileEdge = eg.to2d( p ).x; // } double avgMinY = in.stream().filter( p -> p != null ).mapToDouble( p -> p.get( 0 ).y ).average().getAsDouble(); Set lines = new HashSet<>(); for ( Prof p : in ) for ( int i = 1; i < p.size(); i++ ) lines.add( new Line( p.get( i - 1 ), p.get( i ) ) ); SliceParameters P = new SliceParameters( 5 ); P.FL_REGRESS = true; P.FL_BINS = 20; // double A = 0.4; // simple = 0.4 // double B = 0.1; // simple = 1; double A = 0.2; // simple = 0.4 double B = 0.3; // simple = 0.1; double C = 0.1; // simple = 0.1; rotate threshold, radians double firstFloorHeight = 2; P.MIN_LINES = Math.max( 1, in.size() * A ); lines = new FindLines( lines, P ) { protected double nextAngle( Set remaining, int iteration ) { double delta = Math.PI / P.FL_BINS; Bin aBin = new Bin( -Math.PI - delta, Math.PI + delta, P.FL_BINS * 2, true ); // angle bin for ( Line l : remaining ) { double len = l.length(); double angle = l.aTan2(); aBin.add( angle, len, l ); } // if (iteration < 1) // return MUtils.PI2; if ( iteration < 1 && aBin.getWeight( Mathz.PI2 ) >= 10 ) return Mathz.PI2; int aBinI = aBin.maxI(); return aBin.val( aBinI ); } protected double getTolNearLine( Point2d p ) { return P.FL_NEAR_LINE * ( p.y < avgMinY + firstFloorHeight ? 5 : B ); }; protected double getTolNearLine2( Point2d p ) { return P.FL_NEAR_LINE_2 * ( p.y < avgMinY + firstFloorHeight ? 10 : B ); }; protected double getTolRemoveAngle( Line l ) { return l.start.y < avgMinY + firstFloorHeight ? Math.PI * 0.5 : Math.PI * 0.2; }; }.result.all; List llines = lines.stream().filter( l -> l.lengthSquared() > 0.001 ). // is rubbish filter( l -> l.end.y > avgMinY + 1 || Math.abs( l.start.y - l.end.y ) > 0.1 ). // is floor polygon collect( Collectors.toList() ); Prof clean = new Prof( in.get( in.size() / 2 ) ); clean.clear(); if ( llines.isEmpty() ) { clean.add( new Point2d( 0, 0 ) ); clean.add( new Point2d( 0, 1 ) ); return clean; } for ( int i = 0; i < llines.size(); i++ ) { Line l = llines.get( i ); double angle = l.aTan2(); if ( angle < Mathz.PI2 + C && angle > Mathz.PI2 - C ) llines.set( i, FindLines.rotateToAngle( l, l.fromPPram( 0.5 ), Mathz.PI2 ) ); } Collections.sort( llines, new Comparator() { public int compare( Line o1, Line o2 ) { return Double.compare( o1.fromPPram( 0.2 ).y, o2.fromPPram( 0.2 ).y ); }; } ); Line lastL = null; Point2d lastP = new Point2d( 0, -Double.MAX_VALUE ); for ( Line l : llines ) { Point2d mid = l.fromPPram( 0.5 ); if ( !( lastL != null && !lastL.isOnLeft( mid ) || ( lastP.y == -Double.MAX_VALUE || ( mid.y >= lastP.y - 0.5 && mid.x <= lastP.x + 0.5 ) ) ) ) continue; boolean startAbove = l.start.y >= lastP.y && l.start.x <= lastP.x, endAbove = l.end.y >= lastP.y && l.end.x <= lastP.x; if ( l.end.y < l.start.y ) l.end.y = l.start.y; if ( startAbove && endAbove ) { // okay } else { if ( lastL != null && l.start.distanceSquared( lastP ) < 9 ) { Point2d sec = lastL.intersects( l, false ); if ( sec != null && sec.distanceSquared( lastP ) < 9 && sec.x <= lastL.start.x && sec.y >= lastL.start.y ) { clean.remove( clean.size() - 1 ); clean.add( sec ); lastP = sec; l.start = sec; } else if ( l.start.x < lastP.x ) { sec = new LinearForm( new Vector2d( 1, 0 ) ).findC( l.start ).intersect( new LinearForm( lastL ) ); if ( sec != null && sec.distanceSquared( lastP ) < 9 ) { clean.remove( clean.size() - 1 ); clean.add( sec ); lastP = sec; } } } if ( l.start.x > lastP.x + 0.01 || l.end.x > lastP.x + 0.01 ) { Point2d sec = new LinearForm( new Vector2d( 0, 1 ) ).findC( new Point2d( lastP.x, 0 ) ).intersect( new LinearForm( l ) ); if ( sec != null && sec.distanceSquared( lastP ) < 9 && sec.distanceSquared( l.start ) < 9 ) { if ( l.start.x > lastP.x ) l.start = sec; else l.end = sec; } } } // if (lastL != null) { // Line t = new Line (lastL); // PaintThing.debug( new Color(170,255,0), 2f, new Line( t.start.x+2.5, -t.start.y, t.end.x+2.5, -t.end.y ) ); // } if ( lastL != null && l.start.distanceSquared( lastP ) < 4 ) { Point2d sec = lastL.intersects( l, false ); if ( sec != null && ( sec.distanceSquared( lastP ) < 4 || Math.abs( sec.y - lastP.y ) < 1 ) && sec.x <= lastL.start.x && sec.y >= lastL.start.y ) { clean.remove( clean.size() - 1 ); clean.add( sec ); lastP = sec; l.start = sec; } else if ( l.start.x < lastP.x ) { sec = new LinearForm( new Vector2d( 1, 0 ) ).findC( l.start ).intersect( new LinearForm( lastL ) ); if ( sec != null && ( sec.distanceSquared( lastP ) < 4 || Math.abs( sec.y - lastP.y ) < 1 ) ) { clean.remove( clean.size() - 1 ); clean.add( sec ); lastP = sec; // l.start = sec; } } } if ( lastP.y - l.end.y < 3 && l.end.x - lastP.x < 3 ) { for ( Point2d pt : l.points() ) { pt.x = Math.min( pt.x, lastP.x ); pt.y = Math.max( pt.y, lastP.y ); } if ( !l.start.equals( l.end ) ) for ( Point2d pt : l.points() ) { // if (c == 2) // PaintThing.debug.put(1, new Point2d ( pt.x, -pt.y ) ); pt = new Point2d( pt ); pt.x = Math.min( pt.x, lastP.x ); pt.y = Mathz.max( 0, pt.y, lastP.y ); if ( clean.isEmpty() && pt.y > 0.2 ) { clean.add( new Point2d( pt.x, 0 ) ); } if ( lastP != null && pt.distanceSquared( lastP ) > 0.02 ) { clean.add( pt ); } lastP = clean.get( clean.size() - 1 ); if ( clean.size() >= 3 ) { Point2d a = clean.get( clean.size() - 1 ), b = clean.get( clean.size() - 2 ), c = clean.get( clean.size() - 3 ); if ( Math.abs( Mathz.area( c, b, a ) ) < 0.1 || Mathz.absAngleBetween( a, b, c ) < 0.1 ) clean.remove( clean.size() - 2 ); } } } if ( clean.size() >= 2 ) lastL = new Line( clean.get( clean.size() - 2 ), clean.get( clean.size() - 1 ) ); } // clean.clean( 0.05 ); return clean; } private Prof clean( double areaTol ) { for ( int i = 2; i < size(); i++ ) { Point2d a = get( i - 2 ), b = get( i - 1 ), c = get( i ); if ( Math.abs( Mathz.area( a, b, c ) ) < areaTol ) { remove( i - 1 ); i--; } } return this; } public void render( Tweed tweed, Node gNode, ColorRGBA color, float width ) { Mesh m = new Mesh(); m.setMode( Mesh.Mode.Lines ); List coords = new ArrayList(); List inds = new ArrayList(); for ( Pair p : new ConsecutiveItPairs<>( get3D() ) ) { inds.add( inds.size() ); inds.add( inds.size() ); coords.add( (float) p.first().x ); coords.add( (float) p.first().y ); coords.add( (float) p.first().z ); coords.add( (float) p.second().x ); coords.add( (float) p.second().y ); coords.add( (float) p.second().z ); } m.setBuffer( VertexBuffer.Type.Position, 3, Arrayz.toFloatArray( coords ) ); m.setBuffer( VertexBuffer.Type.Index, 2, Arrayz.toIntArray( inds ) ); Geometry geom = new Geometry( "profile", m ); Material lineMaterial = new Material( tweed.getAssetManager(), "Common/MatDefs/Misc/Unshaded.j3md" ); lineMaterial.getAdditionalRenderState().setLineWidth( Math.max( 1f, width ) ); lineMaterial.setColor( "Color", color == null ? ColorRGBA.Blue : color ); geom.setMaterial( lineMaterial ); geom.updateGeometricState(); geom.updateModelBound(); gNode.attachChild( geom ); } public Mesh renderStrip( double width, Point3d point3d ) { Mesh m = new Mesh(); m.setMode( Mesh.Mode.Triangles ); List coords = new ArrayList(); List inds = new ArrayList(); Vector3d perp = new Vector3d( dir ); perp.scale( width / 2 ); Point3d delta = new Point3d(); if ( point3d != null ) { delta.set( point3d ); delta.sub( to3d( get( 0 ) ) ); } for ( Pair p : new ConsecutiveItPairs<>( get3D() ) ) { int o = coords.size() / 3; inds.add( o + 0 ); inds.add( o + 1 ); inds.add( o + 2 ); inds.add( o + 2 ); inds.add( o + 1 ); inds.add( o + 0 ); inds.add( o + 1 ); inds.add( o + 3 ); inds.add( o + 2 ); inds.add( o + 2 ); inds.add( o + 3 ); inds.add( o + 1 ); Point3d a1 = new Point3d( p.first() ), a2 = new Point3d( p.first() ), b1 = new Point3d( p.second() ), b2 = new Point3d( p.second() ); a1.add( delta ); a2.add( delta ); b1.add( delta ); b2.add( delta ); a1.sub( perp ); a2.add( perp ); b1.sub( perp ); b2.add( perp ); for ( Point3d pt : new Point3d[] { a1, a2, b1, b2 } ) { coords.add( (float) pt.x ); coords.add( (float) pt.y ); coords.add( (float) pt.z ); } } { Point3d p1 = to3d( get( size() - 1 ) ), p2 = to3d( get( size() - 1 ) ); Point2d arrowT = new Point2d( get( size() - 1 ) ), arrowB = null; for ( int e = size() - 2; e >= 0; e-- ) if ( !get( e ).equals( get( size() - 1 ) ) ) { arrowB = new Point2d( get( e ) ); break; } if ( arrowB != null ) { arrowT.sub( arrowB ); arrowT.scale( width * 1.3 / new Vector2d( arrowT ).length() ); arrowT.add( get( size() - 1 ) ); Point3d p3 = to3d( arrowT ); p1.add( perp ); p2.sub( perp ); p1.add( delta ); p2.add( delta ); p3.add( delta ); int o = coords.size() / 3; inds.add( o + 0 ); inds.add( o + 1 ); inds.add( o + 2 ); inds.add( o + 2 ); inds.add( o + 1 ); inds.add( o + 0 ); for ( Point3d pt : new Point3d[] { p1, p2, p3 } ) { coords.add( (float) pt.x ); coords.add( (float) pt.y ); coords.add( (float) pt.z ); } } } m.setBuffer( VertexBuffer.Type.Position, 3, Arrayz.toFloatArray( coords ) ); m.setBuffer( VertexBuffer.Type.Index, 2, Arrayz.toIntArray( inds ) ); return m; } public Point2d findRoofLine() { double nonVertRun = 0; Line up = new Line( 0, 0, 0, 1 ); Point2d runStart = null; for ( Pair line : new ConsecutivePairs<>( this, false ) ) { Line l = new Line( line.first(), line.second() ); double angle = l.absAngle( up ); if ( angle > Math.PI / 6 && angle < Math.PI ) { if ( nonVertRun == 0 ) runStart = l.start; nonVertRun += l.length(); } else { if ( nonVertRun > 2 && runStart != null ) return runStart; nonVertRun = 0; } } return runStart == null ? get( size() - 1 ) : runStart; } // public static List> partition( List profiles, double threshold ) { // // double[] ss = new double[profiles.size()]; // // for (int i = 0; i < profiles.size(); i++) { // suppress non-max // // double wMax = -Double.MAX_VALUE; // int winner = -1; // // for (int k = -3; k <= 3; k++) { // int ii = MUtils.clamp( i+k, 0, profiles.size() -1 ); // // if (profiles.get(ii).similarity > wMax) { // winner = ii; // wMax = profiles.get(ii).similarity; // } // } // // ss[i] = profiles.get(i).similarity; // // if ( winner == i ) // ss[i] *= 3; // } // // List> out = new ArrayList(); // // List lout = null; // for (int i = 0; i < profiles.size(); i++) { // if (lout == null || ss[i] > threshold ) { // lout = new ArrayList<>(); // out.add(lout); // } // lout.add(profiles.get( i )); // profiles.get(i).similarity = ss[i]; // } // // return out; // } public static Prof clean( List partition ) { int[] inds = new int[partition.size()]; Prof loc3 = partition.get( partition.size() / 2 ); Prof out = new Prof( loc3.toFlat, loc3.dir ); double delta = 0.1; double h = 0; // boolean halt; List xs = new ArrayList(); do { // halt = true; xs.clear(); int count = 0; for ( int p = 0; p < partition.size(); p++ ) { Prof prof = partition.get( p ); if ( prof.size() < 2 ) continue; count++; if ( prof.get( inds[ p ] + 1 ).y > h ) { Line l = new Line( prof.get( inds[ p ] ), prof.get( inds[ p ] + 1 ) ); if ( Math.abs( l.start.x - l.end.x ) < 0.01 ) xs.add( l.start.x ); else xs.add( l.xAtY( h ) ); } while ( prof.get( inds[ p ] + 1 ).y < h + delta && inds[ p ] < prof.size() - 2 ) inds[ p ]++; // if ( prof.get ( inds[p] + 1).y > h+delta ) // halt = false; } double sum = xs.stream().collect( Collectors.summingDouble( x -> x ) ).doubleValue(); if ( !Double.isNaN( sum / count ) ) out.add( new Point2d( sum / count, h ) ); h += delta; } while ( xs.size() > partition.size() / 4 ); // out.clean(); return out; } /** * We find an initial base offset. Then we cluster the start point of all * (clean) profiles. If any are a good distance from the initial base, we * add those as their own profile lines. * * The original line is offset by the remaiing data. */ public static List findProfileLines( Collection profiles, Line3d line ) { List out = new ArrayList(); // PaintThing.debug.clear(); SuperLine superLine = new SuperLine( line.start.x, line.start.z, line.end.x, line.end.z ); double outLen = superLine.length(); double min = Double.MAX_VALUE, max = -Double.MAX_VALUE; Cache vLength = new Cache() { @Override public Double create( Prof i ) { return i.verticalLength( 0.5 ); } }; double vLen = profiles.stream().mapToDouble( p -> vLength.get( p ) ).sum(); boolean useVertical = vLen / profiles.size() > 1; class Wrapper implements Clusterable { double[] pt; public Wrapper( Point2d pt ) { this.pt = new double[] { pt.x, pt.y }; } @Override public double[] getPoint() { return pt; } } List toCluster = new ArrayList(); List baseLineOffset = new ArrayList(); for ( Prof p : profiles ) { if ( useVertical && vLength.get( p ) < 1 ) //vLen / (5*profiles.size())) continue; Prof clean = p.parameterize(); Point2d pt = clean.get( 0 ); Point3d pt3 = clean.to3d( pt ); double ppram = superLine.findPPram( new Point2d( pt3.x, pt3.z ) ); baseLineOffset.add( pt.x ); toCluster.add( new Wrapper( new Point2d( pt.x, ppram * outLen ) ) ); min = Math.min( min, ppram ); max = Math.max( max, ppram ); } if ( min == max || toCluster.isEmpty() ) return out; if ( true ) { baseLineOffset.sort( Double::compareTo ); double modeBaselineOffset = baseLineOffset.get( baseLineOffset.size() / 2 ); DBSCANClusterer cr = new DBSCANClusterer<>( 1.5, 0 ); List> results = cr.cluster( toCluster ); Iterator> cit = results.iterator(); while ( cit.hasNext() ) { Cluster cw = cit.next(); if ( cw.getPoints().size() < 2 / TweedSettings.settings.profileHSampleDist ) { cit.remove(); double cMeanY = cw.getPoints().stream().mapToDouble( x -> x.pt[ 1 ] ).average().getAsDouble(); double bestDist = Double.MAX_VALUE; Cluster bestWrapper = null; for ( Cluster near : results ) { double meanY = near.getPoints().stream().mapToDouble( x -> x.pt[ 1 ] ).average().getAsDouble(); double dist = Math.abs( meanY - cMeanY ); if ( dist < bestDist ) { bestDist = dist; bestWrapper = near; } } if ( bestWrapper != null ) bestWrapper.getPoints().addAll( cw.getPoints() ); } } { baseLineOffset.clear(); int c = 0; for ( Cluster cw : results ) { double[] minMax = cw.getPoints().stream().map( p -> new double[] { p.pt[ 1 ] } ).collect( new InAxDoubleArray() ); double[] offsetA = cw.getPoints().stream().mapToDouble( p -> p.pt[ 0 ] ).sorted().toArray(); double offset = offsetA[ offsetA.length / 2 ]; if ( offset - modeBaselineOffset < 1 ) { for ( Wrapper w : cw.getPoints() ) baseLineOffset.add( w.pt[ 0 ] ); continue; } SuperLine sl = new SuperLine( superLine.fromPPram( minMax[ 0 ] / outLen ), superLine.fromPPram( minMax[ 1 ] / outLen ) ); sl.moveLeft( offset ); out.add( sl ); List pts = cw.getPoints().stream().map( w -> new Point2d( w.pt[ 0 ], w.pt[ 1 ] ) ).collect( Collectors.toList() ); PaintThing.debug( Rainbow.getColour( c++ ), 1, pts ); } } } Point2d nStart = superLine.fromPPram( min ), nEnd = superLine.fromPPram( max ); superLine.start = nStart; superLine.end = nEnd; baseLineOffset.sort( Double::compare ); if ( !baseLineOffset.isEmpty() ) superLine.moveLeft( baseLineOffset.get( baseLineOffset.size() / 2 ) ); out.add( 0, superLine ); return out; } protected Double verticalLength( double tol ) { double length = 0; for ( Pair pts : new ConsecutiveItPairs<>( this ) ) { Line line = new Line( pts.first(), pts.second() ); double angle = line.aTan2(); if ( angle > Mathz.PI2 - tol && angle < Mathz.PI2 + tol ) length += line.length(); } return length; } public Point3d at3DHeight( double h3 ) { double h = to2d( new Point3d( 0, h3, 0 ) ).y; int i = 0; while ( get( i ).y <= h && i < size() - 1 ) i++; if ( i == 0 ) return null; else if ( get( i ).y <= h ) return null; else return to3d( new Point2d( new Line( get( i - 1 ), get( i ) ).xAtY( h ), h ) ); } public double length() { double out = 0; for ( Pair line : new ConsecutivePairs<>( this, false ) ) out += new Line( line.first(), line.second() ).length(); return out; } public void createCap( double height ) { { Line last = new Line( get( size() - 2 ), get( size() - 1 ) ); if ( last.start.y == last.end.y && last.end.y < height ) return; } for ( int i = 0; i < size() - 1; i++ ) { Line l = new Line( get( i ), get( i + 1 ) ); if ( l.start.y > height ) { remove( i ); i--; continue; } else if ( l.end.y > height ) { l.end.x = l.xAtY( height ); l.end.y = height; } } Point2d end = get( size() - 1 ); if ( end.y != height ) { end.x = new Line( get( size() - 2 ), get( size() - 1 ) ).xAtY( height ); end.y = height; } add( new Point2d( end.x - 1, height ) ); } }/* * Copyright 2017 Twitter * * 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.twitter.serial.stream; import org.jetbrains.annotations.NotNull; public abstract class SerializerDefs { public static final byte TYPE_UNKNOWN = 0; public static final byte TYPE_BYTE = 1; public static final byte TYPE_INT = 2; public static final byte TYPE_LONG = 3; public static final byte TYPE_FLOAT = 4; public static final byte TYPE_DOUBLE = 5; public static final byte TYPE_BOOLEAN = 6; public static final byte TYPE_NULL = 7; public static final byte TYPE_STRING_UTF8 = 8; public static final byte TYPE_START_OBJECT = 9; public static final byte TYPE_START_OBJECT_DEBUG = 10; public static final byte TYPE_END_OBJECT = 11; public static final byte TYPE_EOF = 12; public static final byte TYPE_STRING_ASCII = 13; public static final byte TYPE_BYTE_ARRAY = 14; @NotNull public static String getTypeName(byte type) { switch (type) { case TYPE_BYTE: { return "byte"; } case TYPE_BOOLEAN: { return "boolean"; } case TYPE_INT: { return "int"; } case TYPE_LONG: { return "long"; } case TYPE_FLOAT: { return "float"; } case TYPE_DOUBLE: { return "double"; } case TYPE_STRING_ASCII: case TYPE_STRING_UTF8: { return "string"; } case TYPE_NULL: { return "null"; } case TYPE_START_OBJECT: case TYPE_START_OBJECT_DEBUG: { return "start_object"; } case TYPE_END_OBJECT: { return "end_object"; } case TYPE_EOF: { return "eof"; } case TYPE_BYTE_ARRAY: { return "byte_array"; } default: { return "unknown (" + type + ")"; } } } } package com.controladora.base; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class Controladora { public final static String URL_UPLOAD_FILE = "ARQUIVO_UPLOAD_FORPDI"; public final static String URL_DOWNLOAD_FILE = "ARQUIVO_DOWNLOAD_FORPDI"; private final Integer MAX_FILE_SIZE = 2 * 1024 * 1024; private String caminhoArquivo = ""; private String caminhoDownArquivo = ""; public Controladora(ServletContext ct) { caminhoArquivo = ct.getInitParameter(URL_UPLOAD_FILE); caminhoDownArquivo = ct.getInitParameter(URL_DOWNLOAD_FILE); } /** * Metodo que remove um arquivo passado por parametro * @param nomeArquivo nome do arquivo que deseja remover * @return true se o arquivo foi removido com sucesso ou nao * @throws IOException excessao no caso de erro de remocao do arquivo */ public boolean removeArquivo(String nomeArquivo) throws IOException { Path arquivo= Paths.get(caminhoArquivo, nomeArquivo); return Files.deleteIfExists(arquivo); } /** * Método que verifica se o arquivo esta correto. * @param arq nome do arquivo */ private void verificaDir(File arq) { if(!arq.exists ()) { System.out.println("O Diretorio não existe no sistema: " + arq.getAbsolutePath()); boolean test = arq.mkdirs(); if(test) { System.out.println("Criação do diretorio de upload com sucesso"); }else { System.out.println("Cuidado diretorio não foi criado"); } } } /** * Método que realizada o upload do arquivo na pasta definida como variavel de ambiente * @param input InputStrem que contem os dados do arquivo a ser armazenado * @param prefixo do arquivo que desejar gravar * @return url do arquivo armazenado */ public String enviaArquivo(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException, Exception{ String result = ""; // verifica se esta requisição esta como envio de arquivo boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(isMultipart ) { // criar a fabrica de enviado do arquivo DiskFileItemFactory factory = new DiskFileItemFactory(); File arquivo = new File(caminhoArquivo); verificaDir(arquivo); factory.setRepository(arquivo); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); List items = upload.parseRequest(request); FileItem arquivoGravar = null; String chave = ""; String prefixo = ""; for(FileItem item:items) { if(!item.isFormField()) { arquivoGravar = item; }else { // nome do arquivo if(item.getFieldName().equalsIgnoreCase("chave")) chave = item.getString(); else if(item.getFieldName().equalsIgnoreCase("nome")) prefixo = item.getString(); } } // tentando gravar arquivo if(arquivoGravar != null) { // nao manter o tipo de arquivo para foto do perfil String typeArquivo = (arquivoGravar.getName().indexOf(".")) >0 && !prefixo.equals("imageicon") ? arquivoGravar.getName().substring(arquivoGravar.getName().indexOf(".")):""; String nome = prefixo + '-' + chave + typeArquivo ; arquivoGravar.getContentType(); arquivoGravar.write(new File(arquivo, nome)); result = caminhoDownArquivo + "/" + nome; } } return result; } } tdt4100/src/objektstrukturer/SudokuAngre.java package objektstrukturer; import java.util.Stack; public class SudokuAngre { private String currentGame; String[][] newSGame = new String[9][9]; Stack undoSt = new Stack<>(); Stack redoSt = new Stack<>(); String[][] SGame2 = new String[9][9]; public void move(String[][] sGame) { this.SGame2=sGame; currentGame = makeOneString(sGame); System.out.println(currentGame); undoSt.push(new String(currentGame)); newSGame = make2DArray(currentGame); redoSt.removeAllElements(); } private void undone(String s){ redoSt.push(new String(s)); } public String[][] redo() { if (redoSt.size()>1){ newSGame = make2DArray(redoSt.pop()); return newSGame; } return SGame2; } public String[][] undo() { if (undoSt.size()>1){ undone(undoSt.pop()); //System.out.println("undo: "+ undoSt.peek()); newSGame = make2DArray(undoSt.peek()); return newSGame; } else{ return SGame2; } } //tar inn et sudoku-spill som en streng og gir ut en 2D-Array av spillet //denne strengen kan være et spill som allerede er i gang (med * og () ) public String[][] make2DArray(String currentGame2) { // TODO Auto-generated method stub Integer k = 0; for (int i = 0; i < 9; i++) { for (int u = 0; u < 9; u++) { try{ if(Character.toString(currentGame2.charAt((i * 9) + u + k)).equals("(")){ k+=1; String s1 = "("+Character.toString(currentGame2.charAt((i * 9) + u + k))+")"; this.newSGame[i][u] = s1 ; k+=1; } else if(((i * 9) + u + k + 1)<(currentGame2.length()) && (Character.toString(currentGame2.charAt((i * 9) + u + k + 1)).equals("*"))){ this.newSGame[i][u] = Character.toString(currentGame2.charAt((i * 9) + u + k))+"*"; k+=1; } else{ this.newSGame[i][u] = Character.toString(currentGame2.charAt((i * 9) + u + k)); } } catch(NullPointerException e2){} } } return newSGame; } public String makeOneString(String[][] sGame) { // makes a single line out of the 2D-String sGame //System.out.println(sGame); currentGame=""; for (int i = 0; i < sGame[0].length; i++) { for (int u = 0; u < sGame[0].length; u++) { this.currentGame += sGame[i][u]; } } return currentGame; } } tom5454/Tom-s-Modsrc/main/java/com/tom/transport/tileentity/TileEntityConveyorBase.java1-10 package com.tom.transport.tileentity; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.ISidedInventory; import net.minecraft.inventory.InventoryBasic; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumFacing.Axis; import net.minecraft.util.ResourceLocation; import net.minecraftforge.items.IItemHandler; import com.tom.api.tileentity.TileEntityTomsModNoTicking; import com.tom.handler.TMPlayerHandler; import com.tom.lib.api.tileentity.IOwnable; import com.tom.lib.handler.WorldHandler; import com.tom.lib.utils.Ticker; import com.tom.transport.block.ConveyorBeltBase; import com.tom.util.TomsModUtils; public abstract class TileEntityConveyorBase extends TileEntityTomsModNoTicking implements ISidedInventory, Ticker, IOwnable { protected InventoryBasic inv = new InventoryBasic("", false, 2); public static final int MAX_POS = 64; protected static final int[] SLOT = new int[]{0}, SIDE = new int[]{1}, FRONT = new int[]{}; protected int itemPos = 0; protected TMPlayerHandler playerHandler; public String playerName; private long lastTick; @Override public ItemStack getStackInSlot(int index) { return inv.getStackInSlot(index); } @Override public ItemStack decrStackSize(int index, int count) { return inv.decrStackSize(index, count); } @Override public ItemStack removeStackFromSlot(int index) { return inv.removeStackFromSlot(index); } @Override public void setInventorySlotContents(int index, ItemStack stack) { inv.setInventorySlotContents(index, stack); if(!stack.isEmpty()){ long ctick = world.getTotalWorldTime(); if(lastTick < (ctick-1)){ queue(); } } } @Override public int getSizeInventory() { return inv.getSizeInventory(); } @Override public void clear() { inv.clear(); } @Override public boolean isEmpty() { return inv.isEmpty(); } @Override public int getInventoryStackLimit() { return 1; } @Override public boolean isUsableByPlayer(EntityPlayer player) { return false; } @Override public void openInventory(EntityPlayer player) { } @Override public void closeInventory(EntityPlayer player) { } @Override public boolean isItemValidForSlot(int index, ItemStack stack) { return true; } @Override public int getField(int id) { return 0; } @Override public void setField(int id, int value) { } @Override public int getFieldCount() { return 0; } @Override public String getName() { return ""; } @Override public boolean hasCustomName() { return false; } @Override public int[] getSlotsForFace(EnumFacing side) { EnumFacing facing = getFacing(); return facing.rotateY().getAxis() == side.getAxis() || side.getAxis() == Axis.Y ? SIDE : facing == side ? FRONT : SLOT; } @Override public boolean canInsertItem(int index, ItemStack itemStackIn, EnumFacing direction) { return (index == 0 || index == 1) && inv.getStackInSlot(1).isEmpty() && inv.getStackInSlot(0).isEmpty(); } @Override public boolean canExtractItem(int index, ItemStack stack, EnumFacing direction) { return index == 0; } public boolean tryPull(IBlockState currentState){ return false; } public void updateConveyor(IBlockState currentState) { if (!world.isRemote) { boolean sync = false; if (!inv.getStackInSlot(0).isEmpty()) { if (itemPos < MAX_POS) { if(playerHandler.checkAndUseGridPower(getPowerUse())){ itemPos = Math.min(itemPos + getSpeed(), MAX_POS); sync = true; } } else if (itemPos == MAX_POS) { sync = pushItemOut(currentState); } } else if (!inv.getStackInSlot(1).isEmpty()) { itemPos = MAX_POS / 2; inv.setInventorySlotContents(0, inv.removeStackFromSlot(1)); sync = true; } else { if (itemPos != 0) sync = true; itemPos = 0; if(world.getTotalWorldTime() % 5 == 0) sync |= tryPull(currentState); } if (sync) markBlockForUpdate(); } else { if (!inv.getStackInSlot(0).isEmpty()) { if (itemPos < MAX_POS) { itemPos = Math.min(itemPos + getSpeed(), MAX_POS); } } } } public boolean pushItemOut(IBlockState currentState){ boolean sync = false; EnumFacing f = getFacing(); IItemHandler h = TomsModUtils.getItemHandler(world, pos.offset(f), f.getOpposite(), true); if (h != null) { inv.setInventorySlotContents(0, TomsModUtils.putStackInInventoryAllSlots(h, inv.getStackInSlot(0))); if (inv.getStackInSlot(0).isEmpty()) { sync = true; itemPos = 0; } } else { TileEntity t = world.getTileEntity(pos.offset(f).down()); if (t instanceof IConveyorSlope) { IConveyorSlope c = (IConveyorSlope) t; if (c.isValid()) { inv.setInventorySlotContents(0, c.insert(inv.getStackInSlot(0), f.getOpposite())); if (inv.getStackInSlot(0).isEmpty()) { sync = true; itemPos = 0; } } } } return sync; } public abstract int getPowerUse(); public abstract int getSpeed(); @Override public NBTTagCompound writeToNBT(NBTTagCompound compound) { TomsModUtils.writeInventory("inv", compound, inv); compound.setInteger("itempos", itemPos); compound.setString("placer", playerName); return super.writeToNBT(compound); } @Override public void readFromNBT(NBTTagCompound compound) { super.readFromNBT(compound); TomsModUtils.loadAllItems(compound, "inv", inv); itemPos = compound.getInteger("itempos"); playerName = compound.getString("placer"); } @Override public void writeToPacket(NBTTagCompound tag) { tag.setInteger("p", itemPos); tag.setTag("i", inv.getStackInSlot(0).writeToNBT(new NBTTagCompound())); } @Override public void readFromPacket(NBTTagCompound tag) { itemPos = tag.getInteger("p"); inv.setInventorySlotContents(0, new ItemStack(tag.getCompoundTag("i"))); } public EnumFacing getFacing() { return world.getBlockState(pos).getValue(ConveyorBeltBase.FACING); } public int getItemPos() { return itemPos; } public ItemStack getStack() { return inv.getStackInSlot(0); } public abstract ResourceLocation getTexture(); public void randomTick() { long ctick = world.getTotalWorldTime(); if(lastTick < (ctick-2) && isTickerValid()){ queue(); } } private void queue() { WorldHandler.addTicker(world.provider.getDimension(), this); } @Override public void onLoad() { tileOnLoad(); } @Override public void updatePlayerHandler() { playerHandler = TMPlayerHandler.getPlayerHandlerForName(playerName); if(playerHandler != null)WorldHandler.queueTask(world.provider.getDimension(), this::randomTick); } @Override public final void updateTicker() { lastTick = world.getTotalWorldTime(); if(playerHandler != null){ IBlockState state = world.getBlockState(pos); updateConveyor(state); } } @Override public boolean isTickerValid() { return !isInvalid() && playerHandler != null && (!inv.getStackInSlot(0).isEmpty() || !inv.getStackInSlot(1).isEmpty()); } @Override public String getOwnerName() { return playerName; } @Override public void setOwner(String owner) { this.playerName = owner; } } lukasblu/hazelcast /* * Copyright (c) 2008-2013, Hazelcast, Inc. 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 com.hazelcast.replicatedmap.impl.client; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.Portable; import com.hazelcast.nio.serialization.PortableReader; import com.hazelcast.nio.serialization.PortableWriter; import java.io.IOException; /** * Response class for client replicated map get requests */ public class ReplicatedMapGetResponse implements Portable { private Object value; private long ttlMillis; private long updateTime; ReplicatedMapGetResponse() { } ReplicatedMapGetResponse(Object value, long ttlMillis, long updateTime) { this.value = value; this.ttlMillis = ttlMillis; this.updateTime = updateTime; } public Object getValue() { return value; } public long getTtlMillis() { return ttlMillis; } public long getUpdateTime() { return updateTime; } @Override public void writePortable(PortableWriter writer) throws IOException { writer.writeLong("ttlMillis", ttlMillis); writer.writeLong("updateTime", updateTime); ObjectDataOutput out = writer.getRawDataOutput(); out.writeObject(value); } @Override public void readPortable(PortableReader reader) throws IOException { ttlMillis = reader.readLong("ttlMillis"); updateTime = reader.readLong("updateTime"); ObjectDataInput in = reader.getRawDataInput(); value = in.readObject(); } @Override public int getFactoryId() { return ReplicatedMapPortableHook.F_ID; } @Override public int getClassId() { return ReplicatedMapPortableHook.GET_RESPONSE; } } package org.moe.gradle.options; import org.moe.gradle.anns.IgnoreUnused; import org.moe.gradle.anns.Nullable; import java.io.File; import java.util.List; public class RemoteBuildOptions { @Nullable private List resources; @Nullable public List getResources() { return resources; } @IgnoreUnused public void setResources(@Nullable List assets) { this.resources = assets; } } package aula02.classeabstrata; public abstract class FormaPagamento { protected double valor; public abstract boolean pagou(); } briemla/clock-radioclock-radio/src/main/java/de/briemla/clockradio/dabpi/command/FMStatusCommand.java package de.briemla.clockradio.dabpi.command; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import de.briemla.clockradio.dabpi.Output; import de.briemla.clockradio.dabpi.result.FMStatus; public class FMStatusCommand extends BaseCommand { private static final Pattern FREQUENCY_PATTERN = Pattern.compile("^Frequency: ([0-9]+)kHz$"); private static final String FREQUENCY_FILTER = "Frequency"; public FMStatusCommand() { super("d"); } @Override protected FMStatus parseSpecialized(Output output) { Optional fmStatus = output.standardAsStream().filter(line -> line.startsWith(FREQUENCY_FILTER)).map(FMStatusCommand::convert).findFirst(); if (fmStatus.isPresent()) { return fmStatus.get(); } throw new IllegalArgumentException("Frequency missing in FM status output."); } private static FMStatus convert(String line) { Matcher matcher = FREQUENCY_PATTERN.matcher(line); if (!matcher.matches()) { throw new IllegalArgumentException("Frequency missing in FM status output."); } Integer frequency = Integer.parseInt(matcher.group(1)); return new FMStatus(frequency); } } package com.example.weinner.liron.happygardener; import java.util.Locale; /** * Created by */ class Utility { private static final Utility ourInstance = new Utility(); static Utility getInstance() { return ourInstance; } private Utility() { } /** * Checks if the number got more then 4 digits after decimal point * @param number Should be a String * @return True if the number got more then 4 digits after decimal point and false otherwise */ private static boolean checkDecimalPoints(final String number){ boolean status = false; String split[]=number.split("\\."); try{ if(split[1].trim().length() > 0){ status = true; } }catch (ArrayIndexOutOfBoundsException e){ status = false; } return status; } /** * Format a number with more then 4 digits after decimal point to a 4 digits after decimal point * @param number Should be a String * @return The same number if no decimal point or 4 or less digits after point or formatted string with 4 digits after decimal point */ static String setRoundedNumber(final String number){ // If got more then 4 digits after decimal point if(checkDecimalPoints(number)){ String result = String.format(Locale.getDefault(),"%.4f",Double.valueOf(number)).replaceAll("0*$",""); int point_index = result.indexOf('.'); if(point_index != -1){ if(result.length()-1 == point_index){ result = result.substring(0, point_index); } } return result; } // If got less then 4 digits after decimal point or no decimal point at all return number; } } package org.apache.hadoop.tools.posum.data.monitor.cluster; import org.apache.hadoop.mapreduce.v2.api.records.TaskState; import org.apache.hadoop.mapreduce.v2.api.records.TaskType; import org.apache.hadoop.tools.posum.client.data.Database; import org.apache.hadoop.tools.posum.common.records.call.FindByQueryCall; import org.apache.hadoop.tools.posum.common.records.dataentity.DataEntityCollection; import org.apache.hadoop.tools.posum.common.records.dataentity.TaskProfile; import org.apache.hadoop.tools.posum.common.records.payload.MultiEntityPayload; import org.apache.hadoop.yarn.util.Records; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatcher; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.argThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class TestTaskInfoCollector { @Mock private HadoopAPIClient apiMock; @Mock private Database dbMock; @InjectMocks private TaskInfoCollector testSubject = new TaskInfoCollector(); private ClusterMonitorEntities entities; @Before public void init() { entities = new ClusterMonitorEntities(); } @Test public void getFinishedTaskInfoTest() { when(dbMock.execute(Matchers.any(FindByQueryCall.class))) .thenReturn(MultiEntityPayload.newInstance(DataEntityCollection.TASK, Arrays.asList(entities.RUNNING_TASKS))); when(apiMock.getFinishedTasksInfo(entities.JOB_ID, Arrays.asList(entities.RUNNING_TASKS))) .thenReturn(Arrays.asList(entities.FINISHED_TASKS)); when(apiMock.getFinishedTaskCounters(entities.JOB_ID, entities.FINISHED_TASKS[0].getId())) .thenReturn(entities.TASK_COUNTERS_MAP); when(apiMock.getFinishedTaskCounters(entities.JOB_ID, entities.FINISHED_TASKS[1].getId())) .thenReturn(entities.TASK_COUNTERS_REDUCE); TaskInfo info = testSubject.getFinishedTaskInfo(entities.FINISHED_JOB); verify(apiMock, times(1)).addFinishedAttemptInfo(entities.FINISHED_TASKS[0]); verify(apiMock, times(1)).addFinishedAttemptInfo(entities.FINISHED_TASKS[1]); assertThat(info.getTasks(), containsInAnyOrder(entities.FINISHED_TASKS)); assertThat(info.getCounters(), containsInAnyOrder(entities.TASK_COUNTERS_MAP, entities.TASK_COUNTERS_REDUCE)); assertThat(entities.FINISHED_TASKS[0].getInputBytes(), is(48L)); assertThat(entities.FINISHED_TASKS[0].getOutputBytes(), is(2235L)); assertThat(entities.FINISHED_TASKS[1].getInputBytes(), is(2235L)); assertThat(entities.FINISHED_TASKS[1].getOutputBytes(), is(0L)); } @Test public void getRunningTaskInfoTest() { when(dbMock.execute(Matchers.any(FindByQueryCall.class))) .thenReturn(MultiEntityPayload.newInstance(DataEntityCollection.TASK, Arrays.asList(entities.RUNNING_TASKS))); when(apiMock.getRunningTasksInfo(entities.RUNNING_JOB, Arrays.asList(entities.RUNNING_TASKS))) .thenReturn(Arrays.asList(entities.RUNNING_TASKS)); when(apiMock.getRunningTaskCounters(entities.APP_ID, entities.JOB_ID, entities.RUNNING_TASKS[0].getId())) .thenReturn(entities.TASK_COUNTERS_MAP); when(apiMock.getRunningTaskCounters(entities.APP_ID, entities.JOB_ID, entities.RUNNING_TASKS[1].getId())) .thenReturn(entities.TASK_COUNTERS_REDUCE); when(apiMock.addRunningAttemptInfo(entities.RUNNING_TASKS[0])).thenReturn(true); when(apiMock.addRunningAttemptInfo(entities.RUNNING_TASKS[1])).thenReturn(true); TaskInfo info = testSubject.getRunningTaskInfo(entities.RUNNING_APP, entities.RUNNING_JOB); verify(apiMock, times(1)).addRunningAttemptInfo(entities.RUNNING_TASKS[0]); verify(apiMock, times(1)).addRunningAttemptInfo(entities.RUNNING_TASKS[1]); assertThat(info.getTasks(), containsInAnyOrder(entities.RUNNING_TASKS)); assertThat(info.getCounters(), containsInAnyOrder(entities.TASK_COUNTERS_MAP, entities.TASK_COUNTERS_REDUCE)); assertThat(entities.RUNNING_TASKS[0].getInputBytes(), is(48L)); assertThat(entities.RUNNING_TASKS[0].getOutputBytes(), is(2235L)); assertThat(entities.RUNNING_TASKS[1].getInputBytes(), is(2235L)); assertThat(entities.RUNNING_TASKS[1].getOutputBytes(), is(0L)); } @Test public void getSubmittedTaskInfoTest() { when(dbMock.execute(Matchers.any(FindByQueryCall.class))) .thenReturn(MultiEntityPayload.newInstance(DataEntityCollection.TASK, new ArrayList())); final TaskProfile mapStub = Records.newRecord(TaskProfile.class); mapStub.setId(entities.RUNNING_MAP_TASK.getId()); mapStub.setType(TaskType.MAP); mapStub.setJobId(entities.RUNNING_JOB.getId()); mapStub.setAppId(entities.RUNNING_JOB.getAppId()); mapStub.setState(TaskState.NEW); mapStub.setSplitSize(entities.SPLIT_SIZES.get(0)); mapStub.setSplitLocations(entities.SPLIT_LOCATIONS.get(0)); final TaskProfile reduceStub = Records.newRecord(TaskProfile.class); reduceStub.setId(entities.RUNNING_REDUCE_TASK.getId()); reduceStub.setType(TaskType.REDUCE); reduceStub.setState(TaskState.NEW); reduceStub.setJobId(entities.RUNNING_JOB.getId()); reduceStub.setAppId(entities.RUNNING_JOB.getAppId()); when(apiMock.getRunningTasksInfo(eq(entities.RUNNING_JOB), argThat(new ArgumentMatcher>() { @Override public boolean matches(Object o) { List createdStubs = (List) o; createdStubs.get(0).setLastUpdated(mapStub.getLastUpdated()); createdStubs.get(1).setLastUpdated(reduceStub.getLastUpdated()); return createdStubs.get(0).equals(mapStub) && createdStubs.get(1).equals(reduceStub); } }))).thenReturn(Arrays.asList(entities.RUNNING_TASKS)); when(apiMock.getRunningTaskCounters(entities.APP_ID, entities.JOB_ID, entities.RUNNING_TASKS[0].getId())) .thenReturn(entities.TASK_COUNTERS_MAP); when(apiMock.getRunningTaskCounters(entities.APP_ID, entities.JOB_ID, entities.RUNNING_TASKS[1].getId())) .thenReturn(entities.TASK_COUNTERS_REDUCE); when(apiMock.addRunningAttemptInfo(entities.RUNNING_TASKS[0])).thenReturn(true); when(apiMock.addRunningAttemptInfo(entities.RUNNING_TASKS[1])).thenReturn(true); TaskInfo info = testSubject.getRunningTaskInfo(entities.RUNNING_APP, entities.RUNNING_JOB); verify(apiMock, times(1)).addRunningAttemptInfo(entities.RUNNING_TASKS[0]); verify(apiMock, times(1)).addRunningAttemptInfo(entities.RUNNING_TASKS[1]); assertThat(info.getTasks(), containsInAnyOrder(entities.RUNNING_TASKS)); assertThat(info.getCounters(), containsInAnyOrder(entities.TASK_COUNTERS_MAP, entities.TASK_COUNTERS_REDUCE)); assertThat(entities.RUNNING_TASKS[0].getInputBytes(), is(48L)); assertThat(entities.RUNNING_TASKS[0].getOutputBytes(), is(2235L)); assertThat(entities.RUNNING_TASKS[1].getInputBytes(), is(2235L)); assertThat(entities.RUNNING_TASKS[1].getOutputBytes(), is(0L)); } } package com.archyx.aureliumskills.loot.builder; import com.archyx.aureliumskills.AureliumSkills; import com.archyx.aureliumskills.commands.CommandExecutor; import com.archyx.aureliumskills.loot.Loot; import com.archyx.aureliumskills.loot.type.CommandLoot; public class CommandLootBuilder extends LootBuilder { private CommandExecutor executor; private String command; public CommandLootBuilder(AureliumSkills plugin) { super(plugin); this.executor = CommandExecutor.CONSOLE; } @Override public Loot build() { return new CommandLoot(plugin, weight, message, xp, sources, executor, command); } public CommandLootBuilder executor(CommandExecutor executor) { this.executor = executor; return this; } public CommandLootBuilder command(String command) { this.command = command; return this; } } // *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package pl.pawelprazak.pulumi.kind.inputs; import javax.annotation.Nullable; import java.util.Objects; import java.util.Optional; import java.util.Map; import java.util.List; import java.util.concurrent.CompletableFuture; import io.pulumi.core.*; import io.pulumi.core.internal.annotations.*; import pl.pawelprazak.pulumi.kind.Utilities; public final class ClusterKindConfigNodeExtraMountArgs extends io.pulumi.resources.ResourceArgs { public static final ClusterKindConfigNodeExtraMountArgs Empty = new ClusterKindConfigNodeExtraMountArgs(); @InputImport(name="containerPath") private final @Nullable Input containerPath; public Input getContainerPath() { return this.containerPath == null ? Input.empty() : this.containerPath; } @InputImport(name="hostPath") private final @Nullable Input hostPath; public Input getHostPath() { return this.hostPath == null ? Input.empty() : this.hostPath; } public ClusterKindConfigNodeExtraMountArgs( @Nullable Input containerPath, @Nullable Input hostPath) { this.containerPath = containerPath; this.hostPath = hostPath; } private ClusterKindConfigNodeExtraMountArgs() { this.containerPath = Input.empty(); this.hostPath = Input.empty(); } public static Builder builder() { return new Builder(); } public static Builder builder(ClusterKindConfigNodeExtraMountArgs defaults) { return new Builder(defaults); } public static final class Builder { private @Nullable Input containerPath; private @Nullable Input hostPath; public Builder() { // Empty } public Builder(ClusterKindConfigNodeExtraMountArgs defaults) { Objects.requireNonNull(defaults); this.containerPath = defaults.containerPath; this.hostPath = defaults.hostPath; } public Builder setContainerPath(@Nullable Input containerPath) { this.containerPath = containerPath; return this; } public Builder setContainerPath(@Nullable String containerPath) { this.containerPath = Input.ofNullable(containerPath); return this; } public Builder setHostPath(@Nullable Input hostPath) { this.hostPath = hostPath; return this; } public Builder setHostPath(@Nullable String hostPath) { this.hostPath = Input.ofNullable(hostPath); return this; } public ClusterKindConfigNodeExtraMountArgs build() { return new ClusterKindConfigNodeExtraMountArgs(containerPath, hostPath); } } } package ink.ikx.rt.impl.matteroverdrive; import matteroverdrive.MatterOverdrive; import matteroverdrive.api.android.IBioticStat; import matteroverdrive.entity.android_player.AndroidPlayer; import matteroverdrive.entity.player.MOPlayerCapabilityProvider; import net.minecraft.entity.player.EntityPlayer; /** * @author skyraah */ public class IMatterOverdriveAndroid { public static boolean isPlayerAndroid(EntityPlayer entityPlayer) { AndroidPlayer androidPlayer = MOPlayerCapabilityProvider.GetAndroidCapability(entityPlayer); return androidPlayer != null && androidPlayer.isAndroid(); } public static void setPlayerAndroid(EntityPlayer entityPlayer, boolean b, boolean animation) { AndroidPlayer androidPlayer = MOPlayerCapabilityProvider.GetAndroidCapability(entityPlayer); if (!animation) { androidPlayer.setAndroid(b); } else if (b) { androidPlayer.startConversion(); } else { androidPlayer.setAndroid(false); } } public static void resetPlayerAndroidSkills(EntityPlayer entityPlayer, boolean b) { AndroidPlayer androidPlayer = MOPlayerCapabilityProvider.GetAndroidCapability(entityPlayer); int xpLevels = androidPlayer.resetUnlocked(); if (b) { entityPlayer.addExperienceLevel(xpLevels); } } public static boolean isPlayerAndroidTurning(EntityPlayer entityPlayer) { AndroidPlayer androidPlayer = MOPlayerCapabilityProvider.GetAndroidCapability(entityPlayer); return androidPlayer.isTurning(); } public static void unlock(EntityPlayer entityPlayer, int id, int level, boolean admin) { AndroidPlayer androidPlayer = MOPlayerCapabilityProvider.GetAndroidCapability(entityPlayer); IBioticStat bioticStat = getIBioticStat(id); if (level < bioticStat.maxLevel() && level != 0) { if (!admin) { androidPlayer.tryUnlock(bioticStat, level); } else { androidPlayer.unlock(bioticStat, level); } } else if (level == 0 || level >= bioticStat.maxLevel()) { if (!admin) { androidPlayer.tryUnlock(bioticStat, bioticStat.maxLevel()); } else { androidPlayer.unlock(bioticStat, bioticStat.maxLevel()); } } } public static IBioticStat getIBioticStat(int id) { String stat = IIBioticStat.values()[id].toString(); return MatterOverdrive.STAT_REGISTRY.getStat(stat); } public static boolean isUnlocked(EntityPlayer entityPlayer, int id, int level) { AndroidPlayer androidPlayer = MOPlayerCapabilityProvider.GetAndroidCapability(entityPlayer); return androidPlayer.isUnlocked(getIBioticStat(id), level); } public static int getUnlockedLevel(EntityPlayer entityPlayer, int id) { AndroidPlayer androidPlayer = MOPlayerCapabilityProvider.GetAndroidCapability(entityPlayer); return androidPlayer.getUnlockedLevel(getIBioticStat(id)); } public static int getEnergy(EntityPlayer entityPlayer) { AndroidPlayer androidPlayer = MOPlayerCapabilityProvider.GetAndroidCapability(entityPlayer); return androidPlayer.getEnergyStored(); } public static int getMaxEnergy(EntityPlayer entityPlayer) { AndroidPlayer androidPlayer = MOPlayerCapabilityProvider.GetAndroidCapability(entityPlayer); return androidPlayer.getMaxEnergyStored(); } public static int receiveEnergy(EntityPlayer entityPlayer, int energy, boolean receive) { AndroidPlayer androidPlayer = MOPlayerCapabilityProvider.GetAndroidCapability(entityPlayer); return androidPlayer.receiveEnergy(energy, receive); } } projects/copper-jmx-interface/src/main/java/org/copperengine/management/model/WorkflowInstanceFilter.java /* * Copyright 2002-2017 SCOOP Software GmbH * * 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.copperengine.management.model; import java.beans.ConstructorProperties; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class WorkflowInstanceFilter implements Serializable { private static final long serialVersionUID = 3695017848783764269L; private List states = new ArrayList<>(); private HalfOpenTimeInterval lastModTS; private HalfOpenTimeInterval creationTS; private String processorPoolId; private String workflowClassname; private int max = 50; private int offset = 0; public WorkflowInstanceFilter() { } @ConstructorProperties({"states","lastModTS","creationTS","processorPoolId","workflowClassname","max","offset"}) public WorkflowInstanceFilter(List states, HalfOpenTimeInterval lastModTS, HalfOpenTimeInterval creationTS, String processorPoolId, String workflowClassname, int max, int offset) { this.states = states; this.lastModTS = lastModTS; this.creationTS = creationTS; this.processorPoolId = processorPoolId; this.workflowClassname = workflowClassname; this.max = max; this.offset = offset; } public List getStates() { return states; } public void setStates(List state) { this.states = state; } public void addState(String state) { this.states.add(state); } public HalfOpenTimeInterval getLastModTS() { return lastModTS; } public void setLastModTS(HalfOpenTimeInterval lastModTS) { this.lastModTS = lastModTS; } public HalfOpenTimeInterval getCreationTS() { return creationTS; } public void setCreationTS(HalfOpenTimeInterval creationTS) { this.creationTS = creationTS; } public String getProcessorPoolId() { return processorPoolId; } public void setProcessorPoolId(String processorPoolId) { this.processorPoolId = processorPoolId; } public String getWorkflowClassname() { return workflowClassname; } public void setWorkflowClassname(String workflowClassname) { this.workflowClassname = workflowClassname; } public int getMax() { return max; } public void setMax(int max) { this.max = max; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } @Override public String toString() { return "WorkflowInstanceFilter [states=[" + (states != null ? String.join(", ", states) : "") + "], lastModTS=" + lastModTS + ", creationTS=" + creationTS + ", processorPoolId=" + processorPoolId + ", workflowClassname=" + workflowClassname +", max=" + max + ", offset=" + offset + "]"; } } 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.netbeans.modules.search.ui; import java.awt.Container; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.AbstractButton; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JSplitPane; import org.netbeans.modules.search.BasicComposition; import org.netbeans.modules.search.ContextView; import org.netbeans.modules.search.FindDialogMemory; import org.netbeans.modules.search.Manager; import org.netbeans.modules.search.ReplaceTask; import org.netbeans.modules.search.ResultModel; import org.netbeans.modules.search.ResultView; import org.openide.awt.Mnemonics; import org.openide.nodes.AbstractNode; import org.openide.nodes.Children; import org.openide.nodes.Node; import org.openide.util.Mutex; import org.openide.util.NbBundle; import org.openide.util.RequestProcessor; /** * * @author jhavlin */ public class BasicReplaceResultsPanel extends BasicAbstractResultsPanel { private static final RequestProcessor RP = new RequestProcessor(BasicReplaceResultsPanel.class.getName()); private final RequestProcessor.Task SAVE_TASK = RP.create(new SaveTask()); private JButton replaceButton; private JSplitPane splitPane; public BasicReplaceResultsPanel(ResultModel resultModel, BasicComposition composition, Node infoNode) { super(resultModel, composition, true, new ResultsOutlineSupport(true, true, resultModel, composition, infoNode)); init(); } private void init() { JPanel leftPanel = new JPanel(); replaceButton = new JButton(); replaceButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { replace(); } }); updateReplaceButton(); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS)); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 2, 1)); buttonPanel.add(replaceButton); replaceButton.setMaximumSize(replaceButton.getPreferredSize()); buttonPanel.setMaximumSize(new Dimension( // #225246 (int) buttonPanel.getMaximumSize().getWidth(), (int) buttonPanel.getPreferredSize().getHeight())); leftPanel.add(resultsOutlineSupport.getOutlineView()); leftPanel.add(buttonPanel); this.splitPane = new JSplitPane(); splitPane.setLeftComponent(leftPanel); splitPane.setRightComponent(new ContextView(resultModel, getExplorerManager())); initSplitDividerLocationHandling(); getContentPanel().add(splitPane); initResultModelListener(); replaceButton.getAccessibleContext().setAccessibleDescription( NbBundle.getMessage(ResultView.class, "ACS_TEXT_BUTTON_REPLACE")); //NOI18N } private void replace() { ReplaceTask taskReplace = new ReplaceTask(resultModel.getMatchingObjects(), this); resultsOutlineSupport.clean(); replaceButton.setEnabled(false); Manager.getInstance().scheduleReplaceTask(taskReplace); } private void initResultModelListener() { resultModel.addPropertyChangeListener(new ModelListener()); } private void initSplitDividerLocationHandling() { int location = FindDialogMemory.getDefault().getReplaceResultsDivider(); if (location > 0) { splitPane.setDividerLocation(location); } splitPane.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { String pn = evt.getPropertyName(); if (pn.equals(JSplitPane.DIVIDER_LOCATION_PROPERTY)) { SAVE_TASK.schedule(1000); } } }); } @Override public void searchFinished() { super.searchFinished(); if (resultModel.isValid()) { updateReplaceButton(); } if (replaceButton.isVisible() && replaceButton.isEnabled()){ replaceButton.requestFocusInWindow(); } } private class ModelListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { String pn = evt.getPropertyName(); if (ResultModel.PROP_VALID.equals(pn) && Boolean.FALSE.equals(evt.getNewValue())) { replaceButton.setText(NbBundle.getMessage(ResultView.class, "TEXT_BUTTON_REPLACE_INVALID")); //NOI18N replaceButton.setEnabled(false); } else if (resultModel.isValid()) { if (ResultModel.PROP_VALID.equals(pn) && Boolean.TRUE.equals(evt.getNewValue())) { setFinalRootNodeText(); } updateReplaceButton(); } } } private void updateReplaceButton() { int matches = resultModel.getSelectedMatchesCount(); Mnemonics.setLocalizedText(replaceButton, NbBundle.getMessage(ResultView.class, "TEXT_BUTTON_REPLACE", matches));//NOI18N replaceButton.setEnabled(matches > 0 && isFinished()); } /** */ public void displayIssuesToUser(final ReplaceTask task, final String title, final String[] problems, final boolean reqAtt) { Mutex.EVENT.writeAccess(new Runnable() { @Override public void run() { IssuesPanel issuesPanel = new IssuesPanel(title, problems); if (isMacLaf) { issuesPanel.setBackground(macBackground); } displayIssues(issuesPanel); if (!ResultView.getInstance().isOpened()) { ResultView.getInstance().open(); } if (reqAtt) { ResultView.getInstance().requestAttention(true); } } }); } void displayIssues(IssuesPanel issuesPanel) { if (issuesPanel != null) { showRefreshButton(); removeButtons(btnNext, btnPrev, btnFlatView, btnTreeView, btnExpand, showDetailsButton); Container p = getContentPanel(); p.removeAll(); p.add(issuesPanel); validate(); repaint(); } } private void removeButtons(AbstractButton... abstractButtons) { for (AbstractButton ab : abstractButtons) { if (ab != null) { Container c = ab.getParent(); c.remove(ab); } } } public void rescan() { BasicComposition bc = new BasicComposition(composition.getSearchInfo(), composition.getMatcher(), composition.getBasicSearchCriteria(), composition.getScopeDisplayName()); Manager.getInstance().scheduleSearchTask(bc, true); } public void showFinishedInfo() { final AbstractNode an = new AbstractNode(Children.LEAF); an.setIconBaseWithExtension( "org/netbeans/modules/search/res/info.png"); //NOI18N an.setDisplayName(NbBundle.getMessage(ResultView.class, "TEXT_INFO_REPLACE_FINISHED", //NOI18N resultModel.getSelectedMatchesCount())); Mutex.EVENT.writeAccess(new Runnable() { @Override public void run() { getOutlineView().getOutline().setRootVisible(true); getExplorerManager().setRootContext(an); getOutlineView().validate(); getOutlineView().repaint(); btnNext.setEnabled(false); btnPrev.setEnabled(false); btnTreeView.setEnabled(false); btnFlatView.setEnabled(false); btnExpand.setEnabled(false); } }); } private class SaveTask implements Runnable { @Override public void run() { if (splitPane != null) { FindDialogMemory.getDefault().setReplaceResultsDivider( splitPane.getDividerLocation()); } } } } package co.edu.campusucc; import java.util.Scanner; public class programalnmanual003 { public static void main(String[] args) { System.out.println("autor: "); System.out.println("fecha: 31/OCTUBRE/2020"); System.out.println("____*##########*"); System.out.println("__*##############"); System.out.println("__################"); System.out.println("_##################_________*####*"); System.out.println("__##################_____*##########"); System.out.println("__##################___*#############"); System.out.println("___#################*_###############*"); System.out.println("____#################################*"); System.out.println("______###############################"); System.out.println("_______#############################"); System.out.println("________=##########################"); System.out.println("__________########################"); System.out.println("___________*#####################"); System.out.println("____________*##################"); System.out.println("_____________*###############"); System.out.println("_______________#############"); System.out.println("________________##########"); System.out.println("________________=#######*"); System.out.println("_________________######"); System.out.println("__________________####"); System.out.println("__________________###"); System.out.println("___________________#"); System.out.println("mi primer programa en java "); System.out.println("autor: "); int rest1, rest2 = 1; boolean l1 = false, l2 = false, k; try (Scanner leer = new Scanner(System.in)) { System.out.println("¿inglaterra es un pais suramericano? [0]... falso [1]...verdad"); rest1 = leer.nextInt(); System.out.println("\"¿marie currie invento el radio? [0]... falso [1]...verdad "); rest2 = leer.nextInt(); } if (rest1!= 0) l1=true; if (rest2!= 0) l2=true; k= l1 && l2; System.out.println("el valor final de k es:" +k); } } spring-boot-project/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/metrics/export/simple/SimplePropertiesTests.java /* * Copyright 2012-2018 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.springframework.boot.actuate.autoconfigure.metrics.export.simple; import io.micrometer.core.instrument.simple.SimpleConfig; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; /** * @author */ public class SimplePropertiesTests { @Test public void defaultValuesAreConsistent() { SimpleProperties properties = new SimpleProperties(); SimpleConfig config = SimpleConfig.DEFAULT; assertThat(properties.getStep()).isEqualTo(config.step()); assertThat(properties.getMode()).isEqualTo(config.mode()); } } 0 // Copyright (c) 2021, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.apimodel; import static com.android.tools.r8.apimodel.ApiModelingTestHelper.setMockApiLevelForClass; import static com.android.tools.r8.apimodel.ApiModelingTestHelper.setMockApiLevelForDefaultInstanceInitializer; import static com.android.tools.r8.apimodel.ApiModelingTestHelper.setMockApiLevelForMethod; import static com.android.tools.r8.apimodel.ApiModelingTestHelper.verifyThat; import static com.android.tools.r8.utils.codeinspector.CodeMatchers.invokesMethodWithName; import static com.android.tools.r8.utils.codeinspector.Matchers.isPresent; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; import com.android.tools.r8.CompilationMode; import com.android.tools.r8.NeverInline; import com.android.tools.r8.SingleTestRunResult; import com.android.tools.r8.TestBase; import com.android.tools.r8.TestCompilerBuilder; import com.android.tools.r8.TestParameters; import com.android.tools.r8.TestParametersCollection; import com.android.tools.r8.ToolHelper.DexVm.Version; import com.android.tools.r8.testing.AndroidBuildVersion; import com.android.tools.r8.utils.AndroidApiLevel; import com.android.tools.r8.utils.codeinspector.CodeInspector; import com.android.tools.r8.utils.codeinspector.FoundMethodSubject; import com.android.tools.r8.utils.codeinspector.MethodSubject; import java.lang.reflect.Method; import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class ApiModelOutlineDuplicateMethodTest extends TestBase { private final AndroidApiLevel classApiLevel = AndroidApiLevel.K; private final AndroidApiLevel methodApiLevel = AndroidApiLevel.M; @Parameter public TestParameters parameters; @Parameters(name = "{0}") public static TestParametersCollection data() { return getTestParameters().withAllRuntimesAndApiLevels().build(); } private Method addedOn23() throws Exception { return LibraryClass.class.getMethod("addedOn23"); } private void setupTestBuilder(TestCompilerBuilder testBuilder) throws Exception { testBuilder .addProgramClasses(Main.class, TestClass.class) .addLibraryClasses(LibraryClass.class) .addDefaultRuntimeLibrary(parameters) .setMinApi(parameters.getApiLevel()) .addAndroidBuildVersion() .apply(setMockApiLevelForClass(LibraryClass.class, classApiLevel)) .apply(setMockApiLevelForDefaultInstanceInitializer(LibraryClass.class, classApiLevel)) .apply(setMockApiLevelForMethod(addedOn23(), methodApiLevel)) // TODO(b/213552119): Remove when enabled by default. .apply(ApiModelingTestHelper::enableApiCallerIdentification) .apply(ApiModelingTestHelper::enableOutliningOfMethods) .apply(ApiModelingTestHelper::disableStubbingOfClasses); } public boolean addToBootClasspath() { return parameters.isDexRuntime() && parameters.getRuntime().maxSupportedApiLevel().isGreaterThanOrEqualTo(classApiLevel); } @Test public void testD8Debug() throws Exception { // TODO(b/197078995): Make this work on 12+. assumeFalse( parameters.isCfRuntime() || parameters.getDexRuntimeVersion().isNewerThanOrEqual(Version.V12_0_0)); testForD8() .setMode(CompilationMode.DEBUG) .apply(this::setupTestBuilder) .compile() .applyIf(addToBootClasspath(), b -> b.addBootClasspathClasses(LibraryClass.class)) .run(parameters.getRuntime(), Main.class) .apply(this::checkOutput) .inspect(this::inspect); } @Test public void testD8Release() throws Exception { assumeFalse( parameters.isCfRuntime() || parameters.getDexRuntimeVersion().isNewerThanOrEqual(Version.V12_0_0)); testForD8() .setMode(CompilationMode.RELEASE) .apply(this::setupTestBuilder) .compile() .applyIf(addToBootClasspath(), b -> b.addBootClasspathClasses(LibraryClass.class)) .run(parameters.getRuntime(), Main.class) .apply(this::checkOutput) .inspect(this::inspect); } @Test public void testR8() throws Exception { // TODO(b/197078995): Make this work on 12+. assumeTrue( parameters.isCfRuntime() || parameters.getDexRuntimeVersion().isOlderThan(Version.V12_0_0)); testForR8(parameters.getBackend()) .apply(this::setupTestBuilder) .addKeepMainRule(Main.class) .enableInliningAnnotations() .compile() .applyIf(addToBootClasspath(), b -> b.addBootClasspathClasses(LibraryClass.class)) .run(parameters.getRuntime(), Main.class) .apply(this::checkOutput) .inspect(this::inspect); } private void inspect(CodeInspector inspector) throws Exception { int classCount = parameters.isDexRuntime() && parameters.getApiLevel().isLessThan(methodApiLevel) ? 4 : 3; assertEquals(classCount, inspector.allClasses().size()); Method testMethod = TestClass.class.getDeclaredMethod("test"); verifyThat(inspector, parameters, addedOn23()).isOutlinedFromUntil(testMethod, methodApiLevel); if (parameters.isDexRuntime() && parameters.getApiLevel().isLessThan(methodApiLevel)) { // Verify that we invoke the synthesized outline, addedOn23, twice. Optional synthesizedAddedOn23 = inspector.allClasses().stream() .flatMap(clazz -> clazz.allMethods().stream()) .filter( methodSubject -> methodSubject.isSynthetic() && invokesMethodWithName("addedOn23").matches(methodSubject)) .findFirst(); assertTrue(synthesizedAddedOn23.isPresent()); MethodSubject testMethodSubject = inspector.method(testMethod); assertThat(testMethodSubject, isPresent()); assertEquals( 2, testMethodSubject .streamInstructions() .filter( instructionSubject -> { if (!instructionSubject.isInvoke()) { return false; } return instructionSubject .getMethod() .asMethodReference() .equals(synthesizedAddedOn23.get().asMethodReference()); }) .count()); } } private void checkOutput(SingleTestRunResult runResult) { if (parameters.isDexRuntime() && parameters.getApiLevel().isGreaterThanOrEqualTo(methodApiLevel)) { runResult.assertSuccessWithOutputLines( "LibraryClass::addedOn23", "LibraryClass::addedOn23", "Hello World"); } else { runResult.assertSuccessWithOutputLines("Hello World"); } } // Only present from api level 19. public static class LibraryClass { public void addedOn23() { System.out.println("LibraryClass::addedOn23"); } } public static class TestClass { @NeverInline public static void test() { if (AndroidBuildVersion.VERSION >= 19) { LibraryClass libraryClass = new LibraryClass(); if (AndroidBuildVersion.VERSION >= 23) { libraryClass.addedOn23(); libraryClass.addedOn23(); } } System.out.println("Hello World"); } } public static class Main { public static void main(String[] args) { TestClass.test(); } } } src/main/java/io/github/parj/App.java package io.github.parj; import io.fabric8.kubernetes.api.model.Pod; import io.fabric8.kubernetes.client.*; import io.github.parj.service.WebHooks; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.core.io.ClassPathResource; @SpringBootApplication public class App { private static final Logger logger = LoggerFactory.getLogger(App.class); @Autowired private WebHooks webHooks; public static void main(String[] args) throws InterruptedException { SpringApplication.run(App.class, args); } @Bean public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() { PropertySourcesPlaceholderConfigurer propsConfig = new PropertySourcesPlaceholderConfigurer(); propsConfig.setLocation(new ClassPathResource("git.properties")); propsConfig.setIgnoreResourceNotFound(true); propsConfig.setIgnoreUnresolvablePlaceholders(true); return propsConfig; } } NLPCCd/Camel/5320_2.java //,temp,sample_4286.java,2,10,temp,sample_8080.java,2,12 //,3 public class xxx { public static void stopGrpcServer() throws IOException { if (grpcServerWithTLS != null) { grpcServerWithTLS.shutdown(); } if (grpcServerWithJWT != null) { grpcServerWithJWT.shutdown(); log.info("grpc server with jwt stoped"); } } };0 package IA.Controllers; import IA.ErrorHandler; import IA.SceneChanger; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Cursor; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.KeyCode; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.text.Text; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class loginController implements Initializable { private SceneChanger changer = new SceneChanger(); @FXML private Pane mainPane; @FXML private TextField usernameField; @FXML private PasswordField passwordField; @FXML private Text signUpText; @FXML private Text incorrectText; @FXML private Button loginButton; @FXML void onLogInButton(ActionEvent event) throws IOException { login(); } @Override public void initialize(URL location, ResourceBundle resources){ mainPane.setOnKeyPressed(e -> { if(e.getCode().equals(KeyCode.ENTER)) { try { login(); } catch (IOException ioException) { ioException.printStackTrace(); ErrorHandler.display(ioException.getMessage()); } } }); } private void login() throws IOException { if(IA.Main.db.getLogin(usernameField.getText(),passwordField.getText())){ changer.mainScene(); } else{ incorrectText.setFill(Color.valueOf("#F04747")); usernameField.setStyle("-fx-border-color: #F04747; -fx-background-color: #3C3F41; -fx-text-fill: #FFFFFF; -fx-border-radius: 4;"); passwordField.setStyle("-fx-border-color: #F04747; -fx-background-color: #3C3F41; -fx-text-fill: #FFFFFF; -fx-border-radius: 4;"); } } @FXML void onSignUpButton(ActionEvent event) throws IOException { changer.signUpScene(); } } CockroachIOT-backend/src/main/java/com/cockroachiot/CockroachIOTApplication.java package com.yikekong; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients @EnableConfigurationProperties @EnableScheduling @EnableAsync public class YkkApplication{ public static void main(String[] args) { SpringApplication.run( YkkApplication.class, args); } } MirageCircuitGenerator/src/jsnark/util/Util.java /******************************************************************************* * Author: <> *******************************************************************************/ package jsnark.util; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import jsnark.circuit.structure.Wire; public class Util { // seeded by 1 for testing purposes static Random rand = new Random(1); public static BigInteger[] split(BigInteger x, int numchunks, int chunksize) { BigInteger[] chunks = new BigInteger[numchunks]; BigInteger mask = new BigInteger("2").pow(chunksize).subtract(BigInteger.ONE); for (int i = 0; i < numchunks; i++) { chunks[i] = x.shiftRight(chunksize * i).and(mask); } return chunks; } public static BigInteger combine(BigInteger[] table, Wire[] blocks, int bitwidth) { BigInteger sum = BigInteger.ZERO; for (int i = 0; i < blocks.length; i++) { if (table[blocks[i].getWireId()] == null) { continue; } sum = sum.add(table[blocks[i].getWireId()].multiply(new BigInteger("2").pow(bitwidth * i))); } return sum; } public static BigInteger group(BigInteger[] list, int width) { BigInteger x = BigInteger.ZERO; for (int i = 0; i < list.length; i++) { x = x.add(list[i].shiftLeft(width * i)); } return x; } public static int[] concat(int[] a1, int[] a2) { int[] all = new int[a1.length + a2.length]; for (int i = 0; i < all.length; i++) { all[i] = i < a1.length ? a1[i] : a2[i - a1.length]; } return all; } public static Wire[] concat(Wire[] a1, Wire[] a2) { Wire[] all = new Wire[a1.length + a2.length]; for (int i = 0; i < all.length; i++) { all[i] = i < a1.length ? a1[i] : a2[i - a1.length]; } return all; } public static Wire[] concat(Wire w, Wire[] a) { Wire[] all = new Wire[1 + a.length]; for (int i = 0; i < all.length; i++) { all[i] = i < 1 ? w : a[i - 1]; } return all; } public static int[] concat(int[][] arrays) { int sum = 0; for (int i = 0; i < arrays.length; i++) { sum += arrays[i].length; } int[] all = new int[sum]; int idx = 0; for (int i = 0; i < arrays.length; i++) { for (int j = 0; j < arrays[i].length; j++) { all[idx++] = arrays[i][j]; } } return all; } public static BigInteger[] randomBigIntegerArray(int num, BigInteger n) { BigInteger[] result = new BigInteger[num]; for (int i = 0; i < num; i++) { result[i] = nextRandomBigInteger(n); } return result; } public static BigInteger nextRandomBigInteger(BigInteger n) { BigInteger result = new BigInteger(n.bitLength(), rand); while (result.compareTo(n) >= 0) { result = new BigInteger(n.bitLength(), rand); } return result; } public static BigInteger[] randomBigIntegerArray(int num, int numBits) { BigInteger[] result = new BigInteger[num]; for (int i = 0; i < num; i++) { result[i] = nextRandomBigInteger(numBits); } return result; } public static BigInteger nextRandomBigInteger(int numBits) { BigInteger result = new BigInteger(numBits, rand); return result; } public static String getDesc(String... desc) { if (desc.length == 0) { return ""; } else { return desc[0]; } } public static ArrayList parseSequenceLists(String s) { ArrayList list = new ArrayList(); String[] chunks = s.split(","); for (String chunk : chunks) { if (chunk.equals("")) continue; int lower = Integer.parseInt(chunk.split(":")[0]); int upper = Integer.parseInt(chunk.split(":")[1]); for (int i = lower; i <= upper; i++) { list.add(i); } } return list; } public static Wire[] reverseBytes(Wire[] inBitWires) { Wire[] outs = Arrays.copyOf(inBitWires, inBitWires.length); int numBytes = inBitWires.length / 8; for (int i = 0; i < numBytes / 2; i++) { int other = numBytes - i - 1; for (int j = 0; j < 8; j++) { Wire temp = outs[i * 8 + j]; outs[i * 8 + j] = outs[other * 8 + j]; outs[other * 8 + j] = temp; } } return outs; } public static String arrayToString(int[] a, String separator) { StringBuilder s = new StringBuilder(); for (int i = 0; i < a.length - 1; i++) { s.append(a[i] + separator); } s.append(a[a.length - 1]); return s.toString(); } public static String arrayToString(Wire[] a, String separator) { StringBuilder s = new StringBuilder(); for (int i = 0; i < a.length - 1; i++) { s.append(a[i] + separator); } s.append(a[a.length - 1]); return s.toString(); } public static boolean isBinary(BigInteger v) { return v.equals(BigInteger.ZERO) || v.equals(BigInteger.ONE); } public static String padZeros(String s, int l) { return String.format("%" + l + "s",s).replace(' ', '0'); } public static BigInteger computeMaxValue(int numBits){ return BigIntStorage.getInstance().getBigInteger( new BigInteger("2").pow(numBits).subtract( BigInteger.ONE)); } public static BigInteger computeBound(int numBits){ return BigIntStorage.getInstance().getBigInteger( new BigInteger("2").pow(numBits)); } public static BigInteger[] split(BigInteger x, int chunksize) { int numChunks = (int)Math.ceil(x.bitLength()*1.0/chunksize); BigInteger[] chunks = new BigInteger[numChunks]; BigInteger mask = new BigInteger("2").pow(chunksize).subtract(BigInteger.ONE); for (int i = 0; i < numChunks; i++) { chunks[i] = x.shiftRight(chunksize * i).and(mask); } return chunks; } public static Wire[] padWireArray(Wire[] a, int length, Wire p) { if (a.length == length) { return a; } else if (a.length > length) { System.err.println("No padding needed!"); return a; } else { Wire[] newArray = new Wire[length]; System.arraycopy(a, 0, newArray, 0, a.length); for (int k = a.length; k < length; k++) { newArray[k] = p; } return newArray; } } public static int[] padIntArray(int[] a, int length, int p) { if (a.length == length) { return a; } else if (a.length > length) { System.err.println("No padding needed!"); return a; } else { int[] newArray = new int[length]; System.arraycopy(a, 0, newArray, 0, a.length); for (int k = a.length; k < length; k++) { newArray[k] = p; } return newArray; } } } package org.ehrbase.client.classgenerator.examples.testalltypesenv1composition.definition; import org.ehrbase.client.annotations.Entity; import org.ehrbase.client.annotations.OptionFor; import org.ehrbase.client.annotations.Path; @Entity @OptionFor("DV_QUANTITY") public class TestAllTypesChoiceDvquantity implements TestAllTypesChoiceChoice { @Path("|magnitude") private Double choiceMagnitude; @Path("|units") private String choiceUnits; public void setChoiceMagnitude(Double choiceMagnitude) { this.choiceMagnitude = choiceMagnitude; } public Double getChoiceMagnitude() { return this.choiceMagnitude; } public void setChoiceUnits(String choiceUnits) { this.choiceUnits = choiceUnits; } public String getChoiceUnits() { return this.choiceUnits; } } 10-100 package org.tibennetwork.iarcade.mame; public class MachineHasNoSoftwareListException extends Exception { static final long serialVersionUID = 7L; public MachineHasNoSoftwareListException(String s) { super(s); } } package com.example.hello; class NotFoundException extends RuntimeException { private static final long serialVersionUID = 7839872909036678944L; NotFoundException(String message) { super(message); } } 10-100 /* ### * IP: GHIDRA * * 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 agent.dbgeng.jna.dbgeng; import java.util.List; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.platform.win32.BaseTSD.ULONG_PTR; import com.sun.jna.platform.win32.WinDef.*; public class WinNTExtra { public static enum Machine { IMAGE_FILE_MACHINE_UNKNOWN(0, "Unknown"), // IMAGE_FILE_MACHINE_I386(0x014c, "x86"), // IMAGE_FILE_MACHINE_ARM(0x01c0, "ARM"), // IMAGE_FILE_MACHINE_IA64(0x0200, "Itanium"), // IMAGE_FILE_MACHINE_AMD64(0x8664, "AMD64 (K8)"), // IMAGE_FILE_MACHINE_EBC(0x0EBC, "EFI"), // ; public static Machine getByNumber(int val) { for (Machine m : Machine.values()) { if (m.val == val) { return m; } } return null; } Machine(int val, String description) { this.val = val; this.description = description; } public final int val; public final String description; } public static class M128A extends Structure { public static class ByReference extends M128A implements Structure.ByReference { } public static final List FIELDS = createFieldsOrder("Low", "High"); public ULONGLONG Low; public LONGLONG High; @Override protected List getFieldOrder() { return FIELDS; } } public static class CONTEXT_AMD64 extends Structure { public static class ByReference extends CONTEXT_AMD64 implements Structure.ByReference { } public static final List FIELDS = createFieldsOrder( "P1Home", "P2Home", "P3Home", "P4Home", "P5Home", "P6Home", "ContextFlags", "MxCsr", "SegCs", "SegDs", "SegEs", "SegFs", "SegGs", "SegSs", "EFlags", "Dr0", "Dr1", "Dr2", "Dr3", "Dr6", "Dr7", "Rax", "Rcx", "Rdx", "Rbx", "Rsp", "Rbp", "Rsi", "Rdi", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15", "Rip", "Header", "Legacy", "Xmm0", "Xmm1", "Xmm2", "Xmm3", "Xmm4", "Xmm5", "Xmm6", "Xmm7", "Xmm8", "Xmm9", "Xmm10", "Xmm11", "Xmm12", "Xmm13", "Xmm14", "Xmm15", "VectorRegister", "VectorControl", "DebugControl", "LastBranchToRip", "LastBranchFromRip", "LastExceptionToRip", "LastExceptionFromRip"); public DWORDLONG P1Home; public DWORDLONG P2Home; public DWORDLONG P3Home; public DWORDLONG P4Home; public DWORDLONG P5Home; public DWORDLONG P6Home; public DWORD ContextFlags; public DWORD MxCsr; public WORD SegCs; public WORD SegDs; public WORD SegEs; public WORD SegFs; public WORD SegGs; public WORD SegSs; public DWORD EFlags; public DWORDLONG Dr0; public DWORDLONG Dr1; public DWORDLONG Dr2; public DWORDLONG Dr3; public DWORDLONG Dr6; public DWORDLONG Dr7; public DWORDLONG Rax; public DWORDLONG Rcx; public DWORDLONG Rdx; public DWORDLONG Rbx; public DWORDLONG Rsp; public DWORDLONG Rbp; public DWORDLONG Rsi; public DWORDLONG Rdi; public DWORDLONG R8; public DWORDLONG R9; public DWORDLONG R10; public DWORDLONG R11; public DWORDLONG R12; public DWORDLONG R13; public DWORDLONG R14; public DWORDLONG R15; public DWORDLONG Rip; public M128A[] Header = new M128A[2]; public M128A[] Legacy = new M128A[8]; public M128A Xmm0; public M128A Xmm1; public M128A Xmm2; public M128A Xmm3; public M128A Xmm4; public M128A Xmm5; public M128A Xmm6; public M128A Xmm7; public M128A Xmm8; public M128A Xmm9; public M128A Xmm10; public M128A Xmm11; public M128A Xmm12; public M128A Xmm13; public M128A Xmm14; public M128A Xmm15; public M128A[] VectorRegister = new M128A[26]; public DWORDLONG VectorControl; public DWORDLONG DebugControl; public DWORDLONG LastBranchToRip; public DWORDLONG LastBranchFromRip; public DWORDLONG LastExceptionToRip; public DWORDLONG LastExceptionFromRip; @Override protected List getFieldOrder() { return FIELDS; } } public static class EXCEPTION_RECORD extends Structure { public static class ByReference extends EXCEPTION_RECORD implements Structure.ByReference { } public static final List FIELDS = createFieldsOrder("ExceptionCode", "ExceptionFlags", "ExceptionRecord", "ExceptionAddress", "NumberParameters", "__unusedAlignment", "ExceptionInformation"); public DWORD ExceptionCode; public DWORD ExceptionFlags; public EXCEPTION_RECORD.ByReference ExceptionRecord; public Pointer ExceptionAddress; public DWORD NumberParameters; public ULONG_PTR ExceptionInformation[] = new ULONG_PTR[15]; @Override protected List getFieldOrder() { return FIELDS; } } public static class EXCEPTION_RECORD32 extends Structure { public static class ByReference extends EXCEPTION_RECORD64 implements Structure.ByReference { } public static final List FIELDS = createFieldsOrder("ExceptionCode", "ExceptionFlags", "ExceptionRecord", "ExceptionAddress", "NumberParameters", "__unusedAlignment", "ExceptionInformation"); public DWORD ExceptionCode; public DWORD ExceptionFlags; public DWORD ExceptionRecord; public DWORD ExceptionAddress; public DWORD NumberParameters; public DWORD __unusedAlignment; public DWORD ExceptionInformation[] = new DWORD[15]; @Override protected List getFieldOrder() { return FIELDS; } } public static class EXCEPTION_RECORD64 extends Structure { public static class ByReference extends EXCEPTION_RECORD64 implements Structure.ByReference { } public static final List FIELDS = createFieldsOrder("ExceptionCode", "ExceptionFlags", "ExceptionRecord", "ExceptionAddress", "NumberParameters", "__unusedAlignment", "ExceptionInformation"); public DWORD ExceptionCode; public DWORD ExceptionFlags; public DWORDLONG ExceptionRecord; public DWORDLONG ExceptionAddress; public DWORD NumberParameters; public DWORD __unusedAlignment; public DWORDLONG ExceptionInformation[] = new DWORDLONG[15]; @Override protected List getFieldOrder() { return FIELDS; } } public static class EXCEPTION_POINTERS extends Structure { public static class ByReference extends EXCEPTION_POINTERS implements Structure.ByReference { } public static final List FIELDS = createFieldsOrder("ExceptionRecord", "ContextRecord"); public EXCEPTION_RECORD.ByReference ExceptionRecord; public CONTEXT_AMD64.ByReference ContextRecord; // TODO: This should be fine for now @Override protected List getFieldOrder() { return FIELDS; } } public static class MEMORY_BASIC_INFORMATION64 extends Structure { public static class ByReference extends MEMORY_BASIC_INFORMATION64 implements Structure.ByReference { } public static final List FIELDS = createFieldsOrder("BaseAddress", "AllocationBase", "AllocationProtect", "__alignment1", "RegionSize", "State", "Protect", "Type", "__alignment2"); public ULONGLONG BaseAddress; public ULONGLONG AllocationBase; public DWORD AllocationProtect; public DWORD __alignment1; public ULONGLONG RegionSize; public DWORD State; public DWORD Protect; public DWORD Type; public DWORD __alignment2; @Override protected List getFieldOrder() { return FIELDS; } } } chapter_002/src/main/java/professions/Patient.java0 package professions; /** * @author * @version 0.0.0.1 * @since 2018.12.01 * класс пациент */ public class Patient { /** * имя */ private String name; } package io.gitlab.jfronny.motortunez; import com.sedmelluq.discord.lavaplayer.player.AudioPlayer; import com.sedmelluq.discord.lavaplayer.player.event.AudioEventAdapter; import com.sedmelluq.discord.lavaplayer.tools.FriendlyException; import com.sedmelluq.discord.lavaplayer.track.AudioTrack; import com.sedmelluq.discord.lavaplayer.track.AudioTrackEndReason; import io.gitlab.jfronny.motortunez.gui.TunezScreen; import net.minecraft.client.MinecraftClient; import net.minecraft.client.gui.screen.Screen; import net.minecraft.client.toast.SystemToast; import net.minecraft.text.TranslatableText; import java.util.ArrayList; import java.util.List; public class TrackScheduler extends AudioEventAdapter { public List tracks = new ArrayList<>(); public void queue(AudioTrack track) { if (track == null) return; MotorTunez.log.info(track.getInfo().title); if (!MotorTunez.player.startTrack(track, true)) { if (tracks.contains(track) || MotorTunez.player.getPlayingTrack() == track) track = track.makeClone(); tracks.add(track); } refreshUI(); } public void setPaused(boolean paused) { MotorTunez.player.setPaused(paused); refreshUI(); } public void setVolume(float volume) { MotorTunez.player.setVolume((int)(volume * 100)); } @Override public void onPlayerPause(AudioPlayer player) { MotorTunez.log.info("Player paused"); } @Override public void onPlayerResume(AudioPlayer player) { MotorTunez.log.info("Player resumed"); } @Override public void onTrackEnd(AudioPlayer player, AudioTrack track, AudioTrackEndReason endReason) { if (endReason.mayStartNext) { playNext(player); } else { refreshUI(); } // endReason == FINISHED: A track finished or died by an exception (mayStartNext = true). // endReason == LOAD_FAILED: Loading of a track failed (mayStartNext = true). // endReason == STOPPED: The player was stopped. // endReason == REPLACED: Another track started playing while this had not finished // endReason == CLEANUP: Player hasn't been queried for a while, if you want you can put a // clone of this back to your queue } @Override public void onTrackException(AudioPlayer player, AudioTrack track, FriendlyException exception) { MotorTunez.toast(new TranslatableText("motor_tunez.toast.trackException.title"), new TranslatableText("motor_tunez.toast.trackException.description"), SystemToast.Type.PACK_COPY_FAILURE); MotorTunez.log.error(exception); } @Override public void onTrackStuck(AudioPlayer player, AudioTrack track, long thresholdMs) { MotorTunez.toast(new TranslatableText("motor_tunez.toast.trackStuck.title"), new TranslatableText("motor_tunez.toast.trackStuck.description", thresholdMs), SystemToast.Type.PACK_COPY_FAILURE); playNext(player); } public void playNext(AudioPlayer player) { if (hasNext()) { player.playTrack(tracks.get(0)); tracks.remove(0); } else { player.stopTrack(); } refreshUI(); } public boolean hasNext() { return !tracks.isEmpty(); } public void refreshUI() { Screen screen = MinecraftClient.getInstance().currentScreen; if (screen instanceof TunezScreen) { ((TunezScreen)screen).construct(); } } } Starshiplad/Worldmaker9000worldbuilder/Map.java package worldbuilder; import java.awt.Color; import java.io.File; import java.io.FileFilter; import java.io.FileWriter; import java.io.IOException; import java.util.*; public class Map { private boolean[][] isFull; private int[][] types; Random random=new Random(); public Map(int Size) { isFull= new boolean[Size][Size]; types= new int[Size][Size]; for(int i=0;i Mono.just(requestHandler)) .bind(LocalServerTransport.create("test-local-server")) .block(); RSocket rsocket = RSocketConnector.connectWith(LocalClientTransport.create("test-local-server")).block(); AtomicBoolean ff = new AtomicBoolean(); IPCRSocket service = Server.service("HelloService") .noMeterRegistry() .noTracer() .marshall(Strings.marshaller()) .unmarshall(Strings.unmarshaller()) .requestResponse("hello", (s, byteBuf) -> Mono.just("Hello -> " + s)) .requestResponse("goodbye", (s, byteBuf) -> Mono.just("Goodbye -> " + s)) .requestResponse( "count", Primitives.intMarshaller(), (charSequence, byteBuf) -> Mono.just(charSequence.length())) .requestResponse( "increment", Primitives.intUnmarshaller(), Primitives.intMarshaller(), (integer, byteBuf) -> Mono.just(integer + 1)) .requestStream( "helloStream", (s, byteBuf) -> Flux.range(1, 10).map(i -> i + " - Hello -> " + s)) .requestStream( "toString", Primitives.longUnmarshaller(), (aLong, byteBuf) -> Flux.just(String.valueOf(aLong))) .fireAndForget( "ff", (s, byteBuf) -> { ff.set(true); return Mono.empty(); }) .requestChannel("helloChannel", (s, publisher, byteBuf) -> Flux.just("Hello -> " + s)) .toIPCRSocket(); requestHandler.withEndpoint(service); Client helloService = Client.service("HelloService") .rsocket(rsocket) .customMetadataEncoder(new DefaultMetadataEncoder(ByteBufAllocator.DEFAULT)) .noMeterRegistry() .noTracer() .marshall(Strings.marshaller()) .unmarshall(Strings.unmarshaller()); String r1 = helloService.requestResponse("hello").apply("Alice").block(); Assert.assertEquals("Hello -> Alice", r1); String r2 = helloService.requestResponse("goodbye").apply("Bob").block(); Assert.assertEquals("Goodbye -> Bob", r2); StepVerifier.create(helloService.requestStream("helloStream").apply("Carol")) .expectNextCount(10) .expectComplete() .verify(); helloService.fireAndForget("ff").apply("boom").block(); Assert.assertTrue(ff.get()); String r3 = helloService.requestChannel("helloChannel").apply(Mono.just("Eve")).blockLast(); Assert.assertEquals("Hello -> Eve", r3); int count = helloService.requestResponse("count", Primitives.intUnmarshaller()).apply("hello").block(); Assert.assertEquals(5, count); long l = System.currentTimeMillis(); String toString = helloService.requestStream("toString", Primitives.longMarshaller()).apply(l).blockLast(); Assert.assertEquals(String.valueOf(l), toString); Integer increment = helloService .requestResponse("increment", Primitives.intMarshaller(), Primitives.intUnmarshaller()) .apply(1) .block(); Assert.assertEquals(2, increment.intValue()); } } 10-100 package kz.kuzhagaliyev.TimboKZ.ActiveVisualiser.RenderModes; import kz.kuzhagaliyev.TimboKZ.ActiveVisualiser.RenderMode; import org.lwjgl.opengl.Display; import static org.lwjgl.opengl.GL11.*; /** * @author * @since 05-12-2014 */ public class Test extends RenderMode { public Test(String name, int key) { super(name, key); } public void render(float delta) { glPushMatrix(); { glColor3f(1.0f, 1.0f, 1.0f); glBegin(GL_QUADS); { glVertex2f(0, Display.getHeight() / 2 - 1); glVertex2f(0, Display.getHeight() / 2 + 1); glVertex2f(Display.getWidth(), Display.getHeight() / 2 + 1); glVertex2f(Display.getWidth(), Display.getHeight() / 2 - 1); } glEnd(); glBegin(GL_QUADS); { glVertex2f(Display.getWidth() / 2 - 1, 0); glVertex2f(Display.getWidth() / 2 - 1, Display.getHeight()); glVertex2f(Display.getWidth() / 2 + 1, Display.getHeight()); glVertex2f(Display.getWidth() / 2 + 1, 0); } glEnd(); } glPopMatrix(); } } 1-10 /* * Copyright 2000-2012 JetBrains s.r.o. * * 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.jetbrains.ether; import org.jetbrains.jps.builders.java.dependencyView.Mappings; import org.jetbrains.jps.incremental.relativizer.PathRelativizerService; import java.io.File; /** * @author: db */ public class StorageDumper { private static class Env { final String myProjectPath; final String myOutputPath; final String myErrors; final boolean myHelp; Env(final String[] args) { int s = 0; String projectPath = null; String outputPath = null; boolean help = false; final StringBuilder errors = new StringBuilder(); for (final String arg : args) { switch (s) { case 0: // Initial state if (arg.equals("-o")) { s = 1; } else if (arg.equals("-h")) { help = true; } else if (arg.startsWith("-")) { errors.append("Unrecognized option: "); errors.append(arg); errors.append("\n"); } else { if (projectPath != null) { errors.append("Multiple storage paths specified, skipping "); errors.append(arg); errors.append("\n"); } else { projectPath = arg; } } break; case 1: // -o if (arg.startsWith("-")) { errors.append("Output path expected after \"-o\", but found: "); errors.append(arg); errors.append("\n"); } else { if (outputPath != null) { errors.append("Multiple output paths specified, skipping "); errors.append(arg); errors.append("\n"); } else { outputPath = arg; } } s = 0; } } myOutputPath = outputPath; myProjectPath = projectPath; myHelp = help; myErrors = errors.toString(); } String getProjectPath() { return myProjectPath; } String getOutputPath() { return myOutputPath; } String getErrors() { return myErrors; } void report() { if (myHelp) { System.out.println("Usage: [-o | -h ] "); System.out.println(); } System.err.println(myErrors); } } public static void main(final String[] args) { final Env env = new Env(args); env.report(); final String dataPath = env.getProjectPath(); final String oath = env.getOutputPath(); if (dataPath == null) { System.err.println("No project path specified."); } else { try { final File parent = new File(oath == null ? "" : oath); final File dataStorageRoot = new File(dataPath, "mappings"); final Mappings mappings = new Mappings(dataStorageRoot, new PathRelativizerService()); try { //final File outputPath = new File(parent, "snapshot-" + new SimpleDateFormat("dd-MM-yy(hh-mm-ss)").format(new Date()) + ".log"); //FileUtil.createIfDoesntExist(outputPath); //final PrintStream p = new PrintStream(outputPath); //mappings.toStream(p); //p.close(); mappings.toStream(parent); } finally { mappings.close(); } } catch (Exception e) { throw new RuntimeException(e); } } } } benmccann/closure-templates /* * Copyright 2010 Google 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 com.google.template.soy.parsepasses.contextautoesc; /** * Utilities for dealing with the names of derived templates. * *

* A derived template is a template that is called in a specific context. * A user may specify some templates that are called in multiple contexts or a single obscure * context such as the template {@code foo} below: *

 * {template main}
 *   <a onclick="alert({call foo/})">{call foo /}</a>
 * {/template}
 * {template foo private="true" autoescape="contextual"}
 *   {print $msg}
 * {/template}
 * 
* * There is no single escaping context which makes sense for {@code $msg}. So the auto-escaper * derives an extra template producing something like: *
 * {template main}
 *   <a onclick="alert({call foo/})">{call foo /}</a>
 * {/template}
 * {template foo private="true"}
 *   {print $msg |escapeHtml}
 * {/template}
 * {template foo__X1234 private="true"}
 *   {print $msg |escapeJsValue}
 * {/template}
 * 
* *

* Each derived template has a name that is built by name mangling an original template name with * the template's start {@link Context context}. * A derived template's name (or qualified name) looks like:

 *     qualifiedName ::== baseName [separator context]
 *                                 ^^^^^^^^^^^^^^^^^^^
 *                                          |
 *                                        suffix
 * 
* *

* The base name is the name of a template in the original Soy source. * The separator is a fixed string. * The context is derived from the {@link Context#packedBits} of the template's start context. * The separator and context together form a suffix. * *

* As shown above, the suffix is optional. The suffix is omitted for any template whose context * is the default starting context: {@link Context#HTML_PCDATA pcdata}. * */ public final class DerivedTemplateUtils { /** Separates the base name from the packed bits. */ private static final String CONTEXT_SEPARATOR = "__C"; /** * The suffix as described above. * * @return the empty string when the suffix is optional. */ public static String getSuffix(Context startContext) { if (Context.HTML_PCDATA.equals(startContext)) { // The default when autoescape=true. return ""; } else { return CONTEXT_SEPARATOR + Integer.toString(startContext.packedBits(), 16); } } /** * The base name for the given template name whether derived or not. */ public static String getBaseName(String templateName) { int separatorIndex = templateName.lastIndexOf(CONTEXT_SEPARATOR); return separatorIndex < 0 ? templateName : templateName.substring(0, separatorIndex); } /** * A derived name for a template derived from the given base template and the given start context. */ public static String getQualifiedName(String baseName, Context startContext) { return getBaseName(baseName) + getSuffix(startContext); } private DerivedTemplateUtils() { // Not instantiable. } } //Lomuto partition of quick sort //This is similar to the implementation of QuickSort //The difference is that once we select the last element as the pivot //we need to keep adjusting its position by sorting and swapping the elements in memory. import java.util.Scanner; public class Main { public static void main(String[]args) { Scanner sc = new Scanner(System.in); System.out.println("Enter size of the array:"); int n =sc.nextInt(); int[] ar = new int[n]; System.out.println("Enter array elements:"); for(int i=0;irrokclient/src/main/java/com/cn/request/request/base/BaseRequest.java package com.cn.request.request.base; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * Date: 2019/8/1 *

* Time: 4:16 PM *

* author: 鹿文龙 */ public abstract class BaseRequest { public String url; public HashMap headers; public HashMap params; public BaseRequest(String url) { this.url = url; headers = new LinkedHashMap<>(); params = new LinkedHashMap<>(); } //################ header ################### @SuppressWarnings("unchecked") public R header(String key, String value) { headers.put(key, value); return (R) this; } @SuppressWarnings("unchecked") public R header(String key, int value) { headers.put(key, String.valueOf(value)); return (R) this; } @SuppressWarnings("unchecked") public R header(String key, double value) { headers.put(key, String.valueOf(value)); return (R) this; } @SuppressWarnings("unchecked") public R haders(HashMap headers) { for (Map.Entry entry : headers.entrySet()) { this.headers.put(entry.getKey(), entry.getValue()); } return (R) this; } //################ 参数 ################### @SuppressWarnings("unchecked") public R param(String key, String value) { params.put(key, value); return (R) this; } @SuppressWarnings("unchecked") public R param(String key, int value) { params.put(key, String.valueOf(value)); return (R) this; } @SuppressWarnings("unchecked") public R param(String key, double value) { params.put(key, String.valueOf(value)); return (R) this; } @SuppressWarnings("unchecked") public R params(HashMap params) { for (Map.Entry entry : params.entrySet()) { this.params.put(entry.getKey(), entry.getValue()); } return (R) this; } } 1-10 package com.group_finity.mascot.generic; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; import java.awt.image.ImageProducer; import javax.swing.Icon; import javax.swing.ImageIcon; import com.group_finity.mascot.image.NativeImage; /** * (@ Link GenericTranslucentWindow) a value that can be used with images. * * (@ Link GenericTranslucentWindow) is available because only Windows bitmap * (@ Link BufferedImage) existing copy pixels from a Windows bitmap. * * Original Author: of Group Finity (http://www.group-finity.com/Shimeji/) * Currently developed by Shimeji-ee Group. */ class GenericNativeImage implements NativeImage{ /** * Java Image object. */ private final BufferedImage managedImage; private final Icon icon; public GenericNativeImage(final BufferedImage image) { this.managedImage = image; this.icon = new ImageIcon(image); } @Override protected void finalize() throws Throwable { super.finalize(); } public void flush() { this.getManagedImage().flush(); } public Graphics getGraphics() { return this.getManagedImage().createGraphics(); } public int getHeight() { return this.getManagedImage().getHeight(); } public int getWidth() { return this.getManagedImage().getWidth(); } public int getHeight(final ImageObserver observer) { return this.getManagedImage().getHeight(observer); } public Object getProperty(final String name, final ImageObserver observer) { return this.getManagedImage().getProperty(name, observer); } public ImageProducer getSource() { return this.getManagedImage().getSource(); } public int getWidth(final ImageObserver observer) { return this.getManagedImage().getWidth(observer); } BufferedImage getManagedImage() { return this.managedImage; } public Icon getIcon() { return this.icon; } } /* Copyright 2013 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 io.neba.api.annotations; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** *

* Can be used to specify an OSGi service filter to narrow the service(s) that shall be * injected. *

* *
 * @javax.inject.Inject
 * @{@link Filter}("(&(property=value)(otherProperty=otherValue))")
 * private SomeService service;
 * 
* * This annotation can not be used on a Spring bean. There, use an XML configuration or the gemini blueprint @ServiceReference annotation. * * @since 5.0.0 */ @Retention(RUNTIME) @Target({PARAMETER, FIELD, ANNOTATION_TYPE}) public @interface Filter { String value(); } package org.tron.core.net.messagehandler; import java.util.ArrayList; import org.junit.Test; import org.tron.core.net.message.InventoryMessage; import org.tron.core.net.peer.PeerConnection; import org.tron.protos.Protocol.Inventory.InventoryType; public class InventoryMsgHandlerTest { private InventoryMsgHandler handler = new InventoryMsgHandler(); private PeerConnection peer = new PeerConnection(); @Test public void testProcessMessage() { InventoryMessage msg = new InventoryMessage(new ArrayList<>(), InventoryType.USDL); peer.setNeedSyncFromPeer(true); peer.setNeedSyncFromUs(true); handler.processMessage(peer, msg); peer.setNeedSyncFromPeer(true); peer.setNeedSyncFromUs(false); handler.processMessage(peer, msg); peer.setNeedSyncFromPeer(false); peer.setNeedSyncFromUs(true); handler.processMessage(peer, msg); } } mschneider/flutter_google_cast_pluginexample/android/app/src/main/java/com/flutter_google_cast_plugin_example/MainActivity.java package com.flutter_google_cast_plugin_example; import android.os.Bundle; import com.flutter_google_cast_plugin.FlutterGoogleCastPlugin; import com.google.android.gms.cast.framework.CastContext; import io.flutter.app.FlutterActivity; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FlutterGoogleCastPlugin.setContext(this); FlutterGoogleCastPlugin.setTheme(new DefaultFlutterGoogleCastTheme()); GeneratedPluginRegistrant.registerWith(this); } } 0 package com.ehu.response.elasticsearch; import lombok.Getter; import lombok.Setter; /** * @author alan * @createtime 17-12-28 * elasticsearch返回类 */ @Getter @Setter public class ElasticsearchResponse { private Hits hits; } /******************************************************************************* * Copyright 2012 * * 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 ch.mimo.netty.handler.codec.icap; import org.jboss.netty.buffer.ChannelBuffer; /** * Decoder State that reads one huge chunk into many smaller chunks * * @author () * * @see IcapMessageDecoder * @see StateEnum */ public class ReadChunkedContentAsChunksState extends State { public ReadChunkedContentAsChunksState(String name) { super(name); } @Override public void onEntry(ChannelBuffer buffer, IcapMessageDecoder icapMessageDecoder) throws DecodingException { } @Override public StateReturnValue execute(ChannelBuffer buffer, IcapMessageDecoder icapMessageDecoder) throws DecodingException { IcapChunk chunk = null; if(icapMessageDecoder.currentChunkSize > icapMessageDecoder.maxChunkSize) { chunk = new DefaultIcapChunk(buffer.readBytes(icapMessageDecoder.maxChunkSize)); icapMessageDecoder.currentChunkSize -= icapMessageDecoder.maxChunkSize; } else { chunk = new DefaultIcapChunk(buffer.readBytes(icapMessageDecoder.currentChunkSize)); icapMessageDecoder.currentChunkSize = 0; } chunk.setPreviewChunk(icapMessageDecoder.message.isPreviewMessage()); if(chunk.isLast()) { icapMessageDecoder.currentChunkSize = 0; return StateReturnValue.createRelevantResult(new Object[]{chunk,new DefaultIcapChunkTrailer()}); } return StateReturnValue.createRelevantResult(chunk); } @Override public StateEnum onExit(ChannelBuffer buffer, IcapMessageDecoder icapMessageDecoder, Object decisionInformation) throws DecodingException { if(icapMessageDecoder.currentChunkSize == 0) { return StateEnum.READ_CHUNK_DELIMITER_STATE; } return StateEnum.READ_CHUNKED_CONTENT_AS_CHUNKS_STATE; } } package com.javathinking.batch.example; import com.javathinking.batch.event.EmailNotification; import com.javathinking.batch.event.EmailNotificationFactory; import com.javathinking.batch.event.Event; import com.javathinking.batch.event.EventService; import com.javathinking.batch.job.AbstractTask; import com.javathinking.batch.job.Queue; import com.javathinking.batch.job.TaskResult; import com.javathinking.batch.job.TaskResult.Result; import com.javathinking.batch.validation.XmlSchemaRule; import com.javathinking.commons.validation.Errors; import com.javathinking.commons.validation.Validator; import org.apache.commons.lang.SystemUtils; import org.apache.log4j.Logger; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.List; /** * @author paul */ public class ShipOrderProcessorTask extends AbstractTask { private static final Logger log = Logger.getLogger(ShipOrderProcessorTask.class); private static final String SHIP_ORDER_XSD = "com/javathinking/batch/example/shiporder.xsd"; private Validator validator; private EventService eventService; private EmailNotificationFactory emailNotificationFactory; public ShipOrderProcessorTask(String discriminator, String name) { super(discriminator, name); validator = new Validator(); validator.add(new XmlSchemaRule(this.getClass().getClassLoader().getResource(SHIP_ORDER_XSD))); } /** * Process a unzipped file, given the directory it was unzipped to. *

* So, for each file in the directory we: * 1. validate the schema * 2. then process the data. *

* This could be split into 2 tasks, but this implementation shows how these steps can easily be combined * if it makes sense to. *

* Note that our previous validation checked that only one file was in the zip file, but this task is written * without that consideration - it will simply process all files. */ public TaskResult process(Object obj) { Queue queue = (Queue) obj; File dir = new File((String) queue.getData()); log.info("Processing files in " + dir.getAbsolutePath()); File[] files = dir.listFiles(new FilenameFilter() { public boolean accept(File f, String name) { return (name.toUpperCase().endsWith(".XML")); } }); Errors errors = new Errors(); List failedFiles = new ArrayList(); for (File file : files) { Errors errs = validator.validate(file); errors.add(errs); log.debug("XML schema validation for " + file + (errs.isEmpty() ? " successful" : " failed [" + errs.toString() + "]")); if (errs.isEmpty()) { // TODO process data } else { failedFiles.add(file); } } if (!errors.isEmpty()) { Event event = new Event(getName(), "Processing failed", getDiscriminator()); EmailNotification notification = emailNotificationFactory.get(Example1.PROC_FAILED_EMAIL); notification.setContent("Processing failed for files in " + dir + " (" + errors.toString() + ")"); for (File f : failedFiles) { notification.addAttachment(f.getName(), f); } event.addNotification(notification); eventService.send(event); } else { Event event = new Event(getName(), "Processing Successful", getDiscriminator()); EmailNotification notification = emailNotificationFactory.get(Example1.PROC_SUCCESS_EMAIL); notification.setContent("Processing successful for files in " + dir + SystemUtils.LINE_SEPARATOR); event.addNotification(notification); eventService.send(event); } return new TaskResult(errors.isEmpty() ? Result.SUCCESS : Result.FAIL, dir.getAbsolutePath()); } public void setEventService(EventService eventService) { this.eventService = eventService; } void setEmailNotificationFactory(EmailNotificationFactory emailNotificationFactory) { this.emailNotificationFactory = emailNotificationFactory; } } package codeblockutil; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridLayout; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Ellipse2D; import java.awt.geom.GeneralPath; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class CSlider extends JPanel implements MouseListener, MouseMotionListener{ private static final long serialVersionUID = 328149080257L; /** Property name of the event thrown by this widget */ public static String VALUE_CHANGED = "VALUE_CHANGED"; /** Rendering Hints of this */ static final RenderingHints renderingHints = new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); /** this.value */ private int value; /** The value representing the left side of slider */ private int left; /** The value representing the right side of the slider */ private int right; /** track color from min to value */ private final Color leadingColor; /** track color from value to max */ private final Color trailingColor; /** color of thumb */ private final Color thumbColor; private final SliderBlueprint blueprint; private final float trackThickness;//a floating point number between 0 and 1 private int offset = 0; private int thumbStart = 0; // position where the thumb starts off private boolean setTicks = false; // on off ticks private int tickNumber = 1; //number of ticks when ticks/sticky is turned on private boolean startMark = false; // whether the start mark of the thumb is turned on private String startMarkLabel = ""; //what the label for the start point is /** * @requires none * @effects Constructs a CSlider such that this.min=0 && this.max=100 && * this.value = 50 && the track color from min to value * is RED && the track color from value to max is gray && * the color of the thumb is BROWN */ public CSlider(){ this(0,100,50,0.2f, Color.blue, Color.black, Color.gray, false, 0, false, ""); } /** * @param left - the value representing the left side of the slider * @param right - the value representing the right side of the slider * @param value - this.value * * @requires min(left, right)Math.max(this.left, this.right)){ this.setValue(Math.max(this.left, this.right)); } this.repaint(); } /** * sets the value representing the left side of slider * @param left * * @requires min(left, right)Math.max(this.left, this.right)){ this.setValue(Math.max(this.left, this.right)); } this.repaint(); } /** * sets value * @param val * * @requires min(left, right)Math.max(this.left, this.right)){ this.value = Math.max(this.left, this.right); }else{ this.value = val; } this.repaint(); this.firePropertyChange(VALUE_CHANGED, oldvalue, this.value); } /** * creates the shape of the track on the left side of the thumb * @param blueprint * @return general path shape of track on the left side of the thumb */ public Shape reformLeadingTrack(SliderBlueprint blueprint){ GeneralPath shape = new GeneralPath(); shape.moveTo(blueprint.closeTrackEdgeLeft, blueprint.trackTop); shape.lineTo(blueprint.thumbCenter, blueprint.trackTop); shape.lineTo(blueprint.thumbCenter, blueprint.trackBottom); shape.lineTo(blueprint.closeTrackEdgeLeft, blueprint.trackBottom); shape.curveTo(blueprint.farTrackEdgeLeft, blueprint.trackBottom, blueprint.farTrackEdgeLeft, blueprint.trackTop, blueprint.closeTrackEdgeLeft, blueprint.trackTop); shape.closePath(); return shape; } /** * creates the shape of the track on the right side of the thumb * @param blueprint * @return general path shape of the track on the right side of the thumb */ public Shape reformTrailingTrack(SliderBlueprint blueprint){ GeneralPath shape = new GeneralPath(); shape.moveTo(blueprint.thumbCenter, blueprint.trackTop); shape.lineTo(blueprint.closeTrackEdgeRight, blueprint.trackTop); shape.curveTo(blueprint.farTrackEdgeRight, blueprint.trackTop, blueprint.farTrackEdgeRight, blueprint.trackBottom, blueprint.closeTrackEdgeRight, blueprint.trackBottom); shape.lineTo(blueprint.thumbCenter, blueprint.trackBottom); shape.lineTo(blueprint.thumbCenter, blueprint.trackTop); shape.closePath(); return shape; } /** * creates the shape of the thumb * @param blueprint * @param diameter * @return ellipse of the thumb */ public Shape reformThumb(SliderBlueprint blueprint, int diameter){ return new Ellipse2D.Double(blueprint.thumbCenter-diameter/2, blueprint.trackMiddleY-diameter/2, diameter, diameter); } /** * creates the shape of the ticks * @param blueprint * @return general path of the ticks */ public Shape reformTicks(SliderBlueprint blueprint){ GeneralPath ticks = new GeneralPath(); int count = 0; float position = blueprint.closeTrackEdgeLeft; float interval = (float) (blueprint.closeTrackEdgeRight-blueprint.closeTrackEdgeLeft)/this.tickNumber; while (count < (tickNumber + 1)) { ticks.moveTo((int) position, blueprint.trackTop); ticks.lineTo((int) position, blueprint.trackBottom); position += interval; count += 1; } ticks.closePath(); return ticks; } /** * Sets the values in the class SliderBlueprint * @param blueprint * @param width * @param height * @param girth * @param thumbX - distance from the upper left corner to the center of the thumb */ public void reformBlueprint(SliderBlueprint blueprint, int width, int height, int girth, int thumbX){ blueprint.farTrackEdgeLeft=height/2-girth/2; blueprint.closeTrackEdgeLeft=height/2; blueprint.thumbCenter=thumbX; blueprint.closeTrackEdgeRight=width-height/2; blueprint.farTrackEdgeRight=width-height/2+girth/2; blueprint.trackTop=height/2-girth/2; blueprint.trackMiddleY=height/2; blueprint.trackBottom=height/2+girth/2; } /** * Paints the CSlider */ public void paintComponent(Graphics g){ Graphics2D g2 = (Graphics2D)g; g2.addRenderingHints(renderingHints); // gets the distance from the left side of the slider to the thumb in pixel int thumbX = getThumbX(); this.reformBlueprint(blueprint, this.getWidth(), this.getHeight(), (int)(trackThickness*this.getHeight()), thumbX); Shape leading = this.reformLeadingTrack(blueprint); Shape trailing = this.reformTrailingTrack(blueprint); Shape thumb = this.reformThumb(blueprint, this.getHeight()/2); Shape miniThumb = this.reformThumb(blueprint, this.getHeight()/4); //draw shapes g2.setPaint(new GradientPaint( 0,blueprint.trackTop,this.leadingColor, 0,blueprint.trackBottom, Color.white, false)); g2.fill(leading); g2.setPaint(new GradientPaint( 0,blueprint.trackTop,this.trailingColor, 0,blueprint.trackBottom, Color.white, false)); g2.fill(trailing); g2.setColor(new Color(250,250,250,100)); g2.draw(leading); g2.draw(trailing); // draws the tick marks if ticks are turned on // also draws where the triangle where thumb starts g2.setColor(Color.lightGray); if (this.tickNumber != 0 && this.setTicks) { Shape ticks = this.reformTicks(blueprint); g2.draw(ticks); } // draws the start label if start mark is turned on // depending on what the start mark was set as when initialized if (this.startMark) { g2.setColor(Color.white); Font font = new Font("Dialog", Font.PLAIN, 8); FontMetrics metrics = getFontMetrics(font); // gets the width of the text so that the words can be centered later on int textWidth = metrics.stringWidth(startMarkLabel); g2.setFont(font); g2.drawString(startMarkLabel, (int) (convertToPixels(this.thumbStart) - (textWidth/2)),(int) (blueprint.trackBottom*1.7)); } //g2.setPaint(new GradientPaint(0,0,Color.white,0,th,this.thumbColor, false)); g2.setColor(Color.lightGray); g2.fill(thumb); //g2.setPaint(new GradientPaint(0,0,Color.darkGray,0,th,this.thumbColor, false)); g2.setColor(Color.darkGray); g2.fill(miniThumb); g2.setColor(thumbColor); g2.draw(thumb); } /** * returns the distance from the left of slider to the center of the thumb (converts to pixels) * @return the distance from the left of slider to the center of the thumb */ private int getThumbX(){ int i = this.right-this.left; return blueprint.closeTrackEdgeLeft+(this.value-this.left)*(blueprint.closeTrackEdgeRight-blueprint.closeTrackEdgeLeft)/(i == 0 ? 1 : i); } /** * Given an x value in pixels (offset from this component's left side) returns * the associated value on the slider. * @param value the X coordinate * @return the slider value associated with the given X coordinate */ private int convertToAbstract(int value){ float i = blueprint.closeTrackEdgeRight - blueprint.closeTrackEdgeLeft; return this.left+(int)Math.round((value-blueprint.closeTrackEdgeLeft)*(this.right-this.left)/(i == 0 ? 1 : i)); } /** * Given an x value in slider value returns * the associated pixels (offset from this component's left side) * @param value the slider value * @return x coordinates associated with the slider value */ private int convertToPixels(int value){ float i = this.right-this.left; return blueprint.closeTrackEdgeLeft + (int)Math.round((value-this.left)*(blueprint.closeTrackEdgeRight-blueprint.closeTrackEdgeLeft)/(i == 0 ? 1 : i)); } public void mousePressed(MouseEvent e) { int thumbX = getThumbX(); // offset is if the mouse clicked on the thumb if(Math.abs(e.getX()-thumbX)= this.right) { xPos = this.right; } else if (xPos <= this.left) { xPos = this.left; // if not at the intervals, set position to the intervals } else if (remain != 0) { // move to smaller numbered position if (remain <= (interval/2)) { //check if goes past beginning position, if true then set to beginning position if ((Math.abs(this.thumbStart - xPos) < (interval - remain)) || ((xPos < this.thumbStart) && ((xPos - remain) > this.thumbStart) && ((xPos + interval) > this.thumbStart))){ xPos = this.thumbStart; } else { xPos = xPos - remain; } // move to larger numbered position } else { //check if goes past beginning position, if true then set to beginning position if ((Math.abs(this.thumbStart - xPos) < (interval - remain)) || ((xPos < this.thumbStart) && ((xPos + (interval - remain)) > this.thumbStart) && ((xPos + interval) > this.thumbStart))) { xPos = this.thumbStart; } else { xPos = xPos + (interval-remain); } } } else if (remain == 0) { xPos = mouseReleaseXPos; }else { xPos = this.thumbStart; } this.setValue(xPos); } /** debugging */ public static void main(String[] args) { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setLayout(new GridLayout(0,1)); f.setSize(400, 200); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); final CSlider c1 = new CSlider(0,200,105, true, 10); panel.add(c1,BorderLayout.CENTER); panel.add(new JLabel("label:"), BorderLayout.WEST); CSlider c2 = new CSlider(0,200,100); CSlider c3 = new CSlider(-5,5,0); CSlider c4 = new CSlider(2,0,1); CSlider c5 = new CSlider(0,2,1); CSlider c6 = new CSlider(0,0,0); CSlider c7 = new CSlider(0,200,100); f.add(panel); f.add(c2); f.add(c3); f.add(c4); f.add(c5); f.add(c6); f.add(c7); JButton b = new JButton(); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.out.println(c1.getValue()); c1.setRight(175); //c.setValue(125); c1.revalidate(); c1.repaint(); System.out.println(c1.getValue()); } }); f.add(b); f.setVisible(true); f.repaint(); } } /** * Contains the location for the CSlider components * (in pixels) */ class SliderBlueprint{ int farTrackEdgeLeft=0; int closeTrackEdgeLeft=0; int thumbCenter=0; int closeTrackEdgeRight=0; int farTrackEdgeRight=0; int trackTop=0; int trackMiddleY=0; int trackBottom=0; } package uk.gov.cslearning.catalogue.repository; import org.elasticsearch.common.unit.Fuzziness; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.MultiMatchQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.sort.SortBuilders; import org.elasticsearch.search.sort.SortOrder; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.stereotype.Repository; import uk.gov.cslearning.catalogue.api.FilterParameters; import uk.gov.cslearning.catalogue.api.OwnerParameters; import uk.gov.cslearning.catalogue.api.ProfileParameters; import uk.gov.cslearning.catalogue.domain.Course; import uk.gov.cslearning.catalogue.domain.SearchPage; import uk.gov.cslearning.catalogue.domain.Status; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; @Repository public class CourseSearchRepositoryImpl implements CourseSearchRepository { private ElasticsearchOperations operations; public CourseSearchRepositoryImpl(ElasticsearchOperations operations) { checkArgument(operations != null); this.operations = operations; } @Override public SearchPage search(String query, Pageable pageable, FilterParameters filterParameters, Collection statusCollection, OwnerParameters ownerParameters, ProfileParameters profileParameters, String visbility) { Page coursePage = executeSearchQuery(query, pageable, filterParameters, statusCollection, ownerParameters, profileParameters, visbility); SearchPage searchPage = new SearchPage(); searchPage.setCourses(coursePage); return searchPage; } private Page executeSearchQuery(String query, Pageable pageable, FilterParameters filterParameters, Collection statusCollection, OwnerParameters ownerParameters, ProfileParameters profileParameters, String visibility) { BoolQueryBuilder boolQuery = boolQuery(); if (isNotBlank(query)) { boolQuery = boolQuery.must(QueryBuilders.multiMatchQuery(query) .field("title", 8) .field("shortDescription", 4) .field("description", 2) .field("learningOutcomes", 2) .type(MultiMatchQueryBuilder.Type.BEST_FIELDS) .fuzziness(Fuzziness.ONE)); } if (filterParameters.hasTypes()) { BoolQueryBuilder filterQuery = QueryBuilders.boolQuery(); for (String type : filterParameters.getTypes()) { filterQuery = filterQuery .should(QueryBuilders.matchQuery("modules.type", type)) .should(QueryBuilders.matchQuery("type", type)); } filterQuery.minimumShouldMatch(1); boolQuery = boolQuery.must(filterQuery); } boolQuery = addFilter(boolQuery, filterParameters.getAreasOfWork(), "audiences.areasOfWork"); boolQuery = addFilter(boolQuery, filterParameters.getDepartments(), "audiences.departments"); boolQuery = addFilter(boolQuery, filterParameters.getInterests(), "audiences.interests"); if (filterParameters.hasCost()) { boolQuery = boolQuery .must(QueryBuilders.boolQuery() .should(QueryBuilders.matchQuery("modules.cost", 0)) .minimumShouldMatch(1)); } List statusList = new ArrayList<>(); statusCollection.forEach(s -> statusList.add(s.getValue())); boolQuery = addFilter(boolQuery, statusList, "status"); BoolQueryBuilder filterQuery = boolQuery(); if (ownerParameters.hasOrganisationalUnitCode()) { filterQuery.must(QueryBuilders.matchQuery("owner.organisationalUnit", ownerParameters.getOrganisationalUnitCode())); } if (ownerParameters.hasProfession()) { filterQuery.must(QueryBuilders.matchQuery("owner.profession", ownerParameters.getProfession())); } if (ownerParameters.hasSupplier()) { filterQuery.must(QueryBuilders.matchQuery("owner.supplier", ownerParameters.getSupplier())); } if (visibility.equals("PUBLIC")) { filterQuery.should(QueryBuilders.matchQuery("visibility", "PUBLIC")); } addOrFilter(filterQuery, profileParameters.getProfileDepartments(), "audiences.departments"); addOrFilter(filterQuery, profileParameters.getProfileGrades(), "audiences.grades"); addOrFilter(filterQuery, profileParameters.getProfileAreasOfWork(), "audiences.areasOfWork"); addOrFilter(filterQuery, profileParameters.getProfileInterests(), "audiences.interests"); SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(boolQuery) .withFilter(filterQuery) .withSort(SortBuilders.scoreSort().order(SortOrder.DESC)) .withPageable(pageable) .build(); return operations.queryForPage(searchQuery, Course.class); } @Override public Page findAllByOrganisationCode(String organisationalUnitCode, Pageable pageable) { BoolQueryBuilder boolQuery = boolQuery(); boolQuery.must(QueryBuilders.matchQuery("owner.organisationalUnit", organisationalUnitCode)); SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(boolQuery) .withPageable(pageable) .build(); return operations.queryForPage(searchQuery, Course.class); } @Override public Page findAllByProfessionId(String professionId, Pageable pageable) { BoolQueryBuilder boolQuery = boolQuery(); boolQuery.must(QueryBuilders.matchQuery("owner.profession", professionId)); SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(boolQuery) .withPageable(pageable) .build(); return operations.queryForPage(searchQuery, Course.class); } @Override public Page findAllBySupplier(String supplier, Pageable pageable) { BoolQueryBuilder boolQuery = boolQuery(); boolQuery.must(QueryBuilders.matchQuery("owner.supplier", supplier)); SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(boolQuery) .withPageable(pageable) .build(); return operations.queryForPage(searchQuery, Course.class); } private BoolQueryBuilder addFilter(BoolQueryBuilder boolQuery, List values, String key) { if (values != null && !values.isEmpty()) { BoolQueryBuilder filterQuery = QueryBuilders.boolQuery(); for (String department : values) { filterQuery = filterQuery .should(QueryBuilders.matchPhraseQuery(key, department)); } filterQuery.minimumShouldMatch(1); return boolQuery.must(filterQuery); } return boolQuery; } private BoolQueryBuilder addOrFilter(BoolQueryBuilder boolQuery, List values, String key) { if (values != null && !values.isEmpty()) { for (String value : values) { boolQuery.should(QueryBuilders.matchPhraseQuery(key, value)); } } return boolQuery; } } package slogo.view.menubar; import javafx.scene.control.ColorPicker; import javafx.scene.paint.Color; import slogo.controller.GlobalProperties; /** * Selector for pen color * * @author */ public class PenSelector extends MenuBarSelector { /** * Main constructor */ public PenSelector() { super("Pen Color", "PenSelector", "PenColorPicker", new ColorPicker(GlobalProperties.DEFAULT_PEN_COLOR)); } } 0 package net.minecraft.dispenser; import net.minecraft.block.DispenserBlock; import net.minecraft.entity.item.ItemEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.Direction; import net.minecraft.world.World; public class DefaultDispenseItemBehavior implements IDispenseItemBehavior { public final ItemStack dispense(IBlockSource p_dispense_1_, ItemStack p_dispense_2_) { ItemStack itemstack = this.execute(p_dispense_1_, p_dispense_2_); this.playSound(p_dispense_1_); this.playAnimation(p_dispense_1_, p_dispense_1_.getBlockState().getValue(DispenserBlock.FACING)); return itemstack; } protected ItemStack execute(IBlockSource p_82487_1_, ItemStack p_82487_2_) { Direction direction = p_82487_1_.getBlockState().getValue(DispenserBlock.FACING); IPosition iposition = DispenserBlock.getDispensePosition(p_82487_1_); ItemStack itemstack = p_82487_2_.split(1); spawnItem(p_82487_1_.getLevel(), itemstack, 6, direction, iposition); return p_82487_2_; } public static void spawnItem(World p_82486_0_, ItemStack p_82486_1_, int p_82486_2_, Direction p_82486_3_, IPosition p_82486_4_) { double d0 = p_82486_4_.x(); double d1 = p_82486_4_.y(); double d2 = p_82486_4_.z(); if (p_82486_3_.getAxis() == Direction.Axis.Y) { d1 = d1 - 0.125D; } else { d1 = d1 - 0.15625D; } ItemEntity itementity = new ItemEntity(p_82486_0_, d0, d1, d2, p_82486_1_); double d3 = p_82486_0_.random.nextDouble() * 0.1D + 0.2D; itementity.setDeltaMovement(p_82486_0_.random.nextGaussian() * (double)0.0075F * (double)p_82486_2_ + (double)p_82486_3_.getStepX() * d3, p_82486_0_.random.nextGaussian() * (double)0.0075F * (double)p_82486_2_ + (double)0.2F, p_82486_0_.random.nextGaussian() * (double)0.0075F * (double)p_82486_2_ + (double)p_82486_3_.getStepZ() * d3); p_82486_0_.addFreshEntity(itementity); } protected void playSound(IBlockSource p_82485_1_) { p_82485_1_.getLevel().levelEvent(1000, p_82485_1_.getPos(), 0); } protected void playAnimation(IBlockSource p_82489_1_, Direction p_82489_2_) { p_82489_1_.getLevel().levelEvent(2000, p_82489_1_.getPos(), p_82489_2_.get3DDataValue()); } }package com.shcem.common; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; /** * Created by lizhihua on 2017/2/16. */ public class ResponseData { private String DATA; private String CODE; private String INFO; public ResponseData(String code,String data,String info) { this.CODE=code; this.DATA=data; this.INFO=info; } public ResponseData(){ this.CODE="99999"; } public String getDATA() { return DATA; } public void setDATA(String DATA) { this.DATA = DATA; } public String getCODE() { return CODE; } public void setCODE(String CODE) { this.CODE = CODE; } public String getINFO() { return INFO; } public void setINFO(String INFO) { this.INFO = INFO; } @Override public String toString(){ JSONObject jsonObject=new JSONObject(); jsonObject.put("DATA",this.getDATA()); jsonObject.put("CODE",this.getCODE()); jsonObject.put("INFO",this.getINFO()); return jsonObject.toString(); } } package qcy.zk; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; public class ZkWatcher implements Watcher{ @Override public void process(WatchedEvent event) { System.out.println("===event===recieved"); } } /* * Copyright 2018 LifetionCoin Core Group * * 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 file was generated by SWIG (http://www.swig.org) and modified. * Version 3.0.12 */ package org.ltpj.bls; import com.google.common.base.Preconditions; public class ChainCode extends BLSObject { protected ChainCode(long cPtr, boolean cMemoryOwn) { super(cPtr, cMemoryOwn); } protected static long getCPtr(ChainCode obj) { return (obj == null) ? 0 : obj.cPointer; } protected void finalize() { delete(); } public synchronized void delete() { JNI.delete_ChainCode(cPointer); } public static ChainCode FromBytes(byte[] bytes) { Preconditions.checkNotNull(bytes); Preconditions.checkArgument(bytes.length == CHAIN_CODE_SIZE); return new ChainCode(JNI.ChainCode_FromBytes(bytes), true); } public ChainCode(ChainCode cc) { this(JNI.new_ChainCode(ChainCode.getCPtr(cc), cc), true); } public void Serialize(byte[] buffer) { Preconditions.checkNotNull(buffer); Preconditions.checkArgument(buffer.length >= CHAIN_CODE_SIZE); JNI.ChainCode_Serialize__SWIG_0(cPointer, this, buffer); } public byte [] Serialize() { byte [] bytes = new byte[(int)CHAIN_CODE_SIZE]; Serialize(bytes); return bytes; } @Override public String toString() { return "ChainCode(" + Utils.HEX.encode(Serialize()) + ")"; } public final static long CHAIN_CODE_SIZE = JNI.ChainCode_CHAIN_CODE_SIZE_get(); } /* * Copyright 2000-2012 JetBrains s.r.o. * * 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.jetbrains.webdemo.test.highlighting; import org.jetbrains.webdemo.kotlin.KotlinWrappersManager; import org.jetbrains.webdemo.kotlin.datastructures.ErrorDescriptor; import org.jetbrains.webdemo.kotlin.datastructures.Severity; import org.jetbrains.webdemo.kotlin.datastructures.TextInterval; import org.jetbrains.webdemo.kotlin.datastructures.TextPosition; import org.jetbrains.webdemo.test.BaseTest; import org.jetbrains.webdemo.test.TestUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.IOException; import java.util.*; @RunWith(Parameterized.class) public class HighlightingTest extends BaseTest { public HighlightingTest(String kotlinVersion) { super(kotlinVersion); } @Test public void test$errors$oneError() throws IOException, InterruptedException { String fileName = TestUtils.getNameByTestName(name.getMethodName()) + ".kt"; List expectedResult = new ArrayList<>(); expectedResult.add(new ErrorDescriptor( new TextInterval(new TextPosition(1, 2), new TextPosition(1, 8)), "Unresolved reference: prntln", Severity.ERROR, null )); compareResponseAndExpectedResult(fileName, expectedResult, false); } @Test public void test$errors$oneError$js() throws IOException, InterruptedException { String fileName = TestUtils.getNameByTestName(name.getMethodName()).substring(0, TestUtils.getNameByTestName(name.getMethodName()).length() - 3) + ".kt"; List expectedResult = new ArrayList<>(); expectedResult.add(new ErrorDescriptor( new TextInterval(new TextPosition(1, 2), new TextPosition(1, 8)), "Unresolved reference: prntln", Severity.ERROR, null )); compareResponseAndExpectedResult(fileName, expectedResult, true); } @Test public void test$warnings$oneWarning() throws IOException, InterruptedException { String fileName = TestUtils.getNameByTestName(name.getMethodName()) + ".kt"; List expectedResult = new ArrayList<>(); expectedResult.add(new ErrorDescriptor( new TextInterval(new TextPosition(2, 5), new TextPosition(2, 7)), "Unnecessary safe call on a non-null receiver of type Int", Severity.WARNING, null )); compareResponseAndExpectedResult(fileName, expectedResult, false); } @Test public void test$errors$twoErrorsInOneLine() throws IOException, InterruptedException { String fileName = TestUtils.getNameByTestName(name.getMethodName()) + ".kt"; List expectedResult = new ArrayList<>(); expectedResult.add(new ErrorDescriptor( new TextInterval(new TextPosition(1, 2), new TextPosition(1, 8)), "Unresolved reference: prntln", Severity.ERROR, null )); expectedResult.add(new ErrorDescriptor( new TextInterval(new TextPosition(1, 15), new TextPosition(1, 16)), "Expecting ')'", Severity.ERROR, "red_wavy_line" )); compareResponseAndExpectedResult(fileName, expectedResult, false); } private void compareResponseAndExpectedResult(String fileName, List expectedResult, boolean isJs) throws IOException { String fileContent = TestUtils.getDataFromFile(fileName); Map files = new HashMap<>(); files.put(fileName, fileContent); List actualErrors = kotlinWrapper.getErrors(files, isJs).get(fileName); for (ErrorDescriptor expectedError : expectedResult) { assertTrue(actualErrors.contains(expectedError)); } for (ErrorDescriptor actualError : actualErrors) { assertTrue(expectedResult.contains(actualError)); } } } package party.lemons.lklib.mixin; import net.minecraft.entity.ai.goal.Goal; import net.minecraft.entity.ai.goal.GoalSelector; import net.minecraft.entity.ai.goal.PrioritizedGoal; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import party.lemons.lklib.util.extension.GoalSelectorExtension; import java.util.Set; @Mixin(GoalSelector.class) public abstract class GoalSelectorMixin implements GoalSelectorExtension { @Shadow @Final private Set goals; @Shadow public abstract void remove(Goal goal); @Shadow public abstract void add(int priority, Goal goal); @Override public void lk_remove(Class goalClass) { goals.removeIf(g->g.getGoal().getClass().equals(goalClass)); } @Override public void lk_copy(GoalSelector from) { goals.removeIf((g)->true); for(PrioritizedGoal goal : ((GoalSelectorExtension)from).lk_getGoals()) add(goal.getPriority(), goal.getGoal()); } @Override public Set lk_getGoals() { return goals; } } /* * Copyright (C) 2019-2021 * * 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.mta.tehreer.demo; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import com.mta.tehreer.font.FontFile; import com.mta.tehreer.font.ColorPalette; import com.mta.tehreer.font.VariationAxis; import com.mta.tehreer.graphics.Typeface; import com.mta.tehreer.widget.TLabel; import java.util.Collections; import java.util.List; public class VariableFontsActivity extends AppCompatActivity { private Spinner mColorPaletteSpinner; private Spinner mVariableInstanceSpinner; private TLabel mPreviewLabel; private Typeface mTypeface; private float[] mVariationCoordinates; private AxisAdapter mAxisAdapter = new AxisAdapter(); private List mVariationAxes = Collections.emptyList(); private static class InstanceAdapter extends ArrayAdapter { public InstanceAdapter(@NonNull Context context, @NonNull FontFile fontFile) { super(context, android.R.layout.simple_spinner_item, fontFile.getTypefaces()); setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } public String getName(int position) { Typeface typeface = getItem(position); return typeface.getStyleName(); } @Override public @NonNull View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { TextView textView = (TextView) super.getView(position, convertView, parent); textView.setText(getName(position)); return textView; } @Override public @NonNull View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { TextView textView = (TextView) super.getDropDownView(position, convertView, parent); textView.setText(getName(position)); return textView; } } private class AxisAdapter extends BaseAdapter { @Override public int getCount() { return mVariationAxes.size(); } @Override public @NonNull VariationAxis getItem(int i) { return mVariationAxes.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); convertView = inflater.inflate(R.layout.item_variation_axis, parent, false); } final TextView axisName = convertView.findViewById(R.id.text_view_axis_name); final TextView minValue = convertView.findViewById(R.id.text_view_min_value); final SeekBar coordinateBar = convertView.findViewById(R.id.seek_bar_coordinate); final TextView maxValue = convertView.findViewById(R.id.text_view_max_value); VariationAxis variationAxis = getItem(position); axisName.setText(variationAxis.name()); minValue.setText(String.valueOf(variationAxis.minValue())); maxValue.setText(String.valueOf(variationAxis.maxValue())); coordinateBar.setOnSeekBarChangeListener(null); coordinateBar.setMax((int) ((variationAxis.maxValue() - variationAxis.minValue()) * 10)); coordinateBar.setProgress((int) ((mVariationCoordinates[position] - mVariationAxes.get(position).minValue()) * 10)); coordinateBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { float newValue = mVariationAxes.get(position).minValue() + (i / 10.0f); setupCoordinate(position, newValue); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); return convertView; } } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_variable_fonts); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } mVariableInstanceSpinner = findViewById(R.id.spinner_variable_instance); mVariableInstanceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView adapterView, View view, int i, long l) { InstanceAdapter instanceAdapter = (InstanceAdapter) adapterView.getAdapter(); setupTypeface(instanceAdapter.getItem(i)); } @Override public void onNothingSelected(AdapterView adapterView) { } }); mColorPaletteSpinner = findViewById(R.id.spinner_color_palette); mColorPaletteSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView adapterView, View view, int i, long l) { ColorPaletteAdapter paletteAdapter = (ColorPaletteAdapter) adapterView.getAdapter(); setupPalette(paletteAdapter.getItem(i).colors()); } @Override public void onNothingSelected(AdapterView adapterView) { } }); Spinner variableFontSpinner = findViewById(R.id.spinner_variable_font); variableFontSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView adapterView, View view, int i, long l) { VariableFontAdapter fontAdapter = (VariableFontAdapter) adapterView.getAdapter(); setupFont(fontAdapter.getFontFile(i)); } @Override public void onNothingSelected(AdapterView adapterView) { } }); variableFontSpinner.setAdapter(new VariableFontAdapter(this)); variableFontSpinner.setSelection(0); ListView listViewAxis = findViewById(R.id.list_view_axis); listViewAxis.setAdapter(mAxisAdapter); mPreviewLabel = findViewById(R.id.label_preview); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } private void setupFont(@NonNull FontFile fontFile) { mTypeface = fontFile.getTypefaces().get(0); mVariationAxes = mTypeface.getVariationAxes(); mVariationCoordinates = mTypeface.getVariationCoordinates(); mAxisAdapter.notifyDataSetChanged(); mVariableInstanceSpinner.setAdapter(new InstanceAdapter(this, fontFile)); mPreviewLabel.setTypeface(mTypeface); } private void setupTypeface(@NonNull Typeface typeface) { List palettes = typeface.getPredefinedPalettes(); if (palettes == null) { palettes = Collections.emptyList(); } mTypeface = typeface; mColorPaletteSpinner.setAdapter(new ColorPaletteAdapter(palettes)); mColorPaletteSpinner.setVisibility(palettes.isEmpty() ? View.GONE : View.VISIBLE); mVariationCoordinates = mTypeface.getVariationCoordinates(); mAxisAdapter.notifyDataSetChanged(); mPreviewLabel.setTypeface(mTypeface); } private void setupCoordinate(int axisIndex, float coordinate) { mVariationCoordinates[axisIndex] = coordinate; mTypeface = mTypeface.getVariationInstance(mVariationCoordinates); mPreviewLabel.setTypeface(mTypeface); } private void setupPalette(@NonNull int[] colors) { mTypeface = mTypeface.getColorInstance(colors); mPreviewLabel.setTypeface(mTypeface); } } GibraltarSoftware/loupe-java1-10 package com.onloupe.appenders.log4j; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.UUID; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.Core; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.core.config.plugins.Plugin; import org.apache.logging.log4j.core.config.plugins.PluginAttribute; import org.apache.logging.log4j.core.config.plugins.PluginFactory; import com.onloupe.core.logging.Log; import com.onloupe.core.logging.ThreadInfo; import com.onloupe.core.util.LogSystems; import com.onloupe.model.log.LogMessageSeverity; @Plugin(name="LoupeLog4jAppender", category= Core.CATEGORY_NAME, elementType= Appender.ELEMENT_TYPE, printObject=true) public final class LoupeLog4j2Appender extends AbstractAppender { private static final String LOG_SYSTEM = LogSystems.LOG4J; private static final int SKIP_FRAMES = 4; private static final Set EXCLUSIONS = new HashSet<>(Arrays.asList("org.apache.log4j")); private UUID appenderRef; private boolean failed; @Override public void append(LogEvent event) { if (failed || event == null || Level.OFF.equals(event.getLevel())) return; Log.write(mapSeverity(event.getLevel()), event.getThrown(), event.getSource(), SKIP_FRAMES, EXCLUSIONS, new ThreadInfo(event.getThreadId(), event.getThreadName()), LOG_SYSTEM, event.getLoggerName(), event.getMessage() != null ? event.getMessage().getFormattedMessage() : null, null); } protected LoupeLog4j2Appender(String name) { super(name, null, null); } @PluginFactory public static LoupeLog4j2Appender createAppender( @PluginAttribute("name") String name) { return new LoupeLog4j2Appender(name); } @Override public void start() { super.start(); try { appenderRef = Log.startAppender(super.getName()); } catch (IOException e) { System.err.print("Loupe failed to start: " + e.getMessage()); failed = true; } } @Override public void stop() { Log.shutdownAppender(appenderRef, false); super.stop(); } private LogMessageSeverity mapSeverity(Level level) { if (Level.FATAL.equals(level)) return LogMessageSeverity.CRITICAL; if (Level.ERROR.equals(level)) return LogMessageSeverity.ERROR; if (Level.WARN.equals(level)) return LogMessageSeverity.WARNING; if (Level.INFO.equals(level)) return LogMessageSeverity.INFORMATION; if (Level.DEBUG.equals(level) || Level.TRACE.equals(level)) return LogMessageSeverity.VERBOSE; return LogMessageSeverity.UNKNOWN; } } 0 /* * Copyright 2019 Red Hat, Inc. *

* Red Hat 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 com.redhat.idaas.connect.hl7; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; @Configuration @ConfigurationProperties(prefix = "idaas") public class ConfigProperties { private String kafkaHost = "localhost"; private int kafkaPort = 9092; private int adtPort = 10001; public String getKafkaHost() { return kafkaHost; } public int getKafkaPort() { return kafkaPort; } public int getAdtPort() { return adtPort; } } brenohof/orange-talents-05-template-proposta0 package br.com.zup.proposta.proposta; import br.com.zup.proposta.cartao.Cartao; import org.hibernate.annotations.GenericGenerator; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import javax.persistence.*; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import javax.validation.constraints.Positive; import java.math.BigDecimal; @Entity @Table(name = "propostas") public class Proposta { @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") private String id; @NotNull @Column(unique = true) private String documento; @NotNull private String email; @NotNull private String nome; @NotNull private String endereco; @NotNull private BigDecimal salario; @Enumerated(EnumType.STRING) private StatusProposta status; @OneToOne(mappedBy = "proposta", cascade = CascadeType.MERGE) private Cartao cartao; @Deprecated public Proposta() { } public Proposta(@NotBlank String documento, @NotBlank @Email String email, @NotBlank String nome, @NotBlank String endereco, @NotNull @Positive BigDecimal salario) { this.documento = documento; this.email = email; this.nome = nome; this.endereco = endereco; this.salario = salario; this.cartao = null; } public String getId() { return this.id; } public String getDocumento() { return documento; } public String getNome() { return nome; } public void defineStatus(StatusProposta status) { this.status = status; } public void associaCartao(Cartao cartao) { this.cartao = cartao; } public StatusProposta getStatus() { return this.status; } } package edu.salleurl.ls30394.foodfinderapp.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import java.util.List; import edu.salleurl.ls30394.foodfinderapp.Adapter.RestaurantAdapter; import edu.salleurl.ls30394.foodfinderapp.R; import edu.salleurl.ls30394.foodfinderapp.activities.RestaurantsListActivity; import edu.salleurl.ls30394.foodfinderapp.model.Restaurante; import edu.salleurl.ls30394.foodfinderapp.repositories.impl.FavoriteDB; import edu.salleurl.ls30394.foodfinderapp.repositories.impl.RestaurantsWebService; import edu.salleurl.ls30394.foodfinderapp.repositories.impl.UserDatabase; /** * Created by avoge on 20/05/2017. */ public class RestaurantListFragment extends Fragment { private ListView listView; private List list; private RestaurantAdapter adapter; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_search_result, container, false); listView = (ListView) view.findViewById(R.id.result_restaurants_list); if(getArguments().getBoolean("favs")){ FavoriteDB fdb = new FavoriteDB(getActivity()); UserDatabase udb = new UserDatabase(getActivity()); list = fdb.getAllFavorites(udb.getUserId(getArguments().getString("username"))); }else { list = RestaurantsWebService.getInstance(getActivity()).getResult(); } adapter = new RestaurantAdapter(getActivity(), list, getArguments().getBoolean("onlyOpen"), getArguments().getString("username")); listView.setAdapter(adapter); listView.setOnItemClickListener(adapter); ((RestaurantsListActivity)getActivity()).initSpinnerOptions(); return view; } public RestaurantAdapter getListAdapter(){ return adapter; } } hxwang/CloudSimEx package org.cloudbus.cloudsim.ex.geolocation.geoip2; import org.apache.commons.net.util.SubnetUtils; import org.apache.commons.net.util.SubnetUtils.SubnetInfo; import com.google.api.client.util.Objects; import com.google.common.base.Preconditions; /** * An immutable class representing an override rule for GeoIP services. * * @author nikolay.grozev * */ public class OverrideRule { private final String ip_prefix; private SubnetInfo netInfo; private final String location; private final double lon; private final double lat; private final String details; /** * Ctor. * * @param ip_prefix * - must be in the form IPv4/mask. May not be null; * @param location * - location of the address. May not be null. * @param lat * - the latitude. * @param lon * - the longitude. * @param details * - miscellaneous details. */ public OverrideRule(final String ip_prefix, final String location, final double lat, final double lon, final String details) { this.ip_prefix = ip_prefix; this.location = location; this.lon = lon; this.lat = lat; this.details = details; } protected SubnetInfo netInfo() { if (netInfo == null) { netInfo = new SubnetUtils(ip_prefix).getInfo(); } return netInfo; } /** * Returns if the specified IP address is in the range of this rule. * * @param ip * - the ip address. Must not be null. Must be in IPv4 notation. * @return if the specified IP address is in the range of this rule. */ public boolean matches(final String ip) { Preconditions.checkNotNull(ip); return netInfo().isInRange(ip); } public double getLon() { return lon; } public double getLat() { return lat; } public String getLocation() { return location; } @Override public String toString() { return Objects.toStringHelper(this).add("ip_prefix", ip_prefix).add("location", location).add("lon", lon) .add("lat", lat).add("Details", details).toString(); } } package com.bymarcin.openglasses.surface.widgets.component.face; import io.netty.buffer.ByteBuf; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.player.EntityPlayer; import org.lwjgl.opengl.GL11; import com.bymarcin.openglasses.surface.IRenderableWidget; import com.bymarcin.openglasses.surface.RenderType; import com.bymarcin.openglasses.surface.WidgetType; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class Quad extends TriangleWidget { public Quad() { x = new float[4]; y = new float[4]; } @Override public void writeData(ByteBuf buff) { super.writeData(buff); buff.writeFloat(x[3]); buff.writeFloat(y[3]); } @Override public void readData(ByteBuf buff) { super.readData(buff); x[3] = buff.readFloat(); y[3] = buff.readFloat(); } @SideOnly(Side.CLIENT) @Override public IRenderableWidget getRenderable() { return new RenderQuad(); } @SideOnly(Side.CLIENT) class RenderQuad implements IRenderableWidget{ @Override public void render(EntityPlayer player, double playerX, double playerY, double playerZ) { GL11.glEnable(GL11.GL_BLEND); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_ALPHA_TEST); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); Tessellator tessellator = Tessellator.instance; tessellator.startDrawing(GL11.GL_QUADS); tessellator.setColorRGBA_F(r, g, b, alpha); tessellator.addVertex(x[0], y[0], 0); tessellator.addVertex(x[1], y[1], 0); tessellator.addVertex(x[2], y[2], 0); tessellator.addVertex(x[3], y[3], 0); tessellator.draw(); GL11.glDisable(GL11.GL_BLEND); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_ALPHA_TEST); } @Override public RenderType getRenderType() { return RenderType.GameOverlayLocated; } @Override public boolean shouldWidgetBeRendered() { return isVisible(); } } @Override public WidgetType getType() { return WidgetType.QUAD; } } 0 package structural.adapter.inherit; import structural.adapter.compositeclass.AdapteeObject; import structural.adapter.compositeclass.Target; /** * Class adapter */ public class AdapterInheritAdaptee extends AdapteeObject implements Target { @Override public void newRequaiments() { System.out.println("todo something new things"); oldSpecificRequest(""); } } amalnev/jnms package ru.amalnev.selenium.language; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import ru.amalnev.selenium.interpreter.ExecutionContext; @Getter @Setter @AllArgsConstructor public class Variable implements IExpression { private String name; public String toString() { return name; } @Override public Object evaluate(final ExecutionContext context) { return context.getLocalVariable(name).getValue(); } } package net.explorviz.reconstructor; import java.time.Instant; import net.explorviz.avro.SpanStructure; import net.explorviz.avro.Timestamp; import net.explorviz.avro.landscape.flat.Application; import net.explorviz.avro.landscape.flat.Node; import net.explorviz.avro.landscape.flat.LandscapeRecord; import net.explorviz.reconstructor.stream.SpanToRecordConverter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class SpanToRecordConverterTest { private SpanToRecordConverter converter; private SpanStructure span; private LandscapeRecord record; @BeforeEach void setUp() { this.converter = new SpanToRecordConverter(); final Instant now = Instant.now(); final String token = "tok"; final String hostname = "Host"; final String hostIp = "192.168.3.11"; final String appName = "Test App"; final String appPid = "1234"; final String appLang = "java"; final String hashCode = "a387988168c607be0b2d886e75c85cb0f2f44ed41d45a1d800cdc857c04e98ae"; this.span = SpanStructure.newBuilder() .setSpanId("id") .setLandscapeToken(token) .setHashCode(hashCode) .setTimestamp(new Timestamp(now.getEpochSecond(), now.getNano())) .setHostname(hostname) .setHostIpAddress(hostIp) .setAppName(appName) .setAppPid(appPid) .setAppLanguage(appLang) .setFullyQualifiedOperationName("foo.bar.TestClass.testMethod()") .setHashCode("12345") .build(); this.record = LandscapeRecord.newBuilder() .setLandscapeToken(token) .setHashCode(hashCode) .setTimestamp(now.toEpochMilli()) .setNode(new Node(hostIp, hostname)) .setApplication(new Application(appName, appPid, appLang)) .setPackage$("foo.bar") .setClass$("TestClass") .setMethod("testMethod()") .setHashCode("12345") .build(); } @Test public void convert() { final LandscapeRecord got = this.converter.toRecord(this.span); Assertions.assertEquals(got, this.record, "Converted records does not match expected"); } } /* * Copyright 2016 The Bazel Authors. 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 com.google.idea.blaze.plugin; import com.intellij.openapi.components.AbstractProjectComponent; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowManager; import com.jetbrains.cidr.cpp.cmake.workspace.CMakeWorkspace; /** Runs on project startup, and customizes CLion UI. */ public class ClwbProjectSpecificInitializer extends AbstractProjectComponent { public ClwbProjectSpecificInitializer(Project project) { super(project); } @Override public void projectOpened() { // removes the CMake tool window for blaze projects ToolWindowManager manager = ToolWindowManager.getInstance(myProject); ToolWindow tw = manager.getToolWindow(CMakeWorkspace.TOOLWINDOW_ID); if (tw != null) { tw.setAvailable(false, null); } } } package org.motechproject.server.messagecampaign; public final class Constants { public static final int REPEATING_DEFAULT_START_OFFSET = 1; public static final String REPEATING_PROGRAM_24HRS_MESSAGE_DISPATCH_STRATEGY = "dispatch.24hours.strategy"; public static final String DAILY_REPEATING_DAYS_CRON_EXPRESSION = "1/1"; private Constants() { } } package com.example.sanja.mymessenger; import java.io.Serializable; import java.util.ArrayList; /** * Created by sanja on 6/21/2017. */ public class User implements Serializable{ String fname; String lname; String gender; String uname; String email; String password; String uid; String imageUrl; boolean isSelected; String status; ArrayList friendReq =new ArrayList<>(); ArrayList myFriends = new ArrayList<>(); public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } 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 getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public ArrayList getFriendReq() { return friendReq; } public void setFriendReq(ArrayList friendReq) { this.friendReq = friendReq; } public ArrayList getMyFriends() { return myFriends; } public void setMyFriends(ArrayList myFriends) { this.myFriends = myFriends; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public boolean isSelected() { return isSelected; } public void setSelected(boolean selected) { isSelected = selected; } @Override public String toString() { return "User{" + "fname='" + fname + '\'' + ", lname='" + lname + '\'' + ", gender='" + gender + '\'' + ", uname='" + uname + '\'' + ", email='" + email + '\'' + ", password='" + password + '\'' + ", uid='" + uid + '\'' + ", imageUrl='" + imageUrl + '\'' + ", status='" + status + '\'' + ", friendReq=" + friendReq + ", myFriends=" + myFriends + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; if (getFname() != null ? !getFname().equals(user.getFname()) : user.getFname() != null) return false; if (getLname() != null ? !getLname().equals(user.getLname()) : user.getLname() != null) return false; if (getGender() != null ? !getGender().equals(user.getGender()) : user.getGender() != null) return false; if (getUname() != null ? !getUname().equals(user.getUname()) : user.getUname() != null) return false; if (getEmail() != null ? !getEmail().equals(user.getEmail()) : user.getEmail() != null) return false; if (getPassword() != null ? !getPassword().equals(user.getPassword()) : user.getPassword() != null) return false; if (getUid() != null ? !getUid().equals(user.getUid()) : user.getUid() != null) return false; if (getImageUrl() != null ? !getImageUrl().equals(user.getImageUrl()) : user.getImageUrl() != null) return false; if (getFriendReq() != null ? !getFriendReq().equals(user.getFriendReq()) : user.getFriendReq() != null) return false; return getMyFriends() != null ? getMyFriends().equals(user.getMyFriends()) : user.getMyFriends() == null; } @Override public int hashCode() { int result = getFname() != null ? getFname().hashCode() : 0; result = 31 * result + (getLname() != null ? getLname().hashCode() : 0); result = 31 * result + (getGender() != null ? getGender().hashCode() : 0); result = 31 * result + (getUname() != null ? getUname().hashCode() : 0); result = 31 * result + (getEmail() != null ? getEmail().hashCode() : 0); result = 31 * result + (getPassword() != null ? getPassword().hashCode() : 0); result = 31 * result + (getUid() != null ? getUid().hashCode() : 0); result = 31 * result + (getImageUrl() != null ? getImageUrl().hashCode() : 0); result = 31 * result + (getFriendReq() != null ? getFriendReq().hashCode() : 0); result = 31 * result + (getMyFriends() != null ? getMyFriends().hashCode() : 0); return result; } } package mage.cards.p; import mage.MageInt; import mage.MageObject; import mage.abilities.Ability; import mage.abilities.common.DiesSourceTriggeredAbility; import mage.abilities.effects.common.search.SearchLibraryPutInPlayEffect; import mage.cards.*; import mage.constants.CardType; import mage.constants.SubType; import mage.filter.FilterCard; import mage.filter.common.FilterCreatureCard; import mage.game.Game; import mage.target.common.TargetCardInLibrary; import java.util.Objects; import java.util.UUID; /** * @author emerald000 */ public final class ProteanHulk extends CardImpl { public ProteanHulk(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{5}{G}{G}"); this.subtype.add(SubType.BEAST); this.power = new MageInt(6); this.toughness = new MageInt(6); // When Protean Hulk dies, search your library for any number of creature cards with total converted mana cost 6 or less and put them onto the battlefield. Then shuffle your library. this.addAbility(new DiesSourceTriggeredAbility(new SearchLibraryPutInPlayEffect(new ProteanHulkTarget()))); } private ProteanHulk(final ProteanHulk card) { super(card); } @Override public ProteanHulk copy() { return new ProteanHulk(this); } } class ProteanHulkTarget extends TargetCardInLibrary { private static final FilterCard filter = new FilterCreatureCard("any number of creature cards with total converted mana cost 6 or less"); ProteanHulkTarget() { super(0, Integer.MAX_VALUE, filter); } private ProteanHulkTarget(final ProteanHulkTarget target) { super(target); } @Override public ProteanHulkTarget copy() { return new ProteanHulkTarget(this); } @Override public boolean canTarget(UUID playerId, UUID id, Ability source, Game game) { if (!super.canTarget(playerId, id, source, game)) { return false; } Card card = game.getCard(id); if (card == null) { return false; } Cards cards = new CardsImpl(this.getTargets()); cards.add(id); return cards.getCards(game).stream().filter(Objects::nonNull).mapToInt(MageObject::getConvertedManaCost).sum() <= 6; } } SVFBr/mnautassrc/main/java/com/mnautas/handler/ResourceExceptionHandler.java package com.mnautas.handler; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import com.mnautas.domain.DetalhesErro; import com.mnautas.service.exception.AnuncioNaoEncontradoException; import com.mnautas.service.exception.AnunciosNaoEncontradosException; @ControllerAdvice public class ResourceExceptionHandler { @ExceptionHandler(AnunciosNaoEncontradosException.class) public ResponseEntity handleAnunciosNaoEncontradosException(AnunciosNaoEncontradosException e, HttpServletRequest request) { DetalhesErro detalhesErro = new DetalhesErro(); detalhesErro.setStatus(404l); detalhesErro.setTitulo("Não há anúncios cadastrados"); detalhesErro.setMensagemDesenvolvedor("http://erros.mnautas.com/404"); detalhesErro.setTimestamp(System.currentTimeMillis()); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(detalhesErro); } @ExceptionHandler(AnuncioNaoEncontradoException.class) public ResponseEntity handleAnuncioNaoEncontradoException(AnuncioNaoEncontradoException e, HttpServletRequest request) { DetalhesErro detalhesErro = new DetalhesErro(); detalhesErro.setStatus(404l); detalhesErro.setTitulo("Anúncio não localizado"); detalhesErro.setMensagemDesenvolvedor("http://erros.mnautas.com/404"); detalhesErro.setTimestamp(System.currentTimeMillis()); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(detalhesErro); } } package me.leovan.hive.udf.geo; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.List; public class CoordinateSystemConvertUDFTest { private final CoordinateSystemConvertUDF udf = new CoordinateSystemConvertUDF(); @Test public void testCoordinateSystemConvertUDF01() throws Exception { List toLatLng = udf.evaluate(39.909175, 116.397452, "GCJ02", "WGS84"); Assertions.assertEquals(39.907771, toLatLng.get(0), 1e-6); Assertions.assertEquals(116.391208, toLatLng.get(1), 1e-6); } @Test public void testCoordinateSystemConvertUDF02() throws Exception { List toLatLng = udf.evaluate(39.909175, 116.397452, "GCJ02", "BD09"); Assertions.assertEquals(39.915518, toLatLng.get(0), 1e-6); Assertions.assertEquals(116.403825, toLatLng.get(1), 1e-6); } } /*- * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= */ package org.onap.so.db.catalog.beans; public enum OrchestrationStatus { ACTIVE("Active", "active"), ACTIVATED("Activated", "activated"), ASSIGNED("Assigned", "assigned"), CREATED("Created", "created"), INVENTORIED("Inventoried", "inventoried"), PENDING("Pending", "pending"), PENDING_ACTIVATION("PendingActivation", "pending.?activation"), PENDING_CREATE("PendingCreate", "pending.?create"), PENDING_DELETE("PendingDelete", "pending.?delete"), PRECREATED("PreCreated", "pre.?created"), CONFIGASSIGNED("ConfigAssigned", "config.?assigned"), CONFIGURE("Configure", "configure"), CONFIGURED("Configured", "configured"), REGISTER("Register", "register"), REGISTERED("Registered", "registered"); private final String name; private final String fuzzyMatcher; private OrchestrationStatus(String name, String fuzzyMatcher) { this.name = name; this.fuzzyMatcher = fuzzyMatcher; } @Override public String toString() { return name; } /** * case insensitive regular expression match to enum value * * @param status * @return */ public boolean fuzzyMap(String status) { if (status != null) { return status.matches("(?i)" + this.fuzzyMatcher); } else { return false; } } } package com.otcdlink.chiron.testing.junit5; import org.junit.jupiter.api.extension.ExtendWith; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.ANNOTATION_TYPE; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target({ TYPE, METHOD, ANNOTATION_TYPE }) @Retention(RUNTIME) @ExtendWith( WithSystemPropertiesExtension.class ) public @interface WithSystemProperties { WithSystemProperty[] value() ; } daggerok/reactive-spring-transactions-example package com.example.demo; import lombok.*; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories; import org.springframework.stereotype.Component; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Flux; @Data @Document @Setter(AccessLevel.PROTECTED) @RequiredArgsConstructor(staticName = "of") @NoArgsConstructor(access = AccessLevel.PROTECTED) class MyData { @Id private String id; @NonNull private String body; } @Repository interface MyDataRepository extends ReactiveMongoRepository {} @Component @RequiredArgsConstructor class TestData implements ApplicationRunner { private final MyDataRepository myData; @Override public void run(ApplicationArguments args) throws Exception { Flux.just("one", "two", "three") .map(MyData::of) .flatMap(myData::save) .subscribe(System.out::println); } } @RestController @RequiredArgsConstructor class RestApi { private final MyDataRepository repository; @GetMapping public Flux index() { return repository.findAll(); } } @SpringBootApplication @EnableTransactionManagement @EnableReactiveMongoRepositories(basePackageClasses = MyData.class) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } java/classes/okhttp3/RequestBody.java1-10 package okhttp3; import d.d; import d.f; import d.l; import d.t; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import javax.annotation.Nullable; import okhttp3.internal.Util; public abstract class RequestBody { public static RequestBody create(@Nullable MediaType paramMediaType, final f paramf) { new RequestBody() { public long contentLength() throws IOException { return paramf.size(); } @Nullable public MediaType contentType() { return RequestBody.this; } public void writeTo(d paramAnonymousd) throws IOException { paramAnonymousd.write(paramf); } }; } public static RequestBody create(@Nullable MediaType paramMediaType, final File paramFile) { if (paramFile == null) { throw new NullPointerException("content == null"); } new RequestBody() { public long contentLength() { return paramFile.length(); } @Nullable public MediaType contentType() { return RequestBody.this; } public void writeTo(d paramAnonymousd) throws IOException { Object localObject = null; try { t localt = l.source(paramFile); localObject = localt; paramAnonymousd.writeAll(localt); Util.closeQuietly(localt); return; } finally { Util.closeQuietly((Closeable)localObject); } } }; } public static RequestBody create(@Nullable MediaType paramMediaType, String paramString) { Object localObject = Util.UTF_8; MediaType localMediaType = paramMediaType; if (paramMediaType != null) { Charset localCharset = paramMediaType.charset(); localObject = localCharset; localMediaType = paramMediaType; if (localCharset == null) { localObject = Util.UTF_8; localMediaType = MediaType.parse(paramMediaType + "; charset=utf-8"); } } return create(localMediaType, paramString.getBytes((Charset)localObject)); } public static RequestBody create(@Nullable MediaType paramMediaType, byte[] paramArrayOfByte) { return create(paramMediaType, paramArrayOfByte, 0, paramArrayOfByte.length); } public static RequestBody create(@Nullable MediaType paramMediaType, final byte[] paramArrayOfByte, final int paramInt1, final int paramInt2) { if (paramArrayOfByte == null) { throw new NullPointerException("content == null"); } Util.checkOffsetAndCount(paramArrayOfByte.length, paramInt1, paramInt2); new RequestBody() { public long contentLength() { return paramInt2; } @Nullable public MediaType contentType() { return RequestBody.this; } public void writeTo(d paramAnonymousd) throws IOException { paramAnonymousd.write(paramArrayOfByte, paramInt1, paramInt2); } }; } public long contentLength() throws IOException { return -1L; } @Nullable public abstract MediaType contentType(); public abstract void writeTo(d paramd) throws IOException; } /* Location: /Users/gaoht/Downloads/zirom/classes-dex2jar.jar!/okhttp3/RequestBody.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */src/test/java/net/imglib2/util/IterablePairTest.java /* * #%L * ImgLib2: a general-purpose, multidimensional image processing library. * %% * Copyright (C) 2009 - 2016 , , , * , , , , , * , , , , , * , , , , , * , , , , , * and . * %% * 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 net.imglib2.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.junit.Test; /** * Tests {@link IterablePair}. * * @author * @author */ public class IterablePairTest { /** * Tests {@link IterablePair#iterator()}. */ @Test public void testIterator() { final List< Integer > iter1 = Arrays.asList( 3, 5, 6, 1, 2, 3 ); final List< String > iter2 = Arrays.asList( "dog", "cat", "mouse", "fox" ); final IterablePair< Integer, String > pair = new IterablePair< >( iter1, iter2 ); final Iterator< Pair< Integer, String > > iterPair = pair.iterator(); assertNotNull( iterPair ); assertNextItems( iterPair, 3, "dog" ); assertNextItems( iterPair, 5, "cat" ); assertNextItems( iterPair, 6, "mouse" ); assertNextItems( iterPair, 1, "fox" ); assertFalse( iterPair.hasNext() ); try { final Pair< Integer, String > next = iterPair.next(); fail( "Next element not expected: " + next ); } catch ( final NoSuchElementException exc ) { // expected behavior } } /** * Tests iteration with null inputs. */ @Test( expected = NullPointerException.class ) public void testNulls() { final IterablePair< Integer, Integer > pair = new IterablePair< >( null, null ); pair.iterator().next(); } /** * Tests iteration with empty inputs. */ @Test( expected = NoSuchElementException.class ) public void testEmpty() { final List< Integer > iter1 = Collections.emptyList(); final List< Integer > iter2 = Collections.emptyList(); final IterablePair< Integer, Integer > pair = new IterablePair< >( iter1, iter2 ); pair.iterator().next(); } /** * Tests iteration when two inputs are the same reference. */ @Test public void testSameIterable() { final List< Integer > iter = Arrays.asList( 3, 5, 6, 1, 2, 3 ); final IterablePair< Integer, Integer > pair = new IterablePair< >( iter, iter ); final Iterator< Pair< Integer, Integer > > iterPair = pair.iterator(); assertNotNull( iterPair ); int count = 0; for ( final Integer i : iter ) { final Pair< Integer, Integer > p = iterPair.next(); assertEquals( i, p.getA() ); assertEquals( i, p.getB() ); count++; } assertEquals( iter.size(), count ); } // -- Helper methods -- private void assertNextItems( final Iterator< Pair< Integer, String > > iter, final Integer i, final String s ) { assertTrue( iter.hasNext() ); final Pair< Integer, String > pair1 = iter.next(); assertEquals( i, pair1.getA() ); assertEquals( s, pair1.getB() ); } } package com.cmbc.most.message; import com.amazon.sqs.javamessaging.AmazonSQSMessagingClientWrapper; import com.amazon.sqs.javamessaging.SQSConnection; import com.amazonaws.util.Base64; import javax.jms.*; /** * Created by zhoupengkai on 16/7/12. */ public class ExampleCommon { /** * A utility function to check the queue exists and create it if needed. For most * use cases this will usually be done by an administrator before the application * is run. */ public static void ensureQueueExists(SQSConnection connection, String queueName) throws JMSException { AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient(); /** * For most cases this could be done with just a createQueue call, but GetQueueUrl * (called by queueExists) is a faster operation for the common case where the queue * already exists. Also many users and roles have permission to call GetQueueUrl * but do not have permission to call CreateQueue. */ if( !client.queueExists(queueName) ) { client.createQueue( queueName ); } } public static void setupLogging() { // Setup logging // BasicConfigurator.configure(); // Logger.getRootLogger().setLevel(Level.WARN); } public static void handleMessage(Message message) throws JMSException { System.out.println( "Got message " + message.getJMSMessageID() ); System.out.println( "Content: "); if( message instanceof TextMessage) { TextMessage txtMessage = ( TextMessage ) message; System.out.println( "\t" + txtMessage.getText() ); } else if( message instanceof BytesMessage){ BytesMessage byteMessage = ( BytesMessage ) message; // Assume the length fits in an int - SQS only supports sizes up to 256k so that // should be true byte[] bytes = new byte[(int)byteMessage.getBodyLength()]; byteMessage.readBytes(bytes); System.out.println( "\t" + Base64.encodeAsString( bytes ) ); } else if( message instanceof ObjectMessage) { ObjectMessage objMessage = (ObjectMessage) message; System.out.println( "\t" + objMessage.getObject() ); } } } 1-10 package top.flytop.studentsign.mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import top.flytop.studentsign.pojo.User; import java.util.List; @Repository public interface UserMapper { User getUser(String username); User userLogin(@Param("username") String username, @Param("pwd") String pwd); Integer deleteUser(@Param("array") String[] sNos, @Param("type") Integer type); Boolean changePwdByUsername(@Param("pwd") String pwd, @Param("username") String username); Integer addUser(User user); Integer resetUserPwd(List list); } /* * 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 Chapter7_Reusing_Classes; /**(2) Create a class called Amphibian. From this, inherit a class called Frog. Put appropriate methods in the base class. In main( ), create a Frog and upcast it to Amphibian and demonstrate that all the methods still work. */ class Amphibian { void swim(Amphibian a) { System.out.println(a + " - swiming."); } static void amphibian (Amphibian a) { a.swim(a); } } // Frog public class Ch07Ex16 extends Amphibian { String name = "Frog"; public static void main(String[] args) { Ch07Ex16 obj = new Ch07Ex16(); Amphibian.amphibian(obj); } @Override public String toString() { return "Ch07Ex16{" + "name=" + name + '}'; } } package net.octyl.nvgtextspaces; import org.lwjgl.glfw.GLFWErrorCallback; import org.lwjgl.nanovg.NVGColor; import org.lwjgl.opengl.GL; import org.lwjgl.system.MemoryStack; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static org.lwjgl.glfw.GLFW.GLFW_CONTEXT_VERSION_MAJOR; import static org.lwjgl.glfw.GLFW.GLFW_CONTEXT_VERSION_MINOR; import static org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE; import static org.lwjgl.glfw.GLFW.GLFW_RELEASE; import static org.lwjgl.glfw.GLFW.glfwCreateWindow; import static org.lwjgl.glfw.GLFW.glfwDestroyWindow; import static org.lwjgl.glfw.GLFW.glfwGetFramebufferSize; import static org.lwjgl.glfw.GLFW.glfwGetWindowContentScale; import static org.lwjgl.glfw.GLFW.glfwInit; import static org.lwjgl.glfw.GLFW.glfwMakeContextCurrent; import static org.lwjgl.glfw.GLFW.glfwSetErrorCallback; import static org.lwjgl.glfw.GLFW.glfwSetKeyCallback; import static org.lwjgl.glfw.GLFW.glfwSetWindowShouldClose; import static org.lwjgl.glfw.GLFW.glfwSwapBuffers; import static org.lwjgl.glfw.GLFW.glfwSwapInterval; import static org.lwjgl.glfw.GLFW.glfwTerminate; import static org.lwjgl.glfw.GLFW.glfwWaitEvents; import static org.lwjgl.glfw.GLFW.glfwWindowHint; import static org.lwjgl.glfw.GLFW.glfwWindowShouldClose; import static org.lwjgl.nanovg.NanoVG.NVG_ALIGN_CENTER; import static org.lwjgl.nanovg.NanoVG.NVG_ALIGN_LEFT; import static org.lwjgl.nanovg.NanoVG.nvgBeginFrame; import static org.lwjgl.nanovg.NanoVG.nvgCreateFont; import static org.lwjgl.nanovg.NanoVG.nvgEndFrame; import static org.lwjgl.nanovg.NanoVG.nvgFillColor; import static org.lwjgl.nanovg.NanoVG.nvgFontBlur; import static org.lwjgl.nanovg.NanoVG.nvgFontFace; import static org.lwjgl.nanovg.NanoVG.nvgFontSize; import static org.lwjgl.nanovg.NanoVG.nvgText; import static org.lwjgl.nanovg.NanoVG.nvgTextAlign; import static org.lwjgl.nanovg.NanoVGGL2.nvgCreate; import static org.lwjgl.nanovg.NanoVGGL2.nvgDelete; import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT; import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT; import static org.lwjgl.opengl.GL11.GL_STENCIL_BUFFER_BIT; import static org.lwjgl.opengl.GL11.glClear; import static org.lwjgl.opengl.GL11.glViewport; import static org.lwjgl.system.MemoryUtil.NULL; import static org.lwjgl.system.MemoryUtil.memFree; import static org.lwjgl.system.MemoryUtil.memUTF8; public class NvgTextTrailingSpaces { private static long window = NULL; private static long nvg = NULL; public static void main(String[] args) { if (!glfwInit()) { throw new IllegalStateException("Failed to initialize GLFW."); } try (MemoryStack ignored = MemoryStack.stackPush()) { glfwSetErrorCallback(GLFWErrorCallback.createPrint()); setup(); run(); } finally { if (window != NULL) { glfwDestroyWindow(window); } if (nvg != NULL) { nvgDelete(nvg); } glfwTerminate(); } } private static void setup() { glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); window = glfwCreateWindow(640, 480, "Trailing Spaces", NULL, NULL); if (window == NULL) { throw new IllegalStateException("Failed to create window."); } glfwMakeContextCurrent(window); GL.createCapabilities(); glfwSetKeyCallback(window, (window1, key, scancode, action, mods) -> { if (key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE) { glfwSetWindowShouldClose(window1, true); } }); glfwSwapInterval(1); nvg = nvgCreate(0); if (nvg == NULL) { throw new IllegalStateException("Failed to create NVG context"); } nvgCreateFont(nvg, "sans", "./src/main/resources/Open_Sans/OpenSans-Regular.ttf"); } private static final NVGColor RED = NVGColor.calloc() .a(1).r(1).g(0).b(0); private static void run() { MemoryStack stack = MemoryStack.stackGet(); IntBuffer fbWidth = stack.mallocInt(1); IntBuffer fbHeight = stack.mallocInt(1); FloatBuffer contentWidth = stack.mallocFloat(1); FloatBuffer contentHeight = stack.mallocFloat(1); while (!glfwWindowShouldClose(window)) { glfwWaitEvents(); glfwGetFramebufferSize(window, fbWidth, fbHeight); glfwGetWindowContentScale(window, contentWidth, contentHeight); int effecWidth = (int) (fbWidth.get(0) / contentWidth.get(0)); int effecHeight = (int) (fbHeight.get(0) / contentHeight.get(0)); glViewport(0, 0, fbWidth.get(0), fbHeight.get(0)); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); nvgBeginFrame(nvg, effecWidth, effecHeight, Math.max(contentWidth.get(0), contentHeight.get(0))); ByteBuffer text = memUTF8("Following text has trailing spaces:", false); int FONT_SIZE = 18; drawText(320, 50, text, FONT_SIZE, 0, "sans", RED, NVG_ALIGN_CENTER); memFree(text); text = memUTF8("Text ", false); drawText(320, 50 + FONT_SIZE, text, FONT_SIZE, 0, "sans", RED, NVG_ALIGN_CENTER); memFree(text); // show what this would look like if spaces were trimmed text = memUTF8("Following text has no trailing spaces:", false); drawText(320, 50 + FONT_SIZE * 2, text, FONT_SIZE, 0, "sans", RED, NVG_ALIGN_CENTER); memFree(text); text = memUTF8("Text", false); drawText(320, 50 + FONT_SIZE * 3, text, FONT_SIZE, 0, "sans", RED, NVG_ALIGN_CENTER); memFree(text); nvgEndFrame(nvg); glfwSwapBuffers(window); } } private static void drawText(int posX, int posY, ByteBuffer asciiBuffer, float fontSize, float fontBlur, String font, NVGColor color, int alignment) { nvgFontSize(nvg, fontSize); nvgFontFace(nvg, font); nvgFontBlur(nvg, fontBlur); nvgFillColor(nvg, color); nvgTextAlign(nvg, alignment); nvgText(nvg, (float)posX, (float)posY, asciiBuffer); } } src/main/java/landmaster/landcore/api/block/IMetaBlockName.java package landmaster.landcore.api.block; import net.minecraft.item.*; public interface IMetaBlockName { String getSpecialName(ItemStack stack); } Zhangwusheng/myflume package com.ctg.aep.kerberostest; public class KafkaCacheJaas extends KafkaComponentBase { @Override protected void doInit() throws Exception { resetJassFileWithCache(); } @Override public String getName() { return "KafkaCacheJaas"; } } paser4se/uimaster /* * Copyright 2015 The UIMaster Project * * The UIMaster 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.shaolin.bmdp.workflow.internal; import java.io.Serializable; import org.shaolin.bmdp.runtime.spi.Event; import org.shaolin.bmdp.workflow.internal.type.NodeInfo; /** * Payload for matching request/response. * * The connector will be responsible for setting the payload. * */ public class FlowContextImpl implements FlowContext, Serializable { private static final long serialVersionUID = -132145046230765346L; private final FlowRuntimeContext runtime; private transient volatile NodeInfo waitingNode; public FlowContextImpl(FlowRuntimeContext runtime) { this.runtime = runtime; } @Override public void registerOutboundEvent(Event event) { event.setFlowContext(this); } public FlowRuntimeContext getFlowRuntime() { return runtime; } public void setWaitingNode(NodeInfo waitingNode) { if (waitingNode == null) { throw new IllegalArgumentException("waitingNode can not be null!"); } this.waitingNode = waitingNode; } public NodeInfo getWaitingNode() { return this.waitingNode; } } wytten/hibernate-projection package org.wyttenbach.dale.projection.hibernate; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Order; import org.hibernate.criterion.ProjectionList; import org.hibernate.criterion.Projections; import org.hibernate.criterion.Restrictions; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.wyttenbach.dale.projection.QuerySpecification; import org.wyttenbach.dale.projection.SearchSpecification; import org.wyttenbach.dale.projection.Specification; import org.wyttenbach.dale.projection.Transform; import org.wyttenbach.dale.projection.Specification.Condition; import org.wyttenbach.dale.projection.Specification.SortOrder; public abstract class HibernateProjectionServiceSupport { private Class persistentClass; public HibernateProjectionServiceSupport(Class class1) { this.persistentClass = class1; } protected abstract HibernateDaoSupport getProjectionDAO(); protected abstract Transform getProjectionTransform(); private List execute(Specification spec, ProjectionList projections) { DetachedCriteria criteria = DetachedCriteria.forClass(persistentClass); // project if (projections != null && projections.getLength() > 0) { criteria.setProjection(projections); } // filter if (spec.getConditions() != null) { for (Condition condition : spec.getConditions()) { criteria.add(Restrictions.eq(condition.property, condition.value)); } } // order if (spec.getSortOrders() != null) { for (SortOrder sort : spec.getSortOrders()) { switch (sort.direction) { case ASCENDING: criteria.addOrder(Order.asc(sort.property)); break; case DESCENDING: criteria.addOrder(Order.desc(sort.property)); break; } } } // limit if (spec.getMaxResults() != null) { return getProjectionDAO().getHibernateTemplate().findByCriteria(criteria, spec.getFirstResult(), spec.getMaxResults()); } return getProjectionDAO().getHibernateTemplate().findByCriteria(criteria); } @SuppressWarnings("unchecked") public List search(SearchSpecification spec) { List list = (List) execute(spec, null); List results = new ArrayList(); for (PERSISTABLE p : list) { DTO dto = getProjectionTransform().doTransform(p); results.add(dto); } return results; } @SuppressWarnings("unchecked") public List query(QuerySpecification spec) { List results = new ArrayList(); if (spec.getProjections() != null && spec.getProjections().size() > 0) { ProjectionList projections = Projections.projectionList(); for (QuerySpecification.Projection projection : spec .getProjections()) { switch (projection.function) { case MAX: projections.add(Projections.max(projection.property)); break; case MIN: projections.add(Projections.min(projection.property)); break; case AVG: projections.add(Projections.avg(projection.property)); break; case COUNT: projections.add(Projections.rowCount()); break; case GROUP_BY: projections.add(Projections .groupProperty(projection.property)); break; } } results = execute(spec, projections); } return results; } } package com.viniciusmo.androidtextspeech.translate; public class ToTranslate { } IvanaNSimonovic/tovar package tovar; public abstract class Tovar { public String vrsta; public double tezina; public String getVrsta() { return vrsta; } public void setTezina(double tezina) { this.tezina = tezina; } public double getTezina() { return tezina; } @Override public String toString() { return "Tovar [vrsta=" + vrsta + ", tezina=" + tezina + "]"; } } 1-10 public class StudentInfo { public void Studentname() { System.out.println("Name:Vengat"); } public void studentList() { System.out.println(); // TODO Auto-generated method stub } public void StudentMark() { System.out.println("Mark:1005"); } public void StudentAddress() { System.out.println("Address: Chennai"); } public static void main(String[] arg) { StudentInfo info = new StudentInfo(); info.Studentname(); info.StudentMark(); info.StudentAddress(); } } 1-10 package com.rfbsoft.game.engine.entites.initializers.g3d; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.physics.bullet.collision.btCollisionShape; import com.rfbsoft.game.engine.entites.initializers.g3d.bullet.BulletDynamicInitializer; public class ModelledBulletDynamicInitializer extends ModelledBulletInitializer { public ModelledBulletDynamicInitializer(ModelInstance instance, float mass, btCollisionShape collisionShape) { model = new ModelInitializer(instance); physics = new BulletDynamicInitializer(instance.transform, mass, collisionShape); } } /* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2022, by and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * -------------- * RangeType.java * -------------- * (C) Copyright 2005-2022, by . * * Original Author: ; * Contributor(s): -; * * Changes: * -------- * 24-Feb-2005 : Version 1 (DG); * 08-Jul-2018 : Made RangeType an enum (TH); * */ package org.jfree.data; /** * Used to indicate the type of range to display on an axis (full, positive or * negative). */ public enum RangeType { /** Full range (positive and negative). */ FULL, /** Positive range. */ POSITIVE, /** Negative range. */ NEGATIVE } package microsoft; public class Solution55 { public boolean canJump(int[] nums) { int lastPos = nums.length - 1; for (int i = nums.length - 1; i >= 0; i--) { if (i + nums[i] >= lastPos) { lastPos = i; } } return lastPos == 0; } enum Index { GOOD, BAD, UNKNOWN } public boolean canJumpWithDP(int[] nums) { Index[] memo = new Index[nums.length]; for (int i = 0; i < memo.length; i++) { memo[i] = Index.UNKNOWN; } memo[memo.length - 1] = Index.GOOD; for (int i = nums.length - 2; i >= 0; i--) { int furthestJump = Math.min(i + nums[i], nums.length - 1); for (int j = i + 1; j <= furthestJump; j++) { if (memo[j] == Index.GOOD) { memo[i] = Index.GOOD; break; } } } return memo[0] == Index.GOOD; } } src/main/java/de/ropemc/api/wrapper/net/minecraft/client/renderer/entity/layers/LayerCape.java package de.ropemc.api.wrapper.net.minecraft.client.renderer.entity.layers; import de.ropemc.api.wrapper.net.minecraft.client.entity.AbstractClientPlayer; import de.ropemc.api.wrapper.net.minecraft.entity.EntityLivingBase; import de.ropemc.api.wrapper.WrappedClass; @WrappedClass("net.minecraft.client.renderer.entity.layers.LayerCape") public interface LayerCape { void doRenderLayer(AbstractClientPlayer var0, float var1, float var2, float var3, float var4, float var5, float var6, float var7); void doRenderLayer(EntityLivingBase var0, float var1, float var2, float var3, float var4, float var5, float var6, float var7); boolean shouldCombineTextures(); } alifffahmi/checks-api-plugin package io.jenkins.plugins.checks.steps; import io.jenkins.plugins.checks.api.ChecksConclusion; import io.jenkins.plugins.checks.api.ChecksDetails; import io.jenkins.plugins.checks.api.ChecksOutput; import io.jenkins.plugins.checks.api.ChecksStatus; import io.jenkins.plugins.checks.util.CapturingChecksPublisher; import io.jenkins.plugins.util.IntegrationTestWithJenkinsPerTest; import org.jenkinsci.plugins.workflow.job.WorkflowJob; import org.junit.Test; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestExtension; import java.io.IOException; import static org.assertj.core.api.Assertions.assertThat; /** * Tests the pipeline step to publish checks. */ public class PublishChecksStepITest extends IntegrationTestWithJenkinsPerTest { /** * Provide a {@link CapturingChecksPublisher} to check published checks on each test. */ @TestExtension public static final CapturingChecksPublisher.Factory PUBLISHER_FACTORY = new CapturingChecksPublisher.Factory(); /** * Tests that the step "publishChecks" can be used in pipeline script. * * @throws IOException if fails get log from run */ @Test public void shouldPublishChecksWhenUsingPipeline() throws IOException { WorkflowJob job = createPipeline(); job.setDefinition(asStage("publishChecks name: 'customized-check', " + "summary: 'customized check created in pipeline', title: 'Publish Checks Step', " + "text: 'Pipeline support for checks', status: 'IN_PROGRESS', conclusion: 'NONE'")); assertThat(JenkinsRule.getLog(buildSuccessfully(job))) .contains("[Pipeline] publishChecks"); assertThat(PUBLISHER_FACTORY.getPublishedChecks().size()).isEqualTo(1); ChecksDetails details = PUBLISHER_FACTORY.getPublishedChecks().get(0); assertThat(details.getName()).isPresent().get().isEqualTo("customized-check"); assertThat(details.getOutput()).isPresent(); assertThat(details.getStatus()).isEqualTo(ChecksStatus.IN_PROGRESS); assertThat(details.getConclusion()).isEqualTo(ChecksConclusion.NONE); ChecksOutput output = details.getOutput().get(); assertThat(output.getTitle()).isPresent().get().isEqualTo("Publish Checks Step"); assertThat(output.getSummary()).isPresent().get().isEqualTo("customized check created in pipeline"); assertThat(output.getText()).isPresent().get().isEqualTo("Pipeline support for checks"); } } /* * Copyright 2014 - 2020 Blazebit. * * 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.blazebit.persistence.examples.showcase.fragments.basic.data; import com.blazebit.persistence.CriteriaBuilder; import com.blazebit.persistence.CriteriaBuilderFactory; import com.blazebit.persistence.PagedList; import com.blazebit.persistence.PaginatedCriteriaBuilder; import com.blazebit.persistence.examples.showcase.base.bean.EntityManagerHolder; import com.blazebit.persistence.examples.showcase.base.model.Cat; import com.blazebit.persistence.view.EntityViewManager; import com.blazebit.persistence.view.EntityViewSetting; import javax.inject.Inject; import javax.transaction.Transactional; import java.util.List; /** * @author * @since 1.2.0 */ @Transactional public class CatDataAccess { @Inject private EntityManagerHolder emHolder; @Inject private EntityViewManager evm; @Inject private CriteriaBuilderFactory cbf; public List getCats(EntityViewSetting> setting) { // formulate a query via a CriteriaBuilder CriteriaBuilder cb = cbf.create(emHolder.getEntityManager(), Cat.class); // you could extend the query by restrictions // at this point we combine the entity view setting with the CriteriaBuilder // this results in a CriteriaBuilder returning instances of the desired entity view CriteriaBuilder basicCb = evm.applySetting(setting, cb); // now we can issue the query and get the results return basicCb.getResultList(); } public T getCatByName(String name, EntityViewSetting> setting) { CriteriaBuilder cb = cbf.create(emHolder.getEntityManager(), Cat.class) .where("name").eq(name); return evm.applySetting(setting, cb).getSingleResult(); } public PagedList getPaginatedCats(EntityViewSetting> setting) { CriteriaBuilder cb = cbf.create(emHolder.getEntityManager(), Cat.class) .orderByAsc("name") .orderByAsc("id"); return evm.applySetting(setting, cb).withKeysetExtraction(true).getResultList(); } } /*- * #%L * The implementation of the pixel classification algorithm, that is used the Labkit image segmentation plugin for Fiji. * %% * Copyright (C) 2017 - 2021 * %% * 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 sc.fiji.labkit.pixel_classification.gpu.random_forest; import net.haesleinhuepf.clij.coremem.enums.NativeTypeEnum; import net.imglib2.RandomAccessibleInterval; import net.imglib2.img.Img; import net.imglib2.img.array.ArrayImgs; import net.imglib2.test.ImgLib2Assert; import sc.fiji.labkit.pixel_classification.gpu.api.AbstractGpuTest; import sc.fiji.labkit.pixel_classification.gpu.api.GpuImage; import net.imglib2.type.numeric.RealType; import net.imglib2.type.numeric.integer.UnsignedShortType; import net.imglib2.type.numeric.real.FloatType; import org.junit.Test; /** * Test {@link GpuRandomForestKernel} */ public class GpuRandomForestKernelTest extends AbstractGpuTest { @Test public void testRandomForest() { int width = 3; int height = 1; int depth = 2; int numberOfTrees = 2; int numberOfFeatures = 1; int numberOfClasses = 2; int numberOfNodes = 2; int numberOfLeafs = 3; GpuImage distributions = gpu.create(new long[] { width, height, depth }, numberOfClasses, NativeTypeEnum.Float); Img src = ArrayImgs.floats(new float[] { 41, 43, 45, 45, 43, 41 }, width, height, depth, numberOfFeatures); Img thresholds = ArrayImgs.floats(new float[] { 42, 44, 43.5f, 0, }, 1, numberOfNodes, numberOfTrees); Img probabilities = ArrayImgs.floats(new float[] { 2, 2, 3, 0, 4, 4, 0, 1, 0, 0, 0, 0 }, numberOfClasses, numberOfLeafs, numberOfTrees); Img indices = ArrayImgs.unsignedShorts(new short[] { 0, Short.MIN_VALUE, 1, 0, Short.MIN_VALUE + 1, Short.MIN_VALUE + 2, 0, Short.MIN_VALUE, Short.MIN_VALUE + 1, 0, 0, 0 }, 3, numberOfNodes, numberOfTrees); GpuRandomForestKernel.randomForest(gpu, distributions, gpu.pushMultiChannel(src), gpu.push(thresholds), gpu.push(probabilities), gpu.push(indices), numberOfFeatures); RandomAccessibleInterval> result = gpu.pullRAIMultiChannel(distributions); Img expected = ArrayImgs.floats(new float[] { 0.4f, 0.75f, 0.5f, 0.5f, 0.75f, 0.4f, 0.6f, 0.25f, 0.5f, 0.5f, 0.25f, 0.6f }, 3, 1, 2, 2); ImgLib2Assert.assertImageEqualsRealType(expected, result, 0.00001); } @Test public void testFindMax() { Img input = ArrayImgs.floats(new float[] { 1, 3, 2, 2, -1, -2, -3, -3, 2, 2, 3, 1, -2, -1, -1, -1, 3, 1, 1, 3, -3, -3, -2, -1 }, 2, 2, 2, 3); GpuImage outputBuffer = gpu.create(new long[] { 2, 2, 2 }, NativeTypeEnum.UnsignedShort); GpuRandomForestKernel.findMax(gpu, gpu.pushMultiChannel(input), outputBuffer); RandomAccessibleInterval> result = gpu.pullRAI(outputBuffer); RandomAccessibleInterval expected = ArrayImgs.floats(new float[] { 2, 0, 1, 2, 0, 1, 1, 1 }, 2, 2, 2); ImgLib2Assert.assertImageEqualsRealType(expected, result, 0.0); } @Test public void testFindMax2d() { Img input = ArrayImgs.floats(new float[] { 1, 3, -1, -2, 2, 2, -2, -1, }, 2, 2, 2); GpuImage outputBuffer = gpu.create(new long[] { 2, 2 }, NativeTypeEnum.UnsignedShort); GpuRandomForestKernel.findMax(gpu, gpu.pushMultiChannel(input), outputBuffer); RandomAccessibleInterval> result = gpu.pullRAI(outputBuffer); RandomAccessibleInterval expected = ArrayImgs.floats(new float[] { 1, 0, 0, 1 }, 2, 2); ImgLib2Assert.assertImageEqualsRealType(expected, result, 0.0); } } package org.jee8ng.users.boundary; import static io.restassured.RestAssured.when; import java.net.URL; import java.util.Optional; import javax.inject.Inject; import javax.json.Json; import javax.json.JsonObject; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.equalTo; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jee8ng.users.entity.Credential; import org.jee8ng.users.entity.User; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.RunWith; /** * Integration tests * @author antp. */ @RunWith(Arquillian.class) public class UsersServiceTest { @Inject private UsersService service; @Deployment(testable=false) public static WebArchive createDeployment() { return ShrinkWrap.create(WebArchive.class, "ims-users.war") .addPackages(true, "org.jee8ng.users") .addPackages(true, "org.jee8ng.security") .addAsWebInfResource("beans.xml") .addAsWebInfResource("web.xml") .addAsResource("persistence.xml", "META-INF/persistence.xml"); } @Test public void testCreateUser(@ArquillianResource URL resource) throws Exception { URL apiUrl = new URL(resource, "resources/users"); JsonObject user = Json.createObjectBuilder() .add("name", "Marcus") .add("email", "") .add("credential", credential("marcus", "1234")) .build(); Response initiallyCreated = ClientBuilder.newClient().target(apiUrl.toURI()) .request(MediaType.APPLICATION_JSON) .post(Entity.json(user)); assertThat(initiallyCreated.getStatus(), is(201)); String location = initiallyCreated.getHeaderString("Location"); assertNotNull(location); } private JsonObject credential(String username, String password) { return Json.createObjectBuilder() .add("username", username) .add("password", password) .build(); } @Test public void testGetUsers(@ArquillianResource URL resource) throws Exception { URL obj = new URL(resource, "resources/users"); // Response resp = ClientBuilder.newClient().target(obj.toURI()) // .request(MediaType.APPLICATION_JSON).get(); // assertThat(resp.getStatus(), is(200)); when().get(obj.toURI()).then() .statusCode(200); // .body("id", is(1)); } // @Test // public void testUserSaved() { // User user = new User(); // user.setEmail(""); // user.setName("test"); // user.setCredential(new Credential("testtt","testing123")); // service.add(user); // final Optional dbUser = service.get(user.getId()); // // assertTrue("user saved", dbUser.isPresent()); // // assertThat(dbUser.get().getEmail(), equalTo("")); // // } } 0 package com.homies.app.service.criteria; import java.io.Serializable; import java.util.Objects; import org.springdoc.api.annotations.ParameterObject; import tech.jhipster.service.Criteria; import tech.jhipster.service.filter.BooleanFilter; import tech.jhipster.service.filter.DoubleFilter; import tech.jhipster.service.filter.Filter; import tech.jhipster.service.filter.FloatFilter; import tech.jhipster.service.filter.IntegerFilter; import tech.jhipster.service.filter.LongFilter; import tech.jhipster.service.filter.StringFilter; /** * Criteria class for the {@link com.homies.app.domain.UserPending} entity. This class is used * in {@link com.homies.app.web.rest.UserPendingResource} to receive all the possible filtering options from * the Http GET request parameters. * For example the following could be a valid request: * {@code /user-pendings?id.greaterThan=5&attr1.contains=something&attr2.specified=false} * As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use * fix type specific filters. */ @ParameterObject public class UserPendingCriteria implements Serializable, Criteria { private static final long serialVersionUID = 1L; private LongFilter id; private FloatFilter pending; private BooleanFilter paid; private LongFilter spendingListId; private LongFilter spendingId; private LongFilter settingsListId; private Boolean distinct; public UserPendingCriteria() {} public UserPendingCriteria(UserPendingCriteria other) { this.id = other.id == null ? null : other.id.copy(); this.pending = other.pending == null ? null : other.pending.copy(); this.paid = other.paid == null ? null : other.paid.copy(); this.spendingListId = other.spendingListId == null ? null : other.spendingListId.copy(); this.spendingId = other.spendingId == null ? null : other.spendingId.copy(); this.settingsListId = other.settingsListId == null ? null : other.settingsListId.copy(); this.distinct = other.distinct; } @Override public UserPendingCriteria copy() { return new UserPendingCriteria(this); } public LongFilter getId() { return id; } public LongFilter id() { if (id == null) { id = new LongFilter(); } return id; } public void setId(LongFilter id) { this.id = id; } public FloatFilter getPending() { return pending; } public FloatFilter pending() { if (pending == null) { pending = new FloatFilter(); } return pending; } public void setPending(FloatFilter pending) { this.pending = pending; } public BooleanFilter getPaid() { return paid; } public BooleanFilter paid() { if (paid == null) { paid = new BooleanFilter(); } return paid; } public void setPaid(BooleanFilter paid) { this.paid = paid; } public LongFilter getSpendingListId() { return spendingListId; } public LongFilter spendingListId() { if (spendingListId == null) { spendingListId = new LongFilter(); } return spendingListId; } public void setSpendingListId(LongFilter spendingListId) { this.spendingListId = spendingListId; } public LongFilter getSpendingId() { return spendingId; } public LongFilter spendingId() { if (spendingId == null) { spendingId = new LongFilter(); } return spendingId; } public void setSpendingId(LongFilter spendingId) { this.spendingId = spendingId; } public LongFilter getSettingsListId() { return settingsListId; } public LongFilter settingsListId() { if (settingsListId == null) { settingsListId = new LongFilter(); } return settingsListId; } public void setSettingsListId(LongFilter settingsListId) { this.settingsListId = settingsListId; } public Boolean getDistinct() { return distinct; } public void setDistinct(Boolean distinct) { this.distinct = distinct; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final UserPendingCriteria that = (UserPendingCriteria) o; return ( Objects.equals(id, that.id) && Objects.equals(pending, that.pending) && Objects.equals(paid, that.paid) && Objects.equals(spendingListId, that.spendingListId) && Objects.equals(spendingId, that.spendingId) && Objects.equals(settingsListId, that.settingsListId) && Objects.equals(distinct, that.distinct) ); } @Override public int hashCode() { return Objects.hash(id, pending, paid, spendingListId, spendingId, settingsListId, distinct); } // prettier-ignore @Override public String toString() { return "UserPendingCriteria{" + (id != null ? "id=" + id + ", " : "") + (pending != null ? "pending=" + pending + ", " : "") + (paid != null ? "paid=" + paid + ", " : "") + (spendingListId != null ? "spendingListId=" + spendingListId + ", " : "") + (spendingId != null ? "spendingId=" + spendingId + ", " : "") + (settingsListId != null ? "settingsListId=" + settingsListId + ", " : "") + (distinct != null ? "distinct=" + distinct + ", " : "") + "}"; } } package cn.jorian.jorianframework.core.article.service; import cn.jorian.jorianframework.core.article.dto.CommontAddDTO; import cn.jorian.jorianframework.core.article.dto.CommontFindDTO; import cn.jorian.jorianframework.core.article.dto.CommontUpdateDTO; import cn.jorian.jorianframework.core.article.entity.Commont; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.service.IService; /** *

* commont 服务类 *

* * @author jorian * @since 2019-09-19 */ public interface CommontService extends IService { /** *新增评论 * @param addDTO */ void add(CommontAddDTO addDTO); /** * 根据id删除评论 * @param id */ void delete(String id); /** * 更新评论 * @param updateDTO */ void update(CommontUpdateDTO updateDTO); /** * 根据用户id和评论分类查询列表 * @param findDTO * @return */ IPage getList(CommontFindDTO findDTO); } 10-100 package com.demo.crypt.core.alias; import org.apache.ibatis.type.Alias; /** * @author NekoChips * @description 自定义Mybatis Java类型 * @date 2020/4/26 */ @Alias("Crypt") public class CryptType { } 0 package cn.udesk.camera.callback; import android.graphics.Bitmap; public interface StopRecordCallback { void recordResult(String url, Bitmap firstFrame); } package it.fvaleri.integ; import java.util.Random; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.eclipse.paho.client.mqttv3.IMqttClient; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class Utils { private static final Logger LOG = LoggerFactory.getLogger(Utils.class); private static final Random RND = new Random(); private Utils() { } public static void sleep(long millis) { try { TimeUnit.MILLISECONDS.sleep(millis); } catch (InterruptedException e) { } } public static String shorten(String str) { return (str != null && str.length() > 30) ? str.substring(0, 31) + "..." : str; } public static IMqttClient openConnection() throws Exception { LOG.debug("Connecting to server"); if (Configuration.SSL_TRUSTSTORE_LOCATION != null) { System.setProperty("javax.net.ssl.trustStore", Configuration.SSL_TRUSTSTORE_LOCATION); System.setProperty("javax.net.ssl.trustStorePassword", Configuration.SSL_TRUSTSTORE_PASSWORD); if (Configuration.SSL_KEYSTORE_LOCATION != null) { System.setProperty("javax.net.ssl.keyStore", Configuration.SSL_KEYSTORE_LOCATION); System.setProperty("javax.net.ssl.keyStorePassword", Configuration.SSL_KEYSTORE_PASSWORD); } } String clientId = UUID.randomUUID().toString(); // using the synchronous implementation String[] urls = Configuration.CONNECTION_URL.split(","); IMqttClient client = new MqttClient(urls[0], clientId, new MqttDefaultFilePersistence("/tmp")); MqttConnectOptions options = new MqttConnectOptions(); options.setServerURIs(urls); options.setAutomaticReconnect(true); options.setCleanSession(true); options.setConnectionTimeout(10); if (Configuration.CONNECTION_USERNAME != null) { options.setUserName(Configuration.CONNECTION_USERNAME); } if (Configuration.CONNECTION_PASSWORD != null) { options.setPassword(Configuration.CONNECTION_PASSWORD.toCharArray()); } client.connect(options); LOG.info("CONNECTED"); return client; } public static void closeConnection(IMqttClient client) { LOG.debug("Closing connection"); if (client != null) { try { client.disconnect(); client.close(); } catch (Exception e) { LOG.error("Client disconnect error: {}", e.getMessage()); } } } public static MqttMessage createMessage() { StringBuilder sb = new StringBuilder(); String alphabet = "ACGT"; for (long i = 0; i < Configuration.MESSAGE_SIZE_BYTES; i++) { sb.append(alphabet.charAt(RND.nextInt(alphabet.length()))); } byte[] payload = sb.toString().getBytes(); MqttMessage message = new MqttMessage(payload); message.setQos(Configuration.MESSAGE_QOS); message.setRetained(Configuration.MESSAGE_RETAINED); return message; } } package com.codenotfound.graphql.resolver; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.codenotfound.model.Greeting; import com.codenotfound.repository.GreetingRepository; import com.coxautodev.graphql.tools.GraphQLMutationResolver; @Component public class GreetingMutation implements GraphQLMutationResolver { @Autowired private GreetingRepository greetingRepository; public Greeting newGreeting(String message) { Greeting greeting = new Greeting(); greeting.setMessage(message); return greetingRepository.save(greeting); } } package com.example.demo.entity; import com.example.demo.entity.Robot.Type; public class RobotFactory { public static Robot createWithName(String name) { return null; } public static Robot createWithType(Type type) { return null; } public static Robot createWithNameAndType(String name, Type type) { return null; } public static Robot createWithTypeAndSwitched(Type type, boolean switched) { return null; } public static Robot createWithNameAndTypeAndSwitched(String name, Type type, boolean switched) { return null; } }eyric/PDPTW package cn.edu.bupt.pdptw.algorithm.scheduling; import java.util.Iterator; import java.util.stream.Collectors; import cn.edu.bupt.pdptw.logging.LoggingUtils; import cn.edu.bupt.pdptw.model.Location; import cn.edu.bupt.pdptw.model.Request; import cn.edu.bupt.pdptw.model.Vehicle; public class DriveFirstScheduler implements Scheduler { @Override public void scheduleRequests(Vehicle vehicle, int firstEarliestRealizationTime) throws IllegalArgumentException { Vehicle copy = vehicle.copy(); if (vehicle.getRoute().getRequests().size() > 0) { Iterator it = vehicle.getRoute().getRequests() .stream() .filter(r -> r.getRealizationTime() >= firstEarliestRealizationTime) .collect(Collectors.toList()) .iterator(); Request prev = null; if (it.hasNext()) { prev = it.next(); } while (it.hasNext()) { Request cur = it.next(); double distance = Location.calculateDistance(prev.getLocation(), cur.getLocation()); int earliestRealizationTime = (int) (prev.getRealizationTime() + prev.getServiceTime() + distance); int timeWindowStart = cur.getTimeWindowStart(); cur.setRealizationTime((earliestRealizationTime >= timeWindowStart) ? earliestRealizationTime : timeWindowStart); if (earliestRealizationTime > cur.getTimeWindowEnd()) { LoggingUtils.error(vehicle.getServedRequestsIds()); LoggingUtils.error(copy); LoggingUtils.error("-----------------------"); LoggingUtils.error(vehicle); throw new IllegalArgumentException("Earliest realization time" + " is greater than the end of the time window" + earliestRealizationTime); } prev = cur; } } } @Override public void updateSuccessor(Request prev, Request cur) { double distance = Location.calculateDistance(prev.getLocation(), cur.getLocation()); int earliestRealizationTime = (int) (prev.getRealizationTime() + prev.getServiceTime() + distance); earliestRealizationTime = (earliestRealizationTime > cur.getTimeWindowStart()) ? earliestRealizationTime : cur.getTimeWindowStart(); cur.setRealizationTime(earliestRealizationTime); } @Override public int getSuccessorRealizationTime(Request prev, Request cur) { int result; int distance = (int) Location.calculateDistance(prev.getLocation(), cur.getLocation()); int earliestRealizationTime = prev.getRealizationTime() + prev.getServiceTime() + distance; result = (earliestRealizationTime > cur.getTimeWindowStart()) ? earliestRealizationTime : cur.getTimeWindowStart(); return result; } @Override public void updateRequestRealizationTime(Request req, int time) { if (req.getRealizationTime() < time) { req.setRealizationTime(time); } } } package jetbrains.mps.workbench.findusages; /*Generated by MPS */ import jetbrains.mps.annotations.GeneratedClass; import org.jetbrains.mps.openapi.persistence.FindUsagesParticipant; import com.intellij.openapi.Disposable; import org.apache.log4j.Logger; import org.apache.log4j.LogManager; import jetbrains.mps.persistence.PersistenceRegistry; import com.intellij.openapi.startup.StartupActivity; import org.jetbrains.annotations.NotNull; import com.intellij.openapi.project.Project; import jetbrains.mps.project.MPSProject; import jetbrains.mps.ide.project.ProjectHelper; import jetbrains.mps.ide.MPSCoreComponents; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.util.Disposer; import java.util.Collection; import org.jetbrains.mps.openapi.model.SModel; import java.util.Set; import org.jetbrains.mps.openapi.model.SNode; import org.jetbrains.mps.openapi.util.Consumer; import org.jetbrains.mps.openapi.model.SReference; import org.jetbrains.annotations.Nullable; import org.jetbrains.mps.openapi.util.ProgressMonitor; import jetbrains.mps.progress.EmptyProgressMonitor; import jetbrains.mps.internal.collections.runtime.SetSequence; import java.util.HashSet; import jetbrains.mps.internal.collections.runtime.IWhereFilter; import jetbrains.mps.smodel.SNodeId; import jetbrains.mps.internal.collections.runtime.Sequence; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SNodeOperations; import jetbrains.mps.findUsages.NodeUsageLookup; import org.jetbrains.mps.openapi.language.SAbstractConcept; import org.jetbrains.mps.openapi.language.SLanguage; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import jetbrains.mps.findUsages.InstanceLookup; import org.jetbrains.mps.openapi.model.SModelReference; import jetbrains.mps.smodel.SModelStereotype; import jetbrains.mps.findUsages.ModelImportLookup; import java.util.function.Function; import jetbrains.mps.persistence.java.library.JavaClassStubModelDescriptor; import java.util.Collections; import jetbrains.mps.util.containers.ManyToManyMap; import com.intellij.openapi.vfs.VirtualFile; import jetbrains.mps.extapi.persistence.FolderSetDataSource; import gnu.trove.THashSet; import jetbrains.mps.vfs.IFile; import java.util.ArrayList; import jetbrains.mps.ide.vfs.VirtualFileUtils; import org.apache.log4j.Level; import java.util.Arrays; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.psi.impl.cache.impl.id.IdIndex; import com.intellij.psi.impl.cache.impl.id.IdIndexEntry; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.IndexNotReadyException; import org.jetbrains.mps.openapi.language.SConcept; @GeneratedClass(node = "r:9e8a9ffa-c450-4841-b749-c11aa0f49452(jetbrains.mps.workbench.findusages)/2810982631457564914", model = "r:9e8a9ffa-c450-4841-b749-c11aa0f49452(jetbrains.mps.workbench.findusages)") public class StubModelsFastFindSupport implements FindUsagesParticipant, Disposable { private static final Logger LOG = LogManager.getLogger(StubModelsFastFindSupport.class); private final PersistenceRegistry myRegistry; private final ProjectModelFilter myModelFilter; public static final class Plug implements StartupActivity.Background { @Override public void runActivity(@NotNull Project project) { MPSProject mpsProject = ProjectHelper.fromIdeaProject(project); if (mpsProject == null) { return; } MPSCoreComponents mpsCore = ApplicationManager.getApplication().getComponent(MPSCoreComponents.class); StubModelsFastFindSupport ffs = new StubModelsFastFindSupport(mpsProject, mpsCore); Disposer.register(project, ffs); } } private StubModelsFastFindSupport(MPSProject mpsProject, MPSCoreComponents mpsCore) { myRegistry = mpsCore.getPlatform().findComponent(PersistenceRegistry.class); myModelFilter = new ProjectModelFilter(mpsProject); myRegistry.addFindUsagesParticipant(this); } @Override public void dispose() { myRegistry.removeFindUsagesParticipant(this); } @Override public void findUsages(Collection models, Set nodes, Consumer consumer, Consumer processedConsumer, @Nullable ProgressMonitor monitor) { if (monitor == null) { monitor = new EmptyProgressMonitor(); } models = myModelFilter.projectModelsOnly(models); if (models.isEmpty()) { return; } // likely, an optimization that takes into account the way MPS identifies nodes in stub models Set oddFilteredNodes = SetSequence.fromSetWithValues(new HashSet(), SetSequence.fromSet(nodes).where(new IWhereFilter() { public boolean accept(SNode it) { return it.getNodeId() instanceof SNodeId.StringBasedId; } })); Set candidates = findCandidates(models, oddFilteredNodes, processedConsumer, (SNode key) -> key.getNodeId().toString()); for (SNode nn : Sequence.fromIterable(SNodeOperations.ofConcept(oddFilteredNodes, CONCEPTS.TypeVariableDeclaration$4Y))) { // I don't know the reason why we extend supplied scope for Type variables. The code is here for a decade, I wonder if it there's any reason to keep it. SModel mm = SNodeOperations.getModel(nn); if (mm != null) { // just in case, don't want to get unexpected NPE down the road candidates.add(mm); } } NodeUsageLookup nuf = new NodeUsageLookup(oddFilteredNodes, consumer); monitor.start("", candidates.size()); for (SModel e : candidates) { if (monitor.isCanceled()) { break; } nuf.collectUsages(e, monitor.subTask(1)); } monitor.done(); } @Override public void findInstances(Collection models, Set concepts, Consumer consumer, Consumer processedConsumer, @Nullable ProgressMonitor monitor) { if (monitor == null) { monitor = new EmptyProgressMonitor(); } models = myModelFilter.projectModelsOnly(models); if (models.isEmpty()) { return; } final SLanguage bl = MetaAdapterFactory.getLanguage(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, "jetbrains.mps.baseLanguage"); // XXX odd filtering by concept language. What about subconcepts of BL concepts in languages that extend BL? concepts = SetSequence.fromSetWithValues(new HashSet(), SetSequence.fromSet(concepts).where(new IWhereFilter() { public boolean accept(SAbstractConcept it) { return bl.equals(it.getLanguage()); } })); // FIXME make sure there's index for concept qualified name! Set candidates = findCandidates(models, concepts, processedConsumer, (SAbstractConcept k) -> k.getQualifiedName()); monitor.start("", candidates.size()); InstanceLookup nif = new InstanceLookup(concepts, consumer); for (SModel e : candidates) { if (monitor.isCanceled()) { break; } nif.collectInstances(e, monitor.subTask(1)); } monitor.done(); } @Override public void findModelUsages(Collection scope, Set modelReferences, Consumer consumer, Consumer processedConsumer) { scope = myModelFilter.projectModelsOnly(scope); if (scope.isEmpty()) { return; } modelReferences = SetSequence.fromSetWithValues(new HashSet(), SetSequence.fromSet(modelReferences).where(new IWhereFilter() { public boolean accept(SModelReference it) { return SModelStereotype.JAVA_STUB.equals(it.getName().getStereotype()); } })); Set candidates = findCandidates(scope, modelReferences, processedConsumer, (SModelReference key) -> key.getModelName()); ModelImportLookup mil = new ModelImportLookup(modelReferences, consumer); mil.withUses(candidates, new EmptyProgressMonitor()); } private Set findCandidates(Collection models, Set elems, Consumer processedConsumer, Function id) { if (elems.isEmpty()) { for (SModel sm : models) { if (sm instanceof JavaClassStubModelDescriptor) { processedConsumer.consume(sm); } } return Collections.emptySet(); } // get all files in scope final ManyToManyMap scopeFiles = new ManyToManyMap(); Set sources = new THashSet(); for (final SModel sm : models) { if (!(sm instanceof JavaClassStubModelDescriptor)) { continue; } FolderSetDataSource source = ((JavaClassStubModelDescriptor) sm).getSource(); if (!(sources.add(source))) { continue; } Collection files = source.getAffectedFiles(); ArrayList vFiles = new ArrayList(); for (IFile path : files) { final VirtualFile vf = VirtualFileUtils.getOrCreateVirtualFile(path); if (vf == null) { if (LOG.isEnabledFor(Level.WARN)) { LOG.warn("File " + path + ", which belows to model source of model " + sm.getReference().toString() + ", was not found in VFS. Assuming no usages in this file."); } continue; } if (vf.isDirectory()) { vFiles.addAll(Arrays.asList(vf.getChildren())); } else { vFiles.add(vf); } } for (VirtualFile vf : vFiles) { // do not enter any directories but one at the top level. Java package (corresponds to model) is just a list of files under single folder, // nested folder corresponds to another package if (vf.isDirectory()) { continue; } scopeFiles.addLink(sm, vf); } if (!(vFiles.isEmpty())) { // for stub models not backed by IDEA's VF, we shall not tell we've processed them. // Let another find participant (e.g. the slowest default that walks model) to look up usages. processedConsumer.consume(sm); } } // filter files with usages ConcreteFilesGlobalSearchScope allFiles = new ConcreteFilesGlobalSearchScope(myModelFilter.project().getProject(), scopeFiles.getSecond()); final Set result = new HashSet(); for (T elem : elems) { String nodeId = id.apply(elem); try { Collection matchingFiles = FileBasedIndex.getInstance().getContainingFiles(IdIndex.NAME, new IdIndexEntry(nodeId, true), allFiles); for (VirtualFile vf : matchingFiles) { // back-transform result.addAll(scopeFiles.getBySecond(vf)); } } catch (ProcessCanceledException | IndexNotReadyException ce) { // ignore } } return result; } private static final class CONCEPTS { /*package*/ static final SConcept TypeVariableDeclaration$4Y = MetaAdapterFactory.getConcept(0xf3061a5392264cc5L, 0xa443f952ceaf5816L, 0x1024639ed74L, "jetbrains.mps.baseLanguage.structure.TypeVariableDeclaration"); } } package io.wizzie.normalizer.funcs.impl; import io.wizzie.metrics.MetricsManager; import io.wizzie.normalizer.funcs.FilterFunc; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; public class OrFilter extends FilterFunc { private static final Logger log = LoggerFactory.getLogger(OrFilter.class); List filters = new ArrayList<>(); @Override public void prepare(Map properties, MetricsManager metricsManager) { List> filtersMap = (List>) properties.get("filters"); for (Map filter : filtersMap) { String className = (String) filter.get("className"); try { Class funcClass = Class.forName(className); FilterFunc func = (FilterFunc) funcClass.newInstance(); func.init((Map) filter.get("properties"), metricsManager); filters.add(func); } catch (ClassNotFoundException e) { log.error("Couldn't find the class associated with the function {}", className); } catch (InstantiationException | IllegalAccessException e) { log.error("Couldn't create the instance associated with the function " + className, e); } } } @Override public Boolean process(String key, Map value) { if(value == null) return false; return filters.parallelStream().map(filter -> filter.test(key, value)).reduce((x,y) -> x || y) .orElseGet(() -> Boolean.FALSE); } @Override public void stop() { } } package io.github.dunwu.module.security.config; import lombok.Data; /** * 令牌配置 * * @author * @since 2020-04-08 */ @Data public class TokenProperties { /** Request Headers: DunwuToken */ private String tokenHeader = "DunwuToken"; /** 令牌前缀,最后留个空格 */ private String tokenPrefix = "dunwu"; /** 必须使用最少88位的Base64对该令牌进行编码 */ private String base64Secret; /** 令牌过期时间 此处单位/秒 ,默认4小时 */ private Long tokenValidityInSeconds = 4 * 60 * 60L; /** 令牌过期时间 此处单位/秒 */ private Long expireTime; /** 在线用户 key 前缀 */ private String onlinePrefix = "dunwu::online::"; /** 验证码 key 前缀 */ private String captchaPrefix = "dunwu::captcha::"; /** token 续期检查时间,单位秒,默认30分钟 */ private Long detect = 1800L; /** 续期时间,单位秒,默认1小时 */ private Long renew = 3600L; public String getTokenPrefix() { return tokenPrefix + "@"; } } package org.maneau.maventools.utils; import org.apache.maven.wagon.Wagon; import org.apache.maven.wagon.providers.http.LightweightHttpWagon; import org.apache.maven.wagon.providers.http.LightweightHttpWagonAuthenticator; import org.apache.maven.wagon.providers.http.LightweightHttpsWagon; import org.sonatype.aether.connector.wagon.WagonProvider; /** * Created by maneau on 05/07/2014. * A simplistic provider for wagon instances when no Plexus-compatible IoC container is used. */ class ManualWagonProvider implements WagonProvider { public Wagon lookup(String roleHint) throws Exception { LightweightHttpWagon wagon; if ("http".equals(roleHint)) { wagon = new LightweightHttpWagon(); } else if ("https".equals(roleHint)) { wagon = new LightweightHttpsWagon(); } else { return null; } wagon.setAuthenticator(new LightweightHttpWagonAuthenticator()); return wagon; } public void release(Wagon wagon) { } }class Handler { private static java.util.Random s_rn = new java.util.Random(); private static int s_next = 1; private int m_id = s_next++; public boolean handle(int num) { if (s_rn.nextInt(4) != 0) { System.out.print(m_id + "-busy "); return false; } System.out.println(m_id + "-handled-" + num); return true; } } public class ChainDemo { public static void main(String[] args) { Handler[] nodes = { new Handler(), new Handler(), new Handler(), new Handler() }; for (int i = 1, j; i < 10; i++) { j = 0; while (!nodes[j].handle(i)) j = (j + 1) % nodes.length; } } } package tech.vengine.v_browser.core.AsyncTasks; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.widget.EditText; import tech.vengine.v_browser.R; import tech.vengine.v_browser.core.activities.PinEntryActivity; public class LockKeyPadOperation extends AsyncTask { private Context mContext; public LockKeyPadOperation(Context ctx) { mContext = ctx; } @Override protected String doInBackground(String... params) { for (int i = 0; i < 2; i++) { try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "Executed"; } @Override protected void onPostExecute(String result) { // updateStatus(false,HoloBlue,Color.WHITE,""); // statusView.setText(""); //Roll over PinEntryActivity.userEntered = ""; EditText pinBoxEditText = (EditText) ((Activity) mContext).findViewById(R.id.pin_box_edittext); pinBoxEditText.setText(PinEntryActivity.userEntered); PinEntryActivity.keyPadLockedFlag = false; } @Override protected void onPreExecute() { } @Override protected void onProgressUpdate(Void... values) { } }/* Given a string, if the string "del" appears starting at index 1, return a string where that "del" has been deleted. Otherwise, return the string unchanged. delDel("adelbc") → "abc" delDel("adelHello") → "aHello" delDel("adedbc") → "adedbc" */ public String delDel(String str) { if ((str.length() < 4) || !(str.substring(1, 4).equals("del"))) { return str; } else { return str.charAt(0) + str.substring(4); } } /** * */ package org.minnal.instrument.util; import static org.testng.Assert.assertEquals; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; import org.minnal.instrument.entity.Searchable; import org.minnal.utils.reflection.ClassUtils; import org.testng.annotations.Test; /** * @author anand.karthik * */ public class ClassUtilsTest { class TempEntity extends TempSuperEntity { @Searchable String field1; public String getField1() { return field1; } /** * @param field8 the field8 to set */ public void setField1(String field1) { this.field1 = field1; } } class TempSuperEntity { @Searchable private String field8; /** * @return the field8 */ public String getField8() { return field8; } /** * @param field8 the field8 to set */ public void setField8(String field8) { this.field8 = field8; } } @Test public void shouldDiscoverSuperClassFields() { List allFields = ClassUtils.getAllFields(TempEntity.class); assertEquals(allFields.size(), 4); } @Test public void shouldDiscoverSuperClassMethods() { List allMethods = ClassUtils.getAllMethods(TempEntity.class); assertEquals(allMethods.size(), 16); } } package org.marc4j.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.TreeMap; /** * Read a file of binary MARC records, sort them by their control numbers, write them out to stdout * @author * */ public class MarcSorter { static TreeMap recordMap = null; static boolean verbose = false; static boolean check = false; static boolean quiet = false; static StringNaturalCompare compare = null; /** * main program for sorting class. * @param args - the provided command line arguments */ public static void main(String[] args) { // try { InputStream input; compare = new StringNaturalCompare(); recordMap = new TreeMap(compare); int offset = 0; while (args[offset].startsWith("-") && args[offset].length() > 1) { if (args[offset].equals("-v")) { quiet = false; verbose = true; offset++; } if (args[offset].equals("-c")) { check = true; offset++; } if (args[offset].equals("-q")) { verbose = false; quiet = true; offset++; } if (args[offset].equals("-usage")) { usage(null, 0); } } String filename = args[offset]; try { if (filename.equals("-")) { input = System.in; if (verbose) System.err.println("reading Stdin"); } else { input = new FileInputStream(new File(filename)); if (verbose) System.err.println("reading file "+ filename); } processInput(input); } catch (FileNotFoundException e) { System.err.println("Error: Cannot find file: " + filename); } catch (Exception e){ System.err.println("Exception: "+e.getMessage()); e.printStackTrace(); } } private static void usage(String error, int exitcode) { if (error != null) { System.err.println("Error: "+ error); } System.err.println("Usage: org.marc4j.util.MarcSorter [-options] "); System.err.println(" -v Write verbose output"); System.err.println(" -c Merely check whether a file is sorted or not"); System.err.println(" -q In conjunction with -c check whether the file is sorted, but don't generate any output, just set the return code (0 = sorted) (-1 = not sorted)"); System.err.println(" -usage = this message"); System.exit(exitcode); } static void processInput(InputStream input) { RawRecordReader rawReader = new RawRecordReader(input); RawRecord rec = rawReader.hasNext() ? rawReader.next() : null; String prevField001 = ""; int rec_count = 0; while (rec != null) { String field001 = "Undefined"; field001 = rec.getRecordId(); byte newRec[] = rec.getRecordBytes(); if (check) { if (prevField001 != "" && compare.compare(prevField001, field001) > 0) { if (!quiet) { System.err.println("ERROR: File not sorted: record "+rec_count + " has id="+ prevField001+ " the following record has id="+field001); } System.exit(-1); } rec_count++; prevField001 = field001; rec = rawReader.hasNext() ? rawReader.next() : null; } else { if (recordMap.containsKey(field001)) { byte existingRec[] = recordMap.get(field001); byte combinedRec[] = new byte[existingRec.length + newRec.length]; System.arraycopy(existingRec, 0, combinedRec, 0, existingRec.length); System.arraycopy(newRec, 0, combinedRec, existingRec.length, newRec.length); recordMap.put(field001, combinedRec); } else { recordMap.put(field001, newRec); } if (verbose) System.err.println("Record read : "+ field001); rec = rawReader.hasNext() ? rawReader.next() : null; } } if (check) { if (verbose) { System.err.println("File correctly sorted"); } System.exit(0); } try { while (recordMap.size() > 0) { String firstKey = recordMap.firstKey(); byte recValue[] = recordMap.remove(firstKey); System.out.write(recValue); System.out.flush(); if (!quiet) System.err.println("Record written : "+ firstKey); } } catch (IOException e) { // e.printStackTrace(); System.err.println(e.getMessage()); } } } wuzhouhui/leetcode import java.util.*; class Solution { public String fractionToDecimal(int numerator, int denominator) { if (denominator == 0) return(""); if (numerator == 0) return("0"); StringBuffer result = new StringBuffer(); if ((numerator < 0) ^ (denominator < 0)) result.append("-"); long num = numerator; long den = denominator; num = Math.abs(num); den = Math.abs(den); long remainder = (num % den) * 10; num /= den; result.append(num); if (remainder == 0) return(result.toString()); result.append("."); Map map = new HashMap<>(); while (remainder != 0) { if (map.containsKey(remainder)) { int start = map.get(remainder); String p1 = result.substring(0, start); String p2 = result.substring(start, result.length()); return(p1 + "(" + p2 + ")"); } map.put(remainder, result.length()); num = remainder / den; result.append(num); remainder = (remainder % den) * 10; } return(result.toString()); } public static void main(String[] args) { int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); System.out.println(new Solution().fractionToDecimal(x, y)); } } git4wht/cloudbreakcore/src/main/java/com/sequenceiq/cloudbreak/service/freeipa/FreeIpaOperationCheckerTask.java package com.sequenceiq.cloudbreak.service.freeipa; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sequenceiq.cloudbreak.auth.ThreadBasedUserCrnProvider; import com.sequenceiq.cloudbreak.polling.SimpleStatusCheckerTask; import com.sequenceiq.freeipa.api.v1.freeipa.user.model.FailureDetails; import com.sequenceiq.freeipa.api.v1.operation.model.OperationState; import com.sequenceiq.freeipa.api.v1.operation.model.OperationStatus; public class FreeIpaOperationCheckerTask extends SimpleStatusCheckerTask { private static final Logger LOGGER = LoggerFactory.getLogger(FreeIpaOperationCheckerTask.class); @Override public boolean checkStatus(T operationPollerObject) { OperationStatus operationStatus = ThreadBasedUserCrnProvider.doAsInternalActor( operationPollerObject.getRegionalAwareInternalCrnGeneratorFactory().iam().getInternalCrnForServiceAsString(), () -> operationPollerObject.getOperationV1Endpoint().getOperationStatus(operationPollerObject.getOperationId(), operationPollerObject.getAccountId())); LOGGER.debug("OperationStatus for operationId[{}]: {}", operationPollerObject.getOperationId(), operationStatus); if (OperationState.COMPLETED.equals(operationStatus.getStatus())) { return true; } else if (OperationState.RUNNING.equals(operationStatus.getStatus())) { return false; } else { String failureDetails = extractFailureDetails(operationStatus); throw new FreeIpaOperationFailedException(String.format("FreeIPA [%s] operation [%s] failed with state [%s] and error message [%s]. " + "Failure details: [%s]", operationStatus.getOperationType(), operationPollerObject.getOperationId(), operationStatus.getStatus(), operationStatus.getError(), failureDetails)); } } private String extractFailureDetails(OperationStatus operationStatus) { String failureDetails = null; try { failureDetails = operationStatus.getFailure() != null && !operationStatus.getFailure().isEmpty() ? operationStatus.getFailure().stream() .map(FailureDetails::getAdditionalDetails) .map(Object::toString) .collect(Collectors.joining(",")) : "empty"; } catch (Exception e) { LOGGER.error("Cannot evaluate Failure details [{}]", failureDetails, e); failureDetails = "empty"; } return failureDetails; } @Override public void handleTimeout(T operationPollerObject) { OperationStatus operationStatus = ThreadBasedUserCrnProvider.doAsInternalActor( operationPollerObject.getRegionalAwareInternalCrnGeneratorFactory().iam().getInternalCrnForServiceAsString(), () -> operationPollerObject.getOperationV1Endpoint().getOperationStatus(operationPollerObject.getOperationId(), operationPollerObject.getAccountId())); throw new FreeIpaOperationFailedException(String.format("FreeIPA [%s] operation [%s] timed out. Current state is [%s]", operationStatus.getOperationType(), operationPollerObject.getOperationId(), operationStatus.getStatus())); } @Override public String successMessage(T operationPollerObject) { return String.format("FreeIPA [%s] operation [%s] finished successfully", operationPollerObject.getOperationType(), operationPollerObject.getOperationId()); } @Override public boolean exitPolling(T operationPollerObject) { return false; } } package uk.gov.hmcts.cmc.ccd.domain.defendant.statementofmeans; public enum CCDPaymentFrequency { WEEK, TWO_WEEKS, FOUR_WEEKS, MONTH } package com.heaven.elegy.message.broker.rabbitmq.step2; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.MessageProperties; /** * 向消息队列中发送消息(发送者、生产者) *

大部分与step1的{@link com.heaven.elegy.message.broker.rabbitmq.step1.Send Send} 相同

*
    *
  1. 加了代表工作的dot工作功能(模拟)
  2. *
  3. 添加了durable队列持久化功能
  4. *
  5. 添加了{@link MessageProperties#PERSISTENT_TEXT_PLAIN} 消息持久化功能
  6. *
* @author li.xiaoxi * @date 2019/06/10 16:06 */ public class Send { /** * 目标队列名 */ private static final String QUEUE_NAME = "task_queue"; /** * 要发送的消息 */ private static final String MESSAGE = "Hello World"; /** * 队列持久化 */ private static final boolean DURABLE = true; /** * 通过main方法启动 */ public static void main(String[] args) { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("localhost"); // 制作一个任务 String task = makeTask(); try (Connection connection = factory.newConnection()){ Channel channel = connection.createChannel(); channel.queueDeclare( QUEUE_NAME, // 这里进行了持久化相关配置 DURABLE, false, false, null ); // 向消息中间件中发送一个消息 channel.basicPublish( "", QUEUE_NAME, // 对消息进行持久化 MessageProperties.PERSISTENT_TEXT_PLAIN, task.getBytes() ); System.out.println("消息发送完成。message:" + task); }catch (Exception e) { e.printStackTrace(); } } private static String makeTask() { int r = 10; StringBuilder message = new StringBuilder(MESSAGE); message.append(" dot:"); message.append(r); while (r > 0) { message.append("."); r--; } return message.toString(); } } package com.yrainy.library.server.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.yrainy.library.server.pojo.Admin; /** *

* Mapper 接口 *

* * @author zhanglun * @since 2022-02-27 */ public interface AdminMapper extends BaseMapper { } src/main/java/com/donghun/reactiveblog/domain/Follow.java package com.donghun.reactiveblog.domain; import lombok.*; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; /** * @author donghL-dev * @since 2019-12-03 */ @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(of = "id") @Document @Builder public class Follow { @Id private String id; private String follow; private String following; } package com.termux.shared.models.errors; /** * The {@link Class} that defines ResultSender error messages and codes. */ public class ResultSenderErrno extends Errno { public static final String TYPE = "ResultSender Error"; /* Errors for null or empty parameters (100-150) */ public static final Errno ERROR_RESULT_FILE_BASENAME_NULL_OR_INVALID = new Errno(TYPE, 100, "The result file basename \"%1$s\" is null, empty or contains forward slashes \"/\"."); public static final Errno ERROR_RESULT_FILES_SUFFIX_INVALID = new Errno(TYPE, 101, "The result files suffix \"%1$s\" contains forward slashes \"/\"."); public static final Errno ERROR_FORMAT_RESULT_ERROR_FAILED_WITH_EXCEPTION = new Errno(TYPE, 102, "Formatting result error failed.\nException: %1$s"); public static final Errno ERROR_FORMAT_RESULT_OUTPUT_FAILED_WITH_EXCEPTION = new Errno(TYPE, 103, "Formatting result output failed.\nException: %1$s"); ResultSenderErrno(final String type, final int code, final String message) { super(type, code, message); } } Wobblyyyy/PathfindingCoresrc/org/xguzm/pathfinding/grid/GridCell.java package org.xguzm.pathfinding.grid; import org.xguzm.pathfinding.NavigationGraph; import org.xguzm.pathfinding.NavigationNode; import org.xguzm.pathfinding.PathFinder; import org.xguzm.pathfinding.util.ObjectIntMap; import java.util.List; public class GridCell implements NavigationGridGraphNode { public int x; public int y; /* for path finders*/ private float f, g, h; private boolean isWalkable; private GridCell parent; private final ObjectIntMap> closedOnJob = new ObjectIntMap>(); private final ObjectIntMap> openedOnJob = new ObjectIntMap>(); //for BTree private int index; public GridCell() { } public GridCell(int x, int y) { this(x, y, true); } public GridCell(int x, int y, boolean isWalkable) { this.y = y; this.x = x; this.isWalkable = isWalkable; } public GridCell(boolean isWalkable) { this.isWalkable = isWalkable; } @Override public int getIndex() { return index; } @Override public void setIndex(int index) { this.index = index; } public boolean isWalkable() { return isWalkable; } public void setWalkable(boolean isWalkable) { this.isWalkable = isWalkable; } public float getF() { return f; } public void setF(float f) { this.f = f; } @Override public float getG() { return g; } @Override public void setG(float g) { this.g = g; } @Override public float getH() { return h; } @Override public void setH(float h) { this.h = h; } @Override public NavigationNode getParent() { return parent; } @Override public void setParent(NavigationNode parent) { this.parent = (GridCell) parent; } @Override public int getClosedOnJob() { return getClosedOnJob(DummyFinder.class); } @Override public void setClosedOnJob(int closedOnJob) { setClosedOnJob(closedOnJob, DummyFinder.class); } @Override public int getOpenedOnJob() { return getOpenedOnJob(DummyFinder.class); } @Override public void setOpenedOnJob(int openedOnJob) { setOpenedOnJob(openedOnJob, DummyFinder.class); } @Override public int getClosedOnJob(Class clazz) { return closedOnJob.get(clazz, 0); } @Override public void setClosedOnJob(int closedOnJob, Class clazz) { this.closedOnJob.put(clazz, closedOnJob); } @Override public int getOpenedOnJob(Class clazz) { return openedOnJob.get(clazz, 0); } @Override public void setOpenedOnJob(int openedOnJob, Class clazz) { this.openedOnJob.put(clazz, openedOnJob); } @Override public String toString() { return "[" + x + ", " + y + "]"; } @Override public int getX() { return x; } @Override public void setX(int x) { this.x = x; } @Override public int getY() { return y; } @Override public void setY(int y) { this.y = y; } private static final class DummyFinder implements PathFinder { @Override public List findPath(T startNode, T endNode, NavigationGraph grid) { return null; } } } 10-100 package fr.aba.ogham.documentation.generator; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component public class GenerateWiki implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { if(args.containsOption("wiki")) { generate(); } } private void generate() { // TODO Auto-generated method stub } } package br.com.muambyte.jpa.Carrinho; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import br.com.muambyte.modelo.Carrinho; public class CarregaCarrinho { public static void main(String[] args) { EntityManagerFactory factory = Persistence. createEntityManagerFactory("muambyte"); EntityManager manager = factory.createEntityManager(); Carrinho encontrada = manager.find(Carrinho.class,1); System.out.println(encontrada.getIdCarrinho()); manager.close(); } }TharukaN17/product-microgateway /* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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.wso2.choreo.connect.enforcer.discovery; import io.envoyproxy.envoy.config.core.v3.Node; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryRequest; import io.envoyproxy.envoy.service.discovery.v3.DiscoveryResponse; import io.grpc.ConnectivityState; import io.grpc.ManagedChannel; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.wso2.choreo.connect.discovery.config.enforcer.Config; import org.wso2.choreo.connect.discovery.service.config.ConfigDiscoveryServiceGrpc; import org.wso2.choreo.connect.enforcer.config.ConfigHolder; import org.wso2.choreo.connect.enforcer.constants.AdapterConstants; import org.wso2.choreo.connect.enforcer.constants.Constants; import org.wso2.choreo.connect.enforcer.discovery.common.XDSCommonUtils; import org.wso2.choreo.connect.enforcer.discovery.scheduler.XdsSchedulerManager; import org.wso2.choreo.connect.enforcer.util.GRPCUtils; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.validation.constraints.NotNull; /** * Client to communicate with configuration discovery service at the adapter. */ public class ConfigDiscoveryClient implements Runnable { private static final Logger log = LogManager.getLogger(ConfigDiscoveryClient.class); private static ConfigDiscoveryClient instance; private final String host; private final int port; private final CountDownLatch latch; private ConfigDiscoveryServiceGrpc.ConfigDiscoveryServiceBlockingStub blockingStub; private ManagedChannel channel; /** * Node struct for the discovery client */ private final Node node; private ConfigDiscoveryClient(String host, int port, CountDownLatch latch) { this.host = host; this.port = port; this.latch = latch; this.node = XDSCommonUtils.generateXDSNode(AdapterConstants.COMMON_ENFORCER_LABEL); initConnection(); } /** * Initialize an instance of {@link ConfigDiscoveryClient}. * * @param latch a latch counter to make calling thread wait for proper * completion of config discovery. * @return initialized instance of {@link ConfigDiscoveryClient} */ public static ConfigDiscoveryClient init(@NotNull CountDownLatch latch) { if (instance == null) { String adsHost = ConfigHolder.getInstance().getEnvVarConfig().getAdapterHost(); int adsPort = Integer.parseInt(ConfigHolder.getInstance().getEnvVarConfig().getAdapterXdsPort()); instance = new ConfigDiscoveryClient(adsHost, adsPort, latch); } return instance; } /** * Retrieves the already initialized instance of this class. Instance must be * initialized first by calling {@link ConfigDiscoveryClient#init(CountDownLatch)} * before calling this methods. This methods doesn't handled initialization * of the instance. * * @return initialized {@link ConfigDiscoveryClient} instance or {@code null} * if the instance is not initialized previously by calling * {@link ConfigDiscoveryClient#init(CountDownLatch)} */ public static ConfigDiscoveryClient getInstance() { return instance; } private void initConnection() { if (GRPCUtils.isReInitRequired(channel)) { if (channel != null && !channel.isShutdown()) { channel.shutdownNow(); do { try { channel.awaitTermination(100, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { log.error("Config discovery channel shutdown wait was interrupted", e); } } while (!channel.isShutdown()); } this.channel = GRPCUtils.createSecuredChannel(log, host, port); this.blockingStub = ConfigDiscoveryServiceGrpc.newBlockingStub(channel); } else if (channel.getState(true) == ConnectivityState.READY) { XdsSchedulerManager.getInstance().stopConfigDiscoveryScheduling(); } } public void requestInitConfig() { DiscoveryRequest req = DiscoveryRequest.newBuilder() .setNode(node) .setTypeUrl(Constants.CONFIG_TYPE_URL).build(); try { DiscoveryResponse res = blockingStub.withDeadlineAfter(60, TimeUnit.SECONDS).fetchConfigs(req); shutdown(); XdsSchedulerManager.getInstance().stopConfigDiscoveryScheduling(); // Theres only one config root resource here. Therefore taking 0, no need to iterate Config config = res.getResources(0).unpack(Config.class); ConfigHolder.load(config); this.latch.countDown(); } catch (Exception e) { // catching generic error here to wrap any grpc communication errors in the runtime log.error("Error occurred during Config discovery", e); XdsSchedulerManager.getInstance().startConfigDiscoveryScheduling(); } } public void shutdown() throws InterruptedException { channel.shutdown().awaitTermination(5, TimeUnit.SECONDS); } @Override public void run() { initConnection(); requestInitConfig(); } } 0 package uk.ac.ox.cs.chaseBench.model; public enum Domain { SYMBOL, STRING, INTEGER, DOUBLE }techrabbit58/JavaBabyStepssrc/main/java/com/example/babysteps/BorderLayoutDemo.java package com.example.babysteps; import javax.swing.*; import java.awt.*; class BorderLayoutDemo extends JFrame { private BorderLayoutDemo() { super("Demo"); setLayout(new BorderLayout()); setMinimumSize(new Dimension(220, 20)); setDefaultCloseOperation(EXIT_ON_CLOSE); add(BorderLayout.NORTH, new JButton("North")); add(BorderLayout.WEST, new JButton("West")); add(BorderLayout.EAST, new JButton("East")); add(BorderLayout.CENTER, new JButton("Center")); add(BorderLayout.SOUTH, new JButton("South")); pack(); setLocationRelativeTo(null); } public static void main(String[] args) { EventQueue.invokeLater(() -> new BorderLayoutDemo().setVisible(true)); } } src/main/java/org/mazurov/errorz/TestUtils.java /* * Copyright 2020 * * 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.mazurov.errorz; /** * Project ErrorZ * * https://github.com/OlegMazurov/ErrorZ * */ public class TestUtils { /** * Generate exactly @E random errors in the code word * @param E number of errors * @return array of error indices */ public static int[] addErrors(BlockCode code, int E) { int[] idx = new int[E]; int N = code.getBlockLength(); boolean[] marks = new boolean[N]; for (int i = 0; i < E;) { int next = Random.nextInt(N); if (marks[next]) continue; long val = Random.nextLong(); if (code.getAt(next) == val) continue; code.setAt(next, val); marks[next] = true; idx[i++] = next; } return idx; } /** * Test error recovery * @param code block code * @param nRuns number of iterations * @param errors number of errors */ public static int testErrors(BlockCode code, int nRuns, int errors) { int rejected = 0; // rejected decoding int failed = 0; // erroneous decoding for (int t = 0; t < nRuns; ++t) { BlockCode testCode = code.clone(); addErrors(testCode, errors); // ignore error locations if (!testCode.decode()) { rejected += 1; } else { for (int i = 0; i < code.getBlockLength(); ++i) { if (testCode.getAt(i) != code.getAt(i)) { failed += 1; break; } } } } int decoded = nRuns - rejected - failed; StringBuilder sb = new StringBuilder(); sb.append(code); sb.append(", redundancy: ").append(code.getBlockLength() - code.getMessageLength()); sb.append(", errors: ").append(errors); sb.append(", runs: ").append(nRuns); sb.append(", decoded: " + decoded); sb.append(", rejected: ").append(rejected); sb.append(", failed: ").append(failed); System.out.println(sb); return decoded; } /** * Iteratively finds what number of errors has recovery probability .5 * @param nRuns maximum number of iterations */ public static void testErrors(BlockCode code, int nRuns) { System.out.println(code); int maxDecoded = 0; int minFailed = Integer.MAX_VALUE; int hi = code.getBlockLength() - code.getMessageLength(); int lo = 0; for (int t = 0; t < nRuns; ++t) { BlockCode testCode = code.clone(); int errors = (lo + hi)/2; addErrors(testCode, errors); boolean decoded = false; if (testCode.decode()) { decoded = true; for (int i = 0; i < code.getBlockLength(); ++i) { if (testCode.getAt(i) != code.getAt(i)) { decoded = false; break; } } } System.out.println(" errors: " + errors + (decoded ? " OK" : " FAIL")); if (decoded) { maxDecoded = Math.max(maxDecoded, errors); lo = errors + 1; if (lo > hi) hi = lo; } else { minFailed = Math.min(minFailed, errors); hi = errors - 1; if (lo > hi) lo = hi; } } System.out.println(" [min failed, max decoded]: [" + minFailed +", " + maxDecoded + "]"); } } package org.swtk.commons.dict.wordnet.indexbyname.controller.d.i; import java.util.Collection; import java.util.Set; import java.util.TreeSet; import org.swtk.common.dict.dto.wordnet.IndexNoun; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.a.WordnetNounIndexNameInstanceDIA; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.b.WordnetNounIndexNameInstanceDIB; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.c.WordnetNounIndexNameInstanceDIC; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.d.WordnetNounIndexNameInstanceDID; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.e.WordnetNounIndexNameInstanceDIE; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.f.WordnetNounIndexNameInstanceDIF; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.g.WordnetNounIndexNameInstanceDIG; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.h.WordnetNounIndexNameInstanceDIH; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.j.WordnetNounIndexNameInstanceDIJ; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.k.WordnetNounIndexNameInstanceDIK; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.l.WordnetNounIndexNameInstanceDIL; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.m.WordnetNounIndexNameInstanceDIM; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.n.WordnetNounIndexNameInstanceDIN; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.o.WordnetNounIndexNameInstanceDIO; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.p.WordnetNounIndexNameInstanceDIP; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.r.WordnetNounIndexNameInstanceDIR; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.s.WordnetNounIndexNameInstanceDIS; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.t.WordnetNounIndexNameInstanceDIT; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.u.WordnetNounIndexNameInstanceDIU; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.v.WordnetNounIndexNameInstanceDIV; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.w.WordnetNounIndexNameInstanceDIW; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.x.WordnetNounIndexNameInstanceDIX; import org.swtk.commons.dict.wordnet.indexbyname.instance.d.i.z.WordnetNounIndexNameInstanceDIZ; import com.trimc.blogger.commons.exception.BusinessException; public final class WordnetNounIndexNameControllerDI { public static Collection get(final String TERM) throws BusinessException { if (TERM.length() < 3) throw new BusinessException("TERM not found (term = %s)", TERM); String key = TERM.replaceAll(" ", "").substring(0, 3).toLowerCase(); if ("dia".equals(key)) return WordnetNounIndexNameInstanceDIA.get(TERM); if ("dib".equals(key)) return WordnetNounIndexNameInstanceDIB.get(TERM); if ("dic".equals(key)) return WordnetNounIndexNameInstanceDIC.get(TERM); if ("did".equals(key)) return WordnetNounIndexNameInstanceDID.get(TERM); if ("die".equals(key)) return WordnetNounIndexNameInstanceDIE.get(TERM); if ("dif".equals(key)) return WordnetNounIndexNameInstanceDIF.get(TERM); if ("dig".equals(key)) return WordnetNounIndexNameInstanceDIG.get(TERM); if ("dih".equals(key)) return WordnetNounIndexNameInstanceDIH.get(TERM); if ("dij".equals(key)) return WordnetNounIndexNameInstanceDIJ.get(TERM); if ("dik".equals(key)) return WordnetNounIndexNameInstanceDIK.get(TERM); if ("dil".equals(key)) return WordnetNounIndexNameInstanceDIL.get(TERM); if ("dim".equals(key)) return WordnetNounIndexNameInstanceDIM.get(TERM); if ("din".equals(key)) return WordnetNounIndexNameInstanceDIN.get(TERM); if ("dio".equals(key)) return WordnetNounIndexNameInstanceDIO.get(TERM); if ("dip".equals(key)) return WordnetNounIndexNameInstanceDIP.get(TERM); if ("dir".equals(key)) return WordnetNounIndexNameInstanceDIR.get(TERM); if ("dis".equals(key)) return WordnetNounIndexNameInstanceDIS.get(TERM); if ("dit".equals(key)) return WordnetNounIndexNameInstanceDIT.get(TERM); if ("diu".equals(key)) return WordnetNounIndexNameInstanceDIU.get(TERM); if ("div".equals(key)) return WordnetNounIndexNameInstanceDIV.get(TERM); if ("diw".equals(key)) return WordnetNounIndexNameInstanceDIW.get(TERM); if ("dix".equals(key)) return WordnetNounIndexNameInstanceDIX.get(TERM); if ("diz".equals(key)) return WordnetNounIndexNameInstanceDIZ.get(TERM); throw new BusinessException("TERM not found (term = %s)", TERM); } public static Collection terms() throws BusinessException { Set set = new TreeSet(); set.addAll(WordnetNounIndexNameInstanceDIA.terms()); set.addAll(WordnetNounIndexNameInstanceDIB.terms()); set.addAll(WordnetNounIndexNameInstanceDIC.terms()); set.addAll(WordnetNounIndexNameInstanceDID.terms()); set.addAll(WordnetNounIndexNameInstanceDIE.terms()); set.addAll(WordnetNounIndexNameInstanceDIF.terms()); set.addAll(WordnetNounIndexNameInstanceDIG.terms()); set.addAll(WordnetNounIndexNameInstanceDIH.terms()); set.addAll(WordnetNounIndexNameInstanceDIJ.terms()); set.addAll(WordnetNounIndexNameInstanceDIK.terms()); set.addAll(WordnetNounIndexNameInstanceDIL.terms()); set.addAll(WordnetNounIndexNameInstanceDIM.terms()); set.addAll(WordnetNounIndexNameInstanceDIN.terms()); set.addAll(WordnetNounIndexNameInstanceDIO.terms()); set.addAll(WordnetNounIndexNameInstanceDIP.terms()); set.addAll(WordnetNounIndexNameInstanceDIR.terms()); set.addAll(WordnetNounIndexNameInstanceDIS.terms()); set.addAll(WordnetNounIndexNameInstanceDIT.terms()); set.addAll(WordnetNounIndexNameInstanceDIU.terms()); set.addAll(WordnetNounIndexNameInstanceDIV.terms()); set.addAll(WordnetNounIndexNameInstanceDIW.terms()); set.addAll(WordnetNounIndexNameInstanceDIX.terms()); set.addAll(WordnetNounIndexNameInstanceDIZ.terms()); return set; } }securebanking-openbanking-aspsp-common/src/main/java/com/forgerock/securebanking/openbanking/aspsp/common/converter/account/FRStandingOrderConverter.java /** * Copyright © 2020 () * * 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.forgerock.securebanking.openbanking.aspsp.common.converter.account; import com.forgerock.securebanking.openbanking.aspsp.common.converter.FRAccountIdentifierConverter; import com.forgerock.securebanking.openbanking.aspsp.common.converter.FRAmountConverter; import com.forgerock.securebanking.openbanking.aspsp.common.converter.FRFinancialInstrumentConverter; import com.forgerock.securebanking.common.openbanking.domain.account.data.FRStandingOrderData; import uk.org.openbanking.datamodel.account.*; public class FRStandingOrderConverter { // FR to OB public static OBStandingOrder1 toOBStandingOrder1(FRStandingOrderData standingOrder) { return standingOrder == null ? null : new OBStandingOrder1() .accountId(standingOrder.getAccountId()) .standingOrderId(standingOrder.getStandingOrderId()) .frequency(standingOrder.getFrequency()) .reference(standingOrder.getReference()) .firstPaymentDateTime(standingOrder.getFirstPaymentDateTime()) .firstPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getFirstPaymentAmount())) .nextPaymentDateTime(standingOrder.getNextPaymentDateTime()) .nextPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getNextPaymentAmount())) .finalPaymentDateTime(standingOrder.getFinalPaymentDateTime()) .finalPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getFinalPaymentAmount())) .servicer(FRFinancialInstrumentConverter.toOBBranchAndFinancialInstitutionIdentification2(standingOrder.getCreditorAgent())) .creditorAccount(FRAccountIdentifierConverter.toOBCashAccount1(standingOrder.getCreditorAccount())); } public static OBStandingOrder2 toOBStandingOrder2(FRStandingOrderData standingOrder) { return standingOrder == null ? null : new OBStandingOrder2() .accountId(standingOrder.getAccountId()) .standingOrderId(standingOrder.getStandingOrderId()) .frequency(standingOrder.getFrequency()) .reference(standingOrder.getReference()) .firstPaymentDateTime(standingOrder.getFirstPaymentDateTime()) .firstPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getFirstPaymentAmount())) .nextPaymentDateTime(standingOrder.getNextPaymentDateTime()) .nextPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getNextPaymentAmount())) .finalPaymentDateTime(standingOrder.getFinalPaymentDateTime()) .finalPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getFinalPaymentAmount())) .standingOrderStatusCode(toOBExternalStandingOrderStatus1Code(standingOrder.getStandingOrderStatusCode())) .creditorAgent(FRFinancialInstrumentConverter.toOBBranchAndFinancialInstitutionIdentification2(standingOrder.getCreditorAgent())) .creditorAccount(FRAccountIdentifierConverter.toOBCashAccount1(standingOrder.getCreditorAccount())); } public static OBStandingOrder3 toOBStandingOrder3(FRStandingOrderData standingOrder) { return standingOrder == null ? null : new OBStandingOrder3() .accountId(standingOrder.getAccountId()) .standingOrderId(standingOrder.getStandingOrderId()) .frequency(standingOrder.getFrequency()) .reference(standingOrder.getReference()) .firstPaymentDateTime(standingOrder.getFirstPaymentDateTime()) .nextPaymentDateTime(standingOrder.getNextPaymentDateTime()) .finalPaymentDateTime(standingOrder.getFinalPaymentDateTime()) .standingOrderStatusCode(toOBExternalStandingOrderStatus1Code(standingOrder.getStandingOrderStatusCode())) .firstPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getFirstPaymentAmount())) .nextPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getNextPaymentAmount())) .finalPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getFinalPaymentAmount())) .creditorAgent(FRFinancialInstrumentConverter.toOBBranchAndFinancialInstitutionIdentification4(standingOrder.getCreditorAgent())) .creditorAccount(FRAccountIdentifierConverter.toOBCashAccount3(standingOrder.getCreditorAccount())); } public static OBStandingOrder4 toOBStandingOrder4(FRStandingOrderData standingOrder) { return standingOrder == null ? null : new OBStandingOrder4() .accountId(standingOrder.getAccountId()) .standingOrderId(standingOrder.getStandingOrderId()) .frequency(standingOrder.getFrequency()) .reference(standingOrder.getReference()) .firstPaymentDateTime(standingOrder.getFirstPaymentDateTime()) .nextPaymentDateTime(standingOrder.getNextPaymentDateTime()) .finalPaymentDateTime(standingOrder.getFinalPaymentDateTime()) .standingOrderStatusCode(toOBExternalStandingOrderStatus1Code(standingOrder.getStandingOrderStatusCode())) .firstPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getFirstPaymentAmount())) .nextPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getNextPaymentAmount())) .finalPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount(standingOrder.getFinalPaymentAmount())) .supplementaryData(FRAccountSupplementaryDataConverter.toOBSupplementaryData1(standingOrder.getSupplementaryData())) .creditorAgent(FRFinancialInstrumentConverter.toOBBranchAndFinancialInstitutionIdentification4(standingOrder.getCreditorAgent())) .creditorAccount(FRAccountIdentifierConverter.toOBCashAccount3(standingOrder.getCreditorAccount())); } public static OBStandingOrder5 toOBStandingOrder5(FRStandingOrderData standingOrder) { return standingOrder == null ? null : new OBStandingOrder5() .accountId(standingOrder.getAccountId()) .standingOrderId(standingOrder.getStandingOrderId()) .frequency(standingOrder.getFrequency()) .reference(standingOrder.getReference()) .firstPaymentDateTime(standingOrder.getFirstPaymentDateTime()) .nextPaymentDateTime(standingOrder.getNextPaymentDateTime()) .finalPaymentDateTime(standingOrder.getFinalPaymentDateTime()) .standingOrderStatusCode(toOBExternalStandingOrderStatus1Code(standingOrder.getStandingOrderStatusCode())) .firstPaymentAmount(FRAmountConverter.toAccountOBActiveOrHistoricCurrencyAndAmount(standingOrder.getFirstPaymentAmount())) .nextPaymentAmount(FRAmountConverter.toAccountOBActiveOrHistoricCurrencyAndAmount(standingOrder.getNextPaymentAmount())) .finalPaymentAmount(FRAmountConverter.toAccountOBActiveOrHistoricCurrencyAndAmount(standingOrder.getFinalPaymentAmount())) .supplementaryData(FRAccountSupplementaryDataConverter.toOBSupplementaryData1(standingOrder.getSupplementaryData())) .creditorAgent(FRFinancialInstrumentConverter.toOBBranchAndFinancialInstitutionIdentification5(standingOrder.getCreditorAgent())) .creditorAccount(FRAccountIdentifierConverter.toOBCashAccount5(standingOrder.getCreditorAccount())); } public static OBStandingOrder6 toOBStandingOrder6(FRStandingOrderData standingOrder) { return standingOrder == null ? null : new OBStandingOrder6() .accountId(standingOrder.getAccountId()) .standingOrderId(standingOrder.getStandingOrderId()) .frequency(standingOrder.getFrequency()) .reference(standingOrder.getReference()) .firstPaymentDateTime(standingOrder.getFirstPaymentDateTime()) .nextPaymentDateTime(standingOrder.getNextPaymentDateTime()) .lastPaymentDateTime(standingOrder.getLastPaymentDateTime()) .finalPaymentDateTime(standingOrder.getFinalPaymentDateTime()) .numberOfPayments(standingOrder.getNumberOfPayments()) .standingOrderStatusCode(toOBExternalStandingOrderStatus1Code(standingOrder.getStandingOrderStatusCode())) .firstPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount2(standingOrder.getFirstPaymentAmount())) .nextPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount3(standingOrder.getNextPaymentAmount())) .lastPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount11(standingOrder.getLastPaymentAmount())) .finalPaymentAmount(FRAmountConverter.toOBActiveOrHistoricCurrencyAndAmount4(standingOrder.getFinalPaymentAmount())) .creditorAgent(FRFinancialInstrumentConverter.toOBBranchAndFinancialInstitutionIdentification51(standingOrder.getCreditorAgent())) .creditorAccount(FRAccountIdentifierConverter.toOBCashAccount51(standingOrder.getCreditorAccount())) .supplementaryData(FRAccountSupplementaryDataConverter.toOBSupplementaryData1(standingOrder.getSupplementaryData())); } public static OBExternalStandingOrderStatus1Code toOBExternalStandingOrderStatus1Code(FRStandingOrderData.FRStandingOrderStatus standingOrderStatusCode) { return standingOrderStatusCode == null ? null : OBExternalStandingOrderStatus1Code.valueOf(standingOrderStatusCode.name()); } // OB to FR public static FRStandingOrderData toFRStandingOrderData(OBStandingOrder5 obStandingOrder) { return obStandingOrder == null ? null : FRStandingOrderData.builder() .accountId(obStandingOrder.getAccountId()) .standingOrderId(obStandingOrder.getStandingOrderId()) .frequency(obStandingOrder.getFrequency()) .reference(obStandingOrder.getReference()) .firstPaymentDateTime(obStandingOrder.getFirstPaymentDateTime()) .nextPaymentDateTime(obStandingOrder.getNextPaymentDateTime()) .finalPaymentDateTime(obStandingOrder.getFinalPaymentDateTime()) .standingOrderStatusCode(toFRStandingOrderStatus(obStandingOrder.getStandingOrderStatusCode())) .firstPaymentAmount(FRAmountConverter.toFRAmount(obStandingOrder.getFirstPaymentAmount())) .nextPaymentAmount(FRAmountConverter.toFRAmount(obStandingOrder.getNextPaymentAmount())) .finalPaymentAmount(FRAmountConverter.toFRAmount(obStandingOrder.getFinalPaymentAmount())) .creditorAgent(FRFinancialInstrumentConverter.toFRFinancialAgent(obStandingOrder.getCreditorAgent())) .creditorAccount(FRAccountIdentifierConverter.toFRAccountIdentifier(obStandingOrder.getCreditorAccount())) .supplementaryData(FRAccountSupplementaryDataConverter.toFRSupplementaryData(obStandingOrder.getSupplementaryData())) .build(); } public static FRStandingOrderData toFRStandingOrderData(OBStandingOrder6 obStandingOrder) { return obStandingOrder == null ? null : FRStandingOrderData.builder() .accountId(obStandingOrder.getAccountId()) .standingOrderId(obStandingOrder.getStandingOrderId()) .frequency(obStandingOrder.getFrequency()) .reference(obStandingOrder.getReference()) .firstPaymentDateTime(obStandingOrder.getFirstPaymentDateTime()) .nextPaymentDateTime(obStandingOrder.getNextPaymentDateTime()) .lastPaymentDateTime(obStandingOrder.getLastPaymentDateTime()) .finalPaymentDateTime(obStandingOrder.getFinalPaymentDateTime()) .numberOfPayments(obStandingOrder.getNumberOfPayments()) .standingOrderStatusCode(toFRStandingOrderStatus(obStandingOrder.getStandingOrderStatusCode())) .firstPaymentAmount(FRAmountConverter.toFRAmount(obStandingOrder.getFirstPaymentAmount())) .nextPaymentAmount(FRAmountConverter.toFRAmount(obStandingOrder.getNextPaymentAmount())) .lastPaymentAmount(FRAmountConverter.toFRAmount(obStandingOrder.getLastPaymentAmount())) .finalPaymentAmount(FRAmountConverter.toFRAmount(obStandingOrder.getFinalPaymentAmount())) .creditorAgent(FRFinancialInstrumentConverter.toFRFinancialAgent(obStandingOrder.getCreditorAgent())) .creditorAccount(FRAccountIdentifierConverter.toFRAccountIdentifier(obStandingOrder.getCreditorAccount())) .supplementaryData(FRAccountSupplementaryDataConverter.toFRSupplementaryData(obStandingOrder.getSupplementaryData())) .build(); } public static FRStandingOrderData.FRStandingOrderStatus toFRStandingOrderStatus(OBExternalStandingOrderStatus1Code standingOrderStatusCode) { return standingOrderStatusCode == null ? null : FRStandingOrderData.FRStandingOrderStatus.valueOf(standingOrderStatusCode.name()); } } /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.redis; import com.microsoft.azure.PagedList; import com.microsoft.azure.management.apigeneration.Beta; import com.microsoft.azure.management.apigeneration.Fluent; import com.microsoft.azure.management.redis.implementation.OperationInner; import com.microsoft.azure.management.redis.implementation.RedisInner; import com.microsoft.azure.management.redis.implementation.RedisManager; import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsBatchDeletion; import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsDeletingByResourceGroup; import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsGettingByResourceGroup; import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsGettingById; import com.microsoft.azure.management.resources.fluentcore.arm.collection.SupportsListingByResourceGroup; import com.microsoft.azure.management.resources.fluentcore.arm.models.HasManager; import com.microsoft.azure.management.resources.fluentcore.collection.SupportsBatchCreation; import com.microsoft.azure.management.resources.fluentcore.collection.SupportsCreating; import com.microsoft.azure.management.resources.fluentcore.collection.SupportsDeletingById; import com.microsoft.azure.management.resources.fluentcore.collection.SupportsListing; import com.microsoft.azure.management.resources.fluentcore.model.HasInner; import rx.Observable; /** * Entry point for Redis Cache management API. */ @Fluent public interface RedisCaches extends SupportsCreating, SupportsListing, SupportsListingByResourceGroup, SupportsGettingByResourceGroup, SupportsGettingById, SupportsDeletingById, SupportsDeletingByResourceGroup, SupportsBatchCreation, SupportsBatchDeletion, HasManager, HasInner { /** * Lists all of the available Redis REST API operations. * * @return list of available Redis REST operations. */ @Beta(Beta.SinceVersion.V1_12_0) PagedList listOperations(); /** * Lists all of the available Redis REST API operations. * * @return a representation of the future computation of this call */ @Beta(Beta.SinceVersion.V1_12_0) Observable listOperationsAsync(); } /* * Copyright 2021 , * * 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 cz.lzaruba.sonar.scm.plugin.impl; import cz.lzaruba.sonar.scm.AnalysisProcessor; import cz.lzaruba.sonar.scm.model.Analysis; import org.sonar.api.ce.posttask.PostProjectAnalysisTask; /** * @author , , 2021 */ public class PostProjectAnalysisExtension implements PostProjectAnalysisTask { @Override public void finished(Context context) { ProjectAnalysis projectAnalysis = context.getProjectAnalysis(); IssuesHolder holder = IssueCollectorExtension.ISSUES_CACHE.get(); new AnalysisProcessor().process(convert(holder, projectAnalysis)); } private Analysis convert(IssuesHolder holder, ProjectAnalysis projectAnalysis) { return new Analysis(holder.getIssues(), projectAnalysis.getScannerContext().getProperties()); } @Override public String getDescription() { return "sonar-scm-plugin:post-project-extension"; } } 0 /* * Copyright (C) 2014-2016 LinkedIn Corp. 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. */ package gobblin.runtime.locks; import java.io.IOException; import java.util.Properties; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.log4j.BasicConfigurator; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import gobblin.configuration.ConfigurationKeys; /** * Unit test for {@link FileBasedJobLock}. * * @author */ @Test(groups = {"gobblin.runtime"}) public class FileBasedJobLockTest extends JobLockTest { private FileSystem fs; private Path path; @BeforeClass public void setUp() throws IOException { BasicConfigurator.configure(); this.fs = FileSystem.getLocal(new Configuration()); this.path = new Path("MRJobLockTest"); if (!this.fs.exists(this.path)) { this.fs.mkdirs(this.path); } } @Override protected JobLock getJobLock() throws JobLockException { Properties properties = new Properties(); properties.setProperty(FileBasedJobLock.JOB_LOCK_DIR, this.path.getName()); properties.setProperty(ConfigurationKeys.JOB_NAME_KEY, "FileBasedJobLockTest-" + System.currentTimeMillis()); return new FileBasedJobLock(properties); } @AfterClass public void tearDown() throws IOException { if (this.fs.exists(this.path)) { this.fs.delete(this.path, true); } } } webapps/cycle/cycle/src/main/java/org/camunda/bpm/cycle/connector/crypt/EncryptionServiceImpl.java1-10 package org.camunda.bpm.cycle.connector.crypt; import java.io.File; import java.io.FileInputStream; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import org.jasypt.util.password.ConfigurablePasswordEncryptor; import org.jasypt.util.text.BasicTextEncryptor; import org.springframework.stereotype.Component; @Component public class EncryptionServiceImpl implements EncryptionService { private static final Logger log = Logger.getLogger(EncryptionServiceImpl.class.getName()); public final static String DEFAULT_PASSWORD = ""; BasicTextEncryptor textEncryptor; private String encryptionPassword = null; private String passwordFilePath = System.getProperty("user.home") + File.separatorChar + "cycle.password"; ConfigurablePasswordEncryptor userPasswordEncryptor; public EncryptionServiceImpl() {} public EncryptionServiceImpl(String encryptionPassword) { super(); this.setEncryptionPassword(encryptionPassword); } private void check() { if (textEncryptor == null){ textEncryptor = new BasicTextEncryptor(); textEncryptor.setPassword(getEncryptionPassword()); } if (userPasswordEncryptor == null) { userPasswordEncryptor = new ConfigurablePasswordEncryptor(); userPasswordEncryptor.setAlgorithm("SHA-1"); userPasswordEncryptor.setPlainDigest(false); } } @Override public String encryptConnectorPassword(String input) { check(); return textEncryptor.encrypt(input); } @Override public String decryptConnectorPassword(String input) { check(); if (input == null){ throw new IllegalArgumentException("Cant decrypt null value, did you try to decrypt an not unset connector password?"); } try{ return textEncryptor.decrypt(input); }catch (Exception e) { throw new EncryptionException(String.format("Could not decrypt text %s, are you using the correct key?", input), e); } } public String getEncryptionPassword() { File passwordFile = new File(getPasswordFilePath()); if (encryptionPassword == null && passwordFile.exists()) { try { FileInputStream passwordFileStream = new FileInputStream(passwordFile); Scanner scanner = new Scanner(passwordFileStream); encryptionPassword = scanner.useDelimiter("\\A").next().replace("\n", ""); passwordFileStream.close(); scanner.close(); } catch (Exception e) { log.log(Level.WARNING, String.format("Could not read the encryption password from specified path %s, using default password", getPasswordFilePath()), e); encryptionPassword = ; } }else if (encryptionPassword == null) { encryptionPassword = ; } return encryptionPassword; } public static void main(String[] args) { System.out.println("Enter the encryption password [press enter to use the default]:"); Scanner scanner = new Scanner (System.in); String password = scanner.nextLine(); if (password.isEmpty()){ password = ; } System.out.println("Enter the text / password to encrypt:"); String text = scanner.nextLine(); scanner.close(); System.out.println("Encrypted Result: "+ new EncryptionServiceImpl(password).encryptConnectorPassword(text) ); } public String getPasswordFilePath() { return passwordFilePath; } public void setPasswordFilePath(String passwordFilePath) { this.passwordFilePath = passwordFilePath; } public void setEncryptionPassword(String encryptionPassword) { this.encryptionPassword = ; } @Override public String encryptUserPassword(String input) { check(); return userPasswordEncryptor.encryptPassword(input); } @Override public boolean checkUserPassword(String plain, String digest) { check(); return userPasswordEncryptor.checkPassword(plain, digest); } } package org.young.common.util; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.young.common.PagingQuery; import org.young.common.PagingResult; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.Serializable; import java.util.List; /** * 分页工具类 * @author jeasonyoung */ @Slf4j public class PagingUtils { /** * 查询数据处理 * @param query * 查询条件 * @param listener * 查询监听器 * @param * 输出结果 * @param * 查询条件 * @param * 数据转换 * @return 返回集合 */ public static List queryHandler( @Nullable final Qry query, @Nonnull final QueryListener listener){ log.debug("queryHandler(query:"+ query +", listener:" + listener +")..."); try{ //查询数据 final List items = listener.query(query); if(items != null && items.size() > 0){ //输出数据 return ConvertUtils.convertHandler(items, listener); } }catch (Throwable e){ log.error("queryHandler(query:"+ query +",listener:"+ listener +")-exp:" + e.getMessage(), e); } return null; } /** * 构建分页查询数据 * @param pagingResult * 分页查询结果 * @param pagingQuery * 分页查询条件 * @param listener * 查询数据处理器 * @param handler * 数据类型转换器 * @param * 反馈结果类型 * @param * 查询条件类型 * @param * 数据类型 */ public static void buildPagingQuery( @Nonnull final PagingResult pagingResult, @Nullable final PagingQuery pagingQuery, @Nonnull final QueryListener listener, @Nullable final PagingQueryHandler handler){ log.debug("pagingQuery(query:"+ pagingQuery +",listener:"+ listener +",handler:"+ handler +")..."); try{ //查询条件 final Qry query = pagingQuery == null ? null : pagingQuery.getQuery(); //启用分页查询 if(handler != null){ handler.startPaging(pagingQuery); } //查询数据 final List items = listener.query(query); if(items != null){ //设置数据总数 if(handler != null) { pagingResult.setTotals(handler.totals(items)); } if(pagingResult.getTotals() == null || pagingResult.getTotals() == 0) { pagingResult.setTotals((long) items.size()); } //设置数据集合 pagingResult.setRows(ConvertUtils.convertHandler(items, listener)); } } catch (Throwable e){ log.error("pagingQuery(query:"+ pagingQuery +",listener:"+ listener +")-exp:" + e.getMessage(), e); } } /** * 构建数据分页查询 * @param pagingResult * 分页查询结果 * @param pagingQuery * 分页查询条件 * @param listener * 查询数据处理器 * @param * 反馈结果类型 * @param * 查询条件类型 * @param * 查询结果类型 */ public static void buildPageableQuery( @Nonnull final PagingResult pagingResult, @Nullable final PagingQuery pagingQuery, @Nonnull final QueryPageableListener listener){ log.debug("buildPageableQuery(pagingResult: {}, pagingQuery: {}, listener: {})...", pagingResult, pagingQuery, listener); try { //查询条件 int index = 0, rows = 10; if(pagingQuery != null) { //设置页码 index = pagingQuery.getIndex() - 1; //设置每页数据 rows = pagingQuery.getRows(); } if (index < 0) { index = 0; } if(rows <= 0){ rows = 10; } //查询结果数据 List items = null; //查询数据 final Page pageItems = listener.query(pagingQuery == null ? null : pagingQuery.getQuery(), PageRequest.of(index, rows)); if(pageItems != null){ //设置数据总数 pagingResult.setTotals(pageItems.getTotalElements()); //设置数据项集合 items = pageItems.getContent(); } //设置数据集合 pagingResult.setRows(ConvertUtils.convertHandler(items, listener)); }catch (Throwable ex){ log.error("buildPageableQuery(pagingQuery: "+ pagingQuery +")-exp:" + ex.getMessage(), ex); } } /** * 构造数据查询 * @param result * 查询结果 * @param qry * 查询条件 * @param listener * 查询数据处理器 * @param * 查询结果类型 * @param * 查询条件类型 * @param * 数据类型 */ public static void buildQuery( @Nonnull final PagingResult result, @Nullable final Qry qry, @Nonnull final QueryListener listener) { log.debug("query(qry:" + qry + ",listener:" + listener + ")..."); buildPagingQuery(result, new PagingQueryImpl<>(qry), listener, null); } /** * 查询监听器 */ public interface QueryListener extends ConvertUtils.ConvertHandler { /** * 查询数据 * @param query * 查询条件 * @return * 查询结果 */ List query(@Nullable final Qry query); } /** * 查询数据监听器 * @param * 查询条件类型 * @param * 查询结果类型 * @param * 反馈类型 */ public interface QueryPageableListener extends ConvertUtils.ConvertHandler{ /** * 查询数据 * @param query * 查询条件 * @param pageable * 分页条件 * @return 查询结果 */ Page query(@Nullable final Qry query, @Nonnull final Pageable pageable); } /** * 查询数据处理 */ public interface PagingQueryHandler extends Serializable { /** * 开始分页 * @param query * 分页条件 */ void startPaging(final PagingQuery query); /** * 统计数据 * @param items * 数据集合 * @return 统计数据 */ Long totals(final List items); } private static class PagingQueryImpl implements PagingQuery { private final Qry query; PagingQueryImpl(final Qry query){ this.query = query; } @Override public String getSort() { return null; } @Override public String getOrder() { return null; } @Override public Integer getRows() { return null; } @Override public Integer getIndex() { return null; } @Override public Qry getQuery() { return query; } } } package logical; public class p1 { public static void main(String args[]) { int a=3,b=5; for(int i=0;i * @author */ public class HexBinaryRenderer extends AbstractRenderer { private static final String RENDER_FAILED_MSG = "Failed to create binary hexadecimal renderer " + SEE_LOG_MSG; @Override public boolean canHandle(String mimeType) { return false; /* * can handle any data but return false here as we do not want this to * be default renderer */ } @Override protected String getSizeQueryTitle() { return "Render binary data (in hexadecimal viewer)?"; } @Override public JComponent getRendererComponent(Path path) throws RendererException { try (InputStream inputStream = getInputStream(path)) { // HexEditor editor = new HexEditor(); // editor.open(inputStream); // return editor; // TODO: Include org.fife.HexEditor from // https://github.com/taverna/taverna-svn/tree/master/taverna/utils/org.fife.ui.hexeditor return new JPanel(); } catch (Exception e) { logger.error("unrenderable: failed to create binhex renderer", e); return new JTextArea(RENDER_FAILED_MSG + e.getMessage()); } } @Override public String getType() { return "Binary (HexDec)"; } } 0 package SacredBeast.relics; import basemod.abstracts.CustomRelic; import com.badlogic.gdx.graphics.Texture; import com.megacrit.cardcrawl.actions.common.ObtainPotionAction; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import SacredBeast.SB_Mod; import SacredBeast.util.TextureLoader; import com.megacrit.cardcrawl.helpers.PotionHelper; import com.megacrit.cardcrawl.relics.AbstractRelic; import com.megacrit.cardcrawl.relics.EternalFeather; import com.megacrit.cardcrawl.rewards.RewardItem; import com.megacrit.cardcrawl.rooms.AbstractRoom; import com.megacrit.cardcrawl.rooms.RestRoom; import static SacredBeast.SB_Mod.makeRelicOutlinePath; import static SacredBeast.SB_Mod.makeRelicPath; public class FrozenCanteen extends CustomRelic { public static final String ID = SB_Mod.makeID("FrozenCanteen"); private static final Texture IMG = TextureLoader.getTexture(makeRelicPath("FrozenCanteen.png")); private static final Texture OUTLINE = TextureLoader.getTexture(makeRelicOutlinePath("FrozenCanteen.png")); public FrozenCanteen() { super(ID, IMG, OUTLINE, RelicTier.STARTER, LandingSound.CLINK); } //have to use a different method to add potions out of combat. public void onEnterRoom(AbstractRoom room) { if (room instanceof RestRoom) { this.flash(); AbstractDungeon.player.obtainPotion(AbstractDungeon.returnRandomPotion(true)); } } @Override public String getUpdatedDescription() { return DESCRIPTIONS[0]; } public AbstractRelic makeCopy() { return new FrozenCanteen(); } } KidSea/MusicPlayer package com.leslie.musicplayer.widget; import android.content.Context; import android.content.res.TypedArray; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.widget.TextView; import com.leslie.musicplayer.R; /** * Created by yuxuehai on 19-6-20. */ public class AutoChangeTextView extends TextView { private float mSelectedSize; private float mUnSelectedSize; public AutoChangeTextView(Context context) { this(context, null); } public AutoChangeTextView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public AutoChangeTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MySelectedSizes); if (ta != null) { mSelectedSize = ta.getDimension(R.styleable.MySelectedSizes_selectedSize, -1); mUnSelectedSize = ta.getDimension(R.styleable.MySelectedSizes_unSelectedSize, -1); } if (ta != null) { ta.recycle(); } } @Override public void setSelected(boolean selected) { Animation animation; if (selected) { animation = new AlphaAnimation(0.4F, 1F); animation.setDuration(500); setAnimation(animation); setTextSize(TypedValue.COMPLEX_UNIT_PX, mSelectedSize); } else { setTextSize(TypedValue.COMPLEX_UNIT_PX, mUnSelectedSize); } super.setSelected(selected); } } 100-1000 package com.ymbj.ordertest.hellowolrd.autoconfig; public class A { } package com.ngondrotracker.meditation.dto; import com.ngondrotracker.user.dto.UserDto; import lombok.Data; import java.util.TimeZone; @Data public class PracticeResultDto { private Long id; private Long timestamp; private TimeZone timeZone; private Integer repetitions; private UserDto userDto; private MeditationDto meditationDto; } guns-admin/src/main/java/com/stylefeng/guns/modular/system/service/ITCategoryService.java package com.stylefeng.guns.modular.system.service; import com.stylefeng.guns.modular.system.model.TCategory; import com.baomidou.mybatisplus.service.IService; /** *

* 商品类别 服务类 *

* * @author 梁华亭 * @since 2018-07-19 */ public interface ITCategoryService extends IService { } package controller; import static org.junit.Assert.assertTrue; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.GregorianCalendar; import java.util.Locale; import model.focus.DeadlineFocus; import model.focus.DurationFocus; import model.focus.FocusStrategy; import model.focus.FocusType; import model.focus.FocusWork; import model.focus.TaskTypeFocus; import model.repositories.RepositoryManager; import org.junit.After; import org.junit.Before; import org.junit.Test; import exception.ArrayLengthException; import exception.TimeException; public class FocusControllerTest { private FocusController controller; private RepositoryManager manager; private DispatchController dcontroller; @Before public void setUp() throws TimeException, ParseException { manager = new RepositoryManager(); dcontroller = new DispatchController(manager); controller = dcontroller.getFocusController(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); Date date = sdf.parse("2009-10-20T20:00:00"); GregorianCalendar gregDate = new GregorianCalendar(); gregDate.setTime(date); manager.getClock().setTime(gregDate); } @After public void tearDown() { manager = null; controller = null; dcontroller = null; } /** * A FocusWork instance is created. Is it a DeadlineFocus? * @throws ArrayLengthException */ @Test public void testCreateDeadline() throws ArrayLengthException { Object[] settings = new Object[] {0}; FocusWork work = controller.createFocus(FocusType.DeadlineFocus, null, settings); assertTrue(work.getStrategy() instanceof DeadlineFocus); } /** * Is the instance of type Duration? * @throws ArrayLengthException */ @Test public void testCreateDuration() throws ArrayLengthException { Object[] settings = new Object[] {0,0}; FocusWork work = controller.createFocus(FocusType.DurationFocus, null, settings); assertTrue(work.getStrategy() instanceof DurationFocus); } /** * Is the instance of type TaskType * @throws ArrayLengthException */ @Test public void testCreateTaskType() throws ArrayLengthException { Object[] settings = new Object[]{0,null}; FocusWork work = controller.createFocus(FocusType.TaskTypeFocus, null, settings); assertTrue(work.getStrategy() instanceof TaskTypeFocus); } /** * No parameters given. Should return a default FocusStrategy * @throws ArrayLengthException */ @Test public void testCreateDefault() throws ArrayLengthException { Object[] settings = new Object[0]; FocusWork work = controller.createFocus(FocusType.Default, null, settings); assertTrue(work.getStrategy() instanceof FocusStrategy); } } 1-10 //package com.bitcola.exchange.security.me.rest; // //import com.bitcola.exchange.security.auth.client.annotation.IgnoreUserToken; //import com.bitcola.exchange.security.auth.client.i18n.ColaLanguage; //import com.bitcola.exchange.security.common.msg.AppResponse; //import com.bitcola.exchange.security.me.biz.ColaIcoDepositBiz; //import com.bitcola.exchange.security.me.biz.ColaIcoUserBiz; //import com.bitcola.exchange.security.me.constant.AuditStatusConstant; //import com.bitcola.exchange.security.me.vo.DepositVo; //import com.bitcola.me.entity.ColaIcoUser; //import org.apache.commons.lang3.StringUtils; //import org.springframework.beans.factory.annotation.Autowired; //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.RestController; //import tk.mybatis.mapper.entity.Example; // //import java.math.BigDecimal; //import java.util.HashMap; //import java.util.List; //import java.util.Map; // // ///** // * ICO 接口 // * // * @author zkq // * @create 2018-09-29 09:45 // **/ //@RestController //@RequestMapping("ico") //public class ColaIcoController { // // @Autowired // ColaIcoUserBiz icoUserBiz; // // @Autowired // ColaIcoDepositBiz depositBiz; // // @RequestMapping(value = "getAllIcoUser",method = RequestMethod.GET) // public AppResponse getAllIcoUser(){ // Example example = new Example(ColaIcoUser.class); // example.orderBy("userId").desc(); // return AppResponse.ok().data(icoUserBiz.selectByExample(example)); // } // // // // /** // * 后台审核 ICO 资料 // * @return // */ // @RequestMapping(value = "audit",method = RequestMethod.POST) // public AppResponse audit(@RequestBody Map params){ // String id = params.get("id"); // String option = params.get("option"); // if (StringUtils.isBlank(id) || StringUtils.isBlank(option)){ // return AppResponse.paramsError(); // } // if (!AuditStatusConstant.AGREE.equals(option) && !AuditStatusConstant.REFUSE.equals(option)){ // return AppResponse.paramsError(); // } // icoUserBiz.audit(id,option); // return AppResponse.ok(); // } // // // // /** // * ico 截止时间 和剩余时间 // * @return // */ // @RequestMapping("getDeadlineAndSellPercent") // @IgnoreUserToken // public AppResponse getDeadlineAndSellPercent(){ // Map map = icoUserBiz.getDeadlineAndSellPercent(); // return AppResponse.ok().data(map); // } // // // /** // * 服务器当前时间 // * @return // */ // @RequestMapping("getCurrentTime") // @IgnoreUserToken // public AppResponse getCurrentTime(){ // return AppResponse.ok().data(System.currentTimeMillis()); // } // // /** // * 用户资料提交审核 // * @param info // * @return // */ // @RequestMapping( value = "userInfoSubmit",method = RequestMethod.POST) // public AppResponse userInfoSubmit(@RequestBody ColaIcoUser info){ // if (StringUtils.isBlank(info.getAreaCode()) || StringUtils.isBlank(info.getBackSide()) || StringUtils.isBlank(info.getBirthday()) || // StringUtils.isBlank(info.getCountry()) || StringUtils.isBlank(info.getEmail()) || // StringUtils.isBlank(info.getFirstName()) || StringUtils.isBlank(info.getFrontSide()) || StringUtils.isBlank(info.getIdCardType()) || // StringUtils.isBlank(info.getLastName()) || StringUtils.isBlank(info.getGender()) || StringUtils.isBlank(info.getTelPhone()) || // info.getPlannedInvestment() == null) { // return AppResponse.error(ColaLanguage.get(ColaLanguage.ME_ICO_INFO_ERROR)); // } // // 检测 eth 地址是否存在 -- 采用 BTC ,不校验地址,使用充值地址判断用户充值 // //boolean b = icoUserBiz.checkAddress(info.getAddress()); // //if (b){ // // return AppResponse.error(ColaLanguage.get(ColaLanguage.ME_ICO_ADDRESS_ERROR)); // //} // icoUserBiz.userInfoSubmit(info); // // return AppResponse.ok(); // } // // /** // * ico 地址 (user) // * @return // */ // @RequestMapping("icoInfo") // public AppResponse icoInfo(){ // ColaIcoUser user = icoUserBiz.icoInfo(); // Map map = new HashMap<>(); // map.put("checkStatus",user.getCheckStatus()); // if (user.getCheckStatus() == 1){ // map.put("depositAddress",user.getDepositAddress()); // } // BigDecimal number = icoUserBiz.colaTokenIcoTotalNumber(); // map.put("colaTokenSaleStatus",0); // if (number.compareTo(new BigDecimal(icoUserBiz.getIcoConfig("ico_total_number"))) > 0){ // map.put("colaTokenSaleStatus",-1); // map.remove("depositAddress"); // } // if (System.currentTimeMillis() > Long.valueOf(icoUserBiz.getIcoConfig("ico_deadline"))){ // map.put("colaTokenSaleStatus", -2); // map.remove("depositAddress"); // } // return AppResponse.ok().data(map); // } // // /** // * 已经购买多少token (deposit) // */ // @RequestMapping("colaTokenNumber") // public AppResponse colaTokenNumber(){ // BigDecimal num = icoUserBiz.colaTokenNumber(); // if (num == null){ // num = BigDecimal.ZERO; // } // return AppResponse.ok().data(num); // } // // /** // * token信息,包含 以太坊价格,奖励比例(api,取币安, zb, okex 平均值) // * @return // */ // @RequestMapping("colaTokenInfo") // public AppResponse colaTokenInfo(){ // Map map = icoUserBiz.colaTokenInfo(); // return AppResponse.ok().data(map); // } // // /** // * 通过状态(通过,拒绝,等待,没有进行申请) (user) // * @return // */ // @RequestMapping("icoStatus") // public AppResponse icoStatus(){ // Integer status = icoUserBiz.icoStatus(); // return AppResponse.ok().data(status); // } // // /** // * 充值列表 // * @return // */ // @RequestMapping("depositList") // public AppResponse depositList(){ // List list = depositBiz.depositList(); // return AppResponse.ok().data(list); // } // // /** // * 订阅 // * @return // */ // @IgnoreUserToken // @RequestMapping("subscribe") // public AppResponse subscribe(String email){ // if (StringUtils.isBlank(email)){ // return AppResponse.paramsError(); // } // if(icoUserBiz.checkSubscribeExist(email)){ // return AppResponse.error(ColaLanguage.get(ColaLanguage.ME_ICO_SUBSCRIBE)); // } // icoUserBiz.subscribe(email); // return AppResponse.ok(); // } // // // //} wlufei-rpc-framework/src/main/java/com/wlufei/rpc/framework/client/SocketRPCClient.java package com.wlufei.rpc.framework.client; import com.wlufei.rpc.framework.common.RPCRequest; import com.wlufei.rpc.framework.common.enums.RpcErrorMessageEnum; import com.wlufei.rpc.framework.common.exception.RpcException; import com.wlufei.rpc.framework.common.extensions.ExtensionLoader; import com.wlufei.rpc.framework.registry.RegistryService; import com.wlufei.rpc.framework.remoting.RPCRequestTransport; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetSocketAddress; import java.net.Socket; import static com.wlufei.rpc.framework.registry.impl.ZKRegistryServiceImpl.ZK_REGISTRY_SPI; /** * 套接字 rpc request 传输 * * @author labu * @date 2021/07/29 */ @Slf4j public class SocketRPCClient implements RPCRequestTransport { private final RegistryService registryService; public SocketRPCClient() { registryService = ExtensionLoader.getExtensionLoader(RegistryService.class).getExtension(ZK_REGISTRY_SPI); } @Override public Object sendRPCRequest(RPCRequest rpcRequest) { InetSocketAddress inetSocketAddress = registryService.lookupService(rpcRequest); log.info("get service provider inetAddr:{}", inetSocketAddress.toString()); Socket socket = new Socket(); try { socket.connect(inetSocketAddress); ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream()); objectOutputStream.writeObject(rpcRequest); ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream()); return objectInputStream.readObject(); } catch (IOException | ClassNotFoundException e) { log.error(e.getMessage(), e); throw new RpcException(RpcErrorMessageEnum.CLIENT_CONNECT_SERVER_FAILURE); } } } /* Copyright (C) 2005-2011 */ package com.lightcrafts.image.export; import java.io.IOException; import com.lightcrafts.utils.xml.XmlNode; import com.lightcrafts.utils.xml.XMLException; /** * An StringExportOption is-an {@link ImageExportOption} for * storing an option that has an string value. * * @author [] */ public class StringExportOption extends ImageExportOption { ////////// public ///////////////////////////////////////////////////////// /** * {@inheritDoc} */ public final boolean equals( Object o ) { if ( !(o instanceof StringExportOption) ) return false; final StringExportOption s = (StringExportOption)o; return s.getName().equals( getName() ) && s.getValue().equals( getValue() ); } /** * Get the string value of this option. * * @return Returns said value. */ public String getValue() { return m_value; } /** * Sets the string value of this option. * * @param newValue The new value. */ public void setValue( String newValue ) { m_value = newValue; } /** * @deprecated */ public void save( XmlNode node ) { node = node.addChild( getName() ); node.setAttribute( ValueTag, getValue() ); } /** * @deprecated */ public void restore( XmlNode node ) throws XMLException { node = node.getChild( getName() ); m_value = node.getAttribute( ValueTag ); } /** * {@inheritDoc} */ public void readFrom( ImageExportOptionReader r ) throws IOException { r.read( this ); } /** * {@inheritDoc} */ public void writeTo( ImageExportOptionWriter w ) throws IOException { w.write( this ); } ////////// protected ////////////////////////////////////////////////////// /** * Construct an StringExportOption. * * @param name The name of this option. * @param defaultValue The default value for this option. * @param options The {@link ImageExportOptions} of which this option is a * member. */ protected StringExportOption( String name, String defaultValue, ImageExportOptions options ) { super( name, options ); m_value = defaultValue; } ////////// private //////////////////////////////////////////////////////// /** * The string value of this option. */ private String m_value; } /* vim:set et sw=4 ts=4: */ beetecu/DigitalSignage package zumzum.app.zunzuneando.visor.ads; import java.io.File; import java.io.IOException; import zumzum.app.zunzuneando.R; import zumzum.app.zunzuneando.visor.contents.ContentAd; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Environment; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.Toast; import android.widget.ViewAnimator; import com.tekle.oss.android.animation.AnimationFactory; import com.tekle.oss.android.animation.AnimationFactory.FlipDirection; public class AdsActivity extends Activity { private static final String TAG = "AdsActivity"; /** Called when the activity is first created. */ private final long startTimeLong = 5*1000; private final long startTimeShort = 15*1000; private final long interval = 1000; public MalibuCountDownTimer countDownTimer; public boolean statusLong = true; ViewAnimator viewAnimator ; ImageView imgFront; ImageView imgBack; ImageView imgBackground; //private ContentAd advertising; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.adsimg); viewAnimator = (ViewAnimator)this.findViewById(R.id.viewFlipper); imgFront = (ImageView)this.findViewById(R.id.imageFront); imgBack = (ImageView)this.findViewById(R.id.imageBack); imgBackground= (ImageView)this.findViewById(R.id.imageBackground); //advertising = (ContentAd) getIntent().getExtras().getSerializable("Advertising"); String background = (String) getIntent().getExtras().getSerializable("background"); Log.e(TAG, background); String logo = (String) getIntent().getExtras().getSerializable("logo"); String offert = (String) getIntent().getExtras().getSerializable("offert"); imgFront.setBackgroundDrawable(new BitmapDrawable(getBitmap(logo))); imgBack.setBackgroundDrawable(new BitmapDrawable(getBitmap(offert))); imgBackground.setBackgroundDrawable(new BitmapDrawable(getBitmap(background))); long duration = (Long) getIntent().getExtras().getSerializable("Duration"); //arreglar countDownTimer = new MalibuCountDownTimer(startTimeLong, interval); countDownTimer.start(); /** * Bind a click listener to initiate the flip transitions */ viewAnimator.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // This is all you need to do to 3D flip AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT); } }); } public static Bitmap getBitmap(String path) { Bitmap result = null; result = getScaleImage(BitmapFactory.decodeFile(path), 1250); return result; } /* * Scaling down the image */ public static Bitmap getScaleImage(Bitmap bitmap, int boundBoxInDp) { // Get current dimensions int width = bitmap.getWidth(); int height = bitmap.getHeight(); // Determine how much to scale: the dimension requiring // less scaling is. // closer to the its side. This way the image always // stays inside your. // bounding box AND either x/y axis touches it. float xScale = ((float) boundBoxInDp) / width; float yScale = ((float) boundBoxInDp) / height; float scale = (xScale <= yScale) ? xScale : yScale; // Create a matrix for the scaling and add the scaling data Matrix matrix = new Matrix(); matrix.postScale((float) scale, (float) scale); // Create a new bitmap and convert it to a format understood // by the // ImageView Bitmap scaledBitmap = Bitmap. createBitmap(bitmap, 0, 0, width, height, matrix, true); // Apply the scaled bitmap return scaledBitmap; } // CountDownTimer class public class MalibuCountDownTimer extends CountDownTimer { public MalibuCountDownTimer(long startTime, long interval) { super(startTime, interval); } @Override public void onFinish() { Log.e("TAG", "Time's up!"); if (statusLong){ Log.e("TAG", "statusLong"); cancel(); statusLong = false; AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT); countDownTimer = new MalibuCountDownTimer(startTimeShort, 1000); countDownTimer.start(); } else{ Log.e("TAG", "statusShort"); cancel(); statusLong = true; AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT); //countDownTimer = new MalibuCountDownTimer(startTimeLong, 1000); //countDownTimer.start(); finish(); } } @Override public void onTick(long millisUntilFinished) { //text.setText("Time remain:" + millisUntilFinished); //timeElapsed = startTime - millisUntilFinished; //timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed)); } } }package com.example.emsdesigntool.searchandshow; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import com.example.emsdesigntool.EMSModule; import java.util.ArrayList; public class SearchAndShowEMSChannels extends LinearLayout { private ArrayAdapter channelsToConnect; private String selectedItem = null; private ArrayList checkedItems = new ArrayList(); private ArrayList testData = new ArrayList(); public SearchAndShowEMSChannels(Context context, AttributeSet attrs, ArrayList emsModules, ArrayList connectedChannels){ super(context, attrs); setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); ListView listView = new ListView(context); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); channelsToConnect = new ArrayAdapter(context, android.R.layout.select_dialog_singlechoice, testData); listView.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); for(EMSModule emsModule : emsModules){ boolean foundCH1 = false; boolean foundCH2 = false; if(emsModule.isConnected()){ for(int i = 0; i < connectedChannels.size(); i++){ if(connectedChannels.get(i).equals(emsModule.getDeviceName() + ",CH0")){ foundCH1 = true; } if(connectedChannels.get(i).equals(emsModule.getDeviceName() + ",CH1")){ foundCH2 = true; } } if(!foundCH1){ channelsToConnect.add(emsModule.getDeviceName() + ",CH0"); } if(!foundCH2){ channelsToConnect.add(emsModule.getDeviceName() + ",CH1"); } } } listView.setAdapter(channelsToConnect); this.addView(listView); listView.setFocusable(true); listView.setSelection(0); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { selectedItem = channelsToConnect.getItem(position); view.setActivated(true); if(checkedItems.contains(selectedItem)){ checkedItems.remove(selectedItem); }else{ checkedItems.add(selectedItem); } } }); } public ArrayList getNamesOfSelectedItems() { return checkedItems; } } sample-app/app/src/main/java/com/nbrown/mathaddict/Keys.java1-10 package com.nbrown.mathaddict; /** * Created by Nigel.Brown on 8/22/2017. */ public interface Keys { String EQUATION = "equation"; String IS_FINAL_PROBLEM = "isFinalProblem"; String QUIZ_RESULTS = "quizResults"; String ANSWER = "answer"; } cambridge-cares/TheWorldAvatarobsolete/JPS_DES/test/uk/ac/cam/cares/des/test/DESSystemAgentTest.java package uk.ac.cam.cares.des.test; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.apache.jena.ontology.OntModel; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import uk.ac.cam.cares.jps.base.discovery.AgentCaller; import uk.ac.cam.cares.jps.base.query.QueryBroker; import uk.ac.cam.cares.jps.des.n.CommercialAgent; import uk.ac.cam.cares.jps.des.n.DESAgentNew; import uk.ac.cam.cares.jps.des.n.IndustrialAgent; import uk.ac.cam.cares.jps.des.n.ResidentialAgent; import uk.ac.cam.cares.jps.des.n.SolarAgent; public class DESSystemAgentTest { private String iriofnetworkdistrict = null; private String irioftempF= null; private String iriofirrF= null; private String iriofnetwork = null; @Before public void setUp() { iriofnetworkdistrict = "http://www.theworldavatar.com/kb/sgp/singapore/District-001.owl#District-001"; irioftempF="http://www.theworldavatar.com/kb/sgp/singapore/SGTemperatureForecast-001.owl#SGTemperatureForecast-001"; iriofirrF="http://www.theworldavatar.com/kb/sgp/singapore/SGSolarIrradiationForecast-001.owl#SGSolarIrradiationForecast-001"; iriofnetwork = "http://www.theworldavatar.com/kb/sgp/singapore/singaporeelectricalnetwork/SingaporeElectricalNetwork.owl#SingaporeElectricalNetwork"; } /** test if validateInput method is working in System Agent * */ @Test public void testInputValidatorSystem() { JSONObject jo = new JSONObject() .put("electricalnetwork", iriofnetwork); jo.put("temperatureforecast", irioftempF); jo.put("irradiationforecast", iriofirrF); jo.put("district",iriofnetworkdistrict); assertTrue(new DESAgentNew().validateInput(jo)); } /** tests if System Agent calls successfully. * System Agent requires caresjpsutil library. * */ @Test public void testSystemAgent() { String baseUrl = "C:\\JPS_DATA\\workingdir\\JPS_SCENARIO\\scenario\\DESTest\\Overall"; new DESAgentNew().queryForIrradTemp(irioftempF,iriofirrF, baseUrl); OntModel model = DESAgentNew.readModelGreedy(iriofnetwork); new SolarAgent().provideGenlist(model, baseUrl); // create Parameters for Solar Cell new ResidentialAgent().extractResidentialData(iriofnetworkdistrict, baseUrl); //csv for residential new CommercialAgent().queryForBuildingConstants(model, baseUrl);;//csv for commercial new IndustrialAgent().queryForConstantsIndustrial(model, baseUrl);;//csv for commercial String result = new DESAgentNew().runPythonScript("system.py", baseUrl); assertNotNull(result); } /** test System agent calls through Agent successfully * dumps result in JPS Scenarios folder * Calls FrontEndTalk to check results of BlockchainWrapper */ @Test public void testSystemAgentCaller() { JSONObject jo = new JSONObject() .put("electricalnetwork", iriofnetwork); jo.put("temperatureforecast", irioftempF); jo.put("irradiationforecast", iriofirrF); jo.put("district",iriofnetworkdistrict); jo.put("cityIRI", "http://dbpedia.org/page/Singapore"); jo.put("baseUrl", QueryBroker.getLocalDataPath()+"/JPS_DES"); String resultStart = AgentCaller.executeGetWithJsonParameter("JPS_DES/DESAgentNew", jo.toString()); assertNotNull(resultStart); } } package nasa.logic.commands; import static java.util.Objects.requireNonNull; import static nasa.logic.parser.CliSyntax.PREFIX_ACTIVITY_NAME; import static nasa.logic.parser.CliSyntax.PREFIX_DATE; import static nasa.logic.parser.CliSyntax.PREFIX_MODULE; import static nasa.logic.parser.CliSyntax.PREFIX_NOTE; import static nasa.logic.parser.CliSyntax.PREFIX_PRIORITY; import static nasa.model.Model.PREDICATE_SHOW_ALL_ACTIVITIES; import static nasa.model.Model.PREDICATE_SHOW_ALL_MODULES; import java.util.Optional; import nasa.commons.core.Messages; import nasa.commons.core.index.Index; import nasa.commons.util.CollectionUtil; import nasa.logic.commands.exceptions.CommandException; import nasa.model.Model; import nasa.model.activity.Activity; import nasa.model.activity.Date; import nasa.model.activity.Deadline; import nasa.model.activity.Event; import nasa.model.activity.Lesson; import nasa.model.activity.Name; import nasa.model.activity.Note; import nasa.model.activity.Priority; import nasa.model.activity.Status; import nasa.model.activity.UniqueActivityList; import nasa.model.module.Module; import nasa.model.module.ModuleCode; /** * Edits a specific activity in the moduleCode's list. */ public class EditActivityCommand extends Command { public static final String COMMAND_WORD = "edit"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits the details of the activity identified " + "by the index number used in the displayed moduleCode's activity list. " + "Existing values will be overwritten by the input values.\n" + "Parameters: " + PREFIX_MODULE + "MODULE CODE " + "INDEX (must be a positive integer) " + "[" + PREFIX_DATE + "DATE] " + "[" + PREFIX_ACTIVITY_NAME + "ACTIVITY NAME] " + "[" + PREFIX_PRIORITY + "PRIORITY] " + "[" + PREFIX_NOTE + "NOTE]\n" + "Example: " + COMMAND_WORD + " " + PREFIX_MODULE + "CS2030 " + "1 " + PREFIX_DATE + "2020-03-20 " + PREFIX_ACTIVITY_NAME + "Assignment 2.3"; public static final String MESSAGE_EDIT_ACTIVITY_SUCCESS = "Edited Activity"; public static final String MESSAGE_NOT_EDITED = "At least one field to edit must be provided."; public static final String MESSAGE_DUPLICATE_ACTIVITY = "This activity already exists in the " + "moduleCode activity list."; private final Index index; private final ModuleCode moduleCode; private final EditActivityCommand.EditActivityDescriptor editActivityDescriptor; /** * Creates an EditActivityCommand to edit an activity * with the specified {@code index} from the specified {@code moduleCode} list. * @param index index of the activity item as specified in the corresponding module * @param moduleCode module code which the activity item is found in * @param editActivityDescriptor */ public EditActivityCommand(Index index, ModuleCode moduleCode, EditActivityDescriptor editActivityDescriptor) { requireNonNull(index); this.index = index; this.moduleCode = moduleCode; this.editActivityDescriptor = new EditActivityDescriptor(editActivityDescriptor); } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); Module module = model.getNasaBook().getUniqueModuleList().getModule(moduleCode); requireNonNull(module); UniqueActivityList moduleUniqueActivityList = module.getActivities(); if (index.getZeroBased() >= moduleUniqueActivityList.getActivityList().size()) { throw new nasa.logic.commands.exceptions.CommandException( Messages.MESSAGE_INVALID_ACTIVITY_DISPLAYED_INDEX); } Activity activityToEdit = moduleUniqueActivityList.getActivityByIndex(index); Activity editedActivity = createEditedActivity(activityToEdit, editActivityDescriptor); requireNonNull(editedActivity); if (!activityToEdit.isSameActivity(editedActivity) && model.hasActivity(moduleCode, editedActivity)) { throw new nasa.logic.commands.exceptions.CommandException(MESSAGE_DUPLICATE_ACTIVITY); } model.setActivityByIndex(moduleCode, index, editedActivity); model.updateFilteredModuleList(PREDICATE_SHOW_ALL_MODULES); model.updateFilteredActivityList(index, PREDICATE_SHOW_ALL_ACTIVITIES); return new CommandResult(String.format(MESSAGE_EDIT_ACTIVITY_SUCCESS, editedActivity)); } /** * Creates and returns an {@code Activity} with the details of {@code activityToEdit} * edited with {@code editModuleDescriptor}. */ private static Activity createEditedActivity(Activity activityToEdit, EditActivityDescriptor editActivityDescriptor) { requireNonNull(activityToEdit); Name updatedName = editActivityDescriptor.getName().orElse(activityToEdit.getName()); Date updatedDate = editActivityDescriptor.getDate().orElse(activityToEdit.getDate()); Note updatedNote = editActivityDescriptor.getNote().orElse(activityToEdit.getNote()); Priority updatedPriority = editActivityDescriptor.getPriority().orElse(activityToEdit.getPriority()); Status status = activityToEdit.getStatus(); // original moduleCode's activity list is preserved if (activityToEdit instanceof Deadline) { Date dueDate = ((Deadline) activityToEdit).getDueDate(); return new Deadline(updatedName, updatedDate, updatedNote, status, updatedPriority, dueDate); } else if (activityToEdit instanceof Event) { Date startDate = ((Event) activityToEdit).getDateFrom(); Date endDate = ((Event) activityToEdit).getDateTo(); return new Event(updatedName, updatedDate, updatedNote, status, updatedPriority, startDate, endDate); } else if (activityToEdit instanceof Lesson) { Date startDate = ((Lesson) activityToEdit).getDateFrom(); Date endDate = ((Lesson) activityToEdit).getDateTo(); return new Event(updatedName, updatedDate, updatedNote, status, updatedPriority, startDate, endDate); } else { return null; } } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof EditActivityCommand // instanceof handles nulls && index.equals(((EditActivityCommand) other).index) && moduleCode.equals(((EditActivityCommand) other).moduleCode) && editActivityDescriptor.equals(((EditActivityCommand) other).editActivityDescriptor)); } /** * Stores the details to edit the activity with. Each non-empty field value will replace the * corresponding field value of the moduleCode. */ public static class EditActivityDescriptor { private Name name; private Date date; private Note note; private Priority priority; public EditActivityDescriptor() {} /** * Copy constructor. */ public EditActivityDescriptor(EditActivityCommand.EditActivityDescriptor toCopy) { setName(toCopy.name); setDate(toCopy.date); setNote(toCopy.note); setPriority(toCopy.priority); } /** * Returns true if at least one field is edited. */ public boolean isAnyFieldEdited() { return CollectionUtil.isAnyNonNull(name, date, note, priority); } public void setName(Name name) { this.name = name; } public Optional getName() { return Optional.ofNullable(name); } public void setDate(Date date) { this.date = date; } public Optional getDate() { return Optional.ofNullable(date); } public void setNote(Note note) { this.note = note; } public Optional getNote() { return Optional.ofNullable(note); } public void setPriority(Priority priority) { this.priority = priority; } public Optional getPriority() { return Optional.ofNullable(priority); } @Override public boolean equals(Object other) { // short circuit if same object if (other == this) { return true; } // instanceof handles nulls if (!(other instanceof EditActivityCommand.EditActivityDescriptor)) { return false; } // state check EditActivityCommand.EditActivityDescriptor e = (EditActivityCommand.EditActivityDescriptor) other; return getName().equals(e.getName()) && getDate().equals(e.getDate()) && getNote().equals(e.getNote()) && getPriority().equals(e.getPriority()); } } } MS_LIBRARY/src/org/yeastrc/ms/dao/run/ms2file/MS2ChargeDependentAnalysisDAO.java1-10 /** * Ms2FileChargeDependentAnalysisDAO.java * @author * Jun 18, 2008 * @version 1.0 */ package org.yeastrc.ms.dao.run.ms2file; import java.util.List; import org.yeastrc.ms.domain.run.ms2file.MS2ChargeDependentAnalysis; import org.yeastrc.ms.domain.run.ms2file.MS2NameValuePair; /** * */ public interface MS2ChargeDependentAnalysisDAO { public abstract void save(MS2NameValuePair analysis, int scanChargeId); public abstract void saveAll(List analysisList); public abstract List loadAnalysisForScanCharge(int scanChargeId); public abstract void deleteByScanChargeId(int scanChargeId); } /* * Copyright 2000-2019 JetBrains s.r.o. * * 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.intellij.ide.favoritesTreeView; import com.intellij.ui.JBColor; import java.awt.*; public enum Flag { orange(JBColor.orange), blue(JBColor.blue), green(JBColor.green), red(JBColor.red), brown(new JBColor(new Color(0x804000), new Color(0x9C5700))), magenta(JBColor.magenta), violet(new JBColor(new Color(0x8000FF), new Color(0x9C57FF))), yellow(JBColor.yellow), grey(JBColor.lightGray); private final Color myColor; Flag(Color color) { myColor = color; } public Color getColor() { return myColor; } } package io.github.lukaszbudnik.hibernate.multitenant.dao; import org.hibernate.context.spi.CurrentTenantIdentifierResolver; public class TenantIdentifierResolver implements CurrentTenantIdentifierResolver { @Override public String resolveCurrentTenantIdentifier() { return TenantThreadLocal.tenantThreadLocal.get(); } @Override public boolean validateExistingCurrentSessions() { return false; } } LeakyAbstractions/result2 package com.leakyabstractions.result; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import java.util.function.Function; import java.util.function.Supplier; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * Tests for {@link LazyResult#map(Function, Function)}. * * @author */ @DisplayName("LazyResult map") class LazyResult_map_Test { private static final String SUCCESS = "SUCCESS"; private static final String FAILURE = "FAILURE"; @Test void should_be_lazy() { // Given final Supplier> supplier = () -> fail("Should not happen"); final LazyResult lazy = new LazyResult<>(supplier); final Function successMapper = s -> fail("Should not happen"); final Function failureMapper = f -> fail("Should not happen"); // When final Result result = lazy.map(successMapper, failureMapper); // Then assertThat(result).isInstanceOf(LazyResult.class); } @Test void should_eventually_map_when_needed() { // Given final Supplier> supplier = () -> new Success<>(123); final LazyResult lazy = new LazyResult<>(supplier); final Function successMapper = s -> SUCCESS; final Function failureMapper = f -> fail("Should not happen"); // When final String value = lazy.map(successMapper, failureMapper).orElse(null); // Then assertThat(value).isSameAs(SUCCESS); } @Test void should_not_be_lazy_if_already_supplied() { // Given final Supplier> supplier = () -> new Failure<>(123); final LazyResult lazy = new LazyResult<>(supplier); final Result expected = new Failure<>(FAILURE); final Function successMapper = s -> fail("Should not happen"); final Function failureMapper = f -> FAILURE; // When final Integer value = lazy.optionalFailure().orElse(null); final Result result = lazy.map(successMapper, failureMapper); // Then assertThat(value).isEqualTo(123); assertThat(result).isEqualTo(expected); } } /* * Copyright 2020 Johnny850807 (Waterball) 潘冠辰 * 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 tw.waterball.judgegirl.primitives.submission.events; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import tw.waterball.judgegirl.primitives.submission.Bag; import tw.waterball.judgegirl.primitives.submission.verdict.Verdict; import java.util.Date; import static java.util.stream.Collectors.joining; /** * @author - (Waterball) */ @Builder @Getter @EqualsAndHashCode(callSuper = true) public class VerdictIssuedEvent extends Event { private final int problemId; private final String problemTitle; private final int studentId; private final String submissionId; private Verdict verdict; private final Date submissionTime; private final Bag submissionBag; public VerdictIssuedEvent(int problemId, String problemTitle, int studentId, String submissionId, Verdict verdict, Date submissionTime, Bag submissionBag) { super(VerdictIssuedEvent.class.getSimpleName()); this.problemId = problemId; this.problemTitle = problemTitle; this.studentId = studentId; this.submissionId = submissionId; this.verdict = verdict; this.submissionTime = submissionTime; this.submissionBag = submissionBag; } @Override public String toString() { return String.format("problemId=%d problemTitle=\"%s\" studentId=%d submissionId=%s submissionTime=%d " + "summaryStatus=%s verdictIssuedTime=%d grade=%s, with bag: %s", problemId, problemTitle, studentId, submissionId, submissionTime.getTime(), verdict.getSummaryStatus(), verdict.getIssueTime().getTime(), getVerdict().getGrade(), submissionBag.entrySet().stream() .map(entry -> String.format("%s=\"%s\"", entry.getKey(), entry.getValue())) .collect(joining(" "))); } public void setVerdict(Verdict verdict) { this.verdict = verdict; } } package VisualizeKM; /* * Common method(s) used throughout the algorithm */ public class Methods { public static int EUC(Vertex a, Vertex b){ float xDiff = a.x-b.x; double xSqr = Math.pow(xDiff, 2); double yDiff = a.y-b.y; double ySqr = Math.pow(yDiff, 2); int output = (int)Math.sqrt(xSqr + ySqr); return output; } } package com.github.pig.admin.model.entity; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; public class CompanyExample { protected String orderByClause; protected boolean distinct; protected List oredCriteria; public CompanyExample() { oredCriteria = new ArrayList(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList(); } public boolean isValid() { return criteria.size() > 0; } public List getAllCriteria() { return criteria; } public List getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } protected void addCriterionForJDBCDate(String condition, Date value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } addCriterion(condition, new java.sql.Date(value.getTime()), property); } protected void addCriterionForJDBCDate(String condition, List values, String property) { if (values == null || values.size() == 0) { throw new RuntimeException("Value list for " + property + " cannot be null or empty"); } List dateList = new ArrayList(); Iterator iter = values.iterator(); while (iter.hasNext()) { dateList.add(new java.sql.Date(iter.next().getTime())); } addCriterion(condition, dateList, property); } protected void addCriterionForJDBCDate(String condition, Date value1, Date value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } addCriterion(condition, new java.sql.Date(value1.getTime()), new java.sql.Date(value2.getTime()), property); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(String value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(String value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(String value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(String value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(String value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(String value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdLike(String value) { addCriterion("id like", value, "id"); return (Criteria) this; } public Criteria andIdNotLike(String value) { addCriterion("id not like", value, "id"); return (Criteria) this; } public Criteria andIdIn(List values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(String value1, String value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(String value1, String value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andFullnameIsNull() { addCriterion("fullName is null"); return (Criteria) this; } public Criteria andFullnameIsNotNull() { addCriterion("fullName is not null"); return (Criteria) this; } public Criteria andFullnameEqualTo(String value) { addCriterion("fullName =", value, "fullname"); return (Criteria) this; } public Criteria andFullnameNotEqualTo(String value) { addCriterion("fullName <>", value, "fullname"); return (Criteria) this; } public Criteria andFullnameGreaterThan(String value) { addCriterion("fullName >", value, "fullname"); return (Criteria) this; } public Criteria andFullnameGreaterThanOrEqualTo(String value) { addCriterion("fullName >=", value, "fullname"); return (Criteria) this; } public Criteria andFullnameLessThan(String value) { addCriterion("fullName <", value, "fullname"); return (Criteria) this; } public Criteria andFullnameLessThanOrEqualTo(String value) { addCriterion("fullName <=", value, "fullname"); return (Criteria) this; } public Criteria andFullnameLike(String value) { addCriterion("fullName like", value, "fullname"); return (Criteria) this; } public Criteria andFullnameNotLike(String value) { addCriterion("fullName not like", value, "fullname"); return (Criteria) this; } public Criteria andFullnameIn(List values) { addCriterion("fullName in", values, "fullname"); return (Criteria) this; } public Criteria andFullnameNotIn(List values) { addCriterion("fullName not in", values, "fullname"); return (Criteria) this; } public Criteria andFullnameBetween(String value1, String value2) { addCriterion("fullName between", value1, value2, "fullname"); return (Criteria) this; } public Criteria andFullnameNotBetween(String value1, String value2) { addCriterion("fullName not between", value1, value2, "fullname"); return (Criteria) this; } public Criteria andAddressIsNull() { addCriterion("address is null"); return (Criteria) this; } public Criteria andAddressIsNotNull() { addCriterion("address is not null"); return (Criteria) this; } public Criteria andAddressEqualTo(String value) { addCriterion("address =", value, "address"); return (Criteria) this; } public Criteria andAddressNotEqualTo(String value) { addCriterion("address <>", value, "address"); return (Criteria) this; } public Criteria andAddressGreaterThan(String value) { addCriterion("address >", value, "address"); return (Criteria) this; } public Criteria andAddressGreaterThanOrEqualTo(String value) { addCriterion("address >=", value, "address"); return (Criteria) this; } public Criteria andAddressLessThan(String value) { addCriterion("address <", value, "address"); return (Criteria) this; } public Criteria andAddressLessThanOrEqualTo(String value) { addCriterion("address <=", value, "address"); return (Criteria) this; } public Criteria andAddressLike(String value) { addCriterion("address like", value, "address"); return (Criteria) this; } public Criteria andAddressNotLike(String value) { addCriterion("address not like", value, "address"); return (Criteria) this; } public Criteria andAddressIn(List values) { addCriterion("address in", values, "address"); return (Criteria) this; } public Criteria andAddressNotIn(List values) { addCriterion("address not in", values, "address"); return (Criteria) this; } public Criteria andAddressBetween(String value1, String value2) { addCriterion("address between", value1, value2, "address"); return (Criteria) this; } public Criteria andAddressNotBetween(String value1, String value2) { addCriterion("address not between", value1, value2, "address"); return (Criteria) this; } public Criteria andOrganizationcodeIsNull() { addCriterion("organizationCode is null"); return (Criteria) this; } public Criteria andOrganizationcodeIsNotNull() { addCriterion("organizationCode is not null"); return (Criteria) this; } public Criteria andOrganizationcodeEqualTo(String value) { addCriterion("organizationCode =", value, "organizationcode"); return (Criteria) this; } public Criteria andOrganizationcodeNotEqualTo(String value) { addCriterion("organizationCode <>", value, "organizationcode"); return (Criteria) this; } public Criteria andOrganizationcodeGreaterThan(String value) { addCriterion("organizationCode >", value, "organizationcode"); return (Criteria) this; } public Criteria andOrganizationcodeGreaterThanOrEqualTo(String value) { addCriterion("organizationCode >=", value, "organizationcode"); return (Criteria) this; } public Criteria andOrganizationcodeLessThan(String value) { addCriterion("organizationCode <", value, "organizationcode"); return (Criteria) this; } public Criteria andOrganizationcodeLessThanOrEqualTo(String value) { addCriterion("organizationCode <=", value, "organizationcode"); return (Criteria) this; } public Criteria andOrganizationcodeLike(String value) { addCriterion("organizationCode like", value, "organizationcode"); return (Criteria) this; } public Criteria andOrganizationcodeNotLike(String value) { addCriterion("organizationCode not like", value, "organizationcode"); return (Criteria) this; } public Criteria andOrganizationcodeIn(List values) { addCriterion("organizationCode in", values, "organizationcode"); return (Criteria) this; } public Criteria andOrganizationcodeNotIn(List values) { addCriterion("organizationCode not in", values, "organizationcode"); return (Criteria) this; } public Criteria andOrganizationcodeBetween(String value1, String value2) { addCriterion("organizationCode between", value1, value2, "organizationcode"); return (Criteria) this; } public Criteria andOrganizationcodeNotBetween(String value1, String value2) { addCriterion("organizationCode not between", value1, value2, "organizationcode"); return (Criteria) this; } public Criteria andTroopsorsecrecyIsNull() { addCriterion("troopsOrSecrecy is null"); return (Criteria) this; } public Criteria andTroopsorsecrecyIsNotNull() { addCriterion("troopsOrSecrecy is not null"); return (Criteria) this; } public Criteria andTroopsorsecrecyEqualTo(Boolean value) { addCriterion("troopsOrSecrecy =", value, "troopsorsecrecy"); return (Criteria) this; } public Criteria andTroopsorsecrecyNotEqualTo(Boolean value) { addCriterion("troopsOrSecrecy <>", value, "troopsorsecrecy"); return (Criteria) this; } public Criteria andTroopsorsecrecyGreaterThan(Boolean value) { addCriterion("troopsOrSecrecy >", value, "troopsorsecrecy"); return (Criteria) this; } public Criteria andTroopsorsecrecyGreaterThanOrEqualTo(Boolean value) { addCriterion("troopsOrSecrecy >=", value, "troopsorsecrecy"); return (Criteria) this; } public Criteria andTroopsorsecrecyLessThan(Boolean value) { addCriterion("troopsOrSecrecy <", value, "troopsorsecrecy"); return (Criteria) this; } public Criteria andTroopsorsecrecyLessThanOrEqualTo(Boolean value) { addCriterion("troopsOrSecrecy <=", value, "troopsorsecrecy"); return (Criteria) this; } public Criteria andTroopsorsecrecyIn(List values) { addCriterion("troopsOrSecrecy in", values, "troopsorsecrecy"); return (Criteria) this; } public Criteria andTroopsorsecrecyNotIn(List values) { addCriterion("troopsOrSecrecy not in", values, "troopsorsecrecy"); return (Criteria) this; } public Criteria andTroopsorsecrecyBetween(Boolean value1, Boolean value2) { addCriterion("troopsOrSecrecy between", value1, value2, "troopsorsecrecy"); return (Criteria) this; } public Criteria andTroopsorsecrecyNotBetween(Boolean value1, Boolean value2) { addCriterion("troopsOrSecrecy not between", value1, value2, "troopsorsecrecy"); return (Criteria) this; } public Criteria andBankIsNull() { addCriterion("bank is null"); return (Criteria) this; } public Criteria andBankIsNotNull() { addCriterion("bank is not null"); return (Criteria) this; } public Criteria andBankEqualTo(String value) { addCriterion("bank =", value, "bank"); return (Criteria) this; } public Criteria andBankNotEqualTo(String value) { addCriterion("bank <>", value, "bank"); return (Criteria) this; } public Criteria andBankGreaterThan(String value) { addCriterion("bank >", value, "bank"); return (Criteria) this; } public Criteria andBankGreaterThanOrEqualTo(String value) { addCriterion("bank >=", value, "bank"); return (Criteria) this; } public Criteria andBankLessThan(String value) { addCriterion("bank <", value, "bank"); return (Criteria) this; } public Criteria andBankLessThanOrEqualTo(String value) { addCriterion("bank <=", value, "bank"); return (Criteria) this; } public Criteria andBankLike(String value) { addCriterion("bank like", value, "bank"); return (Criteria) this; } public Criteria andBankNotLike(String value) { addCriterion("bank not like", value, "bank"); return (Criteria) this; } public Criteria andBankIn(List values) { addCriterion("bank in", values, "bank"); return (Criteria) this; } public Criteria andBankNotIn(List values) { addCriterion("bank not in", values, "bank"); return (Criteria) this; } public Criteria andBankBetween(String value1, String value2) { addCriterion("bank between", value1, value2, "bank"); return (Criteria) this; } public Criteria andBankNotBetween(String value1, String value2) { addCriterion("bank not between", value1, value2, "bank"); return (Criteria) this; } public Criteria andPostalcodeIsNull() { addCriterion("postalCode is null"); return (Criteria) this; } public Criteria andPostalcodeIsNotNull() { addCriterion("postalCode is not null"); return (Criteria) this; } public Criteria andPostalcodeEqualTo(Integer value) { addCriterion("postalCode =", value, "postalcode"); return (Criteria) this; } public Criteria andPostalcodeNotEqualTo(Integer value) { addCriterion("postalCode <>", value, "postalcode"); return (Criteria) this; } public Criteria andPostalcodeGreaterThan(Integer value) { addCriterion("postalCode >", value, "postalcode"); return (Criteria) this; } public Criteria andPostalcodeGreaterThanOrEqualTo(Integer value) { addCriterion("postalCode >=", value, "postalcode"); return (Criteria) this; } public Criteria andPostalcodeLessThan(Integer value) { addCriterion("postalCode <", value, "postalcode"); return (Criteria) this; } public Criteria andPostalcodeLessThanOrEqualTo(Integer value) { addCriterion("postalCode <=", value, "postalcode"); return (Criteria) this; } public Criteria andPostalcodeIn(List values) { addCriterion("postalCode in", values, "postalcode"); return (Criteria) this; } public Criteria andPostalcodeNotIn(List values) { addCriterion("postalCode not in", values, "postalcode"); return (Criteria) this; } public Criteria andPostalcodeBetween(Integer value1, Integer value2) { addCriterion("postalCode between", value1, value2, "postalcode"); return (Criteria) this; } public Criteria andPostalcodeNotBetween(Integer value1, Integer value2) { addCriterion("postalCode not between", value1, value2, "postalcode"); return (Criteria) this; } public Criteria andUnitpropertyIsNull() { addCriterion("unitproperty is null"); return (Criteria) this; } public Criteria andUnitpropertyIsNotNull() { addCriterion("unitproperty is not null"); return (Criteria) this; } public Criteria andUnitpropertyEqualTo(String value) { addCriterion("unitproperty =", value, "unitproperty"); return (Criteria) this; } public Criteria andUnitpropertyNotEqualTo(String value) { addCriterion("unitproperty <>", value, "unitproperty"); return (Criteria) this; } public Criteria andUnitpropertyGreaterThan(String value) { addCriterion("unitproperty >", value, "unitproperty"); return (Criteria) this; } public Criteria andUnitpropertyGreaterThanOrEqualTo(String value) { addCriterion("unitproperty >=", value, "unitproperty"); return (Criteria) this; } public Criteria andUnitpropertyLessThan(String value) { addCriterion("unitproperty <", value, "unitproperty"); return (Criteria) this; } public Criteria andUnitpropertyLessThanOrEqualTo(String value) { addCriterion("unitproperty <=", value, "unitproperty"); return (Criteria) this; } public Criteria andUnitpropertyLike(String value) { addCriterion("unitproperty like", value, "unitproperty"); return (Criteria) this; } public Criteria andUnitpropertyNotLike(String value) { addCriterion("unitproperty not like", value, "unitproperty"); return (Criteria) this; } public Criteria andUnitpropertyIn(List values) { addCriterion("unitproperty in", values, "unitproperty"); return (Criteria) this; } public Criteria andUnitpropertyNotIn(List values) { addCriterion("unitproperty not in", values, "unitproperty"); return (Criteria) this; } public Criteria andUnitpropertyBetween(String value1, String value2) { addCriterion("unitproperty between", value1, value2, "unitproperty"); return (Criteria) this; } public Criteria andUnitpropertyNotBetween(String value1, String value2) { addCriterion("unitproperty not between", value1, value2, "unitproperty"); return (Criteria) this; } public Criteria andUnitattributeIsNull() { addCriterion("unitattribute is null"); return (Criteria) this; } public Criteria andUnitattributeIsNotNull() { addCriterion("unitattribute is not null"); return (Criteria) this; } public Criteria andUnitattributeEqualTo(String value) { addCriterion("unitattribute =", value, "unitattribute"); return (Criteria) this; } public Criteria andUnitattributeNotEqualTo(String value) { addCriterion("unitattribute <>", value, "unitattribute"); return (Criteria) this; } public Criteria andUnitattributeGreaterThan(String value) { addCriterion("unitattribute >", value, "unitattribute"); return (Criteria) this; } public Criteria andUnitattributeGreaterThanOrEqualTo(String value) { addCriterion("unitattribute >=", value, "unitattribute"); return (Criteria) this; } public Criteria andUnitattributeLessThan(String value) { addCriterion("unitattribute <", value, "unitattribute"); return (Criteria) this; } public Criteria andUnitattributeLessThanOrEqualTo(String value) { addCriterion("unitattribute <=", value, "unitattribute"); return (Criteria) this; } public Criteria andUnitattributeLike(String value) { addCriterion("unitattribute like", value, "unitattribute"); return (Criteria) this; } public Criteria andUnitattributeNotLike(String value) { addCriterion("unitattribute not like", value, "unitattribute"); return (Criteria) this; } public Criteria andUnitattributeIn(List values) { addCriterion("unitattribute in", values, "unitattribute"); return (Criteria) this; } public Criteria andUnitattributeNotIn(List values) { addCriterion("unitattribute not in", values, "unitattribute"); return (Criteria) this; } public Criteria andUnitattributeBetween(String value1, String value2) { addCriterion("unitattribute between", value1, value2, "unitattribute"); return (Criteria) this; } public Criteria andUnitattributeNotBetween(String value1, String value2) { addCriterion("unitattribute not between", value1, value2, "unitattribute"); return (Criteria) this; } public Criteria andCompetentdepartmentIsNull() { addCriterion("competentDepartment is null"); return (Criteria) this; } public Criteria andCompetentdepartmentIsNotNull() { addCriterion("competentDepartment is not null"); return (Criteria) this; } public Criteria andCompetentdepartmentEqualTo(String value) { addCriterion("competentDepartment =", value, "competentdepartment"); return (Criteria) this; } public Criteria andCompetentdepartmentNotEqualTo(String value) { addCriterion("competentDepartment <>", value, "competentdepartment"); return (Criteria) this; } public Criteria andCompetentdepartmentGreaterThan(String value) { addCriterion("competentDepartment >", value, "competentdepartment"); return (Criteria) this; } public Criteria andCompetentdepartmentGreaterThanOrEqualTo(String value) { addCriterion("competentDepartment >=", value, "competentdepartment"); return (Criteria) this; } public Criteria andCompetentdepartmentLessThan(String value) { addCriterion("competentDepartment <", value, "competentdepartment"); return (Criteria) this; } public Criteria andCompetentdepartmentLessThanOrEqualTo(String value) { addCriterion("competentDepartment <=", value, "competentdepartment"); return (Criteria) this; } public Criteria andCompetentdepartmentLike(String value) { addCriterion("competentDepartment like", value, "competentdepartment"); return (Criteria) this; } public Criteria andCompetentdepartmentNotLike(String value) { addCriterion("competentDepartment not like", value, "competentdepartment"); return (Criteria) this; } public Criteria andCompetentdepartmentIn(List values) { addCriterion("competentDepartment in", values, "competentdepartment"); return (Criteria) this; } public Criteria andCompetentdepartmentNotIn(List values) { addCriterion("competentDepartment not in", values, "competentdepartment"); return (Criteria) this; } public Criteria andCompetentdepartmentBetween(String value1, String value2) { addCriterion("competentDepartment between", value1, value2, "competentdepartment"); return (Criteria) this; } public Criteria andCompetentdepartmentNotBetween(String value1, String value2) { addCriterion("competentDepartment not between", value1, value2, "competentdepartment"); return (Criteria) this; } public Criteria andAccountnumberIsNull() { addCriterion("accountNumber is null"); return (Criteria) this; } public Criteria andAccountnumberIsNotNull() { addCriterion("accountNumber is not null"); return (Criteria) this; } public Criteria andAccountnumberEqualTo(Integer value) { addCriterion("accountNumber =", value, "accountnumber"); return (Criteria) this; } public Criteria andAccountnumberNotEqualTo(Integer value) { addCriterion("accountNumber <>", value, "accountnumber"); return (Criteria) this; } public Criteria andAccountnumberGreaterThan(Integer value) { addCriterion("accountNumber >", value, "accountnumber"); return (Criteria) this; } public Criteria andAccountnumberGreaterThanOrEqualTo(Integer value) { addCriterion("accountNumber >=", value, "accountnumber"); return (Criteria) this; } public Criteria andAccountnumberLessThan(Integer value) { addCriterion("accountNumber <", value, "accountnumber"); return (Criteria) this; } public Criteria andAccountnumberLessThanOrEqualTo(Integer value) { addCriterion("accountNumber <=", value, "accountnumber"); return (Criteria) this; } public Criteria andAccountnumberIn(List values) { addCriterion("accountNumber in", values, "accountnumber"); return (Criteria) this; } public Criteria andAccountnumberNotIn(List values) { addCriterion("accountNumber not in", values, "accountnumber"); return (Criteria) this; } public Criteria andAccountnumberBetween(Integer value1, Integer value2) { addCriterion("accountNumber between", value1, value2, "accountnumber"); return (Criteria) this; } public Criteria andAccountnumberNotBetween(Integer value1, Integer value2) { addCriterion("accountNumber not between", value1, value2, "accountnumber"); return (Criteria) this; } public Criteria andUnitcharacteristicsIsNull() { addCriterion("unitCharacteristics is null"); return (Criteria) this; } public Criteria andUnitcharacteristicsIsNotNull() { addCriterion("unitCharacteristics is not null"); return (Criteria) this; } public Criteria andUnitcharacteristicsEqualTo(String value) { addCriterion("unitCharacteristics =", value, "unitcharacteristics"); return (Criteria) this; } public Criteria andUnitcharacteristicsNotEqualTo(String value) { addCriterion("unitCharacteristics <>", value, "unitcharacteristics"); return (Criteria) this; } public Criteria andUnitcharacteristicsGreaterThan(String value) { addCriterion("unitCharacteristics >", value, "unitcharacteristics"); return (Criteria) this; } public Criteria andUnitcharacteristicsGreaterThanOrEqualTo(String value) { addCriterion("unitCharacteristics >=", value, "unitcharacteristics"); return (Criteria) this; } public Criteria andUnitcharacteristicsLessThan(String value) { addCriterion("unitCharacteristics <", value, "unitcharacteristics"); return (Criteria) this; } public Criteria andUnitcharacteristicsLessThanOrEqualTo(String value) { addCriterion("unitCharacteristics <=", value, "unitcharacteristics"); return (Criteria) this; } public Criteria andUnitcharacteristicsLike(String value) { addCriterion("unitCharacteristics like", value, "unitcharacteristics"); return (Criteria) this; } public Criteria andUnitcharacteristicsNotLike(String value) { addCriterion("unitCharacteristics not like", value, "unitcharacteristics"); return (Criteria) this; } public Criteria andUnitcharacteristicsIn(List values) { addCriterion("unitCharacteristics in", values, "unitcharacteristics"); return (Criteria) this; } public Criteria andUnitcharacteristicsNotIn(List values) { addCriterion("unitCharacteristics not in", values, "unitcharacteristics"); return (Criteria) this; } public Criteria andUnitcharacteristicsBetween(String value1, String value2) { addCriterion("unitCharacteristics between", value1, value2, "unitcharacteristics"); return (Criteria) this; } public Criteria andUnitcharacteristicsNotBetween(String value1, String value2) { addCriterion("unitCharacteristics not between", value1, value2, "unitcharacteristics"); return (Criteria) this; } public Criteria andAffiliationIsNull() { addCriterion("affiliation is null"); return (Criteria) this; } public Criteria andAffiliationIsNotNull() { addCriterion("affiliation is not null"); return (Criteria) this; } public Criteria andAffiliationEqualTo(String value) { addCriterion("affiliation =", value, "affiliation"); return (Criteria) this; } public Criteria andAffiliationNotEqualTo(String value) { addCriterion("affiliation <>", value, "affiliation"); return (Criteria) this; } public Criteria andAffiliationGreaterThan(String value) { addCriterion("affiliation >", value, "affiliation"); return (Criteria) this; } public Criteria andAffiliationGreaterThanOrEqualTo(String value) { addCriterion("affiliation >=", value, "affiliation"); return (Criteria) this; } public Criteria andAffiliationLessThan(String value) { addCriterion("affiliation <", value, "affiliation"); return (Criteria) this; } public Criteria andAffiliationLessThanOrEqualTo(String value) { addCriterion("affiliation <=", value, "affiliation"); return (Criteria) this; } public Criteria andAffiliationLike(String value) { addCriterion("affiliation like", value, "affiliation"); return (Criteria) this; } public Criteria andAffiliationNotLike(String value) { addCriterion("affiliation not like", value, "affiliation"); return (Criteria) this; } public Criteria andAffiliationIn(List values) { addCriterion("affiliation in", values, "affiliation"); return (Criteria) this; } public Criteria andAffiliationNotIn(List values) { addCriterion("affiliation not in", values, "affiliation"); return (Criteria) this; } public Criteria andAffiliationBetween(String value1, String value2) { addCriterion("affiliation between", value1, value2, "affiliation"); return (Criteria) this; } public Criteria andAffiliationNotBetween(String value1, String value2) { addCriterion("affiliation not between", value1, value2, "affiliation"); return (Criteria) this; } public Criteria andCreatedateIsNull() { addCriterion("CreateDate is null"); return (Criteria) this; } public Criteria andCreatedateIsNotNull() { addCriterion("CreateDate is not null"); return (Criteria) this; } public Criteria andCreatedateEqualTo(Date value) { addCriterionForJDBCDate("CreateDate =", value, "createdate"); return (Criteria) this; } public Criteria andCreatedateNotEqualTo(Date value) { addCriterionForJDBCDate("CreateDate <>", value, "createdate"); return (Criteria) this; } public Criteria andCreatedateGreaterThan(Date value) { addCriterionForJDBCDate("CreateDate >", value, "createdate"); return (Criteria) this; } public Criteria andCreatedateGreaterThanOrEqualTo(Date value) { addCriterionForJDBCDate("CreateDate >=", value, "createdate"); return (Criteria) this; } public Criteria andCreatedateLessThan(Date value) { addCriterionForJDBCDate("CreateDate <", value, "createdate"); return (Criteria) this; } public Criteria andCreatedateLessThanOrEqualTo(Date value) { addCriterionForJDBCDate("CreateDate <=", value, "createdate"); return (Criteria) this; } public Criteria andCreatedateIn(List values) { addCriterionForJDBCDate("CreateDate in", values, "createdate"); return (Criteria) this; } public Criteria andCreatedateNotIn(List values) { addCriterionForJDBCDate("CreateDate not in", values, "createdate"); return (Criteria) this; } public Criteria andCreatedateBetween(Date value1, Date value2) { addCriterionForJDBCDate("CreateDate between", value1, value2, "createdate"); return (Criteria) this; } public Criteria andCreatedateNotBetween(Date value1, Date value2) { addCriterionForJDBCDate("CreateDate not between", value1, value2, "createdate"); return (Criteria) this; } public Criteria andOperatoridIsNull() { addCriterion("OperatorId is null"); return (Criteria) this; } public Criteria andOperatoridIsNotNull() { addCriterion("OperatorId is not null"); return (Criteria) this; } public Criteria andOperatoridEqualTo(String value) { addCriterion("OperatorId =", value, "operatorid"); return (Criteria) this; } public Criteria andOperatoridNotEqualTo(String value) { addCriterion("OperatorId <>", value, "operatorid"); return (Criteria) this; } public Criteria andOperatoridGreaterThan(String value) { addCriterion("OperatorId >", value, "operatorid"); return (Criteria) this; } public Criteria andOperatoridGreaterThanOrEqualTo(String value) { addCriterion("OperatorId >=", value, "operatorid"); return (Criteria) this; } public Criteria andOperatoridLessThan(String value) { addCriterion("OperatorId <", value, "operatorid"); return (Criteria) this; } public Criteria andOperatoridLessThanOrEqualTo(String value) { addCriterion("OperatorId <=", value, "operatorid"); return (Criteria) this; } public Criteria andOperatoridLike(String value) { addCriterion("OperatorId like", value, "operatorid"); return (Criteria) this; } public Criteria andOperatoridNotLike(String value) { addCriterion("OperatorId not like", value, "operatorid"); return (Criteria) this; } public Criteria andOperatoridIn(List values) { addCriterion("OperatorId in", values, "operatorid"); return (Criteria) this; } public Criteria andOperatoridNotIn(List values) { addCriterion("OperatorId not in", values, "operatorid"); return (Criteria) this; } public Criteria andOperatoridBetween(String value1, String value2) { addCriterion("OperatorId between", value1, value2, "operatorid"); return (Criteria) this; } public Criteria andOperatoridNotBetween(String value1, String value2) { addCriterion("OperatorId not between", value1, value2, "operatorid"); return (Criteria) this; } public Criteria andIsdeleteIsNull() { addCriterion("isDelete is null"); return (Criteria) this; } public Criteria andIsdeleteIsNotNull() { addCriterion("isDelete is not null"); return (Criteria) this; } public Criteria andIsdeleteEqualTo(Boolean value) { addCriterion("isDelete =", value, "isdelete"); return (Criteria) this; } public Criteria andIsdeleteNotEqualTo(Boolean value) { addCriterion("isDelete <>", value, "isdelete"); return (Criteria) this; } public Criteria andIsdeleteGreaterThan(Boolean value) { addCriterion("isDelete >", value, "isdelete"); return (Criteria) this; } public Criteria andIsdeleteGreaterThanOrEqualTo(Boolean value) { addCriterion("isDelete >=", value, "isdelete"); return (Criteria) this; } public Criteria andIsdeleteLessThan(Boolean value) { addCriterion("isDelete <", value, "isdelete"); return (Criteria) this; } public Criteria andIsdeleteLessThanOrEqualTo(Boolean value) { addCriterion("isDelete <=", value, "isdelete"); return (Criteria) this; } public Criteria andIsdeleteIn(List values) { addCriterion("isDelete in", values, "isdelete"); return (Criteria) this; } public Criteria andIsdeleteNotIn(List values) { addCriterion("isDelete not in", values, "isdelete"); return (Criteria) this; } public Criteria andIsdeleteBetween(Boolean value1, Boolean value2) { addCriterion("isDelete between", value1, value2, "isdelete"); return (Criteria) this; } public Criteria andIsdeleteNotBetween(Boolean value1, Boolean value2) { addCriterion("isDelete not between", value1, value2, "isdelete"); return (Criteria) this; } public Criteria andUpdatedateIsNull() { addCriterion("updateDate is null"); return (Criteria) this; } public Criteria andUpdatedateIsNotNull() { addCriterion("updateDate is not null"); return (Criteria) this; } public Criteria andUpdatedateEqualTo(Date value) { addCriterionForJDBCDate("updateDate =", value, "updatedate"); return (Criteria) this; } public Criteria andUpdatedateNotEqualTo(Date value) { addCriterionForJDBCDate("updateDate <>", value, "updatedate"); return (Criteria) this; } public Criteria andUpdatedateGreaterThan(Date value) { addCriterionForJDBCDate("updateDate >", value, "updatedate"); return (Criteria) this; } public Criteria andUpdatedateGreaterThanOrEqualTo(Date value) { addCriterionForJDBCDate("updateDate >=", value, "updatedate"); return (Criteria) this; } public Criteria andUpdatedateLessThan(Date value) { addCriterionForJDBCDate("updateDate <", value, "updatedate"); return (Criteria) this; } public Criteria andUpdatedateLessThanOrEqualTo(Date value) { addCriterionForJDBCDate("updateDate <=", value, "updatedate"); return (Criteria) this; } public Criteria andUpdatedateIn(List values) { addCriterionForJDBCDate("updateDate in", values, "updatedate"); return (Criteria) this; } public Criteria andUpdatedateNotIn(List values) { addCriterionForJDBCDate("updateDate not in", values, "updatedate"); return (Criteria) this; } public Criteria andUpdatedateBetween(Date value1, Date value2) { addCriterionForJDBCDate("updateDate between", value1, value2, "updatedate"); return (Criteria) this; } public Criteria andUpdatedateNotBetween(Date value1, Date value2) { addCriterionForJDBCDate("updateDate not between", value1, value2, "updatedate"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }package com.github.camilormz.finalreality.model.character; import com.github.camilormz.finalreality.model.character.player.characterclass.Knight; import com.github.camilormz.finalreality.model.weapon.types.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import static org.junit.jupiter.api.Assertions.*; /** * Abstract class that holds the tests available for any character of the game * * @author */ public abstract class AbstractCharacterTest { protected final String ENEMY_TEST_NAME = "Kronos"; protected final String PLAYABLE_TEST_NAME = "Steel"; protected final String AXE_NAME = "Wood Slayer"; protected final String BOW_NAME = "The Trebuchet"; protected final String KNIFE_NAME = "Stealthy"; protected final String STAFF_NAME = "Shadowmaker"; protected final String SWORD_NAME = "Infidel Redentor"; protected BlockingQueue turns; protected Axe testAxe; protected Bow testBow; protected Knife testKnife; protected Staff testStaff; protected Sword testSword; protected Enemy testEnemy; protected Knight testPlayable; protected Axe anotherTestAxe; protected Bow anotherTestBow; protected Knife anotherTestKnife; protected Staff anotherTestStaff; protected Sword anotherTestSword; protected final float waitTurnTestErrorMargin = 10; private final long epsilonWaitTurnTest = 50; // milliseconds to wait at 0 expected time /** * Executes a setup for every test involving characters */ @BeforeEach void setUp() { turns = new LinkedBlockingQueue<>(); testEnemy = new Enemy(ENEMY_TEST_NAME, 100, 10, 10, 2, turns); testPlayable = new Knight(PLAYABLE_TEST_NAME, 100, 2, turns); testAxe = new Axe(AXE_NAME, 10, 10); testBow = new Bow(BOW_NAME, 10, 10); testKnife = new Knife(KNIFE_NAME, 10, 10); testStaff = new Staff(STAFF_NAME, 10, 10, 10); testSword = new Sword(SWORD_NAME, 10, 10); anotherTestAxe = new Axe(AXE_NAME, 10, 10); anotherTestBow = new Bow(BOW_NAME, 10, 10); anotherTestKnife = new Knife(KNIFE_NAME, 10, 10); anotherTestStaff = new Staff(STAFF_NAME, 10, 10, 10); anotherTestSword = new Sword(SWORD_NAME, 10, 10); } /** * Test for enqueuing time according to character turn-weight */ protected void waitTurnTest(AbstractCharacter character, long expectedTime, float percentageErrorMargin) { assertTrue(turns.isEmpty()); long intervalStartWaitTime = (long)(1000*expectedTime*(100-percentageErrorMargin)/100.0); long intervalToEndWaitTime = (long)(1000*expectedTime*(2*percentageErrorMargin)/100.0); character.waitTurn(); if (expectedTime == 0) { try { Thread.sleep(epsilonWaitTurnTest); assertEquals(1, turns.size()); assertEquals(turns.take(), character); assertEquals(0, turns.size()); } catch (InterruptedException e) { e.printStackTrace(); } } else { try { Thread.sleep(intervalStartWaitTime); assertEquals(0, turns.size()); Thread.sleep(intervalToEndWaitTime); assertEquals(1, turns.size()); assertEquals(turns.take(), character); assertEquals(0, turns.size()); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Test for combat dynamics * @param characterDamage corresponds to character damage and must be less than * strongAdversaryHP and greater to strongAdversaryDefense * @param strongAdversaryDamage corresponds to strongAdversary damage * @param weakAdversaryDamage corresponds to weakAdversary damage and must be less than * characterDefense */ protected void combatTest(AbstractCharacter character, AbstractCharacter sameDomainCharacter, AbstractCharacter strongAdversary, AbstractCharacter weakAdversary, int characterHP, int characterDamage, int characterDefense, int strongAdversaryDamage, int weakAdversaryDamage, int strongAdversaryHP, int strongAdversaryDefense) { // Assert the parameters conditions assert weakAdversaryDamage < characterDefense; assert strongAdversaryDefense < characterDamage && characterDamage < strongAdversaryHP; // Checks that the character's and adversary's HP starts as desired assertEquals(character.getHealthPoints(), characterHP); assertEquals(strongAdversary.getHealthPoints(), strongAdversaryHP); // Tests that an same domain character attack trial has no effect (no friendly fire) sameDomainCharacter.attack(character); assertEquals(character.getHealthPoints(), characterHP); // Tests that the weak adversary has not effect on character HP weakAdversary.attack(character); assertEquals(character.getHealthPoints(), characterHP); // Tests that the character can actually attack its adversary character.attack(strongAdversary); strongAdversaryHP -= characterDamage - strongAdversaryDefense; assertEquals(strongAdversary.getHealthPoints(), strongAdversaryHP); // Tests loop in where the character receive attacks from the strong adversary until it dies while (characterHP > 0) { assertEquals(character.getHealthPoints(), characterHP); assertTrue(character.isAvailableForCombat()); strongAdversary.attack(character); characterHP -= strongAdversaryDamage - characterDefense; } // Tests if the character is actually knock out assertEquals(character.getHealthPoints(), 0); assertFalse(character.isAvailableForCombat()); // Tests that a knocked out character has no effect character.attack(strongAdversary); assertEquals(strongAdversary.getHealthPoints(), strongAdversaryHP); } /** * Test for character domain */ protected void getCharacterDomainTest(AbstractCharacter character, CharacterDomain expectedDomain) { assertEquals(expectedDomain, character.getCharacterDomain()); } /** * Abstract method to execute tests for character domain */ @Test protected abstract void subClassCharacterDomainTest(); /** * Abstract method for the subclasses to execute wait turn test */ @Test protected abstract void subClassWaitTurnTest(); /** * Abstract method for the subclasses to execute the combat test */ @Test protected abstract void subClassCombatTest(); } /* * The MIT License * * Copyright 2021 000ssg. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; /** * Test streams usage (simple) and check performance overhead for trivial * case(s) * * @author 000ssg */ public class Test_Streams { static AtomicInteger nextGroupId = new AtomicInteger(1); static AtomicInteger nextLocId = new AtomicInteger(1); static AtomicInteger nextItemId = new AtomicInteger(1); public static void main(String... args) throws Exception { // prepare data set List locs = new ArrayList<>(); List groups = new ArrayList<>(); List items = new ArrayList<>(); for (int i = 0; i < 3; i++) { locs.add(new Loc()); } for (int i = 0; i < 5; i++) { groups.add(new Group()); } for (Loc l : locs) { for (Group g : groups) { items.add(new Item(l, g)); } } // test stream operations Map i2g = items.stream().collect(Collectors.toMap(Item::getId, Item::getGroupId)); System.out.println(i2g); Map it2g = items.stream().collect(Collectors.toMap(Test_Streams::toItemInGroup, Test_Streams::toItem)); System.out.println(it2g); // test stream operation performance // stream map long s01 = System.nanoTime(); Map it2g2 = items.stream().collect(Collectors.toMap(item -> { return new ItemInGroup(item); }, item -> { return item; })); long s02 = System.nanoTime(); // direct map Map it2g2_ = new HashMap<>(); for (Item i : items) { it2g2_.put(new ItemInGroup(i), i); } long s03 = System.nanoTime(); // stream map Map it2g2__ = items.stream().collect(Collectors.toMap(item -> { return new ItemInGroup(item); }, item -> { return item; })); long s04 = System.nanoTime(); // visualize and verify results identity System.out.println(it2g2); System.out.println(it2g2_); for (ItemInGroup ig : it2g.keySet()) { if (!it2g2.containsKey(ig)) { System.out.println("missing " + ig); } } // finally look on performance test results System.out.println("Streamed map: " + (s02 - s01) / 1000000f + ", direct map: " + (s03 - s02) / 1000000f + ", and streamed again: " + (s04 - s03) / 1000000f); } public static ItemInGroup toItemInGroup(Item item) { return new ItemInGroup(item); } public static Item toItem(Item item) { return item; } public static class Group { public int id = nextGroupId.getAndIncrement(); } public static class Loc { public int id = nextLocId.getAndIncrement(); } public static class Item { private int id = nextItemId.getAndIncrement(); private int locId; private int groupId; public Item(Loc loc, Group group) { if (loc != null) { locId = loc.id; } if (group != null) { groupId = group.id; } } /** * @return the id */ public int getId() { return id; } /** * @return the locId */ public int getLocId() { return locId; } /** * @return the groupId */ public int getGroupId() { return groupId; } } public static class ItemInLoc { public int loc; public int item; @Override public String toString() { return "ItemInLoc{" + "loc=" + loc + ", item=" + item + '}'; } } public static class ItemInGroup { public int group; public int item; public ItemInGroup(Item item) { this.group = item.getGroupId(); this.item = item.getId(); } @Override public String toString() { return "ItemInGroup{" + "group=" + group + ", item=" + item + '}'; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.group; hash = 47 * hash + this.item; return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ItemInGroup other = (ItemInGroup) obj; if (this.group != other.group) { return false; } if (this.item != other.item) { return false; } return true; } } } /** * Copyright (c) 2012 - 2017 by NirvanaXP, LLC. All Rights reserved. Express * written consent required to use, copy, share, alter, distribute or transmit * this source code in part or whole through any means physical or electronic. **/ package com.nirvanaxp.services.jaxrs; import java.io.IOException; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import javax.persistence.NoResultException; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.servlet.http.HttpServletRequest; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.annotate.JsonSerialize; import com.google.zxing.WriterException; import com.nirvanaxp.common.methods.CommonMethods; import com.nirvanaxp.common.utils.ConfigFileReader; import com.nirvanaxp.common.utils.synchistory.MessageConstants; import com.nirvanaxp.common.utils.synchistory.TimezoneTime; import com.nirvanaxp.global.types.entities.DriverOrder; import com.nirvanaxp.global.types.entities.DriverOrder_; import com.nirvanaxp.server.common.MessageSender; import com.nirvanaxp.server.util.GlobalSchemaEntityManager; import com.nirvanaxp.server.util.JSONUtility; import com.nirvanaxp.server.util.LocalSchemaEntityManager; import com.nirvanaxp.server.util.NirvanaLogger; import com.nirvanaxp.server.util.PrinterUtility; import com.nirvanaxp.server.util.ServiceOperationsUtility; import com.nirvanaxp.services.NirvanaServiceErrorResponse; import com.nirvanaxp.services.data.OrderHeaderWithInventoryPostPacket; import com.nirvanaxp.services.data.OrderHeaderWithUser; import com.nirvanaxp.services.email.ReceiptPDFFormat; import com.nirvanaxp.services.exceptions.InvalidSessionException; import com.nirvanaxp.services.exceptions.NirvanaXPException; import com.nirvanaxp.services.jaxrs.packets.InventoryPostPacket; import com.nirvanaxp.services.jaxrs.packets.KDSToOrderDetailItemStatusPacket; import com.nirvanaxp.services.jaxrs.packets.OrderHeaderSource; import com.nirvanaxp.services.jaxrs.packets.OrderHeaderSourcePacket; import com.nirvanaxp.services.jaxrs.packets.OrderPacket; import com.nirvanaxp.services.jaxrs.packets.OrderPacketForOrderTransfer; import com.nirvanaxp.services.jaxrs.packets.OrderTransferPacket; import com.nirvanaxp.services.jaxrs.packets.PostPacket; import com.nirvanaxp.services.jaxrs.packets.PrintQueuePacket; import com.nirvanaxp.services.jaxrs.packets.TipSavedPacket; import com.nirvanaxp.services.util.email.EmailTemplateKeys; import com.nirvanaxp.storeForward.StoreForwardUtility; import com.nirvanaxp.types.entities.address.Address; import com.nirvanaxp.types.entities.catalog.items.Item; import com.nirvanaxp.types.entities.catalog.items.NotPrintedOrderDetailItemsToPrinter; import com.nirvanaxp.types.entities.catalog.items.NotPrintedOrderDetailItemsToPrinter_; import com.nirvanaxp.types.entities.catalog.items.StorageType; import com.nirvanaxp.types.entities.discounts.Discount; import com.nirvanaxp.types.entities.discounts.DiscountsType; import com.nirvanaxp.types.entities.email.PrintQueue; import com.nirvanaxp.types.entities.email.PrintQueue_; import com.nirvanaxp.types.entities.inventory.GoodsReceiveNotes; import com.nirvanaxp.types.entities.inventory.RequestOrder; import com.nirvanaxp.types.entities.inventory.RequestOrderDetailItems; import com.nirvanaxp.types.entities.inventory.UnitOfMeasurement; import com.nirvanaxp.types.entities.locations.Location; import com.nirvanaxp.types.entities.orders.KDSToOrderDetailItemStatus; import com.nirvanaxp.types.entities.orders.KDSToOrderDetailItemStatus_; import com.nirvanaxp.types.entities.orders.OrderDetailAttribute; import com.nirvanaxp.types.entities.orders.OrderDetailAttribute_; import com.nirvanaxp.types.entities.orders.OrderDetailItem; import com.nirvanaxp.types.entities.orders.OrderDetailStatus; import com.nirvanaxp.types.entities.orders.OrderDetailStatus_; import com.nirvanaxp.types.entities.orders.OrderHeader; import com.nirvanaxp.types.entities.orders.OrderSource; import com.nirvanaxp.types.entities.orders.OrderSourceGroup; import com.nirvanaxp.types.entities.orders.OrderStatus; import com.nirvanaxp.types.entities.orders.OrderStatus_; import com.nirvanaxp.types.entities.user.User; import com.nirvanaxp.types.entities.user.UsersToDiscount; import com.nirvanaxp.types.entities.user.UsersToDiscount_; import com.nirvanaxp.user.utility.GlobalUsermanagement; import com.nirvanaxp.websocket.protocol.POSNServiceOperations; import com.nirvanaxp.websocket.protocol.POSNServices; // TODO: Auto-generated Javadoc /** * The Class OrderServiceForPost. */ public class OrderServiceForPost { /** The Constant logger. */ private static final NirvanaLogger logger = new NirvanaLogger(OrderServiceForPost.class.getName()); /** * Instantiates a new order service for post. */ public OrderServiceForPost() { } /** * Addorder. * * @param httpRequest * the http request * @param sessionId * the session id * @param em * the em * @param orderPacket * the order packet * @param isTakeOutOrder * the is take out order * @return the order header with user * @throws NirvanaXPException * the nirvana XP exception * @throws IOException * Signals that an I/O exception has occurred. * @throws WriterException * the writer exception * @throws InvalidSessionException * the invalid session exception * @throws Exception * the exception */ private OrderHeaderWithUser addorder(HttpServletRequest httpRequest, String sessionId, EntityManager em, OrderPacket orderPacket, boolean isTakeOutOrder) throws NirvanaXPException, IOException, WriterException, InvalidSessionException, Exception { String locationIdAsString = orderPacket.getLocationId(); String locationId = null; int merchantId = 0; if (locationIdAsString != null && locationIdAsString.length() > 0) { locationId = locationIdAsString.trim(); } if (orderPacket.getMerchantId() != null && orderPacket.getMerchantId().trim().length() > 0) { merchantId = Integer.parseInt(orderPacket.getMerchantId().trim()); } OrderManagementServiceBean bean = new OrderManagementServiceBean(); return bean.add(httpRequest, sessionId, em, orderPacket.getOrderHeader(), isTakeOutOrder, orderPacket.getGlobalUserId(), locationId, merchantId, orderPacket.getIdOfSessionUsedByPacket(), orderPacket.getSchemaName(), orderPacket); } /** * Adds the nirvana X porder. * * @param httpRequest * the http request * @param sessionId * the session id * @param em * the em * @param orderPacket * the order packet * @param isTakeOutOrder * the is take out order * @return the order header with inventory post packet * @throws Exception * the exception */ private OrderHeaderWithInventoryPostPacket addNirvanaXPorder(HttpServletRequest httpRequest, String sessionId, EntityManager em, OrderPacket orderPacket, boolean isTakeOutOrder) throws Exception { String locationIdAsString = orderPacket.getLocationId(); String locationId = null; int merchantId = 0; if (locationIdAsString != null && locationIdAsString.length() > 0) { locationId = locationIdAsString.trim(); } if (orderPacket.getMerchantId() != null && orderPacket.getMerchantId().trim().length() > 0) { merchantId = Integer.parseInt(orderPacket.getMerchantId().trim()); } OrderManagementServiceBean bean = new OrderManagementServiceBean(); return bean.addNirvanaXP(httpRequest, sessionId, em, orderPacket.getOrderHeader(), isTakeOutOrder, orderPacket.getGlobalUserId(), locationId, merchantId, orderPacket.getIdOfSessionUsedByPacket(), orderPacket.getSchemaName()); } /** * Insert order. * * @param httpRequest * the http request * @param sessionId * the session id * @param em * the em * @param orderPacket * the order packet * @param isTakeOutOrder * the is take out order * @return the order header * @throws NirvanaXPException * the nirvana XP exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. * @throws WriterException * the writer exception * @throws InvalidSessionException * the invalid session exception * @throws Exception * the exception */ public OrderHeader insertOrder(HttpServletRequest httpRequest, String sessionId, EntityManager em, OrderPacket orderPacket, boolean isTakeOutOrder) throws NirvanaXPException, JsonGenerationException, JsonMappingException, IOException, WriterException, InvalidSessionException, Exception { OrderHeaderWithUser ohWithUser = addorder(httpRequest, sessionId, em, orderPacket, isTakeOutOrder); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(ohWithUser.getOrderHeader()); orderPacket.setOrderHeader(orderHeaderForPush); User localUser = ohWithUser.getUser(); if (localUser != null) { User userForPost = new User(); userForPost.setId(localUser.getId()); userForPost.setFirstName(localUser.getFirstName()); userForPost.setLastName(localUser.getLastName()); userForPost.setEmail(localUser.getEmail()); userForPost.setPhone(localUser.getPhone()); userForPost.setAuthPin(localUser.getAuthPin()); userForPost.setCountryId(localUser.getCountryId()); // global user id needed by client during update push userForPost.setGlobalUsersId(localUser.getGlobalUsersId()); orderPacket.setUser(userForPost); } try { addUpdateRequestOrder(ohWithUser.getOrderHeader(), httpRequest, em, null); } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } try { new PrinterUtility().insertIntoPrintQueueForPartySizeUpdate(httpRequest, em, ohWithUser.getOrderHeader(), orderPacket.getLocationId(), false); } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } if (ohWithUser.isTabOrderPush()) { sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_seatTabOrderHeader.name(), true); } else { sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_add.name(), true); } return ohWithUser.getOrderHeader(); } /** * Adds the order to card. * * @param httpRequest * the http request * @param referenceNumber * the reference number * @param em * the em * @param orderPacket * the order packet * @param isTakeOutOrder * the is take out order * @return the order header * @throws NirvanaXPException * the nirvana XP exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. * @throws ParseException * the parse exception * @throws WriterException * the writer exception * @throws InvalidSessionException * the invalid session exception */ public OrderHeader addOrderToCard(HttpServletRequest httpRequest, String referenceNumber, EntityManager em, OrderPacket orderPacket, boolean isTakeOutOrder) throws NirvanaXPException, JsonGenerationException, JsonMappingException, IOException, ParseException, WriterException, InvalidSessionException { OrderHeader prevOrderHeader = orderPacket.getOrderHeader(); OrderHeader orderHeader = addToCart(httpRequest, referenceNumber, em, orderPacket, isTakeOutOrder); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(orderHeader); orderPacket.setOrderHeader(orderHeaderForPush); if (orderHeader != null && orderHeader.getUsersId() != null ) { User user = (User) new CommonMethods().getObjectById("User", em,User.class, orderHeader.getUsersId()); User newUser = new User(); newUser.setUsername(user.getUsername()); newUser.setEmail(user.getEmail()); newUser.setPhone(user.getPhone()); newUser.setFirstName(user.getFirstName()); newUser.setLastName(user.getLastName()); newUser.setId(user.getId()); newUser.setGlobalUsersId(user.getGlobalUsersId()); orderPacket.setUser(newUser); } /* * try { OrderHeader header = new * OrderManagementServiceBean().getOrderById(em, * orderPacket.getOrderHeader().getId()); new * PrinterUtility().insertIntoPrintQueueForCustomer(httpRequest, em, * header, orderPacket.getLocationId()); } catch (Exception e) { // TODO * Auto-generated catch block e.printStackTrace(); } */ if (prevOrderHeader.getId()!= null && prevOrderHeader.getId()== null) { sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_add.name(), true); } else { sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_update.name(), true); } return orderHeader; } /** * Adds the to cart. * * @param httpRequest * the http request * @param referenceNumber * the reference number * @param em * the em * @param orderPacket * the order packet * @param isTakeOutOrder * the is take out order * @return the order header * @throws NirvanaXPException * the nirvana XP exception * @throws IOException * Signals that an I/O exception has occurred. * @throws ParseException * the parse exception * @throws WriterException * the writer exception * @throws InvalidSessionException * the invalid session exception */ private OrderHeader addToCart(HttpServletRequest httpRequest, String referenceNumber, EntityManager em, OrderPacket orderPacket, boolean isTakeOutOrder) throws NirvanaXPException, IOException, ParseException, WriterException, InvalidSessionException { String locationIdAsString = orderPacket.getLocationId(); if (locationIdAsString != null && locationIdAsString.length() > 0) { locationIdAsString.trim(); } if (orderPacket.getMerchantId() != null && orderPacket.getMerchantId().trim().length() > 0) { Integer.parseInt(orderPacket.getMerchantId().trim()); } OrderHeader orderHeader = new OrderManagementServiceBean().addOrderToCard(httpRequest, em, orderPacket, referenceNumber); return orderHeader; } /** * Insert nirvana XP order. * * @param httpRequest * the http request * @param sessionId * the session id * @param em * the em * @param orderPacket * the order packet * @param isTakeOutOrder * the is take out order * @return the order header * @throws Exception * the exception */ public OrderHeader insertNirvanaXPOrder(HttpServletRequest httpRequest, String sessionId, EntityManager em, OrderPacket orderPacket, boolean isTakeOutOrder) throws Exception { OrderHeaderWithInventoryPostPacket ohWithUser = addNirvanaXPorder(httpRequest, sessionId, em, orderPacket, isTakeOutOrder); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(ohWithUser.getOrderHeader()); orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_add.name(), true); return ohWithUser.getOrderHeader(); } /** * Update order. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws Exception * the exception */ public OrderHeader updateOrder(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket,String sessionId) throws Exception { orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); boolean isDuplicatePacketCheck = false; OrderHeaderWithInventoryPostPacket ohWithInventoryPostPacket = new OrderManagementServiceBean().update(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId().trim(), isDuplicatePacketCheck, orderPacket.getIdOfOrderHoldingClientObj(),Integer.parseInt(orderPacket.getMerchantId()),sessionId); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(ohWithInventoryPostPacket.getOrderHeader()); InventoryPostPacket inventoryPostPacket = ohWithInventoryPostPacket.getInventoryPostPacket(); if (inventoryPostPacket != null && inventoryPostPacket.getInventoryList() != null && inventoryPostPacket.getInventoryList().size() > 0) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); String inventoryPostPacketAsStr = objectMapper.writeValueAsString(inventoryPostPacket); orderHeaderForPush.setInventoryPostPacket(inventoryPostPacketAsStr); ohWithInventoryPostPacket.getOrderHeader().setInventoryPostPacket(inventoryPostPacketAsStr); } orderPacket.setOrderHeader(orderHeaderForPush); if (orderPacket.getPacketVersion() == 1) { sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_update.name(), true); } else { // for 0 send sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_update.name(), false); } return ohWithInventoryPostPacket.getOrderHeader(); } /** * Switch order location. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws NumberFormatException * the number format exception * @throws NirvanaXPException * the nirvana XP exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. */ public OrderHeader switchOrderLocation(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws NumberFormatException, NirvanaXPException, JsonGenerationException, JsonMappingException, IOException { orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeader = new OrderManagementServiceBean().switchOrderLocation(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId().trim()); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(orderHeader); orderPacket.setOrderHeader(orderHeaderForPush); try { new PrinterUtility().insertIntoPrintQueueForPartySizeUpdate(httpRequest, em, orderHeader, orderPacket.getLocationId(), false); } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderLocation.name(), false); return orderHeader; } /** * Change point of service count. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws NirvanaXPException * the nirvana XP exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. */ public OrderHeader changePointOfServiceCount(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws NirvanaXPException, JsonGenerationException, JsonMappingException, IOException { orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeader = new OrderManagementServiceBean().changePointOfServiceCount(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId().trim()); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(orderHeader); orderPacket.setOrderHeader(orderHeaderForPush); try { new PrinterUtility().insertIntoPrintQueueForPartySizeUpdate(httpRequest, em, orderHeader, orderPacket.getLocationId(), true); } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderPointOfServiceCount.name(), false); return orderHeader; } /** * Update order status. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws Exception */ public OrderHeader updateOrderStatus(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws Exception { boolean isDuplicatePacketCheck = false; orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeader = new OrderManagementServiceBean().updateOrderStatus(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId().trim(), orderPacket.getPacketVersion(), isDuplicatePacketCheck,Integer.parseInt(orderPacket.getMerchantId())); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(orderHeader); orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderStatus.name(), false); return orderHeader; } /** * Update order schedule date. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws NirvanaXPException * the nirvana XP exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. */ public OrderHeader updateOrderScheduleDate(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws NirvanaXPException, JsonGenerationException, JsonMappingException, IOException { orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeader = new OrderManagementServiceBean().updateOrderScheduleDate(em, orderPacket.getOrderHeader(), orderPacket.getLocationId().trim(), orderPacket.getPacketVersion()); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(orderHeader); orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderScheduleDate.name(), false); return orderHeader; } /** * Merge order. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws NirvanaXPException * the nirvana XP exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. */ public OrderHeader mergeOrder(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws NirvanaXPException, JsonGenerationException, JsonMappingException, IOException { orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeader = new OrderManagementServiceBean().mergeOrder(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getUnmergedLocationsId()); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(orderHeader); orderHeaderForPush.setMergedLocationsId(orderHeader.getMergedLocationsId()); orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_mergeOrder.name(), false); return orderHeader; } /** * Update order payment. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @param isDuplicatePacketCheck * the is duplicate packet check * @param sessionId * the session id * @param isReferenceNumber * the is reference number * @return the order header * @throws Exception * the exception */ public OrderHeader updateOrderPayment(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket, boolean isDuplicatePacketCheck, String sessionId, boolean isReferenceNumber) throws Exception { orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeaderWithInventoryPostPacket ohWithIPP = new OrderManagementServiceBean().updateOrderPayment(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId(), isDuplicatePacketCheck, sessionId, isReferenceNumber, orderPacket); em.getTransaction().commit(); em.getTransaction().begin(); if (ohWithIPP.getOrderHeader() != null && ohWithIPP.getOrderHeader().getOrderDetailItems() != null && ohWithIPP.getOrderHeader().getOrderDetailItems().size() > 0) { try { // OrderSource orderSource = (OrderSource) new CommonMethods().getObjectById("OrderSource", em,OrderSource.class, // ohWithIPP.getOrderHeader().getOrderSourceId()); // OrderSourceGroup orderSourceGroup = // (OrderSourceGroup) new CommonMethods().getObjectById("OrderSourceGroup", em,OrderSourceGroup.class, // orderSource.getOrderSourceGroupId()); new OrderManagementServiceBean().insertIntoKDSToOrderDetailItemStatus(httpRequest, em, ohWithIPP.getOrderHeader()); /* * if (orderSourceGroup.getName().equals("In Store") && * ohWithIPP.getOrderHeader().getReservationsId() == 0 && * ohWithIPP.getOrderHeader().getIsTabOrder() == 0 && * ohWithIPP.getOrderHeader().getLocationsId() == * orderPacket.getLocationId()) { new * OrderManagementServiceBean(). * insertIntoKDSToOrderDetailItemStatus(httpRequest, em, * ohWithIPP.getOrderHeader()); } */ OrderStatus orderStatus = (OrderStatus) new CommonMethods().getObjectById("OrderStatus", em,OrderStatus.class, ohWithIPP.getOrderHeader().getOrderStatusId()); if (orderStatus.getName().equals("Cancel Order")) { try { new PrinterUtility().insertIntoPrintQueueForCancelOrderAndQuickPay(httpRequest, em, ohWithIPP.getOrderHeader(), orderPacket.getLocationId() + ""); } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } } else { new PrinterUtility().insertIntoPrintQueue(httpRequest, em, ohWithIPP.getOrderHeader(), orderPacket.getLocationId()); } } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } } OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(ohWithIPP.getOrderHeader()); InventoryPostPacket inventoryPostPacket = ohWithIPP.getInventoryPostPacket(); if (inventoryPostPacket != null && inventoryPostPacket.getInventoryList() != null && inventoryPostPacket.getInventoryList().size() > 0) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); String inventoryPostPacketAsStr = objectMapper.writeValueAsString(inventoryPostPacket); orderHeaderForPush.setInventoryPostPacket(inventoryPostPacketAsStr); ohWithIPP.getOrderHeader().setInventoryPostPacket(inventoryPostPacketAsStr); } orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderPayment.name(), false); return ohWithIPP.getOrderHeader(); } /** * Update order payment for braintree. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws NirvanaXPException * the nirvana XP exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. */ public OrderHeader updateOrderPaymentForBraintree(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws NirvanaXPException, JsonGenerationException, JsonMappingException, IOException { orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); // by pass need to remove after uzma fixes this orderPacket.setLocationId(orderPacket.getOrderHeader().getLocationsId() + ""); OrderHeader orderHeader = new OrderManagementServiceBean().updateOrderPaymentForBraintree(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId()); return orderHeader; } /** * Update order payment for batch settle. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws NirvanaXPException * the nirvana XP exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. */ public OrderHeader updateOrderPaymentForBatchSettle(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws NirvanaXPException, JsonGenerationException, JsonMappingException, IOException { orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeader = new OrderManagementServiceBean().updateOrderPaymentForBatchSettle(httpRequest, em, orderPacket.getOrderHeader()); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(orderHeader); orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderPayment.name(), false); return orderHeader; } /** * Adds the order for QSR with item details. * * @param httpRequest * the http request * @param sessionId * the session id * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws NirvanaXPException * the nirvana XP exception * @throws NumberFormatException * the number format exception * @throws ParseException * the parse exception * @throws IOException * Signals that an I/O exception has occurred. * @throws WriterException * the writer exception * @throws InvalidSessionException * the invalid session exception * @throws Exception * the exception */ public OrderHeader addOrderForQSRWithItemDetails(HttpServletRequest httpRequest, String sessionId, EntityManager em, OrderPacket orderPacket) throws NirvanaXPException, NumberFormatException, ParseException, IOException, WriterException, InvalidSessionException, Exception { // for QSR order will get created with item details orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeader = null; OrderHeaderWithUser ohWithUser = addorder(httpRequest, sessionId, em, orderPacket, true); if (ohWithUser != null) { User localUser = ohWithUser.getUser(); if (localUser != null) { User userForPost = new User(); userForPost.setId(localUser.getId()); userForPost.setFirstName(localUser.getFirstName()); userForPost.setLastName(localUser.getLastName()); userForPost.setEmail(localUser.getEmail()); userForPost.setPhone(localUser.getPhone()); // global user id needed by client during update push userForPost.setGlobalUsersId(localUser.getGlobalUsersId()); orderPacket.setUser(userForPost); } // now update this order // TODO Ankur - why? boolean isDuplicatePacketCheck = false; OrderHeaderWithInventoryPostPacket ohWithIPP = new OrderManagementServiceBean().update(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId().trim(), isDuplicatePacketCheck, orderPacket.getIdOfOrderHoldingClientObj(),Integer.parseInt(orderPacket.getMerchantId()),sessionId); InventoryPostPacket inventoryPostPacket = ohWithIPP.getInventoryPostPacket(); if (inventoryPostPacket != null && inventoryPostPacket.getItemList() != null && inventoryPostPacket.getItemList().size() != 0) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); String inventoryPostPacketAsStr = null; try { inventoryPostPacketAsStr = objectMapper.writeValueAsString(inventoryPostPacket); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(ohWithIPP.getOrderHeader()); orderPacket.setOrderHeader(orderHeaderForPush); orderHeaderForPush.setInventoryPostPacket(inventoryPostPacketAsStr); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_add.name(), true); } catch (IOException e) { // could not send push // todo shlok need // handle proper Exception logger.severe(httpRequest, e); } if (inventoryPostPacketAsStr != null) { ohWithIPP.getOrderHeader().setInventoryPostPacket(inventoryPostPacketAsStr); } } orderHeader = ohWithIPP.getOrderHeader(); } return orderHeader; } /** * Gets the order header with minimun required details. * * @param orderHeader * the order header * @return the order header with minimun required details */ public OrderHeader getOrderHeaderWithMinimunRequiredDetails(OrderHeader orderHeader) { OrderHeader orderHeaderForPush = new OrderHeader(); orderHeaderForPush.setId(orderHeader.getId()); orderHeaderForPush.setLocationsId(orderHeader.getLocationsId()); orderHeaderForPush.setReservationsId(orderHeader.getReservationsId()); orderHeaderForPush.setOrderStatusId(orderHeader.getOrderStatusId()); orderHeaderForPush.setPointOfServiceCount(orderHeader.getPointOfServiceCount()); orderHeaderForPush.setCreated(orderHeader.getCreated()); orderHeaderForPush.setUpdated(orderHeader.getUpdated()); orderHeaderForPush.setBalanceDue(orderHeader.getBalanceDue()); orderHeaderForPush.setOrderSourceId(orderHeader.getOrderSourceId()); orderHeaderForPush.setAmountPaid(orderHeader.getAmountPaid()); orderHeaderForPush.setFirstName(orderHeader.getFirstName()); orderHeaderForPush.setLastName(orderHeader.getLastName()); orderHeaderForPush.setVoidReasonId(orderHeader.getVoidReasonId()); orderHeaderForPush.setIsOrderReopened(orderHeader.getIsOrderReopened()); orderHeaderForPush.setPriceDiscount(orderHeader.getPriceDiscount()); orderHeaderForPush.setSubTotal(orderHeader.getSubTotal()); orderHeaderForPush.setTaxExemptId(orderHeader.getTaxExemptId()); orderHeaderForPush.setScheduleDateTime(orderHeader.getScheduleDateTime()); orderHeaderForPush.setOrderNumber(orderHeader.getOrderNumber()); orderHeaderForPush.setMergedLocationsId(orderHeader.getMergedLocationsId()); String correctDateFormat = null; correctDateFormat = ConfigFileReader.correctDateFormat(orderHeader.getDate()); if (correctDateFormat != null && correctDateFormat.trim().length() > 0) { orderHeaderForPush.setDate(correctDateFormat); } else { orderHeaderForPush.setDate(orderHeader.getDate()); } orderHeaderForPush.setCreatedBy(orderHeader.getCreatedBy()); orderHeaderForPush.setPartySizeUpdated(orderHeader.isPartySizeUpdated()); if (orderHeader.getCloseTime() != 0) { orderHeaderForPush.setCloseTime(orderHeader.getCloseTime()); } orderHeaderForPush.setIsTabOrder(orderHeader.getIsTabOrder()); orderHeaderForPush.setServername(orderHeader.getServername()); orderHeaderForPush.setAddressShipping(orderHeader.getAddressShipping()); orderHeaderForPush.setNirvanaXpBatchNumber(orderHeader.getNirvanaXpBatchNumber()); orderHeaderForPush.setIsSeatWiseOrder(orderHeader.getIsSeatWiseOrder()); orderHeaderForPush.setMergeOrderId(orderHeader.getMergeOrderId()); orderHeaderForPush.setPriceDiscount(orderHeader.getPriceDiscount()); orderHeaderForPush.setSubTotal(orderHeader.getSubTotal()); // add by apoorv after ketan requirement orderHeaderForPush.setServerId(orderHeader.getServerId()); orderHeaderForPush.setCashierId(orderHeader.getCashierId()); orderHeaderForPush.setShiftSlotId(orderHeader.getShiftSlotId()); orderHeaderForPush.setPriceDiscountItemLevel(orderHeader.getPriceDiscountItemLevel()); orderHeaderForPush.setPoRefrenceNumber(orderHeader.getPoRefrenceNumber()); orderHeaderForPush.setRequestedLocationId(orderHeader.getRequestedLocationId()); orderHeaderForPush.setOrderTypeId(orderHeader.getOrderTypeId()); orderHeaderForPush.setUsersId(orderHeader.getUsersId()); return orderHeaderForPush; } /** * Send packet for broadcast. * * @param httpRequest * the http request * @param orderPacket * the order packet * @param operationName * the operation name * @param shouldSendUSerInfoToo * the should send U ser info too * @throws NirvanaXPException * the nirvana XP exception */ public void sendPacketForBroadcast(HttpServletRequest httpRequest, PostPacket orderPacket, String operationName, boolean shouldSendUSerInfoToo) throws NirvanaXPException { try { // so that session id value does not get broadcasted orderPacket.setIdOfSessionUsedByPacket(0); orderPacket.setSessionId(null); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); String internalJson = null; internalJson = objectMapper.writeValueAsString(orderPacket); operationName = ServiceOperationsUtility.getOperationName(operationName); MessageSender messageSender = new MessageSender(); messageSender.sendMessage(httpRequest, orderPacket.getClientId(), POSNServices.OrderManagementService.name(), operationName, internalJson, orderPacket.getMerchantId(), orderPacket.getLocationId(), orderPacket.getEchoString(), orderPacket.getSchemaName()); } catch (IOException e) { // could not send push logger.severe(httpRequest, e, "Unable to broadcast order packet"); } } public void sendPacketForBroadcast(HttpServletRequest httpRequest, String operation, PostPacket postPacket) { operation = ServiceOperationsUtility.getOperationName(operation); MessageSender messageSender = new MessageSender(); messageSender.sendMessage(httpRequest, postPacket.getClientId(), POSNServices.LookupService.name(), operation, null, postPacket.getMerchantId(), postPacket.getLocationId(), postPacket.getEchoString(), postPacket.getSchemaName()); } /** * Send packet for broadcast. * * @param httpRequest * the http request * @param orderPacket * the order packet * @param operationName * the operation name * @param shouldSendUSerInfoToo * the should send U ser info too * @throws NirvanaXPException * the nirvana XP exception */ public void sendPacketForBroadcast(HttpServletRequest httpRequest, OrderPacket orderPacket, String operationName, boolean shouldSendUSerInfoToo) throws NirvanaXPException { try { // so that session id value does not get broadcasted orderPacket.setIdOfSessionUsedByPacket(0); orderPacket.setSessionId(null); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); String internalJson = null; if (!shouldSendUSerInfoToo) { internalJson = objectMapper.writeValueAsString(orderPacket.getOrderHeader()); } else { internalJson = objectMapper.writeValueAsString(orderPacket); } operationName = ServiceOperationsUtility.getOperationName(operationName); MessageSender messageSender = new MessageSender(); messageSender.sendMessage(httpRequest, orderPacket.getClientId(), POSNServices.OrderManagementService.name(), operationName, internalJson, orderPacket.getMerchantId(), orderPacket.getLocationId(), orderPacket.getEchoString(), orderPacket.getSchemaName()); } catch (IOException e) { // could not send push logger.severe(httpRequest, e, "Unable to broadcast order packet"); } } /** * Update order source. * * @param httpRequest * the http request * @param em * the em * @param orderSourcePacket * the order source packet * @param cancelOrder * the cancel order * @return the order header source packet * @throws NirvanaXPException * the nirvana XP exception */ public OrderHeaderSourcePacket updateOrderSource(HttpServletRequest httpRequest, EntityManager em, OrderHeaderSourcePacket orderSourcePacket, boolean cancelOrder) throws NirvanaXPException { String[] reservationStatusId = null; OrderHeaderSource orderPacket = orderSourcePacket.getOrderHeaderSource(); if (orderSourcePacket.getLocationId() != null) { String locationId = orderSourcePacket.getLocationId(); reservationStatusId = new OrderManagementServiceBean().updateOrderAndSource(httpRequest, em, orderPacket.getOrderId(), orderPacket.getOrderSourceId(), orderPacket.getReservationId(), orderPacket.getUpdatedBy(), locationId, orderPacket.getUserId(), cancelOrder); } if (reservationStatusId[0]!=null ) {// setting previous reservation // status id orderPacket.setPreviousReservationStatusId(reservationStatusId[0]); } if (reservationStatusId[1]!=null ) { orderPacket.setNewReservationStatusId(reservationStatusId[1]); } if (reservationStatusId[2]!=null ) { orderPacket.setPartySize(Integer.parseInt(reservationStatusId[2])); } if (reservationStatusId[3]!=null ) { orderPacket.setOrderStatusId(reservationStatusId[3]); } if (reservationStatusId[4]!=null ) { orderPacket.setOrderId(reservationStatusId[4]); } if (reservationStatusId[5]!=null ) { orderPacket.setCancelOrderId(reservationStatusId[5]); } OrderHeader header = null; if (orderPacket.getOrderId()!=null ) { header = new OrderManagementServiceBean().getOrderById(em, orderPacket.getOrderId()); } OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(header); orderPacket.setOrderHeader(orderHeaderForPush); orderPacket.setOrderHeader(header); orderSourcePacket.setOrderHeaderSource(orderPacket); sendPacketForBroadcast(httpRequest, orderSourcePacket, POSNServiceOperations.OrderManagementService_updateOrderSource.name()); return orderSourcePacket; } /** * Update order status to paid. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws NumberFormatException * the number format exception * @throws Exception * the exception */ public OrderHeader updateOrderStatusToPaid(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket, String ccArray) throws NumberFormatException, Exception { OrderHeader orderHeader = orderPacket.getOrderHeader(); OrderSource orderSource = (OrderSource) new CommonMethods().getObjectById("OrderSource", em,OrderSource.class, orderHeader.getOrderSourceId()); OrderHeaderWithInventoryPostPacket ohWithIPP = new OrderManagementServiceBean().updateOrderStatusToPaid(httpRequest, em, orderHeader.getId(), orderSource.getOrderSourceGroupId(), orderHeader.getUpdatedBy(), orderHeader.getLocationsId(), Integer.parseInt(orderPacket.getMerchantId()), orderPacket.getCashOnDelivery(),ccArray); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(ohWithIPP.getOrderHeader()); InventoryPostPacket inventoryPostPacket = ohWithIPP.getInventoryPostPacket(); if (inventoryPostPacket != null && inventoryPostPacket.getInventoryList() != null && inventoryPostPacket.getInventoryList().size() > 0) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); String inventoryPostPacketAsStr = objectMapper.writeValueAsString(inventoryPostPacket); orderHeaderForPush.setInventoryPostPacket(inventoryPostPacketAsStr); ohWithIPP.getOrderHeader().setInventoryPostPacket(inventoryPostPacketAsStr); } if (orderPacket.getCashOnDelivery() == 1) { OrderHeader header = new OrderManagementServiceBean().getOrderById(em, orderPacket.getOrderHeader().getId()); new PrinterUtility().insertIntoPrintQueueForCustomer(httpRequest, em, header, orderPacket.getLocationId()); } orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderPayment.name(), false); return ohWithIPP.getOrderHeader(); } /** * Close business. * * @param httpRequest * the http request * @param em * the em * @param updatedBy * the updated by * @param locationId * the location id * @param businessId * the business id * @param sessionId * the session id * @return true, if successful * @throws Exception * the exception */ public boolean closeBusiness(HttpServletRequest httpRequest, EntityManager em, String updatedBy, String locationId, int businessId, String sessionId, PostPacket packet, String date) throws Exception { return new OrderManagementServiceBean().closeBusiness(httpRequest, em, updatedBy, locationId, sessionId, packet, date); } /** * Send packet for broadcast. * * @param httpRequest * the http request * @param orderPacket * the order packet * @param operationName * the operation name */ private void sendPacketForBroadcast(HttpServletRequest httpRequest, OrderHeaderSourcePacket orderPacket, String operationName) { try { // so that session id value does not get broadcasted orderPacket.setIdOfSessionUsedByPacket(0); orderPacket.setSessionId(null); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); String internalJson = objectMapper.writeValueAsString(orderPacket.getOrderHeaderSource()); operationName = ServiceOperationsUtility.getOperationName(operationName); MessageSender messageSender = new MessageSender(); messageSender.sendMessage(httpRequest, orderPacket.getClientId(), POSNServices.OrderManagementService.name(), operationName, internalJson, orderPacket.getMerchantId(), orderPacket.getLocationId(), orderPacket.getEchoString(), orderPacket.getSchemaName()); } catch (IOException e) { // could not send push // todo shlok need // handle proper Exception logger.severe(httpRequest, e); } } /** * Update order payment for tip saved. * * @param httpRequest * the http request * @param em * the em * @param tipSavedPacket * the tip saved packet * @return the order header * @throws Exception * the exception */ public OrderHeader updateOrderPaymentForTipSaved(HttpServletRequest httpRequest, EntityManager em, TipSavedPacket tipSavedPacket) throws Exception { OrderPacket orderPacket = new OrderPacket(); OrderHeaderWithInventoryPostPacket ohWithIPP = new OrderManagementServiceBean().updateOrderPaymentForTipSave(httpRequest, em, tipSavedPacket); // setting post packet orderPacket.setClientId(tipSavedPacket.getClientId()); orderPacket.setEchoString(tipSavedPacket.getEchoString()); orderPacket.setLocationId(tipSavedPacket.getLocationId()); orderPacket.setMerchantId(tipSavedPacket.getMerchantId()); orderPacket.setSchemaName(tipSavedPacket.getSchemaName()); orderPacket.setSessionId(tipSavedPacket.getSessionId()); orderPacket.setIdOfSessionUsedByPacket(tipSavedPacket.getIdOfSessionUsedByPacket()); orderPacket.setOrderHeader(ohWithIPP.getOrderHeader()); orderPacket.getOrderHeader().setSessionKey(tipSavedPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(ohWithIPP.getOrderHeader()); orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderPayment.name(), false); return ohWithIPP.getOrderHeader(); } /** * Update order for seatwise. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws Exception * the exception */ public OrderHeader updateOrderForSeatwise(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket,String sessionId) throws Exception { orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeaderWithInventoryPostPacket ohWithIPP = new OrderManagementServiceBean().updateOrderForSeatwise(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId().trim(),Integer.parseInt(orderPacket.getMerchantId()),sessionId); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(ohWithIPP.getOrderHeader()); InventoryPostPacket inventoryPostPacket = ohWithIPP.getInventoryPostPacket(); if (inventoryPostPacket != null && inventoryPostPacket.getInventoryList() != null && inventoryPostPacket.getInventoryList().size() > 0) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); String inventoryPostPacketAsStr = objectMapper.writeValueAsString(inventoryPostPacket); orderHeaderForPush.setInventoryPostPacket(inventoryPostPacketAsStr); ohWithIPP.getOrderHeader().setInventoryPostPacket(inventoryPostPacketAsStr); } orderPacket.setOrderHeader(orderHeaderForPush); if (orderPacket.getPacketVersion() == 1) { sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_update.name(), true); } else { // for 0 send sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_update.name(), false); } return ohWithIPP.getOrderHeader(); } /** * Update order for duplicate check. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws Exception * the exception */ public OrderHeader updateOrderForDuplicateCheck(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket,String sessionId) throws Exception { orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); boolean isDuplicatePacketCheck = true; OrderHeaderWithInventoryPostPacket ohWithIPP = new OrderManagementServiceBean().update(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId().trim(), isDuplicatePacketCheck, orderPacket.getIdOfOrderHoldingClientObj(),Integer.parseInt(orderPacket.getMerchantId()),sessionId); em.getTransaction().commit(); em.getTransaction().begin(); if (ohWithIPP.getOrderHeader() != null && ohWithIPP.getOrderHeader().getOrderDetailItems() != null && ohWithIPP.getOrderHeader().getOrderDetailItems().size() > 0) { logger.severe("ohWithIPP.getOrderHeader().getOrderDetailItems() " + ohWithIPP.getOrderHeader().getOrderDetailItems()); addUpdateRequestOrder(ohWithIPP.getOrderHeader(), httpRequest, em, ohWithIPP.getOrderHeader().getOrderDetailItems()); try { new PrinterUtility().insertIntoPrintQueue(httpRequest, em, ohWithIPP.getOrderHeader(), orderPacket.getLocationId()); } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } } OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(ohWithIPP.getOrderHeader()); InventoryPostPacket inventoryPostPacket = ohWithIPP.getInventoryPostPacket(); if (inventoryPostPacket != null && inventoryPostPacket.getInventoryList() != null && inventoryPostPacket.getInventoryList().size() > 0) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY); objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT); String inventoryPostPacketAsStr = objectMapper.writeValueAsString(inventoryPostPacket); orderHeaderForPush.setInventoryPostPacket(inventoryPostPacketAsStr); ohWithIPP.getOrderHeader().setInventoryPostPacket(inventoryPostPacketAsStr); } orderPacket.setOrderHeader(orderHeaderForPush); if (orderPacket.getPacketVersion() == 1) { sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_update.name(), true); } else { // for 0 send sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_update.name(), false); } return ohWithIPP.getOrderHeader(); } /** * Update order payment for under processing transaction. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws NumberFormatException * the number format exception * @throws IOException * Signals that an I/O exception has occurred. * @throws InvalidSessionException * the invalid session exception * @throws NirvanaXPException * the nirvana XP exception * @throws ParseException * the parse exception */ public OrderHeader updateOrderPaymentForUnderProcessingTransaction(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws NumberFormatException, IOException, InvalidSessionException, NirvanaXPException, ParseException { orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeader = new OrderManagementServiceBean().updateOrderPaymentForUnderProcessingTransaction(em, orderPacket.getOrderHeader()); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(orderHeader); orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderPayment.name(), false); return orderHeader; } /** * Update order status for duplicate check. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws Exception * @throws NumberFormatException */ public OrderHeader updateOrderStatusForDuplicateCheck(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws NumberFormatException, Exception { boolean isDuplicatePacketCheck = true; orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeader = new OrderManagementServiceBean().updateOrderStatus(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId().trim(), orderPacket.getPacketVersion(), isDuplicatePacketCheck,Integer.parseInt(orderPacket.getMerchantId())); OrderStatus orderStatus = (OrderStatus) new CommonMethods().getObjectById("OrderStatus", em,OrderStatus.class, orderHeader.getOrderStatusId()); if (orderStatus.getName().equals("Cancel Order")) { try { new PrinterUtility().insertIntoPrintQueueForCancelOrderAndQuickPay(httpRequest, em, orderHeader, orderPacket.getLocationId()); } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } } OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(orderHeader); orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderStatus.name(), false); return orderHeader; } /** * Merge order with items. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order header * @throws Exception * @throws NumberFormatException */ public OrderHeader mergeOrderWithItems(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws NumberFormatException, Exception { boolean isDuplicatePacketCheck = true; orderPacket.getOrderHeader().setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeader = new OrderManagementServiceBean().updateOrderStatus(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId().trim(), orderPacket.getPacketVersion(), isDuplicatePacketCheck,Integer.parseInt(orderPacket.getMerchantId())); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(orderHeader); orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderStatus.name(), false); return orderHeader; } /** * Update order info for delivery takeout. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order packet * @throws NumberFormatException * the number format exception * @throws NirvanaXPException * the nirvana XP exception * @throws ParseException * the parse exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. * @throws Exception * the exception */ public OrderPacket updateOrderInfoForDeliveryTakeout(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws NumberFormatException, NirvanaXPException, ParseException, JsonGenerationException, JsonMappingException, IOException, Exception { User user = orderPacket.getUser(); OrderHeader orderHeader = orderPacket.getOrderHeader(); OrderHeader o = new OrderManagementServiceBean().getOrderById(em, orderHeader.getId()); // check for global user id GlobalUsermanagement globalUsermanagement = new GlobalUsermanagement(); User localUser = null; // add this user to global and local database and insert into // reservation user id // create new user localUser = new User(); localUser.setFirstName(user.getFirstName()); localUser.setLastName(user.getLastName()); localUser.setPhone(user.getPhone()); localUser.setEmail(user.getEmail()); localUser.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); localUser.setUpdatedBy(user.getCreatedBy()); localUser.setCreatedBy(user.getCreatedBy()); localUser.setStatus("A"); localUser.setCountryId(user.getCountryId()); localUser.setId(new StoreForwardUtility().generateUUID()); if (localUser.getPhone() != null && localUser.getPhone().length() > 0) { localUser.setUsername(localUser.getPhone()); } else { localUser.setUsername(localUser.getEmail()); } EntityManager globalEM = null; try { globalEM = GlobalSchemaEntityManager.getInstance().getEntityManager(); String username = ""; if (localUser.getUsername() != null) { username = localUser.getUsername(); } if (username == null || localUser.getUsername().trim().length() == 0) { if (localUser.getPhone() != null && localUser.getPhone().length() > 0) { username = localUser.getPhone(); } else { username = localUser.getEmail(); } } if (username != null && username.trim().length() != 0) { localUser = globalUsermanagement.addUserToLocalDatabaseProgramatically(httpRequest, globalEM, em, localUser, orderHeader.getLocationsId(),orderPacket); } } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } finally { GlobalSchemaEntityManager.getInstance().closeEntityManager(globalEM); } if (localUser != null) { o.setUsersId(localUser.getId()); o.setPointOfServiceCount(orderHeader.getPointOfServiceCount()); o.setSessionKey(orderHeader.getSessionKey()); o.setFirstName(orderHeader.getFirstName()); o.setLastName(orderHeader.getLastName()); o.setAddressShipping(orderHeader.getAddressShipping()); o.setAddressBilling(orderHeader.getAddressBilling()); // added to insert current time of the location in the // order // header // 37640 changes as time is noit changing in device done by apoorv TimezoneTime timezoneTime = new TimezoneTime(); String locationID = orderHeader.getLocationsId(); String currentDateTime[] = timezoneTime.getCurrentTimeofLocation(locationID, em); if (currentDateTime != null && currentDateTime.length > 0) { o.setDate(currentDateTime[0]); if (orderHeader.getScheduleDateTime() == null) { o.setScheduleDateTime(currentDateTime[2]); o.setScheduleDateTime(timezoneTime.getDateAccordingToGMT(o.getScheduleDateTime(), locationID, em)); } else { o.setScheduleDateTime(orderHeader.getScheduleDateTime()); o.setScheduleDateTime(timezoneTime.getDateAccordingToGMT(o.getScheduleDateTime(), locationID, em)); } } // added by Apoorva by 29-03-2018 #44107 , if (orderHeader.getOrderStatusId() != null) { o.setOrderStatusId(orderHeader.getOrderStatusId()); } o.setOrderSourceId(orderHeader.getOrderSourceId()); o.setDeliveryTax(orderHeader.getDeliveryTax()); o.setDeliveryCharges(orderHeader.getDeliveryCharges()); o.setDeliveryOptionId(orderHeader.getDeliveryOptionId()); o.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); o.setUpdatedBy(orderHeader.getUpdatedBy()); o.setRequestedLocationId(orderHeader.getRequestedLocationId()); orderPacket.setUser(localUser); if (orderHeader.getEventName() != null) { o.setEventName(orderHeader.getEventName()); } if (orderHeader.getStartDate() != null) { o.setStartDate(orderHeader.getStartDate()); } if (orderHeader.getEndDate() != null) { o.setEndDate(orderHeader.getEndDate()); } if (orderHeader.getPointOfServiceCount() != 0) { o.setPointOfServiceCount(orderHeader.getPointOfServiceCount()); } OrderHeader header = em.merge(o); o.setAddressShipping(header.getAddressShipping()); o.setAddressBilling(header.getAddressBilling()); EntityManager emGlobal = null; try { if (header.getDriverId() != null) { emGlobal = GlobalSchemaEntityManager.getInstance().getEntityManager(httpRequest, null); EntityTransaction txGlobal = emGlobal.getTransaction(); txGlobal.begin(); CriteriaBuilder builder = emGlobal.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(DriverOrder.class); Root r = criteria.from(DriverOrder.class); TypedQuery query = emGlobal.createQuery(criteria.select(r).where(builder.and(builder.equal(r.get(DriverOrder_.orderId), o.getId())), builder.and(builder.equal(r.get(DriverOrder_.locationsId), o.getLocationsId())))); DriverOrder driverOrder = query.getSingleResult(); driverOrder.setCustomerAddress(createAddress(o.getAddressShipping())); emGlobal.merge(driverOrder); txGlobal.commit(); } } catch (Exception e) { e.printStackTrace(); } finally { GlobalSchemaEntityManager.getInstance().closeEntityManager(emGlobal); } orderPacket.setOrderHeader(o); try { new PrinterUtility().insertIntoPrintQueueForOrderUpdateFromOutside(httpRequest, em, orderPacket.getOrderHeader(), orderPacket.getLocationId()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } orderPacket.setOrderHeader(header); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_update.name(), true); } return orderPacket; } /** * Update order transfer. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @param tx * the tx * @return the order packet for order transfer * @throws NumberFormatException * the number format exception * @throws NirvanaXPException * the nirvana XP exception * @throws ParseException * the parse exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. * @throws Exception * the exception */ public OrderPacketForOrderTransfer updateOrderTransfer(HttpServletRequest httpRequest, EntityManager em, OrderPacketForOrderTransfer orderPacket, EntityTransaction tx) throws NumberFormatException, NirvanaXPException, ParseException, JsonGenerationException, JsonMappingException, IOException, Exception { OrderPacketForOrderTransfer o = new OrderManagementServiceBean().updateOrderTransfer(httpRequest, em, orderPacket, tx); // check for global user id orderPacket.getFromOrderHeader().setOrderDetailItems(null); orderPacket.getToOrderHeader().setOrderDetailItems(null); orderPacket.getFromOrderHeader().setOrderPaymentDetails(null); orderPacket.getToOrderHeader().setOrderPaymentDetails(null); OrderHeader toOrder = new OrderManagementServiceBean().getOrderById(em, orderPacket.getToOrderHeader().getId()); try { new PrinterUtility().insertIntoPrintQueueForOrderTransfer(httpRequest, em, toOrder, orderPacket.getLocationId(), o.getFromOrderHeader().getId()); } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderTransfer.name(), true); return o; } /** * Gets the two order by id. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the two order by id * @throws NumberFormatException * the number format exception * @throws NirvanaXPException * the nirvana XP exception * @throws ParseException * the parse exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. * @throws Exception * the exception */ public OrderPacketForOrderTransfer getTwoOrderById(HttpServletRequest httpRequest, EntityManager em, OrderPacketForOrderTransfer orderPacket) throws NumberFormatException, NirvanaXPException, ParseException, JsonGenerationException, JsonMappingException, IOException, Exception { orderPacket.setFromOrderHeader(new OrderManagementServiceBean().getOrderByIdAndParentLocationId(em, orderPacket.getFromOrderHeader().getId(), orderPacket.getRootLocationId())); orderPacket.setToOrderHeader(new OrderManagementServiceBean().getOrderByIdAndParentLocationId(em, orderPacket.getToOrderHeader().getId(), orderPacket.getRootLocationId())); return orderPacket; } /** * Update item transfer. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order packet for order transfer * @throws NumberFormatException * the number format exception * @throws NirvanaXPException * the nirvana XP exception * @throws ParseException * the parse exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. * @throws Exception * the exception */ public OrderPacketForOrderTransfer updateItemTransfer(HttpServletRequest httpRequest, EntityManager em, OrderPacketForOrderTransfer orderPacket) throws NumberFormatException, NirvanaXPException, ParseException, JsonGenerationException, JsonMappingException, IOException, Exception { OrderPacketForOrderTransfer o = new OrderManagementServiceBean().updateItemTransfer(httpRequest, em, orderPacket,Integer.parseInt(orderPacket.getMerchantId())); // check for global user id orderPacket.getFromOrderHeader().setOrderDetailItems(null); orderPacket.getToOrderHeader().setOrderDetailItems(null); orderPacket.getFromOrderHeader().setOrderPaymentDetails(null); orderPacket.getToOrderHeader().setOrderPaymentDetails(null); OrderHeader fromOrderHeader = new OrderManagementServiceBean().getOrderById(em, orderPacket.getFromOrderHeader().getId()); OrderHeader toOrderHeader = new OrderManagementServiceBean().getOrderById(em, orderPacket.getToOrderHeader().getId()); try { new PrinterUtility().insertIntoPrintQueueForItemTransfer(httpRequest, em, toOrderHeader, orderPacket.getLocationId(), fromOrderHeader); } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateItemTransfer.name(), true); return o; } /** * Delete order by order management role. * * @param httpRequest * the http request * @param em * the em * @param orderPacket * the order packet * @return the order packet * @throws NirvanaXPException * the nirvana XP exception * @throws JsonGenerationException * the json generation exception * @throws JsonMappingException * the json mapping exception * @throws IOException * Signals that an I/O exception has occurred. */ public OrderPacket deleteOrderByOrderManagementRole(HttpServletRequest httpRequest, EntityManager em, OrderPacket orderPacket) throws NirvanaXPException, JsonGenerationException, JsonMappingException, IOException { for (String orderId : orderPacket.getOrderHeaderIds()) { OrderHeader header = (OrderHeader) new CommonMethods().getObjectById("OrderHeader", em,OrderHeader.class, orderId); if (header != null) { boolean result = new OrderManagementServiceBean().deleteOrderHeader(httpRequest, em, orderId); if (result) { OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(header); orderPacket.setOrderHeader(orderHeaderForPush); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderStatus.name(), false); } } } return orderPacket; } public PrintQueuePacket updatePrintQueue(EntityManager em, HttpServletRequest httpRequest, PrintQueuePacket printQueuePacket) throws NirvanaXPException { PrintQueuePacket packet = new PrintQueuePacket(); List printQueues = new ArrayList(); for (PrintQueue printQueue : printQueuePacket.getPrintQueueList()) { PrintQueue pq= em.find(PrintQueue.class, printQueue.getId()); if(pq!=null){ pq.setStatus(printQueue.getStatus()); pq.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); try { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date scheduleDateTime = formatter.parse(pq.getScheduleDateTime()); if (scheduleDateTime.after(pq.getUpdated())) { pq.setUpdated(formatter.parse(pq.getScheduleDateTime())); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } pq=em.merge(pq); printQueues.add(pq); if (pq.getStatus().equals("B")) { OrderHeader header = new OrderManagementServiceBean().getOrderById(em, pq.getOrderId()); OrderStatus currentOrderStatus = (OrderStatus) new CommonMethods().getObjectById("OrderStatus", em,OrderStatus.class, header.getOrderStatusId()); OrderSource orderSource = (OrderSource) new CommonMethods().getObjectById("OrderSource", em,OrderSource.class, header.getOrderSourceId()); OrderSourceGroup orderSourceGroup = (OrderSourceGroup) new CommonMethods().getObjectById("OrderSourceGroup", em,OrderSourceGroup.class, orderSource.getOrderSourceGroupId()); if ( !currentOrderStatus.getName().equals("Bus Ready") && !currentOrderStatus.getName().equals("Ready to Order") && !currentOrderStatus.getName().equals("Ready To Serve") && !currentOrderStatus.getName().equals("Reopen") ) { OrderStatus orderStatus = null; if (header.getOrderTypeId() == 2) { orderStatus = getOrderStatusByNameAndLocation(em, "Close Production", pq.getLocationId(), orderSource.getOrderSourceGroupId()); } else { if (orderSourceGroup.getName().equals("Pick Up")) { orderStatus = getOrderStatusByNameAndLocation(em, "Ready for pick up", pq.getLocationId(), orderSource.getOrderSourceGroupId()); } else if (orderSourceGroup.getName().equals("Delivery")) { orderStatus = getOrderStatusByNameAndLocation(em, "Ready for delivery", pq.getLocationId(), orderSource.getOrderSourceGroupId()); } else { if(!currentOrderStatus.getName().equals("Order Paid")&& !currentOrderStatus.getName().equals("Cash On Delivery")){ orderStatus = getOrderStatusByNameAndLocation(em, "Ready To Serve", pq.getLocationId(), orderSource.getOrderSourceGroupId()); } } } if(orderStatus!=null){ header.setOrderStatusId(orderStatus.getId()); header.setSessionKey(printQueuePacket.getIdOfSessionUsedByPacket()); header = em.merge(header); OrderPacket orderPacket = new OrderPacket(); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(header); orderPacket.setOrderHeader(orderHeaderForPush); orderPacket.setClientId(printQueuePacket.getClientId()); orderPacket.setEchoString(printQueuePacket.getEchoString()); orderPacket.setMerchantId(printQueuePacket.getMerchantId()); orderPacket.setLocationId(printQueuePacket.getLocationId()); orderPacket.setSessionId(printQueuePacket.getSessionId()); orderPacket.setIdOfSessionUsedByPacket(printQueuePacket.getIdOfSessionUsedByPacket()); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderStatus.name(), false); } // Close in house production PO After Bump // closeProductionOrder(header,em,httpRequest,printQueuePacket,true); } } else if (pq.getStatus().equals("U")) { OrderHeader header = new OrderManagementServiceBean().getOrderById(em, pq.getOrderId()); OrderStatus currentOrderStatus = (OrderStatus) new CommonMethods().getObjectById("OrderStatus", em,OrderStatus.class, header.getOrderStatusId()); OrderSource orderSource = (OrderSource) new CommonMethods().getObjectById("OrderSource", em,OrderSource.class, header.getOrderSourceId()); OrderSourceGroup orderSourceGroup = (OrderSourceGroup) new CommonMethods().getObjectById("OrderSourceGroup", em,OrderSourceGroup.class, orderSource.getOrderSourceGroupId()); if (!currentOrderStatus.getName().equals("Order Paid") && !currentOrderStatus.getName().equals("Bus Ready") && !currentOrderStatus.getName().equals("Ready to Order") && !currentOrderStatus.getName().equals("Cooking") && !currentOrderStatus.getName().equals("Reopen") && !currentOrderStatus.getName().equals("Cash On Delivery")) { OrderStatus orderStatus; if (header.getOrderTypeId() == 2) { orderStatus = getOrderStatusByNameAndLocation(em, "Order Placed", pq.getLocationId(), orderSource.getOrderSourceGroupId()); } else { orderStatus = getOrderStatusByNameAndLocation(em, "Cooking", pq.getLocationId(), orderSource.getOrderSourceGroupId()); } header.setOrderStatusId(orderStatus.getId()); header.setSessionKey(printQueuePacket.getIdOfSessionUsedByPacket()); header = em.merge(header); OrderPacket orderPacket = new OrderPacket(); OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(header); orderPacket.setOrderHeader(orderHeaderForPush); orderPacket.setClientId(printQueuePacket.getClientId()); orderPacket.setEchoString(printQueuePacket.getEchoString()); orderPacket.setMerchantId(printQueuePacket.getMerchantId()); orderPacket.setLocationId(printQueuePacket.getLocationId()); orderPacket.setSessionId(printQueuePacket.getSessionId()); orderPacket.setIdOfSessionUsedByPacket(printQueuePacket.getIdOfSessionUsedByPacket()); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_updateOrderStatus.name(), false); } // Close in house production PO After Bump // closeProductionOrder(header,em,httpRequest,printQueuePacket,false); } } } packet.setMerchantId(printQueuePacket.getMerchantId()); packet.setLocationId(printQueuePacket.getLocationId()); packet.setPrintQueueList(printQueues); return packet; } /* * private void closePoOrder(OrderHeader header,EntityManager em) { * * if(header.getPoRefrenceNumber() != 0) { * * RequestOrder requestOrder = (RequestOrder) new CommonMethods().getObjectById("RequestOrder", em,RequestOrder.class, * header.getPoRefrenceNumber()); * * String queryStringStatus = * "select s from OrderStatus s where s.name =? and s.locationsId=? and s.status !='D'" * ; TypedQuery queryStatus = em.createQuery(queryStringStatus, * OrderStatus.class).setParameter(1, "PO Received") .setParameter(2, * requestOrder.getLocationId()); OrderStatus orderStatus = * queryStatus.getSingleResult(); * * if(orderStatus.getId() != requestOrder.getStatusId() && * requestOrder.getSupplierId() == requestOrder.getLocationId()) { * requestOrder.setStatusId(orderStatus.getId()); * * requestOrder = em.merge(requestOrder); * * String queryStringDetailsStatus = * "select s from OrderDetailStatus s where s.name =? and s.locationsId=? and s.status !='D'" * ; TypedQuery queryDetailsStatus = * em.createQuery(queryStringDetailsStatus, OrderDetailStatus.class) * .setParameter(1, "PO Item Received").setParameter(2, * requestOrder.getLocationId()); OrderDetailStatus orderDetailStatus = * queryDetailsStatus.getSingleResult(); * * * String queryStringItems = * "select s from RequestOrderDetailItems s where s.requestId =? and s.status !='D'" * ; TypedQuery queryDetailsItems = * em.createQuery(queryStringItems, RequestOrderDetailItems.class) * .setParameter(1, requestOrder.getId()); List * detailItems = queryDetailsItems.getResultList(); * * Location location = (Location) new CommonMethods().getObjectById("Location", em,Location.class, * requestOrder.getLocationId()); * * * int grnCount = requestOrder.getGrnCount(); for(RequestOrderDetailItems * detailItems2 : detailItems) { * detailItems2.setStatusId(orderDetailStatus.getId()); * detailItems2.setBalance(new BigDecimal(0)); * detailItems2.setReceivedQuantity(detailItems2.getQuantity()); * detailItems2 = em.merge(detailItems2); * * String name = location.getName().replace("(", "").replace(")", ""); * String[] locationNameString = name.split(" "); String locationName = ""; * for (String locationNameObj : locationNameString) { locationName = * locationName + locationNameObj.substring(0, 1); } String grnNumber = * locationName + "-" + requestOrder.getId() + "-" + (++grnCount); * * insertGoodsReceiveNotes(em, detailItems2, grnNumber, false, * requestOrder.getGrnDate(), true,true,false); * * } } * * * * * * } } */ /* * private void closeProductionOrder(OrderHeader header,EntityManager em, * HttpServletRequest httpRequest, PrintQueuePacket printQueuePacket,boolean * isBump) { * * if(header.getOrderTypeId() == 2) { * * String queryString = * "select s from OrderSourceGroup s where s.name = ? and s.locationsId = ?" * ; TypedQuery query = em.createQuery(queryString, * OrderSourceGroup.class).setParameter(1, "In Store").setParameter(2, * header.getLocationsId()); OrderSourceGroup orderSourceGroup = * query.getSingleResult(); * * String queryStringStatus = * "select s from OrderStatus s where s.name =? and s.locationsId=? and s.orderSourceGroupId=? and s.status !='D'" * ; TypedQuery queryStatus; if(isBump) { queryStatus = * em.createQuery(queryStringStatus, OrderStatus.class).setParameter(1, * "Close Production") .setParameter(2, * header.getLocationsId()).setParameter(3, orderSourceGroup.getId()); }else * { queryStatus = em.createQuery(queryStringStatus, * OrderStatus.class).setParameter(1, "Order Placed") .setParameter(2, * header.getLocationsId()).setParameter(3, orderSourceGroup.getId()); } * * * OrderStatus orderStatus = queryStatus.getSingleResult(); * * * header.setOrderStatusId(orderStatus.getId()); OrderPacket orderPacket = * new OrderPacket(); orderPacket.setOrderHeader(header); * orderPacket.setClientId(printQueuePacket.getClientId()); * orderPacket.setLocationId(header.getLocationsId()+""); * orderPacket.setMerchantId(printQueuePacket.getMerchantId()); * * try { updateOrderStatus(httpRequest, em, orderPacket); } catch * (NirvanaXPException | IOException e) { // TODO Auto-generated catch block * e.printStackTrace(); } * * * } } */ List insertGoodsReceiveNotes(EntityManager em, RequestOrderDetailItems items, String grnNumber, boolean isAllotment, String grnDate, boolean isAdminReceive, boolean isDirectRecieve, boolean isNeedToCloseGRN) { List goodsReceiveNotes = new ArrayList(); if (items.getReceivedQuantity() == null) { items.setReceivedQuantity(new BigDecimal(0)); } BigDecimal balance = new BigDecimal(0); if (isAdminReceive) { balance = items.getQuantity().subtract(items.getReceivedQuantity()); } else { balance = items.getAllotmentQty().subtract(items.getReceivedQuantity()); } GoodsReceiveNotes notes = new GoodsReceiveNotes(); notes.setBalance(balance); notes.setAllotmentQty(items.getAllotmentQty()); notes.setCreated(new Date(new TimezoneTime().getGMTTimeInMilis())); OrderDetailStatus detailStatus = em.find(OrderDetailStatus.class, items.getStatusId()); if (detailStatus != null) { notes.setLocalTime(new TimezoneTime().getLocationSpecificTimeToAdd(detailStatus.getLocationsId(), em)); } notes.setCreatedBy(items.getCreatedBy()); notes.setGrnNumber(grnNumber); notes.setPrice(items.getPrice()); notes.setRate(items.getUnitPurchasedPrice()); notes.setReceivedQuantity(items.getReceivedQuantity()); notes.setRequestOrderDetailsItemId(items.getId()); notes.setStatus("A"); notes.setTax(items.getTax()); notes.setTotal(items.getTotal()); notes.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); notes.setUpdatedBy(items.getUpdatedBy()); notes.setDate(grnDate); notes.setUnitPrice(items.getUnitPrice()); notes.setUnitPurchasedPrice(items.getUnitPurchasedPrice()); notes.setUnitTaxRate(items.getUnitTaxRate()); if (isAllotment) { notes.setIsAllotment(1); } if (isNeedToCloseGRN) { if (notes.getBalance() != null && notes.getBalance().compareTo((new BigDecimal(0))) == 0) { notes.setIsGRNClose(1); } } if (isDirectRecieve) { notes.setIsGRNClose(1); } notes.setUomName(items.getUomName()); notes.setRequestOrderDetailItemName(items.getItemName()); notes.setStatusId(items.getStatusId()); notes = em.merge(notes); goodsReceiveNotes.add(notes); return goodsReceiveNotes; } /** * Gets the order status by name and location. * * @param em * the em * @param statusName * the status name * @param locationId * the location id * @param orderSourceGroupId * the order source group id * @return the order status by name and location */ public OrderStatus getOrderStatusByNameAndLocation(EntityManager em, String statusName, String locationId, String orderSourceGroupId) { try { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(OrderStatus.class); Root r = criteria.from(OrderStatus.class); TypedQuery query = em.createQuery(criteria.select(r).where(builder.equal(r.get(OrderStatus_.name), statusName), builder.equal(r.get(OrderStatus_.locationsId), locationId), builder.equal(r.get(OrderStatus_.orderSourceGroupId), orderSourceGroupId))); return query.getSingleResult(); } catch (Exception e) { // todo shlok need // handle proper Exception logger.severe(e); } return null; } /** * Update oder detail item status. * * @param em * the em * @param httpRequest * the http request * @param packet * the packet * @param kdsToOrderDetailItemStatusList * the kds to order detail item status list * @param isAdd * the is add * @return the KDS to order detail item status packet */ public KDSToOrderDetailItemStatusPacket updateOderDetailItemStatus(EntityManager em, HttpServletRequest httpRequest, KDSToOrderDetailItemStatusPacket packet, List kdsToOrderDetailItemStatusList, boolean isAdd) { try { List orderIds = new ArrayList(); for (KDSToOrderDetailItemStatus kdsToOrderDetailItemStatus : kdsToOrderDetailItemStatusList) { String orderDetailStatusName = getOrderDetailStatusName(em, kdsToOrderDetailItemStatus.getStatusId()); if (orderDetailStatusName.equals("Item Displayed")) { List printQueueList = getPrintQueueByOrderDetailId(em, kdsToOrderDetailItemStatus.getOrderDetailItemId()); List kdsToOrderDetailItemStatus1 = getkdsToODIStatusByOrderDetailId(em, kdsToOrderDetailItemStatus.getOrderDetailItemId(), kdsToOrderDetailItemStatus.getStatusId()); if (printQueueList.size() == kdsToOrderDetailItemStatus1.size()) { OrderDetailItem orderDetailItem = (OrderDetailItem) new CommonMethods().getObjectById("OrderDetailItem", em,OrderDetailItem.class, kdsToOrderDetailItemStatus.getOrderDetailItemId()); String locationsId = null; if (packet.getLocationId() != null && packet.getLocationId().length() > 0) { locationsId = packet.getLocationId(); } OrderDetailStatus detailStatus = getOrderDetailStatusByNameAndLocation(em, "KOT Printed", locationsId); OrderDetailStatus oldDetailStatus = em.find(OrderDetailStatus.class, orderDetailItem.getOrderDetailStatusId()); List notPrintedItems = getNotPrintedItems(em, orderDetailItem.getId()); if (!oldDetailStatus.getName().equals("KOT Printed") && (notPrintedItems == null || notPrintedItems.size() == 0)) { orderDetailItem.setOrderDetailStatusId(detailStatus.getId()); orderDetailItem.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); orderDetailItem = em.merge(orderDetailItem); List OrderDetailAttributeList = getOrderDetailAttributes(em, orderDetailItem.getId()); if (OrderDetailAttributeList != null) { for (OrderDetailAttribute attribute : OrderDetailAttributeList) { OrderDetailStatus attrOrderDetailStatus = em.find(OrderDetailStatus.class, attribute.getOrderDetailStatusId()); if (!attrOrderDetailStatus.getName().equals("Attribute Removed")) { attribute.setOrderDetailStatusId(detailStatus.getId()); } attribute.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); attribute = em.merge(attribute); } } if (!orderIds.contains(orderDetailItem.getOrderHeaderId())) { orderIds.add(orderDetailItem.getOrderHeaderId()); } } } } } packet.setIsOrderBumped(PrinterUtility.isOrderBumped); if (isAdd) { sendPacketForBroadcast(httpRequest, packet, POSNServiceOperations.OrderManagementService_addBumpUnbumpOrder.name(), true); } else { sendPacketForBroadcast(httpRequest, packet, POSNServiceOperations.OrderManagementService_updateBumpUnbumpOrder.name(), true); } return packet; } catch (NumberFormatException e) { // todo shlok need // return proper Exception logger.severe(e); } catch (NirvanaXPException e) { // todo shlok need // return proper Exception logger.severe(e); } return null; } /** * Gets the prints the queue by order detail id. * * @param em * the em * @param orderDetailItemId * the order detail item id * @return the prints the queue by order detail id */ public List getPrintQueueByOrderDetailId(EntityManager em, String orderDetailItemId) { try { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(PrintQueue.class); Root ic = criteria.from(PrintQueue.class); TypedQuery query = em .createQuery(criteria.select(ic).where(builder.equal(ic.get(PrintQueue_.status), "U"), builder.like(ic.get(PrintQueue_.orderDetailItemId), "%" + orderDetailItemId + "%"))); return query.getResultList(); } catch (NoResultException e) { // todo shlok need // return proper Exception return null; } } /** * Gets the kds to ODI status by order detail id. * * @param em * the em * @param orderDetailItemId * the order detail item id * @param statusId * the status id * @return the kds to ODI status by order detail id */ public List getkdsToODIStatusByOrderDetailId(EntityManager em, String orderDetailItemId, int statusId) { try { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(KDSToOrderDetailItemStatus.class); Root ic = criteria.from(KDSToOrderDetailItemStatus.class); TypedQuery query = em.createQuery(criteria.select(ic).where(builder.equal(ic.get(KDSToOrderDetailItemStatus_.orderDetailItemId), orderDetailItemId), builder.equal(ic.get(KDSToOrderDetailItemStatus_.statusId), statusId), builder.notEqual(ic.get(KDSToOrderDetailItemStatus_.status), "D"))); return query.getResultList(); } catch (NoResultException e) { // todo shlok need // return proper Exception return null; } } /** * Gets the order detail status name. * * @param em * the em * @param statusId * the status id * @return the order detail status name */ private String getOrderDetailStatusName(EntityManager em, int statusId) { // todo need to handle null pointer while fetch the name OrderDetailStatus detailStatus = em.find(OrderDetailStatus.class, statusId); return detailStatus.getName(); } /** * Gets the order detail status by name and location. * * @param em * the em * @param statusName * the status name * @param locationId * the location id * @return the order detail status by name and location */ public OrderDetailStatus getOrderDetailStatusByNameAndLocation(EntityManager em, String statusName, String locationId) { try { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(OrderDetailStatus.class); Root r = criteria.from(OrderDetailStatus.class); TypedQuery query = em .createQuery(criteria.select(r).where(builder.equal(r.get(OrderDetailStatus_.name), statusName), builder.equal(r.get(OrderDetailStatus_.locationsId), locationId))); return query.getSingleResult(); } catch (Exception e) { // todo shlok need // return proper Exception logger.severe(e); } return null; } /** * Gets the order detail attributes. * * @param em * the em * @param orderDetailItemId * the order detail item id * @return the order detail attributes */ public List getOrderDetailAttributes(EntityManager em, String orderDetailItemId) { try { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(OrderDetailAttribute.class); Root ic = criteria.from(OrderDetailAttribute.class); TypedQuery query = em.createQuery(criteria.select(ic).where(builder.equal(ic.get(OrderDetailAttribute_.orderDetailItemId), orderDetailItemId))); return query.getResultList(); } catch (NoResultException e) { // todo shlok need // return proper Exception return null; } } /** * Gets the not printed items. * * @param em * the em * @param orderDetailItemId * the order detail item id * @return the not printed items */ public List getNotPrintedItems(EntityManager em, String orderDetailItemId) { try { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(NotPrintedOrderDetailItemsToPrinter.class); Root ic = criteria.from(NotPrintedOrderDetailItemsToPrinter.class); TypedQuery query = em .createQuery(criteria.select(ic).where(builder.equal(ic.get(NotPrintedOrderDetailItemsToPrinter_.orderDetailItemsId), orderDetailItemId))); return query.getResultList(); } catch (NoResultException e) { // todo shlok need // return proper Exception return null; } } public void addUpdateRequestOrder(OrderHeader orderHeader, HttpServletRequest httpRequest, EntityManager em, List detailItems) throws Exception { OrderSource orderSource = (OrderSource) new CommonMethods().getObjectById("OrderSource", em,OrderSource.class, orderHeader.getOrderSourceId()); if (orderHeader.getRequestedLocationId() != null && (orderSource.getName().equals( "Internal") /* || orderSource.getName().equals("External") */)) { // List orderDetailItemsList = new // ArrayList(); EntityTransaction tx = null; try { tx = em.getTransaction(); String queryString = "select s from OrderSourceGroup s where s.locationsId=? and name like '%Inventory%'"; TypedQuery query = em.createQuery(queryString, OrderSourceGroup.class).setParameter(1, orderHeader.getRequestedLocationId()); OrderSourceGroup orderSourceGroup = query.getSingleResult(); if (orderHeader.getPoRefrenceNumber()!=null ) { RequestOrder requestOrder = (RequestOrder) new CommonMethods().getObjectById("RequestOrder", em,RequestOrder.class, orderHeader.getPoRefrenceNumber()); String queryStringStatus = "select s from OrderStatus s where s.name =? and s.locationsId=? and s.orderSourceGroupId=? and s.status !='D'"; TypedQuery queryStatus = em.createQuery(queryStringStatus, OrderStatus.class).setParameter(1, "Request Cancelled") .setParameter(2, orderHeader.getRequestedLocationId()).setParameter(3, orderSourceGroup.getId()); OrderStatus orderStatus = queryStatus.getSingleResult(); if (requestOrder.getStatusId() == orderStatus.getId()) { return; } } String queryStringStatus = "select s from OrderStatus s where s.name =? and s.locationsId=? and s.orderSourceGroupId=? and s.status !='D'"; TypedQuery queryStatus = em.createQuery(queryStringStatus, OrderStatus.class).setParameter(1, "PO Created").setParameter(2, orderHeader.getRequestedLocationId()) .setParameter(3, orderSourceGroup.getId()); OrderStatus orderStatus = queryStatus.getSingleResult(); /* * String queryStringDetailsStatus = * "select s from OrderDetailStatus s where s.name =? and s.locationsId=? and s.status !='D'" * ; TypedQuery queryDetailsStatus = * em.createQuery(queryStringDetailsStatus, * OrderDetailStatus.class).setParameter(1, * "PO Item Requested").setParameter(2, * orderHeader.getRequestedLocationId()); */ OrderDetailStatus orderDetailStatus = getOrderDetailStatusByNameAndLocationId(em, "PO Item Requested", orderHeader.getRequestedLocationId()); RequestOrder requestOrder = new RequestOrder(); requestOrder.setId(orderHeader.getPoRefrenceNumber()); requestOrder.setLocationId(orderHeader.getRequestedLocationId()); requestOrder.setSupplierId(orderHeader.getLocationsId()); requestOrder.setStatus("A"); requestOrder.setStatusId(orderStatus.getId()); requestOrder.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); requestOrder.setCreated(new Date(new TimezoneTime().getGMTTimeInMilis())); requestOrder.setUpdatedBy(orderHeader.getCreatedBy()); requestOrder.setCreatedBy(orderHeader.getUpdatedBy()); requestOrder.setIsPOOrder(1); requestOrder.setOrderSourceGroupId(orderHeader.getOrderSourceId()); requestOrder.setName("Internal Request"); TimezoneTime timezoneTime = new TimezoneTime(); String currentDateTime[] = timezoneTime.getCurrentTimeofLocation(orderHeader.getRequestedLocationId(), em); requestOrder.setDate(currentDateTime[0]); if (requestOrder.getId() != null ) { requestOrder = em.merge(requestOrder); } else { em.persist(requestOrder); } requestOrder.setPurchaseOrderId(requestOrder.getId()); requestOrder = em.merge(requestOrder); orderHeader.setPoRefrenceNumber(requestOrder.getId()); orderHeader = em.merge(orderHeader); if (detailItems != null && detailItems.size() > 0) { for (OrderDetailItem detailItem : detailItems) { Item itemAdapter = null; try { String queryStringItem = "select s from Item s where s.id =?"; TypedQuery queryItem = em.createQuery(queryStringItem, Item.class).setParameter(1, detailItem.getItemsId()); Item itemsQ = queryItem.getSingleResult(); queryStringItem = "select s from Item s where s.globalItemId =? and s.locationsId = ?"; queryItem = em.createQuery(queryStringItem, Item.class).setParameter(1, itemsQ.getGlobalItemId()).setParameter(2, orderHeader.getRequestedLocationId()); itemAdapter = queryItem.getSingleResult(); } catch (Exception e) { // TODO: handle exception logger.severe("No Item Entity Found"); } if (itemAdapter != null) { RequestOrderDetailItems rdetailItem = new RequestOrderDetailItems(); OrderDetailStatus orderDetailStatusRecall = getOrderDetailStatusById(em, detailItem.getOrderDetailStatusId()); if (orderDetailStatusRecall.getName().equals("Item Removed") || orderDetailStatusRecall.getName().equals("Recall")) { rdetailItem.setStatusId(getOrderDetailStatusByNameAndLocationId(em, "Item Removed", orderHeader.getRequestedLocationId()).getId()); if (detailItem.getPoItemRefrenceNumber() != null) { rdetailItem.setId(detailItem.getPoItemRefrenceNumber()); } else { rdetailItem.setId(null); } } else { rdetailItem.setStatusId(orderDetailStatus.getId()); if (detailItem.getPoItemRefrenceNumber() != null) { rdetailItem.setId(detailItem.getPoItemRefrenceNumber()); } else { rdetailItem.setId(null); } } rdetailItem.setItemName(itemAdapter.getShortName()); rdetailItem.setQuantity(detailItem.getItemsQty()); rdetailItem.setCreatedBy(orderHeader.getCreatedBy()); rdetailItem.setUpdatedBy(orderHeader.getCreatedBy()); rdetailItem.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); rdetailItem.setCreated(new Date(new TimezoneTime().getGMTTimeInMilis())); rdetailItem.setStatus("A"); rdetailItem.setRequestTo(orderHeader.getLocationsId()); rdetailItem.setRequestId(requestOrder.getId()); rdetailItem.setBalance(detailItem.getItemsQty()); rdetailItem.setAllotmentQty(new BigDecimal(0)); rdetailItem.setReceivedQuantity(new BigDecimal(0)); rdetailItem.setItemsId(itemAdapter.getId()); rdetailItem.setLocalTime(new TimezoneTime().getLocationSpecificTimeToAdd(requestOrder.getSupplierId(), em)); rdetailItem.setPurchaseOrderId(requestOrder.getId()); rdetailItem.setUnitPrice(itemAdapter.getPurchasingRate()); rdetailItem.setPrice(itemAdapter.getDistributionPrice()); rdetailItem.setTax(new BigDecimal(0)); rdetailItem.setUnitTaxRate(new BigDecimal(0)); rdetailItem.setTotal(new BigDecimal(0)); if (itemAdapter.getStockUom() != null) { try { String queryStringItem = "select s from UnitOfMeasurement s where s.id =?"; TypedQuery queryItem = em.createQuery(queryStringItem, UnitOfMeasurement.class).setParameter(1, itemAdapter.getStockUom()); UnitOfMeasurement itemsQ = queryItem.getSingleResult(); rdetailItem.setUomName(itemsQ.getDisplayName()); } catch (Exception e) { // TODO: handle exception logger.severe("No result found Unit Of Measurement for itemAdapter.getStockUom() " + itemAdapter.getStockUom()); } } rdetailItem = em.merge(rdetailItem); // OrderDetailItem detailItem2 = // (OrderDetailItem) new CommonMethods().getObjectById("OrderDetailItem", em,OrderDetailItem.class, // detailItem.getId()); detailItem.setPoItemRefrenceNumber(rdetailItem.getId()); detailItem = em.merge(detailItem); } } } } catch (Exception e) { logger.severe(e); } } } private OrderDetailStatus getOrderDetailStatusByNameAndLocationId(EntityManager em, String name, String locationId) { String queryStringDetailsStatus = "select s from OrderDetailStatus s where s.name =? and s.locationsId=? and s.status !='D'"; TypedQuery queryDetailsStatus = em.createQuery(queryStringDetailsStatus, OrderDetailStatus.class).setParameter(1, name).setParameter(2, locationId); return queryDetailsStatus.getSingleResult(); } private OrderDetailStatus getOrderDetailStatusById(EntityManager em, int id) { String queryStringDetailsStatus = "select s from OrderDetailStatus s where s.id=?"; TypedQuery queryDetailsStatus = em.createQuery(queryStringDetailsStatus, OrderDetailStatus.class).setParameter(1, id); return queryDetailsStatus.getSingleResult(); } public String sendEmailForAddUpdateRequestOrder(String requestOrderId, String locationId, HttpServletRequest httpRequest) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { // em = // LocalSchemaEntityManager.getInstance().getEntityManager(httpRequest, // sessionId); em = LocalSchemaEntityManager.getInstance().getEntityManager(httpRequest, null); // insert into order history ReceiptPDFFormat receiptPDFFormat = new ReceiptPDFFormat(); RequestOrder requestOrderheader = (RequestOrder) new CommonMethods().getObjectById("RequestOrder", em,RequestOrder.class, requestOrderId); Location supplier = (Location) new CommonMethods().getObjectById("Location", em,Location.class, requestOrderheader.getSupplierId()); // 0 because mail sending from dine in try { tx = em.getTransaction(); tx.begin(); Location foundLocation = null; if (locationId != null) { String queryString = "select l from Location l where " + "l.id ='" + locationId + "' and l.locationsId = '0' and l.locationsTypeId = '1'"; TypedQuery query = em.createQuery(queryString, Location.class); foundLocation = query.getSingleResult(); } String fileName = foundLocation.getName() + " Purchase Order.pdf"; String pdfData = receiptPDFFormat.createRequestOrderInvoicePDFString(em, httpRequest, requestOrderId, locationId, 2, "").toString(); String emailBody = receiptPDFFormat.createRequestOrderInvoiceBodyString().toString(); String emailFooter = receiptPDFFormat.createRequestOrderInvoiceFooterString(em, locationId).toString(); pdfData = pdfData.replace("", emailFooter + ""); EmailTemplateKeys.sendRequestOrderConfirmationEmailToUser(httpRequest, em, locationId, requestOrderheader.getUpdatedBy(), pdfData, EmailTemplateKeys.REQUEST_ORDER_CONFIRMATION, requestOrderheader.getId(), fileName, emailBody, emailFooter, supplier, 2, ""); tx.commit(); } catch (RuntimeException e) { if (tx != null && tx.isActive()) { tx.rollback(); } throw e; } return new JSONUtility(httpRequest).convertToJsonString(true); } catch (RuntimeException e) { if (tx != null && tx.isActive()) { tx.rollback(); } throw e; } finally { LocalSchemaEntityManager.getInstance().closeEntityManager(em); } } private String createAddress(Address address) { String add = ""; if (address != null) { if (address.getAddress1() != null && address.getAddress1().length() > 0) { add += address.getAddress1(); } if (address.getAddress2() != null && address.getAddress2().length() > 0) { add += "," + address.getAddress2(); } if (address.getCity() != null && address.getCity().length() > 0) { add += "," + address.getCity(); } if (address.getState() != null && address.getState().length() > 0) { add += "," + address.getState(); } if (address.getZip() != null && address.getZip().length() > 0) { add += "," + address.getZip(); } } return add; } public String getUsersToDiscountByUserIdAndDiscountCodeAndLocationIdWithoutValidation(HttpServletRequest httpRequest, EntityManager em, String userId, String dicountCode, String locationId, String discountId) throws IOException, InvalidSessionException { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(UsersToDiscount.class); Root r = criteria.from(UsersToDiscount.class); TypedQuery query = null; query = em.createQuery( criteria.select(r).where(builder.equal(r.get(UsersToDiscount_.usersId), userId), builder.equal(builder.lower(r.get(UsersToDiscount_.discountCode)), dicountCode.toLowerCase()), builder.equal(r.get(UsersToDiscount_.locationId), locationId), builder.equal(r.get(UsersToDiscount_.discountId), discountId))); return new JSONUtility(httpRequest).convertToJsonString(query.getSingleResult()); } public boolean updateUsersToDiscountNumberOfTimeDiscountUsed(HttpServletRequest httpRequest, EntityManager em, String userId, String dicountCode, String locationId, String discountId) throws IOException, InvalidSessionException { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(UsersToDiscount.class); Root r = criteria.from(UsersToDiscount.class); TypedQuery query = null; query = em.createQuery( criteria.select(r).where(builder.equal(r.get(UsersToDiscount_.usersId), userId), builder.equal(builder.lower(r.get(UsersToDiscount_.discountCode)), dicountCode.toLowerCase()), builder.equal(r.get(UsersToDiscount_.locationId), locationId), builder.equal(r.get(UsersToDiscount_.discountId), discountId))); UsersToDiscount usersToDiscount = query.getSingleResult(); if (usersToDiscount.getNumberOfTimeDiscountUsed() > 0) { usersToDiscount.setNumberOfTimeDiscountUsed(usersToDiscount.getNumberOfTimeDiscountUsed() - 1); } em.getTransaction().begin(); usersToDiscount = em.merge(usersToDiscount); em.getTransaction().commit(); return true; } public String getUsersToDiscountByUserIdAndDisCode(HttpServletRequest httpRequest, EntityManager em, String userId, String dicountCode, String locationId, String date, String discountId) throws IOException, InvalidSessionException { em.getTransaction().begin(); CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery criteria = builder.createQuery(UsersToDiscount.class); Root r = criteria.from(UsersToDiscount.class); TypedQuery query = null; if (discountId !=null) { query = em.createQuery( criteria.select(r).where(builder.equal(r.get(UsersToDiscount_.usersId), userId), builder.equal(builder.lower(r.get(UsersToDiscount_.discountCode)), dicountCode.toLowerCase()), builder.equal(r.get(UsersToDiscount_.locationId), locationId), builder.equal(r.get(UsersToDiscount_.discountId), discountId))); } else { /* * String queryStringConfig = * "select ci.id from discounts ci where ci.status not in ('D', 'I') and " * + "ci.coupan_code = ? and " + * " ci.is_auto_generated = 0 and ci.locations_id = ?"; */ // Remove is_auto_generated = 0 condition for task #46369 String queryStringConfig = "select ci.id from discounts ci where ci.status not in ('D', 'I') and " + " ci.is_coupan = 1 and " + "ci.coupan_code = ? and " + " ci.locations_id = ?"; Object discountlist = null; try { discountlist = em.createNativeQuery(queryStringConfig).setParameter(1, dicountCode).setParameter(2, locationId).getSingleResult(); } catch (Exception e) { // TODO: handle exception logger.severe(e); } if (discountlist != null) { Discount discount = (Discount) new CommonMethods().getObjectById("Discount", em,Discount.class, (String) discountlist); if (discount.getIsCoupan() == 0) { return (new NirvanaXPException( new NirvanaServiceErrorResponse(MessageConstants.ERROR_CODE_DISCOUNT_CODE_NOT_VALID_FOR_USER, MessageConstants.ERROR_MESSAGE_DISCOUNT_CODE_NOT_VALID_FOR_USER, null)) .toString()); } query = em.createQuery( criteria.select(r).where(builder.equal(r.get(UsersToDiscount_.usersId), userId), builder.equal(builder.lower(r.get(UsersToDiscount_.discountCode)), dicountCode.toLowerCase()), builder.equal(r.get(UsersToDiscount_.locationId), locationId), builder.equal(r.get(UsersToDiscount_.discountId), (int) discountlist))); } else { query = em.createQuery(criteria.select(r).where(builder.equal(r.get(UsersToDiscount_.usersId), userId), builder.equal(builder.lower(r.get(UsersToDiscount_.discountCode)), dicountCode.toLowerCase()), builder.equal(r.get(UsersToDiscount_.locationId), locationId))); /* * return (new NirvanaXPException(new * NirvanaServiceErrorResponse(MessageConstants. * ERROR_CODE_DISCOUNT_CODE_NOT_VALID_FOR_USER, * MessageConstants. * ERROR_MESSAGE_DISCOUNT_CODE_NOT_VALID_FOR_USER, * null)).toString()); */ } } /* * personCriteriaQuery.where(criteriaBuilder.like( * criteriaBuilder.upper(personRoot.get(Person_.description)), * "%"+filter.getDescription().toUpperCase()+"%")); */ UsersToDiscount usersToDiscount = null; try { usersToDiscount = query.getSingleResult(); } catch (Exception e) { // TODO: handle exception logger.severe(e); } if (usersToDiscount == null) { /* * String queryStringConfig = * "select ci.id from discounts ci where ci.status not in ('D', 'I') and " * + "ci.coupan_code = ? and " + " ci.is_auto_generated = 0 and " + * " ci.effective_end_date >= ? "; */ // Remove is_auto_generated = 0 condition for task #46369 String queryStringConfig = "select ci.id from discounts ci where ci.status not in ('D', 'I') and " + "ci.coupan_code = ? and " + " " + " ci.is_coupan = 1 and " + " ci.effective_end_date >= ? and locations_id='" + locationId+"'"; if (discountId !=null) { queryStringConfig = queryStringConfig + " and ci.id = " + discountId; } Object discountlist = null; try { discountlist = em.createNativeQuery(queryStringConfig).setParameter(1, dicountCode).setParameter(2, date).getSingleResult(); } catch (Exception e) { // TODO: handle exception logger.severe(e); } if (discountlist == null) { return (new NirvanaXPException( new NirvanaServiceErrorResponse(MessageConstants.ERROR_CODE_DISCOUNT_CODE_NOT_VALID_FOR_USER, MessageConstants.ERROR_MESSAGE_DISCOUNT_CODE_NOT_VALID_FOR_USER, null)) .toString()); } else { Discount discount = (Discount) new CommonMethods().getObjectById("Discount", em,Discount.class, (String) discountlist); if (discount.getIsAllCustomer() == 1) { if (discount.getIsCoupan() == 0) { return (new NirvanaXPException( new NirvanaServiceErrorResponse(MessageConstants.ERROR_CODE_DISCOUNT_CODE_NOT_VALID_FOR_USER, MessageConstants.ERROR_MESSAGE_DISCOUNT_CODE_NOT_VALID_FOR_USER, null)) .toString()); } usersToDiscount = new UsersToDiscount(); usersToDiscount.setCreated(new Date(new TimezoneTime().getGMTTimeInMilis())); usersToDiscount.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); usersToDiscount.setCreatedBy(userId); usersToDiscount.setUpdatedBy(userId); usersToDiscount.setDiscountId(discount.getId()); usersToDiscount.setNumberOfTimeDiscountUsed(0); usersToDiscount.setDiscountCode(dicountCode); usersToDiscount.setUsersId(userId); usersToDiscount.setLocationId(locationId); try { if(usersToDiscount.getId()==null) usersToDiscount.setId(new StoreForwardUtility().generateDynamicIntId(em, locationId, httpRequest, "users_to_discount")); } catch (Exception e) { logger.severe(e); } usersToDiscount = em.merge(usersToDiscount); DiscountsType discountType = (DiscountsType) new CommonMethods().getObjectById("DiscountsType", em,DiscountsType.class, discount.getDiscountsTypeId()); usersToDiscount.setDiscountType(discountType); usersToDiscount.setDiscount(discount); } else { return (new NirvanaXPException(new NirvanaServiceErrorResponse(MessageConstants.ERROR_CODE_DISCOUNT_CODE_NOT_VALID_FOR_ALL_CUSTOMER, MessageConstants.ERROR_MESSAGE_CODE_DISCOUNT_CODE_NOT_VALID_FOR_ALL_CUSTOMER, null)).toString()); } } } else { Discount discount = (Discount) new CommonMethods().getObjectById("Discount", em,Discount.class, usersToDiscount.getDiscountId()); if (discount.getIsCoupan() == 0) { return (new NirvanaXPException( new NirvanaServiceErrorResponse(MessageConstants.ERROR_CODE_DISCOUNT_CODE_NOT_VALID_FOR_USER, MessageConstants.ERROR_MESSAGE_DISCOUNT_CODE_NOT_VALID_FOR_USER, null)) .toString()); } DiscountsType discountType = (DiscountsType) new CommonMethods().getObjectById("DiscountsType", em,DiscountsType.class, discount.getDiscountsTypeId()); usersToDiscount.setDiscountType(discountType); usersToDiscount.setDiscount(discount); if (discount.getNumberOfTimeDiscountUsed() != -1) { if (!(usersToDiscount.getNumberOfTimeDiscountUsed() < discount.getNumberOfTimeDiscountUsed())) { return (new NirvanaXPException( new NirvanaServiceErrorResponse(MessageConstants.ERROR_CODE_DISCOUNT_CODE_ALREADY_USED_BY_USER, MessageConstants.ERROR_MESSAGE_DISCOUNT_CODE_ALREADY_USED_BY_USER, null)) .toString()); } } } em.getTransaction().commit(); return new JSONUtility(httpRequest).convertToJsonString(usersToDiscount); } public OrderHeader checkTransfer(HttpServletRequest httpRequest, EntityManager em, OrderTransferPacket orderPacket) throws NumberFormatException, NirvanaXPException, JsonGenerationException, JsonMappingException, IOException { OrderHeader order = new OrderManagementServiceBean().getOrderById(em, orderPacket.getOrderId()); order.setSessionKey(orderPacket.getIdOfSessionUsedByPacket()); OrderHeader orderHeader = new OrderManagementServiceBean().checkTransfer(httpRequest, em, order, orderPacket.getLocationId().trim(), orderPacket); if (orderHeader != null) { orderHeader = new OrderManagementServiceBean().getOrderById(em, orderHeader.getId()); } else { orderHeader = order; } OrderHeader orderHeaderForPush = getOrderHeaderWithMinimunRequiredDetails(orderHeader); orderPacket.setOrderHeader(orderHeaderForPush); orderPacket.setLocationId("" + orderHeader.getLocationsId()); sendPacketForBroadcast(httpRequest, orderPacket, POSNServiceOperations.OrderManagementService_update.name(), false); return orderHeader; } public StorageType addUpdateStorageType(EntityManager em, StorageType storageType) { try { if (storageType.getId() == null) { storageType.setCreated(new Date(new TimezoneTime().getGMTTimeInMilis())); storageType.setId(new StoreForwardUtility().generateUUID()); } else { StorageType storageType2 = (StorageType) new CommonMethods().getObjectById("StorageType", em,StorageType.class, storageType.getId()); if(storageType2!=null){ storageType.setCreated(storageType2.getCreated()); } } storageType.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); storageType = em.merge(storageType); return storageType; } catch (Exception e) { // TODO Auto-generated catch block logger.severe(e); } return null; } public StorageType deleteStorageType(EntityManager em, StorageType storageType) { try { storageType = (StorageType) new CommonMethods().getObjectById("StorageType", em,StorageType.class, storageType.getId()); storageType.setStatus("D"); storageType.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); storageType = em.merge(storageType); return storageType; } catch (Exception e) { // TODO Auto-generated catch block logger.severe(e); } return null; } public List getAllStorageType(EntityManager em) { try { String queryString = "select st from StorageType st where st.status != 'D'"; TypedQuery query = em.createQuery(queryString, StorageType.class); List resultSet = query.getResultList(); return resultSet; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /* * public OrderHeader addUpdateOrderDetailItemComment(HttpServletRequest * httpRequest,EntityManager em, OrderDetailItemPacket orderPacket) throws * NirvanaXPException, JsonGenerationException,JsonMappingException, * IOException { * * OrderDetailItem detailItem =(OrderDetailItem) new CommonMethods().getObjectById("OrderDetailItem", em,OrderDetailItem.class, * orderPacket.getOrderDetailItemId()); * detailItem.setComment(orderPacket.getComment()); * detailItem=em.merge(detailItem); OrderHeader orderHeader = new * OrderManagementServiceBean().getOrderById(em, * detailItem.getOrderHeaderId()); OrderHeader orderHeaderForPush = * getOrderHeaderWithMinimunRequiredDetails(orderHeader); * orderPacket.setOrderHeader(orderHeaderForPush); * sendPacketForBroadcast(httpRequest,orderPacket, * POSNServiceOperations.OrderManagementService_update.name(), false); * return orderHeader; } */ public UsersToDiscount updateUserToDiscount(UsersToDiscount discount, EntityManager em,String locationId,HttpServletRequest request) throws Exception { if (discount.getId() == null) { discount.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); discount.setCreated(new Date(new TimezoneTime().getGMTTimeInMilis())); discount.setId(new StoreForwardUtility().generateDynamicIntId(em, locationId, request, "users_to_discount")); discount = em.merge(discount); } else { UsersToDiscount toDiscount = em.find(UsersToDiscount.class, discount.getId()); discount.setCreated(toDiscount.getCreated()); discount.setUpdated(new Date(new TimezoneTime().getGMTTimeInMilis())); discount = em.merge(discount); } return discount; } } core/src/main/java/com/amplifyframework/datastore/DataStoreChannelEventName.java1-10 /* * Copyright 2020 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amplifyframework.datastore; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.amplifyframework.hub.HubCategory; import com.amplifyframework.hub.HubChannel; import com.amplifyframework.hub.HubEvent; import java.util.Objects; /** * An enumeration of the names of events relating the {@link DataStoreCategory}, * that are published via {@link HubCategory#publish(HubChannel, HubEvent)} on the * {@link HubChannel#DATASTORE} channel. */ public enum DataStoreChannelEventName { /** * An item in the local storage has been published to the cloud. * An event that uses this value for {@link HubEvent#getName()} will contain a model object * in the {@link HubEvent#getData()}. */ PUBLISHED_TO_CLOUD("published_to_cloud"), /** * A model was updated locally, from a model version that was received from the cloud. * An event that uses this value for {@link HubEvent#getName()} will contain a model object * in the {@link HubEvent#getData()}. */ RECEIVED_FROM_CLOUD("received_from_cloud"), /** * The remote synchonization processes started. */ REMOTE_SYNC_STARTED("remote_sync_started"), /** * The remote synchonization processes stopped. */ REMOTE_SYNC_STOPPED("remote_sync_stopped"), /** * Indicates that the network is active or not. * It is triggered on DataStore start and also every time the network status changes. */ NETWORK_STATUS("networkStatus"), /** * The websocket connection has been established and all the graphql subscriptions too. */ SUBSCRIPTIONS_ESTABLISHED("subscriptionsEstablished"), /** * The DataStore as a whole (not just the sync piece) is ready. At this point all data is available. */ READY("ready"); private final String hubEventName; /** * Enumerate the name of an event that is published on Hub, on the {@link HubChannel#DATASTORE} channel. * @param hubEventName The name of an event to use when creating an {@link HubEvent} */ DataStoreChannelEventName(@NonNull String hubEventName) { Objects.requireNonNull(hubEventName); this.hubEventName = hubEventName; } @NonNull @Override public String toString() { return hubEventName; } /** * Check if the provided string is one of the enumerated hub event names used by the * DataStore category. * @param possibleEventName Possibly, the name of a Hub event published by DataStore * @return The enumerated event name, if found * @throws IllegalArgumentException If the provided string is not a known event name */ @NonNull public static DataStoreChannelEventName fromString(@Nullable String possibleEventName) { for (DataStoreChannelEventName value : values()) { if (value.toString().equals(possibleEventName)) { return value; } } final String errorMessage = "DataStore category does not publish any Hub event with name = " + possibleEventName; throw new IllegalArgumentException(errorMessage); } } package cn.regionsoft.one.event; import cn.regionsoft.one.annotation.QuickEventListener; import cn.regionsoft.one.common.Logger; @QuickEventListener public class SampleQuickEventListener extends BaseEventListener { public static Logger logger = Logger.getLogger(SampleQuickEventListener.class); public SampleQuickEventListener() { } @Override public Object handleEvent(SampleQuickEventListener.Event event) { EventData eventData = event.getData(); return null; } public static class Event extends BaseEvent { private EventData data; @Override public EventData getData() { return data; } @Override public void setData(EventData data) { this.data = data; } } public static class EventData { public EventData() { } } } package totoye; import java.io.IOException; public class RunClass { boolean check = false; public RunClass(String url, String folder){ // TODO Auto-generated method stub try { //The command is the link or path where is located the program // Running the above command //String command = "javac -d "+folder+"\\classes "+url+""; String[]command = {"javac",url}; Runtime run = Runtime.getRuntime(); Process proc = run.exec(command); proc.waitFor(); int len; if((len = proc.getErrorStream().available()) > 0) { byte[] buf = new byte[len]; proc.getErrorStream().read(buf); System.err.println(new String(buf)); } check = true; } catch (IOException | InterruptedException e) { e.printStackTrace(); } } public boolean get() { return check; } } 0 package theInvoker.cards.items; import basemod.AutoAdd; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.monsters.AbstractMonster; import theInvoker.actions.FastAddTemporaryHPAction; import theInvoker.cards.AbstractInvokerCard; import theInvoker.characters.TheInvoker; import theInvoker.powers.EnergyPower; import theInvoker.powers.VenomPower; import static theInvoker.InvokerMod.makeCardPath; import static theInvoker.InvokerMod.makeID; @AutoAdd.Ignore public class FalconBlade extends AbstractInvokerCard { public static final String ID = makeID(FalconBlade.class.getSimpleName()); public static final String IMG = makeCardPath("Skill.png"); private static final CardRarity RARITY = CardRarity.SPECIAL; private static final CardTarget TARGET = CardTarget.SELF; private static final CardType TYPE = CardType.SKILL; public static final CardColor COLOR = TheInvoker.Enums.COLOR_GRAY; public static final int COST = SagesMask.COST * 2; private static final int MAGIC = SagesMask.MAGIC * 2; private static final int TEMP_HP = FluffyHat.MAGIC * 2; public FalconBlade() { super(ID, IMG, COST, TYPE, COLOR, RARITY, TARGET); this.magicNumber = MAGIC; } @Override public boolean canUpgrade() { return false; } @Override public void upgrade() {} @Override public void use(AbstractPlayer p, AbstractMonster m) { this.addToBot(new ApplyPowerAction(p, p, new EnergyPower(p, magicNumber), magicNumber)); this.addToBot(new FastAddTemporaryHPAction(AbstractDungeon.player, AbstractDungeon.player, TEMP_HP)); } } package handlingMouseEvents; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * This applet demonstrates how mouse events and mouse * motion events can be handled. * It lets the user draw boxes by dragging the mouse */ public class DrawBoxes extends JApplet { private int currentX = 0; private int currentY = 0; private int width = 0; private int height = 0; public void init() { // Add a mouse listener to this applet. addMouseListener(new MyMouseListener()); // Add a mouse motion listener to this applet. addMouseMotionListener(new MyMouseMotionListener()); } public void paint(Graphics g) { super.paint(g); g.drawRect(currentX, currentY, width, height); } private class MyMouseListener implements MouseListener { public void mousePressed(MouseEvent e) { // Get the mouse cursor coordinates currentX = e.getX(); currentY = e.getY(); } public void mouseClicked(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } } private class MyMouseMotionListener implements MouseMotionListener { public void mouseDragged(MouseEvent e) { // Calculate the size of hte recatangle width = e.getX() - currentX; height = e.getY() - currentY; // Repaint the window repaint(); } public void mouseMoved(MouseEvent e) { } } } src/main/java/com/fndef/plug/parser/xml/resolve/provider/RefProvider.java0 package com.fndef.plug.parser.xml.resolve.provider; import com.fndef.plug.Context; import com.fndef.plug.parser.xml.resolve.Resolvable; public class RefProvider implements Provider { private final String id; private final Context context; public RefProvider(String id, Context context) { this.id = id; this.context = context; } @Override public Object get() { return context.getById(id, Resolvable.class).resolve(); } } erasels/RoR-StS-ModRoRStS/src/main/java/riskOfSpire/relics/Lunar/Transcendence.java package riskOfSpire.relics.Lunar; import com.badlogic.gdx.math.MathUtils; import com.evacipated.cardcrawl.mod.stslib.actions.tempHp.AddTemporaryHPAction; import com.megacrit.cardcrawl.actions.common.RelicAboveCreatureAction; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.relics.AbstractRelic; import riskOfSpire.RiskOfSpire; import riskOfSpire.patches.relics.TranscendencePatches; import riskOfSpire.relics.Abstracts.StackableRelic; //Basically Bottled heart, thanks for your code, Kio public class Transcendence extends StackableRelic { public static final String ID = RiskOfSpire.makeID("Transcendence"); private static final float HP_BASE = 0.5f; private static final float HP_INCREMENTS = 0.25f; private int mhp; private int chp; public Transcendence() { super(ID, "Transcendence.png", RelicTier.SPECIAL, LandingSound.MAGICAL); isLunar = true; } @Override public String getUpdatedDescription() { return DESCRIPTIONS[0] + MathUtils.round(getVal()*100) + DESCRIPTIONS[1]; } @Override public void atBattleStart() { flash(); mhp = AbstractDungeon.player.maxHealth; chp = AbstractDungeon.player.currentHealth; AbstractDungeon.player.decreaseMaxHealth(AbstractDungeon.player.maxHealth - 1); AbstractDungeon.actionManager.addToTop(new AddTemporaryHPAction(AbstractDungeon.player, AbstractDungeon.player, MathUtils.floor(mhp*getVal()))); AbstractDungeon.actionManager.addToTop(new RelicAboveCreatureAction(AbstractDungeon.player, this)); } @Override public void onVictory() { AbstractDungeon.player.maxHealth = mhp+(AbstractDungeon.player.maxHealth-1); AbstractDungeon.player.currentHealth = chp; } @Override public void onEquip() { TranscendencePatches.TranscendenceField.hasTranscendence.set(AbstractDungeon.topPanel, true); } @Override public void onUnequip() { TranscendencePatches.TranscendenceField.hasTranscendence.set(AbstractDungeon.topPanel, false); } public float getVal() { return HP_BASE + (HP_INCREMENTS*(relicStack-1)); } @Override public void onLoad(Integer amt) { super.onLoad(amt); TranscendencePatches.TranscendenceField.hasTranscendence.set(AbstractDungeon.topPanel, true); } public AbstractRelic makeCopy() { return new Transcendence(); } }kingofzihua/spring-framework-learning-code100-1000 package com.linkedbear.spring.annotation.f_typefilter.animals; import com.linkedbear.spring.annotation.f_typefilter.anno.Animal; import org.springframework.stereotype.Component; @Component @Animal public class Cat { } backend/manager/modules/vdsbroker/src/main/java/org/ovirt/engine/core/vdsbroker/vdsbroker/VmBackupConfigVDSCommandBase.java package org.ovirt.engine.core.vdsbroker.vdsbroker; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.inject.Inject; import org.ovirt.engine.core.common.businessentities.StorageDomainStatic; import org.ovirt.engine.core.common.businessentities.VmCheckpoint; import org.ovirt.engine.core.common.businessentities.storage.DiskImage; import org.ovirt.engine.core.common.businessentities.storage.DiskType; import org.ovirt.engine.core.common.vdscommands.VmBackupVDSParameters; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.dao.StorageDomainStaticDao; import org.ovirt.engine.core.dao.VmCheckpointDao; public abstract class VmBackupConfigVDSCommandBase

extends VdsBrokerCommand

{ @Inject private VmCheckpointDao vmCheckpointDao; @Inject private StorageDomainStaticDao storageDomainStaticDao; private Set vmCheckpointDisksIds; public VmBackupConfigVDSCommandBase(P parameters) { super(parameters); } protected abstract String getDiskBackupMode(DiskImage diskImage); private HashMap[] createDisksMap(Guid toCheckpointId) { return getParameters().getVmBackup().getDisks().stream().map(diskImage -> { Map imageParams = new HashMap<>(); imageParams.put(VdsProperties.DomainId, diskImage.getStorageIds().get(0).toString()); imageParams.put(VdsProperties.ImageId, diskImage.getId().toString()); imageParams.put(VdsProperties.VolumeId, diskImage.getImageId().toString()); imageParams.put(VdsProperties.CHECKPOINT, isDiskInCheckpoint(diskImage.getImageId(), toCheckpointId)); String backupMode = getDiskBackupMode(diskImage); if (backupMode != null) { imageParams.put(VdsProperties.BACKUP_MODE, backupMode); } Map scratchDisksMap = getParameters().getScratchDisksMap(); if (scratchDisksMap != null && scratchDisksMap.containsKey(diskImage.getId())) { Map scratchDiskParams = new HashMap<>(); scratchDiskParams.put(VdsProperties.Path, scratchDisksMap.get(diskImage.getId())); StorageDomainStatic sourceDomain = storageDomainStaticDao.get(diskImage.getStorageIds().get(0)); DiskType diskType = sourceDomain.getStorageType().isBlockDomain() ? DiskType.Block : DiskType.File; scratchDiskParams.put(VdsProperties.Type, diskType.getName()); imageParams.put(VdsProperties.SCRATCH_DISK, scratchDiskParams); } return imageParams; }).toArray(HashMap[]::new); } protected Map createBackupConfig() { Guid fromCheckpointId = getParameters().getVmBackup().getFromCheckpointId(); Guid toCheckpointId = getParameters().getVmBackup().getToCheckpointId(); Map backupConfig = new HashMap<>(); backupConfig.put("backup_id", getParameters().getVmBackup().getId().toString()); backupConfig.put("disks", createDisksMap(toCheckpointId)); backupConfig.put("from_checkpoint_id", fromCheckpointId != null ? fromCheckpointId.toString() : null); backupConfig.put("to_checkpoint_id", toCheckpointId != null ? toCheckpointId.toString() : null); backupConfig.put("parent_checkpoint_id", getParentId()); backupConfig.put("require_consistency", getParameters().isRequireConsistency()); return backupConfig; } private boolean isDiskInCheckpoint(Guid diskImageId, Guid toCheckpointId) { return toCheckpointId != null && getVmCheckpointDisksIds(toCheckpointId).contains(diskImageId); } private Set getVmCheckpointDisksIds(Guid toCheckpointId) { if (vmCheckpointDisksIds == null) { vmCheckpointDisksIds = vmCheckpointDao.getDisksByCheckpointId(toCheckpointId).stream() .map(DiskImage::getImageId) .collect(Collectors.toSet()); } return vmCheckpointDisksIds; } private String getParentId() { Guid toCheckpointId = getParameters().getVmBackup().getToCheckpointId(); if (toCheckpointId != null) { VmCheckpoint toCheckpoint = vmCheckpointDao.get(toCheckpointId); if (toCheckpoint != null) { return toCheckpoint.getParentId() != null ? toCheckpoint.getParentId().toString() : null; } } return null; } } package btools.codec; import java.util.HashMap; import btools.util.ByteDataReader; import btools.util.IByteArrayUnifier; /** * MicroCache2 is the new format that uses statistical encoding and * is able to do access filtering and waypoint matching during encoding */ public final class MicroCache2 extends MicroCache { private int lonBase; private int latBase; private int cellsize; public MicroCache2( int size, byte[] databuffer, int lonIdx, int latIdx, int divisor ) { super( databuffer ); // sets ab=databuffer, aboffset=0 faid = new int[size]; fapos = new int[size]; this.size = 0; cellsize = 1000000 / divisor; lonBase = lonIdx*cellsize; latBase = latIdx*cellsize; } public byte[] readUnified( int len, IByteArrayUnifier u ) { byte[] b = u.unify( ab, aboffset, len ); aboffset += len; return b; } public MicroCache2( StatCoderContext bc, DataBuffers dataBuffers, int lonIdx, int latIdx, int divisor, TagValueValidator wayValidator, WaypointMatcher waypointMatcher ) { super( null ); cellsize = 1000000 / divisor; lonBase = lonIdx*cellsize; latBase = latIdx*cellsize; TagValueCoder wayTagCoder = new TagValueCoder( bc, dataBuffers, wayValidator ); TagValueCoder nodeTagCoder = new TagValueCoder( bc, dataBuffers, null ); NoisyDiffCoder nodeIdxDiff = new NoisyDiffCoder( bc ); NoisyDiffCoder nodeEleDiff = new NoisyDiffCoder( bc ); NoisyDiffCoder extLonDiff = new NoisyDiffCoder(bc); NoisyDiffCoder extLatDiff = new NoisyDiffCoder(bc); NoisyDiffCoder transEleDiff = new NoisyDiffCoder( bc ); size = bc.decodeNoisyNumber( 5 ); faid = size > dataBuffers.ibuf2.length ? new int[size] : dataBuffers.ibuf2; fapos = size > dataBuffers.ibuf3.length ? new int[size] : dataBuffers.ibuf3; int[] alon = size > dataBuffers.alon.length ? new int[size] : dataBuffers.alon; int[] alat = size > dataBuffers.alat.length ? new int[size] : dataBuffers.alat; if ( debug ) System.out.println( "*** decoding cache of size=" + size + " for lonIdx=" + lonIdx + " latIdx=" + latIdx ); bc.decodeSortedArray( faid, 0, size, 29, 0 ); for( int n = 0; n> 32); alat[n] = (int)(id64 & 0xffffffff); } int netdatasize = bc.decodeNoisyNumber( 10 ); ab = netdatasize > dataBuffers.bbuf1.length ? new byte[netdatasize] : dataBuffers.bbuf1; aboffset = 0; int[] validBits = new int[(size+31)>>5]; int finaldatasize = 0; LinkedListContainer reverseLinks = new LinkedListContainer( size, dataBuffers.ibuf1 ); int selev = 0; for( int n=0; n> 5 ] |= 1 << n; // mark dummy-node valid continue; // empty node escape (delta files only) } while( featureId != 0 ) { int bitsize = bc.decodeNoisyNumber( 5 ); if ( featureId == 2 ) // exceptions to turn-restriction { trExceptions = (short)bc.decodeBounded( 1023 ); } else if ( featureId == 1 ) // turn-restriction { writeBoolean( true ); writeShort( trExceptions ); // exceptions from previous feature trExceptions = 0; writeBoolean( bc.decodeBit() ); // isPositive writeInt( ilon + bc.decodeNoisyDiff( 10 ) ); // fromLon writeInt( ilat + bc.decodeNoisyDiff( 10 ) ); // fromLat writeInt( ilon + bc.decodeNoisyDiff( 10 ) ); // toLon writeInt( ilat + bc.decodeNoisyDiff( 10 ) ); // toLat } else { for( int i=0; i< bitsize; i++ ) bc.decodeBit(); // unknown feature, just skip } featureId = bc.decodeVarBits(); } writeBoolean( false ); selev += nodeEleDiff.decodeSignedValue(); writeShort( (short) selev ); TagValueWrapper nodeTags = nodeTagCoder.decodeTagValueSet(); writeVarBytes( nodeTags == null ? null : nodeTags.data ); int links = bc.decodeNoisyNumber( 1 ); if ( debug ) System.out.println( "*** decoding node " + ilon + "/" + ilat + " with links=" + links ); for( int li=0; li>= 2; } int lon32 = lonBase + dlon; int lat32 = latBase + dlat; return ((long)lon32)<<32 | lat32; } @Override public int shrinkId( long id64 ) { int lon32 = (int)(id64 >> 32); int lat32 = (int)(id64 & 0xffffffff); int dlon = lon32 - lonBase; int dlat = lat32 - latBase; int id32 = 0; for( int bm = 0x4000; bm > 0; bm >>= 1 ) { id32 <<= 2; if ( ( dlon & bm ) != 0 ) id32 |= 1; if ( ( dlat & bm ) != 0 ) id32 |= 2; } return id32; } @Override public boolean isInternal( int ilon, int ilat ) { return ilon >= lonBase && ilon < lonBase + cellsize && ilat >= latBase && ilat < latBase + cellsize; } @Override public int encodeMicroCache( byte[] buffer ) { HashMap idMap = new HashMap(); for( int n=0; n> 32); int ilat = (int)(id64 & 0xffffffff); if ( aboffset == aboffsetEnd ) { bc.encodeVarBits( 13 ); // empty node escape (delta files only) continue; } // write turn restrictions while( readBoolean() ) { short exceptions = readShort(); // except bikes, psv, ... if ( exceptions != 0 ) { bc.encodeVarBits( 2 ); // 2 = tr exceptions bc.encodeNoisyNumber( 10 , 5 ); // bit-count bc.encodeBounded( 1023 , exceptions & 1023 ); } bc.encodeVarBits( 1 ); // 1 = turn restriction bc.encodeNoisyNumber( restrictionBits.getNext(), 5 ); // bit-count using look-ahead fifo long b0 = bc.getWritingBitPosition(); bc.encodeBit( readBoolean() ); // isPositive bc.encodeNoisyDiff( readInt() - ilon, 10 ); // fromLon bc.encodeNoisyDiff( readInt() - ilat, 10 ); // fromLat bc.encodeNoisyDiff( readInt() - ilon, 10 ); // toLon bc.encodeNoisyDiff( readInt() - ilat, 10 ); // toLat restrictionBits.add( (int)( bc.getWritingBitPosition() - b0 ) ); } bc.encodeVarBits( 0 ); // end of extra data if ( dostats ) bc.assignBits( "extradata" ); int selev = readShort(); nodeEleDiff.encodeSignedValue( selev - lastSelev ); if ( dostats ) bc.assignBits( "nodeele" ); lastSelev = selev; nodeTagCoder.encodeTagValueSet( readVarBytes() ); if ( dostats ) bc.assignBits( "nodeTagIdx" ); int nlinks = linkCounts.getNext(); if ( dodebug ) System.out.println( "*** nlinks=" + nlinks ); bc.encodeNoisyNumber( nlinks, 1 ); if ( dostats ) bc.assignBits( "link-counts" ); nlinks = 0; while( hasMoreData() ) // loop over links { // read link data int startPointer = aboffset; int endPointer = getEndPointer(); int ilonlink = ilon + readVarLengthSigned(); int ilatlink = ilat + readVarLengthSigned(); int sizecode = readVarLengthUnsigned(); boolean isReverse = ( sizecode & 1 ) != 0; int descSize = sizecode >> 1; byte[] description = null; if ( descSize > 0 ) { description = new byte[descSize]; readFully( description ); } long link64 = ((long)ilonlink)<<32 | ilatlink; Integer idx = idMap.get( Long.valueOf( link64 ) ); boolean isInternal = idx != null; if ( isReverse && isInternal ) { if ( dodebug ) System.out.println( "*** NOT encoding link reverse=" + isReverse + " internal=" + isInternal ); netdatasize -= aboffset-startPointer; continue; // do not encode internal reverse links } if ( dodebug ) System.out.println( "*** encoding link reverse=" + isReverse + " internal=" + isInternal ); nlinks++; if ( isInternal ) { int nodeIdx = idx.intValue(); if ( dodebug ) System.out.println( "*** target nodeIdx=" + nodeIdx ); if ( nodeIdx == n ) throw new RuntimeException( "ups: self ref?" ); nodeIdxDiff.encodeSignedValue( nodeIdx - n ); if ( dostats ) bc.assignBits( "nodeIdx" ); } else { nodeIdxDiff.encodeSignedValue( 0 ); bc.encodeBit( isReverse ); extLonDiff.encodeSignedValue( ilonlink - ilon ); extLatDiff.encodeSignedValue( ilatlink - ilat ); if ( dostats ) bc.assignBits( "externalNode" ); } wayTagCoder.encodeTagValueSet( description ); if ( dostats ) bc.assignBits( "wayDescIdx" ); if ( !isReverse ) { byte[] geometry = readDataUntil( endPointer ); // write transition nodes int count = transCounts.getNext(); if ( dodebug ) System.out.println( "*** encoding geometry with count=" + count ); bc.encodeVarBits( count++ ); if ( dostats ) bc.assignBits( "transcount" ); int transcount = 0; if ( geometry != null ) { int dlon_remaining = ilonlink - ilon; int dlat_remaining = ilatlink - ilat; ByteDataReader r = new ByteDataReader( geometry ); while ( r.hasMoreData() ) { transcount++; int dlon = r.readVarLengthSigned(); int dlat = r.readVarLengthSigned(); bc.encodePredictedValue( dlon, dlon_remaining/count ); bc.encodePredictedValue( dlat, dlat_remaining/count ); dlon_remaining -= dlon; dlat_remaining -= dlat; if ( count > 1 ) count--; if ( dostats ) bc.assignBits( "transpos" ); transEleDiff.encodeSignedValue( r.readVarLengthSigned() ); if ( dostats ) bc.assignBits( "transele" ); } } transCounts.add( transcount ); } } linkCounts.add( nlinks ); } if ( pass == 3 ) { return bc.closeAndGetEncodedLength(); } } } } package Security; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.crypto.tink.JsonKeysetWriter; import com.google.crypto.tink.KeysetHandle; import com.google.crypto.tink.aead.AeadConfig; import com.google.crypto.tink.aead.AesGcmKeyManager; import com.google.crypto.tink.integration.gcpkms.GcpKmsClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Map; import java.util.Objects; public class EncryptionTools { public MongoDatabase db; public static final String credentials = Objects.requireNonNull(System.getenv("GOOGLE_APPLICATION_CREDENTIALS")); public static final String masterKeyUri = Objects.requireNonNull(System.getenv("MASTERKEYURI")); public EncryptionTools(MongoDatabase db) { this.db = db; } // Used for maintaining keys in mongodb, use with caution. public void generateAndUploadKeySet() throws GeneralSecurityException, IOException { AeadConfig.register(); MongoCollection keyHandles = this.db.getCollection("keys", Document.class); keyHandles.deleteMany(new Document()); KeysetHandle keysetHandle = KeysetHandle.generateNew(AesGcmKeyManager.aes256GcmTemplate()); String keysetFileName = "key.json"; keysetHandle.write( JsonKeysetWriter.withFile(new File(keysetFileName)), new GcpKmsClient().withCredentials(credentials).getAead(masterKeyUri)); ObjectMapper objectMapper = new ObjectMapper(); File file = new File("key.json"); Map map = objectMapper.readValue(file, new TypeReference>() {}); JSONObject keyJson = new JSONObject(map); // Document keyDocument = new Document("key.json"); keyHandles.insertOne(Document.parse(keyJson.toString())); } } /* * Copyright (c) 2014, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ /* * @test * @summary classpath mismatch between dump time and execution time * @requires vm.cds * @library /test/lib * @compile test-classes/Hello.java * @compile test-classes/C2.java * @run driver WrongClasspath */ import java.io.File; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.helpers.ClassFileInstaller; public class WrongClasspath { public static void main(String[] args) throws Exception { String appJar = JarBuilder.getOrCreateHelloJar(); // Dump an archive with a specified JAR file in -classpath TestCommon.testDump(appJar, TestCommon.list("Hello")); // Then try to execute the archive without -classpath -- it should fail TestCommon.run( /* "-cp", appJar, */ // <- uncomment this and the execution should succeed "-Xlog:cds", "Hello") .assertAbnormalExit("Unable to use shared archive", "shared class paths mismatch"); // Dump CDS archive with 2 jars: -cp hello.jar:jar2.jar // Run with 2 jars but the second jar doesn't exist: -cp hello.jarjar2.jarx // Shared class paths mismatch should be detected. String jar2 = ClassFileInstaller.writeJar("jar2.jar", "pkg/C2"); String jars = appJar + File.pathSeparator + jar2; TestCommon.testDump(jars, TestCommon.list("Hello", "pkg/C2")); TestCommon.run( "-cp", jars + "x", "Hello") .assertAbnormalExit("Unable to use shared archive", "shared class paths mismatch"); } } 10-100 /** * The contents of this file are subject to the license and copyright * detailed in the LICENSE and NOTICE files at the root of the source * tree and available online at * * http://www.dspace.org/license/ */ package org.dspace.subscriptions; /** * Extension of {@link SubscriptionEmailNotificationCli} for CLI. * * @author at atis.al * */ public class SubscriptionEmailNotificationCliScriptConfiguration extends SubscriptionEmailNotificationConfiguration { } package com.interview.codechef.ccdsap_2.leetcode.arrays.TopKElements; import java.util.PriorityQueue; import java.util.Scanner; public class ConnectRopes { //https://www.geeksforgeeks.org/connect-n-ropes-minimum-cost/ public static void main( String[] args ) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); while (t-- > 0) { int n = scanner.nextInt(); PriorityQueue pq = new PriorityQueue<>(( a, b ) -> b - a); while (n-- > 0) { pq.add(scanner.nextInt()); } long res = 0; while (pq.size() != 1) { int value = pq.poll(); int value1 = pq.poll(); pq.offer(value + value1); res += value + value1; } System.out.println(res); } } } package com.example.android.newsappstage2project; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; /** * Created by Emanuele on 21/12/2017. */ public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public ImageView imageView; public TextView titleView; public TextView sectionView; public TextView dateView; public TextView authorView; private OnEntryClickListener onEntryClickListener; /** * Create new Recycler View holder * * @param view the view used for the single news * @param onEntryClickListener a reference used to inform the adapter for the user click */ public RecyclerViewHolder(View view, OnEntryClickListener onEntryClickListener) { super(view); imageView = view.findViewById(R.id.main_image); titleView = view.findViewById(R.id.title_view); sectionView = view.findViewById(R.id.section_view); dateView = view.findViewById(R.id.date_view); authorView = view.findViewById(R.id.author_view); //set listener in the view group view.setOnClickListener(this); this.onEntryClickListener = onEntryClickListener; } @Override public void onClick(View view) { //inform the adapter for the user click if (onEntryClickListener != null) { onEntryClickListener.onEntryClick(view, getLayoutPosition()); } } /** * Interface for the command pattern used to handle the user click */ public interface OnEntryClickListener { void onEntryClick(View view, int position); } } package ru.job4j.start; //Данный класс использует StubInput , который мы будем использовать в качестве тестов import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /**StartUITest.**/ public class StartUITest { /*** @param args **first parameter***/ public static void main(String[] args) { //в качестве параметра мы можем передавать любой обьект который реализует интерфейс input Input input = new StubInput(new String[] {"create stub task"}); Tracker tracker = new Tracker(); new StartUIMain(input, tracker).init(); } /*** @Test**/ @Test public void addItemTest() { Tracker tracker = new Tracker(); // создаём Tracker Input input = new StubInput(new String[]{"0", "test name", "desc", "6"}); //создаём StubInput с последовательностью действий new StartUIMain(input, tracker).init(); // создаём StartUI и вызываем метод init() assertThat(tracker.getAll()[0].getName(), is("test name")); // проверяем, что нулевой элемент массива в трекере содержит имя, введённое при эмуляции. } /*** @Test**/ @Test public void editItemTest() { // создаём Tracker Tracker tracker = new Tracker(); //Напрямую добавляем заявку Item item = tracker.add(new Item()); //создаём StubInput с последовательностью действий Input input = new StubInput(new String[]{"2", item.getId(), "test name", "desc", "6"}); // создаём StartUI и вызываем метод init() new StartUIMain(input, tracker).init(); // проверяем, что нулевой элемент массива в трекере содержит имя, введённое при эмуляции. assertThat(tracker.findById(item.getId()).getName(), is("test name")); } /*** @Test**/ @Test public void deleteItemTest() { Tracker tracker = new Tracker(); Item item1 = tracker.add(new Item("test1", "testDescription", 123L)); Item item2 = tracker.add(new Item("test2", "test2Description", 123L)); Item item3 = tracker.add(new Item("test3", "test3Description", 123L)); Input input = new StubInput(new String[]{"3", item1.getId(), "6"}); tracker.delete(item1); Item[] result = tracker.getAll(); Item[] expect = {item2, item3}; new StartUIMain(input, tracker).init(); assertThat(result, is(expect)); } /*** @Test**/ @Test public void findItemByNameTest() { Tracker tracker = new Tracker(); Item item1 = tracker.add(new Item("test1", "1testDescription", 123L)); Item item2 = tracker.add(new Item("test2", "2testDescription", 123L)); Item item3 = tracker.add(new Item("test1", "3testDescription", 123L)); Input input = new StubInput(new String[]{"5", item1.getName(), "6"}); Item[] result = tracker.findByName("test1"); Item[] expect = {item1, item3}; new StartUIMain(input, tracker).init(); assertThat(result, is(expect)); } /*** @Test**/ @Test public void findItemById() { Tracker tracker = new Tracker(); Item item1 = tracker.add(new Item("test1", "1testDescription", 123L)); Item item2 = tracker.add(new Item("test2", "2testDescription", 123L)); Item item3 = tracker.add(new Item("test3", "3testDescription", 123L)); Input input = new StubInput(new String[]{"4", item1.getId(), "6"}); Item result = tracker.findById(item1.getId()); Item expect = item1; new StartUIMain(input, tracker).init(); assertThat(result, is(expect)); } /*** @Test**/ @Test public void showAllItem() { Tracker tracker = new Tracker(); Item item1 = tracker.add(new Item("test1", "testDescription", 123L)); Item item2 = tracker.add(new Item("test2", "test2Description", 123L)); Item item3 = tracker.add(new Item("test3", "test3Description", 123L)); Input input = new StubInput(new String[]{"1", "6"}); Item[] result = tracker.getAll(); Item[] expect = {item1, item2, item3}; new StartUIMain(input, tracker).init(); assertThat(result, is(expect)); } } 0 package models; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class AnimalSightingTest { @BeforeEach void setUp() throws Exception{ } @AfterEach void tearDown() throws Exception{ } @Test void GetAndInstantiatesAllObjectsTrueAndCorrectly() { AnimalSighting testSighting = setupSighting(); assertTrue(testSighting instanceof AnimalSighting); } @Test void GetNameInstantiatesCorrectlyWithStringReturn_true() { AnimalSighting testSighting = setupSighting(); assertEquals("Lion", testSighting.getName()); } @Test void GetLocationOfAnimalSpotted() { AnimalSighting testSighting = setupSighting(); assertEquals("Zone A", testSighting.getLocation()); } @Test void GetRangerNameInstantiatesCorrectly() { AnimalSighting testSighting = setupSighting(); assertEquals("Robb", testSighting.getAnimalRangerName()); } @Test void GetHealthOfSpottedAnimal() { AnimalSighting testSighting = setupSighting(); assertEquals("Okay", testSighting.getHealth()); } @Test void GetAgeOfAnimalSpotted () { AnimalSighting testSighting = setupSighting(); assertEquals("Newborn", testSighting.getAge()); } @Test void GetSpeciesOfAnimalInstantiatesCorrectly() { AnimalSighting testSighting = setupSighting(); assertEquals("Endangered", testSighting.getSpecies()); } public AnimalSighting setupSighting() { return new AnimalSighting("Robb", "Lion", "Okay", "Newborn", "Endangered", "Zone A"); } }/******************************************************************************* * (c) Copyright 2014 Hewlett-Packard Development Company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * *******************************************************************************/ package org.openscore.content.httpclient.build.auth; import org.apache.http.client.config.AuthSchemes; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.NTCredentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.junit.Test; import org.openscore.content.httpclient.build.auth.AuthTypes; import org.openscore.content.httpclient.build.auth.CredentialsProviderBuilder; import static junit.framework.Assert.assertEquals; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; /** * Created with IntelliJ IDEA. * User: tusaa * Date: 7/2/14 */ public class CredentialsProviderBuilderTest { @Test public void createNtlmCredentialsProvider() { CredentialsProvider credentialsProvider = getCredentialsProvider(AuthSchemes.NTLM); Credentials credentials = credentialsProvider.getCredentials(new AuthScope("host", 80)); assertThat(credentials, instanceOf(NTCredentials.class)); NTCredentials ntCredentials = (NTCredentials) credentials; assertEquals("DOMAIN", ntCredentials.getDomain()); assertEquals("HOST", ntCredentials.getWorkstation()); assertEquals("pass", ntCredentials.getPassword()); Credentials proxyCredentials = credentialsProvider.getCredentials(new AuthScope("proxy", 8080)); assertThat(proxyCredentials, instanceOf(UsernamePasswordCredentials.class)); UsernamePasswordCredentials userCredentials = (UsernamePasswordCredentials) proxyCredentials; assertEquals("proxyUsername", userCredentials.getUserName()); } @Test public void createKerberosCredentialsProvider() { CredentialsProvider credentialsProvider = getCredentialsProvider(AuthSchemes.KERBEROS); Credentials credentials = credentialsProvider.getCredentials(new AuthScope("host", 80)); assertThat(credentials, instanceOf(Credentials.class)); } @Test public void createDefaultCredentialsProvider() { CredentialsProvider credentialsProvider = getCredentialsProvider(""); Credentials credentials = credentialsProvider.getCredentials(new AuthScope("host", 80)); assertThat(credentials, instanceOf(UsernamePasswordCredentials.class)); UsernamePasswordCredentials userCredentials = (UsernamePasswordCredentials) credentials; assertEquals("pass", userCredentials.getPassword()); } private CredentialsProvider getCredentialsProvider(String authType) { AuthTypes authTypes = new AuthTypes(authType); CredentialsProviderBuilder builder = new CredentialsProviderBuilder() .setAuthTypes(authTypes) .setUsername("DOMAIN\\username") .setPassword("") .setHost("host") .setPort("80") .setProxyHost("proxy") .setProxyPort("8080") .setProxyPassword("") .setProxyUsername("proxyUsername"); return builder.buildCredentialsProvider(); } } /* * 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.jackrabbit.oak.plugins.document; import java.util.ArrayList; import java.util.List; import com.google.common.collect.Iterables; import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore; import org.junit.Test; import static com.google.common.collect.Iterables.all; import static org.apache.jackrabbit.oak.plugins.document.TestUtils.IS_LAST_REV_UPDATE; import static org.junit.Assert.assertTrue; /** * Tests related to background write operation in DocumentNodeStore. */ public class BackgroundWriteTest { @Test // OAK-1190 public void limitMultiUpdate() { DocumentMK mk = new DocumentMK.Builder().setDocumentStore( new TestStore()).setAsyncDelay(0).open(); List paths = new ArrayList(); StringBuilder sb = new StringBuilder(); for (int i = 0; paths.size() < UnsavedModifications.BACKGROUND_MULTI_UPDATE_LIMIT * 2; i++) { String child = "node-" + i; sb.append("+\"").append(child).append("\":{}"); paths.add("/" + child); for (int j = 0; j < 1000; j++) { String p = child + "/node-" + j; paths.add("/" + p); sb.append("+\"").append(p).append("\":{}"); } } mk.commit("/", sb.toString(), null, null); mk.runBackgroundOperations(); Revision r = mk.getNodeStore().newRevision(); UnsavedModifications pending = mk.getNodeStore().getPendingModifications(); pending.put(Path.ROOT, r); for (String p : paths) { pending.put(Path.fromString(p), r); } mk.runBackgroundOperations(); mk.dispose(); } private static final class TestStore extends MemoryDocumentStore { @Override public List createOrUpdate(Collection collection, List updateOps) { if (all(updateOps, IS_LAST_REV_UPDATE)) { assertTrue(updateOps.size() <= UnsavedModifications.BACKGROUND_MULTI_UPDATE_LIMIT); } return super.createOrUpdate(collection, updateOps); } } } package dev.eastar.operaxinterceptor.event; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class OperaXEventTest { @Test public void sendTest() { OperaXEventObservable.notify(OperaXEvents.Exited); } } package com.java.study.answer.zuo.dadvanced.advanced_class_01; public class Code_01_Palindrome_Number { public static boolean isPalindrome(int n) { if (n < 0) { return false; } int help = 1; while (n / help >= 10) { help *= 10; } while (n != 0) { if (n / help != n % 10) { return false; } n = (n % help) / 10; help /= 100; } return true; } } java/org.msscf.msscf.v2_13.cfsec.CFSecRam/src/main/java/org/msscf/msscf/v2_13/cfsec/CFSecRam/CFSecRamISOLangTable.java // Description: Java 11 in-memory RAM DbIO implementation for ISOLang. /* * org.msscf.msscf.CFSec * * Copyright (c) 2020 * * MSS Code Factory CFSec 2.13 Security Essentials * * Copyright 2020-2021 * * 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. * * Manufactured by MSS Code Factory 2.12 */ package org.msscf.msscf.v2_13.cfsec.CFSecRam; import java.math.*; import java.sql.*; import java.text.*; import java.util.*; import org.apache.commons.codec.binary.Base64; import org.msscf.msscf.v2_13.cflib.CFLib.*; import org.msscf.msscf.v2_13.cfsec.CFSec.*; import org.msscf.msscf.v2_13.cfsec.CFSecObj.*; import org.msscf.msscf.v2_13.cfsec.CFSecObj.*; /* * CFSecRamISOLangTable in-memory RAM DbIO implementation * for ISOLang. */ public class CFSecRamISOLangTable implements ICFSecISOLangTable { private ICFSecSchema schema; private Map< CFSecISOLangPKey, CFSecISOLangBuff > dictByPKey = new HashMap< CFSecISOLangPKey, CFSecISOLangBuff >(); private Map< CFSecISOLangByCode3IdxKey, CFSecISOLangBuff > dictByCode3Idx = new HashMap< CFSecISOLangByCode3IdxKey, CFSecISOLangBuff >(); private Map< CFSecISOLangByCode2IdxKey, Map< CFSecISOLangPKey, CFSecISOLangBuff >> dictByCode2Idx = new HashMap< CFSecISOLangByCode2IdxKey, Map< CFSecISOLangPKey, CFSecISOLangBuff >>(); public CFSecRamISOLangTable( ICFSecSchema argSchema ) { schema = argSchema; } public void createISOLang( CFSecAuthorization Authorization, CFSecISOLangBuff Buff ) { final String S_ProcName = "createISOLang"; CFSecISOLangPKey pkey = schema.getFactoryISOLang().newPKey(); pkey.setRequiredISOLangId( schema.nextISOLangIdGen() ); Buff.setRequiredISOLangId( pkey.getRequiredISOLangId() ); CFSecISOLangByCode3IdxKey keyCode3Idx = schema.getFactoryISOLang().newCode3IdxKey(); keyCode3Idx.setRequiredISO6392Code( Buff.getRequiredISO6392Code() ); CFSecISOLangByCode2IdxKey keyCode2Idx = schema.getFactoryISOLang().newCode2IdxKey(); keyCode2Idx.setOptionalISO6391Code( Buff.getOptionalISO6391Code() ); // Validate unique indexes if( dictByPKey.containsKey( pkey ) ) { throw new CFLibPrimaryKeyNotNewException( getClass(), S_ProcName, pkey ); } if( dictByCode3Idx.containsKey( keyCode3Idx ) ) { throw new CFLibUniqueIndexViolationException( getClass(), S_ProcName, "ISOLang6392Idx", keyCode3Idx ); } // Validate foreign keys // Proceed with adding the new record dictByPKey.put( pkey, Buff ); dictByCode3Idx.put( keyCode3Idx, Buff ); Map< CFSecISOLangPKey, CFSecISOLangBuff > subdictCode2Idx; if( dictByCode2Idx.containsKey( keyCode2Idx ) ) { subdictCode2Idx = dictByCode2Idx.get( keyCode2Idx ); } else { subdictCode2Idx = new HashMap< CFSecISOLangPKey, CFSecISOLangBuff >(); dictByCode2Idx.put( keyCode2Idx, subdictCode2Idx ); } subdictCode2Idx.put( pkey, Buff ); } public CFSecISOLangBuff readDerived( CFSecAuthorization Authorization, CFSecISOLangPKey PKey ) { final String S_ProcName = "CFSecRamISOLang.readDerived"; CFSecISOLangPKey key = schema.getFactoryISOLang().newPKey(); key.setRequiredISOLangId( PKey.getRequiredISOLangId() ); CFSecISOLangBuff buff; if( dictByPKey.containsKey( key ) ) { buff = dictByPKey.get( key ); } else { buff = null; } return( buff ); } public CFSecISOLangBuff lockDerived( CFSecAuthorization Authorization, CFSecISOLangPKey PKey ) { final String S_ProcName = "CFSecRamISOLang.readDerived"; CFSecISOLangPKey key = schema.getFactoryISOLang().newPKey(); key.setRequiredISOLangId( PKey.getRequiredISOLangId() ); CFSecISOLangBuff buff; if( dictByPKey.containsKey( key ) ) { buff = dictByPKey.get( key ); } else { buff = null; } return( buff ); } public CFSecISOLangBuff[] readAllDerived( CFSecAuthorization Authorization ) { final String S_ProcName = "CFSecRamISOLang.readAllDerived"; CFSecISOLangBuff[] retList = new CFSecISOLangBuff[ dictByPKey.values().size() ]; Iterator< CFSecISOLangBuff > iter = dictByPKey.values().iterator(); int idx = 0; while( iter.hasNext() ) { retList[ idx++ ] = iter.next(); } return( retList ); } public CFSecISOLangBuff readDerivedByCode3Idx( CFSecAuthorization Authorization, String ISO6392Code ) { final String S_ProcName = "CFSecRamISOLang.readDerivedByCode3Idx"; CFSecISOLangByCode3IdxKey key = schema.getFactoryISOLang().newCode3IdxKey(); key.setRequiredISO6392Code( ISO6392Code ); CFSecISOLangBuff buff; if( dictByCode3Idx.containsKey( key ) ) { buff = dictByCode3Idx.get( key ); } else { buff = null; } return( buff ); } public CFSecISOLangBuff[] readDerivedByCode2Idx( CFSecAuthorization Authorization, String ISO6391Code ) { final String S_ProcName = "CFSecRamISOLang.readDerivedByCode2Idx"; CFSecISOLangByCode2IdxKey key = schema.getFactoryISOLang().newCode2IdxKey(); key.setOptionalISO6391Code( ISO6391Code ); CFSecISOLangBuff[] recArray; if( dictByCode2Idx.containsKey( key ) ) { Map< CFSecISOLangPKey, CFSecISOLangBuff > subdictCode2Idx = dictByCode2Idx.get( key ); recArray = new CFSecISOLangBuff[ subdictCode2Idx.size() ]; Iterator< CFSecISOLangBuff > iter = subdictCode2Idx.values().iterator(); int idx = 0; while( iter.hasNext() ) { recArray[ idx++ ] = iter.next(); } } else { Map< CFSecISOLangPKey, CFSecISOLangBuff > subdictCode2Idx = new HashMap< CFSecISOLangPKey, CFSecISOLangBuff >(); dictByCode2Idx.put( key, subdictCode2Idx ); recArray = new CFSecISOLangBuff[0]; } return( recArray ); } public CFSecISOLangBuff readDerivedByIdIdx( CFSecAuthorization Authorization, short ISOLangId ) { final String S_ProcName = "CFSecRamISOLang.readDerivedByIdIdx() "; CFSecISOLangPKey key = schema.getFactoryISOLang().newPKey(); key.setRequiredISOLangId( ISOLangId ); CFSecISOLangBuff buff; if( dictByPKey.containsKey( key ) ) { buff = dictByPKey.get( key ); } else { buff = null; } return( buff ); } public CFSecISOLangBuff readBuff( CFSecAuthorization Authorization, CFSecISOLangPKey PKey ) { final String S_ProcName = "CFSecRamISOLang.readBuff"; CFSecISOLangBuff buff = readDerived( Authorization, PKey ); if( ( buff != null ) && ( ! buff.getClassCode().equals( "a007" ) ) ) { buff = null; } return( buff ); } public CFSecISOLangBuff lockBuff( CFSecAuthorization Authorization, CFSecISOLangPKey PKey ) { final String S_ProcName = "lockBuff"; CFSecISOLangBuff buff = readDerived( Authorization, PKey ); if( ( buff != null ) && ( ! buff.getClassCode().equals( "a007" ) ) ) { buff = null; } return( buff ); } public CFSecISOLangBuff[] readAllBuff( CFSecAuthorization Authorization ) { final String S_ProcName = "CFSecRamISOLang.readAllBuff"; CFSecISOLangBuff buff; ArrayList filteredList = new ArrayList(); CFSecISOLangBuff[] buffList = readAllDerived( Authorization ); for( int idx = 0; idx < buffList.length; idx ++ ) { buff = buffList[idx]; if( ( buff != null ) && buff.getClassCode().equals( "a007" ) ) { filteredList.add( buff ); } } return( filteredList.toArray( new CFSecISOLangBuff[0] ) ); } public CFSecISOLangBuff readBuffByIdIdx( CFSecAuthorization Authorization, short ISOLangId ) { final String S_ProcName = "CFSecRamISOLang.readBuffByIdIdx() "; CFSecISOLangBuff buff = readDerivedByIdIdx( Authorization, ISOLangId ); if( ( buff != null ) && buff.getClassCode().equals( "a007" ) ) { return( (CFSecISOLangBuff)buff ); } else { return( null ); } } public CFSecISOLangBuff readBuffByCode3Idx( CFSecAuthorization Authorization, String ISO6392Code ) { final String S_ProcName = "CFSecRamISOLang.readBuffByCode3Idx() "; CFSecISOLangBuff buff = readDerivedByCode3Idx( Authorization, ISO6392Code ); if( ( buff != null ) && buff.getClassCode().equals( "a007" ) ) { return( (CFSecISOLangBuff)buff ); } else { return( null ); } } public CFSecISOLangBuff[] readBuffByCode2Idx( CFSecAuthorization Authorization, String ISO6391Code ) { final String S_ProcName = "CFSecRamISOLang.readBuffByCode2Idx() "; CFSecISOLangBuff buff; ArrayList filteredList = new ArrayList(); CFSecISOLangBuff[] buffList = readDerivedByCode2Idx( Authorization, ISO6391Code ); for( int idx = 0; idx < buffList.length; idx ++ ) { buff = buffList[idx]; if( ( buff != null ) && buff.getClassCode().equals( "a007" ) ) { filteredList.add( (CFSecISOLangBuff)buff ); } } return( filteredList.toArray( new CFSecISOLangBuff[0] ) ); } public void updateISOLang( CFSecAuthorization Authorization, CFSecISOLangBuff Buff ) { CFSecISOLangPKey pkey = schema.getFactoryISOLang().newPKey(); pkey.setRequiredISOLangId( Buff.getRequiredISOLangId() ); CFSecISOLangBuff existing = dictByPKey.get( pkey ); if( existing == null ) { throw new CFLibStaleCacheDetectedException( getClass(), "updateISOLang", "Existing record not found", "ISOLang", pkey ); } if( existing.getRequiredRevision() != Buff.getRequiredRevision() ) { throw new CFLibCollisionDetectedException( getClass(), "updateISOLang", pkey ); } Buff.setRequiredRevision( Buff.getRequiredRevision() + 1 ); CFSecISOLangByCode3IdxKey existingKeyCode3Idx = schema.getFactoryISOLang().newCode3IdxKey(); existingKeyCode3Idx.setRequiredISO6392Code( existing.getRequiredISO6392Code() ); CFSecISOLangByCode3IdxKey newKeyCode3Idx = schema.getFactoryISOLang().newCode3IdxKey(); newKeyCode3Idx.setRequiredISO6392Code( Buff.getRequiredISO6392Code() ); CFSecISOLangByCode2IdxKey existingKeyCode2Idx = schema.getFactoryISOLang().newCode2IdxKey(); existingKeyCode2Idx.setOptionalISO6391Code( existing.getOptionalISO6391Code() ); CFSecISOLangByCode2IdxKey newKeyCode2Idx = schema.getFactoryISOLang().newCode2IdxKey(); newKeyCode2Idx.setOptionalISO6391Code( Buff.getOptionalISO6391Code() ); // Check unique indexes if( ! existingKeyCode3Idx.equals( newKeyCode3Idx ) ) { if( dictByCode3Idx.containsKey( newKeyCode3Idx ) ) { throw new CFLibUniqueIndexViolationException( getClass(), "updateISOLang", "ISOLang6392Idx", newKeyCode3Idx ); } } // Validate foreign keys // Update is valid Map< CFSecISOLangPKey, CFSecISOLangBuff > subdict; dictByPKey.remove( pkey ); dictByPKey.put( pkey, Buff ); dictByCode3Idx.remove( existingKeyCode3Idx ); dictByCode3Idx.put( newKeyCode3Idx, Buff ); subdict = dictByCode2Idx.get( existingKeyCode2Idx ); if( subdict != null ) { subdict.remove( pkey ); } if( dictByCode2Idx.containsKey( newKeyCode2Idx ) ) { subdict = dictByCode2Idx.get( newKeyCode2Idx ); } else { subdict = new HashMap< CFSecISOLangPKey, CFSecISOLangBuff >(); dictByCode2Idx.put( newKeyCode2Idx, subdict ); } subdict.put( pkey, Buff ); } public void deleteISOLang( CFSecAuthorization Authorization, CFSecISOLangBuff Buff ) { final String S_ProcName = "CFSecRamISOLangTable.deleteISOLang() "; String classCode; CFSecISOLangPKey pkey = schema.getFactoryISOLang().newPKey(); pkey.setRequiredISOLangId( Buff.getRequiredISOLangId() ); CFSecISOLangBuff existing = dictByPKey.get( pkey ); if( existing == null ) { return; } if( existing.getRequiredRevision() != Buff.getRequiredRevision() ) { throw new CFLibCollisionDetectedException( getClass(), "deleteISOLang", pkey ); } // Short circuit self-referential code to prevent stack overflows Object arrCheckISOLangCountries[] = schema.getTableISOCtryLang().readDerivedByLangIdx( Authorization, existing.getRequiredISOLangId() ); if( arrCheckISOLangCountries.length > 0 ) { schema.getTableISOCtryLang().deleteISOCtryLangByLangIdx( Authorization, existing.getRequiredISOLangId() ); } CFSecISOLangByCode3IdxKey keyCode3Idx = schema.getFactoryISOLang().newCode3IdxKey(); keyCode3Idx.setRequiredISO6392Code( existing.getRequiredISO6392Code() ); CFSecISOLangByCode2IdxKey keyCode2Idx = schema.getFactoryISOLang().newCode2IdxKey(); keyCode2Idx.setOptionalISO6391Code( existing.getOptionalISO6391Code() ); // Validate reverse foreign keys // Delete is valid Map< CFSecISOLangPKey, CFSecISOLangBuff > subdict; dictByPKey.remove( pkey ); dictByCode3Idx.remove( keyCode3Idx ); subdict = dictByCode2Idx.get( keyCode2Idx ); subdict.remove( pkey ); } public void deleteISOLangByIdIdx( CFSecAuthorization Authorization, short argISOLangId ) { CFSecISOLangPKey key = schema.getFactoryISOLang().newPKey(); key.setRequiredISOLangId( argISOLangId ); deleteISOLangByIdIdx( Authorization, key ); } public void deleteISOLangByIdIdx( CFSecAuthorization Authorization, CFSecISOLangPKey argKey ) { boolean anyNotNull = false; anyNotNull = true; if( ! anyNotNull ) { return; } CFSecISOLangBuff cur; LinkedList matchSet = new LinkedList(); Iterator values = dictByPKey.values().iterator(); while( values.hasNext() ) { cur = values.next(); if( argKey.equals( cur ) ) { matchSet.add( cur ); } } Iterator iterMatch = matchSet.iterator(); while( iterMatch.hasNext() ) { cur = iterMatch.next(); cur = schema.getTableISOLang().readDerivedByIdIdx( Authorization, cur.getRequiredISOLangId() ); deleteISOLang( Authorization, cur ); } } public void deleteISOLangByCode3Idx( CFSecAuthorization Authorization, String argISO6392Code ) { CFSecISOLangByCode3IdxKey key = schema.getFactoryISOLang().newCode3IdxKey(); key.setRequiredISO6392Code( argISO6392Code ); deleteISOLangByCode3Idx( Authorization, key ); } public void deleteISOLangByCode3Idx( CFSecAuthorization Authorization, CFSecISOLangByCode3IdxKey argKey ) { CFSecISOLangBuff cur; boolean anyNotNull = false; anyNotNull = true; if( ! anyNotNull ) { return; } LinkedList matchSet = new LinkedList(); Iterator values = dictByPKey.values().iterator(); while( values.hasNext() ) { cur = values.next(); if( argKey.equals( cur ) ) { matchSet.add( cur ); } } Iterator iterMatch = matchSet.iterator(); while( iterMatch.hasNext() ) { cur = iterMatch.next(); cur = schema.getTableISOLang().readDerivedByIdIdx( Authorization, cur.getRequiredISOLangId() ); deleteISOLang( Authorization, cur ); } } public void deleteISOLangByCode2Idx( CFSecAuthorization Authorization, String argISO6391Code ) { CFSecISOLangByCode2IdxKey key = schema.getFactoryISOLang().newCode2IdxKey(); key.setOptionalISO6391Code( argISO6391Code ); deleteISOLangByCode2Idx( Authorization, key ); } public void deleteISOLangByCode2Idx( CFSecAuthorization Authorization, CFSecISOLangByCode2IdxKey argKey ) { CFSecISOLangBuff cur; boolean anyNotNull = false; if( argKey.getOptionalISO6391Code() != null ) { anyNotNull = true; } if( ! anyNotNull ) { return; } LinkedList matchSet = new LinkedList(); Iterator values = dictByPKey.values().iterator(); while( values.hasNext() ) { cur = values.next(); if( argKey.equals( cur ) ) { matchSet.add( cur ); } } Iterator iterMatch = matchSet.iterator(); while( iterMatch.hasNext() ) { cur = iterMatch.next(); cur = schema.getTableISOLang().readDerivedByIdIdx( Authorization, cur.getRequiredISOLangId() ); deleteISOLang( Authorization, cur ); } } public void releasePreparedStatements() { } } /* * 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.facebook.presto.spi; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.block.BlockBuilder; import com.facebook.presto.spi.block.BlockBuilderStatus; import com.facebook.presto.spi.type.Type; import java.util.ArrayList; import java.util.List; import static com.facebook.presto.spi.block.BlockBuilderStatus.DEFAULT_MAX_BLOCK_SIZE_IN_BYTES; import static com.facebook.presto.spi.block.BlockBuilderStatus.DEFAULT_MAX_PAGE_SIZE_IN_BYTES; import static java.util.Collections.unmodifiableList; import static java.util.Objects.requireNonNull; public class PageBuilder { private final BlockBuilder[] blockBuilders; private final List types; private BlockBuilderStatus blockBuilderStatus; private int declaredPositions; public PageBuilder(List types) { this.types = unmodifiableList(new ArrayList<>(requireNonNull(types, "types is null"))); int maxBlockSizeInBytes; if (!types.isEmpty()) { maxBlockSizeInBytes = (int) (1.0 * DEFAULT_MAX_PAGE_SIZE_IN_BYTES / types.size()); maxBlockSizeInBytes = Math.min(DEFAULT_MAX_BLOCK_SIZE_IN_BYTES, maxBlockSizeInBytes); } else { maxBlockSizeInBytes = 0; } blockBuilderStatus = new BlockBuilderStatus(DEFAULT_MAX_PAGE_SIZE_IN_BYTES, maxBlockSizeInBytes); blockBuilders = new BlockBuilder[types.size()]; for (int i = 0; i < blockBuilders.length; i++) { blockBuilders[i] = types.get(i).createBlockBuilder(blockBuilderStatus, 1, blockBuilderStatus.getMaxBlockSizeInBytes()); } } public void reset() { if (isEmpty()) { return; } declaredPositions = 0; blockBuilderStatus = new BlockBuilderStatus(blockBuilderStatus); for (int i = 0; i < types.size(); i++) { blockBuilders[i] = types.get(i).createBlockBuilder(blockBuilderStatus, 1, blockBuilderStatus.getMaxBlockSizeInBytes()); } } public BlockBuilder getBlockBuilder(int channel) { return blockBuilders[channel]; } /** * Hack to declare positions when producing a page with no channels */ public void declarePosition() { declaredPositions++; } public boolean isFull() { return declaredPositions == Integer.MAX_VALUE || blockBuilderStatus.isFull(); } public boolean isEmpty() { return declaredPositions == 0; } public int getPositionCount() { return declaredPositions; } public long getSizeInBytes() { return blockBuilderStatus.getSizeInBytes(); } public Page build() { if (blockBuilders.length == 0) { return new Page(declaredPositions); } Block[] blocks = new Block[blockBuilders.length]; for (int i = 0; i < blocks.length; i++) { blocks[i] = blockBuilders[i].build(); if (blocks[i].getPositionCount() != declaredPositions) { throw new IllegalStateException(String.format("Declared positions (%s) does not match block %s's number of entries (%s)", declaredPositions, i, blocks[i].getPositionCount())); } } return new Page(blocks); } } package com.dlq.mall.order; import org.springframework.amqp.rabbit.annotation.EnableRabbit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; /** * RabbitMQ: * 1、自动导入amqp配置类:RabbitAutoConfiguration * 2、给容器中自动配置了 * RabbitTemplate、AmqpAdmin、CachingConnectionFactory、RabbitMessagingTemplate * 所有的属性都是 * @ConfigurationProperties(prefix = "spring.rabbitmq") * public class RabbitProperties {...} * 3、给配置文件中配置 spring.rabbitmq 信息 * 4、@EnableRabbit:@EnableXXX;开启功能 * 5、监听消息:使用@RabbitListener;必须有@EnableRabbit * @RabbitListener:标在 类或方法上(监听哪些队列) * @RabbitHandler:标在 方法上(重载区分不同的信息) */ @EnableFeignClients(basePackages = "com.dlq.mall.order.feign") @EnableRedisHttpSession @EnableRabbit @SpringBootApplication public class MiOrderApplication { public static void main(String[] args) { SpringApplication.run(MiOrderApplication.class, args); } } Lucas-Angelo/AED2 import java.io.BufferedReader; import java.io.InputStreamReader; public class TratarExce { public static void metodo1(String s) throws NumberFormatException, ArrayIndexOutOfBoundsException { int i = Integer.parseInt(s); System.out.println("A variavel i vale: " + i); } public static void metodo2(String s) throws NumberFormatException { int i = Integer.parseInt(s); System.out.println("A variavel i vale: " + i); } public static void main(String[] args) throws Exception { BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in)); String s = entrada.readLine(); try { metodo1(s); } catch (NumberFormatException e) { System.out.println("Erro!!"); } System.out.println("------------->>>>>>>>>> <<<<<<<<<---------------"); try { metodo2(s); } catch (NumberFormatException e) { System.out.println("Erro!!"); } System.out.println("------------->>>>>>>>>> <<<<<<<<<---------------"); } } package quek.undergarden.client.render.entity; import net.minecraft.client.renderer.entity.EntityRendererManager; import net.minecraft.client.renderer.entity.MobRenderer; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import quek.undergarden.Undergarden; import quek.undergarden.client.model.MuncherModel; import quek.undergarden.client.render.layer.MuncherEyesLayer; import quek.undergarden.entity.cavern.MuncherEntity; @OnlyIn(Dist.CLIENT) public class MuncherRender extends MobRenderer> { public MuncherRender(EntityRendererManager renderManagerIn) { super(renderManagerIn, new MuncherModel<>(), 0.5F); this.addLayer(new MuncherEyesLayer<>(this)); } @Override public ResourceLocation getTextureLocation(MuncherEntity entity) { return new ResourceLocation(Undergarden.MODID, "textures/entity/muncher.png"); } } package com.learn.mongodb; import com.mongodb.MongoClient; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.bridge.SLF4JBridgeHandler; import java.util.logging.LogManager; import static spark.Spark.*; public class MongoDBService { static final String version = "0.0.1"; static Logger logger; public static void main(String[] args) { port(5000); staticFileLocation("static"); LogManager.getLogManager().reset(); SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); logger = LoggerFactory.getLogger(MongoDBService.class); logger.info("MongoDB Service version " + version); //Initialize MongoDB Client MongoConnection mongoConnection = MongoConnection.getMongoConnection(); mongoConnection.init(); MongoClient mongoClient; mongoClient = mongoConnection.getMongo(); APIRoutes apiRoutes = new APIRoutes(mongoClient); get("/home",(req,res) -> apiRoutes.getHome(req,res)); put("/books",(req,res) -> apiRoutes.addBook(req,res)); get("/books/*",(req,res) -> apiRoutes.getBook(req,res)); get("/books",(req,res) -> apiRoutes.getBooks(req,res)); after((req, res) -> { res.type("application/json"); }); RegisterBookChangeStreamListener(mongoClient); } private static void RegisterBookChangeStreamListener(MongoClient mongoClient) { BookChangeStreamListener bookChangeStreamListener = new BookChangeStreamListener(mongoClient); } }10-100 package io.eiichiro.prodigy; public class Fault2 extends Fault { private String property1; private int property2; public String getProperty1() { return property1; } public int getProperty2() { return property2; } public void setProperty2(int property2) { this.property2 = property2; } public void setProperty1(String property1) { this.property1 = property1; } }src/java/textdisplay/PartnerProject.java1-10 /* * @author Copyright 2011 Saint Louis University. Licensed under the Educational Community 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.osedu.org/licenses/ECL-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 textdisplay; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import static java.sql.Statement.RETURN_GENERATED_KEYS; import java.util.Stack; import static org.owasp.esapi.ESAPI.encoder; import static textdisplay.DatabaseWrapper.closeDBConnection; import static textdisplay.DatabaseWrapper.closePreparedStatement; import static textdisplay.DatabaseWrapper.getConnection; import static textdisplay.Project.getAllAssociatedProjects; import user.User; /**This class provides a mechanism for standardizing certain aspects of a set of projects as well as providing a mechanism for sending notification to a chosen user when a particular project is complete and ready for export. */ public class PartnerProject { private String url; private int controllingUser; private int templateProject; private int id; private String description; private String name; /**Fetch a partner project by its unique ID. That id is stored in the project object for all associated projects.*/ public PartnerProject(int id) throws SQLException { this.id=id; String query="select * from partnerproject where id=?"; Connection j=null; PreparedStatement ps=null; try{ j= getConnection(); ps=j.prepareStatement(query); ps.setInt(1, id); ResultSet rs=ps.executeQuery(); if(rs.next()) { this.name=rs.getString("name"); this.description =rs.getString("description"); this.controllingUser=rs.getInt("user"); this.url=rs.getString("url"); this.templateProject=rs.getInt("projectID"); } else { this.id=-1; } } finally { closeDBConnection(j); closePreparedStatement(ps); } } /**Create a new pipeline based on a template project. The group leader of that project will recieve notifications and be added to projects which associate with this pipeline.*/ public PartnerProject(String name, String description, String url, int controllingUser, int projectID) throws SQLException { String query="insert into partnerproject(name,url,user,description,projectID) values(?,?,?,?,?)"; Connection j=null; PreparedStatement ps=null; try{ j= getConnection(); ps=j.prepareStatement(query, RETURN_GENERATED_KEYS); ps.setString(1, name); ps.setString(2, url); ps.setInt(3, controllingUser); ps.setString(4, description); ps.setInt(5, projectID); ps.execute(); ResultSet rs=ps.getGeneratedKeys(); rs.next(); this.id=rs.getInt(1); this.controllingUser=controllingUser; this.name=name; this.description=description; this.url=url; this.templateProject=projectID; } finally{ closeDBConnection(j); closePreparedStatement(ps); } } public void setControllingUser(int controllingUser) throws SQLException { Connection j=null; PreparedStatement ps=null; try{ String query="update partnerproject set user=? where id=?"; j=getConnection(); ps=j.prepareStatement(query); ps.setInt(1, controllingUser); ps.setInt(2, this.id); ps.execute(); } finally{ closeDBConnection(j); closePreparedStatement(ps); } this.controllingUser = controllingUser; } public void setDescription(String description) throws SQLException { Connection j=null; PreparedStatement ps=null; try{ String query="update partnerproject set description=? where id=?"; j=getConnection(); ps=j.prepareStatement(query); ps.setString(1, description); ps.setInt(2, this.id); ps.execute(); } finally{ closeDBConnection(j); closePreparedStatement(ps); } this.description = description; } public void setName(String name) throws SQLException { Connection j=null; PreparedStatement ps=null; try{ String query="update partnerproject set name=? where id=?"; j=getConnection(); ps=j.prepareStatement(query); ps.setString(1, name); ps.setInt(2, this.id); ps.execute(); } finally{ closeDBConnection(j); closePreparedStatement(ps); } this.name = name; } public void setTemplateProject(int templateProject) throws SQLException { Connection j=null; PreparedStatement ps=null; try{ String query="update partnerproject set projectID=? where id=?"; j=getConnection(); ps=j.prepareStatement(query); ps.setInt(1, templateProject); ps.setInt(2, this.id); ps.execute(); } finally{ closeDBConnection(j); closePreparedStatement(ps); } this.templateProject = templateProject; } public void setUrl(String url) throws SQLException { Connection j=null; PreparedStatement ps=null; try{ String query="update partnerproject set url=? where id=?"; j=getConnection(); ps=j.prepareStatement(query); ps.setString(1, url); ps.setInt(2, this.id); ps.execute(); } finally{ closeDBConnection(j); closePreparedStatement(ps); } this.url = url; } /**Destroy the pipeline record, and remove all associations with this pipeline*/ public static String [] removeTemplateProject(int id) throws SQLException { String [] toret = new String[3]; toret[2] = new PartnerProject(id).getName(); //remove associated projects Project [] associates = getAllAssociatedProjects(id); int numOfAssoc = (associates != null) ? associates.length : 0; for (int i=0;i tmp=new Stack(); try{ j= getConnection(); ps=j.prepareStatement(query); ResultSet rs=ps.executeQuery(); while(rs.next()) { tmp.push(new PartnerProject(rs.getInt(1))); } } finally{ closeDBConnection(j); closePreparedStatement(ps); } all=new PartnerProject [tmp.size()]; //odd looking way of doing this copy, I know, but it was convenient while(!tmp.empty()) all[tmp.size()-1]=tmp.pop(); return all; } } package org.firstinspires.ftc.teamcode.autonomous; import org.firstinspires.ftc.teamcode.bots.FrenzyBot; import org.firstinspires.ftc.teamcode.odometry.VSlamOdometry; public class AutoReplayBaseCam extends AutoBase { @Override protected void preStart() { super.preStart(); String routeName = getModeName(); if (!routeName.isEmpty()) { loadRoute(routeName); if (this.selectedRoute != null){ this.setOpModeSide(this.selectedRoute.getName()); bot.initDetectorThread(this.getOpModeSide(), this); } } } @Override protected void act() { super.act(); if (opModeIsActive()) { runRoute(false); } } @Override protected void initBot() { this.bot = new FrenzyBot(this.getOpModeSide()); } @Override protected void initLocator() { this.locator = VSlamOdometry.getInstance(hardwareMap, VSlamOdometry.THREAD_INTERVAL, this.selectedRoute.getStartX(), this.selectedRoute.getStartY(), (int) this.selectedRoute.getInitRotation()); startLocator(locator); } @Override protected void displayStatus(){ telemetry.addData("Locator", String.format("X: %.2f, Y: %.2f", locator.getCurrentX(), locator.getCurrentY())); telemetry.addData("Orientation", locator.getAdjustedCurrentHeading()); AutoDot result = bot.getCurrentDetectionResult(); if (result!= null) { telemetry.addData("Detection result", result.getDotName()); } telemetry.update(); } } Himmelt/Rikkasrc/main/java/rikka/api/entity/EntityType.java package rikka.api.entity; import org.bukkit.entity.*; import org.bukkit.entity.minecart.CommandMinecart; import org.bukkit.entity.minecart.HopperMinecart; import org.spongepowered.api.entity.explosive.PrimedTNT; import org.spongepowered.api.entity.living.Human; import org.spongepowered.api.entity.living.animal.Mooshroom; import org.spongepowered.api.entity.living.complex.ComplexLivingPart; import org.spongepowered.api.entity.living.golem.SnowGolem; import org.spongepowered.api.entity.living.monster.ZombiePigman; import org.spongepowered.api.entity.projectile.EyeOfEnder; import org.spongepowered.api.entity.vehicle.minecart.*; import org.spongepowered.api.entity.weather.Lightning; import org.spongepowered.api.entity.weather.WeatherEffect; import javax.annotation.Nonnull; import java.util.HashMap; public enum EntityType { AREA_EFFECT_CLOUD("area_effect_cloud", org.bukkit.entity.AreaEffectCloud.class, org.spongepowered.api.entity.AreaEffectCloud.class), ARMOR_STAND("armor_stand", org.bukkit.entity.ArmorStand.class, org.spongepowered.api.entity.living.ArmorStand.class), BAT("bat", org.bukkit.entity.Bat.class, org.spongepowered.api.entity.living.Bat.class), BLAZE("blaze", org.bukkit.entity.Blaze.class, org.spongepowered.api.entity.living.monster.Blaze.class), BOAT("boat", org.bukkit.entity.Boat.class, org.spongepowered.api.entity.vehicle.Boat.class), CAVE_SPIDER("cave_spider", org.bukkit.entity.CaveSpider.class, org.spongepowered.api.entity.living.monster.CaveSpider.class), CHESTED_MINECART("chested_minecart", org.bukkit.entity.Minecart.class, ChestMinecart.class), CHICKEN("chicken", Chicken.class, org.spongepowered.api.entity.living.animal.Chicken.class), COMMANDBLOCK_MINECART("commandblock_minecart", CommandMinecart.class, CommandBlockMinecart.class), COMPLEX_PART("complex_part", ComplexEntityPart.class, ComplexLivingPart.class), COW("cow", Cow.class, org.spongepowered.api.entity.living.animal.Cow.class), CREEPER("creeper", Creeper.class, org.spongepowered.api.entity.living.monster.Creeper.class), DONKEY("donkey", Donkey.class, org.spongepowered.api.entity.living.animal.Donkey.class), DRAGON_FIREBALL("dragon_fireball", DragonFireball.class, org.spongepowered.api.entity.projectile.explosive.DragonFireball.class), EGG("egg", Egg.class, org.spongepowered.api.entity.projectile.Egg.class), // TODO check ELDER_GUARDIAN("elder_guardian", ElderGuardian.class, org.spongepowered.api.entity.living.monster.Guardian.class), ENDERMAN("enderman", Enderman.class, org.spongepowered.api.entity.living.monster.Enderman.class), ENDERMITE("endermite", Endermite.class, org.spongepowered.api.entity.living.monster.Endermite.class), ENDER_CRYSTAL("ender_crystal", EnderCrystal.class, org.spongepowered.api.entity.EnderCrystal.class), ENDER_DRAGON("ender_dragon", EnderDragon.class, org.spongepowered.api.entity.living.complex.EnderDragon.class), ENDER_PEARL("ender_pearl", EnderPearl.class, org.spongepowered.api.entity.projectile.EnderPearl.class), // TODO check EVOCATION_FANGS("evocation_fangs", EvokerFangs.class, org.spongepowered.api.entity.living.monster.Evoker.class), // TODO check // EVOCATION_ILLAGER, EXPERIENCE_ORB("exp_orb", ExperienceOrb.class, org.spongepowered.api.entity.ExperienceOrb.class), // TODO check EYE_OF_ENDER("eye_of_ender", null, EyeOfEnder.class), FALLING_BLOCK("falling_block", FallingBlock.class, org.spongepowered.api.entity.FallingBlock.class), FIREBALL("fireball", Fireball.class, org.spongepowered.api.entity.projectile.explosive.fireball.Fireball.class), FIREWORK("firework", Firework.class, org.spongepowered.api.entity.projectile.Firework.class), FISH_HOOK("fish_hook", FishHook.class, org.spongepowered.api.entity.projectile.FishHook.class), // TODO check FURNACE_MINECART("furnace_minecart", null, FurnaceMinecart.class), GHAST("ghast", Ghast.class, org.spongepowered.api.entity.living.monster.Ghast.class), GIANT("giant", Giant.class, org.spongepowered.api.entity.living.monster.Giant.class), GUARDIAN("guardian", Guardian.class, org.spongepowered.api.entity.living.monster.Guardian.class), HOPPER_MINECART("hopper_minecart", HopperMinecart.class, org.spongepowered.api.entity.vehicle.minecart.HopperMinecart.class), HORSE("horse", Horse.class, org.spongepowered.api.entity.living.animal.Horse.class), // TODO Human Humanoid HUMAN("human", HumanEntity.class, Human.class), HUSK("husk", Husk.class, org.spongepowered.api.entity.living.monster.Husk.class), ILLUSIONER("illusioner", Illusioner.class, org.spongepowered.api.entity.living.monster.Illusioner.class), IRON_GOLEM("iron_golem", IronGolem.class, org.spongepowered.api.entity.living.golem.IronGolem.class), ITEM("item", Item.class, org.spongepowered.api.entity.Item.class), ITEM_FRAME("item_frame", ItemFrame.class, org.spongepowered.api.entity.hanging.ItemFrame.class), LEASH_HITCH("leash_hitch", LeashHitch.class, org.spongepowered.api.entity.hanging.LeashHitch.class), LIGHTNING("lighting", LightningStrike.class, Lightning.class), LLAMA("llama", Llama.class, org.spongepowered.api.entity.living.animal.Llama.class), LLAMA_SPIT("llama_spit", LlamaSpit.class, org.spongepowered.api.entity.projectile.LlamaSpit.class), MAGMA_CUBE("magma_cube", MagmaCube.class, org.spongepowered.api.entity.living.monster.MagmaCube.class), // TODO check MOB_SPAWNER_MINECART("mob_spawner_minecart", null, MobSpawnerMinecart.class), MULE("mule", Mule.class, org.spongepowered.api.entity.living.animal.Mule.class), MUSHROOM_COW("mushroom", MushroomCow.class, Mooshroom.class), OCELOT("ocelot", Ocelot.class, org.spongepowered.api.entity.living.animal.Ocelot.class), PAINTING("painting", Painting.class, org.spongepowered.api.entity.hanging.Painting.class), PARROT("parrot", Parrot.class, org.spongepowered.api.entity.living.animal.Parrot.class), PIG("pig", Pig.class, org.spongepowered.api.entity.living.animal.Pig.class), PIG_ZOMBIE("pig_zombie", PigZombie.class, ZombiePigman.class), PLAYER("player", Player.class, org.spongepowered.api.entity.living.player.Player.class), POLAR_BEAR("polar_bear", PolarBear.class, org.spongepowered.api.entity.living.animal.PolarBear.class), PRIMED_TNT("primed_tnt", TNTPrimed.class, PrimedTNT.class), RABBIT("rabbit", Rabbit.class, org.spongepowered.api.entity.living.animal.Rabbit.class), // TODO check // RIDEABLE_MINECART, SHEEP("sheep", Sheep.class, org.spongepowered.api.entity.living.animal.Sheep.class), SHULKER("shulker", Shulker.class, org.spongepowered.api.entity.living.golem.Shulker.class), SHULKER_BULLET("shulker_bullet", ShulkerBullet.class, org.spongepowered.api.entity.ShulkerBullet.class), SILVERFISH("silverfish", Silverfish.class, org.spongepowered.api.entity.living.monster.Silverfish.class), SKELETON("skeleton", Skeleton.class, org.spongepowered.api.entity.living.monster.Skeleton.class), SKELETON_HORSE("skeleton_horse", SkeletonHorse.class, org.spongepowered.api.entity.living.animal.SkeletonHorse.class), SLIME("slime", Slime.class, org.spongepowered.api.entity.living.monster.Slime.class), SMALL_FIREBALL("small_fireball", SmallFireball.class, org.spongepowered.api.entity.projectile.explosive.fireball.SmallFireball.class), SNOWBALL("snowball", Snowball.class, org.spongepowered.api.entity.projectile.Snowball.class), SNOWMAN("snowman", Snowman.class, SnowGolem.class), SPECTRAL_ARROW("spectral_arrow", SpectralArrow.class, org.spongepowered.api.entity.projectile.arrow.SpectralArrow.class), SPIDER("spider", Spider.class, org.spongepowered.api.entity.living.monster.Spider.class), // TODO check SPLASH_POTION("splash_potion", SplashPotion.class, null), SQUID("squid", Squid.class, org.spongepowered.api.entity.living.Squid.class), STRAY("stray", Stray.class, org.spongepowered.api.entity.living.monster.Stray.class), THROWN_EXP_BOTTLE("exp_bottle", ThrownExpBottle.class, org.spongepowered.api.entity.projectile.ThrownExpBottle.class), TIPPED_ARROW("tipped_arrow", TippedArrow.class, org.spongepowered.api.entity.projectile.arrow.TippedArrow.class), // TODO check TNT_MINECART("tnt_minecart", null, TNTMinecart.class), VEX("vex", Vex.class, org.spongepowered.api.entity.living.monster.Vex.class), VILLAGER("villager", Villager.class, org.spongepowered.api.entity.living.Villager.class), VINDICATOR("vindicator", Vindicator.class, org.spongepowered.api.entity.living.monster.Vindicator.class), WEATHER("weather", Weather.class, WeatherEffect.class), WITCH("witch", Witch.class, org.spongepowered.api.entity.living.monster.Witch.class), WITHER("wither", Wither.class, org.spongepowered.api.entity.living.monster.Wither.class), WITHER_SKELETON("wither_skeleton", WitherSkeleton.class, org.spongepowered.api.entity.living.monster.WitherSkeleton.class), WITHER_SKULL("wither_skull", WitherSkull.class, org.spongepowered.api.entity.projectile.explosive.WitherSkull.class), WOLF("wolf", Wolf.class, org.spongepowered.api.entity.living.animal.Wolf.class), ZOMBIE("zombie", Zombie.class, org.spongepowered.api.entity.living.monster.Zombie.class), ZOMBIE_HORSE("zombie_horse", ZombieHorse.class, org.spongepowered.api.entity.living.animal.ZombieHorse.class), ZOMBIE_VILLAGER("zombie_villager", ZombieVillager.class, org.spongepowered.api.entity.living.monster.ZombieVillager.class), UNKNOWN("unknown", Entity.class, org.spongepowered.api.entity.Entity.class); private final String nameId; private final Class bukkitClass; private final Class spongeClass; private static final HashMap nameIdMap = new HashMap<>(); private static final HashMap, EntityType> bukkitClassMap = new HashMap<>(); private static final HashMap, EntityType> spongeClassMap = new HashMap<>(); static { nameIdMap.clear(); bukkitClassMap.clear(); spongeClassMap.clear(); for (EntityType type : values()) { bukkitClassMap.put(type.bukkitClass, type); spongeClassMap.put(type.spongeClass, type); if (type.nameId != null && !type.nameId.isEmpty()) { if (nameIdMap.containsKey(type.nameId)) { throw new RuntimeException("Multi Map of EntityType nameId: " + type.nameId); } nameIdMap.put(type.nameId, type); } } } EntityType(String nameId, @Nonnull Class bukkitClass, @Nonnull Class spongeClass) { this.nameId = nameId; this.bukkitClass = bukkitClass; this.spongeClass = spongeClass; } public static EntityType getType(T source) { return bukkitClassMap.getOrDefault(source.getClass(), UNKNOWN); } public static EntityType getType(T source) { return spongeClassMap.getOrDefault(source.getClass(), UNKNOWN); } } /** * **************************************************************************** * Copyright (c) 2010-2016 by (). *

* This file is part of the Archimulator multicore architectural simulator. *

* Archimulator is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. *

* Archimulator 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 General Public License for more details. *

* You should have received a copy of the GNU General Public License * along with Archimulator. If not, see . * **************************************************************************** */ package archimulator.common.report; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; /** * Report node. * * @author */ public class ReportNode implements Serializable { private ReportNode parent; private String key; private String value; private List children; /** * Create a report node. * * @param parent the parent node * @param key the key */ public ReportNode(ReportNode parent, String key) { this(parent, key, null); } /** * Create a report node. * * @param parent the parent node * @param key the key * @param value the value */ public ReportNode(ReportNode parent, String key, String value) { this.parent = parent; this.key = key; this.value = value; this.children = new ArrayList<>(); } /** * Get the parent node. * * @return the parent node */ public ReportNode getParent() { return parent; } /** * Get the key. * * @return the key */ public String getKey() { return key; } /** * Get the value. * * @return the value */ public String getValue() { return value; } /** * Get the child nodes. * * @return the child nodes */ public List getChildren() { return children; } /** * Get a value indicating whether the node is leaf or not. * * @return a value indicating whether the node is leaf or not */ public boolean isLeaf() { return this.children.isEmpty(); } /** * Get the path of the node. * * @return the path of the node */ public String getPath() { return String.format("%s%s", getParent() != null && !getParent().getKey().isEmpty() ? getParent().getPath() + "/" : "", getKey()); } /** * Print recursively the node and its child nodes. */ public void print() { traverse(System.out::println); } /** * Traverse the node and its child nodes using the specified callback action. */ public void traverse(Consumer callback) { if (this.value != null) { callback.accept(this); } for (ReportNode child : getChildren()) { child.traverse(callback); } } @Override public String toString() { return String.format("%s=%s", getPath(), value); } } 0 package com.example.personalvehicledelivery; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class RoleSelectActivity extends AppCompatActivity { RadioGroup radioGroup; RadioButton radioButton; private FirebaseAuth mAuth; // DB and DB reference private FirebaseDatabase database; private DatabaseReference mDatabase; Button help_btn; TextView help_txt; private static final String USERS = "users"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_role_select); mAuth = FirebaseAuth.getInstance(); database = FirebaseDatabase.getInstance(); mDatabase = database.getReference(); help_btn = (Button)findViewById(R.id.help_button2); help_txt = (TextView)findViewById(R.id.help_text2); help_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { help_txt.setVisibility((help_txt.getVisibility() == View.VISIBLE) ? View.GONE : View.VISIBLE); } }); radioGroup = findViewById(R.id.radioGroup); Button buttonSubmit = findViewById(R.id.buttonSubmit); buttonSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int radioId = radioGroup.getCheckedRadioButtonId(); radioButton = findViewById(radioId); // Adding user type into database String userType = radioButton.getText().toString().trim(); String uid = mAuth.getCurrentUser().getUid(); String userEmail = mAuth.getCurrentUser().getEmail(); String userEmailKey = userEmail.replace('.', ','); mDatabase.child(USERS).child(uid).child("user_type").setValue(userType); mDatabase.child(userType.toLowerCase() + 's').child(userEmailKey).child("uid").setValue(uid); mDatabase.child(userType.toLowerCase() + 's').child(userEmailKey).child("email").setValue(userEmail); if (userType.equals("Customer")) { finish(); startActivity(new Intent(RoleSelectActivity.this, CustomerInfoActivity.class)); } else if (userType.equals("Driver")) { finish(); startActivity(new Intent(RoleSelectActivity.this, DriverInfoActivity.class)); } else if (userType.equals("Business Owner")) { finish(); startActivity(new Intent(RoleSelectActivity.this, BusinessInfoActivity.class)); } } }); } @Override protected void onStart() { super.onStart(); if (mAuth.getCurrentUser() == null) { finish(); startActivity(new Intent(this, MainActivity.class)); } } public void checkButton(View v) { int radioId = radioGroup.getCheckedRadioButtonId(); radioButton = findViewById(radioId); Toast.makeText(getApplicationContext(), "User type: " + radioButton.getText(), Toast.LENGTH_SHORT).show(); } }src/main/java/com/tupinamba/springbootwebsocket/controller/ChatController.java package com.tupinamba.springbootwebsocket.controller; import com.tupinamba.springbootwebsocket.model.ChatMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessagingTemplate; import org.springframework.stereotype.Controller; import java.util.HashMap; import java.util.Map; @Controller public class ChatController { Map dict = new HashMap<>(); @Autowired private SimpMessagingTemplate simpMessagingTemplate; @MessageMapping("/chat.register") @SendTo("/topic/public") public ChatMessage register(@Header("simpSessionId") String sessionId, @Payload ChatMessage chatMessage, SimpMessageHeaderAccessor headerAccessor) { String sender = chatMessage.getSender(); headerAccessor.getSessionAttributes().put("username", sender); //System.out.println(headerAccessor); dict.put(sender, sessionId); System.out.println(dict); chatMessage.setSessionId(sessionId); return chatMessage; } @MessageMapping("/chat.send") public void sendMessage(@Header("simpSessionId") String sessionId, @Payload ChatMessage chatMessage) { String sender = chatMessage.getSender(); for (Map.Entry entry : dict.entrySet()) { if( !sender.equals(entry.getKey()) ){ simpMessagingTemplate.convertAndSendToUser(entry.getValue(), "/msg", chatMessage); } } chatMessage.setSender("Me"); simpMessagingTemplate.convertAndSendToUser(sessionId, "/msg", chatMessage); } }package android.support.p003v7.widget; import android.support.p003v7.widget.RecyclerView; import android.view.View; /* renamed from: android.support.v7.widget.LayoutState */ class LayoutState { static final int INVALID_LAYOUT = Integer.MIN_VALUE; static final int ITEM_DIRECTION_HEAD = -1; static final int ITEM_DIRECTION_TAIL = 1; static final int LAYOUT_END = 1; static final int LAYOUT_START = -1; static final String TAG = "LayoutState"; int mAvailable; int mCurrentPosition; int mEndLine = 0; boolean mInfinite; int mItemDirection; int mLayoutDirection; boolean mRecycle = true; int mStartLine = 0; boolean mStopInFocusable; LayoutState() { } /* access modifiers changed from: package-private */ public boolean hasMore(RecyclerView.State state) { return this.mCurrentPosition >= 0 && this.mCurrentPosition < state.getItemCount(); } /* access modifiers changed from: package-private */ public View next(RecyclerView.Recycler recycler) { View view = recycler.getViewForPosition(this.mCurrentPosition); this.mCurrentPosition += this.mItemDirection; return view; } public String toString() { return "LayoutState{mAvailable=" + this.mAvailable + ", mCurrentPosition=" + this.mCurrentPosition + ", mItemDirection=" + this.mItemDirection + ", mLayoutDirection=" + this.mLayoutDirection + ", mStartLine=" + this.mStartLine + ", mEndLine=" + this.mEndLine + '}'; } } src/main/java/com/tom/storagemod/network/DataPacket.java package com.tom.storagemod.network; import net.minecraft.nbt.CompoundNBT; import net.minecraft.network.PacketBuffer; public class DataPacket { public CompoundNBT tag; public DataPacket(CompoundNBT tag) { this.tag = tag; } public DataPacket(PacketBuffer pb) { tag = pb.readCompoundTag(); } public void toBytes(PacketBuffer pb) { pb.writeCompoundTag(tag); } } Meruem117/spring-start package start.spring.ioc.bean.life; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; /** * @auther: Meruem117 */ public class Post implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { System.out.println("before init"); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { System.out.println("after init"); return bean; } } package com.android.launcher3.logging; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.LooperMode; import org.robolectric.annotation.LooperMode.Mode; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Calendar; /** * Tests for {@link FileLog} */ @RunWith(RobolectricTestRunner.class) @LooperMode(Mode.PAUSED) public class FileLogTest { private File mTempDir; @Before public void setUp() { int count = 0; do { mTempDir = new File(RuntimeEnvironment.application.getCacheDir(), "log-test-" + (count++)); } while (!mTempDir.mkdir()); FileLog.setDir(mTempDir); } @After public void tearDown() { // Clear existing logs for (int i = 0; i < FileLog.LOG_DAYS; i++) { new File(mTempDir, "log-" + i).delete(); } mTempDir.delete(); } @Test public void testPrintLog() throws Exception { if (!FileLog.ENABLED) { return; } FileLog.print("Testing", "hoolalala"); StringWriter writer = new StringWriter(); assertTrue(FileLog.flushAll(new PrintWriter(writer))); assertTrue(writer.toString().contains("hoolalala")); FileLog.print("Testing", "abracadabra", new Exception("cat! cat!")); writer = new StringWriter(); assertTrue(FileLog.flushAll(new PrintWriter(writer))); assertTrue(writer.toString().contains("abracadabra")); // Exception is also printed assertTrue(writer.toString().contains("cat! cat!")); // Old logs still present after flush assertTrue(writer.toString().contains("hoolalala")); } @Test public void testOldFileTruncated() throws Exception { if (!FileLog.ENABLED) { return; } FileLog.print("Testing", "hoolalala"); StringWriter writer = new StringWriter(); assertTrue(FileLog.flushAll(new PrintWriter(writer))); assertTrue(writer.toString().contains("hoolalala")); Calendar threeDaysAgo = Calendar.getInstance(); threeDaysAgo.add(Calendar.HOUR, -72); for (int i = 0; i < FileLog.LOG_DAYS; i++) { new File(mTempDir, "log-" + i).setLastModified(threeDaysAgo.getTimeInMillis()); } FileLog.print("Testing", "abracadabra", new Exception("cat! cat!")); writer = new StringWriter(); assertTrue(FileLog.flushAll(new PrintWriter(writer))); assertTrue(writer.toString().contains("abracadabra")); // Exception is also printed assertTrue(writer.toString().contains("cat! cat!")); // Old logs have been truncated assertFalse(writer.toString().contains("hoolalala")); } } wk0122/CoreJava package tech.aistar.day09.factory; /** * @author success * @version 1.0 * @description:本类用来演示: * @date 2019/4/4 0004 */ public class PlaneVersion02 extends Plane{ public PlaneVersion02(){ System.out.println("Plane_version...."); } } package com.adahas.tools.jmxeval.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class NagiosRangeValueTest { private final String rangeSpec; private final Double value; private final boolean verifyValid; public NagiosRangeValueTest(final String rangeSpec, final Double value, final boolean verifyValid) { this.rangeSpec = rangeSpec; this.value = value; this.verifyValid = verifyValid; } @Parameters(name = "{index}: for range [{0}] value [{1}] should be valid [{2}]") public static Iterable values() { return Arrays.asList(new Object[][] { // values in range { "10:20", 10d, true }, { "10:20", 20d, true }, { "10:20", 15d, true }, // values outside range { "10:20", 9.99d, false }, { "10:20", 20.001d, false }, { "10:20", -1d, false }, { "10:20", 0d, false }, // is value OK for negative infinity { "~:0", Double.NEGATIVE_INFINITY, true }, { "~:0", -2000.1, true }, { "~:0", 0.0, true }, { "~:0", -0.0, true }, // is value not OK for negative infinity { "~:0", Double.POSITIVE_INFINITY, false }, { "~:0", 0.1, false }, { "~:0", 200.2134, false }, // is value OK for positive infinity { "0:~", Double.POSITIVE_INFINITY, true }, { "0:~", 0.1, true }, { "0:~", 200.2134, true }, // is value not OK for positive infinity { "0:~", Double.NEGATIVE_INFINITY, false }, { "0:~", -2000.1, false }, { "0:~", -0.1, false } }); } @Test public void testValue() throws Exception { final NagiosRange range = new NagiosRange(rangeSpec); if (verifyValid) { assertTrue("range=" + rangeSpec + " value=" + value, range.isInRange(value)); } else { assertFalse("range=" + rangeSpec + " value=" + value, range.isInRange(value)); } final NagiosRange rangeExcl = new NagiosRange("@" + rangeSpec); if (verifyValid) { assertFalse("range=" + rangeSpec + " value=" + value, rangeExcl.isInRange(value)); } else { assertTrue("range=" + rangeSpec + " value=" + value, rangeExcl.isInRange(value)); } } } jhivgensim/src/net/sf/hivgensim/queries/GetNaivePatients.java0 package net.sf.hivgensim.queries; import net.sf.hivgensim.queries.framework.IQuery; import net.sf.hivgensim.queries.framework.Query; import net.sf.hivgensim.queries.framework.utils.TherapyUtils; import net.sf.regadb.db.Patient; import net.sf.regadb.db.Therapy; public class GetNaivePatients extends Query{ private String[] drugClasses = new String[]{"Unknown","PI","NRTI","NNRTI","INI","EI"}; public GetNaivePatients(IQuery nextQuery){ super(nextQuery); } public GetNaivePatients(IQuery nextQuery, String[] drugClasses){ super(nextQuery); this.drugClasses = drugClasses; } public void process(Patient p) { //we use a set to avoid having duplicate patients //caused by the "joins/loops" in the query boolean naive = true; for(Therapy t : p.getTherapies()) { //always check for unknown therapies if(TherapyUtils.hasClassExperience("Unknown", t)){ naive = false; } for(String tT : drugClasses){ if(TherapyUtils.hasClassExperience(tT, t)) { naive = false; } } } if(naive){ getNextQuery().process(p); } } } package com.example.entity; import java.math.BigDecimal; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.extension.activerecord.Model; import com.baomidou.mybatisplus.annotation.TableId; @TableName("service") public class MyService extends Model { /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 名称 */ private String name; /** * 价格 */ private Integer price; /** * 介绍 */ private String hint; /** * 积点 */ private Integer point; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } public String getHint() { return hint; } public void setHint(String hint) { this.hint = hint; } public Integer getPoint() { return point; } public void setPoint(Integer point) { this.point = point; } }1-10 package com.tangenta.parser.result; // Panic is an exception occurred when parsing strings or evaluating Expr. public class Panic extends RuntimeException { private Panic(String errMsg) { super(errMsg); } // msg() build a Panic with an error message. public static Panic msg(String errMsg) { return new Panic(errMsg); } } package fun.gengzi.codecopy.sys.entity; import javax.persistence.*; import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.relational.core.mapping.Column; @Entity @Table(name = "sys_permission") @Data @AllArgsConstructor @NoArgsConstructor public class SysPermission implements Serializable { private static final long serialVersionUID = 4095915507924264952L; @javax.persistence.Id @Id @GeneratedValue(strategy = GenerationType.IDENTITY) // @Column("ID") private Integer id; // @Column("PID") private Integer pid; // @Column("NAME") private String name; // @Column("TYPE") private String type; // @Column("SORT") private Integer sort; // @Column("URL") private String url; // @Column("PERM_CODE") private String permCode; // @Column("ICON") private String icon; // @Column("STATE") private String state; // @Column("DESCRIPTION") private String description; // @Column("FROM_APP_IDENTIFY_ID") private String fromAppIdentifyId; }package com.rposcro.jwavez.tools.shell.commands.node; import com.rposcro.jwavez.tools.shell.commands.CommandGroup; import com.rposcro.jwavez.tools.shell.formatters.NodeInformationFormatter; import com.rposcro.jwavez.tools.shell.models.NodeInformation; import com.rposcro.jwavez.tools.shell.scopes.NodeScopeContext; import com.rposcro.jwavez.tools.shell.services.NodeInformationCache; import com.rposcro.jwavez.tools.shell.services.NodeInformationService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.shell.standard.ShellCommandGroup; import org.springframework.shell.standard.ShellComponent; import org.springframework.shell.standard.ShellMethod; import org.springframework.shell.standard.ShellOption; import java.util.List; import java.util.stream.Collectors; @ShellComponent @ShellCommandGroup(CommandGroup.NODE) public class KnownNodesCommands { @Autowired private NodeScopeContext nodeScopeContext; @Autowired private NodeInformationService nodeInformationService; @Autowired private NodeInformationCache nodeInformationCache; @Autowired private NodeInformationFormatter nodeInformationFormatter; @ShellMethod(value = "List known nodes", key = { "list", "ls" }) public String listKnownNodes() { return nodeInformationCache.getOrderedNodeList().stream() .map(node -> "Id " + node.getNodeId() + ": " + node.getNodeMemo()) .collect(Collectors.joining("\n")); } @ShellMethod(value = "Show known node information", key = { "info", "ni" }) public String showNodeInformation( @ShellOption(value = { "--node-id", "-id" }, defaultValue = ShellOption.NULL) Integer nodeIdArg, @ShellOption(value = { "--verbose", "-v" }, defaultValue = "false") boolean verbose ) { if (nodeIdArg == null && !nodeScopeContext.isAnyNodeSelected()) { return "No node selected, --node-id needs to be provided"; } int nodeId = nodeIdArg != null ? nodeIdArg : nodeScopeContext.getCurrentNodeId(); NodeInformation nodeInformation = nodeInformationCache.getNodeDetails(nodeId); if (nodeInformation != null) { return verbose ? nodeInformationFormatter.formatVerboseNodeInfo(nodeInformation) : nodeInformationFormatter.formatShortNodeInfo(nodeInformation); } else { return String.format("Node %s is unknown, try to fetch it first", nodeId); } } @ShellMethod(value = "Set known node memo", key = { "memo" }) public String setNodeMemo( @ShellOption(value = { "--node-memo", "-memo" }) String nodeMemo, @ShellOption(value = { "--node-id", "-id" }, defaultValue = ShellOption.NULL) Integer nodeIdArg ) { if (nodeIdArg == null && !nodeScopeContext.isAnyNodeSelected()) { return "No node selected, --node-id needs to be provided"; } NodeInformation nodeInformation = findNodeInformation(nodeIdArg); if (nodeInformation != null) { nodeInformation.setNodeMemo(nodeMemo); return "Memo changed\n" + nodeInformationFormatter.formatShortNodeInfo(nodeInformation); } else { return String.format("Node %s is unknown, try to fetch it first", nodeIdArg); } } @ShellMethod(value = "Remove node from known list", key = { "remove" }) public String removeNodeInformation(@ShellOption({ "--node-id", "-id" }) int nodeId) { NodeInformation nodeInformation = nodeInformationCache.removeNodeInformation(nodeId); if (nodeScopeContext.isAnyNodeSelected() && nodeScopeContext.getCurrentNodeId() == nodeId) { nodeScopeContext.setCurrentNodeId(null); } if (nodeInformation != null) { return String.format("Node %s (%s) removed from cache", nodeId, nodeInformation.getNodeMemo()); } else { return "Node id " + nodeId + " was not in cache"; } } @ShellMethod(value = "Match current node with others in cache", key = { "match" }) public String matchNodeInCache() { int currentNodeId = nodeScopeContext.getCurrentNodeId(); NodeInformation currentNode = nodeInformationCache.getNodeDetails(currentNodeId); List discoveredNodes = nodeInformationService.findMatchingNodes(currentNodeId); if (discoveredNodes.isEmpty()) { return String.format("No similar devices discovered for current node %s (%s)", currentNodeId, currentNode.getNodeMemo()); } else { StringBuffer message = new StringBuffer(String.format("Discovered nodes similar to current %s (%s)\n\n", currentNodeId, currentNode.getNodeMemo())); discoveredNodes.stream().forEach( node -> message.append(String.format("Id: %s (%s) with %s parameters\n", node.getNodeId(), node.getNodeMemo(), node.getParametersInformation().getParameterMetas().size())) ); return message.toString(); } } private NodeInformation findNodeInformation(Integer nodeIdArg) { int nodeId = nodeIdArg == null ? nodeScopeContext.getCurrentNodeId() : nodeIdArg; return nodeInformationCache.getNodeDetails(nodeId); } } chopinguillaume/adventofcode2017 package day09; class Transition { final boolean compterGarbage; final int depart; final char caractereLu; final int arrivee; Transition(int depart, char caractereLu, int arrivee) { this(depart, caractereLu, arrivee, false); } Transition(int depart, char caractereLu, int arrivee, boolean compterGarbage) { this.depart = depart; this.caractereLu = caractereLu; this.arrivee = arrivee; this.compterGarbage = compterGarbage; } } manuelgentile/pxlab package de.pxlab.pxl.display; import de.pxlab.pxl.*; /** * A simple audio beep signal with fixed pitch and duration. The actual sound * will be operating system dependent. Under Windows this corresponds to the * "ding" standard sound as it is defined by the system control panel. Note that * the timing parameters do not affect the sound but the time interval reserved * for the sound. You should not set this Display's Duration parameter to 0 * since it will not be shown in this case. * * @author * @version 0.1.0 */ /* * * 06/14/02 */ public class Beep extends Display { /** Constructor creating the title of the display. */ public Beep() { setTitleAndTopic("Audio Beep", AUDIO_DSP | EXP); Timer.set(new ExParValueConstant( "de.pxlab.pxl.TimerCodes.RAW_CLOCK_TIMER")); Duration.set(1); } protected int create() { int s = enterDisplayElement(new AudioBeep(), group[0]); defaultTiming(0); return (s); } protected void computeGeometry() { } } emretanriverdi/java-liang-solutions0 package Example2; /** * Created by User on 23/05/2017. */ public class Employee extends Person { String office; double salary; String dayHired; public Employee(String name, String adress, String phoneNumber, String eMail, String office, double salary) { super(name, adress, phoneNumber, eMail); MyDate myDate = new MyDate(); this.office = office; this.salary = salary; this.dayHired = myDate.getDay() + "-" + myDate.getMonth() + "-" + myDate.getYear(); } public String getOffice() { return office; } public void setOffice(String office) { this.office = office; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public String getDayHired() { return dayHired; } @Override public String toString() { return super.toString() + "\n" + "Office location: " + office + "\n" + "Salary: " + salary + "$\n" + "Day hired: " + dayHired; } } package randomizers.gameplay; import java.io.IOException; import java.util.List; import java.util.Random; import java.util.Set; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import databases.TaggedDatabase; import proto.RandomizerSettings.Settings; import randomizers.BaseRandomizer; import utils.CustomItemFilterHelper; import utils.ItemMultiplierHelper; import utils.Utils; import utils.ZipHelper; public class PreorderLockerRandomizer extends BaseRandomizer { private static final String PREORDER_LOCKER_FILE = "ark/entitlementunlocklibrary.xml"; private static final int MAX_ATTEMPTS = 10; private TaggedDatabase database; public PreorderLockerRandomizer(Settings s, ZipHelper zipHelper, TaggedDatabase database) { super(s, zipHelper); this.database = database; } @Override public void randomize() { if (settings.getGameplaySettings().getItemSpawnSettings().getFiltersCount() == 0) { return; } try { Document d = zipHelper.getDocument(PREORDER_LOCKER_FILE); CustomItemFilterHelper cfh = new CustomItemFilterHelper(settings, database); Element root = d.getRootElement(); List entitlementUnlocks = root.getChild("EntitlementUnlocks").getChildren(); for (Element unlock : entitlementUnlocks) { List items = unlock.getChild("Items").getChildren(); for (Element item : items) { String archetype = item.getAttributeValue("Archetype"); Element newArchetype = getPickup(cfh, archetype, r); if (newArchetype != null) { int multiplier = ItemMultiplierHelper.getMultiplierForEntity(newArchetype, r); String newArchetypeStr = Utils.getNameForEntity(newArchetype); item.setAttribute("Archetype", newArchetypeStr); item.setAttribute("Quantity", Integer.toString(multiplier)); } } } zipHelper.copyToPatch(d, PREORDER_LOCKER_FILE); } catch (IOException | JDOMException e) { e.printStackTrace(); } } private Element getPickup(CustomItemFilterHelper cfh, String archetype, Random r) { // Try different items until we get a valid pickup item // TODO: Make this smarter by just removing non-pickup items from the list first for (int i = 0; i < MAX_ATTEMPTS; i++) { Element toSwap = cfh.getEntity(archetype, null, r); if (toSwap == null) { continue; } // Ensure that this has the tag "ArkPickups" to represent that it can be added // to an inventory Set tags = Utils.getTags(toSwap); if (tags.contains("ArkPickups")) { return toSwap; } } return null; } } package com.forfan.bigbang.view; import android.annotation.TargetApi; import android.content.Context; import android.content.DialogInterface; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.ViewCompat; import android.support.v7.widget.CardView; import android.text.TextUtils; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.FrameLayout; import android.widget.TextView; import com.forfan.bigbang.R; import com.forfan.bigbang.util.ThemeUtil; import com.forfan.bigbang.util.ViewUtil; /** * Created by Rey on 12/10/2014. */ public class Dialog extends android.app.Dialog{ private ContainerFrameLayout mContainer; private int mLayoutWidth = ViewGroup.LayoutParams.WRAP_CONTENT; private int mLayoutHeight = ViewGroup.LayoutParams.WRAP_CONTENT; private int mMaxWidth; private int mMaxHeight; protected TextView mTitle; protected Button mPositiveAction; protected Button mNegativeAction; protected Button mNeutralAction; private View mContent; private DialogCardView mCardView; protected int mContentPadding; protected int mActionHeight; protected int mActionOuterHeight; protected int mActionOuterPadding; protected int mActionMinWidth; protected int mActionPadding_w; protected int mActionPadding_h; protected int mDialogHorizontalPadding; protected int mDialogVerticalPadding; protected int mInAnimationId; protected int mOutAnimationId; private final Handler mHandler = new Handler(); private final Runnable mDismissAction = new Runnable() { public void run() { //dirty fix for java.lang.IllegalArgumentException: View not attached to window manager try { Dialog.super.dismiss(); } catch(IllegalArgumentException ex){} } }; private boolean mLayoutActionVertical = false; private boolean mCancelable = true; private boolean mCanceledOnTouchOutside = true; private boolean mDismissPending = false; /** * The viewId of title view. */ public static final int TITLE = ViewUtil.generateViewId(); /** * The viewId of positive action button. */ public static final int ACTION_POSITIVE = ViewUtil.generateViewId(); /** * The viewId of negative action button. */ public static final int ACTION_NEGATIVE = ViewUtil.generateViewId(); /** * The viewId of neutral action button. */ public static final int ACTION_NEUTRAL = ViewUtil.generateViewId(); public Dialog(Context context) { this(context, R.style.Material_App_Dialog_Light); } public Dialog(Context context, int style) { super(context, style); //Override style to ensure not show window's title or background. //TODO: find a way to ensure windowIsFloating attribute is false. requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setBackgroundDrawable(BlankDrawable.getInstance()); WindowManager.LayoutParams layout = getWindow().getAttributes(); layout.width = ViewGroup.LayoutParams.MATCH_PARENT; layout.height = ViewGroup.LayoutParams.MATCH_PARENT; layout.windowAnimations = R.style.DialogNoAnimation; getWindow().setAttributes(layout); init(context, style); } private void init(Context context, int style){ mContentPadding = ThemeUtil.dpToPx(context, 24); mActionMinWidth = ThemeUtil.dpToPx(context, 64); mActionHeight = ThemeUtil.dpToPx(context, 36); mActionOuterHeight = ThemeUtil.dpToPx(context, 48); mActionPadding_h = ThemeUtil.dpToPx(context, 8); mActionPadding_w = ThemeUtil.dpToPx(context, 8); mActionOuterPadding = ThemeUtil.dpToPx(context, 8); mDialogHorizontalPadding = ThemeUtil.dpToPx(context, 40); mDialogVerticalPadding = ThemeUtil.dpToPx(context, 24); mCardView = new DialogCardView(context); mContainer = new ContainerFrameLayout(context); mTitle = new TextView(context); mPositiveAction = new Button(context); mNegativeAction = new Button(context); mNeutralAction = new Button(context); mCardView.setPreventCornerOverlap(false); mCardView.setUseCompatPadding(true); mTitle.setId(TITLE); mTitle.setGravity(Gravity.START); // mTitle.setPadding(mContentPadding, mContentPadding, mContentPadding, mContentPadding - mActionPadding); mTitle.setPadding(mContentPadding, mContentPadding, 0, mContentPadding /2); mPositiveAction.setId(ACTION_POSITIVE); mPositiveAction.setPadding(mActionPadding_w, mActionPadding_h, mActionPadding_w, mActionPadding_h); //设置背景 mPositiveAction.setBackgroundResource(R.drawable.button_white_stroke_green); mNegativeAction.setId(ACTION_NEGATIVE); mNegativeAction.setPadding(mActionPadding_w, mActionPadding_h, mActionPadding_w, mActionPadding_h); mNegativeAction.setBackgroundResource(0); mNeutralAction.setId(ACTION_NEUTRAL); mNeutralAction.setPadding(mActionPadding_w, mActionPadding_h, mActionPadding_w, mActionPadding_h); mNeutralAction.setBackgroundResource(0); mContainer.addView(mCardView); mCardView.addView(mTitle); mCardView.addView(mPositiveAction); mCardView.addView(mNegativeAction); mCardView.addView(mNeutralAction); backgroundColor(ThemeUtil.windowBackground(context, 0xFFFFFFFF)); elevation(ThemeUtil.dpToPx(context, 4)); cornerRadius(ThemeUtil.dpToPx(context, 2)); dimAmount(0.5f); layoutDirection(View.LAYOUT_DIRECTION_LOCALE); titleTextAppearance(R.style.TextAppearance_AppCompat_Title); actionTextAppearance(R.style.TextAppearance_AppCompat_Button); dividerColor(0x1E000000); dividerHeight(ThemeUtil.dpToPx(context, 1)); cancelable(true); canceledOnTouchOutside(true); clearContent(); onCreate(); applyStyle(style); super.setContentView(mContainer); } protected void onCreate(){ } public Dialog applyStyle(int resId){ Context context = getContext(); TypedArray a = context.obtainStyledAttributes(resId, R.styleable.Dialog); int layout_width = mLayoutWidth; int layout_height = mLayoutHeight; boolean layoutParamsDefined = false; int titleTextAppearance = 0; int titleTextColor = 0; boolean titleTextColorDefined = false; int actionBackground = 0; int actionTextAppearance = 0; ColorStateList actionTextColors = null; int positiveActionBackground = 0; int positiveActionTextAppearance = 0; ColorStateList positiveActionTextColors = null; int negativeActionBackground = 0; int negativeActionTextAppearance = 0; ColorStateList negativeActionTextColors = null; int neutralActionBackground = 0; int neutralActionTextAppearance = 0; ColorStateList neutralActionTextColors = null; for(int i = 0, count = a.getIndexCount(); i < count; i++){ int attr = a.getIndex(i); if(attr == R.styleable.Dialog_android_layout_width) { layout_width = a.getLayoutDimension(attr, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParamsDefined = true; } else if(attr == R.styleable.Dialog_android_layout_height) { layout_height = a.getLayoutDimension(attr, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParamsDefined = true; } else if(attr == R.styleable.Dialog_di_maxWidth) maxWidth(a.getDimensionPixelOffset(attr, 0)); else if(attr == R.styleable.Dialog_di_maxHeight) maxHeight(a.getDimensionPixelOffset(attr, 0)); else if(attr == R.styleable.Dialog_di_dimAmount) dimAmount(a.getFloat(attr, 0)); else if(attr == R.styleable.Dialog_di_backgroundColor) backgroundColor(a.getColor(attr, 0)); else if(attr == R.styleable.Dialog_di_maxElevation) maxElevation(a.getDimensionPixelOffset(attr, 0)); else if(attr == R.styleable.Dialog_di_elevation) elevation(a.getDimensionPixelOffset(attr, 0)); else if(attr == R.styleable.Dialog_di_cornerRadius) cornerRadius(a.getDimensionPixelOffset(attr, 0)); else if(attr == R.styleable.Dialog_di_layoutDirection) layoutDirection(a.getInteger(attr, 0)); else if(attr == R.styleable.Dialog_di_titleTextAppearance) titleTextAppearance = a.getResourceId(attr, 0); else if(attr == R.styleable.Dialog_di_titleTextColor) { titleTextColor = a.getColor(attr, 0); titleTextColorDefined = true; } else if(attr == R.styleable.Dialog_di_actionBackground) actionBackground = a.getResourceId(attr, 0); else if(attr == R.styleable.Dialog_di_actionTextAppearance) actionTextAppearance = a.getResourceId(attr, 0); else if(attr == R.styleable.Dialog_di_actionTextColor) actionTextColors = a.getColorStateList(attr); else if(attr == R.styleable.Dialog_di_positiveActionBackground) positiveActionBackground = a.getResourceId(attr, 0); else if(attr == R.styleable.Dialog_di_positiveActionTextAppearance) positiveActionTextAppearance = a.getResourceId(attr, 0); else if(attr == R.styleable.Dialog_di_positiveActionTextColor) positiveActionTextColors = a.getColorStateList(attr); else if(attr == R.styleable.Dialog_di_negativeActionBackground) negativeActionBackground = a.getResourceId(attr, 0); else if(attr == R.styleable.Dialog_di_negativeActionTextAppearance) negativeActionTextAppearance = a.getResourceId(attr, 0); else if(attr == R.styleable.Dialog_di_negativeActionTextColor) negativeActionTextColors = a.getColorStateList(attr); else if(attr == R.styleable.Dialog_di_neutralActionBackground) neutralActionBackground = a.getResourceId(attr, 0); else if(attr == R.styleable.Dialog_di_neutralActionTextAppearance) neutralActionTextAppearance = a.getResourceId(attr, 0); else if(attr == R.styleable.Dialog_di_neutralActionTextColor) neutralActionTextColors = a.getColorStateList(attr); else if(attr == R.styleable.Dialog_di_inAnimation) inAnimation(a.getResourceId(attr, 0)); else if(attr == R.styleable.Dialog_di_outAnimation) outAnimation(a.getResourceId(attr, 0)); else if(attr == R.styleable.Dialog_di_dividerColor) dividerColor(a.getColor(attr, 0)); else if(attr == R.styleable.Dialog_di_dividerHeight) dividerHeight(a.getDimensionPixelOffset(attr, 0)); else if(attr == R.styleable.Dialog_di_cancelable) cancelable(a.getBoolean(attr, true)); else if(attr == R.styleable.Dialog_di_canceledOnTouchOutside) canceledOnTouchOutside(a.getBoolean(attr, true)); } a.recycle(); if(layoutParamsDefined) layoutParams(layout_width, layout_height); if(titleTextAppearance != 0) titleTextAppearance(titleTextAppearance); if(titleTextColorDefined) titleColor(titleTextColor); if(actionBackground != 0) actionBackground(actionBackground); if(actionTextAppearance != 0) actionTextAppearance(actionTextAppearance); if(actionTextColors != null) actionTextColor(actionTextColors); if(positiveActionBackground != 0) positiveActionBackground(positiveActionBackground); if(positiveActionTextAppearance!= 0) positiveActionTextAppearance(positiveActionTextAppearance); if(positiveActionTextColors != null) positiveActionTextColor(positiveActionTextColors); if(negativeActionBackground != 0) negativeActionBackground(negativeActionBackground); if(negativeActionTextAppearance!= 0) negativeActionTextAppearance(negativeActionTextAppearance); if(negativeActionTextColors != null) negativeActionTextColor(negativeActionTextColors); if(neutralActionBackground != 0) neutralActionBackground(neutralActionBackground); if(neutralActionTextAppearance!= 0) neutralActionTextAppearance(neutralActionTextAppearance); if(neutralActionTextColors != null) neutralActionTextColor(neutralActionTextColors); return this; } /** * Clear the content of this Dialog. * @return The Dialog for chaining methods. */ public Dialog clearContent(){ title(0); positiveAction(0); positiveActionClickListener(null); negativeAction(0); negativeActionClickListener(null); neutralAction(0); neutralActionClickListener(null); contentView(null); return this; } /** * Set the params of this Dialog layout. * @param width The width param. Can be the size in pixels, or {@link ViewGroup.LayoutParams#WRAP_CONTENT} or {@link ViewGroup.LayoutParams#MATCH_PARENT}. * @param height The height param. Can be the size in pixels, or {@link ViewGroup.LayoutParams#WRAP_CONTENT} or {@link ViewGroup.LayoutParams#MATCH_PARENT}. * @return The Dialog for chaining methods. */ public Dialog layoutParams(int width, int height){ mLayoutWidth = width; mLayoutHeight = height; return this; } /** * Set the maximum width of this Dialog layout. * @param width The maximum width in pixels. * @return The Dialog for chaining methods. */ public Dialog maxWidth(int width){ mMaxWidth = width; return this; } /** * Set the maximum height of this Dialog layout. * @param height The maximum height in pixels. * @return The Dialog for chaining methods. */ public Dialog maxHeight(int height){ mMaxHeight = height; return this; } /** * Set the dim amount of the region outside this Dialog. * @param amount The dim amount in [0..1]. * @return The Dialog for chaining methods. */ public Dialog dimAmount(float amount){ Window window = getWindow(); if(amount > 0f){ window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); WindowManager.LayoutParams lp = window.getAttributes(); lp.dimAmount = amount; window.setAttributes(lp); } else window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); return this; } /** * Set the background color of this Dialog * @param color The color value. * @return The Dialog for chaining methods. */ public Dialog backgroundColor(int color){ mCardView.setCardBackgroundColor(color); return this; } /** * Set the elevation value of this Dialog. * @param elevation * @return The Dialog for chaining methods. */ public Dialog elevation(float elevation){ if(mCardView.getMaxCardElevation() < elevation) mCardView.setMaxCardElevation(elevation); mCardView.setCardElevation(elevation); return this; } /** * Set the maximum elevation value of this Dialog. * @param elevation * @return The Dialog for chaining methods. */ public Dialog maxElevation(float elevation){ mCardView.setMaxCardElevation(elevation); return this; } /** * Set the corner radius of this Dialog. * @param radius The corner radius. * @return The Dialog for chaining methods. */ public Dialog cornerRadius(float radius){ mCardView.setRadius(radius); return this; } /** * Set the divider's color of this Dialog. * @param color The color value. * @return The Dialog for chaining methods. */ public Dialog dividerColor(int color){ mCardView.setDividerColor(color); return this; } /** * Set the height of divider of this Dialog. * @param height The size value in pixels. * @return The Dialog for chaining methods. */ public Dialog dividerHeight(int height){ mCardView.setDividerHeight(height); return this; } /** * Set the title of this Dialog. * @param title The title text. * @return The Dialog for chaining methods. */ public Dialog title(CharSequence title){ mTitle.setText(title); mTitle.setVisibility(TextUtils.isEmpty(title) ? View.GONE : View.VISIBLE); return this; } /** * Set the title of this Dialog. * @param id The resourceId of text. * @return The Dialog for chaining methods. */ public Dialog title(int id){ return title(id == 0 ? null : getContext().getResources().getString(id)); } @Override public void setTitle(CharSequence title) { title(title); } @Override public void setTitle(int titleId) { title(titleId); } /** * Set the text's color of Dialog's title. * @param color The color value. * @return The Dialog for chaining methods. */ public Dialog titleColor(int color){ mTitle.setTextColor(color); return this; } public TextView getTitle(){ return mTitle; } /** * Sets the text color, size, style of the title view from the specified TextAppearance resource. * @param resId The resourceId value. * @return The Dialog for chaining methods. */ public Dialog titleTextAppearance(int resId){ mTitle.setTextAppearance(getContext(), resId); return this; } /** * Set the background drawable of all action buttons. * @param id The resourceId of drawable. * @return The Dialog for chaining methods. */ public Dialog actionBackground(int id){ positiveActionBackground(id); negativeActionBackground(id); neutralActionBackground(id); return this; } /** * Set the background drawable of all action buttons. * @param drawable The background drawable. * @return The Dialog for chaining methods. */ public Dialog actionBackground(Drawable drawable){ positiveActionBackground(drawable); negativeActionBackground(drawable); neutralActionBackground(drawable); return this; } /** * Sets the text color, size, style of all action buttons from the specified TextAppearance resource. * @param resId The resourceId value. * @return The Dialog for chaining methods. */ public Dialog actionTextAppearance(int resId){ positiveActionTextAppearance(resId); negativeActionTextAppearance(resId); neutralActionTextAppearance(resId); return this; } /** * Sets the text color of all action buttons. * @param color * @return The Dialog for chaining methods. */ public Dialog actionTextColor(ColorStateList color){ positiveActionTextColor(color); negativeActionTextColor(color); neutralActionTextColor(color); return this; } /** * Sets the text color of all action buttons. * @param color * @return The Dialog for chaining methods. */ public Dialog actionTextColor(int color){ positiveActionTextColor(color); negativeActionTextColor(color); neutralActionTextColor(color); return this; } /** * Set the text of positive action button. * @param action * @return The Dialog for chaining methods. */ public Dialog positiveAction(CharSequence action){ mPositiveAction.setText(action); mPositiveAction.setVisibility(TextUtils.isEmpty(action) ? View.GONE : View.VISIBLE); return this; } /** * Set the text of positive action button. * @param id The resourceId of text. * @return The Dialog for chaining methods. */ public Dialog positiveAction(int id){ return positiveAction(id == 0 ? null : getContext().getResources().getString(id)); } /** * Set the background drawable of positive action button. * @param drawable The background drawable. * @return The Dialog for chaining methods. */ public Dialog positiveActionBackground(Drawable drawable){ ViewUtil.setBackground(mPositiveAction, drawable); return this; } /** * Set the background drawable of positive action button. * @param id The resourceId of drawable. * @return The Dialog for chaining methods. */ public Dialog positiveActionBackground(int id){ return positiveActionBackground(id == 0 ? null : getContext().getResources().getDrawable(id)); } /** * Sets the text color, size, style of positive action button from the specified TextAppearance resource. * @param resId The resourceId value. * @return The Dialog for chaining methods. */ public Dialog positiveActionTextAppearance(int resId){ mPositiveAction.setTextAppearance(getContext(), resId); return this; } /** * Sets the text color of positive action button. * @param color * @return The Dialog for chaining methods. */ public Dialog positiveActionTextColor(ColorStateList color){ mPositiveAction.setTextColor(color); return this; } /** * Sets the text color of positive action button. * @param color * @return The Dialog for chaining methods. */ public Dialog positiveActionTextColor(int color){ mPositiveAction.setTextColor(color); return this; } /** * Set a listener will be called when positive action button is clicked. * @param listener The {@link View.OnClickListener} will be called. * @return The Dialog for chaining methods. */ public Dialog positiveActionClickListener(View.OnClickListener listener){ mPositiveAction.setOnClickListener(listener); return this; } /** * Set the text of negative action button. * @param action * @return The Dialog for chaining methods. */ public Dialog negativeAction(CharSequence action){ mNegativeAction.setText(action); mNegativeAction.setVisibility(TextUtils.isEmpty(action) ? View.GONE : View.VISIBLE); return this; } /** * Set the text of negative action button. * @param id The resourceId of text. * @return The Dialog for chaining methods. */ public Dialog negativeAction(int id){ return negativeAction(id == 0 ? null : getContext().getResources().getString(id)); } /** * Set the background drawable of negative action button. * @param drawable The background drawable. * @return The Dialog for chaining methods. */ public Dialog negativeActionBackground(Drawable drawable){ ViewUtil.setBackground(mNegativeAction, drawable); return this; } /** * Set the background drawable of neagtive action button. * @param id The resourceId of drawable. * @return The Dialog for chaining methods. */ public Dialog negativeActionBackground(int id){ return negativeActionBackground(id == 0 ? null : getContext().getResources().getDrawable(id)); } /** * Sets the text color, size, style of negative action button from the specified TextAppearance resource. * @param resId The resourceId value. * @return The Dialog for chaining methods. */ public Dialog negativeActionTextAppearance(int resId){ mNegativeAction.setTextAppearance(getContext(), resId); return this; } /** * Sets the text color of negative action button. * @param color * @return The Dialog for chaining methods. */ public Dialog negativeActionTextColor(ColorStateList color){ mNegativeAction.setTextColor(color); return this; } /** * Sets the text color of negative action button. * @param color * @return The Dialog for chaining methods. */ public Dialog negativeActionTextColor(int color){ mNegativeAction.setTextColor(color); return this; } /** * Set a listener will be called when negative action button is clicked. * @param listener The {@link View.OnClickListener} will be called. * @return The Dialog for chaining methods. */ public Dialog negativeActionClickListener(View.OnClickListener listener){ mNegativeAction.setOnClickListener(listener); return this; } /** * Set the text of neutral action button. * @param action * @return The Dialog for chaining methods. */ public Dialog neutralAction(CharSequence action){ mNeutralAction.setText(action); mNeutralAction.setVisibility(TextUtils.isEmpty(action) ? View.GONE : View.VISIBLE); return this; } /** * Set the text of neutral action button. * @param id The resourceId of text. * @return The Dialog for chaining methods. */ public Dialog neutralAction(int id){ return neutralAction(id == 0 ? null : getContext().getResources().getString(id)); } /** * Set the background drawable of neutral action button. * @param drawable The background drawable. * @return The Dialog for chaining methods. */ public Dialog neutralActionBackground(Drawable drawable){ ViewUtil.setBackground(mNeutralAction, drawable); return this; } /** * Set the background drawable of neutral action button. * @param id The resourceId of drawable. * @return The Dialog for chaining methods. */ public Dialog neutralActionBackground(int id){ return neutralActionBackground(id == 0 ? null : getContext().getResources().getDrawable(id)); } /** * Sets the text color, size, style of neutral action button from the specified TextAppearance resource. * @param resId The resourceId value. * @return The Dialog for chaining methods. */ public Dialog neutralActionTextAppearance(int resId){ mNeutralAction.setTextAppearance(getContext(), resId); return this; } /** * Sets the text color of neutral action button. * @param color * @return The Dialog for chaining methods. */ public Dialog neutralActionTextColor(ColorStateList color){ mNeutralAction.setTextColor(color); return this; } /** * Sets the text color of neutral action button. * @param color * @return The Dialog for chaining methods. */ public Dialog neutralActionTextColor(int color){ mNeutralAction.setTextColor(color); return this; } /** * Set a listener will be called when neutral action button is clicked. * @param listener The {@link View.OnClickListener} will be called. * @return The Dialog for chaining methods. */ public Dialog neutralActionClickListener(View.OnClickListener listener){ mNeutralAction.setOnClickListener(listener); return this; } /** * Set the layout direction of this Dialog * @param direction The layout direction value. Can be {@link View#LAYOUT_DIRECTION_LTR}, {@link View#LAYOUT_DIRECTION_RTL} or {@link View#LAYOUT_DIRECTION_LOCALE} * @return The Dialog for chaining methods. */ public Dialog layoutDirection(int direction){ ViewCompat.setLayoutDirection(mCardView, direction); return this; } /** * Set the animation when Dialog enter the screen. * @param resId The resourceId of animation. * @return The Dialog for chaining methods. */ public Dialog inAnimation(int resId){ mInAnimationId = resId; return this; } /** * Set the animation when Dialog exit the screen. * @param resId The resourceId of animation. * @return The Dialog for chaining methods. */ public Dialog outAnimation(int resId){ mOutAnimationId = resId; return this; } /** * Indicate that Dialog should show divider when the content is longer than container view. * @param show * @return The Dialog for chaining methods. */ public Dialog showDivider(boolean show){ mCardView.setShowDivider(show); return this; } /** * Set the content view of this Dialog. * @param v The content view. * @return The Dialog for chaining methods. */ public Dialog contentView(View v){ if(mContent != v) { if(mContent != null) mCardView.removeView(mContent); mContent = v; } if(mContent != null) mCardView.addView(mContent); return this; } /** * Set the content view of this Dialog. * @param layoutId The reourceId of layout. * @return The Dialog for chaining methods. */ public Dialog contentView(int layoutId){ if(layoutId == 0) return this; View v = LayoutInflater.from(getContext()).inflate(layoutId, null); return contentView(v); } /** * Sets whether this dialog is cancelable with the * {@link android.view.KeyEvent#KEYCODE_BACK BACK} key. * @return The Dialog for chaining methods. */ public Dialog cancelable(boolean cancelable){ super.setCancelable(cancelable); mCancelable = cancelable; return this; } /** * Sets whether this dialog is canceled when touched outside the window's * bounds. If setting to true, the dialog is set to be cancelable if not * already set. * * @param cancel Whether the dialog should be canceled when touched outside * @return The Dialog for chaining methods. */ public Dialog canceledOnTouchOutside(boolean cancel){ super.setCanceledOnTouchOutside(cancel); mCanceledOnTouchOutside = cancel; return this; } /** * Set the margin between content view and Dialog border. * @param margin The margin size in pixels. * @return The Dialog for chaining methods. */ public Dialog contentMargin(int margin){ mCardView.setContentMargin(margin); return this; } /** * Set the margin between content view and Dialog border. * @param left The left margin size in pixels. * @param top The top margin size in pixels. * @param right The right margin size in pixels. * @param bottom The bottom margin size in pixels. * @return The Dialog for chaining methods. */ public Dialog contentMargin(int left, int top, int right, int bottom){ mCardView.setContentMargin(left, top, right, bottom); return this; } @Override public void setCancelable(boolean flag) { cancelable(flag); } @Override public void setCanceledOnTouchOutside(boolean cancel) { canceledOnTouchOutside(cancel); } @Override public void setContentView(View v){ contentView(v); } @Override public void setContentView(int layoutId){ contentView(layoutId); } @Override public void setContentView(View v, ViewGroup.LayoutParams params) { contentView(v); } @Override public void addContentView(View view, ViewGroup.LayoutParams params) { contentView(view); } @Override protected void onStart() { super.onStart(); mCardView.setVisibility(View.VISIBLE); if(mInAnimationId != 0) mCardView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() { @Override public boolean onPreDraw() { mCardView.getViewTreeObserver().removeOnPreDrawListener(this); Animation anim = AnimationUtils.loadAnimation(mCardView.getContext(), mInAnimationId); mCardView.startAnimation(anim); return false; } }); } /** * Dismiss Dialog immediately without showing out animation. */ public void dismissImmediately(){ super.dismiss(); if(mHandler != null) mHandler.removeCallbacks(mDismissAction); } @Override public void dismiss() { if(!isShowing() || mDismissPending) return; if(mOutAnimationId != 0){ Animation anim = AnimationUtils.loadAnimation(mContainer.getContext(), mOutAnimationId); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { mDismissPending = true; } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationEnd(Animation animation) { mDismissPending = false; mCardView.setVisibility(View.GONE); mHandler.post(mDismissAction); } }); mCardView.startAnimation(anim); } else mHandler.post(mDismissAction); } private class ContainerFrameLayout extends FrameLayout { private boolean mClickOutside = false; public ContainerFrameLayout(Context context) { super(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); mCardView.measure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(widthSize, heightSize); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int childLeft = (right - left - mCardView.getMeasuredWidth()) / 2; int childTop = (bottom - top - mCardView.getMeasuredHeight()) / 2; int childRight = childLeft + mCardView.getMeasuredWidth(); int childBottom = childTop + mCardView.getMeasuredHeight(); mCardView.layout(childLeft, childTop, childRight, childBottom); } private boolean isOutsideDialog(float x, float y){ return x < mCardView.getLeft() + mCardView.getPaddingLeft() || x > mCardView.getRight() - mCardView.getPaddingRight() || y < mCardView.getTop() + mCardView.getPaddingTop() || y > mCardView.getBottom() - mCardView.getPaddingBottom(); } @Override public boolean onTouchEvent(MotionEvent event) { boolean handled = super.onTouchEvent(event); if(handled) return true; switch (event.getAction()){ case MotionEvent.ACTION_DOWN: if(isOutsideDialog(event.getX(), event.getY())){ mClickOutside = true; return true; } return false; case MotionEvent.ACTION_MOVE: return mClickOutside; case MotionEvent.ACTION_CANCEL: mClickOutside = false; return false; case MotionEvent.ACTION_UP: if(mClickOutside && isOutsideDialog(event.getX(), event.getY())){ mClickOutside = false; if(mCancelable && mCanceledOnTouchOutside) dismiss(); return true; } return false; } return false; } } private class DialogCardView extends CardView { private Paint mDividerPaint; private float mDividerPos = -1f; private boolean mShowDivider = false; private int mContentMarginLeft; private int mContentMarginTop; private int mContentMarginRight; private int mContentMarginBottom; private boolean mIsRtl = false; public DialogCardView(Context context) { super(context); mDividerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mDividerPaint.setStyle(Paint.Style.STROKE); setWillNotDraw(false); } public void setContentMargin(int margin){ setContentMargin(margin, margin, margin, margin); } public void setContentMargin(int left, int top, int right, int bottom){ mContentMarginLeft = left; mContentMarginTop = top; mContentMarginRight = right; mContentMarginBottom = bottom; } public void setDividerColor(int color){ mDividerPaint.setColor(color); invalidate(); } public void setDividerHeight(int height){ mDividerPaint.setStrokeWidth(height); invalidate(); } public void setShowDivider(boolean show){ if(mShowDivider != show) { mShowDivider = show; invalidate(); } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) @Override public void onRtlPropertiesChanged(int layoutDirection) { boolean rtl = layoutDirection == LAYOUT_DIRECTION_RTL; if(mIsRtl != rtl) { mIsRtl = rtl; if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){ int direction = mIsRtl ? TEXT_DIRECTION_RTL : TEXT_DIRECTION_LTR; mTitle.setTextDirection(direction); mPositiveAction.setTextDirection(direction); mNegativeAction.setTextDirection(direction); mNeutralAction.setTextDirection(direction); } requestLayout(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int paddingLeft = Math.max(mDialogHorizontalPadding, mCardView.getPaddingLeft()); int paddingRight = Math.max(mDialogHorizontalPadding, mCardView.getPaddingRight()); int paddingTop = Math.max(mDialogVerticalPadding, mCardView.getPaddingTop()); int paddingBottom = Math.max(mDialogVerticalPadding, mCardView.getPaddingBottom()); int maxWidth = widthSize - paddingLeft - paddingRight; if(mMaxWidth > 0) maxWidth = Math.min(maxWidth, mMaxWidth); int maxHeight = heightSize - paddingTop - paddingBottom; if(mMaxHeight > 0) maxHeight = Math.min(maxHeight, mMaxHeight); int width = mLayoutWidth == ViewGroup.LayoutParams.MATCH_PARENT ? maxWidth : mLayoutWidth; int height = mLayoutHeight == ViewGroup.LayoutParams.MATCH_PARENT ? maxHeight : mLayoutHeight; int widthMs; int heightMs; int titleWidth = 0; int titleHeight = 0; if(mTitle.getVisibility() == View.VISIBLE){ widthMs = MeasureSpec.makeMeasureSpec(width == ViewGroup.LayoutParams.WRAP_CONTENT ? maxWidth : width, MeasureSpec.AT_MOST); heightMs = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST); mTitle.measure(widthMs, heightMs); titleWidth = mTitle.getMeasuredWidth(); titleHeight = mTitle.getMeasuredHeight(); } int contentWidth = 0; int contentHeight = 0; if(mContent != null){ widthMs = MeasureSpec.makeMeasureSpec((width == ViewGroup.LayoutParams.WRAP_CONTENT ? maxWidth : width) - mContentMarginLeft - mContentMarginRight, MeasureSpec.AT_MOST); heightMs = MeasureSpec.makeMeasureSpec(maxHeight - mContentMarginTop - mContentMarginBottom, MeasureSpec.AT_MOST); mContent.measure(widthMs, heightMs); contentWidth = mContent.getMeasuredWidth(); contentHeight = mContent.getMeasuredHeight(); } int visibleActions = 0; int positiveActionWidth = 0; if(mPositiveAction.getVisibility() == View.VISIBLE){ widthMs = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); heightMs = MeasureSpec.makeMeasureSpec(mActionHeight, MeasureSpec.EXACTLY); mPositiveAction.measure(widthMs, heightMs); positiveActionWidth = mPositiveAction.getMeasuredWidth(); if(positiveActionWidth < mActionMinWidth){ mPositiveAction.measure(MeasureSpec.makeMeasureSpec(mActionMinWidth, MeasureSpec.EXACTLY), heightMs); positiveActionWidth = mActionMinWidth; } visibleActions++; } int negativeActionWidth = 0; if(mNegativeAction.getVisibility() == View.VISIBLE){ widthMs = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); heightMs = MeasureSpec.makeMeasureSpec(mActionHeight, MeasureSpec.EXACTLY); mNegativeAction.measure(widthMs, heightMs); negativeActionWidth = mNegativeAction.getMeasuredWidth(); if(negativeActionWidth < mActionMinWidth){ mNegativeAction.measure(MeasureSpec.makeMeasureSpec(mActionMinWidth, MeasureSpec.EXACTLY), heightMs); negativeActionWidth = mActionMinWidth; } visibleActions++; } int neutralActionWidth = 0; if(mNeutralAction.getVisibility() == View.VISIBLE){ widthMs = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); heightMs = MeasureSpec.makeMeasureSpec(mActionHeight, MeasureSpec.EXACTLY); mNeutralAction.measure(widthMs, heightMs); neutralActionWidth = mNeutralAction.getMeasuredWidth(); if(neutralActionWidth < mActionMinWidth){ mNeutralAction.measure(MeasureSpec.makeMeasureSpec(mActionMinWidth, MeasureSpec.EXACTLY), heightMs); neutralActionWidth = mActionMinWidth; } visibleActions++; } int actionBarWidth = positiveActionWidth + negativeActionWidth + neutralActionWidth + mActionOuterPadding * 2 + mActionPadding_w * Math.max(0, visibleActions - 1); if(width == ViewGroup.LayoutParams.WRAP_CONTENT) width = Math.min(maxWidth, Math.max(titleWidth, Math.max(contentWidth + mContentMarginLeft + mContentMarginRight, actionBarWidth))); mLayoutActionVertical = actionBarWidth > width; // mLayoutActionVertical=false; int nonContentHeight = titleHeight + (visibleActions > 0 ? mActionPadding_h : 0) + mContentMarginTop + mContentMarginBottom; if(mLayoutActionVertical) nonContentHeight += mActionOuterHeight * visibleActions; else nonContentHeight += (visibleActions > 0) ? mActionOuterHeight : 0; if(height == ViewGroup.LayoutParams.WRAP_CONTENT) height = Math.min(maxHeight, contentHeight + nonContentHeight); if(mContent != null) mContent.measure(MeasureSpec.makeMeasureSpec(width - mContentMarginLeft - mContentMarginRight, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height - nonContentHeight, MeasureSpec.EXACTLY)); setMeasuredDimension(width + getPaddingLeft() + getPaddingRight(), height + getPaddingTop() + getPaddingBottom()); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { int childLeft = 0; int childTop = 0; int childRight = right - left; int childBottom = bottom - top; childLeft += getPaddingLeft(); childTop += getPaddingTop(); childRight -= getPaddingRight(); childBottom -= getPaddingBottom(); if(mTitle.getVisibility() == View.VISIBLE) { if(mIsRtl) mTitle.layout(childRight - mTitle.getMeasuredWidth(), childTop, childRight, childTop + mTitle.getMeasuredHeight()); else mTitle.layout(childLeft, childTop, childLeft + mTitle.getMeasuredWidth(), childTop + mTitle.getMeasuredHeight()); childTop += mTitle.getMeasuredHeight(); } boolean hasAction = mNeutralAction.getVisibility() == View.VISIBLE || mNegativeAction.getVisibility() == View.VISIBLE || mPositiveAction.getVisibility() == View.VISIBLE; if(hasAction) childBottom -= mActionPadding_h; int temp = (mActionOuterHeight - mActionHeight) / 2; if(hasAction){ if(mLayoutActionVertical){ if(mNeutralAction.getVisibility() == View.VISIBLE){ mNeutralAction.layout(childRight - mActionOuterPadding - mNeutralAction.getMeasuredWidth(), childBottom - mActionOuterHeight + temp, childRight - mActionOuterPadding, childBottom - temp); childBottom -= mActionOuterHeight; } if(mNegativeAction.getVisibility() == View.VISIBLE){ mNegativeAction.layout(childRight - mActionOuterPadding - mNegativeAction.getMeasuredWidth(), childBottom - mActionOuterHeight + temp, childRight - mActionOuterPadding, childBottom - temp); childBottom -= mActionOuterHeight; } if(mPositiveAction.getVisibility() == View.VISIBLE){ mPositiveAction.layout(childRight - mActionOuterPadding - mPositiveAction.getMeasuredWidth(), childBottom - mActionOuterHeight + temp, childRight - mActionOuterPadding, childBottom - temp); childBottom -= mActionOuterHeight; } } else{ int actionLeft = childLeft + mActionOuterPadding; int actionRight = childRight - mActionOuterPadding; int actionTop = childBottom - mActionOuterHeight + temp; int actionBottom = childBottom - temp; if(mIsRtl){ if (mPositiveAction.getVisibility() == View.VISIBLE) { mPositiveAction.layout(actionLeft , actionTop, actionLeft + mPositiveAction.getMeasuredWidth(), actionBottom); actionLeft += mPositiveAction.getMeasuredWidth() + mActionPadding_w; } if (mNegativeAction.getVisibility() == View.VISIBLE) mNegativeAction.layout(actionLeft, actionTop, actionLeft + mNegativeAction.getMeasuredWidth(), actionBottom); if (mNeutralAction.getVisibility() == View.VISIBLE) mNeutralAction.layout(actionRight - mNeutralAction.getMeasuredWidth(), actionTop, actionRight, actionBottom); } else { if (mPositiveAction.getVisibility() == View.VISIBLE) { mPositiveAction.layout(actionRight - mPositiveAction.getMeasuredWidth(), actionTop, actionRight, actionBottom); actionRight -= mPositiveAction.getMeasuredWidth() + mActionPadding_w; } if (mNegativeAction.getVisibility() == View.VISIBLE) mNegativeAction.layout(actionRight - mNegativeAction.getMeasuredWidth(), actionTop, actionRight, actionBottom); if (mNeutralAction.getVisibility() == View.VISIBLE) mNeutralAction.layout(actionLeft, actionTop, actionLeft + mNeutralAction.getMeasuredWidth(), actionBottom); } childBottom -= mActionOuterHeight; } } mDividerPos = childBottom - mDividerPaint.getStrokeWidth() / 2f; if(mContent != null) mContent.layout(childLeft + mContentMarginLeft, childTop + mContentMarginTop, childRight - mContentMarginRight, childBottom - mContentMarginBottom); } @Override public void draw(Canvas canvas) { super.draw(canvas); if(mShowDivider && (mPositiveAction.getVisibility() == View.VISIBLE || mNegativeAction.getVisibility() == View.VISIBLE || mNeutralAction.getVisibility() == View.VISIBLE)) canvas.drawLine(getPaddingLeft(), mDividerPos, getWidth() - getPaddingRight(), mDividerPos, mDividerPaint); } } public static class Builder implements DialogFragment.Builder, Parcelable { protected int mStyleId; protected int mContentViewId; protected CharSequence mTitle; protected CharSequence mPositive; protected CharSequence mNegative; protected CharSequence mNeutral; protected Dialog mDialog; public Builder(){ this(R.style.Material_App_Dialog_Light); } public Builder(int styleId){ mStyleId = styleId; } public Builder style(int styleId){ mStyleId = styleId; return this; } public Builder contentView(int layoutId){ mContentViewId = layoutId; return this; } public Builder title(CharSequence title){ mTitle = title; return this; } public Builder positiveAction(CharSequence action){ mPositive = action; return this; } public Builder negativeAction(CharSequence action){ mNegative = action; return this; } public Builder neutralAction(CharSequence action){ mNeutral = action; return this; } public Dialog getDialog(){ return mDialog; } @Override public void onPositiveActionClicked(DialogFragment fragment) { fragment.dismiss(); } @Override public void onNegativeActionClicked(DialogFragment fragment) { fragment.dismiss(); } @Override public void onNeutralActionClicked(DialogFragment fragment) { fragment.dismiss(); } @Override public void onCancel(DialogInterface dialog) {} @Override public void onDismiss(DialogInterface dialog) {} @Override public Dialog build(Context context) { mDialog = onBuild(context, mStyleId); mDialog.title(mTitle) .positiveAction(mPositive) .negativeAction(mNegative) .neutralAction(mNeutral); if(mContentViewId != 0) mDialog.contentView(mContentViewId); onBuildDone(mDialog); return mDialog; } /** * Get a appropriate Dialog instance will be used for styling later. * Child class should override this function to return appropriate Dialog instance. * If you want to apply styling to dialog, or get content view, you should do it in {@link #onBuildDone(Dialog)} * @param context A Context instance. * @param styleId The resourceId of Dialog's style. * @return A Dialog instance will be used for styling later. */ protected Dialog onBuild(Context context, int styleId){ return new Dialog(context, styleId); } /** * This function will be called after Builder done apply styling to Dialog. * @param dialog The Dialog instance. */ protected void onBuildDone(Dialog dialog){} protected Builder(Parcel in) { mStyleId = in.readInt(); mContentViewId = in.readInt(); mTitle = (CharSequence)in.readValue(null); mPositive = (CharSequence)in.readValue(null); mNegative = (CharSequence)in.readValue(null); mNeutral = (CharSequence)in.readValue(null); onReadFromParcel(in); } /** * Child class should override this function and read back any saved attributes. * All read methods should be called after super.onReadFromParcel() call to keep the order. */ protected void onReadFromParcel(Parcel in){} /** * Child class should override this function and write down all attributes will be saved. * All write methods should be called after super.onWriteToParcel() call to keep the order. */ protected void onWriteToParcel(Parcel dest, int flags){} @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(mStyleId); dest.writeInt(mContentViewId); dest.writeValue(mTitle); dest.writeValue(mPositive); dest.writeValue(mNegative); dest.writeValue(mNeutral); onWriteToParcel(dest, flags); } @Override public int describeContents() { return 0; } public static final Creator CREATOR = new Creator() { public Builder createFromParcel(Parcel in) { return new Builder(in); } public Builder[] newArray(int size) { return new Builder[size]; } }; } } src/main/java/bjc/esodata/Stack.java0 package bjc.esodata; import java.util.*; import java.util.function.*; /* * @TODO 10/11/17 :StackCombinators * Implement more combinators for the stack. */ /** * A stack, with support for forth/factor style stack combinators. * *

*

Stack underflow

*

* NOTE: In general, using any operation that attempts to remove more data from * the stack than exists will cause a {@link StackUnderflow} to be thrown. Check * the size of the stack if you want to avoid this. *

*

* * @param * The datatype stored in the stack. * * @author */ public abstract class Stack { /** * The exception thrown when attempting to access an element from the stack that * isn't there. * * @author EVE */ public static class StackUnderflow extends RuntimeException { /* The ID of the exception */ private static final long serialVersionUID = 1423867176204571539L; } /** * Push an element onto the stack. * * @param elm * The element to insert. */ public abstract void push(T elm); /** * Pop an element off of the stack. * * @return The element on top of the stack. */ public abstract T pop(); /** * Retrieve the top element of this stack without removing it from the stack. * * @return The top element of this stack. */ public abstract T top(); /** * Get the number of elements in the stack. * * @return the number of elements in the stack. */ public abstract int size(); /** * Check if the stack is empty. * * @return Whether or not the stack is empty. */ public boolean isEmpty() { return size() == 0; } /** * Create a spaghetti stack branching off of this one. * * @return A spaghetti stack with this stack as a parent. */ public Stack spaghettify() { return new SpaghettiStack<>(this); } /* * Multi-item add/remove. */ /** * Push multiple elements onto the stack. * * @param elms * The elements to insert. */ public void pushAll(@SuppressWarnings("unchecked") T... elms) { for (T elm : elms) push(elm); } /** * Push multiple elements onto the stack. * * @param elms * The elements to insert. */ public void pushAll(List elms) { for (T elm : elms) push(elm); } /** * Pop n items off of the stack and return them. * * @param n * The number of items to pop off of the stack. * * @return A list of the popped items, in the order they were popped. */ public List multipop(int n) { List lst = new LinkedList<>(); for (int i = 0; i < n; i++) lst.add(pop()); return lst; } /** * Pop n items off of the stack and return them. * * @param n * The number of items to pop off of the stack. * * @return A list of the popped items, in the reverse order they were popped. */ public List multipoprev(int n) { LinkedList lst = new LinkedList<>(); for (int i = 0; i < n; i++) lst.addFirst(pop()); return lst; } /* * Basic combinators */ /** * Drop n items from the stack. * * @param n * The number of items to drop. */ public void drop(final int n) { for (int i = 0; i < n; i++) pop(); } /** Drop one item from the stack. */ public void drop() { drop(1); } /** * Delete n items below the current one. * * @param n * The number of items below the top to delete. */ public void nip(final int n) { final T elm = pop(); drop(n); push(elm); } /** Delete the second element in the stack. */ public void nip() { nip(1); } /** * Replicate the top n items of the stack m times. * * @param n * The number of items to duplicate. * * @param m * The number of times to duplicate items. */ public void multidup(final int n, final int m) { List lst = multipoprev(n); for (int i = 0; i <= m; i++) pushAll(lst); } /** * Duplicate the top n items of the stack. * * @param n * The number of items to duplicate. */ public void dup(final int n) { multidup(n, 1); } /** Duplicate the top item on the stack. */ public void dup() { dup(1); } /** * Replicate the n elements below the top one m times. * * @param n * The number of items to duplicate. * * @param m * The number of times to duplicate items. */ public void multiover(final int n, final int m) { T elm = pop(); List lst = multipoprev(n); for (final T nelm : lst) push(nelm); push(elm); for (int i = 0; i < m; i++) pushAll(lst); } /** * Duplicate the n elements below the top one. * * @param n * The number of items to duplicate. */ public void over(final int n) { multiover(n, 1); } /** Duplicate the second item in the stack. */ public void over() { over(1); } /** Duplicate the third item in the stack. */ public void pick() { final T z = pop(); final T y = pop(); final T x = pop(); push(x); push(y); push(z); push(x); } /** * Rotate the n items m deep on the stack i positions. * * @param n * The number of items to rotate. * @param m * The number of positions the item is down in the stack. * @param i * The number of steps to rotate. Pass a negative number to rotate * things in the opposite direction. */ public void deepmultirot(int n, int m, int i) { List kep = multipoprev(m); List lst = multipoprev(n); Collections.rotate(lst, i); pushAll(lst); pushAll(kep); } /** * Rotate the n items on top of the stack i positions. * * @param n * The number of items to rotate. * @param i * The number of steps to rotate. Pass a negative number to rotate * things in the opposite direction. */ public void multirot(int n, int i) { deepmultirot(n, 0, i); } /** Swap the top two items on the stack. */ public void swap() { multirot(2, 1); } /** Duplicate the second item below the first item. */ public void deepdup() { final T y = pop(); final T x = pop(); push(x); push(x); push(y); } /** Swap the second and third items in the stack. */ public void deepswap() { deepmultirot(2, 1, 1); } /** * Rotate the top three items on the stack */ public void rot() { final T z = pop(); final T y = pop(); final T x = pop(); push(y); push(z); push(x); } /** Inversely rotate the top three items on the stack */ public void invrot() { final T z = pop(); final T y = pop(); final T x = pop(); push(z); push(x); push(y); } /* * Dataflow Combinators */ /** * Hides the top n elements on the stack from an action. * * @param n * The number of elements to hide. * * @param action * The action to hide the elements from */ public void dip(final int n, final Consumer> action) { List elms = multipoprev(n); action.accept(this); pushAll(elms); } /** * Hide the top element of the stack from an action. * * @param action * The action to hide the top from */ public void dip(final Consumer> action) { dip(1, action); } /** * Copy the top n elements on the stack, replacing them once an action is done. * * @param n * The number of elements to copy. * * @param action * The action to execute. */ public void keep(final int n, final Consumer> action) { dup(n); dip(n, action); } /** * Copy the first element on the stack, replacing them once an action is done. * * @param action * The action to execute. */ public void keep(final Consumer> action) { keep(1, action); } /** * Apply all the actions in a list to the top n elements of the stack. * * @param n * The number of elements to give to cons. * * @param actions * The actions to execute. */ public void multicleave(final int n, final List>> actions) { List elms = multipoprev(n); for (final Consumer> action : actions) { pushAll(elms); action.accept(this); } } /** * Apply all the actions in a list to the top n elements of the stack. * * @param n * The number of elements to give to cons. * * @param actions * The actions to execute. */ public void multicleave(final int n, @SuppressWarnings("unchecked") final Consumer>... actions) { List elms = multipoprev(n); for (final Consumer> action : actions) { pushAll(elms); action.accept(this); } } /** * Apply all the actions in a list to the top element of the stack. * * @param actions * The actions to execute. */ public void cleave(final List>> actions) { multicleave(1, actions); } /** * Apply all the actions in a list to the top element of the stack. * * @param actions * The actions to execute. */ public void cleave(@SuppressWarnings("unchecked") final Consumer>... actions) { multicleave(1, actions); } /** * Apply every action in a list of actions to n arguments. * * @param n * The number of parameters each action takes. * * @param actions * The actions to execute. */ public void multispread(final int n, final List>> actions) { List> nelms = new LinkedList<>(); for (int i = 0; i < actions.size(); i++) { List elms = multipoprev(n); nelms.add(elms); } Iterator>> itr = actions.iterator(); for (final List elms : nelms) { pushAll(elms); itr.next().accept(this); } } /** * Apply every action in a list of actions to n arguments. * * @param n * The number of parameters each action takes. * * @param actions * The actions to execute. */ public void multispread(final int n, @SuppressWarnings("unchecked") final Consumer>... actions) { List> nelms = new LinkedList<>(); for (int i = 0; i < actions.length; i++) { List elms = multipoprev(n); nelms.add(elms); } int i = 0; for (final List elms : nelms) { pushAll(elms); actions[i++].accept(this); } } /** * Apply the actions in a list of actions to corresponding elements from the * stack. * * @param conses * The actions to execute. */ public void spread(final List>> conses) { multispread(1, conses); } /** * Apply the actions in a list of actions to corresponding elements from the * stack. * * @param conses * The actions to execute. */ public void spread(@SuppressWarnings("unchecked") final Consumer>... conses) { multispread(1, conses); } /** * Apply an action to the first m groups of n arguments. * * @param n * The number of arguments cons takes. * * @param m * The number of time to call cons. * * @param action * The action to execute. */ public void multiapply(final int n, final int m, final Consumer> action) { final List>> actions = new ArrayList<>(m); for (int i = 0; i < m; i++) actions.add(action); multispread(n, actions); } /** * Apply an action n times to the corresponding elements in the stack. * * @param n * The number of times to execute cons. * * @param action * The action to execute. */ public void apply(final int n, final Consumer> action) { multiapply(1, n, action); } /* * Misc. functions */ /** * Get an array representing this stack. * * @return The stack as an array. */ public abstract T[] toArray(); } 1-10 package com.lurencun.http; import java.io.IOException; import java.io.InputStream; import java.net.ConnectException; import java.net.URL; import com.lurencun.http.assist.ResponseStreamUtil; /** * @author : 桥下一粒砂 * @email : * @date : 2012-10-24 * @desc : 字节型数据处理类 */ public abstract class BinaryResponseHandler implements ResponseCallback { @Override final public void onResponse(InputStream response,URL url) { onResponseWithToken(response, url, null); } @Override final public void onResponseWithToken(InputStream response, URL url, Object token) { try { byte[] data = ResponseStreamUtil.convertToByteArray(response); if(token != null){ onResponseWithToken(data,url,token); }else{ onResponse(data,url); } } catch (IOException exp) { onError(new ConnectException(exp.getMessage())); exp.printStackTrace(); } } public abstract void onResponse(byte[] data,URL url); public void onResponseWithToken(byte[] data,URL url,Object token){}; } package com.gmail.cadox8.trinkets.effects; public enum Effects { NONE, JUMP, HEALTH; } package com.example.focuson; public interface OnDateInfo { void inputDateInfo(int year, int month, int day); } package SlayByDay.cards.switchCards; import SlayByDay.characters.TheMedium; import SlayByDay.patches.cards.BackToDeckOnPlayPatch; import com.megacrit.cardcrawl.actions.AbstractGameAction; import com.megacrit.cardcrawl.actions.common.*; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.monsters.AbstractMonster; import com.megacrit.cardcrawl.powers.StrengthPower; import java.util.Arrays; import java.util.List; import java.util.Random; public class RenewFeatherBashSwitch extends AbstractSwitchByModeCard { public List switchListInherit = Arrays.asList( new switchCard("Renew", "FeatherBash", 1, 0, 0, 0, 0, 0, 2, 1, CardType.SKILL, CardTarget.SELF, false, false, false, false), new switchCard("FeatherBash", "Renew", 1, 0, 2, 0, 2, 0, 2, 1, CardType.ATTACK, CardTarget.ENEMY, false, false, false, false) ); public String reasonCardID() { return "Renew"; } public String passionCardID() { return "FeatherBash"; } public RenewFeatherBashSwitch(String switchID) { super("SlayByDay:RenewFeatherBash", "None", null, 0, "None", CardType.SKILL, TheMedium.Enums.COLOR_M_PURPLE, CardRarity.UNCOMMON, CardTarget.NONE, RenewFeatherBashSwitch.class); if (switchID == null) { switchID = switchListInherit.get(new Random().nextInt(switchListInherit.size())).cardID; } this.switchList = switchListInherit; if (this.currentID != null) { this.switchTo(this.currentID); } else { this.switchTo(switchID); } if (AbstractDungeon.isPlayerInDungeon()) { this.validateSwitchCardMode(true); } } @Override public void triggerWhenDrawn() { if (TheMedium.Reason_Mode) { this.flash(); AbstractDungeon.actionManager.addToTop(new DrawCardAction(AbstractDungeon.player, this.magicNumber)); } } public RenewFeatherBashSwitch() { this(null); } @Override public void use(AbstractPlayer p, AbstractMonster m) { switch (this.currentID) { case "Renew": BackToDeckOnPlayPatch.toBePutBackInDeck.set(this, true); BackToDeckOnPlayPatch.inRandomSpot.set(this, true); break; case "FeatherBash": for (int i=0; i < this.magicNumber; i++) { AbstractDungeon.actionManager.addToBottom(new GainBlockAction(p, p, this.block)); } // This uses the same action that Pummel uses. We could also write our own, near identical, action for this instead. for (int i=0; i < this.magicNumber; i++) { AbstractDungeon.actionManager.addToBottom(new PummelDamageAction(m, new DamageInfo(p, this.damage, this.damageTypeForTurn))); } break; } } } package cn.smaxlyb.coolweather.service; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.content.SharedPreferences; import android.os.IBinder; import android.os.SystemClock; import androidx.core.app.AlarmManagerCompat; import org.jetbrains.annotations.NotNull; import java.io.IOException; import cn.smaxlyb.coolweather.gson.Weather; import cn.smaxlyb.coolweather.util.HttpUtil; import cn.smaxlyb.coolweather.util.LogUtil; import cn.smaxlyb.coolweather.util.Utility; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class AutoUpdateService extends Service { // 不需要和活动绑定 @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { LogUtil.d("AutoUpdateService", "服务已启动"); updateWeather(); updateBingPic(); AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE); int anHour = 6 * 60 * 60 * 1000; long triggerAtTime = SystemClock.elapsedRealtime() + anHour; Intent i = new Intent(this, AutoUpdateService.class); PendingIntent pi = PendingIntent.getService(this, 0, i, 0); manager.cancel(pi); manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi); return super.onStartCommand(intent, flags, startId); } private void updateWeather() { // 查看本地是否有数据 SharedPreferences prefs = getSharedPreferences("weatherData", MODE_PRIVATE); String weatherString = prefs.getString("weather", null); //如果本地有数据才进行更新 if (weatherString != null) { // 利用本地的weatherId进行请求 Weather weather = Utility.handleWeatherResponse(weatherString); String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weather.basic.weatherId + "&key=1"; LogUtil.d("AutoUpdateService", weatherUrl); HttpUtil.sendRequestWithOkHttp(weatherUrl, new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { LogUtil.e("AutoUpdateService", "后台服务更新出错:" + e.toString()); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { // 对请求结果进行解析 String responseText = response.body().string(); Weather weather = Utility.handleWeatherResponse(responseText); // 对解析结果进行存储 if (weather != null && "ok".equals(weather.status)) { prefs.edit().putString("weather", responseText).apply(); } } }); } } private void updateBingPic() { String requestBingPic = "http://guolin.tech/api/bing_pic"; HttpUtil.sendRequestWithOkHttp(requestBingPic, new Callback() { @Override public void onFailure(@NotNull Call call, @NotNull IOException e) { LogUtil.e("AutoUpdateService", "后台服务更新图片出错:" + e.toString()); } @Override public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException { String bingPic = response.body().string(); SharedPreferences prefs = getSharedPreferences("weatherData", MODE_PRIVATE); prefs.edit().putString("bing_pic", bingPic).apply(); } }); } } package com.gazbert.rabbitsample.publish.topic; import static com.gazbert.rabbitsample.publish.topic.TopicExchangeConfiguration.BINDING_PATTERN_ERROR; import static com.gazbert.rabbitsample.publish.topic.TopicExchangeConfiguration.BINDING_PATTERN_HIGH_PRIORITY; import static com.gazbert.rabbitsample.publish.topic.TopicExchangeConfiguration.TOPIC_EXCHANGE_NAME; import static com.gazbert.rabbitsample.publish.topic.TopicExchangeConfiguration.TOPIC_QUEUE_1_NAME; import static com.gazbert.rabbitsample.publish.topic.TopicExchangeConfiguration.TOPIC_QUEUE_2_NAME; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import org.junit.Test; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.Declarables; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; /** * Tests the Topic exchange config is created as expected. * * @author gazbert */ public class TestTopicExchangeConfiguration { @Test public void testTopicBindingCreation() { final TopicExchangeConfiguration topicConfig = new TopicExchangeConfiguration(); final Declarables declarables = topicConfig.createTopicBindings(); final List queues = declarables.getDeclarablesByType(Queue.class); assertThat(queues.size()).isEqualTo(2); assertThat(queues.get(0).getName()).isEqualTo(TOPIC_QUEUE_1_NAME); assertThat(queues.get(0).isDurable()).isFalse(); assertThat(queues.get(1).getName()).isEqualTo(TOPIC_QUEUE_2_NAME); assertThat(queues.get(1).isDurable()).isFalse(); final List exchanges = declarables.getDeclarablesByType(TopicExchange.class); assertThat(exchanges.size()).isEqualTo(1); assertThat(exchanges.get(0).getType().equals("topic")).isTrue(); assertThat(exchanges.get(0).getName().equals(TOPIC_EXCHANGE_NAME)).isTrue(); final List bindings = declarables.getDeclarablesByType(Binding.class); assertThat(bindings.size()).isEqualTo(2); assertThat(bindings.get(0).getExchange()).isEqualTo(TOPIC_EXCHANGE_NAME); assertThat(bindings.get(0).getDestination()).isEqualTo(TOPIC_QUEUE_1_NAME); assertThat(bindings.get(0).getRoutingKey()).isEqualTo(BINDING_PATTERN_HIGH_PRIORITY); assertThat(bindings.get(1).getExchange()).isEqualTo(TOPIC_EXCHANGE_NAME); assertThat(bindings.get(1).getDestination()).isEqualTo(TOPIC_QUEUE_2_NAME); assertThat(bindings.get(1).getRoutingKey()).isEqualTo(BINDING_PATTERN_ERROR); } } bouhomoh/gpi-hs21-twitterreview-bouhomoh package ch.zhaw.gpi.admock; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository{ List findByOfficialName(String officialName); } package com.amoseui.camerax; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.widget.Toast; import com.google.common.util.concurrent.ListenableFuture; import java.util.concurrent.ExecutionException; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.camera.core.Camera; import androidx.camera.core.CameraSelector; import androidx.camera.core.Preview; import androidx.camera.lifecycle.ProcessCameraProvider; import androidx.camera.view.PreviewView; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.lifecycle.LifecycleOwner; public class MainActivity extends AppCompatActivity implements LifecycleOwner { private static final int REQUEST_CODE_PERMISSIONS = 10; private static final String[] REQUIRED_PERMISSIONS = { Manifest.permission.CAMERA }; private ListenableFuture mCameraProviderFuture; private PreviewView mPreviewView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPreviewView = findViewById(R.id.preview_view); // Request camera permissions if (allPermissionsGranted()) { startCamera(); } else { ActivityCompat.requestPermissions( this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS); } } private void bindPreview(@NonNull ProcessCameraProvider cameraProvider) { Preview preview = new Preview.Builder().build(); CameraSelector cameraSelector = new CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build(); Camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview); preview.setSurfaceProvider(mPreviewView.createSurfaceProvider(camera.getCameraInfo())); } private void startCamera() { mPreviewView.post(() -> { mCameraProviderFuture = ProcessCameraProvider.getInstance(this); mCameraProviderFuture.addListener(() -> { try { ProcessCameraProvider cameraProvider = mCameraProviderFuture.get(); bindPreview(cameraProvider); } catch (ExecutionException | InterruptedException e) { // No errors need to be handled for this Future. // This should never be reached. } }, ContextCompat.getMainExecutor(this)); }); } /** * Process result from permission request dialog box, has the request * been granted? If yes, start Camera. Otherwise display a toast */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { // super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_PERMISSIONS) { if (allPermissionsGranted()) { startCamera(); } else { Toast.makeText(this, "Permissions not granted by the user.", Toast.LENGTH_SHORT).show(); finish(); } } } /** * Check if all permission specified in the manifest have been granted */ private boolean allPermissionsGranted() { for (String permission : REQUIRED_PERMISSIONS) { if (ContextCompat.checkSelfPermission(getBaseContext(), permission) != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } } 1-10 package skybox; import shaders.ShaderProgram; import shaders.UniformMatrix; import utils.MyFile; public class SkyboxShader extends ShaderProgram { private static final MyFile VERTEX_SHADER = new MyFile("skybox", "skyboxVertex.txt"); private static final MyFile FRAGMENT_SHADER = new MyFile("skybox", "skyboxFragment.txt"); protected UniformMatrix projectionViewMatrix = new UniformMatrix("projectionViewMatrix"); public SkyboxShader() { super(VERTEX_SHADER, FRAGMENT_SHADER, "in_position"); super.storeAllUniformLocations(projectionViewMatrix); } } package io.oasp.gastronomy.restaurant.doctorsmanagement.logic.impl; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import javax.inject.Named; import javax.transaction.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import io.oasp.gastronomy.restaurant.doctorsmanagement.dataaccess.api.DoctorEntity; import io.oasp.gastronomy.restaurant.doctorsmanagement.dataaccess.api.dao.DoctorDao; import io.oasp.gastronomy.restaurant.doctorsmanagement.logic.api.Doctorsmanagement; import io.oasp.gastronomy.restaurant.doctorsmanagement.logic.api.to.DoctorEto; import io.oasp.gastronomy.restaurant.general.common.api.constants.PermissionConstants; import io.oasp.gastronomy.restaurant.general.logic.base.AbstractComponentFacade; /** * Implementation class for {@link Doctorsmanagement}. * */ @Named @Transactional @Component public class DoctorsmanagementImpl extends AbstractComponentFacade implements Doctorsmanagement { private static final Logger LOG = LoggerFactory.getLogger(DoctorsmanagementImpl.class); private DoctorDao doctorDao; @Override @RolesAllowed(PermissionConstants.FIND_DOCTOR) public DoctorEto findDoctor(long id) { LOG.debug("Get Doctor with id '" + id + "' from database."); return getBeanMapper().map(getDoctorDao().findOne(id), DoctorEto.class); } @Override @RolesAllowed(PermissionConstants.FIND_DOCTOR) public List findAllDoctor() { List doctors = getDoctorDao().findAll(); List doctorsBo = new ArrayList<>(); for (DoctorEntity doctor : doctors) { doctorsBo.add(getBeanMapper().map(doctor, DoctorEto.class)); } return doctorsBo; } @Override @RolesAllowed(PermissionConstants.SAVE_DOCTOR) public DoctorEto saveDoctor(DoctorEto doctor) { Objects.requireNonNull(doctor, "doctor"); Long id = doctor.getId(); DoctorEntity targetDoctor = null; if (id != null) { targetDoctor = getDoctorDao().findOne(id); } if (targetDoctor == null) { // StaffMember is new: -> create LOG.debug("Saving Doctor with id '{}' to the database.", id); } else { // Doctor already exists: -> Update LOG.debug("Updating Doctor with id '{}' in the database.", id); if (!Objects.equals(targetDoctor.getNom(), doctor.getNom())) { LOG.debug("Changing login of StaffMember with id '{}' from '{}' to '{}' in the database.", id, targetDoctor.getNom(), doctor.getNom()); } } DoctorEntity persistedDoctor = getDoctorDao().save(getBeanMapper().map(doctor, DoctorEntity.class)); return getBeanMapper().map(persistedDoctor, DoctorEto.class); } /** * @return the {@link DoctorDao} instance. */ public DoctorDao getDoctorDao() { return this.doctorDao; } @Override @RolesAllowed(PermissionConstants.DELETE_DOCTOR) public void deleteDoctor(long doctorId) { getDoctorDao().delete(doctorId); } /** * Sets the field 'doctorDao'. * * @param doctorDao New value for doctorDao */ @Inject public void setDoctorDao(DoctorDao doctorDao) { this.doctorDao = doctorDao; } /** * The constructor. */ public DoctorsmanagementImpl() { super(); } } dp-core/tools/src/test/java/com/dataprofiler/datasetdelta/provider/DeltaCommentProviderTest.java package com.dataprofiler.datasetdelta.provider; /*- * * dataprofiler-tools * * Copyright 2021 Merck & Co., Inc. Kenilworth, NJ, USA. * * 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. * */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import com.dataprofiler.datasetdelta.model.DatasetDeltaStub; import com.dataprofiler.util.objects.CustomAnnotation; import com.dataprofiler.util.objects.CustomAnnotation.AnnotationType; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DeltaCommentProviderTest { Logger logger = LoggerFactory.getLogger(DeltaCommentProvider.class); static final String CREATED_BY = "data profiler system".toLowerCase(); DeltaCommentProvider deltaCommentProvider; @Before public void setup() { deltaCommentProvider = new DeltaCommentProvider(); } @After public void teardown() { deltaCommentProvider = null; } @Test public void canary() { assertNotNull(deltaCommentProvider); } @Test public void testCommentNote1() { String note = deltaCommentProvider.buildNote(DatasetDeltaStub.buildColumnAddedDelta()); assertNotNull(note); assertEquals("Column c1 added to table t1 in dataset ds1", note); } @Test public void testCommentNote2() { String note = deltaCommentProvider.buildNote(DatasetDeltaStub.buildColumnRemovedDelta()); assertNotNull(note); assertEquals("Column c1 removed from table t1 in dataset ds1", note); } @Test public void testCommentNote3() { String note = deltaCommentProvider.buildNote(DatasetDeltaStub.buildDatasetValuesIncreasedDelta()); assertNotNull(note); assertEquals("Dataset values increased from 11.60K to 431.42M", note); } @Test public void testComment1() { CustomAnnotation comment = deltaCommentProvider.buildComment( DatasetDeltaStub.buildColumnAddedDelta()); assertNotNull(comment); Assert.assertEquals(AnnotationType.COLUMN, comment.getAnnotationType()); assertEquals(comment.getDataset(), "ds1"); assertEquals(comment.getTable(), "t1"); assertEquals(comment.getColumn(), "c1"); assertEquals(CREATED_BY, comment.getCreatedBy().toLowerCase()); assertFalse(comment.getNote().isEmpty()); } @Test public void testComment2() { CustomAnnotation comment = deltaCommentProvider.buildComment( DatasetDeltaStub.buildColumnRemovedDelta()); assertNotNull(comment); Assert.assertEquals(AnnotationType.COLUMN, comment.getAnnotationType()); assertEquals(comment.getDataset(), "ds1"); assertEquals(comment.getTable(), "t1"); assertEquals(comment.getColumn(), "c1"); assertEquals(CREATED_BY, comment.getCreatedBy().toLowerCase()); assertFalse(comment.getNote().isEmpty()); } @Test public void testComment3() { CustomAnnotation comment = deltaCommentProvider.buildComment(DatasetDeltaStub.buildDatasetValuesIncreasedDelta()); assertNotNull(comment); Assert.assertEquals(AnnotationType.DATASET, comment.getAnnotationType()); assertEquals(comment.getDataset(), "ds1"); assertNull(comment.getTable()); assertNull(comment.getColumn()); assertEquals(CREATED_BY, comment.getCreatedBy().toLowerCase()); assertFalse(comment.getNote().isEmpty()); } } luxy25/pandorapandora-core/src/main/java/tech/linjiang/pandora/database/protocol/IDriver.java package tech.linjiang.pandora.database.protocol; import android.database.sqlite.SQLiteException; import java.util.List; import tech.linjiang.pandora.database.DatabaseResult; /** * Created by linjiang on 29/05/2018. * * Database driver:SQLite、ContentProvider */ public interface IDriver { List getDatabaseNames(); List getTableNames(T databaseDesc) throws SQLiteException; void executeSQL(T databaseDesc, String query, DatabaseResult result) throws SQLiteException; } package app.zoftwhere.combinatoric; import java.util.List; import java.util.NoSuchElementException; /** *

Permutation Void. *

*

The Permutation Void class is an index-only implementation. *

*

This is a package-private class that implements functionality. *

* * @author Osmund * @since 2.0.0 */ class PermutationVoid extends PermutationBasic { /** * Constructor for {@link app.zoftwhere.combinatoric.PermutationVoid} (package-private). * * @param index index * @param kSize size of display elements * @since 2.0.0 */ PermutationVoid(int[] index, int kSize) { super(index, null, kSize); } /** {@inheritDoc} */ @Override protected Permutation newInstance(int[] index, List list, int kSize) { return new PermutationVoid(index, kSize); } /** {@inheritDoc} */ @Override public List value() { throw new NoSuchElementException(); } /** {@inheritDoc} */ @Override public Void value(int position) { throw new NoSuchElementException(); } /** * Returns the permutation index information. * * @return permutation index information * @since 2.0.0 */ @Override public String toString() { StringBuilder builder = new StringBuilder("["); builder.append(String.format("%d", index[0])); for (int i = 1; i < kSize; i++) { builder.append(String.format(", %d", index[i])); } if (kSize < size) { builder.append(String.format("][%d", index[kSize])); } for (int i = kSize + 1; i < size; i++) { builder.append(String.format(", %d", index[i])); } return builder.append("]").toString(); } } package org.workcraft.types; import java.util.LinkedHashMap; public class LinkedTwoWayMap extends GeneralTwoWayMap { public LinkedTwoWayMap() { super(new LinkedHashMap(), new LinkedHashMap()); } } 0 /* * Copyright 2015 eBay Software 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 com.nexenio.fido.uaf.core.message; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.gson.annotations.SerializedName; import lombok.Data; @Data public class MatchCriteria { /** * List of AAIDs, causing matching to be restricted to certain AAIDs. The match succeeds if at least one AAID entry * in this array matches AuthenticatorInfo.aaids [UAFASM]. Note: This field corresponds to MetadataStatement.aaids * [UAFAuthnrMetadata]. */ @SerializedName("aaid") @JsonProperty("aaid") private String[] aaids; } src/main/java/knightminer/animalcrops/blocks/AnimalShroomBlock.java package knightminer.animalcrops.blocks; import knightminer.animalcrops.AnimalCrops; import knightminer.animalcrops.core.Registration; import knightminer.animalcrops.items.AnimalSeedsItem; import net.minecraft.block.BlockState; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockReader; import net.minecraft.world.IWorldReader; import net.minecraft.world.server.ServerWorld; import net.minecraftforge.common.ForgeHooks; import net.minecraftforge.common.PlantType; import java.util.List; import java.util.Random; import java.util.function.Supplier; /** * Logic for nether crops */ public class AnimalShroomBlock extends AnimalCropsBlock { public AnimalShroomBlock(Properties props, Supplier> animals) { super(props, animals); } @Override protected boolean isValidGround(BlockState state, IBlockReader worldIn, BlockPos pos) { return state.isIn(AnimalCrops.SHROOM_SOIL); } @Override public PlantType getPlantType(IBlockReader world, BlockPos pos) { return PlantType.NETHER; } // override to remove light check @Override public boolean isValidPosition(BlockState state, IWorldReader worldIn, BlockPos pos) { BlockPos down = pos.down(); if (state.getBlock() == this) { return worldIn.getBlockState(down).canSustainPlant(worldIn, down, Direction.UP, this); } return this.isValidGround(worldIn.getBlockState(down), worldIn, down); } @Override protected AnimalSeedsItem getSeed() { // TODO return Registration.seeds; } @Override public void randomTick(BlockState state, ServerWorld worldIn, BlockPos pos, Random random) { int i = this.getAge(state); if (i < this.getMaxAge() && ForgeHooks.onCropsGrowPre(worldIn, pos, state, random.nextInt(10) == 0)) { state = state.with(AGE, i + 1); worldIn.setBlockState(pos, state, 2); ForgeHooks.onCropsGrowPost(worldIn, pos, state); } } } package com.ty.order.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.ty.common.enume.CheckInEnum; import com.ty.common.enume.OrderStatusEnum; import com.ty.common.utils.ApiResp; import com.ty.common.utils.PageUtils; import com.ty.common.utils.Query; import com.ty.order.entity.HotelCheckInEntity; import com.ty.order.entity.HotelOrderEntity; import com.ty.order.dao.HotelOrderDao; import com.ty.order.service.HotelCheckInService; import com.ty.order.service.HotelOrderService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.ty.order.vo.HotelOrderVo; import com.ty.order.vo.PayVo; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; /** *

* 服务实现类 *

* * @author taleyoung * @since 2021-03-17 */ @Service public class HotelOrderServiceImpl extends ServiceImpl implements HotelOrderService { @Autowired HotelCheckInService hotelCheckInService; @Autowired RabbitTemplate rabbitTemplate; @Override public PageUtils queryPage(Map params) { IPage page = this.page( new Query().getPage(params), new QueryWrapper().orderByDesc("create_time")); return new PageUtils(page); } @Transactional @Override public HotelOrderEntity createOrder(HotelOrderVo hotelOrderVo) { HotelOrderEntity hotelOrderEntity = new HotelOrderEntity(); //TODO 登记业务 BeanUtils.copyProperties(hotelOrderVo, hotelOrderEntity); hotelOrderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode()); boolean save = this.save(hotelOrderEntity); // 添加登记表 hotelCheckInService.add(hotelOrderEntity.getId(), hotelOrderVo); //TODO 去支付 //消息队列发消息 创建订单 rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",hotelOrderEntity); return hotelOrderEntity; } @Override public void handlePayResult(boolean payResult, Integer hotelOrderId){ HotelOrderEntity orderEntity = this.getById(hotelOrderId); if(payResult){ //付款成功 更改状态 orderEntity.setStatus(OrderStatusEnum.PAYED.getCode()); this.updateById(orderEntity); hotelCheckInService.updateStatus(hotelOrderId, CheckInEnum.WAIT_CHECK_IN.getCode()); }else{ orderEntity.setStatus(OrderStatusEnum.ERROR.getCode()); this.updateById(orderEntity); //待定 hotelCheckInService.updateStatus(hotelOrderId, CheckInEnum.CANCEL.getCode()); } } @Override public void updateOrder(HotelOrderEntity hotelOrderEntity) { this.update(new QueryWrapper(hotelOrderEntity)); } @Override public PayVo getOrderPay(String orderSn) { PayVo payVo = new PayVo(); payVo.setBody("xxx"); payVo.setOut_trade_no("12344"); payVo.setSubject("xxxx"); payVo.setTotal_amount("200"); return payVo; } @Override public void testPayAndSuccess(HotelOrderVo hotelOrderVo) { HotelOrderEntity orderEntity = this.createOrder(hotelOrderVo); this.handlePayResult(true, orderEntity.getId()); } @Override public void testPayAndCancel(HotelOrderVo hotelOrderVo) { HotelOrderEntity orderEntity = this.createOrder(hotelOrderVo); rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",orderEntity); } } minluzhou/test1redis/redis-proxy/src/test/java/com/ctrip/xpipe/redis/proxy/ssl/NormalServer.java package com.ctrip.xpipe.redis.proxy.ssl; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.logging.LogLevel; import io.netty.handler.logging.LoggingHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLException; import java.nio.charset.Charset; import java.security.cert.CertificateException; /** * @author chen.zhu *

* May 08, 2018 */ public class NormalServer { static final int LOCAL_PORT = Integer.parseInt(System.getProperty("localPort", "8090")); static final Logger logger = LoggerFactory.getLogger(NormalServer.class); public static void main(String[] args) throws CertificateException, SSLException, InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new ChannelInboundHandlerAdapter(){ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg; logger.info("message: {}", buf.toString(Charset.defaultCharset())); } }); } }); b.bind(LOCAL_PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } package com.ruinscraft.panilla.bukkit; import com.ruinscraft.panilla.api.IPanilla; import com.ruinscraft.panilla.api.IPanillaPlayer; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerPreLoginEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.plugin.java.JavaPlugin; public class JoinQuitListener implements Listener { private final IPanilla panilla; private JavaPlugin panillaPlugin; public JoinQuitListener(JavaPlugin panillaPlugin, IPanilla panilla) { this.panillaPlugin = panillaPlugin; this.panilla = panilla; } @EventHandler public void onPreJoin(AsyncPlayerPreLoginEvent event) { } @EventHandler public void onJoin(PlayerJoinEvent event) { IPanillaPlayer pplayer = new BukkitPanillaPlayer(event.getPlayer()); panilla.getPlayerInjector().register(panilla, pplayer); } @EventHandler public void onQuit(PlayerQuitEvent event) { IPanillaPlayer pplayer = new BukkitPanillaPlayer(event.getPlayer()); panilla.getPlayerInjector().unregister(pplayer); } } 10-100 package cn.finder.wae.queryer.handleclass; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.sql.DataSource; import org.activiti.engine.history.HistoricDetail; import org.activiti.engine.history.HistoricVariableInstance; import org.activiti.engine.history.HistoricVariableUpdate; import cn.finder.ui.webtool.QueryCondition; import cn.finder.wae.business.domain.TableQueryResult; import cn.iron.activiti.ActivitiServiceManager; import cn.finder.wae.business.dto.MapParaQueryConditionDto; import cn.finder.wae.common.comm.AppApplicationContextUtil; /** * @author: wuhualong * @data:2014-09-01 上午11cha:25:21 * @function:获取流程变量 处理 */ public class FindProcessInstanceVariableAfterClass extends QueryerDBAfterClass { @Override public TableQueryResult handle(TableQueryResult tableQueryResult, long showTableConfigId, QueryCondition condition) { super.handle(tableQueryResult, showTableConfigId, condition); @SuppressWarnings("unchecked") Map data = ((MapParaQueryConditionDto)condition).getMapParas(); //流程实例ID String processInstanceId =data.get("processInstanceId").toString(); ActivitiServiceManager activitiServiceManager=AppApplicationContextUtil.getContext().getBean("activitiServiceManager", ActivitiServiceManager.class); // activitiServiceManager.getIdentityService().setAuthenticatedUserId("yaoshi01"); Map vs =new HashMap(); /*List variable_list = activitiServiceManager.getHistoryService().createHistoricDetailQuery().processInstanceId(processInstanceId).orderByTime().desc().list(); for (HistoricDetail historicDetail : variable_list) { HistoricVariableUpdate variable = (HistoricVariableUpdate) historicDetail; if(!vs.containsKey(variable.getVariableName())){ vs.put(variable.getVariableName(), variable.getValue()); } }*/ List historicVariableInstances= activitiServiceManager.getHistoryService().createHistoricVariableInstanceQuery().processInstanceId(processInstanceId).list(); for (HistoricVariableInstance historicVariableInstance : historicVariableInstances) { vs.put(historicVariableInstance.getVariableName(), historicVariableInstance.getValue()); } logger.debug("====返回变量"); if(vs!=null && vs.size()>0){ //返回变量输出 Set> es = vs.entrySet(); Iterator> ie = es.iterator(); while(ie.hasNext()){ Entry entry = ie.next(); logger.debug("===variable: " + entry.getKey() + " = " + entry.getValue()); } } logger.debug("============================================"); List> list = new java.util.ArrayList>(); list.add(vs); tableQueryResult.setCount(1l); tableQueryResult.setPageSize(1); tableQueryResult.setPageIndex(1); tableQueryResult.setResultList(list); return tableQueryResult; } @Override public void setJDBCDataSource(DataSource dataSource) { super.setJdbcDataSource(dataSource); } } package main; import main.Ball.BallType; public class Player { public BallType color = BallType.WHITE; public int id; public Player(int index) { id = index; } } package com.bai.ding.common.controller; import com.bai.ding.common.util.RandomCharTool; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; /** * @author BaiDing * @date 2020/3/9 23:58 */ public class BaseController { /** * 获取Request对象 */ public HttpServletRequest getRequest() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .getRequest(); } public String getUserNameFromSession(HttpServletRequest request) { return (String) request.getSession().getAttribute("name"); } /** * 获取Response对象 */ public HttpServletResponse getResponse() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()) .getResponse(); } /** * 获取session对象 */ public HttpSession getSession() { return this.getRequest().getSession(); } /** * 得到文件的后缀名 * @param fileName * @return */ public String getExtraName(String fileName){ int i = fileName.lastIndexOf("."); String extraName = ""; if (i > 0) { // 含有后缀名的文件 extraName = fileName.substring(i+1); } return extraName; } /** * @param excelName * 要生成的文件名字 * @param isAppend * 是否追加{时间戳}_8位字母数字组合随机数 * @return * @throws IOException */ public ServletOutputStream generateResponseExcel(String excelName, boolean isAppend) throws IOException { excelName = excelName == null || "".equals(excelName) ? "excel" : URLEncoder.encode(excelName, "UTF-8"); if (isAppend) { excelName = excelName.concat("_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_") .concat(RandomCharTool.getRandomCharAndNumr(8)); } HttpServletResponse response = getResponse(); response.setContentType("application/vnd.ms-excel;charset=utf-8"); response.setHeader("Content-Disposition", "attachment; filename=" + excelName + ".xlsx"); return response.getOutputStream(); } // /** // * @param rowNo // * 插入的数据的行号 // * @param vals // * 插入的数据值 // * @return // * @throws IOException // */ // public void createExcel(XSSFSheet sheet, int rowNo, String[] vals) throws IOException { // if (vals.length > 0) { // XSSFRow row = sheet.createRow(rowNo); // for (int i = 0; i < vals.length; i++) { // String val = vals[i]; // XSSFCell cell = row.createCell(i); // cell.setCellValue(val); // } // } // } } /** * */ package com.geekforgeeks.main; import java.util.Scanner; /** * @author z017954 * */ public class ChangeString { private static String inputString; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { int T = scanner.nextInt(); if (T < 200) { for (int i = 0; i < T; i++) { inputString = scanner.next(); if (inputString.length() < Math.pow(10, 4)) { char a = inputString.charAt(0); if (Character.isUpperCase(a)) { System.out.println(inputString.toUpperCase()); } else { System.out.println(inputString.toLowerCase()); } } } } } catch (Exception e) { System.err.println("Exception is " + e.getLocalizedMessage()); } scanner.close(); } } package Business.concretes; import Business.abstracts.CustomerCheckService; import Entites.concretes.Customer; import MernisService.EAEKPSPublicSoap; import java.util.Locale; public class MernisCheckService implements CustomerCheckService { @Override public boolean isRealPerson(Customer customer) throws Exception { EAEKPSPublicSoap mernis = new EAEKPSPublicSoap(); return mernis.TCKimlikNoDogrula(Long.parseLong(customer.getNationalityId()), customer.getFirstName().toUpperCase(new Locale("tr")), customer.getLastName().toUpperCase(new Locale("tr")), customer.getBirthOfDate()); } } /* * Copyright 2018-2021 Crown Copyright * * 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 uk.gov.gchq.palisade.service.manager.service; import feign.Response; import feign.RetryableException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import uk.gov.gchq.palisade.service.manager.web.ManagedClient; import java.io.IOException; import java.net.URI; import java.util.Arrays; import java.util.Collection; import java.util.Optional; import java.util.function.Supplier; /** * Wrapper around a Feign client to call out to a collection of URIs rather than a single REST service * Allows multiple instances of a service to be running and all of them to be effected by shutdown, logging changes, etc. */ public class ManagedService { private static final Logger LOGGER = LoggerFactory.getLogger(ManagedService.class); private final ManagedClient managedClient; private final Supplier> uriSupplier; /** * Constructor taking 2 arguments * * @param managedClient the service client * @param uriSupplier a collection of health endpoint {@link URI}s */ public ManagedService(final ManagedClient managedClient, final Supplier> uriSupplier) { this.managedClient = managedClient; this.uriSupplier = uriSupplier; } /** * Get whether a single service in the possible collection is healthy * * @return whether there exists a healthy service */ public boolean isHealthy() { Collection clientUris = this.uriSupplier.get(); return clientUris.stream() .map((URI clientUri) -> { int status = HttpStatus.NOT_FOUND.value(); try { status = this.managedClient.getHealth(clientUri).status(); } catch (RetryableException ex) { // Not up yet LOGGER.error("An error occurred while checking the service health", ex); } LOGGER.debug("Client uri {} has status {}", clientUri, status); return status; }) // Could be anyMatch, as only one healthy service is needed to perform requests // Could be allMatch, as it should be expected that all services are healthy // Note that in the case of an empty list, this should always return false .anyMatch(x -> x == HttpStatus.OK.value()); } /** * Set the logging level for a given java package * * @param packageName the name of the package (eg. uk.gov, root, java.util) * @param configuredLevel the level to log to stdout for the named package (TRACE, DEBUG, INFO, WARN, ERROR) * @throws IOException if any service did not report 200-OK after the REST POST request */ public void setLoggers(final String packageName, final String configuredLevel) throws IOException { Collection clientUris = this.uriSupplier.get(); Optional failures = clientUris.stream() .map((URI clientUri) -> { Response response = this.managedClient.setLoggers(clientUri, packageName, configuredLevel); LOGGER.debug("Client uri {} responded with {}", clientUri, response); return response; }) .filter(x -> x.status() != HttpStatus.OK.value()) .findAny(); // Need to throw an error, so can't wrap inside an Optional.ifPresent // Could be avoided by throwing a RuntimeException if (failures.isPresent()) { Response response = failures.get(); LOGGER.error("An error occurred while setting logging levels: {}", response); String responseBody = Arrays.toString(response.body().asInputStream().readAllBytes()); throw new IOException(String.format("Expected /actuator/loggers/%s %s -> 200 OK but instead was %s", packageName, configuredLevel, responseBody)); } } /** * Requests a shutdown all running instances of the service * Does not verify that services have actually stopped */ public void shutdown() { Collection clientUris = this.uriSupplier.get(); clientUris.forEach(this.managedClient::shutdown); } } package com.study.ponto.services; import com.study.ponto.api.entities.Empresa; import java.util.Optional; public interface EmpresaService { Optional buscarPorCnpj(String CNPJ); Empresa persistirEmpresa(Empresa empresa); } /*- * #%L * Coffee * %% * Copyright (C) 2020 i-Cell Mobilsoft Zrt. * %% * 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. * #L% */ package hu.icellmobilsoft.coffee.tool.utils.crypto; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import hu.icellmobilsoft.coffee.dto.exception.TechnicalException; /** * Test class for {@link AesGcmUtil} * * @author mark.petrenyi * @since 1.1.0 */ @DisplayName("Testing AesGcmUtil") class AesGcmUtilTest { private static final String TEST_INPUT_TEXT = "test input test"; private static final String TEST_KEY = "12345678901234567890123456789012"; @Test @DisplayName("Testing aes256GcmNoPadding encrypt and decrypt - default iv") void aes256GcmNoPadding() throws Exception { // given byte[] key = TEST_KEY.getBytes("UTF-8"); // when byte[] encoded = AesGcmUtil.encryptWithAes256GcmNoPadding(key, TEST_INPUT_TEXT.getBytes("UTF-8")); byte[] decoded = AesGcmUtil.decryptWithAes256GcmNoPadding(key, encoded); // then Assertions.assertEquals(TEST_INPUT_TEXT, new String(decoded, "UTF-8")); } @Test @DisplayName("Testing aes256GcmNoPadding encrypt and decrypt - custom iv") void aes256GcmNoPaddingCustomIv() throws Exception { // given byte[] key = TEST_KEY.getBytes("UTF-8"); byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; // when byte[] encoded = AesGcmUtil.encryptWithAes256GcmNoPadding(key, TEST_INPUT_TEXT.getBytes("UTF-8"), iv); byte[] decoded = AesGcmUtil.decryptWithAes256GcmNoPadding(key, encoded, iv); // then Assertions.assertEquals(TEST_INPUT_TEXT, new String(decoded, "UTF-8")); } @Test @DisplayName("Testing aes256GcmNoPadding encrypt and decrypt - key mismatch") void aes256GcmNoPaddingKeyMismatch() throws Exception { // given byte[] key = TEST_KEY.getBytes("UTF-8"); byte[] key2 = "98765432109876543210987654321098".getBytes("UTF-8"); // when byte[] encoded = AesGcmUtil.encryptWithAes256GcmNoPadding(key, TEST_INPUT_TEXT.getBytes("UTF-8")); // byte[] decoded = AesGcmUtil.decryptWithAes256GcmNoPadding(key2, encoded); // then Executable decryptExecution = () -> AesGcmUtil.decryptWithAes256GcmNoPadding(key2, encoded); Assertions.assertThrows(TechnicalException.class, decryptExecution); } @Test @DisplayName("Testing aes256GcmNoPadding encrypt and decrypt - iv mismatch") void aes256GcmNoPaddingIvMismatch() throws Exception { // given byte[] key = TEST_KEY.getBytes("UTF-8"); byte[] iv1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; byte[] iv2 = { 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; // when byte[] encoded = AesGcmUtil.encryptWithAes256GcmNoPadding(key, TEST_INPUT_TEXT.getBytes("UTF-8"), iv1); // then Executable decryptExecution = () -> AesGcmUtil.decryptWithAes256GcmNoPadding(key, encoded, iv2); Assertions.assertThrows(TechnicalException.class, decryptExecution); } @Test @DisplayName("Testing generateKey()") void generateKey() throws Exception { // given // when byte[] key = AesGcmUtil.generateKey(); // then int expectedByteLength = 256 / 8; // 256 bit Assertions.assertNotNull(key); Assertions.assertEquals(expectedByteLength, key.length); } @Test @DisplayName("Testing generateIv()") void generateIv() throws Exception { // given // when byte[] key = AesGcmUtil.generateIv(); // then int expectedByteLength = 12; Assertions.assertNotNull(key); Assertions.assertEquals(expectedByteLength, key.length); } @Test @DisplayName("Testing aes256GcmNoPadding encrypt and decrypt - with generated key and iv") void aes256GcmNoPaddingWithGeneratedKeyAndIv() throws Exception { // given byte[] key = AesGcmUtil.generateKey(); byte[] iv = AesGcmUtil.generateIv(); // when byte[] encoded = AesGcmUtil.encryptWithAes256GcmNoPadding(key, TEST_INPUT_TEXT.getBytes("UTF-8"), iv); byte[] decoded = AesGcmUtil.decryptWithAes256GcmNoPadding(key, encoded, iv); // then Assertions.assertEquals(TEST_INPUT_TEXT, new String(decoded, "UTF-8")); } @DisplayName("Testing encryptWithAes256GcmNoPadding for invalid input") @ParameterizedTest(name = "Testing encryptWithAes256GcmNoPadding() with invalid input:[{0}]") // given @MethodSource("invalidInputProvider") void encryptWithAes256GcmNoPadding_invalidInput(byte[] key, byte[] text, byte[] iv) throws Exception { Executable encryptExecution = () -> AesGcmUtil.encryptWithAes256GcmNoPadding(key, text, iv); Assertions.assertThrows(TechnicalException.class, encryptExecution); } @DisplayName("Testing decryptWithAes256GcmNoPadding for invalid input") @ParameterizedTest(name = "Testing encryptWithAes256GcmNoPadding() with invalid input:[{0}]") // given @MethodSource("invalidInputProvider") void decryptWithAes256GcmNoPadding_invalidInput(byte[] key, byte[] text, byte[] iv) throws Exception { Executable encryptExecution = () -> AesGcmUtil.decryptWithAes256GcmNoPadding(key, text, iv); Assertions.assertThrows(TechnicalException.class, encryptExecution); } static Stream invalidInputProvider() throws Exception { byte[] validKey = TEST_KEY.getBytes("UTF-8"); byte[] shortKey = { 1, 2, 3 }; byte[] longKey = (TEST_KEY + TEST_KEY).getBytes("UTF-8"); byte[] validIV = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; byte[] shortIv = { 1, 2, 3 }; byte[] longIv = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; byte[] validText = TEST_INPUT_TEXT.getBytes("UTF-8"); return Stream.of(// Arguments.arguments(null, validText, validIV, "null key"), // Arguments.arguments(shortKey, validText, validIV, "too short key"), // Arguments.arguments(longKey, validText, validIV, "too long key"), // Arguments.arguments(validKey, validText, null, "null iv"), // Arguments.arguments(validKey, validText, shortIv, "too short iv"), // Arguments.arguments(validKey, validText, longIv, "too long iv"), // Arguments.arguments(validKey, null, validIV, "null text") // ); } } hibernate-release-5.3.7.Final/project/hibernate-core/src/test/java/org/hibernate/test/exceptionhandling/ExceptionExpectations.java /* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or . */ package org.hibernate.test.exceptionhandling; import java.sql.SQLException; import javax.persistence.OptimisticLockException; import javax.persistence.PersistenceException; import javax.persistence.RollbackException; import org.hibernate.StaleObjectStateException; import org.hibernate.TransactionException; import org.hibernate.TransientObjectException; import org.hibernate.exception.ConstraintViolationException; import org.hibernate.hql.internal.ast.QuerySyntaxException; import org.hibernate.id.IdentifierGenerationException; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; interface ExceptionExpectations { static ExceptionExpectations jpa() { return new ExceptionExpectations() { @Override public void onConstraintViolationOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); } @Override public void onConstraintViolationOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e.getCause(), instanceOf( ConstraintViolationException.class ) ); assertThat( e.getCause().getCause(), instanceOf( SQLException.class ) ); } @Override public void onTransientObjectOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransientObjectException.class ) ); } @Override public void onTransientObjectOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( IllegalStateException.class ) ); assertThat( e.getCause(), instanceOf( TransientObjectException.class ) ); } @Override public void onInvalidQueryExecuted(RuntimeException e) { assertThat( e, instanceOf( IllegalArgumentException.class ) ); assertThat( e.getCause(), instanceOf( QuerySyntaxException.class ) ); } @Override public void onStaleObjectMergeAndUpdateFlush(RuntimeException e) { assertThat( e, instanceOf( OptimisticLockException.class ) ); assertThat( e.getCause(), instanceOf( StaleObjectStateException.class ) ); } @Override public void onIdentifierGeneratorFailure(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e.getCause(), instanceOf( IdentifierGenerationException.class ) ); } @Override public void onTransactionExceptionOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e.getCause(), instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnCommit(RuntimeException e) { assertThat( e, instanceOf( RollbackException.class ) ); assertThat( e.getCause(), instanceOf( PersistenceException.class ) ); assertThat( e.getCause().getCause(), instanceOf( TransactionException.class ) ); } }; } static ExceptionExpectations nativePre52() { return new ExceptionExpectations() { @Override public void onConstraintViolationOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( ConstraintViolationException.class ) ); assertThat( e.getCause(), instanceOf( SQLException.class ) ); } @Override public void onConstraintViolationOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( ConstraintViolationException.class ) ); assertThat( e.getCause(), instanceOf( SQLException.class ) ); } @Override public void onTransientObjectOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransientObjectException.class ) ); } @Override public void onTransientObjectOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( TransientObjectException.class ) ); } @Override public void onInvalidQueryExecuted(RuntimeException e) { assertThat( e, instanceOf( QuerySyntaxException.class ) ); } @Override public void onStaleObjectMergeAndUpdateFlush(RuntimeException e) { assertThat( e, instanceOf( StaleObjectStateException.class ) ); } @Override public void onIdentifierGeneratorFailure(RuntimeException e) { assertThat( e, instanceOf( IdentifierGenerationException.class ) ); } @Override public void onTransactionExceptionOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnCommit(RuntimeException e) { assertThat( e, instanceOf( TransactionException.class ) ); } }; } static ExceptionExpectations nativePost52() { return new ExceptionExpectations() { @Override public void onConstraintViolationOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( ConstraintViolationException.class ) ); assertThat( e.getCause(), instanceOf( SQLException.class ) ); } @Override public void onConstraintViolationOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e.getCause(), instanceOf( ConstraintViolationException.class ) ); assertThat( e.getCause().getCause(), instanceOf( SQLException.class ) ); } @Override public void onTransientObjectOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransientObjectException.class ) ); } @Override public void onTransientObjectOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( IllegalStateException.class ) ); assertThat( e.getCause(), instanceOf( TransientObjectException.class ) ); } @Override public void onInvalidQueryExecuted(RuntimeException e) { assertThat( e, instanceOf( IllegalArgumentException.class ) ); assertThat( e.getCause(), instanceOf( QuerySyntaxException.class ) ); } @Override public void onStaleObjectMergeAndUpdateFlush(RuntimeException e) { assertThat( e, instanceOf( OptimisticLockException.class ) ); assertThat( e.getCause(), instanceOf( StaleObjectStateException.class ) ); } @Override public void onIdentifierGeneratorFailure(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e.getCause(), instanceOf( IdentifierGenerationException.class ) ); } @Override public void onTransactionExceptionOnSaveAndSaveOrUpdate(RuntimeException e) { assertThat( e, instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnPersistAndMergeAndFlush(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e.getCause(), instanceOf( TransactionException.class ) ); } @Override public void onTransactionExceptionOnCommit(RuntimeException e) { assertThat( e, instanceOf( PersistenceException.class ) ); assertThat( e.getCause(), instanceOf( TransactionException.class ) ); } }; } void onConstraintViolationOnSaveAndSaveOrUpdate(RuntimeException e); void onConstraintViolationOnPersistAndMergeAndFlush(RuntimeException e); void onTransientObjectOnSaveAndSaveOrUpdate(RuntimeException e); void onTransientObjectOnPersistAndMergeAndFlush(RuntimeException e); void onInvalidQueryExecuted(RuntimeException e); void onStaleObjectMergeAndUpdateFlush(RuntimeException e); void onIdentifierGeneratorFailure(RuntimeException e); void onTransactionExceptionOnSaveAndSaveOrUpdate(RuntimeException e); void onTransactionExceptionOnPersistAndMergeAndFlush(RuntimeException e); void onTransactionExceptionOnCommit(RuntimeException e); }//package com.backend.rybakowka.model; // //import lombok.Getter; // //import java.util.Collections; // //public class CurrentUser extends org.springframework.security.core.userdetails.User { // // @Getter // private User user; // // public CurrentUser(User user) { // super(user.getLogin(), user.getPassword(), Collections.emptyList()); // } //} package tech.indicio.ariesmobileagentandroid.admin.connections.messages; import com.google.gson.annotations.SerializedName; import tech.indicio.ariesmobileagentandroid.admin.messages.BaseAdminConfirmationMessage; public class DeletedConnectionMessage extends BaseAdminConfirmationMessage { @SerializedName("@type") public final static String type = "https://github.com/hyperledger/aries-toolbox/tree/master/docs/admin-connections/0.1/deleted"; @SerializedName("connection_id") public String connectionId; public String getType() { return type; } } package org.datazup.utils; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Locale; /** * Created by admin@datazup on 11/25/16. */ public class DateTimeUtils { private static List COMMON_DATE_TIME_FORMATS = Arrays.asList(ISODateTimeFormat.dateTime(), getFormatter("yyyy-MM-dd'T'HH:mm:ss.SSS"), getFormatter("yyyy-MM-dd'T'HH:mm:ss"), getFormatter("yyyy-MM-dd'T'HH:mm:ssZ"), getFormatter("yyyy-MM-dd'T'HH:mm:ss.SSSZ"), getFormatter("yyyy-MM-dd'T'hh:mm:ssZ a"), getFormatter("yyyy-MM-dd HH:mm:ss"), getFormatter("yyyy-MM-dd HH:mm:ss"), getFormatter("EEE MMM dd HH:mm:ss Z yyyy"), getFormatter("EEE MMM dd HH:mm:ss zz yyyy"), getFormatter("YYYYMMddHHmmss.SSSZ")); private static DateTimeFormatter getFormatter(String format) { DateTimeFormatter fmt; if (StringUtils.isEmpty(format)) { fmt = DateTimeFormat.longDateTime().withZoneUTC().withLocale(Locale.ENGLISH);//fullDateTime().withZoneUTC().withLocale(Locale.ENGLISH); } else { fmt = DateTimeFormat.forPattern(format).withZoneUTC().withLocale(Locale.ENGLISH); } return fmt; } /* private static DateTimeFormatter getFormatter(String format, Locale locale) { DateTimeFormatter fmt = DateTimeFormat.forPattern(format).withZoneUTC().withLocale(locale); return fmt; } */ public static ZoneOffset resolveZoneOffset(Integer tzValue) { ZoneOffset zoneOffset = ZoneOffset.UTC; if (null == tzValue) return zoneOffset; if (tzValue >= -18 && tzValue <= 18) { zoneOffset = ZoneOffset.ofHours(tzValue); } else { tzValue = tzValue / 60;// if it is in minutes zoneOffset = ZoneOffset.ofHours(tzValue); } return zoneOffset; } public static ZoneOffset resolveZoneOffset(Object tzValue) { ZoneOffset zoneOffset = ZoneOffset.UTC; if (null == tzValue) return zoneOffset; Integer i = TypeUtils.resolveInteger(tzValue); if (null != i) { zoneOffset = resolveZoneOffset(i); } return zoneOffset; } public static Instant resolve(Object dtValue, Object tzValue) { Instant dtInstant = resolve(dtValue); if (null == dtInstant) return null; if (null == tzValue) return dtInstant; ZoneOffset zoneOffset = resolveZoneOffset(tzValue); Instant dtInstantWithZone = dtInstant.atOffset(zoneOffset).toLocalDateTime().toInstant(ZoneOffset.UTC); return dtInstantWithZone; } public static Instant resolve(Object obj) { if (null == obj) return null; if (obj instanceof Instant) { return (Instant) obj; } else if (obj instanceof DateTime) { return from((DateTime) obj); } else if (obj instanceof Date) { return ((Date) obj).toInstant(); } else if (obj instanceof java.sql.Date) { return Instant.ofEpochMilli(((java.sql.Date) obj).getTime()); } else if (obj instanceof Number) return Instant.ofEpochMilli(((Number) obj).longValue()); else if (obj instanceof String) { Instant dt = null; try { dt = Instant.parse((String) obj); return dt; } catch (Exception e) { // nothing } if (null == dt) { for (DateTimeFormatter fmt : COMMON_DATE_TIME_FORMATS) { dt = resolve(fmt, (String) obj); if (null != dt) { return dt; } } } } return null; } public static Instant from(DateTime dt) { Instant i = Instant.ofEpochMilli(dt.getMillis()); return i; } public static Instant resolve(DateTimeFormatter fmt, String dateString) { try { DateTime dt = DateTime.parse(dateString, fmt); dt = dt.withZone(DateTimeZone.UTC); return from(dt); } catch (Exception e) { // e.printStackTrace(); return null; } } public static Instant resolve(Long timestamp) { return Instant.ofEpochMilli(timestamp); } public static Instant resolve(String datetime) { return Instant.parse(datetime); } public static Instant resolve(String datetime, String format) { DateTimeFormatter fmt = getFormatter(format); return resolve(fmt, datetime); } public static int getSecond(Instant instant) { return LocalDateTime.ofInstant(instant, ZoneOffset.UTC).getSecond(); } public static int getMinute(Instant instant) { return LocalDateTime.ofInstant(instant, ZoneOffset.UTC).getMinute(); } public static int getHour(Instant instant) { return LocalDateTime.ofInstant(instant, ZoneOffset.UTC).getHour(); } public static int getDayOfMonth(Instant instant) { return LocalDateTime.ofInstant(instant, ZoneOffset.UTC).getDayOfMonth(); } public static int getMonth(Instant instant) { return LocalDateTime.ofInstant(instant, ZoneOffset.UTC).getMonthValue(); } public static int getYear(Instant instant) { return LocalDateTime.ofInstant(instant, ZoneOffset.UTC).getYear(); } public static Instant format(Instant dt, String format) { DateTimeFormatter formatter = getFormatter(format); DateTime dti = new DateTime(dt.toEpochMilli()); String dtString = dti.toString(formatter); return resolve(dtString, format); } public static Instant format(DateTime dt, String format) { String dtString = dt.toString(format); return resolve(dtString, format); } public static Instant format(Date dt, String format) { Instant instant = dt.toInstant(); return format(instant, format); } public static Instant format(Long dt, String format) { Instant instant = Instant.ofEpochMilli(dt); if (null == format || format.isEmpty()) { return instant; } return format(instant, format); } } Goooler/gradle-download-tasksrc/test/java/de/undercouch/gradle/tasks/download/SslTest.java0 // Copyright 2013-2019 // // 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 de.undercouch.gradle.tasks.download; import com.github.tomakehurst.wiremock.junit5.WireMockExtension; import org.gradle.workers.WorkerExecutionException; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import java.io.File; import java.nio.charset.StandardCharsets; import java.security.cert.CertPathBuilderException; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * Tests if the plugin can handle HTTPS * @author */ public class SslTest extends TestBase { @RegisterExtension static WireMockExtension wireMock = WireMockExtension.newInstance() .options(wireMockConfig() .dynamicHttpsPort() .keystorePath(SslTest.class.getResource("/keystore").toString()) .keystorePassword("") .keyManagerPassword("") .jettyStopTimeout(10000L)) .configureStaticDsl(true) .build(); /** * Tests if the plugin can fetch a resource from an HTTPS URL accepting * any certificate * @throws Exception if anything goes wrong */ @Test public void acceptAnyCertificate() throws Exception { stubFor(get(urlEqualTo("/" + TEST_FILE_NAME)) .willReturn(aResponse() .withBody(CONTENTS))); Download t = makeProjectAndTask(); t.src(wireMock.url(TEST_FILE_NAME)); File dst = newTempFile(); t.dest(dst); t.acceptAnyCertificate(true); assertThat(t.isAcceptAnyCertificate()).isTrue(); execute(t); assertThat(dst).usingCharset(StandardCharsets.UTF_8).hasContent(CONTENTS); } /** * Tests if connecting to an HTTPS URL fails if the certificate is unknown * @throws Exception if anything goes wrong */ @Test public void unknownCertificate() throws Exception { Download t = makeProjectAndTask(); t.src(wireMock.url(TEST_FILE_NAME)); File dst = newTempFile(); t.dest(dst); assertThat(t.isAcceptAnyCertificate()).isFalse(); assertThatThrownBy(() -> execute(t)) .isInstanceOf(WorkerExecutionException.class) .getRootCause() .isInstanceOf(CertPathBuilderException.class) .hasMessageContaining("unable to find valid certification path"); } } package edu.coursera.distributed; import java.util.Map; import java.util.HashMap; import java.util.Iterator; /** * A class to represent a virtual, in-memory filesystem. PCDPFilesystem exposes * two user-visible APIs: one for adding a file to a given virtual filesystem * (addFile) and one for reading the contents of a file that already exists * (readFile). */ public class PCDPFilesystem { /** * The root folder for the virtual filesystem. */ private final PCDPFolder root = new PCDPFolder("static"); /** * Default constructor, creating an empty filesystem. */ public PCDPFilesystem() { } /** * Add a file at the provided path with the provided contents. * * @param path PCDPPath to the new file to create * @param contents Contents of the new file */ public void addFile(PCDPPath path, String contents) { assert path.getNComponents() > 0; assert path.getComponent(0).equals(root.getName()); int componentIndex = 1; PCDPFolder curr = root; while (componentIndex < path.getNComponents()) { String component = path.getComponent(componentIndex++); PCDPFilesystemComponent next = curr.getChild(component); if (componentIndex < path.getNComponents()) { // Haven't reached bottom of path yet so must be folder if (next == null) { PCDPFolder newFolder = new PCDPFolder(component); curr.addChild(newFolder); curr = newFolder; } else { assert next instanceof PCDPFolder; curr = (PCDPFolder)next; } } else { // Reached base filename assert next == null; PCDPFile newFile = new PCDPFile(component, contents); curr.addChild(newFile); } } } /** * Read the file specified by path. * * @param path The absolute path to the file to read. * @return The contents of the specified file, or null if the file does not * seem to exist. */ public String readFile(PCDPPath path) { if (path.getNComponents() == 0) { return null; } if (!path.getComponent(0).equals(root.getName())) { return null; } int componentIndex = 1; PCDPFilesystemComponent curr = root; while (componentIndex < path.getNComponents()) { final String nextComponent = path.getComponent(componentIndex++); if (curr == null || !(curr instanceof PCDPFolder)) { return null; } PCDPFilesystemComponent next = ((PCDPFolder)curr).getChild( nextComponent); curr = next; } if (curr == null || !(curr instanceof PCDPFile)) { return null; } else { return ((PCDPFile)curr).read(); } } } spark-java/src/main/java/cn/ioceye/core/sorted/SencondarySort.java package cn.ioceye.core.sorted; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.PairFunction; import org.apache.spark.api.java.function.VoidFunction; import scala.Tuple2; public class SencondarySort { public static void main(String[] args) { SparkConf conf = new SparkConf() .setAppName("SencondarySort") .setMaster("local"); JavaSparkContext jsc = new JavaSparkContext(conf); JavaRDD linesRDD = jsc.textFile("hdfs://master:9000/user/spark/data/sort.txt", 3); JavaPairRDD linePairRDD = linesRDD.mapToPair(new PairFunction() { private static final long serialVersionUID = 1L; @Override public Tuple2 call(String line) throws Exception { String[] words = line.split(" "); SencondarySortKey key = new SencondarySortKey(Integer.valueOf(words[0]), Integer.valueOf(words[1])); return new Tuple2(key, line); } }); JavaPairRDD lineSortRDD = linePairRDD.sortByKey(); lineSortRDD.foreach(new VoidFunction>() { private static final long serialVersionUID = 1L; @Override public void call(Tuple2 sortedKeys) throws Exception { System.out.println(sortedKeys._1.getFirst() + " " + sortedKeys._1.getSecond()); } }); jsc.close(); } } /* * 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.gs.dmn.signavio.runtime; import com.gs.dmn.feel.analysis.semantics.environment.Declaration; import com.gs.dmn.feel.analysis.semantics.environment.Environment; import com.gs.dmn.feel.analysis.semantics.environment.EnvironmentFactory; import com.gs.dmn.feel.analysis.semantics.environment.StandardEnvironmentFactory; import com.gs.dmn.feel.analysis.semantics.type.BuiltinFunctionType; import com.gs.dmn.feel.analysis.syntax.ast.expression.function.FormalParameter; import com.gs.dmn.runtime.DMNContext; import com.gs.dmn.runtime.DMNContextKind; import com.gs.dmn.runtime.function.BuiltinFunction; import com.gs.dmn.runtime.interpreter.environment.RuntimeEnvironment; import java.util.List; import java.util.Map; import static com.gs.dmn.feel.analysis.semantics.type.AnyType.ANY; import static com.gs.dmn.feel.analysis.semantics.type.BooleanType.BOOLEAN; import static com.gs.dmn.feel.analysis.semantics.type.DateTimeType.DATE_AND_TIME; import static com.gs.dmn.feel.analysis.semantics.type.DateType.DATE; import static com.gs.dmn.feel.analysis.semantics.type.ListType.ANY_LIST; import static com.gs.dmn.feel.analysis.semantics.type.NumberType.NUMBER; import static com.gs.dmn.feel.analysis.semantics.type.StringType.STRING; import static com.gs.dmn.feel.analysis.semantics.type.TimeType.TIME; public class SignavioEnvironmentFactory implements EnvironmentFactory { private static final EnvironmentFactory INSTANCE = new SignavioEnvironmentFactory(); private static final DMNContext BUILT_IN_CONTEXT; static { Environment environment = INSTANCE.emptyEnvironment(); RuntimeEnvironment runtimeEnvironment = RuntimeEnvironment.of(); addSignavioFunctions(environment); for (Map.Entry> entry: environment.getVariablesTable().entrySet()) { runtimeEnvironment.bind(entry.getKey(), BuiltinFunction.of(entry.getValue())); } BUILT_IN_CONTEXT = DMNContext.of( null, DMNContextKind.BUILT_IN, null, environment, runtimeEnvironment ); } public static EnvironmentFactory instance() { return INSTANCE; } @Override public DMNContext getBuiltInContext() { return SignavioEnvironmentFactory.BUILT_IN_CONTEXT; } private static void addSignavioFunctions(Environment environment) { // Data acceptance functions addDataAcceptanceFunctions(environment); // Conversion functions addConversionFunctions(environment); // Number functions addNumberFunctions(environment); // String functions addStringFunctions(environment); // Boolean functions addBooleanFunctions(environment); // Date time functions addDateTimeFunctions(environment); // List functions addListFunctions(environment); // Statistical operations addStatisticalFunctions(environment); } private static void addDataAcceptanceFunctions(Environment environment) { addFunctionDeclaration(environment, "isDefined", new BuiltinFunctionType(BOOLEAN, new FormalParameter("arg", ANY))); addFunctionDeclaration(environment, "isUndefined", new BuiltinFunctionType(BOOLEAN, new FormalParameter("arg", ANY))); addFunctionDeclaration(environment, "isValid", new BuiltinFunctionType(BOOLEAN, new FormalParameter("arg", ANY))); addFunctionDeclaration(environment, "isInvalid", new BuiltinFunctionType(BOOLEAN, new FormalParameter("arg", ANY))); } private static void addConversionFunctions(Environment environment) { addFunctionDeclaration(environment, "date", new BuiltinFunctionType(DATE, new FormalParameter("from", STRING))); addFunctionDeclaration(environment, "date and time", new BuiltinFunctionType(DATE_AND_TIME, new FormalParameter("from", STRING))); addFunctionDeclaration(environment, "time", new BuiltinFunctionType(TIME, new FormalParameter("from", STRING))); addFunctionDeclaration(environment, "string", new BuiltinFunctionType(STRING, new FormalParameter("from", ANY))); } private static void addNumberFunctions(Environment environment) { addFunctionDeclaration(environment, "abs", new BuiltinFunctionType(NUMBER, new FormalParameter("number", NUMBER))); addFunctionDeclaration(environment, "count", new BuiltinFunctionType(NUMBER, new FormalParameter("list", ANY_LIST))); addFunctionDeclaration(environment, "round", new BuiltinFunctionType(NUMBER, new FormalParameter("number", NUMBER), new FormalParameter("digits", NUMBER))); addFunctionDeclaration(environment, "ceiling", new BuiltinFunctionType(NUMBER, new FormalParameter("n", NUMBER))); addFunctionDeclaration(environment, "floor", new BuiltinFunctionType(NUMBER, new FormalParameter("n", NUMBER))); addFunctionDeclaration(environment, "integer", new BuiltinFunctionType(NUMBER, new FormalParameter("number", NUMBER))); addFunctionDeclaration(environment, "modulo", new BuiltinFunctionType(NUMBER, new FormalParameter("dividend", NUMBER), new FormalParameter("divisor", NUMBER))); addFunctionDeclaration(environment, "percent", new BuiltinFunctionType(NUMBER, new FormalParameter("number", NUMBER))); addFunctionDeclaration(environment, "power", new BuiltinFunctionType(NUMBER, new FormalParameter("base", NUMBER), new FormalParameter("exponent", NUMBER))); addFunctionDeclaration(environment, "product", new BuiltinFunctionType(NUMBER, new FormalParameter("list", ANY_LIST))); addFunctionDeclaration(environment, "roundDown", new BuiltinFunctionType(NUMBER, new FormalParameter("number", NUMBER), new FormalParameter("digits", NUMBER))); addFunctionDeclaration(environment, "roundUp", new BuiltinFunctionType(NUMBER, new FormalParameter("number", NUMBER), new FormalParameter("digits", NUMBER))); addFunctionDeclaration(environment, "sum", new BuiltinFunctionType(NUMBER, new FormalParameter("list", ANY_LIST))); } private static void addStringFunctions(Environment environment) { addFunctionDeclaration(environment, "concat", new BuiltinFunctionType(STRING, new FormalParameter("list", ANY_LIST))); addFunctionDeclaration(environment, "isAlpha", new BuiltinFunctionType(BOOLEAN, new FormalParameter("text", STRING))); addFunctionDeclaration(environment, "isAlphanumeric", new BuiltinFunctionType(BOOLEAN, new FormalParameter("text", STRING))); addFunctionDeclaration(environment, "isNumeric", new BuiltinFunctionType(BOOLEAN, new FormalParameter("text", STRING))); addFunctionDeclaration(environment, "isSpaces", new BuiltinFunctionType(BOOLEAN, new FormalParameter("text", STRING))); addFunctionDeclaration(environment, "len", new BuiltinFunctionType(NUMBER, new FormalParameter("text", STRING))); addFunctionDeclaration(environment, "lower", new BuiltinFunctionType(STRING, new FormalParameter("text", STRING))); addFunctionDeclaration(environment, "trim", new BuiltinFunctionType(STRING, new FormalParameter("text", STRING))); addFunctionDeclaration(environment, "upper", new BuiltinFunctionType(STRING, new FormalParameter("text", STRING))); addFunctionDeclaration(environment, "number", new BuiltinFunctionType(NUMBER, new FormalParameter("text", STRING), new FormalParameter("default_value", NUMBER, true, false))); addFunctionDeclaration(environment, "mid", new BuiltinFunctionType(STRING, new FormalParameter("text", STRING), new FormalParameter("start", NUMBER), new FormalParameter("num_chars", NUMBER))); addFunctionDeclaration(environment, "left", new BuiltinFunctionType(STRING, new FormalParameter("text", STRING), new FormalParameter("num_chars", NUMBER))); addFunctionDeclaration(environment, "right", new BuiltinFunctionType(STRING, new FormalParameter("text", STRING), new FormalParameter("num_chars", NUMBER))); addFunctionDeclaration(environment, "text", new BuiltinFunctionType(STRING, new FormalParameter("num", NUMBER), new FormalParameter("format_text", STRING))); addFunctionDeclaration(environment, "textOccurrences", new BuiltinFunctionType(NUMBER, new FormalParameter("find_text", STRING), new FormalParameter("within_text", STRING))); addFunctionDeclaration(environment, "contains", new BuiltinFunctionType(BOOLEAN, new FormalParameter("text", STRING), new FormalParameter("substring", STRING))); addFunctionDeclaration(environment, "startsWith", new BuiltinFunctionType(BOOLEAN, new FormalParameter("string", STRING), new FormalParameter("prefix", STRING))); addFunctionDeclaration(environment, "endsWith", new BuiltinFunctionType(BOOLEAN, new FormalParameter("string", STRING), new FormalParameter("suffix", STRING))); } private static void addBooleanFunctions(Environment environment) { addFunctionDeclaration(environment, "not", new BuiltinFunctionType(BOOLEAN, new FormalParameter("negand", BOOLEAN))); } private static void addDateTimeFunctions(Environment environment) { addFunctionDeclaration(environment, "day", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", DATE))); addFunctionDeclaration(environment, "day", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", DATE_AND_TIME))); addFunctionDeclaration(environment, "dayAdd", new BuiltinFunctionType(DATE, new FormalParameter("datetime", DATE), new FormalParameter("days_to_add", NUMBER))); addFunctionDeclaration(environment, "dayAdd", new BuiltinFunctionType(DATE, new FormalParameter("datetime", DATE_AND_TIME), new FormalParameter("days_to_add", NUMBER))); addFunctionDeclaration(environment, "dayDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", DATE), new FormalParameter("datetime2", DATE))); addFunctionDeclaration(environment, "dayDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", DATE_AND_TIME), new FormalParameter("datetime2", DATE_AND_TIME))); addFunctionDeclaration(environment, "date", new BuiltinFunctionType(DATE, new FormalParameter("year", NUMBER), new FormalParameter("month", NUMBER), new FormalParameter("day", NUMBER))); addFunctionDeclaration(environment, "dateTime", new BuiltinFunctionType(DATE_AND_TIME, new FormalParameter("day", NUMBER), new FormalParameter("month", NUMBER), new FormalParameter("year", NUMBER), new FormalParameter("hour", NUMBER), new FormalParameter("minute", NUMBER), new FormalParameter("second", NUMBER), new FormalParameter("hourOffset", NUMBER, true, false))); addFunctionDeclaration(environment, "hour", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", TIME))); addFunctionDeclaration(environment, "hour", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", DATE_AND_TIME))); addFunctionDeclaration(environment, "hourDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", TIME), new FormalParameter("datetime2", TIME))); addFunctionDeclaration(environment, "hourDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", DATE_AND_TIME), new FormalParameter("datetime2", DATE_AND_TIME))); addFunctionDeclaration(environment, "minute", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", TIME))); addFunctionDeclaration(environment, "minute", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", DATE_AND_TIME))); addFunctionDeclaration(environment, "minutesDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", TIME), new FormalParameter("datetime2", TIME))); addFunctionDeclaration(environment, "minutesDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", DATE_AND_TIME), new FormalParameter("datetime2", DATE_AND_TIME))); addFunctionDeclaration(environment, "month", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", DATE))); addFunctionDeclaration(environment, "month", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", DATE_AND_TIME))); addFunctionDeclaration(environment, "monthAdd", new BuiltinFunctionType(DATE, new FormalParameter("datetime", DATE), new FormalParameter("months_to_add", NUMBER))); addFunctionDeclaration(environment, "monthAdd", new BuiltinFunctionType(DATE, new FormalParameter("datetime", DATE_AND_TIME), new FormalParameter("months_to_add", NUMBER))); addFunctionDeclaration(environment, "monthDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", DATE), new FormalParameter("datetime2", DATE))); addFunctionDeclaration(environment, "monthDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", DATE_AND_TIME), new FormalParameter("datetime2", DATE_AND_TIME))); addFunctionDeclaration(environment, "now", new BuiltinFunctionType(DATE_AND_TIME)); addFunctionDeclaration(environment, "today", new BuiltinFunctionType(DATE)); addFunctionDeclaration(environment, "weekday", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", DATE))); addFunctionDeclaration(environment, "weekday", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", DATE_AND_TIME))); addFunctionDeclaration(environment, "year", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", DATE))); addFunctionDeclaration(environment, "year", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime", DATE_AND_TIME))); addFunctionDeclaration(environment, "yearAdd", new BuiltinFunctionType(DATE_AND_TIME, new FormalParameter("datetime", DATE), new FormalParameter("years_to_add", NUMBER))); addFunctionDeclaration(environment, "yearAdd", new BuiltinFunctionType(DATE_AND_TIME, new FormalParameter("datetime", DATE_AND_TIME), new FormalParameter("years_to_add", NUMBER))); addFunctionDeclaration(environment, "yearDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", DATE), new FormalParameter("datetime2", DATE))); addFunctionDeclaration(environment, "yearDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", DATE_AND_TIME), new FormalParameter("datetime2", DATE_AND_TIME))); addFunctionDeclaration(environment, "yearDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", DATE), new FormalParameter("datetime2", DATE_AND_TIME))); addFunctionDeclaration(environment, "yearDiff", new BuiltinFunctionType(NUMBER, new FormalParameter("datetime1", DATE_AND_TIME), new FormalParameter("datetime2", DATE))); } private static void addListFunctions(Environment environment) { addFunctionDeclaration(environment, "append", StandardEnvironmentFactory.makeSignavioAppendBuiltinFunctionType(ANY_LIST, ANY)); addFunctionDeclaration(environment, "appendAll", StandardEnvironmentFactory.makeSignavioAppendAllBuiltinFunctionType(ANY_LIST)); addFunctionDeclaration(environment, "remove", StandardEnvironmentFactory.makeSignavioRemoveBuiltinFunctionType(ANY_LIST, ANY)); addFunctionDeclaration(environment, "removeAll", StandardEnvironmentFactory.makeSignavioRemoveAllBuiltinFunctionType(ANY_LIST)); addFunctionDeclaration(environment, "zip", StandardEnvironmentFactory.makeSignavioZipBuiltinFunctionType(ANY_LIST, ANY_LIST, ANY_LIST)); addFunctionDeclaration(environment, "notContainsAny", new BuiltinFunctionType(BOOLEAN, new FormalParameter("list1", ANY_LIST), new FormalParameter("list2", ANY_LIST))); addFunctionDeclaration(environment, "containsOnly", new BuiltinFunctionType(BOOLEAN, new FormalParameter("list1", ANY_LIST), new FormalParameter("list2", ANY_LIST))); addFunctionDeclaration(environment, "areElementsOf", new BuiltinFunctionType(BOOLEAN, new FormalParameter("list1", ANY_LIST), new FormalParameter("list2", ANY_LIST))); addFunctionDeclaration(environment, "elementOf", new BuiltinFunctionType(BOOLEAN, new FormalParameter("list1", ANY), new FormalParameter("list2", ANY_LIST))); } private static void addStatisticalFunctions(Environment environment) { addFunctionDeclaration(environment, "avg", new BuiltinFunctionType(NUMBER, new FormalParameter("list", ANY_LIST))); addFunctionDeclaration(environment, "max", new BuiltinFunctionType(NUMBER, new FormalParameter("list", ANY_LIST))); addFunctionDeclaration(environment, "median", new BuiltinFunctionType(NUMBER, new FormalParameter("list", ANY_LIST))); addFunctionDeclaration(environment, "min", new BuiltinFunctionType(NUMBER, new FormalParameter("list", ANY_LIST))); addFunctionDeclaration(environment, "mode", new BuiltinFunctionType(NUMBER, new FormalParameter("list", ANY_LIST))); } private static void addFunctionDeclaration(Environment environment, String name, BuiltinFunctionType functionType) { environment.addDeclaration(INSTANCE.makeVariableDeclaration(name, functionType)); } } module toberkoe.pluto { requires java.annotation; requires java.naming; requires java.persistence; requires java.sql; requires javax.ejb.api; requires javax.inject; requires javafx.base; requires hibernate.core; requires hsqldb; requires log4j; requires org.junit.jupiter.api; requires org.mockito; }src/main/java/com/example/demo/exception/ICustomErrorCode.java package com.example.demo.exception; public interface ICustomErrorCode { String getMessage(); Integer getCode(); } aordorica/javaInterpreter0 package interpreter.bytecode; import interpreter.VirtualMachine; import java.util.ArrayList; public class PopCode extends ByteCode { public int numPop; public void init(ArrayList args) { numPop = Integer.parseInt(args.get(0)); } @Override public void execute(VirtualMachine virtualMachine) { for (int i = 0; i <= numPop; i++){ virtualMachine.pop(); } } } package com.hgys.iptv.model.enums; public enum CpStatusEnum { // 状态:正常、结算、异常、注销。 CP_NORMAL(1), CP_SETTLE(2), CP_ERROR(3), CP_CANCELLED(4); private final Integer status; CpStatusEnum(Integer status) { this.status = status; } public String getStatus() { return name(); } }10-100 package mrl.motion.data; import java.util.HashMap; import java.util.HashSet; import javax.vecmath.Quat4d; import javax.vecmath.Vector3d; public class HumanInertia { private static HashMap map; private static HashSet passSet = new HashSet(); static{ map = new HashMap(); map.put("Hips", new HumanInertia(11.800000, new Quat4d(0.000000, 0.000000, -0.207912, 0.978148), new Vector3d(20.740500, 24.804300, 26.547000))); map.put("Spine", new HumanInertia(2.400000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(4.472140, 21.794500, 29.240400))); map.put("Spine1", new HumanInertia(24.900000, new Quat4d(0.000000, 0.000000, -0.104528, 0.994522), new Vector3d(37.374700, 21.492500, 33.477200))); map.put("Spine2", new HumanInertia(0.000000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(0.000000, 0.000000, 0.000000))); map.put("Neck", new HumanInertia(1.100000, new Quat4d(0.000000, 0.000000, 0.190809, 0.981627), new Vector3d(8.090400, 13.211600, 11.441600))); map.put("Head", new HumanInertia(4.200000, new Quat4d(0.000000, 0.000000, -0.309017, 0.951057), new Vector3d(20.283700, 16.124500, 13.309500))); map.put("LeftShoulder", new HumanInertia(0.000000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(0.000000, 0.000000, 0.000000))); map.put("LeftArm", new HumanInertia(2.000000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(27.550000, 9.327380, 9.327380))); map.put("LeftForeArm", new HumanInertia(1.400000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(26.672600, 7.745970, 7.745970))); map.put("LeftHand", new HumanInertia(0.500000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(15.491900, 8.485280, 4.898980))); map.put("RightShoulder", new HumanInertia(0.000000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(0.000000, 0.000000, 0.000000))); map.put("RightArm", new HumanInertia(2.000000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(27.550000, 9.327380, 9.327380))); map.put("RightForeArm", new HumanInertia(1.400000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(26.672600, 7.745970, 7.745970))); map.put("RightHand", new HumanInertia(0.500000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(15.491900, 8.485280, 4.898980))); map.put("LeftUpLeg", new HumanInertia(9.800000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(41.786600, 16.635300, 16.635300))); map.put("LeftLeg", new HumanInertia(3.800000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(42.445000, 10.588000, 10.588000))); map.put("LeftFoot", new HumanInertia(1.000000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(6.000000, 22.181100, 7.745970))); map.put("LeftToe", new HumanInertia(0.000000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(0.000000, 0.000000, 0.000000))); map.put("RightUpLeg", new HumanInertia(9.800000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(41.786600, 16.635300, 16.635300))); map.put("RightLeg", new HumanInertia(3.800000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(42.445000, 10.588000, 10.588000))); map.put("RightFoot", new HumanInertia(1.000000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(6.000000, 22.181100, 7.745970))); map.put("RightToe", new HumanInertia(0.000000, new Quat4d(0.000000, 0.000000, 0.000000, 1.000000), new Vector3d(0.000000, 0.000000, 0.000000))); passSet.add("LeftShoulder"); passSet.add("RightShoulder"); passSet.add("LeftUpLeg"); passSet.add("RightUpLeg"); passSet.add("Spine1"); } public static HumanInertia get(String joint){ return map.get(joint); } public static boolean isPass(String joint){ return passSet.contains(joint); } public double mass; public Quat4d rotation; public Vector3d inertiaSize; public HumanInertia(double mass, Quat4d rotation, Vector3d inertiaSize) { this.mass = mass; this.rotation = rotation; this.inertiaSize = inertiaSize; } } src/main/java/net/ameba/cassandra/web/controller/SetupController.java package net.ameba.cassandra.web.controller; import net.ameba.cassandra.web.service.CassandraProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; /** * The controller for initial setup. */ @Controller public class SetupController extends AbstractBaseController { @Autowired private CassandraProperties properties; public SetupController() { } @RequestMapping(value="/setup", method=RequestMethod.GET) public void setup(ModelMap model) { if (properties.hasProperties()) { model.put("host", properties.getProperty(CassandraProperties.HOST)); model.put("jmxPort", properties.getProperty(CassandraProperties.JMX_PORT)); model.put("thriftPort", properties.getProperty(CassandraProperties.THRIFT_PORT)); model.put("framedTransport", properties.getProperty(CassandraProperties.FRAMED_TRANSPORT)); } else { model.put("host", ""); model.put("jmxPort", 8080); model.put("thriftPort", 9160); model.put("framedTransport", "false"); } } @RequestMapping(value="/setup", method=RequestMethod.POST) public String setupExecute( @RequestParam("host") String host, @RequestParam("thriftPort") int thriftPort, @RequestParam("jmxPort") int jmxPort, @RequestParam(value="framedTransport", required=false, defaultValue="false") boolean framedTransport, ModelMap model) throws Exception { properties.setProperty(CassandraProperties.HOST, host); properties.setProperty(CassandraProperties.JMX_PORT, String.valueOf(jmxPort)); properties.setProperty(CassandraProperties.THRIFT_PORT, String.valueOf(thriftPort)); properties.setProperty(CassandraProperties.FRAMED_TRANSPORT, Boolean.toString(framedTransport)); properties.saveProperties(); model.clear(); return "redirect:/"; } } 0 package edu.learn.demo; import edu.learn.jpa.entities.Wiki; import org.junit.Assert; 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.web.client.TestRestTemplate; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.reactive.server.WebTestClient; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class WikiTests { @Autowired private WebTestClient webClient; @Autowired private TestRestTemplate restTemplate; @Test public void wiki_list_by_rest_template() { Wiki[] wiki = this.restTemplate.getForObject("/api/wiki/list", Wiki[].class); Assert.assertTrue(wiki.length > 0); ResponseEntity responseEntity = this.restTemplate.getForEntity("/api/wiki/list", Wiki[].class); Assert.assertTrue(responseEntity.getBody().length > 0); } @Test public void wiki_list_by_webclient() { this.webClient.get().uri("/api/wiki/list").accept(MediaType.APPLICATION_JSON) .exchange().expectStatus().isOk().expectBodyList(Wiki.class); } } package com.example.kbvora.arihant1; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.GridView; import android.widget.ListView; import org.json.JSONException; import java.util.ArrayList; import java.util.Locale; public class Pager_suntime extends ActionBarActivity implements suntime_fregment.OnFragmentInteractionListener , ActionBar.TabListener { ArrayList mArrayList; SectionPagerAdapter sectionPagerAdapter; ViewPager mViewPager; ActionBar mActionBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pager_suntime); mArrayList = new ArrayList(); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.customColor))); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/1.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/2.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/3.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/4.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/5.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/6.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/7.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/8.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/9.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/10.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/11.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/12.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/13.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/14.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/15.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/16.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/17.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/18.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/19.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/20.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/21.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/22.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/23.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/24.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/25.png")); mArrayList.add(new suntime("http://www.jinalshah.brainoorja.com//suntime/26.png")); try { mActionBar = getSupportActionBar(); mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); sectionPagerAdapter = new SectionPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.pager2sun); mViewPager.setAdapter(sectionPagerAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { //super.onPageSelected(position); mActionBar.setSelectedNavigationItem(position); } }); for (int i = 0; i < sectionPagerAdapter.getCount(); i++) { mActionBar.addTab( mActionBar.newTab().setText(sectionPagerAdapter.getPageTitle(i)) .setTabListener((Pager_suntime.this) )); } } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_pager_suntime, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.suntirthankar_menu_action_home) { Intent i = new Intent(Pager_suntime.this,Homepage_menu.class); startActivity(i); return true; } if (id == R.id.suntirthankar_menu_action_Tirthplace) { Intent i = new Intent(Pager_suntime.this,getalltirthplace.class); startActivity(i); return true; } if (id == R.id.suntirthankar_menu_action_Tirthankar) { Intent i = new Intent(Pager_suntime.this,Tirthankar.class); startActivity(i); return true; } if (id == R.id.suntirthankar_menu_action_Jainsongs) { Intent i = new Intent(Pager_suntime.this,getallJainsongs.class); startActivity(i); return true; } if (id == R.id.suntirthankar_menu_action_Jainfestival) { Intent i = new Intent(Pager_suntime.this,getAllFestival.class); startActivity(i); return true; } if (id == R.id.suntirthankar_menu_action_Jainmagazine) { Intent i = new Intent(Pager_suntime.this,get_all_magazins.class); startActivity(i); return true; } if (id == R.id.suntirthankar_menu_action_pachhakhanan) { Intent i = new Intent(Pager_suntime.this,allpachakhan.class); startActivity(i); return true; } if (id == R.id.suntirthankar_menu_action_nearby) { Intent i = new Intent(Pager_suntime.this,MapsActivity.class); startActivity(i); return true; } return super.onOptionsItemSelected(item); } @Override public void onFragmentInteraction(Uri uri) { } @Override public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } @Override public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) { } public class SectionPagerAdapter extends FragmentPagerAdapter { public SectionPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position) { case 1: return suntime_fregment.newInstance(mArrayList.get(0).getTpath() + ""); case 2: return suntime_fregment.newInstance(mArrayList.get(1).getTpath() + ""); case 3: return suntime_fregment.newInstance(mArrayList.get(2).getTpath() + ""); case 4: return suntime_fregment.newInstance(mArrayList.get(3).getTpath() + ""); case 5: return suntime_fregment.newInstance(mArrayList.get(4).getTpath() + ""); case 6: return suntime_fregment.newInstance(mArrayList.get(5).getTpath() + ""); case 7: return suntime_fregment.newInstance(mArrayList.get(6).getTpath() + ""); case 8: return suntime_fregment.newInstance(mArrayList.get(7).getTpath() + ""); case 9: return suntime_fregment.newInstance(mArrayList.get(8).getTpath() + ""); case 10: return suntime_fregment.newInstance(mArrayList.get(9).getTpath() + ""); case 11: return suntime_fregment.newInstance(mArrayList.get(10).getTpath() + ""); case 12: return suntime_fregment.newInstance(mArrayList.get(11).getTpath() + ""); case 13: return suntime_fregment.newInstance(mArrayList.get(12).getTpath() + ""); case 14: return suntime_fregment.newInstance(mArrayList.get(13).getTpath() + ""); case 15: return suntime_fregment.newInstance(mArrayList.get(14).getTpath() + ""); case 16: return suntime_fregment.newInstance(mArrayList.get(15).getTpath() + ""); case 17: return suntime_fregment.newInstance(mArrayList.get(16).getTpath() + ""); case 18: return suntime_fregment.newInstance(mArrayList.get(17).getTpath() + ""); case 19: return suntime_fregment.newInstance(mArrayList.get(18).getTpath() + ""); case 20: return suntime_fregment.newInstance(mArrayList.get(19).getTpath() + ""); case 21: return suntime_fregment.newInstance(mArrayList.get(20).getTpath() + ""); case 22: return suntime_fregment.newInstance(mArrayList.get(21).getTpath() + ""); case 23: return suntime_fregment.newInstance(mArrayList.get(22).getTpath() + ""); case 24: return suntime_fregment.newInstance(mArrayList.get(23).getTpath() + ""); case 25: return suntime_fregment.newInstance(mArrayList.get(24).getTpath() + ""); case 26: return suntime_fregment.newInstance(mArrayList.get(25).getTpath() + ""); default: return suntime_fregment.newInstance(mArrayList.get(0).getTpath() + ""); } } @Override public int getCount() { return 26; } @Override public CharSequence getPageTitle(int position) { Locale l=Locale.getDefault(); switch (position) { case 0: return "Kartak Sud".toUpperCase(); case 1: return "Kartak Vad".toUpperCase(); case 2: return "".toUpperCase(); case 3: return "Magshar Vad".toUpperCase(); case 4: return "Posh Sud".toUpperCase(); case 5: return "Posh Vad".toUpperCase(); case 6: return "Maha Sud".toUpperCase(); case 7: return "Maha Vad".toUpperCase(); case 8: return "Fagan Sud".toUpperCase(); case 9: return "Fagan Vad".toUpperCase(); case 10: return "Chaitra Sud".toUpperCase(); case 11: return "Chaitra Vad".toUpperCase(); case 12: return "Vaishakh Sud".toUpperCase(); case 13: return "Vaishakh Vad".toUpperCase(); case 14: return "Jud".toUpperCase(); case 15: return "ad".toUpperCase(); case 16: return "".toUpperCase(); case 17: return "".toUpperCase(); case 18: return "".toUpperCase(); case 19: return "".toUpperCase(); case 20: return "".toUpperCase(); case 21: return "ad".toUpperCase(); case 22: return "ud".toUpperCase(); case 23: return "ad".toUpperCase(); case 24: return "Aso Sud".toUpperCase(); case 25: return "Aso Vad".toUpperCase(); } return null; } } } imrafaelmerino/json-valuessrc/main/java/com/dslplatform/json/JsArraySerializer.java package com.dslplatform.json; import jsonvalues.JsArray; import jsonvalues.JsValue; import java.util.Objects; final class JsArraySerializer implements JsonWriter.WriteObject { private final JsValueSerializer valueSerializer; public JsArraySerializer(final JsValueSerializer valueSerializer) { this.valueSerializer = valueSerializer; } @Override public void write(final JsonWriter writer, final JsArray list ) { writer.writeByte(JsonWriter.ARRAY_START); final int size = Objects.requireNonNull(list).size(); if (size != 0) { final JsValue first = list.get(0); valueSerializer.serialize(writer, first ); for (int i = 1; i < size; i++) { writer.writeByte(JsonWriter.COMMA); final JsValue value = list.get(i); valueSerializer.serialize(writer, value ); } } writer.writeByte(JsonWriter.ARRAY_END); } } AlSidorenko/Junior package ru.job4j.max; /** * Max. * * @author () * @version $Id$ * @since 0.1 */ public class Max { /** *Max element. *@param first - first element. *@param second - second element. *@return - max element. */ public int max(int first, int second) { return (first > second) ? first : second; } /** *Max element of three numbers. *@param first - first element. *@param second - second element. *@param third - third element. *@return - max element. */ public int maxOfThreeNumbers(int first, int second, int third) { int maxFirst = max(first, second); int maxSecond = max(maxFirst, third); return maxSecond; } }1-10 package com.be_hase.honoumi.guice; import org.jboss.netty.channel.ChannelPipelineFactory; import com.be_hase.honoumi.config.ApplicationProperties; import com.be_hase.honoumi.netty.pipeline.MonitoringServerChannelPipelineFactory; import com.be_hase.honoumi.netty.server.AbstractServer; import com.be_hase.honoumi.netty.server.IServer; import com.be_hase.honoumi.netty.server.MonitoringServer; import com.be_hase.honoumi.routing.Route; import com.google.inject.AbstractModule; import com.google.inject.Singleton; import com.google.inject.name.Names; public class MonitoringServerModule extends AbstractModule { private final MonitoringServer monitoringServer; public MonitoringServerModule(MonitoringServer monitoringServer) { this.monitoringServer = monitoringServer; } @Override protected void configure() { Names.bindProperties(binder(), ApplicationProperties.getAllCurrentProperties()); bind(IServer.class).toInstance(monitoringServer); bind(AbstractServer.class).toInstance(monitoringServer); bind(MonitoringServer.class).toInstance(monitoringServer); bind(ChannelPipelineFactory.class).to(MonitoringServerChannelPipelineFactory.class); for (Route route: monitoringServer.getRouter().getRoutes()) { bind(route.getControllerClass()).in(Singleton.class); } } } pathak-gaurav/knight-quest0 package com.gaurav.knightquest.knights; import org.springframework.stereotype.Component; @Component public class SlayDragonQuest implements Quest { @Override public void embark() { System.out.println("Embarking the quest to Slay Dragon!!"); } } /*- * ===============LICENSE_START======================================================= * Acumos * =================================================================================== * Copyright (C) 2017 AT&T Intellectual Property & Tech Mahindra. All rights reserved. * =================================================================================== * This Acumos software file is distributed by AT&T and Tech Mahindra * 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 * * This file 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. * ===============LICENSE_END========================================================= */ package org.acumos.cds.domain; import java.io.Serializable; import java.util.Date; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Size; import org.hibernate.annotations.Type; import io.swagger.annotations.ApiModelProperty; /** * Model for solution website metadata, which transports descriptive statistics * recorded on the server to the client. Never used for update from the client, * so there are no Swagger API annotations on this class. * * In a one:one relationship with solution. The relationship is mapped via * annotations on MLPSolution (unidirectional). * * These stats were separated out of the solution entity to distinguish updates * ON a solution made by the owner (e.g., description) from updates ABOUT a * solution made by the system (e.g., downloads or views). */ @Entity @Table(name = "C_SOLUTION_WEB") public class MLPSolutionWeb implements MLPEntity, Serializable { /* package */ static final String SOL_ID_COL_NAME = "SOLUTION_ID"; private static final long serialVersionUID = 5613267071143825368L; @Id @Column(name = SOL_ID_COL_NAME, nullable = false, columnDefinition = "CHAR(36)") @Size(max = 36) @ApiModelProperty(required = true, value = "UUID", example = "12345678-abcd-90ab-cdef-1234567890ab") private String solutionId; @Column(name = "VIEW_COUNT", columnDefinition = "INT") @ApiModelProperty(value = "View count", example = "1") private Long viewCount = 0L; @Column(name = "DOWNLOAD_COUNT", columnDefinition = "INT") @ApiModelProperty(value = "Download count", example = "1") private Long downloadCount = 0L; @Column(name = "LAST_DOWNLOAD", columnDefinition = "TIMESTAMP") @ApiModelProperty(value = "Date of most recent download") private Date lastDownload; @Column(name = "RATING_COUNT", columnDefinition = "INT") @ApiModelProperty(value = "Rating count", example = "1") private Long ratingCount = 0L; @Column(name = "RATING_AVG_TENTHS", columnDefinition = "INT") @ApiModelProperty(value = "Rating average in tenths; e.g., value 35 means 3.5", example = "35") private Long ratingAverageTenths = 0L; @Column(name = "FEATURED_YN", columnDefinition = "CHAR(1)") @Type(type = "yes_no") @ApiModelProperty(value = "Featured indicator") private boolean featured; /** * No-arg constructor */ public MLPSolutionWeb() { // no-arg constructor } /** * This constructor accepts the required fields; i.e., the minimum that the user * must supply to create a valid instance. * * @param solutionId * ID of solution */ public MLPSolutionWeb(String solutionId) { if (solutionId == null) throw new IllegalArgumentException("Null not permitted"); this.solutionId = solutionId; } /** * Copy constructor * * @param that * Instance to copy */ public MLPSolutionWeb(MLPSolutionWeb that) { this.downloadCount = that.downloadCount; this.featured = that.featured; this.lastDownload = that.lastDownload; this.ratingAverageTenths = that.ratingAverageTenths; this.ratingCount = that.ratingCount; this.solutionId = that.solutionId; this.viewCount = that.viewCount; } public String getSolutionId() { return solutionId; } public void setSolutionId(String solutionId) { this.solutionId = solutionId; } public Long getViewCount() { return viewCount; } public void setViewCount(Long viewCount) { this.viewCount = viewCount; } public Long getDownloadCount() { return downloadCount; } public void setDownloadCount(Long downloadCount) { this.downloadCount = downloadCount; } public Date getLastDownload() { return lastDownload; } public void setLastDownload(Date lastDownload) { this.lastDownload = lastDownload; } public Long getRatingCount() { return ratingCount; } public void setRatingCount(Long ratingCount) { this.ratingCount = ratingCount; } public Long getRatingAverageTenths() { return ratingAverageTenths; } public void setRatingAverageTenths(Long ratingAverageTenths) { this.ratingAverageTenths = ratingAverageTenths; } public boolean isFeatured() { return featured; } public void setFeatured(boolean featured) { this.featured = featured; } @Override public boolean equals(Object that) { if (that == null) return false; if (!(that instanceof MLPSolutionWeb)) return false; MLPSolutionWeb thatObj = (MLPSolutionWeb) that; return Objects.equals(solutionId, thatObj.solutionId); } @Override public int hashCode() { return Objects.hash(solutionId, downloadCount, viewCount); } @Override public String toString() { return this.getClass().getName() + "[solutionId=" + solutionId + ", views=" + viewCount + ", downloads=" + downloadCount + ", ratings=" + ratingCount + ", ..]"; } } package poo; import java.util.Arrays; public class Main { public static void main(String[] args) { Pessoa[] pessoas = new Pessoa[4]; pessoas[0] = new Pessoa("Renan", "245.678.987-03"); pessoas[1] = new Pessoa("Bruno", "245.555.666-00"); pessoas[2] = new Pessoa("Lenilson", "133.567.890-22"); pessoas[3] = new Pessoa("Eduardo", "133.567.799-34"); Ordenator.sort(pessoas); //Arrays.sort(pessoas, new CPFComparator()); for (Pessoa p: pessoas) { System.out.println(p.getNome()); } System.out.println(); Automovel[] automoveis = new Automovel[4]; automoveis[0] = new Automovel("ZZZ-4566"); automoveis[1] = new Automovel("CCC-4566"); automoveis[2] = new Automovel("DDD-4566"); automoveis[3] = new Automovel("AAA-4566"); Ordenator.sort(automoveis); for (Automovel a: automoveis) { System.out.println(a.getPlaca()); } System.out.println(); Ordenator.sort(automoveis, new PlacaInvertidaComparator()); for (Automovel a: automoveis) { System.out.println(a.getPlaca()); } } } package org.jjche.system.modules.security.service; import cn.hutool.core.util.ObjectUtil; import lombok.RequiredArgsConstructor; import org.jjche.security.dto.JwtUserDto; import org.jjche.security.dto.UserVO; import org.jjche.security.service.JwtUserService; import org.jjche.system.modules.system.service.*; import org.springframework.security.core.userdetails.UserDetailsService; /** *

UserDetailsServiceImpl class.

* * @author * @version 1.0.8-SNAPSHOT * @since 2018-11-22 */ @RequiredArgsConstructor public abstract class AbstractUserDetailsService implements UserDetailsService { protected final UserService userService; protected final DeptService deptService; protected final JobService jobService; private final RoleService roleService; private final DataService dataService; private final JwtUserService jwtUserService; /** *

* 查询用户 *

* * @param username 用户名 * @return 用户 */ abstract UserVO findUserDto(String username); /** * {@inheritDoc} */ @Override public JwtUserDto loadUserByUsername(String username) { JwtUserDto jwtUserDto = jwtUserService.getByUserName(username); if (ObjectUtil.isNull(jwtUserDto)) { UserVO user = this.findUserDto(username); if (user != null) { jwtUserDto = new JwtUserDto( user, dataService.getDataScope(user), roleService.mapToGrantedAuthorities(user) ); //防止用户状态不正常时被缓存 Boolean enabled = user.getEnabled(); Boolean isAccountNonExpired = user.getIsAccountNonExpired(); Boolean isAccountNonLocked = user.getIsAccountNonLocked(); Boolean isCredentialsNonExpired = user.getIsCredentialsNonExpired(); if (enabled && isAccountNonExpired && isAccountNonLocked && isCredentialsNonExpired) { jwtUserService.putByUserName(username, jwtUserDto); } else { jwtUserService.removeByUserName(username); } } } return jwtUserDto; } } package com.iluwatar.urm.testdomain; public class PhoneNumber { private String number; } zhoupan/MVVMFrame package com.king.mvvmframe.bean; import androidx.room.Entity; import androidx.room.Index; import androidx.room.PrimaryKey; /** * @author Jenly */ @Entity(indices = {@Index(value = "name", unique = true)}) public class SearchHistory { @PrimaryKey(autoGenerate = true) private long id; private String name; private long time; public SearchHistory(String name) { this.name = name; time = System.currentTimeMillis(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } @Override public String toString() { return "SearchHistory{" + "id=" + id + ", name='" + name + '\'' + ", time=" + time + '}'; } } package org.apache.maven.artifact.versioning; /* * 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. */ import junit.framework.TestCase; /** * Test DefaultArtifactVersion. * * @author */ public class DefaultArtifactVersionTest extends TestCase { private ArtifactVersion newArtifactVersion( String version ) { return new DefaultArtifactVersion( version ); } private void checkVersionParsing( String version, int major, int minor, int incremental, int buildnumber, String qualifier ) { ArtifactVersion artifactVersion = newArtifactVersion( version ); String parsed = "'" + version + "' parsed as ('" + artifactVersion.getMajorVersion() + "', '" + artifactVersion.getMinorVersion() + "', '" + artifactVersion.getIncrementalVersion() + "', '" + artifactVersion.getBuildNumber() + "', '" + artifactVersion.getQualifier() + "'), "; assertEquals( parsed + "check major version", major, artifactVersion.getMajorVersion() ); assertEquals( parsed + "check minor version", minor, artifactVersion.getMinorVersion() ); assertEquals( parsed + "check incremental version", incremental, artifactVersion.getIncrementalVersion() ); assertEquals( parsed + "check build number", buildnumber, artifactVersion.getBuildNumber() ); assertEquals( parsed + "check qualifier", qualifier, artifactVersion.getQualifier() ); assertEquals( "check " + version + " string value", version, artifactVersion.toString() ); } public void testVersionParsing() { checkVersionParsing( "1", 1, 0, 0, 0, null ); checkVersionParsing( "1.2", 1, 2, 0, 0, null ); checkVersionParsing( "1.2.3", 1, 2, 3, 0, null ); checkVersionParsing( "1.2.3-1", 1, 2, 3, 1, null ); checkVersionParsing( "1.2.3-alpha-1", 1, 2, 3, 0, "alpha-1" ); checkVersionParsing( "1.2-alpha-1", 1, 2, 0, 0, "alpha-1" ); checkVersionParsing( "1.2-alpha-1-20050205.060708-1", 1, 2, 0, 0, "alpha-1-20050205.060708-1" ); checkVersionParsing( "RELEASE", 0, 0, 0, 0, "RELEASE" ); checkVersionParsing( "2.0-1", 2, 0, 0, 1, null ); // 0 at the beginning of a number has a special handling checkVersionParsing( "02", 0, 0, 0, 0, "02" ); checkVersionParsing( "0.09", 0, 0, 0, 0, "0.09" ); checkVersionParsing( "0.2.09", 0, 0, 0, 0, "0.2.09" ); checkVersionParsing( "2.0-01", 2, 0, 0, 0, "01" ); // version schemes not really supported: fully transformed as qualifier checkVersionParsing( "1.0.1b", 0, 0, 0, 0, "1.0.1b" ); checkVersionParsing( "1.0M2", 0, 0, 0, 0, "1.0M2" ); checkVersionParsing( "1.0RC2", 0, 0, 0, 0, "1.0RC2" ); checkVersionParsing( "1.1.2.beta1", 1, 1, 2, 0, "beta1" ); checkVersionParsing( "1.7.3.beta1", 1, 7, 3, 0, "beta1" ); checkVersionParsing( "1.7.3.0", 0, 0, 0, 0, "1.7.3.0" ); checkVersionParsing( "1.7.3.0-1", 0, 0, 0, 0, "1.7.3.0-1" ); checkVersionParsing( "PATCH-1193602", 0, 0, 0, 0, "PATCH-1193602" ); checkVersionParsing( "5.0.0alpha-2006020117", 0, 0, 0, 0, "5.0.0alpha-2006020117" ); checkVersionParsing( "1.0.0.-SNAPSHOT", 0, 0, 0, 0, "1.0.0.-SNAPSHOT" ); checkVersionParsing( "1..0-SNAPSHOT", 0, 0, 0, 0, "1..0-SNAPSHOT" ); checkVersionParsing( "1.0.-SNAPSHOT", 0, 0, 0, 0, "1.0.-SNAPSHOT" ); checkVersionParsing( ".1.0-SNAPSHOT", 0, 0, 0, 0, ".1.0-SNAPSHOT" ); checkVersionParsing( "1.2.3.200705301630", 0, 0, 0, 0, "1.2.3.200705301630" ); checkVersionParsing( "1.2.3-200705301630", 1, 2, 3, 0, "200705301630" ); } public void testVersionComparing() { assertVersionEqual( "1", "1" ); assertVersionOlder( "1", "2" ); assertVersionOlder( "1.5", "2" ); assertVersionOlder( "1", "2.5" ); assertVersionEqual( "1", "1.0" ); assertVersionEqual( "1", "1.0.0" ); assertVersionOlder( "1.0", "1.1" ); assertVersionOlder( "1.1", "1.2" ); assertVersionOlder( "1.0.0", "1.1" ); assertVersionOlder( "1.1", "1.2.0" ); assertVersionOlder( "1.1.2.alpha1", "1.1.2" ); assertVersionOlder( "1.1.2.alpha1", "1.1.2.beta1" ); assertVersionOlder( "1.1.2.beta1", "1.2" ); assertVersionOlder( "1.0-alpha-1", "1.0" ); assertVersionOlder( "1.0-alpha-1", "1.0-alpha-2" ); assertVersionOlder( "1.0-alpha-2", "1.0-alpha-15" ); assertVersionOlder( "1.0-alpha-1", "1.0-beta-1" ); assertVersionOlder( "1.0-beta-1", "1.0-SNAPSHOT" ); assertVersionOlder( "1.0-SNAPSHOT", "1.0" ); assertVersionOlder( "1.0-alpha-1-SNAPSHOT", "1.0-alpha-1" ); assertVersionOlder( "1.0", "1.0-1" ); assertVersionOlder( "1.0-1", "1.0-2" ); assertVersionEqual( "2.0-0", "2.0" ); assertVersionOlder( "2.0", "2.0-1" ); assertVersionOlder( "2.0.0", "2.0-1" ); assertVersionOlder( "2.0-1", "2.0.1" ); assertVersionOlder( "2.0.1-klm", "2.0.1-lmn" ); assertVersionOlder( "2.0.1", "2.0.1-xyz" ); assertVersionOlder( "2.0.1-xyz-1", "2.0.1-1-xyz" ); assertVersionOlder( "2.0.1", "2.0.1-123" ); assertVersionOlder( "2.0.1-xyz", "2.0.1-123" ); assertVersionOlder( "1.2.3-10000000000", "1.2.3-10000000001" ); assertVersionOlder( "1.2.3-1", "1.2.3-10000000001" ); assertVersionOlder( "2.3.0-v200706262000", "2.3.0-v200706262130" ); // org.eclipse:emf:2.3.0-v200706262000 // org.eclipse.wst.common_core.feature_2.0.0.v200706041905-7C78EK9E_EkMNfNOd2d8qq assertVersionOlder( "2.0.0.v200706041905-7C78EK9E_EkMNfNOd2d8qq", "2.0.0.v200706041906-7C78EK9E_EkMNfNOd2d8qq" ); } public void testVersionSnapshotComparing() { assertVersionEqual( "1-SNAPSHOT", "1-SNAPSHOT" ); assertVersionOlder( "1-SNAPSHOT", "2-SNAPSHOT" ); assertVersionOlder( "1.5-SNAPSHOT", "2-SNAPSHOT" ); assertVersionOlder( "1-SNAPSHOT", "2.5-SNAPSHOT" ); assertVersionEqual( "1-SNAPSHOT", "1.0-SNAPSHOT" ); assertVersionEqual( "1-SNAPSHOT", "1.0.0-SNAPSHOT" ); assertVersionOlder( "1.0-SNAPSHOT", "1.1-SNAPSHOT" ); assertVersionOlder( "1.1-SNAPSHOT", "1.2-SNAPSHOT" ); assertVersionOlder( "1.0.0-SNAPSHOT", "1.1-SNAPSHOT" ); assertVersionOlder( "1.1-SNAPSHOT", "1.2.0-SNAPSHOT" ); // assertVersionOlder( "1.0-alpha-1-SNAPSHOT", "1.0-SNAPSHOT" ); assertVersionOlder( "1.0-alpha-1-SNAPSHOT", "1.0-alpha-2-SNAPSHOT" ); assertVersionOlder( "1.0-alpha-1-SNAPSHOT", "1.0-beta-1-SNAPSHOT" ); assertVersionOlder( "1.0-beta-1-SNAPSHOT", "1.0-SNAPSHOT-SNAPSHOT" ); assertVersionOlder( "1.0-SNAPSHOT-SNAPSHOT", "1.0-SNAPSHOT" ); assertVersionOlder( "1.0-alpha-1-SNAPSHOT-SNAPSHOT", "1.0-alpha-1-SNAPSHOT" ); assertVersionOlder( "1.0-SNAPSHOT", "1.0-1-SNAPSHOT" ); assertVersionOlder( "1.0-1-SNAPSHOT", "1.0-2-SNAPSHOT" ); // assertVersionEqual( "2.0-0-SNAPSHOT", "2.0-SNAPSHOT" ); assertVersionOlder( "2.0-SNAPSHOT", "2.0-1-SNAPSHOT" ); assertVersionOlder( "2.0.0-SNAPSHOT", "2.0-1-SNAPSHOT" ); assertVersionOlder( "2.0-1-SNAPSHOT", "2.0.1-SNAPSHOT" ); assertVersionOlder( "2.0.1-klm-SNAPSHOT", "2.0.1-lmn-SNAPSHOT" ); // assertVersionOlder( "2.0.1-xyz-SNAPSHOT", "2.0.1-SNAPSHOT" ); assertVersionOlder( "2.0.1-SNAPSHOT", "2.0.1-123-SNAPSHOT" ); assertVersionOlder( "2.0.1-xyz-SNAPSHOT", "2.0.1-123-SNAPSHOT" ); } public void testSnapshotVsReleases() { assertVersionOlder( "1.0-RC1", "1.0-SNAPSHOT" ); assertVersionOlder( "1.0-rc1", "1.0-SNAPSHOT" ); assertVersionOlder( "1.0-rc-1", "1.0-SNAPSHOT" ); } public void testHashCode() { ArtifactVersion v1 = newArtifactVersion( "1" ); ArtifactVersion v2 = newArtifactVersion( "1.0" ); assertEquals( true, v1.equals( v2 ) ); assertEquals( v1.hashCode(), v2.hashCode() ); } public void testEqualsNullSafe() { assertFalse( newArtifactVersion( "1" ).equals( null ) ); } public void testEqualsTypeSafe() { assertFalse( newArtifactVersion( "1" ).equals( "non-an-artifact-version-instance" ) ); } public void testNonNumericVersionRepresentationReturnsANumberFormatException() { try { new DefaultArtifactVersion( "..." ); } catch ( Exception e ) { assertTrue( "We expect a NumberFormatException to be thrown.", e instanceof NumberFormatException ); } } private void assertVersionOlder( String left, String right ) { assertTrue( left + " should be older than " + right, newArtifactVersion( left ).compareTo( newArtifactVersion( right ) ) < 0 ); assertTrue( right + " should be newer than " + left, newArtifactVersion( right ).compareTo( newArtifactVersion( left ) ) > 0 ); } private void assertVersionEqual( String left, String right ) { assertTrue( left + " should be equal to " + right, newArtifactVersion( left ).compareTo( newArtifactVersion( right ) ) == 0 ); assertTrue( right + " should be equal to " + left, newArtifactVersion( right ).compareTo( newArtifactVersion( left ) ) == 0 ); } } package mvedua.msu.com.spartansafety.Fragments; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import mvedua.msu.com.spartansafety.R; /** * Created by mvedua on 12/19/2017. */ class Resource { private String title; private String description; private String phoneNumber; private String color; Resource(String title, String description, String phoneNumber, String color){ this.title = title; this.description = description; this.phoneNumber = phoneNumber; this.color = color; } public String getTitle() { return title; } public String getDescription() { return description; } public String getPhoneNumber() { return phoneNumber; } public String getColor() { return color; } } class ResourceAdapter extends ArrayAdapter{ ResourceAdapter(Context context, ArrayList resources){ super(context, 0, resources); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { Resource resource = getItem(position); if(convertView == null){ convertView = LayoutInflater.from(getContext()).inflate(R.layout.resource_listview_layout, parent, false); } TextView resTitle = convertView.findViewById(R.id.title); TextView resDesc = convertView.findViewById(R.id.description); resTitle.setText(resource.getTitle()); resDesc.setText(resource.getDescription()); resTitle.setTextColor(Color.parseColor(resource.getColor())); return convertView; } } public class ResourcesFragment extends Fragment{ ArrayList resources = new ArrayList(); ListView listView; static ResourceAdapter adapter; private void initResources(){ //TODO: Add Correct Phone Numbers resources.add(new Resource("Alcohol, Tobacco, & Other Drugs", "Collegiate Recovery Program", "(586)214-9433", "#3A172B")); resources.add(new Resource("Counseling Center", "Schedule an Appointment", "ToBeSet", "#2E4348")); resources.add(new Resource("Crisis Text Line", "Get Help Now: Free, 24/7, Confidential", "ToBeSet", "#9E5B3E")); resources.add(new Resource("HIV Counseling & Testing", "Schedule an Appointment", "ToBeSet", "#285631")); resources.add(new Resource("Medical Emergency", "Call 911", "911", "#5C1B17")); resources.add(new Resource("Medical & Wellness Visits", "Schedule an Appointment", "ToBeSet", "#3A172B")); resources.add(new Resource("Nutrition Counseling", "Schedule an Appointment", "ToBeSet", "#2E4348")); resources.add(new Resource("Olin Phone Information Nurse", "24 Hour Service", "ToBeSet", "#9E5B3E")); resources.add(new Resource("Sexual Assault Hotline", "24 Hour Crisis Line", "ToBeSet", "#285631")); resources.add(new Resource("STI Counseling & Testing", "Schedule an Appointment", "ToBeSet", "#5C1B17")); resources.add(new Resource("Suicide Prevention Hotline", "24 Hour Service", "ToBeSet", "#3A172B")); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.resources_fragment, container, false); listView = view.findViewById(R.id.resourceList); adapter = new ResourceAdapter(getContext(), resources); listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { final Resource clickedResource = (Resource)parent.getItemAtPosition(position); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage("\n\t\tPhone Number: " +clickedResource.getPhoneNumber()) .setTitle(clickedResource.getTitle()); builder.setPositiveButton("Call", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent callIntent = new Intent(Intent.ACTION_DIAL); callIntent.setData(Uri.parse("tel:"+clickedResource.getPhoneNumber())); startActivity(callIntent); } }); AlertDialog dialog = builder.create(); dialog.show(); } }); return view; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initResources(); } @Override public void onPause() { super.onPause(); } } Client/src/models/comperessedData/CompressedPlayer.java package models.comperessedData; import models.card.CardType; import view.BattleView.Constants; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class CompressedPlayer { private String userName; private int currentMP; private List hand; private List graveyard; private CompressedCard nextCard; private int playerNumber; private List troops; private CompressedTroop hero; private PropertyChangeSupport support = new PropertyChangeSupport(this); public void addPropertyChangeListener(PropertyChangeListener pcl) { if (support == null) { support = new PropertyChangeSupport(this); } support.addPropertyChangeListener(pcl); } public void removePropertyChangeListener(PropertyChangeListener pcl) { support.removePropertyChangeListener(pcl); } public void addNextCardToHand() { hand.add(nextCard); if (support == null) { support = new PropertyChangeSupport(this); } support.firePropertyChange("hand", null, null); if (hand.size() > Constants.MAXIMUM_CARD_HAND_SIZE) System.out.println("Client Game Error! - current card hand exceeds max card hand size size"); } public void addCardToNext(CompressedCard card) { if (nextCard != null) System.out.println("Client Game Error!"); else { nextCard = card; if (support == null) { support = new PropertyChangeSupport(this); } support.firePropertyChange("next", null, null); } } public void replaceSelectedCard(int selectedCardIndex) { hand.set(selectedCardIndex, nextCard); removeCardFromNext(); if (support == null) { support = new PropertyChangeSupport(this); } support.firePropertyChange("replace", null, null); } void addCardToGraveYard(CompressedCard card) { graveyard.add(card); } void troopUpdate(CompressedTroop troop) { if (troops == null) troops = new ArrayList<>(); removeTroop(troop.getCard().getCardId()); if (troop.getCurrentHp() > 0) { troops.add(troop); if (troop.getCard().getType() == CardType.HERO) hero = troop; } } void removeCardFromHand(String cardId) { hand.removeIf(compressedCard -> compressedCard.getCardId().equalsIgnoreCase(cardId)); if (support == null) { support = new PropertyChangeSupport(this); } support.firePropertyChange("hand", null, null); } public void removeCardFromNext() { nextCard = null; if (support == null) { support = new PropertyChangeSupport(this); } support.firePropertyChange("next", null, null); } void removeTroop(String cardId) { if (troops == null) troops = new ArrayList<>(); troops.removeIf(compressedTroop -> compressedTroop.getCard().getCardId().equalsIgnoreCase(cardId)); if (hero != null && hero.getCard().getCardId().equalsIgnoreCase(cardId)) hero = null; } public List getTroops() { return Collections.unmodifiableList(troops); } public void setTroops(List troops) { this.troops = troops; for (CompressedTroop troop : troops) { if (troop.getCard().getType() == CardType.HERO) { hero = troop; } } } public CompressedTroop getHero() { return hero; } public CompressedCard searchGraveyard(String cardId) { for (CompressedCard card : graveyard) { if (card.getCardId().equalsIgnoreCase(cardId)) { return card; } } return null; } public String getUserName() { return userName; } public int getCurrentMP() { return currentMP; } void setCurrentMP(int currentMP, int turnNumber) { this.currentMP = currentMP; } public List getHand() { return Collections.unmodifiableList(hand); } public List getGraveyard() { return Collections.unmodifiableList(graveyard); } public CompressedCard getNextCard() { return nextCard; } public int getPlayerNumber() { return playerNumber; } }package integration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static com.codeborne.selenide.Condition.exist; import static com.codeborne.selenide.Condition.visible; import static com.codeborne.selenide.Selenide.$; import static com.codeborne.selenide.WebDriverRunner.isHtmlUnit; import static org.assertj.core.api.Assumptions.assumeThat; class TransparencyAndOtherNonStandardVisibilityTest extends IntegrationTest { @BeforeEach void openTestPage() { assumeThat(isHtmlUnit()).as("opacity:0 is visible in HtmlUnit").isFalse(); openFile("page_with_transparent_elements.html"); } @Test void nosizeElementIsVisibleAndClickable() { $("#no-size-link").should(exist) .shouldBe(visible); $("#no-size-link").click(); $("#no-size-link").doubleClick(); $("#no-size-link").contextClick(); } @Test void transparentElementIsInvisibleButClickable() { $("#inv-link").should(exist).shouldNotBe(visible); $("#inv-link").click(); $("#inv-link").doubleClick(); $("#inv-link").contextClick(); } @Test void almostTransparentElementIsVisibleAndClickable() { $("#link").shouldBe(visible); $("#link").click(); $("#link").doubleClick(); $("#link").contextClick(); } @Test void transparentElementIsInvisibleButGetsInput() { $("#inv-input").should(exist).shouldNotBe(visible); $("#inv-input").setValue("abc"); $("#inv-input").clear(); $("#inv-input").pressEnter(); $("#inv-input").pressEscape(); $("#inv-input").pressTab(); } @Test void almostTransparentElementIsVisibleAndGetsInput() { $("#input").shouldBe(visible); $("#input").setValue("abc"); $("#input").clear(); $("#input").pressEnter(); $("#input").pressEscape(); $("#input").pressTab(); } } /* * Copyright (c) 2016 Orange. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Created by on 02/02/16. */ package com.orange.labs.sample; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.widget.Toast; import com.orange.labs.sample.cache.LruBitmapCache; import com.orange.labs.sample.fragment.FolderFragment; import com.orange.labs.sdk.OrangeCloudAPI; import com.orange.labs.sdk.OrangeListener; import com.orange.labs.sdk.exception.OrangeAPIException; import com.orange.labs.sdk.session.AuthSession; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, FolderFragment.OnFolderFragmentInteractionListener { /////////////////////////////////////////////////////////////////////////// // Your app-specific settings. // /////////////////////////////////////////////////////////////////////////// // // Replace this with your app key and secret assigned by Orange and // the redirect Uri. // Note: Obfuscation is good. // // https://developer.orange.com/apis/cloud-france/api-reference // final static private String APP_KEY = "your client app key"; final static private String APP_SECRET = "your client app secret"; final static private String APP_REDIRECT_URI = "your client redirect uri"; /////////////////////////////////////////////////////////////////////////// // End app-specific settings. // /////////////////////////////////////////////////////////////////////////// /** Instance to access to the cloud API */ private OrangeCloudAPI mApi; /** Stored in savedInstanceState to track an ongoing auth attempt, which * must include a locally-generated nonce in the response. */ private String mainStateNonce = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); /////////////////////////////////////////////////////////////////////////// // // We create a new AuthSession so that we can use the Orange Cloud API. // /////////////////////////////////////////////////////////////////////////// AuthSession session = new AuthSession(MainActivity.this, APP_KEY, APP_SECRET, APP_REDIRECT_URI); mApi = new OrangeCloudAPI<>(session); Log.v("MainActivity", "Orange Cloud SDK Version: " + mApi.SDK_VERSION); // An you can set a Image cache policy mApi.setImageCache(new LruBitmapCache()); /** Add scope for example cloudfullread * (see https://developer.orange.com/apis/cloud-france/api-reference) */ //mApi.addScope("cloudfullread"); // Start session session.startAuthentication(); } else { mainStateNonce = savedInstanceState.getString("mainStateNonce"); } } @Override protected void onResume() { super.onResume(); /////////////////////////////////////////////////////////////////////////// // The next part must be inserted in the onResume() method of the // activity from which session.startAuthentication() was called, so // that Orange authentication completes properly. /////////////////////////////////////////////////////////////////////////// final AuthSession session = mApi.getSession(); // need to be sure that is first loading! if (mainStateNonce == null) { session.checkAuthentication(new OrangeListener.Success() { @Override public void onResponse(String response) { // Have a valid session: mainStateNonce = "mainStateNonce"; // Load default fragment loadFragment(new FolderFragment(), false); } }, new OrangeListener.Error() { @Override public void onErrorResponse(OrangeAPIException error) { failure(error, true); } }); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { // Called when picture has been selected if (resultCode == RESULT_OK) { Uri uri = intent.getData(); // Check that currentFragment is a FolderFragment and get the current folder to upload on it. Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container); if (fragment instanceof FolderFragment) { UploadPicture upload = new UploadPicture(this, mApi, ((FolderFragment) fragment).getEntry(), uri); upload.execute(); } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString("mainStateNonce", mainStateNonce); } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { super.onBackPressed(); } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_folders) { // Load root getSupportActionBar().setTitle(R.string.nav_folders); onSelectFolder(null, ""); } else if (id == R.id.nav_freespace) { freespace(); } else if (id == R.id.nav_logout) { // Logout user and display authentication Activity. logout(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } /** * Load a fragment in MainActivity * @param fragment fragment to be loaded * @param addToBackStack true if it will be added in backstack */ private void loadFragment(Fragment fragment, boolean addToBackStack) { FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); fragmentTransaction.replace(R.id.fragment_container, fragment); if (addToBackStack) { fragmentTransaction.addToBackStack(null); } fragmentTransaction.commit(); } /** * Getter * @return instance of Orange Cloud Api */ public OrangeCloudAPI getOrangeCloudApi() { return mApi; } /** * Load a new folder fragment by passing identifier of folder to load. * @param identifier the unique id of folder */ @Override public void onSelectFolder(String identifier, String name) { FolderFragment fragment = new FolderFragment(); if (identifier != null) { Bundle bundle = new Bundle(); bundle.putString("FOLDER_ID", identifier); fragment.setArguments(bundle); } loadFragment(fragment, (identifier != null)); } /** * Method to display freespace */ public void freespace() { mApi.freespace(new OrangeListener.Success() { @Override public void onResponse(Long response) { String freespace = humanReadableByteCount(response, false); String msg = getApplicationContext().getString(R.string.available_freespace) + freespace; Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show(); } }, new OrangeListener.Error() { @Override public void onErrorResponse(OrangeAPIException error) { failure(error, false); } }); } /** * Called by Upload Picture to refresh data of fragment after an Upload. */ public void refreshData() { Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container); if (fragment instanceof FolderFragment) { ((FolderFragment) fragment).refreshData(); } } /** * Called when users clicks on logout Menu * Logout user and display authentication Activity. */ public void logout() { // Clean session AuthSession session = mApi.getSession(); mainStateNonce = null; mApi.unlink(); FolderFragment.breadcrumbs = new ArrayList<>(); session.startAuthentication(); } private String humanReadableByteCount(long bytes, boolean si) { int unit = si ? 1000 : 1024; if (bytes < unit) return bytes + " B"; int exp = (int) (Math.log(bytes) / Math.log(unit)); String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i"); return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre); } /** * Method called when an API error occurred * * @param error an OrangeAPIException * @param forceAuthentication if true, restart authentication */ public void failure(OrangeAPIException error, final boolean forceAuthentication) { error.printStackTrace(); // Display popup alert and retry connect ! AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this); alert.setTitle(R.string.error); String message = error.getMessage(); int id = getResources().getIdentifier(message, "string", getPackageName()); if (id != 0) { message = getString(id); } alert.setMessage(message); alert.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (forceAuthentication) { // For sample retry authentication if error mApi.getSession().startAuthentication(); } } }); alert.show(); } }package software.amazon.iotfleethub.application; import com.google.common.collect.ImmutableMap; import software.amazon.awssdk.core.SdkClient; import software.amazon.awssdk.services.iotfleethub.model.IoTFleetHubRequest; import software.amazon.awssdk.services.iotfleethub.model.DescribeApplicationRequest; import software.amazon.awssdk.services.iotfleethub.model.DescribeApplicationResponse; import software.amazon.awssdk.services.iotfleethub.model.ResourceNotFoundException; import software.amazon.awssdk.services.iotfleethub.model.TagResourceRequest; import software.amazon.awssdk.services.iotfleethub.model.UntagResourceRequest; import software.amazon.awssdk.services.iotfleethub.model.UpdateApplicationRequest; import software.amazon.awssdk.services.iotfleethub.model.UpdateApplicationResponse; import software.amazon.cloudformation.proxy.AmazonWebServicesClientProxy; import software.amazon.cloudformation.proxy.HandlerErrorCode; import software.amazon.cloudformation.proxy.Logger; import software.amazon.cloudformation.proxy.OperationStatus; import software.amazon.cloudformation.proxy.ProgressEvent; import software.amazon.cloudformation.proxy.ProxyClient; import software.amazon.cloudformation.proxy.ResourceHandlerRequest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collection; import java.util.List; import java.util.Map; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static software.amazon.iotfleethub.application.TestConstants.APPLICATION_ARN; import static software.amazon.iotfleethub.application.TestConstants.APPLICATION_CREATION_DATE; import static software.amazon.iotfleethub.application.TestConstants.APPLICATION_DESCRIPTION; import static software.amazon.iotfleethub.application.TestConstants.APPLICATION_DESCRIPTION_2; import static software.amazon.iotfleethub.application.TestConstants.APPLICATION_ID; import static software.amazon.iotfleethub.application.TestConstants.APPLICATION_ID_2; import static software.amazon.iotfleethub.application.TestConstants.APPLICATION_LAST_UPDATE_DATE; import static software.amazon.iotfleethub.application.TestConstants.APPLICATION_NAME; import static software.amazon.iotfleethub.application.TestConstants.APPLICATION_NAME_2; import static software.amazon.iotfleethub.application.TestConstants.APPLICATION_URL; import static software.amazon.iotfleethub.application.TestConstants.CLIENT_TOKEN; import static software.amazon.iotfleethub.application.TestConstants.ERROR_MESSAGE; import static software.amazon.iotfleethub.application.TestConstants.MODEL_TAG_MAP; import static software.amazon.iotfleethub.application.TestConstants.MODEL_TAG_MAP_2; import static software.amazon.iotfleethub.application.TestConstants.MODEL_TAGS; import static software.amazon.iotfleethub.application.TestConstants.MODEL_TAGS_2; import static software.amazon.iotfleethub.application.TestConstants.ROLE_ARN; import static software.amazon.iotfleethub.application.TestConstants.SSO_CLIENT_ID; @ExtendWith(MockitoExtension.class) public class UpdateHandlerTest { @Mock private AmazonWebServicesClientProxy proxy; @Mock private Logger logger; private AutoCloseable closeable; private UpdateHandler handler; @BeforeEach public void setup() { closeable = MockitoAnnotations.openMocks(this); handler = new UpdateHandler(); } @AfterEach public void tear_down() throws Exception { verifyNoMoreInteractions(proxy); closeable.close(); } @Test public void handleRequest_Simple_Success() { ResourceModel previousModel = ResourceModel.builder() .applicationId(APPLICATION_ID) .applicationName(APPLICATION_NAME) .applicationDescription(APPLICATION_DESCRIPTION) .tags(MODEL_TAGS_2) .build(); ResourceModel desiredModel = ResourceModel.builder() .applicationId(APPLICATION_ID) .applicationName(APPLICATION_NAME_2) .applicationDescription(APPLICATION_DESCRIPTION_2) .tags(MODEL_TAGS) .build(); ResourceHandlerRequest request = ResourceHandlerRequest.builder() .previousResourceState(previousModel) .desiredResourceState(desiredModel) .desiredResourceTags(MODEL_TAG_MAP) .clientRequestToken(CLIENT_TOKEN) .build(); // Mocking DescribeApp in UpdateHandler DescribeApplicationRequest expectedDescribeRequest = DescribeApplicationRequest.builder() .applicationId(APPLICATION_ID) .build(); DescribeApplicationResponse describeResponse = DescribeApplicationResponse.builder() .applicationId(APPLICATION_ID) .applicationArn(APPLICATION_ARN) .tags(MODEL_TAG_MAP_2) .build(); when(proxy.injectCredentialsAndInvokeV2(eq(expectedDescribeRequest), any())) .thenReturn(describeResponse); // Mocking UpdateApp in UpdateHandler UpdateApplicationRequest expectedUpdateRequest = UpdateApplicationRequest.builder() .applicationId(APPLICATION_ID) .applicationName(APPLICATION_NAME_2) .applicationDescription(APPLICATION_DESCRIPTION_2) .clientToken(CLIENT_TOKEN) .build(); UpdateApplicationResponse updateResponse = UpdateApplicationResponse.builder().build(); doReturn(updateResponse) .when(proxy) .injectCredentialsAndInvokeV2(eq(expectedUpdateRequest), any()); // Handle Update Request ProgressEvent response = handler.handleRequest(proxy, request, null, logger); ProgressEvent expectedResponse = ProgressEvent.builder() .resourceModel(desiredModel) .status(OperationStatus.SUCCESS) .callbackDelaySeconds(0) .build(); assertThat(response).isEqualTo(expectedResponse); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(IoTFleetHubRequest.class); // IoTFleetHubClient made 4 calls in this case: // describeApplication, updateApplication, tagResource, untagResource verify(proxy, times(4)).injectCredentialsAndInvokeV2(requestCaptor.capture(), any()); List submittedRequests = requestCaptor.getAllValues(); TagResourceRequest submittedTagRequest = (TagResourceRequest) submittedRequests.get(2); assertEquals(submittedTagRequest.tags(), MODEL_TAG_MAP); assertThat(submittedTagRequest.resourceArn()).isEqualTo(APPLICATION_ARN); UntagResourceRequest submittedUntagRequest = (UntagResourceRequest) submittedRequests.get(3); assertEquals(submittedUntagRequest.tagKeys().size(), 1); assertTrue(submittedUntagRequest.tagKeys().contains("resourceTagKey2")); assertThat(submittedUntagRequest.resourceArn()).isEqualTo(APPLICATION_ARN); } @Test public void updateTags_SameKeyDifferentValue_Success() { Map desiredTags = ImmutableMap.of("resourceTagKey", "differentTagValue"); ResourceHandlerRequest request = ResourceHandlerRequest.builder() .previousResourceState(ResourceModel.builder().build()) .desiredResourceState(ResourceModel.builder().build()) .desiredResourceTags(desiredTags) .build(); handler.updateTags(proxy, request, APPLICATION_ARN, MODEL_TAG_MAP, logger); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(IoTFleetHubRequest.class); // There should only be 1 call (we should only be updating one Tag, and no Tag removals) verify(proxy, times(1)).injectCredentialsAndInvokeV2(requestCaptor.capture(), any()); List submittedRequests = requestCaptor.getAllValues(); TagResourceRequest submittedTagRequest = (TagResourceRequest) submittedRequests.get(0); assertEquals(submittedTagRequest.tags(), desiredTags); } @Test public void updateTags_OnlyRemoveTag_Success() { ResourceHandlerRequest request = ResourceHandlerRequest.builder() .previousResourceState(ResourceModel.builder().build()) .desiredResourceState(ResourceModel.builder().build()) .build(); handler.updateTags(proxy, request, APPLICATION_ARN, MODEL_TAG_MAP, logger); ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(IoTFleetHubRequest.class); // There should only be 1 call (we should only be removing one Tag) verify(proxy, times(1)).injectCredentialsAndInvokeV2(requestCaptor.capture(), any()); List submittedRequests = requestCaptor.getAllValues(); UntagResourceRequest submittedUntagRequest = (UntagResourceRequest) submittedRequests.get(0); assertEquals(submittedUntagRequest.tagKeys().size(), 1); assertTrue(submittedUntagRequest.tagKeys().contains("resourceTagKey")); } @Test public void handleRequest_SettingReadOnlyFields_Failure() { ResourceModel previousModel = ResourceModel.builder() .applicationId(APPLICATION_ID) .applicationName(APPLICATION_NAME) .applicationDescription(APPLICATION_DESCRIPTION) .build(); ResourceModel desiredModel = ResourceModel.builder() .applicationId(APPLICATION_ID_2) .applicationArn(APPLICATION_ARN) .applicationName(APPLICATION_NAME) .applicationDescription(APPLICATION_DESCRIPTION) .build(); ResourceHandlerRequest request = ResourceHandlerRequest.builder() .previousResourceState(previousModel) .desiredResourceState(desiredModel) .clientRequestToken(CLIENT_TOKEN) .build(); ProgressEvent response = handler.handleRequest(proxy, request, null, logger); assertThat(response).isNotNull(); assertThat(response.getStatus()).isEqualTo(OperationStatus.FAILED); assertThat(response.getErrorCode()).isEqualTo(HandlerErrorCode.InvalidRequest); assertThat(response.getMessage()).isEqualTo("Can only update ApplicationName, ApplicationDescription, or Tags."); } @Test public void handleRequest_NoAppId_Failure() { ResourceModel desiredModel = ResourceModel.builder() .applicationName(APPLICATION_NAME_2) .applicationDescription(APPLICATION_DESCRIPTION_2) .build(); ResourceHandlerRequest request = ResourceHandlerRequest.builder() .desiredResourceState(desiredModel) .clientRequestToken(CLIENT_TOKEN) .build(); ProgressEvent response = handler.handleRequest(proxy, request, null, logger); assertThat(response).isNotNull(); assertThat(response.getStatus()).isEqualTo(OperationStatus.FAILED); assertThat(response.getErrorCode()).isEqualTo(HandlerErrorCode.NotFound); assertThat(response.getMessage()).isEqualTo("ApplicationId was not provided."); } @Test public void handleRequest_AppNotFound_Failure() { ResourceModel desiredModel = ResourceModel.builder() .applicationId(APPLICATION_ID) .applicationName(APPLICATION_NAME_2) .applicationDescription(APPLICATION_DESCRIPTION_2) .build(); ResourceHandlerRequest request = ResourceHandlerRequest.builder() .desiredResourceState(desiredModel) .clientRequestToken(CLIENT_TOKEN) .build(); when(proxy.injectCredentialsAndInvokeV2(any(), any())) .thenThrow(ResourceNotFoundException.builder().build()); ProgressEvent response = handler.handleRequest(proxy, request, null, logger); assertThat(response).isNotNull(); assertThat(response.getStatus()).isEqualTo(OperationStatus.FAILED); assertThat(response.getErrorCode()).isEqualTo(HandlerErrorCode.NotFound); assertThat(response.getMessage()).isNull(); } @Test public void handleRequest_NoClientRequestToken_Failure() { ResourceModel model = ResourceModel.builder() .applicationId(APPLICATION_ID) .applicationName(APPLICATION_NAME_2) .applicationDescription(APPLICATION_DESCRIPTION_2) .build(); ResourceHandlerRequest request = ResourceHandlerRequest.builder() .desiredResourceState(model) .clientRequestToken(null) .build(); ProgressEvent response = handler.handleRequest(proxy, request, null, logger); assertThat(response).isNotNull(); assertThat(response.getStatus()).isEqualTo(OperationStatus.FAILED); assertThat(response.getErrorCode()).isEqualTo(HandlerErrorCode.InvalidRequest); assertThat(response.getMessage()).isEqualTo("ClientToken was not provided."); } } 1-10 package com.securionpay.enums; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; public enum CardBrand { VISA("Visa"), AMERICAN_EXPRESS("American Express"), MASTERCARD("MasterCard"), MAESTRO("Maestro"), DISCOVER("Discover"), JCB("JCB"), DINERS_CLUB("Diners Club"), UNKNOWN("Unknown"), /** * Used when received value can't be mapped to this enumeration. */ UNRECOGNIZED("unrecognized"); private final String value; CardBrand(String value) { this.value = value; } @JsonCreator public static CardBrand fromValue(String value) { if (value == null) { return null; } for (CardBrand cardBrand : values()) { if (cardBrand.value.equalsIgnoreCase(value)) { return cardBrand; } } return UNRECOGNIZED; } @JsonValue public String getValue() { return value; } } XiXiSdk/src/main/java/com/xixi/sdk/utils/thread/LLThreadPool.java package com.xixi.sdk.utils.thread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class LLThreadPool { final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); private static LLThreadPool instance ; public static synchronized LLThreadPool getInstance() { if ( instance == null ) { instance = new LLThreadPool() ; } return instance ; } public void dispatchRunnable(Runnable r) { fixedThreadPool.execute(r); } } // SMSLib for Java v3 // A Java API library for sending and receiving SMS via a GSM modem // or other supported gateways. // Web Site: http://www.smslib.org // // Copyright (C) 2002-2008, , Athens/GREECE. // SMSLib is distributed under the terms of the Apache License version 2.0 // // 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.smslib; /** * Configuration/settings class. This class holds information about all the * parameters which affect SMSLib operation. */ public class Settings { /** * Specifies whether debug is enabled. */ public boolean DEBUG = false; /** * Specifies whether queue traffic should be included in the debug logging. */ public boolean DEBUG_QUEUE = false; /** * Specifies whether the serial port flashing is disabled or enabled. */ public boolean SERIAL_NOFLUSH = false; /** * Specifies whether the serial port will be polled or SMSLib will be * notified by port interrupts. */ public boolean SERIAL_POLLING = false; /** * Specifies the polling interval (milliseconds). */ public int SERIAL_POLLING_INTERVAL = 200; /** * Specifies the serial ports' timeout (milliseconds). */ public int SERIAL_TIMEOUT = 15000; /** * Specifies the serial ports' keep-alive interval (milliseconds). */ public int SERIAL_KEEPALIVE_INTERVAL = 60000; /** * Specifies the buffer size (bytes). */ public int SERIAL_BUFFER_SIZE = 16384; /** * Wait time before clearing the queues (milliseconds). */ public int SERIAL_CLEAR_WAIT = 1000; /** * Specifies whether hardware handshake should be enabled for outbound port * traffic. */ public boolean SERIAL_RTSCTS_OUT = false; /** * Specifies the interval for the awakening of the background sending queue * (milliseconds). */ public int QUEUE_INTERVAL = 1000; /** * Specifies the number of retries the background queue should give to an * outbound message befrore it classifies it as failed. */ public int QUEUE_RETRIES = 3; /** * Wait time for generic AT commands (milliseconds). */ public int AT_WAIT = 200; /** * Wait time after issuing a RESET command (milliseconds). */ public int AT_WAIT_AFTER_RESET = 10000; /** * Wait time to give the modem after entring COMMAND mode (milliseconds). */ public int AT_WAIT_CMD = 1100; /** * Wait time after issuing a SEND command (milliseconds). */ public int AT_WAIT_CGMS = 200; /** * Wait time before retrying the network status command (milliseconds). */ public int AT_WAIT_NETWORK = 5000; /** * Wait time after entering the PIN (milliseconds). */ public int AT_WAIT_SIMPIN = 5000; /** * Wait time before retrying a failed CNMI command (milliseconds). */ public int AT_WAIT_CNMI = 3000; /** * Number of retries for sending a message. */ public int OUTBOUND_RETRIES = 3; /** * Wait time between retries for sending a message (milliseconds). */ public int OUTBOUND_RETRY_WAIT = 3000; /** * Watchdog - SMSLib background monitoring thread interval (milliseconds). */ public int WATCHDOG_INTERVAL = 15000; /** * Mask or show the IMSI string. */ public boolean MASK_IMSI = true; public boolean DISABLE_CMTI = false; /** * Should all defined gateways start up concurrently? */ public boolean CONCURRENT_GATEWAY_START = true; Settings() { if (System.getProperty("smslib.debug") != null) this.DEBUG = true; if (System.getProperty("smslib.debug_queue") != null) { this.DEBUG = true; this.DEBUG_QUEUE = true; } if (System.getProperty("smslib.serial.noflush") != null) this.SERIAL_NOFLUSH = true; if (System.getProperty("smslib.serial.polling") != null) this.SERIAL_POLLING = true; if (System.getProperty("smslib.serial.pollinginterval") != null) this.SERIAL_POLLING_INTERVAL = Integer.parseInt(System.getProperty("smslib.serial.pollinginterval")); if (System.getProperty("smslib.serial.timeout") != null) this.SERIAL_TIMEOUT = Integer.parseInt(System.getProperty("smslib.serial.timeout")); if (System.getProperty("smslib.serial.keepalive") != null) this.SERIAL_KEEPALIVE_INTERVAL = Integer.parseInt(System.getProperty("smslib.serial.keepalive")); if (System.getProperty("smslib.serial.buffer") != null) this.SERIAL_BUFFER_SIZE = Integer.parseInt(System.getProperty("smslib.serial.buffer")); if (System.getProperty("smslib.serial.clearwait") != null) this.SERIAL_CLEAR_WAIT = Integer.parseInt(System.getProperty("smslib.serial.clearwait")); if (System.getProperty("smslib.queue.interval") != null) this.QUEUE_INTERVAL = Integer.parseInt(System.getProperty("smslib.queue.interval")); if (System.getProperty("smslib.queue.retries") != null) this.QUEUE_RETRIES = Integer.parseInt(System.getProperty("smslib.queue.retries")); if (System.getProperty("smslib.outbound.retries") != null) this.OUTBOUND_RETRIES = Integer.parseInt(System.getProperty("smslib.outbound.retries")); if (System.getProperty("smslib.outbound.retrywait") != null) this.OUTBOUND_RETRY_WAIT = Integer.parseInt(System.getProperty("smslib.outbound.retrywait")); if (System.getProperty("smslib.at.wait") != null) this.AT_WAIT = Integer.parseInt(System.getProperty("smslib.at.wait")); if (System.getProperty("smslib.at.resetwait") != null) this.AT_WAIT_AFTER_RESET = Integer.parseInt(System.getProperty("smslib.at.resetwait")); if (System.getProperty("smslib.at.cmdwait") != null) this.AT_WAIT_CMD = Integer.parseInt(System.getProperty("smslib.at.cmdwait")); if (System.getProperty("smslib.at.cmgswait") != null) this.AT_WAIT_CGMS = Integer.parseInt(System.getProperty("smslib.at.cmgswait")); if (System.getProperty("smslib.at.networkwait") != null) this.AT_WAIT_NETWORK = Integer.parseInt(System.getProperty("smslib.at.networkwait")); if (System.getProperty("smslib.at.simpinwait") != null) this.AT_WAIT_SIMPIN = Integer.parseInt(System.getProperty("smslib.at.simpinwait")); if (System.getProperty("smslib.at.cnmiwait") != null) this.AT_WAIT_CNMI = Integer.parseInt(System.getProperty("smslib.at.cnmiwait")); if (System.getProperty("smslib.watchdog") != null) this.WATCHDOG_INTERVAL = Integer.parseInt(System.getProperty("smslib.watchdog")); if (System.getProperty("smslib.disable.concurrent.gateway.startup") != null) this.CONCURRENT_GATEWAY_START = false; // Temporary Switch - disable inbound message unsolicited notifications (CMTI). if (System.getProperty("smslib.nocmti") != null) this.DISABLE_CMTI = true; } } package repositories; import domainModel.DomainObject; import exceptions.ApplicationException; import java.util.Collection; import java.util.Optional; import java.util.function.Predicate; public interface Repository { Optional tryGetFirst(Predicate p); Collection filter(Predicate p); Collection getAll(); void remove(T e); void save(T e) throws ApplicationException; } package de.pxlab.pxl.display; import de.pxlab.pxl.*; /** * Start a named clock. This starts a clock whose name is given as an * experimental parameter. The current time of this clock may be retrieved by * using Display object ReadClock with the same name. An unlimited number of * clocks may be started. * * @author * @version 0.2.0 * @see ReadClock */ public class StartClock extends Display { /** The name of the clock to be started. */ public ExPar Name = new ExPar(STRING, new ExParValue("Clock1"), "Name of the clock"); public StartClock() { setTitleAndTopic("Start a clock", PARAM_DSP | EXP); JustInTime.set(1); setVisible(false); Timer.set(new ExParValueConstant("de.pxlab.pxl.TimerCodes.NO_TIMER")); } protected int create() { return backgroundFieldIndex; } protected void computeGeometry() { RuntimeRegistry.put(Name.getString(), new Long(HiresClock.getTimeNanos())); } } /* * Copyright (C) 2012 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 android.content.pm; import android.os.Parcel; import android.os.Parcelable; import android.util.Base64; import java.util.Arrays; import java.util.jar.Attributes; /** * Represents the manifest digest for a package. This is suitable for comparison * of two packages to know whether the manifests are identical. * * @hide */ public class ManifestDigest implements Parcelable { /** The digest of the manifest in our preferred order. */ private final byte[] mDigest; /** Digest field names to look for in preferred order. */ private static final String[] DIGEST_TYPES = { "SHA1-Digest", "SHA-Digest", "MD5-Digest", }; /** What we print out first when toString() is called. */ private static final String TO_STRING_PREFIX = "ManifestDigest {mDigest="; ManifestDigest(byte[] digest) { mDigest = digest; } private ManifestDigest(Parcel source) { mDigest = source.createByteArray(); } static ManifestDigest fromAttributes(Attributes attributes) { if (attributes == null) { return null; } String encodedDigest = null; for (int i = 0; i < DIGEST_TYPES.length; i++) { final String value = attributes.getValue(DIGEST_TYPES[i]); if (value != null) { encodedDigest = value; break; } } if (encodedDigest == null) { return null; } final byte[] digest = Base64.decode(encodedDigest, Base64.DEFAULT); return new ManifestDigest(digest); } @Override public int describeContents() { return 0; } @Override public boolean equals(Object o) { if (!(o instanceof ManifestDigest)) { return false; } final ManifestDigest other = (ManifestDigest) o; return this == other || Arrays.equals(mDigest, other.mDigest); } @Override public int hashCode() { return Arrays.hashCode(mDigest); } @Override public String toString() { final StringBuilder sb = new StringBuilder(TO_STRING_PREFIX.length() + (mDigest.length * 3) + 1); sb.append(TO_STRING_PREFIX); final int N = mDigest.length; for (int i = 0; i < N; i++) { final byte b = mDigest[i]; IntegralToString.appendByteAsHex(sb, b, false); sb.append(','); } sb.append('}'); return sb.toString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeByteArray(mDigest); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public ManifestDigest createFromParcel(Parcel source) { return new ManifestDigest(source); } public ManifestDigest[] newArray(int size) { return new ManifestDigest[size]; } }; }package hr.vsite.hive.services.jetty.rest.v1.resources; import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.UUID; import javax.inject.Inject; import javax.ws.rs.BadRequestException; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import hr.vsite.hive.sensors.Sensor; import hr.vsite.hive.sensors.SensorManager; import hr.vsite.hive.services.jetty.rest.v1.jaxb.JAXBTick; import hr.vsite.hive.services.jetty.rest.v1.jaxb.JAXBValueTick; import hr.vsite.hive.ticks.Tick; import hr.vsite.hive.ticks.TickFilter; import hr.vsite.hive.ticks.TickManager; import hr.vsite.hive.ticks.ValueTick; import hr.vsite.hive.ticks.ValueTickFilter; @Path("tick") public class TickResource { @Inject public TickResource(TickManager tickManager, SensorManager sensorManager) { this.tickManager = tickManager; this.sensorManager = sensorManager; } @GET @Path("") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public List list( @QueryParam("createdAfter") Instant createdAfter, @QueryParam("createdBefore") Instant createdBefore, @QueryParam("receivedAfter") Instant receivedAfter, @QueryParam("receivedBefore") Instant receivedBefore, @QueryParam("metaOrdinalFrom") Integer metaOrdinalFrom, @QueryParam("metaOrdinalTo") Integer metaOrdinalTo, @QueryParam("sensorOrdinalFrom") Integer sensorOrdinalFrom, @QueryParam("sensorOrdinalTo") Integer sensorOrdinalTo, @QueryParam("sensor") Set sensors, @QueryParam("type") Set types, @DefaultValue("10") @QueryParam("count") int count, @DefaultValue("0") @QueryParam("offset") int offset ) { TickFilter filter = new TickFilter(); filter.setCreatedAfter(createdAfter); filter.setCreatedBefore(createdBefore); filter.setReceivedAfter(receivedAfter); filter.setReceivedBefore(receivedBefore); filter.setMetaOrdinalFrom(metaOrdinalFrom); filter.setMetaOrdinalTo(metaOrdinalTo); filter.setSensorOrdinalFrom(sensorOrdinalFrom); filter.setSensorOrdinalTo(sensorOrdinalTo); filter.setSensors(sensors != null && !sensors.isEmpty() ? sensors : null); filter.setTypes(types != null && !types.isEmpty() ? types : null); return JAXBTick.wrap(tickManager.list(filter, count, offset)); } @GET @Path("value") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public List listValue( @QueryParam("createdAfter") Instant createdAfter, @QueryParam("createdBefore") Instant createdBefore, @QueryParam("receivedAfter") Instant receivedAfter, @QueryParam("receivedBefore") Instant receivedBefore, @QueryParam("metaOrdinalFrom") Integer metaOrdinalFrom, @QueryParam("metaOrdinalTo") Integer metaOrdinalTo, @QueryParam("sensorOrdinalFrom") Integer sensorOrdinalFrom, @QueryParam("sensorOrdinalTo") Integer sensorOrdinalTo, @QueryParam("sensor") Set sensors, @QueryParam("valueFrom") Integer valueFrom, @QueryParam("valueTo") Integer valueTo, @DefaultValue("10") @QueryParam("count") int count, @DefaultValue("0") @QueryParam("offset") int offset ) { ValueTickFilter filter = new ValueTickFilter(); filter.setCreatedAfter(createdAfter); filter.setCreatedBefore(createdBefore); filter.setReceivedAfter(receivedAfter); filter.setReceivedBefore(receivedBefore); filter.setMetaOrdinalFrom(metaOrdinalFrom); filter.setMetaOrdinalTo(metaOrdinalTo); filter.setSensorOrdinalFrom(sensorOrdinalFrom); filter.setSensorOrdinalTo(sensorOrdinalTo); filter.setSensors(sensors != null && !sensors.isEmpty() ? sensors : null); filter.setTypes(Collections.singleton(Tick.Type.Value)); filter.setValueFrom(valueFrom); filter.setValueTo(valueTo); return JAXBValueTick.wrapValue(tickManager.list(filter, count, offset)); } @PUT @Path("value") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public JAXBValueTick createValue( @QueryParam("time") Instant createdTime, @QueryParam("ordinal") Integer sensorOrdinal, @QueryParam("id") UUID id, @QueryParam("device_id") String deviceId, @QueryParam("value") Integer value ) { Sensor sensor; if (id != null) { sensor = sensorManager.findById(id); if (sensor == null) throw new BadRequestException("Unknown sensor ID \"" + id + "\""); } else if (deviceId != null) { sensor = sensorManager.findByDeviceId(deviceId); if (sensor == null) { // first tick from new sensor, create it sensor = new Sensor(); sensor.setDeviceId(deviceId); sensorManager.create(sensor); } } else throw new BadRequestException("Missing (device) ID"); if (value == null) throw new BadRequestException("Missing value"); ValueTick tick = new ValueTick(); tick.setCreatedTime(createdTime); tick.setSensorOrdinal(sensorOrdinal); tick.setSensor(sensor); tick.setValue(value); tickManager.createValue(tick); return new JAXBValueTick(tick); } private final TickManager tickManager; private final SensorManager sensorManager; }0 package utils.tei; import utils.common.AbnormalProcessException; import xjc.teiAll.TEI; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.UnmarshalException; import javax.xml.bind.Unmarshaller; import java.io.File; import java.util.function.Function; public class TeiReader { TEI tei; Function treeFactory; public TeiReader(String file, Function treeFactory) throws AbnormalProcessException { this.tei = load(file); this.treeFactory = treeFactory; } public Metadata getMetadata() throws AbnormalProcessException { return Metadata.create(tei); } public ATeiTree getTeiTree() { return treeFactory.apply(tei); } public static TEI load(String xml) throws AbnormalProcessException { File file = new File(xml); try { JAXBContext jaxbContext = JAXBContext.newInstance(TEI.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); TEI tei = (TEI) jaxbUnmarshaller.unmarshal(file); return tei; } catch (UnmarshalException e) { throw new AbnormalProcessException(file.toString(), e); } catch (JAXBException e) { throw new AbnormalProcessException(file.toString(), e); } } } package model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import org.mongodb.morphia.annotations.Embedded; import java.io.Serializable; /** * Created by tito on 22/10/15. */ @Data @ToString @Embedded @AllArgsConstructor @NoArgsConstructor public class UserVO implements Serializable{ private String name; private String userId; } package io.opentracing.contrib.specialagent.jaeger; import java.io.File; import java.util.Properties; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.jaegertracing.internal.JaegerTracer; import io.opentracing.Tracer; import io.opentracing.contrib.specialagent.common.Configuration; import io.opentracing.contrib.specialagent.common.Utils; import static org.junit.Assert.assertTrue; public class JaegerTracerFactoryTest { final static String SERVICE_NAME_KEY = "JAEGER_SERVICE_NAME"; Tracer tracer; @Before public void beforeTest() { Properties systemProps = System.getProperties(); for (String propName: systemProps.stringPropertyNames()) { if (propName.startsWith(TracerParameters.JAEGER_PREFIX)) System.clearProperty(propName); } } @After public void afterTest() { if (tracer != null) { ((JaegerTracer)tracer).close(); tracer = null; } } @Test(expected=IllegalArgumentException.class) public void getTracer_noServiceName() { new JaegerTracerFactory().getTracer(); } @Test public void getTracer_serviceNameViaProperty() { System.setProperty(SERVICE_NAME_KEY, "MyService"); tracer = new JaegerTracerFactory().getTracer(); assertTrue(tracer instanceof JaegerTracer); } @Test public void getTracer_serviceNameViaConfigFile() throws Exception { Properties props = new Properties(); props.setProperty(JaegerTracerFactoryTest.SERVICE_NAME_KEY, "MyService"); File file = null; try { file = Utils.savePropertiesToTempFile(props); System.setProperty(Configuration.CONFIGURATION_FILE_KEY, file.getAbsolutePath()); tracer = new JaegerTracerFactory().getTracer(); assertTrue(tracer instanceof JaegerTracer); } finally { if (file != null) file.delete(); } } } java/webappSendSms/src/java/sendsms.java1-10 /* * 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. */ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.twilio.Twilio; import com.twilio.rest.api.v2010.account.Message; import com.twilio.type.PhoneNumber; /** * * @author dthurston */ @WebServlet(urlPatterns = {"/sendsms"}) public class sendsms extends HttpServlet { private static final String ACCOUNT_SID = System.getenv("ACCOUNT_SID"); private static final String AUTH_TOKEN = System.getenv("AUTH_TOKEN"); /** * Processes requests for both HTTP GET and POST * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println(""); out.println(""); out.println(""); out.println("Servlet sendsms"); out.println(""); out.println(""); out.println("

Servlet sendsms at " + request.getContextPath() + "

"); out.println("
"); Twilio.init(ACCOUNT_SID, AUTH_TOKEN); String fromPhoneNumber = System.getenv("PHONE_NUMBER2"); String toPhoneNumber = System.getenv("PHONE_NUMBER3"); String theMsg = "Send from Java Servlet"; Message message = Message.creator( new PhoneNumber(toPhoneNumber), new PhoneNumber(fromPhoneNumber), theMsg ).create(); // Immediately returned values: out.println("+ Message SID: " + message.getSid()); out.println("+ Status: " + message.getStatus()); out.println("+ from: " + message.getFrom()); out.println("+ to: " + message.getTo()); out.println("+ Message text: " + message.getBody()); out.println("
"); out.println(""); out.println(""); } } // /** * Handles the HTTP GET method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP POST method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// } fregaham/KiWi package ideator.action.evaluation; import java.util.LinkedList; public class Paragraph { private LinkedList criterias; private String title; private String user; private boolean rendered; public Paragraph(String title) { this.title = title; this.criterias = new LinkedList(); this.rendered = false; } public void add(Criteria q) { this.criterias.add(q); } public LinkedList getCriteria() { return this.criterias; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public void setUser(String user) { this.user = user; } public String getUser() { return user; } public boolean isEvaluated() { for( Criteria c : criterias ) { if( !c.isEvaluated() ) return false; } return true; } public void setRendered(boolean rendered) { this.rendered = rendered; } public boolean isRendered() { return rendered; } public String toXMLString() { StringBuffer b = new StringBuffer(); b.append(""); for( Criteria c : criterias ) { b.append(c.toXMLString()); } b.append(""); return b.toString(); } } package com.scorpius_enterprises.io.iqm; import com.scorpius_enterprises.log.Logger; /** * Created by rickm on 3/25/2017. */ public class Driver { public static void main(String[] args) { Logger.init(0); Logger.registerTag(IqmLoader.LOG_TAG); IqmLoader.loadModel("/test/test_arm.iqm"); } } src/test/java/com/deepoove/testpie/target/UserServiceImpl.java package com.deepoove.testpie.target; import java.util.List; import java.util.stream.Collectors; import java.util.stream.LongStream; public class UserServiceImpl implements UserService { // real data private static List users = LongStream.of(1590000, 1581111, 1360000) .mapToObj(phone -> new User(phone)).map(user -> { user.setName("Sayi"); return user; }).collect(Collectors.toList()); @Override public List findAll() { return users; } @Override public User find(long phone) { return users.stream().filter(user -> user.getPhone() == phone).findFirst().get(); } @Override public void add(User user) { if (null == user) throw new RuntimeException("null user"); User findUser = find(user.getPhone()); if (null != findUser) throw new RuntimeException("user is exist"); users.add(user); } @Override public void update(User user) { if (null == user) throw new RuntimeException("null user"); User findUser = find(user.getPhone()); if (null == findUser) throw new RuntimeException("user is not exist"); users.remove(findUser); users.add(user); } @Override public boolean delete(long phone) { User findUser = find(phone); if (null == findUser) throw new RuntimeException("user is not exist"); users.remove(findUser); return true; } } package com.xiangzi.config; import java.util.UUID; import javax.annotation.Resource; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.amqp.rabbit.support.CorrelationData; import org.springframework.stereotype.Component; @Component public class MqttMessageSender { @Resource(name = "mqttRabbitTemplate") private RabbitTemplate mqttRabbitTemplate; public void send(String topic, String message) { CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString()); System.out.println("消息id:" + correlationData.getId()); // 用RabbitMQ发送MQTT需将exchange配置为amq.topic // Messages published to MQTT topics use a topic exchange (amq.topic by default) internally. this.mqttRabbitTemplate.convertAndSend("amq.topic", topic, message, correlationData); } } /* * Copyright (c) 2020 Eclipse Krazo committers and contributors * * 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. * * SPDX-License-Identifier: Apache-2.0 */ package org.eclipse.krazo.core; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Defines an SPI which allows the client to unwrap a HTTP request or response * into a standard {@link javax.servlet.http.HttpServletRequest} or {@link javax.servlet.http.HttpServletResponse}. *

* This SPI is intended to be used in case a JAX-RS implementation uses its own wrapper classes for HTTP requests and responses. */ public interface HttpCommunicationUnwrapper { /** * Checks if the current implementation supports the unwrapping of the current object. * * @param obj the object to unwrap into some standard format * @return true, if this unwrapper supports the current object type, false if not */ boolean supports(final Object obj); /** * Unwraps a {@link javax.servlet.http.HttpServletRequest} from a custom wrapper into its original class. * * @param obj the object to unwrap * @param type the target type of the object * @return the unwrapped {@link javax.servlet.http.HttpServletRequest} */ HttpServletRequest unwrapRequest(final HttpServletRequest obj, final Class type); /** * Unwraps a {@link javax.servlet.http.HttpServletResponse} from a custom wrapper into its original class. * * @param obj the object to unwrap * @param type the target type of the object * @return the unwrapped {@link javax.servlet.http.HttpServletResponse} */ HttpServletResponse unwrapResponse(final HttpServletResponse obj, final Class type); } /* * Copyright 2014, Google 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: * * * 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 Google Inc. 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 * OWNER 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 io.grpc; import java.io.IOException; /** * An {@link java.io.InputStream} or alike whose total number of bytes that can be read is known * upfront. * *

Usually it's a {@link java.io.InputStream} that also implements this interface, in which case * {@link java.io.InputStream#available()} has a stronger semantic by returning an accurate number * instead of an estimation. */ public interface KnownLength { /** * Returns the total number of bytes that can be read (or skipped over) from this object until all * bytes have been read out. */ int available() throws IOException; } projects/core/src/main/java/com/opengamma/core/marketdatasnapshot/impl/ManageableSurfaceSnapshot.java /** * Copyright (C) 2009 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.core.marketdatasnapshot.impl; import java.util.Map; import java.util.Set; import org.joda.beans.Bean; import org.joda.beans.BeanBuilder; import org.joda.beans.BeanDefinition; import org.joda.beans.JodaBeanUtils; import org.joda.beans.MetaProperty; import org.joda.beans.Property; import org.joda.beans.PropertyDefinition; import org.joda.beans.impl.direct.DirectBeanBuilder; import org.joda.beans.impl.direct.DirectMetaBean; import org.joda.beans.impl.direct.DirectMetaProperty; import org.joda.beans.impl.direct.DirectMetaPropertyMap; import com.opengamma.core.marketdatasnapshot.SurfaceSnapshot; import com.opengamma.core.marketdatasnapshot.ValueSnapshot; import com.opengamma.util.tuple.Pair; /** * Mutable snapshot of curve data. */ @BeanDefinition public class ManageableSurfaceSnapshot implements Bean, SurfaceSnapshot { /** * The values. */ @PropertyDefinition(validate = "notNull", overrideGet = true) private Map, ValueSnapshot> _values; //------------------------- AUTOGENERATED START ------------------------- ///CLOVER:OFF /** * The meta-bean for {@code ManageableSurfaceSnapshot}. * @return the meta-bean, not null */ public static ManageableSurfaceSnapshot.Meta meta() { return ManageableSurfaceSnapshot.Meta.INSTANCE; } static { JodaBeanUtils.registerMetaBean(ManageableSurfaceSnapshot.Meta.INSTANCE); } @Override public ManageableSurfaceSnapshot.Meta metaBean() { return ManageableSurfaceSnapshot.Meta.INSTANCE; } @Override public Property property(String propertyName) { return metaBean().metaProperty(propertyName).createProperty(this); } @Override public Set propertyNames() { return metaBean().metaPropertyMap().keySet(); } //----------------------------------------------------------------------- /** * Gets the values. * @return the value of the property, not null */ @Override public Map, ValueSnapshot> getValues() { return _values; } /** * Sets the values. * @param values the new value of the property, not null */ public void setValues(Map, ValueSnapshot> values) { JodaBeanUtils.notNull(values, "values"); this._values = values; } /** * Gets the the {@code values} property. * @return the property, not null */ public final Property, ValueSnapshot>> values() { return metaBean().values().createProperty(this); } //----------------------------------------------------------------------- @Override public ManageableSurfaceSnapshot clone() { return JodaBeanUtils.cloneAlways(this); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { ManageableSurfaceSnapshot other = (ManageableSurfaceSnapshot) obj; return JodaBeanUtils.equal(getValues(), other.getValues()); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + JodaBeanUtils.hashCode(getValues()); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(64); buf.append("ManageableSurfaceSnapshot{"); int len = buf.length(); toString(buf); if (buf.length() > len) { buf.setLength(buf.length() - 2); } buf.append('}'); return buf.toString(); } protected void toString(StringBuilder buf) { buf.append("values").append('=').append(JodaBeanUtils.toString(getValues())).append(',').append(' '); } //----------------------------------------------------------------------- /** * The meta-bean for {@code ManageableSurfaceSnapshot}. */ public static class Meta extends DirectMetaBean { /** * The singleton instance of the meta-bean. */ static final Meta INSTANCE = new Meta(); /** * The meta-property for the {@code values} property. */ @SuppressWarnings({"unchecked", "rawtypes" }) private final MetaProperty, ValueSnapshot>> _values = DirectMetaProperty.ofReadWrite( this, "values", ManageableSurfaceSnapshot.class, (Class) Map.class); /** * The meta-properties. */ private final Map> _metaPropertyMap$ = new DirectMetaPropertyMap( this, null, "values"); /** * Restricted constructor. */ protected Meta() { } @Override protected MetaProperty metaPropertyGet(String propertyName) { switch (propertyName.hashCode()) { case -823812830: // values return _values; } return super.metaPropertyGet(propertyName); } @Override public BeanBuilder builder() { return new DirectBeanBuilder(new ManageableSurfaceSnapshot()); } @Override public Class beanType() { return ManageableSurfaceSnapshot.class; } @Override public Map> metaPropertyMap() { return _metaPropertyMap$; } //----------------------------------------------------------------------- /** * The meta-property for the {@code values} property. * @return the meta-property, not null */ public final MetaProperty, ValueSnapshot>> values() { return _values; } //----------------------------------------------------------------------- @Override protected Object propertyGet(Bean bean, String propertyName, boolean quiet) { switch (propertyName.hashCode()) { case -823812830: // values return ((ManageableSurfaceSnapshot) bean).getValues(); } return super.propertyGet(bean, propertyName, quiet); } @SuppressWarnings("unchecked") @Override protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) { switch (propertyName.hashCode()) { case -823812830: // values ((ManageableSurfaceSnapshot) bean).setValues((Map, ValueSnapshot>) newValue); return; } super.propertySet(bean, propertyName, newValue, quiet); } @Override protected void validate(Bean bean) { JodaBeanUtils.notNull(((ManageableSurfaceSnapshot) bean)._values, "values"); } } ///CLOVER:ON //-------------------------- AUTOGENERATED END -------------------------- } 100-1000 package com.dell.gumshoe.inspector.helper; import com.dell.gumshoe.ProbeManager; import com.dell.gumshoe.network.DatagramIODetailAdder; import com.dell.gumshoe.stats.IODetailAdder; import com.dell.gumshoe.stats.StatisticAdder; import com.dell.gumshoe.stats.ValueReporter; import com.dell.gumshoe.stats.ValueReporter.Listener; import javax.swing.JCheckBox; import javax.swing.JComponent; import java.text.ParseException; public class DatagramIOHelper extends IOHelper { private final JCheckBox accept = new JCheckBox("datagram IO", true); @Override public JComponent getSelectionComponent() { return accept; } @Override public boolean isSelected() { return accept.isSelected(); } @Override public StatisticAdder parse(String value) throws ParseException { return DatagramIODetailAdder.fromString(value); } @Override public void addListener(ProbeManager probe, Listener listener) { final ValueReporter reporter = probe.getDatagramIOReporter(); if(reporter!=null) { reporter.addListener(listener); } } @Override protected String getTargetName() { return "addresses"; } } /* * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. Crate 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. * * However, if you have executed another commercial license agreement * with Crate these terms will supersede the license and you may use the * software solely pursuant to the terms of the relevant commercial agreement. */ package io.crate.expression.operator.any; import io.crate.data.Input; import io.crate.expression.operator.LikeOperator; import io.crate.expression.operator.Operator; import io.crate.expression.operator.OperatorModule; import io.crate.metadata.BaseFunctionResolver; import io.crate.metadata.FunctionIdent; import io.crate.metadata.FunctionImplementation; import io.crate.metadata.FunctionInfo; import io.crate.metadata.TransactionContext; import io.crate.metadata.functions.params.FuncParams; import io.crate.metadata.functions.params.Param; import io.crate.types.ArrayType; import io.crate.types.DataType; import io.crate.types.DataTypes; import io.crate.types.ObjectType; import java.util.List; import java.util.function.BiPredicate; import java.util.regex.Pattern; import static com.google.common.base.Preconditions.checkArgument; import static io.crate.expression.operator.any.AnyOperators.collectionValueToIterable; public final class AnyLikeOperator extends Operator { public static final String LIKE = AnyOperator.OPERATOR_PREFIX + "like"; public static final String NOT_LIKE = AnyOperator.OPERATOR_PREFIX + "not_like"; private final FunctionInfo info; private final BiPredicate matches; public static void register(OperatorModule operatorModule) { operatorModule.registerDynamicOperatorFunction( LIKE, new AnyLikeResolver(LIKE, AnyLikeOperator::matches)); operatorModule.registerDynamicOperatorFunction( NOT_LIKE, new AnyLikeResolver(NOT_LIKE, ((BiPredicate) AnyLikeOperator::matches).negate())); } private static boolean matches(String expr, String pattern) { return Pattern.matches(LikeOperator.patternToRegex(pattern, LikeOperator.DEFAULT_ESCAPE, true), expr); } AnyLikeOperator(FunctionInfo info, BiPredicate matches) { this.info = info; this.matches = matches; } @Override public FunctionInfo info() { return info; } private Boolean doEvaluate(Object left, Iterable rightIterable) { String pattern = (String) left; boolean hasNull = false; for (Object elem : rightIterable) { if (elem == null) { hasNull = true; continue; } assert elem instanceof String : "elem must be a String"; String elemValue = (String) elem; if (matches.test(elemValue, pattern)) { return true; } } return hasNull ? null : false; } @Override public Boolean evaluate(TransactionContext txnCtx, Input... args) { Object value = args[0].value(); Object collectionReference = args[1].value(); if (collectionReference == null || value == null) { return null; } return doEvaluate(value, collectionValueToIterable(collectionReference)); } private static class AnyLikeResolver extends BaseFunctionResolver { private final String name; private final BiPredicate matches; AnyLikeResolver(String name, BiPredicate matches) { super(FuncParams.builder( Param.ANY, Param.of( new ArrayType<>(DataTypes.UNDEFINED)) .withInnerType(Param.ANY)) .build()); this.name = name; this.matches = matches; } @Override public FunctionImplementation getForTypes(List dataTypes) throws IllegalArgumentException { DataType innerType = ((ArrayType) dataTypes.get(1)).innerType(); checkArgument(innerType.equals(dataTypes.get(0)), "The inner type of the array/set passed to ANY must match its left expression"); checkArgument(innerType.id() != ObjectType.ID, "ANY on object arrays is not supported"); return new AnyLikeOperator( new FunctionInfo(new FunctionIdent(name, dataTypes), DataTypes.BOOLEAN), matches ); } } } src/com/inubit/research/gui/plugins/NodeViewPlugin.java /** * * Process Editor - inubit Workbench Plugin Package * * (C) 2009, 2010 inubit AG * (C) 2014 the authors * */ package com.inubit.research.gui.plugins; import com.inubit.research.gui.Workbench; import com.inubit.research.gui.WorkbenchEditorListener; import java.awt.Component; import java.awt.event.ActionEvent; import javax.swing.JMenuItem; import net.frapu.code.visualization.ProcessEdge; import net.frapu.code.visualization.ProcessEditor; import net.frapu.code.visualization.ProcessModelListener; import net.frapu.code.visualization.ProcessNode; import net.frapu.code.visualization.ProcessObject; /** * * @author frank */ public class NodeViewPlugin extends WorkbenchPlugin implements WorkbenchEditorListener, ProcessModelListener { private NodeViewPluginDialog dialog; private ProcessEditor currentEditor; private Workbench workbench; public NodeViewPlugin(Workbench workbench) { super(workbench); this.workbench=workbench; } private void init() { dialog = new NodeViewPluginDialog(workbench, false); workbench.addWorkbenchEditorListener(this); selectedProcessEditorChanged(workbench.getSelectedProcessEditor()); } @Override public Component getMenuEntry() { JMenuItem menuItem = new JMenuItem("Node view..."); menuItem.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Show dialog if (dialog==null) init(); dialog.setVisible(true); } }); return menuItem; } @Override public void newEditorCreated(ProcessEditor editor) { // } @Override public void selectedProcessEditorChanged(ProcessEditor editor) { if (editor==null) return; if (currentEditor!=null) currentEditor.getModel().removeListener(this); editor.getModel().addListener(this); dialog.setEditor(editor); currentEditor = editor; } @Override public void processNodeAdded(ProcessNode newNode) { dialog.setEditor(currentEditor); } @Override public void processNodeRemoved(ProcessNode remNode) { dialog.setEditor(currentEditor); } @Override public void processEdgeAdded(ProcessEdge edge) { dialog.setEditor(currentEditor); } @Override public void processEdgeRemoved(ProcessEdge edge) { dialog.setEditor(currentEditor); } @Override public void processObjectPropertyChange(ProcessObject obj, String name, String oldValue, String newValue) { dialog.setEditor(currentEditor); } } protol/src/main/java/redis/util/BytesKeyZSet.java10-100 package redis.util; import java.util.Collection; import java.util.TreeSet; public class BytesKeyZSet extends TreeSet { private redis.util.BytesKeyObjectMap map; public BytesKeyZSet() {} public BytesKeyZSet(redis.util.BytesKeyZSet destination) { super(destination); } @Override public boolean add(ZSetEntry zSetEntry) { getMap().put(zSetEntry.getKey(), zSetEntry); return super.add(zSetEntry); } private redis.util.BytesKeyObjectMap getMap() { if (map == null) { map = new BytesKeyObjectMap(); } return map; } @Override public boolean remove(Object o) { if (o instanceof ZSetEntry) { ZSetEntry removed = getMap().remove(((ZSetEntry) o).getKey()); return removed != null && super.remove(removed); } return super.remove(o); } public ZSetEntry get(BytesKey key) { return getMap().get(key); } public ZSetEntry get(byte[] key) { return getMap().get(new BytesKey(key)); } @Override public boolean addAll(Collection c) { boolean changed = super.addAll(c); for (ZSetEntry zSetEntry : c) { getMap().put(zSetEntry.getKey(), zSetEntry); } return changed; } } package com.sintef_energy.ubisolar.database.energy; import android.content.ContentValues; import android.database.Cursor; import android.os.Parcel; import android.os.Parcelable; import android.provider.BaseColumns; import com.sintef_energy.ubisolar.model.Device; /** * Created by perok on 2/11/14. * * Based on the backend Device model, this class gives it all of Androids * powerful functionality; parcelable, ContentProvider and constructor helper methods. */ public class DeviceModel extends Device implements Parcelable{ private static final String TAG = DeviceModel.class.getName(); /* Column definitions*/ public static interface DeviceEntry extends BaseColumns { public static final String TABLE_NAME = "device"; public static final String COLUMN_USER_ID = "userId"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_DESCRIPTION = "description"; public static final String COLUMN_CATEGORY = "category"; public static final String COLUMN_IS_DELETED = "is_deleted"; public static final String COLUMN_LAST_UPDATED = "lastUpdated"; } public static final String[] projection = new String[]{ DeviceEntry._ID, DeviceEntry.COLUMN_USER_ID, DeviceEntry.COLUMN_NAME, DeviceEntry.COLUMN_DESCRIPTION, DeviceEntry.COLUMN_CATEGORY, DeviceEntry.COLUMN_IS_DELETED, DeviceEntry.COLUMN_LAST_UPDATED }; /* SQL Statements*/ private static final String TEXT_TYPE = " TEXT"; private static final String INTEGER_TYPE = " INTEGER"; private static final String COMMA_SEP = ","; public static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + DeviceEntry.TABLE_NAME + " (" + DeviceEntry._ID + INTEGER_TYPE + COMMA_SEP + DeviceEntry.COLUMN_USER_ID + INTEGER_TYPE + COMMA_SEP + DeviceEntry.COLUMN_NAME + TEXT_TYPE + COMMA_SEP + DeviceEntry.COLUMN_DESCRIPTION + TEXT_TYPE + COMMA_SEP + DeviceEntry.COLUMN_CATEGORY + INTEGER_TYPE + COMMA_SEP + DeviceEntry.COLUMN_IS_DELETED + INTEGER_TYPE + COMMA_SEP + DeviceEntry.COLUMN_LAST_UPDATED + INTEGER_TYPE + COMMA_SEP + " PRIMARY KEY(" + DeviceEntry._ID + COMMA_SEP + DeviceEntry.COLUMN_USER_ID + ")" + " )"; public static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + DeviceEntry.TABLE_NAME; /* POJO */ private int _id = 0; private int _user_id = 1; private int _name = 2; private int _description = 3; private int _category = 4; private int _is_deleted = 5; private int _lastUpdated = 6; /** * Create CalendarEventModel with default values. All relation ID's are '-1' */ public DeviceModel() { super(); setId(-1); setUserId(-1); setName(""); setDescription(""); setCategory(-1); setDeleted(false); setLastUpdated(-1); } /* Parcable */ public DeviceModel(Parcel in) { readFromParcel(in); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public DeviceModel createFromParcel(Parcel in) { return new DeviceModel(in); } public DeviceModel[] newArray(int size) { return new DeviceModel[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel out, int flags) { out.writeLong(getId()); out.writeLong(getUserId()); out.writeString(getName()); out.writeString(getDescription()); out.writeInt(getCategory()); out.writeInt((isDeleted() ? 1 : 0)); out.writeLong(getLastUpdated()); } private void readFromParcel(Parcel in) { setId(in.readLong()); setUserId(in.readLong()); setName(in.readString()); setDescription(in.readString()); setCategory(in.readInt()); setDeleted(in.readInt() != 0); setLastUpdated(in.readLong()); } /** * Get all the values in ContentValues class. * @return */ public ContentValues getContentValues(){ ContentValues values = new ContentValues(); values.put(DeviceEntry._ID, getId()); values.put(DeviceEntry.COLUMN_USER_ID, getUserId()); values.put(DeviceEntry.COLUMN_NAME, getName()); values.put(DeviceEntry.COLUMN_DESCRIPTION, getDescription()); values.put(DeviceEntry.COLUMN_CATEGORY, getCategory()); values.put(DeviceEntry.COLUMN_IS_DELETED, (isDeleted() ? 1 : 0)); values.put(DeviceEntry.COLUMN_LAST_UPDATED, getLastUpdated()); return values; } /** * Create DeviceModel from cursor * @param cursor */ public DeviceModel(Cursor cursor) { setId(cursor.getLong(_id)); setUserId(cursor.getLong(_user_id)); setName(cursor.getString(_name)); setDescription(cursor.getString(_description)); setCategory(cursor.getInt(_category)); setDeleted(cursor.getInt(_is_deleted) != 0); setLastUpdated(cursor.getLong(_lastUpdated)); } public DeviceModel(long id, long user_id, String name, String description, int category) { super(id, user_id, name, description, category, false, -1); } public DeviceModel(long id, long user_id, String name, String description, int category, boolean deleted, long last) { super(id, user_id, name, description, category, deleted, last); } /** * An ugly hack do allow jackson to serialize DeviceModel. * @return new Device */ public Device getSerializeableDevice(){ return new Device(getId(), getUserId(), getName(), getDescription(), getCategory(), isDeleted(), getLastUpdated()); } @Override public String toString(){ String info = "DeviceModel:"; info += "\n\tID: " + getId(); info += "\n\tUser ID: " + getUserId(); info += "\n\tName: " + getName(); info += "\n\tDescription: " + getDescription(); info += "\n\tCategory: " + getCategory(); info += "\n\tdeleted: " + isDeleted(); info += "\n\tlastUpdated: " + getLastUpdated(); return info; } } package com.asaon.html.dsl; import com.asaon.html.HtmlInterpreter; public class Span extends HtmlDsl> { private final PARENT parent; public Span(HtmlInterpreter interpreter, PARENT parent) { super(interpreter); this.parent = parent; } public PARENT _span() { interpreter.onTagEnd("span"); return parent; } } JoneZeroX/jarboot package com.mz.jarboot.controller; import com.mz.jarboot.common.ResponseForList; import com.mz.jarboot.common.ResponseSimple; import com.mz.jarboot.entity.RoleInfo; import com.mz.jarboot.service.RoleService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; @Api(tags="角色管理") @RequestMapping(value = "/api/jarboot-role", method ={RequestMethod.GET, RequestMethod.POST}) @Controller public class RoleController { @Autowired private RoleService roleService; @ApiOperation(value = "分配角色", httpMethod = "PUT") @PutMapping(value="/addRole") @ResponseBody public ResponseSimple addRole(String role, String username) { roleService.addRole(role, username); return new ResponseSimple(); } @ApiOperation(value = "搜索角色", httpMethod = "GET") @GetMapping("/search") @ResponseBody public List searchRoles(@RequestParam String role) { return roleService.findRolesLikeRoleName(role); } @ApiOperation(value = "删除角色", httpMethod = "DELETE") @DeleteMapping("deleteRole") @ResponseBody public ResponseSimple deleteRole(@RequestParam String role, @RequestParam(name = "username", defaultValue = StringUtils.EMPTY) String username) { if (StringUtils.isBlank(username)) { roleService.deleteRole(role); } else { roleService.deleteRole(role, username); } return new ResponseSimple(); } @ApiOperation(value = "获取角色列表", httpMethod = "GET") @GetMapping(value="/getRoles") @ResponseBody public ResponseForList getRoles(Integer pageNo, Integer pageSize) { return roleService.getRoles(pageNo, pageSize); } } /* * * 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.hadoop.hbase.io.hfile; import static org.apache.hadoop.hbase.io.compress.Compression.Algorithm.GZ; import static org.apache.hadoop.hbase.io.compress.Compression.Algorithm.NONE; import static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseTestingUtility; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.Tag; import org.apache.hadoop.hbase.fs.HFileSystem; import org.apache.hadoop.hbase.io.compress.Compression; import org.apache.hadoop.hbase.io.compress.Compression.Algorithm; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.ChecksumType; import org.apache.hadoop.hbase.util.ClassSize; import org.apache.hadoop.io.WritableUtils; import org.apache.hadoop.io.compress.Compressor; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.mockito.Mockito; @Category(MediumTests.class) @RunWith(Parameterized.class) public class TestHFileBlock { // change this value to activate more logs private static final boolean detailedLogging = false; private static final boolean[] BOOLEAN_VALUES = new boolean[] { false, true }; private static final Log LOG = LogFactory.getLog(TestHFileBlock.class); static final Compression.Algorithm[] COMPRESSION_ALGORITHMS = { NONE, GZ }; private static final int NUM_TEST_BLOCKS = 1000; private static final int NUM_READER_THREADS = 26; // Used to generate KeyValues private static int NUM_KEYVALUES = 50; private static int FIELD_LENGTH = 10; private static float CHANCE_TO_REPEAT = 0.6f; private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility(); private FileSystem fs; private final boolean includesMemstoreTS; private final boolean includesTag; public TestHFileBlock(boolean includesMemstoreTS, boolean includesTag) { this.includesMemstoreTS = includesMemstoreTS; this.includesTag = includesTag; } @Parameters public static Collection parameters() { return HBaseTestingUtility.MEMSTORETS_TAGS_PARAMETRIZED; } @Before public void setUp() throws IOException { fs = HFileSystem.get(TEST_UTIL.getConfiguration()); } static void writeTestBlockContents(DataOutputStream dos) throws IOException { // This compresses really well. for (int i = 0; i < 1000; ++i) dos.writeInt(i / 100); } static int writeTestKeyValues(HFileBlock.Writer hbw, int seed, boolean includesMemstoreTS, boolean useTag) throws IOException { List keyValues = new ArrayList(); Random randomizer = new Random(42l + seed); // just any fixed number // generate keyValues for (int i = 0; i < NUM_KEYVALUES; ++i) { byte[] row; long timestamp; byte[] family; byte[] qualifier; byte[] value; // generate it or repeat, it should compress well if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) { row = keyValues.get(randomizer.nextInt(keyValues.size())).getRow(); } else { row = new byte[FIELD_LENGTH]; randomizer.nextBytes(row); } if (0 == i) { family = new byte[FIELD_LENGTH]; randomizer.nextBytes(family); } else { family = keyValues.get(0).getFamily(); } if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) { qualifier = keyValues.get( randomizer.nextInt(keyValues.size())).getQualifier(); } else { qualifier = new byte[FIELD_LENGTH]; randomizer.nextBytes(qualifier); } if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) { value = keyValues.get(randomizer.nextInt(keyValues.size())).getValue(); } else { value = new byte[FIELD_LENGTH]; randomizer.nextBytes(value); } if (0 < i && randomizer.nextFloat() < CHANCE_TO_REPEAT) { timestamp = keyValues.get( randomizer.nextInt(keyValues.size())).getTimestamp(); } else { timestamp = randomizer.nextLong(); } if (!useTag) { keyValues.add(new KeyValue(row, family, qualifier, timestamp, value)); } else { keyValues.add(new KeyValue(row, family, qualifier, timestamp, value, new Tag[] { new Tag( (byte) 1, Bytes.toBytes("myTagVal")) })); } } // sort it and write to stream int totalSize = 0; Collections.sort(keyValues, KeyValue.COMPARATOR); for (KeyValue kv : keyValues) { totalSize += kv.getLength(); if (includesMemstoreTS) { long memstoreTS = randomizer.nextLong(); kv.setSequenceId(memstoreTS); totalSize += WritableUtils.getVIntSize(memstoreTS); } hbw.write(kv); } return totalSize; } public byte[] createTestV1Block(Compression.Algorithm algo) throws IOException { Compressor compressor = algo.getCompressor(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream os = algo.createCompressionStream(baos, compressor, 0); DataOutputStream dos = new DataOutputStream(os); BlockType.META.write(dos); // Let's make this a meta block. writeTestBlockContents(dos); dos.flush(); algo.returnCompressor(compressor); return baos.toByteArray(); } static HFileBlock.Writer createTestV2Block(Compression.Algorithm algo, boolean includesMemstoreTS, boolean includesTag) throws IOException { final BlockType blockType = BlockType.DATA; HFileContext meta = new HFileContextBuilder() .withCompression(algo) .withIncludesMvcc(includesMemstoreTS) .withIncludesTags(includesTag) .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM) .build(); HFileBlock.Writer hbw = new HFileBlock.Writer(null, meta); DataOutputStream dos = hbw.startWriting(blockType); writeTestBlockContents(dos); dos.flush(); hbw.ensureBlockReady(); assertEquals(1000 * 4, hbw.getUncompressedSizeWithoutHeader()); hbw.release(); return hbw; } public String createTestBlockStr(Compression.Algorithm algo, int correctLength, boolean useTag) throws IOException { HFileBlock.Writer hbw = createTestV2Block(algo, includesMemstoreTS, useTag); byte[] testV2Block = hbw.getHeaderAndDataForTest(); int osOffset = HConstants.HFILEBLOCK_HEADER_SIZE + 9; if (testV2Block.length == correctLength) { // Force-set the "OS" field of the gzip header to 3 (Unix) to avoid // variations across operating systems. // See http://www.gzip.org/zlib/rfc-gzip.html for gzip format. // We only make this change when the compressed block length matches. // Otherwise, there are obviously other inconsistencies. testV2Block[osOffset] = 3; } return Bytes.toStringBinary(testV2Block); } @Test public void testNoCompression() throws IOException { CacheConfig cacheConf = Mockito.mock(CacheConfig.class); Mockito.when(cacheConf.isBlockCacheEnabled()).thenReturn(false); HFileBlock block = createTestV2Block(NONE, includesMemstoreTS, false).getBlockForCaching(cacheConf); assertEquals(4000, block.getUncompressedSizeWithoutHeader()); assertEquals(4004, block.getOnDiskSizeWithoutHeader()); assertTrue(block.isUnpacked()); } @Test public void testGzipCompression() throws IOException { final String correctTestBlockStr = "DATABLK*\\x00\\x00\\x00>\\x00\\x00\\x0F\\xA0\\xFF\\xFF\\xFF\\xFF" + "\\xFF\\xFF\\xFF\\xFF" + "\\x01\\x00\\x00@\\x00\\x00\\x00\\x00[" // gzip-compressed block: http://www.gzip.org/zlib/rfc-gzip.html + "\\x1F\\x8B" // gzip magic signature + "\\x08" // Compression method: 8 = "deflate" + "\\x00" // Flags + "\\x00\\x00\\x00\\x00" // mtime + "\\x00" // XFL (extra flags) // OS (0 = FAT filesystems, 3 = Unix). However, this field // sometimes gets set to 0 on Linux and Mac, so we reset it to 3. // This appears to be a difference caused by the availability // (and use) of the native GZ codec. + "\\x03" + "\\xED\\xC3\\xC1\\x11\\x00 \\x08\\xC00DD\\xDD\\x7Fa" + "\\xD6\\xE8\\xA3\\xB9K\\x84`\\x96Q\\xD3\\xA8\\xDB\\xA8e\\xD4c" + "\\xD46\\xEA5\\xEA3\\xEA7\\xE7\\x00LI\\x5Cs\\xA0\\x0F\\x00\\x00" + "\\x00\\x00\\x00\\x00"; // 4 byte checksum (ignored) final int correctGzipBlockLength = 95; final String testBlockStr = createTestBlockStr(GZ, correctGzipBlockLength, false); // We ignore the block checksum because createTestBlockStr can change the // gzip header after the block is produced assertEquals(correctTestBlockStr.substring(0, correctGzipBlockLength - 4), testBlockStr.substring(0, correctGzipBlockLength - 4)); } @Test public void testReaderV2() throws IOException { testReaderV2Internals(); } protected void testReaderV2Internals() throws IOException { if(includesTag) { TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3); } for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) { for (boolean pread : new boolean[] { false, true }) { LOG.info("testReaderV2: Compression algorithm: " + algo + ", pread=" + pread); Path path = new Path(TEST_UTIL.getDataTestDir(), "blocks_v2_" + algo); FSDataOutputStream os = fs.create(path); HFileContext meta = new HFileContextBuilder() .withCompression(algo) .withIncludesMvcc(includesMemstoreTS) .withIncludesTags(includesTag) .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM) .build(); HFileBlock.Writer hbw = new HFileBlock.Writer(null, meta); long totalSize = 0; for (int blockId = 0; blockId < 2; ++blockId) { DataOutputStream dos = hbw.startWriting(BlockType.DATA); for (int i = 0; i < 1234; ++i) dos.writeInt(i); hbw.writeHeaderAndData(os); totalSize += hbw.getOnDiskSizeWithHeader(); } os.close(); FSDataInputStream is = fs.open(path); meta = new HFileContextBuilder() .withHBaseCheckSum(true) .withIncludesMvcc(includesMemstoreTS) .withIncludesTags(includesTag) .withCompression(algo).build(); HFileBlock.FSReader hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta); HFileBlock b = hbr.readBlockData(0, -1, -1, pread); is.close(); assertEquals(0, HFile.getChecksumFailuresCount()); b.sanityCheck(); assertEquals(4936, b.getUncompressedSizeWithoutHeader()); assertEquals(algo == GZ ? 2173 : 4936, b.getOnDiskSizeWithoutHeader() - b.totalChecksumBytes()); HFileBlock expected = b; if (algo == GZ) { is = fs.open(path); hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta); b = hbr.readBlockData(0, 2173 + HConstants.HFILEBLOCK_HEADER_SIZE + b.totalChecksumBytes(), -1, pread); assertEquals(expected, b); int wrongCompressedSize = 2172; try { b = hbr.readBlockData(0, wrongCompressedSize + HConstants.HFILEBLOCK_HEADER_SIZE, -1, pread); fail("Exception expected"); } catch (IOException ex) { String expectedPrefix = "On-disk size without header provided is " + wrongCompressedSize + ", but block header contains " + b.getOnDiskSizeWithoutHeader() + "."; assertTrue("Invalid exception message: '" + ex.getMessage() + "'.\nMessage is expected to start with: '" + expectedPrefix + "'", ex.getMessage().startsWith(expectedPrefix)); } is.close(); } } } } /** * Test encoding/decoding data blocks. * @throws IOException a bug or a problem with temporary files. */ @Test public void testDataBlockEncoding() throws IOException { testInternals(); } private void testInternals() throws IOException { final int numBlocks = 5; if(includesTag) { TEST_UTIL.getConfiguration().setInt("hfile.format.version", 3); } for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) { for (boolean pread : new boolean[] { false, true }) { for (DataBlockEncoding encoding : DataBlockEncoding.values()) { Path path = new Path(TEST_UTIL.getDataTestDir(), "blocks_v2_" + algo + "_" + encoding.toString()); FSDataOutputStream os = fs.create(path); HFileDataBlockEncoder dataBlockEncoder = (encoding != DataBlockEncoding.NONE) ? new HFileDataBlockEncoderImpl(encoding) : NoOpDataBlockEncoder.INSTANCE; HFileContext meta = new HFileContextBuilder() .withCompression(algo) .withIncludesMvcc(includesMemstoreTS) .withIncludesTags(includesTag) .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM) .build(); HFileBlock.Writer hbw = new HFileBlock.Writer(dataBlockEncoder, meta); long totalSize = 0; final List encodedSizes = new ArrayList(); final List encodedBlocks = new ArrayList(); for (int blockId = 0; blockId < numBlocks; ++blockId) { hbw.startWriting(BlockType.DATA); writeTestKeyValues(hbw, blockId, includesMemstoreTS, includesTag); hbw.writeHeaderAndData(os); int headerLen = HConstants.HFILEBLOCK_HEADER_SIZE; byte[] encodedResultWithHeader = hbw.getUncompressedBufferWithHeader().array(); final int encodedSize = encodedResultWithHeader.length - headerLen; if (encoding != DataBlockEncoding.NONE) { // We need to account for the two-byte encoding algorithm ID that // comes after the 24-byte block header but before encoded KVs. headerLen += DataBlockEncoding.ID_SIZE; } byte[] encodedDataSection = new byte[encodedResultWithHeader.length - headerLen]; System.arraycopy(encodedResultWithHeader, headerLen, encodedDataSection, 0, encodedDataSection.length); final ByteBuffer encodedBuf = ByteBuffer.wrap(encodedDataSection); encodedSizes.add(encodedSize); encodedBlocks.add(encodedBuf); totalSize += hbw.getOnDiskSizeWithHeader(); } os.close(); FSDataInputStream is = fs.open(path); meta = new HFileContextBuilder() .withHBaseCheckSum(true) .withCompression(algo) .withIncludesMvcc(includesMemstoreTS) .withIncludesTags(includesTag) .build(); HFileBlock.FSReaderImpl hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta); hbr.setDataBlockEncoder(dataBlockEncoder); hbr.setIncludesMemstoreTS(includesMemstoreTS); HFileBlock blockFromHFile, blockUnpacked; int pos = 0; for (int blockId = 0; blockId < numBlocks; ++blockId) { blockFromHFile = hbr.readBlockData(pos, -1, -1, pread); assertEquals(0, HFile.getChecksumFailuresCount()); blockFromHFile.sanityCheck(); pos += blockFromHFile.getOnDiskSizeWithHeader(); assertEquals((int) encodedSizes.get(blockId), blockFromHFile.getUncompressedSizeWithoutHeader()); assertEquals(meta.isCompressedOrEncrypted(), !blockFromHFile.isUnpacked()); long packedHeapsize = blockFromHFile.heapSize(); blockUnpacked = blockFromHFile.unpack(meta, hbr); assertTrue(blockUnpacked.isUnpacked()); if (meta.isCompressedOrEncrypted()) { LOG.info("packedHeapsize=" + packedHeapsize + ", unpackedHeadsize=" + blockUnpacked .heapSize()); assertFalse(packedHeapsize == blockUnpacked.heapSize()); assertTrue("Packed heapSize should be < unpacked heapSize", packedHeapsize < blockUnpacked.heapSize()); } ByteBuffer actualBuffer = blockUnpacked.getBufferWithoutHeader(); if (encoding != DataBlockEncoding.NONE) { // We expect a two-byte big-endian encoding id. assertEquals( "Unexpected first byte with " + buildMessageDetails(algo, encoding, pread), Long.toHexString(0), Long.toHexString(actualBuffer.get(0))); assertEquals( "Unexpected second byte with " + buildMessageDetails(algo, encoding, pread), Long.toHexString(encoding.getId()), Long.toHexString(actualBuffer.get(1))); actualBuffer.position(2); actualBuffer = actualBuffer.slice(); } ByteBuffer expectedBuffer = encodedBlocks.get(blockId); expectedBuffer.rewind(); // test if content matches, produce nice message assertBuffersEqual(expectedBuffer, actualBuffer, algo, encoding, pread); // test serialized blocks for (boolean reuseBuffer : new boolean[] { false, true }) { ByteBuffer serialized = ByteBuffer.allocate(blockFromHFile.getSerializedLength()); blockFromHFile.serialize(serialized); HFileBlock deserialized = (HFileBlock) blockFromHFile.getDeserializer().deserialize(serialized, reuseBuffer); assertEquals( "Serialization did not preserve block state. reuseBuffer=" + reuseBuffer, blockFromHFile, deserialized); // intentional reference comparison if (blockFromHFile != blockUnpacked) { assertEquals("Deserializaed block cannot be unpacked correctly.", blockUnpacked, deserialized.unpack(meta, hbr)); } } } is.close(); } } } } static String buildMessageDetails(Algorithm compression, DataBlockEncoding encoding, boolean pread) { return String.format("compression %s, encoding %s, pread %s", compression, encoding, pread); } static void assertBuffersEqual(ByteBuffer expectedBuffer, ByteBuffer actualBuffer, Compression.Algorithm compression, DataBlockEncoding encoding, boolean pread) { if (!actualBuffer.equals(expectedBuffer)) { int prefix = 0; int minLimit = Math.min(expectedBuffer.limit(), actualBuffer.limit()); while (prefix < minLimit && expectedBuffer.get(prefix) == actualBuffer.get(prefix)) { prefix++; } fail(String.format( "Content mismatch for %s, commonPrefix %d, expected %s, got %s", buildMessageDetails(compression, encoding, pread), prefix, nextBytesToStr(expectedBuffer, prefix), nextBytesToStr(actualBuffer, prefix))); } } /** * Convert a few next bytes in the given buffer at the given position to * string. Used for error messages. */ private static String nextBytesToStr(ByteBuffer buf, int pos) { int maxBytes = buf.limit() - pos; int numBytes = Math.min(16, maxBytes); return Bytes.toStringBinary(buf.array(), buf.arrayOffset() + pos, numBytes) + (numBytes < maxBytes ? "..." : ""); } @Test public void testPreviousOffset() throws IOException { testPreviousOffsetInternals(); } protected void testPreviousOffsetInternals() throws IOException { // TODO: parameterize these nested loops. for (Compression.Algorithm algo : COMPRESSION_ALGORITHMS) { for (boolean pread : BOOLEAN_VALUES) { for (boolean cacheOnWrite : BOOLEAN_VALUES) { Random rand = defaultRandom(); LOG.info("testPreviousOffset:Compression algorithm: " + algo + ", pread=" + pread + ", cacheOnWrite=" + cacheOnWrite); Path path = new Path(TEST_UTIL.getDataTestDir(), "prev_offset"); List expectedOffsets = new ArrayList(); List expectedPrevOffsets = new ArrayList(); List expectedTypes = new ArrayList(); List expectedContents = cacheOnWrite ? new ArrayList() : null; long totalSize = writeBlocks(rand, algo, path, expectedOffsets, expectedPrevOffsets, expectedTypes, expectedContents); FSDataInputStream is = fs.open(path); HFileContext meta = new HFileContextBuilder() .withHBaseCheckSum(true) .withIncludesMvcc(includesMemstoreTS) .withIncludesTags(includesTag) .withCompression(algo).build(); HFileBlock.FSReader hbr = new HFileBlock.FSReaderImpl(is, totalSize, meta); long curOffset = 0; for (int i = 0; i < NUM_TEST_BLOCKS; ++i) { if (!pread) { assertEquals(is.getPos(), curOffset + (i == 0 ? 0 : HConstants.HFILEBLOCK_HEADER_SIZE)); } assertEquals(expectedOffsets.get(i).longValue(), curOffset); if (detailedLogging) { LOG.info("Reading block #" + i + " at offset " + curOffset); } HFileBlock b = hbr.readBlockData(curOffset, -1, -1, pread); if (detailedLogging) { LOG.info("Block #" + i + ": " + b); } assertEquals("Invalid block #" + i + "'s type:", expectedTypes.get(i), b.getBlockType()); assertEquals("Invalid previous block offset for block " + i + " of " + "type " + b.getBlockType() + ":", (long) expectedPrevOffsets.get(i), b.getPrevBlockOffset()); b.sanityCheck(); assertEquals(curOffset, b.getOffset()); // Now re-load this block knowing the on-disk size. This tests a // different branch in the loader. HFileBlock b2 = hbr.readBlockData(curOffset, b.getOnDiskSizeWithHeader(), -1, pread); b2.sanityCheck(); assertEquals(b.getBlockType(), b2.getBlockType()); assertEquals(b.getOnDiskSizeWithoutHeader(), b2.getOnDiskSizeWithoutHeader()); assertEquals(b.getOnDiskSizeWithHeader(), b2.getOnDiskSizeWithHeader()); assertEquals(b.getUncompressedSizeWithoutHeader(), b2.getUncompressedSizeWithoutHeader()); assertEquals(b.getPrevBlockOffset(), b2.getPrevBlockOffset()); assertEquals(curOffset, b2.getOffset()); assertEquals(b.getBytesPerChecksum(), b2.getBytesPerChecksum()); assertEquals(b.getOnDiskDataSizeWithHeader(), b2.getOnDiskDataSizeWithHeader()); assertEquals(0, HFile.getChecksumFailuresCount()); curOffset += b.getOnDiskSizeWithHeader(); if (cacheOnWrite) { // NOTE: cache-on-write testing doesn't actually involve a BlockCache. It simply // verifies that the unpacked value read back off disk matches the unpacked value // generated before writing to disk. b = b.unpack(meta, hbr); // b's buffer has header + data + checksum while // expectedContents have header + data only ByteBuffer bufRead = b.getBufferWithHeader(); ByteBuffer bufExpected = expectedContents.get(i); boolean bytesAreCorrect = Bytes.compareTo(bufRead.array(), bufRead.arrayOffset(), bufRead.limit() - b.totalChecksumBytes(), bufExpected.array(), bufExpected.arrayOffset(), bufExpected.limit()) == 0; String wrongBytesMsg = ""; if (!bytesAreCorrect) { // Optimization: only construct an error message in case we // will need it. wrongBytesMsg = "Expected bytes in block #" + i + " (algo=" + algo + ", pread=" + pread + ", cacheOnWrite=" + cacheOnWrite + "):\n"; wrongBytesMsg += Bytes.toStringBinary(bufExpected.array(), bufExpected.arrayOffset(), Math.min(32 + 10, bufExpected.limit())) + ", actual:\n" + Bytes.toStringBinary(bufRead.array(), bufRead.arrayOffset(), Math.min(32 + 10, bufRead.limit())); if (detailedLogging) { LOG.warn("expected header" + HFileBlock.toStringHeader(bufExpected) + "\nfound header" + HFileBlock.toStringHeader(bufRead)); LOG.warn("bufread offset " + bufRead.arrayOffset() + " limit " + bufRead.limit() + " expected offset " + bufExpected.arrayOffset() + " limit " + bufExpected.limit()); LOG.warn(wrongBytesMsg); } } assertTrue(wrongBytesMsg, bytesAreCorrect); } } assertEquals(curOffset, fs.getFileStatus(path).getLen()); is.close(); } } } } private Random defaultRandom() { return new Random(189237); } private class BlockReaderThread implements Callable { private final String clientId; private final HFileBlock.FSReader hbr; private final List offsets; private final List types; private final long fileSize; public BlockReaderThread(String clientId, HFileBlock.FSReader hbr, List offsets, List types, long fileSize) { this.clientId = clientId; this.offsets = offsets; this.hbr = hbr; this.types = types; this.fileSize = fileSize; } @Override public Boolean call() throws Exception { Random rand = new Random(clientId.hashCode()); long endTime = System.currentTimeMillis() + 10000; int numBlocksRead = 0; int numPositionalRead = 0; int numWithOnDiskSize = 0; while (System.currentTimeMillis() < endTime) { int blockId = rand.nextInt(NUM_TEST_BLOCKS); long offset = offsets.get(blockId); boolean pread = rand.nextBoolean(); boolean withOnDiskSize = rand.nextBoolean(); long expectedSize = (blockId == NUM_TEST_BLOCKS - 1 ? fileSize : offsets.get(blockId + 1)) - offset; HFileBlock b; try { long onDiskSizeArg = withOnDiskSize ? expectedSize : -1; b = hbr.readBlockData(offset, onDiskSizeArg, -1, pread); } catch (IOException ex) { LOG.error("Error in client " + clientId + " trying to read block at " + offset + ", pread=" + pread + ", withOnDiskSize=" + withOnDiskSize, ex); return false; } assertEquals(types.get(blockId), b.getBlockType()); assertEquals(expectedSize, b.getOnDiskSizeWithHeader()); assertEquals(offset, b.getOffset()); ++numBlocksRead; if (pread) ++numPositionalRead; if (withOnDiskSize) ++numWithOnDiskSize; } LOG.info("Client " + clientId + " successfully read " + numBlocksRead + " blocks (with pread: " + numPositionalRead + ", with onDiskSize " + "specified: " + numWithOnDiskSize + ")"); return true; } } @Test public void testConcurrentReading() throws Exception { testConcurrentReadingInternals(); } protected void testConcurrentReadingInternals() throws IOException, InterruptedException, ExecutionException { for (Compression.Algorithm compressAlgo : COMPRESSION_ALGORITHMS) { Path path = new Path(TEST_UTIL.getDataTestDir(), "concurrent_reading"); Random rand = defaultRandom(); List offsets = new ArrayList(); List types = new ArrayList(); writeBlocks(rand, compressAlgo, path, offsets, null, types, null); FSDataInputStream is = fs.open(path); long fileSize = fs.getFileStatus(path).getLen(); HFileContext meta = new HFileContextBuilder() .withHBaseCheckSum(true) .withIncludesMvcc(includesMemstoreTS) .withIncludesTags(includesTag) .withCompression(compressAlgo) .build(); HFileBlock.FSReader hbr = new HFileBlock.FSReaderImpl(is, fileSize, meta); Executor exec = Executors.newFixedThreadPool(NUM_READER_THREADS); ExecutorCompletionService ecs = new ExecutorCompletionService(exec); for (int i = 0; i < NUM_READER_THREADS; ++i) { ecs.submit(new BlockReaderThread("reader_" + (char) ('A' + i), hbr, offsets, types, fileSize)); } for (int i = 0; i < NUM_READER_THREADS; ++i) { Future result = ecs.take(); assertTrue(result.get()); if (detailedLogging) { LOG.info(String.valueOf(i + 1) + " reader threads finished successfully (algo=" + compressAlgo + ")"); } } is.close(); } } private long writeBlocks(Random rand, Compression.Algorithm compressAlgo, Path path, List expectedOffsets, List expectedPrevOffsets, List expectedTypes, List expectedContents ) throws IOException { boolean cacheOnWrite = expectedContents != null; FSDataOutputStream os = fs.create(path); HFileContext meta = new HFileContextBuilder() .withHBaseCheckSum(true) .withIncludesMvcc(includesMemstoreTS) .withIncludesTags(includesTag) .withCompression(compressAlgo) .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM) .build(); HFileBlock.Writer hbw = new HFileBlock.Writer(null, meta); Map prevOffsetByType = new HashMap(); long totalSize = 0; for (int i = 0; i < NUM_TEST_BLOCKS; ++i) { long pos = os.getPos(); int blockTypeOrdinal = rand.nextInt(BlockType.values().length); if (blockTypeOrdinal == BlockType.ENCODED_DATA.ordinal()) { blockTypeOrdinal = BlockType.DATA.ordinal(); } BlockType bt = BlockType.values()[blockTypeOrdinal]; DataOutputStream dos = hbw.startWriting(bt); int size = rand.nextInt(500); for (int j = 0; j < size; ++j) { // This might compress well. dos.writeShort(i + 1); dos.writeInt(j + 1); } if (expectedOffsets != null) expectedOffsets.add(os.getPos()); if (expectedPrevOffsets != null) { Long prevOffset = prevOffsetByType.get(bt); expectedPrevOffsets.add(prevOffset != null ? prevOffset : -1); prevOffsetByType.put(bt, os.getPos()); } expectedTypes.add(bt); hbw.writeHeaderAndData(os); totalSize += hbw.getOnDiskSizeWithHeader(); if (cacheOnWrite) expectedContents.add(hbw.getUncompressedBufferWithHeader()); if (detailedLogging) { LOG.info("Written block #" + i + " of type " + bt + ", uncompressed size " + hbw.getUncompressedSizeWithoutHeader() + ", packed size " + hbw.getOnDiskSizeWithoutHeader() + " at offset " + pos); } } os.close(); LOG.info("Created a temporary file at " + path + ", " + fs.getFileStatus(path).getLen() + " byte, compression=" + compressAlgo); return totalSize; } @Test public void testBlockHeapSize() { testBlockHeapSizeInternals(); } protected void testBlockHeapSizeInternals() { if (ClassSize.is32BitJVM()) { assertTrue(HFileBlock.BYTE_BUFFER_HEAP_SIZE == 64); } else { assertTrue(HFileBlock.BYTE_BUFFER_HEAP_SIZE == 80); } for (int size : new int[] { 100, 256, 12345 }) { byte[] byteArr = new byte[HConstants.HFILEBLOCK_HEADER_SIZE + size]; ByteBuffer buf = ByteBuffer.wrap(byteArr, 0, size); HFileContext meta = new HFileContextBuilder() .withIncludesMvcc(includesMemstoreTS) .withIncludesTags(includesTag) .withHBaseCheckSum(false) .withCompression(Algorithm.NONE) .withBytesPerCheckSum(HFile.DEFAULT_BYTES_PER_CHECKSUM) .withChecksumType(ChecksumType.NULL).build(); HFileBlock block = new HFileBlock(BlockType.DATA, size, size, -1, buf, HFileBlock.FILL_HEADER, -1, 0, meta); long byteBufferExpectedSize = ClassSize.align(ClassSize.estimateBase(buf.getClass(), true) + HConstants.HFILEBLOCK_HEADER_SIZE + size); long hfileMetaSize = ClassSize.align(ClassSize.estimateBase(HFileContext.class, true)); long hfileBlockExpectedSize = ClassSize.align(ClassSize.estimateBase(HFileBlock.class, true)); long expected = hfileBlockExpectedSize + byteBufferExpectedSize + hfileMetaSize; assertEquals("Block data size: " + size + ", byte buffer expected " + "size: " + byteBufferExpectedSize + ", HFileBlock class expected " + "size: " + hfileBlockExpectedSize + ";", expected, block.heapSize()); } } } ldap/extras/codec/src/test/java/org/apache/directory/api/ldap/extras/controls/ad/AdDirSyncRequestControlTest.java10-100 /* * 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 * * https://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.directory.api.ldap.extras.controls.ad; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import java.nio.ByteBuffer; import org.apache.directory.api.asn1.DecoderException; import org.apache.directory.api.asn1.EncoderException; import org.apache.directory.api.asn1.util.Asn1Buffer; import org.apache.directory.api.ldap.codec.api.LdapApiService; import org.apache.directory.api.ldap.codec.osgi.DefaultLdapCodecService; import org.apache.directory.api.ldap.extras.controls.ad_impl.AdDirSyncRequestFactory; import org.apache.directory.api.util.Strings; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; /** * * TestCase for AdDirSyncRequestControlCodec . * * @author Apache Directory Project */ @Execution( ExecutionMode.CONCURRENT) public class AdDirSyncRequestControlTest { private static LdapApiService codec; @BeforeAll public static void init() { codec = new DefaultLdapCodecService(); codec.registerRequestControl( new AdDirSyncRequestFactory( codec ) ); } @Test public void testAdDirSyncRequestControl() throws DecoderException, EncoderException { ByteBuffer bb = ByteBuffer.allocate( 0x0E ); bb.put( new byte[] { 0x30, 0x0C, 0x02, 0x01, 0x01, // parentsFirst 0x02, 0x01, 0x00, // maxAttributeCount (no limit) 0x04, 0x04, 'x', 'k', 'c', 'd' // the cookie } ); bb.flip(); AdDirSyncRequestFactory factory = ( AdDirSyncRequestFactory ) codec.getRequestControlFactories(). get( AdDirSyncRequest.OID ); AdDirSyncRequest adDirSyncRequest = factory.newControl(); factory.decodeValue( adDirSyncRequest, bb.array() ); assertEquals( 1, adDirSyncRequest.getParentsFirst() ); assertEquals( 0, adDirSyncRequest.getMaxAttributeCount() ); assertEquals( "xkcd", Strings.utf8ToString( adDirSyncRequest.getCookie() ) ); // Check the reverse encoding Asn1Buffer asn1Buffer = new Asn1Buffer(); factory.encodeValue( asn1Buffer, adDirSyncRequest ); assertArrayEquals( bb.array(), asn1Buffer.getBytes().array() ); } @Test public void testAdDirSyncControlNoCookie() throws DecoderException, EncoderException { ByteBuffer bb = ByteBuffer.allocate( 0x0A ); bb.put( new byte[] { 0x30, 0x08, 0x02, 0x01, 0x01, // parentsFirst 0x02, 0x01, 0x00, // maxAttributeCount (no limit) 0x04, 0x00 // the cookie } ); bb.flip(); AdDirSyncRequestFactory factory = ( AdDirSyncRequestFactory ) codec.getRequestControlFactories(). get( AdDirSyncRequest.OID ); AdDirSyncRequest adDirSyncRequest = factory.newControl(); factory.decodeValue( adDirSyncRequest, bb.array() ); assertEquals( 1, adDirSyncRequest.getParentsFirst() ); assertEquals( 0, adDirSyncRequest.getMaxAttributeCount() ); assertEquals( "", Strings.utf8ToString( adDirSyncRequest.getCookie() ) ); // Check the reverse encoding Asn1Buffer asn1Buffer = new Asn1Buffer(); factory.encodeValue( asn1Buffer, adDirSyncRequest ); assertArrayEquals( bb.array(), asn1Buffer.getBytes().array() ); } @Test public void testAdDirSyncControlAbsentCookie() throws DecoderException { ByteBuffer bb = ByteBuffer.allocate( 0x08 ); bb.put( new byte[] { 0x30, 0x06, 0x02, 0x01, 0x00, // parentsFirst 0x02, 0x01, 0x00 // maxAttributeCount (no limit) } ); bb.flip(); AdDirSyncRequestFactory factory = ( AdDirSyncRequestFactory ) codec.getRequestControlFactories(). get( AdDirSyncRequest.OID ); AdDirSyncRequest adDirSyncRequest = factory.newControl(); assertThrows( DecoderException.class, ( ) -> { factory.decodeValue( adDirSyncRequest, bb.array() ); } ); } @Test public void testAdDirSyncControlAbsentParentFirst() throws DecoderException { ByteBuffer bb = ByteBuffer.allocate( 0x07 ); bb.put( new byte[] { 0x30, 0x05, 0x02, 0x01, 0x00, // maxAttributeCount (no limit) 0x04, 0x00 // cookie } ); bb.flip(); AdDirSyncRequestFactory factory = ( AdDirSyncRequestFactory ) codec.getRequestControlFactories(). get( AdDirSyncRequest.OID ); AdDirSyncRequest adDirSyncRequest = factory.newControl(); assertThrows( DecoderException.class, ( ) -> { factory.decodeValue( adDirSyncRequest, bb.array() ); } ); } @Test public void testAdDirSyncControlEmpty() throws DecoderException { ByteBuffer bb = ByteBuffer.allocate( 0x02 ); bb.put( new byte[] { 0x30, 0x00, } ); bb.flip(); AdDirSyncRequestFactory factory = ( AdDirSyncRequestFactory ) codec.getRequestControlFactories(). get( AdDirSyncRequest.OID ); AdDirSyncRequest adDirSyncRequest = factory.newControl(); assertThrows( DecoderException.class, ( ) -> { factory.decodeValue( adDirSyncRequest, bb.array() ); } ); } } package prbm73; public class Solution { /** * no use of extra space, but cannot solve matrix with negative elements. * WA. */ public void setZeroes(int[][] matrix) { int m = matrix.length; if (m == 0) { return; } int n = matrix[0].length; if (n == 0) { return; } for (int i = 1; i < m; i++) { if (matrix[i][0] < 0) { continue; } for (int j = 1; j < n; j++) { if (matrix[i][j] == 0) { if (matrix[i][0] == 0) { matrix[i][0] = -2; } else { matrix[i][0] = -1; } if (matrix[0][j] == 0) { matrix[0][j] = -2; } else { matrix[0][j] = -1; } } } } for (int i = 1; i < m; i++) { if (matrix[i][0] <= 0) { for (int j = 1; j < n; j++) { matrix[i][j] = 0; } } } for (int j = 1; j < n; j++) { if (matrix[0][j] <= 0) { for (int i = 1; i < m; i++) { matrix[i][j] = 0; } } } boolean b1 = false; for (int i = 0; i < m; i++) { if (matrix[i][0] == 0 || matrix[i][0] == -2) { b1 = true; } } boolean b2 = false; for (int j = 0; j < n; j++) { if (matrix[0][j] == 0 || matrix[0][j] == -2) { b2 = true; } } for (int i = 0; i < m; i++) { if (b1 || matrix[i][0] < 0) { matrix[i][0] = 0; } } for (int j = 0; j < n; j++) { if (b2 || matrix[0][j] < 0) { matrix[0][j] = 0; } } } public static void main(String[] args) { Solution s = new Solution(); int[][] m1 = new int[][] { { 1, 2, 0 }, { 1, 0, 1 }, { 4, 5, 6 } }; int[][] m2 = new int[][] { { 1, 0 } }; int[][] m3 = new int[][] { { 0, 1 } }; int[][] m4 = new int[][] { { 1 }, { 0 } }; s.setZeroes(m1); s.setZeroes(m2); s.setZeroes(m3); s.setZeroes(m4); System.out.println(m1); } }JarvisAPI/gdx-lml package com.github.czyzby.websocket.serialization.impl; import com.badlogic.gdx.utils.IntMap; import com.badlogic.gdx.utils.ObjectIntMap; import com.github.czyzby.websocket.serialization.SerializationException; import com.github.czyzby.websocket.serialization.Transferable; /** Uses {@link Serializer} and {@link Deserializer} to handle serialization from objects to byte arrays and vice versa. * Expects that all packets implement {@link Transferable} interface. Before using this serializer, all expected packets * should be registered with {@link #register(Transferable)} method. * *

* This serializer is not thread-safe. When used in multi-threaded environment, synchronization or using thread locals * is required. * * @author MJ * @see #register(Transferable) * @see #setPacketIdSize(Size) */ public class ManualSerializer extends AbstractBinarySerializer { protected static final int UNKNOWN = -1; private final Serializer serializer; private final Deserializer deserializer; /** Packet class mapped to class ID. */ private final ObjectIntMap> typesToIds = new ObjectIntMap>(); /** Class ID mapped to mock-up packet. */ private final IntMap> idsToPackets = new IntMap>(); private Size packetIdSize = Size.BYTE; private int id; private boolean ignoreDeserializationErrors; public ManualSerializer() { this(new Serializer(), new Deserializer()); } /** @param serializer used to serialize packets to byte arrays. * @param deserializer used to create packets from byte arrays. */ public ManualSerializer(final Serializer serializer, final Deserializer deserializer) { this.serializer = serializer; this.deserializer = deserializer; } /** @param packet a mock up packet instance. Will be registered as one of the handled packets. Note that packets * HAVE to be registered in the same order both on the client and on the server, as registration order * determines packet type ID. Unregistered packets cannot be (de)serialized, so this method should be * called for all expected packets before using the web socket. */ public void register(final Transferable packet) { final int classId = id++; typesToIds.put(packet.getClass(), classId); idsToPackets.put(classId, packet); } @Override public byte[] serialize(final Object object) { try { serializer.reset(); final int classId = typesToIds.get(object.getClass(), UNKNOWN); if (classId == UNKNOWN) { throw new SerializationException("Unable to serialize unregistered type: " + object.getClass()); } serializer.serializeInt(classId, packetIdSize); serializer.serializeTransferable((Transferable) object); return serializer.serialize(); } catch (final SerializationException exception) { throw exception; } catch (final Exception exception) { throw new SerializationException("Unable to serialize: " + object, exception); } } @Override public Object deserialize(final byte[] data) { deserializer.setSerializedData(data); final int packetId = deserializer.deserializeInt(packetIdSize); final Transferable mockUpPacket = idsToPackets.get(packetId); if (mockUpPacket == null) { if (!ignoreDeserializationErrors) { throw new SerializationException("Unexpected packet class ID: " + packetId + ". Has server and client registered the same packets in the same order?"); } return null; } return deserializer.deserializeTransferable(mockUpPacket); } /** @return {@link Serializer} instance used to convert {@link Transferable} objects to byte arrays. */ public Serializer getSerializer() { return serializer; } /** @return {@link Deserializer} instance used to convert byte arrays to {@link Transferable} objects. */ public Deserializer getDeserializer() { return deserializer; } /** @param packetIdSize determines how many bytes will be used to serialize packet type. Defaults to * {@link Size#BYTE}, which uses a single byte to serialize packet ID - this allows to use up to * {@link Byte#MAX_VALUE} different packets. If you have more packets in your application, adjust this * value. */ public void setPacketIdSize(final Size packetIdSize) { this.packetIdSize = packetIdSize; } /** @param ignoreDeserializationErrors if true, deserialization of packets with invalid class ID will be quietly * ignored. Useful on server in production mode, when clients can use old application versions or modify * source code on purpose. {@link SerializationException} will still be thrown if data is otherwise * corrupted. */ public void setIgnoreDeserializationErrors(final boolean ignoreDeserializationErrors) { this.ignoreDeserializationErrors = ignoreDeserializationErrors; } } package seedu.address.testutil; import java.time.LocalTime; import seedu.address.model.event.EventDayTime; /** * Typical, Reusable {@code EventDayTime}(s). Guaranteed valid. */ public class TypicalEventDayTimes { public static final EventDayTime DEFAULT_DAY_TIME = EventDayTime.defaultEventDayTime(); public static final EventDayTime TIME_0800_TO_1800 = new EventDayTime(LocalTime.of(8, 0), LocalTime.of(18, 0)); public static final EventDayTime TIME_0800_TO_1230 = new EventDayTime(LocalTime.of(8, 0), LocalTime.of(12, 30)); public static final EventDayTime TIME_1200_TO_1800 = new EventDayTime(LocalTime.of(12, 0), LocalTime.of(18, 0)); } yqboots/platform-services0 package com.yqboots.social.wechat.client.builder; import com.yqboots.social.wechat.WeChatApplication; import com.yqboots.social.wechat.api.pay.data.InitiatePaymentRequest; import com.yqboots.social.wechat.client.builder.support.RequestBuilderParameters; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = {WeChatApplication.class}) public class InitiatePaymentRequestBuilderTest { private static final Logger LOG = LoggerFactory.getLogger(InitiatePaymentRequestBuilderTest.class); @Autowired private InitiatePaymentRequestBuilder builder; @Test public void build() { InitiatePaymentRequest request = builder.build(new RequestBuilderParameters() .setPrepayId("wx130045194745681add0a93881956491000")); LOG.info(ToStringBuilder.reflectionToString(request, ToStringStyle.JSON_STYLE)); } } 1000+ // use every strict math function package classes.test; import java.util.Arrays; import java.lang.StrictMath; public class StrictMathTest { private static void results(String name, int[] results) { System.out.print(name + ": "); System.out.println(Arrays.toString(results)); } private static void results(String name, long[] results) { System.out.print(name + ": "); System.out.println(Arrays.toString(results)); } private static void results(String name, float[] results) { System.out.print(name + ": "); System.out.println(Arrays.toString(results)); } private static void results(String name, double[] results) { System.out.print(name + ": "); boolean first = true; String result = ""; for (double d : results) { if (first) first = false; else result += " "; // paper over precision issues in Chrome, see #181 result += String.format("%.13g", d); } System.out.println(result); } public static void main(String[] args) { double[] d_vals = { 2.12345, -3.256, 0,3,4, Double.MAX_VALUE, Double.MIN_VALUE, Double.MIN_NORMAL, Double.MAX_EXPONENT, Double.MIN_EXPONENT, //Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY }; float[] f_vals = { 2, -5, 0, Float.MAX_VALUE, Float.MIN_VALUE, Float.MIN_NORMAL, Float.MAX_EXPONENT, Float.MIN_EXPONENT, //Float.NaN, Float.POSITIVE_INFINITY, Float.NEGATIVE_INFINITY }; int[] i_vals = { 245, -20, 0, Integer.MAX_VALUE, Integer.MIN_VALUE }; long[] l_vals = { 12345678, -1235, 0, Long.MAX_VALUE, Long.MIN_VALUE }; double[] d_results = new double[d_vals.length]; double[] d_results_2d = new double[d_vals.length*d_vals.length]; int[] i_results = new int[i_vals.length]; int[] i_results_2d = new int[i_vals.length*i_vals.length]; float[] f_results = new float[f_vals.length]; float[] f_results_2d = new float[f_vals.length*f_vals.length]; long[] l_results = new long[l_vals.length]; long[] l_results_2d = new long[l_vals.length*l_vals.length]; // Loop iterators int i, j; // static int abs(int a) for (i=0; i < i_vals.length; i++) { i_results[i] = StrictMath.abs(i_vals[i]); } results("int abs(int a)", i_results); // static double abs(double a) for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.abs(d_vals[i]); } results("double abs(double a)", d_results); // static float abs(float a) for (i=0; i < f_vals.length; i++) { f_results[i] = StrictMath.abs(f_vals[i]); } results("float abs(float a)", f_results); // static long abs(long a) for (i=0; i < l_vals.length; i++) { l_results[i] = StrictMath.abs(l_vals[i]); } results("long abs(long a)", l_results); // static double acos(double a) // Returns the arc cosine of a value; the returned angle is in the range 0.0 through pi. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.acos(d_vals[i]); } results("double acos(double a)", d_results); // static double asin(double a) // Returns the arc sine of a value; the returned angle is in the range -pi/2 through pi/2. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.asin(d_vals[i]); } results("double asin(double a)", d_results); // static double atan(double a) // Returns the arc tangent of a value; the returned angle is in the range -pi/2 through pi/2. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.atan(d_vals[i]); } results("double atan(double a)", d_results); // static double atan2(double y, double x) // Returns the angle theta from the conversion of rectangular coordinates (x, y) to polar coordinates (r, theta). for (i=0; i < d_vals.length; i++) { for (j = 0; j < d_vals.length; j++) { d_results_2d[i] = StrictMath.atan2(d_vals[i], d_vals[j]); } } results("double atan2(double a, double b)", d_results_2d); // static double cbrt(double a) // Returns the cube root of a double value. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.cbrt(d_vals[i]); } results("double cbrt(double a)", d_results); // static double ceil(double a) // Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.ceil(d_vals[i]); } results("double ceil(double a)", d_results); // static double cos(double a) // Returns the trigonometric cosine of an angle. for (i=0; i < d_vals.length; i++) { // Some browsers don't return consistent values for this operation // (e.g. Firefox on Travis-CI) if (d_vals[i] == Double.MAX_VALUE) { continue; } d_results[i] = StrictMath.cos(d_vals[i]); } results("double cos(double a)", d_results); // static double cosh(double x) // Returns the hyperbolic cosine of a double value. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.cosh(d_vals[i]); } results("double cosh(double a)", d_results); // static double exp(double a) // Returns Euler's number e raised to the power of a double value. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.exp(d_vals[i]); } results("double exp(double a)", d_results); // static double expm1(double x) // Returns ex -1. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.expm1(d_vals[i]); } results("double expm1(double a)", d_results); // static double floor(double a) // Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.floor(d_vals[i]); } results("double floor(double a)", d_results); // static double IEEEremainder(double f1, double f2) // Computes the remainder operation on two arguments as prescribed by the IEEE 754 standard. for (i=0; i < d_vals.length; i++) { for (j=0; j < d_vals.length; j++) { d_results_2d[i] = StrictMath.IEEEremainder(d_vals[i], d_vals[j]); } } results("double IEEEremainder(double a, double b)", d_results_2d); // static double log(double a) // Returns the natural logarithm (base e) of a double value. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.log(d_vals[i]); } results("double log(double a)", d_results); // static double log10(double a) // Returns the base 10 logarithm of a double value. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.log10(d_vals[i]); } results("double log10(double a)", d_results); // static double log1p(double x) // Returns the natural logarithm of the sum of the argument and 1. // static double max(double a, double b) // Returns the greater of two double values. for (i=0; i < d_vals.length; i++) { for (j = 0; j < d_vals.length; j++) { d_results_2d[i] = StrictMath.max(d_vals[i], d_vals[j]); } } results("double max(double a, double b)", d_results_2d); // static float max(float a, float b) // Returns the greater of two float values. for (i=0; i < f_vals.length; i++) { for (j = 0; j < f_vals.length; j++) { f_results_2d[i] = StrictMath.max(f_vals[i], f_vals[j]); } } results("float max(float a, float b)", f_results_2d); // static int max(int a, int b) // Returns the greater of two int values. for (i=0; i < i_vals.length; i++) { for (j = 0; j < i_vals.length; j++) { i_results_2d[i] = StrictMath.max(i_vals[i], i_vals[j]); } } results("int max(int a, int b)", i_results_2d); // static long max(long a, long b) // Returns the greater of two long values. for (i=0; i < l_vals.length; i++) { for (j = 0; j < l_vals.length; j++) { l_results_2d[i] = StrictMath.max(l_vals[i], l_vals[j]); } } results("long max(long a, long b)", l_results_2d); // static double min(double a, double b) // Returns the smaller of two double values. for (i=0; i < d_vals.length; i++) { for (j = 0; j < d_vals.length; j++) { d_results_2d[i] = StrictMath.min(d_vals[i], d_vals[j]); } } results("double min(double a, double b)", d_results_2d); // static float min(float a, float b) // Returns the smaller of two float values. for (i=0; i < f_vals.length; i++) { for (j = 0; j < f_vals.length; j++) { f_results_2d[i] = StrictMath.min(f_vals[i], f_vals[j]); } } results("float min(float a, float b)", f_results_2d); // static int min(int a, int b) // Returns the smaller of two int values. for (i=0; i < i_vals.length; i++) { for (j = 0; j < i_vals.length; j++) { i_results_2d[i] = StrictMath.min(i_vals[i], i_vals[j]); } } results("int min(int a, int b)", i_results_2d); // static long min(long a, long b) // Returns the smaller of two long values. for (i=0; i < l_vals.length; i++) { for (j = 0; j < l_vals.length; j++) { l_results_2d[i] = StrictMath.min(l_vals[i], l_vals[j]); } } results("long min(long a, long b)", l_results_2d); // static double pow(double a, double b) // Returns the value of the first argument raised to the power of the second argument. for (i=0; i < d_vals.length; i++) { for (j=0; j < d_vals.length; j++) { d_results[i] = StrictMath.pow(d_vals[i], d_vals[j]); } } results("double pow(double a, double b)", d_results_2d); // static double hypot(double a, double b) // Returns the value of the first argument raised to the power of 2 + second argument raised to the power of . for (i=0; i < d_vals.length; i++) { for (j=0; j < d_vals.length; j++) { d_results[i] = StrictMath.hypot(d_vals[i], d_vals[j]); } } results("double hypot(double a, double b)", d_results_2d); // static double random() // Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. for (i = 0; i < 10; i++) { double rand = StrictMath.random(); if (rand < 0 || rand >= 1) { System.out.println("StrictMath.random(): Return value outside of [0,1): " + rand); } } // static double rint(double a) // Returns the double value that is closest in value to the argument and is equal to a mathematical integer. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.rint(d_vals[i]); } results("double rint(double a)", d_results); // static long round(double a) // Returns the closest long to the argument. long[] l_for_d_results = new long[d_results.length]; for (i=0; i < d_vals.length; i++) { l_for_d_results[i] = StrictMath.round(d_vals[i]); } results("long round(double a)", l_for_d_results); // static int round(float a) // Returns the closest int to the argument. int[] i_for_f_results = new int[f_results.length]; for (i=0; i < f_vals.length; i++) { i_for_f_results[i] = StrictMath.round(f_vals[i]); } results("int round(float a)", i_for_f_results); // static double sin(double a) // Returns the trigonometric sine of an angle. for (i=0; i < d_vals.length; i++) { // Some browsers don't return consistent values for this operation // (e.g. Firefox on Travis-CI) if (d_vals[i] == Double.MAX_VALUE) { continue; } d_results[i] = StrictMath.sin(d_vals[i]); } results("double sin(double a)", d_results); // static double sinh(double x) // Returns the hyperbolic sine of a double value. for (i=0; i < d_vals.length; i++) { if( d_vals[i] == Double.MIN_VALUE || d_vals[i] == Double.MIN_NORMAL){ continue; } d_results[i] = StrictMath.sinh(d_vals[i]); } results("double sinh(double a)", d_results); // static double sqrt(double a) // Returns the correctly rounded positive square root of a double value. for (i=0; i < d_vals.length; i++) { d_results[i] = StrictMath.sqrt(d_vals[i]); } results("double sqrt(double a)", d_results); // static double tan(double a) // Returns the trigonometric tangent of an angle. for (i=0; i < d_vals.length; i++) { // Some browsers don't return consistent values for this operation // (e.g. Firefox on Travis-CI) if (d_vals[i] == Double.MAX_VALUE) { continue; } d_results[i] = StrictMath.tan(d_vals[i]); } results("double tan(double a)", d_results); // static double tanh(double x) // Returns the hyperbolic tangent of a double value. } } andresag01/bwca /** * MIT License * * Copyright (c) 2019 , * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.bwca.cfg; import java.util.Arrays; import java.util.ArrayList; import java.util.HashSet; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.List; import java.util.LinkedList; import java.util.ListIterator; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; import com.bwca.models.Model; import com.bwca.utils.PlatformUtils; public class ISAFunction { static final Pattern INST = Pattern.compile("^\\s+(?

[0-9a-fA-F]+):" + "\\s+[0-9a-fA-F]{4}(\\s+[0-9a-fA-F]{4})?" + "\\s+(?\\w+)(\\.n)?(?.*)$"); static final Pattern FUNC = Pattern.compile("^(?
[0-9a-fA-F]+)\\s+" + "<(?[^>]+)>:$"); static final String DOT_TOP_LEVEL = "digraph G {\n" + " subgraph cluster_cfg {\n" + " color = white;\n" + " graph [fontname=\"monospace\"];\n" + " edge [fontname=\"monospace\"];\n" + " node [shape=box,style=filled,fontname=\"monospace\"," + " fillcolor=yellow];\n" + " label = \"Function: %s()%s\";\n" + " labelloc = \"t\";\n" + " legend [fillcolor=lightgrey,label=<\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
Legend
Basic Block
Loop Block
Loop Header
>];\n" + "%s" + "%s" + " }\n" + "}"; static final String ILP_TOP_LEVEL = "/*\n" + " * ILP for:\n" + " * - Function: %s@0x%08x\n" + " * - Cost model: %s\n" + " */\n\n" + "/* Objective function */\n" + "%s: %s;\n\n" + "/* Output constraints */\n" + "%s\n" + "/* Input constraints */\n" + "%s\n" + "/* Loop constraints */\n" + "%s\n" + "/* Detailed block costs\n" + " *\n" + "%s*/\n\n" + "/* Block variable declarations */\n" + "%s\n" + "/* Edge variable declarations */\n" + "%s"; static final String ILP_PROBLEM_FILE_EXT = ".lp"; static final String ILP_SOLUTION_FILE_EXT = ".sol"; static final String LP_SOLVE = "lp_solve"; static final String[] LP_SOLVE_CMD = { LP_SOLVE }; private Long address; private long size; private String name; private ISABlock entry; private ArrayList blocks; private Set infoMsgs; private CFGConfiguration config; private int nextEdgeId; private int nextBlockId; public ISAFunction(long address, long size, String name, CFGConfiguration config) { // Clear the bottom bit of the address because this is thumb this.address = address & ~0x1; this.size = size; this.name = name; this.entry = null; this.infoMsgs = new HashSet(); this.blocks = new ArrayList(); this.config = config; this.nextBlockId = 0; this.nextEdgeId = 0; } public ISAFunction(long size, String name, CFGConfiguration config) { this.address = null; this.size = size; this.name = name; this.entry = null; this.infoMsgs = new HashSet(); this.blocks = new ArrayList(); this.config = config; this.nextBlockId = 0; this.nextEdgeId = 0; } public String getName() { return name; } public LinkedList getMissingInfoMessages() { LinkedList msgs = new LinkedList(); for (ISABlock block : blocks) { msgs.addAll(block.getMissingInfoMessages()); } msgs.addAll(infoMsgs); return msgs; } private int findStartOfFunctionInObjdump(ArrayList objdump) { boolean foundFunc = false; int funcIndex; // Find the start of the function in the code for (funcIndex = 0; funcIndex < objdump.size(); funcIndex++) { long address; String name; Matcher funcMatch = FUNC.matcher(objdump.get(funcIndex)); if (funcMatch.matches()) { address = Long.parseLong(funcMatch.group("address"), 16); name = funcMatch.group("name"); } else { // This is not the start of a function continue; } // Check that the function values match the symbol table data if (name.indexOf(this.name) == -1) { // We use find() because sometimes the name in readelf is // cropped, so we need to check that name is a substring of // this.name instead of an identical match continue; } if (this.address != null && this.address != address) { // Not the correct function because even though the name in // readelf is a substring of this.name, but the address does // not match. Therefore, the substring matching is aliased to // another function continue; } // We need to check if the address is null because functions that // are in the config file do not have an address. Instead, we // discover the address when parsing the objdump if (this.address == null) { this.address = address; } else if (address != this.address) { // Something went wrong System.out.printf("Function at 0x%08X does not match address " + "at symbol table 0x%08X for function " + "%s\n", address, this.address, name); System.exit(1); } // The readelf output sometimes has the function address clipped, // so make sure we use the function name from the objdump output this.name = name; // Found the start of the function foundFunc = true; break; } if (!foundFunc) { System.out.println("Could not find function " + this.name + " " + "in input binary"); System.exit(1); } return funcIndex; } private ArrayList extractInstructionsFromObjdump( ArrayList objdump, int funcIndex, Map symbolTable) { ArrayList insts = new ArrayList(); // Parse the instructions for (funcIndex = funcIndex + 1; funcIndex < objdump.size(); funcIndex++) { Matcher instMatch = INST.matcher(objdump.get(funcIndex)); if (!instMatch.matches()) { // This is not an instruction, skip it continue; } long address = Long.parseLong(instMatch.group("address"), 16); String opcode = instMatch.group("opcode"); String body = instMatch.group("body"); // Check that we have have not gone past the end of the function if (address >= this.address + this.size) { break; } // Create the instruction ISALine line = new ISALine(address, opcode, body, config, this.address, this.size, symbolTable); insts.add(line); } return insts; } private void extractBranchDestinationAddresses(ArrayList insts, Set branchTargetAddrs) { // Extract target addresses for (ISALine inst : insts) { if (inst.getType() == InstructionType.BRANCH || inst.getType() == InstructionType.COND_BRANCH) { for (BranchTarget target : inst.getBranchTargets()) { Long destAddress = target.getAddress(); if (destAddress != null && destAddress >= this.address && destAddress < this.address + this.size) { // Add it do the map if the target is in the function branchTargetAddrs.add(destAddress); } } } } } private Map groupInstructionsInBlocks( ArrayList insts, Set branchTargetAddrs) { // Create the blocks of the CFG Map blocksMap = new HashMap(); ISABlock cur = null; for (ISALine inst : insts) { // Inspect the instruction and do the following: // - If this address is a branch target create a new block // - Otherwise add the current instruction to the last block long address = inst.getAddress(); if (branchTargetAddrs.contains(address)) { // This is the start of a block cur = new ISABlock(address, nextBlockId++); blocks.add(cur); blocksMap.put(address, cur); cur.addLine(inst); } else { // Add the instruction to the end of the current block if (cur == null) { // This can happen if the function's entry point is not the // target of a branch within the function cur = new ISABlock(address, nextBlockId++); blocks.add(cur); blocksMap.put(address, cur); } cur.addLine(inst); } // Terminate the current block if the current instruction is a // branch to an unknown location without a return or a branch // (regardless of condition) within the function if (inst.getType() == InstructionType.BRANCH || inst.getType() == InstructionType.COND_BRANCH) { cur = null; } } if (blocks.size() < 1) { System.out.println("The function has no blocks!"); System.exit(1); } return blocksMap; } private void createEdges(Map blocksMap, ISABlock exitBlock) { boolean hasExit = false; // Create the edges of the CFG for (int i = 0; i < blocks.size(); i++) { // Look up the last instruction of every block: // - If it is a regular instruction then add an edge to next // - If it is an unconditional branch then add an edge to the // appropriate block // - If it is a conditional branch then add an edge to the next // block and the appropriate target block (which should be // different! ISALine inst = blocks.get(i).getLastLine(); blocks.get(i).setEdges(inst.getBranchTargets()); switch (inst.getType()) { case OTHER: case BRANCH_LINK: if (inst.getInstruction() == Instruction.FUNC_EXIT) { // This is just a dummy block to consolidate all exists // into a single point. Otherwise the solver cannot // handle the ILP break; } else if (inst.isExit()) { // Link this block to the dummy exit block blocks.get(i).addEdge(exitBlock); } else { // This is just a regular block that does not // manipulate the pc, so fall through to the next block if (blocks.size() == i + 1) { System.out.println("Trying to link last block in " + "a function with ith + 1 " + "block!"); System.exit(1); } blocks.get(i).addEdge(blocks.get(i + 1)); } break; case BRANCH: case COND_BRANCH: if (inst.isExit()) { blocks.get(i).addEdge(exitBlock); break; } for (BranchTarget target : inst.getBranchTargets()) { Long address = target.getAddress(); target.setBlock(blocksMap.get(address)); } break; default: System.out.println("Invalid instruction type"); System.exit(1); } if (inst.isExit()) { blocks.get(i).setExit(true); hasExit = true; } } if (!hasExit) { System.out.println("Function does not have exit block!\n"); System.exit(1); } } private ISABlock addExitBlock() { // Create a dummy block to consolidate all exit points into a single // one. Otherwise lp_solve cannot deal with the problem ISABlock dummyBlock = new ISABlock(0, nextBlockId++); dummyBlock.setExit(true); dummyBlock.addLine(new ISALine(0, "func_exit", "", true, null, 0, Instruction.FUNC_EXIT, InstructionType.OTHER)); dummyBlock.setEdges(dummyBlock.getLastLine().getBranchTargets()); blocks.add(dummyBlock); return dummyBlock; } public int parseInstructions(ArrayList objdump, Map symbolTable) { int funcIndex; ArrayList insts; Set branchTargetAddrs; Map blocksMap; ISABlock exitBlock; if (size == 0) { // This is only a place holder block. Do nothing... return 0; } funcIndex = findStartOfFunctionInObjdump(objdump); insts = extractInstructionsFromObjdump(objdump, funcIndex, symbolTable); branchTargetAddrs = new HashSet(); extractBranchDestinationAddresses(insts, branchTargetAddrs); blocksMap = groupInstructionsInBlocks(insts, branchTargetAddrs); entry = blocks.get(0); exitBlock = addExitBlock(); createEdges(blocksMap, exitBlock); return 0; } private void garbageCollectBlocks() { // Clear all mark flags for (ISABlock block : blocks) { block.setMark(false); } // - The root set is the entry block // - Traverse all reachable blocks starting from entry and mark them // - Collect all the unmarked (dead) objects entry.setMark(true); markBlocks(entry); sweepBlocks(); } private void markBlocks(ISABlock block) { for (BranchTarget edge : block.getEdges()) { ISABlock target = edge.getBlock(); if (target != null && !target.isMarked()) { target.setMark(true); markBlocks(target); } } } private void sweepBlocks() { ArrayList clean = new ArrayList(); for (int i = 0; i < blocks.size(); i++) { if (blocks.get(i).isMarked()) { blocks.get(i).setMark(false); clean.add(blocks.get(i)); } } blocks = clean; } private void numberEdges() { for (ISABlock block : blocks) { if (block.getEdges().size() == 0) { continue; } for (BranchTarget edge : block.getEdges()) { edge.setId(nextEdgeId++); } } } public void analyzeCFG() { if (blocks.size() == 0) { // This is just a placeholder ISAFunction. Nothing to do... return; } garbageCollectBlocks(); detectLoops(); numberEdges(); } private void detectLoops() { // The algorithm is taken from the paper at: // https://lenx.100871.net/papers/loop-SAS.pdf // Initialize everything to zero/null/false for (ISABlock block : blocks) { block.setLoopHeader(false); block.setInnerLoopHeader(null); block.setDFSPosition(0); block.setMark(false); } // Label loop headers traverseInDFS(entry, 1); // Set loop depth for (ISABlock block : blocks) { block.setMark(false); } findLoopDepth(entry); } private void findLoopDepth(ISABlock block) { block.setMark(true); if (block.isLoopHeader()) { if (block.getInnerLoopHeader() == null) { block.setLoopDepth(0); } else { block.setLoopDepth(block.getInnerLoopHeader().getLoopDepth() + 1); } } else if (block.getInnerLoopHeader() != null) { block.setLoopDepth(block.getInnerLoopHeader().getLoopDepth()); } for (BranchTarget target : block.getEdges()) { ISABlock successor = target.getBlock(); if (successor.isMarked()) { continue; } findLoopDepth(successor); } } private ISABlock traverseInDFS(ISABlock block, int dfsPosition) { block.setDFSPosition(dfsPosition); block.setMark(true); for (BranchTarget target : block.getEdges()) { ISABlock successor = target.getBlock(); if (!successor.isMarked()) { // Case A ISABlock nh = traverseInDFS(successor, dfsPosition + 1); tagLoopHeader(block, nh); } else { if (successor.getDFSPosition() > 0) { // Case B successor.setLoopHeader(true); tagLoopHeader(block, successor); } else if (successor.getInnerLoopHeader() == null) { // Case C: Do nothing... } else { ISABlock header = successor.getInnerLoopHeader(); if (header.getDFSPosition() > 0) { // Case D tagLoopHeader(block, header); } else { // Case E: Reentry... // The loop is irreducible System.out.printf("Function %s has an irreducible " + "loop!\n", name); System.exit(1); } } } } block.setDFSPosition(0); return block.getInnerLoopHeader(); } private void tagLoopHeader(ISABlock block, ISABlock header) { if (block == header || header == null) { return; } ISABlock cur1 = block; ISABlock cur2 = header; while (cur1.getInnerLoopHeader() != null) { ISABlock ih = cur1.getInnerLoopHeader(); if (ih == cur2) { return; } if (ih.getDFSPosition() < cur2.getDFSPosition()) { cur1.setInnerLoopHeader(cur2); cur1 = cur2; cur2 = ih; } else { cur1 = ih; } } cur1.setInnerLoopHeader(cur2); } public List getBlocks() { return blocks; } public void applyModel(String outputDir, Model model, FunctionCallDetails call) { String baseFilename; String lpFile; String solFile; CFGSolution solution; baseFilename = String.format("%s%s%s@0x%08x", outputDir, File.separator, model.getName(), call.getCallAddress()); lpFile = baseFilename + ILP_PROBLEM_FILE_EXT; solFile = baseFilename + ILP_SOLUTION_FILE_EXT; for (ISABlock block : blocks) { // Add the cost of the blocks and edges block.applyModel(model); // Add any other miscelaneous cost for the block model.addBlockCost(block, call); // Add the cost of the function calls this block makes for (FunctionCallDetails dep : block.getFunctionCallDependencies()) { model.addFunctionCallCost(block, dep); } } // Generate and solve the ILP for the function writeILP(lpFile, model, call); solution = solveILP(lpFile, solFile); // Add the solution for this function call for later use model.addFunctionCallDetailsCost(this, call, solution); // Write the annotated CFG in dot format writeDotFile(baseFilename + ".dot", model, call); // Clear the model's data structures so that we can accurately resolve // another call later without stacking the weights of blocks and edges model.clear(); } private CFGSolution solveILP(String lpFile, String solFile) { ArrayList output = null; File outputLpSolveFile; String[] cmd; // Run the lp_solve utility with the program statement as an input try { outputLpSolveFile = new File(solFile); cmd = Arrays.copyOf(LP_SOLVE_CMD, LP_SOLVE_CMD.length + 1); cmd[cmd.length - 1] = lpFile; output = PlatformUtils.runShell(cmd, outputLpSolveFile); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println(ioe); System.exit(1); } catch (InterruptedException ie) { ie.printStackTrace(); System.out.println(ie); System.exit(1); } return new CFGSolution(output); } public void checkMissingInformation(FunctionCallDetails call) { for (ISABlock block : blocks) { for (BranchTarget edge : block.getEdges()) { ISABlock successor = edge.getBlock(); long successorAddress = successor.getFirstLine().getAddress(); if (!successor.isLoopHeader()) { continue; } else if (block.getInnerLoopHeader() == successor) { continue; } else if (block == successor) { continue; } // This successor is the header of a loop and needs a bound ISALine inst = block.getFirstLine(); // Check if we have information about this bound in the config LoopBound bound = config.getLoopBounds(call.getCallAddress(), successorAddress); if (bound == null) { String msg = String.format("loopbound 0x%08x min " + "max from call " + "0x%08x", successorAddress, call.getCallAddress()); infoMsgs.add(msg); } } // TODO: Skip over this check if we are not applying the relevant // cost mode (e.g. WCA) for (ISALine inst : block.getInstructions()) { if (inst.getInstruction() == Instruction.WFI) { long instAddress = inst.getAddress(); long callAddress = call.getCallAddress(); Long allocSize = config.getAllocationSize(callAddress, instAddress); if (allocSize == null) { String msg = String.format("allocation 0x%08x " + "from call 0x%08x", instAddress, callAddress); infoMsgs.add(msg); } } } } } private void writeILP(String filename, Model model, FunctionCallDetails call) { StringBuilder outConstraints = new StringBuilder(); StringBuilder inConstraints = new StringBuilder(); StringBuilder loopConstraints = new StringBuilder(); StringBuilder blockDecls = new StringBuilder(); StringBuilder edgeDecls = new StringBuilder(); StringBuilder blockCosts = new StringBuilder(); String blockPfix = "b"; String edgePfix = "e"; String ilpFunctionType = model.getObjectiveFunctionType(); // Make the string for the problem List problemSub = new LinkedList(); List problemAdd = new LinkedList(); for (ISABlock block : blocks) { // Add the block cost to the top level formula String positiveCost = model.getPositiveBlockCost(block); String negativeCost = model.getNegativeBlockCost(block); if (positiveCost != null) { positiveCost = String.format( "%s %s%d", positiveCost, blockPfix, block.getId()); problemAdd.add(positiveCost); } if (negativeCost != null) { negativeCost = String.format( "%s %s%d", negativeCost, blockPfix, block.getId()); problemSub.add(negativeCost); } for (BranchTarget edge : block.getEdges()) { positiveCost = model.getPositiveEdgeCost(edge); negativeCost = model.getNegativeEdgeCost(edge); if (positiveCost != null) { positiveCost = String.format( "%s %s%d", positiveCost, edgePfix, edge.getId()); problemAdd.add(positiveCost); } if (negativeCost != null) { negativeCost = String.format( "%s %s%d", negativeCost, edgePfix, edge.getId()); problemSub.add(negativeCost); } } } String intercept = model.getInterceptCost(); if (problemAdd.size() < 1) { System.out.println("Objective function does not have additive " + "components!"); System.exit(1); } String problemStr = String.join("\n + ", problemAdd); if (problemSub.size() > 0) { problemStr += "\n - " + String.join("\n - ", problemSub); } problemStr += (intercept != null) ? "\n " + intercept : ""; // Make the string for the constraints // - Add an output constraint for every block // - Construct a table of block -> inEdge // - Add an input constraint for every block Map> inEdges = new HashMap>(); // Output constraints for (ISABlock block : blocks) { outConstraints.append(blockPfix + block.getId() + " = "); if (block.getEdges().size() == 0) { if (block.getLastLine().getInstruction() != Instruction.FUNC_EXIT) { System.out.println("Block " + block.getId() + " has " + "no output edges and not an " + "exit in function " + name + "\n"); System.exit(1); } outConstraints.append("1;\n"); continue; } List outEdges = new LinkedList(); for (BranchTarget edge : block.getEdges()) { outEdges.add(edgePfix + edge.getId()); ISABlock target = edge.getBlock(); List inEdgeList = inEdges.get(target); if (inEdgeList == null) { inEdgeList = new LinkedList(); inEdges.put(target, inEdgeList); } inEdgeList.add(edgePfix + edge.getId()); } outConstraints.append(String.join(" + ", outEdges) + ";\n"); } // Input constraints for (ISABlock block : blocks) { List edges = inEdges.get(block); if (edges == null && block != entry) { System.out.println("Block has no input edges and is not " + "entry point"); System.exit(1); } else if (edges == null) { // This is the entry block, so there is a chance that it // does not have any in edges. To avoid a null pointer // exception we create a list so that the join() operation // later on works without problems edges = new LinkedList(); } inConstraints.append(blockPfix + block.getId() + " = "); if (block == entry) { edges.add("1"); } inConstraints.append(String.join(" + ", edges) + ";\n"); } // Loop constraints for (ISABlock block : blocks) { for (BranchTarget edge : block.getEdges()) { ISABlock successor = edge.getBlock(); long successorAddress = successor.getFirstLine().getAddress(); if (!successor.isLoopHeader()) { continue; } else if (block.getInnerLoopHeader() == successor) { continue; } else if (block == successor) { continue; } // This successor is the header of a loop and needs a bound ISALine inst = block.getFirstLine(); String lbound = "BOUND"; String ubound = "BOUND"; // Check if we have information about this bound in the config LoopBound bound = config.getLoopBounds(call.getCallAddress(), successorAddress); if (bound != null) { lbound = Long.toString(bound.getLowerBound()); ubound = Long.toString(bound.getUpperBound()); } else { System.out.printf("No information about loop at 0x%08x\n", inst.getAddress()); } String constraint = String.format("\n/* Header 0x%08x */\n" + "%s %s%d <= %s%d;\n", inst.getAddress(), lbound, blockPfix, block.getId(), blockPfix, successor.getId()); loopConstraints.append(constraint); constraint = String.format("%s%d <= %s %s%d;\n", blockPfix, successor.getId(), ubound, blockPfix, block.getId()); loopConstraints.append(constraint); } } // Block and edge declarations (and block cost breakdown) for (ISABlock block : blocks) { blockDecls.append( String.format("int %s%d;\n", blockPfix, block.getId())); if (blockCosts.length() > 0) { blockCosts.append(" *\n"); } blockCosts.append(model.getBlockDetails(block)); for (BranchTarget edge : block.getEdges()) { edgeDecls.append( String.format("int %s%d;\n", edgePfix, edge.getId())); } } try { // Write the data in ILP format FileWriter fwriter = new FileWriter(filename); BufferedWriter bwriter = new BufferedWriter(fwriter); String output = String.format(ILP_TOP_LEVEL, name, call.getCallAddress(), model.getName(), ilpFunctionType, problemStr, outConstraints.toString(), inConstraints.toString(), loopConstraints.toString(), blockCosts.toString(), blockDecls.toString(), edgeDecls.toString()); bwriter.write(output); bwriter.close(); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println(ioe); System.exit(1); } } public void buildFunctionCallDependencyList() { for (ISABlock block : blocks) { block.buildFunctionCallDependencyList(); } } public Set getFunctionCallDependencyNames() { Set deps = new HashSet(); for (ISABlock block : blocks) { for (FunctionCallDetails call : block.getFunctionCallDependencies()) { deps.add(call.getCalleeName()); } } return deps; } public List getFunctionCallDependencies() { List deps = new LinkedList(); for (ISABlock block : blocks) { deps.addAll(block.getFunctionCallDependencies()); } return deps; } public void writeDotFile(String filename, Model model, FunctionCallDetails call) { try { FileWriter fwriter = new FileWriter(filename); BufferedWriter bwriter = new BufferedWriter(fwriter); // Compose the string to write ArrayList nodes = new ArrayList(); ArrayList edges = new ArrayList(); for (ISABlock block : blocks) { String cost = null; if (model != null) { cost = model.getBlockSummary(block); } block.nodesToString(nodes, block == entry, cost); block.edgesToString(edges, model); } // This ISAFunction might be empty because we do not have // information about its size String nodesStr = ""; if (nodes.size() > 0) { nodesStr = String.join(";\n ", nodes); nodesStr = " " + nodesStr; nodesStr += ";\n"; } String edgesStr = ""; if (edges.size() > 0) { edgesStr = String.join(";\n ", edges); edgesStr = " " + edgesStr; edgesStr += ";\n"; } String functionCallCost = ""; if (model != null && call != null) { functionCallCost = String.format( " {cost:%s}", model.getFunctionCallCost(call)); } String dot = String.format(DOT_TOP_LEVEL, this.name, functionCallCost, nodesStr, edgesStr); bwriter.write(dot); bwriter.close(); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println(ioe); System.exit(1); } } } package com.home.base.rest; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import com.home.base.biz.BaseBiz; import com.home.base.exceptions.DataAccessException; import com.home.base.msg.ObjectRestResponse; import com.home.base.secruity.JwtTokenUtil; import org.apache.commons.lang3.StringUtils; 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.cache.annotation.Cacheable; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.PathVariable; 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.multipart.MultipartFile; import org.springframework.web.servlet.support.RequestContext; /** * ${DESCRIPTION} * * @author wanghaobin * @create 2017-06-15 8:48 */ public class BaseRestController { @Autowired protected HttpServletRequest request; @Autowired protected Biz baseBiz; @Autowired private JwtTokenUtil jwtTokenUtil; public static final Logger logger = LoggerFactory.getLogger(BaseRestController.class); protected Map resultMap = new HashMap(); public BaseRestController title( String title) { request.setAttribute("title", title); return this; } public BaseRestController keywords( String keywords) { request.setAttribute("keywords", keywords); return this; } @RequestMapping(value = "",method = RequestMethod.POST) @ResponseBody public ObjectRestResponse add(Entity entity){ baseBiz.insertSelective(entity); return new ObjectRestResponse().rel(true); } @RequestMapping(value = "/{id}",method = RequestMethod.GET) @ResponseBody public ObjectRestResponse get(@PathVariable String id){ return new ObjectRestResponse().rel(true).result(baseBiz.selectById(id)); } @RequestMapping(value = "/{id}",method = RequestMethod.PUT) @ResponseBody public ObjectRestResponse update(Entity entity){ baseBiz.updateSelectiveById(entity); return new ObjectRestResponse().rel(true); } @RequestMapping(value = "/{id}",method = RequestMethod.DELETE) @ResponseBody public ObjectRestResponse remove(@PathVariable Long id){ baseBiz.deleteById(id); return new ObjectRestResponse().rel(true); } @RequestMapping(value = "/all",method = RequestMethod.GET) @ResponseBody public List list(){ return baseBiz.selectListAll(); } public String getCurrentUsertype(){ String usertype= jwtTokenUtil.getUsertypeFromToken(getToken()); if(StringUtils.isBlank(usertype)){ throw new DataAccessException("token无效"); } return usertype; } public String getCurrentId(){ String userid= jwtTokenUtil.getUseridFromToken(getToken()); if(StringUtils.isBlank(userid)){ throw new DataAccessException("token无效"); } return userid; } private String getToken(){ SecurityContext sc = SecurityContextHolder.getContext(); Object principal = sc.getAuthentication().getDetails(); return principal.toString(); } } "3DUfw��������!2CTev�������� 1BSdu��������0ARct�������� /@Qbs�������� .?Par�������� ->O`q�������� ,=N_p�������� +<M^o��������  * ; L ] n  � � � � � � �   ) : K \ m ~ � � � � � � �   ( 9 J [ l } � � � � � � �   ' 8 I Z k | � � � � � � �   & 7 H Y j { � � � � � � � %6GXiz�������$5FWhy�������#4EVgx�������"3DUfw��������!2CTev�������� 1BSdu��������0ARct�������� /@Qbs�������� .?Par�������� ->O`q�������� ,=N_p�������� +<M^o��������*;L]n�������):K\m~�������(9J[l}�������'8IZk|�������&7HYj{�������%6GXiz�������  $ 5 F W h y � � � � � � � !!#!4!E!V!g!x!�!�!�!�!�!�!�!""""3"D"U"f"w"�"�"�"�"�"�"�"�"#!#2#C#T#e#v#�#�#�#�#�#�#�#�#$ $1$B$S$d$u$�$�$�$�$�$�$�$�$%%0%A%R%c%t%�%�%�%�%�%�%�%�% &&/&@&Q&b&s&�&�&�&�&�&�&�&�& ''.'?'P'a'r'�'�'�'�'�'�'�'�' ((-(>(O(`(q(�(�(�(�(�(�(�(�( )),)=)N)_)p)�)�)�)�)�)�)�)�) **+*<*M*^*o*�*�*�*�*�*�*�*�*++*+;+L+]+n++�+�+�+�+�+�+�+,,),:,K,\,m,~,�,�,�,�,�,�,�,--(-9-J-[-l-}-�-�-�-�-�-�-�-..'.8.I.Z.k.|.�.�.�.�.�.�.�.//&/7/H/Y/j/{/�/�/�/�/�/�/�/00%060G0X0i0z0�0�0�0�0�0�0�011$151F1W1h1y1�1�1�1�1�1�1�122#242E2V2g2x2�2�2�2�2�2�2�233"333D3U3f3w3�3�3�3�3�3�3�3�34!424C4T4e4v4�4�4�4�4�4�4�4�45 515B5S5d5u5�5�5�5�5�5�5�5�56606A6R6c6t6�6�6�6�6�6�6�6�6 77/7@7Q7b7s7�7�7�7�7�7�7�7�7 88.8?8P8a8r8�8�8�8�8�8�8�8�8 99-9>9O9`9q9�9�9�9�9�9�9�9�9 ::,:=:N:_:p:�:�:�:�:�:�:�:�: ;;+;<;M;^;o;�;�;�;�;�;�;�;�;<<*<;<L<]<n<<�<�<�<�<�<�<�<==)=:=K=\=m=~=�=�=�=�=�=�=�=>>(>9>J>[>l>}>�>�>�>�>�>�>�>??'?8?I?Z?k?|?�?�?�?�?�?�?�?@@&@7@H@Y@j@{@�@�@�@�@�@�@�@AA%A6AGAXAiAzA�A�A�A�A�A�A�ABB$B5BFBWBhBStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJavaStarcoderdataJava����  �N2   �@   ��� �"]�18282 @(2@&@@@$+3:AHOW^fnv~����������������� %-4<CKRZ`gnu}����������������� #)07>EMU]els{�����������������&.6>EKSZahov}����������������� &.5=DLT\dks{����������������� &.6<CKRYaipx������������������ !)08<DKSYaiqx�����������������  (08?GNV]emu|������������������ $,3;AHPW^fnu}�����������������   " ) 1 9 A I P X ` g o v ~ � � � � � � � � � � � � � � � �     % , 4 ; C K S [ b i p x  � � � � � � � � � � � � � � � � �    $ , 3 : @ G O V ] d l r y  � � � � � � � � � � � � � � � �    ' . 6 = D L T [ b i p w  � � � � � � � � � � � � � � � � �    # * 1 9 A I P X _ f n v ~ � � � � � � � � � � � � � � � � �  #+3:AHOV]djqy������������������$+29AIQYaiqv~����������������� "*19@GOW_gou}����������150178896970851126384901010017937159689931012068906535788055653105128470920325411998233478672418224851147996091815134916428397382997510338562190942251313495311562840991784010904032181792628043520194556421091636817750248481546956242221660019589185422188113406674166093281203743914167522159081701019995420837401236016441739681185076844445451647358229267020892633655167525903212402198177098648549154157161064010141077667912784028189369761682860510989142157155991370908079105111572281042184514164132110387105977362842457011289778162436838072651948071942049230630354847776279336861867561031505010333440109919201930269667570513983720149194541728408617689873163496281562120035146961257190070677677052120340411424715309170601462096295835481553240211700763142395285837489482042771024428716446188917731075928715351261792946718913703182193459807926547602116849327438444755611762297203725309210276783872681223183675822046811145249607510694103961119865960035973694104794541132255131841695293718621497713115910478069843957214169410161500591921136493858811230995815542812328976195300608738757140248319033995110338861976712413535497148600329713686118147911374376119295164836617886850682198360169647901997938613275366747230412337147899657761446651186193379387573731733536965485857831864503015252575137265151401650377094845444101049324614833409108163506691552083155179725373749586279538218172802199708113095055189824171492897316666812136796291423080427990561427665516653777454746118035868609532388916194876393337481094319170713038987052684651611388211103622162500019689450948722814944663105118299184448178114602400145262833605487199466681221271742903118652236192498937299901135959521190394514967270392258692988451999489317077284134755241737907128167687048218182020721615661336883561893189181989691075923115672897419601457933461113670311559065161044521207251817824626827343315009467518077215178489503157915891362198085741933269851019391306735448654065126511077245160450706196262515228612247322173072591548861178290714011288772541416246014198121664677231890172612824234993994416120109623595956221133489171333112188992021643930423686877527301706556867858866113743104175761000323898853411348474815401733187731597308920102728989082344693200517557317174560111215974575363461902787585011461363684240729548446366128735251868426527305742907081641460822776071621196189067741093480615242441123237071721109487919351193498612861624611013212106803731571517128945184792951475162263111521573697410648012145537671599270217321525190322936306410625451203942610614155111508341391080416227201478367810370692347576762689541980156042940405051274146333772259290191328181117002418116099169363854884566350485342704861956066199323951225774012577688877678148208532133391191108149333246167309631043147317849401910340665851398293511723784437684819731137107893304019112178400241676077317637196104362381397971778656025048801649633654383110964119159296488466464611907189778288851996995021858866112442241865427620505516169007172167141144988313544994168687551239332615767272740145817274040125815671249705513277680187063137129167626707184276621131053849401115452286240854612109315985700449774151698734912815706224731434887243633788461088379417691355930174113812769151316076137255882729752944096312727662113732341883521716069577729038915901094193077410984647368310115681209195510102499174175054081735759791684812937960267460088998211523825814609624135185339564282144934715591591103985018749570121360671831520619196695799502215008611768141940992981789115690443264114081973387314645748157059751652595018353366498371772578414315806182026823968931163707701429894218480135804453319253465129992324912378127213961390119820048718444157443289134841221999778518011322851156369712175711944562714938634105958131009790317331643350145611401017656726082714081056164453714124149161298264150124732797249187225281679190052925801081228879060915589180324577418754501398233199362051168680419355264118042811741509416751826100637804963515294625147977348197144192998441082042298273241985530891680118114535130312881802190813597653183925702758815677675126859611934567739808244547023270761617785697481429043714821663418040933331499801747422063399196161655301825828318543150167203471910069753594417411256132334179057198370644880741116484798826444050810184068552146886923400518���.�0@2�25�DOJ�T�W�m�u�{؁��,�����������ʸ�����lqӯI���������W���Q�>   $�-�[�Ӛ��V��������G����(0LCR`co�odr|�Ȉ��'�ܸ�����D�6�&�L�q4�=H<[�`�b)dMf�s:w�{ǚ=�7�{���8�;�����7�l����� g ���2FF�IY[�\I]�]�m|nzt�t�y�z1�v�������� �,���>����������� 3 � �?8suv������7���u�c������ ^��7UE�GKI�a{n�z�����܋���4�+! �% �5 ; � . � P �U 6f �g �k v |� j � . ]8 �8 �A 1F �V Dk l �m �v 0y � h� � �� � � $� � n� �� ?� �� �� �  �  m �m �q �w %� Շ �� &� �  � � 0 e T8 ~F %G RX �c +e _w ~� �� � 7� h� � �� o� ��6PE0H�I@M�Ux[�ag�qfy�~����&�(�`;e3g�i@;dg8n#z��!|%�2.5j=?lRo2v�э��C����^�A�m����6�������G�<�ʴ�����������B�T��Sr��. 8~;�Bf�g�x�:�x��įF�������C���$�$t%$v.$k8$�>$b[$^$ao$�p$'s$kz$ �$��$C�$��$T�$��$��$q�$��$�%� %W%0%Q<%�L%�R%xU%L^%�a%|f%5s%�z%��%<�%��%��%��%&�O&^X&�~'h�'�'��'�'��'�'��''�'3�'��'T�'M(�(&a(9c(�c(Cf(�x(9|(^�(t�(A�(ý(��(��(�(@)�)6()�0)53)�l)fq)x)�|)�)R�)��) �)��)M�)�*�*�**�;*tB* L*n*�|*�~*�* �*K�*ʷ*��*U�*V�*O�*+�*<�*&�*��*6+++&+�-+ 5+h7+ C+�e+ �+Ԅ+ש+��+��+��+b�+F�+��+��+a�+��+�+��+��+($, R,�y,�|,n,��,��,̸,��,��,�,/�,�-�-�L-:O-�P-�W-nZ-�j-�q-�v-�y-�-�-1�-�-'�-�-�-��-�.�.�.�D.|\.].�d.�e.i{.�}.��.��.��.1�.��.E�.�.�.��.�./� /9l/��/��/��/��/��/��/�/��/��/\�/��/�+0�50�=0�]0L�0�0(�0-�0�'1�)1$31eR1sr1jt18x1V�1Ɍ1P�1F�1V�1b�1�1l�1��1��1�1��1]�11-10 /* * Copyright 2020 The DistributedEventing 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.distributedeventing.codec.kafka.messages.requests.createtopics; import com.distributedeventing.codec.kafka.Schema; import com.distributedeventing.codec.kafka.exceptions.UnsupportedVersionException; import com.distributedeventing.codec.kafka.headers.RequestHeader; import com.distributedeventing.codec.kafka.messages.requests.RequestMessage; import com.distributedeventing.codec.kafka.values.*; import com.distributedeventing.codec.kafka.ApiType; import com.distributedeventing.codec.kafka.Field; import com.distributedeventing.codec.kafka.values.Boolean; /** * A request to create one or more topics. Create topics requests must be * sent to the controller of the cluster. To perform this operation successfully, * one must be authorized to create topics in the cluster. * * Creation of multiple topics with one request is not a transactional operation, * i.e. if the creation of one topic fails, others might still succeed. */ public final class CreateTopicsRequest extends RequestMessage { /** * The topics to create. Per topic, one can specify only one of the two: *
    *
  • * the number of partitions and the replication factor. This leads to automatic * replica assignment. *
  • *
  • * the replica assignment (as decided by user). The number of partitions and the * replication factor are determined from this. The first replica in the list is * taken to be the preferred leader. *
  • *
*/ public static final Field TOPICS = new Field("topics"); /** * The interval (in ms) that the broker should wait before sending a response. * A timeout greater than 0 will cause the controller to block until either * the create is complete and the controller has updated the metadata or a timeout * occurs. If the request times out, it does not imply that it has failed. Rather, * it implies that the controller could not finish the operation by then. User * will have to query the updated metadata to find the result of operation. * * Setting timeout to <= 0 causes the controller to validate the arguments, initiate * a create, and then return immediately. This is the fully asynchronous mode. */ public static final Field TIMEOUT_MS = new Field("timeout_ms"); /** * If set to true, it instructs the broker to only validate whether the topics can * be created as specified. The broker will not actually create the topics under such * circumstances. */ public static final Field VALIDATE_ONLY = new Field("validate_only"); public static final Field TAGGED_FEILDS = new Field("tagged_fields"); public static final Schema SCHEMA_V5 = new Schema(TOPICS, TIMEOUT_MS, VALIDATE_ONLY, TAGGED_FEILDS); public static final Schema[] SCHEMAS = new Schema[] {null, null, null, null, null, SCHEMA_V5}; private final CreateableTopic.CreateableTopicFactory topicFactory; { if (schema == SCHEMA_V5) { topicFactory = new CreateableTopic.CreateableTopicFactory((short) 5); } else { topicFactory = null; } } private final CompactArray topics = new CompactArray<>(topicFactory); private final Int32 timeoutMs = new Int32(); private final Boolean validateOnly = new Boolean(); private final UvilArray taggedFields = new UvilArray<>(new TaggedBytes.TaggedBytesFactory()); public static CreateTopicsRequest getInstance(final int version) { if (version < 0 || version >= SCHEMAS.length || SCHEMAS[version] == null) { throw new UnsupportedVersionException(version); } final short ver = (short) version; final ApiType apiType = new ApiType.CreateTopics(ver); return new CreateTopicsRequest(createRequestHeader(apiType), SCHEMAS[ver], apiType); } private static RequestHeader createRequestHeader(final ApiType apiType) { final short headerVersion = (short) (apiType.version() >= 5? 2: 1); final RequestHeader header = RequestHeader.getInstance(headerVersion); header.requestApiKey(apiType.key().key()); header.requestApiVersion(apiType.version()); return header; } public CreateableTopic createTopic() { final CreateableTopic createableTopic = topicFactory.createInstance(); topics.add(createableTopic); return createableTopic; } public void timeoutMs(final int interval) { timeoutMs.value(interval); } public void validateOnly(final boolean validate) { validateOnly.value(validate); } public void taggedFields(final TaggedBytes...taggedBytes) { taggedFields.value(taggedBytes); } private void setFieldValueBindings() { fieldValueBindings.put(TOPICS, topics); fieldValueBindings.put(TIMEOUT_MS, timeoutMs); fieldValueBindings.put(VALIDATE_ONLY, validateOnly); fieldValueBindings.put(TAGGED_FEILDS, taggedFields); } private CreateTopicsRequest(final RequestHeader header, final Schema schema, final ApiType apiType) { super(header, schema, apiType); setFieldValueBindings(); } } MessiMercy/MessiCrawler1-10 package com.downloader.cookie.impl; import com.downloader.cookie.CookiePersistence; import org.apache.http.impl.client.BasicCookieStore; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; /** * 将file存储于redis中 * Created by Administrator on 2016/12/26. */ public class RedisCookiePersistence implements CookiePersistence { private JedisPool pool = new JedisPool("127.0.0.1", 6379); @Override public void saveCookieStore(String key, BasicCookieStore store) { try (Jedis jedis = pool.getResource()) { jedis.set(key.getBytes(), serialize(store).toByteArray());//虽然存储键为bytes,但是实际键还是string。可以get(key)方式取出byte的str形式 } } @Override public BasicCookieStore recoverCookieStore(String key) { try (Jedis jedis = pool.getResource()) { byte[] objBytes = jedis.get(key.getBytes());//当传入键为byte[]形式的时候,取出的键也是byte[]形式 return unserialize(key, objBytes); } } } AlmostReliable/energymeter-forge package com.github.almostreliable.energymeter.core; import com.github.almostreliable.energymeter.meter.MeterBlock; import com.github.almostreliable.energymeter.meter.MeterContainer; import com.github.almostreliable.energymeter.meter.MeterEntity; import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.Item.Properties; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.entity.BlockEntityType.BlockEntitySupplier; import net.minecraft.world.level.block.entity.BlockEntityType.Builder; import net.minecraftforge.common.extensions.IForgeMenuType; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.*; import java.util.function.BiFunction; import java.util.function.Supplier; import static com.github.almostreliable.energymeter.core.Constants.METER_ID; import static com.github.almostreliable.energymeter.core.Constants.MOD_ID; public final class Setup { private static final Tab TAB = new Tab(MOD_ID); private Setup() {} public static void init(IEventBus modEventBus) { Blocks.REGISTRY.register(modEventBus); Blocks.ITEMS.register(modEventBus); Entities.REGISTRY.register(modEventBus); Containers.REGISTRY.register(modEventBus); } private static > DeferredRegister createRegistry(IForgeRegistry registry) { return DeferredRegister.create(registry, MOD_ID); } public static final class Entities { private static final DeferredRegister> REGISTRY = createRegistry(ForgeRegistries.BLOCK_ENTITIES); private Entities() {} @SuppressWarnings("SameParameterValue") private static RegistryObject> register( String id, RegistryObject block, BlockEntitySupplier entity ) { // noinspection ConstantConditions return REGISTRY.register(id, () -> Builder.of(entity, block.get()).build(null)); } public static final RegistryObject> METER = register(METER_ID, Blocks.METER, MeterEntity::new ); } public static final class Containers { private static final DeferredRegister> REGISTRY = createRegistry(ForgeRegistries.CONTAINERS); private Containers() {} @SuppressWarnings("SameParameterValue") private static RegistryObject> register( String id, BiFunction constructor ) { return REGISTRY.register(id, () -> IForgeMenuType.create((containerID, inventory, data) -> { var entity = (MeterEntity) inventory.player.level.getBlockEntity(data.readBlockPos()); return constructor.apply(entity, containerID); })); } public static final RegistryObject> METER = register(METER_ID, MeterContainer::new); } private static final class Tab extends CreativeModeTab { private Tab(String label) { super(label); } @Override public ItemStack makeIcon() { return new ItemStack(Blocks.METER.get()); } } private static final class Blocks { private static final DeferredRegister REGISTRY = createRegistry(ForgeRegistries.BLOCKS); private static final DeferredRegister ITEMS = createRegistry(ForgeRegistries.ITEMS); private static final RegistryObject METER = register(METER_ID, MeterBlock::new); @SuppressWarnings("SameParameterValue") private static RegistryObject register(String id, Supplier supplier) { var result = REGISTRY.register(id, supplier); ITEMS.register(id, () -> new BlockItem(result.get(), new Properties().tab(TAB))); return result; } } } package tests; import configuration.EmulatedFirefoxTestSetup; import org.testng.annotations.Test; import pages.UserAgentPage; import static org.testng.Assert.assertTrue; public class ModifiedUserAgentTest extends EmulatedFirefoxTestSetup { @Test public void checkThatUserAgentIsCorrect() { UserAgentPage userAgentPage = new UserAgentPage(webDriver); userAgentPage.openPage(); String testUserAgent = userAgentPage.getUserAgentText(); assertTrue(testUserAgent.contains("Firefox")); } } package com.csl.observer.future; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; /** * @author MaoLongLong * @date 2021-04-17 0:57 */ class CompletableFutureTest { @Test void testCompletableFuture() { assertDoesNotThrow(() -> App.main(new String[]{})); } } package com.bitwig.extensions.controllers.mackie.layer; public enum ParamElement { VOLUME, PAN, SENDMIXER, SEND_TRACK, INSTRUMENT, PLUGIN, EQ, NOTE_DEVICE; } src/main/java/io/choerodon/iam/infra/annotation/NamingRuleTransStrategy.java package io.choerodon.iam.infra.annotation; /** * @author dengyouquan * UNDER_LINE:实体类为Under_line命名,前端url传值为camel命名 * CAMEL:实体类为Camel命名,前端url传值为under_line命名 **/ public enum NamingRuleTransStrategy { CAMEL("CAMEL"), UNDER_LINE("UNDER_LINE"); private String value; public String value() { return value; } NamingRuleTransStrategy(String value) { this.value = value; } } package com.secuconnect.client.model; import com.google.gson.annotations.SerializedName; import com.secuconnect.client.model.LoyaltyCardgroupsDTOMerchant; import java.util.Objects; /** * LoyaltyCardgroupsDTO */ public class LoyaltyCardgroupsDTO { @SerializedName("display_name") private String displayName = null; @SerializedName("display_name_raw") private String displayNameRaw = null; @SerializedName("stock_warn_limit") private String stockWarnLimit = null; @SerializedName("picture") private String picture = null; @SerializedName("merchant") private LoyaltyCardgroupsDTOMerchant merchant = null; public LoyaltyCardgroupsDTO displayName(String displayName) { this.displayName = displayName; return this; } /** * Display name * @return displayName **/ public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public LoyaltyCardgroupsDTO displayNameRaw(String displayNameRaw) { this.displayNameRaw = displayNameRaw; return this; } /** * Display name raw * @return displayNameRaw **/ public String getDisplayNameRaw() { return displayNameRaw; } public void setDisplayNameRaw(String displayNameRaw) { this.displayNameRaw = displayNameRaw; } public LoyaltyCardgroupsDTO stockWarnLimit(String stockWarnLimit) { this.stockWarnLimit = stockWarnLimit; return this; } /** * Stock warn limit * @return stockWarnLimit **/ public String getStockWarnLimit() { return stockWarnLimit; } public void setStockWarnLimit(String stockWarnLimit) { this.stockWarnLimit = stockWarnLimit; } public LoyaltyCardgroupsDTO picture(String picture) { this.picture = picture; return this; } /** * Picture * @return picture **/ public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public LoyaltyCardgroupsDTO merchant(LoyaltyCardgroupsDTOMerchant merchant) { this.merchant = merchant; return this; } /** * Get merchant * @return merchant **/ public LoyaltyCardgroupsDTOMerchant getMerchant() { return merchant; } public void setMerchant(LoyaltyCardgroupsDTOMerchant merchant) { this.merchant = merchant; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LoyaltyCardgroupsDTO loyaltyCardgroupsDTO = (LoyaltyCardgroupsDTO) o; return Objects.equals(this.displayName, loyaltyCardgroupsDTO.displayName) && Objects.equals(this.displayNameRaw, loyaltyCardgroupsDTO.displayNameRaw) && Objects.equals(this.stockWarnLimit, loyaltyCardgroupsDTO.stockWarnLimit) && Objects.equals(this.picture, loyaltyCardgroupsDTO.picture) && Objects.equals(this.merchant, loyaltyCardgroupsDTO.merchant); } @Override public int hashCode() { return Objects.hash(displayName, displayNameRaw, stockWarnLimit, picture, merchant); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LoyaltyCardgroupsDTO {\n"); sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n"); sb.append(" displayNameRaw: ").append(toIndentedString(displayNameRaw)).append("\n"); sb.append(" stockWarnLimit: ").append(toIndentedString(stockWarnLimit)).append("\n"); sb.append(" picture: ").append(toIndentedString(picture)).append("\n"); sb.append(" merchant: ").append(toIndentedString(merchant)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } } package origami.crease_pattern.element; public enum LineColor { ANGLE(-2), NONE(-1), BLACK_0(0), RED_1(1), BLUE_2(2), CYAN_3(3), ORANGE_4(4), MAGENTA_5(5), GREEN_6(6), YELLOW_7(7), PURPLE_8(8), OTHER_9(9); private final int type; LineColor(int type) { this.type = type; } public static LineColor fromNumber(int type) { for (LineColor val : values()) { if (val.getNumber() == type) { return val; } } throw new IllegalArgumentException("Type " + type + " unknown"); } public static LineColor from(String type) { return fromNumber(Integer.parseInt(type)); } public LineColor advanceFolding() { if (!isFoldingLine()) { throw new IllegalArgumentException("Cannot advance folding on non folding line " + type); } if (type == 2) { return BLACK_0; } return fromNumber(type + 1); } public LineColor changeMV() { if (this == RED_1) return BLUE_2; if (this == BLUE_2) return RED_1; return this; } public int getNumber() { return this.type; } public boolean isFoldingLine() { return this == BLACK_0 || this == RED_1 || this == BLUE_2; } @Override public String toString() { return Integer.toString(type); } } package io.mercury.transport.zmq; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import org.zeromq.SocketType; import org.zeromq.ZContext; import org.zeromq.ZMQ; import io.mercury.common.character.Charsets; import io.mercury.transport.core.api.Subscriber; import io.mercury.transport.zmq.configurator.ZmqConfigurator; public class ZmqSubscriber implements Subscriber, Closeable { private ZContext zCtx; private ZMQ.Socket zSocket; private String subscriberName; private Consumer callback; private ZmqConfigurator configurator; private AtomicBoolean isRun = new AtomicBoolean(true); public ZmqSubscriber(ZmqConfigurator configurator, Consumer callback) { if (configurator == null || callback == null) throw new IllegalArgumentException("configurator is null in JeroMQSubscriber init mothed !"); this.configurator = configurator; this.callback = callback; init(); } private void init() { this.zCtx = new ZContext(configurator.ioThreads()); this.zSocket = zCtx.createSocket(SocketType.SUB); this.zSocket.connect(configurator.host()); this.zSocket.subscribe(configurator.topic().getBytes()); this.zSocket.setTCPKeepAlive(1); this.zSocket.setTCPKeepAliveCount(10); this.zSocket.setTCPKeepAliveIdle(15); this.zSocket.setTCPKeepAliveInterval(15); this.subscriberName = "JeroMQ.SUB$" + configurator.host() + "::" + configurator.topic(); } @Override public void subscribe() { while (isRun.get()) { zSocket.recv(); byte[] msgBytes = zSocket.recv(); callback.accept(msgBytes); } } @Override public boolean destroy() { this.isRun.set(false); zSocket.close(); zCtx.close(); return zCtx.isClosed(); } @Override public String name() { return subscriberName; } public static void main(String[] args) { // JeroMqConfigurator configurator = // JeroMqConfigurator.builder().setHost("tcp://127.0.0.1:10001").setIoThreads(2).setTopic("").build(); ZmqConfigurator configurator = ZmqConfigurator.builder().setHost("tcp://127.0.0.1:13001").setTopic("command") .setIoThreads(2).build(); try (ZmqSubscriber jeroMQSubscriber = new ZmqSubscriber(configurator, (byte[] byteMsg) -> System.out.println(new String(byteMsg, Charsets.UTF8)))) { jeroMQSubscriber.subscribe(); } catch (IOException e) { e.printStackTrace(); } } @Override public boolean isConnected() { return !zCtx.isClosed(); } @Override public void close() throws IOException { destroy(); } @Override public void reconnect() { // TODO Auto-generated method stub } } package Pnc; import java.awt.Color; import java.net.MalformedURLException; import java.net.URL; import com.thehowtotutorial.splashscreen.JSplash; public class Splash { public static void main(String[] args) throws InterruptedException { JSplash j=new JSplash(Splash.class.getResource("/img/aa.jpg"), true, true, true, "", null, Color.RED, Color.blue); j.getProgressBar().setForeground(new Color(0, 0, 0)); j.getProgressBar().setBounds(1, 278, 419, 29); j.getProgressBar().setBorder(null); j.getProgressBar().setBorderPainted(false); j.getContentPane().setLayout(null); j.splashOn(); for(int i=0;i<100;i++){ j.setProgress(i, "as"); Thread.sleep(30); } j.splashOff(); PNC p=new PNC(); p.main(null); //p.setVisible(true); } } /* * 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.brooklyn.core.plan; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.ServiceLoader; import org.apache.brooklyn.api.mgmt.ManagementContext; import org.apache.brooklyn.util.exceptions.Exceptions; import org.apache.brooklyn.util.exceptions.PropagatedRuntimeException; import org.apache.brooklyn.util.guava.Maybe; import org.apache.brooklyn.util.text.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; public class PlanToSpecFactory { private static final Logger log = LoggerFactory.getLogger(PlanToSpecFactory.class); private static Collection getAll() { return ImmutableList.copyOf(ServiceLoader.load(PlanToSpecTransformer.class)); } private static Collection> OVERRIDE; @SafeVarargs @VisibleForTesting public synchronized static void forceAvailable(Class ...classes) { OVERRIDE = Arrays.asList(classes); } public synchronized static void clearForced() { OVERRIDE = null; } public static Collection all(ManagementContext mgmt) { Collection> override = OVERRIDE; Collection result = new ArrayList(); if (override!=null) { for (Class o1: override) { try { result.add(o1.newInstance()); } catch (Exception e) { Exceptions.propagate(e); } } } else { result.addAll(getAll()); } for(PlanToSpecTransformer t : result) { t.injectManagementContext(mgmt); } return result; } @Beta public static PlanToSpecTransformer forPlanType(ManagementContext mgmt, String planType) { Collection transformers = all(mgmt); for (PlanToSpecTransformer transformer : transformers) { if (transformer.accepts(planType)) { return transformer; } } throw new IllegalStateException("PlanToSpecTransformer for plan type " + planType + " not found. Registered transformers are: " + transformers); } // TODO primitive loading mechanism, just tries all in order; we'll want something better as we get more plan transformers @Beta public static Maybe attemptWithLoaders(ManagementContext mgmt, Function f) { return attemptWithLoaders(all(mgmt), f); } public static Maybe attemptWithLoaders(Iterable transformers, Function f) { Collection transformersWhoDontSupport = new ArrayList(); Collection otherProblemsFromTransformers = new ArrayList(); for (PlanToSpecTransformer t: transformers) { try { T result = f.apply(t); if (result==null) { transformersWhoDontSupport.add(t.getShortDescription() + " (returned null)"); continue; } return Maybe.of(result); } catch (PlanNotRecognizedException e) { transformersWhoDontSupport.add(t.getShortDescription() + (Strings.isNonBlank(e.getMessage()) ? " ("+e.getMessage()+")" : "")); } catch (Throwable e) { Exceptions.propagateIfFatal(e); otherProblemsFromTransformers.add(new PropagatedRuntimeException("Transformer for "+t.getShortDescription()+" gave an error creating this plan: "+ Exceptions.collapseText(e), e)); } } // failed Exception result; if (!otherProblemsFromTransformers.isEmpty()) { // at least one thought he could do it log.debug("Plan could not be transformed; failure will be propagated (other transformers tried = "+transformersWhoDontSupport+"): "+otherProblemsFromTransformers); result = otherProblemsFromTransformers.size()==1 ? Exceptions.create(null, otherProblemsFromTransformers) : Exceptions.create("Plan transformers all failed", otherProblemsFromTransformers); } else { result = new PlanNotRecognizedException("Invalid plan; format could not be recognized, trying with: "+transformersWhoDontSupport); } return Maybe.absent(result); } } package work.eanson.service.user; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import work.eanson.dao.SchoolDao; import work.eanson.pojo.School; import work.eanson.service.base.BaseService; import work.eanson.service.base.GlobalService; import work.eanson.service.base.Input; import work.eanson.util.Context; import work.eanson.util.Result; import java.util.List; /** * @author eanson */ @Service("get_school") public class GetSchoolListServiceImpl extends BaseService implements GlobalService { @Autowired private SchoolDao schoolDao; @Autowired private JedisPool jedisPool; private static final Logger logger = LoggerFactory.getLogger(GetSchoolListServiceImpl.class); @Input(required = "province_id") @Override public void service(Context context) throws Exception { Integer proId = (Integer) context.get("province_id"); context.clear(); String key = "school_" + proId; try (Jedis jedis = jedisPool.getResource();) { ObjectMapper objectMapper = new ObjectMapper(); if (!jedis.exists(key)) { List schools = schoolDao.selectByForeignKey(proId); String value = objectMapper.writeValueAsString(schools); jedis.set(key, value); context.setResult(Result.success(schools)); logger.info("school from db"); } else { String json = jedis.get(key); List schools = objectMapper.readValue(json, new TypeReference>() { }); context.setResult(Result.success(schools)); logger.info("school from jedis"); } } } } package es.guiguegon.mapmodule.sample; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.Toast; import es.guiguegon.mapmodule.MapActivity; import es.guiguegon.mapmodule.model.Place; public class MainActivity extends AppCompatActivity { public static final int REQUEST_CODE_MAP = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener((view) -> openMap()); } public void openMap() { startActivityForResult(MapActivity.getCallingIntent(this), REQUEST_CODE_MAP); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_MAP && resultCode == RESULT_OK && data != null && data.getExtras() != null) { Place place = data.getExtras().getParcelable(MapActivity.RESULT_PLACE); if (place != null) { Toast.makeText(this, "Place selected: " + place.toString(), Toast.LENGTH_LONG).show(); } } } } stylesmile/snow package com.stylesmile.modules.system.vo.query; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.stylesmile.modules.system.entity.SysUser; /** * @author chenye * @date 2018/12/10 */ public class SysMenuQuery extends Page { private int id; private String name; private String code; private String sort; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } } package org.motechproject.mots.dto; import lombok.Getter; import lombok.Setter; import org.hibernate.validator.constraints.NotBlank; import org.motechproject.mots.constants.ValidationMessages; import org.motechproject.mots.validate.annotations.Uuid; public class ChwInfoDto { @Getter @Setter @Uuid private String id; @Getter @Setter @NotBlank(message = ValidationMessages.EMPTY_CHW_ID) private String chwId; @Getter @Setter @NotBlank(message = ValidationMessages.EMPTY_FIRST_NAME) private String firstName; @Getter @Setter @NotBlank(message = ValidationMessages.EMPTY_SECOND_NAME) private String secondName; @Getter @Setter private String otherName; } package com.jfixby.scarabei.red.input; import com.jfixby.scarabei.api.input.UserInputComponent; public class RedInput implements UserInputComponent { final RedKeyboard keyboard = new RedKeyboard(); final RedMouseButtons mouse = new RedMouseButtons(); @Override public com.jfixby.scarabei.api.input.Keyboard Keyboard () { return keyboard; } @Override public com.jfixby.scarabei.api.input.MouseButtons MouseButtons () { return mouse; } } 0 package com.nimbus.engine.ecs.component.lib; import com.nimbus.engine.ecs.component.IComponent; import com.nimbus.engine.graphics.image.Image; public class CSprite implements IComponent{ Image sprite; String name; public CSprite(Image sprite, String name) { this.sprite = sprite; this.name = name; } public CSprite(Image sprite) { this.sprite = sprite; this.name = null; } public Image getSprite() { return sprite; } public void setSprite(Image sprite) { this.sprite = sprite; } public String getName() { return name; } public void setName(String name) { this.name = name; } } package com.cottee.managerstore.utils; /** * Created by chn on 2018/1/18. * (╯°□°)╯︵ ┻━┻ MMP好气啊! * (╯‵□′)╯︵┻━┻ 老子怒掀桌子! * ┻━┻︵╰(‵□′)╯︵┻━┻老子双手掀桌! * ┬─┬ ノ( ゜-゜ノ) 算了,我不生气了!日子还得过老老实实敲吧~ */ public class OssBean { /** * RequestId : 102903BB-7408-444B-97E4-422A2A95EF27 * AssumedRoleUser : {"AssumedRoleId":"336777017757943326:bbb","Arn":"acs:ram::1321290185118957:role/aliyunosstokengeneratorrole/bbb"} * Credentials : {"AccessKeySecret":"","AccessKeyId":"","Expiration":"2018-01-18T10:21:12Z","SecurityToken":"} */ private String RequestId; private AssumedRoleUserBean AssumedRoleUser; private CredentialsBean Credentials; public String getRequestId() { return RequestId; } public void setRequestId(String RequestId) { this.RequestId = RequestId; } public AssumedRoleUserBean getAssumedRoleUser() { return AssumedRoleUser; } public void setAssumedRoleUser(AssumedRoleUserBean AssumedRoleUser) { this.AssumedRoleUser = AssumedRoleUser; } public CredentialsBean getCredentials() { return Credentials; } public void setCredentials(CredentialsBean Credentials) { this.Credentials = Credentials; } public static class AssumedRoleUserBean { /** * AssumedRoleId : 336777017757943326:bbb * Arn : acs:ram::1321290185118957:role/aliyunosstokengeneratorrole/bbb */ private String AssumedRoleId; private String Arn; public String getAssumedRoleId() { return AssumedRoleId; } public void setAssumedRoleId(String AssumedRoleId) { this.AssumedRoleId = AssumedRoleId; } public String getArn() { return Arn; } public void setArn(String Arn) { this.Arn = Arn; } } public static class CredentialsBean { /** * AccessKeySecret : * AccessKeyId : * Expiration : 2018-01-18T10:21:12Z * SecurityToken : */ private String AccessKeySecret; private String AccessKeyId; private String Expiration; private String SecurityToken; public String getAccessKeySecret() { return AccessKeySecret; } public void setAccessKeySecret(String AccessKeySecret) { this.AccessKeySecret = AccessKeySecret; } public String getAccessKeyId() { return AccessKeyId; } public void setAccessKeyId(String AccessKeyId) { this.AccessKeyId = AccessKeyId; } public String getExpiration() { return Expiration; } public void setExpiration(String Expiration) { this.Expiration = Expiration; } public String getSecurityToken() { return SecurityToken; } public void setSecurityToken(String SecurityToken) { this.SecurityToken = SecurityToken; } } } package com.senior.project.genealogy.response; public class Couple { private People mainPeople; private People partnerPeople; public Couple(People mainPeople) { this.mainPeople = mainPeople; } public People getMainPeople() { return mainPeople; } public void setMainPeople(People mainPeople) { this.mainPeople = mainPeople; } public People getPartnerPeople() { return partnerPeople; } public void setPartnerPeople(People partnerPeople) { this.partnerPeople = partnerPeople; } } package top.bluesword.feignclient; import feign.Response; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; /** * @author 李林峰 */ @FeignClient(value = "sword-laboratory-eureka-base-service",path = "file",contextId = "file") public interface FileClient { @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) Response map(@RequestPart("file") MultipartFile file, @RequestParam String fileName); } /*- * ============LICENSE_START======================================================= * ONAP - SO * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= */ package org.openecomp.mso.adapters.network; import static org.openecomp.mso.openstack.utils.MsoCommonUtils.isNullOrEmpty; import java.util.ArrayList; import java.util.List; import org.openecomp.mso.logger.MessageEnum; import org.openecomp.mso.logger.MsoLogger; import org.openecomp.mso.openstack.beans.HostRoute; import org.openecomp.mso.openstack.beans.Pool; import org.openecomp.mso.openstack.beans.Subnet; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class ContrailSubnet { private static MsoLogger logger = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA); @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet") private ContrailSubnetIp subnet = new ContrailSubnetIp(); @JsonProperty("network_ipam_refs_data_ipam_subnets_default_gateway") private String defaultGateway; @JsonProperty("network_ipam_refs_data_ipam_subnets_subnet_name") private String subnetName; @JsonProperty("network_ipam_refs_data_ipam_subnets_enable_dhcp") private Boolean enableDhcp; @JsonProperty("network_ipam_refs_data_ipam_subnets_addr_from_start") private Boolean addrFromStart = true; /** future - leave this commented private String subnet_uuid; private String dns_server_address; private List dns_nameservers; private String dhcp_option_list; **/ @JsonProperty("network_ipam_refs_data_ipam_subnets_allocation_pools") private List allocationPools = new ArrayList <> (); @JsonProperty("network_ipam_refs_data_ipam_subnets_host_routes") private ContrailSubnetHostRoutes host_routes = new ContrailSubnetHostRoutes(); public ContrailSubnet() { super(); } public String getDefaultGateway() { return defaultGateway; } public void setDefaultGateway(String defaultGateway) { this.defaultGateway = defaultGateway; } public ContrailSubnetIp getSubnet() { return subnet; } public void setSubnet(ContrailSubnetIp subnet) { this.subnet = subnet; } public Boolean isEnableDhcp() { return enableDhcp; } public void setEnableDhcp(Boolean enableDhcp) { this.enableDhcp = enableDhcp; } public String getSubnetName() { return subnetName; } public void setSubnetName(String subnetName) { this.subnetName = subnetName; } public List getAllocationPools() { return allocationPools; } public void setPools(List allocationPools) { this.allocationPools = allocationPools; } public Boolean isAddrFromStart() { return addrFromStart; } public void setAddrFromStart(Boolean addrFromStart) { this.addrFromStart = addrFromStart; } public JsonNode toJsonNode() { JsonNode node = null; try { ObjectMapper mapper = new ObjectMapper(); node = mapper.convertValue(this, JsonNode.class); } catch (Exception e) { String error = "Error creating JsonNode for Contrail Subnet:" + subnetName; logger.error (MessageEnum.RA_MARSHING_ERROR, error, "", "", MsoLogger.ErrorCode.SchemaError, "Exception creating JsonNode for Contrail Subnet", e); } return node; } public String toJsonString() { String jsonString = null; try { ObjectMapper mapper = new ObjectMapper(); jsonString = mapper.writeValueAsString(this); } catch (Exception e) { String error = "Error creating JsonString for Contrail Subnet:" + subnetName; logger.error (MessageEnum.RA_MARSHING_ERROR, error, "", "", MsoLogger.ErrorCode.SchemaError, "Exception creating JsonString for Contrail Subnet", e); } return jsonString; } //poulate contrail subnet with input(from bopel) subnet public void populateWith(Subnet inputSubnet) { if (inputSubnet != null) { if (!isNullOrEmpty(inputSubnet.getSubnetName())) subnetName = inputSubnet.getSubnetName(); else subnetName = inputSubnet.getSubnetId(); enableDhcp = inputSubnet.getEnableDHCP(); defaultGateway = inputSubnet.getGatewayIp(); if (!isNullOrEmpty(inputSubnet.getCidr()) ) { int idx = inputSubnet.getCidr().indexOf("/"); if (idx != -1) { subnet.setIpPrefix(inputSubnet.getCidr().substring(0, idx)); subnet.setIpPrefixLen(inputSubnet.getCidr().substring(idx+1)); } } if (inputSubnet.getAllocationPools() != null) { for (Pool pool : inputSubnet.getAllocationPools()) { if ( !isNullOrEmpty(pool.getStart()) && !isNullOrEmpty(pool.getEnd()) ) { ContrailSubnetPool csp = new ContrailSubnetPool(); csp.populateWith(pool); allocationPools.add (csp); } } } if (inputSubnet.getHostRoutes() != null) { List hrList = host_routes.getHost_routes(); for (HostRoute hr : inputSubnet.getHostRoutes()) { if ( !isNullOrEmpty(hr.getPrefix()) || !isNullOrEmpty(hr.getNextHop()) ) { ContrailSubnetHostRoute cshr = new ContrailSubnetHostRoute(); cshr.populateWith(hr); hrList.add (cshr); } } } } } @Override public String toString() { StringBuilder buf = new StringBuilder (); for (ContrailSubnetPool pool : allocationPools) { buf.append(pool.toString()); } return "ContrailSubnet [subnet=" + subnet.toString() + " default_gateway=" + defaultGateway + " enable_dhcp=" + enableDhcp + " addr_from_start=" + addrFromStart + " subnet_name=" + subnetName + " allocation_pools=" + buf + " ]"; } } cleitonferreira/DesignPatternsObserver/financeiro/src/main/java/com/algaworks/Principal.java0 package com.algaworks; import static org.quartz.CronScheduleBuilder.cronSchedule; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; import org.quartz.CronTrigger; import org.quartz.JobDataMap; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.impl.StdSchedulerFactory; import com.algaworks.job.LancamentosVencidosJob; import com.algaworks.listeners.EmailListener; import com.algaworks.listeners.Listener; import com.algaworks.listeners.SMSListener; import com.algaworks.notifier.Notificador; import com.algaworks.notifier.NotificadorLancamentosVencidos; import com.algaworks.repository.Lancamentos; public class Principal { public static void main(String[] args) throws Exception { Notificador notificador = new NotificadorLancamentosVencidos(); Listener enviadorEmail = new EmailListener(notificador); Listener enviadorSms = new SMSListener(notificador); JobDataMap jobDataMap = new JobDataMap(); Lancamentos lancamentos = new Lancamentos(); Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler(); jobDataMap.put("lancamentos", lancamentos); jobDataMap.put("notificador", notificador); JobDetail job = newJob(LancamentosVencidosJob.class) .setJobData(jobDataMap) .withIdentity("lancamentosVencidosJob", "lancamentosVencidosGroup") .build(); CronTrigger trigger = newTrigger() .withIdentity("trigger1", "group1") .withSchedule(cronSchedule("0 * * * * ?")) .build(); scheduler.scheduleJob(job, trigger); scheduler.start(); Thread.sleep(220000); scheduler.shutdown(true); } } package com.mwj.cms.common.enums; /** * @author mengweijin */ public enum ErrorCode { /** 数据校验不通过 */ VALIDATE_ERROR(1001); private final int code; ErrorCode (int code){ this.code = code; } public int getCode(){ return code; } } EndPointCorp/interactivespacesinteractivespaces-core/src/test/java/interactivespaces/util/process/restart/NoRestartRestartStrategyTest.java /* * Copyright (C) 2013 Google 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 interactivespaces.util.process.restart; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; /** * Tests for the {@link NoRestartRestartStrategy}. * * @author */ public class NoRestartRestartStrategyTest { /** * Test that no restart happens. */ @Test public void testRestart() { Restartable restartable = Mockito.mock(Restartable.class); RestartStrategyListener listener = Mockito.mock(RestartStrategyListener.class); NoRestartRestartStrategy strategy = new NoRestartRestartStrategy(); strategy.addRestartStrategyListener(listener); RestartStrategyInstance instance = strategy.newInstance(restartable); Assert.assertFalse(instance.isRestarting()); Mockito.verify(restartable, Mockito.times(1)).restartComplete(false); Mockito.verify(listener, Mockito.times(1)).onRestartFailure(strategy, restartable); Mockito.verify(listener, Mockito.times(0)).onRestartAttempt(strategy, restartable, true); Mockito.verify(listener, Mockito.times(0)).onRestartSuccess(strategy, restartable); } } /* * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.jmx.interceptor; // JMX RI import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER; import com.sun.jmx.mbeanserver.DynamicMBean2; import com.sun.jmx.mbeanserver.Introspector; import com.sun.jmx.mbeanserver.MBeanInstantiator; import com.sun.jmx.mbeanserver.ModifiableClassLoaderRepository; import com.sun.jmx.mbeanserver.NamedObject; import com.sun.jmx.mbeanserver.Repository; import com.sun.jmx.mbeanserver.Repository.RegistrationContext; import com.sun.jmx.mbeanserver.Util; import com.sun.jmx.remote.util.EnvHelp; import java.io.ObjectInputStream; import java.lang.ref.WeakReference; import java.security.AccessControlContext; import java.security.AccessController; import java.security.Permission; import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.WeakHashMap; import java.lang.System.Logger.Level; // JMX import import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.IntrospectionException; import javax.management.InvalidAttributeValueException; import javax.management.JMRuntimeException; import javax.management.ListenerNotFoundException; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanPermission; import javax.management.MBeanRegistration; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MBeanServerDelegate; import javax.management.MBeanServerNotification; import javax.management.MBeanTrustPermission; import javax.management.NotCompliantMBeanException; import javax.management.Notification; import javax.management.NotificationBroadcaster; import javax.management.NotificationEmitter; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.OperationsException; import javax.management.QueryEval; import javax.management.QueryExp; import javax.management.ReflectionException; import javax.management.RuntimeErrorException; import javax.management.RuntimeMBeanException; import javax.management.RuntimeOperationsException; import javax.management.loading.ClassLoaderRepository; /** * This is the default class for MBean manipulation on the agent side. It * contains the methods necessary for the creation, registration, and * deletion of MBeans as well as the access methods for registered MBeans. * This is the core component of the JMX infrastructure. *

* Every MBean which is added to the MBean server becomes manageable: its attributes and operations * become remotely accessible through the connectors/adaptors connected to that MBean server. * A Java object cannot be registered in the MBean server unless it is a JMX compliant MBean. *

* When an MBean is registered or unregistered in the MBean server an * {@link javax.management.MBeanServerNotification MBeanServerNotification} * Notification is emitted. To register an object as listener to MBeanServerNotifications * you should call the MBean server method {@link #addNotificationListener addNotificationListener} with ObjectName * the ObjectName of the {@link javax.management.MBeanServerDelegate MBeanServerDelegate}. * This ObjectName is: *
* JMImplementation:type=MBeanServerDelegate. * * @since 1.5 */ public class DefaultMBeanServerInterceptor implements MBeanServerInterceptor { /** The MBeanInstantiator object used by the * DefaultMBeanServerInterceptor */ private final transient MBeanInstantiator instantiator; /** The MBean server object that is associated to the * DefaultMBeanServerInterceptor */ private transient MBeanServer server = null; /** The MBean server delegate object that is associated to the * DefaultMBeanServerInterceptor */ private final transient MBeanServerDelegate delegate; /** The Repository object used by the DefaultMBeanServerInterceptor */ private final transient Repository repository; /** Wrappers for client listeners. */ /* See the comment before addNotificationListener below. */ private final transient WeakHashMap> listenerWrappers = new WeakHashMap>(); /** The default domain of the object names */ private final String domain; /** The sequence number identifying the notifications sent */ // Now sequence number is handled by MBeanServerDelegate. // private int sequenceNumber=0; /** * Creates a DefaultMBeanServerInterceptor with the specified * repository instance. *

Do not forget to call initialize(outer,delegate) * before using this object. * @param outer A pointer to the MBeanServer object that must be * passed to the MBeans when invoking their * {@link javax.management.MBeanRegistration} interface. * @param delegate A pointer to the MBeanServerDelegate associated * with the new MBeanServer. The new MBeanServer must register * this MBean in its MBean repository. * @param instantiator The MBeanInstantiator that will be used to * instantiate MBeans and take care of class loading issues. * @param repository The repository to use for this MBeanServer. */ public DefaultMBeanServerInterceptor(MBeanServer outer, MBeanServerDelegate delegate, MBeanInstantiator instantiator, Repository repository) { if (outer == null) throw new IllegalArgumentException("outer MBeanServer cannot be null"); if (delegate == null) throw new IllegalArgumentException("MBeanServerDelegate cannot be null"); if (instantiator == null) throw new IllegalArgumentException("MBeanInstantiator cannot be null"); if (repository == null) throw new IllegalArgumentException("Repository cannot be null"); this.server = outer; this.delegate = delegate; this.instantiator = instantiator; this.repository = repository; this.domain = repository.getDefaultDomain(); } public ObjectInstance createMBean(String className, ObjectName name) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException { return createMBean(className, name, (Object[]) null, (String[]) null); } public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException { return createMBean(className, name, loaderName, (Object[]) null, (String[]) null); } public ObjectInstance createMBean(String className, ObjectName name, Object[] params, String[] signature) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException { try { return createMBean(className, name, null, true, params, signature); } catch (InstanceNotFoundException e) { /* Can only happen if loaderName doesn't exist, but we just passed null, so we shouldn't get this exception. */ throw EnvHelp.initCause( new IllegalArgumentException("Unexpected exception: " + e), e); } } public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Object[] params, String[] signature) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException { return createMBean(className, name, loaderName, false, params, signature); } private ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, boolean withDefaultLoaderRepository, Object[] params, String[] signature) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException { Class theClass; if (className == null) { final RuntimeException wrapped = new IllegalArgumentException("The class name cannot be null"); throw new RuntimeOperationsException(wrapped, "Exception occurred during MBean creation"); } if (name != null) { if (name.isPattern()) { final RuntimeException wrapped = new IllegalArgumentException("Invalid name->" + name.toString()); final String msg = "Exception occurred during MBean creation"; throw new RuntimeOperationsException(wrapped, msg); } name = nonDefaultDomain(name); } checkMBeanPermission(className, null, null, "instantiate"); checkMBeanPermission(className, null, name, "registerMBean"); /* Load the appropriate class. */ if (withDefaultLoaderRepository) { if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "ClassName = " + className + ", ObjectName = " + name); } theClass = instantiator.findClassWithDefaultLoaderRepository(className); } else if (loaderName == null) { if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "ClassName = " + className + ", ObjectName = " + name + ", Loader name = null"); } theClass = instantiator.findClass(className, server.getClass().getClassLoader()); } else { loaderName = nonDefaultDomain(loaderName); if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "ClassName = " + className + ", ObjectName = " + name + ", Loader name = " + loaderName); } theClass = instantiator.findClass(className, loaderName); } checkMBeanTrustPermission(theClass); // Check that the MBean can be instantiated by the MBeanServer. Introspector.testCreation(theClass); // Check the JMX MBean compliance of the class Introspector.checkCompliance(theClass); Object moi= instantiator.instantiate(theClass, params, signature, server.getClass().getClassLoader()); final String infoClassName = getNewMBeanClassName(moi); return registerObject(infoClassName, moi, name); } public ObjectInstance registerMBean(Object object, ObjectName name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { // ------------------------------ // ------------------------------ Class theClass = object.getClass(); Introspector.checkCompliance(theClass); final String infoClassName = getNewMBeanClassName(object); checkMBeanPermission(infoClassName, null, name, "registerMBean"); checkMBeanTrustPermission(theClass); return registerObject(infoClassName, object, name); } private static String getNewMBeanClassName(Object mbeanToRegister) throws NotCompliantMBeanException { if (mbeanToRegister instanceof DynamicMBean) { DynamicMBean mbean = (DynamicMBean) mbeanToRegister; final String name; try { name = mbean.getMBeanInfo().getClassName(); } catch (Exception e) { // Includes case where getMBeanInfo() returns null NotCompliantMBeanException ncmbe = new NotCompliantMBeanException("Bad getMBeanInfo()"); ncmbe.initCause(e); throw ncmbe; } if (name == null) { final String msg = "MBeanInfo has null class name"; throw new NotCompliantMBeanException(msg); } return name; } else return mbeanToRegister.getClass().getName(); } private final Set beingUnregistered = new HashSet(); public void unregisterMBean(ObjectName name) throws InstanceNotFoundException, MBeanRegistrationException { if (name == null) { final RuntimeException wrapped = new IllegalArgumentException("Object name cannot be null"); throw new RuntimeOperationsException(wrapped, "Exception occurred trying to unregister the MBean"); } name = nonDefaultDomain(name); /* The semantics of preDeregister are tricky. If it throws an exception, then the unregisterMBean fails. This allows an MBean to refuse to be unregistered. If it returns successfully, then the unregisterMBean can proceed. In this case the preDeregister may have cleaned up some state, and will not expect to be called a second time. So if two threads try to unregister the same MBean at the same time then one of them must wait for the other one to either (a) call preDeregister and get an exception or (b) call preDeregister successfully and unregister the MBean. Suppose thread T1 is unregistering an MBean and thread T2 is trying to unregister the same MBean, so waiting for T1. Then a deadlock is possible if the preDeregister for T1 ends up needing a lock held by T2. Given the semantics just described, there does not seem to be any way to avoid this. This will not happen to code where it is clear for any given MBean what thread may unregister that MBean. On the other hand we clearly do not want a thread that is unregistering MBean A to have to wait for another thread that is unregistering another MBean B (see bug 6318664). A deadlock in this situation could reasonably be considered gratuitous. So holding a global lock across the preDeregister call would be bad. So we have a set of ObjectNames that some thread is currently unregistering. When a thread wants to unregister a name, it must first check if the name is in the set, and if so it must wait. When a thread successfully unregisters a name it removes the name from the set and notifies any waiting threads that the set has changed. This implies that we must be very careful to ensure that the name is removed from the set and waiters notified, no matter what code path is taken. */ synchronized (beingUnregistered) { while (beingUnregistered.contains(name)) { try { beingUnregistered.wait(); } catch (InterruptedException e) { throw new MBeanRegistrationException(e, e.toString()); // pretend the exception came from preDeregister; // in another execution sequence it could have } } beingUnregistered.add(name); } try { exclusiveUnregisterMBean(name); } finally { synchronized (beingUnregistered) { beingUnregistered.remove(name); beingUnregistered.notifyAll(); } } } private void exclusiveUnregisterMBean(ObjectName name) throws InstanceNotFoundException, MBeanRegistrationException { DynamicMBean instance = getMBean(name); // may throw InstanceNotFoundException checkMBeanPermission(instance, null, name, "unregisterMBean"); if (instance instanceof MBeanRegistration) preDeregisterInvoke((MBeanRegistration) instance); final Object resource = getResource(instance); // Unregisters the MBean from the repository. // Returns the resource context that was used. // The returned context does nothing for regular MBeans. // For ClassLoader MBeans and JMXNamespace (and JMXDomain) // MBeans - the context makes it possible to unregister these // objects from the appropriate framework artifacts, such as // the CLR or the dispatcher, from within the repository lock. // In case of success, we also need to call context.done() at the // end of this method. // final ResourceContext context = unregisterFromRepository(resource, instance, name); try { if (instance instanceof MBeanRegistration) postDeregisterInvoke(name,(MBeanRegistration) instance); } finally { context.done(); } } public ObjectInstance getObjectInstance(ObjectName name) throws InstanceNotFoundException { name = nonDefaultDomain(name); DynamicMBean instance = getMBean(name); checkMBeanPermission(instance, null, name, "getObjectInstance"); final String className = getClassName(instance); return new ObjectInstance(name, className); } public Set queryMBeans(ObjectName name, QueryExp query) { @SuppressWarnings("removal") SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Check if the caller has the right to invoke 'queryMBeans' // checkMBeanPermission((String) null, null, null, "queryMBeans"); // Perform query without "query". // Set list = queryMBeansImpl(name, null); // Check if the caller has the right to invoke 'queryMBeans' // on each specific classname/objectname in the list. // Set allowedList = new HashSet(list.size()); for (ObjectInstance oi : list) { try { checkMBeanPermission(oi.getClassName(), null, oi.getObjectName(), "queryMBeans"); allowedList.add(oi); } catch (SecurityException e) { // OK: Do not add this ObjectInstance to the list } } // Apply query to allowed MBeans only. // return filterListOfObjectInstances(allowedList, query); } else { // Perform query. // return queryMBeansImpl(name, query); } } private Set queryMBeansImpl(ObjectName name, QueryExp query) { // Query the MBeans on the repository // Set list = repository.query(name, query); return (objectInstancesFromFilteredNamedObjects(list, query)); } public Set queryNames(ObjectName name, QueryExp query) { Set queryList; @SuppressWarnings("removal") SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Check if the caller has the right to invoke 'queryNames' // checkMBeanPermission((String) null, null, null, "queryNames"); // Perform query without "query". // Set list = queryMBeansImpl(name, null); // Check if the caller has the right to invoke 'queryNames' // on each specific classname/objectname in the list. // Set allowedList = new HashSet(list.size()); for (ObjectInstance oi : list) { try { checkMBeanPermission(oi.getClassName(), null, oi.getObjectName(), "queryNames"); allowedList.add(oi); } catch (SecurityException e) { // OK: Do not add this ObjectInstance to the list } } // Apply query to allowed MBeans only. // Set queryObjectInstanceList = filterListOfObjectInstances(allowedList, query); queryList = new HashSet(queryObjectInstanceList.size()); for (ObjectInstance oi : queryObjectInstanceList) { queryList.add(oi.getObjectName()); } } else { // Perform query. // queryList = queryNamesImpl(name, query); } return queryList; } private Set queryNamesImpl(ObjectName name, QueryExp query) { // Query the MBeans on the repository // Set list = repository.query(name, query); return (objectNamesFromFilteredNamedObjects(list, query)); } public boolean isRegistered(ObjectName name) { if (name == null) { throw new RuntimeOperationsException( new IllegalArgumentException("Object name cannot be null"), "Object name cannot be null"); } name = nonDefaultDomain(name); /* No Permission check */ // isRegistered is always unchecked as per JMX spec. return (repository.contains(name)); } public String[] getDomains() { @SuppressWarnings("removal") SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Check if the caller has the right to invoke 'getDomains' // checkMBeanPermission((String) null, null, null, "getDomains"); // Return domains // String[] domains = repository.getDomains(); // Check if the caller has the right to invoke 'getDomains' // on each specific domain in the list. // List result = new ArrayList(domains.length); for (int i = 0; i < domains.length; i++) { try { ObjectName dom = Util.newObjectName(domains[i] + ":x=x"); checkMBeanPermission((String) null, null, dom, "getDomains"); result.add(domains[i]); } catch (SecurityException e) { // OK: Do not add this domain to the list } } // Make an array from result. // return result.toArray(new String[result.size()]); } else { return repository.getDomains(); } } public Integer getMBeanCount() { return (repository.getCount()); } public Object getAttribute(ObjectName name, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException { if (name == null) { throw new RuntimeOperationsException(new IllegalArgumentException("Object name cannot be null"), "Exception occurred trying to invoke the getter on the MBean"); } if (attribute == null) { throw new RuntimeOperationsException(new IllegalArgumentException("Attribute cannot be null"), "Exception occurred trying to invoke the getter on the MBean"); } name = nonDefaultDomain(name); if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "Attribute = " + attribute + ", ObjectName = " + name); } final DynamicMBean instance = getMBean(name); checkMBeanPermission(instance, attribute, name, "getAttribute"); try { return instance.getAttribute(attribute); } catch (AttributeNotFoundException e) { throw e; } catch (Throwable t) { rethrowMaybeMBeanException(t); throw new AssertionError(); // not reached } } public AttributeList getAttributes(ObjectName name, String[] attributes) throws InstanceNotFoundException, ReflectionException { if (name == null) { throw new RuntimeOperationsException(new IllegalArgumentException("ObjectName name cannot be null"), "Exception occurred trying to invoke the getter on the MBean"); } if (attributes == null) { throw new RuntimeOperationsException(new IllegalArgumentException("Attributes cannot be null"), "Exception occurred trying to invoke the getter on the MBean"); } name = nonDefaultDomain(name); if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "ObjectName = " + name); } final DynamicMBean instance = getMBean(name); final String[] allowedAttributes; @SuppressWarnings("removal") final SecurityManager sm = System.getSecurityManager(); if (sm == null) allowedAttributes = attributes; else { final String classname = getClassName(instance); // Check if the caller has the right to invoke 'getAttribute' // checkMBeanPermission(classname, null, name, "getAttribute"); // Check if the caller has the right to invoke 'getAttribute' // on each specific attribute // List allowedList = new ArrayList(attributes.length); for (String attr : attributes) { try { checkMBeanPermission(classname, attr, name, "getAttribute"); allowedList.add(attr); } catch (SecurityException e) { // OK: Do not add this attribute to the list } } allowedAttributes = allowedList.toArray(new String[allowedList.size()]); } try { return instance.getAttributes(allowedAttributes); } catch (Throwable t) { rethrow(t); throw new AssertionError(); } } public void setAttribute(ObjectName name, Attribute attribute) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { if (name == null) { throw new RuntimeOperationsException(new IllegalArgumentException("ObjectName name cannot be null"), "Exception occurred trying to invoke the setter on the MBean"); } if (attribute == null) { throw new RuntimeOperationsException(new IllegalArgumentException("Attribute cannot be null"), "Exception occurred trying to invoke the setter on the MBean"); } name = nonDefaultDomain(name); if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "ObjectName = " + name + ", Attribute = " + attribute.getName()); } DynamicMBean instance = getMBean(name); checkMBeanPermission(instance, attribute.getName(), name, "setAttribute"); try { instance.setAttribute(attribute); } catch (AttributeNotFoundException e) { throw e; } catch (InvalidAttributeValueException e) { throw e; } catch (Throwable t) { rethrowMaybeMBeanException(t); throw new AssertionError(); } } public AttributeList setAttributes(ObjectName name, AttributeList attributes) throws InstanceNotFoundException, ReflectionException { if (name == null) { throw new RuntimeOperationsException(new IllegalArgumentException("ObjectName name cannot be null"), "Exception occurred trying to invoke the setter on the MBean"); } if (attributes == null) { throw new RuntimeOperationsException(new IllegalArgumentException("AttributeList cannot be null"), "Exception occurred trying to invoke the setter on the MBean"); } name = nonDefaultDomain(name); final DynamicMBean instance = getMBean(name); final AttributeList allowedAttributes; @SuppressWarnings("removal") final SecurityManager sm = System.getSecurityManager(); if (sm == null) allowedAttributes = attributes; else { String classname = getClassName(instance); // Check if the caller has the right to invoke 'setAttribute' // checkMBeanPermission(classname, null, name, "setAttribute"); // Check if the caller has the right to invoke 'setAttribute' // on each specific attribute // allowedAttributes = new AttributeList(attributes.size()); for (Attribute attribute : attributes.asList()) { try { checkMBeanPermission(classname, attribute.getName(), name, "setAttribute"); allowedAttributes.add(attribute); } catch (SecurityException e) { // OK: Do not add this attribute to the list } } } try { return instance.setAttributes(allowedAttributes); } catch (Throwable t) { rethrow(t); throw new AssertionError(); } } public Object invoke(ObjectName name, String operationName, Object params[], String signature[]) throws InstanceNotFoundException, MBeanException, ReflectionException { name = nonDefaultDomain(name); DynamicMBean instance = getMBean(name); checkMBeanPermission(instance, operationName, name, "invoke"); try { return instance.invoke(operationName, params, signature); } catch (Throwable t) { rethrowMaybeMBeanException(t); throw new AssertionError(); } } /* Centralize some of the tedious exception wrapping demanded by the JMX spec. */ private static void rethrow(Throwable t) throws ReflectionException { try { throw t; } catch (ReflectionException e) { throw e; } catch (RuntimeOperationsException e) { throw e; } catch (RuntimeErrorException e) { throw e; } catch (RuntimeException e) { throw new RuntimeMBeanException(e, e.toString()); } catch (Error e) { throw new RuntimeErrorException(e, e.toString()); } catch (Throwable t2) { // should not happen throw new RuntimeException("Unexpected exception", t2); } } private static void rethrowMaybeMBeanException(Throwable t) throws ReflectionException, MBeanException { if (t instanceof MBeanException) throw (MBeanException) t; rethrow(t); } /** * Register object in the repository, with the * given name. * This method is called by the various createMBean() flavours * and by registerMBean() after all MBean compliance tests * have been performed. *

* This method does not performed any kind of test compliance, * and the caller should make sure that the given object * is MBean compliant. *

* This methods performed all the basic steps needed for object * registration: *

    *
  • If the object implements the MBeanRegistration * interface, it invokes preRegister() on the object.
  • *
  • Then the object is added to the repository with the given * name.
  • *
  • Finally, if the object implements the * MBeanRegistration interface, it invokes postRegister() * on the object.
  • *
* @param object A reference to a MBean compliant object. * @param name The ObjectName of the object MBean. * @return the actual ObjectName with which the object was registered. * @exception InstanceAlreadyExistsException if an object is already * registered with that name. * @exception MBeanRegistrationException if an exception occurs during * registration. **/ private ObjectInstance registerObject(String classname, Object object, ObjectName name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { if (object == null) { final RuntimeException wrapped = new IllegalArgumentException("Cannot add null object"); throw new RuntimeOperationsException(wrapped, "Exception occurred trying to register the MBean"); } DynamicMBean mbean = Introspector.makeDynamicMBean(object); return registerDynamicMBean(classname, mbean, name); } private ObjectInstance registerDynamicMBean(String classname, DynamicMBean mbean, ObjectName name) throws InstanceAlreadyExistsException, MBeanRegistrationException, NotCompliantMBeanException { name = nonDefaultDomain(name); if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "ObjectName = " + name); } ObjectName logicalName = preRegister(mbean, server, name); // preRegister returned successfully, so from this point on we // must call postRegister(false) if there is any problem. boolean registered = false; boolean registerFailed = false; ResourceContext context = null; try { if (mbean instanceof DynamicMBean2) { try { ((DynamicMBean2) mbean).preRegister2(server, logicalName); registerFailed = true; // until we succeed } catch (Exception e) { if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof InstanceAlreadyExistsException) throw (InstanceAlreadyExistsException) e; throw new RuntimeException(e); } } if (logicalName != name && logicalName != null) { logicalName = ObjectName.getInstance(nonDefaultDomain(logicalName)); } checkMBeanPermission(classname, null, logicalName, "registerMBean"); if (logicalName == null) { final RuntimeException wrapped = new IllegalArgumentException("No object name specified"); throw new RuntimeOperationsException(wrapped, "Exception occurred trying to register the MBean"); } final Object resource = getResource(mbean); // Register the MBean with the repository. // Returns the resource context that was used. // The returned context does nothing for regular MBeans. // For ClassLoader MBeans the context makes it possible to register these // objects with the appropriate framework artifacts, such as // the CLR, from within the repository lock. // In case of success, we also need to call context.done() at the // end of this method. // context = registerWithRepository(resource, mbean, logicalName); registerFailed = false; registered = true; } finally { try { postRegister(logicalName, mbean, registered, registerFailed); } finally { if (registered && context!=null) context.done(); } } return new ObjectInstance(logicalName, classname); } private static void throwMBeanRegistrationException(Throwable t, String where) throws MBeanRegistrationException { if (t instanceof RuntimeException) { throw new RuntimeMBeanException((RuntimeException)t, "RuntimeException thrown " + where); } else if (t instanceof Error) { throw new RuntimeErrorException((Error)t, "Error thrown " + where); } else if (t instanceof MBeanRegistrationException) { throw (MBeanRegistrationException)t; } else if (t instanceof Exception) { throw new MBeanRegistrationException((Exception)t, "Exception thrown " + where); } else // neither Error nor Exception?? throw new RuntimeException(t); } private static ObjectName preRegister( DynamicMBean mbean, MBeanServer mbs, ObjectName name) throws InstanceAlreadyExistsException, MBeanRegistrationException { ObjectName newName = null; try { if (mbean instanceof MBeanRegistration) newName = ((MBeanRegistration) mbean).preRegister(mbs, name); } catch (Throwable t) { throwMBeanRegistrationException(t, "in preRegister method"); } if (newName != null) return newName; else return name; } private static void postRegister( ObjectName logicalName, DynamicMBean mbean, boolean registrationDone, boolean registerFailed) { if (registerFailed && mbean instanceof DynamicMBean2) ((DynamicMBean2) mbean).registerFailed(); try { if (mbean instanceof MBeanRegistration) ((MBeanRegistration) mbean).postRegister(registrationDone); } catch (RuntimeException e) { MBEANSERVER_LOGGER.log(Level.DEBUG, "While registering MBean ["+logicalName+ "]: " + "Exception thrown by postRegister: " + "rethrowing <"+e+">, but keeping the MBean registered"); throw new RuntimeMBeanException(e, "RuntimeException thrown in postRegister method: "+ "rethrowing <"+e+">, but keeping the MBean registered"); } catch (Error er) { MBEANSERVER_LOGGER.log(Level.DEBUG, "While registering MBean ["+logicalName+ "]: " + "Error thrown by postRegister: " + "rethrowing <"+er+">, but keeping the MBean registered"); throw new RuntimeErrorException(er, "Error thrown in postRegister method: "+ "rethrowing <"+er+">, but keeping the MBean registered"); } } private static void preDeregisterInvoke(MBeanRegistration moi) throws MBeanRegistrationException { try { moi.preDeregister(); } catch (Throwable t) { throwMBeanRegistrationException(t, "in preDeregister method"); } } private static void postDeregisterInvoke(ObjectName mbean, MBeanRegistration moi) { try { moi.postDeregister(); } catch (RuntimeException e) { MBEANSERVER_LOGGER.log(Level.DEBUG, "While unregistering MBean ["+mbean+ "]: " + "Exception thrown by postDeregister: " + "rethrowing <"+e+">, although the MBean is succesfully " + "unregistered"); throw new RuntimeMBeanException(e, "RuntimeException thrown in postDeregister method: "+ "rethrowing <"+e+ ">, although the MBean is sucessfully unregistered"); } catch (Error er) { MBEANSERVER_LOGGER.log(Level.DEBUG, "While unregistering MBean ["+mbean+ "]: " + "Error thrown by postDeregister: " + "rethrowing <"+er+">, although the MBean is succesfully " + "unregistered"); throw new RuntimeErrorException(er, "Error thrown in postDeregister method: "+ "rethrowing <"+er+ ">, although the MBean is sucessfully unregistered"); } } /** * Gets a specific MBean controlled by the DefaultMBeanServerInterceptor. * The name must have a non-default domain. */ private DynamicMBean getMBean(ObjectName name) throws InstanceNotFoundException { if (name == null) { throw new RuntimeOperationsException(new IllegalArgumentException("Object name cannot be null"), "Exception occurred trying to get an MBean"); } DynamicMBean obj = repository.retrieve(name); if (obj == null) { if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, name + " : Found no object"); } throw new InstanceNotFoundException(name.toString()); } return obj; } private static Object getResource(DynamicMBean mbean) { if (mbean instanceof DynamicMBean2) return ((DynamicMBean2) mbean).getResource(); else return mbean; } private ObjectName nonDefaultDomain(ObjectName name) { if (name == null || name.getDomain().length() > 0) return name; /* The ObjectName looks like ":a=b", and that's what its toString() will return in this implementation. So we can just stick the default domain in front of it to get a non-default-domain name. We depend on the fact that toString() works like that and that it leaves wildcards in place (so we can detect an error if one is supplied where it shouldn't be). */ final String completeName = domain + name; return Util.newObjectName(completeName); } public String getDefaultDomain() { return domain; } /* * Notification handling. * * This is not trivial, because the MBeanServer translates the * source of a received notification from a reference to an MBean * into the ObjectName of that MBean. While that does make * notification sending easier for MBean writers, it comes at a * considerable cost. We need to replace the source of a * notification, which is basically wrong if there are also * listeners registered directly with the MBean (without going * through the MBean server). We also need to wrap the listener * supplied by the client of the MBeanServer with a listener that * performs the substitution before forwarding. This is why we * strongly discourage people from putting MBean references in the * source of their notifications. Instead they should arrange to * put the ObjectName there themselves. * * However, existing code relies on the substitution, so we are * stuck with it. * * Here's how we handle it. When you add a listener, we make a * ListenerWrapper around it. We look that up in the * listenerWrappers map, and if there was already a wrapper for * that listener with the given ObjectName, we reuse it. This map * is a WeakHashMap, so a listener that is no longer registered * with any MBean can be garbage collected. * * We cannot use simpler solutions such as always creating a new * wrapper or always registering the same listener with the MBean * and using the handback to find the client's original listener. * The reason is that we need to support the removeListener * variant that removes all (listener,filter,handback) triples on * a broadcaster that have a given listener. And we do not have * any way to inspect a broadcaster's internal list of triples. * So the same client listener must always map to the same * listener registered with the broadcaster. * * Another possible solution would be to map from ObjectName to * list of listener wrappers (or IdentityHashMap of listener * wrappers), making this list the first time a listener is added * on a given MBean, and removing it when the MBean is removed. * This is probably more costly in memory, but could be useful if * some day we don't want to rely on weak references. */ public void addNotificationListener(ObjectName name, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException { // ------------------------------ // ------------------------------ if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "ObjectName = " + name); } DynamicMBean instance = getMBean(name); checkMBeanPermission(instance, null, name, "addNotificationListener"); NotificationBroadcaster broadcaster = getNotificationBroadcaster(name, instance, NotificationBroadcaster.class); // ------------------ // Check listener // ------------------ if (listener == null) { throw new RuntimeOperationsException(new IllegalArgumentException("Null listener"),"Null listener"); } NotificationListener listenerWrapper = getListenerWrapper(listener, name, instance, true); broadcaster.addNotificationListener(listenerWrapper, filter, handback); } public void addNotificationListener(ObjectName name, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException { // ------------------------------ // ------------------------------ // ---------------- // Get listener object // ---------------- DynamicMBean instance = getMBean(listener); Object resource = getResource(instance); if (!(resource instanceof NotificationListener)) { throw new RuntimeOperationsException(new IllegalArgumentException(listener.getCanonicalName()), "The MBean " + listener.getCanonicalName() + " does not implement the NotificationListener interface") ; } // ---------------- // Add a listener on an MBean // ---------------- if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "ObjectName = " + name + ", Listener = " + listener); } server.addNotificationListener(name,(NotificationListener) resource, filter, handback) ; } public void removeNotificationListener(ObjectName name, NotificationListener listener) throws InstanceNotFoundException, ListenerNotFoundException { removeNotificationListener(name, listener, null, null, true); } public void removeNotificationListener(ObjectName name, NotificationListener listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException { removeNotificationListener(name, listener, filter, handback, false); } public void removeNotificationListener(ObjectName name, ObjectName listener) throws InstanceNotFoundException, ListenerNotFoundException { NotificationListener instance = getListener(listener); if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "ObjectName = " + name + ", Listener = " + listener); } server.removeNotificationListener(name, instance); } public void removeNotificationListener(ObjectName name, ObjectName listener, NotificationFilter filter, Object handback) throws InstanceNotFoundException, ListenerNotFoundException { NotificationListener instance = getListener(listener); if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "ObjectName = " + name + ", Listener = " + listener); } server.removeNotificationListener(name, instance, filter, handback); } private NotificationListener getListener(ObjectName listener) throws ListenerNotFoundException { // ---------------- // Get listener object // ---------------- DynamicMBean instance; try { instance = getMBean(listener); } catch (InstanceNotFoundException e) { throw EnvHelp.initCause( new ListenerNotFoundException(e.getMessage()), e); } Object resource = getResource(instance); if (!(resource instanceof NotificationListener)) { final RuntimeException exc = new IllegalArgumentException(listener.getCanonicalName()); final String msg = "MBean " + listener.getCanonicalName() + " does not " + "implement " + NotificationListener.class.getName(); throw new RuntimeOperationsException(exc, msg); } return (NotificationListener) resource; } private void removeNotificationListener(ObjectName name, NotificationListener listener, NotificationFilter filter, Object handback, boolean removeAll) throws InstanceNotFoundException, ListenerNotFoundException { if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "ObjectName = " + name); } DynamicMBean instance = getMBean(name); checkMBeanPermission(instance, null, name, "removeNotificationListener"); /* We could simplify the code by assigning broadcaster after assigning listenerWrapper, but that would change the error behavior when both the broadcaster and the listener are erroneous. */ Class reqClass = removeAll ? NotificationBroadcaster.class : NotificationEmitter.class; NotificationBroadcaster broadcaster = getNotificationBroadcaster(name, instance, reqClass); NotificationListener listenerWrapper = getListenerWrapper(listener, name, instance, false); if (listenerWrapper == null) throw new ListenerNotFoundException("Unknown listener"); if (removeAll) broadcaster.removeNotificationListener(listenerWrapper); else { NotificationEmitter emitter = (NotificationEmitter) broadcaster; emitter.removeNotificationListener(listenerWrapper, filter, handback); } } private static T getNotificationBroadcaster(ObjectName name, Object instance, Class reqClass) { if (reqClass.isInstance(instance)) return reqClass.cast(instance); if (instance instanceof DynamicMBean2) instance = ((DynamicMBean2) instance).getResource(); if (reqClass.isInstance(instance)) return reqClass.cast(instance); final RuntimeException exc = new IllegalArgumentException(name.getCanonicalName()); final String msg = "MBean " + name.getCanonicalName() + " does not " + "implement " + reqClass.getName(); throw new RuntimeOperationsException(exc, msg); } public MBeanInfo getMBeanInfo(ObjectName name) throws InstanceNotFoundException, IntrospectionException, ReflectionException { // ------------------------------ // ------------------------------ DynamicMBean moi = getMBean(name); final MBeanInfo mbi; try { mbi = moi.getMBeanInfo(); } catch (RuntimeMBeanException e) { throw e; } catch (RuntimeErrorException e) { throw e; } catch (RuntimeException e) { throw new RuntimeMBeanException(e, "getMBeanInfo threw RuntimeException"); } catch (Error e) { throw new RuntimeErrorException(e, "getMBeanInfo threw Error"); } if (mbi == null) throw new JMRuntimeException("MBean " + name + "has no MBeanInfo"); checkMBeanPermission(mbi.getClassName(), null, name, "getMBeanInfo"); return mbi; } public boolean isInstanceOf(ObjectName name, String className) throws InstanceNotFoundException { final DynamicMBean instance = getMBean(name); checkMBeanPermission(instance, null, name, "isInstanceOf"); try { Object resource = getResource(instance); final String resourceClassName = (resource instanceof DynamicMBean) ? getClassName((DynamicMBean) resource) : resource.getClass().getName(); if (resourceClassName.equals(className)) return true; final ClassLoader cl = resource.getClass().getClassLoader(); final Class classNameClass = Class.forName(className, false, cl); if (classNameClass.isInstance(resource)) return true; final Class resourceClass = Class.forName(resourceClassName, false, cl); return classNameClass.isAssignableFrom(resourceClass); } catch (Exception x) { /* Could be SecurityException or ClassNotFoundException */ if (MBEANSERVER_LOGGER.isLoggable(Level.DEBUG)) { MBEANSERVER_LOGGER.log(Level.DEBUG, "Exception calling isInstanceOf", x); } return false; } } /** *

Return the {@link java.lang.ClassLoader} that was used for * loading the class of the named MBean. * @param mbeanName The ObjectName of the MBean. * @return The ClassLoader used for that MBean. * @exception InstanceNotFoundException if the named MBean is not found. */ public ClassLoader getClassLoaderFor(ObjectName mbeanName) throws InstanceNotFoundException { DynamicMBean instance = getMBean(mbeanName); checkMBeanPermission(instance, null, mbeanName, "getClassLoaderFor"); return getResource(instance).getClass().getClassLoader(); } /** *

Return the named {@link java.lang.ClassLoader}. * @param loaderName The ObjectName of the ClassLoader. * @return The named ClassLoader. * @exception InstanceNotFoundException if the named ClassLoader * is not found. */ public ClassLoader getClassLoader(ObjectName loaderName) throws InstanceNotFoundException { if (loaderName == null) { checkMBeanPermission((String) null, null, null, "getClassLoader"); return server.getClass().getClassLoader(); } DynamicMBean instance = getMBean(loaderName); checkMBeanPermission(instance, null, loaderName, "getClassLoader"); Object resource = getResource(instance); /* Check if the given MBean is a ClassLoader */ if (!(resource instanceof ClassLoader)) throw new InstanceNotFoundException(loaderName.toString() + " is not a classloader"); return (ClassLoader) resource; } /** * Sends an MBeanServerNotifications with the specified type for the * MBean with the specified ObjectName */ private void sendNotification(String NotifType, ObjectName name) { // ------------------------------ // ------------------------------ // --------------------- // Create notification // --------------------- MBeanServerNotification notif = new MBeanServerNotification( NotifType,MBeanServerDelegate.DELEGATE_NAME,0,name); if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, NotifType + " " + name); } delegate.sendNotification(notif); } /** * Applies the specified queries to the set of NamedObjects. */ private Set objectNamesFromFilteredNamedObjects(Set list, QueryExp query) { Set result = new HashSet(); // No query ... if (query == null) { for (NamedObject no : list) { result.add(no.getName()); } } else { // Access the filter final MBeanServer oldServer = QueryEval.getMBeanServer(); query.setMBeanServer(server); try { for (NamedObject no : list) { boolean res; try { res = query.apply(no.getName()); } catch (Exception e) { res = false; } if (res) { result.add(no.getName()); } } } finally { /* * query.setMBeanServer is probably * QueryEval.setMBeanServer so put back the old * value. Since that method uses a ThreadLocal * variable, this code is only needed for the * unusual case where the user creates a custom * QueryExp that calls a nested query on another * MBeanServer. */ query.setMBeanServer(oldServer); } } return result; } /** * Applies the specified queries to the set of NamedObjects. */ private Set objectInstancesFromFilteredNamedObjects(Set list, QueryExp query) { Set result = new HashSet(); // No query ... if (query == null) { for (NamedObject no : list) { final DynamicMBean obj = no.getObject(); final String className = safeGetClassName(obj); result.add(new ObjectInstance(no.getName(), className)); } } else { // Access the filter MBeanServer oldServer = QueryEval.getMBeanServer(); query.setMBeanServer(server); try { for (NamedObject no : list) { final DynamicMBean obj = no.getObject(); boolean res; try { res = query.apply(no.getName()); } catch (Exception e) { res = false; } if (res) { String className = safeGetClassName(obj); result.add(new ObjectInstance(no.getName(), className)); } } } finally { /* * query.setMBeanServer is probably * QueryEval.setMBeanServer so put back the old * value. Since that method uses a ThreadLocal * variable, this code is only needed for the * unusual case where the user creates a custom * QueryExp that calls a nested query on another * MBeanServer. */ query.setMBeanServer(oldServer); } } return result; } private static String safeGetClassName(DynamicMBean mbean) { try { return getClassName(mbean); } catch (Exception e) { if (MBEANSERVER_LOGGER.isLoggable(Level.DEBUG)) { MBEANSERVER_LOGGER.log(Level.DEBUG, "Exception getting MBean class name", e); } return null; } } /** * Applies the specified queries to the set of ObjectInstances. */ private Set filterListOfObjectInstances(Set list, QueryExp query) { // Null query. // if (query == null) { return list; } else { Set result = new HashSet(); // Access the filter. // for (ObjectInstance oi : list) { boolean res = false; MBeanServer oldServer = QueryEval.getMBeanServer(); query.setMBeanServer(server); try { res = query.apply(oi.getObjectName()); } catch (Exception e) { res = false; } finally { /* * query.setMBeanServer is probably * QueryEval.setMBeanServer so put back the old * value. Since that method uses a ThreadLocal * variable, this code is only needed for the * unusual case where the user creates a custom * QueryExp that calls a nested query on another * MBeanServer. */ query.setMBeanServer(oldServer); } if (res) { result.add(oi); } } return result; } } /* * Get the existing wrapper for this listener, name, and mbean, if * there is one. Otherwise, if "create" is true, create and * return one. Otherwise, return null. * * We use a WeakHashMap so that if the only reference to a user * listener is in listenerWrappers, it can be garbage collected. * This requires a certain amount of care, because only the key in * a WeakHashMap is weak; the value is strong. We need to recover * the existing wrapper object (not just an object that is equal * to it), so we would like listenerWrappers to map any * ListenerWrapper to the canonical ListenerWrapper for that * (listener,name,mbean) set. But we do not want this canonical * wrapper to be referenced strongly. Therefore we put it inside * a WeakReference and that is the value in the WeakHashMap. */ private NotificationListener getListenerWrapper(NotificationListener l, ObjectName name, DynamicMBean mbean, boolean create) { Object resource = getResource(mbean); ListenerWrapper wrapper = new ListenerWrapper(l, name, resource); synchronized (listenerWrappers) { WeakReference ref = listenerWrappers.get(wrapper); if (ref != null) { NotificationListener existing = ref.get(); if (existing != null) return existing; } if (create) { ref = new WeakReference(wrapper); listenerWrappers.put(wrapper, ref); return wrapper; } else return null; } } public Object instantiate(String className) throws ReflectionException, MBeanException { throw new UnsupportedOperationException("Not supported yet."); } public Object instantiate(String className, ObjectName loaderName) throws ReflectionException, MBeanException, InstanceNotFoundException { throw new UnsupportedOperationException("Not supported yet."); } public Object instantiate(String className, Object[] params, String[] signature) throws ReflectionException, MBeanException { throw new UnsupportedOperationException("Not supported yet."); } public Object instantiate(String className, ObjectName loaderName, Object[] params, String[] signature) throws ReflectionException, MBeanException, InstanceNotFoundException { throw new UnsupportedOperationException("Not supported yet."); } public ClassLoaderRepository getClassLoaderRepository() { throw new UnsupportedOperationException("Not supported yet."); } private static class ListenerWrapper implements NotificationListener { ListenerWrapper(NotificationListener l, ObjectName name, Object mbean) { this.listener = l; this.name = name; this.mbean = mbean; } public void handleNotification(Notification notification, Object handback) { if (notification != null) { if (notification.getSource() == mbean) notification.setSource(name); } /* * Listeners are not supposed to throw exceptions. If * this one does, we could remove it from the MBean. It * might indicate that a connector has stopped working, * for instance, and there is no point in sending future * notifications over that connection. However, this * seems rather drastic, so instead we propagate the * exception and let the broadcaster handle it. */ listener.handleNotification(notification, handback); } @Override public boolean equals(Object o) { if (!(o instanceof ListenerWrapper)) return false; ListenerWrapper w = (ListenerWrapper) o; return (w.listener == listener && w.mbean == mbean && w.name.equals(name)); /* * We compare all three, in case the same MBean object * gets unregistered and then reregistered under a * different name, or the same name gets assigned to two * different MBean objects at different times. We do the * comparisons in this order to avoid the slow * ObjectName.equals when possible. */ } @Override public int hashCode() { return (System.identityHashCode(listener) ^ System.identityHashCode(mbean)); /* * We do not include name.hashCode() in the hash because * computing it is slow and usually we will not have two * instances of ListenerWrapper with the same mbean but * different ObjectNames. That can happen if the MBean is * unregistered from one name and reregistered with * another, and there is no garbage collection between; or * if the same object is registered under two names (which * is not recommended because MBeanRegistration will * break). But even in these unusual cases the hash code * does not have to be unique. */ } private NotificationListener listener; private ObjectName name; private Object mbean; } // SECURITY CHECKS //---------------- private static String getClassName(DynamicMBean mbean) { if (mbean instanceof DynamicMBean2) return ((DynamicMBean2) mbean).getClassName(); else return mbean.getMBeanInfo().getClassName(); } private static void checkMBeanPermission(DynamicMBean mbean, String member, ObjectName objectName, String actions) { @SuppressWarnings("removal") SecurityManager sm = System.getSecurityManager(); if (sm != null) { checkMBeanPermission(safeGetClassName(mbean), member, objectName, actions); } } private static void checkMBeanPermission(String classname, String member, ObjectName objectName, String actions) { @SuppressWarnings("removal") SecurityManager sm = System.getSecurityManager(); if (sm != null) { Permission perm = new MBeanPermission(classname, member, objectName, actions); sm.checkPermission(perm); } } private static void checkMBeanTrustPermission(final Class theClass) throws SecurityException { @SuppressWarnings("removal") SecurityManager sm = System.getSecurityManager(); if (sm != null) { Permission perm = new MBeanTrustPermission("register"); PrivilegedAction act = new PrivilegedAction() { public ProtectionDomain run() { return theClass.getProtectionDomain(); } }; @SuppressWarnings("removal") ProtectionDomain pd = AccessController.doPrivileged(act); @SuppressWarnings("removal") AccessControlContext acc = new AccessControlContext(new ProtectionDomain[] { pd }); sm.checkPermission(perm, acc); } } // ------------------------------------------------------------------ // // Dealing with registration of special MBeans in the repository. // // ------------------------------------------------------------------ /** * A RegistrationContext that makes it possible to perform additional * post registration actions (or post unregistration actions) outside * of the repository lock, once postRegister (or postDeregister) has * been called. * The method {@code done()} will be called in registerMBean or * unregisterMBean, at the end. */ private static interface ResourceContext extends RegistrationContext { public void done(); /** An empty ResourceContext which does nothing **/ public static final ResourceContext NONE = new ResourceContext() { public void done() {} public void registering() {} public void unregistered() {} }; } /** * Adds a MBean in the repository, * sends MBeanServerNotification.REGISTRATION_NOTIFICATION, * returns ResourceContext for special resources such as ClassLoaders * or JMXNamespaces. For regular MBean this method returns * ResourceContext.NONE. * @return a ResourceContext for special resources such as ClassLoaders * or JMXNamespaces. */ private ResourceContext registerWithRepository( final Object resource, final DynamicMBean object, final ObjectName logicalName) throws InstanceAlreadyExistsException, MBeanRegistrationException { // Creates a registration context, if needed. // final ResourceContext context = makeResourceContextFor(resource, logicalName); repository.addMBean(object, logicalName, context); // May throw InstanceAlreadyExistsException // --------------------- // Send create event // --------------------- if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "Send create notification of object " + logicalName.getCanonicalName()); } sendNotification( MBeanServerNotification.REGISTRATION_NOTIFICATION, logicalName); return context; } /** * Removes a MBean in the repository, * sends MBeanServerNotification.UNREGISTRATION_NOTIFICATION, * returns ResourceContext for special resources such as ClassLoaders * or JMXNamespaces, or null. For regular MBean this method returns * ResourceContext.NONE. * * @return a ResourceContext for special resources such as ClassLoaders * or JMXNamespaces. */ private ResourceContext unregisterFromRepository( final Object resource, final DynamicMBean object, final ObjectName logicalName) throws InstanceNotFoundException { // Creates a registration context, if needed. // final ResourceContext context = makeResourceContextFor(resource, logicalName); repository.remove(logicalName, context); // --------------------- // Send deletion event // --------------------- if (MBEANSERVER_LOGGER.isLoggable(Level.TRACE)) { MBEANSERVER_LOGGER.log(Level.TRACE, "Send delete notification of object " + logicalName.getCanonicalName()); } sendNotification(MBeanServerNotification.UNREGISTRATION_NOTIFICATION, logicalName); return context; } /** * Registers a ClassLoader with the CLR. * This method is called by the ResourceContext from within the * repository lock. * @param loader The ClassLoader. * @param logicalName The ClassLoader MBean ObjectName. */ private void addClassLoader(ClassLoader loader, final ObjectName logicalName) { /** * Called when the newly registered MBean is a ClassLoader * If so, tell the ClassLoaderRepository (CLR) about it. We do * this even if the loader is a PrivateClassLoader. In that * case, the CLR remembers the loader for use when it is * explicitly named (e.g. as the loader in createMBean) but * does not add it to the list that is consulted by * ClassLoaderRepository.loadClass. */ final ModifiableClassLoaderRepository clr = getInstantiatorCLR(); if (clr == null) { final RuntimeException wrapped = new IllegalArgumentException( "Dynamic addition of class loaders" + " is not supported"); throw new RuntimeOperationsException(wrapped, "Exception occurred trying to register" + " the MBean as a class loader"); } clr.addClassLoader(logicalName, loader); } /** * Unregisters a ClassLoader from the CLR. * This method is called by the ResourceContext from within the * repository lock. * @param loader The ClassLoader. * @param logicalName The ClassLoader MBean ObjectName. */ private void removeClassLoader(ClassLoader loader, final ObjectName logicalName) { /** * Removes the MBean from the default loader repository. */ if (loader != server.getClass().getClassLoader()) { final ModifiableClassLoaderRepository clr = getInstantiatorCLR(); if (clr != null) { clr.removeClassLoader(logicalName); } } } /** * Creates a ResourceContext for a ClassLoader MBean. * The resource context makes it possible to add the ClassLoader to * (ResourceContext.registering) or resp. remove the ClassLoader from * (ResourceContext.unregistered) the CLR * when the associated MBean is added to or resp. removed from the * repository. * * @param loader The ClassLoader MBean being registered or * unregistered. * @param logicalName The name of the ClassLoader MBean. * @return a ResourceContext that takes in charge the addition or removal * of the loader to or from the CLR. */ private ResourceContext createClassLoaderContext( final ClassLoader loader, final ObjectName logicalName) { return new ResourceContext() { public void registering() { addClassLoader(loader, logicalName); } public void unregistered() { removeClassLoader(loader, logicalName); } public void done() { } }; } /** * Creates a ResourceContext for the given resource. * If the resource does not need a ResourceContext, returns * ResourceContext.NONE. * At this time, only ClassLoaders need a ResourceContext. * * @param resource The resource being registered or unregistered. * @param logicalName The name of the associated MBean. * @return */ private ResourceContext makeResourceContextFor(Object resource, ObjectName logicalName) { if (resource instanceof ClassLoader) { return createClassLoaderContext((ClassLoader) resource, logicalName); } return ResourceContext.NONE; } @SuppressWarnings("removal") private ModifiableClassLoaderRepository getInstantiatorCLR() { return AccessController.doPrivileged(new PrivilegedAction() { @Override public ModifiableClassLoaderRepository run() { return instantiator != null ? instantiator.getClassLoaderRepository() : null; } }); } } public class empException extends Exception { public empException() { super(); } public empException(String error) { super(error); } } package com.coolslow.leetcode.topics.array; /** * 矩阵置零 * by MrThanksgiving */ public class Code73SetMatrixZeroes { /** *

     * 题目:
     *      给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。
     *
     * 示例 1:
     *      输入:
     *      [
     *        [1,1,1],
     *        [1,0,1],
     *        [1,1,1]
     *      ]
     *      输出:
     *      [
     *        [1,0,1],
     *        [0,0,0],
     *        [1,0,1]
     *      ]
     *
     * 示例 2:
     *      输入:
     *      [
     *        [0,1,2,0],
     *        [3,4,5,2],
     *        [1,3,1,5]
     *      ]
     *      输出:
     *      [
     *        [0,0,0,0],
     *        [0,4,5,0],
     *        [0,3,1,0]
     *      ]
     *
     * 进阶:
     *      一个直接的解决方案是使用  O(mn) 的额外空间,但这并不是一个好的解决方案。
     *      一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。
     *      你能想出一个常数空间的解决方案吗?
     *
     * 
*/ public void setZeroes(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return; int rc = matrix.length, cc = matrix[0].length; boolean flag = false; for (int i = 0; i < rc; i++) { if (matrix[i][0] == 0) flag = true; for (int j = 1; j < cc; j++) { if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } } } for (int i = 1; i < rc; i++) { for (int j = 1; j < cc; j++) { if (matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } } if (matrix[0][0] == 0) { for (int i = 0; i < cc; i++) { matrix[0][i] = 0; } } if (flag) { for (int i = 0; i < rc; i++) { matrix[i][0] = 0; } } } // 空间复杂度O(1), 利用表头行与表头列。 public void setZeroes2(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return; int[] row = new int[matrix.length]; int[] column = new int[matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (matrix[i][j] == 0) { row[i] = 1; column[j] = 1; } } } for (int i = 0; i < row.length; i++) { if (row[i] == 1) { for (int j = 0; j < matrix[0].length; j++) { matrix[i][j] = 0; } } } for (int i = 0; i < column.length; i++) { if (column[i] == 1) { for (int j = 0; j < matrix.length; j++) { matrix[j][i] = 0; } } } } // O(n*m) O(n+m) public void setZeroes3(int[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return; int[][] mark = new int[matrix.length][matrix[0].length]; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (matrix[i][j] == 0) { for (int k = 0; k < matrix[i].length; k++) { // row mark[i][k] = 1; } for (int k = 0; k < matrix.length; k++) { // column mark[k][j] = 1; } } } } for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (mark[i][j] == 1) matrix[i][j] = 0; } } } // O(n*m) O(n^2) } vitassuper/javavt17-coursework package edu.javavt17.dao.jpa; import edu.javavt17.dao.CarModelDAO; import edu.javavt17.model.CarModel; import org.springframework.stereotype.Repository; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.List; @Repository public class CarModelDAOJpaImpl implements CarModelDAO { @PersistenceContext private EntityManager em; public void saveOrUpdate(CarModel item) { if (item.getIdBrand() > 0) { // update em.merge(item); } else { // insert em.persist(item); } } public void delete(int itemId) { em.remove(get(itemId)); } public CarModel get(int itemId) { return em.find(CarModel.class, itemId); } public List list() { List carModels = em.createNamedQuery("CarModel.findAll",CarModel.class).getResultList(); return carModels; } } essobedo/application-manager /* * Copyright (C) 2016 essobedo. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.github.essobedo.appma.exception; /** * The main exception of the application manager. * * @author () * @version $Id$ * @since 1.0 */ public class ApplicationException extends Exception { /** * The serial version UID. */ private static final long serialVersionUID = -7491091906224057082L; /** * Constructs an {@code ApplicationException} with the specified detail message. * * @param message The detail message (which is saved for later retrieval * by the {@link #getMessage()} method) */ public ApplicationException(final String message) { super(message); } /** * Constructs an {@code ApplicationException} with the specified detail message * and cause. * *

Note that the detail message associated with {@code cause} is * not automatically incorporated into this exception's detail * message. * * @param message The detail message (which is saved for later retrieval * by the {@link #getMessage()} method) * @param cause The cause (which is saved for later retrieval by the * {@link #getCause()} method). (A null value is permitted, * and indicates that the cause is nonexistent or unknown.) */ public ApplicationException(final String message, final Throwable cause) { super(message, cause); } } ctripcorp/ferris-wheel // Generated by the protocol buffer compiler. DO NOT EDIT! // source: com/ctrip/ferriswheel/proto/action.proto package com.ctrip.ferriswheel.proto.v1; public final class ActionOuterClass { private ActionOuterClass() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_AddChart_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_AddChart_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_AddSheet_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_AddSheet_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_AddTable_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_AddTable_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_AutomateTable_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_AutomateTable_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_SetCellValue_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_SetCellValue_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_SetCellFormula_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_SetCellFormula_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_RefreshCellValue_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_RefreshCellValue_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_ChartConsult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_ChartConsult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_EraseColumns_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_EraseColumns_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_EraseRows_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_EraseRows_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_FillUp_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_FillUp_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_FillRight_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_FillRight_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_FillDown_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_FillDown_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_FillLeft_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_FillLeft_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_InsertColumns_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_InsertColumns_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_InsertRows_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_InsertRows_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_MoveSheet_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_MoveSheet_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_RemoveAsset_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_RemoveAsset_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_RemoveColumns_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_RemoveColumns_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_RemoveRows_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_RemoveRows_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_RemoveSheet_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_RemoveSheet_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_RenameAsset_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_RenameAsset_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_RenameSheet_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_RenameSheet_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_TransferAsset_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_TransferAsset_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_UpdateAutomaton_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_UpdateAutomaton_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_UpdateChart_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_UpdateChart_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_LayoutAsset_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_LayoutAsset_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_AddText_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_AddText_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_UpdateText_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_UpdateText_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_ExecuteQuery_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_ExecuteQuery_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_ResetTable_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_ResetTable_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_SetCellsFormat_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_SetCellsFormat_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_WorkbookOperation_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_WorkbookOperation_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_Action_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_Action_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_EditRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_EditRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_ChangeList_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_ChangeList_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_ferriswheel_v1_EditResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ferriswheel_v1_EditResponse_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n(com/ctrip/ferriswheel/proto/action.pro" + "to\022\016ferriswheel.v1\032*com/ctrip/ferriswhee" + "l/proto/workbook.proto\"D\n\010AddChart\022\022\n\nsh" + "eet_name\030\001 \001(\t\022$\n\005chart\030\002 \001(\0132\025.ferriswh" + "eel.v1.Chart\"-\n\010AddSheet\022\022\n\nsheet_name\030\001" + " \001(\t\022\r\n\005index\030\002 \001(\005\"D\n\010AddTable\022\022\n\nsheet" + "_name\030\001 \001(\t\022$\n\005table\030\002 \001(\0132\025.ferriswheel" + ".v1.Table\"j\n\rAutomateTable\022\022\n\nsheet_name" + "\030\001 \001(\t\022\022\n\ntable_name\030\002 \001(\t\0221\n\tautomaton\030" + "\003 \001(\0132\036.ferriswheel.v1.TableAutomaton\"\212\001" + "\n\014SetCellValue\022\022\n\nsheet_name\030\001 \001(\t\022\022\n\nta" + "ble_name\030\002 \001(\t\022\021\n\trow_index\030\003 \001(\005\022\024\n\014col" + "umn_index\030\004 \001(\005\022)\n\005value\030\005 \001(\0132\032.ferrisw" + "heel.v1.UnionValue\"y\n\016SetCellFormula\022\022\n\n" + "sheet_name\030\001 \001(\t\022\022\n\ntable_name\030\002 \001(\t\022\021\n\t" + "row_index\030\003 \001(\005\022\024\n\014column_index\030\004 \001(\005\022\026\n" + "\016formula_string\030\005 \001(\t\"\216\001\n\020RefreshCellVal" + "ue\022\022\n\nsheet_name\030\001 \001(\t\022\022\n\ntable_name\030\002 \001" + "(\t\022\021\n\trow_index\030\003 \001(\005\022\024\n\014column_index\030\004 " + "\001(\005\022)\n\005value\030\005 \001(\0132\032.ferriswheel.v1.Unio" + "nValue\"~\n\014ChartConsult\022\022\n\nsheet_name\030\001 \001" + "(\t\022\022\n\ntable_name\030\002 \001(\t\022\014\n\004type\030\003 \001(\t\022\014\n\004" + "left\030\004 \001(\005\022\013\n\003top\030\005 \001(\005\022\r\n\005right\030\006 \001(\005\022\016" + "\n\006bottom\030\007 \001(\005\"_\n\014EraseColumns\022\022\n\nsheet_" + "name\030\001 \001(\t\022\022\n\ntable_name\030\002 \001(\t\022\024\n\014column" + "_index\030\003 \001(\005\022\021\n\tn_columns\030\004 \001(\005\"V\n\tErase" + "Rows\022\022\n\nsheet_name\030\001 \001(\t\022\022\n\ntable_name\030\002" + " \001(\t\022\021\n\trow_index\030\003 \001(\005\022\016\n\006n_rows\030\004 \001(\005\"" + "~\n\006FillUp\022\022\n\nsheet_name\030\001 \001(\t\022\022\n\ntable_n" + "ame\030\002 \001(\t\022\021\n\trow_index\030\003 \001(\005\022\024\n\014first_co" + "lumn\030\004 \001(\005\022\023\n\013last_column\030\005 \001(\005\022\016\n\006n_row" + "s\030\006 \001(\005\"\201\001\n\tFillRight\022\022\n\nsheet_name\030\001 \001(" + "\t\022\022\n\ntable_name\030\002 \001(\t\022\021\n\tfirst_row\030\003 \001(\005" + "\022\020\n\010last_row\030\004 \001(\005\022\024\n\014column_index\030\005 \001(\005" + "\022\021\n\tn_columns\030\006 \001(\005\"\200\001\n\010FillDown\022\022\n\nshee" + "t_name\030\001 \001(\t\022\022\n\ntable_name\030\002 \001(\t\022\021\n\trow_" + "index\030\003 \001(\005\022\024\n\014first_column\030\004 \001(\005\022\023\n\013las" + "t_column\030\005 \001(\005\022\016\n\006n_rows\030\006 \001(\005\"\200\001\n\010FillL" + "eft\022\022\n\nsheet_name\030\001 \001(\t\022\022\n\ntable_name\030\002 " + "\001(\t\022\021\n\tfirst_row\030\003 \001(\005\022\020\n\010last_row\030\004 \001(\005" + "\022\024\n\014column_index\030\005 \001(\005\022\021\n\tn_columns\030\006 \001(" + "\005\"`\n\rInsertColumns\022\022\n\nsheet_name\030\001 \001(\t\022\022" + "\n\ntable_name\030\002 \001(\t\022\024\n\014column_index\030\003 \001(\005" + "\022\021\n\tn_columns\030\004 \001(\005\"W\n\nInsertRows\022\022\n\nshe" + "et_name\030\001 \001(\t\022\022\n\ntable_name\030\002 \001(\t\022\021\n\trow" + "_index\030\003 \001(\005\022\016\n\006n_rows\030\004 \001(\005\"5\n\tMoveShee" + "t\022\022\n\nsheet_name\030\001 \001(\t\022\024\n\014target_index\030\002 " + "\001(\005\"5\n\013RemoveAsset\022\022\n\nsheet_name\030\001 \001(\t\022\022" + "\n\nasset_name\030\002 \001(\t\"`\n\rRemoveColumns\022\022\n\ns" + "heet_name\030\001 \001(\t\022\022\n\ntable_name\030\002 \001(\t\022\024\n\014c" + "olumn_index\030\003 \001(\005\022\021\n\tn_columns\030\004 \001(\005\"W\n\n" + "RemoveRows\022\022\n\nsheet_name\030\001 \001(\t\022\022\n\ntable_" + "name\030\002 \001(\t\022\021\n\trow_index\030\003 \001(\005\022\016\n\006n_rows\030" + "\004 \001(\005\"!\n\013RemoveSheet\022\022\n\nsheet_name\030\001 \001(\t" + "\"Q\n\013RenameAsset\022\022\n\nsheet_name\030\001 \001(\t\022\026\n\016o" + "ld_asset_name\030\002 \001(\t\022\026\n\016new_asset_name\030\003 " + "\001(\t\"=\n\013RenameSheet\022\026\n\016old_sheet_name\030\001 \001" + "(\t\022\026\n\016new_sheet_name\030\002 \001(\t\"o\n\rTransferAs" + "set\022\027\n\017from_sheet_name\030\001 \001(\t\022\027\n\017from_ass" + "et_name\030\002 \001(\t\022\025\n\rto_sheet_name\030\003 \001(\t\022\025\n\r" + "to_asset_name\030\004 \001(\t\"l\n\017UpdateAutomaton\022\022" + "\n\nsheet_name\030\001 \001(\t\022\022\n\ntable_name\030\002 \001(\t\0221" + "\n\tautomaton\030\003 \001(\0132\036.ferriswheel.v1.Table" + "Automaton\"G\n\013UpdateChart\022\022\n\nsheet_name\030\001" + " \001(\t\022$\n\005chart\030\002 \001(\0132\025.ferriswheel.v1.Cha" + "rt\"]\n\013LayoutAsset\022\022\n\nsheet_name\030\001 \001(\t\022\022\n" + "\nasset_name\030\002 \001(\t\022&\n\006layout\030\003 \001(\0132\026.ferr" + "iswheel.v1.Layout\"A\n\007AddText\022\022\n\nsheet_na" + "me\030\001 \001(\t\022\"\n\004text\030\002 \001(\0132\024.ferriswheel.v1." + "Text\"D\n\nUpdateText\022\022\n\nsheet_name\030\001 \001(\t\022\"" + "\n\004text\030\002 \001(\0132\024.ferriswheel.v1.Text\"b\n\014Ex" + "ecuteQuery\022\022\n\nsheet_name\030\001 \001(\t\022\022\n\ntable_" + "name\030\002 \001(\t\022*\n\006params\030\003 \003(\0132\032.ferriswheel" + ".v1.NamedValue\"F\n\nResetTable\022\022\n\nsheet_na" + "me\030\001 \001(\t\022$\n\005table\030\002 \001(\0132\025.ferriswheel.v1" + ".Table\"\224\001\n\016SetCellsFormat\022\022\n\nsheet_name\030" + "\001 \001(\t\022\022\n\ntable_name\030\002 \001(\t\022\021\n\trow_index\030\003" + " \001(\005\022\024\n\014column_index\030\004 \001(\005\022\016\n\006n_rows\030\005 \001" + "(\005\022\021\n\tn_columns\030\006 \001(\005\022\016\n\006format\030\007 \001(\t\"%\n" + "\021WorkbookOperation\022\020\n\010pathname\030\001 \001(\t\"\233\017\n" + "\006Action\022-\n\tadd_chart\030\001 \001(\0132\030.ferriswheel" + ".v1.AddChartH\000\022-\n\tadd_sheet\030\002 \001(\0132\030.ferr" + "iswheel.v1.AddSheetH\000\022-\n\tadd_table\030\003 \001(\013" + "2\030.ferriswheel.v1.AddTableH\000\0227\n\016automate" + "_table\030\004 \001(\0132\035.ferriswheel.v1.AutomateTa" + "bleH\000\0226\n\016set_cell_value\030\005 \001(\0132\034.ferriswh" + "eel.v1.SetCellValueH\000\022:\n\020set_cell_formul" + "a\030\006 \001(\0132\036.ferriswheel.v1.SetCellFormulaH" + "\000\022>\n\022refresh_cell_value\030\007 \001(\0132 .ferriswh" + "eel.v1.RefreshCellValueH\000\0225\n\rchart_consu" + "lt\030\010 \001(\0132\034.ferriswheel.v1.ChartConsultH\000" + "\0225\n\rerase_columns\030\t \001(\0132\034.ferriswheel.v1" + ".EraseColumnsH\000\022/\n\nerase_rows\030\n \001(\0132\031.fe" + "rriswheel.v1.EraseRowsH\000\022)\n\007fill_up\030\013 \001(" + "\0132\026.ferriswheel.v1.FillUpH\000\022/\n\nfill_righ" + "t\030\014 \001(\0132\031.ferriswheel.v1.FillRightH\000\022-\n\t" + "fill_down\030\r \001(\0132\030.ferriswheel.v1.FillDow" + "nH\000\022-\n\tfill_left\030\016 \001(\0132\030.ferriswheel.v1." + "FillLeftH\000\0227\n\016insert_columns\030\017 \001(\0132\035.fer" + "riswheel.v1.InsertColumnsH\000\0221\n\013insert_ro" + "ws\030\020 \001(\0132\032.ferriswheel.v1.InsertRowsH\000\022/" + "\n\nmove_sheet\030\021 \001(\0132\031.ferriswheel.v1.Move" + "SheetH\000\0223\n\014remove_asset\030\022 \001(\0132\033.ferriswh" + "eel.v1.RemoveAssetH\000\0227\n\016remove_columns\030\023" + " \001(\0132\035.ferriswheel.v1.RemoveColumnsH\000\0221\n" + "\013remove_rows\030\024 \001(\0132\032.ferriswheel.v1.Remo" + "veRowsH\000\0223\n\014remove_sheet\030\025 \001(\0132\033.ferrisw" + "heel.v1.RemoveSheetH\000\0223\n\014rename_asset\030\026 " + "\001(\0132\033.ferriswheel.v1.RenameAssetH\000\0223\n\014re" + "name_sheet\030\027 \001(\0132\033.ferriswheel.v1.Rename" + "SheetH\000\0227\n\016transfer_asset\030\030 \001(\0132\035.ferris" + "wheel.v1.TransferAssetH\000\022;\n\020update_autom" + "aton\030\031 \001(\0132\037.ferriswheel.v1.UpdateAutoma" + "tonH\000\0223\n\014update_chart\030\032 \001(\0132\033.ferriswhee" + "l.v1.UpdateChartH\000\022<\n\017create_workbook\030\033 " + "\001(\0132!.ferriswheel.v1.WorkbookOperationH\000" + "\022:\n\ropen_workbook\030\034 \001(\0132!.ferriswheel.v1" + ".WorkbookOperationH\000\022:\n\rsave_workbook\030\035 " + "\001(\0132!.ferriswheel.v1.WorkbookOperationH\000" + "\022;\n\016close_workbook\030\036 \001(\0132!.ferriswheel.v" + "1.WorkbookOperationH\000\0223\n\014layout_asset\030\037 " + "\001(\0132\033.ferriswheel.v1.LayoutAssetH\000\022+\n\010ad" + "d_text\030 \001(\0132\027.ferriswheel.v1.AddTextH\000\022" + "1\n\013update_text\030! \001(\0132\032.ferriswheel.v1.Up" + "dateTextH\000\0225\n\rexecute_query\030\" \001(\0132\034.ferr" + "iswheel.v1.ExecuteQueryH\000\0221\n\013reset_table" + "\030# \001(\0132\032.ferriswheel.v1.ResetTableH\000\022:\n\020" + "set_cells_format\030$ \001(\0132\036.ferriswheel.v1." + "SetCellsFormatH\000B\010\n\006action\"D\n\013EditReques" + "t\022\r\n\005tx_id\030\001 \001(\003\022&\n\006action\030\002 \001(\0132\026.ferri" + "swheel.v1.Action\"5\n\nChangeList\022\'\n\007action" + "s\030\001 \003(\0132\026.ferriswheel.v1.Action\"\336\001\n\014Edit" + "Response\022\r\n\005tx_id\030\001 \001(\003\022\023\n\013status_code\030\002" + " \001(\005\022\017\n\007message\030\003 \001(\t\022-\n\007changes\030\004 \001(\0132\032" + ".ferriswheel.v1.ChangeListH\000\022,\n\010workbook" + "\030\005 \001(\0132\030.ferriswheel.v1.WorkbookH\000\0220\n\017su" + "ggested_chart\030\006 \001(\0132\025.ferriswheel.v1.Cha" + "rtH\000B\n\n\010responseB\"\n\036com.ctrip.ferriswhee" + "l.proto.v1P\001b\006proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.ctrip.ferriswheel.proto.v1.WorkbookOuterClass.getDescriptor(), }, assigner); internal_static_ferriswheel_v1_AddChart_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_ferriswheel_v1_AddChart_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_AddChart_descriptor, new java.lang.String[] { "SheetName", "Chart", }); internal_static_ferriswheel_v1_AddSheet_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_ferriswheel_v1_AddSheet_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_AddSheet_descriptor, new java.lang.String[] { "SheetName", "Index", }); internal_static_ferriswheel_v1_AddTable_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_ferriswheel_v1_AddTable_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_AddTable_descriptor, new java.lang.String[] { "SheetName", "Table", }); internal_static_ferriswheel_v1_AutomateTable_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_ferriswheel_v1_AutomateTable_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_AutomateTable_descriptor, new java.lang.String[] { "SheetName", "TableName", "Automaton", }); internal_static_ferriswheel_v1_SetCellValue_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_ferriswheel_v1_SetCellValue_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_SetCellValue_descriptor, new java.lang.String[] { "SheetName", "TableName", "RowIndex", "ColumnIndex", "Value", }); internal_static_ferriswheel_v1_SetCellFormula_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_ferriswheel_v1_SetCellFormula_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_SetCellFormula_descriptor, new java.lang.String[] { "SheetName", "TableName", "RowIndex", "ColumnIndex", "FormulaString", }); internal_static_ferriswheel_v1_RefreshCellValue_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_ferriswheel_v1_RefreshCellValue_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_RefreshCellValue_descriptor, new java.lang.String[] { "SheetName", "TableName", "RowIndex", "ColumnIndex", "Value", }); internal_static_ferriswheel_v1_ChartConsult_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_ferriswheel_v1_ChartConsult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_ChartConsult_descriptor, new java.lang.String[] { "SheetName", "TableName", "Type", "Left", "Top", "Right", "Bottom", }); internal_static_ferriswheel_v1_EraseColumns_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_ferriswheel_v1_EraseColumns_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_EraseColumns_descriptor, new java.lang.String[] { "SheetName", "TableName", "ColumnIndex", "NColumns", }); internal_static_ferriswheel_v1_EraseRows_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_ferriswheel_v1_EraseRows_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_EraseRows_descriptor, new java.lang.String[] { "SheetName", "TableName", "RowIndex", "NRows", }); internal_static_ferriswheel_v1_FillUp_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_ferriswheel_v1_FillUp_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_FillUp_descriptor, new java.lang.String[] { "SheetName", "TableName", "RowIndex", "FirstColumn", "LastColumn", "NRows", }); internal_static_ferriswheel_v1_FillRight_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_ferriswheel_v1_FillRight_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_FillRight_descriptor, new java.lang.String[] { "SheetName", "TableName", "FirstRow", "LastRow", "ColumnIndex", "NColumns", }); internal_static_ferriswheel_v1_FillDown_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_ferriswheel_v1_FillDown_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_FillDown_descriptor, new java.lang.String[] { "SheetName", "TableName", "RowIndex", "FirstColumn", "LastColumn", "NRows", }); internal_static_ferriswheel_v1_FillLeft_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_ferriswheel_v1_FillLeft_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_FillLeft_descriptor, new java.lang.String[] { "SheetName", "TableName", "FirstRow", "LastRow", "ColumnIndex", "NColumns", }); internal_static_ferriswheel_v1_InsertColumns_descriptor = getDescriptor().getMessageTypes().get(14); internal_static_ferriswheel_v1_InsertColumns_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_InsertColumns_descriptor, new java.lang.String[] { "SheetName", "TableName", "ColumnIndex", "NColumns", }); internal_static_ferriswheel_v1_InsertRows_descriptor = getDescriptor().getMessageTypes().get(15); internal_static_ferriswheel_v1_InsertRows_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_InsertRows_descriptor, new java.lang.String[] { "SheetName", "TableName", "RowIndex", "NRows", }); internal_static_ferriswheel_v1_MoveSheet_descriptor = getDescriptor().getMessageTypes().get(16); internal_static_ferriswheel_v1_MoveSheet_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_MoveSheet_descriptor, new java.lang.String[] { "SheetName", "TargetIndex", }); internal_static_ferriswheel_v1_RemoveAsset_descriptor = getDescriptor().getMessageTypes().get(17); internal_static_ferriswheel_v1_RemoveAsset_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_RemoveAsset_descriptor, new java.lang.String[] { "SheetName", "AssetName", }); internal_static_ferriswheel_v1_RemoveColumns_descriptor = getDescriptor().getMessageTypes().get(18); internal_static_ferriswheel_v1_RemoveColumns_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_RemoveColumns_descriptor, new java.lang.String[] { "SheetName", "TableName", "ColumnIndex", "NColumns", }); internal_static_ferriswheel_v1_RemoveRows_descriptor = getDescriptor().getMessageTypes().get(19); internal_static_ferriswheel_v1_RemoveRows_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_RemoveRows_descriptor, new java.lang.String[] { "SheetName", "TableName", "RowIndex", "NRows", }); internal_static_ferriswheel_v1_RemoveSheet_descriptor = getDescriptor().getMessageTypes().get(20); internal_static_ferriswheel_v1_RemoveSheet_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_RemoveSheet_descriptor, new java.lang.String[] { "SheetName", }); internal_static_ferriswheel_v1_RenameAsset_descriptor = getDescriptor().getMessageTypes().get(21); internal_static_ferriswheel_v1_RenameAsset_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_RenameAsset_descriptor, new java.lang.String[] { "SheetName", "OldAssetName", "NewAssetName", }); internal_static_ferriswheel_v1_RenameSheet_descriptor = getDescriptor().getMessageTypes().get(22); internal_static_ferriswheel_v1_RenameSheet_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_RenameSheet_descriptor, new java.lang.String[] { "OldSheetName", "NewSheetName", }); internal_static_ferriswheel_v1_TransferAsset_descriptor = getDescriptor().getMessageTypes().get(23); internal_static_ferriswheel_v1_TransferAsset_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_TransferAsset_descriptor, new java.lang.String[] { "FromSheetName", "FromAssetName", "ToSheetName", "ToAssetName", }); internal_static_ferriswheel_v1_UpdateAutomaton_descriptor = getDescriptor().getMessageTypes().get(24); internal_static_ferriswheel_v1_UpdateAutomaton_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_UpdateAutomaton_descriptor, new java.lang.String[] { "SheetName", "TableName", "Automaton", }); internal_static_ferriswheel_v1_UpdateChart_descriptor = getDescriptor().getMessageTypes().get(25); internal_static_ferriswheel_v1_UpdateChart_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_UpdateChart_descriptor, new java.lang.String[] { "SheetName", "Chart", }); internal_static_ferriswheel_v1_LayoutAsset_descriptor = getDescriptor().getMessageTypes().get(26); internal_static_ferriswheel_v1_LayoutAsset_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_LayoutAsset_descriptor, new java.lang.String[] { "SheetName", "AssetName", "Layout", }); internal_static_ferriswheel_v1_AddText_descriptor = getDescriptor().getMessageTypes().get(27); internal_static_ferriswheel_v1_AddText_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_AddText_descriptor, new java.lang.String[] { "SheetName", "Text", }); internal_static_ferriswheel_v1_UpdateText_descriptor = getDescriptor().getMessageTypes().get(28); internal_static_ferriswheel_v1_UpdateText_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_UpdateText_descriptor, new java.lang.String[] { "SheetName", "Text", }); internal_static_ferriswheel_v1_ExecuteQuery_descriptor = getDescriptor().getMessageTypes().get(29); internal_static_ferriswheel_v1_ExecuteQuery_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_ExecuteQuery_descriptor, new java.lang.String[] { "SheetName", "TableName", "Params", }); internal_static_ferriswheel_v1_ResetTable_descriptor = getDescriptor().getMessageTypes().get(30); internal_static_ferriswheel_v1_ResetTable_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_ResetTable_descriptor, new java.lang.String[] { "SheetName", "Table", }); internal_static_ferriswheel_v1_SetCellsFormat_descriptor = getDescriptor().getMessageTypes().get(31); internal_static_ferriswheel_v1_SetCellsFormat_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_SetCellsFormat_descriptor, new java.lang.String[] { "SheetName", "TableName", "RowIndex", "ColumnIndex", "NRows", "NColumns", "Format", }); internal_static_ferriswheel_v1_WorkbookOperation_descriptor = getDescriptor().getMessageTypes().get(32); internal_static_ferriswheel_v1_WorkbookOperation_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_WorkbookOperation_descriptor, new java.lang.String[] { "Pathname", }); internal_static_ferriswheel_v1_Action_descriptor = getDescriptor().getMessageTypes().get(33); internal_static_ferriswheel_v1_Action_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_Action_descriptor, new java.lang.String[] { "AddChart", "AddSheet", "AddTable", "AutomateTable", "SetCellValue", "SetCellFormula", "RefreshCellValue", "ChartConsult", "EraseColumns", "EraseRows", "FillUp", "FillRight", "FillDown", "FillLeft", "InsertColumns", "InsertRows", "MoveSheet", "RemoveAsset", "RemoveColumns", "RemoveRows", "RemoveSheet", "RenameAsset", "RenameSheet", "TransferAsset", "UpdateAutomaton", "UpdateChart", "CreateWorkbook", "OpenWorkbook", "SaveWorkbook", "CloseWorkbook", "LayoutAsset", "AddText", "UpdateText", "ExecuteQuery", "ResetTable", "SetCellsFormat", "Action", }); internal_static_ferriswheel_v1_EditRequest_descriptor = getDescriptor().getMessageTypes().get(34); internal_static_ferriswheel_v1_EditRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_EditRequest_descriptor, new java.lang.String[] { "TxId", "Action", }); internal_static_ferriswheel_v1_ChangeList_descriptor = getDescriptor().getMessageTypes().get(35); internal_static_ferriswheel_v1_ChangeList_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_ChangeList_descriptor, new java.lang.String[] { "Actions", }); internal_static_ferriswheel_v1_EditResponse_descriptor = getDescriptor().getMessageTypes().get(36); internal_static_ferriswheel_v1_EditResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_ferriswheel_v1_EditResponse_descriptor, new java.lang.String[] { "TxId", "StatusCode", "Message", "Changes", "Workbook", "SuggestedChart", "Response", }); com.ctrip.ferriswheel.proto.v1.WorkbookOuterClass.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) } src/main/core/java/io/github/greyp9/arwo/core/xed/view/html/HtmlView.java0 package io.github.greyp9.arwo.core.xed.view.html; import io.github.greyp9.arwo.core.alert.view.AlertsView; import io.github.greyp9.arwo.core.app.App; import io.github.greyp9.arwo.core.app.AppHtml; import io.github.greyp9.arwo.core.app.AppTitle; import io.github.greyp9.arwo.core.bundle.Bundle; import io.github.greyp9.arwo.core.config.Preferences; import io.github.greyp9.arwo.core.html.Html; import io.github.greyp9.arwo.core.http.Http; import io.github.greyp9.arwo.core.http.HttpResponse; import io.github.greyp9.arwo.core.http.servlet.ServletHttpRequest; import io.github.greyp9.arwo.core.io.StreamU; import io.github.greyp9.arwo.core.menu.MenuSystem; import io.github.greyp9.arwo.core.menu.view.MenuView; import io.github.greyp9.arwo.core.value.NameTypeValue; import io.github.greyp9.arwo.core.value.NameTypeValues; import io.github.greyp9.arwo.core.value.Value; import io.github.greyp9.arwo.core.view.StatusBarView; import io.github.greyp9.arwo.core.xed.action.XedActionCommit; import io.github.greyp9.arwo.core.xed.action.XedActionLocale; import io.github.greyp9.arwo.core.xed.menu.XedMenuFactory; import io.github.greyp9.arwo.core.xed.request.XedRequest; import io.github.greyp9.arwo.core.xed.state.XedUserState; import io.github.greyp9.arwo.core.xml.DocumentU; import io.github.greyp9.arwo.core.xpath.XPather; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.util.Locale; import java.util.Properties; @SuppressWarnings({ "PMD.AbstractNaming", "PMD.ExcessiveImports" }) public abstract class HtmlView { private final XedRequest request; public final XedRequest getRequest() { return request; } public HtmlView(final XedRequest request) { this.request = request; } public final HttpResponse doGetHtml() throws IOException { final ServletHttpRequest httpRequest = request.getHttpRequest(); final XedUserState userState = request.getState(); // template html final Document html = DocumentU.toDocument(StreamU.read(userState.getXHTML())); final Element body = new XPather(html, null).getElement(Html.XPath.BODY); addHeaderView(body, userState); // cursor content final String context = addContentTo(body); // touch ups final boolean displayAlerts = (httpRequest.getHttpRequest().getHeader(App.Header.RESULT) == null); new AlertsView(displayAlerts, request.getAlerts(), userState.getLocus(), request.getBundle(), userState.getSubmitID()).addContentTo(body); new StatusBarView(httpRequest, userState.getLocus()).addContentTo(body); final String sessionLabel = request.getSession().getEntry().getTitle(); final AppTitle title = (sessionLabel == null) ? AppTitle.Factory.getHostLabel(httpRequest, request.getBundle(), context) : AppTitle.Factory.getHostLabel(httpRequest, sessionLabel, context); final Preferences preferences = new Preferences(request.getState().getSession(App.Servlet.SETTINGS).getXed()); final String iconColor = Value.defaultOnEmpty(preferences.getIconColor(), "black"); final String theme = Value.defaultOnEmpty(preferences.getTheme(), "default"); new AppHtml(httpRequest).fixup(html, title, iconColor, theme); // package into response final byte[] entity = DocumentU.toXHtml(html); final NameTypeValue contentType = new NameTypeValue(Http.Header.CONTENT_TYPE, Http.Mime.TEXT_HTML_UTF8); final NameTypeValue contentLength = new NameTypeValue(Http.Header.CONTENT_LENGTH, entity.length); final NameTypeValues headers = new NameTypeValues(contentType, contentLength); return new HttpResponse(HttpURLConnection.HTTP_OK, headers, new ByteArrayInputStream(entity)); } private void addHeaderView(final Element html, final XedUserState userState) throws IOException { // context menu final Bundle bundle = request.getSession().getXedUI(request.getFactory(), request.getLocale()).getBundle(); final ServletHttpRequest httpRequest = request.getHttpRequest(); final MenuSystem menuSystem = request.getState().getMenuSystem(); new MenuView(bundle, httpRequest, menuSystem).addContentTo(html, XedMenuFactory.Const.XED, true); // settings property strips final Locale locale = userState.getLocale(); final String submitID = userState.getSubmitID(); final Properties properties = userState.getProperties(); new XedActionLocale(userState.getFactory(), locale).addContentTo(html, submitID, properties); new XedActionCommit(userState.getFactory(), locale).addContentTo(html, submitID, properties); } public abstract String addContentTo(Element html) throws IOException; } Selenou/MoonEngine package engine.input; import static org.lwjgl.glfw.GLFW.*; public class Input { private KeyboardHandler keyboardHandler; private MouseButtonHandler mouseButtonHandler; private CursorPositionHandler cursorPositionHandler; public Input(long window) { this.keyboardHandler = new KeyboardHandler(); this.mouseButtonHandler = new MouseButtonHandler(); this.cursorPositionHandler = new CursorPositionHandler(); glfwSetKeyCallback(window, this.keyboardHandler); glfwSetMouseButtonCallback(window, this.mouseButtonHandler); glfwSetCursorPosCallback(window, this.cursorPositionHandler); } public void update() { this.keyboardHandler.update(); this.mouseButtonHandler.update(); // Poll for window events. The key callback above will only be invoked during this call. glfwPollEvents(); } public boolean isKeyPressed(int key) { return keyboardHandler.isKeyPressed(key); } public boolean isKeyHeld(int key) { return keyboardHandler.isKeyHeld(key); } } /* * Copyright (C) 2009-2011 * * 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.parboiled.support; import static org.parboiled.common.Preconditions.*; import org.parboiled.Node; import org.parboiled.buffers.InputBuffer; import org.parboiled.errors.ParseError; import java.util.List; /** * A simple container encapsulating the result of a parsing run. */ public class ParsingResult { /** * Indicates whether the input was successfully parsed. */ public final boolean matched; /** * The root node of the parse tree created by the parsing run. This field will only be non-null when * parse-tree-building has been enabled. */ public final Node parseTreeRoot; /** * The top value of the value stack at the end of the parsing run or null, if the value stack is empty. */ public final V resultValue; /** * The ValueStack used during the parsing run containing all values not popped of the stack by the parser. */ public final ValueStack valueStack; /** * The list of parse errors created during the parsing run. */ public final List parseErrors; /** * The underlying input buffer. */ public final InputBuffer inputBuffer; /** * Creates a new ParsingResult. * * @param matched true if the rule matched the input * @param parseTreeRoot the parse tree root node * @param valueStack the value stack of the parsing run * @param parseErrors the list of parse errors * @param inputBuffer the input buffer */ public ParsingResult(boolean matched, Node parseTreeRoot, ValueStack valueStack, List parseErrors, InputBuffer inputBuffer) { this.matched = matched; this.parseTreeRoot = parseTreeRoot; this.valueStack = checkArgNotNull(valueStack, "valueStack"); this.resultValue = valueStack.isEmpty() ? null : valueStack.peek(); this.parseErrors = checkArgNotNull(parseErrors, "parseErrors"); this.inputBuffer = checkArgNotNull(inputBuffer, "inputBuffer"); } /** * @return true if this parsing result contains parsing errors. */ public boolean hasErrors() { return !parseErrors.isEmpty(); } } package org.firstinspires.ftc.teamcode; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator; import com.qualcomm.hardware.rev.Rev2mDistanceSensor; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; @Autonomous(name = "Auto") public class Auto extends LinearOpMode { private ElapsedTime runtime = new ElapsedTime(); public static Rev2mDistanceSensor rangeSensor; public enum piecePosition { close, medium, far }; BNO055IMU imu; @Override public void runOpMode() throws InterruptedException { Bot bot = new Bot(this); rangeSensor = hardwareMap.get(Rev2mDistanceSensor.class, "sensor_range"); BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC; parameters.calibrationDataFile = "BNO055IMUCalibration.json"; parameters.loggingEnabled = true; parameters.loggingTag = "IMU"; parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator(); imu = hardwareMap.get(BNO055IMU.class, "imu"); imu.initialize(parameters); waitForStart(); runtime.reset(); bot.encoderDrive(1, 25.5, 25.5, 30); double distanceAvg = 0; for(int i = 0; i < 50; i++) { distanceAvg += rangeSensorFunction(); } distanceAvg = distanceAvg / 50; piecePosition block = blockPosition(distanceAvg); telemetry.addData("Average Distance", "%.2f", distanceAvg); telemetry.addData("Position", "%s", block.toString()); telemetry.update(); bot.encoderDrive(1, 30, 30, 30); Orientation angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); double startAngle = angle(angles.angleUnit, angles.firstAngle); double targetAngle = startAngle + (90 - 10); double currentAngle = angle(angles.angleUnit, angles.firstAngle); while(Math.abs(currentAngle) < targetAngle) { bot.setDriveTrain(0.5,0); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); currentAngle = angle(angles.angleUnit, angles.firstAngle); telemetry.addData("Start Angle: ", "%.2f", startAngle); telemetry.addData("Target Angle: ", "%.2f", targetAngle); telemetry.addData("Current Angle: ", "%.2f", currentAngle); telemetry.addData("Loop? ", "%b", (currentAngle < targetAngle)); telemetry.update(); } bot.setDriveTrain(0,0); bot.encoderDrive(1, 18, 18, 30);2 } public static double rangeSensorFunction() { return rangeSensor.getDistance(DistanceUnit.INCH); } piecePosition blockPosition(double position) { if(position < 8) { return piecePosition.close; } else if(position < 14) { return piecePosition.medium; } else { return piecePosition.far; } } double angle(AngleUnit angleUnit, double angle) { return AngleUnit.DEGREES.normalize(AngleUnit.DEGREES.fromUnit(angleUnit, angle)); } }src/main/java/inheritance/Child.java package inheritance; public class Child extends Parent{ public Double age; } src/main/java/org/gooru/nucleus/handlers/classes/processors/repositories/activejdbc/dbauth/ClassOwnerOrCollaboratorAuthorizer.java0 package org.gooru.nucleus.handlers.classes.processors.repositories.activejdbc.dbauth; import io.vertx.core.json.JsonArray; import java.util.ResourceBundle; import org.gooru.nucleus.handlers.classes.processors.ProcessorContext; import org.gooru.nucleus.handlers.classes.processors.repositories.activejdbc.entities.AJEntityClass; import org.gooru.nucleus.handlers.classes.processors.responses.ExecutionResult; import org.gooru.nucleus.handlers.classes.processors.responses.MessageResponse; import org.gooru.nucleus.handlers.classes.processors.responses.MessageResponseFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by ashish on 8/2/16. */ class ClassOwnerOrCollaboratorAuthorizer implements Authorizer { private static final Logger LOGGER = LoggerFactory.getLogger(ClassOwnerAuthorizer.class); private final ProcessorContext context; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("messages"); ClassOwnerOrCollaboratorAuthorizer(ProcessorContext context) { this.context = context; } @Override public ExecutionResult authorize(AJEntityClass model) { String courseId = model.getString(AJEntityClass.COURSE_ID); if (courseId != null && !courseId.isEmpty()) { LOGGER.warn("Authorization request for class '{}' which is having a course '{}'", context.classId(), courseId); } if (checkOwner(model) || checkCollaborator(model)) { return new ExecutionResult<>(null, ExecutionResult.ExecutionStatus.CONTINUE_PROCESSING); } return new ExecutionResult<>( MessageResponseFactory.createForbiddenResponse(RESOURCE_BUNDLE.getString("not.allowed")), ExecutionResult.ExecutionStatus.FAILED); } private boolean checkOwner(AJEntityClass model) { String creatorId = model.getString(AJEntityClass.CREATOR_ID); if (creatorId == null || creatorId.isEmpty() || !creatorId.equalsIgnoreCase(context.userId())) { LOGGER.warn("User '{}' is not owner of class '{}'", context.userId(), context.classId()); return false; } return true; } private boolean checkCollaborator(AJEntityClass model) { String collaboratorString = model.getString(AJEntityClass.COLLABORATOR); if (collaboratorString != null && !collaboratorString.isEmpty()) { JsonArray collaborators = new JsonArray(collaboratorString); if (collaborators.contains(context.userId())) { return true; } } LOGGER.warn("User '{}' is not collaborator of class '{}'", context.userId(), context.classId()); return false; } } package com.integralads.avid.library.inmobi.session.internal; import android.content.Context; import android.webkit.WebView; import com.integralads.avid.library.inmobi.session.ExternalAvidAdSessionContext; public abstract class InternalAvidHtmlAdSession extends InternalAvidAdSession { public InternalAvidHtmlAdSession(Context context, String str, ExternalAvidAdSessionContext externalAvidAdSessionContext) { super(context, str, externalAvidAdSessionContext); } public WebView getWebView() { return (WebView) getView(); } /* access modifiers changed from: protected */ public void onViewRegistered() { super.onViewRegistered(); updateWebViewManager(); } /* access modifiers changed from: protected */ public void onViewUnregistered() { super.onViewUnregistered(); updateWebViewManager(); } } 0 /* * Copyright 2017 Red Hat, Inc. and/or 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 org.kie.workbench.common.dmn.client.editors.expressions.types.function; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Collectors; import com.ait.lienzo.client.core.shape.Group; import org.jboss.errai.ui.client.local.spi.TranslationService; import org.kie.workbench.common.dmn.api.definition.v1_1.FunctionDefinition; import org.kie.workbench.common.dmn.api.definition.v1_1.InformationItem; import org.kie.workbench.common.dmn.client.editors.expressions.types.function.parameters.HasParametersControl; import org.kie.workbench.common.dmn.client.editors.expressions.types.function.parameters.ParametersPopoverView; import org.kie.workbench.common.dmn.client.editors.expressions.util.RendererUtils; import org.kie.workbench.common.dmn.client.resources.i18n.DMNEditorConstants; import org.kie.workbench.common.dmn.client.widgets.grid.columns.EditablePopupHeaderMetaData; import org.kie.workbench.common.dmn.client.widgets.grid.controls.container.CellEditorControlsView; import org.uberfire.ext.wires.core.grids.client.widget.context.GridHeaderColumnRenderContext; public class FunctionColumnParametersHeaderMetaData extends EditablePopupHeaderMetaData { static final String PARAMETER_COLUMN_GROUP = "FunctionColumnParametersHeaderMetaData$Parameters"; private final Supplier functionSupplier; private final FunctionGrid gridWidget; private final TranslationService translationService; public FunctionColumnParametersHeaderMetaData(final Supplier functionSupplier, final TranslationService translationService, final CellEditorControlsView.Presenter cellEditorControls, final ParametersPopoverView.Presenter editor, final Optional editorTitle, final FunctionGrid gridWidget) { super(cellEditorControls, editor, editorTitle); this.functionSupplier = functionSupplier; this.translationService = translationService; this.gridWidget = gridWidget; } @Override protected HasParametersControl getPresenter() { return gridWidget; } @Override public String getColumnGroup() { return PARAMETER_COLUMN_GROUP; } @Override public String getTitle() { return getFormalParametersTitle(); } @Override public Group render(final GridHeaderColumnRenderContext context, final double blockWidth, final double blockHeight) { if (!hasFormalParametersSet()) { return RendererUtils.getEditableHeaderPlaceHolderText(this, context, blockWidth, blockHeight); } else { return super.render(context, blockWidth, blockHeight); } } @Override public Optional getPlaceHolder() { return Optional.of(translationService.getTranslation(DMNEditorConstants.FunctionEditor_EditParameters)); } String getExpressionLanguageTitle() { final FunctionDefinition.Kind kind = KindUtilities.getKind(functionSupplier.get()); return kind == null ? translationService.getTranslation(DMNEditorConstants.FunctionEditor_Undefined) : kind.code(); } String getFormalParametersTitle() { final List formalParameters = functionSupplier.get().getFormalParameter(); final StringBuilder sb = new StringBuilder(); sb.append("("); if (!formalParameters.isEmpty()) { sb.append(formalParameters.stream().map(ii -> ii.getName().getValue()).collect(Collectors.joining(", "))); } sb.append(")"); return sb.toString(); } boolean hasFormalParametersSet() { return !functionSupplier.get().getFormalParameter().isEmpty(); } }trunksbomb/Cyclic package com.lothrazar.cyclicmagic.skill; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; public interface ISkill { public void toggle(EntityPlayer player); public boolean isEnabled(EntityPlayer player); public ItemStack getIcon(); }DonAjit/ToDo0 package com.bridgeit.entity; import org.springframework.stereotype.Component; /** * @author Token Entity with fields userId it belongs to, * tokenType to know accessToken/refreshToken/forgotToken and actual token value */ @Component("token") public class Token { private Integer userId; private String tokenType; private String tokenValue; public String getTokenValue() { return tokenValue; } public void setTokenValue(String tokenValue) { this.tokenValue = tokenValue; } public String getTokenType() { return tokenType; } public Token(Integer userId, String tokenType, String tokenValue) { super(); this.userId = userId; this.tokenType = tokenType; this.tokenValue = tokenValue; } public void setTokenType(String tokenType) { this.tokenType = tokenType; } @Override public String toString() { return "Token [userId=" + userId + ", tokenType=" + tokenType + ", tokenValue=" + tokenValue + "]"; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public Token() { } public Token(Integer userId) { super(); this.userId = userId; } } package com.networknt.oas.model.impl; import com.fasterxml.jackson.databind.JsonNode; import com.networknt.oas.jsonoverlay.*; import com.networknt.oas.model.OpenApi3; import com.networknt.oas.model.Server; import com.networknt.oas.model.ServerVariable; import java.util.Map; public class ServerImpl extends OpenApiObjectImpl implements Server { public ServerImpl(JsonNode json, JsonOverlay parent, ReferenceRegistry refReg) { super(json, parent, refReg); super.maybeElaborateChildrenAtCreation(); } public ServerImpl(Server server, JsonOverlay parent, ReferenceRegistry refReg) { super(server, parent, refReg); super.maybeElaborateChildrenAtCreation(); } private ChildOverlay url = null; private ChildOverlay description = null; private ChildMapOverlay serverVariables = null; private ChildMapOverlay variablesExtensions = null; private ChildMapOverlay extensions = null; // Url @Override public String getUrl() { return url.get(); } @Override public String getUrl(boolean elaborate) { return url.get(elaborate); } @Override public void setUrl(String url) { this.url.set(url); } // Description @Override public String getDescription() { return description.get(); } @Override public String getDescription(boolean elaborate) { return description.get(elaborate); } @Override public void setDescription(String description) { this.description.set(description); } // ServerVariable @Override public Map getServerVariables() { return serverVariables.get(); } @Override public Map getServerVariables(boolean elaborate) { return serverVariables.get(elaborate); } @Override public boolean hasServerVariable(String name) { return serverVariables.containsKey(name); } @Override public ServerVariable getServerVariable(String name) { return serverVariables.get(name); } @Override public void setServerVariables(Map serverVariables) { this.serverVariables.set(serverVariables); } @Override public void setServerVariable(String name, ServerVariable serverVariable) { serverVariables.set(name, serverVariable); } @Override public void removeServerVariable(String name) { serverVariables.remove(name); } // VariablesExtension @Override public Map getVariablesExtensions() { return variablesExtensions.get(); } @Override public Map getVariablesExtensions(boolean elaborate) { return variablesExtensions.get(elaborate); } @Override public boolean hasVariablesExtension(String name) { return variablesExtensions.containsKey(name); } @Override public Object getVariablesExtension(String name) { return variablesExtensions.get(name); } @Override public void setVariablesExtensions(Map variablesExtensions) { this.variablesExtensions.set(variablesExtensions); } @Override public void setVariablesExtension(String name, Object variablesExtension) { variablesExtensions.set(name, variablesExtension); } @Override public void removeVariablesExtension(String name) { variablesExtensions.remove(name); } // Extension @Override public Map getExtensions() { return extensions.get(); } @Override public Map getExtensions(boolean elaborate) { return extensions.get(elaborate); } @Override public boolean hasExtension(String name) { return extensions.containsKey(name); } @Override public Object getExtension(String name) { return extensions.get(name); } @Override public void setExtensions(Map extensions) { this.extensions.set(extensions); } @Override public void setExtension(String name, Object extension) { extensions.set(name, extension); } @Override public void removeExtension(String name) { extensions.remove(name); } @Override protected void elaborateChildren() { url = createChild("url", this, StringOverlay.factory); description = createChild("description", this, StringOverlay.factory); serverVariables = createChildMap("variables", this, ServerVariableImpl.factory, "(?!x-)[a-zA-Z0-9\\._-]+"); variablesExtensions = createChildMap("variables", this, ObjectOverlay.factory, "x-.+"); extensions = createChildMap("", this, ObjectOverlay.factory, "x-.+"); } public static OverlayFactory factory = new OverlayFactory() { @Override protected Class getOverlayClass() { return ServerImpl.class; } @Override public ServerImpl _create(Server server, JsonOverlay parent, ReferenceRegistry refReg) { return new ServerImpl(server, parent, refReg); } @Override public ServerImpl _create(JsonNode json, JsonOverlay parent, ReferenceRegistry refReg) { return new ServerImpl(json, parent, refReg); } }; } package org.occideas.question.dao; import org.occideas.entity.JobModule; import org.occideas.entity.Node; import org.occideas.entity.NodesAgent; import org.occideas.entity.Question; import java.util.List; public interface IQuestionDao { Question getQuestionByModuleIdAndNumber(String parentId, String number); List getQuestionsByParentId(String parentId); List getAllMultipleQuestions(); JobModule getModuleByParentId(Long idNode); Question findMultipleQuestion(long questionId); Node getTopModuleByTopNodeId(long topNodeId); List getNodesWithAgent(long agentId); Question get(Class class1, Long valueOf); void saveOrUpdate(Question question); Question get(long id); void saveOrUpdateIgnoreFK(Question question); Question getQuestionByLinkIdAndTopId(long linkId, long topId); Question getQuestionByTopIdAndNumber(Long topNodeId, String number); Question getNearestQuestionByLinkIdAndTopId(long linkId, long topId); } TinkerBoard-Android/packages_apps_TV0 /* * Copyright (C) 2015 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.tv; import android.test.mock.MockApplication; import com.android.tv.analytics.Analytics; import com.android.tv.analytics.Tracker; import com.android.tv.data.ChannelDataManager; import com.android.tv.data.ProgramDataManager; import com.android.tv.dvr.DvrDataManager; import com.android.tv.dvr.DvrManager; import com.android.tv.dvr.DvrSessionManager; import com.android.tv.util.TvInputManagerHelper; /** * A mock TV Application used for testing. */ public class MockTvApplication extends MockApplication implements ApplicationSingletons { public final ApplicationSingletons mDelegate; public MockTvApplication(ApplicationSingletons delegate) { mDelegate = delegate; } @Override public DvrManager getDvrManager() { return mDelegate.getDvrManager(); } @Override public DvrSessionManager getDvrSessionManger() { return mDelegate.getDvrSessionManger(); } @Override public Analytics getAnalytics() { return mDelegate.getAnalytics(); } @Override public Tracker getTracker() { return mDelegate.getTracker(); } @Override public ChannelDataManager getChannelDataManager() { return mDelegate.getChannelDataManager(); } @Override public ProgramDataManager getProgramDataManager() { return mDelegate.getProgramDataManager(); } @Override public DvrDataManager getDvrDataManager() { return mDelegate.getDvrDataManager(); } @Override public TvInputManagerHelper getTvInputManagerHelper() { return mDelegate.getTvInputManagerHelper(); } @Override public MainActivityWrapper getMainActivityWrapper() { return mDelegate.getMainActivityWrapper(); } } package com.loopme.controllers.display; import android.content.Context; import android.content.pm.ActivityInfo; import android.graphics.Color; import android.graphics.SurfaceTexture; import androidx.annotation.Nullable; import android.text.TextUtils; import android.view.MotionEvent; import android.view.Surface; import android.view.View; import android.webkit.WebView; import android.widget.FrameLayout; import com.iab.omid.library.loopme.adsession.AdEvents; import com.iab.omid.library.loopme.adsession.AdSession; import com.iab.omid.library.loopme.adsession.FriendlyObstructionPurpose; import com.loopme.Constants; import com.loopme.Logging; import com.loopme.LoopMeBannerGeneral; import com.loopme.MinimizedMode; import com.loopme.MoatViewAbilityUtils; import com.loopme.ad.AdParams; import com.loopme.ad.AdSpotDimensions; import com.loopme.ad.LoopMeAd; import com.loopme.bridges.Bridge; import com.loopme.common.LoopMeError; import com.loopme.controllers.MraidController; import com.loopme.controllers.VideoController; import com.loopme.controllers.interfaces.LoopMeDisplayController; import com.loopme.controllers.view.IViewController; import com.loopme.controllers.view.View360Controller; import com.loopme.controllers.view.ViewControllerLoopMe; import com.loopme.listener.Listener; import com.loopme.loaders.FileLoaderNewImpl; import com.loopme.loaders.Loader; import com.loopme.models.Errors; import com.loopme.models.Message; import com.loopme.om.OmidEventTrackerWrapper; import com.loopme.om.OmidHelper; import com.loopme.utils.UiUtils; import com.loopme.utils.Utils; import com.loopme.views.AdView; import com.loopme.views.LoopMeWebView; import com.loopme.views.MraidView; public class DisplayControllerLoopMe extends BaseTrackableController implements LoopMeDisplayController { private static final String LOG_TAG = DisplayControllerLoopMe.class.getSimpleName(); private static final int MRAID_WIDTH = 400; private static final int MRAID_HEIGHT = 600; private boolean mVideoPresented; private LoopMeAd mLoopMeAd; private AdParams mAdParams; private AdView mAdView; private MraidView mMraidView; private Loader mFileLoader; private VideoController mVideoController; private IViewController mViewController; private MraidController mMraidController; private volatile Bridge.Listener mBridgeListener; private View.OnTouchListener mOnTouchListener; private DisplayModeResolver mDisplayModeResolver; private AdSession omidAdSession; private OmidEventTrackerWrapper omidEventTrackerWrapper; private boolean needWaitOmidJsLoad; public DisplayControllerLoopMe(LoopMeAd loopMeAd) { super(loopMeAd); if (loopMeAd == null) { return; } mLoopMeAd = loopMeAd; mAdParams = mLoopMeAd.getAdParams(); mDisplayModeResolver = new DisplayModeResolver(this, loopMeAd); mLogTag = DisplayControllerLoopMe.class.getSimpleName(); Logging.out(mLogTag); } public void initControllers() { if (isMraidAd()) { initMraidControllers(); } else { initLoopMeControllers(); initVideoController(); initViewController(); } } private void initLoopMeControllers() { onMessage(Message.LOG, "initLoopMeSdkController"); mAdView = new AdView(mLoopMeAd.getContext(), createAdReadyListener()); mBridgeListener = initBridgeListener(); mAdView.addBridgeListener(mBridgeListener); mOnTouchListener = initOnTouchListener(); mAdView.setOnTouchListener(mOnTouchListener); } private void initMraidControllers() { onMessage(Message.LOG, "initMraidController"); mMraidController = new MraidController(mLoopMeAd); mMraidView = new MraidView( mLoopMeAd.getContext(), mMraidController, createAdReadyListener()); } public void initVideoController() { VideoController.Callback callback = initVideoControllerCallback(); mVideoController = new VideoController(mAdView, callback, mLoopMeAd.getAdFormat()); } public void initViewController() { if (!mAdParams.isVideo360()) { ViewControllerLoopMe.Callback viewCallback = initViewControllerCallback(); mViewController = new ViewControllerLoopMe(viewCallback); } else { View360Controller.Callback callback = initView360ControllerCallback(); mViewController = new View360Controller(callback); } } private void buildMraidContainer(FrameLayout containerView) { if (mMraidController != null) mMraidController.buildMraidContainer(containerView); } // TODO. Ugly. public void tryAddOmidFriendlyObstructionCloseButton(View view) { if (omidAdSession == null || view == null) return; try { omidAdSession.addFriendlyObstruction(view, FriendlyObstructionPurpose.CLOSE_AD, null); } catch (RuntimeException ex) { Logging.out(LOG_TAG, ex.toString()); } } // TODO. Ugly. public void tryRemoveOmidFriendlyObstruction(View view) { if (omidAdSession == null || view == null) return; omidAdSession.removeFriendlyObstruction(view); } public void collapseMraidBanner() { if (mLoopMeAd instanceof LoopMeBannerGeneral && isMraidAd()) { LoopMeBannerGeneral banner = (LoopMeBannerGeneral) mLoopMeAd; buildMraidContainer(banner.getBannerView()); onCollapseBanner(); } } private void onCollapseBanner() { if (mMraidController != null) { mMraidController.onCollapseBanner(); } } private void handleVideoLoad(String videoUrl) { onMessage(Message.LOG, "JS command: resolve video " + videoUrl); mVideoPresented = true; mVideoController.setVideo360(mAdParams.isVideo360()); loadVideoFile(videoUrl); } private void loadVideoFile(final String videoUrl) { boolean preload = mAdParams.getPartPreload(); Context context = mLoopMeAd.getContext(); mFileLoader = new FileLoaderNewImpl(videoUrl, context, initFileLoaderCallback(preload)); mFileLoader.start(); } private FileLoaderNewImpl.Callback initFileLoaderCallback(final boolean preload) { return new FileLoaderNewImpl.Callback() { @Override public void onError(LoopMeError error) { onAdLoadFail(error); } @Override public void onFileFullLoaded(String filePath) { onMessage(Message.LOG, "fullVideoLoaded: " + filePath); fullVideoLoaded(filePath, preload, mLoopMeAd.isShowing()); } }; } private void fullVideoLoaded(String filePath, boolean preload, boolean adShowing) { if (mVideoController != null) { mVideoController.fullVideoLoaded(filePath, preload, adShowing); } } private boolean isInterstitial() { return mLoopMeAd != null && mLoopMeAd.isInterstitial(); } private boolean isBanner() { return mLoopMeAd != null && mLoopMeAd.isBanner(); } private void handleLoadSuccess() { if (mLoopMeAd != null) { mLoopMeAd.onAdLoadSuccess(); } } private void onAdVideoDidReachEnd() { if (mLoopMeAd != null) { mLoopMeAd.onAdVideoDidReachEnd(); } } private void onAdLoadFail(LoopMeError error) { if (mLoopMeAd != null && error != null) { error.setErrorType(Constants.ErrorType.CUSTOM); mLoopMeAd.onInternalLoadFail(error); } } private void playbackFinishedWithError() { if (mLoopMeAd != null && isBanner()) { ((LoopMeBannerGeneral) mLoopMeAd).playbackFinishedWithError(); } } private void destroyLoopMeAd() { if (mLoopMeAd != null) { mLoopMeAd.dismiss(); } } private void onAdClicked() { if (mLoopMeAd != null) { mLoopMeAd.onAdClicked(); } } @Override public void onStartLoad() { super.onStartLoad(); initControllers(); initTrackers(); preloadHtml(); } private void preloadHtml() { onAdRegisterView(mLoopMeAd.getContext(), getWebView()); injectTrackingJsForWeb(); final String preInjectOmidHtml = isMraidAd() ? Utils.addMraidScript(mAdParams.getHtml()) : mAdParams.getHtml(); OmidHelper.injectScriptContentIntoHtmlAsync( mLoopMeAd.getContext().getApplicationContext(), preInjectOmidHtml, new OmidHelper.ScriptInjectListener() { @Override public void onReady(String injectedOmidHtml) { onOmidScriptInjectResult(injectedOmidHtml, null); } @Override public void onError(String injectOmidError) { onOmidScriptInjectResult(preInjectOmidHtml, injectOmidError); } }); } private void onOmidScriptInjectResult(String html, String injectOmidError) { Logging.out(LOG_TAG, injectOmidError); // Omid has been injected successfully. // Wait for html loading and then create omid ad session. if (TextUtils.isEmpty(injectOmidError)) needWaitOmidJsLoad = true; // Start loading html. WebView wv = getWebView(); if (wv instanceof LoopMeWebView) ((LoopMeWebView) wv).loadHtml(html); } // TODO. Ugly. Use LoopMeAd.onLoadSuccess at least. private Listener createAdReadyListener() { return new Listener() { @Override public void onCall() { tryCreateOmidAdSession(); } }; } // TODO. Refactor. private void tryCreateOmidAdSession() { if (!needWaitOmidJsLoad) return; needWaitOmidJsLoad = false; if (omidAdSession != null) return; WebView wv = getWebView(); omidAdSession = OmidHelper.createWebDisplayAdSession(wv); // Something went wrong with omid. See logs. if (omidAdSession == null) return; omidEventTrackerWrapper = new OmidEventTrackerWrapper( AdEvents.createAdEvents(omidAdSession), null); omidAdSession.registerAdView(wv); omidAdSession.start(); omidEventTrackerWrapper.sendLoaded(); } private void injectTrackingJsForWeb() { if (!isVideo360()) { onAdInjectJs(mLoopMeAd); } } private boolean isVideo360() { return mLoopMeAd != null && mLoopMeAd.isVideo360(); } @Override public void onPlay(int position) { if (mVideoController != null) { resumeViewController(); mVideoController.playVideo(position); } onStartWebMeasuringDelayed(); } @Override public void onResume() { if (isBanner()) { resumeBanner(); } else { resumeInterstitial(); } super.onResume(); } private void resumeBanner() { if (isFullScreen()) { setWebViewState(Constants.WebviewState.VISIBLE); } else { checkBannerVisibility(); } } @Override public void onPause() { super.onPause(); pauseControllers(); } private void resumeInterstitial() { resumeMraid(); resumeViewController(); resumeVideoController(); setWebViewState(Constants.WebviewState.VISIBLE); } private void pauseControllers() { pauseViewController(); pauseMraid(); if (isInterstitial()) { pauseVideoController(false); setWebViewState(Constants.WebviewState.HIDDEN); } } private void resumeMraid() { if (mMraidView != null) { mMraidView.notifySizeChangeEvent(MRAID_WIDTH, MRAID_HEIGHT); mMraidView.setIsViewable(true); } } private void resumeVideoController() { if (mVideoController != null) { mVideoController.resumeVideo(); } } private void resumeViewController() { if (mViewController != null) { mViewController.onResume(); } } private void pauseMraid() { if (mMraidView != null) { mMraidView.setIsViewable(false); } } private void pauseViewController() { if (mViewController != null) { mViewController.onPause(); } } private void pauseVideoController(boolean isSkip) { if (mVideoController != null) { mVideoController.pauseVideo(isSkip); } } @Override public void onVolumeMute(boolean mute) { if (mAdView != null) { mAdView.setVideoMute(mute); } if (mVideoController != null) { mVideoController.muteVideo(mute); } } @Override public void onBuildVideoAdView(FrameLayout containerView) { if (mViewController != null) { mViewController.buildVideoAdView(mLoopMeAd.getContext(), containerView, mAdView); } } @Override public void onDestroy() { super.onDestroy(); if (omidAdSession != null) omidAdSession.finish(); omidAdSession = null; omidEventTrackerWrapper = null; needWaitOmidJsLoad = false; destroyMraidController(); destroyVideoController(); stopVideoLoader(); clearWebView(mAdView); clearWebView(mMraidView); mAdView = null; mMraidView = null; mBridgeListener = null; mOnTouchListener = null; mDisplayModeResolver.destroy(); } private void destroyMraidController() { if (mMraidController != null) { mMraidController.destroyExpandedView(); } } public void destroyMinimizedView() { if (mDisplayModeResolver != null) { mDisplayModeResolver.destroy(); } } @Override public void onRedirect(@Nullable String url, LoopMeAd loopMeAd) { UiUtils.broadcastIntent(mLoopMeAd.getContext(), Constants.CLICK_INTENT); onAdClicked(); super.onRedirect(url, loopMeAd); } @Override public Constants.VideoState getCurrentVideoState() { return mAdView.getCurrentVideoState(); } @Override public void onBuildStaticAdView(FrameLayout containerView) { if (containerView == null || mAdView == null) { return; } mAdView.setBackgroundColor(Color.BLACK); containerView.addView(mAdView); } public void setVideoState(Constants.VideoState state) { if (mAdView != null) { mAdView.setVideoState(state); } } @Override public void onBuildMraidView(FrameLayout containerView) { if (mMraidView != null && containerView != null) { buildMraidContainer(containerView); mMraidView.setIsViewable(true); mMraidView.notifyStateChange(); } } @Override public void onRebuildView(FrameLayout containerView) { if (isMraidAd()) { if (mMraidController != null) { mMraidController.onRebuildView(containerView); } } else { if (mViewController != null) { mViewController.rebuildView(containerView, mAdView, Constants.DisplayMode.NORMAL); } } } @Override public boolean isNativeAd() { return isVideoPresented(); } private void checkBannerVisibility() { if (isBanner() && mLoopMeAd != null) { MoatViewAbilityUtils.calculateViewAbilitySyncDelayed(mLoopMeAd.getContainerView(), new MoatViewAbilityUtils.OnResultListener() { @Override public void onResult(MoatViewAbilityUtils.ViewAbilityInfo info) { if (info.isVisibleMore50Percents()) { setWebViewState(Constants.WebviewState.VISIBLE); dispatchEvent(); } else { setWebViewState(Constants.WebviewState.HIDDEN); } } }); } } private void dispatchEvent() { onNewActivity(mLoopMeAd.getContext()); onStartWebMeasuringDelayed(); } @Override public boolean isFullScreen() { return (mDisplayModeResolver != null && mDisplayModeResolver.isFullScreenMode()) || isMraidExpandMode(); } private boolean isMraidExpandMode() { return mMraidController != null && mMraidController.isExpanded(); } public void setFullScreen(boolean isFullScreen) { mDisplayModeResolver.switchToFullScreenMode(isFullScreen); } @Override public int getOrientation() { if (isMraidAd()) { return getMraidOrientation(); } else if (isInterstitial()) { return getOrientationFromAdParams(); } else { return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; } } private void handleVideoStretch(boolean videoStretch) { onMessage(Message.LOG, "JS command: stretch video "); Constants.StretchOption stretch = videoStretch ? Constants.StretchOption.STRETCH : Constants.StretchOption.NO_STRETCH; mViewController.setStretchParam(stretch); } public boolean isVideoPresented() { return mVideoPresented; } public void onAdShake() { if (mAdView != null) { mAdView.shake(); } } public void setWebViewState(Constants.WebviewState state) { if (mAdView != null) mAdView.setWebViewState(state); if (mMraidView != null) mMraidView.setWebViewState(state); if (omidEventTrackerWrapper != null && state == Constants.WebviewState.VISIBLE) omidEventTrackerWrapper.sendOneTimeImpression(); } private View.OnTouchListener initOnTouchListener() { return new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { mViewController.handleTouchEvent(event); return false; } }; } private Bridge.Listener initBridgeListener() { return new Bridge.Listener() { @Override public void onJsVideoPlay(int time) { onPlay(time); } @Override public void onJsVideoPause(final int time) { pauseViewController(); pauseVideoController(true); onAdSkippedEvent(); } @Override public void onJsVideoMute(boolean mute) { onVolumeMute(mute); } @Override public void onJsVideoLoad(final String videoUrl) { handleVideoLoad(videoUrl); } @Override public void onJsLoadSuccess() { handleLoadSuccess(); } @Override public void onJsClose() { onAdUserCloseEvent(); destroyLoopMeAd(); } @Override public void onJsLoadFail(String mess) { onAdLoadFail(Errors.FAILED_TO_PROCESS_AD); } @Override public void onJsFullscreenMode(boolean isFullScreen) { switchToFullScreenMode(isFullScreen); } @Override public void onNonLoopMe(String url) { onRedirect(url, mLoopMeAd); } @Override public void onJsVideoStretch(boolean b) { handleVideoStretch(b); } }; } private void switchToFullScreenMode(boolean isFullScreen) { if (mDisplayModeResolver != null) { mDisplayModeResolver.switchToFullScreenMode(isFullScreen); } } public void switchToPreviousMode() { if (isBanner() && mDisplayModeResolver != null) { mDisplayModeResolver.switchToPreviousMode(); } } private View360Controller.Callback initView360ControllerCallback() { return new View360Controller.Callback() { @Override public void onSurfaceReady(Surface surface) { onMessage(Message.LOG, "onSurfaceReady ####"); if (mVideoController != null) { mVideoController.setSurface(surface); } } @Override public void onEvent(String event) { if (mAdView != null) { mAdView.send360Event(event); } } }; } private ViewControllerLoopMe.Callback initViewControllerCallback() { return new ViewControllerLoopMe.Callback() { @Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture) { onMessage(Message.LOG, "onSurfaceTextureAvailable"); surfaceTextureAvailable(surfaceTexture); setViewSize(); } @Override public void onSurfaceTextureDestroyed() { onMessage(Message.LOG, "onSurfaceTextureDestroyed"); surfaceTextureDestroyed(); } }; } private void setViewSize() { MinimizedMode minimizedMode = mDisplayModeResolver.getMinimizedMode(); Constants.DisplayMode currentDisplayMode = mDisplayModeResolver.getDisplayMode(); AdSpotDimensions viewSize = UiUtils.getViewSize(minimizedMode, mLoopMeAd, currentDisplayMode); mViewController.setViewSize(viewSize.getWidth(), viewSize.getHeight()); } private void surfaceTextureAvailable(SurfaceTexture surfaceTexture) { if (mVideoController != null) { mVideoController.setSurfaceTextureAvailable(true); mVideoController.setSurfaceTexture(surfaceTexture); } } private void surfaceTextureDestroyed() { if (mVideoController != null) { mVideoController.surfaceTextureDestroyed(); } } private VideoController.Callback initVideoControllerCallback() { return new VideoController.Callback() { @Override public void onVideoReachEnd() { onAdCompleteEvent(); onAdVideoDidReachEnd(); } @Override public void onFail(LoopMeError error) { onAdLoadFail(error); } @Override public void onVideoSizeChanged(int width, int height) { setVideoSize(width, height); } @Override public void onPlaybackFinishedWithError() { playbackFinishedWithError(); } @Override public void onVolumeChangedEvent(float volume, int currentPosition) { onAdVolumeChangedEvent(volume, currentPosition); } @Override public void onDurationChangedEvent(int currentPosition, int adDuration) { onAdDurationEvents(currentPosition, adDuration); } }; } private void setVideoSize(int width, int height) { if (mViewController != null) { mViewController.setVideoSize(width, height); } } private void clearWebView(LoopMeWebView webView) { if (webView != null) { webView.destroy(); } } public void closeMraidAd() { if (mMraidController != null) { mMraidController.close(); } } public void buildView(FrameLayout containerView) { if (isMraidAd()) { onBuildMraidView(containerView); } else { if (isNativeAd()) { onBuildVideoAdView(containerView); } else { onBuildStaticAdView(containerView); setVideoState(Constants.VideoState.PLAYING); } } if (mAdParams.isVideo360()) { initVr360(); } } public void initVr360() { mViewController.initVRLibrary(mLoopMeAd.getContext()); mViewController.onResume(); } private void destroyVideoController() { if (mVideoController != null) { mVideoController.destroy(); } } private void stopVideoLoader() { if (mFileLoader != null) { mFileLoader.stop(); } } @Override public WebView getWebView() { if (isMraidAd()) { return mMraidView; } else { return mAdView; } } public void setFullscreenMode(boolean isFullScreen) { if (mAdView != null) { mAdView.setFullscreenMode(isFullScreen); } } public void rebuildView(FrameLayout view, Constants.DisplayMode displayMode) { if (mVideoController != null) { mViewController.rebuildView(view, mAdView, displayMode); } } public void setMinimizedMode(MinimizedMode mode) { if (mDisplayModeResolver != null) { mDisplayModeResolver.setMinimizedMode(mode); } } public boolean isMinimizedModeEnable() { return mDisplayModeResolver != null && mDisplayModeResolver.isMinimizedModeEnable(); } public void switchToMinimizedMode() { if (mDisplayModeResolver != null) { mDisplayModeResolver.switchToMinimizedMode(); } } public void switchToNormalMode() { if (mDisplayModeResolver != null) { mDisplayModeResolver.switchToNormalMode(); } } public void dismissAd() { if (mLoopMeAd != null) { mLoopMeAd.dismiss(); } } public boolean isVideoPlaying() { return getCurrentVideoState() == Constants.VideoState.PLAYING; } public boolean isVideoPaused() { return getCurrentVideoState() == Constants.VideoState.PAUSED; } public int getMraidOrientation() { if (mMraidController != null) { return mMraidController.getForceOrientation(); } else { return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; } } public void dismiss() { setWebViewState(Constants.WebviewState.CLOSED); } private boolean isMraidAd() { return mLoopMeAd != null && mLoopMeAd.isMraidAd(); } }Andreas237/AndroidPolicyAutomationExtractedJars/Ibotta_com.ibotta.android/javafiles/com/crashlytics/android/core/LogFileManager$DirectoryProvider.java1-10 // Decompiled by Jad v1.5.8g. Copyright 2001 . // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.crashlytics.android.core; import java.io.File; // Referenced classes of package com.crashlytics.android.core: // LogFileManager public static interface LogFileManager$DirectoryProvider { public abstract File getLogFileDir(); } 0 package test; import junit.framework.*; public class PackTest extends TestCase { public void testNot() {} // public void testSimple() throws Exception { // Workspace ws= Workspace.getWorkspace("/Ws/aQute"); // Project p = ws.getProject("aQute.metatype"); // ProjectLauncher pl = p.getProjectLauncher(); // // Jar jar = pl.executable(); // // } } // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.01.15 at 03:07:29 PM EST // package org.hr_xml._3; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlValue; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * * A non-numeric or textual representation of a Score. * A record of the marks allotted to an individual in the measurement of abilities, capacity to learn, in the assessment of personality, or in other measurable characteristics (e.g., credit worthiness). Represents either the total number of points awarded, or a general standard achieved. Includes a set of attributes to identify the scoring scheme. * * *

Java class for ScoreTextType complex type. * *

The following schema fragment specifies the expected content contained within this class. * *

 * <complexType name="ScoreTextType">
 *   <simpleContent>
 *     <extension base="<http://www.openapplications.org/oagis/9>NormalizedStringType">
 *       <attribute name="scoreTextCode" type="{http://www.hr-xml.org/3}ScoreTextCodeContentType" />
 *       <attribute name="minimumScoreText" type="{http://www.openapplications.org/oagis/9}StringType" />
 *       <attribute name="maximumScoreText" type="{http://www.openapplications.org/oagis/9}StringType" />
 *     </extension>
 *   </simpleContent>
 * </complexType>
 * 
* * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ScoreTextType", propOrder = { "value" }) public class ScoreTextType { @XmlValue @XmlJavaTypeAdapter(NormalizedStringAdapter.class) protected String value; @XmlAttribute protected String scoreTextCode; @XmlAttribute protected String minimumScoreText; @XmlAttribute protected String maximumScoreText; /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ public String getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value) { this.value = value; } /** * Gets the value of the scoreTextCode property. * * @return * possible object is * {@link String } * */ public String getScoreTextCode() { return scoreTextCode; } /** * Sets the value of the scoreTextCode property. * * @param value * allowed object is * {@link String } * */ public void setScoreTextCode(String value) { this.scoreTextCode = value; } /** * Gets the value of the minimumScoreText property. * * @return * possible object is * {@link String } * */ public String getMinimumScoreText() { return minimumScoreText; } /** * Sets the value of the minimumScoreText property. * * @param value * allowed object is * {@link String } * */ public void setMinimumScoreText(String value) { this.minimumScoreText = value; } /** * Gets the value of the maximumScoreText property. * * @return * possible object is * {@link String } * */ public String getMaximumScoreText() { return maximumScoreText; } /** * Sets the value of the maximumScoreText property. * * @param value * allowed object is * {@link String } * */ public void setMaximumScoreText(String value) { this.maximumScoreText = value; } } src/main/java/io/primeval/reflex/proxy/handler/impl/SimpleCharInterceptionHandler.java1-10 package io.primeval.reflex.proxy.handler.impl; import io.primeval.reflex.arguments.Arguments; import io.primeval.reflex.proxy.handler.CharInterceptionHandler; public final class SimpleCharInterceptionHandler implements CharInterceptionHandler { @FunctionalInterface public interface ToCharFunction { char applyAsChar(A a); } private final Arguments arguments; private final ToCharFunction invokeFun; public SimpleCharInterceptionHandler(Arguments arguments, ToCharFunction invokeFun) { this.arguments = arguments; this.invokeFun = invokeFun; } @Override public Arguments getArguments() { return arguments; } @Override public char invoke(Arguments arguments) throws E { return invokeFun.applyAsChar(arguments); } } 1-10 package com.goboomtown.supportsdk.fragment; import java.util.HashMap; import java.util.List; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ImageView; import android.widget.TextView; import com.goboomtown.supportsdk.R; import com.goboomtown.supportsdk.api.SupportSDK; import com.goboomtown.supportsdk.model.KBEntryModel; import com.goboomtown.supportsdk.view.SupportButton; public class KBExpandableListAdapter extends BaseExpandableListAdapter { private Context context; private List listDataHeader; // header titles // child data in format of header title, child title private HashMap> listDataChild; public ExpandableListView expandableListView; public boolean expanded; public SupportButton mSupportButton = null; public SupportSDK supportSDK = null; public List groupIcons = null; public interface KBExpandableListAdapterListener { void adapterDidSelectEntry(int groupPosition, int childPosition, Object object); } public KBExpandableListAdapterListener mListener; public KBExpandableListAdapter(Context context, List listDataHeader, HashMap> listChildData) { this.context = context; this.listDataHeader = listDataHeader; this.listDataChild = listChildData; } public void updateData(List listDataHeader, HashMap> listChildData) { this.listDataHeader = listDataHeader; this.listDataChild = listChildData; notifyDataSetChanged(); } @Override public Object getChild(int groupPosition, int childPosititon) { Object object = null; try { object = this.listDataChild.get(this.listDataHeader.get(groupPosition)) .get(childPosititon); } catch( Exception e ) { } return object; } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.fragment_article, parent, false); } ImageView iconView = convertView.findViewById(R.id.iconView); TextView articleLabel = convertView.findViewById(R.id.articleLabel); if ( articleLabel != null ) { articleLabel.setTextColor(supportSDK.appearance.kbTextColor()); } if ( expanded && expandableListView!=null ) { expandableListView.expandGroup(groupPosition); } iconView.setVisibility(View.GONE); if ( groupIcons != null ) { Drawable icon = groupIcons.get(groupPosition); if (icon != null) { iconView.setImageDrawable(icon); iconView.setColorFilter(supportSDK.appearance.kbTextColor()); iconView.setVisibility(View.VISIBLE); } } Object child = getChild(groupPosition, childPosition); if ( child instanceof KBEntryModel ) { final KBEntryModel entry = (KBEntryModel) child; if ( entry.isFolder() ) { if ( supportSDK.appearance.kbFolderIcon != null ) { iconView.setImageDrawable(supportSDK.appearance.kbFolderIcon()); iconView.setColorFilter(supportSDK.appearance.kbTextColor()); iconView.setVisibility(View.VISIBLE); } } String childText = entry.title(); articleLabel.setText(childText); } else if ( child instanceof String ) { final String text = (String) child; articleLabel.setText(text); } convertView.setOnClickListener(v -> { if ( mListener != null ) { mListener.adapterDidSelectEntry(groupPosition, childPosition, child); } }); return convertView; } @Override public int getChildrenCount(int groupPosition) { if ( this.listDataHeader.get(groupPosition) != null ) { return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size(); } return 0; } @Override public Object getGroup(int groupPosition) { return this.listDataHeader.get(groupPosition); } @Override public int getGroupCount() { return this.listDataHeader.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if ( convertView == null ) { LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.fragment_article_section_header, parent, false); } // convertView.setBackgroundColor(this.context.getResources().getColor(R.color.kbFolderL0BackgroundColor)); ImageView iconView = convertView.findViewById(R.id.sectionHeaderIcon); if ( supportSDK!=null && supportSDK.appearance!=null && supportSDK.appearance.kbFolderIcon != null ) { iconView.setImageDrawable(supportSDK.appearance.kbFolderIcon()); iconView.setColorFilter(supportSDK.appearance.kbTextColor()); iconView.setVisibility(View.VISIBLE); } else { iconView.setVisibility(View.GONE); } TextView sectionHeaderLabel = convertView.findViewById(R.id.sectionHeaderLabel); sectionHeaderLabel.setTextColor(supportSDK.appearance.kbTextColor()); String title = (String) getGroup(groupPosition); sectionHeaderLabel.setText(title); if ( expanded && expandableListView!=null ) { expandableListView.expandGroup(groupPosition); } return convertView; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } }package blog.controllers; import blog.forms.LoginForm; import blog.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; @Controller public class UserController { @Autowired UserService userService; @RequestMapping("/users") public String index(Model model,HttpServletRequest request){ LoginForm userData = (LoginForm) request.getSession().getAttribute("LOGGEDIN_USER"); if(userData == null) return "redirect:/404"; model.addAttribute("users",userService.findAll()); return "users/index"; } @RequestMapping(value="/users/logout") public String logout (HttpServletRequest request) { LoginForm userData = (LoginForm) request.getSession().getAttribute("LOGGEDIN_USER"); if(userData == null) return "redirect:/404"; request.getSession().setAttribute("LOGGEDIN_USER", null); request.getSession().setAttribute("LOGGEDIN_USER_NAME",null); request.getSession().setAttribute("LOGGEDIN_USER_USERNAME", null); request.getSession().setAttribute("LOGGEDIN_USER_ID", null); return "redirect:/"; } }/* * Created on Oct 4, 2009 * * 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. * * Copyright @2009-2013 the original author or authors. */ package org.fest.assertions; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import static org.fest.assertions.ErrorMessages.*; import static org.fest.assertions.Fail.comparisonFailed; /** * Template for assertions applicable to {@link Comparable}s. * * @param used to simulate "self types." For more information please read "Emulating 'self types' using Java Generics to simplify fluent API implementation." * @param the type of the "actual" value. * @author * @author */ public abstract class ComparableAssert> extends GenericAssert { /** * Creates a new {@link ComparableAssert}. * * @param selfType the "self type." * @param actual the target to verify. */ protected ComparableAssert(@NotNull Class selfType, @Nullable T actual) { super(selfType, actual); } /** * Verifies that the actual {@link Comparable} is equal to the given one. * * @param expected the given {@code Comparable} to compare the actual {@code Comparable} to. * @return this assertion object. * @throws AssertionError if the actual {@code Comparable} is {@code null}. * @throws AssertionError if the actual {@code Comparable} is not equal to the given one. */ public final @NotNull S isEqualByComparingTo(T expected) { isNotNull(); if (actual.compareTo(expected) == 0) { return myself(); } failIfCustomMessageIsSet(); throw comparisonFailed(rawDescription(), actual, expected); } /** * Verifies that the actual {@link Comparable} is not equal to the given one. * * @param expected the given {@code Comparable} to use to compare to the actual {@code Comparable}. * @return this assertion object. * @throws AssertionError if the actual {@code Comparable} is {@code null}. * @throws AssertionError if the actual {@code Comparable} is equal to the given one. */ public final @NotNull S isNotEqualByComparingTo(T expected) { isNotNull(); if (actual.compareTo(expected) != 0) { return myself(); } failIfCustomMessageIsSet(); throw failure(unexpectedEqual(actual, expected)); } /** * Verifies that the actual {@link Comparable} is less than the given one. * * @param other the given value. * @return this assertion object. * @throws AssertionError if the actual {@code Comparable} is {@code null}. * @throws AssertionError if the actual {@code Comparable} is not less than the given one. */ public final @NotNull S isLessThan(T other) { isNotNull(); if (actual.compareTo(other) < 0) { return myself(); } failIfCustomMessageIsSet(); throw failure(unexpectedGreaterThanOrEqualTo(actual, other)); } /** * Verifies that the actual {@link Comparable} is greater than the given one. * * @param other the given value. * @return this assertion object. * @throws AssertionError if the actual {@code Comparable} is {@code null}. * @throws AssertionError if the actual {@code Comparable} is not greater than the given one. */ public final @NotNull S isGreaterThan(@Nullable T other) { isNotNull(); if (actual.compareTo(other) > 0) { return myself(); } failIfCustomMessageIsSet(); throw failure(unexpectedLessThanOrEqualTo(actual, other)); } /** * Verifies that the actual {@link Comparable} is less than or equal to the given one. * * @param other the given value. * @return this assertion object. * @throws AssertionError if the actual {@code Comparable} is {@code null}. * @throws AssertionError if the actual {@code Comparable} is not less than or equal to the given one. */ public final @NotNull S isLessThanOrEqualTo(@Nullable T other) { isNotNull(); if (actual.compareTo(other) <= 0) { return myself(); } failIfCustomMessageIsSet(); throw failure(unexpectedGreaterThan(actual, other)); } /** * Verifies that the actual {@link Comparable} is greater than or equal to the given one. * * @param other the given value. * @return this assertion object. * @throws AssertionError if the actual {@code Comparable} is {@code null}. * @throws AssertionError if the actual {@code Comparable} is not greater than or equal to the given one. */ public final @NotNull S isGreaterThanOrEqualTo(@Nullable T other) { isNotNull(); if (actual.compareTo(other) >= 0) { return myself(); } failIfCustomMessageIsSet(); throw failure(unexpectedLessThan(actual, other)); } }package com.kongbig.java8.service; /** * @Description: * @author: lianggangda * @date: 2020/5/2 16:35 */ @FunctionalInterface public interface MyFunction2 { /** * @param t1 * @param t2 * @return */ public R getValue(T t1, T t2); } package org.bluemagic.config.service.dao.impl.helper; import java.util.Collection; import org.bluemagic.config.api.tag.Tag; public class CompletePropertyDto extends PropertyDto { private Collection attributes; public Collection getAttributes() { return attributes; } public void setAttributes(Collection attributes) { this.attributes = attributes; } } /* Copyright 2011-2016 IBM 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.ibm.rhapsody.sprint.rdfsync; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; 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.net.URL; import java.util.Map; import java.util.Properties; import org.junit.Test; import com.hp.hpl.jena.rdf.model.Model; import com.ibm.rhapsody.sm.rdfsync.Helper; import com.telelogic.rhapsody.core.IRPApplication; import com.telelogic.rhapsody.core.RhapsodyAppServer; import com.telelogic.rhapsody.core.RhapsodyRuntimeException; /** * @author sergeyzo * */ public class HelperTests { private static final String RHAPSODY_GUID_PREFIX = "GUID "; private static final String SPRINT_URI_PREFIX = "http://sprint/ID-"; private static final String RHAPSODY_URI_PREFIX = "http://com.ibm.rhapsody/sprint/GUID-"; /** * Test method for {@link com.ibm.rhapsody.sm.rdfsync.Helper#loadModel(java.lang.String)}. */ @Test public void testLoadModel() { assertNotNull(Helper.loadModel(getRDFTestStream())); } /** * Test method for {@link com.ibm.rhapsody.sm.rdfsync.Helper#extractIdMap(com.hp.hpl.jena.rdf.model.Model)}. */ @Test public void testExtractIdMap() { Model model = Helper.loadModel(getRDFTestStream()); Map idMap = Helper.extractIdMap(model, new Helper.URITransform() { @Override public String transform(String uri) { return "_" + uri; } }); assertNotNull(idMap); assertTrue("idMap must not be empty", idMap.size() > 0); Properties p = new Properties(); p.putAll(idMap); p.putAll(Helper.inverseIdMap(idMap)); assertTrue("Properties should be twice as big as idMap", idMap.size() * 2 == p.size()); System.out.println("Successfully created Properties of total: " + p.size()); //p.list(System.out); } /** * Test method for {@link com.ibm.rhapsody.sm.rdfsync.Helper#transformURIs(com.hp.hpl.jena.rdf.model.Model)}. * @throws IOException */ @Test public void testTransformURIs() throws IOException { Model model = Helper.loadModel(getRDFTestStream()); Map idMap1 = Helper.transformURIs(model, new Helper.PrefixURITransform(RHAPSODY_URI_PREFIX, SPRINT_URI_PREFIX)); assertNotNull(idMap1); System.out.println("------ Successfully created Jena RDF model of total: " + idMap1.size()); assertTrue("idMap1 must not be empty", idMap1.size() > 0); Map idMap2 = Helper.extractIdMap(model, new Helper.PrefixURITransform(SPRINT_URI_PREFIX, RHAPSODY_GUID_PREFIX)); assertNotNull(idMap2); assertTrue("idMap2 must not be empty", idMap2.size() > 0); Properties p = new Properties(); p.putAll(idMap2); p.putAll(Helper.inverseIdMap(idMap2)); assertTrue("Properties should be twice as big as idMap", idMap2.size() * 2 == p.size()); System.out.println("------ Successfully created Properties of total: " + p.size()); //p.list(System.out); URL rootDirURL = Helper.class.getResource("/"); File rootDir = new File(rootDirURL.getFile()).getParentFile(); File rdfFile = new File(rootDir, "transformedIds.rdf"); FileOutputStream rdfOutStream = new FileOutputStream(rdfFile); model.write(rdfOutStream); rdfOutStream.close(); System.out.println("------ Successfully saved RDF model to file: " + rdfFile.getAbsolutePath()); File propFile = new File(rootDir, "idmap.prop"); FileOutputStream propOutStream = new FileOutputStream(propFile); p.save(propOutStream, "Auto-generated for test purposes, please do not modify manually"); propOutStream.close(); System.out.println("------ Successfully saved Properties to file: " + propFile.getAbsolutePath()); } /** * Test method for {@link com.ibm.rhapsody.sm.rdfsync.Helper#syncRDF2IRP(com.hp.hpl.jena.rdf.model.Model)}. * @throws IOException */ @Test public void testsyncRDF2IRP() throws Exception { Model model = Helper.loadModel(getRDFTestStream()); Map idMap1 = Helper.transformURIs(model, new Helper.PrefixURITransform(RHAPSODY_URI_PREFIX, SPRINT_URI_PREFIX)); assertNotNull(idMap1); // System.out.println("------ Successfully created Jena RDF model of total: " + idMap1.size()); // assertTrue("idMap1 must not be empty", idMap1.size() > 0); Map idMap2 = Helper.extractIdMap(model, new Helper.PrefixURITransform(SPRINT_URI_PREFIX, RHAPSODY_GUID_PREFIX)); assertNotNull(idMap2); // assertTrue("idMap2 must not be empty", idMap2.size() > 0); Properties p = new Properties(); p.putAll(idMap2); p.putAll(Helper.inverseIdMap(idMap2)); assertTrue("Properties should be twice as big as idMap", idMap2.size() * 2 == p.size()); System.out.println("------ Successfully created Properties of total: " + p.size()); // open RHP project IRPApplication rhpApp = null;; try { rhpApp = openRhpProject("D:\\temp\\rhp\\EmptyTest\\EmptyTest.rpy"); Helper.syncRDF2IRP(model, rhpApp.activeProject(), p, null); rhpApp.saveAll(); } catch(Exception x) { if(rhpApp != null) System.err.println("Fail cause: " + rhpApp.getErrorMessage()); throw x; } finally { if(rhpApp != null) { if(rhpApp.activeProject() != null) rhpApp.activeProject().close(); rhpApp.quit(); } RhapsodyAppServer.CloseSession(); // RhapsodyAppServer.CloseSessionNative(); } } IRPApplication openRhpProject(String rpy) { IRPApplication rhpApp = null;; try { rhpApp = RhapsodyAppServer.getActiveRhapsodyApplication(); } catch(RhapsodyRuntimeException x) {} // Ignore and fallback if (rhpApp == null) { try { rhpApp = RhapsodyAppServer.createRhapsodyApplicationDllServer(); } catch(RhapsodyRuntimeException x) {} // Ignore and fallback if (rhpApp == null) rhpApp = RhapsodyAppServer.createRhapsodyApplication(); if (rhpApp == null) { System.out.println("Error. Cannot create Rhapsody instance."); return null; } if(rhpApp.activeProject() == null) { if(rpy != null) rhpApp.openProject(rpy); } } return rhpApp; } // Utility method private static InputStream getRDFTestStream() { try { return new FileInputStream(new File("data/rhapsody.import.rdf")); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; //Helper.class.getResourceAsStream("/error-data-for-bug.xml"); } } package com.venky.swf.exceptions; public class IncompleteDataException extends RuntimeException { /** * */ private static final long serialVersionUID = 809101847413646997L; public IncompleteDataException() { super(); } public IncompleteDataException(String message, Throwable cause) { super(message, cause); } public IncompleteDataException(String message) { super(message); } public IncompleteDataException(Throwable cause) { super(cause); } } package com.yveshe.utils.encrypt; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; /** * 标准加密工具
* Data encryption standard * * @author YvesHe * */ public class DesUtil { private static final String DES = "DES"; private static final String STRING_ENCODE = "UTF-8"; private static final String SALT = "2b2dc4cc-8cd6-458f-885e-1a2151bfabe4"; /* 加密盐 */ private static final String DEFAULT_KEY = "yveshe_des_key"; public static String encrypt(String data) { try { return encrypt(data, DEFAULT_KEY); } catch (Exception e) { return data; } } public static String decrypt(String data) { try { return decrypt(data, DEFAULT_KEY); } catch (Exception e) { return data; } } /** * 加密 * * @param data * 待加密字符串 * @param key * 密钥(长度应大于8字节) * @return * @throws Exception */ public static String encrypt(String data, String key) throws Exception { if (data == null) { return null; } if (key == null) { throw new Exception("the encrypt key is null"); } data = SALT + data; try { byte abyte0[] = key.getBytes(STRING_ENCODE); if (abyte0.length < 8) {// 将字符串Key转化为特定的字节数组,如果长度小于8字节,不可以进行加密,这是DES的要求 throw new Exception("the key " + key + " length must large than 8 bytes"); } byte abyte1[] = encrypt(data.getBytes(STRING_ENCODE), key.getBytes(STRING_ENCODE)); return bytes2Hex(abyte1); } catch (Exception exception) { throw exception; } } /** * 解密 * * @param data * 待加密字符串 * @param key * 密钥(长度应大于8字节) * @return * @throws Exception */ public static String decrypt(String data, String key) throws Exception { if (data == null) { return null; } if (key == null) { throw new Exception("the decrypt key is null"); } try { byte srcData[] = hex2Bytes(data); byte abyte1[] = decrypt(srcData, key.getBytes(STRING_ENCODE)); String result = new String(abyte1, STRING_ENCODE); if (result != null && result.length() < SALT.length()) { throw new Exception("the decrypt data " + data + " is not correct"); } return result.substring(SALT.length()); } catch (Exception e) { throw e; } } /** * 根据Key字节数组加密data字节数组的数据,返回加密后的字节数组 * * @param data * 待加密的字节数组 * @param key * 密钥数组,密钥数组必须大于等于8个字节 * @return * @throws Exception */ private static synchronized byte[] encrypt(byte data[], byte key[]) throws Exception { // 生成一个随机数源 SecureRandom random = new SecureRandom(); // 从原始密钥数据创建DESKeySpec对象 DESKeySpec spec = new DESKeySpec(key); // 创建工密钥工程,生成密钥 SecretKeyFactory factory = SecretKeyFactory.getInstance(DES); javax.crypto.SecretKey secretkey = factory.generateSecret(spec); Cipher cipher = Cipher.getInstance(DES); cipher.init(Cipher.ENCRYPT_MODE, secretkey, random); return cipher.doFinal(data); } private static synchronized byte[] decrypt(byte data[], byte key[]) throws Exception { SecureRandom random = new SecureRandom(); DESKeySpec spec = new DESKeySpec(key); SecretKeyFactory factory = SecretKeyFactory.getInstance(DES); javax.crypto.SecretKey secretKey = factory.generateSecret(spec); Cipher cipher = Cipher.getInstance(DES); cipher.init(2, secretKey, random); return cipher.doFinal(data); } private static String bytes2Hex(byte[] bytes) throws Exception { if (bytes == null) { throw new Exception("the byte array is null"); } StringBuilder stringbuilder = new StringBuilder(); String zero = "0"; for (int j = 0; j < bytes.length; j++) { String s1 = Integer.toHexString(0xFF & bytes[j]); if (s1.length() == 1) stringbuilder.append(zero); stringbuilder.append(s1); } return stringbuilder.toString().toUpperCase(); } private static byte[] hex2Bytes(String data) throws Exception { if (data == null) { throw new Exception("the data is null"); } byte abyte0[] = data.getBytes(); if (abyte0.length % 2 != 0) { throw new Exception("the decrypt data " + data + " is not correct"); } byte[] result = new byte[abyte0.length / 2]; for (int i = 0; i < abyte0.length / 2; i++) result[i] = (byte) Integer.parseInt(new String(abyte0, 2 * i, 2), 16); return result; } public static void main(String[] args) { String pwd = ""; String des_key = "yveshe-key"; try { String encrypt = DesUtil.encrypt(pwd, des_key); System.out.println(encrypt); String decrypt = DesUtil.decrypt(encrypt, des_key); System.out.println(decrypt); } catch (Exception e) { e.printStackTrace(); } } } zmattis/University_of_Pittsburgh1-10 // CS 0445 Spring 2017 // Assig1A driver program. This program must work as is with your // MultiDS class. Look carefully at all of the method calls so that // you create your MultiDS methods correctly. For example, note the // constructor calls and the toString() method call. The output should // be identical to my sample output, with the exception of the result of // the shuffle() methods -- since this should be random yours should not // match mine. public class Assig1A { public static void main(String [] args) { // Testing constructor and PrimQ interface PrimQ theQ = new MultiDS(5); // Testing addItem for (int i = 0; i < 6; i++) { Integer newItem = new Integer(2 * i); if (!(theQ.full())) { theQ.addItem(newItem); System.out.println(newItem + " added to Q"); } else { System.out.println("No room for " + newItem); } } // Testing removeItem while (!(theQ.empty())) { Integer oldItem = theQ.removeItem(); System.out.println(oldItem + " retrieved from Q"); } Integer noItem = theQ.removeItem(); if (noItem == null) System.out.println("Nothing in the Q"); // Testing array management int count = 1; PrimQ theQ2 = new MultiDS(5); String theItem = new String("Item " + count); System.out.println("Adding " + theItem); theQ2.addItem(theItem); for (int i = 0; i < 8; i++) { count++; theItem = new String("Item " + count); System.out.println("Adding " + theItem); theQ2.addItem(theItem); theItem = theQ2.removeItem(); System.out.println("Removing " + theItem); } int sz = theQ2.size(); System.out.println("There are " + sz + " items in the buffer"); // This code will test the toString() method and the Reorder // interface. System.out.println("\nAbout to test Reorder methods"); MultiDS newDS = new MultiDS(15); for (int i = 0; i < 8; i++) { newDS.addItem(new Integer(i)); } System.out.println(newDS.toString()); System.out.println("Reversing"); newDS.reverse(); System.out.println(newDS.toString()); System.out.println("Removing 3 items then adding 1"); Integer bogus = newDS.removeItem(); bogus = newDS.removeItem(); bogus = newDS.removeItem(); newDS.addItem(new Integer(8)); System.out.println(newDS.toString()); System.out.println("Reversing"); newDS.reverse(); System.out.println(newDS.toString()); System.out.println("Shifting right"); newDS.shiftRight(); System.out.println(newDS.toString()); System.out.println("Shifting left twice"); newDS.shiftLeft(); newDS.shiftLeft(); System.out.println(newDS.toString()); System.out.println("\nAbout to test shuffle..."); newDS.clear(); for (int i = 0; i < 10; i++) { newDS.addItem(new Integer(i)); } System.out.println(newDS.toString()); System.out.println("Shuffling..."); newDS.shuffle(); System.out.println(newDS.toString()); System.out.println("Removing 2 and adding 1"); bogus = newDS.removeItem(); bogus = newDS.removeItem(); newDS.addItem(new Integer(22)); System.out.println(newDS.toString()); System.out.println("Shuffling again"); newDS.shuffle(); System.out.println(newDS.toString()); } }0 package com.codepath.apps.MySimpleTweets.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.Toast; import com.codepath.apps.MySimpleTweets.R; import com.codepath.apps.MySimpleTweets.TweetsArrayAdapter; import com.codepath.apps.MySimpleTweets.listeners.EndlessScrollListener; import com.codepath.apps.MySimpleTweets.models.Tweet; import java.util.ArrayList; import java.util.List; public abstract class TweetsListFragment extends Fragment { private List tweets; private TweetsArrayAdapter aTweets; private ListView lvTweets; private EndlessScrollListener endlessScrollListener; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_tweets_list, parent, false); lvTweets = (ListView) v.findViewById(R.id.lvTweets); lvTweets.setAdapter(aTweets); endlessScrollListener = new EndlessScrollListener() { @Override public boolean onLoadMore(int page, int totalItemsCount) { populateTimeline(); Toast.makeText(getActivity(), "Getting more tweets...", Toast.LENGTH_SHORT).show(); return true; } }; lvTweets.setOnScrollListener(endlessScrollListener); return v; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); tweets = new ArrayList<>(); aTweets = new TweetsArrayAdapter(getActivity(), tweets); } public void addAll(List tweets) { aTweets.addAll(tweets); } public void insert(Tweet tweet, int index) { aTweets.insert(tweet, index); } abstract protected void populateTimeline(); } package com.kfyty.database.jdbc.intercept; import com.kfyty.database.jdbc.annotation.Execute; import com.kfyty.database.jdbc.exception.ExecuteInterceptorException; import com.kfyty.support.generic.SimpleGeneric; import com.kfyty.support.jdbc.TransactionHolder; import com.kfyty.support.method.MethodParameter; import com.kfyty.support.utils.CommonUtil; import com.kfyty.support.utils.JdbcUtil; import com.kfyty.support.utils.ReflectUtil; import com.kfyty.support.utils.ResultSetUtil; import com.kfyty.support.wrapper.WrapperValue; import lombok.extern.slf4j.Slf4j; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import static com.kfyty.support.utils.CommonUtil.size; import static com.kfyty.support.utils.JdbcUtil.commitTransactionIfNecessary; /** * 描述: SQL 执行拦截器链 * * @author kfyty725 * @date 2021/9/19 11:12 * @email */ @Slf4j public class InterceptorChain implements AutoCloseable { private final MethodParameter mapperMethod; private final Annotation annotation; private final WrapperValue sql; private final SimpleGeneric returnType; private final List methodParameters; private final Iterator> interceptors; private PreparedStatement preparedStatement; private ResultSet resultSet; private Object retValue; private boolean hasRet; public InterceptorChain(MethodParameter method, Annotation annotation, String sql, SimpleGeneric returnType, List methodParameters, Iterator> interceptors) { this.mapperMethod = method; this.annotation = annotation; this.sql = new WrapperValue<>(sql); this.returnType = returnType; this.methodParameters = new ArrayList<>(methodParameters); this.interceptors = interceptors; } public MethodParameter getMapperMethod() { return mapperMethod; } public PreparedStatement getPreparedStatement() { return preparedStatement; } public ResultSet getResultSet() { return resultSet; } public void setPreparedStatement(PreparedStatement preparedStatement) { this.preparedStatement = preparedStatement; } public void setRetValue(Object retValue) { this.retValue = retValue; this.hasRet = true; } public Object proceed() { if (!this.interceptors.hasNext()) { return this.processChainResult(); } Map.Entry interceptor = this.interceptors.next(); if (interceptor.getValue() instanceof QueryInterceptor && this.annotation.annotationType().equals(Execute.class)) { return this.proceed(); } return this.retValue = ReflectUtil.invokeMethod(interceptor.getValue(), interceptor.getKey(), this.bindInterceptorParameters(interceptor.getKey())); } @Override public void close() { try { CommonUtil.close(this.getPreparedStatement()); CommonUtil.close(this.getResultSet()); } finally { try { commitTransactionIfNecessary(TransactionHolder.currentTransaction()); } catch (SQLException e) { log.error("try commit transaction error !", e); } } } protected Object[] bindInterceptorParameters(Method method) { Parameter[] parameters = method.getParameters(); Object[] paramValues = new Object[method.getParameterCount()]; for (byte i = 0, size = (byte) parameters.length; i < size; i++) { paramValues[i] = this.doBindParameter(parameters[i]); if (paramValues[i] == null) { throw new IllegalArgumentException("interceptor parameter bind failed of parameter: " + parameters[i]); } } return paramValues; } protected Object doBindParameter(Parameter parameter) { Class parameterType = parameter.getType(); if (MethodParameter.class.equals(parameterType)) { return this.mapperMethod; } if (Annotation.class.isAssignableFrom(parameterType)) { return this.annotation; } if (WrapperValue.class.isAssignableFrom(parameterType)) { return this.sql; } if (SimpleGeneric.class.isAssignableFrom(parameterType)) { return this.returnType; } if (List.class.isAssignableFrom(parameterType)) { return this.methodParameters; } if (PreparedStatement.class.isAssignableFrom(parameterType)) { return this.preparePreparedStatement(); } if (ResultSet.class.isAssignableFrom(parameterType)) { return this.prepareResultSet(); } if (Object.class.equals(parameterType)) { return this.prepareReturnValue(); } if (InterceptorChain.class.isAssignableFrom(parameterType)) { return this; } return null; } protected PreparedStatement preparePreparedStatement() { if (this.preparedStatement == null) { try { this.preparedStatement = JdbcUtil.getPreparedStatement(TransactionHolder.currentTransaction().getConnection(), this.sql.get(), this.methodParameters.toArray(new MethodParameter[0])); } catch (SQLException e) { throw new ExecuteInterceptorException(e); } } return this.preparedStatement; } protected ResultSet prepareResultSet() { if (this.resultSet == null) { try { this.resultSet = this.preparePreparedStatement().executeQuery(); } catch (SQLException e) { throw new ExecuteInterceptorException(e); } } return this.resultSet; } protected Object prepareReturnValue() { if (!this.hasRet) { try { this.setRetValue(ResultSetUtil.processObject(this.prepareResultSet(), this.returnType)); if (log.isDebugEnabled()) { log.debug("<== total: {} [{}]", size(this.retValue), this.retValue == null ? null : this.retValue.getClass()); } } catch (SQLException e) { throw new ExecuteInterceptorException(e); } } return this.retValue; } protected Object processChainResult() { if (this.hasRet) { return this.retValue; } try { this.preparePreparedStatement().execute(); this.setRetValue(this.preparePreparedStatement().getUpdateCount()); if (log.isDebugEnabled()) { log.debug("<== affected rows: {}", this.retValue); } return this.retValue; } catch (SQLException e) { throw new ExecuteInterceptorException(e); } } } package com.github.iridatelegrambot.test.repository; import com.github.iridatelegrambot.entity.UserTelegram; import com.github.iridatelegrambot.repository.UserTelegramRepository; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.jdbc.Sql; import java.util.List; import java.util.Optional; @DataJpaTest @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE) public class UserTelegramRepositoryIT { @Autowired private UserTelegramRepository userTelegramRepository; @Sql(scripts = {"/sql/delete_table.sql","/sql/users_telegram.sql"}) @Test void shouldProperlyFindAllActiveUsers(){ //when List users = userTelegramRepository.findAllByActiveTrue(); //then Assertions.assertEquals(6,users.size()); } @Sql(scripts = {"/sql/delete_table.sql"}) @Test void shouldProperlySaveUser(){ //given UserTelegram user = new UserTelegram(); user.setChatId(100000010L); user.setActive(true); userTelegramRepository.save(user); //when Optional userFromDB = userTelegramRepository.findById(100000010L); //then Assertions.assertTrue(userFromDB.isPresent()); Assertions.assertEquals(user,userFromDB.get()); } } package ch.valtech.kubernetes.microservice.cluster.filestorage.kafka; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import static org.springframework.kafka.test.assertj.KafkaConditions.key; import ch.valtech.kubernetes.microservice.cluster.filestorage.service.FunctionsService; import ch.valtech.kubernetes.microservice.cluster.persistence.api.dto.Action; import ch.valtech.kubernetes.microservice.cluster.persistence.api.dto.AuditingRequestDto; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.listener.ContainerProperties; import org.springframework.kafka.listener.KafkaMessageListenerContainer; import org.springframework.kafka.listener.MessageListener; import org.springframework.kafka.test.EmbeddedKafkaBroker; import org.springframework.kafka.test.context.EmbeddedKafka; import org.springframework.kafka.test.utils.ContainerTestUtils; import org.springframework.kafka.test.utils.KafkaTestUtils; import org.springframework.test.annotation.DirtiesContext; @Slf4j @DirtiesContext @SpringBootTest @EmbeddedKafka(topics = {"auditing", "reverseAuditing"}, partitions = 1, bootstrapServersProperty = "application.kafka.bootstrapAddress") @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ProducerServiceTest { public static final String FILENAME = "test.txt"; private static final String TOPIC = "auditing"; private static final String TOPIC2 = "reverseAuditing"; private final ObjectMapper mapper = new ObjectMapper(); @Autowired private ProducerService producerService; @Autowired private EmbeddedKafkaBroker embeddedKafkaBroker; @MockBean private FunctionsService functionsService; BlockingQueue> consumerRecords; KafkaMessageListenerContainer container; @BeforeAll void setUp() { ContainerProperties containerProperties = new ContainerProperties(TOPIC, TOPIC2); Map configs = new HashMap<>(KafkaTestUtils.consumerProps("consumer", "false", embeddedKafkaBroker)); DefaultKafkaConsumerFactory consumerFactory = new DefaultKafkaConsumerFactory<>( configs); container = new KafkaMessageListenerContainer<>(consumerFactory, containerProperties); consumerRecords = new LinkedBlockingQueue<>(); container.setupMessageListener((MessageListener) consumerRecords::add); container.start(); ContainerTestUtils.waitForAssignment(container, embeddedKafkaBroker.getPartitionsPerTopic() * embeddedKafkaBroker.getTopics().size()); } @AfterAll public void tearDown() { container.stop(); } @Test void shouldCheckMessageIsProduced() throws InterruptedException, IOException { //given AuditingRequestDto auditingRequestDto = AuditingRequestDto.builder() .filename(FILENAME) .action(Action.UPLOAD) .build(); //when when(functionsService.reverse(any())).thenReturn("test"); producerService.sendMessage(FILENAME, Action.UPLOAD); //then ConsumerRecord received = consumerRecords.poll(10, TimeUnit.SECONDS); String json = mapper.writeValueAsString(auditingRequestDto); assertEquals(json, received.value()); assertThat(received).has(key(null)); received = consumerRecords.poll(10, TimeUnit.SECONDS); json = mapper.writeValueAsString(auditingRequestDto.toBuilder().filename("test").build()); assertEquals(json, received.value()); assertThat(received).has(key(null)); } }LeoNero/Instagram0 package com.nerone.instagram.adapters; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.nerone.instagram.R; import com.nerone.instagram.activities.PostDetailsActivity; import com.nerone.instagram.models.Post; import com.nerone.instagram.utils.Time; import java.util.List; public class PostsAdapter extends RecyclerView.Adapter { private List posts; private Context context; public PostsAdapter(Context context, List posts) { this.context = context; this.posts = posts; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { LayoutInflater inflater = LayoutInflater.from(context); View postView = inflater.inflate(R.layout.item_post, viewGroup, false); ViewHolder viewHolder = new ViewHolder(postView); return viewHolder; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Post post = posts.get(position); holder.tvDescription.setText(post.getDescription()); holder.tvCreatedAt.setText(Time.getRelativeTimeAgo(post.getCreatedAt().toString())); holder.tvUsername.setText(post.getUser().getUsername()); Glide.with(context) .load(post.getImage().getUrl()) .into(holder.ivPhoto); } @Override public int getItemCount() { return posts.size(); } public void clear() { posts.clear(); notifyDataSetChanged(); } public void addAll(List posts) { this.posts.addAll(posts); notifyDataSetChanged(); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { ImageView ivPhoto; TextView tvDescription; TextView tvUsername; TextView tvCreatedAt; public ViewHolder(View itemView) { super(itemView); ivPhoto = itemView.findViewById(R.id.ivPhoto); tvDescription = itemView.findViewById(R.id.tvDescription); tvUsername = itemView.findViewById(R.id.tvUsername); tvCreatedAt = itemView.findViewById(R.id.tvCreatedAt); ivPhoto.setScaleType(ImageView.ScaleType.FIT_XY); itemView.setOnClickListener(this); } @Override public void onClick(View v) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { Post post = posts.get(position); Intent intent = new Intent(context, PostDetailsActivity.class); intent.putExtra("post_id", post.getObjectId()); context.startActivity(intent); } } } } package info.jab.microservices; public record Host(String address, String name) {} src/main/java/com/watson/propert/tycoon/game/bord/Card.java package com.watson.propert.tycoon.game.bord; import com.watson.propert.tycoon.game.entitys.Player; public class Card implements Action { private String deckName; private String description; private Action action; public Card(String deckName, String description, Action action) { this.deckName = deckName; this.description = description; this.action = action; } public String getDeckName() { return deckName; } public String getDescription() { return description; } @Override public void run(Player player) { action.run(player); } } /* * 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.rya.api.function.aggregation; import static java.util.Objects.requireNonNull; import java.util.Optional; import org.eclipse.rdf4j.query.algebra.AggregateOperator; import org.eclipse.rdf4j.query.algebra.Avg; import org.eclipse.rdf4j.query.algebra.Count; import org.eclipse.rdf4j.query.algebra.Max; import org.eclipse.rdf4j.query.algebra.Min; import org.eclipse.rdf4j.query.algebra.Sum; import com.google.common.collect.ImmutableMap; import edu.umd.cs.findbugs.annotations.DefaultAnnotation; import edu.umd.cs.findbugs.annotations.NonNull; /** * The different types of Aggregation functions that an aggregate node may perform. */ @DefaultAnnotation(NonNull.class) public enum AggregationType { MIN(Min.class), MAX(Max.class), COUNT(Count.class), SUM(Sum.class), AVERAGE(Avg.class); private final Class operatorClass; private AggregationType(final Class operatorClass) { this.operatorClass = requireNonNull(operatorClass); } private static final ImmutableMap, AggregationType> byOperatorClass; static { final ImmutableMap.Builder, AggregationType> builder = ImmutableMap.builder(); for(final AggregationType type : AggregationType.values()) { builder.put(type.operatorClass, type); } byOperatorClass = builder.build(); } public static Optional byOperatorClass(final Class operatorClass) { return Optional.ofNullable( byOperatorClass.get(operatorClass) ); } }package com.github.gnx.automate.service.impl; import com.github.gnx.automate.common.file.FileInfo; import com.github.gnx.automate.common.file.FileListSha256Util; import com.github.gnx.automate.entity.FileListShaEntity; import com.github.gnx.automate.repository.FileListShaRepository; import com.github.gnx.automate.service.IFileListShaService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA. * Description: * @author genx * @date 2020/4/3 20:26 */ @Service public class FileListShaServiceImpl implements IFileListShaService { @Autowired private FileListShaRepository fileListShaRepository; @Override public void save(String sha256, String fileList) { FileListShaEntity fileListShaEntity = new FileListShaEntity(); fileListShaEntity.setSha256(sha256); fileListShaEntity.setFileList(fileList); fileListShaEntity.setCreateTime(new Timestamp(System.currentTimeMillis())); fileListShaRepository.save(fileListShaEntity); } @Override public List getFileInfoList(String sha256) { FileListShaEntity fileListShaEntity = this.fileListShaRepository.getFirstBySha256(sha256); if (fileListShaEntity != null) { return FileListSha256Util.parseToList(fileListShaEntity.getFileList()); } else { return new ArrayList(0); } } } AshShawn/baseiobaseio-core/src/main/java/com/generallycloud/baseio/component/ssl/ProtocolSelector.java1-10 /* * Copyright 2015-2017 GenerallyCloud.com * * 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.generallycloud.baseio.component.ssl; import java.util.List; /** * @author wangkai * */ public interface ProtocolSelector { /** * Callback invoked to let the application know that the peer does not support this * {@link ApplicationProtocolNegotiator}. */ void unsupported(); /** * Callback invoked to select the application level protocol from the {@code protocols} provided. * * @param protocols the protocols sent by the protocol advertiser * @return the protocol selected by this {@link ProtocolSelector}. A {@code null} value will indicate the no * protocols were selected but the handshake should not fail. The decision to fail the handshake is left to the * other end negotiating the SSL handshake. * @throws Exception If the {@code protocols} provide warrant failing the SSL handshake with a fatal alert. */ String select(List protocols) throws Exception; } /* * 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 com.github.javarch.repository; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.sql.SQLException; import java.util.List; import org.hibernate.SessionFactory; import org.hibernate.criterion.Projection; import org.hibernate.criterion.Projections; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import com.github.javarch.domain.User; import com.github.javarch.persistence.NamedQueryParameter; import com.github.javarch.persistence.PageRequest; import com.github.javarch.persistence.orm.hibernate.HibernateRepository; import com.github.javarch.persistence.orm.hibernate.conf.DataSourceH2Config; import com.github.javarch.persistence.orm.hibernate.conf.HibernateConfig; import com.github.javarch.persistence.orm.hibernate.conf.HibernatePropertiesConfig; import com.github.javarch.persistence.orm.test.DataBaseTestBuilder; import com.github.javarch.persistence.orm.test.HibernateDataBaseTestBuilder; import com.github.javarch.support.spring.Profiles; /** * * * @author * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( classes={HibernateConfig.class, DataSourceH2Config.class, HibernatePropertiesConfig.class}, loader=AnnotationConfigContextLoader.class) @TransactionConfiguration(defaultRollback=false) @Transactional @ActiveProfiles({ Profiles.TEST , "migration" } ) public class HibernateBaseRepositoryIntegrationTest { @Autowired private HibernateRepository defaultRepository; @Autowired private SessionFactory sf; private static boolean databaseSetup; @Before public void execute() throws SQLException, IOException { DataBaseTestBuilder dbbuilder = new HibernateDataBaseTestBuilder(sf) .populeData("/sqls/HibernateBaseRepository.sql") .destroyData("/sqls/HibernateBaseRepository-destroy.sql"); if ( ! databaseSetup ){ dbbuilder.populeDatabase(); databaseSetup = true; } } //Avoid false positives when testing ORM code @After public void after(){ sf.getCurrentSession().flush(); } @Test public void testInjecao(){ assertNotNull(defaultRepository); } @Test public void testLoad(){ List users = defaultRepository.findAll(User.class); assertNotNull(users); assertTrue("Esperava 50 mas encontrou " + users.size(), users.size() == 50 ); } @Test public void testLoadNamedQuerySemParametros(){ List users = defaultRepository.findAllByNamedQuery("User.findAll", null); assertNotNull(users); assertTrue(users.size() == 50 ); } @Test public void testLoadNamedQueryComParametros(){ NamedQueryParameter params = NamedQueryParameter.with("email", ""); User user = defaultRepository.findOneByNamedQuery("User.findByEmail", params ); assertNotNull(user); assertTrue(user.getNomeUsuario().equals("Nome Usuário 43" )); } @Test public void testLoadPaginado(){ List users = defaultRepository.findAll(User.class, new PageRequest(20, 10)); assertNotNull(users); assertTrue(users.size() == 10 ); assertTrue(users.get(0).getEmail().equals("")); assertTrue(users.get(9).getEmail().equals("")); } @Test public void testLoadProjecao(){ Projection p = Projections.projectionList() .add( Projections.property("email"), "email" ); List users = defaultRepository.findAll(User.class, p); assertNotNull(users); for (User User : users) { assertNotNull(User.getEmail()); assertNull(User.getNomeUsuario()); assertNull(User.getSenha()); assertTrue(User.getBlogs().isEmpty()); } } } app/src/main/java/com/dummy/myapplication/ui/utils/ObservableViewModel.java0 package com.dummy.myapplication.ui.utils; import androidx.databinding.Observable; import androidx.databinding.PropertyChangeRegistry; import androidx.lifecycle.ViewModel; public class ObservableViewModel extends ViewModel implements Observable { private final PropertyChangeRegistry registry = new PropertyChangeRegistry(); @Override public void addOnPropertyChangedCallback(OnPropertyChangedCallback callback) { registry.add(callback); } @Override public void removeOnPropertyChangedCallback(OnPropertyChangedCallback callback) { registry.remove(callback); } protected void notifyChange() { registry.notifyCallbacks(this, 0, null); } protected void notifyPropertyChanged(int fieldId) { registry.notifyCallbacks(this, fieldId, null); } } bianapis/sd-card-case-v2.00 /** * @author Virtusa */ package org.bian.service; import java.util.List; import org.springframework.stereotype.Service; import org.bian.dto.*; import org.bian.util.JsonReader; import com.fasterxml.jackson.core.type.TypeReference; @Service public class CardCaseApiServiceImpl implements CardCaseApiService { public SDCardCaseActivateOutputModel activate(SDCardCaseActivateInputModel request){ return JsonReader.read("activate-SDCardCaseActivateOutputModel.json",new TypeReference(){}); } public SDCardCaseConfigureOutputModel configure(String sdReferenceId, SDCardCaseConfigureInputModel request){ return JsonReader.read("configure-SDCardCaseConfigureOutputModel.json",new TypeReference(){}); } public CRCardCaseProcedureControlOutputModel control(String sdReferenceId, String crReferenceId, CRCardCaseProcedureControlInputModel request){ return JsonReader.read("control-CRCardCaseProcedureControlOutputModel.json",new TypeReference(){}); } public BQArbitrationExchangeOutputModel exchangeArbitration(String sdReferenceId, String crReferenceId, String bqReferenceId, BQArbitrationExchangeInputModel request){ return JsonReader.read("exchange-BQArbitrationExchangeOutputModel.json",new TypeReference(){}); } public BQResolutionExchangeOutputModel exchangeResolution(String sdReferenceId, String crReferenceId, String bqReferenceId, BQResolutionExchangeInputModel request){ return JsonReader.read("exchange-BQResolutionExchangeOutputModel.json",new TypeReference(){}); } public CRCardCaseProcedureExchangeOutputModel exchange(String sdReferenceId, String crReferenceId, CRCardCaseProcedureExchangeInputModel request){ return JsonReader.read("exchange-CRCardCaseProcedureExchangeOutputModel.json",new TypeReference(){}); } public CRCardCaseProcedureExecuteOutputModel execute(String sdReferenceId, String crReferenceId, CRCardCaseProcedureExecuteInputModel request){ return JsonReader.read("execute-CRCardCaseProcedureExecuteOutputModel.json",new TypeReference(){}); } public SDCardCaseFeedbackOutputModel feedback(String sdReferenceId, SDCardCaseFeedbackInputModel request){ return JsonReader.read("feedback-SDCardCaseFeedbackOutputModel.json",new TypeReference(){}); } public CRCardCaseProcedureInitiateOutputModel initiate(String sdReferenceId, CRCardCaseProcedureInitiateInputModel request){ return JsonReader.read("initiate-CRCardCaseProcedureInitiateOutputModel.json",new TypeReference(){}); } public CRCardCaseProcedureRequestOutputModel request(String sdReferenceId, String crReferenceId, CRCardCaseProcedureRequestInputModel request){ return JsonReader.read("request-CRCardCaseProcedureRequestOutputModel.json",new TypeReference(){}); } public CRCardCaseProcedureRetrieveOutputModel retrieve(String sdReferenceId, String crReferenceId){ return JsonReader.read("retrieve-CRCardCaseProcedureRetrieveOutputModel.json",new TypeReference(){}); } public List retrieveBQIds(String sdReferenceId, String crReferenceId, String behaviorQualifier){ return JsonReader.read("retrieveBQIds-String.json",new TypeReference>(){}); } public List retrieveBQs(){ return JsonReader.read("retrieveBQs-String.json",new TypeReference>(){}); } public BQArbitrationRetrieveOutputModel retrieveArbitration(String sdReferenceId, String crReferenceId, String bqReferenceId){ return JsonReader.read("retrieve-BQArbitrationRetrieveOutputModel.json",new TypeReference(){}); } public BQChargebackRetrieveOutputModel retrieveChargeback(String sdReferenceId, String crReferenceId, String bqReferenceId){ return JsonReader.read("retrieve-BQChargebackRetrieveOutputModel.json",new TypeReference(){}); } public BQConsolidationRetrieveOutputModel retrieveConsolidation(String sdReferenceId, String crReferenceId, String bqReferenceId){ return JsonReader.read("retrieve-BQConsolidationRetrieveOutputModel.json",new TypeReference(){}); } public BQResolutionRetrieveOutputModel retrieveResolution(String sdReferenceId, String crReferenceId, String bqReferenceId){ return JsonReader.read("retrieve-BQResolutionRetrieveOutputModel.json",new TypeReference(){}); } public List retrieveRefIds(String sdReferenceId){ return JsonReader.read("retrieveRefIds-String.json",new TypeReference>(){}); } public SDCardCaseRetrieveOutputModel retrieveSD(String sdReferenceId){ return JsonReader.read("retrieveSD-SDCardCaseRetrieveOutputModel.json",new TypeReference(){}); } public CRCardCaseProcedureUpdateOutputModel update(String sdReferenceId, String crReferenceId, CRCardCaseProcedureUpdateInputModel request){ return JsonReader.read("update-CRCardCaseProcedureUpdateOutputModel.json",new TypeReference(){}); } public BQArbitrationUpdateOutputModel updateArbitration(String sdReferenceId, String crReferenceId, String bqReferenceId, BQArbitrationUpdateInputModel request){ return JsonReader.read("update-BQArbitrationUpdateOutputModel.json",new TypeReference(){}); } public BQChargebackUpdateOutputModel updateChargeback(String sdReferenceId, String crReferenceId, String bqReferenceId, BQChargebackUpdateInputModel request){ return JsonReader.read("update-BQChargebackUpdateOutputModel.json",new TypeReference(){}); } public BQConsolidationUpdateOutputModel updateConsolidation(String sdReferenceId, String crReferenceId, String bqReferenceId, BQConsolidationUpdateInputModel request){ return JsonReader.read("update-BQConsolidationUpdateOutputModel.json",new TypeReference(){}); } public BQResolutionUpdateOutputModel updateResolution(String sdReferenceId, String crReferenceId, String bqReferenceId, BQResolutionUpdateInputModel request){ return JsonReader.read("update-BQResolutionUpdateOutputModel.json",new TypeReference(){}); } } package com.theokanning.openai.classification; import lombok.*; import java.util.List; import java.util.Map; /** *

Classifies the specified {@link #query} using provided examples.

*

The endpoint first searches over the labeled examples to select the ones most relevant for the particular query. Then, the relevant examples are combined with the query to construct a prompt to produce the final label via the completions endpoint.

*

Labeled examples can be provided via an uploaded {@link #file}, or explicitly listed in the request using the {@link #examples} parameter for quick tests and small scale use cases.

* Online Docs */ @Builder @NoArgsConstructor @AllArgsConstructor @Data public class ClassificationRequest { /** *

ID of the engine to use for completion.

*

* Online Docs */ @NonNull String model; /** *

Query to be classified.

*

* Online Docs */ @NonNull String query; /** *

A list of examples with labels, in the following format:

*

[["The movie is so interesting.", "Positive"], ["It is quite boring.", "Negative"], ...]

*

All the label strings will be normalized to be capitalized.

*

You should specify either {@link #examples} or {@link #file}, but not both.

*

* Online Docs */ @Singular("example") List> examples; /** *

The ID of the uploaded file that contains training examples. See upload file for how to upload a file of the desired format and purpose.

*

You should specify either {@link #examples} or {@link #file}, but not both.

*

* Online Docs */ String file; /** *

The set of categories being classified. If not specified, candidate labels will be automatically collected from the examples you provide. All the label strings will be normalized to be capitalized.

*

* Defaults to null *

* Online Docs */ @Singular("label") List labels; /** *

ID of the engine to use for Search.

*

* Defaults to ada *

* Online Docs */ String searchModel; /** *

What sampling {@link #temperature} to use. Higher values mean the model will take more risks. Try 0.9 for more creative applications, and 0 (argmax sampling) for ones with a well-defined answer.

*

* Defaults to 0 *

* Online Docs */ Double temperature; /** *

Include the log probabilities on the {@link #logprobs} most likely tokens, as well the chosen tokens. For example, if {@link #logprobs} is 10, the API will return a list of the 10 most likely tokens. the API will always return the logprob of the sampled token, so there may be up to logprobs+1 elements in the response.

*

When {@link #logprobs} is set, completion will be automatically added into {@link #expand} to get the logprobs.

*

* Defaults to null *

* Online Docs */ Integer logprobs; /** *

The maximum number of examples to be ranked by Search when using {@link #file}. Setting it to a higher value leads to improved accuracy but with increased latency and cost.

*

* Defaults to 200 *

* Online Docs */ Integer maxExamples; /** *

Modify the likelihood of specified tokens appearing in the completion.

*

Accepts a json object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this tokenizer tool (which works for both GPT-2 and GPT-3) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.

*

As an example, you can pass {"50256": -100} to prevent the <|endoftext|> token from being generated.

*

* Defaults to null *

* Online Docs */ @Singular("logitBias") Map logitBias; /** *

If set to true, the returned JSON will include a "prompt" field containing the final prompt that was used to request a completion. This is mainly useful for debugging purposes.

*

* Defaults to false *

* Online Docs */ Boolean returnPrompt; /** *

A special boolean flag for showing metadata. If set to true, each document entry in the returned JSON will contain a "metadata" field.

*

This flag only takes effect when {@link #file} is set.

*

* Defaults to false *

* Online Docs */ Boolean returnMetadata; /** *

If an object name is in the list, we provide the full information of the object; otherwise, we only provide the object ID. Currently we support completion and {@link #file} objects for expansion.

*

* Defaults to [] *

* Online Docs */ @Singular("expand") List expand; }package com.sunmi.toastutils; import com.billy.cc.core.component.CC; import com.billy.cc.core.component.CCResult; import com.billy.cc.core.component.CCUtil; import com.billy.cc.core.component.IComponent; public class ComponentT implements IComponent { public String getName() { //指定组件的名称 return "ComponentT"; } public boolean onCall(CC cc) { String actionName = cc.getActionName(); switch (actionName) { case "ToastUtils": //响应actionName为"showActivity"的组件调用 ToastUtils.makeToast("我来自Toast-lib,嘻嘻~"); //跳转到页面:ActivityA // CCUtil.navigateTo(cc, ActivityA.class); //返回处理结果给调用方 CC.sendCCResult(cc.getCallId(), CCResult.success()); //同步方式实现(在return之前听过CC.sendCCResult()返回组件调用结果),return false return false; default: //其它actionName当前组件暂时不能响应,可以通过如下方式返回状态码为-12的CCResult给调用方 CC.sendCCResult(cc.getCallId(), CCResult.errorUnsupportedActionName()); return false; } } } package com.android.NBZxing; import android.app.Application; /** * @Package: com.android.NBZxing * @ClassName: App * @Description: * @Author: SWY * @CreateDate: 2020/10/1 9:22 PM */ public class App extends Application { @Override public void onCreate() { super.onCreate(); // CrashReport.initCrashReport(getApplicationContext(), "99de934384", true); // Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { // @Override // public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) { // // } // }); } } package com.nmys.story.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.nmys.story.exception.TipException; import com.nmys.story.mapper.MetaMapper; import com.nmys.story.model.dto.Types; import com.nmys.story.model.entity.Contents; import com.nmys.story.model.entity.Metas; import com.nmys.story.model.entity.Relationships; import com.nmys.story.service.IContentService; import com.nmys.story.service.IMetaService; import com.nmys.story.service.IRelationshipService; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.annotation.Transient; import org.springframework.stereotype.Service; import java.util.List; /** * @author itachi * @Title: MetaServiceImpl * @Description: 友链实现类 * @date 2018/5/12下午7:59 */ @Service public class MetaServiceImpl implements IMetaService { @Autowired private MetaMapper metaMapper; @Autowired private IRelationshipService relationshipService; @Autowired private IContentService contentService; @Override public List getMetasByType(String type) { return metaMapper.getMetasByType(type); } @Override public void delMetaById(Integer id) { // 根据id查询meta Metas metas = metaMapper.getMetaById(id); if (null != metas) { String type = metas.getType(); String name = metas.getName(); metaMapper.delMetaById(id); // 根据id搜索 List rlist = relationshipService.getRelationshipById(null, id); if (null != rlist) { for (Relationships r : rlist) { // 根据文章的id来查询文章 Contents contents = contentService.getContentById(r.getCid()); if (null != contents) { Contents temp = new Contents(); temp.setCid(r.getCid()); // 分类 if (type.equals(Types.CATEGORY)) { temp.setCategories(reMeta(name, contents.getCategories())); } // 标签 if (type.equals(Types.TAG)) { temp.setTags(reMeta(name, contents.getTags())); } contentService.updateContent(temp); } } } relationshipService.delRelationshipById(null, id); } metaMapper.delMetaById(id); } private String reMeta(String name, String metas) { String[] ms = StringUtils.split(metas, ","); StringBuilder sbuf = new StringBuilder(); for (String m : ms) { if (!name.equals(m)) { sbuf.append(",").append(m); } } if (sbuf.length() > 0) { return sbuf.substring(1); } return ""; } @Override public Metas getMetaById(Integer id) { return metaMapper.getMetaById(id); } @Override public void saveMeta(String type, String name, Integer mid) { if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(name)) { // 根据类型和名字来查询meta List metaVos = metaMapper.selectMetaListByConditions(type, name); Metas metas; if (metaVos.size() != 0) { throw new TipException("已经存在该项"); } else { metas = new Metas(); metas.setName(name); if (null != mid) { // mid不为空,根据mid查询meta Metas original = metaMapper.getMetaById(mid); metas.setMid(mid); // 更新meta metaMapper.updateMeta(metas); // 更新原有文章的categories ----- ????????? // contentService.updateCategory(original.getName(), name); } else { metas.setType(type); // 保存meta metaMapper.saveMeta(metas); } } } } @Override public List getMetaList(String type, String orderby, Integer limit) { PageHelper.startPage(1, limit); List list = metaMapper.getMetasBySql(type); PageInfo pageInfo = new PageInfo(list); return pageInfo.getList(); } @Override public Metas getMeta(String type, String name) { return metaMapper.getMeta(type, name); } @Override public void saveMetas(Integer cid, String names, String type) { if (null == cid) { throw new TipException("项目关联id不能为空"); } if (StringUtils.isNotBlank(names) && StringUtils.isNotBlank(type)) { String[] nameArr = StringUtils.split(names, ","); for (String name : nameArr) { this.saveOrUpdate(cid, name, type); } } } private void saveOrUpdate(Integer cid, String name, String type) { // 根据类型和名称查询metas List metaVos = metaMapper.selectMetaListByConditions(type, name); int mid; Metas metas; if (metaVos.size() == 1) { metas = metaVos.get(0); mid = metas.getMid(); } else if (metaVos.size() > 1) { throw new TipException("查询到多条数据"); } else { metas = new Metas(); metas.setSlug(name); metas.setName(name); metas.setType(type); metaMapper.saveMeta(metas); mid = metas.getMid(); } if (mid != 0) { Long count = relationshipService.countById(cid, mid); if (count == 0) { Relationships relationships = new Relationships(); relationships.setCid(cid); relationships.setMid(mid); relationshipService.saveRelationship(relationships); } } } } package com.revolsys.ui.html.view; import com.revolsys.record.io.format.xml.XmlWriter; import com.revolsys.ui.html.decorator.Decorator; public class NbspElement extends Element { public static final NbspElement INSTANCE = new NbspElement(); @Override public void serializeElement(final XmlWriter out) { out.entityRef("nbsp"); } @Override public void setContainer(final ElementContainer container) { } @Override public void setDecorator(final Decorator decorator) { } } /** Copyright 2009-2013 The MITRE Corporation. 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. * ************************************************************************** * NOTICE * This software was produced for the U. S. Government under Contract No. * W15P7T-12-C-F600, and is subject to the Rights in Noncommercial Computer * Software and Noncommercial Computer Software Documentation Clause * 252.227-7014 (JUN 1995) * * (c) 2012 The MITRE Corporation. All Rights Reserved. * ************************************************************************** **/ package org.mitre.opensextant.toolbox; import gate.AnnotationSet; import gate.Factory; import gate.FeatureMap; import gate.ProcessingResource; import gate.Resource; import gate.creole.AbstractLanguageAnalyser; import gate.creole.ExecutionException; import gate.creole.ResourceInstantiationException; import gate.creole.metadata.CreoleParameter; import gate.creole.metadata.CreoleResource; import gate.creole.metadata.Optional; import gate.creole.metadata.RunTime; import gate.util.InvalidOffsetException; import java.net.URL; import java.util.List; import org.mitre.flexpat.TextMatch; import org.mitre.xtemporal.DateMatch; import org.mitre.xtemporal.XTempException; import org.mitre.xtemporal.XTemporal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * *

* The Date Finder uses regular expression rules specified in an external * file to identify dates in a GATE {@link gate.Document Document}. Any * date found will be added to the output {@link gate.AnnotationSet * AnnotationSet}. *

* *

* Date {@link gate.AnnotationSet Annotation}:
*

    *
  • type = "date"
  • *
*
    * Features: *
  • string - text of the document containing the geocoord
  • *
  • normedDateText - string form of the standarized date
  • *
  • normedDate - standardized date as a Java Date *
*

* *

* * *

* */ @CreoleResource(name = "OpenSextant Date Finder", comment = "A simple plugin that finds and standardizes date references") public class DateFinderPR extends AbstractLanguageAnalyser implements ProcessingResource { private static final long serialVersionUID = 1375472181851584128L; // the xtemporal object which does all of the work private XTemporal xt; // the annotationSet into which the dates will be written private String outputAnnotationSet; // the file containing the geocoord patterns private URL patternFile = null; // the log static Logger log = LoggerFactory.getLogger(DateFinderPR.class); /** * Initializes the DateFinderPR resource. */ private void initialize() { // initialize the Xtemporal xt = new XTemporal(false); try { xt.configure(patternFile); } catch (XTempException e) { log.error("DateFinderPR: Error when loading patternfile" + patternFile.toString() + ":" + e.getMessage()); } // since we don't need the pre/post match text set to length 0 xt.setMatchWidth(0); }// end initialize /** * * @return * @throws ResourceInstantiationException */ @Override public Resource init() throws ResourceInstantiationException { this.initialize(); return this; } /** * * @throws ResourceInstantiationException */ @Override public void reInit() throws ResourceInstantiationException { this.initialize(); } // find all of the dates in a string and put them into a AnnotationSet void findDates(String text, AnnotationSet annotSet) throws ExecutionException { List timeResults = xt.extract_dates(text, document.getName()).matches; // create an annotation for each result if(timeResults != null){ for (TextMatch t : timeResults) { if (t.is_submatch){ continue; } DateMatch d = (DateMatch) t; // fill in all the annotation features FeatureMap feats = Factory.newFeatureMap(); feats.put("string", d.getText()); feats.put("normedDateText", d.datenorm_text); feats.put("normedDate", d.datenorm); feats.put("datePattern", d.pattern_id); feats.put("hierarchy", "Time.date"); feats.put("isEntity", true); // create a "date" annotation try { annotSet.add((long) d.start, (long) d.end, "Date", feats); } catch (InvalidOffsetException e) { log.error("DateFinderPR: Invalid Offset exception when creating date annotation" + e.getMessage()); } } } } /** * * @throws ExecutionException */ public void execute() throws ExecutionException { // get the annotation set into which we will place any annotations found AnnotationSet annotSet = (outputAnnotationSet == null || outputAnnotationSet .equals("")) ? document.getAnnotations() : document .getAnnotations(outputAnnotationSet); // get the text of the document String text = getDocument().getContent().toString(); // find the dates findDates(text, annotSet); } /** * * @return */ public String getOutputAnnotationSet() { return outputAnnotationSet; } /** * * @param outputAnnotationSet */ @Optional @RunTime @CreoleParameter public void setOutputAnnotationSet(String outputAnnotationSet) { this.outputAnnotationSet = outputAnnotationSet; } /** * * @return */ public URL getPatternFile() { return patternFile; } /** * * @param patternFile */ @CreoleParameter public void setPatternFile(URL patternFile) { this.patternFile = patternFile; } } // class DateFinderPR weevent-broker/src/main/java/com/webank/weevent/broker/protocol/mqtt/store/AuthService.java package com.webank.weevent.broker.protocol.mqtt.store; import com.webank.weevent.broker.entiry.AccountEntity; import com.webank.weevent.broker.enums.IsDeleteEnum; import com.webank.weevent.broker.repository.AccountRepository; import lombok.extern.slf4j.Slf4j; /** * @author websterchen * @version v1.0 * @since 2019/6/1 */ @Slf4j public class AuthService { private final boolean isAuth; private final AccountRepository accountRepository; public AuthService(boolean isAuth, AccountRepository accountRepository) { this.isAuth = isAuth; this.accountRepository = accountRepository; } public boolean verifyUserName(String userName, String password) { if (!isAuth) { return true; } AccountEntity accountEntity = accountRepository.findAllByUserNameAndDeleteAt(userName, IsDeleteEnum.NOT_DELETED.getCode()); if (null == accountEntity) { return false; } log.info("accountEntity:{}", accountEntity.toString()); return password.equals(accountEntity.getPassword()); } } package com.alibaba.alink.params.classification; import com.alibaba.alink.params.mapper.RichModelMapperParams; import com.alibaba.alink.params.shared.HasNumThreads; import com.alibaba.alink.params.shared.colname.HasVectorColDefaultAsNull; public interface MultilayerPerceptronPredictParams extends RichModelMapperParams , HasVectorColDefaultAsNull , HasNumThreads { } /* Copyright 2018 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.github.mvpbasearchitecture.data.source.prefs; import android.support.annotation.NonNull; /** * Created by gk. */ public interface PreferencesHelper { //GENERIC boolean getBoolean(@NonNull String key); long getLong(@NonNull String key); int getInt(@NonNull String key); String getString(@NonNull String key); void setBoolean(@NonNull String key, boolean value); void setLong(@NonNull String key, long value); void setInt(@NonNull String key, int value); void getString(@NonNull String key, @NonNull String value); } /* * Copyright 2018 org.LTR4L * * 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.ltr4l.cli; import java.io.File; import java.io.IOException; import java.lang.invoke.MethodHandles; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.ltr4l.Version; import org.ltr4l.query.QuerySet; import org.ltr4l.tools.Config; import org.ltr4l.trainers.AbstractTrainer; public class Train { private static final String REQUIRED_ARG = ""; public static void main(String[] args) throws Exception { Options options = createOptions(); CommandLine line = getCommandLine(options, args); if(line.hasOption("help")) printUsage(options); if(line.hasOption("version")){ System.out.printf("%s release %s\n", MethodHandles.lookup().lookupClass().getCanonicalName(), Version.version); System.exit(0); } // get LTR-algorithm-name String[] params = line.getArgs(); if(params == null || params.length == 0){ System.err.printf("No required argument %s specified\n", REQUIRED_ARG); printUsage(options); } else if(params.length > 1){ System.err.printf("Too many argument is specified: %s\n", params[1]); printUsage(options); } String configPath = getConfigPath(line, params); Config optionalConfig = createOptionalConfig(configPath, line); QuerySet trainingSet = QuerySet.create(optionalConfig.dataSet.training); QuerySet validationSet = QuerySet.create(optionalConfig.dataSet.validation); AbstractTrainer trainer = AbstractTrainer.TrainerFactory.getTrainer(trainingSet, validationSet, configPath, optionalConfig); long startTime = System.currentTimeMillis(); trainer.trainAndValidate(); long endTime = System.currentTimeMillis(); System.out.println("Took " + (endTime - startTime) + " ms to complete epochs."); } public static Options createOptions(){ Option help = new Option( "help", "print this message" ); Option configFile = Option.builder("config").argName("file").hasArg() .desc("use given file for configuration").build(); Option numIte = Option.builder("iterations").argName("num").hasArg() .desc("use given number of iterations").build(); Option trainDataSet = Option.builder("training").argName("file").hasArg() .desc("use given file for training").build(); Option validDataSet = Option.builder("validation").argName("file").hasArg() .desc("use given file for validation").build(); Option modelFile = Option.builder("model").argName("file").hasArg() .desc("specify model file name").build(); Option reportFile = Option.builder("report").argName("file").hasArg() .desc("specify report file name").build(); Option version = new Option( "version", "print the version information and exit" ); Option verbose = new Option( "verbose", "be extra verbose" ); Option noverbose = new Option( "noverbose", "override verboseness" ); Option nomodel = new Option( "nomodel", "restrain model output" ); Option debug = new Option( "debug", "print debugging information" ); Options options = new Options(); options.addOption(help) .addOption(configFile) .addOption(numIte) .addOption(trainDataSet) .addOption(validDataSet) .addOption(modelFile) .addOption(reportFile) .addOption(version) .addOption(verbose) .addOption(noverbose) .addOption(nomodel) .addOption(debug); return options; } public static CommandLine getCommandLine(Options options, String[] args){ CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { // parse the command line arguments line = parser.parse(options, args); } catch(ParseException exp) { // oops, something went wrong System.err.printf("Parsing failed. Reason: %s\n\n", exp.getMessage()); printUsage(options); } return line; } public static void printUsage(Options options){ HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( "train " + REQUIRED_ARG, "\nExecute Learning-to-Rank training algorithm. The algorithm is specified by the required argument ." + " The program will look for the configuration file \"config/.json\"" + " unless config option is specified." + " The following options can be specified in order to override the existing settings in the config file.\n\n", options, null, true ); System.exit(0); } public static String getConfigPath(CommandLine line, String[] params){ assert(params.length == 1); return line.hasOption("config") ? line.getOptionValue("config") : String.format("confs/%s.json", params[0]); } public static Config createOptionalConfig(String configPath, CommandLine line) throws IOException { ObjectMapper mapper = new ObjectMapper(); Config optionalConfig = mapper.readValue(new File(configPath), Config.class); if(line.hasOption("iterations")) optionalConfig.numIterations = Integer.parseInt(line.getOptionValue("iterations")); if(line.hasOption("verbose")) optionalConfig.verbose = true; if(line.hasOption("noverbose")) optionalConfig.verbose = false; // noverbose always overrides verboseness if(line.hasOption("training")) optionalConfig.dataSet.training = line.getOptionValue("training"); if(line.hasOption("validation")) optionalConfig.dataSet.validation = line.getOptionValue("validation"); if(line.hasOption("model")) { if(optionalConfig.model == null) optionalConfig.model = new Config.Model(); optionalConfig.model.file = line.getOptionValue("model"); } if(line.hasOption("nomodel")) optionalConfig.nomodel = true; if(line.hasOption("report")) optionalConfig.report.file = line.getOptionValue("report"); return optionalConfig; } } 100-1000 package com.firsts; //Takes a Rotated and Increasing Sorted array, a target and returns its index public class RotatedArray { static int rotatedBinarySearch(int[] arr,int target){ int pivot = findPivot(arr); if(pivot == -1) return binarySearch(arr,target,0,arr.length - 1); else if(target == arr[pivot]) return pivot; else if (target >= arr[0])//if the target is greater than arr[0],target lies in the left portion of the pivot return binarySearch(arr,target,0,pivot - 1); return binarySearch(arr,target,pivot + 1,arr.length - 1);//else right portion of the pivot } /*Pivot is the peak element in the rotated sorted array and last element in its original sorted array All the elements left to the pivot are increasingly sorted ,pivot and pivot + 1 are dec sorted and pivot + 1 to last index are increasingly sorted again*/ /*Since pivot is the last index of the original array,in rot sorted array all the elements left to the pivot are always greater than all the elements right to the pivot*/ static int findPivot(int[] arr){ int start = 0; int end = arr.length - 1; while(start < end){ int mid = start + (end - start) / 2; if(arr[mid] > arr[mid + 1]) return mid; //return mid, if mid is on the pivot index if(arr[mid] < arr[mid - 1]) return mid - 1; // return mid - 1,if mid is on the pivot + 1 index if(arr[start] < arr[mid]) start = mid + 1; // mid is on the left side of the pivot and left portion(start to mid)is sorted else end = mid - 1;//mid is on the right side ,so we move to the left of mid } return -1;//return -1 if pivot is not found (case of strictly inc array) } static int binarySearch(int[] arr,int target,int start,int end){ while(start <= end){ int mid = start + (end - start) / 2; if(target > arr[mid]) start = mid + 1; else if (target < arr[mid]) end = mid - 1; else return mid; } return -1; } public static void main(String[] args) { int[] arr = {10,12,15,18,19,1,3,4,5,6,7,8}; int target = 15; System.out.println(rotatedBinarySearch(arr,target)); } } src/main/java/org/fatmansoft/teach/controllers/academic/CourseSelectionController.java package org.fatmansoft.teach.controllers.academic; import org.fatmansoft.teach.SpringBootSecurityJwtApplication; import org.fatmansoft.teach.SystemApplicationListener; import org.fatmansoft.teach.models.academic.CourseSelection; import org.fatmansoft.teach.payload.request.DataRequest; import org.fatmansoft.teach.payload.response.DataResponse; import org.fatmansoft.teach.repository.academic.CourseSelectionRepository; import org.fatmansoft.teach.service.academic.CourseSelectionService; import org.fatmansoft.teach.service.academic.CourseService; import org.fatmansoft.teach.util.CommonMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import javax.validation.Valid; import java.util.*; @CrossOrigin(origins = "*", maxAge = 3600) @RestController @RequestMapping("/api/teach") public class CourseSelectionController { private static final Logger logger = LoggerFactory.getLogger(SpringBootSecurityJwtApplication.class); @Resource private CourseSelectionService courseSelectionService; @PostMapping("/courseSelectionInit") @PreAuthorize("hasRole('ADMIN')") public DataResponse courseSelectionInit(@Valid @RequestBody DataRequest dataRequest) { List result = courseSelectionService.getAllCourseSelection(dataRequest); return CommonMethod.getReturnData(result); } @PostMapping("/courseSelectionEditInit") @PreAuthorize("hasRole('ADMIN')") public DataResponse courseSelectionEditInit(@Valid @RequestBody DataRequest dataRequest) { Map result = courseSelectionService.getCourseSelectionDetail(dataRequest); return CommonMethod.getReturnData(result); } @PostMapping("/courseSelectionEditSubmit") @PreAuthorize("hasRole('ADMIN')") public DataResponse courseSelectionEditSubmit(@Valid @RequestBody DataRequest dataRequest) { Integer result = courseSelectionService.saveCourseSelection(dataRequest); return CommonMethod.getReturnData(result); } @PostMapping("/courseSelectionDelete") @PreAuthorize("hasRole('ADMIN')") public DataResponse courseSelectionDelete(@Valid @RequestBody DataRequest dataRequest) { courseSelectionService.deleteCourseSelection(dataRequest); return CommonMethod.getReturnMessageOk(); } } AndrewQuijano/SSTREU2017 package Localization.structs; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.math.BigInteger; import java.util.List; //import security.DGK.DGKPrivateKey; //import security.paillier.PaillierPrivateKey; import Localization.LOCALIZATION_SCHEME; import security.DGK.DGKPublicKey; import security.elgamal.ElGamalPublicKey; import security.elgamal.ElGamal_Ciphertext; import security.paillier.PaillierPublicKey; public class SendLocalizationData implements Serializable { //Localization Parameters public final LOCALIZATION_SCHEME LOCALIZATION_SCHEME; // PlainText Data public final Integer [] RSS; public final String [] APs; // Secure Triple Data Paillier and DGK public final BigInteger [] S2; public final BigInteger [] S3_comp; public final BigInteger S3; // Secure Triple Data ElGamal public final List e_S2; public final List e_S3_comp; public final ElGamal_Ciphertext e_S3; private static final long serialVersionUID = 201194517759072124L; // Public Keys public final ElGamalPublicKey e_pk; public final DGKPublicKey pubKey; public final PaillierPublicKey pk; // Mode public final boolean isREU2017; // Phone data just in case it filtering by phone data public final String [] phone_data; // Also, now the tables are by map public final String map; // PlainText public SendLocalizationData(String [] APs, Integer [] RSS, DGKPublicKey pubKey, LOCALIZATION_SCHEME local, boolean isREU2017, String [] phone_data, String map) { this.RSS = RSS; this.APs = APs; this.LOCALIZATION_SCHEME = local; this.S2 = null; this.S3 = null; this.S3_comp = null; this.e_S2 = null; this.e_S3 = null; this.e_S3_comp = null; this.pubKey = pubKey; this.pk = null; this.e_pk = null; this.isREU2017 = isREU2017; this.phone_data = phone_data; this.map = map; } // Paillier, yes you need the DGK Key just in case you run comparison protocol! public SendLocalizationData(String [] APs, BigInteger[] S2, BigInteger S3, BigInteger [] S3_comp, PaillierPublicKey pk, DGKPublicKey _pubKey, LOCALIZATION_SCHEME local, boolean isREU2017, String [] phone_data, String map) { this.RSS = null; this.APs = APs; this.S2 = S2; this.S3 = S3; this.S3_comp = S3_comp; this.e_S2 = null; this.e_S3 = null; this.e_S3_comp = null; this.LOCALIZATION_SCHEME = local; this.pubKey = _pubKey; this.pk = pk; this.e_pk = null; this.isREU2017 = isREU2017; this.phone_data = phone_data; this.map = map; } // DGK public SendLocalizationData(String [] APs, BigInteger [] S2, BigInteger S3, BigInteger [] S3_comp, DGKPublicKey pubKey, LOCALIZATION_SCHEME local, boolean isREU2017, String [] phone_data, String map) { this.RSS = null; this.APs = APs; this.S2 = S2; this.S3 = S3; this.S3_comp = S3_comp; this.e_S2 = null; this.e_S3 = null; this.e_S3_comp = null; this.LOCALIZATION_SCHEME = local; this.pubKey = pubKey; this.pk = null; this.e_pk = null; this.isREU2017 = isREU2017; this.phone_data = phone_data; this.map = map; } // ElGamal, yes you need the DGK Key just in case you run comparison protocol! public SendLocalizationData(String [] APs, List e_S2, ElGamal_Ciphertext e_S3, List e_S3_comp, ElGamalPublicKey pk, DGKPublicKey pubKey, LOCALIZATION_SCHEME local, boolean isREU2017, String [] phone_data, String map) { this.RSS = null; this.APs = APs; this.S2 = null; this.S3 = null; this.S3_comp = null; this.e_S2 = e_S2; this.e_S3 = e_S3; this.e_S3_comp = e_S3_comp; this.LOCALIZATION_SCHEME = local; this.pubKey = pubKey; this.pk = null; this.e_pk = pk; this.isREU2017 = isREU2017; this.phone_data = phone_data; this.map = map; } private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException { aInputStream.defaultReadObject(); } private void writeObject(ObjectOutputStream aOutputStream) throws IOException { aOutputStream.defaultWriteObject(); } }app/src/main/java/com/blogspot/thanhstech/hdtodo/EditItemActivity.java package com.blogspot.thanhstech.hdtodo; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class EditItemActivity extends AppCompatActivity { private EditText etItemEditView; private int pos; private String value; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_item); value = getIntent().getStringExtra("editValue"); pos = getIntent().getIntExtra("editPosition", 0); etItemEditView = (EditText)findViewById(R.id.etItemEditView); etItemEditView.setText(value); } @Override public void onBackPressed() { doFinish(value); } public void onSubmit(View view) { doFinish(((EditText)findViewById(R.id.etItemEditView)).getText().toString()); } /** * Sets return value and position and finishes the activity * @param updatedValue */ private void doFinish(String updatedValue) { Intent data = new Intent(); data.putExtra("updatedValue",updatedValue ); data.putExtra("updatedPos",pos ); setResult(1, data); finish(); } } package me.liuhui.mall.repository.model.enums; import lombok.Getter; /** * Created on 2020/10/27 17:28 *

* Description: [TODO] *

* Company: [] * * @author [清远] */ @Getter public enum UserStatus { /** * */ NORMAL(1, "正常"), FROZEN(2, "冻结"); private final Integer code; private final String desc; UserStatus(Integer code, String desc) { this.code = code; this.desc = desc; } } /* Vous êtes libre de : */ package info.emptycanvas.library.object; public class MODHomothetie { private Point3D centre; private double f; public Point3D centre() { return centre; } public void centre(Point3D p) { this.centre = p; } public double facteur() { return f; } public void facteur(double d) { this.f = d; return; } } package com.suwonsmartapp.tourlist.database; /** * Created by Administrator on 2015-04-09. */ public class Info_PHOTODT { public int _id; public int mid; public String fullUrl; public String wdt; public Info_PHOTODT() { } public Info_PHOTODT(int mid, String fullUrl){ this.mid = mid; this.fullUrl = fullUrl; } public Info_PHOTODT(int _id, int mid, String fullUrl, String wdt){ this._id = _id; this.mid = mid; this.fullUrl = fullUrl; this.wdt = wdt; } } package game.server.controller; import static org.junit.Assert.*; import game.server.model.Dinar; import game.server.model.Game; import game.server.model.InitialCard; import game.server.model.Player; import game.server.model.Region; import game.server.model.Sheep; import game.server.model.SheepBlack; import game.server.model.Shepherd; import game.server.model.StandardCard; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import javax.rmi.CORBA.Util; import org.junit.Test; /** * Main game score counter-test class * * @author Dario * */ public class CounterTest { /** * private constructor test */ @Test public void constructorTest(){ try { Constructor c = Util.class.getDeclaredConstructor(); c.setAccessible(true); c.newInstance(); } catch (Exception e) {;} assertTrue(true); } /** * Check if the score compute of each player is correct */ @Test public void doStatsTest(){ int checktot = 2; List sheplist = new ArrayList(); sheplist.add(new Shepherd(0, "red")); List dinlist = new ArrayList(); dinlist.add(new Dinar()); Player pl = new Player("testplayer", sheplist, dinlist,new InitialCard("Hill", 0)); pl.addCardToOwned(new StandardCard("Hill", 0, 0)); List> regType = new ArrayList>(); List reglist = new ArrayList(); reglist.add(new Region(0, new Sheep(), "Hill")); regType.add(reglist); Counter.doStats(pl, null, regType); assertEquals(checktot, pl.getScore()); } /** * Check if the score compute of each player is correct and even for black sheep and plot value */ @Test public void doStatsTestB(){ int checktot = 4; List sheplist = new ArrayList(); sheplist.add(new Shepherd(0, "red")); List dinlist = new ArrayList(); dinlist.add(new Dinar()); Player pl = new Player("testplayer", sheplist, dinlist,new InitialCard("Hill", 0)); pl.addCardToOwned(new StandardCard("Hill", 0, 0)); List> regType = new ArrayList>(); List reglist = new ArrayList(); reglist.add(new Region(0, new Sheep(), "Hill")); reglist.get(0).addANewBlackSheep(new SheepBlack()); regType.add(reglist); Counter.doStats(pl, null, regType); assertEquals(checktot, pl.getScore()); } /** * Checking if sorting return a correct value */ @Test public void playerScoreSortingTest(){ List playList = new ArrayList(); List> checkScore = new ArrayList>(); Player pl0 = new Player(); Player pl1 = new Player(); pl0.setScore(5); pl1.setScore(10); playList.add(pl0); playList.add(pl1); List score1 = new ArrayList(); score1.add(1); score1.add(10); List score0 = new ArrayList(); score0.add(0); score0.add(5); checkScore.add(score1); checkScore.add(score0); //exec List> returnlist = Counter.playersScoreSorting(playList); assertTrue( checkScore.get(0).get(0) == returnlist.get(1).get(0) && checkScore.get(1).get(0) == returnlist.get(0).get(0) ); } /** * Check score */ @Test public void showScoreStatsTest(){ Game g = new Game(); Counter.showScoreStats(g, true); assertTrue(g.isAllPlayersInitialized()); } } package org.axesoft.jaxos.algo; import org.slf4j.Logger; public class RunnableWithLog implements Runnable { private int squadId; private Runnable r; private Logger logger; public RunnableWithLog(Logger logger, Runnable r) { this(-1, logger, r); } public RunnableWithLog(int squadId, Logger logger, Runnable r) { this.squadId = squadId; this.r = r; this.logger = logger; } @Override public void run() { try { r.run(); } catch (Exception e) { if (e.getCause() instanceof InterruptedException) { Thread.currentThread().interrupt(); throw e; } else { String msg = squadId >= 0 ? "Exec error" : "S " + squadId + " Exec ballot task error"; logger.error(msg, e); } } } } web-florist/src/main/java/com/sxm/florist/service/FloristFlowersService.java /* * * * */ package com.sxm.florist.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.sxm.core.repository.BaseRepository; import com.sxm.core.service.BaseService; import com.sxm.florist.domain.FloristFlowers; import com.sxm.florist.repository.FloristFlowersRepository; /** * 鲜花Service. * * @author sxm * @version 2016-05-23 * @---------------------------------------------------------------------------------------- * @updated 修改描述. * @updated by sxm * @updated at 2016-05-23 */ @Service @Transactional public class FloristFlowersService extends BaseService { @SuppressWarnings("unused") private static Logger logger = LoggerFactory.getLogger(FloristFlowersService.class); @Autowired private FloristFlowersRepository floristFlowersRepository; @Override public BaseRepository getRepository() { return floristFlowersRepository; } } 100-1000 package com.king.wanandroid.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.zip.Deflater; import java.util.zip.Inflater; public class Base64 { private static final int LOWER_CASE_A_VALUE = 26; private static final int ZERO_VALUE = 52; private static final int PLUS_VALUE = 62; private static final int SLASH_VALUE = 63; private static final int SIX_BIT_MASK = 63; private static final int EIGHT_BIT_MASK = 255; private String mString; private int mIndex = 0; public static String encode(byte[] data) { return new Base64().internalEncode(data); } public String internalEncode(byte[] data) { int charCount = data.length * 4 / 3 + 4; StringBuffer result = new StringBuffer(charCount * 77 / 76); int byteArrayLength = data.length; int byteArrayIndex = 0; int byteTriplet = 0; while (byteArrayIndex < byteArrayLength - 2) { byteTriplet = convertUnsignedByteToInt(data[(byteArrayIndex++)]); byteTriplet <<= 8; byteTriplet |= convertUnsignedByteToInt(data[(byteArrayIndex++)]); byteTriplet <<= 8; byteTriplet |= convertUnsignedByteToInt(data[(byteArrayIndex++)]); byte b4 = (byte) (0x3F & byteTriplet); byteTriplet >>= 6; byte b3 = (byte) (0x3F & byteTriplet); byteTriplet >>= 6; byte b2 = (byte) (0x3F & byteTriplet); byteTriplet >>= 6; byte b1 = (byte) (0x3F & byteTriplet); result.append(mapByteToChar(b1)); result.append(mapByteToChar(b2)); result.append(mapByteToChar(b3)); result.append(mapByteToChar(b4)); } if (byteArrayIndex == byteArrayLength - 1) { byteTriplet = convertUnsignedByteToInt(data[(byteArrayIndex++)]); byteTriplet <<= 4; byte b2 = (byte) (0x3F & byteTriplet); byteTriplet >>= 6; byte b1 = (byte) (0x3F & byteTriplet); result.append(mapByteToChar(b1)); result.append(mapByteToChar(b2)); result.append("=="); } if (byteArrayIndex == byteArrayLength - 2) { byteTriplet = convertUnsignedByteToInt(data[(byteArrayIndex++)]); byteTriplet <<= 8; byteTriplet |= convertUnsignedByteToInt(data[(byteArrayIndex++)]); byteTriplet <<= 2; byte b3 = (byte) (0x3F & byteTriplet); byteTriplet >>= 6; byte b2 = (byte) (0x3F & byteTriplet); byteTriplet >>= 6; byte b1 = (byte) (0x3F & byteTriplet); result.append(mapByteToChar(b1)); result.append(mapByteToChar(b2)); result.append(mapByteToChar(b3)); result.append("="); } return result.toString(); } public static byte[] decode(String data) { return new Base64().internalDecode(data); } public byte[] internalDecode(String data) { this.mString = data; this.mIndex = 0; int mUsefulLength = 0; int length = this.mString.length(); for (int i = 0; i < length; i++) { if (isUsefulChar(this.mString.charAt(i))) { mUsefulLength++; } } int byteArrayLength = mUsefulLength * 3 / 4; byte[] result = new byte[byteArrayLength]; int byteTriplet = 0; int byteIndex = 0; while (byteIndex + 2 < byteArrayLength) { byteTriplet = mapCharToInt(getNextUsefulChar()); byteTriplet <<= 6; byteTriplet |= mapCharToInt(getNextUsefulChar()); byteTriplet <<= 6; byteTriplet |= mapCharToInt(getNextUsefulChar()); byteTriplet <<= 6; byteTriplet |= mapCharToInt(getNextUsefulChar()); result[(byteIndex + 2)] = (byte) (byteTriplet & 0xFF); byteTriplet >>= 8; result[(byteIndex + 1)] = (byte) (byteTriplet & 0xFF); byteTriplet >>= 8; result[byteIndex] = (byte) (byteTriplet & 0xFF); byteIndex += 3; } if (byteIndex == byteArrayLength - 1) { byteTriplet = mapCharToInt(getNextUsefulChar()); byteTriplet <<= 6; byteTriplet |= mapCharToInt(getNextUsefulChar()); byteTriplet >>= 4; result[byteIndex] = (byte) (byteTriplet & 0xFF); } if (byteIndex == byteArrayLength - 2) { byteTriplet = mapCharToInt(getNextUsefulChar()); byteTriplet <<= 6; byteTriplet |= mapCharToInt(getNextUsefulChar()); byteTriplet <<= 6; byteTriplet |= mapCharToInt(getNextUsefulChar()); byteTriplet >>= 2; result[(byteIndex + 1)] = (byte) (byteTriplet & 0xFF); byteTriplet >>= 8; result[byteIndex] = (byte) (byteTriplet & 0xFF); } return result; } private int mapCharToInt(char c) { if ((c >= 'A') && (c <= 'Z')) { return c - 'A'; } if ((c >= 'a') && (c <= 'z')) { return c - 'a' + 26; } if ((c >= '0') && (c <= '9')) { return c - '0' + 52; } if (c == '+') { return 62; } if (c == '/') { return 63; } throw new IllegalArgumentException(c + " is not a valid Base64 character."); } private char mapByteToChar(byte b) { if (b < 26) { return (char) (65 + b); } if (b < 52) { return (char) (97 + (b - 26)); } if (b < 62) { return (char) (48 + (b - 52)); } if (b == 62) { return '+'; } if (b == 63) { return '/'; } throw new IllegalArgumentException("Byte " + new Integer(b) + " is not a valid Base64 value"); } private boolean isUsefulChar(char c) { return ((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9')) || (c == '+') || (c == '/'); } private char getNextUsefulChar() { char result = '_'; while (!isUsefulChar(result)) { result = this.mString.charAt(this.mIndex++); } return result; } private int convertUnsignedByteToInt(byte b) { if (b >= 0) { return b; } return 256 + b; } public static String getEncodeMsg(String tMessage) { String returnStr = ""; try { ByteArrayOutputStream byteStream = getCompressedStr(tMessage); if (byteStream != null) returnStr = encode(byteStream.toByteArray()); } catch (Exception ex) { ex.printStackTrace(); } return returnStr; } private static ByteArrayOutputStream getCompressedStr(String tMessage) { ByteArrayOutputStream compressedStream = null; try { if ((tMessage != null) && (!"".equals(tMessage))) { byte[] input = tMessage.getBytes("UTF-8"); Deflater compresser = new Deflater(); compresser.setInput(input); compresser.finish(); compressedStream = new ByteArrayOutputStream(); byte[] buf = new byte[2048]; while (!compresser.finished()) { int got = compresser.deflate(buf); if (got < 1) break; compressedStream.write(buf, 0, got); } compresser.end(); } } catch (Exception ioex) { ioex.printStackTrace(); } finally { if (compressedStream != null) { try { compressedStream.close(); } catch (IOException ioex) { ioex.printStackTrace(); } } } return compressedStream; } public static String getDecodeMsg(String tMessage) { String outputString = ""; byte[] inputStr = null; try { String newStr = tMessage; newStr = newStr.replaceAll(" ", "+"); inputStr = decode(newStr); outputString = getDeCompressedStr(inputStr); } catch (Exception ex) { ex.printStackTrace(); } return outputString; } private static String getDeCompressedStr(byte[] tMessage) { String returnStr = ""; ByteArrayOutputStream aDeCompressedStream = null; try { Inflater decompresser = new Inflater(); decompresser.setInput(tMessage); aDeCompressedStream = new ByteArrayOutputStream(); byte[] buf = new byte[2048]; while (!decompresser.finished()) { int got = decompresser.inflate(buf); if (got < 1) break; aDeCompressedStream.write(buf, 0, got); } decompresser.end(); } catch (Exception ioex) { ioex.printStackTrace(); } finally { try { if (aDeCompressedStream != null) aDeCompressedStream.close(); } catch (IOException ioex) { ioex.printStackTrace(); } } try { if (aDeCompressedStream != null) { returnStr = aDeCompressedStream.toString("UTF-8"); } } catch (UnsupportedEncodingException encodeEx) { encodeEx.printStackTrace(); } return returnStr; } }mainActivity/src/main/java/co/wakarimasen/ceredux/BoardCategoryIndexer.java package co.wakarimasen.ceredux; /* * Copyright (C) 2008 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. */ import android.util.SparseIntArray; import android.widget.AlphabetIndexer; import android.widget.SectionIndexer; import co.wakarimasen.ceredux.imageboard.Board; /** * A {@link SectionIndexer} implementation on an array of {@link String} objects. * Based on the {@link AlphabetIndexer}. */ public class BoardCategoryIndexer implements SectionIndexer { /** * The array of data */ protected BoardDataSource mArray; /** * The string of characters that make up the indexing sections. */ // protected CharSequence mAlphabet; /** * Cached length of the alphabet array. */ private int mAlphabetLength; /** * This contains a cache of the computed indices so far. It will get reset whenever * the dataset changes or the cursor changes. */ private SparseIntArray mAlphaMap; /** * The section array converted from the alphabet string. */ private String[] mAlphabetArray; /** * Constructs the indexer. * @param cursor the cursor containing the data set * @param sortedColumnIndex the column number in the cursor that is sorted * alphabetically * @param alphabet string containing the alphabet, with space as the first character. * For example, use the string " ABCDEFGHIJKLMNOPQRSTUVWXYZ" for English indexing. * The characters must be uppercase and be sorted in ascii/unicode order. Basically * characters in the alphabet will show up as preview letters. */ public BoardCategoryIndexer(BoardDataSource data) { mArray = data; mAlphabetLength = co.wakarimasen.ceredux.imageboard.Board.categories.size(); mAlphabetArray = new String[mAlphabetLength]; for (int i = 0; i < mAlphabetLength; i++) { mAlphabetArray[i] = co.wakarimasen.ceredux.imageboard.Board.categories.get(i).getName(); } mAlphaMap = new SparseIntArray(mAlphabetLength); } /** * Returns the section array constructed from the alphabet provided in the constructor. * @return the section array */ @Override public Object[] getSections() { return mAlphabetArray; } /** * Performs a binary search or cache lookup to find the first row that * matches a given section's starting letter. * @param sectionIndex the section to search for * @return the row index of the first occurrence, or the nearest next letter. * For instance, if searching for "T" and no "T" is found, then the first * row starting with "U" or any higher letter is returned. If there is no * data following "T" at all, then the list size is returned. */ @Override public int getPositionForSection(int sectionIndex) { final SparseIntArray alphaMap = mAlphaMap; final BoardDataSource array = mArray; if (array == null) { return 0; } // Check bounds if (sectionIndex <= 0) { return 0; } if (sectionIndex >= mAlphabetLength) { sectionIndex = mAlphabetLength - 1; } int count = array.size(); int start = 0; int end = count; int pos; Board.Category targetGroup = Board.categories.get(sectionIndex); int key = targetGroup.hashCode(); // Check map if (Integer.MIN_VALUE != (pos = alphaMap.get(key, Integer.MIN_VALUE))) { // Is it approximate? Using negative value to indicate that it's // an approximation and positive value when it is the accurate // position. if (pos < 0) { pos = -pos; end = pos; } else { // Not approximate, this is the confirmed start of section, return it return pos; } } // Do we have the position of the previous section? if (sectionIndex > 0) { int prevLetter = Board.categories.get(sectionIndex - 1).hashCode(); int prevLetterPos = alphaMap.get(prevLetter, Integer.MIN_VALUE); if (prevLetterPos != Integer.MIN_VALUE) { start = Math.abs(prevLetterPos); } } // Now that we have a possibly optimized start and end, let's binary search pos = (end + start) / 2; while (pos < end) { // Get letter at pos Board curName = array.get(pos); if (curName == null) { if (pos == 0) { break; } else { pos--; continue; } } if (!curName.getCategory().equals(targetGroup)) { // TODO: Commenting out approximation code because it doesn't work for certain // lists with custom comparators // Enter approximation in hash if a better solution doesn't exist // String startingLetter = Character.toString(getFirstLetter(curName)); // int startingLetterKey = startingLetter.charAt(0); // int curPos = alphaMap.get(startingLetterKey, Integer.MIN_VALUE); // if (curPos == Integer.MIN_VALUE || Math.abs(curPos) > pos) { // Negative pos indicates that it is an approximation // alphaMap.put(startingLetterKey, -pos); // } // if (mCollator.compare(startingLetter, targetLetter) < 0) { if (Board.categories.indexOf(curName.getCategory()) < Board.categories.indexOf(targetGroup)) { start = pos + 1; if (start >= count) { pos = count; break; } } else { end = pos; } } else { // They're the same, but that doesn't mean it's the start if (start == pos) { // This is it break; } else { // Need to go further lower to find the starting row end = pos; } } pos = (start + end) / 2; } alphaMap.put(key, pos); return pos; } /** * Returns the section index for a given position in the list by querying the item * and comparing it with all items in the section array. */ @Override public int getSectionForPosition(int position) { Board curBoard = mArray.get(position); // Linear search, as there are only a few items in the section index // Could speed this up later if it actually gets used. //for (int i = 0; i < mAlphabetLength; i++) { // if (curBoard.getCategory().equals(Board.categories.get(i))) { // return i; // } //} return Math.max(Board.categories.indexOf(curBoard.getCategory()), 0); // Don't recognize the letter - falls under zero'th section } public void resetCache() { mAlphaMap.clear(); } public interface BoardDataSource { public T get(int position); public int size(); } } package Apc; import java.io.*; class Apc_59_4 { public static void main(String args[])throws IOException { InputStreamReader ab = new InputStreamReader(System.in); BufferedReader cd = new BufferedReader(ab); int m[]={5,7,9,11,15,20,30,45,89,97}; System.out.println("Enter a number to check whether it is present or not::"); int ns = Integer.parseInt(cd.readLine()); int ub=9,lb=0,p,k=0,pos=0; while(lb<=ub) { p=(ub+lb)/2; if(m[p]ns) { ub=p-1; } if(m[p]==ns) { k=1; pos = p; break; } } if(k==1) { System.out.println("FOUND "+pos); } else { System.out.println("SEARCHED ELEMENT NOT FOUND"); } } } 1-10 package glap.model; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the role database table. * */ @Entity @Table(name="role") @NamedQuery(name="Role.findAll", query="SELECT r FROM Role r") public class Role implements Serializable { private static final long serialVersionUID = 1L; @EmbeddedId private RolePK id; @Column(name="porteur_projet", nullable=false) private byte porteurProjet; //bi-directional many-to-one association to Idee @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="idee_id", nullable=false, insertable=false, updatable=false) private Idee idee; //bi-directional many-to-one association to Membre @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name="membre_id", nullable=false, insertable=false, updatable=false) private Membre membre; public Role() { } public RolePK getId() { return this.id; } public void setId(RolePK id) { this.id = id; } public byte getPorteurProjet() { return this.porteurProjet; } public void setPorteurProjet(byte porteurProjet) { this.porteurProjet = porteurProjet; } public Idee getIdee() { return this.idee; } public void setIdee(Idee idee) { this.idee = idee; } public Membre getMembre() { return this.membre; } public void setMembre(Membre membre) { this.membre = membre; } }package io.cattle.platform.archaius.sources; import java.util.HashMap; import java.util.Map; import org.apache.commons.configuration.MapConfiguration; import org.apache.commons.lang.StringUtils; public abstract class AbstractTransformedEnvironmentProperties extends MapConfiguration implements NamedConfigurationSource { public AbstractTransformedEnvironmentProperties(String contains, String prefix) { super(getValues(contains, prefix)); } protected static Map getValues(String contains, String prefix) { Map values = new HashMap(); for (Map.Entry entry : System.getenv().entrySet()) { String key = entry.getKey(); if (StringUtils.isNotBlank(contains) && !key.contains(contains)) { continue; } if (key.startsWith(prefix)) { key = key.substring(prefix.length()); } key = key.replace('_', '.').toLowerCase(); if (!StringUtils.isBlank(entry.getValue())) { values.put(key, entry.getValue()); } } return values; } } s20834/SORCER-multiFi /* * Copyright 2014 Sorcersoft.com S.A. * * 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 sorcer.container.jeri; import net.jini.jeri.http.HttpServerEndpoint; import sorcer.util.Sorcer; import javax.inject.Provider; import java.net.UnknownHostException; /** * @author */ public class HttpServerEndpointFactory implements Provider { private String host; /** * Construct TcpServerEndpointFactory with {@link sorcer.core.SorcerEnv#getHostAddress()} as the listening address and port 0. * * @throws IllegalStateException if the local address cannot be obtained. */ public HttpServerEndpointFactory() { try { host = Sorcer.getHostAddress(); } catch (UnknownHostException e) { throw new IllegalStateException("Could not resolve local address", e); } } @Override public HttpServerEndpoint get() { return HttpServerEndpoint.getInstance(host, 0); } } 0 package protocol; import lombok.AllArgsConstructor; import lombok.Getter; /** * Monique message with tag * * @author * */ @Getter @AllArgsConstructor public class MoniqueTaggedMessage { private String tag; private MoniqueMessage moniqueMessage; } /* Copyright 2014 Google Inc. 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 com.google.cloud.genomics.api.client.commands.align; import com.beust.jcommander.Parameter; import com.beust.jcommander.Parameters; import com.google.api.services.genomics.model.AlignReadGroupSetsRequest; import com.google.api.services.genomics.model.InterleavedFastqSource; import java.util.List; @Parameters(commandDescription = "Align interleaved FASTQs from Google Cloud Storage") public class AlignInterleavedFastqsCommand extends BaseAlignFastqsCommand { @Parameter(names = "--fastq_file", description = "An interleaved FASTQ file (as Google Cloud Storage gs:// URL) to be" + " aligned. You can use a wildcard in this flag to specify multiple files at once" + " (e.g. gs://mybucket/myfiles/*.fastq) or use the flag multiple times if a wildcard" + " won't work.", required = true) public List fastqFiles; @Override protected AlignReadGroupSetsRequest getRequest() { return new AlignReadGroupSetsRequest() .setInterleavedFastqSource(new InterleavedFastqSource() .setSourceUris(fastqFiles) .setMetadata(getMetadata())); } @Override protected List getSources() { return fastqFiles; } } huashen/Takin /* * Copyright 2021 Shulie Technology, Co.Ltd * Email: * 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, * See the License for the specific language governing permissions and * limitations under the License. */ package com.pamirs.tro.entity.domain.entity.linkmanage; import java.util.Set; import lombok.Data; /** * @description: 节点IP信息、MQ TOPIC信息、DB 链接 表信息等 * @author: * @create: 2020-07-19 13:56 **/ @Data public class VertexOpData { private Set ipList; private Set dataList; private Set unKnowIpList; } package frameworkjava.interfaceprac.func; public class FuncPractice2 { public static void main(String[] args) { // 익명 메소드를 사용해서 표현하는 방법 : 람다 표현식 MyRunnable r1 = () -> System.out.println("Hello"); MyRunnable r2 = new MyRunnable() { @Override public void run() { System.out.println("Hello"); } }; r2.run(); MySupply s1 = () -> "hello"; MyRunnable r3 = () -> { MySupply s2 = () -> "Hello Hello Hello"; System.out.println(s2.supply()); }; r3.run(); } } package com.github.nekolr.read.listener; import com.github.nekolr.metadata.ExcelListener; /** * Excel 读监听器 */ public interface ExcelReadListener extends ExcelListener { } 0 // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.models.extensions; import com.microsoft.graph.serializer.ISerializer; import com.microsoft.graph.serializer.IJsonBackedObject; import com.microsoft.graph.serializer.AdditionalDataManager; import java.util.EnumSet; import com.microsoft.graph.models.extensions.ContactFolder; import com.microsoft.graph.models.extensions.Contact; import com.microsoft.graph.models.extensions.MultiValueLegacyExtendedProperty; import com.microsoft.graph.models.extensions.SingleValueLegacyExtendedProperty; import com.microsoft.graph.models.extensions.Entity; import com.microsoft.graph.requests.extensions.ContactFolderCollectionPage; import com.microsoft.graph.requests.extensions.ContactCollectionPage; import com.microsoft.graph.requests.extensions.MultiValueLegacyExtendedPropertyCollectionPage; import com.microsoft.graph.requests.extensions.SingleValueLegacyExtendedPropertyCollectionPage; import com.google.gson.JsonObject; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Contact Folder. */ public class ContactFolder extends Entity implements IJsonBackedObject { /** * The Display Name. * The folder's display name. */ @SerializedName("displayName") @Expose public String displayName; /** * The Parent Folder Id. * The ID of the folder's parent folder. */ @SerializedName("parentFolderId") @Expose public String parentFolderId; /** * The Child Folders. * The collection of child folders in the folder. Navigation property. Read-only. Nullable. */ @SerializedName("childFolders") @Expose public ContactFolderCollectionPage childFolders; /** * The Contacts. * The contacts in the folder. Navigation property. Read-only. Nullable. */ @SerializedName("contacts") @Expose public ContactCollectionPage contacts; /** * The Multi Value Extended Properties. * The collection of multi-value extended properties defined for the contactFolder. Read-only. Nullable. */ @SerializedName("multiValueExtendedProperties") @Expose public MultiValueLegacyExtendedPropertyCollectionPage multiValueExtendedProperties; /** * The Single Value Extended Properties. * The collection of single-value extended properties defined for the contactFolder. Read-only. Nullable. */ @SerializedName("singleValueExtendedProperties") @Expose public SingleValueLegacyExtendedPropertyCollectionPage singleValueExtendedProperties; /** * The raw representation of this class */ private JsonObject rawObject; /** * The serializer */ private ISerializer serializer; /** * Gets the raw representation of this class * * @return the raw representation of this class */ public JsonObject getRawObject() { return rawObject; } /** * Gets serializer * * @return the serializer */ protected ISerializer getSerializer() { return serializer; } /** * Sets the raw JSON object * * @param serializer the serializer * @param json the JSON object to set this object to */ public void setRawObject(final ISerializer serializer, final JsonObject json) { this.serializer = serializer; rawObject = json; if (json.has("childFolders")) { childFolders = serializer.deserializeObject(json.get("childFolders").toString(), ContactFolderCollectionPage.class); } if (json.has("contacts")) { contacts = serializer.deserializeObject(json.get("contacts").toString(), ContactCollectionPage.class); } if (json.has("multiValueExtendedProperties")) { multiValueExtendedProperties = serializer.deserializeObject(json.get("multiValueExtendedProperties").toString(), MultiValueLegacyExtendedPropertyCollectionPage.class); } if (json.has("singleValueExtendedProperties")) { singleValueExtendedProperties = serializer.deserializeObject(json.get("singleValueExtendedProperties").toString(), SingleValueLegacyExtendedPropertyCollectionPage.class); } } } import java.util.ArrayList; import java.util.function.Consumer; import java.util.function.Predicate; public class Assignment7 { public Assignment7() { // TODO Auto-generated constructor stub } public static void main(String[] args) { ArrayList arrList=new ArrayList<>(); arrList.add(64); arrList.add(39); arrList.add(47); arrList.add(20); arrList.add(169); arrList.add(10); arrList.add(25); arrList.add(98); arrList.add(28); arrList.add(86); Predicate i=p->p%2==0; Consumer> con=all->all.forEach(num->System.out.println(num+(i.test(num)?" even":" odd"))); } } hjjohny/editorsrc/com.mentor.nucleus.bp.core/src/com/mentor/nucleus/bp/core/sorter/AlphaSorter.java1-10 //===================================================================== // //File: $RCSfile: AlphaSorter.java,v $ //Version: $Revision: 1.13 $ //Modified: $Date: 2012/01/23 21:28:59 $ // //(c) Copyright 2004-2014 by Mentor Graphics Corp. 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 com.mentor.nucleus.bp.core.sorter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.Collator; import java.util.Arrays; import java.util.Comparator; import com.mentor.nucleus.bp.core.common.NonRootModelElement; public class AlphaSorter implements MetadataSortingManager.ISorter, Comparator { public static final String APLHA_METHOD_1 = "getName"; //$NON-NLS-1$ public static final String APLHA_METHOD_2 = "Get_name"; //$NON-NLS-1$ private boolean fIgnoreCase = true; private boolean descending = false; public boolean canSort(Object[] elements) { Class type = getType(elements); if (type == null || !NonRootModelElement.class.isAssignableFrom(type)) { return false; } Method[] methods = type.getMethods(); for (int i = 0; i < methods.length; i++) { String methodName = methods[i].getName(); if (methodName.equals(APLHA_METHOD_1) || methodName.equals(APLHA_METHOD_2)) { if (methods[i].getParameterTypes().length == 0) { return true; } } } return false; } public void setIgnoreCase(boolean value) { fIgnoreCase = value; } public void sort(Object[] elements) { descending = false; Arrays.sort(elements, this); } public void sortDescending(Object[] elements) { descending = true; Arrays.sort(elements, this); } public int compare(Object arg0, Object arg1) { if (arg0 instanceof NonRootModelElement && arg1 instanceof NonRootModelElement) { if(descending) { // switch the arguments Object temp = arg0; arg0 = arg1; arg1 = temp; } String compArg0 = getTextRepresentation(arg0); String compArg1 = getTextRepresentation(arg1); if(fIgnoreCase) { return compArg0.compareToIgnoreCase(compArg1); } else { return compArg0.compareTo(compArg1); } } return 1; } public static String getTextRepresentation(Object object) { String value = getStringByMethodDynamically(object, APLHA_METHOD_1); if (value == null) { value = getStringByMethodDynamically(object, APLHA_METHOD_2); } if (value == null) { throw new IllegalArgumentException("Does not have appropiate methods " + APLHA_METHOD_1 + " or " + APLHA_METHOD_2); } return value; } private static Class getType(Object[] elements) { if (elements.length > 0) { return elements[0].getClass(); } return null; } private static String getStringByMethodDynamically(Object object, String methodName) { try { Method method = object.getClass().getMethod(methodName, new Class[0]); if (method != null) { Object value = method.invoke(object, new Object[0]); return String.valueOf(value); } } catch (NoSuchMethodException e) { } catch (IllegalAccessException e) { } catch (IllegalArgumentException e) { } catch (InvocationTargetException e) { } return null; } } package com.fincatto.documentofiscal.nfe310.classes.evento.downloadnf; import org.simpleframework.xml.Element; import org.simpleframework.xml.Namespace; import org.simpleframework.xml.Root; @Root(name = "retNFe") @Namespace(reference = "http://www.portalfiscal.inf.br/nfe") public class NFDownloadNFeRetornoInfo { @Element(name = "chNFe", required = true) private String chave; @Element(name = "cStat", required = true) private String status; @Element(name = "xMotivo", required = true) private String motivo; @Element(name = "procNFeZip", required = false) private String procNfeZip; @Element(name = "procNFe", required = false) private NFDownloadNFeRetornoInfoProcNfe procNfe; public NFDownloadNFeRetornoInfo() { this.chave = null; this.status = null; this.motivo = null; this.procNfeZip = null; this.procNfe = null; } public String getChave() { return chave; } public void setChave(final String chave) { this.chave = chave; } public String getStatus() { return status; } public void setStatus(final String status) { this.status = status; } public String getMotivo() { return motivo; } public void setMotivo(final String motivo) { this.motivo = motivo; } public String getProcNfeZip() { return procNfeZip; } public void setProcNfeZip(final String procNfeZip) { this.procNfeZip = procNfeZip; } public NFDownloadNFeRetornoInfoProcNfe getProcNfe() { return procNfe; } public void setProcNfe(final NFDownloadNFeRetornoInfoProcNfe procNfe) { this.procNfe = procNfe; } } the-code-journal/code-challenges-java package io.codejournal.codingbat.string1; import java.util.Optional; public class NonStart { public final String nonStart(final String a, final String b) { final String strA = Optional.ofNullable(a).orElse(""); final String strB = Optional.ofNullable(b).orElse(""); final String resultA = strA.substring(Math.min(strA.length(), 1)); final String resultB = strB.substring(Math.min(strB.length(), 1)); return resultA + resultB; } } package com.github.m5.netutil.request; import com.github.m5.netutil.response.Response; import java.io.Serializable; /** * @author xiaoyu */ public interface Request extends Serializable { /** * @return */ String getRequestId(); /** * @param requestId */ void setRequestId(String requestId); } package com.percyvega.lombok; import java.math.BigDecimal; import lombok.ToString; @ToString public class ToStringExample { private String name; private final int age; private static final BigDecimal BONUSES = new BigDecimal(3000); public ToStringExample(String name, int age) { this.name = name; this.age = age; } public String getName() { System.out.println("Executing getName()"); return name; } } @ToString(doNotUseGetters = true) class Dot { private int size = 1; public int getSize() { System.out.println("Executing getSize()"); return size; } } @ToString(exclude = "y") class Point { private int x = 10; private int y = 10; } class Line { private int x1 = 10; private int y1 = 10; private int x2 = 20; private int y2 = 20; } package theForsaken.relics; import basemod.abstracts.CustomRelic; import com.badlogic.gdx.graphics.Texture; import com.megacrit.cardcrawl.actions.AbstractGameAction; import com.megacrit.cardcrawl.actions.common.DamageAllEnemiesAction; import com.megacrit.cardcrawl.actions.common.RelicAboveCreatureAction; import com.megacrit.cardcrawl.cards.DamageInfo; import com.megacrit.cardcrawl.core.AbstractCreature; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.unlock.UnlockTracker; import theForsaken.TheForsakenMod; import theForsaken.util.TextureLoader; import static theForsaken.TheForsakenMod.makeRelicOutlinePath; import static theForsaken.TheForsakenMod.makeRelicPath; public class ArmorOfThorns extends CustomRelic { /* * https://github.com/daviscook477/BaseMod/wiki/Custom-Relics * * If you play no attacks, gain 1 strength, If you play no skills, gain 1 dexterity. */ // ID, images, text. public static final String ID = TheForsakenMod.makeID(ArmorOfThorns.class.getSimpleName()); private static final Texture IMG = TextureLoader.getTexture(makeRelicPath("ArmorOfThorns.png")); private static final Texture OUTLINE = TextureLoader.getTexture(makeRelicOutlinePath("ArmorOfThorns.png")); public ArmorOfThorns() { super(ID, IMG, OUTLINE, RelicTier.BOSS, LandingSound.HEAVY); } @Override public int onPlayerGainedBlock(float blockAmount) { if (blockAmount >= 1.0F) { AbstractDungeon.actionManager.addToBottom(new RelicAboveCreatureAction(AbstractDungeon.player, this)); AbstractDungeon.actionManager.addToBottom(new DamageAllEnemiesAction((AbstractCreature) null, DamageInfo.createDamageMatrix(3, true), DamageInfo.DamageType.THORNS, AbstractGameAction.AttackEffect.BLUNT_LIGHT)); } return super.onPlayerGainedBlock(blockAmount); } // Description @Override public String getUpdatedDescription() { return DESCRIPTIONS[0]; } @Override public boolean canSpawn() { return !UnlockTracker.isRelicLocked(this.relicId); } }/* * * * Copyright 2016 The Symphony Software Foundation * * Licensed to The Symphony Software Foundation (SSF) 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.symphonyoss.proxydesk.listeners.chat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.symphonyoss.ai.constants.MLTypes; import org.symphonyoss.ai.listeners.AiCommandListener; import org.symphonyoss.ai.utils.Messenger; import org.symphonyoss.client.SymphonyClient; import org.symphonyoss.client.model.Chat; import org.symphonyoss.client.services.ChatListener; import org.symphonyoss.client.util.MlMessageParser; import org.symphonyoss.proxydesk.models.calls.Call; import org.symphonyoss.proxydesk.models.users.DeskUser; import org.symphonyoss.proxydesk.utils.DeskUserCache; import org.symphonyoss.symphony.clients.model.SymMessage; import java.util.HashMap; /** * Created by nicktarsillo on 6/21/16. * A chat listener for calls between members and clients. */ public class CallChatListener implements ChatListener { private final Logger logger = LoggerFactory.getLogger(CallChatListener.class); /** * Calls do not push commands when listener is registered. * To avoid pushing commands on chat registration, we use a hash map to * keep track if the player is entering or has already entered. */ private HashMap entered = new HashMap(); private Call call; private SymphonyClient symClient; public CallChatListener(Call call, SymphonyClient symClient) { this.symClient = symClient; this.call = call; } /** * A method called by the chat listener, when a new message is received. * On new chat message, if the message is not a command, relay the message * between both parties. * * @param message the received message */ public void onChatMessage(SymMessage message) { if (message == null || message.getStreamId() == null || AiCommandListener.isCommand(message, symClient) || isPushMessage(message)) { if (logger != null) logger.warn("Ignored message {}.", message); return; } MlMessageParser mlMessageParser; try { mlMessageParser = new MlMessageParser(symClient); mlMessageParser.parseMessage(message.getMessage()); } catch (Exception e) { if (logger != null) logger.error("Could not parse message {}", message.getMessage(), e); return; } String text = mlMessageParser.getText(); DeskUser deskUser = null; if (message.getFromUserId() != null) deskUser = DeskUserCache.getDeskUser(message.getFromUserId().toString()); if (deskUser != null) { relayMessage(deskUser, text); } else { if (logger != null) logger.warn("Ignored message. Desk SymUser {} could not be found.", message.getFromUserId()); } call.setInactivityTime(0); } /** * Registers this listener to the chat. * Then set entered to true, using the stream id. * * @param chat the chat to register listeners to */ public void listenOn(Chat chat) { if (chat != null) { chat.registerListener(this); if (chat.getStream() != null && chat.getStream().getId() != null) entered.put(chat.getStream().getId().toString(), true); else { logChatError(chat, new NullPointerException()); } } else { logChatError(chat, new NullPointerException()); } } /** * Remove this listener to the chat. * Then set entered to false, based on the stream. * * @param chat the chat to remove listeners from */ public void stopListening(Chat chat) { if (chat != null) { chat.removeListener(this); if (chat.getStream() != null && chat.getStream().getId() != null) entered.put(chat.getStream().getId().toString(), false); else { logChatError(chat, new NullPointerException()); } } else { logChatError(chat, new NullPointerException()); } } /** * Determine if received message is a push message. * (Push message occurs when a listener is registered) * * @param message the received message * @return if the message is a push message */ private boolean isPushMessage(SymMessage message) { return (entered.get(message.getStreamId()) == null || !entered.get(message.getStreamId())); } /** * Send the message sent from a member to both parties. * Retain the identity preference of the member. * * @param deskUser the desk SymUser * @param text the message sent from the member */ private void relayMessage(DeskUser deskUser, String text) { for (DeskUser d : call.getDeskUsers()) { if (d != deskUser) { Messenger.sendMessage(MLTypes.START_ML.toString() + constructRelayMessage(deskUser, text) + MLTypes.END_ML, SymMessage.Format.MESSAGEML, d.getUserID(), symClient); } } } protected String constructRelayMessage(DeskUser deskUser, String text) { if (deskUser.getEmail() != null) { return MLTypes.START_BOLD.toString() + deskUser.getEmail() + ": " + MLTypes.END_BOLD + text; } else { return MLTypes.START_BOLD.toString() + deskUser.getUserID() + ": " + MLTypes.END_BOLD + text; } } public void logChatError(Chat chat, Exception e) { if (logger != null) { if (chat == null) { logger.error("Ignored method call. Chat was null value.", e); } else if (chat.getStream() == null) { logger.error("Could not put stream in push hash. " + "Chat stream was null value.", e); } else if (chat.getStream().getId() == null) { logger.error("Could not put stream in push hash. " + "Chat stream id was null value.", e); } } } } package com.aoliao.notebook.utils; import android.annotation.TargetApi; import android.content.Context; import android.net.ConnectivityManager; import android.net.Network; import android.net.NetworkInfo; import android.os.Build; import android.support.annotation.NonNull; public class NetworkUtils { private NetworkUtils() { } /** * 判断网络是否连接 * * @param context * @return */ public static boolean isConnected(@NonNull Context context) { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return (networkInfo != null && networkInfo.isConnected()); } /** * 判断WIFI是否连接 * * @param context * @return */ public static boolean isWifiConnected(@NonNull Context context) { return isConnected(context, ConnectivityManager.TYPE_WIFI); } /** * 判断移动网络是否连接 * * @param context * @return */ public static boolean isMobileConnected(@NonNull Context context) { return isConnected(context, ConnectivityManager.TYPE_MOBILE); } private static boolean isConnected(@NonNull Context context, int type) { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); //检测API是否小于21,因为API21之后getNetworkInfo(int networkType)方法被弃用 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { NetworkInfo networkInfo = connMgr.getNetworkInfo(type); return networkInfo != null && networkInfo.isConnected(); } else { return isConnected(connMgr, type); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private static boolean isConnected(@NonNull ConnectivityManager connMgr, int type) { Network[] networks = connMgr.getAllNetworks(); NetworkInfo networkInfo; for (Network mNetwork : networks) { networkInfo = connMgr.getNetworkInfo(mNetwork); if (networkInfo != null && networkInfo.getType() == type && networkInfo.isConnected()) { return true; } } return false; } //没有连接网络 public static final int NETWORK_NONE = -1; //移动网络 public static final int NETWORK_MOBILE = 0; //无线网络 public static final int NETWORK_WIFI = 1; /** * 检测网络类型 * @param context * @return */ public static int checkNetWorkState(@NonNull Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); //检测API是否小于21,因为API21之后getNetworkInfo(int networkType)方法被弃用 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { //获取WIFI连接的信息 NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); //获取移动数据连接的信息 NetworkInfo mobileNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (wifiNetworkInfo.isConnected()) { return NETWORK_WIFI; } else if (mobileNetworkInfo.isConnected()) { return NETWORK_MOBILE; } else { return NETWORK_NONE; } /*NetworkInfo mNetworkInfo = connectivityManager.getActiveNetworkInfo(); if (mNetworkInfo != null && mNetworkInfo.isConnected()) { if (mNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) { return NETWORK_WIFI; } else if (mNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) { return NETWORK_MOBILE; } else { return NETWORK_NONE; } }*/ } else { Network[] networks = connectivityManager.getAllNetworks(); NetworkInfo mNetworkInfo; for (Network mNetwork : networks) { mNetworkInfo = connectivityManager.getNetworkInfo(mNetwork); if (mNetworkInfo != null) { if (mNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) { //Log.e("------------>", "NETWORK_WIFI"); return NETWORK_WIFI; } else if (mNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) { //Log.e("------------>", "NETWORK_MOBILE"); return NETWORK_MOBILE; } } else { //Log.e("------------>", "NETWORK_NONE"); return NETWORK_NONE; } } } return NETWORK_NONE; } } package com.github.franckyi.ibeeditor.client.gui.editor.base.property.custom; import com.github.franckyi.ibeeditor.client.gui.editor.base.category.EditableCategory; import net.minecraft.potion.EffectInstance; import net.minecraft.util.ResourceLocation; import net.minecraftforge.registries.ForgeRegistries; import java.util.function.Consumer; public class EntityPotionEffectProperty extends BasePotionEffectProperty { public EntityPotionEffectProperty(EditableCategory category, int index, EffectInstance initialValue, Consumer action) { super(category, index, initialValue, action); } @Override protected EffectInstance getValue() { return new EffectInstance(ForgeRegistries.POTIONS.getValue(ResourceLocation.tryCreate(name.getValue())), duration.getValue(), amplifier.getValue(), false, false, false); } } package rxhelpers; import java.util.Arrays; import java.util.Collection; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import io.reactivex.disposables.Disposable; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import io.reactivex.Observer; import io.reactivex.Scheduler; import io.reactivex.schedulers.Schedulers; import static java.util.concurrent.Executors.newSingleThreadExecutor; import static org.junit.Assert.assertTrue; // This is a copy of this: // https://bitbucket.org/marshallpierce/rxjava-ReplayRemoveSubject-race/src/master/src/test/java/org/mpierce/rxjava/SubjectDispatchTest.java // found there: // https://github.com/ReactiveX/RxJava/issues/1940 // The Remove functionality is not tested here - just checking that ReplayRemoveSubject is working for the scenarios // where the ReplaySubject is. // @RunWith(Parameterized.class) public final class SubjectDispatchCopiedTest { private static ExecutorService observeExecutor; private static ExecutorService subscribeExecutor; private static ExecutorService miscExecutor; private Scheduler observeScheduler; private Scheduler subscribeScheduler; private CountDownLatch latch; private ReplayRemoveSubject subj; public SubjectDispatchCopiedTest(int ignored) { } @Parameters public static Collection data() { Integer[][] a = new Integer[10000][1]; for (Integer[] integers : a) { Arrays.fill(integers, 0); } return Arrays.asList((Object[][]) a); } @BeforeClass public static void setUpClass() throws Exception { observeExecutor = newSingleThreadExecutor(); subscribeExecutor = newSingleThreadExecutor(); miscExecutor = newSingleThreadExecutor(); } @AfterClass public static void tearDownClass() throws Exception { observeExecutor.shutdownNow(); subscribeExecutor.shutdownNow(); miscExecutor.shutdownNow(); } @Before public void setUp() throws Exception { observeScheduler = Schedulers.from(observeExecutor); subscribeScheduler = Schedulers.from(subscribeExecutor); latch = new CountDownLatch(1); subj = ReplayRemoveSubject.create(); } @Test public void testCallsObserverWhenSubscribedFromMainThread() throws InterruptedException { submitRunnableThatWaitsThenCallsOnNext(); SemaphoreObserver observer = new SemaphoreObserver(); subj .observeOn(observeScheduler) .subscribe(observer); latch.countDown(); assertTrue(observer.next.tryAcquire(2000, TimeUnit.MILLISECONDS)); } @Test public void testCallsObserverWhenSubscribesFromSubscriberScheduler() throws InterruptedException { submitRunnableThatWaitsThenCallsOnNext(); SemaphoreObserver observer = new SemaphoreObserver(); subj .observeOn(observeScheduler) .subscribeOn(subscribeScheduler) .subscribe(observer); latch.countDown(); assertTrue(observer.next.tryAcquire(2000, TimeUnit.MILLISECONDS)); } private void submitRunnableThatWaitsThenCallsOnNext() { miscExecutor.submit(() -> { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } subj.onNext("foo"); }); } private static class SemaphoreObserver implements Observer { final Semaphore next = new Semaphore(0); final Semaphore complete = new Semaphore(0); final Semaphore error = new Semaphore(0); @Override public void onComplete() { complete.release(); } @Override public void onError(Throwable e) { error.release(); } @Override public void onSubscribe(Disposable d) { } @Override public void onNext(String s) { next.release(); } } } package seng2200; public class StrangleExpress extends Cantons { private static final String synX1214String = "Starve State"; private static final String synX1213String = "Starve State"; public StrangleExpress() { super(synX1213String); } public StrangleExpress(double vil) { super(synX1214String, vil); } } package org.outstudio.wxtest; import org.outstudio.wxtest.ui.MainFrame; public class Main { public static void main(String[] args) { MainFrame.launch(); } } package io.kermoss.trx.domain.exception; public class BusinessLocalTransactionNotFoundException extends RuntimeException { } /** * Copyright (c) 2015, www.cubbery.com. All rights reserved. */ package com.cubbery.rule.console.web; import com.cubbery.rule.console.utils.JsonConverter; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.beans.PropertyEditorSupport; import java.io.IOException; import java.io.PrintWriter; import java.sql.Timestamp; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Map; /** * 项目名: rule-parent
* 包名称: com.cubbery.rule.console.web
* 类名称: BaseAjaxController
* 类描述
* 创建人cubber[百墨]
* 修改人
* 创建时间: 2015/12/10
* 修改时间
* 修改备注
* * @version 1.0.0
*/ public class BaseAjaxController extends MultiActionController { private static DateFormat normalDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); private static DateFormat otherDateFormat = new SimpleDateFormat("yyyy-MM-dd"); protected void bindObject(HttpServletRequest request, Object object) { ServletRequestDataBinder binder = new ServletRequestDataBinder(object); binder.registerCustomEditor(java.util.Date.class, new PropertyEditorSupport() { public void setAsText(String value) { try { setValue(BaseAjaxController.normalDateFormat.parse(value)); } catch (ParseException e) { try { setValue(BaseAjaxController.otherDateFormat.parse(value)); } catch (ParseException e1) { setValue(null); } } } public String getAsText() { return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format((java.util.Date) getValue()); } }); binder.bind(request); } public void outJsonString(HttpServletResponse response, Object object, String ContentType) { response.setContentType(ContentType); response.setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); try { PrintWriter out = response.getWriter(); out.write(toJson(object)); out.close(); } catch (IOException e) { e.printStackTrace(); } } public void outJsonString(HttpServletResponse response, String json) { response.setContentType("text/javascript;charset=UTF-8"); response.setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); try { PrintWriter out = response.getWriter(); out.write(json); out.close(); } catch (IOException e) { throw new RuntimeException(e); } } public void outJsonString(HttpServletResponse response, Object object) { response.setContentType("text/javascript;charset=UTF-8"); response.setHeader("Cache-Control", "no-store, max-age=0, no-cache, must-revalidate"); response.addHeader("Cache-Control", "post-check=0, pre-check=0"); response.setHeader("Pragma", "no-cache"); try { PrintWriter out = response.getWriter(); String s = toJson(object); out.write(s); out.close(); } catch (IOException e) { logger.warn("BaseAjaxController | outJsonString | " + object + " | error:" + e.getMessage()); } } private String toJson(Object object) { return JsonConverter.serialize(object); } } mamez/netCashMovilBase package com.bbva.pibee.web.dto.notifi.request; public enum StateUsuario { ACTIVO,INACTIVO } suzzy777/typescript-generator100-1000 package cz.habarta.typescript.generator.compiler; import java.util.stream.Collectors; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class ModelCompilerUtilsTest { @Test public void testSplitIdentifierIntoWords() { Assertions.assertEquals("Red", splitIdentifierIntoWords("Red")); Assertions.assertEquals("ATYPE", splitIdentifierIntoWords("ATYPE")); Assertions.assertEquals("camel Case Type", splitIdentifierIntoWords("camelCaseType")); Assertions.assertEquals("Pascal Case Type", splitIdentifierIntoWords("PascalCaseType")); Assertions.assertEquals("UPPER CASE TYPE", splitIdentifierIntoWords("UPPER_CASE_TYPE")); Assertions.assertEquals("XML Http Request", splitIdentifierIntoWords("XMLHttpRequest")); Assertions.assertEquals("HÁČKY A ČÁRKY", splitIdentifierIntoWords("HÁČKY_A_ČÁRKY")); Assertions.assertEquals("Háčky A Čárky", splitIdentifierIntoWords("HáčkyAČárky")); Assertions.assertEquals("String 2 Json", splitIdentifierIntoWords("String2Json")); Assertions.assertEquals("string 2 json", splitIdentifierIntoWords("string2json")); Assertions.assertEquals("version 42 final", splitIdentifierIntoWords("version42final")); } private static String splitIdentifierIntoWords(String identifier) { return ModelCompiler.splitIdentifierIntoWords(identifier).stream().collect(Collectors.joining(" ")); } } KrishnaPhani/MyStuff /** * */ /** * @author Krishna * */ package com.krishna.cdi.beans;fastcoderepos/codegensrc/main/java/com/fastcode/entitycodegen/JoinDetails.java package com.fastcode.entitycodegen; public class JoinDetails { String joinColumn; String joinColumnType; Boolean isJoinColumnOptional; String referenceColumn; String mappedBy; String joinEntityName; public String getJoinEntityName() { return joinEntityName; } public void setJoinEntityName(String joinEntityName) { this.joinEntityName = joinEntityName; } public String getMappedBy() { return mappedBy; } public void setMappedBy(String mappedBy) { this.mappedBy = mappedBy; } public String getJoinColumn() { return joinColumn; } public void setJoinColumn(String joinColumn) { this.joinColumn = joinColumn; } public String getReferenceColumn() { return referenceColumn; } public void setReferenceColumn(String referenceColumn) { this.referenceColumn = referenceColumn; } public String getJoinColumnType() { return joinColumnType; } public void setJoinColumnType(String joinColumnType) { this.joinColumnType = joinColumnType; } public Boolean getIsJoinColumnOptional() { return isJoinColumnOptional; } public void setIsJoinColumnOptional(Boolean isJoinColumnOptional) { this.isJoinColumnOptional = isJoinColumnOptional; } } jaudriga/jmap package rs.ltt.jmap.client.api; public interface SessionStateListener { void onSessionStateRetrieved(String sessionState); } package slicker.com.slicker.View; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.android.volley.VolleyError; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import io.realm.Realm; import io.realm.RealmQuery; import slicker.com.slicker.Adapters.PhotoAdapter; import slicker.com.slicker.Controller.API.Api; import slicker.com.slicker.Controller.API.UpdateFavoritesAsyncTask; import slicker.com.slicker.Controller.EndlessRecyclerViewScrollListener; import slicker.com.slicker.Controller.MyInterfaces; import slicker.com.slicker.Model.MyConstants; import slicker.com.slicker.Model.Photo; import slicker.com.slicker.R; public class InterestingPhotoFragment extends android.support.v4.app.Fragment implements SwipeRefreshLayout.OnRefreshListener,MyInterfaces.RecyclerViewClickListener, MyInterfaces.OnUpdateFavorite{ private PhotoAdapter mAdapter; private RecyclerView mRecyclerView; private SwipeRefreshLayout mSwipeContainer; private int mNumOfPages = 100; private int mCurrentPage = 0; private Realm mRealm; private Photo mFavorite; public InterestingPhotoFragment() { } public static InterestingPhotoFragment newInstance() { InterestingPhotoFragment fragment = new InterestingPhotoFragment(); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_interesting_photos, container, false); mRealm = Realm.getInstance(getContext()); mSwipeContainer = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeInterestingContainer); mSwipeContainer.setOnRefreshListener(this); mAdapter = new PhotoAdapter(getActivity(),this); mRecyclerView = (RecyclerView) rootView.findViewById(R.id.rvInteresting); getActivity().setTitle("Flickr Interesting Photos"); StaggeredGridLayoutManager sglm = null; LinearLayoutManager llm = null; if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){ sglm = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); mRecyclerView.setLayoutManager(sglm); } else { llm = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false); mRecyclerView.setLayoutManager(llm); } mRecyclerView.setAdapter(mAdapter); mRecyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(llm) { @Override public void onLoadMore(int page, int totalItemsCount) { } }); getPhotos(); return rootView; } private void getPhotos() { if (mCurrentPage < mNumOfPages){ mSwipeContainer.post(new Runnable() { @Override public void run() { mSwipeContainer.setRefreshing(true); } }); String url = assembleURL(); Log.d("Loading","Loading page " + mCurrentPage + " of page " + mNumOfPages); Api.get(getActivity()).getJSON(url, new Api.JSONCallback() { @Override public void onGetJSONComplete(JSONObject json) { try { JSONObject photos = json.getJSONObject("photos"); mNumOfPages = photos.getInt("pages"); JSONArray items = photos.getJSONArray("photo"); for (int i = 0; i < items.length(); i++){ Photo photo = new Photo(items.getJSONObject(i)); mAdapter.add(photo); } mCurrentPage++; } catch (JSONException e) { e.printStackTrace(); } if (mSwipeContainer != null && mSwipeContainer.isRefreshing()){ mSwipeContainer.setRefreshing(false); } mAdapter.notifyDataSetChanged(); } @Override public void onGetJSONComplete(VolleyError error) { Toast.makeText(getActivity(),R.string.basic_error,Toast.LENGTH_LONG).show(); if (mSwipeContainer != null && mSwipeContainer.isRefreshing()){ mSwipeContainer.setRefreshing(false); } } }); } } private String assembleURL() { return String.format(MyConstants.BASE_FLICKR_URL, MyConstants.FLICKR_METHOD_INTERESTING, MyConstants.API_KEY) + "&page=" + String.valueOf(mCurrentPage + 1); } @Override public void onRefresh() { mCurrentPage = 0; mNumOfPages = 100; mAdapter.clear(); mAdapter.notifyDataSetChanged(); mSwipeContainer.setRefreshing(false); getPhotos(); } @Override public void onPause() { super.onPause(); if (mSwipeContainer != null && mSwipeContainer.isRefreshing()){ mSwipeContainer.setRefreshing(false); } } @Override public void recyclerViewMainImageClicked(Photo photo, View v) { /*Intent intent = new Intent(getActivity(),FullScreenActivity.class); intent.putExtra("farm", photo.getFarm()); intent.putExtra("server",photo.getServer()); intent.putExtra("id", photo.getId()); intent.putExtra("secret", photo.getSecret()); intent.putExtra("owner", photo.getOwner()); intent.putExtra("title",photo.getTitle()); startActivity(intent);*/ } @Override public void recyclerViewShareClicked() { } @Override public void recyclerViewFavoriteClicked(Photo photo) { mFavorite = photo; SharedPreferences sp = getActivity().getSharedPreferences(MyConstants.SP_KEY, Context.MODE_PRIVATE); String token = sp.getString(MyConstants.KEY_OAUTH_TOKEN,null); String secret = sp.getString(MyConstants.KEY_TOKEN_SECRET,null); if (photo.getIsFavorite()){ UpdateFavoritesAsyncTask updateFavoriteAsyncTask = new UpdateFavoritesAsyncTask(getContext(), this); updateFavoriteAsyncTask.execute(token,secret,"remove",photo.getId()); } else { UpdateFavoritesAsyncTask updateFavoriteAsyncTask = new UpdateFavoritesAsyncTask(getContext(), this); updateFavoriteAsyncTask.execute(token, secret, "add", photo.getId()); } } @Override public void recyclerViewFavoriteUserClicked() { } @Override public void recyclerViewProfileClicked(String userID) { Intent intent = new Intent(getContext(),UserActivity.class); intent.putExtra("user_id",userID); startActivity(intent); } @Override public void onUpdateFavorite(String response) { if (response.contains("Photo is owned by you")){ Toast.makeText(getContext(), "Can't favorite you're own photo.", Toast.LENGTH_LONG).show(); } else if (response.contains("error") || response.contains("fail")){ Toast.makeText(getContext(), R.string.basic_error, Toast.LENGTH_LONG).show(); } else { toggleFavorite(); } } private void toggleFavorite(){ RealmQuery query = mRealm.where(Photo.class); query.equalTo("id",mFavorite.getId()); Photo favorite = query.findFirst(); if (mFavorite.getIsFavorite()){ //unfavorite mFavorite.setIsFavorite(false); //remove from realm if (query.count() > 0){ mRealm.beginTransaction(); favorite.removeFromRealm(); mRealm.commitTransaction(); } } else { //favorite mFavorite.setIsFavorite(true); //add to realm mRealm.beginTransaction(); mRealm.copyToRealmOrUpdate(mFavorite); mRealm.commitTransaction(); } } } package com.tgrl.exp.j8.functional; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.function.Function; /** * When lambda expressions, method-references, the Stream interface, and immutable data-structures * are combined, Java enables what could be called “functional programming” (FP) * * @author tugrul.ocak * */ public class WhatAboutFunctions { /** * The Function interface (and related interfaces IntFunction, * DoubleFunction, LongFunction, BiFunction, etc.) * represents the compromise made by Java 8 in elevating functions to objects. This interface * allows functions to be passed as arguments, stored as variables, and be returned by methods * *

* The Function interface has the following default methods:
* * andThen(Function): Returns a composed function that first applies this function to * its input, and then applies the given function to the result.
* compose(Function): Similar to andThen but in reversed order (first applies the * given function to its input, and then this function).
* identity(): Returns a function that always returns its input argument.
*

*/ public void howToUseFunctions() { Function f = Function.identity().andThen(i -> 2 * i).andThen(i -> "str" + i); } /** * andThen can be used any number of times to create a single function. Also, * remember that functions can be passed and returned from methods. Following is an example * involving the new Date-Time API */ public Function dateTimeFunction( final Function f) { return f.andThen(d -> d.atTime(2, 2)); } } 1-10 package acmicpc.basic.part7; import java.util.Scanner; public class exam2941 { public static void main(String[] args) { Scanner s = new Scanner(System.in); String str = s.nextLine(); int result = 0; String[] alpha = {"c=", "c-", "dz=", "d-", "lj", "nj", "s=", "z="}; for (int i = 0; i < str.length(); i++) { check: for (int j = 0; j < alpha.length; j++) { if (str.startsWith(alpha[j], i)) { result++; break check; } } } System.out.println(str.length()-result); } }package accesoDatos; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.HashMap; public class DatosManager { private String host = "jdbc:mysql://localhost:3306/"; private String user = "root"; private String pass = ""; private String dbName ="universidad?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; private Connection cn; private Statement st; private ResultSet rs; private java.sql.CallableStatement cst; public ResultSet getRs() { return rs; } public DatosManager() { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { cn=DriverManager.getConnection(host+dbName,user,pass); st=cn.createStatement(); } catch (Exception e) { e.printStackTrace(); } } //Al pasarle una consulta llena el rs con los datos public boolean executeQuery(String query) { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } boolean rst=false; try { rs=st.executeQuery(query); rst=true; } catch (Exception e) { e.printStackTrace(); } return rst; } //Al pasarle una consulta llena el rs con los datos public int executeUpdate(String query) { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } int rst=0; try { rst=st.executeUpdate(query); } catch (Exception e) { e.printStackTrace(); } return rst; } //Al pasarle un sp carga el st con la consulta public void executeSP(String spName,HashMap params) { try { String query="{CALL "+spName; int tam=params.keySet().size(); //recorro cada clave del hash map for( int i=0;i> extends io.kubernetes.client.fluent.BaseFluent implements io.kubernetes.client.openapi.models.V1PersistentVolumeClaimVolumeSourceFluent{ public V1PersistentVolumeClaimVolumeSourceFluentImpl() { } public V1PersistentVolumeClaimVolumeSourceFluentImpl(io.kubernetes.client.openapi.models.V1PersistentVolumeClaimVolumeSource instance) { this.withClaimName(instance.getClaimName()); this.withReadOnly(instance.getReadOnly()); } private java.lang.String claimName; private java.lang.Boolean readOnly; public java.lang.String getClaimName() { return this.claimName; } public A withClaimName(java.lang.String claimName) { this.claimName=claimName; return (A) this; } public java.lang.Boolean hasClaimName() { return this.claimName != null; } /** * Method is deprecated. use withClaimName instead. */ @java.lang.Deprecated public A withNewClaimName(java.lang.String original) { return (A)withClaimName(new String(original)); } public java.lang.Boolean getReadOnly() { return this.readOnly; } public A withReadOnly(java.lang.Boolean readOnly) { this.readOnly=readOnly; return (A) this; } public java.lang.Boolean hasReadOnly() { return this.readOnly != null; } public boolean equals(java.lang.Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; V1PersistentVolumeClaimVolumeSourceFluentImpl that = (V1PersistentVolumeClaimVolumeSourceFluentImpl) o; if (claimName != null ? !claimName.equals(that.claimName) :that.claimName != null) return false; if (readOnly != null ? !readOnly.equals(that.readOnly) :that.readOnly != null) return false; return true; } public int hashCode() { return java.util.Objects.hash(claimName, readOnly, super.hashCode()); } }1-10 package com.jumbo.introducao.operadores; public class Operadores { public static void main(String[] args){ int variavel1 = 10; int variaavel2 = 20; double numero; float numero1; char s; boolean f; long numero2; int resto = 15%2; System.out.println("Resultado " + resto); } } /* Copyright (C) 2013-2018 Expedia 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 com.hotels.styx.proxy.interceptors; import com.hotels.styx.api.HttpInterceptor; import com.hotels.styx.api.LiveHttpResponse; import com.hotels.styx.api.Eventual; import java.util.Optional; import static com.hotels.styx.api.HttpHeaderNames.CONTENT_LENGTH; import com.hotels.styx.api.LiveHttpRequest; /** * Fixes bad content length headers. */ public class UnexpectedRequestContentLengthRemover implements HttpInterceptor { @Override public Eventual intercept(LiveHttpRequest request, Chain chain) { return chain.proceed(removeBadContentLength(request)); } private static LiveHttpRequest removeBadContentLength(LiveHttpRequest request) { Optional contentLength = request.contentLength(); if (contentLength.isPresent() && request.chunked()) { return request.newBuilder() .removeHeader(CONTENT_LENGTH) .build(); } return request; } } siddhesh21ace/cs5200-summer2018-salgaonkar package edu.northeastern.cs5200.battle; import edu.northeastern.cs5200.person.GymLeader.GymLeader; import edu.northeastern.cs5200.person.GymLeader.GymLeaderRepository; import edu.northeastern.cs5200.person.trainer.Trainer; import edu.northeastern.cs5200.person.trainer.TrainerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Objects; import java.util.Optional; @Service public class BattleService { private final BattleRepository battleRepository; private final TrainerRepository trainerRepository; private final GymLeaderRepository gymLeaderRepository; @Autowired public BattleService(BattleRepository battleRepository, TrainerRepository trainerRepository, GymLeaderRepository gymLeaderRepository) { this.battleRepository = battleRepository; this.trainerRepository = trainerRepository; this.gymLeaderRepository = gymLeaderRepository; } Battle createBattle(Battle battle) { return battleRepository.save(battle); } List findAllBattles() { return (List) battleRepository.findAll(); } Battle findBattleById(Long battleId) { Optional data = battleRepository.findById(battleId); return data.orElse(null); } Battle updateBattle(Long battleId, Battle newBattle) throws Exception { Optional data = battleRepository.findById(battleId); if (data.isPresent()) { Battle battle = data.get(); battle.setGymLeader(newBattle.getGymLeader()); battle.setTrainer(newBattle.getTrainer()); return battleRepository.save(battle); } throw new Exception("No battle found with id = " + battleId); } void deleteBattle(Long id) { battleRepository.deleteById(id); } Trainer addBattleData(Long trainerId, Long gymLeaderId) { Optional optionalTrainer = trainerRepository.findById(trainerId); Trainer trainer = optionalTrainer.orElse(null); Optional optionalGymLeader = gymLeaderRepository.findById(gymLeaderId); GymLeader gymLeader = optionalGymLeader.orElse(null); Objects.requireNonNull(trainer).addBattle(gymLeader); return trainerRepository.save(trainer); } Trainer removeBattleData(Long trainerId, Long gymLeaderId) { Optional optionalTrainer = trainerRepository.findById(trainerId); Trainer trainer = optionalTrainer.orElse(null); Optional optionalGymLeader = gymLeaderRepository.findById(gymLeaderId); GymLeader gymLeader = optionalGymLeader.orElse(null); Objects.requireNonNull(trainer).removeBattle(gymLeader); return trainerRepository.save(trainer); } Trainer updateBattleData(Long trainerId, Long gymLeaderId) { Optional optionalTrainer = trainerRepository.findById(trainerId); Trainer trainer = optionalTrainer.orElse(null); Optional optionalGymLeader = gymLeaderRepository.findById(gymLeaderId); GymLeader gymLeader = optionalGymLeader.orElse(null); Objects.requireNonNull(trainer).updateBattle(gymLeader); return trainerRepository.save(trainer); } } package org.zalando.zmon.exception; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.zalando.zmon.exception.ZMonRuntimeException; public class ZMonAuthorizationException extends ZMonRuntimeException { private static final long serialVersionUID = 1L; private final String userName; private final Collection authorities; private final Object details; public ZMonAuthorizationException(final String userName, final Collection authorities, final String msg) { this(userName, authorities, msg, null); } public ZMonAuthorizationException(final String userName, final Collection authorities, final String msg, final Object details) { super(msg); this.userName = userName; this.authorities = authorities; this.details = details; } public String getUserName() { return userName; } public Collection getAuthorities() { return authorities; } public Object getDetails() { return details; } } /** * Created by pro on 23.05.2017. */ package ru.job4j.collections;package jsortie.quicksort.tracer; import javax.management.RuntimeErrorException; import jsortie.quicksort.expander.PartitionExpander; public class TracedPartitionExpander extends Traced implements PartitionExpander { public TracedPartitionExpander ( PartitionExpander innerObject ) { super(innerObject); } @Override public int expandPartition ( int[] vArray, int start, int stopLeft , int hole, int startRight, int stop) { boolean threw = false; String s = "expanding partition " + PartitionDescription ( vArray, start, stopLeft, hole , startRight, stop ); traceEntry(prefix("expandPartition") + s); try { hole = inner.expandPartition ( vArray, start, stopLeft, hole , startRight, stop); } catch (RuntimeErrorException e) { threw = true; traceException ( inner.toString() + ".expandPartition", e); } finally { traceExit ( prefix("expandPartition") + s + (threw ? " failed" : (" left the pivot at " + hole))); } return hole; } private String PartitionDescription ( int[] vArray, int start, int stopLeft , int hole, int startRight, int stop) { boolean canSeeHoleCard = (vArray!=null && 0<=hole && hole0 /* * Copyright (c) 2011-2019 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package io.vertx.core.impl; import io.netty.channel.EventLoop; import io.vertx.core.Handler; import io.vertx.core.spi.tracing.VertxTracer; import java.util.concurrent.RejectedExecutionException; /** * @author */ public class EventLoopContext extends ContextImpl { EventLoopContext(VertxInternal vertx, VertxTracer tracer, EventLoop eventLoop, WorkerPool internalBlockingPool, WorkerPool workerPool, Deployment deployment, CloseFuture closeFuture, ClassLoader tccl) { super(vertx, tracer, eventLoop, internalBlockingPool, workerPool, deployment, closeFuture, tccl); } @Override void runOnContext(AbstractContext ctx, Handler action) { try { nettyEventLoop().execute(() -> ctx.dispatch(action)); } catch (RejectedExecutionException ignore) { // Pool is already shut down } } @Override void emit(AbstractContext ctx, T argument, Handler task) { EventLoop eventLoop = nettyEventLoop(); if (eventLoop.inEventLoop()) { ContextInternal prev = ctx.beginDispatch(); try { task.handle(argument); } catch (Throwable t) { reportException(t); } finally { ctx.endDispatch(prev); } } else { eventLoop.execute(() -> emit(ctx, argument, task)); } } /** *
    *
  • When the current thread is event-loop thread of this context the implementation will execute the {@code task} directly
  • *
  • Otherwise the task will be scheduled on the event-loop thread for execution
  • *
*/ @Override void execute(AbstractContext ctx, T argument, Handler task) { EventLoop eventLoop = nettyEventLoop(); if (eventLoop.inEventLoop()) { task.handle(argument); } else { eventLoop.execute(() -> task.handle(argument)); } } @Override void execute(AbstractContext ctx, Runnable task) { EventLoop eventLoop = nettyEventLoop(); if (eventLoop.inEventLoop()) { task.run(); } else { eventLoop.execute(task); } } @Override public boolean isEventLoopContext() { return true; } @Override boolean inThread() { return nettyEventLoop().inEventLoop(); } } /** * Copyright 2019 the project cranberry authors * and the original author or authors annotated by {@author} *

* 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.cranberry.commons.handler; import com.sun.source.util.TaskEvent; import com.sun.source.util.TaskListener; import java.util.function.Consumer; /** * The interface Compilation handler. * * @param the type parameter * @author * project cranberry * created 2019 -12-23 14:12 */ public interface CompilationHandler extends TaskListener { /** * Sets start handling. * * @param startedProcessor the started processor */ void setStartHandling(Consumer startedProcessor); /** * Sets finish handling. * * @param finishedProcessor the finished processor */ void setFinishHandling(Consumer finishedProcessor); } Sbingo/LikeCloudMusic package sbingo.likecloudmusic.ui.fragment.NetMusic; import sbingo.likecloudmusic.R; import sbingo.likecloudmusic.ui.fragment.BaseFragment; /** * Author: Sbingo * Date: 2016/12/14 */ public class NetMusicFragment extends BaseFragment { private static NetMusicFragment netMusicFragment; public static NetMusicFragment getInstance() { if (null == netMusicFragment) { synchronized (NetMusicFragment.class){ if (null == netMusicFragment) { netMusicFragment = new NetMusicFragment(); } } } return netMusicFragment; } @Override protected int getLayoutId() { return R.layout.net_music_layout; } @Override protected void initInjector() { } @Override protected void initViews() { } } addons/nuxeo-connect-tools/report-core/src/main/java/org/nuxeo/connect/tools/report/management/MXComponent.java /* * (C) Copyright 2016 Nuxeo SA (http://nuxeo.com/) and contributors. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * 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. * * Contributors: * at Nuxeo (aka matic) */ package org.nuxeo.connect.tools.report.management; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import javax.management.JMException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jolokia.backend.BackendManager; import org.jolokia.config.ConfigKey; import org.jolokia.config.Configuration; import org.jolokia.request.JmxRequest; import org.jolokia.request.JmxRequestFactory; import org.jolokia.util.LogHandler; import org.jolokia.util.RequestType; import org.json.simple.JSONObject; import org.nuxeo.runtime.model.DefaultComponent; /** * Platform mbean server invoker which output results in json based on jolokia. * * @since 8.3 */ public class MXComponent extends DefaultComponent { static MXComponent instance; public MXComponent() { instance = this; } // jolokia configuration final Configuration config = new Configuration(ConfigKey.AGENT_ID, "false", ConfigKey.IGNORE_ERRORS, "true"); final BackendManager manager = new BackendManager(config, new LogHandler() { final Log log = LogFactory.getLog(MXComponent.class); @Override public void info(String message) { log.info(message); } @Override public void error(String message, Throwable t) { log.error(message, t); } @Override public void debug(String message) { log.debug(message); } }); /** * Jolokia request builder * * */ class RequestBuilder { RequestBuilder(RequestType oftype) { pRequestMap.put("type", oftype.getName()); } @SuppressWarnings("unchecked") final Map pRequestMap = new JSONObject(); RequestBuilder withMbean(String value) { pRequestMap.put("mbean", value); return this; } RequestBuilder withOperation(String value, Object... arguments) { pRequestMap.put("operation", value); pRequestMap.put("arguments", Arrays.asList(arguments)); return this; } final Map pParams = new HashMap<>(); void run(OutputStream sink) { try { JmxRequest request = JmxRequestFactory.createPostRequest(pRequestMap, config.getProcessingParameters(pParams)); JSONObject json = manager.handleRequest(request); OutputStreamWriter writer = new OutputStreamWriter(sink); json.writeJSONString(writer); writer.flush(); } catch (JMException | IOException cause) { throw new AssertionError("Cannot invoke jolokia", cause); } } } RequestBuilder list() { return new RequestBuilder(RequestType.LIST); } RequestBuilder search(String pattern) { return new RequestBuilder(RequestType.SEARCH) .withMbean(pattern); } RequestBuilder read(String pattern) { return new RequestBuilder(RequestType.READ) .withMbean(pattern); } RequestBuilder exec(String pattern, String operation, Object... arguments) { return new RequestBuilder(RequestType.EXEC) .withMbean(pattern) .withOperation(operation, arguments); } } 1-10 package com.jpfeng.framework.data.net; import com.jpfeng.framework.data.model.ModelManager; import com.jpfeng.framework.data.net.util.NetConfig; import androidx.annotation.NonNull; import okhttp3.OkHttpClient; import retrofit2.Retrofit; /** * 网络连接管理类 *

* Author: Jpfeng * E-mail: * Date: 2018/5/18 */ public class NetClient { private static volatile NetClient mInstance; private NetConfig mConfig; private NetClient(NetConfig config) { mConfig = config; } /** * 初始化。必须首先调用初始化并传入 {@link NetConfig} * * @param config 设置 */ public static void init(@NonNull NetConfig config) { if (null == mInstance) { synchronized (NetClient.class) { if (null == mInstance) { mInstance = new NetClient(config); } else { throw new IllegalStateException("NetClient has already been initialized."); } } } else { throw new IllegalStateException("NetClient has already been initialized."); } } /** * 获取实例。必须在 {@link #init(NetConfig)} 方法之后调用 * * @return 实例 */ public static NetClient getInstance() { if (null == mInstance) { throw new IllegalStateException("NetClient has not yet been initialized."); } return mInstance; } /** * 获取 httpClient 实例 * * @return httpClient 实例 */ public OkHttpClient getHttpClient() { return HttpClient.getInstance(); } /** * 获取 retrofitClient 实例 * * @return retrofitClient 实例 */ public Retrofit getRetrofitClient() { return RetrofitClient.getInstance(); } /** * 更新网路设置 * * @param config 新的网络设置 */ public void updateConfig(NetConfig config) { mConfig = config; HttpClient.reconstruct(); RetrofitClient.reconstruct(); ModelManager.reconstructModels(); } NetConfig getConfig() { return mConfig; } } 0 package com.abnamro.assessment.client; import javax.inject.Named; @Named public class PersonsClient { } package com.cosmos.workflow.logic; import java.net.URL; import java.net.URLClassLoader; class LogicClassLoader extends URLClassLoader{ public LogicClassLoader(ClassLoader parent) { super(new URL[0], parent); } public Class loadClass(String fullName, JavaClassCodeFileObject jco) { byte[] classData = jco.getClassCodeByteArray(); return this.defineClass(fullName, classData, 0, classData.length); } } package frc.robot; import java.lang.reflect.Modifier; import java.util.Arrays; public final class ShuffleboardConstants { private ShuffleboardConstants(){} public static final String // Distance pid DISTANCE_KP = "PID.Distance.KP", DISTANCE_KI = "PID.Distance.KI", DISTANCE_KD = "PID.Distance.KD", DISTANCE_TOLERANCE = "PID.Distance.Tolerance", // Angle pid ANGLE_KP = "PID.Angle.KP", ANGLE_KI = "PID.Angle.KI", ANGLE_KD = "PID.Angle.KD", ANGLE_TOLERANCE = "PID.Angle.Tolerance", // Main AUTO_COMMAND = "Auto.Command", DISTANCE_TO_TARGET = "PID.DistanceToTarget", ANGLE_TO_TARGET = "PID.AngleToTarget", ANGULAR_VELOCITY = "PID.AngularVelocity" ; public static final String[] MEMBERS = Arrays.stream( ShuffleboardConstants.class .getDeclaredFields() ) .filter(f -> (f.getModifiers() & Modifier.STATIC) != 0) .filter(f -> f.getType().equals(String.class)) .map(f -> { try { return (String)f.get(null); } catch (Exception e) { return null; } }) .toArray(String[]::new) ; } Homework/Jeremy/01_Decorator_Pattern_CASE/TglApp/src/main/java/idv/kiwi/app/decorator/PolicyRootImpl.java package idv.kiwi.app.decorator; import idv.kiwi.app.vo.UserVO; public class PolicyRootImpl implements IPolicyRoot { /** */ private static final long serialVersionUID = -6844389702541512907L; public void passSecurityCheck(UserVO userVO) { String memo = userVO.getMemo(); if(userVO.getUserStatus().equals("A")) { memo = memo + "帳號有效\n"; } else { memo = memo + "帳號無效\n"; } userVO.setMemo(memo); } } jdk11/java.base/sun/security/ssl/SSLHandshake.java /* * Copyright (c) 2006, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package sun.security.ssl; import java.io.IOException; import java.nio.ByteBuffer; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Map; import javax.net.ssl.SSLException; enum SSLHandshake implements SSLConsumer, HandshakeProducer { @SuppressWarnings({"unchecked", "rawtypes"}) HELLO_REQUEST ((byte)0x00, "hello_request", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( HelloRequest.handshakeConsumer, ProtocolVersion.PROTOCOLS_TO_12 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( HelloRequest.handshakeProducer, ProtocolVersion.PROTOCOLS_TO_12 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) CLIENT_HELLO ((byte)0x01, "client_hello", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ClientHello.handshakeConsumer, ProtocolVersion.PROTOCOLS_TO_13 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ClientHello.handshakeProducer, ProtocolVersion.PROTOCOLS_TO_13 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) SERVER_HELLO ((byte)0x02, "server_hello", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ServerHello.handshakeConsumer, ProtocolVersion.PROTOCOLS_TO_13 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ServerHello.t12HandshakeProducer, ProtocolVersion.PROTOCOLS_TO_12 ), new SimpleImmutableEntry( ServerHello.t13HandshakeProducer, ProtocolVersion.PROTOCOLS_OF_13 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) HELLO_RETRY_REQUEST ((byte)0x02, "hello_retry_request", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ServerHello.handshakeConsumer, // Use ServerHello consumer ProtocolVersion.PROTOCOLS_TO_13 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ServerHello.hrrHandshakeProducer, ProtocolVersion.PROTOCOLS_OF_13 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) HELLO_VERIFY_REQUEST ((byte)0x03, "hello_verify_request", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( HelloVerifyRequest.handshakeConsumer, ProtocolVersion.PROTOCOLS_TO_12 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( HelloVerifyRequest.handshakeProducer, ProtocolVersion.PROTOCOLS_TO_12 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) NEW_SESSION_TICKET ((byte)0x04, "new_session_ticket", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( NewSessionTicket.handshakeConsumer, ProtocolVersion.PROTOCOLS_OF_13 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( NewSessionTicket.handshakeProducer, ProtocolVersion.PROTOCOLS_OF_13 ) })), END_OF_EARLY_DATA ((byte)0x05, "end_of_early_data"), @SuppressWarnings({"unchecked", "rawtypes"}) ENCRYPTED_EXTENSIONS ((byte)0x08, "encrypted_extensions", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( EncryptedExtensions.handshakeConsumer, ProtocolVersion.PROTOCOLS_OF_13 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( EncryptedExtensions.handshakeProducer, ProtocolVersion.PROTOCOLS_OF_13 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) CERTIFICATE ((byte)0x0B, "certificate", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( CertificateMessage.t12HandshakeConsumer, ProtocolVersion.PROTOCOLS_TO_12 ), new SimpleImmutableEntry( CertificateMessage.t13HandshakeConsumer, ProtocolVersion.PROTOCOLS_OF_13 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( CertificateMessage.t12HandshakeProducer, ProtocolVersion.PROTOCOLS_TO_12 ), new SimpleImmutableEntry( CertificateMessage.t13HandshakeProducer, ProtocolVersion.PROTOCOLS_OF_13 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) SERVER_KEY_EXCHANGE ((byte)0x0C, "server_key_exchange", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ServerKeyExchange.handshakeConsumer, ProtocolVersion.PROTOCOLS_TO_12 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ServerKeyExchange.handshakeProducer, ProtocolVersion.PROTOCOLS_TO_12 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) CERTIFICATE_REQUEST ((byte)0x0D, "certificate_request", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( CertificateRequest.t10HandshakeConsumer, ProtocolVersion.PROTOCOLS_TO_11 ), new SimpleImmutableEntry( CertificateRequest.t12HandshakeConsumer, ProtocolVersion.PROTOCOLS_OF_12 ), new SimpleImmutableEntry( CertificateRequest.t13HandshakeConsumer, ProtocolVersion.PROTOCOLS_OF_13 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( CertificateRequest.t10HandshakeProducer, ProtocolVersion.PROTOCOLS_TO_11 ), new SimpleImmutableEntry( CertificateRequest.t12HandshakeProducer, ProtocolVersion.PROTOCOLS_OF_12 ), new SimpleImmutableEntry( CertificateRequest.t13HandshakeProducer, ProtocolVersion.PROTOCOLS_OF_13 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) SERVER_HELLO_DONE ((byte)0x0E, "server_hello_done", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ServerHelloDone.handshakeConsumer, ProtocolVersion.PROTOCOLS_TO_12 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ServerHelloDone.handshakeProducer, ProtocolVersion.PROTOCOLS_TO_12 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) CERTIFICATE_VERIFY ((byte)0x0F, "certificate_verify", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( CertificateVerify.s30HandshakeConsumer, ProtocolVersion.PROTOCOLS_OF_30 ), new SimpleImmutableEntry( CertificateVerify.t10HandshakeConsumer, ProtocolVersion.PROTOCOLS_10_11 ), new SimpleImmutableEntry( CertificateVerify.t12HandshakeConsumer, ProtocolVersion.PROTOCOLS_OF_12 ), new SimpleImmutableEntry( CertificateVerify.t13HandshakeConsumer, ProtocolVersion.PROTOCOLS_OF_13 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( CertificateVerify.s30HandshakeProducer, ProtocolVersion.PROTOCOLS_OF_30 ), new SimpleImmutableEntry( CertificateVerify.t10HandshakeProducer, ProtocolVersion.PROTOCOLS_10_11 ), new SimpleImmutableEntry( CertificateVerify.t12HandshakeProducer, ProtocolVersion.PROTOCOLS_OF_12 ), new SimpleImmutableEntry( CertificateVerify.t13HandshakeProducer, ProtocolVersion.PROTOCOLS_OF_13 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) CLIENT_KEY_EXCHANGE ((byte)0x10, "client_key_exchange", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ClientKeyExchange.handshakeConsumer, ProtocolVersion.PROTOCOLS_TO_12 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( ClientKeyExchange.handshakeProducer, ProtocolVersion.PROTOCOLS_TO_12 ) })), @SuppressWarnings({"unchecked", "rawtypes"}) FINISHED ((byte)0x14, "finished", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( Finished.t12HandshakeConsumer, ProtocolVersion.PROTOCOLS_TO_12 ), new SimpleImmutableEntry( Finished.t13HandshakeConsumer, ProtocolVersion.PROTOCOLS_OF_13 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( Finished.t12HandshakeProducer, ProtocolVersion.PROTOCOLS_TO_12 ), new SimpleImmutableEntry( Finished.t13HandshakeProducer, ProtocolVersion.PROTOCOLS_OF_13 ) })), CERTIFICATE_URL ((byte)0x15, "certificate_url"), @SuppressWarnings({"unchecked", "rawtypes"}) CERTIFICATE_STATUS ((byte)0x16, "certificate_status", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( CertificateStatus.handshakeConsumer, ProtocolVersion.PROTOCOLS_TO_12 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( CertificateStatus.handshakeProducer, ProtocolVersion.PROTOCOLS_TO_12 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( CertificateStatus.handshakeAbsence, ProtocolVersion.PROTOCOLS_TO_12 ) })), SUPPLEMENTAL_DATA ((byte)0x17, "supplemental_data"), @SuppressWarnings({"unchecked", "rawtypes"}) KEY_UPDATE ((byte)0x18, "key_update", (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( KeyUpdate.handshakeConsumer, ProtocolVersion.PROTOCOLS_OF_13 ) }), (Map.Entry[])(new Map.Entry[] { new SimpleImmutableEntry( KeyUpdate.handshakeProducer, ProtocolVersion.PROTOCOLS_OF_13 ) })), MESSAGE_HASH ((byte)0xFE, "message_hash"), NOT_APPLICABLE ((byte)0xFF, "not_applicable"); final byte id; final String name; final Map.Entry[] handshakeConsumers; final Map.Entry[] handshakeProducers; final Map.Entry[] handshakeAbsences; @SuppressWarnings({"unchecked", "rawtypes"}) SSLHandshake(byte id, String name) { this(id, name, (Map.Entry[])( new Map.Entry[0]), (Map.Entry[])( new Map.Entry[0]), (Map.Entry[])( new Map.Entry[0])); } @SuppressWarnings({"unchecked", "rawtypes"}) SSLHandshake(byte id, String name, Map.Entry[] handshakeConsumers, Map.Entry[] handshakeProducers) { this(id, name, handshakeConsumers, handshakeProducers, (Map.Entry[])( new Map.Entry[0])); } SSLHandshake(byte id, String name, Map.Entry[] handshakeConsumers, Map.Entry[] handshakeProducers, Map.Entry[] handshakeAbsence) { this.id = id; this.name = name; this.handshakeConsumers = handshakeConsumers; this.handshakeProducers = handshakeProducers; this.handshakeAbsences = handshakeAbsence; } @Override public void consume(ConnectionContext context, ByteBuffer message) throws IOException { SSLConsumer hc = getHandshakeConsumer(context); if (hc != null) { hc.consume(context, message); } else { throw new UnsupportedOperationException( "Unsupported handshake consumer: " + this.name); } } private SSLConsumer getHandshakeConsumer(ConnectionContext context) { if (handshakeConsumers.length == 0) { return null; } // The consuming happens in handshake context only. HandshakeContext hc = (HandshakeContext)context; ProtocolVersion protocolVersion; if ((hc.negotiatedProtocol == null) || (hc.negotiatedProtocol == ProtocolVersion.NONE)) { if (hc.conContext.isNegotiated && hc.conContext.protocolVersion != ProtocolVersion.NONE) { protocolVersion = hc.conContext.protocolVersion; } else { protocolVersion = hc.maximumActiveProtocol; } } else { protocolVersion = hc.negotiatedProtocol; } for (Map.Entry phe : handshakeConsumers) { for (ProtocolVersion pv : phe.getValue()) { if (protocolVersion == pv) { return phe.getKey(); } } } return null; } @Override public byte[] produce(ConnectionContext context, HandshakeMessage message) throws IOException { HandshakeProducer hp = getHandshakeProducer(context); if (hp != null) { return hp.produce(context, message); } else { throw new UnsupportedOperationException( "Unsupported handshake producer: " + this.name); } } private HandshakeProducer getHandshakeProducer( ConnectionContext context) { if (handshakeConsumers.length == 0) { return null; } // The consuming happens in handshake context only. HandshakeContext hc = (HandshakeContext)context; ProtocolVersion protocolVersion; if ((hc.negotiatedProtocol == null) || (hc.negotiatedProtocol == ProtocolVersion.NONE)) { if (hc.conContext.isNegotiated && hc.conContext.protocolVersion != ProtocolVersion.NONE) { protocolVersion = hc.conContext.protocolVersion; } else { protocolVersion = hc.maximumActiveProtocol; } } else { protocolVersion = hc.negotiatedProtocol; } for (Map.Entry phe : handshakeProducers) { for (ProtocolVersion pv : phe.getValue()) { if (protocolVersion == pv) { return phe.getKey(); } } } return null; } @Override public String toString() { return name; } static String nameOf(byte id) { // If two handshake message share the same handshake type, returns // the first handshake message name. // // It is not a big issue at present as only ServerHello and // HellRetryRequest share a handshake type. for (SSLHandshake hs : SSLHandshake.values()) { if (hs.id == id) { return hs.name; } } return "UNKNOWN-HANDSHAKE-MESSAGE(" + id + ")"; } static boolean isKnown(byte id) { for (SSLHandshake hs : SSLHandshake.values()) { if (hs.id == id && id != NOT_APPLICABLE.id) { return true; } } return false; } static final void kickstart(HandshakeContext context) throws IOException { if (context instanceof ClientHandshakeContext) { // For initial handshaking, including session resumption, // ClientHello message is used as the kickstart message. // // (D)TLS 1.2 and older protocols support renegotiation on existing // connections. A ClientHello messages is used to kickstart the // renegotiation. // // (D)TLS 1.3 forbids renegotiation. The post-handshake KeyUpdate // message is used to update the sending cryptographic keys. if (context.conContext.isNegotiated && context.conContext.protocolVersion.useTLS13PlusSpec()) { // Use KeyUpdate message for renegotiation. KeyUpdate.kickstartProducer.produce(context); } else { // Using ClientHello message for the initial handshaking // (including session resumption) or renegotiation. // SSLHandshake.CLIENT_HELLO.produce(context); ClientHello.kickstartProducer.produce(context); } } else { // The server side can delivering kickstart message after the // connection has established. // // (D)TLS 1.2 and older protocols use HelloRequest to begin a // negotiation process anew. // // While (D)TLS 1.3 uses the post-handshake KeyUpdate message // to update the sending cryptographic keys. if (context.conContext.protocolVersion.useTLS13PlusSpec()) { // Use KeyUpdate message for renegotiation. KeyUpdate.kickstartProducer.produce(context); } else { // SSLHandshake.HELLO_REQUEST.produce(context); HelloRequest.kickstartProducer.produce(context); } } } /** * A (transparent) specification of handshake message. */ static abstract class HandshakeMessage { final HandshakeContext handshakeContext; HandshakeMessage(HandshakeContext handshakeContext) { this.handshakeContext = handshakeContext; } abstract SSLHandshake handshakeType(); abstract int messageLength(); abstract void send(HandshakeOutStream hos) throws IOException; void write(HandshakeOutStream hos) throws IOException { int len = messageLength(); if (len >= Record.OVERFLOW_OF_INT24) { throw new SSLException("Handshake message is overflow" + ", type = " + handshakeType() + ", len = " + len); } hos.write(handshakeType().id); hos.putInt24(len); send(hos); hos.complete(); } } } /** * © Copyright HCL Technologies Ltd. 2017. * LICENSE: Apache License, Version 2.0 https://www.apache.org/licenses/LICENSE-2.0 */ package com.hcl.appscan.sdk.scanners.sast.targets; import java.util.HashSet; import java.util.Set; public abstract class DefaultTarget implements ISASTTarget { Set m_exclusionPatterns; Set m_inclusionPatterns; public DefaultTarget() { m_exclusionPatterns = new HashSet(); m_inclusionPatterns = new HashSet(); } @Override public String getTarget() { return getTargetFile().getAbsolutePath(); } @Override public Set getExclusionPatterns() { return m_exclusionPatterns; } @Override public Set getInclusionPatterns() { return m_inclusionPatterns; } @Override public boolean outputsOnly() { return false; } } wan/src/main/java/com/transcendence/wan/utils/AliPayUtils.java package com.transcendence.wan.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.widget.Toast; import com.transcendence.core.utils.L; import com.transcendence.ui.dialog.hjq.layout.BaseDialog; import com.transcendence.ui.dialog.hjq.layout.MessageDialog; import com.transcendence.wan.R; /** * @Author Joephone on 2021/5/14 0014 上午 10:24 * @E-Mail Address: * @Desc * @Edition 1.0 * @EditionHistory */ public class AliPayUtils { public static void showDonateDialog(Activity activity) { L.d("showDonateDialog"); new MessageDialog.Builder(activity) .setTitle(R.string.tip) .setMessage("确认跳转到支付宝?") .setConfirm(R.string.ok) // 设置 null 表示不显示取消按钮 .setCancel(R.string.cancel) // 设置点击按钮后不关闭对话框 //.setAutoDismiss(false) .setListener(new MessageDialog.OnListener() { @Override public void onConfirm(BaseDialog dialog) { if (RomUtils.checkApkExist(activity, "com.eg.android.AlipayGphone")) { donate(activity); } else { Toast.makeText(activity,"拐子呃,您家冇装支付宝",Toast.LENGTH_SHORT).show(); } } }).show(); // final MaterialDialog dialog = new MaterialDialog(activity); // dialog.content("确认跳转到支付宝?").btnText("关闭", "确认").show(); // //left btn click listener // //right btn click listener // dialog.setOnBtnClickL( // dialog::dismiss, // () -> { // if (RomUtils.checkApkExist(activity, "com.eg.android.AlipayGphone")) { // donate(activity); // } else { // Toasty.warning(activity, "本机未安装支付宝", Toast.LENGTH_SHORT).show(); // } // dialog.dismiss(); // } // ); } //跳转到支付宝付款界面 private static void donate(Context context) { String intentFullUrl = "intent://platformapi/startapp?saId=10000007&" + "clientVersion=3.7.0.0718&qrcode=https%3A%2F%2Fqr.alipay.com%2F{URLcode}%3F_s" + //这里的URLcode换成扫码得到的结果 "%3Dweb-other&_t=1472443966571#Intent;" + "scheme=alipayqr;package=com.eg.android.AlipayGphone;end"; try { Intent intent = Intent.parseUri(intentFullUrl, Intent.URI_INTENT_SCHEME); context.startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } } vjmadrid/workspace-api-labacme-message-api-restful-crud/src/main/java/com/acme/message/api/restful/crud/service/impl/UserMessageServiceImpl.java0 package com.acme.message.api.restful.crud.service.impl; import java.util.Date; import java.util.List; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.acme.message.api.restful.crud.entity.UserMessage; import com.acme.message.api.restful.crud.repository.UserMessageRepository; import com.acme.message.api.restful.crud.service.UserMessageService; import com.acme.message.api.restful.crud.util.converter.CollectionConverter; @Service("userMessageService") @Transactional(readOnly = true) public class UserMessageServiceImpl implements UserMessageService { private final Logger LOG = LoggerFactory.getLogger(UserMessageServiceImpl.class); @Autowired private UserMessageRepository userMessageRepository; @Override public List findAll() { LOG.trace("Find all UserMessage"); return CollectionConverter.toList(userMessageRepository.findAll()); } @Override public Optional findByPK(Long id) { LOG.trace("Find UserMessage by id : {}", id); return userMessageRepository.findById(id); } @Override @Transactional public UserMessage insert(UserMessage userMessage) { LOG.trace("Insert UserMessage"); userMessage.setCreationDate(new Date()); return userMessageRepository.save(userMessage); } @Override @Transactional public UserMessage update(UserMessage userMessage) { LOG.trace("Update UserMessage with id : {}", userMessage.getId()); return userMessageRepository.save(userMessage); } @Override @Transactional public void delete(UserMessage userMessage) { LOG.trace("Delete UserMessage by id : {}", userMessage.getId()); userMessageRepository.delete(userMessage); } public void setUserMessageRepository(UserMessageRepository userMessageRepository) { this.userMessageRepository = userMessageRepository; } } java/classes2/com/umeng/analytics/pro/cf.java1-10 package com.umeng.analytics.pro; public class cf extends cm { public static final int a = 0; public static final int b = 1; public static final int c = 2; public static final int d = 3; public static final int e = 4; public static final int f = 5; public static final int g = 6; public static final int h = 7; private static final dk j = new dk("TApplicationException"); private static final da k = new da("message", (byte)11, (short)1); private static final da l = new da("type", (byte)8, (short)2); private static final long m = 1L; protected int i = 0; public cf() {} public cf(int paramInt) { this.i = paramInt; } public cf(int paramInt, String paramString) { super(paramString); this.i = paramInt; } public cf(String paramString) { super(paramString); } public static cf a(df paramdf) throws cm { paramdf.j(); String str = null; int n = 0; da localda = paramdf.l(); if (localda.b == 0) { paramdf.k(); return new cf(n, str); } switch (localda.c) { default: di.a(paramdf, localda.b); } for (;;) { paramdf.m(); break; if (localda.b == 11) { str = paramdf.z(); } else { di.a(paramdf, localda.b); continue; if (localda.b == 8) { n = paramdf.w(); } else { di.a(paramdf, localda.b); } } } } public int a() { return this.i; } public void b(df paramdf) throws cm { paramdf.a(j); if (getMessage() != null) { paramdf.a(k); paramdf.a(getMessage()); paramdf.c(); } paramdf.a(l); paramdf.a(this.i); paramdf.c(); paramdf.d(); paramdf.b(); } } /* Location: /Users/gaoht/Downloads/zirom/classes2-dex2jar.jar!/com/umeng/analytics/pro/cf.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 *//** * */ package it.univpm.progetto.model; import org.json.simple.JSONObject; import it.univpm.progetto.parser.CurrentWeatherParser; import it.univpm.progetto.stats.StatsForecast; import it.univpm.progetto.stats.StatsHistorical; /** * questa classe si occupa di inizializzare i dati relativi a: dati attuali contenuti nel dataset * o anche dati relativi alle statistiche calcolate su dati storici e preivisioni future * (per lo scopo del progetto è stata usata in SaveToFile.java per salvare i dati attuali e creare * lo storico dei dati, ed inoltre viene usata nel controller per restituire i metadati) * @author camplese * @author colleluori * */ public class WeatherData { JSONObject jsonObjectFormatted = new JSONObject(); /** * costruttore che inizializza i dati restituiti da una chiamata tipo * all'API di OpenWeather sulle previsioni attuali, già parsati tramite * l'uso della classe CurrentWeatherParser.java * @param cityName */ public WeatherData(String cityName) { CurrentWeatherParser currentWeatherParser = new CurrentWeatherParser(cityName); currentWeatherParser.parsing(); jsonObjectFormatted = currentWeatherParser.formatter(); //accedo al metodo formatter() della superclasse } /** * costruttore che inizializza i dati restituiti da una chiamata tipo * alle statistiche fatte sui dati storici del dataset * (come esempio viene presa la città di Trieste, e le statistiche * calcolate dal primo fino all'ultimo giorno) */ @SuppressWarnings("unchecked") public WeatherData() { StatsHistorical statsHistorical = new StatsHistorical("Trieste,Ortona,Venezia", false, false, 1, 1, 1, 5); StatsForecast statsForecast = new StatsForecast("Trieste,Ortona,Venezia", true, true, 1, 1, 1, 5); JSONObject jsonObject = new JSONObject(); jsonObject.put("statsHistorical", statsHistorical.formatter()); jsonObject.put("statsForecast", statsForecast.formatter(50)); jsonObjectFormatted = jsonObject; } /** * @return the jsonObj */ public JSONObject getJsonObjectFormatted() { return jsonObjectFormatted; } } Prololgamers/WhatHerName package egovframework.bareun.cop.mnu.service; import java.util.List; import java.util.Map; import egovframework.bareun.cop.bbs.service.BrdVO; public interface MnuService { } package unimelb.bitbox; import org.apache.commons.cli.*; import org.bouncycastle.openssl.PEMKeyPair; import org.bouncycastle.openssl.PEMParser; import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter; import unimelb.bitbox.util.Document; import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.security.*; import java.security.interfaces.RSAPrivateKey; import java.util.*; import java.util.logging.Logger; /** * Client * Usage: * Create the client * @author * create time 2019/5/16 - 10:36 AM */ public class Client { private static Logger log = Logger.getLogger(Client.class.getName()); private static ClientCommand command; private static String serverIp; private static String peerIp = null; private static String identity; private static SecretKey secretKey; public static void main(String[] args) throws Exception { final Options options = new Options(); final Option commandOption = new Option("c", true, "command"); final Option severOption = new Option("s", true, "severIp"); final Option peerOption = new Option("p", true, "peerIp"); final Option identityOption = new Option("i", true, "identity"); //Set the peerIp as optional requirement peerOption.setRequired(false); options.addOption(commandOption); options.addOption(severOption); options.addOption(peerOption); options.addOption(identityOption); final CommandLineParser parser = new PosixParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { throw new Exception("command line error", e); } if(cmd.hasOption("c") && cmd.hasOption("s") && cmd.hasOption("i")) { command = ClientCommand.valueOf(cmd.getOptionValue("c")); serverIp = cmd.getOptionValue("s").replace("localhost", "127.0.0.1"); identity = cmd.getOptionValue("i"); if(cmd.hasOption("p")) { peerIp = cmd.getOptionValue("p"); if(peerIp != null){ peerIp.replace("localhost", "127.0.0.1"); } } }else { System.out.println("Please input correct command"); System.exit(1); } monitor(); } /** * Monitor client */ private static void monitor() { System.out.println("Begin Monitor Client"); String[] serverAddress = serverIp.split(":"); try { Socket socket = new Socket(serverAddress[0], Integer.parseInt(serverAddress[1])); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8)); System.out.println("Input ready"); Document authRequest = new Document(); authRequest.append("command", Operation.AUTH_REQUEST.name()); authRequest.append("identity", identity); print(authRequest, output); System.out.println("Wait for auth res"); Document authResponse = waitForRes(input); if (authResponse == null) { throw new RuntimeException("Invalid response"); } if (!authResponse.getBoolean("status")) { log.severe(authResponse.getString("message")); return; } // begin to parse the command -c Document commandReq = new Document(); commandReq.append("command", command.reqName); switch (command) { case list_peers: break; case connect_peer: case disconnect_peer: String[] peerAddress = peerIp.split(":"); commandReq.append("host", peerAddress[0]); commandReq.append("port", Integer.parseInt(peerAddress[1])); } File findPrivateKey = new File("bitboxclient_rsa"); PEMParser pemParser = new PEMParser(new FileReader(findPrivateKey)); PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject(); KeyPair keyPair = new JcaPEMKeyConverter().getKeyPair(pemKeyPair); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.DECRYPT_MODE, privateKey); String AES = authResponse.getString("AES128"); byte[] temp_sec = Base64.getDecoder().decode(AES.getBytes("UTF-8")); secretKey = new SecretKeySpec(cipher.doFinal(temp_sec), "AES"); // encrypt command Document encryptReq = new Document(); Cipher en_cipher = Cipher.getInstance("AES"); byte[] wrapped = commandReq.toJson().getBytes(); en_cipher.init(Cipher.ENCRYPT_MODE, secretKey); String encryptedKey = Base64.getEncoder().encodeToString(en_cipher.doFinal(wrapped)); encryptReq.append("payload", encryptedKey); print(encryptReq, output); Document encryptRes = waitForRes(input); if (encryptRes == null) { throw new RuntimeException("Invalid command response"); } String information = null; try{ Cipher de_cipher = Cipher.getInstance("AES"); de_cipher.init(Cipher.DECRYPT_MODE, secretKey); String de_AES = encryptRes.getString("payload"); if (!de_AES.isEmpty()) { byte[] sec = Base64.getDecoder().decode(de_AES.getBytes("UTF-8")); information = new String(de_cipher.doFinal(sec)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } log.info(information); } catch (Exception e) { e.printStackTrace(); } } private enum ClientCommand { list_peers("LIST_PEERS_REQUEST"), connect_peer("CONNECT_PEER_REQUEST"), disconnect_peer("DISCONNECT_PEER_REQUEST"); ClientCommand(String reqName) { this.reqName = reqName; } String reqName; } public static void print(Document re, BufferedWriter out) throws IOException { String data = re.toJson(); out.write(data); out.newLine(); out.flush(); } /** * Wait for response, time-block * * @param in input * @return res/null */ public static Document waitForRes(BufferedReader in) { while (true) { String data; try { data = in.readLine(); System.out.println(data); if (data.isEmpty()) { continue; } } catch (Exception e) { // connection closed or EOF e.printStackTrace(); break; } Document request = Document.parse(data); if (request.getString("payload") != null || request.getString("command") != null) { return request; } } return null; } } axibase/aggregation-log-filter /* * Copyright 2016 Axibase Corporation or its affiliates. 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. * A copy of the License is located at * * https://www.axibase.com/atsd/axibase-apache-2.0.pdf * * or in the "license" file accompanying this file. This file 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.axibase.tsd.collector.log4j2; import com.axibase.tsd.collector.SendMessageTrigger; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.LogEvent; public class Log4j2EventTrigger extends SendMessageTrigger { public static final Level DEFAULT_LEVEL = Level.WARN; private Level level; private boolean definedSendMultiplier = false; public Log4j2EventTrigger() { this(DEFAULT_LEVEL); } public Log4j2EventTrigger(Level level) { super(); this.level = level; } @Override public boolean onEvent(LogEvent event) { return event != null && event.getLevel().intLevel() == level.intLevel() && super.onEvent(event); } public static boolean isErrorInstance(LogEvent event) { return (event.getLevel().intLevel() == Level.ERROR.intLevel() && event.getThrown() instanceof Error); } @Override public String resolveKey(LogEvent event) { return event.getLoggerName(); } public void setLevel(Level level) { this.level = level; } @Override public void setStackTraceLines(int stackTraceLines) { super.setStackTraceLines(stackTraceLines); definedSendMultiplier = true; } @Override public void setSendMultiplier(double sendMultiplier) { super.setSendMultiplier(sendMultiplier); definedSendMultiplier = true; } @Override public void init() { if (!definedSendMultiplier) { if (level.intLevel() <= (Level.ERROR.intLevel())) { setSendMultiplier(ERROR_SKIP_MULTIPLIER); setStackTraceLines(ERROR_STACK_TRACE_LINES); } else if (level.intLevel() <= (Level.WARN.intLevel())) { setSendMultiplier(WARN_SKIP_MULTIPLIER); } else { setSendMultiplier(INFO_SKIP_MULTIPLIER); } } } @Override public int getIntLevel() { return level.intLevel(); } } mmsns-web/mmsns-web-portal/src/main/java/com/lovecws/mumu/mmsns/configuration/MMSnsPortalUserRealm.java package com.lovecws.mumu.mmsns.configuration; import com.lovecws.mumu.core.response.ResponseEntity; import com.lovecws.mumu.core.utils.StringUtil; import com.lovecws.mumu.core.utils.ValidateUtils; import com.lovecws.mumu.mmsns.common.user.entity.MMSnsCommonUserEntity; import com.lovecws.mumu.mmsns.common.user.service.MMSnsCommonUserService; import com.lovecws.mumu.security.exception.AccountUnActiveException; import com.lovecws.mumu.security.realm.UserRealm; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import org.springframework.beans.factory.annotation.Autowired; import java.util.List; /** * @author babymm * @version 1.0-SNAPSHOT * @Description: 官网用户认证 * @date 2017-11-28 10:17 */ public class MMSnsPortalUserRealm extends UserRealm { @Autowired(required = false) private MMSnsCommonUserService commonUserService; /** * 校验用户登录权限 * * @param principals * @return */ @Override public AuthorizationInfo authorizationInfo(final PrincipalCollection principals) { System.out.println(principals); return null; } /** * 校验登录用户 */ @Override public AuthenticationInfo authenticationInfo(final AuthenticationToken token) { String loginName = (String) token.getPrincipal(); if (StringUtil.isEmpty(loginName)) { throw new UnknownAccountException();// 没找到帐号 } //根据用户登录信息[用户名、手机号码、用户邮箱] 来获取用户信息 String userName = null, userPhone = null, userEmail = null; if (ValidateUtils.isMobile(loginName)) { userPhone = loginName; } else if (ValidateUtils.isEmail(loginName)) { userEmail = loginName; } else { userName = loginName; } List users = commonUserService.getCommonUserByCondition(userName, userPhone, userEmail, null,null); //用户不存在 if (users == null || users.size() == 0 || users.size() > 1) { throw new UnknownAccountException(); } //校验 账户状态信息 MMSnsCommonUserEntity commonUserEntity = users.get(0); if (commonUserEntity.getUserStatus().equals(MMSnsCommonUserEntity.USER_STATUS_FORBIT)) { throw new LockedAccountException(); } else if (commonUserEntity.getUserStatus().equals(MMSnsCommonUserEntity.USER_STATUS_DELETE)) { throw new DisabledAccountException(); } else if (commonUserEntity.getUserStatus().equals(MMSnsCommonUserEntity.USER_STATUS_UNACTIVE)) { throw new AccountUnActiveException(); } //将用户信息保存到session中 SecurityUtils.getSubject().getSession().setAttribute(MMSnsCommonUserEntity.MMSNS_COMMON_USER, commonUserEntity); // 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配 SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(commonUserEntity.getUserName(), commonUserEntity.getUserPassword(), ByteSource.Util.bytes(commonUserEntity.getUserName() + commonUserEntity.getUserSalt()), getName()); return authenticationInfo; } } src/test/java/io/lettuce/core/sentinel/SentinelConnectionIntegrationTests.java /* * Copyright 2011-2020 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 * * https://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 io.lettuce.core.sentinel; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.inject.Inject; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import io.lettuce.core.*; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.sentinel.api.StatefulRedisSentinelConnection; import io.lettuce.core.sentinel.api.async.RedisSentinelAsyncCommands; import io.lettuce.core.sentinel.api.sync.RedisSentinelCommands; import io.lettuce.test.LettuceExtension; import io.lettuce.test.TestFutures; import io.lettuce.test.Wait; import io.lettuce.test.settings.TestSettings; /** * @author */ @ExtendWith(LettuceExtension.class) public class SentinelConnectionIntegrationTests extends TestSupport { private final RedisClient redisClient; private StatefulRedisSentinelConnection connection; private RedisSentinelCommands sentinel; private RedisSentinelAsyncCommands sentinelAsync; @Inject public SentinelConnectionIntegrationTests(RedisClient redisClient) { this.redisClient = redisClient; } @BeforeEach void before() { this.connection = this.redisClient.connectSentinel(SentinelTestSettings.SENTINEL_URI); this.sentinel = getSyncConnection(this.connection); this.sentinelAsync = this.connection.async(); } protected RedisSentinelCommands getSyncConnection(StatefulRedisSentinelConnection connection) { return connection.sync(); } @AfterEach void after() { this.connection.close(); } @Test void testAsync() { RedisFuture>> future = sentinelAsync.masters(); assertThat(TestFutures.getOrTimeout(future)).isNotNull(); assertThat(future.isDone()).isTrue(); assertThat(future.isCancelled()).isFalse(); } @Test void testFuture() throws Exception { RedisFuture> future = sentinelAsync.master("unknown master"); AtomicBoolean state = new AtomicBoolean(); future.exceptionally(throwable -> { state.set(true); return null; }); assertThat(future.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(state.get()).isTrue(); } @Test void testStatefulConnection() { StatefulRedisSentinelConnection statefulConnection = sentinel.getStatefulConnection(); assertThat(statefulConnection).isSameAs(statefulConnection.async().getStatefulConnection()); } @Test void testSyncConnection() { StatefulRedisSentinelConnection statefulConnection = sentinel.getStatefulConnection(); RedisSentinelCommands sync = statefulConnection.sync(); assertThat(sync.ping()).isEqualTo("PONG"); } @Test void testSyncAsyncConversion() { StatefulRedisSentinelConnection statefulConnection = sentinel.getStatefulConnection(); assertThat(statefulConnection.sync().getStatefulConnection()).isSameAs(statefulConnection); assertThat(statefulConnection.sync().getStatefulConnection().sync()).isSameAs(statefulConnection.sync()); } @Test void testSyncClose() { StatefulRedisSentinelConnection statefulConnection = sentinel.getStatefulConnection(); statefulConnection.sync().getStatefulConnection().close(); Wait.untilTrue(() -> !sentinel.isOpen()).waitOrTimeout(); assertThat(sentinel.isOpen()).isFalse(); assertThat(statefulConnection.isOpen()).isFalse(); } @Test void testAsyncClose() { StatefulRedisSentinelConnection statefulConnection = sentinel.getStatefulConnection(); statefulConnection.async().getStatefulConnection().close(); Wait.untilTrue(() -> !sentinel.isOpen()).waitOrTimeout(); assertThat(sentinel.isOpen()).isFalse(); assertThat(statefulConnection.isOpen()).isFalse(); } @Test void connectToOneNode() { RedisSentinelCommands connection = redisClient.connectSentinel(SentinelTestSettings.SENTINEL_URI) .sync(); assertThat(connection.ping()).isEqualTo("PONG"); connection.getStatefulConnection().close(); } @Test void connectWithByteCodec() { RedisSentinelCommands connection = redisClient.connectSentinel(new ByteArrayCodec(), SentinelTestSettings.SENTINEL_URI).sync(); assertThat(connection.master(SentinelTestSettings.MASTER_ID.getBytes())).isNotNull(); connection.getStatefulConnection().close(); } @Test void sentinelConnectionShouldDiscardPassword() { RedisURI redisURI = RedisURI.Builder.sentinel(TestSettings.host(), SentinelTestSettings.MASTER_ID) .withPassword("").build(); redisClient.setOptions(ClientOptions.builder().build()); StatefulRedisSentinelConnection connection = redisClient.connectSentinel(redisURI); assertThat(connection.sync().ping()).isEqualTo("PONG"); connection.close(); redisClient.setOptions(ClientOptions.create()); } @Test void sentinelConnectionShouldSetClientName() { RedisURI redisURI = RedisURI.Builder.sentinel(TestSettings.host(), SentinelTestSettings.MASTER_ID) .withClientName("my-client").build(); StatefulRedisSentinelConnection connection = redisClient.connectSentinel(redisURI); assertThat(connection.sync().clientGetname()).isEqualTo(redisURI.getClientName()); connection.close(); } @Test void sentinelManagedConnectionShouldSetClientName() { RedisURI redisURI = RedisURI.Builder.sentinel(TestSettings.host(), SentinelTestSettings.MASTER_ID) .withClientName("my-client").build(); StatefulRedisConnection connection = redisClient.connect(redisURI); assertThat(connection.sync().clientGetname()).isEqualTo(redisURI.getClientName()); connection.sync().quit(); assertThat(connection.sync().clientGetname()).isEqualTo(redisURI.getClientName()); connection.close(); } @Test void sentinelWithAuthentication() { RedisURI redisURI = RedisURI.Builder.sentinel(TestSettings.host(), 26381, SentinelTestSettings.MASTER_ID, "foobared") .withClientName("my-client").build(); redisClient.setOptions(ClientOptions.builder().pingBeforeActivateConnection(true).build()); StatefulRedisConnection connection = redisClient.connect(redisURI); connection.sync().quit(); assertThat(connection.sync().clientGetname()).isEqualTo(redisURI.getClientName()); connection.close(); } } 0 package com.blamejared.crafttweaker_annotation_processors.processors.document.page.member.header; import com.blamejared.crafttweaker_annotation_processors.processors.document.page.comment.DocumentationComment; import com.blamejared.crafttweaker_annotation_processors.processors.document.page.type.AbstractTypeInfo; import javax.annotation.Nonnull; import java.io.PrintWriter; public class DocumentedParameter implements Comparable { protected final String name; protected final AbstractTypeInfo type; protected final DocumentationComment comment; public DocumentedParameter(String name, AbstractTypeInfo type, DocumentationComment comment) { this.name = name; this.type = type; this.comment = comment; } public String formatForSignatureExample() { return String.format("%s as %s", name, type.getDisplayName()); } public int numberOfExamples() { return comment.numberOfExamplesFor(name); } public String getDescription() { return comment.getMarkdownDescription(); } public boolean isOptional() { return false; } public void writeParameterInfoIncludeOptionality(PrintWriter writer) { writer.printf("| %s | %s | %s | %s | %s |%n", name, type.getClickableMarkdown(), getDescription(), false, ""); } public void writeParameterInfoExcludeOptionality(PrintWriter writer) { writer.printf("| %s | %s | %s |%n", name, type.getClickableMarkdown(), getDescription()); } public String getExample(int index) { return comment.getExamples().getExampleFor(name).getTextValue(index); } @Override public int compareTo(@Nonnull DocumentedParameter other) { int temp = this.name.compareTo(other.name); if(temp != 0) { return temp; } return this.type.compareTo(other.type); } } reubenvarghese1/manage_coursessrc/test/course/CourseMappingDAOTest.java package test.course; import static org.junit.Assert.*; import org.junit.Test; import main.course.coursedao.CourseMappingDAO; public class CourseMappingDAOTest { CourseMappingDAO dao = null; @Test public void test_getDirectoryPathForProf() throws Exception { dao = new CourseMappingDAO(); String prof = "jimson"; String course = "CS225"; assertNotNull(dao.getDirectoryPathForProf(course, prof)); assertEquals("/home/Btech15/kshitij.cs15/cms/CS225_jimson/",dao.getDirectoryPathForProf(course, prof)); assertEquals("/home/Btech15/kshitij.cs15/cms/",dao.getDirectoryPathForProf("CS229", "samrat")); } @Test public void test_getDirectoryPath()throws Exception { dao = new CourseMappingDAO(); String course = "CS226"; String batch = "cse15b"; assertNotNull(dao.getDirectoryPath(course, batch)); assertEquals("/home/Btech15/kshitij.cs15/cms/CS226_jimson/",dao.getDirectoryPath(course, batch)); assertEquals("/home/Btech15/kshitij.cs15/cms/",dao.getDirectoryPath("CS231", "cse15b")); } } package iextrader; import iextrader.model.Client; import io.restassured.RestAssured; import net.serenitybdd.rest.SerenityRest; import org.junit.Before; import org.junit.Test; import static net.serenitybdd.rest.SerenityRest.given; import static net.serenitybdd.rest.SerenityRest.when; import static org.hamcrest.Matchers.equalTo; public class WhenMaintainingClientRecords { Client newClient; String clientId; @Before public void prepareTestData() { RestAssured.baseURI = "http://localhost:8080/api"; // Given an existing client Client newClient = Client.Builder.aClient() .withFirstName("Sarah-Jane") .withLastName("Smith") .withEmail("") .build(); given().contentType("application/json"). and().body(newClient) .when().post("/client") .then().statusCode(200); clientId = SerenityRest.lastResponse().jsonPath().getString("id"); } @Test public void should_be_able_to_update_an_existing_client() { Client updatedClient = Client.Builder.aClient().withFirstName("Sarah-Jane") .withLastName("Smith") .withEmail("") .build(); given().contentType("application/json") .and().body(updatedClient) .and().pathParam("id",clientId) .when().put("/client/{id}") .then().statusCode(200); given().pathParam("id", clientId) .when().get("/client/{id}") .then().body("email", equalTo("")); } @Test public void should_remove_client_from_the_registry() { // When I delete the client SerenityRest .given().pathParam("id", clientId) .when().delete("/client/{id}") .then().statusCode(204); // Then the client should no longer be found SerenityRest.given().pathParam("id",clientId) .when().get("/client/{id}") .then().statusCode(404); } } package com.xunlei.tdlive; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.xunlei.tdlive.protocol.XLLiveCreatePublishRoomRequest; import com.xunlei.tdlive.util.w; // compiled from: LivePlayerActivity.java class aq implements OnClickListener { final /* synthetic */ String a; final /* synthetic */ String b; final /* synthetic */ ap c; aq(ap apVar, String str, String str2) { this.c = apVar; this.a = str; this.b = str2; } public void onClick(DialogInterface dialogInterface, int i) { if (dialogInterface != null) { dialogInterface.dismiss(); } if (i == 1) { w wVar = new w("stream_get"); wVar.c(); LivePlayerActivity.e(this.c.c).a("\u6b63\u5728\u521b\u5efa\u76f4\u64ad...", false); new XLLiveCreatePublishRoomRequest(this.c.a, this.c.b, this.a, 0).send(new ar(this, wVar)); } } } package com.winterwell.utils.io; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Properties; import org.junit.Test; import com.winterwell.utils.containers.ArrayMap; import junit.framework.TestCase; public class ConfigBuilderTest extends TestCase { @Test public void testBoolean() throws IOException { TestSettings settings = new TestSettings(); ConfigBuilder parser = new ConfigBuilder(settings); Properties props = new Properties(); props.put("maybe", "true"); parser.set(props); assert settings.maybe; } @Test public void testArgsSet() throws IOException { TestSettings settings = new TestSettings(); ConfigBuilder parser = new ConfigBuilder(settings); Properties props = new Properties(); props.put("nolog", "true"); props.put("logdir", "/home/daniel/temp"); props.put("n", "7"); props.put("map.a", "Alice"); parser.set(props); assert settings.noLogging == true; assert settings.loggingDir.equals(new File("/home/daniel/temp")); assert settings.n == 7; } @Test public void testMap() throws IOException { TestSettings settings = new TestSettings(); ConfigBuilder parser = new ConfigBuilder(settings); Properties props = new Properties(); props.put("map.a", "Alice"); parser.set(props); assert settings.map.get("a").equals("Alice") : settings.map; } @Test public void testNest() throws IOException { NestedTestSettings settings = new NestedTestSettings(); ConfigBuilder parser = new ConfigBuilder(settings); Properties props = new Properties(); props.put("n", "2"); props.put("ts.n", "3"); parser.set(props); assert settings.n == 2; assert settings.ts.n == 3; } @Test public void testDebug() throws IOException { NestedTestSettings settings = new NestedTestSettings(); ConfigBuilder parser = new ConfigBuilder(settings).setDebug(true); Properties props = new Properties(); props.put("n", "2"); props.put("ts.n", "3"); parser.set(props); parser.setFromMain(new String[] {"-ts.meh", "foo"}); parser.get(); assert settings.n == 2; assert settings.ts.n == 3; } @Test public void testOptionsMessage() throws IOException { TestSettings settings = new TestSettings(); ConfigBuilder parser = new ConfigBuilder(settings); String om = parser.getOptionsMessage(); System.out.println(om); } @Test public void testCommandLineOptions() throws IOException { { TestSettings settings = new TestSettings(); ConfigBuilder parser = new ConfigBuilder(settings); parser.setFromMain(new String[] {"-meh", "whatever", "-logdir", "home"}); assert settings.meh.equals("whatever") : settings.meh; } { TestSettings settings = new TestSettings(); ConfigBuilder parser = new ConfigBuilder(settings); parser.setFromMain(new String[] {"-n", "10", "-logdir", "home"}); assert settings.n == 10 : settings.n; } } } class TestSettings { @Option public Boolean maybe; @Option public Map map = new ArrayMap("a","b"); @Option(tokens = "-logdir", description = "Directory to write log files to", required = true) public File loggingDir = new File("boblog"); @Option(tokens = "-n", description = "Number of things") public int n = 5; @Option(tokens = "-nolog", description = "Switch off logging") public boolean noLogging; @Option(tokens = "-v") public boolean verbose; @Option public String meh; } class NestedTestSettings { @Option TestSettings ts = new TestSettings(); @Option int n = 5; }yamanobori-old/design-pattern package net.yamanoboriold.designpattern.decorator.uppercaseinputstream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; public class UpperCaseInputStream extends FilterInputStream { public UpperCaseInputStream(InputStream in) { super(in); } @Override public int read() throws IOException { int c = in.read(); return c == -1 ? c : Character.toUpperCase(c); } @Override public int read(byte b[]) throws IOException { byte c[] = new byte[b.length]; int total = in.read(c, 0, c.length); if (total != -1) { for (int i = 0; i < total; i++) { b[i] = (byte) Character.toUpperCase(c[i]); } } return total; } @Override public int read(byte b[], int off, int len) throws IOException { byte c[] = new byte[b.length]; int total = in.read(c, off, len); if (total != -1) { for (int i = off; i < off + total; i++) { b[i] = (byte) Character.toUpperCase(c[i]); } } return total; } } package mc.carlton.freerpg.guiEvents; import mc.carlton.freerpg.gameTools.LanguageSelector; import mc.carlton.freerpg.playerAndServerInfo.PlayerStats; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.ClickType; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.lang.reflect.Array; import java.util.*; public class SkillsConfigGUIClick implements Listener { @EventHandler public void clickEvent(InventoryClickEvent e) { boolean proceed = true; try { InventoryType invType = e.getClickedInventory().getType(); } catch (Exception except) { proceed = false; return; } String[] titles_0 = {"Digging", "Woodcutting", "Mining", "Farming", "Fishing", "Archery", "Beast Mastery", "Swordsmanship", "Defense", "Axe Mastery", "Repair", "Agility", "Alchemy", "Smelting", "Enchanting"}; String[] labels_0 = {"digging", "woodcutting", "mining", "farming", "fishing", "archery", "beastMastery", "swordsmanship", "defense", "axeMastery", "repair", "agility", "alchemy", "smelting", "enchanting"}; String[] passiveLabels_0 = {"repair", "agility", "alchemy", "smelting", "enchanting"}; List labels = Arrays.asList(labels_0); List skillTitles = Arrays.asList(titles_0); List passiveLabels = Arrays.asList(passiveLabels_0); for (String skillTitle : skillTitles) { if (e.getView().getTitle().equalsIgnoreCase(skillTitle + " Configuration")) { String skillName = labels.get(skillTitles.indexOf(skillTitle)); if (e.getClickedInventory().getType() == InventoryType.PLAYER) { e.setCancelled(true); return; } if (e.getClick() != ClickType.LEFT) { e.setCancelled(true); } if (e.getCursor().getType() != Material.AIR) { e.setCancelled(true); } Player p = (Player) e.getWhoClicked(); LanguageSelector lang = new LanguageSelector(p); Inventory inv = e.getClickedInventory(); PlayerStats pStatClass = new PlayerStats(p); Map>> statAll = pStatClass.getData(); Map> pStat = pStatClass.getPlayerData(); if (e.getCurrentItem() != null) { PlayerStats languageChange = new PlayerStats(p); if (e.getCurrentItem().getType().equals(Material.ARROW)) { p.performCommand("frpg skillTreeGUI " + skillName); } else if (e.getRawSlot() == 19) {//Toggle EXPBar for skill pStatClass.togglePlayerSkillExpBar(skillName); p.performCommand("frpg skillConfigGUI " + skillName); } else if(e.getRawSlot() == 20 && !passiveLabels.contains(skillName)) { //Toggle Ability for skill pStatClass.togglePlayerSkillAbility(skillName); p.performCommand("frpg skillConfigGUI " + skillName); } else { switch (skillName) { case "digging": if (e.getSlot() == 37) { p.performCommand("frpg flintToggle"); p.performCommand("frpg skillConfigGUI " + skillName); } else if (e.getSlot() == 38) { p.performCommand("frpg megaDigToggle"); p.performCommand("frpg skillConfigGUI " + skillName); } break; case "woodcutting": if (e.getSlot() == 37) { p.performCommand("frpg leafBlowerToggle"); p.performCommand("frpg skillConfigGUI " + skillName); } break; case "mining": if (e.getSlot() == 37) { p.performCommand("frpg veinMinerToggle"); p.performCommand("frpg skillConfigGUI " + skillName); } break; case "fishing": if (e.getSlot() == 37) { p.performCommand("frpg grappleToggle"); p.performCommand("frpg skillConfigGUI " + skillName); } else if (e.getSlot() == 38) { p.performCommand("frpg hotRodToggle"); p.performCommand("frpg skillConfigGUI " + skillName); } break; case "axeMastery": if (e.getSlot() == 37) { p.performCommand("frpg holyAxeToggle"); p.performCommand("frpg skillConfigGUI " + skillName); } break; case "agility": if (e.getSlot() == 37) { p.performCommand("frpg speedToggle"); p.performCommand("frpg skillConfigGUI " + skillName); } break; case "alchemy": if (e.getSlot() == 37) { p.performCommand("frpg potionToggle"); p.performCommand("frpg skillConfigGUI " + skillName); } break; case "smelting": if (e.getSlot() == 37) { p.performCommand("frpg flamePickToggle"); p.performCommand("frpg skillConfigGUI " + skillName); } break; default: break; } } e.setCancelled(true); //So they cant take the items } break; } } } } DepanNodeUI/prod/src/com/google/devtools/depan/nodes/filters/eclipse/ui/widgets/ComposeModeControl.java10-100 /* * Copyright 2016 The Depan Project 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 com.google.devtools.depan.nodes.filters.eclipse.ui.widgets; import com.google.devtools.depan.nodes.filters.sequence.ComposeMode; import com.google.devtools.depan.platform.AlphabeticSorter; import com.google.devtools.depan.platform.ViewerObjectToString; import com.google.devtools.depan.platform.eclipse.ui.widgets.Selections; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.ComboViewer; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.widgets.Composite; /** * Allow the user to choice among several values for {@link ComposeMode}. * * @author */ public class ComposeModeControl extends Composite { private final ComboViewer viewer; private ControlSelectionChangedListener listener; public ComposeModeControl(Composite parent) { super(parent, SWT.NONE); setLayout(new FillLayout()); viewer = new ComboViewer(this, SWT.READ_ONLY | SWT.FLAT); viewer.setContentProvider(new ArrayContentProvider()); viewer.setLabelProvider(CONTROL_LABEL_PROVIDER); viewer.setComparator(new AlphabeticSorter(new ViewerObjectToString() { @Override public String getString(Object object) { return CONTROL_LABEL_PROVIDER.getText(object); } })); viewer.setInput(ComposeMode.values()); listener = new ControlSelectionChangedListener(); viewer.addSelectionChangedListener(listener); } private static ControlLabelProvider CONTROL_LABEL_PROVIDER = new ControlLabelProvider(); private static class ControlLabelProvider extends LabelProvider { @Override public String getText(Object element) { if (element instanceof ComposeMode) { ComposeMode item = (ComposeMode) element; return item.getTitle(); } // Not what was expected. return null; } } public void setComposeMode(ComposeMode mode) { viewer.setSelection(new StructuredSelection(mode)); } public ComposeMode getComposeMode() { return listener.getChoice(); } private class ControlSelectionChangedListener implements ISelectionChangedListener { private ComposeMode choice; @Override public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); choice = Selections.getFirstElement(selection, ComposeMode.class); } public ComposeMode getChoice() { return choice; } } } package ooclipse.editors; import org.eclipse.jface.text.*; import org.eclipse.jface.text.rules.*; public class OocTagScanner extends RuleBasedScanner { public OocTagScanner(ColorManager manager) { IToken string = new Token( new TextAttribute(manager.getColor(ColorConstants.STRING))); setRules(new IRule[] { // Add rule for double quotes new SingleLineRule("\"", "\"", string, '\\'), // Add a rule for single quotes new SingleLineRule("'", "'", string, '\\'), // Add generic whitespace rule. new WhitespaceRule(new WhitespaceDetector()), }); } } import org.junit.Test; import org.junit.jupiter.api.Assertions; public class RandomControllerTest { @Test public void test_checkObereGrenze() { at.klug.RandomController randomController = new at.klug.RandomController(); return; } @Test public void test_checkUntereGrenze() { at.klug.RandomController randomController = new at.klug.RandomController(); return; } } 0 package com.proofpoint.stats; import com.proofpoint.reporting.Bucketed; import com.proofpoint.stats.SparseTimeStat.BlockTimer; import com.proofpoint.testing.TestingTicker; import com.proofpoint.units.Duration; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.lang.reflect.Method; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.testng.Assert.assertEquals; public class TestSparseTimeStat { private TestingBucketIdProvider bucketIdProvider; private TestingTicker ticker; @BeforeMethod public void setup() { bucketIdProvider = new TestingBucketIdProvider(); ticker = new TestingTicker(); } @Test public void testInitialState() throws Exception { SparseTimeStat stat = new SparseTimeStat(); stat.add(1, NANOSECONDS); assertPreviousDistributionEmpty(stat); } @Test public void testWithBucketIdProvider() throws Exception { SparseTimeStat stat = new SparseTimeStat(); stat.setBucketIdProvider(bucketIdProvider); stat.add(1, MILLISECONDS); assertPreviousDistributionEmpty(stat); ++bucketIdProvider.id; stat.add(new Duration(2, MILLISECONDS)); stat.add(3_000_000, NANOSECONDS); assertPreviousDistribution(stat, 1, .001, .001, .001); ++bucketIdProvider.id; assertPreviousDistribution(stat, 2, .002, .003, .005); } @Test public void testDiscardsBuckets() throws Exception { SparseTimeStat distribution = new SparseTimeStat(); distribution.add(100, MILLISECONDS); distribution.setBucketIdProvider(bucketIdProvider); distribution.add(1, MILLISECONDS); assertPreviousDistributionEmpty(distribution); ++bucketIdProvider.id; distribution.add(2, MILLISECONDS); distribution.add(3, MILLISECONDS); assertPreviousDistribution(distribution, 1, .001, .001, .001); ++bucketIdProvider.id; ++bucketIdProvider.id; distribution.add(0.1, SECONDS); assertPreviousDistributionEmpty(distribution); ++bucketIdProvider.id; assertPreviousDistribution(distribution, 1, .1, .1, .1); distribution.add(0.2, SECONDS); ++bucketIdProvider.id; ++bucketIdProvider.id; assertPreviousDistributionEmpty(distribution); } @Test public void testTimeCallable() throws Exception { SparseTimeStat stat = new SparseTimeStat(ticker); stat.setBucketIdProvider(bucketIdProvider); stat.time(new Callable() { @Override public Void call() { ticker.increment(10, TimeUnit.MILLISECONDS); return null; } }); ++bucketIdProvider.id; assertPreviousDistribution(stat, 1, 0.010, 0.010, 0.010); } @Test public void testTimeCallableException() throws Exception { SparseTimeStat stat = new SparseTimeStat(ticker); stat.setBucketIdProvider(bucketIdProvider); try { stat.time(new Callable() { @Override public Void call() { ticker.increment(10, TimeUnit.MILLISECONDS); throw new RuntimeException("test exception"); } }); } catch (RuntimeException ignored) { } ++bucketIdProvider.id; assertPreviousDistribution(stat, 1, 0.010, 0.010, 0.010); } @Test public void testTimeTry() throws Exception { SparseTimeStat stat = new SparseTimeStat(ticker); stat.setBucketIdProvider(bucketIdProvider); try (BlockTimer ignored = stat.time()) { ticker.increment(10, TimeUnit.MILLISECONDS); } ++bucketIdProvider.id; assertPreviousDistribution(stat, 1, 0.010, 0.010, 0.010); } @Test public void testTimeTryException() throws Exception { SparseTimeStat stat = new SparseTimeStat(ticker); stat.setBucketIdProvider(bucketIdProvider); try (BlockTimer ignored = stat.time()) { ticker.increment(10, TimeUnit.MILLISECONDS); throw new Exception("test exception"); } catch (Exception ignored) { } ++bucketIdProvider.id; assertPreviousDistribution(stat, 1, 0.010, 0.010, 0.010); } @Test public void testTimeTrySetTimer() throws Exception { SparseTimeStat oldStat = new SparseTimeStat(ticker); SparseTimeStat stat = new SparseTimeStat(ticker); stat.setBucketIdProvider(bucketIdProvider); try (BlockTimer timer = oldStat.time()) { ticker.increment(10, TimeUnit.MILLISECONDS); timer.timeTo(stat); } ++bucketIdProvider.id; assertPreviousDistribution(stat, 1, 0.010, 0.010, 0.010); assertPreviousDistributionEmpty(oldStat); } private void assertPreviousDistributionEmpty(SparseTimeStat distribution) throws Exception { assertPreviousDistribution(distribution, Double.NaN, Double.NaN, Double.NaN, Double.NaN); } private void assertPreviousDistribution(SparseTimeStat distribution, double expectedCount, double expectedMin, double expectedMax, double expectedTotal) throws Exception { Method method = Bucketed.class.getDeclaredMethod("getPreviousBucket"); method.setAccessible(true); SparseTimeStat.Distribution previousBucket = (SparseTimeStat.Distribution) method.invoke(distribution); assertEquals(previousBucket.getCount(), expectedCount); assertEquals(previousBucket.getMin(), expectedMin); assertEquals(previousBucket.getMax(), expectedMax); assertEquals(previousBucket.getTotal(), expectedTotal); } } jEdit/org/gjt/sp/jedit/JEditMode.java0 /* * JEditMode.java - jEdit editing mode * :tabSize=4:indentSize=4:noTabs=false: * :folding=explicit:collapseFolds=1: * * Copyright (C) 2007 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.gjt.sp.jedit; import org.gjt.sp.util.Log; /** * @author * @version $Id: Buffer.java 8190 2006-12-07 07:58:34Z kpouer $ * @since jEdit 4.3pre10 */ class JEditMode extends Mode { //{{{ JEditMode constructor JEditMode(String name) { super(name); } //}}} //{{{ setProperty() method /** * Sets a mode property. * @param key The property name * @param value The property value */ @Override public void setProperty(String key, Object value) { if (initialized) { String prefix = "mode." + name + '.'; jEdit.setProperty(prefix + key, value.toString()); } props.put(key,value); } //}}} //{{{ unsetProperty() method /** * Unsets a mode property. * @param key The property name */ @Override public void unsetProperty(String key) { if (initialized) { String prefix = "mode." + name + '.'; jEdit.unsetProperty(prefix + key); } props.remove(key); } //}}} //{{{ getProperty() method /** * Returns a mode property. * * @param key The property name * @since jEdit 4.3pre10 */ @Override public Object getProperty(String key) { //if(jEdit.getBooleanProperty(prefix + "customSettings")) //{ String prefix = "mode." + name + '.'; String property = jEdit.getProperty(prefix + key); if(property != null) { Object value; try { value = new Integer(property); } catch(NumberFormatException nf) { value = property; } return value; } //} Object value = props.get(key); if(value != null) return value; String global = jEdit.getProperty("buffer." + key); if(global != null) { try { return new Integer(global); } catch(NumberFormatException nf) { return global; } } else return null; } //}}} //{{{ init() method /** * Keeps track of mode initialization, to avoid overwriting * custom mode properties in the user's settings. */ @Override public void init() { initialized = true; super.init(); } //}}} //{{{ loadIfNecessary() method /** * Loads the mode from disk if it hasn't been loaded already. * @since jEdit 4.3pre10 */ @Override public void loadIfNecessary() { if(marker == null) { jEdit.loadMode(this); if (marker == null) Log.log(Log.ERROR, this, "Mode not correctly loaded, token marker is still null"); } } //}}} private boolean initialized; } 0 package org.salamansar.oder.module.payments.mapper; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.Date; import org.envbuild.generator.RandomGenerator; import org.junit.Test; import static org.junit.Assert.*; import org.mapstruct.factory.Mappers; import org.salamansar.oder.core.domain.Income; import org.salamansar.oder.module.payments.dto.IncomeDto; /** * * @author Salamansar */ public class IncomeMapperTest { private IncomeMapper mapper = Mappers.getMapper(IncomeMapper.class); private RandomGenerator generator = new RandomGenerator(); @Test public void mapIncome() { LocalDate date = LocalDate.of(2018, Month.MARCH, 1); Income income = generator.generate(Income.class, date); IncomeDto result = mapper.mapToDto(income); assertNotNull(result); assertNotNull(result.getAmount()); assertTrue(income.getAmount().compareTo(result.getAmount()) == 0); assertNotNull(result.getDescription()); assertEquals(income.getDescription(), result.getDescription()); assertNotNull(result.getDocumentNumber()); assertEquals(income.getDocumentNumber(), result.getDocumentNumber()); assertNotNull(result.getId()); assertEquals(income.getId(), result.getId()); assertNotNull(result.getIncomeDate()); assertEquals(new Date(date.atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli()), result.getIncomeDate()); } @Test public void mapIncomeWithEmptyDate() { Income income = generator.generate(Income.class); IncomeDto result = mapper.mapToDto(income); assertNotNull(result); assertNull(result.getIncomeDate()); } @Test public void mapNullIncome() { IncomeDto result = mapper.mapToDto(null); assertNull(result); } @Test public void mapIncomeDto() { LocalDateTime current = LocalDateTime.now().truncatedTo(ChronoUnit.DAYS); IncomeDto income = generator.generate(IncomeDto.class); income.setIncomeDate(new Date(current.toInstant(ZoneOffset.UTC).toEpochMilli())); Income result = mapper.mapFromDto(income); assertNotNull(result); assertNotNull(result.getAmount()); assertTrue(income.getAmount().compareTo(result.getAmount()) == 0); assertNotNull(result.getDescription()); assertEquals(income.getDescription(), result.getDescription()); assertNotNull(result.getDocumentNumber()); assertEquals(income.getDocumentNumber(), result.getDocumentNumber()); assertNotNull(result.getId()); assertEquals(income.getId(), result.getId()); assertNotNull(result.getIncomeDate()); assertEquals(income.getIncomeDate(), new Date(result.getIncomeDate().atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli())); } @Test public void mapIncomeDtoWithEmptyDate() { IncomeDto income = generator.generate(IncomeDto.class); income.setIncomeDate(null); Income result = mapper.mapFromDto(income); assertNotNull(result); assertNull(result.getIncomeDate()); } @Test public void mapNullIncomeDto() { Income result = mapper.mapFromDto(null); assertNull(result); } } package com.msas.MSAS.UIControllers.Grids.Personnel; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.msas.MSAS.DomainModel.Personnel.Personnel; import com.msas.MSAS.Repositories.DroitRepository; import com.msas.MSAS.Repositories.PersonnelRepository; import com.msas.MSAS.UIControllers.MSASUIControls.PersonnelDroitAsChildTableRenderer; import com.msas.MSAS.UIControllers.Others.IconsHolder; import com.msas.MSAS.UIControllers.UsefulModules.GridCells.MSRenderer; import com.msas.MSAS.UIControllers.UsefulModules.Grids.MSEditableDeletableGrid; import com.vaadin.flow.component.icon.VaadinIcon; public class PersonnelGrid extends MSEditableDeletableGrid { private static final long serialVersionUID = 2309149258862179576L; private PersonnelDroitAsChildTableRenderer personnelDroitAsChildTableRenderer; public PersonnelGrid(PersonnelRepository repository, DroitRepository droitRepository) { super(Personnel.class, repository); this.personnelDroitAsChildTableRenderer.setRepository(droitRepository); } @Override protected Map propertyNamesToColumnHeadersTranslator() { Map result = new HashMap(); result.put("nom", "Nom"); result.put("prenom", "Prénom"); result.put("numeroTelephone", "N° Téléphone"); result.put("pieceIdentitee", "N° d'identitée"); result.put("metier", "Métier"); result.put("grade", "Grade"); return result; } @Override protected String[] simplePropertyNamesToShow() { return new String[] { "nom", "prenom", "numeroTelephone", "metier", "grade", "pieceIdentitee" }; } @Override protected Map propertyNamesToColumnIconsTranslator() { Map result = new HashMap<>(); result.put("nom", IconsHolder.extractIcon("personnel.nom")); result.put("prenom", IconsHolder.extractIcon("personnel.prenom")); result.put("numeroTelephone", IconsHolder.extractIcon("personnel.numeroTelephone")); result.put("metier", IconsHolder.extractIcon("metier.designation")); result.put("grade", IconsHolder.extractIcon("grade.designation")); result.put("pieceIdentitee", IconsHolder .extractIcon("personnel.pieceIdentitee.serialNumber")); return result; } @Override protected Collection> getAdditionalColumns() { this.personnelDroitAsChildTableRenderer = new PersonnelDroitAsChildTableRenderer(); Set> result = new HashSet<>(); result.add(this.personnelDroitAsChildTableRenderer); return result; } } DDTH/DASP package ddth.dasp.common.module; public interface IModuleManager { } 1-10 package rocks.gioac96.veronica.samples; import rocks.gioac96.veronica.common.CommonRequestHandlers; import rocks.gioac96.veronica.core.Application; import rocks.gioac96.veronica.common.CommonRoutes; import rocks.gioac96.veronica.core.Route; import rocks.gioac96.veronica.core.Router; import rocks.gioac96.veronica.static_server.FilePermissionsManager; public class StaticServer { public static void main(String[] args) { Application.builder() .router(Router.builder() .route(Route.staticRouteBuilder() .permissionManager(FilePermissionsManager.builder() .permissions("D:\\projects\\veronica\\src",true) .permissions("D:\\projects\\veronica\\src\\test",false) .build()) .permissionDecider((request, filePermissions) -> filePermissions) .baseDir("D:\\projects\\veronica") .basePath("/static") .build()) .defaultRequestHandler(CommonRequestHandlers.notFound()) .build()) .port(80) .build() .start(); } } src/main/java/com/xthena/dzb/manager/DyManager.java package com.xthena.dzb.manager; import com.xthena.dzb.domain.Dy; import com.xthena.core.hibernate.HibernateEntityDao; import org.springframework.stereotype.Service; @Service public class DyManager extends HibernateEntityDao { } lbenda/sp-model package cz.lbenda.spmodel.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Stored procedure * @author lbenda on 9/10/17. */ @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface StoredProcedure { /** Catalog name */ String catalog(); /** DB schema name */ String schema(); /** Name of stored procedure */ String name(); } package space.galactictavern.app.core.fcm; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; import com.pixplicity.easyprefs.library.Prefs; import space.galactictavern.app.Secrets; import space.galactictavern.app.core.Utility; import space.galactictavern.app.core.retrofit.FcmApiService; import space.galactictavern.app.models.common.StandardResponse; public class GtFirebaseInstanceIdService extends FirebaseInstanceIdService { /** * Called if InstanceID token is updated. This may occur if the security of * the previous token had been compromised. This call is initiated by the * InstanceID provider. */ @Override public void onTokenRefresh() { try { // Fetch updated Instance ID token and notify our app's server of any changes (if applicable). String token = FirebaseInstanceId.getInstance().getToken(); StandardResponse resp = FcmApiService.Factory.getInstance() .registerDevice(Secrets.GT_API_SECRET, token, "").toBlocking().first(); if (!resp.successful) { throw new Exception("Failed to complete token refresh: " + resp.err, null); } // You should store a boolean that indicates whether the generated token has been // sent to your server. If the boolean is false, send the token to your server, // otherwise your server should have already received the token. Prefs.putBoolean(Utility.PREFS_FCM_DEVICE_REGISTRATION_TOKEN_SENT, true); } catch (Exception e) { // If an exception happens while fetching the new token or updating our registration data // on a third-party server, this ensures that we'll attempt the update at a later time. Prefs.putBoolean(Utility.PREFS_FCM_DEVICE_REGISTRATION_TOKEN_SENT, false); } // Notify UI that registration has completed, so the progress indicator can be hidden. Intent registrationComplete = new Intent(Utility.FCM_DEVICE_REGISTRATION_COMPLETE); LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete); } } /* * Copyright (c) 2019 by . * * The author 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 com.simiacryptus.util; import com.simiacryptus.ref.wrappers.RefSystem; import javax.annotation.Nonnull; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; public class TimerText { final long start = RefSystem.currentTimeMillis(); @Nonnull private final SimpleDateFormat formatter; public TimerText() { formatter = new SimpleDateFormat("[HH:mm:ss]"); formatter.setTimeZone(TimeZone.getTimeZone("GMT")); } @Nonnull @Override public String toString() { return formatter.format(new Date(RefSystem.currentTimeMillis() - start)); } } 0 package org.recap.model.jpa; import org.junit.jupiter.api.Test; import org.recap.BaseTestCaseUT; import static org.junit.jupiter.api.Assertions.assertNotNull; public class MatchingMatchPointsEntityUT extends BaseTestCaseUT { @Test public void MatchingMatchPointsEntity() { String matchCriteria = "singlematch"; MatchingMatchPointsEntity matchingMatchPointsEntity = new MatchingMatchPointsEntity(); matchingMatchPointsEntity.setMatchCriteria(matchCriteria); assertNotNull(matchingMatchPointsEntity.getMatchCriteria()); } } 100-1000 package org.springframework.roo.classpath.antlrjavaparser; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.lang3.ObjectUtils; import com.github.antlrjavaparser.api.CompilationUnit; import com.github.antlrjavaparser.api.ImportDeclaration; import com.github.antlrjavaparser.api.body.BodyDeclaration; import com.github.antlrjavaparser.api.body.ClassOrInterfaceDeclaration; import com.github.antlrjavaparser.api.body.ConstructorDeclaration; import com.github.antlrjavaparser.api.body.EnumConstantDeclaration; import com.github.antlrjavaparser.api.body.EnumDeclaration; import com.github.antlrjavaparser.api.body.FieldDeclaration; import com.github.antlrjavaparser.api.body.MethodDeclaration; import com.github.antlrjavaparser.api.body.Parameter; import com.github.antlrjavaparser.api.body.TypeDeclaration; import com.github.antlrjavaparser.api.body.VariableDeclarator; import com.github.antlrjavaparser.api.expr.AnnotationExpr; import com.github.antlrjavaparser.api.expr.MarkerAnnotationExpr; import com.github.antlrjavaparser.api.expr.MemberValuePair; import com.github.antlrjavaparser.api.expr.NormalAnnotationExpr; import com.github.antlrjavaparser.api.expr.SingleMemberAnnotationExpr; import com.github.antlrjavaparser.api.stmt.BlockStmt; import com.github.antlrjavaparser.api.stmt.Statement; import com.github.antlrjavaparser.api.type.ClassOrInterfaceType; import com.github.antlrjavaparser.api.type.PrimitiveType; import com.github.antlrjavaparser.api.type.Type; import com.github.antlrjavaparser.api.type.VoidType; import com.github.antlrjavaparser.api.type.WildcardType; /** * Utilities to update a Java Parser compilation unit from other * * @author * @since 1.2.2 */ public class UpdateCompilationUnitUtils { /** * Structure to store a {@link VariableDeclarator} and its * {@link FieldDeclaration} together * * @author Di */ private static class FieldEntry { private final FieldDeclaration fieldDeclaration; private final VariableDeclarator variableDeclarator; FieldEntry(final FieldDeclaration fieldDeclaration, final VariableDeclarator variableDeclarator) { this.fieldDeclaration = fieldDeclaration; this.variableDeclarator = variableDeclarator; } } /** * Compare two {@link ImportDeclaration} * * @param declaration1 * @param declaration2 * @return true if are equals */ public static boolean equals(final ImportDeclaration declaration1, final ImportDeclaration declaration2) { return declaration1.isAsterisk() == declaration2.isAsterisk() && declaration1.isStatic() == declaration2.isStatic() && declaration1.getName().getName().equals(declaration2.getName().getName()); } /** * Compare two {@link Type} * * @param type * @param type2 * @return */ private static boolean equals(final Type type, final Type type2) { if (ObjectUtils.equals(type, type2)) { return true; } if (type.getClass() != type2.getClass()) { return false; } if (type instanceof ClassOrInterfaceType) { final ClassOrInterfaceType cType = (ClassOrInterfaceType) type; final ClassOrInterfaceType cType2 = (ClassOrInterfaceType) type2; return cType.getName().equals(cType2.getName()); } else if (type instanceof PrimitiveType) { final PrimitiveType pType = (PrimitiveType) type; final PrimitiveType pType2 = (PrimitiveType) type2; return pType.getType() == pType2.getType(); } else if (type instanceof VoidType) { return true; } else if (type instanceof WildcardType) { final WildcardType wType = (WildcardType) type; final WildcardType wType2 = (WildcardType) type2; return equals(wType.getSuper(), wType2.getSuper()) && equals(wType.getExtends(), wType2.getExtends()); } return false; } /** * Update {@code compilationUnit} imports, annotation, fields, methods... * from {@code cidCompilationUnit} information * * @param compilationUnit * @param cidCompilationUnit */ public static void updateCompilationUnitImports(final CompilationUnit compilationUnit, final CompilationUnit cidCompilationUnit) { boolean notFound; final List cidImports = new ArrayList(); if (cidCompilationUnit.getImports() != null) { cidImports.addAll(cidCompilationUnit.getImports()); } if (compilationUnit.getImports() != null) { for (final Iterator originalImportIter = compilationUnit.getImports().iterator(); originalImportIter.hasNext();) { final ImportDeclaration originalImport = originalImportIter.next(); notFound = true; for (final Iterator newImportIter = cidImports.iterator(); newImportIter .hasNext();) { final ImportDeclaration newImport = newImportIter.next(); if (equals(originalImport, newImport)) { // new Import found in original imports // remove from newImports to check newImportIter.remove(); // Mark as found notFound = false; } } if (notFound) { // If not found in newImports remove from compilation unit originalImportIter.remove(); } } } if (cidImports.isEmpty()) { // Done it return; } // Add missing new imports compilationUnit.getImports().addAll(cidImports); } /** * Updates {@code compilationUnit} types from {@code cidCompilationUnit} * information * * @param compilationUnit * @param cidCompilationUnit */ public static void updateCompilationUnitTypes(final CompilationUnit compilationUnit, final CompilationUnit cidCompilationUnit) { boolean notFound; final List cidTypes = new ArrayList(cidCompilationUnit.getTypes()); for (final Iterator originalTypestIter = compilationUnit.getTypes().iterator(); originalTypestIter .hasNext();) { final TypeDeclaration originalType = originalTypestIter.next(); notFound = true; for (final Iterator newTypeIter = cidTypes.iterator(); newTypeIter.hasNext();) { final TypeDeclaration newType = newTypeIter.next(); if (originalType.getName().equals(newType.getName()) && originalType.getClass() == newType.getClass()) { // new Type found in original imports if (originalType instanceof EnumDeclaration) { updateCompilationUnitEnumeration((EnumDeclaration) originalType, (EnumDeclaration) newType); } else { updateCompilationUnitType(originalType, newType); } // remove from newImports to check newTypeIter.remove(); // Mark as found notFound = false; } } if (notFound) { // If not found in newTypes so remove from compilation unit originalTypestIter.remove(); } } if (cidTypes.isEmpty()) { // Done it return; } // Add missing new imports compilationUnit.getTypes().addAll(cidTypes); } /** * Update {@code originalType} annotation, fields, methods... from * {@code cidCompilationUnit} information * * @param originalType * @param newType */ public static void updateCompilationUnitType(final TypeDeclaration originalType, final TypeDeclaration newType) { if (originalType.getModifiers() != newType.getModifiers()) { originalType.setModifiers(newType.getModifiers()); } if (originalType.getAnnotations() == null && newType.getAnnotations() != null) { originalType.setAnnotations(new ArrayList()); } updateAnnotations(originalType.getAnnotations(), newType.getAnnotations()); updateFields(originalType, newType); updateConstructors(originalType, newType); updateMethods(originalType, newType); updateInnerTypes(originalType, newType); // Check if TypeDeclarations are instance of ClassOrInterfaceDeclaration // to be able to obtain extends and implements types if (originalType instanceof ClassOrInterfaceDeclaration && newType instanceof ClassOrInterfaceDeclaration) { updateExtends((ClassOrInterfaceDeclaration) originalType, (ClassOrInterfaceDeclaration) newType); updateImplements((ClassOrInterfaceDeclaration) originalType, (ClassOrInterfaceDeclaration) newType); } } /** * Update {@code originalType} constructors from {@code cidCompilationUnit} * information * * @param originalType * @param newType */ private static void updateConstructors(final TypeDeclaration originalType, final TypeDeclaration newType) { // Get a list of all constructors final List cidConstructor = new ArrayList(); if (newType.getMembers() != null) { for (final BodyDeclaration element : newType.getMembers()) { if (element instanceof ConstructorDeclaration) { cidConstructor.add((ConstructorDeclaration) element); } } } ConstructorDeclaration originalConstructor, newConstructor; boolean notFound; // Iterate over every method definition if (originalType.getMembers() != null) { for (final Iterator originalMemberstIter = originalType.getMembers().iterator(); originalMemberstIter.hasNext();) { final BodyDeclaration originalMember = originalMemberstIter.next(); if (!(originalMember instanceof ConstructorDeclaration)) { // this is not a method definition continue; } originalConstructor = (ConstructorDeclaration) originalMember; notFound = true; // look at cidConstructor for originalConstructor for (final Iterator newConstructorIter = cidConstructor.iterator(); newConstructorIter .hasNext();) { newConstructor = newConstructorIter.next(); // Check if is the same constructor (comparing its // parameters) if (equalsDeclaration(originalConstructor, newConstructor)) { notFound = false; // Remove from cid methods to check newConstructorIter.remove(); // Update modifier if is changed if (originalConstructor.getModifiers() != newConstructor.getModifiers()) { originalConstructor.setModifiers(newConstructor.getModifiers()); } // Update annotations if are changed if (!equalsAnnotations(originalConstructor.getAnnotations(), newConstructor.getAnnotations())) { originalConstructor.setAnnotations(newConstructor.getAnnotations()); } // Update body if is changed if (!equals(originalConstructor.getBlock(), newConstructor.getBlock())) { originalConstructor.setBlock(newConstructor.getBlock()); } break; } } if (notFound) { originalMemberstIter.remove(); } } } if (cidConstructor.isEmpty()) { // Done it return; } // add new constructors if (originalType.getMembers() == null) { originalType.setMembers(new ArrayList()); } originalType.getMembers().addAll(cidConstructor); } /** * Compares {@code originalConstructor} declaration to * {@code newConstructor}
* This compares constructor parameters and its types * * @param originalConstructor * @param newConstructor * @return true if declaration are equals */ private static boolean equalsDeclaration(final ConstructorDeclaration originalConstructor, final ConstructorDeclaration newConstructor) { if (!equalsParameters(originalConstructor.getParameters(), newConstructor.getParameters())) { return false; } return true; } /** * Updates all subclasses of {@code originalType} from {@code newType} * information * * @param originalType * @param newType */ private static void updateInnerTypes(final TypeDeclaration originalType, final TypeDeclaration newType) { // Get a list of all types final List cidTypes = new ArrayList(); if (newType.getMembers() != null) { for (final BodyDeclaration element : newType.getMembers()) { if (element instanceof TypeDeclaration) { cidTypes.add((TypeDeclaration) element); } } } TypeDeclaration originalInner, newInner; boolean notFound; // Iterate over every type definition if (originalType.getMembers() != null) { for (final Iterator originalMemberstIter = originalType.getMembers().iterator(); originalMemberstIter.hasNext();) { final BodyDeclaration originalMember = originalMemberstIter.next(); if (!(originalMember instanceof TypeDeclaration)) { // this is not a method definition continue; } originalInner = (TypeDeclaration) originalMember; notFound = true; // look at ciMethods for method for (final Iterator newInnerIter = cidTypes.iterator(); newInnerIter .hasNext();) { newInner = newInnerIter.next(); if (originalInner.getName().equals(newInner.getName()) && originalInner.getClass() == newInner.getClass()) { notFound = false; if (originalInner instanceof EnumDeclaration) { updateCompilationUnitEnumeration((EnumDeclaration) originalInner, (EnumDeclaration) newInner); } else { updateCompilationUnitType(originalInner, newInner); } newInnerIter.remove(); break; } } if (notFound) { originalMemberstIter.remove(); } } } if (cidTypes.isEmpty()) { // Done it return; } // Add new methods if (originalType.getMembers() == null) { originalType.setMembers(new ArrayList()); } originalType.getMembers().addAll(cidTypes); } /** * Updates {@code originalType} enumeration from {@code newType} information * * @param originalType * @param newType */ private static void updateCompilationUnitEnumeration(final EnumDeclaration originalType, final EnumDeclaration newType) { if (originalType.getModifiers() != newType.getModifiers()) { originalType.setModifiers(newType.getModifiers()); } if (originalType.getAnnotations() == null && newType.getAnnotations() != null) { originalType.setAnnotations(new ArrayList()); } if (!equalsEnumConstants(originalType.getEntries(), newType.getEntries())) { originalType.setEntries(newType.getEntries()); } updateAnnotations(originalType.getAnnotations(), newType.getAnnotations()); updateFields(originalType, newType); updateConstructors(originalType, newType); updateMethods(originalType, newType); } /** * Compares two {@link EnumConstantDeclaration} list * * @param entries * @param entries2 * @return */ private static boolean equalsEnumConstants(final List entries, final List entries2) { if (ObjectUtils.equals(entries, entries2)) { return true; } if (entries == null || entries2 == null) { return false; } if (entries.size() != entries2.size()) { return false; } for (int i = 0; i < entries.size(); i++) { final EnumConstantDeclaration constant = entries.get(i); final EnumConstantDeclaration constant2 = entries2.get(i); if (!equals(constant, constant2)) { return false; } } return true; } /** * Compares to {@link EnumConstantDeclaration} * * @param constant * @param constant2 * @return */ private static boolean equals(final EnumConstantDeclaration constant, final EnumConstantDeclaration constant2) { if (!constant.getName().equals(constant2.getName())) { return false; } if (!equalsAnnotations(constant.getAnnotations(), constant2.getAnnotations())) { return false; } if (ObjectUtils.equals(constant.getClassBody(), constant2.getClassBody())) { return true; } if (constant.getClassBody() == null || constant2.getClassBody() == null) { return false; } final List body = constant.getClassBody(); final List body2 = constant2.getClassBody(); if (body.size() != body2.size()) { return false; } for (int i = 0; i < body.size(); i++) { final BodyDeclaration item = body.get(i); final BodyDeclaration item2 = body2.get(i); if (item.getClass() != item2.getClass()) { return false; } // Compares contents if (!item.toString().equals(item2.toString())) { return false; } } return true; } /** * Updates {@code originalType} methods from {@code newType} information * * @param originalType * @param newType */ private static void updateMethods(final TypeDeclaration originalType, final TypeDeclaration newType) { // Get a list of all methods final List cidMethods = new ArrayList(); if (newType.getMembers() != null) { for (final BodyDeclaration element : newType.getMembers()) { if (element instanceof MethodDeclaration) { cidMethods.add((MethodDeclaration) element); } } } MethodDeclaration originalMethod, newMethod; boolean notFound; // Iterate over every method definition if (originalType.getMembers() != null) { for (final Iterator originalMemberstIter = originalType.getMembers().iterator(); originalMemberstIter.hasNext();) { final BodyDeclaration originalMember = originalMemberstIter.next(); if (!(originalMember instanceof MethodDeclaration)) { // this is not a method definition continue; } originalMethod = (MethodDeclaration) originalMember; notFound = true; // look at ciMethos for method for (final Iterator newMethodsIter = cidMethods.iterator(); newMethodsIter .hasNext();) { newMethod = newMethodsIter.next(); if (equals(originalMethod, newMethod)) { notFound = false; // Remove from cid methods to check newMethodsIter.remove(); break; } } if (notFound) { originalMemberstIter.remove(); } } } if (cidMethods.isEmpty()) { // Done it return; } // Add new methods if (originalType.getMembers() == null) { originalType.setMembers(new ArrayList()); } originalType.getMembers().addAll(cidMethods); } /** * Compares two {@link MethodDeclaration} * * @param originalMethod * @param newMethod * @return */ private static boolean equals(final MethodDeclaration originalMethod, final MethodDeclaration newMethod) { return originalMethod.getModifiers() == newMethod.getModifiers() && originalMethod.getName().equals(newMethod.getName()) && equalsParameters(originalMethod.getParameters(), newMethod.getParameters()) && equals(originalMethod.getBody(), newMethod.getBody()); } /** * Compares two {@link BlockStmt} * * @param body * @param body2 * @return */ private static boolean equals(final BlockStmt body, final BlockStmt body2) { if (ObjectUtils.equals(body, body2)) { return true; } if (body == null || body2 == null) { return false; } if (body.getStmts().size() != body2.getStmts().size()) { return false; } final List statements = body.getStmts(); final List statements2 = body2.getStmts(); for (int i = 0; i < statements.size(); i++) { if (!equals(statements.get(i), statements2.get(i))) { return false; } } return true; } /** * Compares tow {@link Statement} * * @param statement * @param statement2 * @return */ private static boolean equals(final Statement statement, final Statement statement2) { if (statement.getClass() != statement2.getClass()) { return false; } // TODO As Roo doesn't make statement changes we can ignore it return true; } /** * Compares two {@link Parameter} list * * @param parameters * @param parameters2 * @return */ private static boolean equalsParameters(final List parameters, final List parameters2) { if (parameters == parameters2) { return true; } if (parameters == null || parameters2 == null) { return false; } if (parameters.size() != parameters2.size()) { return false; } Parameter parameter, parameter2; for (int i = 0; i < parameters.size(); i++) { parameter = parameters.get(i); parameter2 = parameters2.get(i); if (!parameter.getId().getName().equals(parameter2.getId().getName())) { return false; } if (!equals(parameter.getType(), parameter2.getType())) { return false; } if (!equalsAnnotations(parameter.getAnnotations(), parameter2.getAnnotations())) { return false; } } return true; } /** * Update {@code originalType} fields from {@code newType} information * * @param originalType * @param newType */ private static void updateFields(final TypeDeclaration originalType, final TypeDeclaration newType) { // Get a map of all fields (as FieldDeclaration could contain more than // one field) final Map cidFields = new HashMap(); String fieldName; FieldDeclaration field; if (newType.getMembers() != null) { for (final BodyDeclaration element : newType.getMembers()) { if (element instanceof FieldDeclaration) { field = (FieldDeclaration) element; for (final VariableDeclarator variable : field.getVariables()) { fieldName = variable.getId().getName(); cidFields.put(fieldName, new FieldEntry(field, variable)); } } } } // Iterate over every field definition if (originalType.getMembers() != null) { for (final Iterator originalMemberstIter = originalType.getMembers().iterator(); originalMemberstIter.hasNext();) { final BodyDeclaration originalMember = originalMemberstIter.next(); if (!(originalMember instanceof FieldDeclaration)) { // this is not a field definition continue; } field = (FieldDeclaration) originalMember; // Check every variable declared in definition for (final Iterator variablesIter = field.getVariables().iterator(); variablesIter .hasNext();) { final VariableDeclarator originalVariable = variablesIter.next(); fieldName = originalVariable.getId().getName(); // look for field name in cid final FieldEntry entry = cidFields.get(fieldName); if (entry == null) { // Not found: remove field from original compilation // unit variablesIter.remove(); continue; } // Check modifiers, type and annotations if (equalFieldTypeModifiersAnnotations(field, entry.fieldDeclaration)) { // Variable declaration is equals: // remove from cid map as already exists cidFields.remove(fieldName); } else { // as there are more variable definition remove it // from original. At the end, process will create it // again // using new modifiers and type variablesIter.remove(); // Modifiers changed if (field.getVariables().size() == 1) { // if no more variables update all field definition field.setModifiers(entry.fieldDeclaration.getModifiers()); field.setType(entry.fieldDeclaration.getType()); if (field.getAnnotations() == null && entry.fieldDeclaration.getAnnotations() != null) { field.setAnnotations(new ArrayList()); } updateAnnotations(field.getAnnotations(), entry.fieldDeclaration.getAnnotations()); // remove processed field of cid cidFields.remove(fieldName); continue; } } } if (field.getVariables().isEmpty()) { originalMemberstIter.remove(); } } } if (cidFields.isEmpty()) { // Done it return; } if (originalType.getMembers() == null) { originalType.setMembers(new ArrayList()); } // Add new fields List variables; for (final FieldEntry entry : cidFields.values()) { variables = new ArrayList(1); variables.add(entry.variableDeclarator); field = new FieldDeclaration(entry.fieldDeclaration.getModifiers(), entry.fieldDeclaration.getType(), variables); field.setAnnotations(entry.fieldDeclaration.getAnnotations()); field.setBeginComments(entry.fieldDeclaration.getBeginComments()); field.setInternalComments(entry.fieldDeclaration.getInternalComments()); field.setEndComments(entry.fieldDeclaration.getEndComments()); originalType.getMembers().add(field); } } /** * Compares Type, modifies and annotation of two {@link FieldDeclaration} * * @param fieldDeclaration * @param fieldDeclaration2 * @return */ public static boolean equalFieldTypeModifiersAnnotations(final FieldDeclaration fieldDeclaration, final FieldDeclaration fieldDeclaration2) { return fieldDeclaration.getModifiers() == fieldDeclaration2.getModifiers() && equals(fieldDeclaration.getType(), fieldDeclaration2.getType()) && equalsAnnotations(fieldDeclaration.getAnnotations(), fieldDeclaration2.getAnnotations()); } /** * Compares two {@link AnnotationExpr} list * * @param annotations * @param annotations2 * @return */ private static boolean equalsAnnotations(final List annotations, final List annotations2) { if (annotations == annotations2) { return true; } else if (annotations == null || annotations2 == null) { return false; } if (annotations.size() != annotations2.size()) { return false; } boolean found; for (final AnnotationExpr annotation1 : annotations) { found = false; for (final AnnotationExpr annotation2 : annotations2) { if (equals(annotation1, annotation2)) { found = true; break; } } if (!found) { return false; } } return true; } /** * Compares two annotation expression * * @param annotation1 * @param annotation2 * @return */ public static boolean equals(final AnnotationExpr annotation1, final AnnotationExpr annotation2) { if (annotation1 == annotation2) { return true; } if (annotation1 == null || annotation2 == null) { return false; } if (!annotation1.getName().getName().equals(annotation2.getName().getName())) { return false; } if (!annotation1.getName().equals(annotation2.getName())) { return false; } if (!annotation1.getClass().equals(annotation2.getClass())) { return false; } if (annotation1 instanceof SingleMemberAnnotationExpr) { // Compare expression String expression1 = ((SingleMemberAnnotationExpr) annotation1).getMemberValue().toString(); String expression2 = ((SingleMemberAnnotationExpr) annotation2).getMemberValue().toString(); return expression1.equals(expression2); } else if (annotation1 instanceof NormalAnnotationExpr) { // Compare pairs List pairs1 = ((NormalAnnotationExpr) annotation1).getPairs(); List pairs2 = ((NormalAnnotationExpr) annotation2).getPairs(); return equals(pairs1, pairs2); } else if (annotation1 instanceof MarkerAnnotationExpr) { // just compare name (and already done it) return true; } else { // No other way to check are equals but toString output return annotation1.toString().equals(annotation2.toString()); } } /** * Compares to {@link MemberValuePair} list * * @param pairs1 * @param pairs2 * @return */ private static boolean equals(List pairs1, List pairs2) { if (ObjectUtils.equals(pairs1, pairs2)) { return true; } if (pairs1 == null || pairs2 == null) { return false; } if (pairs1.size() != pairs2.size()) { return false; } // Clone pair2 to better performance List pairs2Cloned = new ArrayList(pairs2); MemberValuePair pair2; Iterator pairIterator; boolean found; // For every pair in 1 for (MemberValuePair pair1 : pairs1) { found = false; pairIterator = pairs2Cloned.iterator(); // Iterate over remaining pair2 elements while (pairIterator.hasNext()) { pair2 = pairIterator.next(); if (pair1.getName().equals(pair2.getName())) { // Found name found = true; // Remove from remaining pair2 elements pairIterator.remove(); // compare value if (ObjectUtils.equals(pair1.getValue(), pair2.getValue())) { // Equals: check for pair1 finished break; } else { String value1 = ObjectUtils.defaultIfNull(pair1.getValue(), "").toString(); String value2 = ObjectUtils.defaultIfNull(pair2.getValue(), "").toString(); if (value1.equals(value2)) { // Equals: check for pair1 finished break; } else { // Not equals: return false return false; } } } } if (!found) { // Pair1 not found: return false return false; } } return true; } /** * Update {@code annotations} with {@code } * * @param annotations * @param annotations2 */ public static void updateAnnotations(final List annotations, final List annotations2) { if (!equalsAnnotations(annotations, annotations2)) { // XXX japa version (1.0.7) has no way to manage // AnnotationExpr annotations.clear(); annotations.addAll(annotations2); } } /** * Update {@code extends} with {@code } * * @param originalType * @param newType */ private static void updateExtends(final ClassOrInterfaceDeclaration originalType, final ClassOrInterfaceDeclaration newType) { // Getting original an new extends List originalExtends = originalType.getExtends() == null ? new ArrayList() : originalType .getExtends(); List newExtends = newType.getExtends() == null ? new ArrayList() : newType.getExtends(); // Check if has the same extends if (!originalExtends.equals(newExtends)) { // If not, merge extends and add it to original List finalExtends = originalExtends; for (ClassOrInterfaceType x : newExtends) { if (!finalExtends.contains(x)) { finalExtends.add(x); } } originalType.setExtends(finalExtends); } } /** * Update {@code implements} with {@code } * * @param originalType * @param newType */ private static void updateImplements(final ClassOrInterfaceDeclaration originalType, final ClassOrInterfaceDeclaration newType) { // Getting original an new implements List originalImplements = originalType.getImplements() == null ? new ArrayList() : originalType .getImplements(); List newImplements = newType.getImplements() == null ? new ArrayList() : newType .getImplements(); // Check if has the same implements if (!originalImplements.equals(newImplements)) { // If not, merge implements and add it to original List finalImplements = originalImplements; for (ClassOrInterfaceType x : newImplements) { if (!finalImplements.contains(x)) { finalImplements.add(x); } } originalType.setImplements(finalImplements); } } } projects/batfish-common-protocol/src/main/java/org/batfish/specifier/parboiled/TcpAppAstNode.java100-1000 package org.batfish.specifier.parboiled; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Objects; import javax.annotation.ParametersAreNonnullByDefault; import org.batfish.datamodel.SubRange; /** AST node for tcp application definition */ @ParametersAreNonnullByDefault final class TcpAppAstNode extends PortAppAstNode { public TcpAppAstNode() { this(ImmutableList.of()); } public TcpAppAstNode(List ports) { super(ports); } @Override public T accept(AstNodeVisitor visitor) { return visitor.visitTcpAppAstNode(this); } @Override public T accept(AppAstNodeVisitor visitor) { return visitor.visitTcpAppAstNode(this); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof TcpAppAstNode)) { return false; } TcpAppAstNode that = (TcpAppAstNode) o; return Objects.equals(_ports, that._ports); } @Override public int hashCode() { return Objects.hashCode(_ports); } } /* * Copyright 2000-2021 JetBrains s.r.o. * * 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 jetbrains.buildServer.sharedResources.server.report; import com.google.gson.*; import com.google.gson.internal.Streams; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.Collection; import java.util.List; import jetbrains.buildServer.sharedResources.model.Lock; import jetbrains.buildServer.sharedResources.model.LockType; import jetbrains.buildServer.sharedResources.model.resources.*; import org.jetbrains.annotations.NotNull; /** * Created with IntelliJ IDEA. * * @author () */ public class UsedResourcesSerializer { public List read(@NotNull final Reader reader) { final GsonBuilder builder = new GsonBuilder(); builder.setFieldNamingStrategy(STRATEGY); builder.registerTypeAdapter(Resource.class, (InstanceCreator)type -> ResourceFactory.newInfiniteResource("", "", "", true)); builder.registerTypeAdapter(Lock.class, (InstanceCreator)type -> new Lock("", LockType.READ, "")); builder.registerTypeAdapterFactory(MY_TYPE_ADAPTER_FACTORY); return builder.setPrettyPrinting().create().fromJson(reader, new TypeToken>(){}.getType()); } public void write(Collection usedResources, Writer writer) { final GsonBuilder builder = new GsonBuilder(); builder.setFieldNamingStrategy(STRATEGY); builder.setPrettyPrinting(); builder.create().toJson(usedResources, writer); } private static final FieldNamingStrategy STRATEGY = field -> { String name = field.getName(); if (name.startsWith("my")) { char c[] = name.substring(2).toCharArray(); c[0] = Character.toLowerCase(c[0]); return new String(c); } else { return name; } }; private final TypeAdapterFactory MY_TYPE_ADAPTER_FACTORY = new CustomTypeAdapterFactory(); private static final class CustomTypeAdapterFactory implements TypeAdapterFactory { @Override public TypeAdapter create(final Gson gson, final TypeToken type) { if (type.getRawType() != Resource.class) { return null; } final TypeAdapter delegate = gson.getDelegateAdapter(this, type); return new TypeAdapter() { @Override public void write(final JsonWriter jsonWriter, final T t) throws IOException { delegate.write(jsonWriter, t); } @SuppressWarnings("unchecked") @Override public T read(final JsonReader jsonReader) throws JsonParseException { JsonElement tree = Streams.parse(jsonReader); JsonObject object = tree.getAsJsonObject(); if (object.has("type")) { ResourceType resourceType = ResourceType.fromString(object.get("type").getAsString()); if (resourceType == ResourceType.QUOTED) { return (T)gson.getDelegateAdapter(CustomTypeAdapterFactory.this, TypeToken.get(QuotedResource.class)).fromJsonTree(tree); } else if (resourceType == ResourceType.CUSTOM) { return (T)gson.getDelegateAdapter(CustomTypeAdapterFactory.this, TypeToken.get(CustomResource.class)).fromJsonTree(tree); } } throw new JsonParseException("Cannot deserialize " + type + ". It is not a valid Resource JSON."); } }; } } } @Override public > F get(MatchField field) throws UnsupportedOperationException { // FIXME yotam - please replace with real implementation return null; } @Override public > Masked getMasked(MatchField field) throws UnsupportedOperationException { // FIXME yotam - please replace with real implementation return null; } @Override public boolean supports(MatchField field) { // FIXME yotam - please replace with real implementation return false; } @Override public boolean supportsMasked(MatchField field) { // FIXME yotam - please replace with real implementation return false; } @Override public boolean isExact(MatchField field) { // FIXME yotam - please replace with real implementation return false; } @Override public boolean isFullyWildcarded(MatchField field) { // FIXME yotam - please replace with real implementation return false; } @Override public boolean isPartiallyMasked(MatchField field) { // FIXME yotam - please replace with real implementation return false; } @Override public Iterable> getMatchFields() { throw new UnsupportedOperationException(); } 0 package com.senior.cyber.frmk.repository; import com.senior.cyber.frmk.jdbc.query.*; import org.apache.commons.lang3.StringUtils; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import javax.sql.DataSource; import java.sql.SQLException; import java.util.*; public class Jdbc { public static final String SUMMARY_TABLE = "sum"; public static final String HISTORY_TABLE = "his"; public static final String BEFORE = "bef"; public static final String AFTER = "aft"; // public static final String SYSTEM_TRANSACTION_ID = "sys_tid"; public static final String INSTALL = "sys_install"; public static final String TASK = "sys_task"; private static final int LEVEL_NONE = 0; private static final int LEVEL_DRAFT = 1; private static final int LEVEL_REVIEW = 2; private static final String DRAFT_TABLE = "dra"; private static final String REVIEW_TABLE = "rev"; private final DataSource dataSource; private final JdbcTemplate jdbcTemplate; private final NamedParameterJdbcTemplate named; private final String userTable; private final String userPk; public Jdbc(DataSource dataSource, String userTable, String userPk) { this.dataSource = dataSource; this.jdbcTemplate = new JdbcTemplate(dataSource); this.named = new NamedParameterJdbcTemplate(this.dataSource); this.userTable = userTable; this.userPk = userPk; } public String insert(String table, Map values) throws SQLException { return insert(table, values, new HashMap<>()); } public String insert(String table, Map values, Map systems) throws SQLException { SelectQuery selectQuery = new MySqlSelectQuery(INSTALL); selectQuery.addWhere("`table` = :table", table); Install install = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), Install.class); if (install == null) { throw new SQLException(table + " is not configured"); } String pk = install.getPk(); Object id = values.remove(pk); String historyTable = table + "_" + HISTORY_TABLE; String draftTable = table + "_" + DRAFT_TABLE; String reviewTable = table + "_" + REVIEW_TABLE; String reviewPk = reviewTable + "_id"; String draftPk = draftTable + "_id"; String historyPk = historyTable + "_id"; if (install.getLevel() == LEVEL_NONE) { if (install.isHistory()) { if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } // if (systems.get(SYSTEM_TRANSACTION_ID) == null || "".equals(systems.get(SYSTEM_TRANSACTION_ID))) { // throw new SQLException(SYSTEM_TRANSACTION_ID + " is required"); // } InsertQuery insertQuery = new InsertQuery(historyTable); for (Map.Entry attr : values.entrySet()) { insertQuery.addValueInternal(AFTER + "_" + attr.getKey() + " = :" + AFTER + "_" + attr.getKey(), attr.getValue()); } insertQuery.addValueInternal(this.userPk + " = :" + this.userPk, systems.get(this.userPk)); insertQuery.addValue("dt_when = :dt_when", new Date()); insertQuery.addValue("op = :op", "INSERT"); insertQuery.addValueInternal(pk + " = :" + pk, id); insertQuery.addValue("level = :level", install.getLevel()); insertQuery.addValue(historyPk + " = uuid()"); // insertQuery.addValue(SYSTEM_TRANSACTION_ID + " = :" + SYSTEM_TRANSACTION_ID, systems.get(SYSTEM_TRANSACTION_ID)); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); } InsertQuery insertQuery = new InsertQuery(table); for (Map.Entry attr : values.entrySet()) { insertQuery.addValueInternal(attr.getKey() + " = :" + attr.getKey(), attr.getValue()); } insertQuery.addValueInternal(pk + " = :" + pk, id); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); return null; } else if (install.getLevel() == LEVEL_DRAFT) { if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } // if (systems.get(SYSTEM_TRANSACTION_ID) == null || "".equals(systems.get(SYSTEM_TRANSACTION_ID))) { // throw new SQLException(SYSTEM_TRANSACTION_ID + " is required"); // } String taskId = this.jdbcTemplate.queryForObject("SELECT uuid() FROM DUAL", String.class); InsertQuery insertQuery = new InsertQuery(Jdbc.TASK); insertQuery.addValue("task_id = :task_id", taskId); insertQuery.addValue("`table` = :table", table); insertQuery.addValue("action = :action", "REVIEW"); insertQuery.addValue("op = :op", "INSERT"); insertQuery.addValue("draft_yes = :draft_yes", 0); insertQuery.addValue("draft_no = :draft_no", 0); insertQuery.addValue("review_yes = :review_yes", 0); insertQuery.addValue("review_no = :review_no", 0); insertQuery.addValue("dt_when = :dt_when", new Date()); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); insertQuery = new InsertQuery(draftTable); for (Map.Entry attr : values.entrySet()) { insertQuery.addValueInternal(AFTER + "_" + attr.getKey() + " = :" + AFTER + "_" + attr.getKey(), attr.getValue()); } insertQuery.addValueInternal(this.userPk + " = :" + this.userPk, systems.get(this.userPk)); insertQuery.addValue("dt_when = :dt_when", new Date()); insertQuery.addValue("yes = :yes", install.getDraftYes()); insertQuery.addValue("no = :no", install.getDraftNo()); insertQuery.addValue("op = :op", "INSERT"); insertQuery.addValueInternal(pk + " = :" + pk, id); insertQuery.addValue(draftPk + " = :" + draftPk, taskId); // insertQuery.addValue(SYSTEM_TRANSACTION_ID + " = :" + SYSTEM_TRANSACTION_ID, systems.get(SYSTEM_TRANSACTION_ID)); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); return taskId; } else if (install.getLevel() == LEVEL_REVIEW) { if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } // if (systems.get(SYSTEM_TRANSACTION_ID) == null || "".equals(systems.get(SYSTEM_TRANSACTION_ID))) { // throw new SQLException(SYSTEM_TRANSACTION_ID + " is required"); // } String taskId = this.jdbcTemplate.queryForObject("SELECT uuid() FROM DUAL", String.class); InsertQuery insertQuery = new InsertQuery(Jdbc.TASK); insertQuery.addValue("task_id = :task_id", taskId); insertQuery.addValue("`table` = :table", table); insertQuery.addValue("action = :action", "APPROVE"); insertQuery.addValue("op = :op", "INSERT"); insertQuery.addValue("draft_yes = :draft_yes", 0); insertQuery.addValue("draft_no = :draft_no", 0); insertQuery.addValue("review_yes = :review_yes", 0); insertQuery.addValue("review_no = :review_no", 0); insertQuery.addValue("dt_when = :dt_when", new Date()); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); insertQuery = new InsertQuery(reviewTable); for (Map.Entry attr : values.entrySet()) { insertQuery.addValueInternal(AFTER + "_" + attr.getKey() + " = :" + AFTER + "_" + attr.getKey(), attr.getValue()); } insertQuery.addValueInternal(this.userPk + " = :" + this.userPk, systems.get(this.userPk)); insertQuery.addValue("dt_when = :dt_when", new Date()); insertQuery.addValue("yes = :yes", install.getReviewYes()); insertQuery.addValue("no = :no", install.getReviewNo()); insertQuery.addValue("op = :op", "INSERT"); insertQuery.addValueInternal(pk + " = :" + pk, id); insertQuery.addValue(reviewPk + " = :" + reviewPk, taskId); // insertQuery.addValue(SYSTEM_TRANSACTION_ID + " = :" + SYSTEM_TRANSACTION_ID, systems.get(SYSTEM_TRANSACTION_ID)); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); return taskId; } else { return null; } } public String delete(String table, Map wheres) throws SQLException { return delete(table, wheres, new HashMap<>()); } public String delete(String table, Map wheres, Map systems) throws SQLException { SelectQuery selectQuery = new MySqlSelectQuery(INSTALL); selectQuery.addWhere("`table` = :table", table); Install install = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), Install.class); if (install == null) { throw new SQLException(table + " is not configured"); } String historyTable = table + "_" + HISTORY_TABLE; String historyPk = historyTable + "_id"; String pk = install.getPk(); String draftTable = table + "_" + DRAFT_TABLE; String reviewTable = table + "_" + REVIEW_TABLE; String reviewPk = reviewTable + "_id"; String draftPk = draftTable + "_id"; if (install.getLevel() == LEVEL_NONE) { if (install.isHistory()) { if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } // if (systems.get(SYSTEM_TRANSACTION_ID) == null || "".equals(systems.get(SYSTEM_TRANSACTION_ID))) { // throw new SQLException(SYSTEM_TRANSACTION_ID + " is required"); // } List where = new ArrayList<>(); Map param = new HashMap<>(); for (Map.Entry w : wheres.entrySet()) { where.add(w.getKey() + " = :" + w.getKey()); param.put(w.getKey(), w.getValue()); } List fromFields = Repository.lookupField(this.jdbcTemplate, table); List intoFields = new ArrayList<>(); for (String fromField : fromFields) { intoFields.add(BEFORE + "_" + fromField); } intoFields.add(table + "_id"); fromFields.add(table + "_id"); intoFields.add(historyPk); fromFields.add("uuid()"); intoFields.add("op"); fromFields.add("'DELETE'"); intoFields.add("dt_when"); fromFields.add(":dt_when"); param.put("dt_when", new Date()); intoFields.add(this.userPk); fromFields.add(":" + this.userPk); param.put(this.userPk, systems.get(this.userPk)); intoFields.add("level"); fromFields.add(":level"); param.put("level", install.getLevel()); // intoFields.add(Engine.SYSTEM_TRANSACTION_ID); // fromFields.add(":" + Engine.SYSTEM_TRANSACTION_ID); // param.put(Engine.SYSTEM_TRANSACTION_ID, systems.get(Engine.SYSTEM_TRANSACTION_ID)); String query = "INSERT INTO " + historyTable + "(" + StringUtils.join(intoFields, ", ") + ") SELECT " + StringUtils.join(fromFields, ", ") + " FROM " + table + " WHERE " + StringUtils.join(where, " AND "); this.named.update(query, param); } DeleteQuery deleteQuery = new DeleteQuery(table); for (Map.Entry attr : wheres.entrySet()) { deleteQuery.addWhereInternal(attr.getKey() + " = :" + attr.getKey(), attr.getValue()); } this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); return null; } else if (install.getLevel() == LEVEL_DRAFT) { if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } // if (systems.get(SYSTEM_TRANSACTION_ID) == null || "".equals(systems.get(SYSTEM_TRANSACTION_ID))) { // throw new SQLException(SYSTEM_TRANSACTION_ID + " is required"); // } String taskId = this.jdbcTemplate.queryForObject("SELECT uuid() FROM DUAL", String.class); InsertQuery insertQuery = new InsertQuery(Jdbc.TASK); insertQuery.addValue("task_id = :task_id", taskId); insertQuery.addValue("`table` = :table", table); insertQuery.addValue("action = :action", "REVIEW"); insertQuery.addValue("op = :op", "DELETE"); insertQuery.addValue("draft_yes = :draft_yes", 0); insertQuery.addValue("draft_no = :draft_no", 0); insertQuery.addValue("review_yes = :review_yes", 0); insertQuery.addValue("review_no = :review_no", 0); insertQuery.addValue("dt_when = :dt_when", new Date()); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); List where = new ArrayList<>(); Map param = new HashMap<>(); for (Map.Entry w : wheres.entrySet()) { where.add(w.getKey() + " = :" + w.getKey()); param.put(w.getKey(), w.getValue()); } List fromFields = Repository.lookupField(this.jdbcTemplate, table); List intoFields = new ArrayList<>(); for (String fromField : fromFields) { intoFields.add(BEFORE + "_" + fromField); } intoFields.add("yes"); fromFields.add(":yes"); param.put("yes", install.getDraftYes()); intoFields.add("no"); fromFields.add(":no"); param.put("no", install.getDraftNo()); intoFields.add("op"); fromFields.add(":op"); param.put("op", "DELETE"); intoFields.add("dt_when"); fromFields.add(":dt_when"); param.put("dt_when", new Date()); // intoFields.add(SYSTEM_TRANSACTION_ID); // fromFields.add(":" + SYSTEM_TRANSACTION_ID); // param.put(SYSTEM_TRANSACTION_ID, systems.get(SYSTEM_TRANSACTION_ID)); intoFields.add(this.userPk); fromFields.add(":" + this.userPk); param.put(this.userPk, systems.get(this.userPk)); intoFields.add(draftPk); fromFields.add(":" + draftPk); param.put(draftPk, taskId); intoFields.add(pk); fromFields.add(pk); String query = "INSERT INTO " + draftTable + "(" + StringUtils.join(intoFields, ", ") + ") SELECT " + StringUtils.join(fromFields, ", ") + " FROM " + table + " WHERE " + StringUtils.join(where, " AND "); this.named.update(query, param); return taskId; } else if (install.getLevel() == LEVEL_REVIEW) { if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } // if (systems.get(SYSTEM_TRANSACTION_ID) == null || "".equals(systems.get(SYSTEM_TRANSACTION_ID))) { // throw new SQLException(SYSTEM_TRANSACTION_ID + " is required"); // } String taskId = this.jdbcTemplate.queryForObject("SELECT uuid() FROM DUAL", String.class); InsertQuery insertQuery = new InsertQuery(Jdbc.TASK); insertQuery.addValue("task_id = :task_id", taskId); insertQuery.addValue("`table` = :table", table); insertQuery.addValue("action = :action", "APPROVE"); insertQuery.addValue("op = :op", "DELETE"); insertQuery.addValue("draft_yes = :draft_yes", 0); insertQuery.addValue("draft_no = :draft_no", 0); insertQuery.addValue("review_yes = :review_yes", 0); insertQuery.addValue("review_no = :review_no", 0); insertQuery.addValue("dt_when = :dt_when", new Date()); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); List where = new ArrayList<>(); Map param = new HashMap<>(); for (Map.Entry w : wheres.entrySet()) { where.add(w.getKey() + " = :" + w.getKey()); param.put(w.getKey(), w.getValue()); } List fromFields = Repository.lookupField(this.jdbcTemplate, table); List intoFields = new ArrayList<>(); for (String fromField : fromFields) { intoFields.add(BEFORE + "_" + fromField); } intoFields.add("yes"); fromFields.add(":yes"); param.put("yes", install.getDraftYes()); intoFields.add("no"); fromFields.add(":no"); param.put("no", install.getDraftNo()); intoFields.add("op"); fromFields.add(":op"); param.put("op", "DELETE"); intoFields.add("dt_when"); fromFields.add(":dt_when"); param.put("dt_when", new Date()); // intoFields.add(SYSTEM_TRANSACTION_ID); // fromFields.add(":" + SYSTEM_TRANSACTION_ID); // param.put(SYSTEM_TRANSACTION_ID, systems.get(SYSTEM_TRANSACTION_ID)); intoFields.add(this.userPk); fromFields.add(":" + this.userPk); param.put(this.userPk, systems.get(this.userPk)); intoFields.add(reviewPk); fromFields.add(":" + reviewPk); param.put(reviewPk, taskId); intoFields.add(pk); fromFields.add(pk); String query = "INSERT INTO " + reviewTable + "(" + StringUtils.join(intoFields, ", ") + ") SELECT " + StringUtils.join(fromFields, ", ") + " FROM " + table + " WHERE " + StringUtils.join(where, " AND "); this.named.update(query, param); return taskId; } else { return null; } } public String update(String table, Map values, Map wheres) throws SQLException { return update(table, values, wheres, new HashMap<>()); } public String update(String table, Map values, Map wheres, Map systems) throws SQLException { SelectQuery selectQuery = new MySqlSelectQuery(INSTALL); selectQuery.addWhere("`table` = :table", table); Install install = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), Install.class); if (install == null) { throw new SQLException(table + " is not configured"); } String pk = install.getPk(); if (values.containsKey(pk) || values.get(pk) != null) { throw new SQLException(pk + " is not allow to update"); } String historyTable = table + "_" + HISTORY_TABLE; String historyPk = historyTable + "_id"; String draftTable = table + "_" + DRAFT_TABLE; String reviewTable = table + "_" + REVIEW_TABLE; String reviewPk = reviewTable + "_id"; String draftPk = draftTable + "_id"; if (install.getLevel() == LEVEL_NONE) { if (install.isHistory()) { if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } // if (systems.get(SYSTEM_TRANSACTION_ID) == null || "".equals(systems.get(SYSTEM_TRANSACTION_ID))) { // throw new SQLException(SYSTEM_TRANSACTION_ID + " is required"); // } List where = new ArrayList<>(); Map param = new HashMap<>(); for (Map.Entry w : wheres.entrySet()) { where.add(w.getKey() + " = :" + w.getKey()); param.put(w.getKey(), w.getValue()); } List fromFields = Repository.lookupField(this.jdbcTemplate, table); List intoFields = new ArrayList<>(); for (String fromField : fromFields) { intoFields.add(BEFORE + "_" + fromField); } for (Map.Entry attr : values.entrySet()) { intoFields.add(AFTER + "_" + attr.getKey()); fromFields.add(":" + attr.getKey()); param.put(attr.getKey(), attr.getValue()); } for (String f : Repository.lookupField(this.jdbcTemplate, table)) { if (!intoFields.contains(AFTER + "_" + f)) { intoFields.add(AFTER + "_" + f); fromFields.add(f); } } intoFields.add(table + "_id"); fromFields.add(table + "_id"); intoFields.add(historyPk); fromFields.add("uuid()"); intoFields.add("op"); fromFields.add("'UPDATE'"); intoFields.add("dt_when"); fromFields.add(":dt_when"); param.put("dt_when", new Date()); intoFields.add("level"); fromFields.add(":level"); param.put("level", install.getLevel()); intoFields.add(this.userPk); fromFields.add(":" + this.userPk); param.put(this.userPk, systems.get(this.userPk)); // intoFields.add(Engine.SYSTEM_TRANSACTION_ID); // fromFields.add(":" + Engine.SYSTEM_TRANSACTION_ID); // param.put(Engine.SYSTEM_TRANSACTION_ID, systems.get(Engine.SYSTEM_TRANSACTION_ID)); String query = "INSERT INTO " + historyTable + "(" + StringUtils.join(intoFields, ", ") + ") SELECT " + StringUtils.join(fromFields, ", ") + " FROM " + table + " WHERE " + StringUtils.join(where, " AND "); this.named.update(query, param); } UpdateQuery updateQuery = new UpdateQuery(table); for (Map.Entry attr : values.entrySet()) { updateQuery.addValueInternal(attr.getKey() + " = :" + attr.getKey(), attr.getValue()); } for (Map.Entry attr : wheres.entrySet()) { updateQuery.addWhereInternal(attr.getKey() + " = :" + attr.getKey(), attr.getValue()); } this.named.update(updateQuery.toSQL(), updateQuery.toParam()); return null; } else if (install.getLevel() == LEVEL_DRAFT) { if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } // if (systems.get(SYSTEM_TRANSACTION_ID) == null || "".equals(systems.get(SYSTEM_TRANSACTION_ID))) { // throw new SQLException(SYSTEM_TRANSACTION_ID + " is required"); // } String taskId = this.jdbcTemplate.queryForObject("SELECT uuid() FROM DUAL", String.class); InsertQuery insertQuery = new InsertQuery(Jdbc.TASK); insertQuery.addValue("task_id = :task_id", taskId); insertQuery.addValue("`table` = :table", table); insertQuery.addValue("action = :action", "REVIEW"); insertQuery.addValue("op = :op", "UPDATE"); insertQuery.addValue("draft_yes = :draft_yes", 0); insertQuery.addValue("draft_no = :draft_no", 0); insertQuery.addValue("review_yes = :review_yes", 0); insertQuery.addValue("review_no = :review_no", 0); insertQuery.addValue("dt_when = :dt_when", new Date()); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); List where = new ArrayList<>(); Map param = new HashMap<>(); for (Map.Entry w : wheres.entrySet()) { where.add(w.getKey() + " = :" + w.getKey()); param.put(w.getKey(), w.getValue()); } List fromFields = Repository.lookupField(this.jdbcTemplate, table); List intoFields = new ArrayList<>(); for (String fromField : fromFields) { intoFields.add(BEFORE + "_" + fromField); } for (Map.Entry attr : values.entrySet()) { intoFields.add(AFTER + "_" + attr.getKey()); fromFields.add(":" + attr.getKey()); param.put(attr.getKey(), attr.getValue()); } for (String f : Repository.lookupField(this.jdbcTemplate, table)) { if (!intoFields.contains(AFTER + "_" + f)) { intoFields.add(AFTER + "_" + f); fromFields.add(f); } } intoFields.add("yes"); fromFields.add(":yes"); param.put("yes", install.getDraftYes()); intoFields.add("no"); fromFields.add(":no"); param.put("no", install.getDraftNo()); intoFields.add("op"); fromFields.add(":op"); param.put("op", "UPDATE"); intoFields.add("dt_when"); fromFields.add(":dt_when"); param.put("dt_when", new Date()); // intoFields.add(SYSTEM_TRANSACTION_ID); // fromFields.add(":" + SYSTEM_TRANSACTION_ID); // param.put(SYSTEM_TRANSACTION_ID, systems.get(SYSTEM_TRANSACTION_ID)); intoFields.add(this.userPk); fromFields.add(":" + this.userPk); param.put(this.userPk, systems.get(this.userPk)); intoFields.add(draftPk); fromFields.add(":" + draftPk); param.put(draftPk, taskId); intoFields.add(pk); fromFields.add(pk); String query = "INSERT INTO " + draftTable + "(" + StringUtils.join(intoFields, ", ") + ") SELECT " + StringUtils.join(fromFields, ", ") + " FROM " + table + " WHERE " + StringUtils.join(where, " AND "); this.named.update(query, param); return taskId; } else if (install.getLevel() == LEVEL_REVIEW) { if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } // if (systems.get(SYSTEM_TRANSACTION_ID) == null || "".equals(systems.get(SYSTEM_TRANSACTION_ID))) { // throw new SQLException(SYSTEM_TRANSACTION_ID + " is required"); // } String taskId = this.jdbcTemplate.queryForObject("SELECT uuid() FROM DUAL", String.class); InsertQuery insertQuery = new InsertQuery(Jdbc.TASK); insertQuery.addValue("task_id = :task_id", taskId); insertQuery.addValue("`table` = :table", table); insertQuery.addValue("action = :action", "APPROVE"); insertQuery.addValue("op = :op", "UPDATE"); insertQuery.addValue("draft_yes = :draft_yes", 0); insertQuery.addValue("draft_no = :draft_no", 0); insertQuery.addValue("review_yes = :review_yes", 0); insertQuery.addValue("review_no = :review_no", 0); insertQuery.addValue("dt_when = :dt_when", new Date()); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); List where = new ArrayList<>(); Map param = new HashMap<>(); for (Map.Entry w : wheres.entrySet()) { where.add(w.getKey() + " = :" + w.getKey()); param.put(w.getKey(), w.getValue()); } List fromFields = Repository.lookupField(this.jdbcTemplate, table); List intoFields = new ArrayList<>(); for (String fromField : fromFields) { intoFields.add(BEFORE + "_" + fromField); } for (Map.Entry attr : values.entrySet()) { intoFields.add(AFTER + "_" + attr.getKey()); fromFields.add(":" + attr.getKey()); param.put(attr.getKey(), attr.getValue()); } for (String f : Repository.lookupField(this.jdbcTemplate, table)) { if (!intoFields.contains(AFTER + "_" + f)) { intoFields.add(AFTER + "_" + f); fromFields.add(f); } } intoFields.add("yes"); fromFields.add(":yes"); param.put("yes", install.getDraftYes()); intoFields.add("no"); fromFields.add(":no"); param.put("no", install.getDraftNo()); intoFields.add("op"); fromFields.add(":op"); param.put("op", "UPDATE"); intoFields.add("dt_when"); fromFields.add(":dt_when"); param.put("dt_when", new Date()); // intoFields.add(SYSTEM_TRANSACTION_ID); // fromFields.add(":" + SYSTEM_TRANSACTION_ID); // param.put(SYSTEM_TRANSACTION_ID, systems.get(SYSTEM_TRANSACTION_ID)); intoFields.add(this.userPk); fromFields.add(":" + this.userPk); param.put(this.userPk, systems.get(this.userPk)); intoFields.add(reviewPk); fromFields.add(":" + reviewPk); param.put(reviewPk, taskId); intoFields.add(pk); fromFields.add(pk); String query = "INSERT INTO " + reviewTable + "(" + StringUtils.join(intoFields, ", ") + ") SELECT " + StringUtils.join(fromFields, ", ") + " FROM " + table + " WHERE " + StringUtils.join(where, " AND "); this.named.update(query, param); return taskId; } else { return null; } } public void draftReject(String taskId, String reason, Map systems) throws SQLException { SelectQuery selectQuery = new MySqlSelectQuery(TASK); selectQuery.addWhere("task_id = :task_id", taskId); Task task = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), Task.class); if (task == null) { throw new SQLException("task " + taskId + " is not found"); } selectQuery = new MySqlSelectQuery(INSTALL); selectQuery.addWhere("`table` = :table", task.getTable()); Install install = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), Install.class); if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } String table = install.getTable(); String draftTable = table + "_" + DRAFT_TABLE; String draftPk = draftTable + "_id"; String draftSummaryTable = draftTable + "_" + SUMMARY_TABLE; String draftSummaryPk = draftSummaryTable + "_id"; selectQuery = new MySqlSelectQuery(draftTable); selectQuery.addWhere(draftPk + " = :" + draftPk, task.getTaskId()); Map record = null; try { record = this.named.queryForMap(selectQuery.toSQL(), selectQuery.toParam()); } catch (EmptyResultDataAccessException e) { } if (record == null) { throw new SQLException("task " + taskId + " is not found"); } int draftNo = (int) record.get("no"); InsertQuery insertQuery = new InsertQuery(draftSummaryTable); insertQuery.addValue(draftSummaryPk + " = uuid()"); insertQuery.addValue(draftPk + " = :" + draftPk, task.getTaskId()); insertQuery.addValueInternal(this.userPk + " = :" + this.userPk, systems.get(this.userPk)); insertQuery.addValue("reason = :reason", reason); insertQuery.addValue("action = :action", "NO"); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); selectQuery = new MySqlSelectQuery(draftSummaryTable); selectQuery.addField("COUNT(*)"); selectQuery.addWhere("action = :action", "NO"); selectQuery.addWhere(draftPk + " = :" + draftPk, task.getTaskId()); Integer runDraftNo = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), int.class); UpdateQuery updateQuery = new UpdateQuery(TASK); updateQuery.addValue("draft_no = :draft_no", runDraftNo); updateQuery.addWhere("task_id = :task_id", taskId); this.named.update(updateQuery.toSQL(), updateQuery.toParam()); if (runDraftNo != null && runDraftNo >= draftNo) { taskClean(draftTable, draftPk, draftSummaryTable, task.getTaskId()); } } private void taskClean(String table, String pk, String summaryTable, String id) { DeleteQuery deleteQuery = new DeleteQuery(table); deleteQuery.addWhere(pk + " = :" + pk, id); this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); deleteQuery = new DeleteQuery(summaryTable); deleteQuery.addWhere(pk + " = :" + pk, id); this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); deleteQuery = new DeleteQuery(TASK); deleteQuery.addWhere("task_id = :task_id", id); this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); } public void draftApprove(String taskId, Map systems) throws SQLException { SelectQuery selectQuery = new MySqlSelectQuery(TASK); selectQuery.addWhere("task_id = :task_id", taskId); Task task = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), Task.class); if (task == null) { throw new SQLException("task " + taskId + " is not found"); } if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } String table = task.getTable(); String draftTable = table + "_" + DRAFT_TABLE; String reviewTable = table + "_" + REVIEW_TABLE; String reviewPk = reviewTable + "_id"; String draftPk = draftTable + "_id"; String draftSummaryTable = draftTable + "_" + SUMMARY_TABLE; String draftSummaryPk = draftSummaryTable + "_id"; selectQuery = new MySqlSelectQuery(draftTable); selectQuery.addWhere(draftPk + " = :" + draftPk, task.getTaskId()); Map record = null; try { record = this.named.queryForMap(selectQuery.toSQL(), selectQuery.toParam()); } catch (EmptyResultDataAccessException e) { } if (record == null) { throw new SQLException("task " + taskId + " is not found"); } int draftYes = (int) record.get("yes"); InsertQuery insertQuery = new InsertQuery(draftSummaryTable); insertQuery.addValue(draftSummaryPk + " = uuid()"); insertQuery.addValue(draftPk + " = :" + draftPk, task.getTaskId()); insertQuery.addValueInternal(this.userPk + " = :" + this.userPk, systems.get(this.userPk)); insertQuery.addValue("action = :action", "YES"); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); selectQuery = new MySqlSelectQuery(draftSummaryTable); selectQuery.addField("COUNT(*)"); selectQuery.addWhere("action = :action", "YES"); selectQuery.addWhere(draftPk + " = :" + draftPk, task.getTaskId()); Integer runDraftYes = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), int.class); UpdateQuery updateQuery = new UpdateQuery(TASK); updateQuery.addValue("draft_yes = :draft_yes", runDraftYes); updateQuery.addWhere("task_id = :task_id", taskId); this.named.update(updateQuery.toSQL(), updateQuery.toParam()); if (runDraftYes != null && runDraftYes >= draftYes) { List where = new ArrayList<>(); Map params = new HashMap<>(); where.add(draftPk + " = :" + draftPk); params.put(draftPk, task.getTaskId()); List fromFields = Repository.lookupField(this.jdbcTemplate, draftTable); List intoFields = new ArrayList<>(fromFields); intoFields.add(reviewPk); fromFields.add(draftPk); String query = "INSERT INTO " + reviewTable + "(" + StringUtils.join(intoFields, ", ") + ") SELECT " + StringUtils.join(fromFields, ", ") + " FROM " + draftTable + " WHERE " + StringUtils.join(where, " AND "); this.named.update(query, params); updateQuery = new UpdateQuery(TASK); updateQuery.addValue("action = :action", "APPROVE"); updateQuery.addWhere("task_id = :task_id", taskId); this.named.update(updateQuery.toSQL(), updateQuery.toParam()); } } public void reviewReject(String taskId, String reason, Map systems) throws SQLException { SelectQuery selectQuery = new MySqlSelectQuery(TASK); selectQuery.addWhere("task_id = :task_id", taskId); Task task = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), Task.class); if (task == null) { throw new SQLException("task " + taskId + " is not found"); } if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } String table = task.getTable(); String draftTable = table + "_" + DRAFT_TABLE; String draftSummaryTable = draftTable + "_" + SUMMARY_TABLE; String draftPk = draftTable + "_id"; String reviewTable = table + "_" + REVIEW_TABLE; String reviewPk = reviewTable + "_id"; String reviewSummaryTable = reviewTable + "_" + SUMMARY_TABLE; String reviewSummaryPk = reviewSummaryTable + "_id"; selectQuery = new MySqlSelectQuery(reviewTable); selectQuery.addWhere(reviewPk + " = :" + reviewPk, task.getTaskId()); Map record = null; try { record = this.named.queryForMap(selectQuery.toSQL(), selectQuery.toParam()); } catch (EmptyResultDataAccessException e) { } if (record == null) { throw new SQLException("task " + taskId + " is not found"); } int reviewNo = (int) record.get("no"); InsertQuery insertQuery = new InsertQuery(reviewSummaryTable); insertQuery.addValue(reviewSummaryPk + " = uuid()"); insertQuery.addValue(reviewPk + " = :" + reviewPk, task.getTaskId()); insertQuery.addValueInternal(this.userPk + " = :" + this.userPk, systems.get(this.userPk)); insertQuery.addValue("reason = :reason", reason); insertQuery.addValue("action = :action", "NO"); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); selectQuery = new MySqlSelectQuery(reviewSummaryTable); selectQuery.addField("COUNT(*)"); selectQuery.addWhere("action = :action", "NO"); selectQuery.addWhere(reviewPk + " = :" + reviewPk, task.getTaskId()); Integer runReviewNo = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), int.class); UpdateQuery updateQuery = new UpdateQuery(TASK); updateQuery.addValue("review_no = :review_no", runReviewNo); updateQuery.addWhere("task_id = :task_id", taskId); this.named.update(updateQuery.toSQL(), updateQuery.toParam()); if (runReviewNo != null && runReviewNo >= reviewNo) { taskClean(reviewTable, reviewPk, reviewSummaryTable, task.getTaskId()); DeleteQuery deleteQuery = new DeleteQuery(draftTable); deleteQuery.addWhere(draftPk + " = :" + draftPk, task.getTaskId()); this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); deleteQuery = new DeleteQuery(draftSummaryTable); deleteQuery.addWhere(draftPk + " = :" + draftPk, task.getTaskId()); this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); } } public void reviewApprove(String taskId, Map systems) throws SQLException { SelectQuery selectQuery = new MySqlSelectQuery(TASK); selectQuery.addWhere("task_id = :task_id", taskId); Task task = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), Task.class); if (task == null) { throw new SQLException("task " + taskId + " is not found"); } selectQuery = new MySqlSelectQuery(INSTALL); selectQuery.addWhere("`table` = :table", task.getTable()); Install install = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), Install.class); if (systems.get(this.userPk) == null || "".equals(systems.get(this.userPk))) { throw new SQLException(this.userPk + " is required"); } String table = task.getTable(); String draftTable = table + "_" + DRAFT_TABLE; String draftSummaryTable = draftTable + "_" + SUMMARY_TABLE; String draftPk = draftTable + "_id"; String historyTable = table + "_" + HISTORY_TABLE; String historySummaryTable = historyTable + "_" + SUMMARY_TABLE; String historySummaryPk = historySummaryTable + "_id"; String historyPk = historyTable + "_id"; String pk = install.getPk(); String reviewTable = table + "_" + REVIEW_TABLE; String reviewPk = reviewTable + "_id"; String reviewSummaryTable = reviewTable + "_" + SUMMARY_TABLE; String reviewSummaryPk = reviewSummaryTable + "_id"; selectQuery = new MySqlSelectQuery(reviewTable); selectQuery.addWhere(reviewPk + " = :" + reviewPk, task.getTaskId()); Map record = null; try { record = this.named.queryForMap(selectQuery.toSQL(), selectQuery.toParam()); } catch (EmptyResultDataAccessException e) { } if (record == null) { throw new SQLException("task " + taskId + " is not found"); } int reviewYes = (int) record.get("yes"); String op = (String) record.get("op"); InsertQuery insertQuery = new InsertQuery(reviewSummaryTable); insertQuery.addValue(reviewSummaryPk + " = uuid()"); insertQuery.addValue(reviewPk + " = :" + reviewPk, task.getTaskId()); insertQuery.addValueInternal(this.userPk + " = :" + this.userPk, systems.get(this.userPk)); insertQuery.addValue("action = :action", "YES"); this.named.update(insertQuery.toSQL(), insertQuery.toParam()); selectQuery = new MySqlSelectQuery(reviewSummaryTable); selectQuery.addField("COUNT(*)"); selectQuery.addWhere("action = :action", "YES"); selectQuery.addWhere(reviewPk + " = :" + reviewPk, task.getTaskId()); Integer runReviewYes = this.named.queryForObject(selectQuery.toSQL(), selectQuery.toParam(), int.class); UpdateQuery updateQuery = new UpdateQuery(TASK); updateQuery.addValue("review_yes = :review_yes", runReviewYes); updateQuery.addWhere("task_id = :task_id", taskId); this.named.update(updateQuery.toSQL(), updateQuery.toParam()); if (runReviewYes != null && runReviewYes >= reviewYes) { if (install.isHistory()) { String historyId = this.jdbcTemplate.queryForObject("SELECT uuid() FROM DUAL", String.class); List where = new ArrayList<>(); Map param = new HashMap<>(); where.add(reviewPk + " = :" + reviewPk); param.put(reviewPk, taskId); List fromFields = Repository.lookupField(this.jdbcTemplate, historyTable); fromFields.remove("level"); List intoFields = new ArrayList<>(fromFields); intoFields.add("level"); fromFields.add(":level"); param.put("level", install.getLevel()); intoFields.add(historyPk); fromFields.add(":" + historyPk); param.put(historyPk, historyId); String query = "INSERT INTO " + historyTable + "(" + StringUtils.join(intoFields, ", ") + ") SELECT " + StringUtils.join(fromFields, ", ") + " FROM " + reviewTable + " WHERE " + StringUtils.join(where, " AND "); this.named.update(query, param); where = new ArrayList<>(); param = new HashMap<>(); where.add(draftPk + " = :" + draftPk); param.put(draftPk, taskId); fromFields = Repository.lookupField(this.jdbcTemplate, draftSummaryTable); fromFields.remove(draftPk); intoFields = new ArrayList<>(fromFields); intoFields.add("level"); fromFields.add(":level"); param.put("level", "REVIEW"); intoFields.add(historySummaryPk); fromFields.add("uuid()"); intoFields.add(historyPk); fromFields.add(":" + historyPk); param.put(historyPk, historyId); query = "INSERT INTO " + historySummaryTable + "(" + StringUtils.join(intoFields, ", ") + ") SELECT " + StringUtils.join(fromFields, ", ") + " FROM " + draftSummaryTable + " WHERE " + StringUtils.join(where, " AND "); this.named.update(query, param); where = new ArrayList<>(); param = new HashMap<>(); where.add(reviewPk + " = :" + reviewPk); param.put(reviewPk, taskId); fromFields = Repository.lookupField(this.jdbcTemplate, reviewSummaryTable); fromFields.remove(reviewPk); intoFields = new ArrayList<>(fromFields); intoFields.add("level"); fromFields.add(":level"); param.put("level", "APPROVE"); intoFields.add(historySummaryPk); fromFields.add("uuid()"); intoFields.add(historyPk); fromFields.add(":" + historyPk); param.put(historyPk, historyId); query = "INSERT INTO " + historySummaryTable + "(" + StringUtils.join(intoFields, ", ") + ") SELECT " + StringUtils.join(fromFields, ", ") + " FROM " + reviewSummaryTable + " WHERE " + StringUtils.join(where, " AND "); this.named.update(query, param); } if ("INSERT".equals(op)) { List where = new ArrayList<>(); Map params = new HashMap<>(); where.add(reviewPk + " = :" + reviewPk); params.put(reviewPk, task.getTaskId()); List intoFields = Repository.lookupField(this.jdbcTemplate, table); List fromFields = new ArrayList<>(); for (String intoField : intoFields) { fromFields.add(AFTER + "_" + intoField); } intoFields.add(pk); fromFields.add(pk); String query = "INSERT INTO " + table + "(" + StringUtils.join(intoFields, ", ") + ") SELECT " + StringUtils.join(fromFields, ", ") + " FROM " + reviewTable + " WHERE " + StringUtils.join(where, " AND "); this.named.update(query, params); } else if ("UPDATE".equals(op)) { List intoFields = Repository.lookupField(this.jdbcTemplate, table); selectQuery = new MySqlSelectQuery(reviewTable); selectQuery.addWhere(reviewPk + " = :" + reviewPk, task.getTaskId()); Map from = this.named.queryForMap(selectQuery.toSQL(), selectQuery.toParam()); updateQuery = new UpdateQuery(table); updateQuery.addWhereInternal(pk + " = :" + pk, record.get(pk)); for (String intoField : intoFields) { updateQuery.addValueInternal(intoField + " = :" + intoField, from.get(AFTER + "_" + intoField)); } this.named.update(updateQuery.toSQL(), updateQuery.toParam()); } else if ("DELETE".equals(op)) { DeleteQuery deleteQuery = new DeleteQuery(table); deleteQuery.addWhereInternal(pk + " = :" + pk, record.get(pk)); this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); } DeleteQuery deleteQuery = new DeleteQuery(draftTable); deleteQuery.addWhere(draftPk + " = :" + draftPk, task.getTaskId()); this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); deleteQuery = new DeleteQuery(draftSummaryTable); deleteQuery.addWhere(draftPk + " = :" + draftPk, task.getTaskId()); this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); deleteQuery = new DeleteQuery(reviewTable); deleteQuery.addWhere(reviewPk + " = :" + reviewPk, task.getTaskId()); this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); deleteQuery = new DeleteQuery(reviewSummaryTable); deleteQuery.addWhere(reviewPk + " = :" + reviewPk, task.getTaskId()); this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); deleteQuery = new DeleteQuery(TASK); deleteQuery.addWhere("task_id = :task_id", task.getTaskId()); this.named.update(deleteQuery.toSQL(), deleteQuery.toParam()); } } }0 package com.gy.activiti.service; import com.gy.activiti.domain.BizLeave; import java.util.List; /** * 请假Service接口 * * @author gy * @date 2020-01-07 */ public interface IBizLeaveService { /** * 查询请假 * * @param id 请假ID * @return 请假 */ public BizLeave selectBizLeaveById(String id); /** * 查询请假列表 * * @param bizLeave 请假 * @return 请假集合 */ public List selectBizLeaveList(BizLeave bizLeave); /** * 新增请假 * * @param bizLeave 请假 * @return 结果 */ public int insertBizLeave(BizLeave bizLeave); /** * 修改请假 * * @param bizLeave 请假 * @return 结果 */ public int updateBizLeave(BizLeave bizLeave); /** * 批量删除请假 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteBizLeaveByIds(String ids); /** * 删除请假信息 * * @param id 请假ID * @return 结果 */ public int deleteBizLeaveById(String id); } 10-100 package com.prowidesoftware.swift.model.mx.dic; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * Details of settlement of a transaction. * * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SettlementDetails100", propOrder = { "sttlmTxCond", "regn", "lglRstrctns", "sctiesRTGS", "sttlmSysMtd", "taxCpcty", "stmpDtyTaxBsis" }) public class SettlementDetails100 { @XmlElement(name = "SttlmTxCond") protected List sttlmTxCond; @XmlElement(name = "Regn") protected Registration9Choice regn; @XmlElement(name = "LglRstrctns") protected Restriction5Choice lglRstrctns; @XmlElement(name = "SctiesRTGS") protected SecuritiesRTGS4Choice sctiesRTGS; @XmlElement(name = "SttlmSysMtd") protected SettlementSystemMethod4Choice sttlmSysMtd; @XmlElement(name = "TaxCpcty") protected TaxCapacityParty4Choice taxCpcty; @XmlElement(name = "StmpDtyTaxBsis") protected GenericIdentification30 stmpDtyTaxBsis; /** * Gets the value of the sttlmTxCond property. * *

* This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a set method for the sttlmTxCond property. * *

* For example, to add a new item, do as follows: *

     *    getSttlmTxCond().add(newItem);
     * 
* * *

* Objects of the following type(s) are allowed in the list * {@link SettlementTransactionCondition19Choice } * * */ public List getSttlmTxCond() { if (sttlmTxCond == null) { sttlmTxCond = new ArrayList(); } return this.sttlmTxCond; } /** * Gets the value of the regn property. * * @return * possible object is * {@link Registration9Choice } * */ public Registration9Choice getRegn() { return regn; } /** * Sets the value of the regn property. * * @param value * allowed object is * {@link Registration9Choice } * */ public SettlementDetails100 setRegn(Registration9Choice value) { this.regn = value; return this; } /** * Gets the value of the lglRstrctns property. * * @return * possible object is * {@link Restriction5Choice } * */ public Restriction5Choice getLglRstrctns() { return lglRstrctns; } /** * Sets the value of the lglRstrctns property. * * @param value * allowed object is * {@link Restriction5Choice } * */ public SettlementDetails100 setLglRstrctns(Restriction5Choice value) { this.lglRstrctns = value; return this; } /** * Gets the value of the sctiesRTGS property. * * @return * possible object is * {@link SecuritiesRTGS4Choice } * */ public SecuritiesRTGS4Choice getSctiesRTGS() { return sctiesRTGS; } /** * Sets the value of the sctiesRTGS property. * * @param value * allowed object is * {@link SecuritiesRTGS4Choice } * */ public SettlementDetails100 setSctiesRTGS(SecuritiesRTGS4Choice value) { this.sctiesRTGS = value; return this; } /** * Gets the value of the sttlmSysMtd property. * * @return * possible object is * {@link SettlementSystemMethod4Choice } * */ public SettlementSystemMethod4Choice getSttlmSysMtd() { return sttlmSysMtd; } /** * Sets the value of the sttlmSysMtd property. * * @param value * allowed object is * {@link SettlementSystemMethod4Choice } * */ public SettlementDetails100 setSttlmSysMtd(SettlementSystemMethod4Choice value) { this.sttlmSysMtd = value; return this; } /** * Gets the value of the taxCpcty property. * * @return * possible object is * {@link TaxCapacityParty4Choice } * */ public TaxCapacityParty4Choice getTaxCpcty() { return taxCpcty; } /** * Sets the value of the taxCpcty property. * * @param value * allowed object is * {@link TaxCapacityParty4Choice } * */ public SettlementDetails100 setTaxCpcty(TaxCapacityParty4Choice value) { this.taxCpcty = value; return this; } /** * Gets the value of the stmpDtyTaxBsis property. * * @return * possible object is * {@link GenericIdentification30 } * */ public GenericIdentification30 getStmpDtyTaxBsis() { return stmpDtyTaxBsis; } /** * Sets the value of the stmpDtyTaxBsis property. * * @param value * allowed object is * {@link GenericIdentification30 } * */ public SettlementDetails100 setStmpDtyTaxBsis(GenericIdentification30 value) { this.stmpDtyTaxBsis = value; return this; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * Adds a new item to the sttlmTxCond list. * @see #getSttlmTxCond() * */ public SettlementDetails100 addSttlmTxCond(SettlementTransactionCondition19Choice sttlmTxCond) { getSttlmTxCond().add(sttlmTxCond); return this; } } package model; import jboolexpr.BooleanExpression; import jboolexpr.MalformedBooleanException; import org.joda.time.DateTime; import org.joda.time.DateTimeFieldType; import play.data.format.Formats; import play.db.ebean.Model; import utils.TimestampUtils; import javax.persistence.*; import java.text.Normalizer; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Describes an event. * Created by Ced on 31/01/2015. */ @Entity public class Event extends Model { @Id public String id; /** * The name of the event. */ public String name; /** * List of the basic events composing the event. */ @ManyToMany(cascade = CascadeType.REMOVE) public List basicEvents = new ArrayList<>(); /** * The duration of the event. */ public int duration; @Formats.DateTime(pattern = "HH:mm") public DateTime beginTime; @Formats.DateTime(pattern = "HH:mm") public DateTime endTime; /** * The expression combining BasicEvent ids */ public String expression; public String icon; public String color; public String validate() { if (expression.isEmpty()) { return "Expression vide !"; } if (!validateExpression(expression)) { return "Expression fausse ou un évènement de base n'existe pas."; } return null; } public boolean validateExpression(String toEval) { Pattern p = Pattern.compile("\\w+"); Matcher m = p.matcher(toEval); List matches = new ArrayList(); while (m.find()) { matches.add(m.group()); } String[] basicEventIds = matches.toArray(new String[matches.size()]); // first, check if all given basic events exist in database for (String id : basicEventIds) { id = id.trim(); toEval = toEval.replace(id, "true"); boolean basicEventExist = BasicEvent.find.where().eq("id", id).findRowCount() == 1; System.out.println("--- basicEventID: " + id + " " + basicEventExist + " ---"); if (!basicEventExist) { return false; } } // then, test if the expression is syntactically correct by trying to parse it (after having replacer all the ids by true for example BooleanExpression boolExpr; try { System.out.println("Expression: " + toEval); boolExpr = BooleanExpression.readLeftToRight(toEval); boolean bool = boolExpr.booleanValue(); System.out.println("Result of the evaluation: " + boolExpr + " == " + bool); } catch (MalformedBooleanException e) { System.err.println("Invalid Expression"); // e.printStackTrace(); return false; } return true; } /** * The list of all the existing Event. */ public static Model.Finder find = new Model.Finder<>(String.class, Event.class); /** * Initializes the given Event with the given time interval and saves it. * * @param event the Event to initialize. * @param timeInterval a description of the TimeInterval. * @return the Event saved and initialized. */ public static Event create(Event event, String timeInterval) { // event.timeInterval = TimeInterval.find.byId(timeInterval); // set the id to something meaningful String meaningfulId = event.getName().replaceAll(" ", "_").toLowerCase(); // delete all the accents meaningfulId = Normalizer.normalize(meaningfulId, Normalizer.Form.NFD); meaningfulId = meaningfulId.replaceAll("[^\\p{ASCII}]", ""); event.setId(meaningfulId); event.save(); event.saveManyToManyAssociations("basicEvents"); event.save(); return event; } /** * Returns the list of all the Events * * @return the list of all the Events */ public static List all() { return find.all(); } public void check() { // TODO: verify that event has not already been detected for the last TimeInterval long[] todayTimeInterval = getActualTimeInterval(); if (EventOccurrence.find.where().eq("event_id", getId()) .between("timestamp", todayTimeInterval[0], todayTimeInterval[1]) .findIds().size() > 0) { // Event already in DB return; } BasicEventOccurrence basicEventOccurrence = new BasicEventOccurrence(); String toEval = expression; // copy the string // System.out.println("STRING : " + toEval); long mean = 0; int cpt = 0; // fetch the ids of the basic events composing the event Pattern p = Pattern.compile("\\w+"); Matcher m = p.matcher(toEval); List matches = new ArrayList<>(); while (m.find()) { matches.add(m.group()); } String[] basicEventIds = matches.toArray(new String[matches.size()]); List timeIntervals = new ArrayList<>(); timeIntervals.add(todayTimeInterval); if (EventOccurrence.find.where().eq("event_id", getId()).findList().size() == 0 && BasicEventOccurrence.find.findRowCount() > 0) { // no Event occurrence in DB // but BasicEventOccurrence in DB // find the oldest BasicEventOccurrence // compute for each day between now and this date long oldestBasicOccurrence = BasicEventOccurrence.find.where().orderBy("timestamp ascending"). findPagingList(1).getPage(1) .getList().get(0).getTimestamp(); System.out.println(oldestBasicOccurrence); DateTime firstBasic = new DateTime(oldestBasicOccurrence*1000); // needs milliseconds DateTime now = new DateTime(System.currentTimeMillis()); int dayBetween = now.get(DateTimeFieldType.dayOfYear()) - firstBasic.get(DateTimeFieldType.dayOfYear()); for(int i = 0; i < dayBetween; i++) { long[] timeInterval = new long[2]; timeInterval[0] = todayTimeInterval[0] - (i+1)*24*3600; timeInterval[1] = todayTimeInterval[1] - (i+1)*24*3600; timeIntervals.add(timeInterval); } // DEBUG // for(int i = 0; i 0 ? mean / cpt : System.currentTimeMillis() / 1000, TimestampUtils.formatToString(mean / cpt, "dd-MM-yyyy HH:mm:ss")); if (EventOccurrence.find.where().eq("timestamp", eventOccurrence.getTimestamp()).eq("event_id", eventOccurrence.getEvent().getId()).findUnique() == null) { eventOccurrence.save(); } } } catch (MalformedBooleanException e) { e.printStackTrace(); } } } public long[] getActualTimeInterval() { long[] res = new long[2]; res[0] = getTimestampStart(); res[1] = getTimestampEnd(res[0]); return res; } public long getTimestampStart() { GregorianCalendar start = setCalWithLocalTime(beginTime); if (start.getTimeInMillis() > System.currentTimeMillis()) { // it's 1:00 and event begin at 6 for example return start.getTimeInMillis() / 1000 - 24 * 3600; // subtract on day in second } else { return start.getTimeInMillis() / 1000; } } public long getTimestampEnd(long begin) { long end = begin + (getEndTime().getMillis() - getBeginTime().getMillis()) / 1000; return end > begin ? end : end + 3600*24; } private GregorianCalendar setCalWithLocalTime(DateTime localTime) { GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(System.currentTimeMillis()); cal.set(Calendar.HOUR_OF_DAY, localTime.get(DateTimeFieldType.clockhourOfDay())); cal.set(Calendar.MINUTE, localTime.get(DateTimeFieldType.minuteOfHour())); cal.set(Calendar.SECOND, 0); return cal; } /** * Returns the name of the Event. * * @return the name of the Event. */ public String getName() { return name; } /** * Sets the name of the Event. * * @param name the new Event name. */ public void setName(String name) { this.name = name; } /** * Returns the list of the BasicEvent used to identify this Event. * * @return the list of the BasicEvent used to identify this Event. */ public List getBasicEvents() { return basicEvents; } /** * Sets the list of the BasicEvent used to identify this Event. * * @param basicEvents the new list. */ public void setBasicEvents(List basicEvents) { this.basicEvents = basicEvents; } /** * Returns the duration of the Event. * * @return the duration of the Event. */ public int getDuration() { return duration; } /** * Sets the duration of the Event. * * @param duration the new duration. */ public void setDuration(int duration) { this.duration = duration; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getExpression() { return expression; } public void setExpression(String expression) { this.expression = expression; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public DateTime getBeginTime() { return beginTime; } public void setBeginTime(DateTime beginTime) { this.beginTime = beginTime; } public DateTime getEndTime() { return endTime; } public void setEndTime(DateTime endTime) { this.endTime = endTime; } /** * Returns the description of the object as JSON. * * @return the description of the object as JSON. */ @Override public String toString() { String basicEventsStr = ""; for (BasicEvent b : getBasicEvents()) { basicEventsStr += b.toString() + " --- "; } return "Event{" + "name='" + getName() + '\'' + ", basicEvents=" + basicEventsStr + ", duration=" + getDuration() + '}'; } } package org.sirix.fs; import com.google.common.base.Optional; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import javax.xml.namespace.QName; import org.sirix.api.INodeWriteTrx; import org.sirix.exception.SirixException; import org.sirix.utils.LogWrapper; import org.slf4j.LoggerFactory; /** * Process file system attributes. * * @author , University of Konstanz * */ public class ProcessFileSystemAttributes implements IVisitor { /** {@link LogWrapper} reference. */ private static final LogWrapper LOGWRAPPER = new LogWrapper(LoggerFactory .getLogger(ProcessFileSystemAttributes.class)); @Override public void processDirectory(final INodeWriteTrx pTransaction, final Path pDir, final Optional pAttrs) { } @Override public void processFile(final INodeWriteTrx pTransaction, Path pFile, final Optional pAttrs) { if (Files.exists(pFile)) { final String file = pFile.getFileName().toString(); final int index = file.lastIndexOf('.'); if (index > 0) { final String suffix = file.substring(index + 1); if (!suffix.isEmpty()) { try { pTransaction.insertAttribute(new QName("suffix"), file.substring(index + 1)); pTransaction.moveToParent(); } catch (SirixException e) { LOGWRAPPER.error(e.getMessage(), e); } } } } } } // The MIT License (MIT) // Copyright © 2015 AppsLandia. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. package com.appslandia.plum.base; import java.util.HashMap; import java.util.Map; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import com.appslandia.common.base.InitializeObject; import com.appslandia.common.utils.AssertUtils; import com.appslandia.common.utils.StringUtils; /** * * @author * */ public class DynServletRegister extends InitializeObject { private String servletName; private Class servletClass; private String servletClassName; private String[] urlPatterns; final Map initParameters = new HashMap<>(); private boolean asyncSupported; private int loadOnStartup = -1; private DynMultipartConfig multipartConfig; @Override protected void init() throws Exception { AssertUtils.assertNotNull(this.servletName); AssertUtils.assertTrue((this.servletClass != null) || (this.servletClassName != null), "No servlet provided."); AssertUtils.assertHasElements(this.urlPatterns, "urlPatterns is required."); } public DynServletRegister registerTo(ServletContext sc) { initialize(); ServletRegistration.Dynamic reg = (this.servletClass != null) ? sc.addServlet(this.servletName, this.servletClass) : sc.addServlet(this.servletName, this.servletClassName); reg.addMapping(this.urlPatterns); reg.setInitParameters(this.initParameters); reg.setAsyncSupported(this.asyncSupported); reg.setLoadOnStartup(this.loadOnStartup); if (this.multipartConfig != null) { reg.setMultipartConfig(this.multipartConfig.toMultipartConfigElement()); } return this; } public DynServletRegister servletName(String servletName) { assertNotInitialized(); this.servletName = StringUtils.trimToNull(servletName); return this; } public DynServletRegister servletClassName(String servletClassName) { assertNotInitialized(); this.servletClassName = StringUtils.trimToNull(servletClassName); return this; } public DynServletRegister servletClass(Class servletClass) { assertNotInitialized(); this.servletClass = servletClass; if (this.servletName == null) { this.servletName = StringUtils.trimToNull(servletClass.getSimpleName()); } return this; } public DynServletRegister urlPatterns(String... urlPatterns) { assertNotInitialized(); this.urlPatterns = urlPatterns; return this; } public DynServletRegister initParameter(String name, String value) { assertNotInitialized(); this.initParameters.put(name, value); return this; } public DynServletRegister asyncSupported(boolean asyncSupported) { assertNotInitialized(); this.asyncSupported = asyncSupported; return this; } public DynServletRegister loadOnStartup(int loadOnStartup) { assertNotInitialized(); this.loadOnStartup = loadOnStartup; return this; } public DynServletRegister multipartConfig(DynMultipartConfig multipartConfig) { assertNotInitialized(); this.multipartConfig = multipartConfig; return this; } } package org.ljelic.instafram.view.component; import org.ljelic.instafram.observer.ChangeObservable; public interface Menu extends Component, ChangeObservable { void addComponent(Component component); void addSeparator(); void setText(String text); void setIcon(byte[] icon); void setMnemonic(char mnemonic); }nschlimm/playground package com.schlimm.forkjoindip; import java.util.List; import java.util.concurrent.ForkJoinTask; /** * Abstract class that isolates the logic how a list of input objects can be distributed across multiple threads using * {@link ForkJoinTask#fork()} operations. * * @author * * @param * the original {@link ForkJoinTask} in charge of the computation (for recursive invocation) */ public abstract class ForkAndJoinProcessor> { protected A forkAndJoinTask; public ForkAndJoinProcessor(A forkAndJoinTask) { super(); this.forkAndJoinTask = forkAndJoinTask; } /** * Subclasses implement this method to decide how to distribute processing of the decomposed input objects. * * @param decomposedInput the list of input objects to distribute across threads using {@link ForkJoinTask#fork()} * @return a result of subtasks composed by using {@link ForkJoinTask#join()} */ public abstract ComposableResult forkAndJoin(List> decomposedInput); } src/main/gen-src/net/java/dev/wiseman/schemas/metadata/messagetypes/MessageDefinitions.java // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-382 // See http://java.sun.com/xml/jaxb // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2007.05.29 at 01:59:34 PM EDT // package net.java.dev.wiseman.schemas.metadata.messagetypes; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** *

* Java class for anonymous complex type. * *

* The following schema fragment specifies the expected content contained within this class. * *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="schemas" type="{http://schemas.wiseman.dev.java.net/metadata/messagetypes}SchemasType"/>
 *         <element name="operations" type="{http://schemas.wiseman.dev.java.net/metadata/messagetypes}OperationsType"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * 
* * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "schemas", "operations" }) @XmlRootElement(name = "message-definitions") public class MessageDefinitions { @XmlElement(required = true) protected SchemasType schemas; @XmlElement(required = true) protected OperationsType operations; /** * Gets the value of the schemas property. * * @return possible object is {@link SchemasType } * */ public SchemasType getSchemas() { return schemas; } /** * Sets the value of the schemas property. * * @param value allowed object is {@link SchemasType } * */ public void setSchemas(SchemasType value) { this.schemas = value; } /** * Gets the value of the operations property. * * @return possible object is {@link OperationsType } * */ public OperationsType getOperations() { return operations; } /** * Sets the value of the operations property. * * @param value allowed object is {@link OperationsType } * */ public void setOperations(OperationsType value) { this.operations = value; } } /* * 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.connectors.jdbc.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import java.sql.Blob; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Types; import java.util.Date; import junitparams.JUnitParamsRunner; import junitparams.Parameters; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.apache.geode.connectors.jdbc.JdbcConnectorException; import org.apache.geode.connectors.jdbc.internal.configuration.RegionMapping; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.pdx.FieldType; import org.apache.geode.pdx.PdxInstance; import org.apache.geode.pdx.PdxInstanceFactory; import org.apache.geode.pdx.internal.PdxField; import org.apache.geode.pdx.internal.PdxType; import org.apache.geode.pdx.internal.TypeRegistry; @RunWith(JUnitParamsRunner.class) public class SqlToPdxInstanceCreatorTest { private static final String COLUMN_NAME_1 = "columnName1"; private static final Object COLUMN_VALUE_1 = "columnValue1"; private static final Object COLUMN_VALUE_2 = "columnValue2"; private static final String COLUMN_NAME_2 = "columnName2"; private static final String KEY_COLUMN = "keyColumn"; private static final String PDX_FIELD_NAME_1 = COLUMN_NAME_1.toLowerCase(); private static final String PDX_FIELD_NAME_2 = COLUMN_NAME_2.toLowerCase(); private InternalCache cache; private RegionMapping regionMapping; private ResultSet resultSet; private TableMetaDataView tableMetaDataView; @Rule public ExpectedException thrown = ExpectedException.none(); @Before public void setup() throws Exception { cache = mock(InternalCache.class); regionMapping = mock(RegionMapping.class); resultSet = mock(ResultSet.class); tableMetaDataView = mock(TableMetaDataView.class); when(tableMetaDataView.getKeyColumnName()).thenReturn(KEY_COLUMN); } @Test public void usesPdxFactoryForClassWhenExists() throws Exception { String pdxClassName = "classname"; when(regionMapping.getPdxName()).thenReturn(pdxClassName); when(resultSet.next()).thenReturn(false); createPdxInstance(); verify(cache).createPdxInstanceFactory(pdxClassName); verifyNoMoreInteractions(cache); } @Test public void readReturnsNullIfNoResultsReturned() throws Exception { when(resultSet.next()).thenReturn(false); PdxInstance pdxInstance = createPdxInstance(); assertThat(pdxInstance).isNull(); } @Test public void readResultIncludesKeyColumnInPdxValue() throws Exception { setupResultSetForTwoObjectColumns(resultSet); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = mock(PdxInstanceFactory.class); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_2), any())) .thenReturn(PDX_FIELD_NAME_2); tableMetaDataView = mock(TableMetaDataView.class); when(tableMetaDataView.getKeyColumnName()).thenReturn(COLUMN_NAME_1); TypeRegistry pdxTypeRegistry = mock(TypeRegistry.class); when(cache.getPdxRegistry()).thenReturn(pdxTypeRegistry); String pdxClassName = "myPdxClassName"; when(cache.createPdxInstanceFactory(pdxClassName)).thenReturn(factory); PdxType pdxType = mock(PdxType.class); when(regionMapping.getPdxName()).thenReturn(pdxClassName); when(pdxTypeRegistry.getPdxTypeForField(PDX_FIELD_NAME_1, pdxClassName)).thenReturn(pdxType); PdxField pdxField = mock(PdxField.class); when(pdxField.getFieldType()).thenReturn(FieldType.OBJECT); when(pdxType.getPdxField(PDX_FIELD_NAME_1)).thenReturn(pdxField); when(pdxTypeRegistry.getPdxTypeForField(PDX_FIELD_NAME_2, pdxClassName)).thenReturn(pdxType); when(pdxType.getPdxField(PDX_FIELD_NAME_2)).thenReturn(pdxField); createPdxInstance(); verify(factory).writeObject(PDX_FIELD_NAME_1, COLUMN_VALUE_1); verify(factory).writeObject(PDX_FIELD_NAME_2, COLUMN_VALUE_2); verify(factory).create(); } @Test public void readReturnsDataFromAllResultColumns() throws Exception { setupResultSetForTwoObjectColumns(resultSet); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = mock(PdxInstanceFactory.class); String pdxClassName = "myPdxClassName"; when(cache.createPdxInstanceFactory(pdxClassName)).thenReturn(factory); when(cache.createPdxInstanceFactory(anyString(), anyBoolean())).thenReturn(factory); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_2), any())) .thenReturn(PDX_FIELD_NAME_2); TypeRegistry pdxTypeRegistry = mock(TypeRegistry.class); when(cache.getPdxRegistry()).thenReturn(pdxTypeRegistry); PdxType pdxType = mock(PdxType.class); when(regionMapping.getPdxName()).thenReturn(pdxClassName); when(pdxTypeRegistry.getPdxTypeForField(PDX_FIELD_NAME_1, pdxClassName)).thenReturn(pdxType); PdxField pdxField = mock(PdxField.class); when(pdxField.getFieldType()).thenReturn(FieldType.OBJECT); when(pdxType.getPdxField(PDX_FIELD_NAME_1)).thenReturn(pdxField); when(pdxTypeRegistry.getPdxTypeForField(PDX_FIELD_NAME_2, pdxClassName)).thenReturn(pdxType); when(pdxType.getPdxField(PDX_FIELD_NAME_2)).thenReturn(pdxField); createPdxInstance(); verify(factory).writeObject(PDX_FIELD_NAME_1, COLUMN_VALUE_1); verify(factory).writeObject(PDX_FIELD_NAME_2, COLUMN_VALUE_2); verify(factory).create(); } @Test public void usesMappedPdxFieldNameWhenReading() throws Exception { setupResultSet(resultSet, FieldType.OBJECT, COLUMN_VALUE_1); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = mock(PdxInstanceFactory.class); String fieldName1 = "pdxFieldName1"; when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())).thenReturn(fieldName1); TypeRegistry pdxTypeRegistry = mock(TypeRegistry.class); when(cache.getPdxRegistry()).thenReturn(pdxTypeRegistry); String pdxClassName = "myPdxClassName"; when(cache.createPdxInstanceFactory(pdxClassName)).thenReturn(factory); PdxType pdxType = mock(PdxType.class); when(regionMapping.getPdxName()).thenReturn(pdxClassName); when(pdxTypeRegistry.getPdxTypeForField(fieldName1, pdxClassName)).thenReturn(pdxType); PdxField pdxField = mock(PdxField.class); when(pdxField.getFieldType()).thenReturn(FieldType.OBJECT); when(pdxType.getPdxField(fieldName1)).thenReturn(pdxField); createPdxInstance(); verify(factory).writeObject(fieldName1, COLUMN_VALUE_1); verify(factory).create(); } @Test @Parameters(source = FieldType.class) public void readWritesFieldGivenPdxFieldType(FieldType fieldType) throws Exception { setupResultSet(resultSet, fieldType); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType); verify(factory).create(); } private PdxInstance createPdxInstance() throws SQLException { SqlToPdxInstanceCreator sqlToPdxInstanceCreator = new SqlToPdxInstanceCreator(cache, regionMapping, resultSet, tableMetaDataView); return sqlToPdxInstanceCreator.create(); } @Test @Parameters(source = FieldType.class) public void readOfNullWritesFieldGivenPdxFieldType(FieldType fieldType) throws Exception { setupResultSet(resultSet, fieldType, null); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, null); verify(factory).create(); } @Test public void readOfCharFieldWithEmptyStringWritesCharZero() throws Exception { char expectedValue = 0; FieldType fieldType = FieldType.CHAR; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); when(resultSet.getString(1)).thenReturn(""); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, expectedValue); verify(factory).create(); } @Test public void readOfDateFieldWithDateColumnWritesDate() throws Exception { FieldType fieldType = FieldType.DATE; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); when(tableMetaDataView.getColumnDataType(COLUMN_NAME_1)).thenReturn(Types.DATE); java.sql.Date sqlDate = java.sql.Date.valueOf("1979-09-11"); Date expectedValue = new Date(sqlDate.getTime()); when(resultSet.getDate(1)).thenReturn(sqlDate); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, expectedValue); verify(factory).create(); } @Test public void readOfByteArrayFieldWithBlob() throws Exception { FieldType fieldType = FieldType.BYTE_ARRAY; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); when(tableMetaDataView.getColumnDataType(COLUMN_NAME_1)).thenReturn(Types.BLOB); byte[] expectedValue = new byte[] {1, 2, 3}; Blob blob = mock(Blob.class); when(blob.length()).thenReturn((long) expectedValue.length); when(blob.getBytes(1, expectedValue.length)).thenReturn(expectedValue); when(resultSet.getBlob(1)).thenReturn(blob); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, expectedValue); verify(factory).create(); } @Test public void readOfByteArrayFieldWithNullBlob() throws Exception { FieldType fieldType = FieldType.BYTE_ARRAY; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); when(tableMetaDataView.getColumnDataType(COLUMN_NAME_1)).thenReturn(Types.BLOB); byte[] expectedValue = null; Blob blob = null; when(resultSet.getBlob(1)).thenReturn(blob); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, expectedValue); verify(factory).create(); } @Test public void readOfByteArrayFieldWithHugeBlobThrows() throws Exception { FieldType fieldType = FieldType.BYTE_ARRAY; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); when(tableMetaDataView.getColumnDataType(COLUMN_NAME_1)).thenReturn(Types.BLOB); Blob blob = mock(Blob.class); when(blob.length()).thenReturn((long) Integer.MAX_VALUE + 1); when(resultSet.getBlob(1)).thenReturn(blob); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); thrown.expect(JdbcConnectorException.class); thrown.expectMessage("Blob of length 2147483648 is too big to be converted to a byte array."); createPdxInstance(); } @Test public void readOfObjectFieldWithBlob() throws Exception { FieldType fieldType = FieldType.OBJECT; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); when(tableMetaDataView.getColumnDataType(COLUMN_NAME_1)).thenReturn(Types.BLOB); byte[] expectedValue = new byte[] {1, 2, 3}; Blob blob = mock(Blob.class); when(blob.length()).thenReturn((long) expectedValue.length); when(blob.getBytes(1, expectedValue.length)).thenReturn(expectedValue); when(resultSet.getBlob(1)).thenReturn(blob); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, expectedValue); verify(factory).create(); } @Test public void readOfDateFieldWithTimeColumnWritesDate() throws Exception { FieldType fieldType = FieldType.DATE; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); when(tableMetaDataView.getColumnDataType(COLUMN_NAME_1)).thenReturn(Types.TIME); java.sql.Time sqlTime = java.sql.Time.valueOf("22:33:44"); Date expectedValue = new Date(sqlTime.getTime()); when(resultSet.getTime(1)).thenReturn(sqlTime); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, expectedValue); verify(factory).create(); } @Test public void readOfDateFieldWithTimestampColumnWritesDate() throws Exception { FieldType fieldType = FieldType.DATE; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); when(tableMetaDataView.getColumnDataType(COLUMN_NAME_1)).thenReturn(Types.TIMESTAMP); java.sql.Timestamp sqlTimestamp = java.sql.Timestamp.valueOf("1979-09-11 22:33:44.567"); Date expectedValue = new Date(sqlTimestamp.getTime()); when(resultSet.getTimestamp(1)).thenReturn(sqlTimestamp); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, expectedValue); verify(factory).create(); } @Test public void readOfObjectFieldWithDateColumnWritesDate() throws Exception { FieldType fieldType = FieldType.OBJECT; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); java.sql.Date sqlDate = java.sql.Date.valueOf("1979-09-11"); Date expectedValue = new Date(sqlDate.getTime()); when(resultSet.getObject(1)).thenReturn(sqlDate); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, expectedValue); verify(factory).create(); } @Test public void readOfObjectFieldWithJavaUtilDateWritesDate() throws Exception { FieldType fieldType = FieldType.OBJECT; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); Date expectedValue = new Date(); when(resultSet.getObject(1)).thenReturn(expectedValue); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, expectedValue); verify(factory).create(); } @Test public void readOfObjectFieldWithTimeColumnWritesDate() throws Exception { FieldType fieldType = FieldType.OBJECT; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); java.sql.Time sqlTime = java.sql.Time.valueOf("22:33:44"); Date expectedValue = new Date(sqlTime.getTime()); when(resultSet.getObject(1)).thenReturn(sqlTime); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, expectedValue); verify(factory).create(); } @Test public void readOfObjectFieldWithTimestampColumnWritesDate() throws Exception { FieldType fieldType = FieldType.OBJECT; ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(resultSet.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); java.sql.Timestamp sqlTimestamp = java.sql.Timestamp.valueOf("1979-09-11 22:33:44.567"); Date expectedValue = new Date(sqlTimestamp.getTime()); when(resultSet.getObject(1)).thenReturn(sqlTimestamp); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = setupPdxInstanceFactory(fieldType); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); createPdxInstance(); verifyPdxFactoryWrite(factory, fieldType, expectedValue); verify(factory).create(); } @Test @Parameters({"BOOLEAN_ARRAY", "OBJECT_ARRAY", "CHAR_ARRAY", "SHORT_ARRAY", "INT_ARRAY", "LONG_ARRAY", "FLOAT_ARRAY", "DOUBLE_ARRAY", "STRING_ARRAY", "ARRAY_OF_BYTE_ARRAYS"}) public void throwsExceptionWhenReadWritesUnsupportedType(FieldType fieldType) throws Exception { String returnValue = "ReturnValue"; setupPdxInstanceFactory(fieldType); setupResultSetForObject(resultSet, returnValue); when(resultSet.next()).thenReturn(true).thenReturn(false); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_2), any())) .thenReturn(PDX_FIELD_NAME_2); thrown.expect(JdbcConnectorException.class); thrown.expectMessage("Could not convert "); createPdxInstance(); } @Test public void throwsExceptionIfMoreThanOneResultReturned() throws Exception { setupResultSet(resultSet, FieldType.OBJECT); when(resultSet.next()).thenReturn(true); when(resultSet.getStatement()).thenReturn(mock(PreparedStatement.class)); PdxInstanceFactory factory = mock(PdxInstanceFactory.class); String pdxClassName = "myPdxClassName"; when(cache.createPdxInstanceFactory(pdxClassName)).thenReturn(factory); TypeRegistry pdxTypeRegistry = mock(TypeRegistry.class); when(cache.getPdxRegistry()).thenReturn(pdxTypeRegistry); PdxType pdxType = mock(PdxType.class); when(regionMapping.getPdxName()).thenReturn(pdxClassName); when(pdxTypeRegistry.getPdxTypeForField(PDX_FIELD_NAME_1, pdxClassName)).thenReturn(pdxType); PdxField pdxField = mock(PdxField.class); when(pdxField.getFieldType()).thenReturn(FieldType.OBJECT); when(pdxType.getPdxField(PDX_FIELD_NAME_1)).thenReturn(pdxField); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); thrown.expect(JdbcConnectorException.class); thrown.expectMessage("Multiple rows returned for query: "); createPdxInstance(); } @Test public void readThrowsGivenPdxTypeWithFieldMissing() throws Exception { setupResultSet(resultSet, FieldType.OBJECT); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = mock(PdxInstanceFactory.class); String pdxClassName = "myPdxClassName"; when(cache.createPdxInstanceFactory(pdxClassName)).thenReturn(factory); TypeRegistry pdxTypeRegistry = mock(TypeRegistry.class); when(cache.getPdxRegistry()).thenReturn(pdxTypeRegistry); PdxType pdxType = mock(PdxType.class); when(regionMapping.getPdxName()).thenReturn(pdxClassName); when(pdxTypeRegistry.getPdxTypeForField(PDX_FIELD_NAME_1, pdxClassName)).thenReturn(pdxType); when(pdxType.getPdxField(PDX_FIELD_NAME_1)).thenReturn(null); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); thrown.expect(JdbcConnectorException.class); thrown.expectMessage("Could not find PdxType"); createPdxInstance(); } @Test public void readThrowsWithMissingPdxType() throws Exception { setupResultSet(resultSet, FieldType.OBJECT); when(resultSet.next()).thenReturn(true).thenReturn(false); PdxInstanceFactory factory = mock(PdxInstanceFactory.class); String pdxClassName = "myPdxClassName"; when(cache.createPdxInstanceFactory(pdxClassName)).thenReturn(factory); TypeRegistry pdxTypeRegistry = mock(TypeRegistry.class); when(cache.getPdxRegistry()).thenReturn(pdxTypeRegistry); when(regionMapping.getPdxName()).thenReturn(pdxClassName); when(pdxTypeRegistry.getPdxTypeForField(PDX_FIELD_NAME_1, pdxClassName)).thenReturn(null); when(regionMapping.getFieldNameForColumn(eq(COLUMN_NAME_1), any())) .thenReturn(PDX_FIELD_NAME_1); thrown.expect(JdbcConnectorException.class); thrown.expectMessage("Could not find PdxType"); createPdxInstance(); } private void setupResultSetForTwoObjectColumns(ResultSet result) throws SQLException { setupResultSet(result, FieldType.OBJECT); ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(result.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(2); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); when(metaData.getColumnName(2)).thenReturn(COLUMN_NAME_2); when(result.getObject(1)).thenReturn(COLUMN_VALUE_1); when(result.getObject(2)).thenReturn(COLUMN_VALUE_2); } private void setupResultSet(ResultSet result, FieldType fieldType) throws SQLException { setupResultSet(result, fieldType, getValueByFieldType(fieldType)); } private void setupResultSet(ResultSet result, FieldType fieldType, Object value) throws SQLException { ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(result.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(1); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); switch (fieldType) { case STRING: when(result.getString(1)).thenReturn((String) value); break; case CHAR: Character charValue = (Character) value; when(result.getString(1)).thenReturn(value == null ? null : charValue.toString()); break; case SHORT: when(result.getShort(1)).thenReturn(value == null ? 0 : (Short) value); break; case INT: when(result.getInt(1)).thenReturn(value == null ? 0 : (Integer) value); break; case LONG: when(result.getLong(1)).thenReturn(value == null ? 0 : (Long) value); break; case FLOAT: when(result.getFloat(1)).thenReturn(value == null ? 0 : (Float) value); break; case DOUBLE: when(result.getDouble(1)).thenReturn(value == null ? 0 : (Double) value); break; case BYTE: when(result.getByte(1)).thenReturn(value == null ? 0 : (Byte) value); break; case BOOLEAN: when(result.getBoolean(1)).thenReturn(value == null ? false : (Boolean) value); break; case DATE: Date date = (Date) value; java.sql.Timestamp sqlTimeStamp = null; if (date != null) { sqlTimeStamp = new java.sql.Timestamp(date.getTime()); } when(result.getTimestamp(1)).thenReturn(sqlTimeStamp); break; case BYTE_ARRAY: when(result.getBytes(1)).thenReturn((byte[]) value); break; case BOOLEAN_ARRAY: when(result.getObject(1)).thenReturn(value); break; case CHAR_ARRAY: when(result.getObject(1)).thenReturn(value); break; case SHORT_ARRAY: when(result.getObject(1)).thenReturn(value); break; case INT_ARRAY: when(result.getObject(1)).thenReturn(value); break; case LONG_ARRAY: when(result.getObject(1)).thenReturn(value); break; case FLOAT_ARRAY: when(result.getObject(1)).thenReturn(value); break; case DOUBLE_ARRAY: when(result.getObject(1)).thenReturn(value); break; case STRING_ARRAY: when(result.getObject(1)).thenReturn(value); break; case OBJECT_ARRAY: when(result.getObject(1)).thenReturn(value); break; case ARRAY_OF_BYTE_ARRAYS: when(result.getObject(1)).thenReturn(value); break; case OBJECT: when(result.getObject(1)).thenReturn(value); break; default: throw new IllegalStateException("unhandled fieldType " + fieldType); } } private static byte[][] arrayOfByteArray = new byte[][] {{1, 2}, {3, 4}}; @SuppressWarnings("unchecked") private T getValueByFieldType(FieldType fieldType) { switch (fieldType) { case STRING: return (T) "stringValue"; case CHAR: return (T) Character.valueOf('A'); case SHORT: return (T) Short.valueOf((short) 36); case INT: return (T) Integer.valueOf(36); case LONG: return (T) Long.valueOf(36); case FLOAT: return (T) Float.valueOf(36); case DOUBLE: return (T) Double.valueOf(36); case BYTE: return (T) Byte.valueOf((byte) 36); case BOOLEAN: return (T) Boolean.TRUE; case DATE: return (T) new Date(1000); case BYTE_ARRAY: return (T) new byte[] {1, 2}; case BOOLEAN_ARRAY: return (T) new boolean[] {true, false}; case CHAR_ARRAY: return (T) new char[] {1, 2}; case SHORT_ARRAY: return (T) new short[] {1, 2}; case INT_ARRAY: return (T) new int[] {1, 2}; case LONG_ARRAY: return (T) new long[] {1, 2}; case FLOAT_ARRAY: return (T) new float[] {1, 2}; case DOUBLE_ARRAY: return (T) new double[] {1, 2}; case STRING_ARRAY: return (T) new String[] {"1", "2"}; case OBJECT_ARRAY: return (T) new Object[] {1, 2}; case ARRAY_OF_BYTE_ARRAYS: return (T) arrayOfByteArray; case OBJECT: return (T) "objectValue"; default: throw new IllegalStateException("unhandled fieldType " + fieldType); } } private PdxInstanceFactory setupPdxInstanceFactory(FieldType fieldType) { PdxInstanceFactory factory = mock(PdxInstanceFactory.class); String pdxClassName = "myPdxClassName"; when(cache.createPdxInstanceFactory(pdxClassName)).thenReturn(factory); TypeRegistry pdxTypeRegistry = mock(TypeRegistry.class); when(cache.getPdxRegistry()).thenReturn(pdxTypeRegistry); PdxType pdxType = mock(PdxType.class); when(regionMapping.getPdxName()).thenReturn(pdxClassName); when(pdxTypeRegistry.getPdxTypeForField(PDX_FIELD_NAME_1, pdxClassName)).thenReturn(pdxType); PdxField pdxField = mock(PdxField.class); when(pdxType.getPdxField(PDX_FIELD_NAME_1)).thenReturn(pdxField); when(pdxField.getFieldType()).thenReturn(fieldType); return factory; } private void verifyPdxFactoryWrite(PdxInstanceFactory factory, FieldType fieldType) { verifyPdxFactoryWrite(factory, fieldType, getValueByFieldType(fieldType)); } private void verifyPdxFactoryWrite(PdxInstanceFactory factory, FieldType fieldType, Object value) { switch (fieldType) { case STRING: verify(factory).writeString(PDX_FIELD_NAME_1, (String) value); break; case CHAR: verify(factory).writeChar(PDX_FIELD_NAME_1, value == null ? 0 : (char) value); break; case SHORT: verify(factory).writeShort(PDX_FIELD_NAME_1, value == null ? 0 : (short) value); break; case INT: verify(factory).writeInt(PDX_FIELD_NAME_1, value == null ? 0 : (int) value); break; case LONG: verify(factory).writeLong(PDX_FIELD_NAME_1, value == null ? 0 : (long) value); break; case FLOAT: verify(factory).writeFloat(PDX_FIELD_NAME_1, value == null ? 0 : (float) value); break; case DOUBLE: verify(factory).writeDouble(PDX_FIELD_NAME_1, value == null ? 0 : (double) value); break; case BYTE: verify(factory).writeByte(PDX_FIELD_NAME_1, value == null ? 0 : (byte) value); break; case BOOLEAN: verify(factory).writeBoolean(PDX_FIELD_NAME_1, value == null ? false : (boolean) value); break; case DATE: verify(factory).writeDate(PDX_FIELD_NAME_1, (Date) value); break; case BYTE_ARRAY: verify(factory).writeByteArray(PDX_FIELD_NAME_1, (byte[]) value); break; case BOOLEAN_ARRAY: verify(factory).writeBooleanArray(PDX_FIELD_NAME_1, (boolean[]) value); break; case CHAR_ARRAY: verify(factory).writeCharArray(PDX_FIELD_NAME_1, (char[]) value); break; case SHORT_ARRAY: verify(factory).writeShortArray(PDX_FIELD_NAME_1, (short[]) value); break; case INT_ARRAY: verify(factory).writeIntArray(PDX_FIELD_NAME_1, (int[]) value); break; case LONG_ARRAY: verify(factory).writeLongArray(PDX_FIELD_NAME_1, (long[]) value); break; case FLOAT_ARRAY: verify(factory).writeFloatArray(PDX_FIELD_NAME_1, (float[]) value); break; case DOUBLE_ARRAY: verify(factory).writeDoubleArray(PDX_FIELD_NAME_1, (double[]) value); break; case STRING_ARRAY: verify(factory).writeStringArray(PDX_FIELD_NAME_1, (String[]) value); break; case OBJECT_ARRAY: verify(factory).writeObjectArray(PDX_FIELD_NAME_1, (Object[]) value); break; case ARRAY_OF_BYTE_ARRAYS: verify(factory).writeArrayOfByteArrays(PDX_FIELD_NAME_1, (byte[][]) value); break; case OBJECT: verify(factory).writeObject(PDX_FIELD_NAME_1, value); break; default: throw new IllegalStateException("unhandled fieldType " + fieldType); } } private void setupResultSetForObject(ResultSet result, Object objectToReturn) throws SQLException { ResultSetMetaData metaData = mock(ResultSetMetaData.class); when(result.getMetaData()).thenReturn(metaData); when(metaData.getColumnCount()).thenReturn(2); when(result.getObject(1)).thenReturn(objectToReturn); when(metaData.getColumnName(1)).thenReturn(COLUMN_NAME_1); when(result.getObject(2)).thenReturn(COLUMN_VALUE_2); when(metaData.getColumnName(2)).thenReturn(COLUMN_NAME_2); } } rzwinters/securify_revised /* * Copyright 2018 Secure, Reliable, and Intelligent Systems Lab, ETH Zurich * * 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 ch.securify.decompiler.printer; import ch.securify.decompiler.evm.OpCodes; import ch.securify.decompiler.EvmParser; import java.io.PrintStream; public class Disassembler { /** * Disassemble the bytecode and print the EVM instructions in a readable format. * @param bytecode EVM bytecode. */ public static void disassemble(byte[] bytecode) { disassemble(bytecode, System.out); } /** * Disassemble the bytecode and print the EVM instructions in a readable format. * @param bytecode EVM bytecode. * @param outputStream Stream to print the output to. */ public static void disassemble(byte[] bytecode, PrintStream outputStream) { outputStream.println("-- START"); EvmParser.parse(bytecode, new EvmParser.OnOperationParsedCallback() { int tag = 1; public void onOperationParsed(int offset, int instrNumber, int opcode, byte[] payload) { if (opcode == OpCodes.JUMPDEST) { outputStream.println("-- tag " + tag); tag++; } outputStream.print(String.format("%02X: ", offset)); outputStream.print(String.format("%02X ", opcode)); String opName = OpCodes.getOpName(opcode); if (opName != null) { outputStream.print(opName); if (OpCodes.isPush(opcode) > -1) { outputStream.print(" 0x"); for (byte data : payload) { int val = data & 0xFF; outputStream.print(String.format("%02X", val)); } } outputStream.println(); } else { outputStream.println("unknown operation " + String.format("%02X", opcode)); } } }); outputStream.println("-- EOF"); } } 0 package com.example.yin.domain; import lombok.Data; import lombok.ToString; import org.apache.commons.lang3.builder.ToStringBuilder; import java.util.Date; @Data @ToString public class Singer { private Integer id; private String name; private Byte sex; private String pic; private Date birth; private String location; private String introduction; } /* * 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 tsp; public class TSP { public static void main(String[] args) throws InterruptedException { int i1,i2,igual,Ciudades; int el_mejor,el_mejor_Mejorado,Mejorado; int[] Ciudades1={20,40,60,80,100,200,500}; for(int r=0;r=10;Mejorado--) { for(int e=0;e<10;e++) { int p=8; int lim=100; GenerarProblema auxi=new GenerarProblema(Ciudades,lim); int [][]C=auxi.GetC(); Algoritmo []q=new Algoritmo[p]; for(int i=0;iCostes[i]){max_peor=Costes[i];} } max_mejor=-1; for(i=4;i<8;i++) { Costes=q[i].getCoste(); if(max_mejor==-1 || max_mejor>Costes[i]){max_mejor=Costes[i];} } if(max_peor==max_mejor){igual++;quitar=true;} if(quitar==false){ CosteFinal=-1; for(i=0;iCostes[i]){CosteFinal=Costes[i];aux=i;} } if(aux<=3){i1++;} else{i2++;} } //System.out.println("El mejor ha sido: "+aux); /*int [][]v=q[aux].getk(); System.out.println("La ruta es:"); for (int i=0;ii2){System.out.println("Ha salido victorioso el algoritmo no mejoraso por "+(i1-i2)+" problemas.");}*/ if(i1 { private static final Logger logger = LogManager.getLogger(WebSocketHandler.class); /** * * @param webSocketFrameRequest - WebSocketFrameRequest received from WebSocketFrameRequest * @return WebSocketResponseObject - Response sent via WebSocketFrameService */ @Override public WebSocketThrottleResponse process(WebSocketFrameRequest webSocketFrameRequest) { TracingSpan webSocketHandlerSpan = null; Scope webSocketHandlerSpanScope = null; if (Utils.tracingEnabled()) { TracingTracer tracer = Utils.getGlobalTracer(); webSocketHandlerSpan = Utils.startSpan(TracingConstants.WS_HANDLER_SPAN, tracer); webSocketHandlerSpanScope = webSocketHandlerSpan.getSpan().makeCurrent(); Utils.setTag(webSocketHandlerSpan, APIConstants.LOG_TRACE_ID, ThreadContext.get(APIConstants.LOG_TRACE_ID)); } try { WebSocketAPI matchedAPI = APIFactory.getInstance().getMatchedAPI(webSocketFrameRequest); if (matchedAPI == null) { WebSocketThrottleResponse webSocketThrottleResponse = new WebSocketThrottleResponse(); webSocketThrottleResponse.setUnknownState(); String basePath = webSocketFrameRequest.getMetadata().getExtAuthzMetadataMap() .get(APIConstants.GW_BASE_PATH_PARAM); String version = webSocketFrameRequest.getMetadata().getExtAuthzMetadataMap() .get(APIConstants.GW_VERSION_PARAM); logger.info("API {}/{} not found in the cache", basePath, version); return webSocketThrottleResponse; } else if (logger.isDebugEnabled()) { APIConfig api = matchedAPI.getAPIConfig(); logger.info("API {}/{} found in the cache", api.getBasePath(), api.getVersion()); } RequestContext requestContext = buildRequestContext(matchedAPI, webSocketFrameRequest); return matchedAPI.processFramedata(requestContext); } finally { if (Utils.tracingEnabled()) { webSocketHandlerSpanScope.close(); Utils.finishSpan(webSocketHandlerSpan); } } } /** * @param api - Matched WebSocket API * @param webSocketFrameRequest - WebSocketFrameRequest received from WebSocketFrameRequest * @return RequestContext - Build RequestContext by populating relevant fields from api and webSocketFrameRequest */ private RequestContext buildRequestContext(WebSocketAPI api, WebSocketFrameRequest webSocketFrameRequest) { Map extAuthMetadata = webSocketFrameRequest.getMetadata().getExtAuthzMetadataMap(); // Extracting ext_authz metadata from WebSocketFrameRequest String apiName = extAuthMetadata.get(APIConstants.GW_API_NAME_PARAM); String apiVersion = extAuthMetadata.get(APIConstants.GW_VERSION_PARAM); String apiBasePath = extAuthMetadata.get(APIConstants.GW_BASE_PATH_PARAM); String username = extAuthMetadata.get(MetadataConstants.USERNAME); String appTier = extAuthMetadata.get(MetadataConstants.APP_TIER); String tier = extAuthMetadata.get(MetadataConstants.TIER); boolean isContentAwareTierPresent = Boolean.parseBoolean(extAuthMetadata .get(MetadataConstants.CONTENT_AWARE_TIER_PRESENT)); String apiKey = extAuthMetadata.get(MetadataConstants.API_KEY); String keyType = extAuthMetadata.get(MetadataConstants.KEY_TYPE); String callerToken = extAuthMetadata.get(MetadataConstants.CALLER_TOKEN); int applicationId = -1; if (!StringUtils.isEmpty(extAuthMetadata.get(MetadataConstants.APP_ID))) { applicationId = Integer.parseInt(extAuthMetadata.get(MetadataConstants.APP_ID)); } String applicationName = extAuthMetadata.get(MetadataConstants.APP_NAME); String consumerKey = extAuthMetadata.get(MetadataConstants.CONSUMER_KEY); String subscriber = extAuthMetadata.get(MetadataConstants.SUBSCRIBER); int spikeArrestLimit = Integer.parseInt(extAuthMetadata.get(MetadataConstants.SPIKE_ARREST_LIMIT)); String subscriberTenantDomain = extAuthMetadata.get(MetadataConstants.SUBSCRIBER_TENANT_DOMAIN); String spikeArrestUnit = extAuthMetadata.get(MetadataConstants.SPIKE_ARREST_UNIT); boolean stopOnQuota = Boolean.parseBoolean(extAuthMetadata.get(MetadataConstants.STOP_ON_QUOTA)); String productName = extAuthMetadata.get(MetadataConstants.PRODUCT_NAME); String productProvider = extAuthMetadata.get(MetadataConstants.PRODUCT_PROVIDER); String apiPublisher = extAuthMetadata.get(MetadataConstants.API_PUBLISHER); String requestId = extAuthMetadata.get(MetadataConstants.REQUEST_ID); // Extracting mgw_wasm_websocket filter metadata int frameLength = webSocketFrameRequest.getFrameLength(); String remoteIp = webSocketFrameRequest.getRemoteIp(); String streamId = extAuthMetadata.get(MetadataConstants.GRPC_STREAM_ID); WebSocketFrameContext webSocketFrameContext = new WebSocketFrameContext(streamId, frameLength, remoteIp); AuthenticationContext authenticationContext = new AuthenticationContext(); authenticationContext.setApiName(apiName); authenticationContext.setApiVersion(apiVersion); authenticationContext.setUsername(username); authenticationContext.setApplicationTier(appTier); authenticationContext.setTier(tier); authenticationContext.setIsContentAware(isContentAwareTierPresent); authenticationContext.setApiKey(apiKey); authenticationContext.setKeyType(keyType); authenticationContext.setCallerToken(callerToken); authenticationContext.setApplicationId(applicationId); authenticationContext.setApplicationName(applicationName); authenticationContext.setConsumerKey(consumerKey); authenticationContext.setSubscriber(subscriber); authenticationContext.setSpikeArrestLimit(spikeArrestLimit); authenticationContext.setSubscriberTenantDomain(subscriberTenantDomain); authenticationContext.setSpikeArrestUnit(spikeArrestUnit); authenticationContext.setStopOnQuotaReach(stopOnQuota); authenticationContext.setProductName(productName); authenticationContext.setProductProvider(productProvider); authenticationContext.setApiPublisher(apiPublisher); return new RequestContext.Builder(apiBasePath).authenticationContext(authenticationContext). webSocketFrameContext(webSocketFrameContext).matchedAPI(api.getAPIConfig()) .requestID(requestId).address(extractIpAddress(remoteIp)).build(); } private String extractIpAddress(String remoteIpStringWithPort) { try { URI uri = new URI("ws://" + remoteIpStringWithPort); return uri.getHost(); } catch (URISyntaxException e) { logger.error(e); return null; } } } package myfirstproject.demo.exception; public class EmployerNotFoundException { } Hulva/kjm package luva.xx.kafka.kjm.db.processor; /** * @author * @date 2019年2月23日 * @description * */ public interface StateRestoreListener { /** * Method called at the very beginning of {@link StateStore} restoration. * * @param topicPartition the TopicPartition containing the values to restore * @param storeName the name of the store undergoing restoration * @param startingOffset the starting offset of the entire restoration process * for this TopicPartition * @param endingOffset the exclusive ending offset of the entire restoration * process for this TopicPartition */ void onRestoreStart(final T topicPartition, final String storeName, final long startingOffset, final long endingOffset); /** * Method called after restoring a batch of records. In this case the maximum * size of the batch is whatever the value of the MAX_POLL_RECORDS is set to. * * This method is called after restoring each batch and it is advised to keep * processing to a minimum. Any heavy processing will hold up recovering the * next batch, hence slowing down the restore process as a whole. * * If you need to do any extended processing or connecting to an external * service consider doing so asynchronously. * * @param topicPartition the TopicPartition containing the values to restore * @param storeName the name of the store undergoing restoration * @param batchEndOffset the inclusive ending offset for the current restored * batch for this TopicPartition * @param numRestored the total number of records restored in this batch for * this TopicPartition */ void onBatchRestored(final T topicPartition, final String storeName, final long batchEndOffset, final long numRestored); /** * Method called when restoring the {@link StateStore} is complete. * * @param topicPartition the TopicPartition containing the values to restore * @param storeName the name of the store just restored * @param totalRestored the total number of records restored for this * TopicPartition */ void onRestoreEnd(final T topicPartition, final String storeName, final long totalRestored); } cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/query/ChildrenQueryNode.java /* * Copyright © 2017 IBM Corp. All rights reserved. * * Copyright © 2014 Cloudant, Inc. 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 com.cloudant.sync.internal.query; import java.util.ArrayList; import java.util.List; /** * A ChildrenQueryNode object represents a tree node that is not a leaf, * specialized further in subclasses. */ class ChildrenQueryNode implements QueryNode { public List children; ChildrenQueryNode() { children = new ArrayList(); } } /** * Copyright (c) 2015 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.sail.lucene.fn; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.eclipse.rdf4j.common.iteration.CloseableIteration; import org.eclipse.rdf4j.common.iteration.CloseableIteratorIteration; import org.eclipse.rdf4j.common.iteration.ConvertingIteration; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Resource; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryEvaluationException; import org.eclipse.rdf4j.query.algebra.Var; import org.eclipse.rdf4j.query.algebra.evaluation.QueryContext; import org.eclipse.rdf4j.query.algebra.evaluation.function.TupleFunction; import org.eclipse.rdf4j.sail.lucene.DistanceQuerySpec; import org.eclipse.rdf4j.sail.lucene.LuceneSailSchema; import org.eclipse.rdf4j.sail.lucene.SearchIndex; import org.eclipse.rdf4j.sail.lucene.SearchIndexQueryContextInitializer; import org.eclipse.rdf4j.sail.lucene.SearchQueryEvaluator; /** * Arguments: *
    *
  1. from is the WKT point to measure from.
  2. *
  3. maxDistance is the maximum distance to consider.
  4. *
  5. units are the measurement units.
  6. *
  7. geoProperty is the predicate to use.
  8. *
  9. search:distance else omitted.
  10. *
  11. search:context else omitted.
  12. *
* Results: *
    *
  1. subject is the subject whose geometry is within the given max distance.
  2. *
  3. to is the WKT of the shape measured to.
  4. *
  5. distance is the distance to the shape if search:distance is present.
  6. *
  7. context is the context if search:context is present.
  8. *
* * @deprecated since 3.0. The LuceneSpinSail is to removed in the next major release. */ @Deprecated public class DistanceTupleFunction implements TupleFunction { @Override public String getURI() { return LuceneSailSchema.WITHIN_DISTANCE.toString(); } @Override public CloseableIteration, QueryEvaluationException> evaluate( ValueFactory valueFactory, Value... args) throws QueryEvaluationException { int i = 0; Literal from = (Literal) args[i++]; Literal maxDist = (Literal) args[i++]; IRI units = (IRI) args[i++]; IRI geoProperty = (IRI) args[i++]; String geoVar = "geometry"; String subjectVar = "subject"; String distanceVar = null; if (args.length - i > 0 && LuceneSailSchema.DISTANCE.equals(args[i])) { distanceVar = "distance"; i++; } Var contextVar = null; if (args.length - i > 0) { contextVar = new Var("context"); Resource context = (Resource) args[i]; if (!LuceneSailSchema.CONTEXT.equals(context)) { contextVar.setValue(context); } } final DistanceQuerySpec query = new DistanceQuerySpec(from, units, maxDist.doubleValue(), distanceVar, geoProperty, geoVar, subjectVar, contextVar); SearchIndex luceneIndex = SearchIndexQueryContextInitializer.getSearchIndex(QueryContext.getQueryContext()); Collection results = luceneIndex.evaluate((SearchQueryEvaluator) query); return new ConvertingIteration, QueryEvaluationException>( new CloseableIteratorIteration<>(results.iterator())) { @Override protected List convert(BindingSet bindings) throws QueryEvaluationException { List results = new ArrayList<>(3); if (query.getSubjectVar() != null) { results.add(bindings.getValue(query.getSubjectVar())); } if (query.getGeoVar() != null) { results.add(bindings.getValue(query.getGeoVar())); } if (query.getDistanceVar() != null) { results.add(bindings.getValue(query.getDistanceVar())); } if (query.getContextVar() != null) { results.add(bindings.getValue(query.getContextVar().getName())); } return results; } }; } } package com.aferidor.view; import android.app.Activity; import android.hardware.Sensor; import android.hardware.SensorManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.TextView; import com.aferidor.control.ControlSensorEvent; import com.aferidor.control.ControlSerialManagemant; import com.aferidor.R; import com.aferidor.control.ControlServerStartStop; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class MainActivity extends Activity { private ControlSerialManagemant controlSerialManagemant; private ControlSensorEvent controlSensorEvent; private SensorManager sensorManager; private TextView textView_serverStatus, textView_serverIP, textView_angleXValue, textView_angleYValue; private Button button_serverStartStop; private int direction; private boolean dataSave, sendStatus; private String ipSendStatus; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.direction = 11; this.dataSave = false; this.sendStatus = false; this.ipSendStatus = null; this.sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); this.controlSerialManagemant = new ControlSerialManagemant(this); this.controlSensorEvent = new ControlSensorEvent(this); this.textView_serverStatus = (TextView) findViewById(R.id.textView_serverStatus); this.textView_serverIP = (TextView) findViewById(R.id.textView_severIP); this.textView_serverIP.setText("IP: " + getIp()); this.textView_angleXValue = (TextView) findViewById(R.id.textView_angleXValue); this.textView_angleYValue = (TextView) findViewById(R.id.textView_angleYValue); this.button_serverStartStop = (Button) findViewById(R.id.button_serverStartStop); this.button_serverStartStop.setOnClickListener(new ControlServerStartStop(this)); } @Override protected void onResume() { super.onResume(); this.controlSerialManagemant.openUSBConnection(); this.controlSerialManagemant.startUSBConnection(); } @Override protected void onPause() { super.onPause(); this.controlSerialManagemant.closeUSBConnection(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public TextView getTextView_serverStatus() { return this.textView_serverStatus; } public TextView getTextView_angleXValue() { return textView_angleXValue; } public int getDirection() { return direction; } public void setDirection(int direction) { this.direction = direction; } public void setDataSave(boolean dataSave) { this.dataSave = dataSave; } public boolean isDataSave() { return dataSave; } public boolean isSendStatus() { return sendStatus; } public void setSendStatus(boolean sendStatus) { this.sendStatus = sendStatus; } public TextView getTextView_angleYValue() { return textView_angleYValue; } public Button getButton_serverStartStop() { return button_serverStartStop; } public String getIpSendStatus() { return ipSendStatus; } public void setIpSendStatus(String ipSendStatus) { this.ipSendStatus = ipSendStatus; } public void registerSensorManager() { sensorManager.registerListener(controlSensorEvent, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST); } public void unregisterSensorManager() { sensorManager.unregisterListener(controlSensorEvent); } public String getIp() { String ipAddress = null; Enumeration net = null; try { net = NetworkInterface.getNetworkInterfaces(); } catch (SocketException e) { throw new RuntimeException(e); } while (net.hasMoreElements()) { NetworkInterface element = net.nextElement(); Enumeration addresses = element.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress ip = addresses.nextElement(); if (ip.isSiteLocalAddress()) { ipAddress = ip.getHostAddress(); } } } return ipAddress; } } macorapci/CuriousAboutCoding public class Main014 { public static void main(String... args) { var array = new String[5][5]; Object[] objArray = array; System.out.println("Compiled!"); } } Dennis-Koch/ambethjambeth/jambeth-cache/src/main/java/com/koch/ambeth/cache/mixin/IPropertyChangeItemListenerExtendable.java0 package com.koch.ambeth.cache.mixin; public interface IPropertyChangeItemListenerExtendable { void registerIPropertyChangeItemListener(IPropertyChangeItemListener propertyChangeItemListener); void unregisterIPropertyChangeItemListener( IPropertyChangeItemListener propertyChangeItemListener); } src/main/java/org/java_websocket/util/ByteBufferUtils.java /* * Copyright (c) 2010-2017 * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.java_websocket.util; import java.nio.ByteBuffer; /** * Utility class for ByteBuffers */ public class ByteBufferUtils { /** * Private constructor for static class */ private ByteBufferUtils() { } /** * Transfer from one ByteBuffer to another ByteBuffer * * @param source the ByteBuffer to copy from * @param dest the ByteBuffer to copy to * @return the number of transferred bytes */ public static int transferByteBuffer( ByteBuffer source, ByteBuffer dest ) { if( source == null || dest == null ) { throw new IllegalArgumentException(); } int fremain = source.remaining(); int toremain = dest.remaining(); if( fremain > toremain ) { int limit = Math.min( fremain, toremain ); source.limit( limit ); dest.put( source ); return limit; } else { dest.put( source ); return fremain; } } /** * Get a ByteBuffer with zero capacity * * @return empty ByteBuffer */ public static ByteBuffer getEmptyByteBuffer() { return ByteBuffer.allocate( 0 ); } } package com.amazonaws.http.comment; public class DeleteCommentResponse { private int statusCode; private String statusMessage; public DeleteCommentResponse(int sc, String sm) { this.statusCode = sc; this.statusMessage = sm; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public String getStatusMessage() { return statusMessage; } public void setStatusMessage(String statusMessage) { this.statusMessage = statusMessage; } public String toString() { return "DeleteComentResponse(" + this.statusCode + ", " + this.statusMessage + ")"; } } package org.broadinstitute.hellbender.tools.walkers.mutect.Mutect2Acc; import htsjdk.samtools.SAMFileHeader; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.vcf.VCFEncoder; import htsjdk.variant.vcf.VCFHeader; import org.broadinstitute.hellbender.cmdline.CommandLineProgram; import org.broadinstitute.hellbender.cmdline.argumentcollections.ReferenceInputArgumentCollection; import org.broadinstitute.hellbender.engine.*; import org.broadinstitute.hellbender.tools.walkers.annotator.Annotation; import org.broadinstitute.hellbender.tools.walkers.annotator.VariantAnnotatorEngine; import org.broadinstitute.hellbender.tools.walkers.haplotypecaller.AssemblyBasedCallerUtils; import org.broadinstitute.hellbender.tools.walkers.haplotypecaller.AssemblyResultSet; import org.broadinstitute.hellbender.tools.walkers.haplotypecaller.HaplotypeCallerGenotypingEngine; import org.broadinstitute.hellbender.tools.walkers.mutect.M2ArgumentCollection; import org.broadinstitute.hellbender.tools.walkers.mutect.SomaticGenotypingEngine; import org.broadinstitute.hellbender.utils.genotyper.ReadLikelihoods; import org.broadinstitute.hellbender.utils.genotyper.SampleList; import org.broadinstitute.hellbender.utils.haplotype.Haplotype; import org.broadinstitute.hellbender.utils.read.GATKRead; import org.broadinstitute.hellbender.utils.smithwaterman.SmithWatermanAligner; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; public class GenotypingRunnable implements Runnable { private final MonitorRunnable monitor; private final CommandLineProgram instance; private final M2ArgumentCollection MTAC; private final ReferenceInputArgumentCollection referenceArguments; private final int cloudPrefetchBuffer; private final int cloudIndexPrefetchBuffer; private final SampleList samplesList; private final String tumorSample; private final String normalSample; private final SAMFileHeader header; private ReferenceDataSource reference; private FeatureManager features; private SmithWatermanAligner aligner; private VariantAnnotatorEngine annotatorEngine; private SomaticGenotypingEngine genotypingEngine; private VCFEncoder vcfEncoder; GenotypingRunnable ( final MonitorRunnable monitor, final CommandLineProgram instance, final M2ArgumentCollection MTAC, final ReferenceInputArgumentCollection referenceArguments, final int cloudPrefetchBuffer, final int cloudIndexPrefetchBuffer, final SampleList samplesList, final String tumorSample, final String normalSample, final Collection annotations, final SAMFileHeader header, final VCFHeader vcfHeader, final boolean allowMissingFieldsInHeader ) { this.monitor = monitor; this.instance = instance; this.MTAC = MTAC; this.referenceArguments = referenceArguments; this.cloudPrefetchBuffer = cloudPrefetchBuffer; this.cloudIndexPrefetchBuffer = cloudIndexPrefetchBuffer; this.samplesList = samplesList; this.tumorSample = tumorSample; this.normalSample = normalSample; this.header = header; reference = Mutect2Acc.LocalInitializeReference(referenceArguments); features = Mutect2Acc.LocalInitializeFeatures(instance, referenceArguments, cloudPrefetchBuffer, cloudIndexPrefetchBuffer); aligner = SmithWatermanAligner.getAligner(MTAC.smithWatermanImplementation); annotatorEngine = new VariantAnnotatorEngine(annotations, null, Collections.emptyList(), false); genotypingEngine = new SomaticGenotypingEngine(samplesList, MTAC, tumorSample, normalSample); genotypingEngine.setAnnotationEngine(annotatorEngine); vcfEncoder = new VCFEncoder(vcfHeader, allowMissingFieldsInHeader, false); } public void run () { monitor.numInitializedThreadsForGenotyping.incrementAndGet(); monitor.genotypingRunnableLock.lock(); monitor.numRemainedThreadsForGenotyping.incrementAndGet(); monitor.genotypingRunnableLock.unlock(); monitor.runnableIsStarted = true; while (true) { AssemblyResultSet assemblyResult = monitor.pairHMMResultQueue.poll(); if (assemblyResult == null) { if (monitor.vectorLogessPairHMMWorkDone && monitor.numRemainedThreadsForLoglessPairHMM.get()<=0) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { } continue; } List variants = doWork ( assemblyResult, new ReferenceContext(reference, assemblyResult.extendedSpan), new FeatureContext(features, assemblyResult.extendedSpan) ); monitor.numActiveRegionAddressedByGenotyping.incrementAndGet(); if (variants == null) { continue; } ActiveRegionVariantSet set = new ActiveRegionVariantSet( variants, assemblyResult.tid, assemblyResult.regionStart, assemblyResult.regionEnd ); while (!monitor.variantSetQueue.offer(set)) { try { Thread.sleep(1); } catch (InterruptedException e) { } } assemblyResult = null; if (monitor.tooManyEnginesForGenotyping && monitor.genotypingRunnableLock.tryLock()) { if (monitor.tooManyEnginesForGenotyping) { monitor.tooManyEnginesForGenotyping = false; monitor.genotypingRunnableLock.unlock(); break; } monitor.genotypingRunnableLock.unlock(); } } monitor.genotypingRunnableLock.lock(); monitor.numRemainedThreadsForGenotyping.decrementAndGet(); monitor.genotypingRunnableLock.unlock(); } private List doWork ( final AssemblyResultSet assemblyResult, final ReferenceContext referenceContext, final FeatureContext featureContext ) { ReadLikelihoods readLikelihoods = assemblyResult.readLikelihoods; final AssemblyRegion regionForGenotyping = assemblyResult.getRegionForGenotyping(); final Map readRealignments = AssemblyBasedCallerUtils.realignReadsToTheirBestHaplotype( readLikelihoods, assemblyResult.getReferenceHaplotype(), assemblyResult.getPaddedReferenceLoc(), aligner ); readLikelihoods.changeReads(readRealignments); final HaplotypeCallerGenotypingEngine.CalledHaplotypes calledHaplotypes = genotypingEngine.callMutations( readLikelihoods, assemblyResult, referenceContext, regionForGenotyping.getSpan(), featureContext, assemblyResult.givenAlleles, header ); List variants = calledHaplotypes.getCalls(); if (variants.size() <= 0) { return null; } for (final VariantContext var : variants) { var.dumpString = vcfEncoder.encode(var); } return variants; } } package com.krupalshah.observablecollections; import com.krupalshah.observablecollections.change.Change; import com.krupalshah.observablecollections.change.Insertion; import com.krupalshah.observablecollections.change.Removal; import java.util.Collection; import java.util.Collections; import java.util.NoSuchElementException; import java.util.Queue; import io.reactivex.annotations.NonNull; import io.reactivex.subjects.Subject; /** * Created on 17-Dec-17. */ public class ObservableQueue extends ObservableCollection implements Queue { protected ObservableQueue(@NonNull Queue collection) { super(collection); } protected ObservableQueue(@NonNull Queue collection, @NonNull Subject subject) { super(collection, subject); } //region custom implementation @Override public boolean offer(E element) { Collection original = Collections.unmodifiableCollection(items()); boolean changed; try { changed = items().offer(element); } catch (IllegalArgumentException | ClassCastException | NullPointerException e) { changed = false; subject().onError(e); } if (changed) { Collection inserted = Collections.singleton(element); Change, Collection> change = new Insertion<>( this, original, inserted ); subject().onNext(change); } return changed; } @Override public E remove() { Collection original = Collections.unmodifiableCollection(items()); try { E head = items().remove(); Collection removed = Collections.singleton(head); Change, Collection> change = new Removal<>( this, original, removed ); subject().onNext(change); return head; } catch (NoSuchElementException e) { subject().onError(e); return null; } } @Override public E poll() { Collection original = Collections.unmodifiableCollection(items()); E head = items().poll(); if (head != null) { Collection removed = Collections.singleton(head); Change, Collection> change = new Removal<>( this, original, removed ); subject().onNext(change); } return head; } //endregion //region delegate only @Override public E element() { return items().element(); } @Override public E peek() { return items().peek(); } //endregion @Override public Queue items() { return (Queue) super.items(); } @Override public String toString() { return items().toString(); } } /** * */ package no.sintef.model; import no.sintef.fates.io.BinaryFileDAO.Sizes; /** * @author ubr */ public class ResponseUnit { private int responseType; private int xref; private float shiplat; private float shiplon; private int responseStatus; private float shiplat2; private float shiplon2; private float acumulatedMass; public static int SIZE = 3 * Sizes.INT_FIELD_SIZE + 5 * Sizes.FLOAT_FIELD_SIZE; /*********************************************************************************************/ /** * @return the responseType */ public int getResponseType() { return responseType; } /** * @param responseType * the responseType to set */ public void setResponseType(int responseType) { this.responseType = responseType; } /** * @return the xref */ public int getXref() { return xref; } /** * @param xref * the xref to set */ public void setXref(int xref) { this.xref = xref; } /** * @return the shiplat */ public float getShiplat() { return shiplat; } /** * @param shiplat * the shiplat to set */ public void setShiplat(float shiplat) { this.shiplat = shiplat; } /** * @return the shiplon */ public float getShiplon() { return shiplon; } /** * @param shiplon * the shiplon to set */ public void setShiplon(float shiplon) { this.shiplon = shiplon; } /** * @return the responseStatus */ public int getResponseStatus() { return responseStatus; } /** * @param responseStatus * the responseStatus to set */ public void setResponseStatus(int responseStatus) { this.responseStatus = responseStatus; } /** * @return the shiplat2 */ public float getShiplat2() { return shiplat2; } /** * @param shiplat2 * the shiplat2 to set */ public void setShiplat2(float shiplat2) { this.shiplat2 = shiplat2; } /** * @return the shiplon2 */ public float getShiplon2() { return shiplon2; } /** * @param shiplon2 * the shiplon2 to set */ public void setShiplon2(float shiplon2) { this.shiplon2 = shiplon2; } /** * @return the acumulatedMass */ public float getAcumulatedMass() { return acumulatedMass; } /** * @param acumulatedMass * the acumulatedMass to set */ public void setAcumulatedMass(float acumulatedMass) { this.acumulatedMass = acumulatedMass; } }shaowei-su/shaowei-su.github.io /* * [139] Word Break * * https://leetcode.com/problems/word-break/description/ * * algorithms * Medium (32.76%) * Total Accepted: 254.3K * Total Submissions: 776.3K * Testcase Example: '"leetcode"\n["leet","code"]' * * Given a non-empty string s and a dictionary wordDict containing a list of * non-empty words, determine if s can be segmented into a space-separated * sequence of one or more dictionary words. * * Note: * * * The same word in the dictionary may be reused multiple times in the * segmentation. * You may assume the dictionary does not contain duplicate words. * * * Example 1: * * * Input: s = "leetcode", wordDict = ["leet", "code"] * Output: true * Explanation: Return true because "leetcode" can be segmented as "leet * code". * * * Example 2: * * * Input: s = "applepenapple", wordDict = ["apple", "pen"] * Output: true * Explanation: Return true because "applepenapple" can be segmented as "apple * pen apple". * Note that you are allowed to reuse a dictionary word. * * * Example 3: * * * Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] * Output: false * * */ class Solution { Set set; public boolean wordBreak(String s, List wordDict) { boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for (int i = 1; i <= s.length(); i++) { for (String word : wordDict) { if (i - word.length() >= 0 && dp[i - word.length()] && s.substring(i - word.length(), i).equals(word)) { dp[i] = true; continue; } } } return dp[s.length()]; } public boolean wordBreak3(String s, List wordDict) { set = new HashSet<>(wordDict); return wordBreakS(s); } public boolean wordBreakS(String s) { if (s.length() == 0) { return true; } for (int i = 1; i <= s.length(); i++) { if (set.contains(s.substring(0, i)) && wordBreakS(s.substring(i))) { return true; } } return false; } public boolean wordBreak2(String s, List wordDict) { return dfs(s, "", wordDict); } public boolean dfs(String s, String cur, List wordDict) { if (s.equals(cur)) { return true; } if (cur.length() >= s.length()) { return false; } for (String word : wordDict) { if (s.contains(word) && s.startsWith(cur + word) && dfs(s, cur + word, wordDict)) { return true; } } return false; } } fuatbakkal/hms-cordova-plugin /* Copyright 2020. Huawei Technologies Co., Ltd. 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 com.huawei.hms.cordova.mlkit.translate; import android.util.Log; import com.huawei.hmf.tasks.OnFailureListener; import com.huawei.hmf.tasks.OnSuccessListener; import com.huawei.hmf.tasks.Task; import com.huawei.hms.cordova.mlkit.utils.HMSMLUtils; import com.huawei.hms.mlsdk.langdetect.MLDetectedLang; import com.huawei.hms.mlsdk.langdetect.MLLangDetectorFactory; import com.huawei.hms.mlsdk.langdetect.cloud.MLRemoteLangDetector; import com.huawei.hms.mlsdk.langdetect.cloud.MLRemoteLangDetectorSetting; import com.huawei.hms.mlsdk.translate.MLTranslatorFactory; import com.huawei.hms.mlsdk.translate.cloud.MLRemoteTranslateSetting; import com.huawei.hms.mlsdk.translate.cloud.MLRemoteTranslator; import org.apache.cordova.CallbackContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.List; public class Translator { private String TAG = Translator.class.getSimpleName(); private MLRemoteTranslator translator; public void remoteTranslator(JSONObject params, CallbackContext callbackContext) throws JSONException { String targetLangCode; String sourceLangCode; String sourceText; if (!params.has("targetLangCode") || params.isNull("targetLangCode")) { Log.e(TAG, "Illegal argument. targetLangCode field is mandatory and it must not be null."); callbackContext.error("Illegal argument. targetLangCode field is mandatory and it must not be null."); return; } if (!params.has("sourceText") || params.isNull("sourceText")) { Log.e(TAG, "Illegal argument. sourceText field is mandatory and it must not be null."); callbackContext.error("Illegal argument. sourceText field is mandatory and it must not be null."); return; } targetLangCode = params.getString("targetLangCode"); sourceLangCode = params.optString("sourceLangCode", null); sourceText = params.getString("sourceText"); MLRemoteTranslateSetting setting = new MLRemoteTranslateSetting.Factory().setTargetLangCode(targetLangCode).setSourceLangCode(sourceLangCode).create(); Log.i(TAG, "remoteTranslatorTranslateSetting: " + setting.getSourceLangCode() + " " + setting.getTargetLangCode()); translator = MLTranslatorFactory.getInstance().getRemoteTranslator(setting); Task task = translator.asyncTranslate(sourceText); task.addOnSuccessListener(text -> callbackContext.success(text)) .addOnFailureListener(e -> callbackContext.error(e.getMessage())); } public void stopTranslatorService(CallbackContext callbackContext) { if (translator != null) { try { translator.stop(); translator = null; callbackContext.success("Translator is successfully closed."); } catch (Exception e) { callbackContext.error(e.getMessage()); } } } } reltreug/mesh package com.gentics.mesh.core.data.node.field.impl; import static com.gentics.mesh.core.rest.error.Errors.error; import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST; import java.util.Arrays; import java.util.Objects; import com.gentics.mesh.context.BulkActionContext; import com.gentics.mesh.core.data.ContainerType; import com.gentics.mesh.core.data.GraphFieldContainer; import com.gentics.mesh.core.data.Project; import com.gentics.mesh.core.data.node.field.AbstractBasicField; import com.gentics.mesh.core.data.node.field.FieldGetter; import com.gentics.mesh.core.data.node.field.FieldTransformer; import com.gentics.mesh.core.data.node.field.FieldUpdater; import com.gentics.mesh.core.data.node.field.GraphField; import com.gentics.mesh.core.data.node.field.StringGraphField; import com.gentics.mesh.core.rest.node.field.StringField; import com.gentics.mesh.core.rest.node.field.impl.StringFieldImpl; import com.gentics.mesh.core.rest.schema.StringFieldSchema; import com.gentics.mesh.dagger.MeshInternal; import com.gentics.mesh.handler.ActionContext; import com.gentics.mesh.parameter.LinkType; import com.syncleus.ferma.AbstractVertexFrame; public class StringGraphFieldImpl extends AbstractBasicField implements StringGraphField { public static FieldTransformer STRING_TRANSFORMER = (container, ac, fieldKey, fieldSchema, languageTags, level, parentNode) -> { // TODO validate found fields has same type as schema // StringGraphField graphStringField = new com.gentics.mesh.core.data.node.field.impl.basic.StringGraphFieldImpl( // fieldKey, this); StringGraphField graphStringField = container.getString(fieldKey); if (graphStringField == null) { return null; } else { StringField field = graphStringField.transformToRest(ac); if (ac.getNodeParameters().getResolveLinks() != LinkType.OFF) { Project project = ac.getProject(); if (project == null) { project = parentNode.get().getProject(); } field.setString(MeshInternal.get().webRootLinkReplacer().replace(ac, ac.getBranch().getUuid(), ContainerType.forVersion(ac.getVersioningParameters().getVersion()), field.getString(), ac.getNodeParameters().getResolveLinks(), project.getName(), languageTags)); } return field; } }; public static FieldUpdater STRING_UPDATER = (container, ac, fieldMap, fieldKey, fieldSchema, schema) -> { StringField stringField = fieldMap.getStringField(fieldKey); StringGraphField graphStringField = container.getString(fieldKey); boolean isStringFieldSetToNull = fieldMap.hasField(fieldKey) && (stringField == null || stringField.getString() == null); GraphField.failOnDeletionOfRequiredField(graphStringField, isStringFieldSetToNull, fieldSchema, fieldKey, schema); boolean restIsNullOrEmpty = stringField == null || stringField.getString() == null; // Skip this check for no migrations if (!ac.isMigrationContext()) { GraphField.failOnMissingRequiredField(graphStringField, restIsNullOrEmpty, fieldSchema, fieldKey, schema); } // Handle Deletion if (isStringFieldSetToNull && graphStringField != null) { graphStringField.removeField(container); return; } // Rest model is empty or null - Abort if (restIsNullOrEmpty) { return; } // check value restrictions StringFieldSchema stringFieldSchema = (StringFieldSchema) fieldSchema; if (stringFieldSchema.getAllowedValues() != null) { if (stringField.getString() != null && !Arrays.asList(stringFieldSchema.getAllowedValues()).contains(stringField.getString())) { throw error(BAD_REQUEST, "node_error_invalid_string_field_value", fieldKey, stringField.getString()); } } // Handle Update / Create if (graphStringField == null) { graphStringField = container.createString(fieldKey); } graphStringField.setString(stringField.getString()); }; public static FieldGetter STRING_GETTER = (container, fieldSchema) -> { return container.getString(fieldSchema.getName()); }; public StringGraphFieldImpl(String fieldKey, AbstractVertexFrame parentContainer) { super(fieldKey, parentContainer); } @Override public void setString(String string) { setFieldProperty("string", string); } @Override public String getString() { return getFieldProperty("string"); } @Override public String getDisplayName() { return getString(); } @Override public StringField transformToRest(ActionContext ac) { StringFieldImpl stringField = new StringFieldImpl(); String text = getString(); stringField.setString(text == null ? "" : text); return stringField; } @Override public void removeField(BulkActionContext bac, GraphFieldContainer container) { setFieldProperty("string", null); setFieldKey(null); } @Override public GraphField cloneTo(GraphFieldContainer container) { StringGraphField clone = container.createString(getFieldKey()); clone.setString(getString()); return clone; } @Override public boolean equals(Object obj) { if (obj instanceof StringGraphField) { String valueA = getString(); String valueB = ((StringGraphField) obj).getString(); return Objects.equals(valueA, valueB); } if (obj instanceof StringField) { String valueA = getString(); String valueB = ((StringField) obj).getString(); return Objects.equals(valueA, valueB); } return false; } } package io.spring2go.promdemo.instrument; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; import io.prometheus.client.Gauge; /** * 作业队列 * 已被Prometheus度量 */ public class JobQueue { private final Gauge jobQueueSize = Gauge.build() .name("job_queue_size") .help("Current number of jobs waiting in queue") .register(); private Queue queue = new LinkedBlockingQueue(); public int size() { return queue.size(); } public void push(Job job) { queue.offer(job); jobQueueSize.inc(); } public Job pull() { Job job = queue.poll(); if (job != null) { jobQueueSize.dec(); } return job; } } package com.trade.stock.auth.service; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.trade.stock.auth.bo.TradeUser; import com.trade.stock.auth.mapper.TradeUserMapper; import com.trade.stock.auth.oauth.OAuth2TradeUser; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; /** * @author yuelimin * @version 1.0.0 * @since 11 */ @Log4j2 @Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private TradeUserMapper tradeUserMapper; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { TradeUser tradeUser = tradeUserMapper.selectOne(new LambdaQueryWrapper().eq(TradeUser::getUserNo, s)); if (tradeUser == null) { log.info("用户编号: {} 不存在", s); throw new UsernameNotFoundException("用户不存在"); } return new OAuth2TradeUser(tradeUser); } } package magicbees.util; import forestry.api.apiculture.IAlleleBeeSpecies; import forestry.api.genetics.IAllele; import forestry.apiculture.genetics.BeeMutation; /** * Created by Elec332 on 5-1-2020 */ public class MagicBeesMutationBuilder extends BeeMutation { public MagicBeesMutationBuilder(IAlleleBeeSpecies bee0, IAlleleBeeSpecies bee1, IAllele[] result, int chance) { super(bee0, bee1, result, chance); } public MagicBeesMutationBuilder requireResource(EnumOreResourceType ore) { super.requireResource(ore.getBlockName()); return this; } } package in.minewave.janusvideoroom.Janus.PeerConnectionParameters; import android.app.Activity; public class PeerConnectionCameraParameters extends PeerConnectionParameters { public PeerConnectionCameraParameters(String janus_web_socket_uri, Activity activity, int videoWidth, int videoHeight, int videoFps, String videoCodec, VideoCapturerType capturerType, int audioStartBitrate, String audioCodec, boolean noAudioProcessing) { super(janus_web_socket_uri, activity, videoWidth, videoHeight, videoFps, videoCodec, capturerType, audioStartBitrate, audioCodec, noAudioProcessing); } } /** * */ package io.proximax.proximity.rest.v1; import java.io.IOException; import java.net.URI; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import javax.ws.rs.core.UriBuilder; import org.apache.shiro.web.jaxrs.ShiroAnnotationFilterFeature; import org.apache.shiro.web.jaxrs.SubjectPrincipalRequestFilter; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.server.ResourceConfig; import io.proximax.proximity.exception.ProximityExceptionMapper; import io.proximax.proximity.rest.v1.resources.AccountResource; import io.proximax.proximity.rest.v1.resources.DriveResource; import io.proximax.proximity.util.AuthenticatedDriveFactory; import io.proximax.proximity.util.StorageApiFactory; /** * @author tono * */ @ApplicationPath("/api/v1") public class ProximityApp extends Application { @Override public Set> getClasses() { Set> classes = new HashSet<>(); // add mapper for proximity exceptions classes.add(ProximityExceptionMapper.class); // add shiro security classes.add(SubjectPrincipalRequestFilter.class); classes.add(ShiroAnnotationFilterFeature.class); // add resources classes.add(AccountResource.class); classes.add(DriveResource.class); // return the classes return classes; } @Override public Set getSingletons() { Set singletons = new HashSet<>(); // add app specific singleton binders singletons.add(new StorageApiFactory.Binder()); singletons.add(new AuthenticatedDriveFactory.Binder()); return singletons; } @Override public Map getProperties() { return super.getProperties(); } /** * run the app from command line * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { URI baseUri = UriBuilder.fromUri("http://localhost/proximity").port(8080).build(); ResourceConfig resConfig = new ResourceConfig(ProximityApp.class); GrizzlyHttpServerFactory.createHttpServer(baseUri, resConfig); } } src/main/java/leetcode/Problem1324.java package leetcode; import java.util.ArrayList; import java.util.List; /** * https://leetcode.com/problems/print-words-vertically/ */ public class Problem1324 { public List printVertically(String s) { String[] words = s.split(" "); int maxLength = 0; for (String word : words) { maxLength = Math.max(maxLength, word.length()); } List answer = new ArrayList<>(); for (int i = 0; i < maxLength; i++) { String str = ""; for (String word : words) { if (i >= word.length()) { str += " "; } else { str += word.charAt(i); } } answer.add(str.replaceFirst("\\s++$", "")); } return answer; } } package org.jetbrains.modelToText; /** * @author <>; google.com/+MatejKripner */ public class UserInput { private final String extension; private final String destFolder; public UserInput(String extension, String destFolder) { this.extension = extension; this.destFolder = destFolder; } public String getExtension() { return extension; } public String getDestFolder() { return destFolder; } } package com.lpoo.game; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.badlogic.gdx.graphics.g2d.Animation; import com.google.example.games.basegameutils.GameHelper; /** * Class responsible for launching the game in Android. */ public class AndroidLauncher extends AndroidApplication implements GameHelper.GameHelperListener { /** * Android Launcher's game Helper, for intercation with google play services. */ private GameHelper gameHelper; private PlayServices playServices; /** * {@inheritDoc} */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); gameHelper = new GameHelper(this, GameHelper.CLIENT_GAMES); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); config.hideStatusBar = true; config.useAccelerometer = true; gameHelper.setup(this); playServices = new PlayServices(this, gameHelper); initialize(new Armadillo(playServices), config); } /** * {@inheritDoc} */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus && Build.VERSION.SDK_INT >= 19) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE); } } /** * {@inheritDoc} */ @Override protected void onStart() { super.onStart(); gameHelper.onStart(this); } /** * {@inheritDoc} */ @Override protected void onStop() { super.onStop(); gameHelper.onStop(); } /** * {@inheritDoc} */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); gameHelper.onActivityResult(requestCode, resultCode, data); } /** * {@inheritDoc} */ @Override public void onSignInFailed() { System.out.println("Sign in failed"); } /** * {@inheritDoc} */ @Override public void onSignInSucceeded() { System.out.println("Sign in succeeded"); playServices.incrementAchievement(getString(R.string.achievement_really_bored___)); } } package com.blog.start.controller; import com.blog.start.jpa.entity.User; import com.blog.start.jpa.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.validation.Valid; /** * Created by MahfuzCSE'11 on 14-Oct-16. */ @Controller @RequestMapping("/register") public class RegisterController { @Autowired private UserService userService; @ModelAttribute("user") public User construct() { return new User(); } @RequestMapping public String showRegisterForm() { return "user-register"; } @RequestMapping(method = RequestMethod.POST) public String doRegisterForm(@Valid @ModelAttribute("user") User user, BindingResult result, RedirectAttributes redirectAttributes) { if (result.hasErrors()) { return "user-register"; } redirectAttributes.addFlashAttribute("success", true); userService.save(user); return "redirect:/register"; } } package com.storesales.tools; import java.io.IOException; import java.io.PrintWriter; import java.util.Map; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; /** * 响应工具 * * @author * @since * @version 0.1 初始版本 * */ public class ResponseUtil { private static String DEFAULT_CHARACTER_ENCODING ="UTF-8"; /** * 输出JSON内容 (字符编码为UTF-8) * * @param response * @param responseMap */ public static void writeJSON(HttpServletResponse response, Map responseMap) { response.setCharacterEncoding(DEFAULT_CHARACTER_ENCODING); response.setContentType("application/x-json"); response.setHeader("Cache-Control", "no-cache"); Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create(); try { PrintWriter writer = response.getWriter(); writer.write(gson.toJson(responseMap)); } catch (IOException e) { e.printStackTrace(); } } /** * 输出文本内容 (字符编码为UTF-8) * * @param response * @param responseMap */ public static void write(HttpServletResponse response, String content) { response.setCharacterEncoding(DEFAULT_CHARACTER_ENCODING); response.setContentType("application/x-json"); response.setHeader("Cache-Control", "no-cache"); try { PrintWriter writer = response.getWriter(); writer.write(content); } catch (IOException e) { e.printStackTrace(); } } public static void write(HttpServletResponse response, Boolean content) { write(response, content + ""); } /** * 输出JSON内容 (字符编码为UTF-8) * * @param response * @param responseMap */ public static void writeJSON(HttpServletResponse response, JsonObject jsonObject) { response.setCharacterEncoding(DEFAULT_CHARACTER_ENCODING); response.setContentType("application/x-json"); response.setHeader("Cache-Control", "no-cache"); try { PrintWriter writer = response.getWriter(); writer.write(jsonObject.toString()); } catch (IOException e) { e.printStackTrace(); } } } package ru.myx.e5.vm.build; public interface VmConditionalBuilder extends VmBasicBuilder { // } begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package DECL|package|org.apache.hadoop.hdfs.server.common package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hdfs operator|. name|server operator|. name|common package|; end_package begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hdfs operator|. name|web operator|. name|WebHdfsFileSystem import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|security operator|. name|authentication operator|. name|server operator|. name|AuthenticationFilter import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|mockito operator|. name|Mockito import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|javax operator|. name|servlet operator|. name|Filter import|; end_import begin_import import|import name|javax operator|. name|servlet operator|. name|FilterChain import|; end_import begin_import import|import name|javax operator|. name|servlet operator|. name|FilterConfig import|; end_import begin_import import|import name|javax operator|. name|servlet operator|. name|ServletContext import|; end_import begin_import import|import name|javax operator|. name|servlet operator|. name|ServletException import|; end_import begin_import import|import name|javax operator|. name|servlet operator|. name|ServletRequest import|; end_import begin_import import|import name|javax operator|. name|servlet operator|. name|ServletResponse import|; end_import begin_import import|import name|javax operator|. name|servlet operator|. name|http operator|. name|HttpServletRequest import|; end_import begin_import import|import name|javax operator|. name|servlet operator|. name|http operator|. name|HttpServletResponse import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collections import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Enumeration import|; end_import begin_import import|import name|java operator|. name|util operator|. name|HashMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_comment comment|/** * Test Host Restriction Filter. */ end_comment begin_class DECL|class|TestHostRestrictingAuthorizationFilter specifier|public class|class name|TestHostRestrictingAuthorizationFilter block|{ DECL|field|log specifier|private name|Logger name|log init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|TestHostRestrictingAuthorizationFilter operator|. name|class argument_list|) decl_stmt|; comment|/* * Test running in unrestricted mode */ annotation|@ name|Test DECL|method|testAcceptAll () specifier|public name|void name|testAcceptAll parameter_list|() throws|throws name|Exception block|{ name|HttpServletRequest name|request init|= name|Mockito operator|. name|mock argument_list|( name|HttpServletRequest operator|. name|class argument_list|) decl_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRemoteAddr argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|null argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getMethod argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"GET" argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRequestURI argument_list|() argument_list|) operator|. name|thenReturn argument_list|( operator|new name|StringBuffer argument_list|( name|WebHdfsFileSystem operator|. name|PATH_PREFIX operator|+ literal|"/user" operator|+ literal|"/ubuntu/foo" argument_list|) operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getQueryString argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"op=OPEN" argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRemoteAddr argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"192.168.1.2" argument_list|) expr_stmt|; name|HttpServletResponse name|response init|= name|Mockito operator|. name|mock argument_list|( name|HttpServletResponse operator|. name|class argument_list|) decl_stmt|; name|FilterChain name|chain init|= operator|new name|FilterChain argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|doFilter parameter_list|( name|ServletRequest name|servletRequest parameter_list|, name|ServletResponse name|servletResponse parameter_list|) throws|throws name|IOException throws|, name|ServletException block|{ } block|} decl_stmt|; name|Filter name|filter init|= operator|new name|HostRestrictingAuthorizationFilter argument_list|() decl_stmt|; name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> name|configs init|= operator|new name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> argument_list|() block|{ } decl_stmt|; name|String name|allowRule init|= literal|"*,*,/" decl_stmt|; name|log operator|. name|trace argument_list|( literal|"Passing configs:\n{}" argument_list|, name|allowRule argument_list|) expr_stmt|; name|configs operator|. name|put argument_list|( literal|"host.allow.rules" argument_list|, name|allowRule argument_list|) expr_stmt|; name|configs operator|. name|put argument_list|( name|AuthenticationFilter operator|. name|AUTH_TYPE argument_list|, literal|"simple" argument_list|) expr_stmt|; name|FilterConfig name|fc init|= operator|new name|DummyFilterConfig argument_list|( name|configs argument_list|) decl_stmt|; name|filter operator|. name|init argument_list|( name|fc argument_list|) expr_stmt|; name|filter operator|. name|doFilter argument_list|( name|request argument_list|, name|response argument_list|, name|chain argument_list|) expr_stmt|; name|Mockito operator|. name|verify argument_list|( name|response argument_list|, name|Mockito operator|. name|times argument_list|( literal|0 argument_list|) argument_list|) operator|. name|sendError argument_list|( name|Mockito operator|. name|eq argument_list|( name|HttpServletResponse operator|. name|SC_FORBIDDEN argument_list|) argument_list|, name|Mockito operator|. name|anyString argument_list|() argument_list|) expr_stmt|; name|filter operator|. name|destroy argument_list|() expr_stmt|; block|} comment|/* * Test accepting a GET request for the file checksum when prohibited from * doing * a GET open call */ annotation|@ name|Test DECL|method|testAcceptGETFILECHECKSUM () specifier|public name|void name|testAcceptGETFILECHECKSUM parameter_list|() throws|throws name|Exception block|{ name|HttpServletRequest name|request init|= name|Mockito operator|. name|mock argument_list|( name|HttpServletRequest operator|. name|class argument_list|) decl_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRemoteAddr argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|null argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getMethod argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"GET" argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRequestURI argument_list|() argument_list|) operator|. name|thenReturn argument_list|( operator|new name|StringBuffer argument_list|( name|WebHdfsFileSystem operator|. name|PATH_PREFIX operator|+ literal|"/user" operator|+ literal|"/ubuntu/" argument_list|) operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getQueryString argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"op=GETFILECHECKSUM " argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRemoteAddr argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"192.168.1.2" argument_list|) expr_stmt|; name|HttpServletResponse name|response init|= name|Mockito operator|. name|mock argument_list|( name|HttpServletResponse operator|. name|class argument_list|) decl_stmt|; name|FilterChain name|chain init|= operator|new name|FilterChain argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|doFilter parameter_list|( name|ServletRequest name|servletRequest parameter_list|, name|ServletResponse name|servletResponse parameter_list|) throws|throws name|IOException throws|, name|ServletException block|{ } block|} decl_stmt|; name|Filter name|filter init|= operator|new name|HostRestrictingAuthorizationFilter argument_list|() decl_stmt|; name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> name|configs init|= operator|new name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> argument_list|() block|{ } decl_stmt|; name|configs operator|. name|put argument_list|( name|AuthenticationFilter operator|. name|AUTH_TYPE argument_list|, literal|"simple" argument_list|) expr_stmt|; name|FilterConfig name|fc init|= operator|new name|DummyFilterConfig argument_list|( name|configs argument_list|) decl_stmt|; name|filter operator|. name|init argument_list|( name|fc argument_list|) expr_stmt|; name|filter operator|. name|doFilter argument_list|( name|request argument_list|, name|response argument_list|, name|chain argument_list|) expr_stmt|; name|Mockito operator|. name|verify argument_list|( name|response argument_list|, name|Mockito operator|. name|times argument_list|( literal|0 argument_list|) argument_list|) operator|. name|sendError argument_list|( name|Mockito operator|. name|eq argument_list|( name|HttpServletResponse operator|. name|SC_FORBIDDEN argument_list|) argument_list|, name|Mockito operator|. name|anyString argument_list|() argument_list|) expr_stmt|; name|filter operator|. name|destroy argument_list|() expr_stmt|; block|} comment|/* * Test accepting a GET request for reading a file via an open call */ annotation|@ name|Test DECL|method|testRuleAllowedGet () specifier|public name|void name|testRuleAllowedGet parameter_list|() throws|throws name|Exception block|{ name|HttpServletRequest name|request init|= name|Mockito operator|. name|mock argument_list|( name|HttpServletRequest operator|. name|class argument_list|) decl_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRemoteAddr argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|null argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getMethod argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"GET" argument_list|) expr_stmt|; name|String name|queryString init|= literal|"op=OPEN" decl_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRequestURI argument_list|() argument_list|) operator|. name|thenReturn argument_list|( operator|new name|StringBuffer argument_list|( name|WebHdfsFileSystem operator|. name|PATH_PREFIX operator|+ literal|"/user" operator|+ literal|"/ubuntu/foo?" operator|+ name|queryString argument_list|) operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getQueryString argument_list|() argument_list|) operator|. name|thenReturn argument_list|( name|queryString argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRemoteAddr argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"192.168.1.2" argument_list|) expr_stmt|; name|HttpServletResponse name|response init|= name|Mockito operator|. name|mock argument_list|( name|HttpServletResponse operator|. name|class argument_list|) decl_stmt|; name|FilterChain name|chain init|= operator|new name|FilterChain argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|doFilter parameter_list|( name|ServletRequest name|servletRequest parameter_list|, name|ServletResponse name|servletResponse parameter_list|) throws|throws name|IOException throws|, name|ServletException block|{ } block|} decl_stmt|; name|Filter name|filter init|= operator|new name|HostRestrictingAuthorizationFilter argument_list|() decl_stmt|; name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> name|configs init|= operator|new name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> argument_list|() block|{ } decl_stmt|; name|String name|allowRule init|= literal|"ubuntu,127.0.0.1/32,/localbits/*|*,192.168.0.1/22," operator|+ literal|"/user/ubuntu/*" decl_stmt|; name|log operator|. name|trace argument_list|( literal|"Passing configs:\n{}" argument_list|, name|allowRule argument_list|) expr_stmt|; name|configs operator|. name|put argument_list|( literal|"host.allow.rules" argument_list|, name|allowRule argument_list|) expr_stmt|; name|configs operator|. name|put argument_list|( name|AuthenticationFilter operator|. name|AUTH_TYPE argument_list|, literal|"simple" argument_list|) expr_stmt|; name|FilterConfig name|fc init|= operator|new name|DummyFilterConfig argument_list|( name|configs argument_list|) decl_stmt|; name|filter operator|. name|init argument_list|( name|fc argument_list|) expr_stmt|; name|filter operator|. name|doFilter argument_list|( name|request argument_list|, name|response argument_list|, name|chain argument_list|) expr_stmt|; name|filter operator|. name|destroy argument_list|() expr_stmt|; block|} comment|/* * Test by default we deny an open call GET request */ annotation|@ name|Test DECL|method|testRejectsGETs () specifier|public name|void name|testRejectsGETs parameter_list|() throws|throws name|Exception block|{ name|HttpServletRequest name|request init|= name|Mockito operator|. name|mock argument_list|( name|HttpServletRequest operator|. name|class argument_list|) decl_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRemoteAddr argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|null argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getMethod argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"GET" argument_list|) expr_stmt|; name|String name|queryString init|= literal|"bar=foo&delegationToken=dt&op=OPEN" decl_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRequestURI argument_list|() argument_list|) operator|. name|thenReturn argument_list|( operator|new name|StringBuffer argument_list|( name|WebHdfsFileSystem operator|. name|PATH_PREFIX operator|+ literal|"/user" operator|+ literal|"/ubuntu/?" operator|+ name|queryString argument_list|) operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getQueryString argument_list|() argument_list|) operator|. name|thenReturn argument_list|( name|queryString argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRemoteAddr argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"192.168.1.2" argument_list|) expr_stmt|; name|HttpServletResponse name|response init|= name|Mockito operator|. name|mock argument_list|( name|HttpServletResponse operator|. name|class argument_list|) decl_stmt|; name|FilterChain name|chain init|= operator|new name|FilterChain argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|doFilter parameter_list|( name|ServletRequest name|servletRequest parameter_list|, name|ServletResponse name|servletResponse parameter_list|) throws|throws name|IOException throws|, name|ServletException block|{ } block|} decl_stmt|; name|Filter name|filter init|= operator|new name|HostRestrictingAuthorizationFilter argument_list|() decl_stmt|; name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> name|configs init|= operator|new name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> argument_list|() block|{ } decl_stmt|; name|configs operator|. name|put argument_list|( name|AuthenticationFilter operator|. name|AUTH_TYPE argument_list|, literal|"simple" argument_list|) expr_stmt|; name|FilterConfig name|fc init|= operator|new name|DummyFilterConfig argument_list|( name|configs argument_list|) decl_stmt|; name|filter operator|. name|init argument_list|( name|fc argument_list|) expr_stmt|; name|filter operator|. name|doFilter argument_list|( name|request argument_list|, name|response argument_list|, name|chain argument_list|) expr_stmt|; name|filter operator|. name|destroy argument_list|() expr_stmt|; block|} comment|/* * Test acceptable behavior to malformed requests * Case: no operation (op parameter) specified */ annotation|@ name|Test DECL|method|testUnexpectedInputMissingOpParameter () specifier|public name|void name|testUnexpectedInputMissingOpParameter parameter_list|() throws|throws name|Exception block|{ name|HttpServletRequest name|request init|= name|Mockito operator|. name|mock argument_list|( name|HttpServletRequest operator|. name|class argument_list|) decl_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRemoteAddr argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|null argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getMethod argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"GET" argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRequestURI argument_list|() argument_list|) operator|. name|thenReturn argument_list|( operator|new name|StringBuffer argument_list|( name|WebHdfsFileSystem operator|. name|PATH_PREFIX operator|+ literal|"/IAmARandomRequest/" argument_list|) operator|. name|toString argument_list|() argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getQueryString argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|null argument_list|) expr_stmt|; name|Mockito operator|. name|when argument_list|( name|request operator|. name|getRemoteAddr argument_list|() argument_list|) operator|. name|thenReturn argument_list|( literal|"192.168.1.2" argument_list|) expr_stmt|; name|HttpServletResponse name|response init|= name|Mockito operator|. name|mock argument_list|( name|HttpServletResponse operator|. name|class argument_list|) decl_stmt|; name|FilterChain name|chain init|= operator|new name|FilterChain argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|doFilter parameter_list|( name|ServletRequest name|servletRequest parameter_list|, name|ServletResponse name|servletResponse parameter_list|) throws|throws name|IOException throws|, name|ServletException block|{ } block|} decl_stmt|; name|Filter name|filter init|= operator|new name|HostRestrictingAuthorizationFilter argument_list|() decl_stmt|; name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> name|configs init|= operator|new name|HashMap argument_list|< name|String argument_list|, name|String argument_list|> argument_list|() block|{ } decl_stmt|; name|configs operator|. name|put argument_list|( name|AuthenticationFilter operator|. name|AUTH_TYPE argument_list|, literal|"simple" argument_list|) expr_stmt|; name|FilterConfig name|fc init|= operator|new name|DummyFilterConfig argument_list|( name|configs argument_list|) decl_stmt|; name|filter operator|. name|init argument_list|( name|fc argument_list|) expr_stmt|; name|filter operator|. name|doFilter argument_list|( name|request argument_list|, name|response argument_list|, name|chain argument_list|) expr_stmt|; name|log operator|. name|error argument_list|( literal|"XXX {}" argument_list|, name|response operator|. name|getStatus argument_list|() argument_list|) expr_stmt|; name|filter operator|. name|destroy argument_list|() expr_stmt|; block|} DECL|class|DummyFilterConfig specifier|private specifier|static class|class name|DummyFilterConfig implements|implements name|FilterConfig block|{ DECL|field|map specifier|final name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|map decl_stmt|; DECL|method|DummyFilterConfig (Map map) name|DummyFilterConfig parameter_list|( name|Map argument_list|< name|String argument_list|, name|String argument_list|> name|map parameter_list|) block|{ name|this operator|. name|map operator|= name|map expr_stmt|; block|} annotation|@ name|Override DECL|method|getFilterName () specifier|public name|String name|getFilterName parameter_list|() block|{ return|return literal|"dummy" return|; block|} annotation|@ name|Override DECL|method|getInitParameter (String arg0) specifier|public name|String name|getInitParameter parameter_list|( name|String name|arg0 parameter_list|) block|{ return|return name|map operator|. name|get argument_list|( name|arg0 argument_list|) return|; block|} annotation|@ name|Override DECL|method|getInitParameterNames () specifier|public name|Enumeration argument_list|< name|String argument_list|> name|getInitParameterNames parameter_list|() block|{ return|return name|Collections operator|. name|enumeration argument_list|( name|map operator|. name|keySet argument_list|() argument_list|) return|; block|} annotation|@ name|Override DECL|method|getServletContext () specifier|public name|ServletContext name|getServletContext parameter_list|() block|{ name|ServletContext name|context init|= name|Mockito operator|. name|mock argument_list|( name|ServletContext operator|. name|class argument_list|) decl_stmt|; name|Mockito operator|. name|when argument_list|( name|context operator|. name|getAttribute argument_list|( name|AuthenticationFilter operator|. name|SIGNER_SECRET_PROVIDER_ATTRIBUTE argument_list|) argument_list|) operator|. name|thenReturn argument_list|( literal|null argument_list|) expr_stmt|; return|return name|context return|; block|} block|} block|} end_class end_unit package net.pixfumy.legacyelytras.networking; public interface IClientPlayNetworkHandler { public void onFallFlying(FallFlyingS2CPacket fallFlyingS2CPacket); } /* * Copyright 2012 * * 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.redshape.io.net.auth; import java.net.InetAddress; import java.util.Collection; /** * Interface for credentials providers * @author nikelin */ public interface ICredentialsProvider { /** * Get authentication information for given network node * @param node * @return */ public Collection getCredentials( InetAddress node ) throws AuthenticatorException; } Nalhin/Leetcode package com.leetcode.tree.easy; // // Given a binary tree, you need to compute the length of the diameter of the tre // e. The diameter of a binary tree is the length of the longest path between any t // wo nodes in a tree. This path may or may not pass through the root. // // // // Example: // Given a binary tree // // 1 // / \ // 2 3 // / \ // 4 5 // // // // Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3]. // // // Note: // The length of path between two nodes is represented by the number of edges bet // ween them. // Related Topics Tree // 👍 3834 👎 227 // leetcode submit region begin(Prohibit modification and deletion) import com.leetcode.utils.BinaryTree.TreeNode; /** * Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode * right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, * TreeNode right) { this.val = val; this.left = left; this.right = right; } } */ public class DiameterOfBinaryTree_543 { private int result = 0; public int diameterOfBinaryTree(TreeNode root) { depthDfs(root); return result; } public int depthDfs(TreeNode root) { if (root == null) { return 0; } int left = depthDfs(root.left); int right = depthDfs(root.right); result = Math.max(result, left + right); return Math.max(left, right) + 1; } } // leetcode submit region end(Prohibit modification and deletion) 0 /* * Copyright 2019 Arcus 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 arcus.app.subsystems.rules.model; import android.support.annotation.NonNull; import arcus.app.R; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public enum RuleCategory { BUTTONS_FOBS("Buttons & Fobs", R.string.rules_category_buttonsfobs, R.drawable.icon_rule_button), CAMERAS_SENSORS("Cameras & Sensors", R.string.rules_category_camerassensors, R.drawable.icon_rule_camera), CARE("Care", R.string.rules_category_care, R.drawable.icon_rule_care), CLIMATE_CONTROL("Climate", R.string.rules_category_climatecontrol, R.drawable.icon_rule_climate), DOORS_LOCKS("Doors & Locks", R.string.rules_category_doorslocks, R.drawable.icon_rules_doorslocks), ENERGY_MONITORING("Energy", R.string.rules_category_energymonitoring, R.drawable.icon_rules_energy), LAWN_GARDEN("Lawn & Garden", R.string.rules_category_lawngarden, R.drawable.icon_rules_lawngarden), LIGHTS_SWITCHES("Lights & Switches", R.string.rules_category_lightswitches, R.drawable.icon_rules_lightsswitches), NOTIFICATION("Notifications", R.string.rules_category_notifications, R.drawable.icon_rules_notifications), HOME_FAMILY("Home & Family", R.string.rules_category_family_friends,R.drawable.icon_rules_family), OTHER("Other", R.string.rules_category_other, R.drawable.icon_rules_other), SMOKE_CO("Smoke & CO", R.string.rules_category_smokeco, R.drawable.icon_rules_smoke), SECURITY_ALARM("Security Alarm",R.string.rules_category_securityalarm, R.drawable.icon_rules_security), SCENES("Scene",R.string.rules_category_scenes, R.drawable.icon_rules_scenes), WATER("Water",R.string.rules_category_water, R.drawable.icon_rules_water), WINDOWS_BLINDS("Windows & Blinds",R.string.rules_category_windowsblinds, R.drawable.icon_rules_windows); private final static Logger logger = LoggerFactory.getLogger(RuleCategory.class); private final String platformTag; private final int titleResId; private final int imageResId; RuleCategory (String platformTag, int titleResId, int imageResId) { this.platformTag = platformTag; this.titleResId = titleResId; this.imageResId = imageResId; } @NonNull public static RuleCategory fromPlatformTag (String platformTag) { for (RuleCategory thisCategory : RuleCategory.values()) { if (thisCategory.platformTag.equalsIgnoreCase(platformTag)) return thisCategory; } // Shouldn't ever happen, but just in case... logger.error("Bug! Cannot resolve category {} into a known well-defined category. There is a problem with the rule template catalog!", platformTag); return OTHER; } public int getTitleResId () { return titleResId; } public int getImageResId() { return imageResId; } public String getPlatformTag() {return platformTag; } } package com.example.zhw.dao; import java.io.Serializable; /** * @author: zhw * @createDate: 2020/4/12 */ public class TShopAttribute implements Serializable { private static final long serialVersionUID = 779884812394806046L; private Integer id; private String attributeName; private Integer skuId; public Integer getSkuId() { return skuId; } public void setSkuId(Integer skuId) { this.skuId = skuId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAttributeName() { return attributeName; } public void setAttributeName(String attributeName) { this.attributeName = attributeName; } } /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ package org.elasticsearch.xpack.transform.integration; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.elasticsearch.client.Request; import org.elasticsearch.common.Strings; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.rest.action.admin.indices.RestPutIndexTemplateAction; import org.elasticsearch.xcontent.XContentBuilder; import org.junit.Before; import java.io.IOException; import java.util.List; import java.util.Map; import static org.elasticsearch.xcontent.XContentFactory.jsonBuilder; import static org.hamcrest.Matchers.equalTo; public class TransformPivotRestSpecialCasesIT extends TransformRestTestCase { private static boolean indicesCreated = false; // preserve indices in order to reuse source indices in several test cases @Override protected boolean preserveIndicesUponCompletion() { return true; } @Before public void createIndexes() throws IOException { // it's not possible to run it as @BeforeClass as clients aren't initialized then, so we need this little hack if (indicesCreated) { return; } createReviewsIndex(); indicesCreated = true; } public void testIndexTemplateMappingClash() throws Exception { String transformId = "special_pivot_template_mappings_clash"; String transformIndex = "special_pivot_template_mappings_clash"; // create a template that defines a field "rating" with a type "float" which will clash later with // output field "rating.avg" in the pivot config final Request createIndexTemplateRequest = new Request("PUT", "_template/special_pivot_template"); String template = """ { "index_patterns": [ "special_pivot_template*" ], "mappings": { "properties": { "rating": { "type": "float" } } } }"""; createIndexTemplateRequest.setJsonEntity(template); createIndexTemplateRequest.setOptions(expectWarnings(RestPutIndexTemplateAction.DEPRECATION_WARNING)); Map createIndexTemplateResponse = entityAsMap(client().performRequest(createIndexTemplateRequest)); assertThat(createIndexTemplateResponse.get("acknowledged"), equalTo(Boolean.TRUE)); final Request createTransformRequest = new Request("PUT", getTransformEndpoint() + transformId); String config = """ { "source": { "index": "%s" }, "dest": { "index": "%s" }, "pivot": { "group_by": { "reviewer": { "terms": { "field": "user_id" } } }, "aggregations": { "rating.avg": { "avg": { "field": "stars" } } } } }""".formatted(REVIEWS_INDEX_NAME, transformIndex); createTransformRequest.setJsonEntity(config); Map createTransformResponse = entityAsMap(client().performRequest(createTransformRequest)); assertThat(createTransformResponse.get("acknowledged"), equalTo(Boolean.TRUE)); startAndWaitForTransform(transformId, transformIndex); assertTrue(indexExists(transformIndex)); // we expect 27 documents as there shall be 27 user_id's Map indexStats = getAsMap(transformIndex + "/_stats"); assertEquals(27, XContentMapValues.extractValue("_all.total.docs.count", indexStats)); // get and check some users Map searchResult = getAsMap(transformIndex + "/_search?q=reviewer:user_4"); assertEquals(1, XContentMapValues.extractValue("hits.total.value", searchResult)); Number actual = (Number) ((List) XContentMapValues.extractValue("hits.hits._source.rating.avg", searchResult)).get(0); assertEquals(3.878048780, actual.doubleValue(), 0.000001); } public void testSparseDataPercentiles() throws Exception { String indexName = "cpu-utilization"; String transformIndex = "pivot-cpu"; String transformId = "pivot-cpu"; try (XContentBuilder builder = jsonBuilder()) { builder.startObject(); { builder.startObject("mappings") .startObject("properties") .startObject("host") .field("type", "keyword") .endObject() .startObject("cpu") .field("type", "integer") .endObject() .endObject() .endObject(); } builder.endObject(); final StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON); Request req = new Request("PUT", indexName); req.setEntity(entity); client().performRequest(req); } final StringBuilder bulk = new StringBuilder(); bulk.append(""" {"index":{"_index":"%s"}} {"host":"host-1","cpu": 22} {"index":{"_index":"%s"}} {"host":"host-1","cpu": 55} {"index":{"_index":"%s"}} {"host":"host-1","cpu": 23} {"index":{"_index":"%s"}} {"host":"host-2","cpu": 0} {"index":{"_index":"%s"}} {"host":"host-2","cpu": 99} {"index":{"_index":"%s"}} {"host":"host-1","cpu": 28} {"index":{"_index":"%s"}} {"host":"host-1","cpu": 77} """.formatted(indexName, indexName, indexName, indexName, indexName, indexName, indexName)); // missing value for cpu bulk.append(""" {"index":{"_index":"%s"}} {"host":"host-3"} """.formatted(indexName)); final Request bulkRequest = new Request("POST", "/_bulk"); bulkRequest.addParameter("refresh", "true"); bulkRequest.setJsonEntity(bulk.toString()); client().performRequest(bulkRequest); final Request createTransformRequest = new Request("PUT", getTransformEndpoint() + transformId); String config = """ { "source": { "index": "%s" }, "dest": { "index": "%s" }, "pivot": { "group_by": { "host": { "terms": { "field": "host" } } }, "aggregations": { "p": { "percentiles": { "field": "cpu" } } } } }""".formatted(indexName, transformIndex); createTransformRequest.setJsonEntity(config); Map createTransformResponse = entityAsMap(client().performRequest(createTransformRequest)); assertThat(createTransformResponse.get("acknowledged"), equalTo(Boolean.TRUE)); startAndWaitForTransform(transformId, transformIndex); assertTrue(indexExists(transformIndex)); Map indexStats = getAsMap(transformIndex + "/_stats"); assertEquals(3, XContentMapValues.extractValue("_all.total.docs.count", indexStats)); // get and check some data Map searchResult = getAsMap(transformIndex + "/_search?q=host:host-1"); assertEquals(1, XContentMapValues.extractValue("hits.total.value", searchResult)); @SuppressWarnings("unchecked") Map percentiles = (Map) ((List) XContentMapValues.extractValue( "hits.hits._source.p", searchResult )).get(0); assertEquals(28.0, (double) percentiles.get("50"), 0.000001); assertEquals(77.0, (double) percentiles.get("99"), 0.000001); searchResult = getAsMap(transformIndex + "/_search?q=host:host-3"); assertEquals(1, XContentMapValues.extractValue("hits.total.value", searchResult)); @SuppressWarnings("unchecked") Map percentilesEmpty = (Map) ((List) XContentMapValues.extractValue( "hits.hits._source.p", searchResult )).get(0); assertTrue(percentilesEmpty.containsKey("50")); assertNull(percentilesEmpty.get("50")); assertTrue(percentilesEmpty.containsKey("99")); assertNull(percentilesEmpty.get("99")); } } package com.orientechnologies.orient.core.storage.impl.local; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.storage.OStorage; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.File; import java.util.HashMap; import java.util.Map; @Test public class OStorageLocalTest { public void withLegacyPath() { String dbPath = getDatabasePath(); System.out.println("Using db = plocal:" + dbPath); File dbDir = new File(dbPath); System.out.println("Clean db directory for test..."); delTree(dbDir); ODatabaseDocumentTx db = new ODatabaseDocumentTx("plocal:" + dbPath); db.create(); OStorage storage = db.getStorage(); db.close(); storage.close(true, false); System.out.println("Reopen it..."); // Something was added to dbPath so the legacy situation was simulated dbPath += "/foo"; db = new ODatabaseDocumentTx("plocal:" + dbPath).open("admin", "admin"); db.drop(); } public void withNormalPath() { String dbPath = getDatabasePath(); System.out.println("Using db = plocal:" + dbPath); File dbDir = new File(dbPath); System.out.println("Clean db directory for test..."); delTree(dbDir); ODatabaseDocumentTx db = new ODatabaseDocumentTx("plocal:" + dbPath); db.create(); OStorage storage = db.getStorage(); db.close(); storage.close(true, false); System.out.println("Reopen it..."); db = new ODatabaseDocumentTx("plocal:" + dbPath).open("admin", "admin"); db.drop(); } public void dbOperations() { String dbPath = getDatabasePath(); System.out.println("Using db = plocal:" + dbPath); File dbDir = new File(dbPath); System.out.println("Clean db directory for test..."); delTree(dbDir); ODatabaseDocumentTx db = new ODatabaseDocumentTx("plocal:" + dbPath); db.create(); db.close(); System.out.println("Create OK!"); db = new ODatabaseDocumentTx("plocal:" + dbPath).open("admin", "admin"); System.out.println("Open OK!"); Assert.assertTrue(db.exists()); System.out.println("Exists OK!"); db.drop(); System.out.println("Delete OK!"); } public void contextConfigurationOnCreation() { ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:testCtxCfgOnCreate"); Map settings = new HashMap(); settings.put(OGlobalConfiguration.STORAGE_COMPRESSION_METHOD, "gzip"); db.create(settings); db.close(); ODatabaseDocumentTx db2 = new ODatabaseDocumentTx("memory:testCtxCfgOnCreate").open("admin", "admin"); Assert.assertEquals(db2.getConfiguration().getValueAsString(OGlobalConfiguration.STORAGE_COMPRESSION_METHOD), "gzip"); } public void contextConfigurationAfterCreation() { ODatabaseDocumentTx db = new ODatabaseDocumentTx("memory:testCtxCfgAfterCreate").create(); db.getConfiguration().setValue(OGlobalConfiguration.USE_WAL, false); Assert.assertFalse(db.getConfiguration().getValueAsBoolean(OGlobalConfiguration.USE_WAL)); } private boolean delTree(File directory) { if (directory.exists()) { File[] files = directory.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { delTree(files[i]); } else { files[i].delete(); } } } return directory.delete(); } private String getDatabasePath() { String buildDirectory = System.getProperty("buildDirectory"); if (buildDirectory == null) buildDirectory = "./target"; return buildDirectory + File.separator + "OStorageLocalTestDB__42"; } } /* * Zeebe Broker Core * Copyright © 2017 camunda services GmbH () * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see . */ package io.zeebe.broker.system; import static io.zeebe.broker.system.configuration.ClusterCfg.DEFAULT_CLUSTER_SIZE; import static io.zeebe.broker.system.configuration.ClusterCfg.DEFAULT_CONTACT_POINTS; import static io.zeebe.broker.system.configuration.ClusterCfg.DEFAULT_NODE_ID; import static io.zeebe.broker.system.configuration.ClusterCfg.DEFAULT_PARTITIONS_COUNT; import static io.zeebe.broker.system.configuration.ClusterCfg.DEFAULT_REPLICATION_FACTOR; import static io.zeebe.broker.system.configuration.DataCfg.DEFAULT_DIRECTORY; import static io.zeebe.broker.system.configuration.EnvironmentConstants.ENV_CLUSTER_NAME; import static io.zeebe.broker.system.configuration.EnvironmentConstants.ENV_CLUSTER_SIZE; import static io.zeebe.broker.system.configuration.EnvironmentConstants.ENV_DIRECTORIES; import static io.zeebe.broker.system.configuration.EnvironmentConstants.ENV_EMBED_GATEWAY; import static io.zeebe.broker.system.configuration.EnvironmentConstants.ENV_HOST; import static io.zeebe.broker.system.configuration.EnvironmentConstants.ENV_INITIAL_CONTACT_POINTS; import static io.zeebe.broker.system.configuration.EnvironmentConstants.ENV_METRICS_HTTP_SERVER; import static io.zeebe.broker.system.configuration.EnvironmentConstants.ENV_NODE_ID; import static io.zeebe.broker.system.configuration.EnvironmentConstants.ENV_PARTITIONS_COUNT; import static io.zeebe.broker.system.configuration.EnvironmentConstants.ENV_PORT_OFFSET; import static io.zeebe.broker.system.configuration.EnvironmentConstants.ENV_REPLICATION_FACTOR; import static io.zeebe.broker.system.configuration.NetworkCfg.DEFAULT_HOST; import static io.zeebe.protocol.Protocol.START_PARTITION_ID; import static org.assertj.core.api.Assertions.assertThat; import io.zeebe.broker.system.configuration.BrokerCfg; import io.zeebe.broker.system.configuration.ClusterCfg; import io.zeebe.broker.system.configuration.DataCfg; import io.zeebe.broker.system.configuration.EmbeddedGatewayCfg; import io.zeebe.broker.system.configuration.ExporterCfg; import io.zeebe.broker.system.configuration.MetricsCfg; import io.zeebe.broker.system.configuration.NetworkCfg; import io.zeebe.broker.system.configuration.SocketBindingAtomixCfg; import io.zeebe.broker.system.configuration.SocketBindingClientApiCfg; import io.zeebe.util.Environment; import io.zeebe.util.TomlConfigurationReader; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.file.Paths; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.assertj.core.api.Condition; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; public class ConfigurationTest { public static final String BROKER_BASE = "test"; @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); public Map environment = new HashMap<>(); public static final int CLIENT_PORT = SocketBindingClientApiCfg.DEFAULT_PORT; public static final int METRICS_PORT = MetricsCfg.DEFAULT_PORT; public static final int ATOMIX_PORT = SocketBindingAtomixCfg.DEFAULT_PORT; @Test public void shouldUseSpecifiedClusterName() { assertClusterName("specific-cluster-name", "cluster-name"); } @Test public void shouldUseClusterNameFromEnvironment() { environment.put(ENV_CLUSTER_NAME, "test-cluster"); assertClusterName("default", "test-cluster"); } @Test public void shouldUseSpecifiedNodeId() { assertNodeId("specific-node-id", 123); } @Test public void shouldUseNodeIdFromEnvironment() { environment.put(ENV_NODE_ID, "42"); assertNodeId("default", 42); } @Test public void shouldUseNodeIdFromEnvironmentWithSpecifiedNodeId() { environment.put(ENV_NODE_ID, "42"); assertNodeId("specific-node-id", 42); } @Test public void shouldIgnoreInvalidNodeIdFromEnvironment() { environment.put(ENV_NODE_ID, "a"); assertNodeId("default", DEFAULT_NODE_ID); } @Test public void shouldUseDefaultPorts() { assertPorts("default", CLIENT_PORT, ATOMIX_PORT, METRICS_PORT); } @Test public void shouldUseSpecifiedPorts() { assertPorts("specific-ports", 1, 5, 6); } @Test public void shouldUsePortOffset() { final int offset = 50; assertPorts("port-offset", CLIENT_PORT + offset, ATOMIX_PORT + offset, METRICS_PORT + offset); } @Test public void shouldUsePortOffsetWithSpecifiedPorts() { final int offset = 30; assertPorts("specific-ports-offset", 1 + offset, 5 + offset, 6 + offset); } @Test public void shouldUsePortOffsetFromEnvironment() { environment.put(ENV_PORT_OFFSET, "5"); final int offset = 50; assertPorts("default", CLIENT_PORT + offset, ATOMIX_PORT + offset, METRICS_PORT + offset); } @Test public void shouldUsePortOffsetFromEnvironmentWithSpecifiedPorts() { environment.put(ENV_PORT_OFFSET, "3"); final int offset = 30; assertPorts("specific-ports", 1 + offset, 5 + offset, 6 + offset); } @Test public void shouldIgnoreInvalidPortOffsetFromEnvironment() { environment.put(ENV_PORT_OFFSET, "a"); assertPorts("default", CLIENT_PORT, ATOMIX_PORT, METRICS_PORT); } @Test public void shouldOverridePortOffsetFromEnvironment() { environment.put(ENV_PORT_OFFSET, "7"); final int offset = 70; assertPorts("port-offset", CLIENT_PORT + offset, ATOMIX_PORT + offset, METRICS_PORT + offset); } @Test public void shouldExpandExporterJarPathRelativeToBrokerBaseIffPresent() { // given final InputStream input = new ByteArrayInputStream( ("[[exporters]]\n" + "id=\"external\"\n" + "jarPath=\"exporters/exporter.jar\"\n" + "[[exporters]]\n" + "id=\"internal-1\"\n" + "jarPath=\"\"\n" + "[[exporters]]\n" + "id=\"internal-2\"") .getBytes()); final BrokerCfg config = TomlConfigurationReader.read(input, BrokerCfg.class); final String base = temporaryFolder.getRoot().getAbsolutePath(); final String jarFile = Paths.get(base, "exporters", "exporter.jar").toAbsolutePath().toString(); // when config.init(base); // then assertThat(config.getExporters()).hasSize(3); assertThat(config.getExporters().get(0)) .hasFieldOrPropertyWithValue("jarPath", jarFile) .is(new Condition<>(ExporterCfg::isExternal, "is external")); assertThat(config.getExporters().get(1).isExternal()).isFalse(); assertThat(config.getExporters().get(2).isExternal()).isFalse(); } @Test public void shouldUseDefaultHost() { assertHost("default", DEFAULT_HOST); } @Test public void shouldUseSpecifiedHosts() { assertHost( "specific-hosts", DEFAULT_HOST, "gatewayHost", "clientHost", "atomixHost", "metricsHost"); } @Test public void shouldUseGlobalHost() { assertHost("host", "1.1.1.1"); } @Test public void shouldUseHostFromEnvironment() { environment.put(ENV_HOST, "2.2.2.2"); assertHost("default", "2.2.2.2"); } @Test public void shouldUseHostFromEnvironmentWithGlobalHost() { environment.put(ENV_HOST, "myHost"); assertHost("host", "myHost"); } @Test public void shouldNotOverrideSpecifiedHostsFromEnvironment() { environment.put(ENV_HOST, "myHost"); assertHost( "specific-hosts", "myHost", "gatewayHost", "clientHost", "atomixHost", "metricsHost"); } @Test public void shouldUseDefaultContactPoints() { assertContactPoints("default", DEFAULT_CONTACT_POINTS); } @Test public void shouldUseSpecifiedContactPoints() { assertContactPoints("contact-points", "broker1", "broker2", "broker3"); } @Test public void shouldUseContactPointsFromEnvironment() { environment.put(ENV_INITIAL_CONTACT_POINTS, "foo,bar"); assertContactPoints("default", "foo", "bar"); } @Test public void shouldUseContactPointsFromEnvironmentWithSpecifiedContactPoints() { environment.put(ENV_INITIAL_CONTACT_POINTS, "1.1.1.1,2.2.2.2"); assertContactPoints("contact-points", "1.1.1.1", "2.2.2.2"); } @Test public void shouldUseSingleContactPointFromEnvironment() { environment.put(ENV_INITIAL_CONTACT_POINTS, "hello"); assertContactPoints("contact-points", "hello"); } @Test public void shouldClearContactPointFromEnvironment() { environment.put(ENV_INITIAL_CONTACT_POINTS, ""); assertContactPoints("contact-points"); } @Test public void shouldIgnoreTrailingCommaContactPointFromEnvironment() { environment.put(ENV_INITIAL_CONTACT_POINTS, "foo,bar,"); assertContactPoints("contact-points", "foo", "bar"); } @Test public void shouldUseDefaultDirectories() { assertDirectories("default", DEFAULT_DIRECTORY); } @Test public void shouldUseSpecifiedDirectories() { assertDirectories("directories", "data1", "data2", "data3"); } @Test public void shouldUseDirectoriesFromEnvironment() { environment.put(ENV_DIRECTORIES, "foo,bar"); assertDirectories("default", "foo", "bar"); } @Test public void shouldUseDirectoriesFromEnvironmentWithSpecifiedDirectories() { environment.put(ENV_DIRECTORIES, "foo,bar"); assertDirectories("directories", "foo", "bar"); } @Test public void shouldUseSingleDirectoryFromEnvironment() { environment.put(ENV_DIRECTORIES, "hello"); assertDirectories("directories", "hello"); } @Test public void shouldIgnoreTrailingCommaDirectoriesFromEnvironment() { environment.put(ENV_DIRECTORIES, "foo,bar,"); assertDirectories("directories", "foo", "bar"); } @Test public void shouldReadDefaultSystemClusterConfiguration() { // given final BrokerCfg cfg = readConfig("default"); final ClusterCfg cfgCluster = cfg.getCluster(); // when - then assertThat(cfgCluster.getInitialContactPoints()).isEmpty(); assertThat(cfgCluster.getNodeId()).isEqualTo(DEFAULT_NODE_ID); assertThat(cfgCluster.getPartitionsCount()).isEqualTo(DEFAULT_PARTITIONS_COUNT); assertThat(cfgCluster.getReplicationFactor()).isEqualTo(DEFAULT_REPLICATION_FACTOR); assertThat(cfgCluster.getClusterSize()).isEqualTo(DEFAULT_CLUSTER_SIZE); } @Test public void shouldReadSpecificSystemClusterConfiguration() { // given final BrokerCfg cfg = readConfig("cluster-cfg"); final ClusterCfg cfgCluster = cfg.getCluster(); // when - then assertThat(cfgCluster.getInitialContactPoints()).isEmpty(); assertThat(cfgCluster.getNodeId()).isEqualTo(2); assertThat(cfgCluster.getPartitionsCount()).isEqualTo(3); assertThat(cfgCluster.getReplicationFactor()).isEqualTo(4); assertThat(cfgCluster.getClusterSize()).isEqualTo(5); } @Test public void shouldCreatePartitionIds() { // given final BrokerCfg cfg = readConfig("cluster-cfg"); final ClusterCfg cfgCluster = cfg.getCluster(); // when - then assertThat(cfgCluster.getPartitionsCount()).isEqualTo(3); final List partitionIds = cfgCluster.getPartitionIds(); final int startId = START_PARTITION_ID; assertThat(partitionIds).contains(startId, startId + 1, startId + 2); } @Test public void shouldOverrideReplicationFactorViaEnvironment() { // given environment.put(ENV_REPLICATION_FACTOR, "2"); // when final BrokerCfg cfg = readConfig("cluster-cfg"); final ClusterCfg cfgCluster = cfg.getCluster(); // then assertThat(cfgCluster.getReplicationFactor()).isEqualTo(2); } @Test public void shouldOverridePartitionsCountViaEnvironment() { // given environment.put(ENV_PARTITIONS_COUNT, "2"); // when final BrokerCfg cfg = readConfig("cluster-cfg"); final ClusterCfg cfgCluster = cfg.getCluster(); // then assertThat(cfgCluster.getPartitionsCount()).isEqualTo(2); } @Test public void shouldOverrideClusterSizeViaEnvironment() { // given environment.put(ENV_CLUSTER_SIZE, "2"); // when final BrokerCfg cfg = readConfig("cluster-cfg"); final ClusterCfg cfgCluster = cfg.getCluster(); // then assertThat(cfgCluster.getClusterSize()).isEqualTo(2); } @Test public void shouldOverrideAllClusterPropertiesViaEnvironment() { // given environment.put(ENV_CLUSTER_SIZE, "1"); environment.put(ENV_PARTITIONS_COUNT, "2"); environment.put(ENV_REPLICATION_FACTOR, "3"); environment.put(ENV_NODE_ID, "4"); // when final BrokerCfg cfg = readConfig("cluster-cfg"); final ClusterCfg cfgCluster = cfg.getCluster(); // then assertThat(cfgCluster.getClusterSize()).isEqualTo(1); assertThat(cfgCluster.getPartitionsCount()).isEqualTo(2); assertThat(cfgCluster.getReplicationFactor()).isEqualTo(3); assertThat(cfgCluster.getNodeId()).isEqualTo(4); } @Test public void shouldReadDefaultEmbedGateway() { // when final EmbeddedGatewayCfg gatewayCfg = readConfig("default").getGateway(); // then assertThat(gatewayCfg.isEnable()).isTrue(); } @Test public void shouldReadEmbedGateway() { // when final EmbeddedGatewayCfg gatewayCfg = readConfig("disabled-gateway").getGateway(); // then assertThat(gatewayCfg.isEnable()).isFalse(); } @Test public void shouldSetEmbedGatewayViaEnvironment() { // given environment.put(ENV_EMBED_GATEWAY, "true"); // when final EmbeddedGatewayCfg gatewayCfg = readConfig("disabled-gateway").getGateway(); // then assertThat(gatewayCfg.isEnable()).isTrue(); } @Test public void shouldReadDefaultEnableMetricsHttpServer() { // when final MetricsCfg metricsCfg = readConfig("default").getMetrics(); // then assertThat(metricsCfg.isEnableHttpServer()).isFalse(); } @Test public void shouldReadEnableMetricsHttpServer() { // when final MetricsCfg metricsCfg = readConfig("enabled-metrics-http-server").getMetrics(); // then assertThat(metricsCfg.isEnableHttpServer()).isTrue(); } @Test public void shouldEnableMetricsHttpServerViaEnvironment() { // given environment.put(ENV_METRICS_HTTP_SERVER, "true"); // when final MetricsCfg metricsCfg = readConfig("default").getMetrics(); // then assertThat(metricsCfg.isEnableHttpServer()).isTrue(); } private BrokerCfg readConfig(final String name) { final String configPath = "/system/" + name + ".toml"; final InputStream resourceAsStream = ConfigurationTest.class.getResourceAsStream(configPath); assertThat(resourceAsStream) .withFailMessage("Unable to read configuration file %s", configPath) .isNotNull(); final BrokerCfg config = TomlConfigurationReader.read(resourceAsStream, BrokerCfg.class); config.init(BROKER_BASE, new Environment(environment)); return config; } private void assertNodeId(final String configFileName, final int nodeId) { final BrokerCfg cfg = readConfig(configFileName); assertThat(cfg.getCluster().getNodeId()).isEqualTo(nodeId); } private void assertClusterName(final String configFileName, final String clusterName) { final BrokerCfg cfg = readConfig(configFileName); assertThat(cfg.getCluster().getClusterName()).isEqualTo(clusterName); } private void assertPorts( final String configFileName, final int client, final int atomix, final int metrics) { final BrokerCfg brokerCfg = readConfig(configFileName); final NetworkCfg network = brokerCfg.getNetwork(); assertThat(network.getClient().getPort()).isEqualTo(client); assertThat(network.getAtomix().getPort()).isEqualTo(atomix); assertThat(brokerCfg.getMetrics().getPort()).isEqualTo(metrics); } private void assertHost(final String configFileName, final String host) { assertHost(configFileName, host, host, host, host, host); } private void assertHost( final String configFileName, final String host, final String gateway, final String client, final String atomix, final String metrics) { final BrokerCfg brokerCfg = readConfig(configFileName); final NetworkCfg networkCfg = brokerCfg.getNetwork(); assertThat(networkCfg.getHost()).isEqualTo(host); assertThat(brokerCfg.getGateway().getNetwork().getHost()).isEqualTo(gateway); assertThat(networkCfg.getClient().getHost()).isEqualTo(client); assertThat(networkCfg.getAtomix().getHost()).isEqualTo(atomix); assertThat(brokerCfg.getMetrics().getHost()).isEqualTo(metrics); } private void assertContactPoints(final String configFileName, final String... contactPoints) { assertContactPoints(configFileName, Arrays.asList(contactPoints)); } private void assertContactPoints(final String configFileName, final List contactPoints) { final ClusterCfg cfg = readConfig(configFileName).getCluster(); assertThat(cfg.getInitialContactPoints()).containsExactlyElementsOf(contactPoints); } private void assertDirectories(final String configFileName, final String... directories) { assertDirectories(configFileName, Arrays.asList(directories)); } private void assertDirectories(final String configFileName, final List directories) { final DataCfg cfg = readConfig(configFileName).getData(); final List expected = directories.stream() .map(d -> Paths.get(BROKER_BASE, d).toString()) .collect(Collectors.toList()); assertThat(cfg.getDirectories()).containsExactlyElementsOf(expected); } } /* * Copyright 2019 Odnoklassniki Ltd, Mail.Ru Group * * 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 one.nio.mgt; import javax.management.JMException; import javax.management.ObjectName; import java.lang.management.ManagementFactory; public class DiagnosticCommand { public static String execute(String command, String... args) throws JMException { return (String) ManagementFactory.getPlatformMBeanServer().invoke( new ObjectName("com.sun.management:type=DiagnosticCommand"), command, new Object[]{args}, new String[]{"[Ljava.lang.String;"}); } } package org.apache.helix.healthcheck; /* * 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. */ import java.util.Random; import java.util.Timer; import java.util.TimerTask; import org.apache.helix.HelixTimerTask; import org.apache.log4j.Logger; public class HealthStatsAggregationTask extends HelixTimerTask { private static final Logger LOG = Logger.getLogger(HealthStatsAggregationTask.class); public final static int DEFAULT_HEALTH_CHECK_LATENCY = 30 * 1000; final HealthStatsAggregator _healthStatsAggregator; class HealthStatsAggregationTaskTimer extends TimerTask { @Override public void run() { _healthStatsAggregator.aggregate(); } } private Timer _timer; private final int _delay; private final int _period; public HealthStatsAggregationTask(HealthStatsAggregator healthStatsAggregator, int delay, int period) { _healthStatsAggregator = healthStatsAggregator; _delay = delay; _period = period; } public HealthStatsAggregationTask(HealthStatsAggregator healthStatsAggregator) { this(healthStatsAggregator, DEFAULT_HEALTH_CHECK_LATENCY, DEFAULT_HEALTH_CHECK_LATENCY); } @Override public void start() { if (_timer == null) { LOG.info("START HealthStatsAggregationTimerTask"); // Remove all the previous health check values, if any _healthStatsAggregator.init(); _timer = new Timer("HealthStatsAggregationTimerTask", true); _timer.scheduleAtFixedRate(new HealthStatsAggregationTaskTimer(), new Random().nextInt(_delay), _period); } else { LOG.warn("HealthStatsAggregationTimerTask already started"); } } @Override public synchronized void stop() { if (_timer != null) { LOG.info("Stop HealthStatsAggregationTimerTask"); _timer.cancel(); _healthStatsAggregator.reset(); _timer = null; } else { LOG.warn("HealthStatsAggregationTimerTask already stopped"); } } } package bayern.steinbrecher.sepaxmlgenerator.sepatypes.pain00800109; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlSchemaType; import jakarta.xml.bind.annotation.XmlType; /** *

Java-Klasse für FrequencyAndMoment1 complex type. * *

Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * *

 * <complexType name="FrequencyAndMoment1">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Tp" type="{urn:iso:std:iso:20022:tech:xsd:pain.008.001.09}Frequency6Code"/>
 *         <element name="PtInTm" type="{urn:iso:std:iso:20022:tech:xsd:pain.008.001.09}Exact2NumericText"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * 
* * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "FrequencyAndMoment1", propOrder = { "tp", "ptInTm" }) public class FrequencyAndMoment1 { @XmlElement(name = "Tp", required = true) @XmlSchemaType(name = "string") protected Frequency6Code tp; @XmlElement(name = "PtInTm", required = true) protected String ptInTm; /** * Ruft den Wert der tp-Eigenschaft ab. * * @return * possible object is * {@link Frequency6Code } * */ public Frequency6Code getTp() { return tp; } /** * Legt den Wert der tp-Eigenschaft fest. * * @param value * allowed object is * {@link Frequency6Code } * */ public void setTp(Frequency6Code value) { this.tp = value; } /** * Ruft den Wert der ptInTm-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getPtInTm() { return ptInTm; } /** * Legt den Wert der ptInTm-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setPtInTm(String value) { this.ptInTm = value; } } package uk.co.bty.mock.cybersource.controller.form; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import uk.co.bty.mock.cybersource.constants.PayerAuthValidateResult; @Builder @NoArgsConstructor @AllArgsConstructor @Data public class ThreeDeeSubmitForm { private String PaReq; private String TermUrl; private String MD; private PayerAuthValidateResult choice; } package com.teamset.colcap; public class Ruler { } /* * Copyright (C) 2012-2016 , greenrobot (http://greenrobot.org) * * 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.greenrobot.eventbusperf.testsubject; import android.app.Activity; import android.content.Context; import android.os.Looper; import com.squareup.otto.Bus; import com.squareup.otto.Subscribe; import com.squareup.otto.ThreadEnforcer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; import org.greenrobot.eventbusperf.Test; import org.greenrobot.eventbusperf.TestEvent; import org.greenrobot.eventbusperf.TestParams; public abstract class PerfTestOtto extends Test { private final Bus eventBus; private final ArrayList subscribers; private final Class subscriberClass; private final int eventCount; private final int expectedEventCount; public PerfTestOtto(Context context, TestParams params) { super(context, params); eventBus = new Bus(ThreadEnforcer.ANY); subscribers = new ArrayList(); eventCount = params.getEventCount(); expectedEventCount = eventCount * params.getSubscriberCount(); subscriberClass = Subscriber.class; } @Override public void prepareTest() { Looper.prepare(); try { Constructor constructor = subscriberClass.getConstructor(PerfTestOtto.class); for (int i = 0; i < params.getSubscriberCount(); i++) { Object subscriber = constructor.newInstance(this); subscribers.add(subscriber); } } catch (Exception e) { throw new RuntimeException(e); } } public static class Post extends PerfTestOtto { public Post(Context context, TestParams params) { super(context, params); } @Override public void prepareTest() { super.prepareTest(); super.registerSubscribers(); } public void runTest() { TestEvent event = new TestEvent(); long timeStart = System.nanoTime(); for (int i = 0; i < super.eventCount; i++) { super.eventBus.post(event); if (canceled) { break; } } long timeAfterPosting = System.nanoTime(); waitForReceivedEventCount(super.expectedEventCount); primaryResultMicros = (timeAfterPosting - timeStart) / 1000; primaryResultCount = super.expectedEventCount; } @Override public String getDisplayName() { return "Otto Post Events"; } } public static class RegisterAll extends PerfTestOtto { public RegisterAll(Context context, TestParams params) { super(context, params); } public void runTest() { super.registerUnregisterOneSubscribers(); long timeNanos = super.registerSubscribers(); primaryResultMicros = timeNanos / 1000; primaryResultCount = params.getSubscriberCount(); } @Override public String getDisplayName() { return "Otto Register, no unregister"; } } public static class RegisterOneByOne extends PerfTestOtto { protected Field cacheField; public RegisterOneByOne(Context context, TestParams params) { super(context, params); } @SuppressWarnings("rawtypes") public void runTest() { long time = 0; if (cacheField == null) { // Skip first registration unless just the first registration is tested super.registerUnregisterOneSubscribers(); } for (Object subscriber : super.subscribers) { if (cacheField != null) { try { cacheField.set(null, new ConcurrentHashMap()); } catch (Exception e) { throw new RuntimeException(e); } } long beforeRegister = System.nanoTime(); super.eventBus.register(subscriber); long afterRegister = System.nanoTime(); long end = System.nanoTime(); long timeMeasureOverhead = (end - afterRegister) * 2; long timeRegister = end - beforeRegister - timeMeasureOverhead; time += timeRegister; super.eventBus.unregister(subscriber); if (canceled) { return; } } primaryResultMicros = time / 1000; primaryResultCount = params.getSubscriberCount(); } @Override public String getDisplayName() { return "Otto Register"; } } public static class RegisterFirstTime extends RegisterOneByOne { public RegisterFirstTime(Context context, TestParams params) { super(context, params); try { Class clazz = Class.forName("com.squareup.otto.AnnotatedHandlerFinder"); cacheField = clazz.getDeclaredField("SUBSCRIBERS_CACHE"); cacheField.setAccessible(true); } catch (Exception e) { throw new RuntimeException(e); } } @Override public String getDisplayName() { return "Otto Register, first time"; } } public class Subscriber extends Activity { public Subscriber() { } @Subscribe public void onEvent(TestEvent event) { eventsReceivedCount.incrementAndGet(); } public void dummy() { } public void dummy2() { } public void dummy3() { } public void dummy4() { } public void dummy5() { } } private long registerSubscribers() { long time = 0; for (Object subscriber : subscribers) { long timeStart = System.nanoTime(); eventBus.register(subscriber); long timeEnd = System.nanoTime(); time += timeEnd - timeStart; if (canceled) { return 0; } } return time; } private void registerUnregisterOneSubscribers() { if (!subscribers.isEmpty()) { Object subscriber = subscribers.get(0); eventBus.register(subscriber); eventBus.unregister(subscriber); } } } /* * Copyright 2014 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.guvnor.client.screens.clients; import java.util.ArrayList; import javax.enterprise.context.Dependent; import javax.inject.Inject; import com.github.gwtbootstrap.client.ui.NavSearch; import com.github.gwtbootstrap.client.ui.TextBox; import com.google.gwt.cell.client.FieldUpdater; import com.google.gwt.cell.client.TextCell; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.view.client.ListDataProvider; import org.guvnor.messageconsole.client.console.HyperLinkCell; import org.kie.uberfire.client.tables.SimpleTable; import org.uberfire.client.annotations.WorkbenchPartTitle; import org.uberfire.client.annotations.WorkbenchPartView; import org.uberfire.client.annotations.WorkbenchScreen; import org.uberfire.client.mvp.PlaceManager; @Dependent @WorkbenchScreen(identifier = "clientsScreen") public class ClientsScreenPresenter extends Composite { interface Binder extends UiBinder { } private static Binder uiBinder = GWT.create(Binder.class); @UiField SimpleTable table; @Inject private PlaceManager placeManager; public ClientsScreenPresenter() { initWidget(uiBinder.createAndBindUi(this)); TextBox textBox = new TextBox(); textBox.setSearchQuery(true); textBox.setPlaceholder("Search..."); table.getLeftToolbar().add(textBox); Column column = new Column(new HyperLinkCell()) { @Override public HyperLinkCell.HyperLink getValue(String object) { return HyperLinkCell.HyperLink.newLink("third-party"); } }; table.addColumn(column, "OAuth Client Name"); table.addColumn(new Column(new TextCell()) { @Override public String getValue(String object) { return "true"; } }, "Enabled"); column.setFieldUpdater(new FieldUpdater() { @Override public void update(final int index, final String row, final HyperLinkCell.HyperLink value) { placeManager.goTo("oauthClientSettingsScreen"); } }); ListDataProvider dataProvider = new ListDataProvider(); dataProvider.addDataDisplay(table); ArrayList list = new ArrayList(); list.add("mock"); dataProvider.setList(list); } @WorkbenchPartView public Widget getWidget() { return this; } @WorkbenchPartTitle public String getTitle() { return "Clients"; } } package pokecube.core.database.abilities.g; import pokecube.core.database.abilities.Ability; public class GulpMissile extends Ability { // TODO Implement this. } meodaiduoi/onos /* * Copyright 2018-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.onosproject.xmpp.core.ctl.handlers; import com.fasterxml.aalto.stax.OutputFactoryImpl; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToMessageDecoder; import org.dom4j.io.DOMReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLEventWriter; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import javax.xml.transform.dom.DOMResult; import java.util.List; /** * Merges incoming XML events (elements) into XML document. */ public class XmlMerger extends MessageToMessageDecoder { private final Logger logger = LoggerFactory.getLogger(getClass()); protected final XMLOutputFactory xmlOutputFactory = new OutputFactoryImpl(); protected DocumentBuilder docBuilder; protected Document document; protected DOMResult result; protected XMLEventWriter writer; protected int depth; public XmlMerger() throws ParserConfigurationException { initDocBuilder(); this.resetWriter(); } private void initDocBuilder() throws ParserConfigurationException { try { final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setIgnoringElementContentWhitespace(true); docBuilderFactory.setIgnoringComments(true); this.docBuilder = docBuilderFactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw e; } } @Override protected void decode(ChannelHandlerContext ctx, Object object, List out) throws Exception { try { if (object instanceof XMLEvent) { final XMLEvent event = (XMLEvent) object; if (event.isStartDocument() || event.isEndDocument()) { return; } if (event.isCharacters() && depth <= 1) { return; } if (depth < 1 && event.isStartElement()) { out.add(object); depth++; return; } if (depth <= 1 && event.isEndElement()) { out.add(object); depth--; return; } writer.add(event); if (event.isStartElement()) { depth++; } else if (event.isEndElement()) { depth--; if (depth == 1) { writer.flush(); org.dom4j.Element xmlElement = transform().getRootElement(); out.add(xmlElement); writer.close(); resetWriter(); } } } } catch (Exception e) { logger.info(e.getCause().getMessage()); throw e; } } private org.dom4j.Document transform() { org.dom4j.io.DOMReader reader = new DOMReader(); return reader.read(document); } private void resetWriter() { try { document = newDocument(); result = new DOMResult(document); writer = xmlOutputFactory.createXMLEventWriter(result); } catch (XMLStreamException e) { throw new InternalError("Error creating writer"); } } private Document newDocument() { return docBuilder.newDocument(); } } yura-hb/sesame-sampled-pairssamples/686/b.java import java.util.Arrays; class ArgTokenizer { /** * Parses the next token of this tokenizer. */ public void nextToken() { byte ct[] = ctype; int c; int lctype; sval = null; isQuoted = false; do { c = read(); if (c < 0) { return; } lctype = (c < 256) ? ct[c] : unicode2ctype(c); } while (lctype == CT_WHITESPACE); if (lctype == CT_ALPHA) { int i = 0; do { if (i >= buf.length) { buf = Arrays.copyOf(buf, buf.length * 2); } buf[i++] = (char) c; c = read(); lctype = c < 0 ? CT_WHITESPACE : (c < 256) ? ct[c] : unicode2ctype(c); } while (lctype == CT_ALPHA); if (c >= 0) --next; // push last back sval = String.copyValueOf(buf, 0, i); return; } if (lctype == CT_QUOTE) { int quote = c; int i = 0; /* Invariants (because \Octal needs a lookahead): * (i) c contains char value * (ii) d contains the lookahead */ int d = read(); while (d >= 0 && d != quote) { if (d == '\\') { c = read(); int first = c; /* To allow \377, but not \477 */ if (c >= '0' && c <= '7') { c = c - '0'; int c2 = read(); if ('0' <= c2 && c2 <= '7') { c = (c << 3) + (c2 - '0'); c2 = read(); if ('0' <= c2 && c2 <= '7' && first <= '3') { c = (c << 3) + (c2 - '0'); d = read(); } else d = c2; } else d = c2; } else { switch (c) { case 'a': c = 0x7; break; case 'b': c = '\b'; break; case 'f': c = 0xC; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'v': c = 0xB; break; } d = read(); } } else { c = d; d = read(); } if (i >= buf.length) { buf = Arrays.copyOf(buf, buf.length * 2); } buf[i++] = (char) c; } if (d == quote) { isQuoted = true; } sval = String.copyValueOf(buf, 0, i); } } private final byte ctype[] = new byte[256]; private String sval; private boolean isQuoted = false; private static final byte CT_WHITESPACE = 1; private static final byte CT_ALPHA = 0; private char buf[] = new char[20]; private int next = 0; private static final byte CT_QUOTE = 8; private final int length; private final String str; /** * Reads a single character. * * @return The character read, or -1 if the end of the stream has been * reached */ private int read() { if (next >= length) { return -1; } return str.charAt(next++); } private int unicode2ctype(int c) { switch (c) { case 0x1680: case 0x180E: case 0x200A: case 0x202F: case 0x205F: case 0x3000: return CT_WHITESPACE; default: return CT_ALPHA; } } } src/main/java/net/webcumo/tests/kafka/messaging/CalculatableMessage.java package net.webcumo.tests.kafka.messaging; import lombok.Data; import java.io.Serializable; @Data public class CalculatableMessage implements Serializable { private String message; private String responseTopic; } package it.almaviva.cordovaplugins; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.AssetManager; import android.net.Uri; import android.os.Environment; import android.util.Log; import org.apache.cordova.CordovaWebView; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaInterface; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class InAppPdf extends CordovaPlugin { private Context c; /** * Constructor. */ public InAppPdf() { } /** * Sets the context of the Command. This can then be used to do things like * get file paths associated with the Activity. * * @param cordova The context of the main Activity. * @param webView The CordovaWebView Cordova is running in. */ public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackContext The callback id used when calling back into JavaScript. * @return True if the action was valid, false if not. */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("show")) { JSONObject r = args.getJSONObject(0); String targetPath = r.optString("targetPath"); c = this.cordova.getActivity().getApplicationContext(); AssetManager assetManager = c.getAssets(); InputStream in = null; OutputStream out = null; //File file = new File(c.getFilesDir(), "abc.pdf"); //File file = new File(targetPath); /*try { in = assetManager.open("abc.pdf"); out = c.openFileOutput(file.getName(), Context.MODE_WORLD_READABLE); copyFile(in, out); in.close(); in = null; out.flush(); out.close(); out = null; } catch (Exception e) { Log.e("tag", e.getMessage()); }*/ //file = new File("file://" + c.getFilesDir() + "/abc.pdf"); Intent target = new Intent(Intent.ACTION_VIEW); target.setDataAndType(Uri.parse(targetPath),"application/pdf"); target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); target.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Intent intent = Intent.createChooser(target, "Open File"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { c.startActivity(intent); } catch (ActivityNotFoundException e) { // No application to view, ask to download one AlertDialog.Builder builder = new AlertDialog.Builder(c); builder.setTitle("No Viewer"); builder.setMessage("Download PDF Viewer?"); builder.setPositiveButton("Okay", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent innerIntent = new Intent( Intent.ACTION_VIEW); innerIntent.setData(Uri .parse("market://details?id=com.adobe.reader")); innerIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); InAppPdf.this.c.startActivity(innerIntent); } }); //builder.setNegativeButton("Cancel"), null); builder.create().show(); } callbackContext.success(r); } else { return false; } return true; } private void copyFile(InputStream in, OutputStream out) throws IOException { byte[] buffer = new byte[1024]; int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } } } 0 package org.metahut.octopus.server.controller; import org.metahut.octopus.api.dto.MetaDatabaseResponseDTO; import org.metahut.octopus.api.dto.MetaDatasetResponseDTO; import org.metahut.octopus.api.dto.MetaDatasourceResponseDTO; import org.metahut.octopus.api.dto.PageResponseDTO; import org.metahut.octopus.api.dto.ResultEntity; import org.metahut.octopus.scheduler.dolphinscheduler.JSONUtils; import org.metahut.octopus.server.WebMvcApplicationTest; import org.metahut.octopus.server.service.MetaService; import com.fasterxml.jackson.core.type.TypeReference; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.BDDMockito; import org.mockito.Mockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.Arrays; public class MetaControllerImplTest extends WebMvcApplicationTest { private static final String REST_FUNCTION_URL_PREFIX = "/meta/"; @MockBean private MetaService metaService; @Test public void queryDatasourceListPage() throws Exception { String url = REST_FUNCTION_URL_PREFIX + "queryDatasourceListPage"; MetaDatasourceResponseDTO responseDTO = new MetaDatasourceResponseDTO(); responseDTO.setType("Hive"); responseDTO.setCode("1"); responseDTO.setName("HIVE-IDC"); BDDMockito.given(this.metaService.queryDatasourceListPage(Mockito.argThat(request -> "Hive".equals(request.getType())))) .willReturn(PageResponseDTO.of(1, 100, 1L, Arrays.asList(responseDTO))); MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(url) .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) .param("type", "Hive")) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); String result = mvcResult.getResponse().getContentAsString(); ResultEntity resultEntity = JSONUtils.parseObject(result, new TypeReference>() { }); Assertions.assertTrue(resultEntity.isSuccess()); Assertions.assertNotNull(resultEntity.getData()); } @Test public void queryDatabaseListPage() throws Exception { String url = REST_FUNCTION_URL_PREFIX + "queryDatabaseListPage"; MetaDatabaseResponseDTO responseDTO = new MetaDatabaseResponseDTO(); responseDTO.setCode("1"); responseDTO.setName("dwd"); BDDMockito.given(this.metaService.queryDatabaseListPage(Mockito.any())) .willReturn(PageResponseDTO.of(1, 100, 1L, Arrays.asList(responseDTO))); MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(url) .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) .param("dataSourceType", "Hive") .param("name", "dwd")) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); String result = mvcResult.getResponse().getContentAsString(); ResultEntity resultEntity = JSONUtils.parseObject(result, new TypeReference>() { }); Assertions.assertTrue(resultEntity.isSuccess()); Assertions.assertNotNull(resultEntity.getData()); } @Test public void queryDatasetListPage() throws Exception { String url = REST_FUNCTION_URL_PREFIX + "queryDatasetList"; MetaDatasetResponseDTO responseDTO = new MetaDatasetResponseDTO(); responseDTO.setCode("1"); responseDTO.setName("dwd_xxx"); BDDMockito.given(this.metaService.queryDatasetListPage(Mockito.any())) .willReturn(PageResponseDTO.of(1, 100, 1L, Arrays.asList(responseDTO))); MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get(url) .contentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE) .param("dataSourceType", "Hive")) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); String result = mvcResult.getResponse().getContentAsString(); ResultEntity resultEntity = JSONUtils.parseObject(result, new TypeReference>() { }); Assertions.assertTrue(resultEntity.isSuccess()); Assertions.assertNotNull(resultEntity.getData()); } } /** * Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy) * * 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.commonjava.indy.core.bind.jaxrs.admin; import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.commonjava.indy.IndyWorkflowException; import org.commonjava.indy.bind.jaxrs.IndyResources; import org.commonjava.indy.bind.jaxrs.util.REST; import org.commonjava.indy.bind.jaxrs.util.ResponseHelper; import org.commonjava.indy.core.ctl.SchedulerController; import org.commonjava.indy.core.expire.Expiration; import org.commonjava.indy.core.expire.ExpirationSet; import org.commonjava.indy.model.core.StoreKey; import org.commonjava.indy.model.core.StoreType; import org.commonjava.indy.util.ApplicationContent; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Response; import java.nio.file.Paths; import static org.commonjava.indy.pkg.maven.model.MavenPackageTypeDescriptor.MAVEN_PKG_KEY; @Api( value = "Schedules and Expirations", description = "Retrieve and manipulate scheduled expirations for various parts of Indy" ) @Path( "/api/admin/schedule" ) @Produces( ApplicationContent.application_json ) @REST public class SchedulerHandler implements IndyResources { @Inject private SchedulerController controller; @Inject private ObjectMapper objectMapper; @Inject private ResponseHelper responseHelper; @ApiOperation( "[Deprecated] Retrieve the expiration information related to re-enablement of a repository" ) @ApiResponses( { @ApiResponse( code = 200, message = "Expiration information retrieved successfully.", response = Expiration.class ), @ApiResponse( code = 400, message = "Store is manually disabled (doesn't automatically re-enable), or isn't disabled." ) } ) @Path( "store/{type: (hosted|group|remote)}/{name}/disable-timeout" ) @GET @Deprecated public Response deprecatedGetStoreDisableTimeout( @ApiParam( allowableValues = "hosted,group,remote", required=true ) @PathParam( "type" ) String storeType, @ApiParam( required=true ) @PathParam( "name" ) String storeName ) { StoreType type = StoreType.get( storeType ); String altPath = Paths.get( "/api/admin/schedule", MAVEN_PKG_KEY, type.singularEndpointName(), storeName ).toString(); StoreKey storeKey = new StoreKey( type, storeName ); Expiration timeout = null; try { timeout = controller.getStoreDisableTimeout( storeKey ); if ( timeout == null ) { throw new WebApplicationException( Response.Status.NOT_FOUND ); } return responseHelper.formatOkResponseWithJsonEntity( timeout, rb -> responseHelper.markDeprecated( rb, altPath ) ); } catch ( IndyWorkflowException e ) { responseHelper.throwError( e, rb->responseHelper.markDeprecated( rb, altPath ) ); } return null; } @ApiOperation( "Retrieve the expiration information related to re-enablement of a repository" ) @ApiResponses( { @ApiResponse( code = 200, message = "Expiration information retrieved successfully.", response = Expiration.class ), @ApiResponse( code = 400, message = "Store is manually disabled (doesn't automatically re-enable), or isn't disabled." ) } ) @Path( "store/{packageType}/{type: (hosted|group|remote)}/{name}/disable-timeout" ) @GET public Expiration getStoreDisableTimeout( @ApiParam( value = "Package type (maven, generic-http, npm, etc)", required = true ) @PathParam( "packageType" ) String packageType, @ApiParam( allowableValues = "hosted,group,remote", required = true ) @PathParam( "type" ) String storeType, @ApiParam( required = true ) @PathParam( "name" ) String storeName ) { StoreKey storeKey = new StoreKey( packageType, StoreType.get( storeType ), storeName ); Expiration timeout = null; try { timeout = controller.getStoreDisableTimeout( storeKey ); } catch ( IndyWorkflowException e ) { responseHelper.throwError( e ); } if ( timeout == null ) { throw new WebApplicationException( Response.Status.NOT_FOUND ); } return timeout; } @ApiOperation( "Retrieve the expiration information related to re-enablement of any currently disabled repositories" ) @ApiResponse( code = 200, message = "List of disabled repository re-enablement timeouts.", response = ExpirationSet.class ) @Path( "store/all/disable-timeout" ) @GET public ExpirationSet getDisabledStores() { try { return controller.getDisabledStores(); } catch ( IndyWorkflowException e ) { responseHelper.throwError( e ); } throw new WebApplicationException( "Impossible Error", 500 ); } } package net.bvargo.airplay; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; /** * Thread that posts a desktop screenshot to the AirPlay at a given interval. */ class DesktopPoster extends Thread { // color/radius of the mouse pointer private static final Color COLOR = Color.RED; private static final int RADIUS = 10; private final AirPlay airplay; private final int interval; /** * @param interval Interval, in ms, at which the desktop image should be * posted. */ public DesktopPoster(AirPlay airplay, int interval) { this.airplay = airplay; this.interval = interval; } @Override public void run() { while(!Thread.interrupted()) { BufferedImage image = this.captureScreen(); if(image != null) { try { airplay.showImage(image, Transition.NONE); try { Thread.sleep(this.interval); } catch(InterruptedException e) { // stop running break; } } catch(IOException e) { System.err.println("Could not post image: " + e); } } } } /** * Captures the screen. * * @return null if a screenshot could not be taken. */ private BufferedImage captureScreen() { Toolkit tk = Toolkit.getDefaultToolkit(); Dimension dim = tk.getScreenSize(); Rectangle rect = new Rectangle(dim); Robot robot = null; try { robot = new Robot(); } catch(AWTException e) { return null; } BufferedImage image = robot.createScreenCapture(rect); // draw an oval where the mouse pointer is, since the screen capture // does not include the pointer int x = MouseInfo.getPointerInfo().getLocation().x; int y = MouseInfo.getPointerInfo().getLocation().y; Graphics g = image.createGraphics(); g.setColor(COLOR); g.fillOval(x - RADIUS, y - RADIUS, RADIUS * 2, RADIUS * 2); g.dispose(); return image; } } package com.hortonworks.streaming.interfaces; public interface DomainObject { } src/main/java/com/opsmatters/media/db/dao/monitor/ContentReviewDAO.java /* * Copyright 2021 * * 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.opsmatters.media.db.dao.monitor; import java.util.List; import java.util.ArrayList; import java.sql.Types; import java.sql.PreparedStatement; import java.sql.Timestamp; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Logger; import com.opsmatters.media.model.monitor.ContentReview; import com.opsmatters.media.model.monitor.ReviewStatus; /** * DAO that provides operations on the CONTENT_REVIEWS table in the database. * * @author (opsmatters) */ public class ContentReviewDAO extends MonitorDAO { private static final Logger logger = Logger.getLogger(ContentReviewDAO.class.getName()); /** * The query to use to select a review from the CONTENT_REVIEWS table by id. */ private static final String GET_BY_ID_SQL = "SELECT ID, CREATED_DATE, UPDATED_DATE, EFFECTIVE_DATE, CODE, REASON, STATUS, MONITOR_ID, NOTES, \"CHANGE\", CREATED_BY " + "FROM CONTENT_REVIEWS WHERE ID=?"; /** * The query to use to insert a review into the CONTENT_REVIEWS table. */ private static final String INSERT_SQL = "INSERT INTO CONTENT_REVIEWS" + "( ID, CREATED_DATE, UPDATED_DATE, EFFECTIVE_DATE, CODE, REASON, STATUS, MONITOR_ID, NOTES, \"CHANGE\", CREATED_BY )" + "VALUES" + "( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"; /** * The query to use to update a review in the CONTENT_REVIEWS table. */ private static final String UPDATE_SQL = "UPDATE CONTENT_REVIEWS SET UPDATED_DATE=?, STATUS=?, NOTES=?, \"CHANGE\"=?, CREATED_BY=? " + "WHERE ID=?"; /** * The query to use to select the reviews from the CONTENT_REVIEWS table. */ private static final String LIST_SQL = "SELECT CR.ID, CR.CREATED_DATE, CR.UPDATED_DATE, EFFECTIVE_DATE, CR.CODE, REASON, CR.STATUS, MONITOR_ID, NOTES, \"CHANGE\", CREATED_BY " + "FROM CONTENT_REVIEWS CR, CONTENT_MONITORS CM " + "WHERE CR.MONITOR_ID = CM.ID AND (CR.CREATED_DATE >= (NOW() + INTERVAL -30 DAY) OR CR.STATUS='NEW') ORDER BY CR.CREATED_DATE"; /** * The query to use to select the reviews from the CONTENT_REVIEWS table by status. */ private static final String LIST_BY_STATUS_SQL = "SELECT CR.ID, CR.CREATED_DATE, CR.UPDATED_DATE, EFFECTIVE_DATE, CR.CODE, REASON, CR.STATUS, MONITOR_ID, NOTES, \"CHANGE\", CREATED_BY " + "FROM CONTENT_REVIEWS CR, CONTENT_MONITORS CM " + "WHERE CR.MONITOR_ID = CM.ID AND CR.STATUS=? AND (CR.CREATED_DATE >= (NOW() + INTERVAL -30 DAY) OR CR.STATUS='NEW') ORDER BY CR.CREATED_DATE"; /** * The query to use to get the count of reviews from the CONTENT_REVIEWS table. */ private static final String COUNT_SQL = "SELECT COUNT(*) FROM CONTENT_REVIEWS"; /** * The query to use to delete a review from the CONTENT_REVIEWS table. */ private static final String DELETE_SQL = "DELETE FROM CONTENT_REVIEWS WHERE ID=?"; /** * Constructor that takes a DAO factory. */ public ContentReviewDAO(MonitorDAOFactory factory) { super(factory, "CONTENT_REVIEWS"); } /** * Defines the columns and indices for the CONTENT_REVIEWS table. */ @Override protected void defineTable() { table.addColumn("ID", Types.VARCHAR, 36, true); table.addColumn("CREATED_DATE", Types.TIMESTAMP, true); table.addColumn("UPDATED_DATE", Types.TIMESTAMP, false); table.addColumn("EFFECTIVE_DATE", Types.TIMESTAMP, false); table.addColumn("CODE", Types.VARCHAR, 5, true); table.addColumn("REASON", Types.VARCHAR, 15, true); table.addColumn("STATUS", Types.VARCHAR, 15, true); table.addColumn("MONITOR_ID", Types.VARCHAR, 36, true); table.addColumn("NOTES", Types.VARCHAR, 256, false); table.addColumn("CHANGE", Types.BOOLEAN, true); table.addColumn("CREATED_BY", Types.VARCHAR, 15, true); table.setPrimaryKey("CONTENT_REVIEWS_PK", new String[] {"ID"}); table.addIndex("CONTENT_REVIEWS_STATUS_IDX", new String[] {"STATUS"}); table.setInitialised(true); } /** * Returns a review from the CONTENT_REVIEWS table by id. */ public synchronized ContentReview getById(String id) throws SQLException { ContentReview ret = null; if(!hasConnection()) return ret; preQuery(); if(getByIdStmt == null) getByIdStmt = prepareStatement(getConnection(), GET_BY_ID_SQL); clearParameters(getByIdStmt); ResultSet rs = null; try { getByIdStmt.setString(1, id); getByIdStmt.setQueryTimeout(QUERY_TIMEOUT); rs = getByIdStmt.executeQuery(); while(rs.next()) { ContentReview review = new ContentReview(); review.setId(rs.getString(1)); review.setCreatedDateMillis(rs.getTimestamp(2, UTC).getTime()); review.setUpdatedDateMillis(rs.getTimestamp(3, UTC) != null ? rs.getTimestamp(3, UTC).getTime() : 0L); review.setEffectiveDateMillis(rs.getTimestamp(4, UTC) != null ? rs.getTimestamp(4, UTC).getTime() : 0L); review.setCode(rs.getString(5)); review.setReason(rs.getString(6)); review.setStatus(rs.getString(7)); review.setMonitorId(rs.getString(8)); review.setNotes(rs.getString(9)); review.setChange(rs.getBoolean(10)); review.setCreatedBy(rs.getString(11)); ret = review; } } finally { try { if(rs != null) rs.close(); } catch (SQLException ex) { } } postQuery(); return ret; } /** * Stores the given review in the CONTENT_REVIEWS table. */ public synchronized void add(ContentReview review) throws SQLException { if(!hasConnection() || review == null) return; if(insertStmt == null) insertStmt = prepareStatement(getConnection(), INSERT_SQL); clearParameters(insertStmt); try { insertStmt.setString(1, review.getId()); insertStmt.setTimestamp(2, new Timestamp(review.getCreatedDateMillis()), UTC); insertStmt.setTimestamp(3, new Timestamp(review.getUpdatedDateMillis()), UTC); insertStmt.setTimestamp(4, new Timestamp(review.getEffectiveDateMillis()), UTC); insertStmt.setString(5, review.getCode()); insertStmt.setString(6, review.getReason().name()); insertStmt.setString(7, review.getStatus().name()); insertStmt.setString(8, review.getMonitorId()); insertStmt.setString(9, review.getNotes()); insertStmt.setBoolean(10, review.hasChange()); insertStmt.setString(11, review.getCreatedBy()); insertStmt.executeUpdate(); logger.info("Created review '"+review.getId()+"' in CONTENT_REVIEWS"); } catch(SQLException ex) { // SQLite closes the statement on an exception if(getDriver().closeOnException()) { closeStatement(insertStmt); insertStmt = null; } // Unique constraint violated means that the review already exists if(!getDriver().isConstraintViolation(ex)) throw ex; } } /** * Updates the given review in the CONTENT_REVIEWS table. */ public synchronized void update(ContentReview review) throws SQLException { if(!hasConnection() || review == null) return; if(updateStmt == null) updateStmt = prepareStatement(getConnection(), UPDATE_SQL); clearParameters(updateStmt); updateStmt.setTimestamp(1, new Timestamp(review.getUpdatedDateMillis()), UTC); updateStmt.setString(2, review.getStatus().name()); updateStmt.setString(3, review.getNotes()); updateStmt.setBoolean(4, review.hasChange()); updateStmt.setString(5, review.getCreatedBy()); updateStmt.setString(6, review.getId()); updateStmt.executeUpdate(); logger.info("Updated review '"+review.getId()+"' in CONTENT_REVIEWS"); } /** * Returns the reviews from the CONTENT_REVIEWS table. */ public synchronized List list() throws SQLException { List ret = null; if(!hasConnection()) return ret; preQuery(); if(listStmt == null) listStmt = prepareStatement(getConnection(), LIST_SQL); clearParameters(listStmt); ResultSet rs = null; try { listStmt.setQueryTimeout(QUERY_TIMEOUT); rs = listStmt.executeQuery(); ret = new ArrayList(); while(rs.next()) { ContentReview review = new ContentReview(); review.setId(rs.getString(1)); review.setCreatedDateMillis(rs.getTimestamp(2, UTC).getTime()); review.setUpdatedDateMillis(rs.getTimestamp(3, UTC) != null ? rs.getTimestamp(3, UTC).getTime() : 0L); review.setEffectiveDateMillis(rs.getTimestamp(4, UTC) != null ? rs.getTimestamp(4, UTC).getTime() : 0L); review.setCode(rs.getString(5)); review.setReason(rs.getString(6)); review.setStatus(rs.getString(7)); review.setMonitorId(rs.getString(8)); review.setNotes(rs.getString(9)); review.setChange(rs.getBoolean(10)); review.setCreatedBy(rs.getString(11)); ret.add(review); } } finally { try { if(rs != null) rs.close(); } catch (SQLException ex) { } } postQuery(); return ret; } /** * Returns the reviews from the CONTENT_REVIEWS table by status. */ public synchronized List list(ReviewStatus status) throws SQLException { List ret = null; if(!hasConnection()) return ret; preQuery(); if(listByStatusStmt == null) listByStatusStmt = prepareStatement(getConnection(), LIST_BY_STATUS_SQL); clearParameters(listByStatusStmt); ResultSet rs = null; try { listByStatusStmt.setString(1, status.name()); listByStatusStmt.setQueryTimeout(QUERY_TIMEOUT); rs = listByStatusStmt.executeQuery(); ret = new ArrayList(); while(rs.next()) { ContentReview review = new ContentReview(); review.setId(rs.getString(1)); review.setCreatedDateMillis(rs.getTimestamp(2, UTC).getTime()); review.setUpdatedDateMillis(rs.getTimestamp(3, UTC) != null ? rs.getTimestamp(3, UTC).getTime() : 0L); review.setEffectiveDateMillis(rs.getTimestamp(4, UTC) != null ? rs.getTimestamp(4, UTC).getTime() : 0L); review.setCode(rs.getString(5)); review.setReason(rs.getString(6)); review.setStatus(rs.getString(7)); review.setMonitorId(rs.getString(8)); review.setNotes(rs.getString(9)); review.setChange(rs.getBoolean(10)); review.setCreatedBy(rs.getString(11)); ret.add(review); } } finally { try { if(rs != null) rs.close(); } catch (SQLException ex) { } } postQuery(); return ret; } /** * Returns the count of reviews from the table. */ public int count() throws SQLException { if(!hasConnection()) return -1; if(countStmt == null) countStmt = prepareStatement(getConnection(), COUNT_SQL); clearParameters(countStmt); countStmt.setQueryTimeout(QUERY_TIMEOUT); ResultSet rs = countStmt.executeQuery(); rs.next(); return rs.getInt(1); } /** * Removes the given review from the CONTENT_REVIEWS table. */ public synchronized void delete(ContentReview review) throws SQLException { if(!hasConnection() || review == null) return; if(deleteStmt == null) deleteStmt = prepareStatement(getConnection(), DELETE_SQL); clearParameters(deleteStmt); deleteStmt.setString(1, review.getId()); deleteStmt.executeUpdate(); logger.info("Deleted review '"+review.getId()+"' in CONTENT_REVIEWS"); } /** * Close any resources associated with this DAO. */ @Override protected void close() { closeStatement(getByIdStmt); getByIdStmt = null; closeStatement(insertStmt); insertStmt = null; closeStatement(updateStmt); updateStmt = null; closeStatement(listStmt); listStmt = null; closeStatement(listByStatusStmt); listByStatusStmt = null; closeStatement(countStmt); countStmt = null; closeStatement(deleteStmt); deleteStmt = null; } private PreparedStatement getByIdStmt; private PreparedStatement insertStmt; private PreparedStatement updateStmt; private PreparedStatement listStmt; private PreparedStatement listByStatusStmt; private PreparedStatement countStmt; private PreparedStatement deleteStmt; } 10-100 package com.javayh; //import com.spring4all.mongodb.EnableMongoPlus; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; //@EnableMongoPlus @SpringBootApplication public class JavayhMongodbApplication { public static void main(String[] args) { SpringApplication.run(JavayhMongodbApplication.class, args); } } /* * 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. */ /* $Id$ */ package org.apache.fop.afp; /** * A common class used to convey locations, * dimensions and resolutions of data objects. */ public class AFPObjectAreaInfo { private final int x; private final int y; private final int width; private final int height; private int widthRes; private int heightRes; private final int rotation; /** * Constructor * * @param x the x coordinate * @param y the y coordinate * @param width the width * @param height the height * @param resolution the resolution (sets both width and height resolutions) * @param rotation the rotation angle */ public AFPObjectAreaInfo(int x, int y, int width, int height, int resolution, int rotation) { this.x = x; this.y = y; this.width = width; this.height = height; this.rotation = rotation; this.widthRes = resolution; this.heightRes = resolution; } /** * Sets both the width and the height resolutions. * * @param resolution the resolution */ public void setResolution(int resolution) { this.widthRes = resolution; this.heightRes = resolution; } /** * Sets the width resolution. * * @param resolution the resolution */ public void setWidthRes(int resolution) { this.widthRes = resolution; } /** * Sets the height resolution. * * @param resolution the resolution */ public void setHeightRes(int resolution) { this.heightRes = resolution; } /** * Returns the x coordinate of this data object * * @return the x coordinate of this data object */ public int getX() { return x; } /** * Returns the y coordinate of this data object * * @return the y coordinate of this data object */ public int getY() { return y; } /** * Returns the width of this data object * * @return the width of this data object */ public int getWidth() { return width; } /** * Returns the height of this data object * * @return the height of this data object */ public int getHeight() { return height; } /** * Returns the width resolution of this data object * * @return the resolution of this data object */ public int getWidthRes() { return widthRes; } /** * Returns the height resolution of this data object * * @return the resolution of this data object */ public int getHeightRes() { return heightRes; } /** * Returns the rotation of this data object * * @return the rotation of this data object */ public int getRotation() { return rotation; } /** {@inheritDoc} */ public String toString() { return "x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + ", widthRes=" + widthRes + ", heigtRes=" + heightRes + ", rotation=" + rotation; } } app/utils/Utils.java package utils; import java.io.IOException; import java.io.StringWriter; import java.time.Instant; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class Utils { static ObjectMapper objectMapper = new ObjectMapper(); public static String getJsonStringFromObject(Object obj) throws JsonGenerationException, JsonMappingException, IOException { StringWriter writer = new StringWriter(); objectMapper.writeValue(writer, obj); return writer.toString(); } public static JsonNode convertObjectToJsonNode(Object object) { JsonNode jsonAdObject = objectMapper.valueToTree(object); return jsonAdObject; } static public Integer generateThreadId() { Long currentEpocTime = Instant.now().getEpochSecond(); Long randomNumber = currentEpocTime/987+(currentEpocTime%10000000); return randomNumber.intValue(); } static public Integer generateMailId() { Long currentEpocTime = Instant.now().getEpochSecond(); Long randomNumber = currentEpocTime/458+(currentEpocTime%100000); return randomNumber.intValue(); } } package cmccsi.mhealth.app.sports.db; import java.util.ArrayList; import java.util.List; import cmccsi.mhealth.app.sports.bean.GPSListInfo; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.provider.BaseColumns; public class GPSListMetaData implements BaseColumns{ public static final String TABLE_NAME = "list_gpsinfo"; private static final String START_TIME = "starttime"; private static final String DURATION = "duration"; private static final String SPEED = "speed"; private static final String DISTANCE = "distance"; private static final String CAL = "cal"; private static final String STEPNUM = "stepNum"; private static final String DURATIONPERKM = "durationperkm"; private static final String SPEEDMAX = "speedmax"; private static final String SPEEDMIN = "speedmin"; private static final String CLIMBSUM = "climbsum"; private static final String SPORTTYPE = "sporttype"; private static final String ISUPLOAD = "isupload"; public static final String CREATE_TABLE = "create table " + TABLE_NAME + " (" + _ID + " integer primary key autoincrement," + START_TIME + " text," + DURATION + " text," + SPEED + " float," + DISTANCE + " float," + CAL + " float," + STEPNUM + " text," + DURATIONPERKM + " text," + SPEEDMAX + " text," + SPEEDMIN + " text," + CLIMBSUM + " text," + ISUPLOAD + " int," + SPORTTYPE + " int" +")"; public static String deleteSql(String starttime){ return "DELETE FROM "+TABLE_NAME+" WHERE "+START_TIME+" = '"+starttime+"' "; } public static boolean deleteData(DatabaseHelper dbHelper,String sql){ SQLiteDatabase db = dbHelper.getReadableDatabase(); try { db.execSQL(sql); } catch (Exception e) { e.printStackTrace(); }finally{ } return true; } public static void DeleteListGPSData(DatabaseHelper dbHelper) { SQLiteDatabase db = dbHelper.getWritableDatabase(); db.execSQL("DELETE FROM " + TABLE_NAME); } public static void AllPointInsert(DatabaseHelper dbHelper, GPSListInfo gpsInfo) { ContentValues values = new ContentValues(); SQLiteDatabase db = dbHelper.getWritableDatabase(); db.beginTransaction(); // for (int i = 0; i < arrGeoPoint.size(); i++) { values.put(START_TIME, gpsInfo.getStarttime()); values.put(SPEED, gpsInfo.getSpeed()); values.put(DISTANCE, gpsInfo.getDistance()); values.put(CAL, gpsInfo.getCal()); values.put(DURATION, gpsInfo.getDuration()); values.put(STEPNUM, gpsInfo.getStepNum()); values.put(DURATIONPERKM, gpsInfo.getDurationperkm()); values.put(SPEEDMAX, gpsInfo.getSpeedmax()); values.put(SPEEDMIN, gpsInfo.getSpeedmin()); values.put(CLIMBSUM, gpsInfo.getClimbsum()); values.put(SPORTTYPE, gpsInfo.getSporttype()); values.put(ISUPLOAD, gpsInfo.getIsUpload()); db.insert(TABLE_NAME, null, values); // } db.setTransactionSuccessful(); db.endTransaction(); } // public static List getHistoryStartTimeArr(DatabaseHelper dbHelper) { // List date = new ArrayList(); // String sql = "select "+START_TIME+" from " + TABLE_NAME; // Cursor cursor = null; // try { // SQLiteDatabase db = dbHelper.getReadableDatabase(); // db.beginTransaction(); // cursor = db.rawQuery(sql, null); // while (cursor.moveToNext()) { // date.add(cursor.getString(cursor.getColumnIndex(START_TIME))); // } // db.setTransactionSuccessful(); // db.endTransaction(); // } catch (Exception e) { // e.printStackTrace(); // } finally { // if (cursor != null) // cursor.close(); // } // return date; // } public static List getListGPSData(DatabaseHelper dbHelper) { List date = new ArrayList(); String sql = "select * from " + TABLE_NAME + " ORDER BY " + START_TIME +" DESC "; Cursor cursor = null; SQLiteDatabase db = null; try { db = dbHelper.getReadableDatabase(); cursor = db.rawQuery(sql, null); while (cursor.moveToNext()) { GPSListInfo gpsInfo = new GPSListInfo(); gpsInfo.setStarttime(cursor.getString(cursor.getColumnIndex(START_TIME))); gpsInfo.setSpeed(cursor.getFloat(cursor.getColumnIndex(SPEED))); gpsInfo.setDistance(cursor.getFloat(cursor.getColumnIndex(DISTANCE))); gpsInfo.setCal(cursor.getFloat(cursor.getColumnIndex(CAL))); gpsInfo.setDuration(cursor.getString(cursor.getColumnIndex(DURATION))); gpsInfo.setStepNum(cursor.getString(cursor.getColumnIndex(STEPNUM))); gpsInfo.setDurationperkm(cursor.getString(cursor.getColumnIndex(DURATIONPERKM))); gpsInfo.setSpeedmax(cursor.getString(cursor.getColumnIndex(SPEEDMAX))); gpsInfo.setSpeedmin(cursor.getString(cursor.getColumnIndex(SPEEDMIN))); gpsInfo.setClimbsum(cursor.getString(cursor.getColumnIndex(CLIMBSUM))); gpsInfo.setSporttype(cursor.getInt(cursor.getColumnIndex(SPORTTYPE))); gpsInfo.setIsUpload(cursor.getInt(cursor.getColumnIndex(ISUPLOAD))); date.add(gpsInfo); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) cursor.close(); } return date; } public static List getListGPSDataByIsload(DatabaseHelper dbHelper,String isload) { List date = new ArrayList(); String sql = "select * from " + TABLE_NAME +" where "+ISUPLOAD+" = '"+isload+"' ORDER BY " + START_TIME +" DESC "; Cursor cursor = null; SQLiteDatabase db = null; try { db = dbHelper.getReadableDatabase(); cursor = db.rawQuery(sql, null); while (cursor.moveToNext()) { GPSListInfo gpsInfo = new GPSListInfo(); gpsInfo.setStarttime(cursor.getString(cursor.getColumnIndex(START_TIME))); gpsInfo.setSpeed(cursor.getFloat(cursor.getColumnIndex(SPEED))); gpsInfo.setDistance(cursor.getFloat(cursor.getColumnIndex(DISTANCE))); gpsInfo.setCal(cursor.getFloat(cursor.getColumnIndex(CAL))); gpsInfo.setDuration(cursor.getString(cursor.getColumnIndex(DURATION))); gpsInfo.setStepNum(cursor.getString(cursor.getColumnIndex(STEPNUM))); gpsInfo.setDurationperkm(cursor.getString(cursor.getColumnIndex(DURATIONPERKM))); gpsInfo.setSpeedmax(cursor.getString(cursor.getColumnIndex(SPEEDMAX))); gpsInfo.setSpeedmin(cursor.getString(cursor.getColumnIndex(SPEEDMIN))); gpsInfo.setClimbsum(cursor.getString(cursor.getColumnIndex(CLIMBSUM))); gpsInfo.setSporttype(cursor.getInt(cursor.getColumnIndex(SPORTTYPE))); gpsInfo.setIsUpload(cursor.getInt(cursor.getColumnIndex(ISUPLOAD))); date.add(gpsInfo); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) cursor.close(); } return date; } public static String getDataByStartTime(DatabaseHelper dbHelper,String starttime) { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = null; String sql = "select "+START_TIME+" from "+TABLE_NAME+" where "+START_TIME+" = '"+starttime+"'"; try { cursor = db.rawQuery(sql, null); if(cursor.moveToNext()) return cursor.getString(cursor.getColumnIndex(START_TIME)); } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) cursor.close(); } return null; } public static boolean updateIsLoadData(DatabaseHelper dbHelper,String isload,String starttime){ SQLiteDatabase db = dbHelper.getReadableDatabase(); db.beginTransaction(); String sql = "update "+TABLE_NAME+" set "+ISUPLOAD+" = '"+isload+"' where "+START_TIME+"= '"+starttime+"' "; try { db.execSQL(sql); } catch (Exception e) { e.printStackTrace(); return false; }finally{ } db.setTransactionSuccessful(); db.endTransaction(); return true; } // // private static Cursor getGeoPointCursor(SQLiteDatabase db,String starttime) { // String sql = "select * from " + TABLE_NAME + " where "+START_TIME+" = '" + starttime + "' "; // Cursor cursor = db.rawQuery(sql, null); // return cursor; // } // public static int getPointCount(DatabaseHelper dbHelper) { // SQLiteDatabase db = dbHelper.getReadableDatabase(); // Cursor cursor = null; // try { // cursor = db.rawQuery("select count(*)from " + TABLE_NAME + "", null); // cursor.moveToFirst(); // int count = cursor.getInt(0); // return count; // } finally { // if (cursor != null) // cursor.close(); // } // } } package de.konfidas.ttc.messages.systemlogs; import de.konfidas.ttc.exceptions.BadFormatForLogMessageException; import de.konfidas.ttc.messages.SystemLogMessage; import de.konfidas.ttc.utilities.DLTaggedObjectConverter; import org.bouncycastle.asn1.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; /** * Diese Klasse repräsentiert eine configureLogging Message. Dabei werden in der Methode * parseSystemOperationDataContent die folgenden Elemente aus systemOperationData geparst *
 * ╔═══════════════════════╤══════╤═══════════════════════════════════════════════════════════════╤════════════╗
 * ║ Data field            │ Tag  │ Data Type                                                     │ Mandatory? ║
 * ╠═══════════════════════╪══════╪═══════════════════════════════════════════════════════════════╪════════════╣
 * ║ componentName         │ 0x81 │ PrintableString                                               │ m          ║
 * ╟───────────────────────┼──────┼───────────────────────────────────────────────────────────────┼────────────╢
 * ║ result                │ 0x82 │ Boolean                                                       │ m          ║
 * ╟───────────────────────┼──────┼───────────────────────────────────────────────────────────────┼────────────╢
 * ║ parameters            │ 0x83 │ OCTECTSTRING                                                  │ c          ║
 * ╚═══════════════════════╧══════╧══════════════════════════════════╧═════════════════════════════════════════╝
 * 
*/ public class ConfigureLoggingSystemLogMessage extends SystemLogMessage { final static Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME); static Locale locale = new Locale("de", "DE");//NON-NLS static ResourceBundle properties = ResourceBundle.getBundle("ttc",locale);//NON-NLS DLTaggedObject componentName; DLTaggedObject result; DLTaggedObject parameters; List loggingParameter; String componentNameAsString; Boolean resultAsBoolean; // String reasonForFailureAsString; public ConfigureLoggingSystemLogMessage(byte[] content, String filename) throws BadFormatForLogMessageException { super(content, filename); } @Override protected void parseSystemOperationDataContent(ASN1InputStream stream) throws SystemLogParsingException, IOException { ASN1Primitive systemOperationData = stream.readObject(); if (!(systemOperationData instanceof ASN1Sequence)) throw new SystemLogParsingException(properties.getString("de.konfidas.ttc.messages.systemlogs.errorParsingSystemOperationDataContent")); List systemOperationDataAsAsn1List = Collections.list(((ASN1Sequence) systemOperationData).getObjects()); ListIterator systemOperationDataIterator = systemOperationDataAsAsn1List.listIterator(); try { //componentName einlesen DLTaggedObject nextElement = (DLTaggedObject) systemOperationDataAsAsn1List.get(systemOperationDataIterator.nextIndex()); if (nextElement.getTagNo() != 1) throw new SystemLogParsingException(properties.getString("de.konfidas.ttc.messages.systemlogs.errorComonentNameNotFound")); this.componentName = (DLTaggedObject) systemOperationDataIterator.next(); this.componentNameAsString = DLTaggedObjectConverter.dLTaggedObjectToString(this.componentName); //result nextElement = (DLTaggedObject) systemOperationDataAsAsn1List.get(systemOperationDataIterator.nextIndex()); if (nextElement.getTagNo() != 3) throw new SystemLogParsingException(properties.getString("de.konfidas.ttc.messages.systemlogs.errorResultNotFound")); this.result = (DLTaggedObject) systemOperationDataIterator.next(); this.resultAsBoolean = DLTaggedObjectConverter.dLTaggedObjectToBoolean(this.result); //parameters nextElement = (DLTaggedObject) systemOperationDataAsAsn1List.get(systemOperationDataIterator.nextIndex()); if (nextElement.getTagNo() != 3) throw new SystemLogParsingException(properties.getString("de.konfidas.ttc.messages.systemlogs.errorParametersNotFound")); this.parameters = (DLTaggedObject) systemOperationDataIterator.next(); //parameters is a Sequence in itself. Parsing follows if (this.parameters.getObject() instanceof ASN1Sequence) { List parametersAsASN1List = Collections.list(((ASN1Sequence) this.parameters.getObject()).getObjects()); ListIterator parametersSetIterator = parametersAsASN1List.listIterator(); while (parametersSetIterator.hasNext()) { ASN1Primitive loggingParameter = parametersSetIterator.next(); this.loggingParameter.add(loggingParameter); } for (ASN1Primitive loggingParameter :this.loggingParameter) { if (!(loggingParameter instanceof ASN1Sequence)) { throw new SystemLogParsingException(properties.getString("de.konfidas.ttc.messages.systemlogs.errorLoggingParameterNotOfTypeASN1Sequence")); } else{ List parametersContentAsASN1List = Collections.list(((ASN1Sequence) loggingParameter).getObjects()); ListIterator parametersContentSetIterator = parametersContentAsASN1List.listIterator(); //TODO HIER WEITER } } } else throw new SystemLogParsingException(properties.getString("de.konfidas.ttc.messages.systemlogs.errorParamtersDoesNotStartWithSequence")); } catch (NoSuchElementException ex){ throw new SystemLogParsingException(properties.getString("de.konfidas.ttc.messages.systemlogs.errorEarlyEndOfSystemOperationData"), ex); } } }yohto/yosegi /** * 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 jp.co.yahoo.yosegi.reader; import jp.co.yahoo.yosegi.message.objects.PrimitiveObject; import jp.co.yahoo.yosegi.message.parser.IParser; import jp.co.yahoo.yosegi.message.parser.ISettableIndexParser; import jp.co.yahoo.yosegi.message.parser.PrimitiveConverter; import jp.co.yahoo.yosegi.spread.column.ArrayCell; import jp.co.yahoo.yosegi.spread.column.ColumnType; import jp.co.yahoo.yosegi.spread.column.ICell; import jp.co.yahoo.yosegi.spread.column.IColumn; import java.io.IOException; public class YosegiArrayParser implements ISettableIndexParser { private final IColumn column; private final IColumn arrayColumn; private int start; private int length; public YosegiArrayParser( final IColumn column ) { this.column = column; arrayColumn = column.getColumn(0); } @Override public void setIndex( final int index ) { ICell cell = column.get( index ); if ( cell.getType() == ColumnType.ARRAY ) { ArrayCell arrayCell = (ArrayCell)cell; start = arrayCell.getStart(); length = arrayCell.getEnd() - start; } else { start = 0; length = 0; } } @Override public PrimitiveObject get( final String key ) throws IOException { return null; } @Override public PrimitiveObject get( final int index ) throws IOException { if ( length <= index ) { return null; } return PrimitiveConverter.convert( arrayColumn.get( start + index ) ); } @Override public IParser getParser( final String key ) throws IOException { return YosegiNullParser.getInstance(); } @Override public IParser getParser( final int index ) throws IOException { if ( length <= index ) { return YosegiNullParser.getInstance(); } int target = start + index; ISettableIndexParser parser = YosegiParserFactory.get( arrayColumn , target ); parser.setIndex( target ); return parser; } @Override public String[] getAllKey() throws IOException { return new String[0]; } @Override public boolean containsKey( final String key ) throws IOException { return false; } @Override public int size() throws IOException { return length; } @Override public boolean isArray() throws IOException { return true; } @Override public boolean isMap() throws IOException { return false; } @Override public boolean isStruct() throws IOException { return false; } @Override public boolean hasParser( final int index ) throws IOException { if ( length <= index ) { return false; } int target = start + index; return YosegiParserFactory.hasParser( arrayColumn , target ); } @Override public boolean hasParser( final String key ) throws IOException { return false; } @Override public Object toJavaObject() throws IOException { return null; } } sql/catalyst/target/java/org/apache/spark/sql/catalyst/analysis/CTESubstitution$.java package org.apache.spark.sql.catalyst.analysis; /** * Analyze WITH nodes and substitute child plan with CTE definitions. */ public class CTESubstitution$ extends org.apache.spark.sql.catalyst.rules.Rule { /** * Static reference to the singleton instance of this Scala object. */ public static final CTESubstitution$ MODULE$ = null; public CTESubstitution$ () { throw new RuntimeException(); } public org.apache.spark.sql.catalyst.plans.logical.LogicalPlan apply (org.apache.spark.sql.catalyst.plans.logical.LogicalPlan plan) { throw new RuntimeException(); } } tutttuwi/JNDI-Injection-Target-App package me.tutttuwi.JNDIInjectionTargetApp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JndiInjectionTargetAppApplication { public static void main(String[] args) { SpringApplication.run(JndiInjectionTargetAppApplication.class, args); } } 0 package io.sentry.core; import io.sentry.core.protocol.SentryId; import org.jetbrains.annotations.Nullable; final class SentryEnvelope { private final SentryEnvelopeHeader header; private final Iterable items; public Iterable getItems() { return items; } public SentryEnvelopeHeader getHeader() { return header; } SentryEnvelope(SentryEnvelopeHeader header, Iterable items) { this.header = header; this.items = items; } public SentryEnvelope( SentryId sentryId, @Nullable String auth, Iterable items) { header = new SentryEnvelopeHeader(sentryId, auth); this.items = items; } public SentryEnvelope(SentryId sentryId, Iterable items) { header = new SentryEnvelopeHeader(sentryId, null); this.items = items; } } /* * Copyright (c) 2019 - 2020. * Author: * Project name: Java_Optional * Filename: Dice.java * Date: 20/12/2020, 21:21 */ package homework.chapter13; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class Dice extends JFrame { int val = 4; Panel dice = new Panel(); void draw(Graphics graphics, int val, int x, int y) { graphics.setColor(Color.BLACK); graphics.drawRect(x, y, 34, 34); if (val%2 == 1) graphics.fillOval(x+13, y+13, 9, 9); if (val == 6) graphics.fillOval(x+23, y+13, 9, 9); if (val > 3) graphics.fillOval(x+3, y+23, 9, 9); if (val >1) graphics.fillOval(x+23, y+23, 9, 9); } class Panel extends JPanel { public void paintComponent(Graphics graphics) { super.paintComponent(graphics); draw(graphics, val, 40, 40); } } /** * Constructs a new frame that is initially invisible. *

* This constructor sets the component's locale property to the value * returned by JComponent.getDefaultLocale. * * @throws HeadlessException if GraphicsEnvironment.isHeadless() * returns true. * @see GraphicsEnvironment#isHeadless * @see Component#setSize * @see Component#setVisible * @see JComponent#getDefaultLocale */ public Dice() throws HeadlessException { dice.setBackground(Color.pink); dice.setBorder(BorderFactory.createTitledBorder("Dice Panel")); setContentPane(dice); setSize(300, 200); setVisible(true); dice.addMouseListener(new MouseAdapter() { /** * {@inheritDoc} * * @param e */ @Override public void mousePressed(MouseEvent e) { super.mousePressed(e); val = (int)(Math.random()*6) + 1; dice.repaint(); } }); } public static void main(String[] args) { Dice dice1 = new Dice(); } } Z-Alan/springbootmybatis/src/main/java/com/example/mybatis/model/temp/LogisticsSfDO.java package com.example.mybatis.model.temp; import com.xjjk.ec.Core.vo.BaseDO; import lombok.Data; import lombok.EqualsAndHashCode; import tk.mybatis.mapper.annotation.KeySql; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.Table; /** * className: LogisticsSfDO * description: * date: 2019/11/28 * * @author zhouqiang * @version 1.0 */ @Data @EqualsAndHashCode(callSuper = true) @Table(name = "logistics_sf") public class LogisticsSfDO extends BaseDO { @Id @Column(name = "Id", insertable = false, updatable = false) @KeySql(useGeneratedKeys = true) private Long id; /** * 路由编号,每一个id代表一条不同的路由 */ @Column(name = "MailId") private Long mailId; /** * 运单号 */ @Column(name = "MailNo") private String mailNo; /** * 订单号 */ @Column(name = "OrderId") private String orderId; /** * 路由产生时间 */ @Column(name = "AcceptTime") private String acceptTime; /** * 路由发生城市 */ @Column(name = "AcceptAddress") private String acceptAddress; /** * 路由说明 */ @Column(name = "Remark") private String remark; /** * 操作码 */ @Column(name = "OpCode") private String opCode; } package me.earth.earthhack.impl.event.events; import me.earth.earthhack.api.event.events.Event; import net.minecraft.network.INetHandler; import net.minecraft.network.Packet; /** * A cancellable Event, * wrapping a packet. * * @param the type of packet. */ public class PacketEvent> extends Event { private final T packet; private PacketEvent(T packet) { this.packet = packet; } public T getPacket() { return packet; } /** * An object of this sub class gets created when * a packet is sent. * * @param the type of packet sent. */ public static class Send> extends PacketEvent { public Send(T packet) { super(packet); } } /** * An object of this sub class gets created when * a packet is received. * * @param the type of packet received. */ public static class Receive> extends PacketEvent { public Receive(T packet) { super(packet); } } /** * Exists only for Sending, not required for receiving. * Objects of this class will be created after a packet has * successfully been sent. * * @param the type of packet sent. */ public static class Post> extends PacketEvent { public Post(T packet) { super(packet); } } } package com.example.shuka.currencyconverter; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.widget.Toast; /** * Created by shuka on 8/4/2016. */ public class MyDialogFragment extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder theDialog = new AlertDialog.Builder(getActivity()); theDialog.setTitle("Settings"); theDialog.setMessage("Advanced Settings coming soon. In future versions, you will be able to change exchange rates manually to accurately model changing markets."); theDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getActivity(), "Clicked OK", Toast.LENGTH_SHORT).show(); } }); theDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getActivity(), "Clicked Cancel", Toast.LENGTH_SHORT).show(); } }); return theDialog.create(); } } perlausten/org.openntf.xsp.jakartaee0 /** * Copyright © 2018-2022 Contributors to the XPages Jakarta EE Support 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 org.openntf.xsp.jakartaee.xml; import java.security.PrivilegedExceptionAction; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import java.security.AccessController; import java.security.PrivilegedActionException; /** * Utilities for working with XML Binding in a low-privilege context. * * @since 2.0.0 */ public enum JaxbUtil { ; /** * Creates a new {@link JAXBContext} instance for the provided classes. * *

This method performs conversion in an {@link AccessController#doPrivileged} block * to avoid permissions issues in an XPages application.

* * @param classesToBeBound * list of java classes to be recognized by the new {@link JAXBContext}. * Can be empty, in which case a {@link JAXBContext} that only knows about * spec-defined classes will be returned. * @return * A new instance of a JAXBContext. Always non-null valid object. * @throws JAXBException * if an error was encountered while creating the * JAXBContext, such as (but not limited to): *
    *
  1. No JAXB implementation was discovered *
  2. Classes use JAXB annotations incorrectly *
  3. Classes have colliding annotations (i.e., two classes with the same type name) *
  4. The JAXB implementation was unable to locate * provider-specific out-of-band information (such as additional * files generated at the development time.) *
* @see JAXBContext#newInstance(Class...) */ public static JAXBContext newInstance(Class... classes) throws JAXBException { try { return AccessController.doPrivileged((PrivilegedExceptionAction)() -> JAXBContext.newInstance(classes) ); } catch (PrivilegedActionException e) { Throwable cause = e.getCause(); if(cause instanceof JAXBException) { throw (JAXBException)cause; } else { throw new RuntimeException(e); } } } } /* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.keycloak.storage; import org.keycloak.common.util.MultivaluedHashMap; import org.keycloak.component.ComponentModel; import org.keycloak.models.RealmModel; import java.io.Serializable; import java.util.Comparator; import java.util.HashMap; import java.util.Map; /** * Stored configuration of a User Storage provider instance. * * @author * @author */ public class UserStorageProviderModel extends ComponentModel { public static Comparator comparator = new Comparator() { @Override public int compare(UserStorageProviderModel o1, UserStorageProviderModel o2) { return o1.getPriority() - o2.getPriority(); } }; public UserStorageProviderModel() { setProviderType(UserStorageProvider.class.getName()); } public UserStorageProviderModel(ComponentModel copy) { super(copy); } public int getPriority() { String priority = getConfig().getFirst("priority"); if (priority == null) return 0; return Integer.valueOf(priority); } public void setPriority(int priority) { getConfig().putSingle("priority", Integer.toString(priority)); } } src/main/java/com/bbn/openmap/tools/roads/RoadClass.java // ********************************************************************** // // // // BBN Technologies // 10 Moulton Street // Cambridge, MA 02138 // (617) 873-8000 // // Copyright (C) BBNT Solutions LLC. All rights reserved. // // // ********************************************************************** // // $Source: // /cvs/distapps/openmap/src/openmap/com/bbn/openmap/tools/roads/RoadClass.java,v // $ // $RCSfile: RoadClass.java,v $ // $Revision: 1.3 $ // $Date: 2005/08/12 21:47:49 $ // $Author: dietrick $ // // ********************************************************************** package com.bbn.openmap.tools.roads; import java.awt.Color; import java.io.Serializable; public class RoadClass implements Serializable { private Serializable name; private Color color; private int width; private float convoySpeed; public RoadClass(Serializable name, Color color, int width, float convoySpeed) { this.name = name; this.color = color; this.width = width; this.convoySpeed = convoySpeed; } public Serializable getName() { return name; } public Color getColor() { return color; } public int getWidth() { return width; } public float getConvoySpeed() { return convoySpeed; } }src/org/traccar/location/OpenCellIdLocationProvider.java /* * Copyright 2015 () * * 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.traccar.location; import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.Response; import org.traccar.Context; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonReader; public class OpenCellIdLocationProvider extends BaseLocationProvider { private String url; public OpenCellIdLocationProvider(String key) { this("http://opencellid.org/cell/get", key); } public OpenCellIdLocationProvider(String url, String key) { this.url = url + "?format=json&mcc=%d&mnc=%d&lac=%d&cellid=%d&key=" + key; } protected void getLocation(int mcc, int mnc, long lac, long cid, final LocationProviderCallback callback) { Context.getAsyncHttpClient().prepareGet(String.format(url, mcc, mnc, lac, cid)) .execute(new AsyncCompletionHandler() { @Override public Object onCompleted(Response response) throws Exception { try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) { JsonObject json = reader.readObject(); if (json.containsKey("lat") && json.containsKey("lon")) { callback.onSuccess( json.getJsonNumber("lat").doubleValue(), json.getJsonNumber("lon").doubleValue()); } else { callback.onFailure(); } } return null; } @Override public void onThrowable(Throwable t) { callback.onFailure(); } }); } } package com.angkorteam.fintech.dto.builder.client.center; import java.io.Serializable; import io.github.openunirest.http.JsonNode; public class CenterNoteBuilder implements Serializable { private String centerId; private boolean hasCenterId; public CenterNoteBuilder withCenterId(String centerId) { this.centerId = centerId; this.hasCenterId = true; return this; } private String note; private boolean hasNote; public CenterNoteBuilder withNote(String note) { this.note = note; this.hasNote = true; return this; } public JsonNode build() { JsonNode object = new com.angkorteam.fintech.dto.JsonNode(); if (this.hasCenterId) { object.getObject().put("centerId", this.centerId); } if (this.hasNote) { object.getObject().put("note", this.note); } return object; } } ApplauseAQI/mysql_perf_analyzer /* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the Apache License. * See the accompanying LICENSE file for terms. */ package com.yahoo.dba.perf.myperf.springmvc; import java.math.BigDecimal; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import com.yahoo.dba.perf.myperf.common.ColumnDescriptor; import com.yahoo.dba.perf.myperf.common.Constants; import com.yahoo.dba.perf.myperf.common.DBInstanceInfo; import com.yahoo.dba.perf.myperf.common.DBUtils; import com.yahoo.dba.perf.myperf.common.QueryParameters; import com.yahoo.dba.perf.myperf.common.ResultList; import com.yahoo.dba.perf.myperf.common.ResultListUtil; import com.yahoo.dba.perf.myperf.common.ResultRow; import com.yahoo.dba.perf.myperf.db.DBConnectionWrapper; public class InnoController extends MyPerfBaseController { private static Logger logger = Logger.getLogger(InnoController.class.getName()); @Override protected ModelAndView handleRequestImpl(HttpServletRequest req, HttpServletResponse resp) throws Exception { int status = Constants.STATUS_OK; String message = "OK"; String group = req.getParameter("group"); String host = req.getParameter("host"); QueryParameters qps = new QueryParameters(); qps.setGroup(group); qps.setHost(host); qps.setSql("mysql_innodb_engine_status"); ResultList rList = null; LinkedHashMap listMap = new LinkedHashMap(); DBInstanceInfo dbinfo = null; DBConnectionWrapper connWrapper = null; try { dbinfo = this.frameworkContext.getDbInfoManager().findDB(group,host).copy(); connWrapper = WebAppUtil.getDBConnection(req, this.frameworkContext, dbinfo); if(connWrapper==null) { status = Constants.STATUS_BAD; message = "failed to connect to target db ("+dbinfo+")"; }else { rList = this.frameworkContext.getQueryEngine().executeQueryGeneric(qps, connWrapper, qps.getMaxRows()); logger.info("Done query "+qps.getSql() + " with "+(rList!=null?rList.getRows().size():0)+" records."); if(rList!=null && rList.getRows().size()>0) { logger.info(rList.getRows().get(0).getColumns().get(rList.getRows().get(0).getColumns().size()-1)); listMap = parse(rList.getRows().get(0).getColumns().get(rList.getRows().get(0).getColumns().size()-1)); } WebAppUtil.closeDBConnection(req, connWrapper, false, this.getFrameworkContext().getMyperfConfig().isReuseMonUserConnction()); } }catch(Throwable th) { logger.log(Level.SEVERE,"Exception", th); if(th instanceof SQLException) { SQLException sqlEx = SQLException.class.cast(th); String msg = th.getMessage(); logger.info(sqlEx.getSQLState()+", "+sqlEx.getErrorCode()+", "+msg); //check if the connection is still good if(!DBUtils.checkConnection(connWrapper.getConnection())) { WebAppUtil.closeDBConnection(req, connWrapper, true, false); } else WebAppUtil.closeDBConnection(req, connWrapper, true, false); }else { if(connWrapper!=null)WebAppUtil.closeDBConnection(req, connWrapper, false,this.getFrameworkContext().getMyperfConfig().isReuseMonUserConnction()); } status = Constants.STATUS_BAD; message = "Exception: "+th.getMessage(); } finally { } ModelAndView mv = new ModelAndView(this.jsonView); if(req.getParameter("callback")!=null&&req.getParameter("callback").trim().length()>0) mv.addObject("callback", req.getParameter("callback"));//YUI datasource binding mv = new ModelAndView(this.jsonView); mv.addObject("json_result", ResultListUtil.toMultiListJSONStringUpper(listMap, qps, status, message)); return mv; } private LinkedHashMap parse(String str) { final int BEFORE_STARTLINE = -1; final int STARTLINE = 0; final int AFTER_STARTLINE = 1; final int SECTION_HEADER_STARTLINE = 2; final int SECTION_HEADER_ENDLINE = 3; int state = BEFORE_STARTLINE; String currentSection = null; LinkedHashMap listMap = new LinkedHashMap(); java.io.StringReader reader = new java.io.StringReader(str); java.io.BufferedReader bufReader = new java.io.BufferedReader(reader); String line = null; Map valMap = new java.util.LinkedHashMap(); List txList = new ArrayList(); List semapList = new ArrayList(); List deadLockInfo = new ArrayList();//TODO not parsing the content for now Transaction curTx = null; SemaphoreEntry curSemap = null; try { while( (line = bufReader.readLine())!=null) { switch(state) { case BEFORE_STARTLINE: if(line.startsWith("===")) state = STARTLINE; break; case STARTLINE: if(line.startsWith("===")) state = AFTER_STARTLINE; else { int idx = line.indexOf(" INNODB"); if(idx>0) { valMap.put("Time", line.substring(0, idx).trim()); } } break; case AFTER_STARTLINE: if(line.startsWith("-")) state = SECTION_HEADER_STARTLINE; else { if(line.startsWith("Per second averages")) { valMap.put("Duration", line.substring(line.indexOf("last")+5).trim()); } } break; case SECTION_HEADER_STARTLINE: if(line.startsWith("-")) { state = SECTION_HEADER_ENDLINE; } else { currentSection = line.trim(); } break; case SECTION_HEADER_ENDLINE: if(line.startsWith("-") && !line.startsWith("---TRANSACTION") && !line.startsWith("--Thread") &&!(line.startsWith("-------")&&line.contains("TRX")) &&!"------------------".equals(line)) { state = SECTION_HEADER_STARTLINE; //store previous section if("BACKGROUND THREAD".equalsIgnoreCase(currentSection)) { //dump valMap listMap.put("inno_status_summary",createHeader(valMap)); valMap.clear(); }else if("FILE I/O".equalsIgnoreCase(currentSection)) { //dump valMap listMap.put("inno_status_file_io",createHeader(valMap)); valMap.clear(); }else if("BUFFER POOL AND MEMORY".equalsIgnoreCase(currentSection)) { //dump valMap listMap.put("inno_status_buffer_pool",createHeader(valMap)); valMap.clear(); }else if("ROW OPERATIONS".equalsIgnoreCase(currentSection)) { //dump valMap listMap.put("inno_status_row_operations",createHeader(valMap)); valMap.clear(); }else if("SEMAPHORES".equalsIgnoreCase(currentSection)) { //dump valMap listMap.put("inno_status_semaphores",createHeader(valMap)); valMap.clear(); logger.info("Processing semaphore list: "+semapList.size()); listMap.put("inno_status_semap",buildSemapList(semapList)); txList.clear(); }else if("LOG".equalsIgnoreCase(currentSection)) { //dump valMap listMap.put("inno_status_log",createHeader(valMap)); valMap.clear(); } else if("INSERT BUFFER AND ADAPTIVE HASH INDEX".equalsIgnoreCase(currentSection)) { //dump valMap listMap.put("inno_status_ibuf",createHeader(valMap)); valMap.clear(); } else if("LATEST DETECTED DEADLOCK".equalsIgnoreCase(currentSection)) { logger.info("Processing deadlocks: " + deadLockInfo.size()); listMap.put("inno_status_deadlocks", buildDeadlockList(deadLockInfo)); } else if("TRANSACTIONS".equalsIgnoreCase(currentSection)) { if(curTx!=null)txList.add(curTx); curTx = null; logger.info("Processing tx: "+txList.size()); listMap.put("inno_status_txs",buildTransactionList(txList)); txList.clear(); } } else if("BACKGROUND THREAD".equalsIgnoreCase(currentSection)) { String vals[] = line.split(":"); if(vals.length>1) { valMap.put(vals[0], vals[1]); } }else if("LATEST DETECTED DEADLOCK".equalsIgnoreCase(currentSection)) { deadLockInfo.add(line); } else if("FILE I/O".equalsIgnoreCase(currentSection)) { this.parseFileIO(valMap, line); }else if("BUFFER POOL AND MEMORY".equalsIgnoreCase(currentSection)) { this.parseBufferPool(valMap, line); }else if("ROW OPERATIONS".equalsIgnoreCase(currentSection)) { this.parseRowOperation(valMap, line); }else if("SEMAPHORES".equalsIgnoreCase(currentSection)) { boolean parsed = false; if(line!=null && line.startsWith("--Thread ")) { //start a new semaphore curSemap = new SemaphoreEntry(); semapList.add(curSemap); } if(curSemap!=null) parsed = curSemap.parse(line); if(!parsed) this.parseSemaphore(valMap, line); }else if("LOG".equalsIgnoreCase(currentSection)) { this.parseLog(valMap, line); }else if("INSERT BUFFER AND ADAPTIVE HASH INDEX".equalsIgnoreCase(currentSection)) { this.parseIBuf(valMap, line); } else if("TRANSACTIONS".equalsIgnoreCase(currentSection)) { //TODO skip summary portion if(curTx==null && !line.startsWith("---TRANSACTION")) break; if(line.startsWith("---TRANSACTION")) { if(curTx!=null) txList.add(curTx); curTx = new Transaction(); } curTx.parseLine(line); } break; default: break; } } }catch(Exception iex) { logger.log(Level.INFO, "Error during parsing", iex); } return listMap; } private ResultList buildSemapList(List semapList) { ResultList rList = new ResultList(); ColumnDescriptor desc = new ColumnDescriptor(); int idx = 1; desc.addColumn("THREAD_ID", false, idx++); desc.addColumn("LOCK_TYPE", false, idx++); desc.addColumn("LOCK_NAME", false, idx++); desc.addColumn("MODE", false, idx++); desc.addColumn("LOCATION", false, idx++); desc.addColumn("TIME_SEC", false, idx++); desc.addColumn("HOLDER", false, idx++); desc.addColumn("HODL_MODE", false, idx++); desc.addColumn("WAITED_AT", false, idx++); rList.setColumnDescriptor(desc); for(SemaphoreEntry tx: semapList) { if(tx.thread_id==null)continue; ResultRow row = new ResultRow(); rList.addRow(row); row.setColumnDescriptor(desc); List cols = new ArrayList(16); row.setColumns(cols); cols.add(tx.thread_id); cols.add(tx.lock_type); cols.add(tx.lock_name); cols.add(tx.request_mode); cols.add(tx.lock_loc); cols.add(tx.waited_time); cols.add(tx.lock_holder); cols.add(tx.hold_mode); cols.add(tx.waited_at); } return rList; } private ResultList createHeader(Map valMap) { ResultList rList = new ResultList(); ColumnDescriptor desc = new ColumnDescriptor(); desc.addColumn("NAME", false, 1); desc.addColumn("VALUE", false, 2); rList.setColumnDescriptor(desc); for(Map.Entry e: valMap.entrySet()) { ResultRow row = new ResultRow(); List vals = new ArrayList(2); vals.add(e.getKey()); vals.add(e.getValue()); row.setColumnDescriptor(desc); row.setColumns(vals); rList.addRow(row); } return rList; } private void parseFileIO(Map valMap, String str) { try { if(str==null||str.isEmpty())return; str = str.trim(); if(str.startsWith("I/O thread ")) { String vals[] = str.split(":"); if(vals.length>1) { valMap.put(vals[0], vals[1]); } }else if(str.charAt(0)>='0'&&str.charAt(0)<='9') { String[] vals = str.split(","); for(String v: vals) { String v2 = v.trim(); int idx = v2.indexOf(' '); if(idx>0) { valMap.put(v2.substring(idx+1).trim(),v2.substring(0, idx).trim()); } } }else if(str.indexOf(',')>=0) { String[] strs = str.split(","); for(String s: strs) { String[] res = this.splitSpaceDelemitNameValuePair(s); if(res!=null) { String name = res[0]; if(name.indexOf(":")>=0)name = name.substring(0, name.indexOf(":")); valMap.put(name, res[1]); } } } }catch(Exception ex){} } private void parseRowOperation(Map valMap, String str) { try { if(str==null||str.isEmpty())return; str = str.trim(); if(str.indexOf("queries inside InnoDB")>=0||str.indexOf("read views")>=0) { String vals[] = str.split(","); for(String v: vals) { v = v.trim(); int idx = v.indexOf(' '); if(idx>0) valMap.put(v.substring(idx+1),v.substring(0,idx)); } }else if(str.indexOf("Main thread")>=0) { String[] vals = str.split(","); for(String v: vals) { String v2 = v.trim(); int idx = v2.lastIndexOf(' '); if(idx>0) { String k = v2.substring(0, idx).trim(); if(!k.startsWith("Main thread")) k = "Main thread "+k; valMap.put(k,v2.substring(idx+1).trim()); } } }else if(str.indexOf("Number of rows")>=0) { String[] vals = str.split(","); for(String v: vals) { String v2 = v.trim(); int idx = v2.lastIndexOf(' '); if(idx>0) { String k = v2.substring(0, idx).trim(); if(!k.startsWith("Number of rows")) k = "Number of rows "+k; valMap.put(k,v2.substring(idx+1).trim()); } } }else if(str.charAt(0)>='0'&&str.charAt(0)<='9') { String[] vals = str.split(","); for(String v: vals) { String v2 = v.trim(); int idx = v2.indexOf(' '); if(idx>0) { String k = v2.substring(idx+1).trim(); valMap.put(k,v2.substring(0, idx).trim()); } } }else { logger.warning("Data not parsed: "+str); } }catch(Exception ex){} } private void parseSemaphore(Map valMap, String str) { try { if(str==null||str.isEmpty())return; str = str.trim(); if(str.startsWith("OS WAIT ARRAY INFO: ")) { String str2 = str.substring(str.indexOf(':')+1).trim(); String vals[] = str2.split(","); for(String v: vals) { v = v.trim(); int idx = v.lastIndexOf(' '); if(idx>0) valMap.put("OS WAIT ARRAY INFO: "+v.substring(0,idx), v.substring(idx+1)); } }else if(str.startsWith("Mutex")) { String str2 = str.substring(6).trim(); String vals[] = str2.split(","); for(String v: vals) { v = v.trim(); int idx = v.lastIndexOf(' '); if(idx>0) valMap.put("Mutex "+v.substring(0,idx), v.substring(idx+1)); } }else if(str.startsWith("Spin rounds per wait:")) { String str2 = str.substring(str.indexOf(':')+1).trim(); String vals[] = str2.split(","); for(String v: vals) { v = v.trim(); int idx = v.indexOf(' '); if(idx>0) valMap.put("Spin rounds per wait: "+v.substring(idx+1),v.substring(0,idx)); } }else if(str.indexOf("RW-shared spins")>=0||str.indexOf("RW-excl spins")>=0) { String vals[] = str.split(";"); for(String v: vals) { v = v.trim(); String[] vals2 = v.split(","); for(String v2: vals2) { int idx = v2.lastIndexOf(' '); if(idx>0) { String k = v2.substring(0, idx); if(v.indexOf("RW-shared")>=0 && k.indexOf("RW-shared")<0) k = "RW-shared "+k; else if(v.indexOf("RW-excl")>=0 && k.indexOf("RW-excl")<0) k = "RW-excl "+k; valMap.put(k,v2.substring(idx+1)); } } } }else if(str.startsWith("RW-sx")) { String str2 = str.substring(str.indexOf(' ')+1).trim(); String vals[] = str2.split(","); for(String v: vals) { v = v.trim(); int idx = v.lastIndexOf(' '); if(idx>0) valMap.put("RW-sx "+v.substring(0,idx), v.substring(idx+1)); } } else { logger.warning("Data not parsed: "+str); } }catch(Exception ex){} } /** * Split a space delimit name value pair, with name followed by value. The name could have space too. * @param str * @return 2 element array. The first is name, the second is value */ private String[] splitSpaceDelemitNameValuePair(String str) { if(str==null||str.isEmpty())return null; String str2 = str.trim(); int idx = str2.lastIndexOf(' ');//since we trimmed, it cannot be the last one if(idx<=0)return null; String name = str2.substring(0, idx); String val = str2.substring(idx+1); if(name.isEmpty()||val.isEmpty())return null; name = name.trim(); try { //check if we can parse BigDecimal bdecimal = new BigDecimal(val); if(bdecimal!=null) { String[] res = new String[2]; res[0] = name; res[1] = val; return res; } }catch(Exception ex) { } return null; } private String[] splitSpaceDelemitValueNamePair(String str) { if(str==null||str.isEmpty())return null; String str2 = str.trim(); int idx = str2.indexOf(' ');//since we trimmed, it cannot be the last one if(idx<=0)return null; String val = str2.substring(0, idx); String name = str2.substring(idx+1); if(name.isEmpty()||val.isEmpty())return null; name = name.trim(); try { //check if we can parse BigDecimal bdecimal = new BigDecimal(val); if(bdecimal!=null) { String[] res = new String[2]; res[0] = name; res[1] = val; return res; } }catch(Exception ex) { } return null; } private void parseLog(Map valMap, String str) { try { if(str==null||str.isEmpty())return; str = str.trim(); if(str.indexOf(',')<0)//not comma separated line, so name value pair { String[] res = splitSpaceDelemitNameValuePair(str); if(res!=null) valMap.put(res[0], res[1]); }else //comma separated, each substring has value name pair { String[] strs = str.split(","); for(String s: strs) { String[] res = splitSpaceDelemitValueNamePair(s); if(res!=null) valMap.put(res[0], res[1]); } } }catch(Exception ex){} } private void parseIBuf(Map valMap, String str) { try { if(str==null||str.isEmpty())return; str = str.trim(); if(str.startsWith("Ibuf: ")) { String str2 = str.substring(5).trim(); String[] strs = str2.split(","); for(String s: strs) { String[] res = splitSpaceDelemitNameValuePair(s); if(res!=null) valMap.put("Ibuf "+res[0], res[1]); } }else if(Character.isDigit(str.charAt(0)))//value name pair { String[] strs = str.split(","); for(String s: strs) { String[] res = splitSpaceDelemitValueNamePair(s); if(res!=null) valMap.put(res[0], res[1]); } }else if(str.startsWith("Hash table")) { String[] strs = str.split(","); for(String s: strs) { if(s!=null)s = s.trim(); else continue; if(s.startsWith("Hash table")) { String[] res = splitSpaceDelemitNameValuePair(s); if(res!=null) valMap.put(res[0], res[1]); }else if(s.startsWith("node heap")) { String[] ss = s.split(" "); if(ss!=null && ss.length>3) valMap.put("node heap buffer(s)", ss[3]); } } } }catch(Exception ex){} } private static String[] BUFFER_INTERNALS = new String[]{"Adaptive hash index","Page hash","Dictionary cache", "File system", "Lock system", "Recovery system"}; private void parseBufferPool(Map valMap, String str) { try { if(str==null||str.isEmpty())return; String str2 = str.trim(); if(str2.startsWith("Total memory")) { String vals[] = str2.split(";"); for(String v: vals) { String v2 = v.trim(); int idx = v2.lastIndexOf(' '); if(idx>0) valMap.put(v2.substring(0, idx), v2.substring(idx+1)); } }else if(str.startsWith("Internal hash"))//Skil sub header { } else if(str.startsWith(" ")||str.indexOf('(')>0)//indented { for(String hts: BUFFER_INTERNALS) { if(str.indexOf(hts)>=0) { str2 = str.substring( str.indexOf(hts)+hts.length()).trim(); int idx = str2.lastIndexOf(')'); if(idx>=0)valMap.put("Internal hash tables - "+hts, str2.substring(0, idx+1)); } } }else if(str2.startsWith("Dictionary memory allocated") ||str2.startsWith("Buffer pool size") ||str2.startsWith("Free buffers") ||str2.startsWith("Database pages") ||str2.startsWith("Old database pages") ||str2.startsWith("Modified db pages") ||str2.startsWith("Pending reads")) { int idx = str2.lastIndexOf(' '); if(idx>=0) { valMap.put(str2.substring(0, idx), str2.substring(idx+1)); } }else if(str2.startsWith("Pending writes")) { String str3 = str2.substring(str2.indexOf(':')+1).trim(); String vals[] = str3.split(","); for(String v: vals) { v = v.trim(); if(v.indexOf("flush list")>=0 && v.indexOf("single page")>=0) { valMap.put("flush list", v.substring(v.indexOf("flush list")+11, v.indexOf("single page")-1)); valMap.put("single page", v.substring(v.lastIndexOf(' ')+1)); }else { int idx = v.lastIndexOf(' '); if(idx>=0) valMap.put("Pending writes: "+ v.substring(0, idx),v.substring(idx+1)); } } } else if(str2.indexOf(',')>=0) { String vals[] = str2.split(","); for(String v: vals) { v = v.trim(); if(v.charAt(0)>='0' && v.charAt(0)<='9') { int idx = v.lastIndexOf(' '); if(idx>=0) { String k = v.substring(idx+1); k = "Pages "+k; valMap.put(k,v.substring(0, idx)); } }else if(v.indexOf(':')>=0) { int idx = v.lastIndexOf(':'); if(idx>=0) { valMap.put(v.substring(0, idx),v.substring(idx+1)); } }else if(v.startsWith("Buffer pool hit rate")) { valMap.put("Buffer pool hit rate", v.substring(21)); }else if(v.startsWith("young-making rate")) { int idx = v.lastIndexOf("not"); valMap.put("young-making rate", v.substring(18, idx)); }else { int idx = v.lastIndexOf(' '); if(idx>=0) { String k = v.substring(0, idx); if(str.startsWith("Pages") && !k.startsWith("Pages")) k = "Pages "+k; valMap.put(k,v.substring(idx+1)); } } } }else { logger.warning("Data not parsed: "+str2); } }catch(Exception ex){} } private static ResultList buildTransactionList(List txs) { ResultList rList = new ResultList(); ColumnDescriptor desc = new ColumnDescriptor(); int idx = 1; desc.addColumn("ID", false, idx++); desc.addColumn("STATE", false, idx++); desc.addColumn("TIME", false, idx++); desc.addColumn("PROCESS", false, idx++); desc.addColumn("THREAD", false, idx++); desc.addColumn("USER", false, idx++); desc.addColumn("HOST", false, idx++); desc.addColumn("QUERY_ID", false, idx++); //desc.addColumn("ACTION", false, idx++); desc.addColumn("SQL_STATE", false, idx++); desc.addColumn("SQL", false, idx++); desc.addColumn("LOCKS", false, idx++); //TODO lock strcuts rList.setColumnDescriptor(desc); for(Transaction tx: txs) { if("not started".equalsIgnoreCase(tx.state) && (tx.sql==null || tx.sql.isEmpty())) continue;//ignore idle one ResultRow row = new ResultRow(); rList.addRow(row); row.setColumnDescriptor(desc); List cols = new ArrayList(16); row.setColumns(cols); cols.add(tx.id); cols.add(tx.state); cols.add(tx.txTime); cols.add(tx.processNumber); cols.add(tx.threadId); cols.add(tx.user); cols.add(tx.host); cols.add(tx.queryId); //cols.add(tx.action); cols.add(tx.cmd); cols.add(tx.sql); if(tx.action!=null && !tx.action.isEmpty() && tx.comments!=null) cols.add(tx.action+"\n"+tx.comments); else if(tx.action!=null && !tx.action.isEmpty() && tx.comments==null) cols.add(tx.action); else cols.add(tx.comments); } return rList; } private static ResultList buildDeadlockList(List infoList) { ResultList rList = new ResultList(); ColumnDescriptor desc = new ColumnDescriptor(); int idx = 1; desc.addColumn("INFO", false, idx++); //TODO lock strcuts rList.setColumnDescriptor(desc); for(String tx: infoList) { ResultRow row = new ResultRow(); rList.addRow(row); row.setColumnDescriptor(desc); List cols = new ArrayList(1); row.setColumns(cols); cols.add(tx); } return rList; } /** * Used to parse transaction record * @author xrao * */ private static class Transaction { String id;//TX ID String state;//transaction status: ACTIVE or not started String txTime; String processNumber; String action; String lockStructs;//number of lock structs String lockStructsStatus;//number of lock structs String undoLogEntries; String heapSize; String threadId; String queryId; String host; String user; String cmd; String sql; String comments; static final int TX_BEFORE = -1; static final int TX_START =0; static final int TX_ACTION = 1; static final int TX_THREAD = 2; static final int TX_SQL_START = 3; static final int TX_COMMENT = 4; private int txstate = -1; Transaction() { } void parseLine(String str) { if((str.startsWith("------") && str.contains("TRX")) ||str.startsWith("Trx read view will not see trx with id") ||str.startsWith("TABLE LOCK table ") ||str.startsWith("RECORD LOCK space ")) txstate = TX_COMMENT; else if(str.startsWith("MySQL thread id")) txstate = TX_THREAD; try { switch(txstate) { case TX_BEFORE: if(str.startsWith("---TRANSACTION ")) { txstate = TX_START; id = str.substring(str.indexOf(' ')+1, str.indexOf(',')); String str2 = str.substring(str.indexOf(',')+1).trim(); if(str2.startsWith("not started")) { state = "not started"; if(str2.indexOf(',')>=0) str2 = str2.substring(str2.indexOf(',')+1).trim(); else str2 = null; } else if(str2.startsWith("ACTIVE")) { state = "ACTIVE"; if(str2.indexOf(',')>0) { txTime = str2.substring(str2.indexOf(' ')+1, str2.indexOf(',')); str2 = str2.substring(str2.indexOf(',')+1).trim(); } else { int idx1 = str2.indexOf(' '); int idx2 = str2.indexOf(' ', idx1+1); if(idx2>0) idx2 = str2.indexOf(' ', idx2+1); if(idx2>0) { txTime = str2.substring(idx1+1, idx2); str2 = str2.substring(idx2).trim(); } else { txTime = str2.substring(idx1+1); str2 = null; } } }else { if(str2.indexOf(',')>=0) { state = str2.substring(0, str2.indexOf(',')).trim(); str2.substring(str2.indexOf(',')+1).trim(); }else { state = str2; str2 = null; } } if(str2!=null) { if(str2.startsWith("process ")) { if(str2.indexOf(',')>0) str2 = str2.substring(0, str2.indexOf(',')); this.processNumber = str2.substring(str2.lastIndexOf(' ')+1); } else this.action = str2; } } break; case TX_START: this.action = str.trim(); txstate = TX_ACTION; break; case TX_ACTION: //TODO txstate = TX_THREAD; break; case TX_THREAD: String str2 = str.substring(0, str.indexOf(',')); this.threadId = str2.substring(str2.lastIndexOf(' ')); str2 = str.substring(str.indexOf("query id")).trim(); this.queryId = str2.substring(8, str2.indexOf(' ',10)); str2 = str2.substring(str2.indexOf(' ', 10)+1).trim(); if(str2.startsWith("Slave ")) { txstate = TX_SQL_START; this.cmd = str2; break; } else if(str2.startsWith("update")||str2.startsWith("Updating")||str2.startsWith("init")) { txstate = TX_SQL_START; this.cmd = str2; break; } try { this.host = str2.substring(0,str2.indexOf(' ')); str2 = str2.substring(str2.indexOf(' ')+1).trim(); if(str2.charAt(0)>='0'&&str2.charAt(0)<='9' && str2.indexOf('.')>=0) { //ip address this.host += " "+str2.substring(0, str2.indexOf(' ')); str2 = str2.substring(str2.indexOf(' ')+1).trim(); } if(str2.indexOf(' ')>0) { this.user = str2.substring(0, str2.indexOf(' ')); this.cmd = str2.substring(str2.indexOf(' ')+1); }else this.user = str2; }catch(Exception iex) { logger.log(Level.INFO, str2+", "+str, iex); } txstate = TX_SQL_START; break; case TX_SQL_START: if(this.sql==null) this.sql = str; else this.sql += "\n"+str; break; case TX_COMMENT: if(this.comments==null) this.comments = str; else this.comments += "\n"+str; break; default: break; } }catch(Exception ex) { logger.log(Level.INFO, str, ex); } } } public static class SemaphoreEntry { String thread_id; String waited_at; String waited_time; String request_mode; String lock_type; String lock_name; String lock_loc; String lock_holder; String hold_mode; String lock_var; String lock_word; String readers; String waiters_flag; String last_read_locked; String last_write_locked; public SemaphoreEntry() { } public boolean parse(String line) { //--Thread 140455387199232 has waited at btr/btr0cur.c line 501 for 0.0000 seconds the semaphore: if(line==null||line.isEmpty())return false; if(this.thread_id==null && !line.startsWith("--Thread "))return false; try { if(line.startsWith("--Thread ")) { Pattern pt = Pattern.compile("\\-\\-Thread\\s+(\\d+)\\s+has\\s+waited\\s+at\\s+(.+)\\s+for\\s+(.+)\\s+seconds\\s+the\\s+semaphore:"); Matcher mt = pt.matcher(line); if(mt.find()) { this.thread_id = mt.group(1); this.waited_at = mt.group(2); this.waited_time = mt.group(3); }else { logger.info("Failed to parse semaphore line: "+line); } }else if(this.lock_name==null) { //S-lock on RW-latch at 0x7fc0e40a46f0 '&new_index->lock' //Mutex at 0x7fc43c785ee0 '&ibuf_mutex', lock var 1 if(line.startsWith("Mutex ")) { this.lock_type = "Mutex"; Pattern pt = Pattern.compile("Mutex\\s+at\\s+(0x[a-z0-9]+)\\s+'(.+)'\\s*,\\s*lock\\s+var\\s+(\\d+)"); Matcher mt = pt.matcher(line); if(mt.find()) { this.lock_loc = mt.group(1); this.lock_name = mt.group(2); this.lock_var = mt.group(3); }else { logger.info("Failed to parse semaphore Mutex line: "+line); } }else { Pattern pt = Pattern.compile("([A-Z]+)\\-lock\\s+on\\s+([a-zA-Z\\-]+)\\s+at\\s+(0x[a-z0-9]+)\\s+'(.+)'"); Matcher mt = pt.matcher(line); if(mt.find()) { this.request_mode = mt.group(1); this.lock_type = mt.group(2); this.lock_loc = mt.group(3); this.lock_name = mt.group(4); }else { logger.info("Failed to parse semaphore lock line: "+line); } } }else if(line.contains("thread id") && line.contains("mode")) {//a writer (thread id 139924314879744) has reserved it in mode exclusive Pattern pt = Pattern.compile("thread\\s+id\\s+(\\d+).+mode\\s+(.+)"); Matcher mt = pt.matcher(line); if(mt.find()) { this.lock_holder = mt.group(1); this.hold_mode = mt.group(2); }else { logger.info("Failed to parse semaphore holder line: "+line); } }else return false; //ignore other line for now }catch(Exception ex) { logger.log(Level.INFO, "Failed to parse semophore: "+line, ex); } return true;//we parsed it } } } chenjinshu/javaBase package com.cjs.designModeTest.observerMode; import java.util.Observable; /** * 新闻广播(被观察者) * @author chen.jinshu * 2018/11/09 */ public class NewsBroadcast extends Observable { public void sendBroadcast(String broadcast) { this.setChanged(); this.notifyObservers(broadcast); } } /* * Copyright (C) 2011 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.scenegraph; import java.lang.Math; import java.util.ArrayList; import com.android.scenegraph.SceneManager; import android.renderscript.*; import android.renderscript.Matrix4f; import android.renderscript.RenderScriptGL; import android.util.Log; /** * @hide */ public class Camera extends SceneGraphBase { Transform mTransform; ScriptField_Camera_s.Item mData; ScriptField_Camera_s mField; public Camera() { mData = new ScriptField_Camera_s.Item(); mData.near = 0.1f; mData.far = 1000.0f; mData.horizontalFOV = 60.0f; mData.aspect = 0; } public void setTransform(Transform t) { mTransform = t; if (mField != null) { mField.set_transformMatrix(0, mTransform.getRSData().getAllocation(), true); mField.set_isDirty(0, 1, true); } } public void setFOV(float fov) { mData.horizontalFOV = fov; if (mField != null) { mField.set_horizontalFOV(0, fov, true); mField.set_isDirty(0, 1, true); } } public void setNear(float n) { mData.near = n; if (mField != null) { mField.set_near(0, n, true); mField.set_isDirty(0, 1, true); } } public void setFar(float f) { mData.far = f; if (mField != null) { mField.set_far(0, f, true); mField.set_isDirty(0, 1, true); } } public void setName(String n) { super.setName(n); if (mField != null) { RenderScriptGL rs = SceneManager.getRS(); mData.name = getNameAlloc(rs); mField.set_name(0, mData.name, true); mField.set_isDirty(0, 1, true); } } ScriptField_Camera_s getRSData() { if (mField != null) { return mField; } RenderScriptGL rs = SceneManager.getRS(); if (rs == null) { return null; } if (mTransform == null) { throw new RuntimeException("Cameras without transforms are invalid"); } mField = new ScriptField_Camera_s(rs, 1); mData.transformMatrix = mTransform.getRSData().getAllocation(); mData.transformTimestamp = 1; mData.timestamp = 1; mData.isDirty = 1; mData.name = getNameAlloc(rs); mField.set(mData, 0, true); return mField; } } package net.jbock.examples.fixture; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import static net.jbock.examples.fixture.ParserTestFixture.assertArraysEquals; public class TestOutputStream { private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); public final PrintStream out = new PrintStream(baos); @Override public String toString() { return baos.toString(); } public void assertEquals(String... expected) { String stdout = baos.toString(); String[] actual = stdout.split("\\R", -1); assertArraysEquals(expected, actual); } public String[] split() { String stdout = baos.toString(); return stdout.split("\\R", -1); } } app/src/main/java/com/scenappsm/android/wcPlayerStatistics/PlayerActivity.java package com.scenappsm.android.wcPlayerStatistics; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.google.android.exoplayer2.ExoPlaybackException; import com.google.android.exoplayer2.PlaybackParameters; import com.google.android.exoplayer2.Player; import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.source.TrackGroupArray; import com.google.android.exoplayer2.trackselection.TrackSelectionArray; import com.google.android.exoplayer2.ui.PlayerView; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.scenappsm.wecandeosdkplayer.SdkInterface; import com.scenappsm.wecandeosdkplayer.WecandeoSdk; import com.scenappsm.wecandeosdkplayer.WecandeoVideo; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; public class PlayerActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener, Player.EventListener, SdkInterface.onSdkListener{ WecandeoSdk wecandeoSdk; WecandeoVideo wecandeoVideo; VodStatistics vodStatistics; // 통계 연동 객체 private static final String TAG = "PlayerActivity"; boolean isInitVideoInfo = true; // 플레이어가 준비 완료되면 true 이후 false (최초 한번만 실행) boolean isPlaying = false; // 재생 시작 여부 // 풀스크린 여부 private boolean isFullscreen = false; ConstraintLayout mainLayout; ConstraintLayout playerParent; PlayerView playerView; Button retryButton; Button stopButton; Button playButton; Button pauseButton; Button muteButton; Button volumeUpButton; Button volumeDownButton; Button rewindButton; Button forwardButton; Button fullScreenButton; Spinner resizeSpinner; TextView actionText; TextView debugText; List