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 ( ) ) && errorToken . length ( ) < 15 ) errorToken . append ( ( char ) advanceChar ( ) ) ; return createParseException ( null , "Unexpected token '" + errorToken + "'" + ( expected == null ? "" : ". Did you mean '" + first + new String ( expected ) + "'?" ) , true ) ; }
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 ) ; capturingLayer = dispatchLayer ; captureMode = mode ; notifyCancel ( capturingLayer , captureMode , event ) ; }
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 ( thisPos ) ; otherFloat = otherBuffer . get ( otherPos ) ; if ( ( thisFloat != otherFloat ) && ( ( thisFloat == thisFloat ) || ( otherFloat == otherFloat ) ) ) { return thisFloat < otherFloat ? - 1 : 1 ; } thisPos ++ ; otherPos ++ ; compareRemaining -- ; } return remaining ( ) - otherBuffer . remaining ( ) ; }
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 , uploadManager , messageReader , new ZookeeperConnector ( config ) , metricCollector , deterministicUploadPolicyTracker ) ; }
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 ; mOffsetTracker = offsetTracker ; mFileRegistry = fileRegistry ; mUploadManager = uploadManager ; mMessageReader = messageReader ; mZookeeperConnector = zookeeperConnector ; mTopicFilter = mConfig . getKafkaTopicUploadAtMinuteMarkFilter ( ) ; mMetricCollector = metricCollector ; mDeterministicUploadPolicyTracker = deterministicUploadPolicyTracker ; if ( mConfig . getOffsetsStorage ( ) . equals ( SecorConstants . KAFKA_OFFSETS_STORAGE_KAFKA ) ) { isOffsetsStorageKafka = true ; } }
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 fileReader = ReflectionUtil . createFileReader ( mConfig . getFileReaderWriterFactory ( ) , logFilePath , codec , mConfig ) ; return 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't parse protobuf message, since parseMethod() is not callable. " + "Please check your protobuf version (this code works with protobuf >= 2.6.1)" , e ) ; } catch ( IllegalAccessException e ) { throw new RuntimeException ( "Can't parse protobuf message, since parseMethod() is not accessible. " + "Please check your protobuf version (this code works with protobuf >= 2.6.1)" , e ) ; } catch ( InvocationTargetException e ) { throw new RuntimeException ( "Error parsing protobuf message" , e ) ; } }
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 ( payload , Charsets . UTF_8 ) ) ; } return decodeProtobufMessage ( topic , payload ) ; }
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'." , className , UploadManager . class . getName ( ) ) ) ; } return ( UploadManager ) clazz . getConstructor ( SecorConfig . class ) . newInstance ( config ) ; }
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 . getName ( ) ) ) ; } return ( Uploader ) clazz . newInstance ( ) ; }
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'." , className , MessageParser . class . getName ( ) ) ) ; } return ( MessageParser ) clazz . getConstructor ( SecorConfig . class ) . newInstance ( config ) ; }
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 '%s' is not assignable to '%s'." , className , FileReaderWriterFactory . class . getName ( ) ) ) ; } try { return ( FileReaderWriterFactory ) clazz . getConstructor ( SecorConfig . class ) . newInstance ( config ) ; } catch ( NoSuchMethodException e ) { return ( FileReaderWriterFactory ) clazz . newInstance ( ) ; } }
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 assignable to '%s'." , className , MessageTransformer . class . getName ( ) ) ) ; } return ( MessageTransformer ) clazz . getConstructor ( SecorConfig . class ) . newInstance ( config ) ; }
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 assignable to '%s'." , className , ORCSchemaProvider . class . getName ( ) ) ) ; } return ( ORCSchemaProvider ) clazz . getConstructor ( SecorConfig . class ) . newInstance ( config ) ; }
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 MessageDigest messageDigest = MessageDigest . getInstance ( "MD5" ) ; byte [ ] md5Bytes = messageDigest . digest ( pathPrefix . getBytes ( "UTF-8" ) ) ; return getHexEncode ( md5Bytes ) . substring ( 0 , 4 ) ; } catch ( NoSuchAlgorithmException e ) { LOG . error ( e . getMessage ( ) ) ; } catch ( UnsupportedEncodingException e ) { LOG . error ( e . getMessage ( ) ) ; } return "" ; }
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 ( ) ) ; topicToSchemaMap . put ( topic , schema ) ; if ( "*" . equals ( topic ) ) { schemaForAlltopic = schema ; } } }
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 . put ( key . substring ( prefix . length ( ) + 1 ) , value ) ; } return 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 . getName ( ) ) ) ; if ( mConfig . getStatsdDogstatdsTagsEnabled ( ) ) { String metricName = ( String ) stat . get ( Stat . STAT_KEYS . METRIC . getName ( ) ) ; String [ ] tagArray = new String [ tags . size ( ) ] ; int i = 0 ; for ( Map . Entry < String , String > e : tags . entrySet ( ) ) { tagArray [ i ++ ] = e . getKey ( ) + ':' + e . getValue ( ) ; } mStatsDClient . recordGaugeValue ( metricName , value , tagArray ) ; } else { StringBuilder builder = new StringBuilder ( ) ; if ( mConfig . getStatsDPrefixWithConsumerGroup ( ) ) { builder . append ( tags . get ( Stat . STAT_KEYS . GROUP . getName ( ) ) ) . append ( PERIOD ) ; } String metricName = builder . append ( ( String ) stat . get ( Stat . STAT_KEYS . METRIC . getName ( ) ) ) . append ( PERIOD ) . append ( tags . get ( Stat . STAT_KEYS . TOPIC . getName ( ) ) ) . append ( PERIOD ) . append ( tags . get ( Stat . STAT_KEYS . PARTITION . getName ( ) ) ) . toString ( ) ; mStatsDClient . recordGaugeValue ( metricName , value ) ; } } }
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 . getTopicPartitions ( ) ) ; } } return tps ; }
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 TopicPartitionGroup ( path . getTopic ( ) , path . getKafkaPartitions ( ) ) ; HashSet < LogFilePath > files = mFiles . get ( topicPartition ) ; if ( files == null ) { files = new HashSet < LogFilePath > ( ) ; mFiles . put ( topicPartition , files ) ; } if ( ! files . contains ( path ) ) { files . add ( path ) ; } writer = ReflectionUtil . createFileWriter ( mConfig . getFileReaderWriterFactory ( ) , path , codec , mConfig ) ; mWriters . put ( path , writer ) ; mCreationTimes . put ( path , System . currentTimeMillis ( ) / 1000L ) ; LOG . debug ( "created writer for path {}" , path . getLogFilePath ( ) ) ; LOG . debug ( "Register deleteOnExit for path {}" , path . getLogFilePath ( ) ) ; FileUtil . deleteOnExit ( path . getLogFileParentDir ( ) ) ; FileUtil . deleteOnExit ( path . getLogFileDir ( ) ) ; FileUtil . deleteOnExit ( path . getLogFilePath ( ) ) ; FileUtil . deleteOnExit ( path . getLogFileCrcPath ( ) ) ; } return writer ; }
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 ( topicPartition ) ; StatsUtil . clearLabel ( "secor.size." + topicPartition . getTopic ( ) + "." + topicPartition . getPartitions ( ) [ 0 ] ) ; StatsUtil . clearLabel ( "secor.modification_age_sec." + topicPartition . getTopic ( ) + "." + topicPartition . getPartitions ( ) [ 0 ] ) ; } deleteWriter ( path ) ; FileUtil . delete ( path . getLogFilePath ( ) ) ; FileUtil . delete ( path . getLogFileCrcPath ( ) ) ; }
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 ( ) ; mWriters . remove ( path ) ; mCreationTimes . remove ( path ) ; } }
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 ) . unregisterReceiver ( mProgressBroadcastReceiver ) ; mProgressBroadcastReceiver = null ; } } }
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 ( mLogBroadcastReceiver ) ; mLogBroadcastReceiver = null ; } } }
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 ( characteristic , data , size ) ; if ( crc32 != null ) crc32 . update ( data , 0 , size ) ; } } catch ( final IOException e ) { loge ( "Error while reading Init packet file" , e ) ; throw new DfuException ( "Error while reading Init packet file" , DfuBaseService . ERROR_FILE_ERROR ) ; } }
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 ; final byte [ ] buffer = mBuffer ; try { final int size = mFirmwareStream . read ( buffer ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_VERBOSE , "Sending firmware to characteristic " + packetCharacteristic . getUuid ( ) + "..." ) ; writePacket ( mGatt , packetCharacteristic , buffer , size ) ; } catch ( final HexFileValidationException e ) { throw new DfuException ( "HEX file not valid" , DfuBaseService . ERROR_FILE_INVALID ) ; } catch ( final IOException e ) { throw new DfuException ( "Error while reading file" , DfuBaseService . ERROR_FILE_IO_EXCEPTION ) ; } try { synchronized ( mLock ) { while ( ( mFirmwareUploadInProgress && mReceivedData == null && mConnected && mError == 0 ) || mPaused ) mLock . wait ( ) ; } } catch ( final InterruptedException e ) { loge ( "Sleeping interrupted" , e ) ; } if ( ! mConnected ) throw new DeviceDisconnectedException ( "Uploading Firmware Image failed: device disconnected" ) ; if ( mError != 0 ) throw new DfuException ( "Uploading Firmware Image failed" , mError ) ; }
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 , size ) ; } characteristic . setWriteType ( BluetoothGattCharacteristic . WRITE_TYPE_NO_RESPONSE ) ; characteristic . setValue ( locBuffer ) ; gatt . writeCharacteristic ( characteristic ) ; }
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 new UploadAbortedException ( ) ; if ( characteristic == null ) return 0 ; mReceivedData = null ; mError = 0 ; logi ( "Reading DFU version number..." ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_VERBOSE , "Reading DFU version number..." ) ; characteristic . setValue ( ( byte [ ] ) null ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_DEBUG , "gatt.readCharacteristic(" + characteristic . getUuid ( ) + ")" ) ; gatt . readCharacteristic ( characteristic ) ; try { synchronized ( mLock ) { while ( ( ( ! mRequestCompleted || characteristic . getValue ( ) == null ) && mConnected && mError == 0 && ! mAborted ) || mPaused ) { mRequestCompleted = false ; mLock . wait ( ) ; } } } catch ( final InterruptedException e ) { loge ( "Sleeping interrupted" , e ) ; } if ( ! mConnected ) throw new DeviceDisconnectedException ( "Unable to read version number: device disconnected" ) ; if ( mError != 0 ) throw new DfuException ( "Unable to read version number" , mError ) ; return characteristic . getIntValue ( BluetoothGattCharacteristic . FORMAT_UINT16 , 0 ) ; }
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 ) ; } 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 .
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 = false ; try { final Method removeBond = device . getClass ( ) . getMethod ( "removeBond" ) ; mRequestCompleted = false ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_DEBUG , "gatt.getDevice().removeBond() (hidden)" ) ; result = ( Boolean ) removeBond . invoke ( device ) ; 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 .
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 . LOG_LEVEL_VERBOSE , "Requesting new MTU..." ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_DEBUG , "gatt.requestMtu(" + mtu + ")" ) ; if ( ! mGatt . requestMtu ( mtu ) ) return ; 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 .
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 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 .
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 . 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 ) ; 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 .
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 . putExtra ( DfuBaseService . EXTRA_DEVICE_ADDRESS , deviceAddress ) ; intent . putExtra ( DfuBaseService . EXTRA_DEVICE_NAME , deviceName ) ; intent . putExtra ( DfuBaseService . EXTRA_DISABLE_NOTIFICATION , disableNotification ) ; intent . putExtra ( DfuBaseService . EXTRA_FOREGROUND_SERVICE , startAsForegroundService ) ; intent . putExtra ( DfuBaseService . EXTRA_FILE_MIME_TYPE , mimeType ) ; intent . putExtra ( DfuBaseService . EXTRA_FILE_TYPE , fileType ) ; intent . putExtra ( DfuBaseService . EXTRA_FILE_URI , fileUri ) ; intent . putExtra ( DfuBaseService . EXTRA_FILE_PATH , filePath ) ; intent . putExtra ( DfuBaseService . EXTRA_FILE_RES_ID , fileResId ) ; intent . putExtra ( DfuBaseService . EXTRA_INIT_FILE_URI , initFileUri ) ; intent . putExtra ( DfuBaseService . EXTRA_INIT_FILE_PATH , initFilePath ) ; intent . putExtra ( DfuBaseService . EXTRA_INIT_FILE_RES_ID , initFileResId ) ; intent . putExtra ( DfuBaseService . EXTRA_KEEP_BOND , keepBond ) ; intent . putExtra ( DfuBaseService . EXTRA_RESTORE_BOND , restoreBond ) ; intent . putExtra ( DfuBaseService . EXTRA_FORCE_DFU , forceDfu ) ; intent . putExtra ( DfuBaseService . EXTRA_DISABLE_RESUME , disableResume ) ; intent . putExtra ( DfuBaseService . EXTRA_MAX_DFU_ATTEMPTS , numberOfRetries ) ; intent . putExtra ( DfuBaseService . EXTRA_MBR_SIZE , mbrSize ) ; if ( mtu > 0 ) intent . putExtra ( DfuBaseService . EXTRA_MTU , mtu ) ; intent . putExtra ( DfuBaseService . EXTRA_CURRENT_MTU , currentMtu ) ; intent . putExtra ( DfuBaseService . EXTRA_UNSAFE_EXPERIMENTAL_BUTTONLESS_DFU , enableUnsafeExperimentalButtonlessDfu ) ; if ( packetReceiptNotificationsEnabled != null ) { intent . putExtra ( DfuBaseService . EXTRA_PACKET_RECEIPT_NOTIFICATIONS_ENABLED , packetReceiptNotificationsEnabled ) ; intent . putExtra ( DfuBaseService . EXTRA_PACKET_RECEIPT_NOTIFICATIONS_VALUE , numberOfPackets ) ; } else { } if ( legacyDfuUuids != null ) intent . putExtra ( DfuBaseService . EXTRA_CUSTOM_UUIDS_FOR_LEGACY_DFU , legacyDfuUuids ) ; if ( secureDfuUuids != null ) intent . putExtra ( DfuBaseService . EXTRA_CUSTOM_UUIDS_FOR_SECURE_DFU , secureDfuUuids ) ; if ( experimentalButtonlessDfuUuids != null ) intent . putExtra ( DfuBaseService . EXTRA_CUSTOM_UUIDS_FOR_EXPERIMENTAL_BUTTONLESS_DFU , experimentalButtonlessDfuUuids ) ; if ( buttonlessDfuWithoutBondSharingUuids != null ) intent . putExtra ( DfuBaseService . EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITHOUT_BOND_SHARING , buttonlessDfuWithoutBondSharingUuids ) ; if ( buttonlessDfuWithBondSharingUuids != null ) intent . putExtra ( DfuBaseService . EXTRA_CUSTOM_UUIDS_FOR_BUTTONLESS_DFU_WITH_BOND_SHARING , buttonlessDfuWithBondSharingUuids ) ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . O && startAsForegroundService ) { context . startForegroundService ( intent ) ; } else { context . startService ( intent ) ; } return new DfuServiceController ( context ) ; }
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 [ ] 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 .
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 ] = ( 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 .
25,350
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 .
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_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 .
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 . 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 .
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 ) ; 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 ) ; 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 .
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" ) ; 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 .
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 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 .
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 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 ) ; 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 ) ; final PendingIntent pendingIntent = PendingIntent . getActivity ( this , 0 , intent , PendingIntent . FLAG_UPDATE_CURRENT ) ; builder . setContentIntent ( pendingIntent ) ; 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 .
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 = bluetoothManager . getAdapter ( ) ; if ( mBluetoothAdapter == null ) { loge ( "Unable to obtain a BluetoothAdapter." ) ; return false ; } return true ; }
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 += 4 ; type = readByte ( in ) ; pos += 2 ; switch ( type ) { case 0x00 : if ( lastAddress + offset < MBRSize ) { type = - 1 ; pos += skip ( in , lineSize * 2 + 2 ) ; } break ; case 0x01 : pos = - 1 ; return 0 ; case 0x02 : { final int address = readAddress ( in ) << 4 ; pos += 4 ; if ( bytesRead > 0 && ( address >> 16 ) != ( lastAddress >> 16 ) + 1 ) return 0 ; lastAddress = address ; pos += skip ( in , 2 ) ; break ; } case 0x04 : { final int address = readAddress ( in ) ; pos += 4 ; if ( bytesRead > 0 && address != ( lastAddress >> 16 ) + 1 ) return 0 ; lastAddress = address << 16 ; pos += skip ( in , 2 ) ; break ; } default : final long toBeSkipped = lineSize * 2 + 2 ; pos += skip ( in , toBeSkipped ) ; break ; } } while ( type != 0 ) ; for ( int i = 0 ; i < localBuf . length && i < lineSize ; ++ i ) { b = readByte ( in ) ; pos += 2 ; localBuf [ i ] = ( byte ) b ; } pos += skip ( in , 2 ) ; localPos = 0 ; return lineSize ; }
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 . PROGRESS_DISCONNECTING ) ; logi ( "Sending Reset command (Op Code = 6)" ) ; writeOpCode ( mControlPointCharacteristic , OP_CODE_RESET ) ; mService . sendLogBroadcast ( DfuBaseService . LOG_LEVEL_APPLICATION , "Reset request sent" ) ; 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 ) ; 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 .
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" , 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 .
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 ( "result" ) ; }
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 '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 .
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 processCallbackResponse ( resp ) ; } 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 .
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 = 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 .
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 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 ( traceEnabled ) { startPipeErrorStreamThread ( ) ; } } catch ( IOException e ) { throw new JsiiException ( e ) ; } }
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_VERSION , runtimeVersion ) ; }
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 . 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 .
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 ( 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 .
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 ( 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 .
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 . newInstance ( ) ; } catch ( IllegalAccessException | InstantiationException e ) { throw new JsiiException ( e ) ; } if ( this . loadedModules . containsKey ( module . getModuleName ( ) ) ) { return ; } for ( Class < ? extends JsiiModule > dep : module . getDependencies ( ) ) { loadModule ( dep ) ; } this . getClient ( ) . loadModule ( module ) ; this . loadedModules . put ( module . getModuleName ( ) , module ) ; }
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 . fromObjId ( objid ) ; } } return createNewObject ( nativeObject ) ; }
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 ) ; 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 .
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 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 .
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 ( invokeMethod ( obj , getter ) ) ; } catch ( NoSuchMethodException e ) { throw new JsiiException ( e ) ; } }
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 . 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 .