idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
500
|
public void error ( Throwable error , String description ) { log ( error , null , description , Level . ERROR ) ; }
|
Record an error with human readable description .
|
501
|
public void warning ( Throwable error , String description ) { log ( error , null , description , Level . WARNING ) ; }
|
Record a warning with human readable description .
|
502
|
public void info ( Throwable error , String description ) { log ( error , null , description , Level . INFO ) ; }
|
Record an info error with human readable description .
|
503
|
public void debug ( Throwable error , String description ) { log ( error , null , description , Level . DEBUG ) ; }
|
Record a debug error with human readable description .
|
504
|
public void log ( Throwable error , Map < String , Object > custom , String description , Level level , boolean isUncaught ) { this . rollbar . log ( error , custom , description , level , isUncaught ) ; }
|
Record an error or message with extra data at the level specified . At least ene of error or description must be non - null . If error is null description will be sent as a message . If error is non - null description will be sent as the description of the error . Custom data will be attached to message if the error is null .
|
505
|
public Body from ( Throwable throwable , String description ) { if ( throwable == null ) { return new Body . Builder ( ) . bodyContent ( message ( description ) ) . build ( ) ; } return from ( new RollbarThrowableWrapper ( throwable ) , description ) ; }
|
Builds the body for the throwable and description supplied .
|
506
|
public static Rollbar init ( Config config ) { if ( notifier == null ) { synchronized ( Rollbar . class ) { if ( notifier == null ) { notifier = new Rollbar ( config ) ; LOGGER . debug ( "Rollbar managed notifier created." ) ; } } } return notifier ; }
|
Method to initialize the library managed notifier instance .
|
507
|
public void configure ( Config config ) { LOGGER . debug ( "Reloading configuration." ) ; this . configWriteLock . lock ( ) ; try { this . config = config ; processAppPackages ( config ) ; } finally { this . configWriteLock . unlock ( ) ; } }
|
Replace the configuration of this instance directly .
|
508
|
public void sendJsonPayload ( String json ) { try { this . configReadLock . lock ( ) ; Config config = this . config ; this . configReadLock . unlock ( ) ; sendPayload ( config , new Payload ( json ) ) ; } catch ( Exception e ) { LOGGER . error ( "Error while sending payload to Rollbar: {}" , e ) ; } }
|
Send JSON payload .
|
509
|
public static < T > T requireNonNull ( T object , String errorMessage ) { if ( object == null ) { throw new NullPointerException ( errorMessage ) ; } else { return object ; } }
|
Checks that the specified object reference is not null .
|
510
|
public static RollbarAppender createAppender ( @ PluginAttribute ( "accessToken" ) final String accessToken , @ PluginAttribute ( "endpoint" ) final String endpoint , @ PluginAttribute ( "environment" ) final String environment , @ PluginAttribute ( "language" ) final String language , @ PluginAttribute ( "configProviderClassName" ) final String configProviderClassName , @ PluginAttribute ( "name" ) final String name , @ PluginElement ( "Layout" ) Layout < ? extends Serializable > layout , @ PluginElement ( "Filter" ) Filter filter , @ PluginAttribute ( "ignoreExceptions" ) final String ignore ) { ConfigProvider configProvider = ConfigProviderHelper . getConfigProvider ( configProviderClassName ) ; Config config ; ConfigBuilder configBuilder = withAccessToken ( accessToken ) . environment ( environment ) . endpoint ( endpoint ) . server ( new ServerProvider ( ) ) . language ( language ) ; if ( configProvider != null ) { config = configProvider . provide ( configBuilder ) ; } else { config = configBuilder . build ( ) ; } Rollbar rollbar = new Rollbar ( config ) ; boolean ignoreExceptions = Booleans . parseBoolean ( ignore , true ) ; return new RollbarAppender ( name , filter , layout , ignoreExceptions , rollbar ) ; }
|
Create appender plugin factory method .
|
511
|
public static Intent newEmailIntent ( String address , String subject , String body ) { return newEmailIntent ( address , subject , body , null ) ; }
|
Create an intent to send an email to a single recipient
|
512
|
public static Intent newEmailIntent ( String address , String subject , String body , Uri attachment ) { return newEmailIntent ( address == null ? null : new String [ ] { address } , subject , body , attachment ) ; }
|
Create an intent to send an email with an attachment to a single recipient
|
513
|
public static Intent newEmailIntent ( String [ ] addresses , String subject , String body , Uri attachment ) { Intent intent = new Intent ( Intent . ACTION_SEND ) ; if ( addresses != null ) intent . putExtra ( Intent . EXTRA_EMAIL , addresses ) ; if ( body != null ) intent . putExtra ( Intent . EXTRA_TEXT , body ) ; if ( subject != null ) intent . putExtra ( Intent . EXTRA_SUBJECT , subject ) ; if ( attachment != null ) intent . putExtra ( Intent . EXTRA_STREAM , attachment ) ; intent . setType ( MIME_TYPE_EMAIL ) ; return intent ; }
|
Create an intent to send an email with an attachment
|
514
|
public static Intent newPlayYouTubeVideoIntent ( String videoId ) { try { return new Intent ( Intent . ACTION_VIEW , Uri . parse ( "vnd.youtube:" + videoId ) ) ; } catch ( ActivityNotFoundException ex ) { return new Intent ( Intent . ACTION_VIEW , Uri . parse ( "http://www.youtube.com/watch?v=" + videoId ) ) ; } }
|
Open a YouTube video . If the app is not installed it opens it in the browser
|
515
|
public static Intent newPlayMediaIntent ( Uri uri , String type ) { Intent intent = new Intent ( Intent . ACTION_VIEW ) ; intent . setDataAndType ( uri , type ) ; return intent ; }
|
Open the media player to play the given media Uri
|
516
|
public static Intent newTakePictureIntent ( File tempFile ) { Intent intent = new Intent ( MediaStore . ACTION_IMAGE_CAPTURE ) ; intent . putExtra ( MediaStore . EXTRA_OUTPUT , Uri . fromFile ( tempFile ) ) ; return intent ; }
|
Creates an intent that will launch the camera to take a picture that s saved to a temporary file so you can use it directly without going through the gallery .
|
517
|
public static Intent newSelectPictureIntent ( ) { Intent intent = new Intent ( Intent . ACTION_PICK ) ; intent . setType ( "image/*" ) ; return intent ; }
|
Creates an intent that will launch the phone s picture gallery to select a picture from it .
|
518
|
public static Intent newShareTextIntent ( String subject , String message , String chooserDialogTitle ) { Intent shareIntent = new Intent ( Intent . ACTION_SEND ) ; shareIntent . putExtra ( Intent . EXTRA_TEXT , message ) ; shareIntent . putExtra ( Intent . EXTRA_SUBJECT , subject ) ; shareIntent . setType ( MIME_TYPE_TEXT ) ; return Intent . createChooser ( shareIntent , chooserDialogTitle ) ; }
|
Creates a chooser to share some data .
|
519
|
public static Intent newSmsIntent ( Context context , String body , String [ ] phoneNumbers ) { Uri smsUri ; if ( phoneNumbers == null || phoneNumbers . length == 0 ) { smsUri = Uri . parse ( "smsto:" ) ; } else { smsUri = Uri . parse ( "smsto:" + Uri . encode ( TextUtils . join ( "," , phoneNumbers ) ) ) ; } Intent intent ; if ( Build . VERSION . SDK_INT >= Build . VERSION_CODES . KITKAT ) { intent = new Intent ( Intent . ACTION_SENDTO , smsUri ) ; intent . setPackage ( Telephony . Sms . getDefaultSmsPackage ( context ) ) ; } else { intent = new Intent ( Intent . ACTION_VIEW , smsUri ) ; } if ( body != null ) { intent . putExtra ( "sms_body" , body ) ; } return intent ; }
|
Creates an intent that will allow to send an SMS to a phone number
|
520
|
public static Intent newMarketForAppIntent ( Context context ) { String packageName = context . getApplicationContext ( ) . getPackageName ( ) ; return newMarketForAppIntent ( context , packageName ) ; }
|
Intent that should open the app store of the device on the current application page
|
521
|
public static Intent newMarketForAppIntent ( Context context , String packageName ) { Intent intent = new Intent ( Intent . ACTION_VIEW , Uri . parse ( "market://details?id=" + packageName ) ) ; if ( ! IntentUtils . isIntentAvailable ( context , intent ) ) { intent = new Intent ( Intent . ACTION_VIEW , Uri . parse ( "amzn://apps/android?p=" + packageName ) ) ; } if ( ! IntentUtils . isIntentAvailable ( context , intent ) ) { intent = null ; } if ( intent != null ) { intent . addFlags ( Intent . FLAG_ACTIVITY_NO_HISTORY | Intent . FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET ) ; } return intent ; }
|
Intent that should open the app store of the device on the given application
|
522
|
public static Intent newGooglePlayIntent ( Context context , String packageName ) { Intent intent = new Intent ( Intent . ACTION_VIEW , Uri . parse ( "market://details?id=" + packageName ) ) ; if ( ! IntentUtils . isIntentAvailable ( context , intent ) ) { intent = MediaIntents . newOpenWebBrowserIntent ( "https://play.google.com/store/apps/details?id=" + packageName ) ; } if ( intent != null ) { intent . addFlags ( Intent . FLAG_ACTIVITY_NO_HISTORY | Intent . FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET ) ; } return intent ; }
|
Intent that should open either the Google Play app or if not available the web browser on the Google Play website
|
523
|
private String getSymbolExceptions ( ) { if ( TextUtils . isEmpty ( filteredMask ) ) return "" ; StringBuilder maskSymbolException = new StringBuilder ( ) ; for ( char c : filteredMask . toCharArray ( ) ) { if ( ! Character . isDigit ( c ) && maskSymbolException . indexOf ( String . valueOf ( c ) ) == - 1 ) { maskSymbolException . append ( c ) ; } } maskSymbolException . append ( replacementChar ) ; return maskSymbolException . toString ( ) ; }
|
Generate symbol exception for inputType = number
|
524
|
public E remove ( int index ) { E e = data [ index ] ; data [ index ] = data [ -- size ] ; data [ size ] = null ; return e ; }
|
Removes the element at the specified position in this Bag . Order of elements is not preserved .
|
525
|
public E removeLast ( ) { if ( size > 0 ) { E e = data [ -- size ] ; data [ size ] = null ; return e ; } return null ; }
|
Removes and return the last object in the bag .
|
526
|
public boolean remove ( E e ) { for ( int i = 0 ; i < size ; i ++ ) { E e2 = data [ i ] ; if ( e == e2 ) { data [ i ] = data [ -- size ] ; data [ size ] = null ; return true ; } } return false ; }
|
Removes the first occurrence of the specified element from this Bag if it is present . If the Bag does not contain the element it is unchanged . It does not preserve order of elements .
|
527
|
public boolean contains ( E e ) { for ( int i = 0 ; size > i ; i ++ ) { if ( e == data [ i ] ) { return true ; } } return false ; }
|
Check if bag contains this element . The operator == is used to check for equality .
|
528
|
public void add ( E e ) { if ( size == data . length ) { grow ( ) ; } data [ size ++ ] = e ; }
|
Adds the specified element to the end of this bag . if needed also increases the capacity of the bag .
|
529
|
public void set ( int index , E e ) { if ( index >= data . length ) { grow ( index * 2 ) ; } size = index + 1 ; data [ index ] = e ; }
|
Set element at specified index in the bag .
|
530
|
public void addEntity ( Entity entity ) { boolean delayed = updating || familyManager . notifying ( ) ; entityManager . addEntity ( entity , delayed ) ; }
|
Adds an entity to this Engine . This will throw an IllegalArgumentException if the given entity was already registered with an engine .
|
531
|
public void removeEntity ( Entity entity ) { boolean delayed = updating || familyManager . notifying ( ) ; entityManager . removeEntity ( entity , delayed ) ; }
|
Removes an entity from this Engine .
|
532
|
public void update ( float deltaTime ) { if ( updating ) { throw new IllegalStateException ( "Cannot call update() on an Engine that is already updating." ) ; } updating = true ; ImmutableArray < EntitySystem > systems = systemManager . getSystems ( ) ; try { for ( int i = 0 ; i < systems . size ( ) ; ++ i ) { EntitySystem system = systems . get ( i ) ; if ( system . checkProcessing ( ) ) { system . update ( deltaTime ) ; } while ( componentOperationHandler . hasOperationsToProcess ( ) || entityManager . hasPendingOperations ( ) ) { componentOperationHandler . processOperations ( ) ; entityManager . processPendingOperations ( ) ; } } } finally { updating = false ; } }
|
Updates all the systems in this Engine .
|
533
|
@ SuppressWarnings ( "unchecked" ) < T extends Component > T getComponent ( ComponentType componentType ) { int componentTypeIndex = componentType . getIndex ( ) ; if ( componentTypeIndex < components . getCapacity ( ) ) { return ( T ) components . get ( componentType . getIndex ( ) ) ; } else { return null ; } }
|
Internal use .
|
534
|
public void dispatch ( T object ) { final Object [ ] items = listeners . begin ( ) ; for ( int i = 0 , n = listeners . size ; i < n ; i ++ ) { Listener < T > listener = ( Listener < T > ) items [ i ] ; listener . receive ( this , object ) ; } listeners . end ( ) ; }
|
Dispatches an event to all Listeners registered to this Signal
|
535
|
private static void warmup ( Argon2 argon2 , char [ ] password ) { for ( int i = 0 ; i < WARMUP_RUNS ; i ++ ) { argon2 . hash ( MIN_ITERATIONS , MIN_MEMORY , MIN_PARALLELISM , password ) ; } }
|
Calls Argon2 a number of times to warm up the JIT
|
536
|
private byte [ ] toByteArray ( char [ ] chars , Charset charset ) { assert chars != null ; CharBuffer charBuffer = CharBuffer . wrap ( chars ) ; ByteBuffer byteBuffer = charset . encode ( charBuffer ) ; byte [ ] bytes = Arrays . copyOfRange ( byteBuffer . array ( ) , byteBuffer . position ( ) , byteBuffer . limit ( ) ) ; Arrays . fill ( byteBuffer . array ( ) , ( byte ) 0 ) ; return bytes ; }
|
Converts the given char array to a UTF - 8 encoded byte array .
|
537
|
public < T > T makeRequest ( String call , String method , boolean authenticate , ApiRequestWriter writer , ApiResponseReader < T > reader ) { HttpURLConnection connection = null ; try { connection = sendRequest ( call , method , authenticate , writer ) ; handleResponseCode ( connection ) ; if ( reader != null ) return handleResponse ( connection , reader ) ; else return null ; } catch ( IOException e ) { throw new OsmConnectionException ( e ) ; } catch ( OAuthException e ) { throw new OsmAuthorizationException ( e ) ; } finally { if ( connection != null ) connection . disconnect ( ) ; } }
|
Make a request to the Http Osm Api
|
538
|
public ChangesetInfo get ( long id ) { SingleElementHandler < ChangesetInfo > handler = new SingleElementHandler < > ( ) ; String query = CHANGESET + "/" + id + "?include_discussion=true" ; try { osm . makeAuthenticatedRequest ( query , null , new ChangesetParser ( handler ) ) ; } catch ( OsmNotFoundException e ) { return null ; } return handler . get ( ) ; }
|
Get the changeset information with the given id . Always includes the changeset discussion .
|
539
|
public void find ( Handler < ChangesetInfo > handler , QueryChangesetsFilters filters ) { String query = filters != null ? "?" + filters . toParamString ( ) : "" ; try { osm . makeAuthenticatedRequest ( CHANGESET + "s" + query , null , new ChangesetParser ( handler ) ) ; } catch ( OsmNotFoundException e ) { } }
|
Get a number of changesets that match the given filters .
|
540
|
public ChangesetInfo comment ( long id , String text ) { if ( text . isEmpty ( ) ) { throw new IllegalArgumentException ( "Text must not be empty" ) ; } SingleElementHandler < ChangesetInfo > handler = new SingleElementHandler < > ( ) ; String apiCall = CHANGESET + "/" + id + "/comment?text=" + urlEncodeText ( text ) ; osm . makeAuthenticatedRequest ( apiCall , "POST" , new ChangesetParser ( handler ) ) ; return handler . get ( ) ; }
|
Add a comment to the given changeset . The changeset must already be closed . Adding a comment to a changeset automatically subscribes the user to it .
|
541
|
public ChangesetInfo subscribe ( long id ) { SingleElementHandler < ChangesetInfo > handler = new SingleElementHandler < > ( ) ; ChangesetInfo result ; try { String apiCall = CHANGESET + "/" + id + "/subscribe" ; osm . makeAuthenticatedRequest ( apiCall , "POST" , new ChangesetParser ( handler ) ) ; result = handler . get ( ) ; } catch ( OsmConflictException ignore ) { result = get ( id ) ; } return result ; }
|
Subscribe the user to a changeset discussion . The changeset must be closed already .
|
542
|
public ChangesetInfo unsubscribe ( long id ) { SingleElementHandler < ChangesetInfo > handler = new SingleElementHandler < > ( ) ; ChangesetInfo result ; try { String apiCall = CHANGESET + "/" + id + "/unsubscribe" ; osm . makeAuthenticatedRequest ( apiCall , "POST" , new ChangesetParser ( handler ) ) ; result = handler . get ( ) ; } catch ( OsmNotFoundException e ) { result = get ( id ) ; if ( result == null ) throw e ; } return result ; }
|
Unsubscribe the user from a changeset discussion . The changeset must be closed already .
|
543
|
public void getData ( long id , MapDataChangesHandler handler , MapDataFactory factory ) { osm . makeAuthenticatedRequest ( CHANGESET + "/" + id + "/download" , null , new MapDataChangesParser ( handler , factory ) ) ; }
|
Get map data changes associated with the given changeset .
|
544
|
public long create ( final String name , final GpsTraceDetails . Visibility visibility , final String description , final List < String > tags , final Iterable < GpsTrackpoint > trackpoints ) { checkFieldLength ( "Name" , name ) ; checkFieldLength ( "Description" , description ) ; checkTagsLength ( tags ) ; FormDataWriter writer = new FormDataWriter ( ) { protected void write ( ) throws IOException { ApiRequestWriter trackWriter = new GpxTrackWriter ( osm . getUserAgent ( ) , trackpoints ) ; addFileField ( "file" , name , trackWriter ) ; if ( tags != null && ! tags . isEmpty ( ) ) addField ( "tags" , toCommaList ( tags ) ) ; addField ( "description" , description ) ; addField ( "visibility" , visibility . toString ( ) . toLowerCase ( Locale . UK ) ) ; } } ; return osm . makeAuthenticatedRequest ( GPX + "/create" , "POST" , writer , new IdResponseReader ( ) ) ; }
|
Upload a new trace of trackpoints .
|
545
|
public long create ( String name , GpsTraceDetails . Visibility visibility , String description , final Iterable < GpsTrackpoint > trackpoints ) { return create ( name , visibility , description , null , trackpoints ) ; }
|
Upload a new trace with no tags
|
546
|
public void update ( long id , GpsTraceDetails . Visibility visibility , String description , List < String > tags ) { checkFieldLength ( "Description" , description ) ; checkTagsLength ( tags ) ; GpsTraceWriter writer = new GpsTraceWriter ( id , visibility , description , tags ) ; osm . makeAuthenticatedRequest ( GPX + "/" + id , "PUT" , writer ) ; }
|
Change the visibility description and tags of a GPS trace . description and tags may be null if there should be none .
|
547
|
public GpsTraceDetails get ( long id ) { SingleElementHandler < GpsTraceDetails > handler = new SingleElementHandler < > ( ) ; try { osm . makeAuthenticatedRequest ( GPX + "/" + id , "GET" , new GpsTracesParser ( handler ) ) ; } catch ( OsmNotFoundException e ) { return null ; } return handler . get ( ) ; }
|
Get information about a given GPS trace or null if it does not exist .
|
548
|
public void getData ( long id , Handler < GpsTrackpoint > handler ) { osm . makeAuthenticatedRequest ( GPX + "/" + id + "/data" , "GET" , new GpxTrackParser ( handler ) ) ; }
|
Get all trackpoints contained in the given trace id . Note that the trace is a GPX file so there is potentially much more information in there than simply the trackpoints . However this method only parses the trackpoints and ignores everything else .
|
549
|
public Note create ( LatLon pos , String text ) { if ( text . isEmpty ( ) ) { throw new IllegalArgumentException ( "Text may not be empty" ) ; } String data = "lat=" + numberFormat . format ( pos . getLatitude ( ) ) + "&lon=" + numberFormat . format ( pos . getLongitude ( ) ) + "&text=" + urlEncode ( text ) ; String call = NOTES + "?" + data ; SingleElementHandler < Note > noteHandler = new SingleElementHandler < > ( ) ; osm . makeAuthenticatedRequest ( call , "POST" , new NotesParser ( noteHandler ) ) ; return noteHandler . get ( ) ; }
|
Create a new note at the given location
|
550
|
public Note reopen ( long id , String reason ) { SingleElementHandler < Note > noteHandler = new SingleElementHandler < > ( ) ; makeSingleNoteRequest ( id , "reopen" , reason , new NotesParser ( noteHandler ) ) ; return noteHandler . get ( ) ; }
|
Reopen the given note with the given reason . The reason is optional .
|
551
|
public void getAll ( BoundingBox bounds , Handler < Note > handler , int limit , int hideClosedNoteAfter ) { getAll ( bounds , null , handler , limit , hideClosedNoteAfter ) ; }
|
Retrieve all notes in the given area and feed them to the given handler .
|
552
|
public void getAll ( BoundingBox bounds , String search , Handler < Note > handler , int limit , int hideClosedNoteAfter ) { if ( limit <= 0 || limit > 10000 ) { throw new IllegalArgumentException ( "limit must be within 1 and 10000" ) ; } if ( bounds . crosses180thMeridian ( ) ) { throw new IllegalArgumentException ( "bounds may not cross the 180th meridian" ) ; } String searchQuery = "" ; if ( search != null && ! search . isEmpty ( ) ) { searchQuery = "&q=" + urlEncode ( search ) ; } final String call = NOTES + "?bbox=" + bounds . getAsLeftBottomRightTopString ( ) + searchQuery + "&limit=" + limit + "&closed=" + hideClosedNoteAfter ; try { osm . makeAuthenticatedRequest ( call , null , new NotesParser ( handler ) ) ; } catch ( OsmBadUserInputException e ) { throw new OsmQueryTooBigException ( e ) ; } }
|
Retrieve those notes in the given area that match the given search string
|
553
|
public void find ( Handler < Note > handler , QueryNotesFilters filters ) { String query = filters != null ? "?" + filters . toParamString ( ) : "" ; osm . makeAuthenticatedRequest ( NOTES + "/search" + query , null , new NotesParser ( handler ) ) ; }
|
Get a number of notes that match the given filters .
|
554
|
public long updateMap ( Map < String , String > tags , Iterable < Element > elements , Handler < DiffElement > handler ) { tags . put ( "created_by" , osm . getUserAgent ( ) ) ; long changesetId = openChangeset ( tags ) ; try { uploadChanges ( changesetId , elements , handler ) ; } finally { closeChangeset ( changesetId ) ; } return changesetId ; }
|
Opens a changeset uploads the data closes the changeset and subscribes the user to it .
|
555
|
public void uploadChanges ( long changesetId , Iterable < Element > elements , Handler < DiffElement > handler ) { MapDataDiffParser parser = null ; if ( handler != null ) { parser = new MapDataDiffParser ( handler ) ; } osm . makeAuthenticatedRequest ( "changeset/" + changesetId + "/upload" , "POST" , new MapDataChangesWriter ( changesetId , elements ) , parser ) ; }
|
Upload changes into an opened changeset .
|
556
|
public void setAll ( Map < String , String > preferences ) { for ( Map . Entry < String , String > preference : preferences . entrySet ( ) ) { checkPreferenceKeyLength ( preference . getKey ( ) ) ; checkPreferenceValueLength ( preference . getValue ( ) ) ; } final Map < String , String > prefs = preferences ; osm . makeAuthenticatedRequest ( USERPREFS , "PUT" , new XmlWriter ( ) { protected void write ( ) throws IOException { begin ( "osm" ) ; begin ( "preferences" ) ; for ( Map . Entry < String , String > preference : prefs . entrySet ( ) ) { begin ( "preference" ) ; attribute ( "k" , preference . getKey ( ) ) ; attribute ( "v" , preference . getValue ( ) ) ; end ( ) ; } end ( ) ; end ( ) ; } } ) ; }
|
Sets all the given preference keys to the given preference values .
|
557
|
public void set ( String key , String value ) { String urlKey = urlEncode ( key ) ; checkPreferenceKeyLength ( urlKey ) ; checkPreferenceValueLength ( value ) ; osm . makeAuthenticatedRequest ( USERPREFS + urlKey , "PUT" , new PlainTextWriter ( value ) ) ; }
|
Sets the given preference key to the given preference value .
|
558
|
public void delete ( String key ) { String urlKey = urlEncode ( key ) ; checkPreferenceKeyLength ( urlKey ) ; osm . makeAuthenticatedRequest ( USERPREFS + urlKey , "DELETE" ) ; }
|
Deletes the given preference key from the user preferences
|
559
|
public QueryChangesetsFilters byOpenSomeTimeBetween ( Date createdBefore , Date closedAfter ) { params . put ( "time" , dateFormat . format ( closedAfter ) + "," + dateFormat . format ( createdBefore ) ) ; return this ; }
|
Filter by changesets that have at one time been open during the given time range
|
560
|
public R call ( ) throws BackendException { while ( hasNext ) { pagesProcessed ++ ; next ( ) ; } delegate . updatePagesHistogram ( apiName , tableName , pagesProcessed ) ; return getMergedPages ( ) ; }
|
Paginates through pages of an entity .
|
561
|
private ScanContext grab ( ) throws ExecutionException , InterruptedException { final Future < ScanContext > ret = exec . take ( ) ; final ScanRequest originalRequest = ret . get ( ) . getScanRequest ( ) ; final int segment = originalRequest . getSegment ( ) ; final ScanSegmentWorker sw = workers [ segment ] ; if ( sw . hasNext ( ) ) { currentFutures [ segment ] = exec . submit ( sw ) ; } else { finishSegment ( segment ) ; currentFutures [ segment ] = null ; } return ret . get ( ) ; }
|
This method gets a segmentedScanResult and submits the next scan request for that segment if there is one .
|
562
|
public boolean contains ( final AbstractDynamoDbStore store , final StaticBuffer key , final StaticBuffer column ) { return expectedValues . containsKey ( store ) && expectedValues . get ( store ) . containsKey ( key ) && expectedValues . get ( store ) . get ( key ) . containsKey ( column ) ; }
|
Determins whether a particular key and column are part of this transaction
|
563
|
public StaticBuffer get ( final AbstractDynamoDbStore store , final StaticBuffer key , final StaticBuffer column ) { return expectedValues . get ( store ) . get ( key ) . get ( column ) ; }
|
Gets the expected value for a particular key and column if any
|
564
|
public void putKeyColumnOnlyIfItIsNotYetChangedInTx ( final AbstractDynamoDbStore store , final StaticBuffer key , final StaticBuffer column , final StaticBuffer expectedValue ) { expectedValues . computeIfAbsent ( store , s -> new HashMap < > ( ) ) ; expectedValues . get ( store ) . computeIfAbsent ( key , k -> new HashMap < > ( ) ) ; expectedValues . get ( store ) . get ( key ) . putIfAbsent ( column , expectedValue ) ; }
|
Puts the expected value for a particular key and column
|
565
|
public CreateTableRequest getTableSchema ( ) { return new CreateTableRequest ( ) . withTableName ( tableName ) . withProvisionedThroughput ( new ProvisionedThroughput ( client . readCapacity ( tableName ) , client . writeCapacity ( tableName ) ) ) ; }
|
Creates the schemata for the DynamoDB table or tables each store requires . Implementations should override and reuse this logic
|
566
|
private int calculateExpressionBasedUpdateSize ( final UpdateItemRequest request ) { if ( request == null || request . getUpdateExpression ( ) == null ) { throw new IllegalArgumentException ( "request did not use update expression" ) ; } int size = calculateItemSizeInBytes ( request . getKey ( ) ) ; for ( AttributeValue value : request . getExpressionAttributeValues ( ) . values ( ) ) { size += calculateAttributeSizeInBytes ( value ) ; } return size ; }
|
This method calculates a lower bound of the size of a new item created with UpdateItem UpdateExpression . It does not account for the size of the attribute names of the document paths in the attribute names map and it assumes that the UpdateExpression only uses the SET action to assign to top - level attributes .
|
567
|
public static Map < String , AttributeValue > cloneItem ( final Map < String , AttributeValue > item ) { if ( item == null ) { return null ; } final Map < String , AttributeValue > clonedItem = Maps . newHashMap ( ) ; final IdentityHashMap < AttributeValue , AttributeValue > sourceDestinationMap = new IdentityHashMap < > ( ) ; for ( Entry < String , AttributeValue > entry : item . entrySet ( ) ) { if ( ! sourceDestinationMap . containsKey ( entry . getValue ( ) ) ) { sourceDestinationMap . put ( entry . getValue ( ) , clone ( entry . getValue ( ) , sourceDestinationMap ) ) ; } clonedItem . put ( entry . getKey ( ) , sourceDestinationMap . get ( entry . getValue ( ) ) ) ; } return clonedItem ; }
|
Helper method that clones an item
|
568
|
private static int calculateAttributeSizeInBytes ( final AttributeValue value ) { int attrValSize = 0 ; if ( value == null ) { return attrValSize ; } if ( value . getB ( ) != null ) { final ByteBuffer b = value . getB ( ) ; attrValSize += b . remaining ( ) ; } else if ( value . getS ( ) != null ) { final String s = value . getS ( ) ; attrValSize += s . getBytes ( UTF8 ) . length ; } else if ( value . getN ( ) != null ) { attrValSize += MAX_NUMBER_OF_BYTES_FOR_NUMBER ; } else if ( value . getBS ( ) != null ) { final List < ByteBuffer > bs = value . getBS ( ) ; for ( ByteBuffer b : bs ) { if ( b != null ) { attrValSize += b . remaining ( ) ; } } } else if ( value . getSS ( ) != null ) { final List < String > ss = value . getSS ( ) ; for ( String s : ss ) { if ( s != null ) { attrValSize += s . getBytes ( UTF8 ) . length ; } } } else if ( value . getNS ( ) != null ) { final List < String > ns = value . getNS ( ) ; for ( String n : ns ) { if ( n != null ) { attrValSize += MAX_NUMBER_OF_BYTES_FOR_NUMBER ; } } } else if ( value . getBOOL ( ) != null ) { attrValSize += 1 ; } else if ( value . getNULL ( ) != null ) { attrValSize += 1 ; } else if ( value . getM ( ) != null ) { for ( Map . Entry < String , AttributeValue > entry : value . getM ( ) . entrySet ( ) ) { attrValSize += entry . getKey ( ) . getBytes ( UTF8 ) . length ; attrValSize += calculateAttributeSizeInBytes ( entry . getValue ( ) ) ; attrValSize += BASE_LOGICAL_SIZE_OF_NESTED_TYPES ; } attrValSize += LOGICAL_SIZE_OF_EMPTY_DOCUMENT ; } else if ( value . getL ( ) != null ) { final List < AttributeValue > list = value . getL ( ) ; for ( Integer i = 0 ; i < list . size ( ) ; i ++ ) { attrValSize += calculateAttributeSizeInBytes ( list . get ( i ) ) ; attrValSize += BASE_LOGICAL_SIZE_OF_NESTED_TYPES ; } attrValSize += LOGICAL_SIZE_OF_EMPTY_DOCUMENT ; } return attrValSize ; }
|
Calculate attribute value size
|
569
|
private void readObject ( ObjectInputStream ois ) { try { ois . defaultReadObject ( ) ; pauseLock = new ReentrantLock ( ) ; pauseLock . newCondition ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }
|
makes findbugs happy but unused
|
570
|
public < T > void addListenerIfPending ( final Class < T > clazz , final Object requestCacheKey , final PendingRequestListener < T > requestListener ) { addListenerIfPending ( clazz , requestCacheKey , ( RequestListener < T > ) requestListener ) ; }
|
Add listener to a pending request if it exists . If no such request exists this method calls onRequestNotFound on the listener . If a request identified by clazz and requestCacheKey it will receive an additional listener .
|
571
|
public < T > void execute ( final CachedSpiceRequest < T > cachedSpiceRequest , final RequestListener < T > requestListener ) { addRequestListenerToListOfRequestListeners ( cachedSpiceRequest , requestListener ) ; Ln . d ( "adding request to request queue" ) ; this . requestQueue . add ( cachedSpiceRequest ) ; }
|
Execute a request put the result in cache and register listeners to notify when request is finished .
|
572
|
public < U , T extends U > void putInCache ( final Class < U > clazz , final Object requestCacheKey , final T data , RequestListener < U > listener ) { @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) final SpiceRequest < U > spiceRequest = new SpiceRequest ( clazz ) { public U loadDataFromNetwork ( ) throws Exception { return data ; } } ; CachedSpiceRequest < U > cachedSpiceRequest = new CachedSpiceRequest < U > ( spiceRequest , requestCacheKey , DurationInMillis . ALWAYS_EXPIRED ) ; cachedSpiceRequest . setOffline ( true ) ; execute ( cachedSpiceRequest , listener ) ; }
|
Adds some data to the cache asynchronously .
|
573
|
public < T > void cancel ( final Class < T > clazz , final Object requestCacheKey ) { final SpiceRequest < T > request = new SpiceRequest < T > ( clazz ) { public T loadDataFromNetwork ( ) throws Exception { return null ; } } ; final CachedSpiceRequest < T > cachedSpiceRequest = new CachedSpiceRequest < T > ( request , requestCacheKey , DurationInMillis . ALWAYS_EXPIRED ) ; cachedSpiceRequest . setProcessable ( false ) ; cachedSpiceRequest . setOffline ( true ) ; cachedSpiceRequest . cancel ( ) ; execute ( cachedSpiceRequest , null ) ; }
|
Cancel a pending request if it exists . If no such request exists this method does nothing . If a request identified by clazz and requestCacheKey exists it will be cancelled and its associated listeners will get notified . This method is asynchronous .
|
574
|
protected void dontNotifyAnyRequestListenersInternal ( ) { lockSendRequestsToService . lock ( ) ; try { if ( spiceService == null ) { return ; } synchronized ( mapRequestToLaunchToRequestListener ) { if ( ! mapRequestToLaunchToRequestListener . isEmpty ( ) ) { for ( final CachedSpiceRequest < ? > cachedSpiceRequest : mapRequestToLaunchToRequestListener . keySet ( ) ) { final Set < RequestListener < ? > > setRequestListeners = mapRequestToLaunchToRequestListener . get ( cachedSpiceRequest ) ; if ( setRequestListeners != null ) { Ln . d ( "Removing listeners of request to launch : " + cachedSpiceRequest . toString ( ) + " : " + setRequestListeners . size ( ) ) ; spiceService . dontNotifyRequestListenersForRequest ( cachedSpiceRequest , setRequestListeners ) ; } } } mapRequestToLaunchToRequestListener . clear ( ) ; } Ln . v ( "Cleared listeners of all requests to launch" ) ; removeListenersOfAllPendingCachedRequests ( ) ; } catch ( final InterruptedException e ) { Ln . e ( e , "Interrupted while removing listeners." ) ; } finally { lockSendRequestsToService . unlock ( ) ; } }
|
Remove all listeners of requests . All requests that have not been yet passed to the service will see their of listeners cleaned . For all requests that have been passed to the service we ask the service to remove their listeners .
|
575
|
private void removeListenersOfAllPendingCachedRequests ( ) throws InterruptedException { synchronized ( mapPendingRequestToRequestListener ) { if ( ! mapPendingRequestToRequestListener . isEmpty ( ) ) { for ( final CachedSpiceRequest < ? > cachedSpiceRequest : mapPendingRequestToRequestListener . keySet ( ) ) { final Set < RequestListener < ? > > setRequestListeners = mapPendingRequestToRequestListener . get ( cachedSpiceRequest ) ; if ( setRequestListeners != null ) { Ln . d ( "Removing listeners of pending request : " + cachedSpiceRequest . toString ( ) + " : " + setRequestListeners . size ( ) ) ; spiceService . dontNotifyRequestListenersForRequest ( cachedSpiceRequest , setRequestListeners ) ; } } mapPendingRequestToRequestListener . clear ( ) ; } } Ln . v ( "Cleared listeners of all pending requests" ) ; }
|
Asynchronously ask service to remove all listeners of pending requests .
|
576
|
public Future < Boolean > isDataInCache ( Class < ? > clazz , final Object cacheKey , long cacheExpiryDuration ) throws CacheCreationException { return executeCommand ( new IsDataInCacheCommand ( this , clazz , cacheKey , cacheExpiryDuration ) ) ; }
|
Tests whether some data is present in cache or not .
|
577
|
public Future < Date > getDateOfDataInCache ( Class < ? > clazz , final Object cacheKey ) throws CacheCreationException { return executeCommand ( new GetDateOfDataInCacheCommand ( this , clazz , cacheKey ) ) ; }
|
Returns the last date of storage of a given data into the cache .
|
578
|
public void dumpState ( ) { executorService . execute ( new Runnable ( ) { public void run ( ) { lockSendRequestsToService . lock ( ) ; try { final StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder . append ( "[SpiceManager : " ) ; stringBuilder . append ( "Requests to be launched : \n" ) ; dumpMap ( stringBuilder , mapRequestToLaunchToRequestListener ) ; stringBuilder . append ( "Pending requests : \n" ) ; dumpMap ( stringBuilder , mapPendingRequestToRequestListener ) ; stringBuilder . append ( ']' ) ; waitForServiceToBeBound ( ) ; if ( spiceService == null ) { return ; } spiceService . dumpState ( ) ; } catch ( final InterruptedException e ) { Ln . e ( e , "Interrupted while waiting for acquiring service." ) ; } finally { lockSendRequestsToService . unlock ( ) ; } } } ) ; }
|
Dumps request processor state .
|
579
|
public void notifyObserversOfRequestFailure ( CachedSpiceRequest < ? > request ) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext ( ) ; requestProcessingContext . setExecutionThread ( Thread . currentThread ( ) ) ; post ( new RequestFailedNotifier ( request , spiceServiceListenerList , requestProcessingContext ) ) ; }
|
Notify interested observers that the request failed .
|
580
|
public < T > void notifyObserversOfRequestSuccess ( CachedSpiceRequest < T > request ) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext ( ) ; requestProcessingContext . setExecutionThread ( Thread . currentThread ( ) ) ; post ( new RequestSucceededNotifier < T > ( request , spiceServiceListenerList , requestProcessingContext ) ) ; }
|
Notify interested observers that the request succeeded .
|
581
|
public void notifyObserversOfRequestCancellation ( CachedSpiceRequest < ? > request ) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext ( ) ; requestProcessingContext . setExecutionThread ( Thread . currentThread ( ) ) ; post ( new RequestCancelledNotifier ( request , spiceServiceListenerList , requestProcessingContext ) ) ; }
|
Notify interested observers that the request was cancelled .
|
582
|
public void notifyObserversOfRequestProgress ( CachedSpiceRequest < ? > request , RequestProgress requestProgress ) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext ( ) ; requestProcessingContext . setExecutionThread ( Thread . currentThread ( ) ) ; requestProcessingContext . setRequestProgress ( requestProgress ) ; post ( new RequestProgressNotifier ( request , spiceServiceListenerList , requestProcessingContext ) ) ; }
|
Notify interested observers of request progress .
|
583
|
public void notifyObserversOfRequestProcessed ( CachedSpiceRequest < ? > request , Set < RequestListener < ? > > requestListeners ) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext ( ) ; requestProcessingContext . setExecutionThread ( Thread . currentThread ( ) ) ; requestProcessingContext . setRequestListeners ( requestListeners ) ; post ( new RequestProcessedNotifier ( request , spiceServiceListenerList , requestProcessingContext ) ) ; }
|
Notify interested observers of request completion .
|
584
|
protected void post ( Runnable runnable ) { Ln . d ( "Message queue is " + messageQueue ) ; if ( messageQueue == null ) { return ; } messageQueue . postAtTime ( runnable , SystemClock . uptimeMillis ( ) ) ; }
|
Add the request update to the observer message queue .
|
585
|
public void setCacheFolder ( File cacheFolder ) throws CacheCreationException { if ( cacheFolder == null ) { cacheFolder = new File ( getApplication ( ) . getCacheDir ( ) , DEFAULT_ROOT_CACHE_DIR ) ; } synchronized ( cacheFolder . getAbsolutePath ( ) . intern ( ) ) { if ( ! cacheFolder . exists ( ) && ! cacheFolder . mkdirs ( ) ) { throw new CacheCreationException ( "The cache folder " + cacheFolder . getAbsolutePath ( ) + " could not be created." ) ; } } this . cacheFolder = cacheFolder ; }
|
Set the cacheFolder to use .
|
586
|
public Future < ? > submit ( Runnable task ) { if ( task == null ) { throw new NullPointerException ( ) ; } RunnableFuture < Object > ftask = newTaskFor ( task , null ) ; execute ( ftask ) ; return ftask ; }
|
form JDK 1 . 6 to ensure backward compatibility
|
587
|
public KafkaProducer < String , String > createStringProducer ( Properties overrideConfig ) { return createProducer ( new StringSerializer ( ) , new StringSerializer ( ) , overrideConfig ) ; }
|
Create a producer that writes String keys and values
|
588
|
public < K , V > void produce ( String topic , KafkaProducer < K , V > producer , Map < K , V > data ) { data . forEach ( ( k , v ) -> producer . send ( new ProducerRecord < > ( topic , k , v ) ) ) ; producer . flush ( ) ; }
|
Produce data to the specified topic
|
589
|
public void produceStrings ( String topic , String ... values ) { try ( KafkaProducer < String , String > producer = createStringProducer ( ) ) { Map < String , String > data = Arrays . stream ( values ) . collect ( Collectors . toMap ( k -> String . valueOf ( k . hashCode ( ) ) , Function . identity ( ) ) ) ; produce ( topic , producer , data ) ; } }
|
Convenience method to produce a set of strings to the specified topic
|
590
|
public KafkaConsumer < String , String > createStringConsumer ( Properties overrideConfig ) { return createConsumer ( new StringDeserializer ( ) , new StringDeserializer ( ) , overrideConfig ) ; }
|
Create a consumer that reads strings
|
591
|
public < K , V > ListenableFuture < List < ConsumerRecord < K , V > > > consume ( String topic , KafkaConsumer < K , V > consumer , int numMessagesToConsume ) { consumer . subscribe ( Lists . newArrayList ( topic ) ) ; ListeningExecutorService executor = MoreExecutors . listeningDecorator ( Executors . newSingleThreadExecutor ( ) ) ; return executor . submit ( new RecordConsumer < > ( numMessagesToConsume , consumer ) ) ; }
|
Attempt to consume the specified number of messages
|
592
|
public ListenableFuture < List < String > > consumeStrings ( String topic , int numMessagesToConsume ) { KafkaConsumer < String , String > consumer = createStringConsumer ( ) ; ListenableFuture < List < ConsumerRecord < String , String > > > records = consume ( topic , consumer , numMessagesToConsume ) ; return Futures . transform ( records , this :: extractValues , MoreExecutors . directExecutor ( ) ) ; }
|
Consume specified number of string messages
|
593
|
public static EphemeralKafkaBroker create ( int kafkaPort , int zookeeperPort , Properties overrideBrokerProperties ) { return new EphemeralKafkaBroker ( kafkaPort , zookeeperPort , overrideBrokerProperties ) ; }
|
Create a new ephemeral Kafka broker with the specified broker port Zookeeper port and config overrides .
|
594
|
public Optional < String > getLogDir ( ) { return brokerStarted ? Optional . of ( kafkaLogDir . toString ( ) ) : Optional . empty ( ) ; }
|
Get the path to the Kafka log directory
|
595
|
public Optional < String > getZookeeperConnectString ( ) { return brokerStarted ? Optional . of ( zookeeper . getConnectString ( ) ) : Optional . empty ( ) ; }
|
Get the current Zookeeper connection string
|
596
|
public Optional < String > getBrokerList ( ) { return brokerStarted ? Optional . of ( LOCALHOST + ":" + kafkaPort ) : Optional . empty ( ) ; }
|
Get the current broker list string
|
597
|
public static < E extends Exception , E2 extends Exception > void parse ( final Connection conn , final String sql , final long offset , final long count , final int processThreadNum , final int queueSize , final Try . Consumer < Object [ ] , E > rowParser , final Try . Runnable < E2 > onComplete ) throws UncheckedSQLException , E , E2 { PreparedStatement stmt = null ; try { stmt = prepareStatement ( conn , sql ) ; stmt . setFetchSize ( 200 ) ; parse ( stmt , offset , count , processThreadNum , queueSize , rowParser , onComplete ) ; } catch ( SQLException e ) { throw new UncheckedSQLException ( e ) ; } finally { closeQuietly ( stmt ) ; } }
|
Parse the ResultSet obtained by executing query with the specified Connection and sql .
|
598
|
public static < E extends Exception , E2 extends Exception > void parse ( final PreparedStatement stmt , final long offset , final long count , final int processThreadNum , final int queueSize , final Try . Consumer < Object [ ] , E > rowParser , final Try . Runnable < E2 > onComplete ) throws UncheckedSQLException , E , E2 { ResultSet rs = null ; try { rs = stmt . executeQuery ( ) ; parse ( rs , offset , count , processThreadNum , queueSize , rowParser , onComplete ) ; } catch ( SQLException e ) { throw new UncheckedSQLException ( e ) ; } finally { closeQuietly ( rs ) ; } }
|
Parse the ResultSet obtained by executing query with the specified PreparedStatement .
|
599
|
public static < E extends Exception , E2 extends Exception > void parse ( final ResultSet rs , long offset , long count , final int processThreadNum , final int queueSize , final Try . Consumer < Object [ ] , E > rowParser , final Try . Runnable < E2 > onComplete ) throws UncheckedSQLException , E , E2 { final Iterator < Object [ ] > iter = new ObjIterator < Object [ ] > ( ) { private final JdbcUtil . BiRecordGetter < Object [ ] , RuntimeException > biFunc = BiRecordGetter . TO_ARRAY ; private List < String > columnLabels = null ; private boolean hasNext ; public boolean hasNext ( ) { if ( hasNext == false ) { try { hasNext = rs . next ( ) ; } catch ( SQLException e ) { throw new UncheckedSQLException ( e ) ; } } return hasNext ; } public Object [ ] next ( ) { if ( hasNext ( ) == false ) { throw new NoSuchElementException ( ) ; } hasNext = false ; try { if ( columnLabels == null ) { columnLabels = JdbcUtil . getColumnLabelList ( rs ) ; } return biFunc . apply ( rs , columnLabels ) ; } catch ( SQLException e ) { throw new UncheckedSQLException ( e ) ; } } } ; Iterables . parse ( iter , offset , count , processThreadNum , queueSize , rowParser , onComplete ) ; }
|
Parse the ResultSet .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.