idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
25,300
private JsonParserException createHelpfulException ( char first , char [ ] expected , int failurePosition ) throws JsonParserException { StringBuilder errorToken = new StringBuilder ( first + ( expected == null ? "" : new String ( expected , 0 , failurePosition ) ) ) ; while ( isAsciiLetter ( peekChar ( ) ) && errorTok...
Throws a helpful exception based on the current alphanumeric token .
25,301
public void capture ( CaptureMode mode ) { assert dispatchLayer != null ; if ( canceled ) throw new IllegalStateException ( "Cannot capture canceled interaction." ) ; if ( capturingLayer != dispatchLayer && captured ( ) ) throw new IllegalStateException ( "Interaction already captured by " + capturingLayer ) ; capturin...
Captures this interaction in the specified capture mode . Depending on the mode subsequent events will go only to the current layer or that layer and its parents or that layer and its children . Other layers in the interaction will receive a cancellation event and nothing further .
25,302
public void begin ( float fbufWidth , float fbufHeight , boolean flip ) { if ( begun ) throw new IllegalStateException ( getClass ( ) . getSimpleName ( ) + " mismatched begin()" ) ; begun = true ; }
Must be called before this batch is used to accumulate and send drawing commands .
25,303
public static void registerVariant ( String name , Style style , String variantName ) { Map < String , String > styleVariants = _variants . get ( style ) ; if ( styleVariants == null ) { _variants . put ( style , styleVariants = new HashMap < String , String > ( ) ) ; } styleVariants . put ( name , variantName ) ; }
Registers a font for use when a bold italic or bold italic variant is requested . iOS does not programmatically generate bold italic and bold italic variants of fonts . Instead it uses the actual bold italic or bold italic variant of the font provided by the original designer .
25,304
public static FloatBuffer allocate ( int capacity ) { if ( capacity < 0 ) { throw new IllegalArgumentException ( ) ; } ByteBuffer bb = ByteBuffer . allocateDirect ( capacity * 4 ) ; bb . order ( ByteOrder . nativeOrder ( ) ) ; return bb . asFloatBuffer ( ) ; }
Creates a float buffer based on a newly allocated float array .
25,305
public int compareTo ( FloatBuffer otherBuffer ) { int compareRemaining = ( remaining ( ) < otherBuffer . remaining ( ) ) ? remaining ( ) : otherBuffer . remaining ( ) ; int thisPos = position ; int otherPos = otherBuffer . position ; float thisFloat , otherFloat ; while ( compareRemaining > 0 ) { thisFloat = get ( thi...
Compare the remaining floats of this buffer to another float buffer s remaining floats .
25,306
@ SuppressWarnings ( "rawtypes" ) public Class < ? extends TBase > getMessageClass ( String topic ) { return allTopics ? messageClassForAll : messageClassByTopic . get ( topic ) ; }
Returns configured thrift message class for the given Kafka topic
25,307
public void init ( SecorConfig config , OffsetTracker offsetTracker , FileRegistry fileRegistry , UploadManager uploadManager , MessageReader messageReader , MetricCollector metricCollector , DeterministicUploadPolicyTracker deterministicUploadPolicyTracker ) { init ( config , offsetTracker , fileRegistry , uploadManag...
Init the Uploader with its dependent objects .
25,308
public void init ( SecorConfig config , OffsetTracker offsetTracker , FileRegistry fileRegistry , UploadManager uploadManager , MessageReader messageReader , ZookeeperConnector zookeeperConnector , MetricCollector metricCollector , DeterministicUploadPolicyTracker deterministicUploadPolicyTracker ) { mConfig = config ;...
For testing use only .
25,309
protected FileReader createReader ( LogFilePath srcPath , CompressionCodec codec ) throws Exception { return ReflectionUtil . createFileReader ( mConfig . getFileReaderWriterFactory ( ) , srcPath , codec , mConfig ) ; }
This method is intended to be overwritten in tests .
25,310
public void applyPolicy ( boolean forceUpload ) throws Exception { Collection < TopicPartition > topicPartitions = mFileRegistry . getTopicPartitions ( ) ; for ( TopicPartition topicPartition : topicPartitions ) { checkTopicPartition ( topicPartition , forceUpload ) ; } }
Apply the Uploader policy for pushing partition files to the underlying storage .
25,311
private CompressionKind resolveCompression ( CompressionCodec codec ) { if ( codec instanceof Lz4Codec ) return CompressionKind . LZ4 ; else if ( codec instanceof SnappyCodec ) return CompressionKind . SNAPPY ; else if ( codec instanceof GzipCodec ) return CompressionKind . ZLIB ; else return CompressionKind . NONE ; }
Used for returning the compression kind used in ORC
25,312
private FileReader createFileReader ( LogFilePath logFilePath ) throws Exception { CompressionCodec codec = null ; if ( mConfig . getCompressionCodec ( ) != null && ! mConfig . getCompressionCodec ( ) . isEmpty ( ) ) { codec = CompressionUtil . createCompressionCodec ( mConfig . getCompressionCodec ( ) ) ; } FileReader...
Helper to create a file reader writer from config
25,313
public Class < ? extends Message > getMessageClass ( String topic ) { return allTopics ? messageClassForAll : messageClassByTopic . get ( topic ) ; }
Returns configured protobuf message class for the given Kafka topic
25,314
public Message decodeProtobufMessage ( String topic , byte [ ] payload ) { Method parseMethod = allTopics ? messageParseMethodForAll : messageParseMethodByTopic . get ( topic ) ; try { return ( Message ) parseMethod . invoke ( null , payload ) ; } catch ( IllegalArgumentException e ) { throw new RuntimeException ( "Can...
Decodes protobuf message
25,315
public Message decodeProtobufOrJsonMessage ( String topic , byte [ ] payload ) { try { if ( shouldDecodeFromJsonMessage ( topic ) ) { return decodeJsonMessage ( topic , payload ) ; } } catch ( InvalidProtocolBufferException e ) { LOG . debug ( "Unable to translate JSON string {} to protobuf message" , new String ( payl...
Decodes protobuf message If the secor . topic . message . format property is set to JSON for topic assume payload is JSON
25,316
public static UploadManager createUploadManager ( String className , SecorConfig config ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! UploadManager . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assignable to '%s'....
Create an UploadManager from its fully qualified class name .
25,317
public static Uploader createUploader ( String className ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! Uploader . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assignable to '%s'." , className , Uploader . class . g...
Create an Uploader from its fully qualified class name .
25,318
public static MessageParser createMessageParser ( String className , SecorConfig config ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! MessageParser . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assignable to '%s'....
Create a MessageParser from it s fully qualified class name . The class passed in by name must be assignable to MessageParser and have 1 - parameter constructor accepting a SecorConfig . Allows the MessageParser to be pluggable by providing the class name of a desired MessageParser in config .
25,319
private static FileReaderWriterFactory createFileReaderWriterFactory ( String className , SecorConfig config ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! FileReaderWriterFactory . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class ...
Create a FileReaderWriterFactory that is able to read and write a specific type of output log file . The class passed in by name must be assignable to FileReaderWriterFactory . Allows for pluggable FileReader and FileWriter instances to be constructed for a particular type of log file .
25,320
public static FileWriter createFileWriter ( String className , LogFilePath logFilePath , CompressionCodec codec , SecorConfig config ) throws Exception { return createFileReaderWriterFactory ( className , config ) . BuildFileWriter ( logFilePath , codec ) ; }
Use the FileReaderWriterFactory specified by className to build a FileWriter
25,321
public static FileReader createFileReader ( String className , LogFilePath logFilePath , CompressionCodec codec , SecorConfig config ) throws Exception { return createFileReaderWriterFactory ( className , config ) . BuildFileReader ( logFilePath , codec ) ; }
Use the FileReaderWriterFactory specified by className to build a FileReader
25,322
public static MessageTransformer createMessageTransformer ( String className , SecorConfig config ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! MessageTransformer . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assi...
Create a MessageTransformer from it s fully qualified class name . The class passed in by name must be assignable to MessageTransformers and have 1 - parameter constructor accepting a SecorConfig . Allows the MessageTransformers to be pluggable by providing the class name of a desired MessageTransformers in config .
25,323
public static ORCSchemaProvider createORCSchemaProvider ( String className , SecorConfig config ) throws Exception { Class < ? > clazz = Class . forName ( className ) ; if ( ! ORCSchemaProvider . class . isAssignableFrom ( clazz ) ) { throw new IllegalArgumentException ( String . format ( "The class '%s' is not assigna...
Create a ORCSchemaProvider from it s fully qualified class name . The class passed in by name must be assignable to ORCSchemaProvider and have 1 - parameter constructor accepting a SecorConfig . Allows the ORCSchemaProvider to be pluggable by providing the class name of a desired ORCSchemaProvider in config .
25,324
public static String getMd5Hash ( String topic , String [ ] partitions ) { ArrayList < String > elements = new ArrayList < String > ( ) ; elements . add ( topic ) ; for ( String partition : partitions ) { elements . add ( partition ) ; } String pathPrefix = StringUtils . join ( elements , "/" ) ; try { final MessageDig...
Generate MD5 hash of topic and partitions . And extract first 4 characters of the MD5 hash .
25,325
private void setSchemas ( SecorConfig config ) { Map < String , String > schemaPerTopic = config . getORCMessageSchema ( ) ; for ( Entry < String , String > entry : schemaPerTopic . entrySet ( ) ) { String topic = entry . getKey ( ) ; TypeDescription schema = TypeDescription . fromString ( entry . getValue ( ) ) ; topi...
This method is used for fetching all ORC schemas from config
25,326
public Map < String , String > getPropertyMapForPrefix ( String prefix ) { Iterator < String > keys = mProperties . getKeys ( prefix ) ; Map < String , String > map = new HashMap < String , String > ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; String value = mProperties . getString ( key ) ; map ...
This method is used for fetching all the properties which start with the given prefix . It returns a Map of all those key - val .
25,327
private void exportToStatsD ( List < Stat > stats ) { for ( Stat stat : stats ) { @ SuppressWarnings ( "unchecked" ) Map < String , String > tags = ( Map < String , String > ) stat . get ( Stat . STAT_KEYS . TAGS . getName ( ) ) ; long value = Long . parseLong ( ( String ) stat . get ( Stat . STAT_KEYS . VALUE . getNam...
Helper to publish stats to statsD client
25,328
public Collection < TopicPartition > getTopicPartitions ( ) { Collection < TopicPartitionGroup > topicPartitions = getTopicPartitionGroups ( ) ; Set < TopicPartition > tps = new HashSet < TopicPartition > ( ) ; if ( topicPartitions != null ) { for ( TopicPartitionGroup g : topicPartitions ) { tps . addAll ( g . getTopi...
Get all topic partitions .
25,329
public Collection < LogFilePath > getPaths ( TopicPartitionGroup topicPartitionGroup ) { HashSet < LogFilePath > logFilePaths = mFiles . get ( topicPartitionGroup ) ; if ( logFilePaths == null ) { return new HashSet < LogFilePath > ( ) ; } return new HashSet < LogFilePath > ( logFilePaths ) ; }
Get paths in a given topic partition .
25,330
public FileWriter getOrCreateWriter ( LogFilePath path , CompressionCodec codec ) throws Exception { FileWriter writer = mWriters . get ( path ) ; if ( writer == null ) { FileUtil . delete ( path . getLogFilePath ( ) ) ; FileUtil . delete ( path . getLogFileCrcPath ( ) ) ; TopicPartitionGroup topicPartition = new Topic...
Retrieve a writer for a given path or create a new one if it does not exist .
25,331
public void deletePath ( LogFilePath path ) throws IOException { TopicPartitionGroup topicPartition = new TopicPartitionGroup ( path . getTopic ( ) , path . getKafkaPartitions ( ) ) ; HashSet < LogFilePath > paths = mFiles . get ( topicPartition ) ; paths . remove ( path ) ; if ( paths . isEmpty ( ) ) { mFiles . remove...
Delete a given path the underlying file and the corresponding writer .
25,332
public void deleteWriter ( LogFilePath path ) throws IOException { FileWriter writer = mWriters . get ( path ) ; if ( writer == null ) { LOG . warn ( "No writer found for path {}" , path . getLogFilePath ( ) ) ; } else { LOG . info ( "Deleting writer for path {}" , path . getLogFilePath ( ) ) ; writer . close ( ) ; mWr...
Delete writer for a given topic partition . Underlying file is not removed .
25,333
public static void unregisterProgressListener ( final Context context , final DfuProgressListener listener ) { if ( mProgressBroadcastReceiver != null ) { final boolean empty = mProgressBroadcastReceiver . removeProgressListener ( listener ) ; if ( empty ) { LocalBroadcastManager . getInstance ( context ) . unregisterR...
Unregisters the previously registered progress listener .
25,334
public static void unregisterLogListener ( final Context context , final DfuLogListener listener ) { if ( mLogBroadcastReceiver != null ) { final boolean empty = mLogBroadcastReceiver . removeLogListener ( listener ) ; if ( empty ) { LocalBroadcastManager . getInstance ( context ) . unregisterReceiver ( mLogBroadcastRe...
Unregisters the previously registered log listener .
25,335
public void fullReset ( ) { if ( softDeviceBytes != null && bootloaderBytes != null && currentSource == bootloaderBytes ) { currentSource = softDeviceBytes ; } bytesReadFromCurrentSource = 0 ; mark ( 0 ) ; reset ( ) ; }
Resets to the beginning of current stream . If SD and BL were updated the stream will be reset to the beginning . If SD and BL were already sent and the current stream was changed to application this method will reset to the beginning of the application stream .
25,336
void writeInitData ( final BluetoothGattCharacteristic characteristic , final CRC32 crc32 ) throws DfuException , DeviceDisconnectedException , UploadAbortedException { try { byte [ ] data = mBuffer ; int size ; while ( ( size = mInitPacketStream . read ( data , 0 , data . length ) ) != - 1 ) { writeInitPacket ( charac...
Wends the whole init packet stream to the given characteristic .
25,337
void uploadFirmwareImage ( final BluetoothGattCharacteristic packetCharacteristic ) throws DeviceDisconnectedException , DfuException , UploadAbortedException { if ( mAborted ) throw new UploadAbortedException ( ) ; mReceivedData = null ; mError = 0 ; mFirmwareUploadInProgress = true ; mPacketsSentSinceNotification = 0...
Starts sending the data . This method is SYNCHRONOUS and terminates when the whole file will be uploaded or the device get disconnected . If connection state will change or an error will occur an exception will be thrown .
25,338
private void writePacket ( final BluetoothGatt gatt , final BluetoothGattCharacteristic characteristic , final byte [ ] buffer , final int size ) { byte [ ] locBuffer = buffer ; if ( size <= 0 ) return ; if ( buffer . length != size ) { locBuffer = new byte [ size ] ; System . arraycopy ( buffer , 0 , locBuffer , 0 , s...
Writes the buffer to the characteristic . The maximum size of the buffer is dependent on MTU . This method is ASYNCHRONOUS and returns immediately after adding the data to TX queue .
25,339
private int readVersion ( final BluetoothGatt gatt , final BluetoothGattCharacteristic characteristic ) throws DeviceDisconnectedException , DfuException , UploadAbortedException { if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to read version number: device disconnected" ) ; if ( mAborted ) throw ...
Reads the DFU Version characteristic if such exists . Otherwise it returns 0 .
25,340
private boolean createBondApi18 ( final BluetoothDevice device ) { try { final Method createBond = device . getClass ( ) . getMethod ( "createBond" ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_DEBUG , "gatt.getDevice().createBond() (hidden)" ) ; return ( Boolean ) createBond . invoke ( device ) ; } catc...
A method that creates the bond to given device on API lower than Android 5 .
25,341
@ 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 = ...
Removes the bond information for the given device .
25,342
@ 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 . LO...
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 .
25,343
byte [ ] readNotificationResponse ( ) throws DeviceDisconnectedException , DfuException , UploadAbortedException { try { synchronized ( mLock ) { while ( ( mReceivedData == null && mConnected && mError == 0 && ! mAborted ) || mPaused ) mLock . wait ( ) ; } } catch ( final InterruptedException e ) { loge ( "Sleeping int...
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 .
25,344
void restartService ( 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 . g...
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 .
25,345
public DfuServiceInitiator setZip ( final Uri uri , 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 .
25,346
public DfuServiceController start ( final Context context , final Class < ? extends DfuBaseService > service ) { if ( fileType == - 1 ) throw new UnsupportedOperationException ( "You must specify the firmware file before starting the service" ) ; final Intent intent = new Intent ( context , service ) ; intent . putExtr...
Starts the DFU service .
25,347
private void setObjectSize ( 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 .
25,348
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 [ ] d...
Writes Create Object request providing the type and size of the object .
25,349
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 ] = ...
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 .
25,350
private ObjectChecksum readChecksum ( ) throws DeviceDisconnectedException , DfuException , UploadAbortedException , RemoteDfuException , UnknownResponseException { if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to read Checksum: device disconnected" ) ; writeOpCode ( mControlPointCharacteristic , ...
Sends the Calculate Checksum request . As a response a notification will be sent with current offset and CRC32 of the current object .
25,351
private void writeExecute ( ) throws DfuException , DeviceDisconnectedException , UploadAbortedException , UnknownResponseException , RemoteDfuException { if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to read Checksum: device disconnected" ) ; writeOpCode ( mControlPointCharacteristic , OP_CODE_EX...
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 .
25,352
public static BootloaderScanner getScanner ( ) { if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . LOLLIPOP ) return new BootloaderScannerLollipop ( ) ; return new BootloaderScannerJB ( ) ; }
Returns the scanner implementation .
25,353
private InputStream openInputStream ( 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 . t...
Opens the binary input stream that returns the firmware image content . A Path to the file is given .
25,354
private InputStream openInputStream ( 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 ) ; fin...
Opens the binary input stream . A Uri to the stream is given .
25,355
protected void terminateConnection ( final BluetoothGatt gatt , final int error ) { if ( mConnectionState != STATE_DISCONNECTED ) { disconnect ( gatt ) ; } refreshDeviceCache ( gatt , false ) ; 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 .
25,356
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 .
25,357
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 .
25,358
protected void refreshDeviceCache ( final BluetoothGatt gatt , final boolean force ) { if ( force || gatt . getDevice ( ) . getBondState ( ) == BluetoothDevice . BOND_NONE ) { sendLogBroadcast ( LOG_LEVEL_DEBUG , "gatt.refresh() (hidden)" ) ; try { final Method refresh = gatt . getClass ( ) . getMethod ( "refresh" ) ; ...
Clears the device cache . After uploading new firmware the DFU target will have other services than before .
25,359
protected void updateProgressNotification ( final NotificationCompat . Builder builder , final int progress ) { if ( progress != PROGRESS_ABORTED && progress != PROGRESS_COMPLETED ) { final Intent abortIntent = new Intent ( BROADCAST_ACTION ) ; abortIntent . putExtra ( EXTRA_ACTION , ACTION_ABORT ) ; final PendingInten...
This method allows you to update the notification showing the upload progress .
25,360
private void report ( final int error ) { sendErrorBroadcast ( error ) ; if ( mDisableNotification ) return ; final String deviceAddress = mDeviceAddress ; final String deviceName = mDeviceName != null ? mDeviceName : getString ( R . string . dfu_unknown_name ) ; final NotificationCompat . Builder builder = new Notific...
Creates or updates the notification in the Notification Manager . Sends broadcast with given error number to the activity .
25,361
@ SuppressWarnings ( "UnusedReturnValue" ) private boolean initialize ( ) { final BluetoothManager bluetoothManager = ( BluetoothManager ) getSystemService ( Context . BLUETOOTH_SERVICE ) ; if ( bluetoothManager == null ) { loge ( "Unable to initialize BluetoothManager." ) ; return false ; } mBluetoothAdapter = bluetoo...
Initializes bluetooth adapter .
25,362
private int readLine ( ) throws IOException { if ( pos == - 1 ) return 0 ; final InputStream in = this . in ; int b ; int lineSize , type , offset ; do { do { b = in . read ( ) ; pos ++ ; } while ( b == '\n' || b == '\r' ) ; checkComma ( b ) ; lineSize = readByte ( in ) ; pos += 2 ; offset = readAddress ( in ) ; pos +=...
Reads new line from the input stream . Input stream must be a HEX file . The first line is always skipped .
25,363
private int readVersion ( final BluetoothGattCharacteristic characteristic ) { return characteristic != null ? characteristic . getIntValue ( BluetoothGattCharacteristic . FORMAT_UINT16 , 0 ) : 0 ; }
Returns the DFU Version characteristic if such exists . Otherwise it returns 0 .
25,364
private void resetAndRestart ( final BluetoothGatt gatt , final Intent intent ) throws DfuException , DeviceDisconnectedException , UploadAbortedException { mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_WARNING , "Last upload interrupted. Restarting device..." ) ; mProgressInfo . setProgress ( DfuBaseService...
Sends Reset command to the target device to reset its state and restarts the DFU Service that will start again .
25,365
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 .
25,366
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 .
25,367
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...
Loads a JavaScript module into the remote sandbox .
25,368
public void deleteObject ( final JsiiObjectRef objRef ) { ObjectNode req = makeRequest ( "del" , objRef ) ; this . runtime . requestResponse ( req ) ; }
Deletes a remote object .
25,369
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 .
25,370
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 .
25,371
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 .
25,372
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 .
25,373
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 ( "re...
Invokes a static method .
25,374
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 .
25,375
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 ; } return resp . get ( "result" ) ; }
Ends the execution of an async method .
25,376
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 'callback...
Dequques all the currently pending callbacks .
25,377
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 .
25,378
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 .
25,379
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 .
25,380
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 .
25,381
JsonNode requestResponse ( final JsonNode request ) { try { String str = request . toString ( ) ; this . stdin . write ( str + "\n" ) ; this . stdin . flush ( ) ; JsonNode resp = readNextResponse ( ) ; if ( resp . has ( "error" ) ) { return processErrorResponse ( resp ) ; } if ( resp . has ( "callback" ) ) { return pro...
The main API of this class . Sends a JSON request to jsii - runtime and returns the JSON response .
25,382
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 .
25,383
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 = n...
Processes a callback response which is a request to invoke a synchronous callback and send back the result .
25,384
private void startRuntimeIfNeeded ( ) { if ( childProcess != null ) { return ; } String jsiiDebug = System . getenv ( "JSII_DEBUG" ) ; if ( jsiiDebug != null && ! jsiiDebug . isEmpty ( ) && ! jsiiDebug . equalsIgnoreCase ( "false" ) && ! jsiiDebug . equalsIgnoreCase ( "0" ) ) { traceEnabled = true ; } String jsiiRuntim...
Starts jsii - server as a child process if it is not already started .
25,385
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_VERSI...
Verifies the hello message and runtime version compatibility . In the meantime we require full version compatibility but we should use semver eventually .
25,386
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 . INSTAN...
Reads the next response from STDOUT of the child process .
25,387
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 .
25,388
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 ( shortExpectedVers...
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 .
25,389
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 ( getClas...
Extracts all files needed for jsii - runtime . js from JAR into a temp directory .
25,390
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 . new...
Loads a JavaScript module into the remote jsii - server . No - op if the module is already loaded .
25,391
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 .
25,392
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 .
25,393
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 ...
Returns the jsii object reference given a native object .
25,394
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 .
25,395
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 )...
Given a jsii FQN returns the Java class for it .
25,396
private JsiiObject createNative ( final String fqn ) { try { Class < ? > klass = resolveJavaClass ( fqn ) ; if ( klass . isInterface ( ) || Modifier . isAbstract ( klass . getModifiers ( ) ) ) { klass = Class . forName ( klass . getCanonicalName ( ) + "$" + INTERFACE_PROXY_CLASS_NAME ) ; } try { Constructor < ? extends...
Given a jsii FQN instantiates a Java JsiiObject .
25,397
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 .
25,398
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 (...
Invokes an override for a property getter .
25,399
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 ...
Invokes an override for a property setter .