idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
10,300
public void setArduinoEnabled ( boolean enable ) { Buffer buffer = new Buffer ( ) ; buffer . writeByte ( enable ? 1 : 0 ) ; sendMessage ( BeanMessageID . CC_POWER_ARDUINO , buffer ) ; }
Enable or disable the Arduino .
10,301
public void readArduinoPowerState ( final Callback < Boolean > callback ) { addCallback ( BeanMessageID . CC_GET_AR_POWER , callback ) ; sendMessageWithoutPayload ( BeanMessageID . CC_GET_AR_POWER ) ; }
Read the Arduino power state .
10,302
public void readBatteryLevel ( final Callback < BatteryLevel > callback ) { gattClient . getBatteryProfile ( ) . getBatteryLevel ( new BatteryLevelCallback ( ) { public void onBatteryLevel ( int percentage ) { callback . onResult ( new BatteryLevel ( percentage ) ) ; } } ) ; }
Read the battery level .
10,303
public OADProfile . OADApproval programWithFirmware ( FirmwareBundle bundle , OADProfile . OADListener listener ) { return gattClient . getOADProfile ( ) . programWithFirmware ( bundle , listener ) ; }
Programs the Bean with new firmware images .
10,304
public boolean isTargetClassAndCurrentJvmTargetClassMatch ( ) { Class < ? > targetClassOnThisJVM ; try { targetClassOnThisJVM = Class . forName ( targetClassName ) ; } catch ( ClassNotFoundException e ) { log . error ( "target class " + targetClassName + " does not exist on this JVM." ) ; return false ; } ObjectStreamClass osc = ObjectStreamClass . lookup ( targetClassOnThisJVM ) ; if ( osc == null ) { return false ; } return targetClassSerialVersionUID == osc . getSerialVersionUID ( ) ; }
Compare targetClassSerialVersionUID and current JVM s targetClass serialVersionUID . If they are same return true else return false .
10,305
public static boolean checkIfClassVersionApplicable ( Object cacheEntry , boolean useStructuredCache ) { if ( ! useStructuredCache && cacheEntry instanceof CacheEntry ) { return true ; } if ( useStructuredCache && cacheEntry instanceof Map ) { return true ; } return false ; }
Check if class version comparable .
10,306
private void refreshDeviceCache ( BluetoothGatt gatt ) { try { BluetoothGatt localBluetoothGatt = gatt ; Method localMethod = localBluetoothGatt . getClass ( ) . getMethod ( "refresh" , new Class [ 0 ] ) ; if ( localMethod != null ) { localMethod . invoke ( localBluetoothGatt , new Object [ 0 ] ) ; } else { Log . e ( TAG , "Couldn't find local method: refresh" ) ; } } catch ( Exception localException ) { Log . e ( TAG , "An exception occurred while refreshing device" ) ; } }
Attempt to invalidate Androids internal GATT table cache
10,307
protected ConnectionFactoryBuilder createConnectionFactoryBuilder ( OverridableReadOnlyProperties properties ) { ConnectionFactoryBuilder builder = new ConnectionFactoryBuilder ( ) ; builder . setProtocol ( ConnectionFactoryBuilder . Protocol . BINARY ) ; builder . setLocatorType ( ConnectionFactoryBuilder . Locator . CONSISTENT ) ; builder . setUseNagleAlgorithm ( false ) ; builder . setFailureMode ( FailureMode . Redistribute ) ; String hashAlgorithmProeprty = properties . getRequiredProperty ( HASH_ALGORITHM_PROPERTY_KEY ) ; builder . setHashAlg ( DefaultHashAlgorithm . valueOf ( hashAlgorithmProeprty ) ) ; String operationTimeoutProperty = properties . getRequiredProperty ( OPERATION_TIMEOUT_MILLIS_PROPERTY_KEY ) ; builder . setOpTimeout ( Long . parseLong ( operationTimeoutProperty ) ) ; String transcoderClassProperty = properties . getRequiredProperty ( TRANSCODER_PROPERTY_KEY ) ; builder . setTranscoder ( createTranscoder ( properties , transcoderClassProperty ) ) ; authenticate ( builder , properties ) ; return builder ; }
creating ConnectionFactoryBuilder object . Override thid method if you need .
10,308
String getNamespacedKey ( CacheNamespace cacheNamespace , String key ) { String namespaceIndicator = getNamespaceIndicator ( cacheNamespace ) ; if ( cacheNamespace . isNamespaceExpirationRequired ( ) == false ) { return namespaceIndicator + ":" + key ; } String namespaceIndicatorKey = namespaceIndicator + NAMESPACE_NAME_SQUENCE_SEPARATOR ; long namespaceSquence = memcachedClient . incr ( namespaceIndicatorKey , 0L , System . currentTimeMillis ( ) , DEFAULT_NAMESPACE_SEQUENCE_EXPIRY_SECONDS ) ; return namespaceIndicatorKey + namespaceSquence + ":" + key ; }
Return cache namespace decorated key .
10,309
private int uint16FromData ( int offset ) { return twoBytesToInt ( Arrays . copyOfRange ( data ( ) , offset , offset + 2 ) , Constants . CC2540_BYTE_ORDER ) ; }
Parse a little - endian UInt16 from the data at the given offset .
10,310
private boolean scan ( ) { if ( btAdapter . startLeScan ( mCallback ) ) { mScanning = true ; Log . i ( TAG , "BLE scan started successfully" ) ; if ( mHandler . postDelayed ( scanTimeoutCallback , scanTimeout * 1000 ) ) { Log . i ( TAG , String . format ( "Cancelling discovery in %d seconds" , scanTimeout ) ) ; } else { Log . e ( TAG , "Failed to schedule discovery complete callback!" ) ; } return true ; } else { Log . i ( TAG , "BLE scan failed!" ) ; return false ; } }
Helper function for starting scan and scheduling the scan timeout
10,311
public void setScanTimeout ( int timeout ) { scanTimeout = timeout ; Log . i ( TAG , String . format ( "New scan timeout set: %d seconds" , scanTimeout ) ) ; }
Set the desired scan timeout in seconds
10,312
public boolean startDiscovery ( ) { if ( mScanning ) { Log . e ( TAG , "Already discovering" ) ; return true ; } if ( mListener == null ) { throw new NullPointerException ( "Listener cannot be null" ) ; } return scan ( ) ; }
Start discovering nearby Beans using an existing BeanListener .
10,313
public void cancelDiscovery ( ) { mHandler . removeCallbacks ( scanTimeoutCallback ) ; if ( mScanning ) { Log . i ( TAG , "Cancelling discovery process" ) ; BluetoothAdapter . getDefaultAdapter ( ) . stopLeScan ( mCallback ) ; mScanning = false ; boolean success = mHandler . post ( new Runnable ( ) { public void run ( ) { mListener . onDiscoveryComplete ( ) ; } } ) ; if ( ! success ) { Log . e ( TAG , "Failed to post Discovery Complete callback!" ) ; } } else { Log . e ( TAG , "No discovery in progress" ) ; } }
Cancel a scan currently in progress . If no scan is in progress this method does nothing .
10,314
public static byte [ ] decompressSafe ( final byte [ ] src , int maxDecompressedSize ) { if ( src == null ) { throw new IllegalArgumentException ( "src must not be null." ) ; } if ( maxDecompressedSize <= 0 ) { throw new IllegalArgumentException ( "maxDecompressedSize must be larger than 0 but " + maxDecompressedSize ) ; } LZ4SafeDecompressor decompressor = factory . safeDecompressor ( ) ; return decompressor . decompress ( src , maxDecompressedSize ) ; }
When the exact decompressed size is unknown . Decompress data size cannot be larger then maxDecompressedSize
10,315
public static byte [ ] decompressFast ( byte [ ] src , int srcOffset , int exactDecompressedSize ) { if ( src == null ) { throw new IllegalArgumentException ( "src must not be null." ) ; } if ( srcOffset < 0 ) { throw new IllegalArgumentException ( "srcOffset must equal to or larger than 0 but " + srcOffset ) ; } if ( exactDecompressedSize < 0 ) { throw new IllegalArgumentException ( "exactDecompressedSize must equal to or larger than 0 but " + exactDecompressedSize ) ; } LZ4FastDecompressor decompressor = factory . fastDecompressor ( ) ; return decompressor . decompress ( src , srcOffset , exactDecompressedSize ) ; }
When the exact decompressed size is known use this method to decompress . It s faster .
10,316
public static SketchHex create ( String sketchName , String hexString ) throws HexParsingException { if ( sketchName . length ( ) > Constants . MAX_SKETCH_NAME_LENGTH ) { sketchName = sketchName . substring ( 0 , Constants . MAX_SKETCH_NAME_LENGTH ) ; } List < Line > lines = parseHexStringToLines ( hexString ) ; byte [ ] bytes = convertLinesToBytes ( lines ) ; return new AutoParcel_SketchHex ( sketchName , bytes ) ; }
Initialize a SketchHex object with a string of Intel Hex data .
10,317
public static < T extends Chunkable > byte [ ] bytesFrom ( T chunkable , int offset , int length ) { byte [ ] data = chunkable . getChunkableData ( ) ; if ( offset + length > data . length ) { return Arrays . copyOfRange ( data , offset , data . length ) ; } else { return Arrays . copyOfRange ( data , offset , offset + length ) ; } }
Retrieve a number of raw bytes at an offset .
10,318
public static < T extends Chunkable > byte [ ] chunkFrom ( T chunkable , int chunkLength , int chunkNum ) { int start = chunkNum * chunkLength ; return bytesFrom ( chunkable , start , chunkLength ) ; }
Retrieve a chunk of raw bytes . Chunks are created by slicing the array at even intervals . The final chunk may be shorter than the other chunks if it s been truncated .
10,319
public static < T extends Chunkable > int chunkCountFrom ( T chunkable , int chunkLength ) { byte [ ] data = chunkable . getChunkableData ( ) ; return ( int ) Math . ceil ( data . length * 1.0 / chunkLength ) ; }
Retrieve the count of chunks for a given chunk length .
10,320
public static < T extends Chunkable > List < byte [ ] > chunksFrom ( T chunkable , int chunkLength ) { List < byte [ ] > chunks = new ArrayList < > ( ) ; int chunkCount = chunkCountFrom ( chunkable , chunkLength ) ; for ( int i = 0 ; i < chunkCount ; i ++ ) { byte [ ] chunk = chunkFrom ( chunkable , chunkLength , i ) ; chunks . add ( chunk ) ; } return chunks ; }
Retrieve all chunks for a given chunk length . The final chunk may be shorter than the other chunks if it s been truncated .
10,321
public static int twoBytesToInt ( byte [ ] bytes , ByteOrder order ) { if ( order == ByteOrder . BIG_ENDIAN ) { return bytesToInt ( bytes [ 0 ] , bytes [ 1 ] ) ; } else if ( order == ByteOrder . LITTLE_ENDIAN ) { return bytesToInt ( bytes [ 1 ] , bytes [ 0 ] ) ; } else { throw new IllegalArgumentException ( "ByteOrder must be BIG_ENDIAN or LITTLE_ENDIAN" ) ; } }
Convert an array of two unsigned bytes with the given byte order to one signed int .
10,322
public static byte [ ] intArrayToByteArray ( int [ ] intArray ) { byte [ ] byteArray = new byte [ intArray . length ] ; for ( int i = 0 ; i < intArray . length ; i ++ ) { byteArray [ i ] = intToByte ( intArray [ i ] ) ; } return byteArray ; }
Convert an array of ints to an array of unsigned bytes . This is useful when you want to construct a literal array of unsigned bytes with values greater than 127 . Only the lowest 8 bits of the int values are used .
10,323
public static byte [ ] intToUInt32 ( int i , ByteOrder endian ) { int truncated = ( int ) ( ( long ) i ) ; return ByteBuffer . allocate ( 4 ) . order ( endian ) . putInt ( truncated ) . array ( ) ; }
Convert an int to a four - byte array of its representation as an unsigned byte .
10,324
public static GattSerialMessage fromPayload ( byte [ ] payload ) { Buffer buffer = new Buffer ( ) ; byte [ ] header = new byte [ 2 ] ; header [ 0 ] = ( byte ) ( payload . length & 0xff ) ; header [ 1 ] = 0 ; int crc = computeCRC16 ( header , 0 , header . length ) ; crc = computeCRC16 ( crc , payload , 0 , payload . length ) ; buffer . write ( header ) ; buffer . write ( payload ) ; buffer . writeByte ( crc & 0xff ) ; buffer . writeByte ( ( crc >> 8 ) & 0xff ) ; return new GattSerialMessage ( buffer ) ; }
Create a GattSerialMessage from a byte array payload
10,325
public static int bytesToInt ( byte [ ] bytes ) { int value = ( ( int ) bytes [ 0 ] & 0xFF ) << 24 ; value += ( ( int ) bytes [ 1 ] & 0xFF ) << 16 ; value += ( ( int ) bytes [ 2 ] & 0xFF ) << 8 ; value += ( int ) bytes [ 3 ] & 0xFF ; return value ; }
4 bytes array to int
10,326
public void send ( byte [ ] data , int id ) { boolean isFirstPacket = ( packets . size ( ) == 0 ) ; packets . add ( data ) ; ids . add ( id ) ; if ( isFirstPacket ) { scheduleSendTask ( true ) ; } Log . d ( TAG , "Added packet " + id + " to buffer; " + packets . size ( ) + " packets in buffer" ) ; }
Add a packet to the buffer to be sent . If no other packets are in the buffer it will be sent immediately .
10,327
private void scheduleSendTask ( boolean runNow ) { TimerTask task = new TimerTask ( ) { public void run ( ) { byte [ ] packet ; try { packet = packets . get ( 0 ) ; } catch ( IndexOutOfBoundsException e ) { return ; } charc . setValue ( packet ) ; boolean result = gattClient . writeCharacteristic ( charc ) ; if ( result ) { packets . remove ( 0 ) ; int id = ids . remove ( 0 ) ; retries = 0 ; if ( onPacketSent != null ) { onPacketSent . onResult ( id ) ; } Log . d ( TAG , "Packet " + id + " sent after " + retries + " retries" ) ; } else { retries ++ ; } scheduleSendTask ( false ) ; } } ; if ( runNow ) { task . run ( ) ; } else { sendTimer . schedule ( task , SEND_INTERVAL ) ; } }
Schedules the send task to run either immediately or at SEND_INTERVAL .
10,328
public void setSbbContext ( SbbContext context ) { sbbContext = ( SbbContextExt ) context ; sipActivityContextInterfaceFactory = ( SipActivityContextInterfaceFactory ) sbbContext . getActivityContextInterfaceFactory ( sipRATypeID ) ; sleeSipProvider = ( SleeSipProvider ) sbbContext . getResourceAdaptorInterface ( sipRATypeID , sipRALink ) ; addressFactory = sleeSipProvider . getAddressFactory ( ) ; headerFactory = sleeSipProvider . getHeaderFactory ( ) ; messageFactory = sleeSipProvider . getMessageFactory ( ) ; timerFacility = sbbContext . getTimerFacility ( ) ; }
SbbObject lifecycle methods
10,329
private ContactHeader getContactHeader ( ) throws ParseException { if ( contactHeader == null ) { final ListeningPoint listeningPoint = sleeSipProvider . getListeningPoint ( "udp" ) ; final javax . sip . address . SipURI sipURI = addressFactory . createSipURI ( null , listeningPoint . getIPAddress ( ) ) ; sipURI . setPort ( listeningPoint . getPort ( ) ) ; sipURI . setTransportParam ( listeningPoint . getTransport ( ) ) ; contactHeader = headerFactory . createContactHeader ( addressFactory . createAddress ( sipURI ) ) ; } return contactHeader ; }
some helper methods to deal with lazy init of static fields
10,330
public void onInviteEvent ( javax . sip . RequestEvent requestEvent , ActivityContextInterface aci ) { final ServerTransaction serverTransaction = requestEvent . getServerTransaction ( ) ; try { Response response = messageFactory . createResponse ( Response . TRYING , requestEvent . getRequest ( ) ) ; serverTransaction . sendResponse ( response ) ; final SbbLocalObject sbbLocalObject = this . sbbContext . getSbbLocalObject ( ) ; response = messageFactory . createResponse ( Response . RINGING , requestEvent . getRequest ( ) ) ; serverTransaction . sendResponse ( response ) ; setFinalReplySent ( false ) ; timerFacility . setTimer ( aci , null , System . currentTimeMillis ( ) + 1000L , getTimerOptions ( ) ) ; } catch ( Exception e ) { getTracer ( ) . severe ( "failure while processing initial invite" , e ) ; } }
Event handler method for the invite SIP message .
10,331
public void onTimerEvent ( TimerEvent event , ActivityContextInterface aci ) { if ( getFinalReplySent ( ) ) { aci . detach ( sbbContext . getSbbLocalObject ( ) ) ; final DialogActivity dialog = ( DialogActivity ) aci . getActivity ( ) ; try { dialog . sendRequest ( dialog . createRequest ( Request . BYE ) ) ; } catch ( Exception e ) { getTracer ( ) . severe ( "failure while processing timer event" , e ) ; } } else { aci . detach ( sbbContext . getSbbLocalObject ( ) ) ; final ServerTransaction serverTransaction = ( ServerTransaction ) aci . getActivity ( ) ; try { final DialogActivity dialog = ( DialogActivity ) sleeSipProvider . getNewDialog ( serverTransaction ) ; final ActivityContextInterfaceExt dialogAci = ( ActivityContextInterfaceExt ) sipActivityContextInterfaceFactory . getActivityContextInterface ( dialog ) ; dialogAci . attach ( sbbContext . getSbbLocalObject ( ) ) ; Response response = messageFactory . createResponse ( Response . OK , serverTransaction . getRequest ( ) ) ; response . addHeader ( getContactHeader ( ) ) ; serverTransaction . sendResponse ( response ) ; setFinalReplySent ( true ) ; timerFacility . setTimer ( dialogAci , null , System . currentTimeMillis ( ) + 60000L , getTimerOptions ( ) ) ; } catch ( Exception e ) { getTracer ( ) . severe ( "failure while sending 200 OK response" , e ) ; } } }
Event handler method for the timer event .
10,332
public void getBindingsResult ( int resultCode , List < RegistrationBinding > bindings ) { ServerTransaction serverTransaction = getRegisterTransactionToReply ( ) ; if ( serverTransaction == null ) { tracer . warning ( "failed to find SIP server tx to send response" ) ; return ; } try { if ( resultCode < 300 ) { sendRegisterSuccessResponse ( resultCode , bindings , serverTransaction ) ; } else { sendErrorResponse ( resultCode , serverTransaction ) ; } } catch ( Exception e ) { tracer . severe ( "failed to send SIP response" , e ) ; } }
call backs from data source child sbb
10,333
private void cancelTimers ( List < org . mobicents . slee . example . sjr . data . RegistrationBinding > removedContacts ) { for ( RegistrationBinding binding : removedContacts ) { ActivityContextInterfaceExt aci = ( ActivityContextInterfaceExt ) this . activityContextNamingFacility . lookup ( getACIName ( binding . getContactAddress ( ) , binding . getSipAddress ( ) ) ) ; if ( aci != null ) { ( ( NullActivity ) aci . getActivity ( ) ) . endActivity ( ) ; } } }
Simple method to cancel pending timers for contacts that have been removed
10,334
private void updateTimers ( List < org . mobicents . slee . example . sjr . data . RegistrationBinding > contacts ) { String bindingAciName = null ; ActivityContextInterface aci = null ; for ( RegistrationBinding binding : contacts ) { bindingAciName = getACIName ( binding . getContactAddress ( ) , binding . getSipAddress ( ) ) ; aci = this . activityContextNamingFacility . lookup ( bindingAciName ) ; if ( aci != null ) { for ( TimerID timerID : ( ( ActivityContextInterfaceExt ) aci ) . getTimers ( ) ) { this . timerFacility . cancelTimer ( timerID ) ; } } else { NullActivity nullActivity = this . nullActivityFactory . createNullActivity ( ) ; aci = this . nullActivityContextInterfaceFactory . getActivityContextInterface ( nullActivity ) ; try { this . activityContextNamingFacility . bind ( aci , bindingAciName ) ; } catch ( Exception e ) { this . tracer . severe ( "Failed to bind aci name " + bindingAciName , e ) ; } SbbActivityContextInterface rgAci = asSbbActivityContextInterface ( aci ) ; rgAci . setData ( new RegistrationBindingData ( ) . setAddress ( binding . getSipAddress ( ) ) . setContact ( binding . getContactAddress ( ) ) ) ; } timerFacility . setTimer ( aci , null , System . currentTimeMillis ( ) + ( ( binding . getExpires ( ) + 1 ) * 1000 ) , defaultTimerOptions ) ; } }
Simple method to update timers for passed contacts . If timer exists it will be reset to new timeout . If it does not exist it will be create along with NullActivity .
10,335
public DialogWrapper getDialogWrapper ( Dialog d ) { if ( d == null ) { return null ; } DialogWrapper dw = null ; DialogWrapperAppData dwad = ( DialogWrapperAppData ) d . getApplicationData ( ) ; if ( dwad != null ) { dw = dwad . getDialogWrapper ( d , this ) ; } return dw ; }
Retrieves the wrapper associated with a dialog recreating if needed in a cluster env .
10,336
public TransactionWrapper getTransactionWrapper ( Transaction t ) { if ( t == null ) { return null ; } final TransactionWrapperAppData twad = ( TransactionWrapperAppData ) t . getApplicationData ( ) ; return twad != null ? twad . getTransactionWrapper ( t , this ) : null ; }
Retrieves the wrapper associated with a tx recreating if needed in a cluster env .
10,337
public static List < RouteHeader > getRouteList ( Response response , HeaderFactory headerFactory ) throws ParseException { final ArrayList < RouteHeader > routeList = new ArrayList < RouteHeader > ( ) ; final ListIterator < ? > rrLit = response . getHeaders ( RecordRouteHeader . NAME ) ; while ( rrLit . hasNext ( ) ) { final RecordRouteHeader rrh = ( RecordRouteHeader ) rrLit . next ( ) ; final RouteHeader rh = headerFactory . createRouteHeader ( rrh . getAddress ( ) ) ; final Iterator < ? > pIt = rrh . getParameterNames ( ) ; while ( pIt . hasNext ( ) ) { final String pName = ( String ) pIt . next ( ) ; rh . setParameter ( pName , rrh . getParameter ( pName ) ) ; } routeList . add ( 0 , rh ) ; } return routeList ; }
Generates route list the same way dialog does .
10,338
public static URI getRequestUri ( Response response , AddressFactory addressFactory ) throws ParseException { final ContactHeader contact = ( ( ContactHeader ) response . getHeader ( ContactHeader . NAME ) ) ; return ( contact != null ) ? ( URI ) contact . getAddress ( ) . getURI ( ) . clone ( ) : null ; }
Forges Request - URI using contact and To name par to address URI this is required on dialog fork this is how target is determined
10,339
public void onMessageEvent ( javax . sip . RequestEvent event , ActivityContextInterface aci ) { final Request request = event . getRequest ( ) ; try { final String body = new String ( request . getRawContent ( ) ) ; final int firstTokenStart = body . indexOf ( FIRST_TOKEN ) ; final int timerDurationStart = firstTokenStart + FIRST_TOKEN_LENGTH ; final int middleTokenStart = body . indexOf ( MIDDLE_TOKEN , timerDurationStart ) ; final int bodyMessageStart = middleTokenStart + MIDDLE_TOKEN_LENGTH ; final int lastTokenStart = body . indexOf ( LAST_TOKEN , bodyMessageStart ) ; if ( firstTokenStart > - 1 && middleTokenStart > - 1 && lastTokenStart > - 1 ) { final int timerDuration = Integer . parseInt ( body . substring ( timerDurationStart , middleTokenStart ) ) ; final ActivityContextInterface timerACI = this . nullACIFactory . getActivityContextInterface ( this . nullActivityFactory . createNullActivity ( ) ) ; timerACI . attach ( sbbContext . getSbbLocalObject ( ) ) ; this . timerFacility . setTimer ( timerACI , null , System . currentTimeMillis ( ) + ( timerDuration * 1000 ) , new TimerOptions ( ) ) ; final String bodyMessage = body . substring ( bodyMessageStart , lastTokenStart ) ; setBody ( bodyMessage ) ; setCallId ( ( CallIdHeader ) request . getHeader ( CallIdHeader . NAME ) ) ; final FromHeader fromHeader = ( FromHeader ) request . getHeader ( FromHeader . NAME ) ; if ( tracer . isInfoEnabled ( ) ) { tracer . info ( "Received a valid message from " + fromHeader . getAddress ( ) + " requesting a reply containing '" + bodyMessage + "' after " + timerDuration + "s" ) ; } setSender ( fromHeader . getAddress ( ) ) ; sendResponse ( event , Response . OK ) ; } else { tracer . warning ( "Invalid msg '" + body + "' received" ) ; sendResponse ( event , Response . BAD_REQUEST ) ; } } catch ( Throwable e ) { tracer . severe ( "Exception while processing MESSAGE" , e ) ; try { sendResponse ( event , Response . SERVER_INTERNAL_ERROR ) ; } catch ( Exception f ) { tracer . severe ( "Exception while sending SERVER INTERNAL ERROR" , f ) ; } } }
Event handler for the SIP MESSAGE from the UA
10,340
public void onTimerEvent ( TimerEvent event , ActivityContextInterface aci ) { aci . detach ( sbbContext . getSbbLocalObject ( ) ) ; try { DataSourceChildSbbLocalInterface child = ( DataSourceChildSbbLocalInterface ) getLocationChildRelation ( ) . create ( ) ; child . getBindings ( getSender ( ) . getURI ( ) . toString ( ) ) ; } catch ( Exception e ) { tracer . severe ( "failed to create sip registrar child sbb, to lookup the sender's contacts" , e ) ; return ; } }
Event handler from the timer event which signals that a message must be sent back to the UA
10,341
public void serviceActive ( ReceivableService receivableService ) { for ( ReceivableEvent receivableEvent : receivableService . getReceivableEvents ( ) ) { Set < ServiceID > servicesReceivingEvent = eventID2serviceIDs . get ( receivableEvent . getEventType ( ) ) ; if ( servicesReceivingEvent == null ) { servicesReceivingEvent = new HashSet < ServiceID > ( ) ; Set < ServiceID > anotherSet = eventID2serviceIDs . putIfAbsent ( receivableEvent . getEventType ( ) , servicesReceivingEvent ) ; if ( anotherSet != null ) { servicesReceivingEvent = anotherSet ; } } synchronized ( servicesReceivingEvent ) { servicesReceivingEvent . add ( receivableService . getService ( ) ) ; } } }
Informs the filter that a receivable service is now active . For the events related with the service and if there are no other services bound then events of such event type should now not be filtered .
10,342
public void serviceInactive ( ReceivableService receivableService ) { for ( ReceivableEvent receivableEvent : receivableService . getReceivableEvents ( ) ) { Set < ServiceID > servicesReceivingEvent = eventID2serviceIDs . get ( receivableEvent . getEventType ( ) ) ; if ( servicesReceivingEvent != null ) { synchronized ( servicesReceivingEvent ) { servicesReceivingEvent . remove ( receivableService . getService ( ) ) ; } if ( servicesReceivingEvent . isEmpty ( ) ) { eventID2serviceIDs . remove ( receivableEvent . getEventType ( ) ) ; } } } }
Informs the filter that a receivable service is now inactive . For the events related with the service if there are no other services bound then events of such event type should be filtered
10,343
public FireableEventType getEventId ( EventLookupFacility eventLookupFacility , Request request , boolean inDialogActivity ) { final String requestMethod = request . getMethod ( ) ; if ( requestMethod . equals ( Request . CANCEL ) ) inDialogActivity = false ; FireableEventType eventID = null ; if ( inDialogActivity ) { eventID = getEventId ( eventLookupFacility , new StringBuilder ( INDIALOG_REQUEST_EVENT_PREFIX ) . append ( requestMethod ) . toString ( ) ) ; if ( eventID == null ) { eventID = getEventId ( eventLookupFacility , new StringBuilder ( INDIALOG_REQUEST_EVENT_PREFIX ) . append ( SIP_EXTENSION_REQUEST_EVENT_NAME_SUFIX ) . toString ( ) ) ; } } else { eventID = getEventId ( eventLookupFacility , new StringBuilder ( OUT_OF_DIALOG_REQUEST_EVENT_PREFIX ) . append ( requestMethod ) . toString ( ) ) ; if ( eventID == null ) { eventID = getEventId ( eventLookupFacility , new StringBuilder ( OUT_OF_DIALOG_REQUEST_EVENT_PREFIX ) . append ( SIP_EXTENSION_REQUEST_EVENT_NAME_SUFIX ) . toString ( ) ) ; } } return eventID ; }
Retrieves the event id for a SIP Request event .
10,344
public FireableEventType getEventId ( EventLookupFacility eventLookupFacility , Response response ) { String statusCodeName = null ; final int responseStatus = response . getStatusCode ( ) ; if ( responseStatus == 100 ) { statusCodeName = "TRYING" ; } else if ( 100 < responseStatus && responseStatus < 200 ) { statusCodeName = "PROVISIONAL" ; } else if ( responseStatus < 300 ) { statusCodeName = "SUCCESS" ; } else if ( responseStatus < 400 ) { statusCodeName = "REDIRECT" ; } else if ( responseStatus < 500 ) { statusCodeName = "CLIENT_ERROR" ; } else if ( responseStatus < 600 ) { statusCodeName = "SERVER_ERROR" ; } else { statusCodeName = "GLOBAL_FAILURE" ; } return getEventId ( eventLookupFacility , new StringBuilder ( RESPONSE_EVENT_PREFIX ) . append ( statusCodeName ) . toString ( ) ) ; }
Retrieves the event id for a SIP Response event .
10,345
private void executeTask ( DataSourceJdbcTask jdbcTask ) { JdbcActivity jdbcActivity = jdbcRA . createActivity ( ) ; ActivityContextInterface jdbcACI = jdbcACIF . getActivityContextInterface ( jdbcActivity ) ; jdbcACI . attach ( sbbContextExt . getSbbLocalObject ( ) ) ; jdbcActivity . execute ( jdbcTask ) ; }
Simple method to create JDBC activity and execute given task .
10,346
protected final void args ( Object ... args ) { if ( args == null ) args = NO_ARGS ; this . args = args ; retry ( ) ; }
Sets the arguments for internal use only .
10,347
private synchronized void ensureIsRun ( ) { if ( ! isRun ) { isRun = true ; try { result = executeProc ( args ) ; exception = null ; } catch ( ProcError e ) { throw e . asRuntimeException ( ) ; } catch ( Throwable t ) { exception = t ; result = null ; } } }
Execute the proc if not done so already .
10,348
protected int describeArgsTo ( Description description ) { for ( int i = 0 ; i < args . length ; i ++ ) { if ( i > 0 ) description . appendText ( ", " ) ; description . appendValue ( args [ i ] ) ; } return args . length ; }
Describes the arguments that are used for execution this asProc .
10,349
public static long fromAlpha1 ( String s ) { s = s . trim ( ) ; if ( s . isEmpty ( ) ) return 0 ; return fromAlpha ( s ) + 1 ; }
Parses a one - based alpha - index . An empty string will be parsed as zero .
10,350
protected Object run ( A a , B b , C c , D d ) throws Throwable { throw notImplemented ( "run(A, B, C, D)" ) ; }
Executes the proc .
10,351
public static < T > T boxAllAs ( Object src , Class < T > type ) { return ( T ) boxAll ( type , src , 0 , - 1 ) ; }
Transforms any array into an array of boxed values .
10,352
public < E extends Enum < ? > > String getMessage ( E key , Object ... args ) throws MessageConveyorException { String declararingClassName = key . getDeclaringClass ( ) . getName ( ) ; CAL10NResourceBundle rb = cache . get ( declararingClassName ) ; if ( rb == null || rb . hasChanged ( ) ) { rb = lookup ( key ) ; cache . put ( declararingClassName , rb ) ; } String keyAsStr = key . toString ( ) ; String value = rb . getString ( keyAsStr ) ; if ( value == null ) { return "?" + keyAsStr + "?" ; } else { if ( args == null || args . length == 0 ) { return value ; } else { return format ( value , args ) ; } } }
Given an enum as key find the corresponding resource bundle and return the corresponding internationalized .
10,353
public int findHighestKey ( int max ) { int highest = Integer . MIN_VALUE ; int index = index ( hash ( max ) ) ; final int maxTry = capacity ; for ( int i = 0 ; i < maxTry ; i ++ ) { if ( ! slotIsFree ( index ) ) { int k = keys [ index ] ; if ( k == max ) return max ; if ( max > k && k > highest ) highest = k ; } index = nextIndex ( index ) ; } return highest ; }
Finds the highest key LE max for which there is a value .
10,354
public int findLowestKey ( int min ) { int lowest = Integer . MAX_VALUE ; int index = index ( hash ( min ) ) ; final int maxTry = capacity ; for ( int i = 0 ; i < maxTry ; i ++ ) { if ( ! slotIsFree ( index ) ) { int k = keys [ index ] ; if ( k == min ) return min ; if ( min < k && k < lowest ) lowest = k ; } index = nextIndex ( index ) ; } return lowest ; }
Finds the highest key GE min for which there is a value .
10,355
private int find ( int key , int hash ) { int index = index ( hash ) ; final int maxTry = capacity ; for ( int i = 0 ; i < maxTry ; i ++ ) { Object slot = values [ index ] ; if ( slot == null ) return - 1 ; if ( slot != GUARD ) return keys [ index ] == key ? index : - 1 ; index = nextIndex ( index ) ; } return - 1 ; }
Finds the slot of an existing value for key ;
10,356
private int findInsertIndex ( int key , int hash ) { int index = index ( hash ) ; final int maxTry = capacity ; for ( int i = 0 ; i < maxTry ; i ++ ) { if ( slotIsFree ( index ) ) return index ; index = nextIndex ( index ) ; } throw new IllegalStateException ( "Free slots expected" ) ; }
Find slot to inser key - value
10,357
public UriMappingResolver addResource ( String uri , String resource ) { uriMap . put ( uri , resource ) ; return this ; }
Adds a single resource that can be looked - up by its uri .
10,358
protected String getMappingString ( ) { StringBuilder sb = new StringBuilder ( ) ; final int schemaSize = uriMap . size ( ) ; final int domainSize = patternMap . size ( ) ; int s = 0 , d = 0 ; for ( String schema : uriMap . keySet ( ) ) { if ( s > 0 ) sb . append ( ", " ) ; sb . append ( schema ) ; s ++ ; if ( s > 2 && schemaSize > 3 ) { sb . append ( ", " ) ; sb . append ( schemaSize - s ) ; sb . append ( " more" ) ; break ; } } if ( schemaSize > 0 && domainSize > 0 ) sb . append ( "; " ) ; for ( Pattern domain : patternMap . keySet ( ) ) { if ( d > 0 ) sb . append ( ", " ) ; sb . append ( domain . pattern ( ) ) ; d ++ ; if ( d > 2 && domainSize > 3 ) { sb . append ( ", " ) ; sb . append ( domainSize - s ) ; sb . append ( " more" ) ; break ; } } return sb . toString ( ) ; }
string representation for debugging purposes
10,359
protected String expandSystemId ( String baseId , String systemId ) { return getRequest ( ) . expandSystemId ( baseId , systemId ) ; }
Calculates the resource location .
10,360
private static int quoteSingle ( final StringBuilder sb , final String string , final int start ) { int i = start + 1 ; if ( needsBlockQuoting ( string . charAt ( start ) ) ) return - i ; int unquoteLen = 0 ; int quotedMap = 1 ; for ( int j = 1 ; i < string . length ( ) ; i ++ , j ++ ) { char c = string . charAt ( i ) ; if ( needsQuoting ( c ) ) { if ( j > MAX_SINGLE_QUOTE_LEN || needsBlockQuoting ( c ) ) return - i - 1 ; quotedMap |= 1 << j ; unquoteLen = 0 ; } else { if ( unquoteLen == MAX_UNQUOTE_LEN || ( quotedMap == 1 && unquoteLen == MAX_SINGLE_UNQUOTE_LEN ) ) { break ; } unquoteLen ++ ; } } appendSingleQuoted ( sb , string , start , i - unquoteLen , quotedMap ) ; sb . append ( string , i - unquoteLen , i ) ; return i ; }
Tries to quote each character with a backslash .
10,361
public static boolean useParentheses ( int pSelf , int pNested ) { if ( pSelf == PrecedencedSelfDescribing . P_NONE || pSelf == PrecedencedSelfDescribing . P_UNARY_NO_PAREN ) { return false ; } if ( pNested < PrecedencedSelfDescribing . P_UNARY ) { return pNested <= pSelf ; } else { return pNested < pSelf ; } }
Compares own precedence against nested and return
10,362
private int compareParameter ( Class < ? > a , Class < ? > b ) { final int a_preferred = - 1 ; if ( a . equals ( b ) ) { return 0 ; } else if ( b . isAssignableFrom ( a ) ) { return a_preferred ; } else if ( a . isAssignableFrom ( b ) ) { return - a_preferred ; } else { return 0 ; } }
Compares two parameter types .
10,363
public int applicability ( final Class < ? > [ ] paramTypes , boolean varArgs ) { if ( argTypes == null ) { return MATCH_WILDCARD ; } int level = MATCH ; final int fixArgs = paramTypes . length - ( varArgs ? 1 : 0 ) ; if ( fixArgs > argTypes . length || ( ! varArgs && fixArgs != argTypes . length ) ) { return NO_MATCH ; } for ( int i = 0 ; i < fixArgs ; i ++ ) { int m = applicable ( argTypes [ i ] , paramTypes [ i ] ) ; if ( m == NO_MATCH ) return NO_MATCH ; if ( m < level ) level = m ; } if ( varArgs ) { Class < ? > varArgType = paramTypes [ fixArgs ] ; if ( paramTypes . length == argTypes . length ) { int m = applicable ( argTypes [ fixArgs ] , varArgType ) ; if ( m != NO_MATCH ) { return Math . min ( m , level ) ; } } level = MATCH_VARARGS ; Class < ? > comp = varArgType . getComponentType ( ) ; for ( int i = fixArgs ; i < argTypes . length ; i ++ ) { int m = applicable ( argTypes [ i ] , comp ) ; if ( m == NO_MATCH ) return NO_MATCH ; } } return level ; }
Returns the applicabilty of a signature . A signature with higher applicability is always preferred even if the other is more specific .
10,364
public static int maxLetterValue ( final int numberOfLetters ) { int v = 1 ; for ( int i = 1 ; i < numberOfLetters ; i ++ ) { v *= i % 2 == 0 ? 2 : 5 ; } return v ; }
Given an array of letters returns the value of the highest letter .
10,365
public static String toRoman ( final int number , final int [ ] [ ] digits , final String zero , final String [ ] letters ) { int maxVal = maxLetterValue ( letters ) ; return toRoman ( new StringBuilder ( ) , number , digits , zero , letters , maxVal ) . toString ( ) ; }
Converts an integer into a roman number .
10,366
public List < Object > match ( ) { final IntMatchResults result = new IntMatchResults ( ) ; if ( matches ( result ) ) { return result . getIntResultList ( ) ; } else { return null ; } }
Matches the entire input and returns a list of extracted values .
10,367
public boolean find ( int start , MatchResults result ) { if ( ! matcher . find ( start ) ) return false ; applyMatch ( result ) ; return true ; }
Finds the next match and fills the result
10,368
public static < T > Constructor < T > bestConstructor ( Class < T > clazz , Object [ ] args ) throws AmbiguousConstructorMatchException { return bestConstructor ( collectConstructors ( clazz ) , args ) ; }
Finds the best constructor for the given arguments .
10,369
public static < T > Constructor < T > bestConstructor ( Class < T > clazz , Class < ? > [ ] argTypes ) throws AmbiguousConstructorMatchException { return bestConstructor ( collectConstructors ( clazz ) , argTypes ) ; }
Finds the best constructor for the given arguments types .
10,370
public static < T > Constructor < T > bestConstructor ( Constructor < T > [ ] constructors , Object [ ] args ) throws AmbiguousConstructorMatchException { return bestConstructor ( constructors , collectArgTypes ( args ) ) ; }
Selects the best constructor for the given arguments .
10,371
public static < T > Constructor < T > bestConstructor ( Constructor < T > [ ] constructors , Class < ? > [ ] argTypes ) throws AmbiguousConstructorMatchException { try { return best ( constructors , collectSignatures ( constructors ) , collectVarArgs ( constructors ) , argTypes ) ; } catch ( AmbiguousSignatureMatchException e ) { throw new AmbiguousConstructorMatchException ( e , constructors ) ; } }
Selects the best constructor for the given argument types .
10,372
public static < T > Constructor < T > [ ] candidateConstructors ( Class < T > clazz , Object [ ] args ) { return candidateConstructors ( collectConstructors ( clazz ) , args ) ; }
Finds the best equally - matching constructors for the given arguments .
10,373
public static < T > Constructor < T > [ ] candidateConstructors ( Class < T > clazz , Class < ? > [ ] argTypes ) { return candidateConstructors ( collectConstructors ( clazz ) , argTypes ) ; }
Finds the best equally - matching constructors for the given argument types .
10,374
public static < T > Constructor < T > [ ] candidateConstructors ( Constructor < T > [ ] constructors , Object [ ] args ) { return candidateConstructors ( constructors , collectArgTypes ( args ) ) ; }
Selects the best equally - matching constructors for the given arguments .
10,375
public static < T > Constructor < T > [ ] candidateConstructors ( Constructor < T > [ ] constructors , Class < ? > [ ] argTypes ) { return candidates ( constructors , collectSignatures ( constructors ) , collectVarArgs ( constructors ) , argTypes ) ; }
Selects the best equally - matching constructors for the given argument types .
10,376
public static Method bestMethod ( Class < ? > clazz , String name , Object [ ] args ) throws AmbiguousMethodMatchException { return bestMethod ( collectMethods ( clazz , name ) , args ) ; }
Finds the best method for the given arguments .
10,377
public static Method bestMethod ( Class < ? > clazz , String name , Class < ? > [ ] argTypes ) throws AmbiguousMethodMatchException { return bestMethod ( collectMethods ( clazz , name ) , argTypes ) ; }
Finds the best method for the given argument types .
10,378
public static Method bestMethod ( Method [ ] methods , Object [ ] args ) throws AmbiguousMethodMatchException { return bestMethod ( methods , collectArgTypes ( args ) ) ; }
Selects the best method for the given arguments .
10,379
public static Method bestMethod ( Method [ ] methods , Class < ? > [ ] argTypes ) throws AmbiguousMethodMatchException { try { return best ( methods , collectSignatures ( methods ) , collectVarArgs ( methods ) , argTypes ) ; } catch ( AmbiguousSignatureMatchException e ) { throw new AmbiguousMethodMatchException ( e , methods ) ; } }
Selects the best method for the given argument types .
10,380
public static Method [ ] candidateMethods ( Class < ? > clazz , String name , Object [ ] args ) { return candidateMethods ( collectMethods ( clazz , name ) , args ) ; }
Finds the best equally - matching methods for the given arguments .
10,381
public static Method [ ] candidateMethods ( Class < ? > clazz , String name , Class < ? > [ ] argTypes ) { return candidateMethods ( collectMethods ( clazz , name ) , argTypes ) ; }
Finds the best equally - matching methods for the given argument types .
10,382
public static Method [ ] candidateMethods ( Method [ ] methods , Object [ ] args ) { return candidateMethods ( methods , collectArgTypes ( args ) ) ; }
Selects the best equally - matching methods for the given arguments .
10,383
public static Method [ ] candidateMethods ( Method [ ] methods , Class < ? > [ ] argTypes ) { return candidates ( methods , collectSignatures ( methods ) , collectVarArgs ( methods ) , argTypes ) ; }
Selects the best equally - matching methods for the given argument types .
10,384
public static < T > T best ( T [ ] items , Class < ? > [ ] [ ] signatures , boolean [ ] varArgs , Class < ? > [ ] argTypes ) throws AmbiguousSignatureMatchException { int i = bestMatch ( signatures , varArgs , argTypes ) ; if ( i < 0 ) return null ; return items [ i ] ; }
Selects the best item for the given argument types .
10,385
public static < T > T [ ] candidates ( T [ ] items , Class < ? > [ ] [ ] signatures , boolean [ ] varArgs , Class < ? > [ ] argTypes ) { final int [ ] indices = candidateMatches ( signatures , varArgs , argTypes ) ; T [ ] result = newArray ( items . getClass ( ) . getComponentType ( ) , indices . length ) ; for ( int i = 0 ; i < indices . length ; i ++ ) { result [ i ] = items [ indices [ i ] ] ; } return result ; }
Selects the best equally - matching item for the given argument types .
10,386
public static int bestMatch ( Class < ? > [ ] [ ] signatures , boolean [ ] varArgs , Class < ? > [ ] argTypes ) throws AmbiguousSignatureMatchException { return bestMatch ( signatures , varArgs , new JavaSignatureComparator ( argTypes ) ) ; }
Selects the best match in signatures for the given argument types .
10,387
public static int [ ] candidateMatches ( Class < ? > [ ] [ ] signatures , boolean [ ] varArgs , Class < ? > [ ] argTypes ) { return candidateMatches ( signatures , varArgs , new JavaSignatureComparator ( argTypes ) ) ; }
Returns indices of all signatures that are a best match for the given argument types .
10,388
public static Object [ ] fixVarArgs ( Class < ? > [ ] paramsWithVarArgs , Object [ ] arguments ) { int n = paramsWithVarArgs . length ; return fixVarArgs ( n , paramsWithVarArgs [ n - 1 ] , arguments ) ; }
Fixes an arguments array to fit parameter types where the last parameter is an varargs array .
10,389
@ SuppressWarnings ( "SuspiciousSystemArraycopy" ) public static Object [ ] fixVarArgs ( int length , Class < ? > varArgType , Object [ ] arguments ) { final Object [ ] result ; if ( arguments . length == length && varArgType . isInstance ( arguments [ length - 1 ] ) ) { return arguments ; } else { result = Arrays . copyOf ( arguments , length , Object [ ] . class ) ; } final Object varArgs ; Class < ? > varArgElementType = varArgType . getComponentType ( ) ; if ( varArgElementType . isPrimitive ( ) ) { varArgs = Boxing . unboxAll ( varArgElementType , arguments , length - 1 , - 1 ) ; } else { int varLen = arguments . length - length + 1 ; varArgs = Array . newInstance ( varArgElementType , varLen ) ; System . arraycopy ( arguments , length - 1 , varArgs , 0 , varLen ) ; } result [ length - 1 ] = varArgs ; return result ; }
Fixes an arguments array to fit a given length the last value is an array filled with varargs .
10,390
protected void uncountable ( String word ) { Rule r = new UncountableRule ( lower ( word ) ) ; plural ( r ) ; singular ( r ) ; }
Declares a word as uncountable which means that singular and plural are identical .
10,391
public synchronized Pluralizer register ( Locale l , Pluralizer p ) { return pluralizers . put ( l , p ) ; }
Registers a pluralizer
10,392
public synchronized Pluralizer find ( Locale l ) { while ( l != null ) { List < Locale > candidates = control . getCandidateLocales ( PLURALIZER_CLASS , l ) ; for ( Locale c : candidates ) { Pluralizer p = pluralizers . get ( c ) ; if ( p != null ) return p ; } l = control . getFallbackLocale ( PLURALIZER_CLASS , l ) ; } return null ; }
Finds the best pluralizer for a locale .
10,393
public synchronized PluralizerRegistry copy ( ) { PluralizerRegistry r = new PluralizerRegistry ( control ) ; r . pluralizers . putAll ( pluralizers ) ; return r ; }
Creates a shallow copy of this registry .
10,394
protected Match < ? > match ( ) { Match < ? > m = result ( ) . getMatch ( ) ; if ( m == null ) { throw new IllegalStateException ( "Match failed" ) ; } return m ; }
For internal use . Fails if this is a mismatch .
10,395
protected Mismatch < ? > mismatch ( ) { Mismatch < ? > m = result ( ) . getMismatch ( ) ; if ( m == null ) { throw new IllegalStateException ( "Match succeded" ) ; } return m ; }
For internal use . Fails if this is a match .
10,396
public static ResolvingException wrap ( RRequest request , Exception e ) { if ( e instanceof ResolvingException ) return ( ResolvingException ) e ; return new ResolvingException ( request , e ) ; }
Wraps e in an resolving exception if it isn t one already .
10,397
public Throwable getResolvingCause ( ) { Throwable t = this , c = this ; while ( c instanceof ResolvingException ) { t = c ; c = t . getCause ( ) ; } return c == null ? t : c ; }
Returns the underlying cause of this resolving exceptions . Unpacks nested resolving exceptions if necessary .
10,398
protected String expandSystemId ( String baseId , String systemId ) { if ( baseId == null || baseId . isEmpty ( ) ) return systemId ; if ( systemId == null || systemId . isEmpty ( ) ) return baseId ; try { return new URI ( baseId ) . resolve ( new URI ( systemId ) ) . toASCIIString ( ) ; } catch ( URISyntaxException ex ) { throw new ResolvingException ( toString ( ) , ex ) ; } }
Calculates the schema file location .
10,399
public void push ( T token ) { if ( token == lastPushed ) return ; lastPushed = token ; if ( token . getChannel ( ) == TokenChannel . Default ) { main . add ( token ) ; } all . add ( token ) ; }
make Liskov spin