idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
25,300 | private boolean createBondApi18 ( @ NonNull final BluetoothDevice device ) { /* * There is a createBond() method in BluetoothDevice class but for now it's hidden. We will call it using reflections. It has been revealed in KitKat (Api19) */ try { final Method createBond = device . getClass ( ) . getMethod ( "createBond" ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_DEBUG , "gatt.getDevice().createBond() (hidden)" ) ; return ( Boolean ) createBond . invoke ( device ) ; } catch ( final Exception e ) { Log . w ( TAG , "An exception occurred while creating bond" , e ) ; } return false ; } | A method that creates the bond to given device on API lower than Android 5 . | 164 | 16 |
25,301 | @ SuppressWarnings ( "UnusedReturnValue" ) boolean removeBond ( ) { final BluetoothDevice device = mGatt . getDevice ( ) ; if ( device . getBondState ( ) == BluetoothDevice . BOND_NONE ) return true ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_VERBOSE , "Removing bond information..." ) ; boolean result = false ; /* * There is a removeBond() method in BluetoothDevice class but for now it's hidden. We will call it using reflections. */ try { //noinspection JavaReflectionMemberAccess final Method removeBond = device . getClass ( ) . getMethod ( "removeBond" ) ; mRequestCompleted = false ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_DEBUG , "gatt.getDevice().removeBond() (hidden)" ) ; result = ( Boolean ) removeBond . invoke ( device ) ; // We have to wait until device is unbounded try { synchronized ( mLock ) { while ( ! mRequestCompleted && ! mAborted ) mLock . wait ( ) ; } } catch ( final InterruptedException e ) { loge ( "Sleeping interrupted" , e ) ; } } catch ( final Exception e ) { Log . w ( TAG , "An exception occurred while removing bond information" , e ) ; } return result ; } | Removes the bond information for the given device . | 306 | 10 |
25,302 | @ RequiresApi ( api = Build . VERSION_CODES . LOLLIPOP ) void requestMtu ( @ IntRange ( from = 0 , to = 517 ) final int mtu ) throws DeviceDisconnectedException , UploadAbortedException { if ( mAborted ) throw new UploadAbortedException ( ) ; mRequestCompleted = false ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_VERBOSE , "Requesting new MTU..." ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_DEBUG , "gatt.requestMtu(" + mtu + ")" ) ; if ( ! mGatt . requestMtu ( mtu ) ) return ; // We have to wait until the MTU exchange finishes try { synchronized ( mLock ) { while ( ( ! mRequestCompleted && mConnected && mError == 0 ) || mPaused ) mLock . wait ( ) ; } } catch ( final InterruptedException e ) { loge ( "Sleeping interrupted" , e ) ; } if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to read Service Changed CCCD: device disconnected" ) ; } | Requests given MTU . This method is only supported on Android Lollipop or newer versions . Only DFU from SDK 14 . 1 or newer supports MTU > 23 . | 264 | 35 |
25,303 | byte [ ] readNotificationResponse ( ) throws DeviceDisconnectedException , DfuException , UploadAbortedException { // do not clear the mReceiveData here. The response might already be obtained. Clear it in write request instead. try { synchronized ( mLock ) { while ( ( mReceivedData == null && mConnected && mError == 0 && ! mAborted ) || mPaused ) mLock . wait ( ) ; } } catch ( final InterruptedException e ) { loge ( "Sleeping interrupted" , e ) ; } if ( mAborted ) throw new UploadAbortedException ( ) ; if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to write Op Code: device disconnected" ) ; if ( mError != 0 ) throw new DfuException ( "Unable to write Op Code" , mError ) ; return mReceivedData ; } | Waits until the notification will arrive . Returns the data returned by the notification . This method will block the thread until response is not ready or the device gets disconnected . If connection state will change or an error will occur an exception will be thrown . | 193 | 49 |
25,304 | void restartService ( @ NonNull final Intent intent , final boolean scanForBootloader ) { String newAddress = null ; if ( scanForBootloader ) { mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_VERBOSE , "Scanning for the DFU Bootloader..." ) ; newAddress = BootloaderScannerFactory . getScanner ( ) . searchFor ( mGatt . getDevice ( ) . getAddress ( ) ) ; logi ( "Scanning for new address finished with: " + newAddress ) ; if ( newAddress != null ) mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_INFO , "DFU Bootloader found with address " + newAddress ) ; else { mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_INFO , "DFU Bootloader not found. Trying the same address..." ) ; } } if ( newAddress != null ) intent . putExtra ( DfuBaseService . EXTRA_DEVICE_ADDRESS , newAddress ) ; // Reset the DFU attempt counter intent . putExtra ( DfuBaseService . EXTRA_DFU_ATTEMPT , 0 ) ; mService . startService ( intent ) ; } | Restarts the service based on the given intent . If parameter set this method will also scan for an advertising bootloader that has address equal or incremented by 1 to the current one . | 269 | 37 |
25,305 | public DfuServiceInitiator setZip ( @ Nullable final Uri uri , @ Nullable final String path ) { return init ( uri , path , 0 , DfuBaseService . TYPE_AUTO , DfuBaseService . MIME_TYPE_ZIP ) ; } | Sets the URI or path of the ZIP file . At least one of the parameters must not be null . If the URI and path are not null the URI will be used . | 61 | 36 |
25,306 | private void setObjectSize ( @ NonNull final byte [ ] data , final int value ) { data [ 2 ] = ( byte ) ( value & 0xFF ) ; data [ 3 ] = ( byte ) ( ( value >> 8 ) & 0xFF ) ; data [ 4 ] = ( byte ) ( ( value >> 16 ) & 0xFF ) ; data [ 5 ] = ( byte ) ( ( value >> 24 ) & 0xFF ) ; } | Sets the object size in correct position of the data array . | 97 | 13 |
25,307 | private void writeCreateRequest ( final int type , final int size ) throws DeviceDisconnectedException , DfuException , UploadAbortedException , RemoteDfuException , UnknownResponseException { if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to create object: device disconnected" ) ; final byte [ ] data = ( type == OBJECT_COMMAND ) ? OP_CODE_CREATE_COMMAND : OP_CODE_CREATE_DATA ; setObjectSize ( data , size ) ; writeOpCode ( mControlPointCharacteristic , data ) ; final byte [ ] response = readNotificationResponse ( ) ; final int status = getStatusCode ( response , OP_CODE_CREATE_KEY ) ; if ( status == SecureDfuError . EXTENDED_ERROR ) throw new RemoteDfuExtendedErrorException ( "Creating Command object failed" , response [ 3 ] ) ; if ( status != DFU_STATUS_SUCCESS ) throw new RemoteDfuException ( "Creating Command object failed" , status ) ; } | Writes Create Object request providing the type and size of the object . | 228 | 14 |
25,308 | private ObjectInfo selectObject ( final int type ) throws DeviceDisconnectedException , DfuException , UploadAbortedException , RemoteDfuException , UnknownResponseException { if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to read object info: device disconnected" ) ; OP_CODE_SELECT_OBJECT [ 1 ] = ( byte ) type ; writeOpCode ( mControlPointCharacteristic , OP_CODE_SELECT_OBJECT ) ; final byte [ ] response = readNotificationResponse ( ) ; final int status = getStatusCode ( response , OP_CODE_SELECT_OBJECT_KEY ) ; if ( status == SecureDfuError . EXTENDED_ERROR ) throw new RemoteDfuExtendedErrorException ( "Selecting object failed" , response [ 3 ] ) ; if ( status != DFU_STATUS_SUCCESS ) throw new RemoteDfuException ( "Selecting object failed" , status ) ; final ObjectInfo info = new ObjectInfo ( ) ; info . maxSize = mControlPointCharacteristic . getIntValue ( BluetoothGattCharacteristic . FORMAT_UINT32 , 3 ) ; info . offset = mControlPointCharacteristic . getIntValue ( BluetoothGattCharacteristic . FORMAT_UINT32 , 3 + 4 ) ; info . CRC32 = mControlPointCharacteristic . getIntValue ( BluetoothGattCharacteristic . FORMAT_UINT32 , 3 + 8 ) ; return info ; } | Selects the current object and reads its metadata . The object info contains the max object size and the offset and CRC32 of the whole object until now . | 315 | 31 |
25,309 | private ObjectChecksum readChecksum ( ) throws DeviceDisconnectedException , DfuException , UploadAbortedException , RemoteDfuException , UnknownResponseException { if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to read Checksum: device disconnected" ) ; writeOpCode ( mControlPointCharacteristic , OP_CODE_CALCULATE_CHECKSUM ) ; final byte [ ] response = readNotificationResponse ( ) ; final int status = getStatusCode ( response , OP_CODE_CALCULATE_CHECKSUM_KEY ) ; if ( status == SecureDfuError . EXTENDED_ERROR ) throw new RemoteDfuExtendedErrorException ( "Receiving Checksum failed" , response [ 3 ] ) ; if ( status != DFU_STATUS_SUCCESS ) throw new RemoteDfuException ( "Receiving Checksum failed" , status ) ; final ObjectChecksum checksum = new ObjectChecksum ( ) ; checksum . offset = mControlPointCharacteristic . getIntValue ( BluetoothGattCharacteristic . FORMAT_UINT32 , 3 ) ; checksum . CRC32 = mControlPointCharacteristic . getIntValue ( BluetoothGattCharacteristic . FORMAT_UINT32 , 3 + 4 ) ; return checksum ; } | Sends the Calculate Checksum request . As a response a notification will be sent with current offset and CRC32 of the current object . | 287 | 28 |
25,310 | private void writeExecute ( ) throws DfuException , DeviceDisconnectedException , UploadAbortedException , UnknownResponseException , RemoteDfuException { if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to read Checksum: device disconnected" ) ; writeOpCode ( mControlPointCharacteristic , OP_CODE_EXECUTE ) ; final byte [ ] response = readNotificationResponse ( ) ; final int status = getStatusCode ( response , OP_CODE_EXECUTE_KEY ) ; if ( status == SecureDfuError . EXTENDED_ERROR ) throw new RemoteDfuExtendedErrorException ( "Executing object failed" , response [ 3 ] ) ; if ( status != DFU_STATUS_SUCCESS ) throw new RemoteDfuException ( "Executing object failed" , status ) ; } | Sends the Execute operation code and awaits for a return notification containing status code . The Execute command will confirm the last chunk of data or the last command that was sent . Creating the same object again instead of executing it allows to retransmitting it in case of a CRC error . | 182 | 58 |
25,311 | public static BootloaderScanner getScanner ( ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) return new BootloaderScannerLollipop ( ) ; return new BootloaderScannerJB ( ) ; } | Returns the scanner implementation . | 60 | 5 |
25,312 | private InputStream openInputStream ( @ NonNull final String filePath , final String mimeType , final int mbrSize , final int types ) throws IOException { final InputStream is = new FileInputStream ( filePath ) ; if ( MIME_TYPE_ZIP . equals ( mimeType ) ) return new ArchiveInputStream ( is , mbrSize , types ) ; if ( filePath . toLowerCase ( Locale . US ) . endsWith ( "hex" ) ) return new HexInputStream ( is , mbrSize ) ; return is ; } | Opens the binary input stream that returns the firmware image content . A Path to the file is given . | 121 | 21 |
25,313 | private InputStream openInputStream ( @ NonNull final Uri stream , final String mimeType , final int mbrSize , final int types ) throws IOException { final InputStream is = getContentResolver ( ) . openInputStream ( stream ) ; if ( MIME_TYPE_ZIP . equals ( mimeType ) ) return new ArchiveInputStream ( is , mbrSize , types ) ; final String [ ] projection = { MediaStore . Images . Media . DISPLAY_NAME } ; final Cursor cursor = getContentResolver ( ) . query ( stream , projection , null , null , null ) ; try { if ( cursor . moveToNext ( ) ) { final String fileName = cursor . getString ( 0 /* DISPLAY_NAME*/ ) ; if ( fileName . toLowerCase ( Locale . US ) . endsWith ( "hex" ) ) return new HexInputStream ( is , mbrSize ) ; } } finally { cursor . close ( ) ; } return is ; } | Opens the binary input stream . A Uri to the stream is given . | 213 | 15 |
25,314 | protected void terminateConnection ( @ NonNull final BluetoothGatt gatt , final int error ) { if ( mConnectionState != STATE_DISCONNECTED ) { // Disconnect from the device disconnect ( gatt ) ; } // Close the device refreshDeviceCache ( gatt , false ) ; // This should be set to true when DFU Version is 0.5 or lower close ( gatt ) ; waitFor ( 600 ) ; if ( error != 0 ) report ( error ) ; } | Disconnects from the device and cleans local variables in case of error . This method is SYNCHRONOUS and wait until the disconnecting process will be completed . | 102 | 34 |
25,315 | protected void waitFor ( final int millis ) { synchronized ( mLock ) { try { sendLogBroadcast ( DfuBaseService . LOG_LEVEL_DEBUG , "wait(" + millis + ")" ) ; mLock . wait ( millis ) ; } catch ( final InterruptedException e ) { loge ( "Sleeping interrupted" , e ) ; } } } | Wait for given number of milliseconds . | 82 | 7 |
25,316 | protected void close ( final BluetoothGatt gatt ) { logi ( "Cleaning up..." ) ; sendLogBroadcast ( LOG_LEVEL_DEBUG , "gatt.close()" ) ; gatt . close ( ) ; mConnectionState = STATE_CLOSED ; } | Closes the GATT device and cleans up . | 60 | 10 |
25,317 | protected void refreshDeviceCache ( final BluetoothGatt gatt , final boolean force ) { /* * If the device is bonded this is up to the Service Changed characteristic to notify Android that the services has changed. * There is no need for this trick in that case. * If not bonded, the Android should not keep the services cached when the Service Changed characteristic is present in the target device database. * However, due to the Android bug (still exists in Android 5.0.1), it is keeping them anyway and the only way to clear services is by using this hidden refresh method. */ if ( force || gatt . getDevice ( ) . getBondState ( ) == BluetoothDevice . BOND_NONE ) { sendLogBroadcast ( LOG_LEVEL_DEBUG , "gatt.refresh() (hidden)" ) ; /* * There is a refresh() method in BluetoothGatt class but for now it's hidden. We will call it using reflections. */ try { //noinspection JavaReflectionMemberAccess final Method refresh = gatt . getClass ( ) . getMethod ( "refresh" ) ; final boolean success = ( Boolean ) refresh . invoke ( gatt ) ; logi ( "Refreshing result: " + success ) ; } catch ( Exception e ) { loge ( "An exception occurred while refreshing device" , e ) ; sendLogBroadcast ( LOG_LEVEL_WARNING , "Refreshing failed" ) ; } } } | Clears the device cache . After uploading new firmware the DFU target will have other services than before . | 307 | 21 |
25,318 | protected void updateProgressNotification ( @ NonNull final NotificationCompat . Builder builder , final int progress ) { // Add Abort action to the notification if ( progress != PROGRESS_ABORTED && progress != PROGRESS_COMPLETED ) { final Intent abortIntent = new Intent ( BROADCAST_ACTION ) ; abortIntent . putExtra ( EXTRA_ACTION , ACTION_ABORT ) ; final PendingIntent pendingAbortIntent = PendingIntent . getBroadcast ( this , 1 , abortIntent , PendingIntent . FLAG_UPDATE_CURRENT ) ; builder . addAction ( R . drawable . ic_action_notify_cancel , getString ( R . string . dfu_action_abort ) , pendingAbortIntent ) ; } } | This method allows you to update the notification showing the upload progress . | 173 | 13 |
25,319 | private void report ( final int error ) { sendErrorBroadcast ( error ) ; if ( mDisableNotification ) return ; // create or update notification: final String deviceAddress = mDeviceAddress ; final String deviceName = mDeviceName != null ? mDeviceName : getString ( R . string . dfu_unknown_name ) ; final NotificationCompat . Builder builder = new NotificationCompat . Builder ( this , NOTIFICATION_CHANNEL_DFU ) . setSmallIcon ( android . R . drawable . stat_sys_upload ) . setOnlyAlertOnce ( true ) . setColor ( Color . RED ) . setOngoing ( false ) . setContentTitle ( getString ( R . string . dfu_status_error ) ) . setSmallIcon ( android . R . drawable . stat_sys_upload_done ) . setContentText ( getString ( R . string . dfu_status_error_msg ) ) . setAutoCancel ( true ) ; // update the notification final Intent intent = new Intent ( this , getNotificationTarget ( ) ) ; intent . addFlags ( Intent . FLAG_ACTIVITY_NEW_TASK ) ; intent . putExtra ( EXTRA_DEVICE_ADDRESS , deviceAddress ) ; intent . putExtra ( EXTRA_DEVICE_NAME , deviceName ) ; intent . putExtra ( EXTRA_PROGRESS , error ) ; // this may contains ERROR_CONNECTION_MASK bit! final PendingIntent pendingIntent = PendingIntent . getActivity ( this , 0 , intent , PendingIntent . FLAG_UPDATE_CURRENT ) ; builder . setContentIntent ( pendingIntent ) ; // Any additional configuration? updateErrorNotification ( builder ) ; final NotificationManager manager = ( NotificationManager ) getSystemService ( Context . NOTIFICATION_SERVICE ) ; manager . notify ( NOTIFICATION_ID , builder . build ( ) ) ; } | Creates or updates the notification in the Notification Manager . Sends broadcast with given error number to the activity . | 420 | 22 |
25,320 | @ SuppressWarnings ( "UnusedReturnValue" ) private boolean initialize ( ) { // For API level 18 and above, get a reference to BluetoothAdapter through // BluetoothManager. final BluetoothManager bluetoothManager = ( BluetoothManager ) getSystemService ( Context . BLUETOOTH_SERVICE ) ; if ( bluetoothManager == null ) { loge ( "Unable to initialize BluetoothManager." ) ; return false ; } mBluetoothAdapter = bluetoothManager . getAdapter ( ) ; if ( mBluetoothAdapter == null ) { loge ( "Unable to obtain a BluetoothAdapter." ) ; return false ; } return true ; } | Initializes bluetooth adapter . | 138 | 6 |
25,321 | private int readLine ( ) throws IOException { // end of file reached if ( pos == - 1 ) return 0 ; final InputStream in = this . in ; // temporary value int b ; int lineSize , type , offset ; do { // skip end of line do { b = in . read ( ) ; pos ++ ; } while ( b == ' ' || b == ' ' ) ; /* * Each line starts with comma (':') * Data is written in HEX, so each 2 ASCII letters give one byte. * After the comma there is one byte (2 HEX signs) with line length * (normally 10 -> 0x10 -> 16 bytes -> 32 HEX characters) * After that there is a 4 byte of an address. This part may be skipped. * There is a packet type after the address (1 byte = 2 HEX characters). * 00 is the valid data. Other values can be skipped when converting to BIN file. * Then goes n bytes of data followed by 1 byte (2 HEX chars) of checksum, * which is also skipped in BIN file. */ checkComma ( b ) ; // checking the comma at the beginning lineSize = readByte ( in ) ; // reading the length of the data in this line pos += 2 ; offset = readAddress ( in ) ; // reading the offset pos += 4 ; type = readByte ( in ) ; // reading the line type pos += 2 ; // if the line type is no longer data type (0x00), we've reached the end of the file switch ( type ) { case 0x00 : // data type if ( lastAddress + offset < MBRSize ) { // skip MBR type = - 1 ; // some other than 0 pos += skip ( in , lineSize * 2 /* 2 hex per one byte */ + 2 /* check sum */ ) ; } break ; case 0x01 : // end of file pos = - 1 ; return 0 ; case 0x02 : { // extended segment address final int address = readAddress ( in ) << 4 ; pos += 4 ; if ( bytesRead > 0 && ( address >> 16 ) != ( lastAddress >> 16 ) + 1 ) return 0 ; lastAddress = address ; pos += skip ( in , 2 /* check sum */ ) ; break ; } case 0x04 : { // extended linear address final int address = readAddress ( in ) ; pos += 4 ; if ( bytesRead > 0 && address != ( lastAddress >> 16 ) + 1 ) return 0 ; lastAddress = address << 16 ; pos += skip ( in , 2 /* check sum */ ) ; break ; } default : final long toBeSkipped = lineSize * 2 /* 2 hex per one byte */ + 2 /* check sum */ ; pos += skip ( in , toBeSkipped ) ; break ; } } while ( type != 0 ) ; // otherwise read lineSize bytes or fill the whole buffer for ( int i = 0 ; i < localBuf . length && i < lineSize ; ++ i ) { b = readByte ( in ) ; pos += 2 ; localBuf [ i ] = ( byte ) b ; } pos += skip ( in , 2 ) ; // skip the checksum localPos = 0 ; return lineSize ; } | Reads new line from the input stream . Input stream must be a HEX file . The first line is always skipped . | 682 | 25 |
25,322 | private int readVersion ( @ Nullable final BluetoothGattCharacteristic characteristic ) { // The value of this characteristic has been read before by LegacyButtonlessDfuImpl return characteristic != null ? characteristic . getIntValue ( BluetoothGattCharacteristic . FORMAT_UINT16 , 0 ) : 0 ; } | Returns the DFU Version characteristic if such exists . Otherwise it returns 0 . | 64 | 15 |
25,323 | private void resetAndRestart ( @ NonNull final BluetoothGatt gatt , @ NonNull final Intent intent ) throws DfuException , DeviceDisconnectedException , UploadAbortedException { mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_WARNING , "Last upload interrupted. Restarting device..." ) ; // Send 'jump to bootloader command' (Start DFU) mProgressInfo . setProgress ( DfuBaseService . PROGRESS_DISCONNECTING ) ; logi ( "Sending Reset command (Op Code = 6)" ) ; writeOpCode ( mControlPointCharacteristic , OP_CODE_RESET ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_APPLICATION , "Reset request sent" ) ; // The device will reset so we don't have to send Disconnect signal. mService . waitUntilDisconnected ( ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_INFO , "Disconnected by the remote device" ) ; final BluetoothGattService gas = gatt . getService ( GENERIC_ATTRIBUTE_SERVICE_UUID ) ; final boolean hasServiceChanged = gas != null && gas . getCharacteristic ( SERVICE_CHANGED_UUID ) != null ; mService . refreshDeviceCache ( gatt , ! hasServiceChanged ) ; // Close the device mService . close ( gatt ) ; logi ( "Restarting the service" ) ; final Intent newIntent = new Intent ( ) ; newIntent . fillIn ( intent , Intent . FILL_IN_COMPONENT | Intent . FILL_IN_PACKAGE ) ; restartService ( newIntent , false ) ; } | Sends Reset command to the target device to reset its state and restarts the DFU Service that will start again . | 381 | 24 |
25,324 | public static JsiiObjectRef parse ( final JsonNode objRef ) { if ( ! objRef . has ( TOKEN_REF ) ) { throw new JsiiException ( "Malformed object reference. Expecting " + TOKEN_REF ) ; } return new JsiiObjectRef ( objRef . get ( TOKEN_REF ) . textValue ( ) , objRef ) ; } | Creates an object reference . | 85 | 6 |
25,325 | public static JsiiObjectRef fromObjId ( final String objId ) { ObjectNode node = JsonNodeFactory . instance . objectNode ( ) ; node . put ( TOKEN_REF , objId ) ; return new JsiiObjectRef ( objId , node ) ; } | Creates an object ref from an object ID . | 61 | 10 |
25,326 | public void loadModule ( final JsiiModule module ) { try { String tarball = extractResource ( module . getModuleClass ( ) , module . getBundleResourceName ( ) , null ) ; ObjectNode req = makeRequest ( "load" ) ; req . put ( "tarball" , tarball ) ; req . put ( "name" , module . getModuleName ( ) ) ; req . put ( "version" , module . getModuleVersion ( ) ) ; this . runtime . requestResponse ( req ) ; } catch ( IOException e ) { throw new JsiiException ( "Unable to extract resource " + module . getBundleResourceName ( ) , e ) ; } } | Loads a JavaScript module into the remote sandbox . | 150 | 10 |
25,327 | public void deleteObject ( final JsiiObjectRef objRef ) { ObjectNode req = makeRequest ( "del" , objRef ) ; this . runtime . requestResponse ( req ) ; } | Deletes a remote object . | 41 | 6 |
25,328 | public JsonNode getPropertyValue ( final JsiiObjectRef objRef , final String property ) { ObjectNode req = makeRequest ( "get" , objRef ) ; req . put ( "property" , property ) ; return this . runtime . requestResponse ( req ) . get ( "value" ) ; } | Gets a value for a property from a remote object . | 67 | 12 |
25,329 | public void setPropertyValue ( final JsiiObjectRef objRef , final String property , final JsonNode value ) { ObjectNode req = makeRequest ( "set" , objRef ) ; req . put ( "property" , property ) ; req . set ( "value" , value ) ; this . runtime . requestResponse ( req ) ; } | Sets a value for a property in a remote object . | 74 | 12 |
25,330 | public JsonNode getStaticPropertyValue ( final String fqn , final String property ) { ObjectNode req = makeRequest ( "sget" ) ; req . put ( "fqn" , fqn ) ; req . put ( "property" , property ) ; return this . runtime . requestResponse ( req ) . get ( "value" ) ; } | Gets a value of a static property . | 78 | 9 |
25,331 | public void setStaticPropertyValue ( final String fqn , final String property , final JsonNode value ) { ObjectNode req = makeRequest ( "sset" ) ; req . put ( "fqn" , fqn ) ; req . put ( "property" , property ) ; req . set ( "value" , value ) ; this . runtime . requestResponse ( req ) ; } | Sets the value of a mutable static property . | 85 | 11 |
25,332 | public JsonNode callStaticMethod ( final String fqn , final String method , final ArrayNode args ) { ObjectNode req = makeRequest ( "sinvoke" ) ; req . put ( "fqn" , fqn ) ; req . put ( "method" , method ) ; req . set ( "args" , args ) ; JsonNode resp = this . runtime . requestResponse ( req ) ; return resp . get ( "result" ) ; } | Invokes a static method . | 100 | 6 |
25,333 | public JsonNode callMethod ( final JsiiObjectRef objRef , final String method , final ArrayNode args ) { ObjectNode req = makeRequest ( "invoke" , objRef ) ; req . put ( "method" , method ) ; req . set ( "args" , args ) ; JsonNode resp = this . runtime . requestResponse ( req ) ; return resp . get ( "result" ) ; } | Calls a method on a remote object . | 89 | 9 |
25,334 | public JsonNode endAsyncMethod ( final JsiiPromise promise ) { ObjectNode req = makeRequest ( "end" ) ; req . put ( "promiseid" , promise . getPromiseId ( ) ) ; JsonNode resp = this . runtime . requestResponse ( req ) ; if ( resp == null ) { return null ; // result is null } return resp . get ( "result" ) ; } | Ends the execution of an async method . | 90 | 9 |
25,335 | public List < Callback > pendingCallbacks ( ) { ObjectNode req = makeRequest ( "callbacks" ) ; JsonNode resp = this . runtime . requestResponse ( req ) ; JsonNode callbacksResp = resp . get ( "callbacks" ) ; if ( callbacksResp == null || ! callbacksResp . isArray ( ) ) { throw new JsiiException ( "Expecting a 'callbacks' key with an array in response" ) ; } ArrayNode callbacksArray = ( ArrayNode ) callbacksResp ; List < Callback > result = new ArrayList <> ( ) ; callbacksArray . forEach ( node -> { result . add ( JsiiObjectMapper . treeToValue ( node , Callback . class ) ) ; } ) ; return result ; } | Dequques all the currently pending callbacks . | 171 | 10 |
25,336 | public void completeCallback ( final Callback callback , final String error , final JsonNode result ) { ObjectNode req = makeRequest ( "complete" ) ; req . put ( "cbid" , callback . getCbid ( ) ) ; req . put ( "err" , error ) ; req . set ( "result" , result ) ; this . runtime . requestResponse ( req ) ; } | Completes a callback . | 84 | 6 |
25,337 | public JsonNode getModuleNames ( final String moduleName ) { ObjectNode req = makeRequest ( "naming" ) ; req . put ( "assembly" , moduleName ) ; JsonNode resp = this . runtime . requestResponse ( req ) ; return resp . get ( "naming" ) ; } | Returns all names for a jsii module . | 66 | 9 |
25,338 | private ObjectNode makeRequest ( final String api ) { ObjectNode req = JSON . objectNode ( ) ; req . put ( "api" , api ) ; return req ; } | Returns a request object for a specific API call . | 37 | 10 |
25,339 | private ObjectNode makeRequest ( final String api , final JsiiObjectRef objRef ) { ObjectNode req = makeRequest ( api ) ; req . set ( "objref" , objRef . toJson ( ) ) ; return req ; } | Returns a new request object for a specific API and a specific object . | 53 | 14 |
25,340 | JsonNode requestResponse ( final JsonNode request ) { try { // write request String str = request . toString ( ) ; this . stdin . write ( str + "\n" ) ; this . stdin . flush ( ) ; // read response JsonNode resp = readNextResponse ( ) ; // throw if this is an error response if ( resp . has ( "error" ) ) { return processErrorResponse ( resp ) ; } // process synchronous callbacks (which 'interrupt' the response flow). if ( resp . has ( "callback" ) ) { return processCallbackResponse ( resp ) ; } // null "ok" means undefined result (or void). return resp . get ( "ok" ) ; } catch ( IOException e ) { throw new JsiiException ( "Unable to send request to jsii-runtime: " + e . toString ( ) , e ) ; } } | The main API of this class . Sends a JSON request to jsii - runtime and returns the JSON response . | 194 | 23 |
25,341 | private JsonNode processErrorResponse ( final JsonNode resp ) { String errorMessage = resp . get ( "error" ) . asText ( ) ; if ( resp . has ( "stack" ) ) { errorMessage += "\n" + resp . get ( "stack" ) . asText ( ) ; } throw new JsiiException ( errorMessage ) ; } | Handles an error response by extracting the message and stack trace and throwing a JsiiException . | 79 | 20 |
25,342 | private JsonNode processCallbackResponse ( final JsonNode resp ) { if ( this . callbackHandler == null ) { throw new JsiiException ( "Cannot process callback since callbackHandler was not set" ) ; } Callback callback = JsiiObjectMapper . treeToValue ( resp . get ( "callback" ) , Callback . class ) ; JsonNode result = null ; String error = null ; try { result = this . callbackHandler . handleCallback ( callback ) ; } catch ( Exception e ) { if ( e . getCause ( ) instanceof InvocationTargetException ) { error = e . getCause ( ) . getCause ( ) . getMessage ( ) ; } else { error = e . getMessage ( ) ; } } ObjectNode completeResponse = JsonNodeFactory . instance . objectNode ( ) ; completeResponse . put ( "cbid" , callback . getCbid ( ) ) ; if ( error != null ) { completeResponse . put ( "err" , error ) ; } if ( result != null ) { completeResponse . set ( "result" , result ) ; } ObjectNode req = JsonNodeFactory . instance . objectNode ( ) ; req . set ( "complete" , completeResponse ) ; return requestResponse ( req ) ; } | Processes a callback response which is a request to invoke a synchronous callback and send back the result . | 272 | 21 |
25,343 | private void startRuntimeIfNeeded ( ) { if ( childProcess != null ) { return ; } // If JSII_DEBUG is set, enable traces. String jsiiDebug = System . getenv ( "JSII_DEBUG" ) ; if ( jsiiDebug != null && ! jsiiDebug . isEmpty ( ) && ! jsiiDebug . equalsIgnoreCase ( "false" ) && ! jsiiDebug . equalsIgnoreCase ( "0" ) ) { traceEnabled = true ; } // If JSII_RUNTIME is set, use it to find the jsii-server executable // otherwise, we default to "jsii-runtime" from PATH. String jsiiRuntimeExecutable = System . getenv ( "JSII_RUNTIME" ) ; if ( jsiiRuntimeExecutable == null ) { jsiiRuntimeExecutable = prepareBundledRuntime ( ) ; } if ( traceEnabled ) { System . err . println ( "jsii-runtime: " + jsiiRuntimeExecutable ) ; } ProcessBuilder pb = new ProcessBuilder ( "node" , jsiiRuntimeExecutable ) ; if ( traceEnabled ) { pb . environment ( ) . put ( "JSII_DEBUG" , "1" ) ; } pb . environment ( ) . put ( "JSII_AGENT" , "Java/" + System . getProperty ( "java.version" ) ) ; try { this . childProcess = pb . start ( ) ; } catch ( IOException e ) { throw new JsiiException ( "Cannot find the 'jsii-runtime' executable (JSII_RUNTIME or PATH)" ) ; } try { OutputStreamWriter stdinStream = new OutputStreamWriter ( this . childProcess . getOutputStream ( ) , "UTF-8" ) ; InputStreamReader stdoutStream = new InputStreamReader ( this . childProcess . getInputStream ( ) , "UTF-8" ) ; InputStreamReader stderrStream = new InputStreamReader ( this . childProcess . getErrorStream ( ) , "UTF-8" ) ; this . stderr = new BufferedReader ( stderrStream ) ; this . stdout = new BufferedReader ( stdoutStream ) ; this . stdin = new BufferedWriter ( stdinStream ) ; handshake ( ) ; this . client = new JsiiClient ( this ) ; // if trace is enabled, start a thread that continuously reads from the child process's // STDERR and prints to my STDERR. if ( traceEnabled ) { startPipeErrorStreamThread ( ) ; } } catch ( IOException e ) { throw new JsiiException ( e ) ; } } | Starts jsii - server as a child process if it is not already started . | 574 | 17 |
25,344 | private void handshake ( ) { JsonNode helloResponse = this . readNextResponse ( ) ; if ( ! helloResponse . has ( "hello" ) ) { throw new JsiiException ( "Expecting 'hello' message from jsii-runtime" ) ; } String runtimeVersion = helloResponse . get ( "hello" ) . asText ( ) ; assertVersionCompatible ( JSII_RUNTIME_VERSION , runtimeVersion ) ; } | Verifies the hello message and runtime version compatibility . In the meantime we require full version compatibility but we should use semver eventually . | 95 | 26 |
25,345 | JsonNode readNextResponse ( ) { try { String responseLine = this . stdout . readLine ( ) ; if ( responseLine == null ) { String error = this . stderr . lines ( ) . collect ( Collectors . joining ( "\n\t" ) ) ; throw new JsiiException ( "Child process exited unexpectedly: " + error ) ; } return JsiiObjectMapper . INSTANCE . readTree ( responseLine ) ; } catch ( IOException e ) { throw new JsiiException ( "Unable to read reply from jsii-runtime: " + e . toString ( ) , e ) ; } } | Reads the next response from STDOUT of the child process . | 139 | 13 |
25,346 | private void startPipeErrorStreamThread ( ) { Thread daemon = new Thread ( ( ) -> { while ( true ) { try { String line = stderr . readLine ( ) ; System . err . println ( line ) ; if ( line == null ) { break ; } } catch ( IOException e ) { e . printStackTrace ( ) ; } } } ) ; daemon . setDaemon ( true ) ; daemon . start ( ) ; } | Starts a thread that pipes STDERR from the child process to our STDERR . | 97 | 17 |
25,347 | static void assertVersionCompatible ( final String expectedVersion , final String actualVersion ) { final String shortActualVersion = actualVersion . replaceAll ( VERSION_BUILD_PART_REGEX , "" ) ; final String shortExpectedVersion = expectedVersion . replaceAll ( VERSION_BUILD_PART_REGEX , "" ) ; if ( shortExpectedVersion . compareTo ( shortActualVersion ) != 0 ) { throw new JsiiException ( "Incompatible jsii-runtime version. Expecting " + shortExpectedVersion + ", actual was " + shortActualVersion ) ; } } | Asserts that a peer runtimeVersion is compatible with this Java runtime version which means they share the same version components with the possible exception of the build number . | 129 | 32 |
25,348 | private String prepareBundledRuntime ( ) { try { String directory = Files . createTempDirectory ( "jsii-java-runtime" ) . toString ( ) ; String entrypoint = extractResource ( getClass ( ) , "jsii-runtime.js" , directory ) ; extractResource ( getClass ( ) , "jsii-runtime.js.map" , directory ) ; extractResource ( getClass ( ) , "mappings.wasm" , directory ) ; return entrypoint ; } catch ( IOException e ) { throw new JsiiException ( "Unable to extract bundle of jsii-runtime.js from jar" , e ) ; } } | Extracts all files needed for jsii - runtime . js from JAR into a temp directory . | 142 | 21 |
25,349 | public void loadModule ( final Class < ? extends JsiiModule > moduleClass ) { if ( ! JsiiModule . class . isAssignableFrom ( moduleClass ) ) { throw new JsiiException ( "Invalid module class " + moduleClass . getName ( ) + ". It must be derived from JsiiModule" ) ; } JsiiModule module ; try { module = moduleClass . newInstance ( ) ; } catch ( IllegalAccessException | InstantiationException e ) { throw new JsiiException ( e ) ; } if ( this . loadedModules . containsKey ( module . getModuleName ( ) ) ) { return ; } // Load dependencies for ( Class < ? extends JsiiModule > dep : module . getDependencies ( ) ) { loadModule ( dep ) ; } this . getClient ( ) . loadModule ( module ) ; // indicate that it was loaded this . loadedModules . put ( module . getModuleName ( ) , module ) ; } | Loads a JavaScript module into the remote jsii - server . No - op if the module is already loaded . | 213 | 23 |
25,350 | public void registerObject ( final JsiiObjectRef objRef , final Object obj ) { if ( obj instanceof JsiiObject ) { ( ( JsiiObject ) obj ) . setObjRef ( objRef ) ; } this . objects . put ( objRef . getObjId ( ) , obj ) ; } | Registers an object into the object cache . | 68 | 9 |
25,351 | public Object nativeFromObjRef ( final JsiiObjectRef objRef ) { Object obj = this . objects . get ( objRef . getObjId ( ) ) ; if ( obj == null ) { obj = createNative ( objRef . getFqn ( ) ) ; this . registerObject ( objRef , obj ) ; } return obj ; } | Returns the native java object for a given jsii object reference . If it already exists in our native objects cache we return it . | 75 | 26 |
25,352 | public JsiiObjectRef nativeToObjRef ( final Object nativeObject ) { if ( nativeObject instanceof JsiiObject ) { return ( ( JsiiObject ) nativeObject ) . getObjRef ( ) ; } for ( String objid : this . objects . keySet ( ) ) { Object obj = this . objects . get ( objid ) ; if ( obj == nativeObject ) { return JsiiObjectRef . fromObjId ( objid ) ; } } // we don't know of an jsii object that represents this object, so we will need to create it. return createNewObject ( nativeObject ) ; } | Returns the jsii object reference given a native object . | 135 | 11 |
25,353 | public Object getObject ( final JsiiObjectRef objRef ) { Object obj = this . objects . get ( objRef . getObjId ( ) ) ; if ( obj == null ) { throw new JsiiException ( "Cannot find jsii object: " + objRef . getObjId ( ) ) ; } return obj ; } | Gets an object by reference . Throws if the object cannot be found . | 73 | 16 |
25,354 | private Class < ? > resolveJavaClass ( final String fqn ) throws ClassNotFoundException { String [ ] parts = fqn . split ( "\\." ) ; if ( parts . length < 2 ) { throw new JsiiException ( "Malformed FQN: " + fqn ) ; } String moduleName = parts [ 0 ] ; JsonNode names = this . getClient ( ) . getModuleNames ( moduleName ) ; if ( ! names . has ( "java" ) ) { throw new JsiiException ( "No java name for module " + moduleName ) ; } final JsiiModule module = this . loadedModules . get ( moduleName ) ; if ( module == null ) { throw new JsiiException ( "No loaded module is named " + moduleName ) ; } return module . resolveClass ( fqn ) ; } | Given a jsii FQN returns the Java class for it . | 188 | 14 |
25,355 | private JsiiObject createNative ( final String fqn ) { try { Class < ? > klass = resolveJavaClass ( fqn ) ; if ( klass . isInterface ( ) || Modifier . isAbstract ( klass . getModifiers ( ) ) ) { // "$" is used to represent inner classes in Java klass = Class . forName ( klass . getCanonicalName ( ) + "$" + INTERFACE_PROXY_CLASS_NAME ) ; } try { Constructor < ? extends Object > ctor = klass . getDeclaredConstructor ( JsiiObject . InitializationMode . class ) ; ctor . setAccessible ( true ) ; JsiiObject newObj = ( JsiiObject ) ctor . newInstance ( JsiiObject . InitializationMode . Jsii ) ; ctor . setAccessible ( false ) ; return newObj ; } catch ( NoSuchMethodException e ) { throw new JsiiException ( "Cannot create native object of type " + klass . getName ( ) + " without a constructor that accepts an InitializationMode argument" , e ) ; } catch ( IllegalAccessException | InstantiationException | InvocationTargetException e ) { throw new JsiiException ( "Unable to instantiate a new object for FQN " + fqn + ": " + e . getMessage ( ) , e ) ; } } catch ( ClassNotFoundException e ) { this . log ( "WARNING: Cannot find the class: %s. Defaulting to JsiiObject" , fqn ) ; return new JsiiObject ( JsiiObject . InitializationMode . Jsii ) ; } } | Given a jsii FQN instantiates a Java JsiiObject . | 367 | 16 |
25,356 | public void processAllPendingCallbacks ( ) { while ( true ) { List < Callback > callbacks = this . getClient ( ) . pendingCallbacks ( ) ; if ( callbacks . size ( ) == 0 ) { break ; } callbacks . forEach ( this :: processCallback ) ; } } | Dequeues and processes pending jsii callbacks until there are no more callbacks to process . | 66 | 20 |
25,357 | private JsonNode invokeCallbackGet ( final GetRequest req ) { Object obj = this . getObject ( req . getObjref ( ) ) ; String methodName = javaScriptPropertyToJavaPropertyName ( "get" , req . getProperty ( ) ) ; try { Method getter = obj . getClass ( ) . getMethod ( methodName ) ; return JsiiObjectMapper . valueToTree ( invokeMethod ( obj , getter ) ) ; } catch ( NoSuchMethodException e ) { throw new JsiiException ( e ) ; } } | Invokes an override for a property getter . | 119 | 10 |
25,358 | private JsonNode invokeCallbackSet ( final SetRequest req ) { final Object obj = this . getObject ( req . getObjref ( ) ) ; String setterMethodName = javaScriptPropertyToJavaPropertyName ( "set" , req . getProperty ( ) ) ; Method setter = null ; for ( Method method : obj . getClass ( ) . getMethods ( ) ) { if ( method . getName ( ) . equals ( setterMethodName ) ) { setter = method ; break ; } } if ( setter == null ) { throw new JsiiException ( "Unable to find property setter " + setterMethodName ) ; } final Object arg = JsiiObjectMapper . treeToValue ( req . getValue ( ) , setter . getParameterTypes ( ) [ 0 ] ) ; return JsiiObjectMapper . valueToTree ( invokeMethod ( obj , setter , arg ) ) ; } | Invokes an override for a property setter . | 201 | 10 |
25,359 | private JsonNode invokeCallbackMethod ( final InvokeRequest req , final String cookie ) { Object obj = this . getObject ( req . getObjref ( ) ) ; Method method = this . findCallbackMethod ( obj . getClass ( ) , cookie ) ; final Class < ? > [ ] argTypes = method . getParameterTypes ( ) ; final Object [ ] args = new Object [ argTypes . length ] ; for ( int i = 0 ; i < argTypes . length ; i ++ ) { args [ i ] = JsiiObjectMapper . treeToValue ( req . getArgs ( ) . get ( i ) , argTypes [ i ] ) ; } return JsiiObjectMapper . valueToTree ( invokeMethod ( obj , method , args ) ) ; } | Invokes an override for a method . | 166 | 8 |
25,360 | private Object invokeMethod ( final Object obj , final Method method , final Object ... args ) { // turn method to accessible. otherwise, we won't be able to callback to methods // on non-public classes. boolean accessibility = method . isAccessible ( ) ; method . setAccessible ( true ) ; try { try { return method . invoke ( obj , args ) ; } catch ( Exception e ) { this . log ( "Error while invoking %s with %s: %s" , method , Arrays . toString ( args ) , Throwables . getStackTraceAsString ( e ) ) ; throw e ; } } catch ( InvocationTargetException e ) { throw new JsiiException ( e . getTargetException ( ) ) ; } catch ( IllegalAccessException e ) { throw new JsiiException ( e ) ; } finally { // revert accessibility. method . setAccessible ( accessibility ) ; } } | Invokes a Java method even if the method is protected . | 194 | 12 |
25,361 | private void processCallback ( final Callback callback ) { try { JsonNode result = handleCallback ( callback ) ; this . getClient ( ) . completeCallback ( callback , null , result ) ; } catch ( JsiiException e ) { this . getClient ( ) . completeCallback ( callback , e . getMessage ( ) , null ) ; } } | Process a single callback by invoking the native method it refers to . | 75 | 13 |
25,362 | private Method findCallbackMethod ( final Class < ? > klass , final String signature ) { for ( Method method : klass . getMethods ( ) ) { if ( method . toString ( ) . equals ( signature ) ) { // found! return method ; } } throw new JsiiException ( "Unable to find callback method with signature: " + signature ) ; } | Finds the Java method that implements a callback . | 79 | 10 |
25,363 | private static Collection < JsiiOverride > discoverOverrides ( final Class < ? > classToInspect ) { Map < String , JsiiOverride > overrides = new HashMap <> ( ) ; Class < ? > klass = classToInspect ; // if we reached a generated jsii class or Object, we should stop collecting those overrides since // all the rest of the hierarchy is generated all the way up to JsiiObject and java.lang.Object. while ( klass != null && klass . getDeclaredAnnotationsByType ( Jsii . class ) . length == 0 && klass != Object . class ) { // add all the methods in the current class for ( Method method : klass . getDeclaredMethods ( ) ) { if ( Modifier . isPrivate ( method . getModifiers ( ) ) ) { continue ; } String methodName = method . getName ( ) ; // check if this is a property ("getXXX" or "setXXX", oh java!) if ( isJavaPropertyMethod ( methodName ) ) { String propertyName = javaPropertyToJSProperty ( methodName ) ; // skip if this property is already in the overrides list if ( overrides . containsKey ( propertyName ) ) { continue ; } JsiiOverride override = new JsiiOverride ( ) ; override . setProperty ( propertyName ) ; overrides . put ( propertyName , override ) ; } else { // if this method is already overridden, skip it if ( overrides . containsKey ( methodName ) ) { continue ; } // we use the method's .toString() as a cookie, which will later be used to identify the // method when it is called back. JsiiOverride override = new JsiiOverride ( ) ; override . setMethod ( methodName ) ; override . setCookie ( method . toString ( ) ) ; overrides . put ( methodName , override ) ; } } klass = klass . getSuperclass ( ) ; } return overrides . values ( ) ; } | Prepare a list of methods which are overridden by Java classes . | 435 | 14 |
25,364 | static Jsii tryGetJsiiAnnotation ( final Class < ? > type , final boolean inherited ) { Jsii [ ] ann ; if ( inherited ) { ann = ( Jsii [ ] ) type . getAnnotationsByType ( Jsii . class ) ; } else { ann = ( Jsii [ ] ) type . getDeclaredAnnotationsByType ( Jsii . class ) ; } if ( ann . length == 0 ) { return null ; } return ann [ 0 ] ; } | Attempts to find the | 109 | 4 |
25,365 | String loadModuleForClass ( Class < ? > nativeClass ) { final Jsii jsii = tryGetJsiiAnnotation ( nativeClass , true ) ; if ( jsii == null ) { throw new JsiiException ( "Unable to find @Jsii annotation for class" ) ; } this . loadModule ( jsii . module ( ) ) ; return jsii . fqn ( ) ; } | Given a java class that extends a Jsii proxy loads the corresponding jsii module and returns the FQN of the jsii type . | 88 | 29 |
25,366 | static String readString ( final InputStream is ) { try ( final Scanner s = new Scanner ( is , "UTF-8" ) ) { s . useDelimiter ( "\\A" ) ; if ( s . hasNext ( ) ) { return s . next ( ) ; } else { return "" ; } } } | Reads a string from an input stream . | 71 | 9 |
25,367 | static String extractResource ( final Class < ? > klass , final String resourceName , final String outputDirectory ) throws IOException { String directory = outputDirectory ; if ( directory == null ) { directory = Files . createTempDirectory ( "jsii-java-runtime-resource" ) . toString ( ) ; } Path target = Paths . get ( directory , resourceName ) ; // make sure directory tree is created, for the case of "@scoped/deps" Files . createDirectories ( target . getParent ( ) ) ; try ( InputStream inputStream = klass . getResourceAsStream ( resourceName ) ) { Files . copy ( inputStream , target ) ; } return target . toAbsolutePath ( ) . toString ( ) ; } | Extracts a resource file from the . jar and saves it into an output directory . | 160 | 18 |
25,368 | @ Nullable protected final < T > T jsiiCall ( final String method , final Class < T > returnType , @ Nullable final Object ... args ) { return JsiiObjectMapper . treeToValue ( JsiiObject . engine . getClient ( ) . callMethod ( this . objRef , method , JsiiObjectMapper . valueToTree ( args ) ) , returnType ) ; } | Calls a JavaScript method on the object . | 88 | 9 |
25,369 | @ Nullable protected static < T > T jsiiStaticCall ( final Class < ? > nativeClass , final String method , final Class < T > returnType , @ Nullable final Object ... args ) { String fqn = engine . loadModuleForClass ( nativeClass ) ; return JsiiObjectMapper . treeToValue ( engine . getClient ( ) . callStaticMethod ( fqn , method , JsiiObjectMapper . valueToTree ( args ) ) , returnType ) ; } | Calls a static method . | 108 | 6 |
25,370 | @ Nullable protected final < T > T jsiiAsyncCall ( final String method , final Class < T > returnType , @ Nullable final Object ... args ) { JsiiClient client = engine . getClient ( ) ; JsiiPromise promise = client . beginAsyncMethod ( this . objRef , method , JsiiObjectMapper . valueToTree ( args ) ) ; engine . processAllPendingCallbacks ( ) ; return JsiiObjectMapper . treeToValue ( client . endAsyncMethod ( promise ) , returnType ) ; } | Calls an async method on the object . | 120 | 9 |
25,371 | @ Nullable protected final < T > T jsiiGet ( final String property , final Class < T > type ) { return JsiiObjectMapper . treeToValue ( engine . getClient ( ) . getPropertyValue ( this . objRef , property ) , type ) ; } | Gets a property value from the object . | 60 | 9 |
25,372 | @ Nullable protected static < T > T jsiiStaticGet ( final Class < ? > nativeClass , final String property , final Class < T > type ) { String fqn = engine . loadModuleForClass ( nativeClass ) ; return JsiiObjectMapper . treeToValue ( engine . getClient ( ) . getStaticPropertyValue ( fqn , property ) , type ) ; } | Returns the value of a static property . | 85 | 8 |
25,373 | protected final void jsiiSet ( final String property , @ Nullable final Object value ) { engine . getClient ( ) . setPropertyValue ( this . objRef , property , JsiiObjectMapper . valueToTree ( value ) ) ; } | Sets a property value of an object . | 53 | 9 |
25,374 | protected static void jsiiStaticSet ( final Class < ? > nativeClass , final String property , @ Nullable final Object value ) { String fqn = engine . loadModuleForClass ( nativeClass ) ; engine . getClient ( ) . setStaticPropertyValue ( fqn , property , JsiiObjectMapper . valueToTree ( value ) ) ; } | Sets a value for a static property . | 78 | 9 |
25,375 | @ RequiresPermission ( Manifest . permission . BLUETOOTH ) static void checkAdapterStateOn ( @ Nullable final BluetoothAdapter adapter ) { if ( adapter == null || adapter . getState ( ) != BluetoothAdapter . STATE_ON ) { throw new IllegalStateException ( "BT Adapter is not turned ON" ) ; } } | Ensure Bluetooth is turned on . | 70 | 7 |
25,376 | private static boolean matchesServiceUuid ( @ NonNull final UUID uuid , @ Nullable final UUID mask , @ NonNull final UUID data ) { if ( mask == null ) { return uuid . equals ( data ) ; } if ( ( uuid . getLeastSignificantBits ( ) & mask . getLeastSignificantBits ( ) ) != ( data . getLeastSignificantBits ( ) & mask . getLeastSignificantBits ( ) ) ) { return false ; } return ( ( uuid . getMostSignificantBits ( ) & mask . getMostSignificantBits ( ) ) == ( data . getMostSignificantBits ( ) & mask . getMostSignificantBits ( ) ) ) ; } | Check if the uuid pattern matches the particular service uuid . | 164 | 13 |
25,377 | @ SuppressWarnings ( "BooleanMethodIsAlwaysInverted" ) private boolean matchesPartialData ( @ Nullable final byte [ ] data , @ Nullable final byte [ ] dataMask , @ Nullable final byte [ ] parsedData ) { if ( data == null ) { // If filter data is null it means it doesn't matter. // We return true if any data matching the manufacturerId were found. return parsedData != null ; } if ( parsedData == null || parsedData . length < data . length ) { return false ; } if ( dataMask == null ) { for ( int i = 0 ; i < data . length ; ++ i ) { if ( parsedData [ i ] != data [ i ] ) { return false ; } } return true ; } for ( int i = 0 ; i < data . length ; ++ i ) { if ( ( dataMask [ i ] & parsedData [ i ] ) != ( dataMask [ i ] & data [ i ] ) ) { return false ; } } return true ; } | Check whether the data pattern matches the parsed data . | 220 | 10 |
25,378 | @ NonNull public synchronized static BluetoothLeScannerCompat getScanner ( ) { if ( instance != null ) return instance ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . O ) return instance = new BluetoothLeScannerImplOreo ( ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . M ) return instance = new BluetoothLeScannerImplMarshmallow ( ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) return instance = new BluetoothLeScannerImplLollipop ( ) ; return instance = new BluetoothLeScannerImplJB ( ) ; } | Returns the scanner compat object | 152 | 5 |
25,379 | private void setPowerSaveSettings ( ) { long minRest = Long . MAX_VALUE , minScan = Long . MAX_VALUE ; synchronized ( wrappers ) { for ( final ScanCallbackWrapper wrapper : wrappers . values ( ) ) { final ScanSettings settings = wrapper . scanSettings ; if ( settings . hasPowerSaveMode ( ) ) { if ( minRest > settings . getPowerSaveRest ( ) ) { minRest = settings . getPowerSaveRest ( ) ; } if ( minScan > settings . getPowerSaveScan ( ) ) { minScan = settings . getPowerSaveScan ( ) ; } } } } if ( minRest < Long . MAX_VALUE && minScan < Long . MAX_VALUE ) { powerSaveRestInterval = minRest ; powerSaveScanInterval = minScan ; if ( powerSaveHandler != null ) { powerSaveHandler . removeCallbacks ( powerSaveScanTask ) ; powerSaveHandler . removeCallbacks ( powerSaveSleepTask ) ; powerSaveHandler . postDelayed ( powerSaveSleepTask , powerSaveScanInterval ) ; } } else { powerSaveRestInterval = powerSaveScanInterval = 0 ; if ( powerSaveHandler != null ) { powerSaveHandler . removeCallbacks ( powerSaveScanTask ) ; powerSaveHandler . removeCallbacks ( powerSaveSleepTask ) ; } } } | This method goes through registered callbacks and sets the power rest and scan intervals to next lowest value . | 286 | 20 |
25,380 | public void setCode ( ExprCode code ) { mCode = code ; mStartPos = mCode . mStartPos ; mCurIndex = mStartPos ; } | private int mCount ; | 36 | 5 |
25,381 | public static boolean isRtl ( ) { if ( sEnable && Build . VERSION . SDK_INT >= Build . VERSION_CODES . JELLY_BEAN_MR1 ) { return View . LAYOUT_DIRECTION_RTL == TextUtils . getLayoutDirectionFromLocale ( Locale . getDefault ( ) ) ; } return false ; } | In Rtl env or not . | 83 | 7 |
25,382 | public static int getRealLeft ( boolean isRtl , int parentLeft , int parentWidth , int left , int width ) { if ( isRtl ) { // 1, trim the parent's left. left -= parentLeft ; // 2, calculate the RTL left. left = parentWidth - width - left ; // 3, add the parent's left. left += parentLeft ; } return left ; } | Convert left to RTL left if need . | 85 | 10 |
25,383 | public static ViewServer get ( Context context ) { ApplicationInfo info = context . getApplicationInfo ( ) ; if ( BUILD_TYPE_USER . equals ( Build . TYPE ) && ( info . flags & ApplicationInfo . FLAG_DEBUGGABLE ) != 0 ) { if ( sServer == null ) { sServer = new ViewServer ( ViewServer . VIEW_SERVER_DEFAULT_PORT ) ; } if ( ! sServer . isRunning ( ) ) { try { sServer . start ( ) ; } catch ( IOException e ) { Log . d ( LOG_TAG , "Error:" , e ) ; } } } else { sServer = new NoopViewServer ( ) ; } return sServer ; } | Returns a unique instance of the ViewServer . This method should only be called from the main thread of your application . The server will have the same lifetime as your process . | 153 | 34 |
25,384 | public void removeWindow ( View view ) { mWindowsLock . writeLock ( ) . lock ( ) ; try { mWindows . remove ( view . getRootView ( ) ) ; } finally { mWindowsLock . writeLock ( ) . unlock ( ) ; } fireWindowsChangedEvent ( ) ; } | Invoke this method to unregister a view hierarchy . | 63 | 11 |
25,385 | public void setFocusedWindow ( View view ) { mFocusLock . writeLock ( ) . lock ( ) ; try { mFocusedWindow = view == null ? null : view . getRootView ( ) ; } finally { mFocusLock . writeLock ( ) . unlock ( ) ; } fireFocusChangedEvent ( ) ; } | Invoke this method to change the currently focused window . | 70 | 11 |
25,386 | public void run ( ) { try { mServer = new ServerSocket ( mPort , VIEW_SERVER_MAX_CONNECTIONS , InetAddress . getLocalHost ( ) ) ; } catch ( Exception e ) { Log . w ( LOG_TAG , "Starting ServerSocket error: " , e ) ; } while ( mServer != null && Thread . currentThread ( ) == mThread ) { // Any uncaught exception will crash the system process try { Socket client = mServer . accept ( ) ; if ( mThreadPool != null ) { mThreadPool . submit ( new ViewServerWorker ( client ) ) ; } else { try { client . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } catch ( Exception e ) { Log . w ( LOG_TAG , "Connection error: " , e ) ; } } } | Main server loop . | 189 | 4 |
25,387 | public static String removeQueryParameter ( String url , String key ) { String [ ] urlParts = url . split ( "\\?" ) ; if ( urlParts . length == 2 ) { Map < String , List < String > > paramMap = extractParametersFromQueryString ( urlParts [ 1 ] ) ; if ( paramMap . containsKey ( key ) ) { String queryValue = paramMap . get ( key ) . get ( 0 ) ; String result = url . replace ( key + "=" + queryValue , "" ) ; // improper separators have to be fixed // @TODO find a better way to solve this result = result . replace ( "?&" , "?" ) . replace ( "&&" , "&" ) ; if ( result . endsWith ( "&" ) ) { return result . substring ( 0 , result . length ( ) - 1 ) ; } else { return result ; } } } return url ; } | Remove the given key from the url query string and return the new URL as String . | 200 | 17 |
25,388 | protected void verifyParameterLegality ( Parameter ... parameters ) { for ( Parameter parameter : parameters ) if ( illegalParamNames . contains ( parameter . name ) ) { throw new IllegalArgumentException ( "Parameter '" + parameter . name + "' is reserved for RestFB use - you cannot specify it yourself." ) ; } } | Verifies that the provided parameter names don t collide with the ones we internally pass along to Facebook . | 69 | 20 |
25,389 | public < T extends BaseNlpEntity > List < T > getEntities ( Class < T > clazz ) { List < BaseNlpEntity > resultList = new ArrayList <> ( ) ; for ( BaseNlpEntity item : getEntities ( ) ) { if ( item . getClass ( ) . equals ( clazz ) ) { resultList . add ( item ) ; } } return ( List < T > ) resultList ; } | returns a subset of the found entities . | 95 | 9 |
25,390 | private void fillOrder ( JsonObject summary ) { if ( summary != null ) { order = summary . getString ( "order" , order ) ; } if ( order == null && openGraphCommentOrder != null ) { order = openGraphCommentOrder ; } } | set the order the comments are sorted | 56 | 7 |
25,391 | private void fillCanComment ( JsonObject summary ) { if ( summary != null && summary . get ( "can_comment" ) != null ) { canComment = summary . get ( "can_comment" ) . asBoolean ( ) ; } if ( canComment == null && openGraphCanComment != null ) { canComment = openGraphCanComment ; } } | set the can_comment | 78 | 5 |
25,392 | public static byte [ ] decodeBase64 ( String base64 ) { if ( base64 == null ) throw new NullPointerException ( "Parameter 'base64' cannot be null." ) ; String fixedBase64 = padBase64 ( base64 ) ; return Base64 . getDecoder ( ) . decode ( fixedBase64 ) ; } | Decodes a base64 - encoded string padding out if necessary . | 71 | 13 |
25,393 | public static String encodeAppSecretProof ( String appSecret , String accessToken ) { try { byte [ ] key = appSecret . getBytes ( StandardCharsets . UTF_8 ) ; SecretKeySpec signingKey = new SecretKeySpec ( key , "HmacSHA256" ) ; Mac mac = Mac . getInstance ( "HmacSHA256" ) ; mac . init ( signingKey ) ; byte [ ] raw = mac . doFinal ( accessToken . getBytes ( ) ) ; byte [ ] hex = encodeHex ( raw ) ; return new String ( hex , StandardCharsets . UTF_8 ) ; } catch ( Exception e ) { throw new IllegalStateException ( "Creation of appsecret_proof has failed" , e ) ; } } | Generates an appsecret_proof for facebook . | 162 | 10 |
25,394 | public JsonObject remove ( String name ) { if ( name == null ) { throw new NullPointerException ( NAME_IS_NULL ) ; } int index = indexOf ( name ) ; if ( index != - 1 ) { table . remove ( index ) ; names . remove ( index ) ; values . remove ( index ) ; } return this ; } | Removes a member with the specified name from this object . If this object contains multiple members with the given name only the last one is removed . If this object does not contain a member with the specified name the object is not modified . | 75 | 47 |
25,395 | public JsonObject merge ( JsonObject object ) { if ( object == null ) { throw new NullPointerException ( OBJECT_IS_NULL ) ; } for ( Member member : object ) { this . set ( member . name , member . value ) ; } return this ; } | Copies all members of the specified object into this object . When the specified object contains members with names that also exist in this object the existing values in this object will be replaced by the corresponding values in the specified object . | 61 | 44 |
25,396 | protected String urlDecodeSignedRequestToken ( String signedRequestToken ) { verifyParameterPresence ( "signedRequestToken" , signedRequestToken ) ; return signedRequestToken . replace ( "-" , "+" ) . replace ( "_" , "/" ) . trim ( ) ; } | Decodes a component of a signed request received from Facebook using FB s special URL - encoding strategy . | 60 | 20 |
25,397 | protected boolean verifySignedRequest ( String appSecret , String algorithm , String encodedPayload , byte [ ] signature ) { verifyParameterPresence ( "appSecret" , appSecret ) ; verifyParameterPresence ( "algorithm" , algorithm ) ; verifyParameterPresence ( "encodedPayload" , encodedPayload ) ; verifyParameterPresence ( "signature" , signature ) ; // Normalize algorithm name...FB calls it differently than Java does if ( "HMAC-SHA256" . equalsIgnoreCase ( algorithm ) ) { algorithm = "HMACSHA256" ; } try { Mac mac = Mac . getInstance ( algorithm ) ; mac . init ( new SecretKeySpec ( toBytes ( appSecret ) , algorithm ) ) ; byte [ ] payloadSignature = mac . doFinal ( toBytes ( encodedPayload ) ) ; return Arrays . equals ( signature , payloadSignature ) ; } catch ( Exception e ) { throw new FacebookSignedRequestVerificationException ( "Unable to perform signed request verification" , e ) ; } } | Verifies that the signed request is really from Facebook . | 223 | 11 |
25,398 | protected String toParameterString ( boolean withJsonParameter , Parameter ... parameters ) { if ( ! isBlank ( accessToken ) ) { parameters = parametersWithAdditionalParameter ( Parameter . with ( ACCESS_TOKEN_PARAM_NAME , accessToken ) , parameters ) ; } if ( ! isBlank ( accessToken ) && ! isBlank ( appSecret ) ) { parameters = parametersWithAdditionalParameter ( Parameter . with ( APP_SECRET_PROOF_PARAM_NAME , obtainAppSecretProof ( accessToken , appSecret ) ) , parameters ) ; } if ( withJsonParameter ) { parameters = parametersWithAdditionalParameter ( Parameter . with ( FORMAT_PARAM_NAME , "json" ) , parameters ) ; } StringBuilder parameterStringBuilder = new StringBuilder ( ) ; boolean first = true ; for ( Parameter parameter : parameters ) { if ( first ) { first = false ; } else { parameterStringBuilder . append ( "&" ) ; } parameterStringBuilder . append ( urlEncode ( parameter . name ) ) ; parameterStringBuilder . append ( "=" ) ; parameterStringBuilder . append ( urlEncodedValueForParameterName ( parameter . name , parameter . value ) ) ; } return parameterStringBuilder . toString ( ) ; } | Generate the parameter string to be included in the Facebook API request . | 274 | 14 |
25,399 | protected String getFacebookGraphEndpointUrl ( ) { if ( apiVersion . isUrlElementRequired ( ) ) { return getFacebookEndpointUrls ( ) . getGraphEndpoint ( ) + ' ' + apiVersion . getUrlElement ( ) ; } else { return getFacebookEndpointUrls ( ) . getGraphEndpoint ( ) ; } } | Returns the base endpoint URL for the Graph API . | 75 | 10 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.