idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
150,300
public void deleteEmailAlias ( String emailAliasID ) { URL url = EMAIL_ALIAS_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) , this . getID ( ) , emailAliasID ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , url , "DELETE" ) ; BoxAPIResponse response = request . send ( ) ; response . disconnect ( ) ; }
Deletes an email alias from this user s account .
102
11
150,301
public Collection < EmailAlias > getEmailAliases ( ) { URL url = EMAIL_ALIASES_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) , this . getID ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , url , "GET" ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; int totalCount = responseJSON . get ( "total_count" ) . asInt ( ) ; Collection < EmailAlias > emailAliases = new ArrayList < EmailAlias > ( totalCount ) ; JsonArray entries = responseJSON . get ( "entries" ) . asArray ( ) ; for ( JsonValue value : entries ) { JsonObject emailAliasJSON = value . asObject ( ) ; emailAliases . add ( new EmailAlias ( emailAliasJSON ) ) ; } return emailAliases ; }
Gets a collection of all the email aliases for this user .
225
13
150,302
public void delete ( boolean notifyUser , boolean force ) { String queryString = new QueryStringBuilder ( ) . appendParam ( "notify" , String . valueOf ( notifyUser ) ) . appendParam ( "force" , String . valueOf ( force ) ) . toString ( ) ; URL url = USER_URL_TEMPLATE . buildWithQuery ( this . getAPI ( ) . getBaseURL ( ) , queryString , this . getID ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , url , "DELETE" ) ; BoxAPIResponse response = request . send ( ) ; response . disconnect ( ) ; }
Deletes a user from an enterprise account .
149
9
150,303
public InputStream getAvatar ( ) { URL url = USER_AVATAR_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) , this . getID ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , url , "GET" ) ; BoxAPIResponse response = request . send ( ) ; return response . getBody ( ) ; }
Retrieves the avatar of a user as an InputStream .
93
13
150,304
public static Info inviteUserToEnterprise ( BoxAPIConnection api , String userLogin , String enterpriseID ) { URL url = INVITE_CREATION_URL_TEMPLATE . build ( api . getBaseURL ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( api , url , "POST" ) ; JsonObject body = new JsonObject ( ) ; JsonObject enterprise = new JsonObject ( ) ; enterprise . add ( "id" , enterpriseID ) ; body . add ( "enterprise" , enterprise ) ; JsonObject actionableBy = new JsonObject ( ) ; actionableBy . add ( "login" , userLogin ) ; body . add ( "actionable_by" , actionableBy ) ; request . setBody ( body ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxInvite invite = new BoxInvite ( api , responseJSON . get ( "id" ) . asString ( ) ) ; return invite . new Info ( responseJSON ) ; }
Invite a user to an enterprise .
248
8
150,305
private static JsonArray toJsonArray ( Collection < String > values ) { JsonArray array = new JsonArray ( ) ; for ( String value : values ) { array . add ( value ) ; } return array ; }
Helper function to create JsonArray from collection .
49
10
150,306
@ Override public void setBody ( String body ) { super . setBody ( body ) ; this . jsonValue = JsonValue . readFrom ( body ) ; }
Sets the body of this request to a given JSON string .
36
13
150,307
public Info changeMessage ( String newMessage ) { Info newInfo = new Info ( ) ; newInfo . setMessage ( newMessage ) ; URL url = COMMENT_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) , this . getID ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( this . getAPI ( ) , url , "PUT" ) ; request . setBody ( newInfo . getPendingChanges ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject jsonResponse = JsonObject . readFrom ( response . getJSON ( ) ) ; return new Info ( jsonResponse ) ; }
Changes the message of this comment .
151
7
150,308
public BoxComment . Info reply ( String message ) { JsonObject itemJSON = new JsonObject ( ) ; itemJSON . add ( "type" , "comment" ) ; itemJSON . add ( "id" , this . getID ( ) ) ; JsonObject requestJSON = new JsonObject ( ) ; requestJSON . add ( "item" , itemJSON ) ; if ( BoxComment . messageContainsMention ( message ) ) { requestJSON . add ( "tagged_message" , message ) ; } else { requestJSON . add ( "message" , message ) ; } URL url = ADD_COMMENT_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( this . getAPI ( ) , url , "POST" ) ; request . setBody ( requestJSON . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxComment addedComment = new BoxComment ( this . getAPI ( ) , responseJSON . get ( "id" ) . asString ( ) ) ; return addedComment . new Info ( responseJSON ) ; }
Replies to this comment with another message .
277
9
150,309
public void put ( String key , String value ) { synchronized ( this . cache ) { this . cache . put ( key , value ) ; } }
Add an entry to the cache .
31
7
150,310
public URL buildWithQuery ( String base , String queryString , Object ... values ) { String urlString = String . format ( base + this . template , values ) + queryString ; URL url = null ; try { url = new URL ( urlString ) ; } catch ( MalformedURLException e ) { assert false : "An invalid URL template indicates a bug in the SDK." ; } return url ; }
Build a URL with Query String and URL Parameters .
87
10
150,311
public BoxFileUploadSessionPart uploadPart ( InputStream stream , long offset , int partSize , long totalSizeOfFile ) { URL uploadPartURL = this . sessionInfo . getSessionEndpoints ( ) . getUploadPartEndpoint ( ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , uploadPartURL , HttpMethod . PUT ) ; request . addHeader ( HttpHeaders . CONTENT_TYPE , ContentType . APPLICATION_OCTET_STREAM ) ; //Read the partSize bytes from the stream byte [ ] bytes = new byte [ partSize ] ; try { stream . read ( bytes ) ; } catch ( IOException ioe ) { throw new BoxAPIException ( "Reading data from stream failed." , ioe ) ; } return this . uploadPart ( bytes , offset , partSize , totalSizeOfFile ) ; }
Uploads chunk of a stream to an open upload session .
188
12
150,312
public BoxFileUploadSessionPart uploadPart ( byte [ ] data , long offset , int partSize , long totalSizeOfFile ) { URL uploadPartURL = this . sessionInfo . getSessionEndpoints ( ) . getUploadPartEndpoint ( ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , uploadPartURL , HttpMethod . PUT ) ; request . addHeader ( HttpHeaders . CONTENT_TYPE , ContentType . APPLICATION_OCTET_STREAM ) ; MessageDigest digestInstance = null ; try { digestInstance = MessageDigest . getInstance ( DIGEST_ALGORITHM_SHA1 ) ; } catch ( NoSuchAlgorithmException ae ) { throw new BoxAPIException ( "Digest algorithm not found" , ae ) ; } //Creates the digest using SHA1 algorithm. Then encodes the bytes using Base64. byte [ ] digestBytes = digestInstance . digest ( data ) ; String digest = Base64 . encode ( digestBytes ) ; request . addHeader ( HttpHeaders . DIGEST , DIGEST_HEADER_PREFIX_SHA + digest ) ; //Content-Range: bytes offset-part/totalSize request . addHeader ( HttpHeaders . CONTENT_RANGE , "bytes " + offset + "-" + ( offset + partSize - 1 ) + "/" + totalSizeOfFile ) ; //Creates the body request . setBody ( new ByteArrayInputStream ( data ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject jsonObject = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxFileUploadSessionPart part = new BoxFileUploadSessionPart ( ( JsonObject ) jsonObject . get ( "part" ) ) ; return part ; }
Uploads bytes to an open upload session .
397
9
150,313
public BoxFileUploadSessionPartList listParts ( int offset , int limit ) { URL listPartsURL = this . sessionInfo . getSessionEndpoints ( ) . getListPartsEndpoint ( ) ; URLTemplate template = new URLTemplate ( listPartsURL . toString ( ) ) ; QueryStringBuilder builder = new QueryStringBuilder ( ) ; builder . appendParam ( OFFSET_QUERY_STRING , offset ) ; String queryString = builder . appendParam ( LIMIT_QUERY_STRING , limit ) . toString ( ) ; //Template is initalized with the full URL. So empty string for the path. URL url = template . buildWithQuery ( "" , queryString ) ; BoxJSONRequest request = new BoxJSONRequest ( this . getAPI ( ) , url , HttpMethod . GET ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject jsonObject = JsonObject . readFrom ( response . getJSON ( ) ) ; return new BoxFileUploadSessionPartList ( jsonObject ) ; }
Returns a list of all parts that have been uploaded to an upload session .
226
15
150,314
public BoxFile . Info commit ( String digest , List < BoxFileUploadSessionPart > parts , Map < String , String > attributes , String ifMatch , String ifNoneMatch ) { URL commitURL = this . sessionInfo . getSessionEndpoints ( ) . getCommitEndpoint ( ) ; BoxJSONRequest request = new BoxJSONRequest ( this . getAPI ( ) , commitURL , HttpMethod . POST ) ; request . addHeader ( HttpHeaders . DIGEST , DIGEST_HEADER_PREFIX_SHA + digest ) ; request . addHeader ( HttpHeaders . CONTENT_TYPE , ContentType . APPLICATION_JSON ) ; if ( ifMatch != null ) { request . addHeader ( HttpHeaders . IF_MATCH , ifMatch ) ; } if ( ifNoneMatch != null ) { request . addHeader ( HttpHeaders . IF_NONE_MATCH , ifNoneMatch ) ; } //Creates the body of the request String body = this . getCommitBody ( parts , attributes ) ; request . setBody ( body ) ; BoxAPIResponse response = request . send ( ) ; //Retry the commit operation after the given number of seconds if the HTTP response code is 202. if ( response . getResponseCode ( ) == 202 ) { String retryInterval = response . getHeaderField ( "retry-after" ) ; if ( retryInterval != null ) { try { Thread . sleep ( new Integer ( retryInterval ) * 1000 ) ; } catch ( InterruptedException ie ) { throw new BoxAPIException ( "Commit retry failed. " , ie ) ; } return this . commit ( digest , parts , attributes , ifMatch , ifNoneMatch ) ; } } if ( response instanceof BoxJSONResponse ) { //Create the file instance from the response return this . getFile ( ( BoxJSONResponse ) response ) ; } else { throw new BoxAPIException ( "Commit response content type is not application/json. The response code : " + response . getResponseCode ( ) ) ; } }
Commit an upload session after all parts have been uploaded creating the new file or the version .
448
19
150,315
public BoxFileUploadSession . Info getStatus ( ) { URL statusURL = this . sessionInfo . getSessionEndpoints ( ) . getStatusEndpoint ( ) ; BoxJSONRequest request = new BoxJSONRequest ( this . getAPI ( ) , statusURL , HttpMethod . GET ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject jsonObject = JsonObject . readFrom ( response . getJSON ( ) ) ; this . sessionInfo . update ( jsonObject ) ; return this . sessionInfo ; }
Get the status of the upload session . It contains the number of parts that are processed so far the total number of parts required for the commit and expiration date and time of the upload session .
117
38
150,316
public void abort ( ) { URL abortURL = this . sessionInfo . getSessionEndpoints ( ) . getAbortEndpoint ( ) ; BoxJSONRequest request = new BoxJSONRequest ( this . getAPI ( ) , abortURL , HttpMethod . DELETE ) ; request . send ( ) ; }
Abort an upload session discarding any chunks that were uploaded to it .
66
15
150,317
public String getHeaderField ( String fieldName ) { // headers map is null for all regular response calls except when made as a batch request if ( this . headers == null ) { if ( this . connection != null ) { return this . connection . getHeaderField ( fieldName ) ; } else { return null ; } } else { return this . headers . get ( fieldName ) ; } }
Gets the value of the given header field .
82
10
150,318
private InputStream getErrorStream ( ) { InputStream errorStream = this . connection . getErrorStream ( ) ; if ( errorStream != null ) { final String contentEncoding = this . connection . getContentEncoding ( ) ; if ( contentEncoding != null && contentEncoding . equalsIgnoreCase ( "gzip" ) ) { try { errorStream = new GZIPInputStream ( errorStream ) ; } catch ( IOException e ) { // just return the error stream as is } } } return errorStream ; }
Returns the response error stream handling the case when it contains gzipped data .
113
16
150,319
public void updateInfo ( BoxWebLink . Info info ) { URL url = WEB_LINK_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) , this . getID ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( this . getAPI ( ) , url , "PUT" ) ; request . setBody ( info . getPendingChanges ( ) ) ; String body = info . getPendingChanges ( ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject jsonObject = JsonObject . readFrom ( response . getJSON ( ) ) ; info . update ( jsonObject ) ; }
Updates the information about this weblink with any info fields that have been modified locally .
149
19
150,320
public static BoxStoragePolicyAssignment . Info create ( BoxAPIConnection api , String policyID , String userID ) { URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE . build ( api . getBaseURL ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( api , url , HttpMethod . POST ) ; JsonObject requestJSON = new JsonObject ( ) . add ( "storage_policy" , new JsonObject ( ) . add ( "type" , "storage_policy" ) . add ( "id" , policyID ) ) . add ( "assigned_to" , new JsonObject ( ) . add ( "type" , "user" ) . add ( "id" , userID ) ) ; request . setBody ( requestJSON . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment ( api , responseJSON . get ( "id" ) . asString ( ) ) ; return storagePolicyAssignment . new Info ( responseJSON ) ; }
Create a BoxStoragePolicyAssignment for a BoxStoragePolicy .
271
13
150,321
public static BoxStoragePolicyAssignment . Info getAssignmentForTarget ( final BoxAPIConnection api , String resolvedForType , String resolvedForID ) { QueryStringBuilder builder = new QueryStringBuilder ( ) ; builder . appendParam ( "resolved_for_type" , resolvedForType ) . appendParam ( "resolved_for_id" , resolvedForID ) ; URL url = STORAGE_POLICY_ASSIGNMENT_URL_TEMPLATE . buildWithQuery ( api . getBaseURL ( ) , builder . toString ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( api , url , HttpMethod . GET ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; BoxStoragePolicyAssignment storagePolicyAssignment = new BoxStoragePolicyAssignment ( api , response . getJsonObject ( ) . get ( "entries" ) . asArray ( ) . get ( 0 ) . asObject ( ) . get ( "id" ) . asString ( ) ) ; BoxStoragePolicyAssignment . Info info = storagePolicyAssignment . new Info ( response . getJsonObject ( ) . get ( "entries" ) . asArray ( ) . get ( 0 ) . asObject ( ) ) ; return info ; }
Returns a BoxStoragePolicyAssignment information .
279
9
150,322
public void delete ( ) { URL url = STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) , this . getID ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( this . getAPI ( ) , url , HttpMethod . DELETE ) ; request . send ( ) ; }
Deletes this BoxStoragePolicyAssignment .
90
9
150,323
public static Iterable < BoxGroup . Info > getAllGroupsByName ( final BoxAPIConnection api , String name ) { final QueryStringBuilder builder = new QueryStringBuilder ( ) ; if ( name == null || name . trim ( ) . isEmpty ( ) ) { throw new BoxAPIException ( "Searching groups by name requires a non NULL or non empty name" ) ; } else { builder . appendParam ( "name" , name ) ; } return new Iterable < BoxGroup . Info > ( ) { public Iterator < BoxGroup . Info > iterator ( ) { URL url = GROUPS_URL_TEMPLATE . buildWithQuery ( api . getBaseURL ( ) , builder . toString ( ) ) ; return new BoxGroupIterator ( api , url ) ; } } ; }
Gets an iterable of all the groups in the enterprise that are starting with the given name string .
175
21
150,324
public Collection < BoxGroupMembership . Info > getMemberships ( ) { final BoxAPIConnection api = this . getAPI ( ) ; final String groupID = this . getID ( ) ; Iterable < BoxGroupMembership . Info > iter = new Iterable < BoxGroupMembership . Info > ( ) { public Iterator < BoxGroupMembership . Info > iterator ( ) { URL url = MEMBERSHIPS_URL_TEMPLATE . build ( api . getBaseURL ( ) , groupID ) ; return new BoxGroupMembershipIterator ( api , url ) ; } } ; // We need to iterate all results because this method must return a Collection. This logic should be removed in // the next major version, and instead return the Iterable directly. Collection < BoxGroupMembership . Info > memberships = new ArrayList < BoxGroupMembership . Info > ( ) ; for ( BoxGroupMembership . Info membership : iter ) { memberships . add ( membership ) ; } return memberships ; }
Gets information about all of the group memberships for this group . Does not support paging .
220
20
150,325
public BoxGroupMembership . Info addMembership ( BoxUser user , Role role ) { BoxAPIConnection api = this . getAPI ( ) ; JsonObject requestJSON = new JsonObject ( ) ; requestJSON . add ( "user" , new JsonObject ( ) . add ( "id" , user . getID ( ) ) ) ; requestJSON . add ( "group" , new JsonObject ( ) . add ( "id" , this . getID ( ) ) ) ; if ( role != null ) { requestJSON . add ( "role" , role . toJSONString ( ) ) ; } URL url = ADD_MEMBERSHIP_URL_TEMPLATE . build ( api . getBaseURL ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( api , url , "POST" ) ; request . setBody ( requestJSON . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxGroupMembership membership = new BoxGroupMembership ( api , responseJSON . get ( "id" ) . asString ( ) ) ; return membership . new Info ( responseJSON ) ; }
Adds a member to this group with the specified role .
276
11
150,326
public static BoxTermsOfService . Info create ( BoxAPIConnection api , BoxTermsOfService . TermsOfServiceStatus termsOfServiceStatus , BoxTermsOfService . TermsOfServiceType termsOfServiceType , String text ) { URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE . build ( api . getBaseURL ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( api , url , "POST" ) ; JsonObject requestJSON = new JsonObject ( ) . add ( "status" , termsOfServiceStatus . toString ( ) ) . add ( "tos_type" , termsOfServiceType . toString ( ) ) . add ( "text" , text ) ; request . setBody ( requestJSON . toString ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; BoxTermsOfService createdTermsOfServices = new BoxTermsOfService ( api , responseJSON . get ( "id" ) . asString ( ) ) ; return createdTermsOfServices . new Info ( responseJSON ) ; }
Creates a new Terms of Services .
265
8
150,327
public static List < BoxTermsOfService . Info > getAllTermsOfServices ( final BoxAPIConnection api , BoxTermsOfService . TermsOfServiceType termsOfServiceType ) { QueryStringBuilder builder = new QueryStringBuilder ( ) ; if ( termsOfServiceType != null ) { builder . appendParam ( "tos_type" , termsOfServiceType . toString ( ) ) ; } URL url = ALL_TERMS_OF_SERVICES_URL_TEMPLATE . buildWithQuery ( api . getBaseURL ( ) , builder . toString ( ) ) ; BoxAPIRequest request = new BoxAPIRequest ( api , url , "GET" ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; int totalCount = responseJSON . get ( "total_count" ) . asInt ( ) ; List < BoxTermsOfService . Info > termsOfServices = new ArrayList < BoxTermsOfService . Info > ( totalCount ) ; JsonArray entries = responseJSON . get ( "entries" ) . asArray ( ) ; for ( JsonValue value : entries ) { JsonObject termsOfServiceJSON = value . asObject ( ) ; BoxTermsOfService termsOfService = new BoxTermsOfService ( api , termsOfServiceJSON . get ( "id" ) . asString ( ) ) ; BoxTermsOfService . Info info = termsOfService . new Info ( termsOfServiceJSON ) ; termsOfServices . add ( info ) ; } return termsOfServices ; }
Retrieves a list of Terms of Service that belong to your Enterprise as an Iterable .
359
19
150,328
public static Map < String , Map < String , Metadata > > parseAndPopulateMetadataMap ( JsonObject jsonObject ) { Map < String , Map < String , Metadata > > metadataMap = new HashMap < String , Map < String , Metadata > > ( ) ; //Parse all templates for ( JsonObject . Member templateMember : jsonObject ) { if ( templateMember . getValue ( ) . isNull ( ) ) { continue ; } else { String templateName = templateMember . getName ( ) ; Map < String , Metadata > scopeMap = metadataMap . get ( templateName ) ; //If templateName doesn't yet exist then create an entry with empty scope map if ( scopeMap == null ) { scopeMap = new HashMap < String , Metadata > ( ) ; metadataMap . put ( templateName , scopeMap ) ; } //Parse all scopes in a template for ( JsonObject . Member scopeMember : templateMember . getValue ( ) . asObject ( ) ) { String scope = scopeMember . getName ( ) ; Metadata metadataObject = new Metadata ( scopeMember . getValue ( ) . asObject ( ) ) ; scopeMap . put ( scope , metadataObject ) ; } } } return metadataMap ; }
Creates a map of metadata from json .
270
9
150,329
public static List < Representation > parseRepresentations ( JsonObject jsonObject ) { List < Representation > representations = new ArrayList < Representation > ( ) ; for ( JsonValue representationJson : jsonObject . get ( "entries" ) . asArray ( ) ) { Representation representation = new Representation ( representationJson . asObject ( ) ) ; representations . add ( representation ) ; } return representations ; }
Parse representations from a file object response .
91
9
150,330
public void updateInfo ( BoxTermsOfServiceUserStatus . Info info ) { URL url = TERMS_OF_SERVICE_USER_STATUSES_TEMPLATE . build ( this . getAPI ( ) . getBaseURL ( ) , this . getID ( ) ) ; BoxJSONRequest request = new BoxJSONRequest ( this . getAPI ( ) , url , "PUT" ) ; request . setBody ( info . getPendingChanges ( ) ) ; BoxJSONResponse response = ( BoxJSONResponse ) request . send ( ) ; JsonObject responseJSON = JsonObject . readFrom ( response . getJSON ( ) ) ; info . update ( responseJSON ) ; }
Updates the information about the user status for this terms of service with any info fields that have been modified locally .
147
23
150,331
public List < BoxAPIResponse > execute ( List < BoxAPIRequest > requests ) { this . prepareRequest ( requests ) ; BoxJSONResponse batchResponse = ( BoxJSONResponse ) send ( ) ; return this . parseResponse ( batchResponse ) ; }
Execute a set of API calls as batch request .
54
11
150,332
protected void prepareRequest ( List < BoxAPIRequest > requests ) { JsonObject body = new JsonObject ( ) ; JsonArray requestsJSONArray = new JsonArray ( ) ; for ( BoxAPIRequest request : requests ) { JsonObject batchRequest = new JsonObject ( ) ; batchRequest . add ( "method" , request . getMethod ( ) ) ; batchRequest . add ( "relative_url" , request . getUrl ( ) . toString ( ) . substring ( this . api . getBaseURL ( ) . length ( ) - 1 ) ) ; //If the actual request has a JSON body then add it to vatch request if ( request instanceof BoxJSONRequest ) { BoxJSONRequest jsonRequest = ( BoxJSONRequest ) request ; batchRequest . add ( "body" , jsonRequest . getBodyAsJsonValue ( ) ) ; } //Add any headers that are in the request, except Authorization if ( request . getHeaders ( ) != null ) { JsonObject batchRequestHeaders = new JsonObject ( ) ; for ( RequestHeader header : request . getHeaders ( ) ) { if ( header . getKey ( ) != null && ! header . getKey ( ) . isEmpty ( ) && ! HttpHeaders . AUTHORIZATION . equals ( header . getKey ( ) ) ) { batchRequestHeaders . add ( header . getKey ( ) , header . getValue ( ) ) ; } } batchRequest . add ( "headers" , batchRequestHeaders ) ; } //Add the request to array requestsJSONArray . add ( batchRequest ) ; } //Add the requests array to body body . add ( "requests" , requestsJSONArray ) ; super . setBody ( body ) ; }
Prepare a batch api request using list of individual reuests .
373
14
150,333
protected List < BoxAPIResponse > parseResponse ( BoxJSONResponse batchResponse ) { JsonObject responseJSON = JsonObject . readFrom ( batchResponse . getJSON ( ) ) ; List < BoxAPIResponse > responses = new ArrayList < BoxAPIResponse > ( ) ; Iterator < JsonValue > responseIterator = responseJSON . get ( "responses" ) . asArray ( ) . iterator ( ) ; while ( responseIterator . hasNext ( ) ) { JsonObject jsonResponse = responseIterator . next ( ) . asObject ( ) ; BoxAPIResponse response = null ; //Gather headers Map < String , String > responseHeaders = new HashMap < String , String > ( ) ; if ( jsonResponse . get ( "headers" ) != null ) { JsonObject batchResponseHeadersObject = jsonResponse . get ( "headers" ) . asObject ( ) ; for ( JsonObject . Member member : batchResponseHeadersObject ) { String headerName = member . getName ( ) ; String headerValue = member . getValue ( ) . asString ( ) ; responseHeaders . put ( headerName , headerValue ) ; } } // Construct a BoxAPIResponse when response is null, or a BoxJSONResponse when there's a response // (not anticipating any other response as per current APIs. // Ideally we should do it based on response header) if ( jsonResponse . get ( "response" ) == null || jsonResponse . get ( "response" ) . isNull ( ) ) { response = new BoxAPIResponse ( jsonResponse . get ( "status" ) . asInt ( ) , responseHeaders ) ; } else { response = new BoxJSONResponse ( jsonResponse . get ( "status" ) . asInt ( ) , responseHeaders , jsonResponse . get ( "response" ) . asObject ( ) ) ; } responses . add ( response ) ; } return responses ; }
Parses btch api response to create a list of BoxAPIResponse objects .
417
19
150,334
private static void generateJson ( CellScanner cellScanner , Function < Bytes , String > encoder , PrintStream out ) throws JsonIOException { Gson gson = new GsonBuilder ( ) . serializeNulls ( ) . setDateFormat ( DateFormat . LONG ) . setFieldNamingPolicy ( FieldNamingPolicy . LOWER_CASE_WITH_UNDERSCORES ) . setVersion ( 1.0 ) . create ( ) ; Map < String , String > json = new LinkedHashMap <> ( ) ; for ( RowColumnValue rcv : cellScanner ) { json . put ( FLUO_ROW , encoder . apply ( rcv . getRow ( ) ) ) ; json . put ( FLUO_COLUMN_FAMILY , encoder . apply ( rcv . getColumn ( ) . getFamily ( ) ) ) ; json . put ( FLUO_COLUMN_QUALIFIER , encoder . apply ( rcv . getColumn ( ) . getQualifier ( ) ) ) ; json . put ( FLUO_COLUMN_VISIBILITY , encoder . apply ( rcv . getColumn ( ) . getVisibility ( ) ) ) ; json . put ( FLUO_VALUE , encoder . apply ( rcv . getValue ( ) ) ) ; gson . toJson ( json , out ) ; out . append ( "\n" ) ; if ( out . checkError ( ) ) { break ; } } out . flush ( ) ; }
Generate JSON format as result of the scan .
337
10
150,335
public static TxInfo getTransactionInfo ( Environment env , Bytes prow , Column pcol , long startTs ) { // TODO ensure primary is visible IteratorSetting is = new IteratorSetting ( 10 , RollbackCheckIterator . class ) ; RollbackCheckIterator . setLocktime ( is , startTs ) ; Entry < Key , Value > entry = ColumnUtil . checkColumn ( env , is , prow , pcol ) ; TxInfo txInfo = new TxInfo ( ) ; if ( entry == null ) { txInfo . status = TxStatus . UNKNOWN ; return txInfo ; } ColumnType colType = ColumnType . from ( entry . getKey ( ) ) ; long ts = entry . getKey ( ) . getTimestamp ( ) & ColumnConstants . TIMESTAMP_MASK ; switch ( colType ) { case LOCK : { if ( ts == startTs ) { txInfo . status = TxStatus . LOCKED ; txInfo . lockValue = entry . getValue ( ) . get ( ) ; } else { txInfo . status = TxStatus . UNKNOWN ; // locked by another tx } break ; } case DEL_LOCK : { DelLockValue dlv = new DelLockValue ( entry . getValue ( ) . get ( ) ) ; if ( ts != startTs ) { // expect this to always be false, must be a bug in the iterator throw new IllegalStateException ( prow + " " + pcol + " (" + ts + " != " + startTs + ") " ) ; } if ( dlv . isRollback ( ) ) { txInfo . status = TxStatus . ROLLED_BACK ; } else { txInfo . status = TxStatus . COMMITTED ; txInfo . commitTs = dlv . getCommitTimestamp ( ) ; } break ; } case WRITE : { long timePtr = WriteValue . getTimestamp ( entry . getValue ( ) . get ( ) ) ; if ( timePtr != startTs ) { // expect this to always be false, must be a bug in the iterator throw new IllegalStateException ( prow + " " + pcol + " (" + timePtr + " != " + startTs + ") " ) ; } txInfo . status = TxStatus . COMMITTED ; txInfo . commitTs = ts ; break ; } default : throw new IllegalStateException ( "unexpected col type returned " + colType ) ; } return txInfo ; }
determine the what state a transaction is in by inspecting the primary column
529
15
150,336
public static boolean oracleExists ( CuratorFramework curator ) { boolean exists = false ; try { exists = curator . checkExists ( ) . forPath ( ZookeeperPath . ORACLE_SERVER ) != null && ! curator . getChildren ( ) . forPath ( ZookeeperPath . ORACLE_SERVER ) . isEmpty ( ) ; } catch ( Exception nne ) { if ( nne instanceof KeeperException . NoNodeException ) { // you'll do nothing } else { throw new RuntimeException ( nne ) ; } } return exists ; }
Checks to see if an Oracle Server exists .
124
10
150,337
public void waitForAsyncFlush ( ) { long numAdded = asyncBatchesAdded . get ( ) ; synchronized ( this ) { while ( numAdded > asyncBatchesProcessed ) { try { wait ( ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } } } }
waits for all async mutations that were added before this was called to be flushed . Does not wait for async mutations added after call .
67
27
150,338
public static Span exact ( Bytes row ) { Objects . requireNonNull ( row ) ; return new Span ( row , true , row , true ) ; }
Creates a span that covers an exact row
33
9
150,339
public static Span exact ( CharSequence row ) { Objects . requireNonNull ( row ) ; return exact ( Bytes . of ( row ) ) ; }
Creates a Span that covers an exact row . String parameters will be encoded as UTF - 8
33
19
150,340
public static Span prefix ( Bytes rowPrefix ) { Objects . requireNonNull ( rowPrefix ) ; Bytes fp = followingPrefix ( rowPrefix ) ; return new Span ( rowPrefix , true , fp == null ? Bytes . EMPTY : fp , false ) ; }
Returns a Span that covers all rows beginning with a prefix .
65
12
150,341
public static Span prefix ( CharSequence rowPrefix ) { Objects . requireNonNull ( rowPrefix ) ; return prefix ( Bytes . of ( rowPrefix ) ) ; }
Returns a Span that covers all rows beginning with a prefix String parameters will be encoded as UTF - 8
39
20
150,342
public void load ( InputStream in ) { try { PropertiesConfiguration config = new PropertiesConfiguration ( ) ; // disabled to prevent accumulo classpath value from being shortened config . setDelimiterParsingDisabled ( true ) ; config . load ( in ) ; ( ( CompositeConfiguration ) internalConfig ) . addConfiguration ( config ) ; } catch ( ConfigurationException e ) { throw new IllegalArgumentException ( e ) ; } }
Loads configuration from InputStream . Later loads have lower priority .
90
13
150,343
public void load ( File file ) { try { PropertiesConfiguration config = new PropertiesConfiguration ( ) ; // disabled to prevent accumulo classpath value from being shortened config . setDelimiterParsingDisabled ( true ) ; config . load ( file ) ; ( ( CompositeConfiguration ) internalConfig ) . addConfiguration ( config ) ; } catch ( ConfigurationException e ) { throw new IllegalArgumentException ( e ) ; } }
Loads configuration from File . Later loads have lower priority .
89
12
150,344
public static long getTxInfoCacheWeight ( FluoConfiguration conf ) { long size = conf . getLong ( TX_INFO_CACHE_WEIGHT , TX_INFO_CACHE_WEIGHT_DEFAULT ) ; if ( size <= 0 ) { throw new IllegalArgumentException ( "Cache size must be positive for " + TX_INFO_CACHE_WEIGHT ) ; } return size ; }
Gets the txinfo cache weight
89
7
150,345
public static long getVisibilityCacheWeight ( FluoConfiguration conf ) { long size = conf . getLong ( VISIBILITY_CACHE_WEIGHT , VISIBILITY_CACHE_WEIGHT_DEFAULT ) ; if ( size <= 0 ) { throw new IllegalArgumentException ( "Cache size must be positive for " + VISIBILITY_CACHE_WEIGHT ) ; } return size ; }
Gets the visibility cache weight
89
6
150,346
public static String parseServers ( String zookeepers ) { int slashIndex = zookeepers . indexOf ( "/" ) ; if ( slashIndex != - 1 ) { return zookeepers . substring ( 0 , slashIndex ) ; } return zookeepers ; }
Parses server section of Zookeeper connection string
62
11
150,347
public static String parseRoot ( String zookeepers ) { int slashIndex = zookeepers . indexOf ( "/" ) ; if ( slashIndex != - 1 ) { return zookeepers . substring ( slashIndex ) . trim ( ) ; } return "/" ; }
Parses chroot section of Zookeeper connection string
61
12
150,348
public static long getGcTimestamp ( String zookeepers ) { ZooKeeper zk = null ; try { zk = new ZooKeeper ( zookeepers , 30000 , null ) ; // wait until zookeeper is connected long start = System . currentTimeMillis ( ) ; while ( ! zk . getState ( ) . isConnected ( ) && System . currentTimeMillis ( ) - start < 30000 ) { Uninterruptibles . sleepUninterruptibly ( 10 , TimeUnit . MILLISECONDS ) ; } byte [ ] d = zk . getData ( ZookeeperPath . ORACLE_GC_TIMESTAMP , false , null ) ; return LongUtil . fromByteArray ( d ) ; } catch ( KeeperException | InterruptedException | IOException e ) { log . warn ( "Failed to get oldest timestamp of Oracle from Zookeeper" , e ) ; return OLDEST_POSSIBLE ; } finally { if ( zk != null ) { try { zk . close ( ) ; } catch ( InterruptedException e ) { log . error ( "Failed to close zookeeper client" , e ) ; } } } }
Retrieves the GC timestamp set by the Oracle from zookeeper
262
14
150,349
public static Bytes toBytes ( Text t ) { return Bytes . of ( t . getBytes ( ) , 0 , t . getLength ( ) ) ; }
Convert from Hadoop Text to Bytes
35
10
150,350
public static void configure ( Job conf , SimpleConfiguration config ) { try { FluoConfiguration fconfig = new FluoConfiguration ( config ) ; try ( Environment env = new Environment ( fconfig ) ) { long ts = env . getSharedResources ( ) . getTimestampTracker ( ) . allocateTimestamp ( ) . getTxTimestamp ( ) ; conf . getConfiguration ( ) . setLong ( TIMESTAMP_CONF_KEY , ts ) ; ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; config . save ( baos ) ; conf . getConfiguration ( ) . set ( PROPS_CONF_KEY , new String ( baos . toByteArray ( ) , StandardCharsets . UTF_8 ) ) ; AccumuloInputFormat . setZooKeeperInstance ( conf , fconfig . getAccumuloInstance ( ) , fconfig . getAccumuloZookeepers ( ) ) ; AccumuloInputFormat . setConnectorInfo ( conf , fconfig . getAccumuloUser ( ) , new PasswordToken ( fconfig . getAccumuloPassword ( ) ) ) ; AccumuloInputFormat . setInputTableName ( conf , env . getTable ( ) ) ; AccumuloInputFormat . setScanAuthorizations ( conf , env . getAuthorizations ( ) ) ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Configure properties needed to connect to a Fluo application
302
11
150,351
private void readUnread ( CommitData cd , Consumer < Entry < Key , Value > > locksSeen ) { // TODO make async // TODO need to keep track of ranges read (not ranges passed in, but actual data read... user // may not iterate over entire range Map < Bytes , Set < Column > > columnsToRead = new HashMap <> ( ) ; for ( Entry < Bytes , Set < Column > > entry : cd . getRejected ( ) . entrySet ( ) ) { Set < Column > rowColsRead = columnsRead . get ( entry . getKey ( ) ) ; if ( rowColsRead == null ) { columnsToRead . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } else { HashSet < Column > colsToRead = new HashSet <> ( entry . getValue ( ) ) ; colsToRead . removeAll ( rowColsRead ) ; if ( ! colsToRead . isEmpty ( ) ) { columnsToRead . put ( entry . getKey ( ) , colsToRead ) ; } } } for ( Entry < Bytes , Set < Column > > entry : columnsToRead . entrySet ( ) ) { getImpl ( entry . getKey ( ) , entry . getValue ( ) , locksSeen ) ; } }
This function helps handle the following case
287
7
150,352
public byte byteAt ( int i ) { if ( i < 0 ) { throw new IndexOutOfBoundsException ( "i < 0, " + i ) ; } if ( i >= length ) { throw new IndexOutOfBoundsException ( "i >= length, " + i + " >= " + length ) ; } return data [ offset + i ] ; }
Gets a byte within this sequence of bytes
78
9
150,353
public Bytes subSequence ( int start , int end ) { if ( start > end || start < 0 || end > length ) { throw new IndexOutOfBoundsException ( "Bad start and/end start = " + start + " end=" + end + " offset=" + offset + " length=" + length ) ; } return new Bytes ( data , offset + start , end - start ) ; }
Returns a portion of the Bytes object
87
8
150,354
public byte [ ] toArray ( ) { byte [ ] copy = new byte [ length ] ; System . arraycopy ( data , offset , copy , 0 , length ) ; return copy ; }
Returns a byte array containing a copy of the bytes
40
10
150,355
public boolean contentEquals ( byte [ ] bytes , int offset , int len ) { Preconditions . checkArgument ( len >= 0 && offset >= 0 && offset + len <= bytes . length ) ; return contentEqualsUnchecked ( bytes , offset , len ) ; }
Returns true if this Bytes object equals another . This method checks it s arguments .
58
17
150,356
private boolean contentEqualsUnchecked ( byte [ ] bytes , int offset , int len ) { if ( length != len ) { return false ; } return compareToUnchecked ( bytes , offset , len ) == 0 ; }
Returns true if this Bytes object equals another . This method doesn t check it s arguments .
47
19
150,357
public static final Bytes of ( byte [ ] array ) { Objects . requireNonNull ( array ) ; if ( array . length == 0 ) { return EMPTY ; } byte [ ] copy = new byte [ array . length ] ; System . arraycopy ( array , 0 , copy , 0 , array . length ) ; return new Bytes ( copy ) ; }
Creates a Bytes object by copying the data of the given byte array
76
15
150,358
public static final Bytes of ( byte [ ] data , int offset , int length ) { Objects . requireNonNull ( data ) ; if ( length == 0 ) { return EMPTY ; } byte [ ] copy = new byte [ length ] ; System . arraycopy ( data , offset , copy , 0 , length ) ; return new Bytes ( copy ) ; }
Creates a Bytes object by copying the data of a subsequence of the given byte array
76
19
150,359
public static final Bytes of ( ByteBuffer bb ) { Objects . requireNonNull ( bb ) ; if ( bb . remaining ( ) == 0 ) { return EMPTY ; } byte [ ] data ; if ( bb . hasArray ( ) ) { data = Arrays . copyOfRange ( bb . array ( ) , bb . position ( ) + bb . arrayOffset ( ) , bb . limit ( ) + bb . arrayOffset ( ) ) ; } else { data = new byte [ bb . remaining ( ) ] ; // duplicate so that it does not change position bb . duplicate ( ) . get ( data ) ; } return new Bytes ( data ) ; }
Creates a Bytes object by copying the data of the given ByteBuffer .
150
16
150,360
public static final Bytes of ( CharSequence cs ) { if ( cs instanceof String ) { return of ( ( String ) cs ) ; } Objects . requireNonNull ( cs ) ; if ( cs . length ( ) == 0 ) { return EMPTY ; } ByteBuffer bb = StandardCharsets . UTF_8 . encode ( CharBuffer . wrap ( cs ) ) ; if ( bb . hasArray ( ) ) { // this byte buffer has never escaped so can use its byte array directly return new Bytes ( bb . array ( ) , bb . position ( ) + bb . arrayOffset ( ) , bb . limit ( ) ) ; } else { byte [ ] data = new byte [ bb . remaining ( ) ] ; bb . get ( data ) ; return new Bytes ( data ) ; } }
Creates a Bytes object by copying the data of the CharSequence and encoding it using UTF - 8 .
178
23
150,361
public static final Bytes of ( String s ) { Objects . requireNonNull ( s ) ; if ( s . isEmpty ( ) ) { return EMPTY ; } byte [ ] data = s . getBytes ( StandardCharsets . UTF_8 ) ; return new Bytes ( data , s ) ; }
Creates a Bytes object by copying the value of the given String
66
14
150,362
public static final Bytes of ( String s , Charset c ) { Objects . requireNonNull ( s ) ; Objects . requireNonNull ( c ) ; if ( s . isEmpty ( ) ) { return EMPTY ; } byte [ ] data = s . getBytes ( c ) ; return new Bytes ( data ) ; }
Creates a Bytes object by copying the value of the given String with a given charset
71
19
150,363
public boolean startsWith ( Bytes prefix ) { Objects . requireNonNull ( prefix , "startWith(Bytes prefix) cannot have null parameter" ) ; if ( prefix . length > this . length ) { return false ; } else { int end = this . offset + prefix . length ; for ( int i = this . offset , j = prefix . offset ; i < end ; i ++ , j ++ ) { if ( this . data [ i ] != prefix . data [ j ] ) { return false ; } } } return true ; }
Checks if this has the passed prefix
113
8
150,364
public boolean endsWith ( Bytes suffix ) { Objects . requireNonNull ( suffix , "endsWith(Bytes suffix) cannot have null parameter" ) ; int startOffset = this . length - suffix . length ; if ( startOffset < 0 ) { return false ; } else { int end = startOffset + this . offset + suffix . length ; for ( int i = startOffset + this . offset , j = suffix . offset ; i < end ; i ++ , j ++ ) { if ( this . data [ i ] != suffix . data [ j ] ) { return false ; } } } return true ; }
Checks if this has the passed suffix
128
8
150,365
public void copyTo ( int start , int end , byte [ ] dest , int destPos ) { // this.subSequence(start, end).copyTo(dest, destPos) would allocate another Bytes object arraycopy ( start , dest , destPos , end - start ) ; }
Copy a subsequence of Bytes to specific byte array . Uses the specified offset in the dest byte array to start the copy .
62
26
150,366
public void copyTo ( ColumnBuffer dest , LongPredicate timestampTest ) { dest . clear ( ) ; if ( key != null ) { dest . key = new Key ( key ) ; } for ( int i = 0 ; i < timeStamps . size ( ) ; i ++ ) { long time = timeStamps . get ( i ) ; if ( timestampTest . test ( time ) ) { dest . add ( time , values . get ( i ) ) ; } } }
Clears the dest ColumnBuffer and inserts all entries in dest where the timestamp passes the timestampTest .
101
20
150,367
public static AccumuloClient getClient ( FluoConfiguration config ) { return Accumulo . newClient ( ) . to ( config . getAccumuloInstance ( ) , config . getAccumuloZookeepers ( ) ) . as ( config . getAccumuloUser ( ) , config . getAccumuloPassword ( ) ) . build ( ) ; }
Creates Accumulo connector given FluoConfiguration
80
10
150,368
public static byte [ ] encode ( byte [ ] ba , int offset , long v ) { ba [ offset + 0 ] = ( byte ) ( v >>> 56 ) ; ba [ offset + 1 ] = ( byte ) ( v >>> 48 ) ; ba [ offset + 2 ] = ( byte ) ( v >>> 40 ) ; ba [ offset + 3 ] = ( byte ) ( v >>> 32 ) ; ba [ offset + 4 ] = ( byte ) ( v >>> 24 ) ; ba [ offset + 5 ] = ( byte ) ( v >>> 16 ) ; ba [ offset + 6 ] = ( byte ) ( v >>> 8 ) ; ba [ offset + 7 ] = ( byte ) ( v >>> 0 ) ; return ba ; }
Encode a long into a byte array at an offset
151
11
150,369
public static long decodeLong ( byte [ ] ba , int offset ) { return ( ( ( ( long ) ba [ offset + 0 ] << 56 ) + ( ( long ) ( ba [ offset + 1 ] & 255 ) << 48 ) + ( ( long ) ( ba [ offset + 2 ] & 255 ) << 40 ) + ( ( long ) ( ba [ offset + 3 ] & 255 ) << 32 ) + ( ( long ) ( ba [ offset + 4 ] & 255 ) << 24 ) + ( ( ba [ offset + 5 ] & 255 ) << 16 ) + ( ( ba [ offset + 6 ] & 255 ) << 8 ) + ( ( ba [ offset + 7 ] & 255 ) << 0 ) ) ) ; }
Decode long from byte array at offset
152
8
150,370
public static byte [ ] concat ( Bytes ... listOfBytes ) { int offset = 0 ; int size = 0 ; for ( Bytes b : listOfBytes ) { size += b . length ( ) + checkVlen ( b . length ( ) ) ; } byte [ ] data = new byte [ size ] ; for ( Bytes b : listOfBytes ) { offset = writeVint ( data , offset , b . length ( ) ) ; b . copyTo ( 0 , b . length ( ) , data , offset ) ; offset += b . length ( ) ; } return data ; }
Concatenates of list of Bytes objects to create a byte array
127
15
150,371
public static int writeVint ( byte [ ] dest , int offset , int i ) { if ( i >= - 112 && i <= 127 ) { dest [ offset ++ ] = ( byte ) i ; } else { int len = - 112 ; if ( i < 0 ) { i ^= - 1L ; // take one's complement' len = - 120 ; } long tmp = i ; while ( tmp != 0 ) { tmp = tmp >> 8 ; len -- ; } dest [ offset ++ ] = ( byte ) len ; len = ( len < - 120 ) ? - ( len + 120 ) : - ( len + 112 ) ; for ( int idx = len ; idx != 0 ; idx -- ) { int shiftbits = ( idx - 1 ) * 8 ; long mask = 0xFF L << shiftbits ; dest [ offset ++ ] = ( byte ) ( ( i & mask ) >> shiftbits ) ; } } return offset ; }
Writes a vInt directly to a byte array
201
10
150,372
public static int checkVlen ( int i ) { int count = 0 ; if ( i >= - 112 && i <= 127 ) { return 1 ; } else { int len = - 112 ; if ( i < 0 ) { i ^= - 1L ; // take one's complement' len = - 120 ; } long tmp = i ; while ( tmp != 0 ) { tmp = tmp >> 8 ; len -- ; } count ++ ; len = ( len < - 120 ) ? - ( len + 120 ) : - ( len + 112 ) ; while ( len != 0 ) { count ++ ; len -- ; } return count ; } }
Determines the number bytes required to store a variable length
133
12
150,373
private ResourceReport getResourceReport ( TwillController controller , int maxWaitMs ) { ResourceReport report = controller . getResourceReport ( ) ; int elapsed = 0 ; while ( report == null ) { report = controller . getResourceReport ( ) ; try { Thread . sleep ( 500 ) ; } catch ( InterruptedException e ) { throw new IllegalStateException ( e ) ; } elapsed += 500 ; if ( ( maxWaitMs != - 1 ) && ( elapsed > maxWaitMs ) ) { String msg = String . format ( "Exceeded max wait time to retrieve ResourceReport from Twill." + " Elapsed time = %s ms" , elapsed ) ; log . error ( msg ) ; throw new IllegalStateException ( msg ) ; } if ( ( elapsed % 10000 ) == 0 ) { log . info ( "Waiting for ResourceReport from Twill. Elapsed time = {} ms" , elapsed ) ; } } return report ; }
Attempts to retrieves ResourceReport until maxWaitMs time is reached . Set maxWaitMs to - 1 to retry forever .
199
26
150,374
private void verifyApplicationName ( String name ) { if ( name == null ) { throw new IllegalArgumentException ( "Application name cannot be null" ) ; } if ( name . isEmpty ( ) ) { throw new IllegalArgumentException ( "Application name length must be > 0" ) ; } String reason = null ; char [ ] chars = name . toCharArray ( ) ; char c ; for ( int i = 0 ; i < chars . length ; i ++ ) { c = chars [ i ] ; if ( c == 0 ) { reason = "null character not allowed @" + i ; break ; } else if ( c == ' ' || c == ' ' || c == ' ' ) { reason = "invalid character '" + c + "'" ; break ; } else if ( c > ' ' && c <= ' ' || c >= ' ' && c <= ' ' || c >= ' ' && c <= ' ' || c >= ' ' && c <= ' ' ) { reason = "invalid character @" + i ; break ; } } if ( reason != null ) { throw new IllegalArgumentException ( "Invalid application name \"" + name + "\" caused by " + reason ) ; } }
Verifies application name . Avoids characters that Zookeeper does not like in nodes & Hadoop does not like in HDFS paths .
259
29
150,375
@ Deprecated public FluoConfiguration addObservers ( Iterable < ObserverSpecification > observers ) { int next = getNextObserverId ( ) ; for ( ObserverSpecification oconf : observers ) { addObserver ( oconf , next ++ ) ; } return this ; }
Adds multiple observers using unique integer prefixes for each .
60
11
150,376
@ Deprecated public FluoConfiguration clearObservers ( ) { Iterator < String > iter1 = getKeys ( OBSERVER_PREFIX . substring ( 0 , OBSERVER_PREFIX . length ( ) - 1 ) ) ; while ( iter1 . hasNext ( ) ) { String key = iter1 . next ( ) ; clearProperty ( key ) ; } return this ; }
Removes any configured observers .
88
6
150,377
public void print ( ) { Iterator < String > iter = getKeys ( ) ; while ( iter . hasNext ( ) ) { String key = iter . next ( ) ; log . info ( key + " = " + getRawString ( key ) ) ; } }
Logs all properties
57
4
150,378
public boolean hasRequiredClientProps ( ) { boolean valid = true ; valid &= verifyStringPropSet ( CONNECTION_APPLICATION_NAME_PROP , CLIENT_APPLICATION_NAME_PROP ) ; valid &= verifyStringPropSet ( ACCUMULO_USER_PROP , CLIENT_ACCUMULO_USER_PROP ) ; valid &= verifyStringPropSet ( ACCUMULO_PASSWORD_PROP , CLIENT_ACCUMULO_PASSWORD_PROP ) ; valid &= verifyStringPropSet ( ACCUMULO_INSTANCE_PROP , CLIENT_ACCUMULO_INSTANCE_PROP ) ; return valid ; }
Returns true if required properties for FluoClient are set
151
11
150,379
public boolean hasRequiredAdminProps ( ) { boolean valid = true ; valid &= hasRequiredClientProps ( ) ; valid &= verifyStringPropSet ( ACCUMULO_TABLE_PROP , ADMIN_ACCUMULO_TABLE_PROP ) ; return valid ; }
Returns true if required properties for FluoAdmin are set
62
11
150,380
public boolean hasRequiredMiniFluoProps ( ) { boolean valid = true ; if ( getMiniStartAccumulo ( ) ) { // ensure that client properties are not set since we are using MiniAccumulo valid &= verifyStringPropNotSet ( ACCUMULO_USER_PROP , CLIENT_ACCUMULO_USER_PROP ) ; valid &= verifyStringPropNotSet ( ACCUMULO_PASSWORD_PROP , CLIENT_ACCUMULO_PASSWORD_PROP ) ; valid &= verifyStringPropNotSet ( ACCUMULO_INSTANCE_PROP , CLIENT_ACCUMULO_INSTANCE_PROP ) ; valid &= verifyStringPropNotSet ( ACCUMULO_ZOOKEEPERS_PROP , CLIENT_ACCUMULO_ZOOKEEPERS_PROP ) ; valid &= verifyStringPropNotSet ( CONNECTION_ZOOKEEPERS_PROP , CLIENT_ZOOKEEPER_CONNECT_PROP ) ; if ( valid == false ) { log . error ( "Client properties should not be set in your configuration if MiniFluo is " + "configured to start its own accumulo (indicated by fluo.mini.start.accumulo being " + "set to true)" ) ; } } else { valid &= hasRequiredClientProps ( ) ; valid &= hasRequiredAdminProps ( ) ; valid &= hasRequiredOracleProps ( ) ; valid &= hasRequiredWorkerProps ( ) ; } return valid ; }
Returns true if required properties for MiniFluo are set
337
12
150,381
public SimpleConfiguration getClientConfiguration ( ) { SimpleConfiguration clientConfig = new SimpleConfiguration ( ) ; Iterator < String > iter = getKeys ( ) ; while ( iter . hasNext ( ) ) { String key = iter . next ( ) ; if ( key . startsWith ( CONNECTION_PREFIX ) || key . startsWith ( ACCUMULO_PREFIX ) || key . startsWith ( CLIENT_PREFIX ) ) { clientConfig . setProperty ( key , getRawString ( key ) ) ; } } return clientConfig ; }
Returns a SimpleConfiguration clientConfig with properties set from this configuration
118
12
150,382
public static void setDefaultConfiguration ( SimpleConfiguration config ) { config . setProperty ( CONNECTION_ZOOKEEPERS_PROP , CONNECTION_ZOOKEEPERS_DEFAULT ) ; config . setProperty ( CONNECTION_ZOOKEEPER_TIMEOUT_PROP , CONNECTION_ZOOKEEPER_TIMEOUT_DEFAULT ) ; config . setProperty ( DFS_ROOT_PROP , DFS_ROOT_DEFAULT ) ; config . setProperty ( ACCUMULO_ZOOKEEPERS_PROP , ACCUMULO_ZOOKEEPERS_DEFAULT ) ; config . setProperty ( WORKER_NUM_THREADS_PROP , WORKER_NUM_THREADS_DEFAULT ) ; config . setProperty ( TRANSACTION_ROLLBACK_TIME_PROP , TRANSACTION_ROLLBACK_TIME_DEFAULT ) ; config . setProperty ( LOADER_NUM_THREADS_PROP , LOADER_NUM_THREADS_DEFAULT ) ; config . setProperty ( LOADER_QUEUE_SIZE_PROP , LOADER_QUEUE_SIZE_DEFAULT ) ; config . setProperty ( MINI_START_ACCUMULO_PROP , MINI_START_ACCUMULO_DEFAULT ) ; config . setProperty ( MINI_DATA_DIR_PROP , MINI_DATA_DIR_DEFAULT ) ; }
Sets all Fluo properties to their default in the given configuration . NOTE - some properties do not have defaults and will not be set .
319
28
150,383
public static void configure ( Job conf , SimpleConfiguration props ) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; props . save ( baos ) ; conf . getConfiguration ( ) . set ( PROPS_CONF_KEY , new String ( baos . toByteArray ( ) , StandardCharsets . UTF_8 ) ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Call this method to initialize the Fluo connection props
95
10
150,384
public Stamp allocateTimestamp ( ) { synchronized ( this ) { Preconditions . checkState ( ! closed , "tracker closed " ) ; if ( node == null ) { Preconditions . checkState ( allocationsInProgress == 0 , "expected allocationsInProgress == 0 when node == null" ) ; Preconditions . checkState ( ! updatingZk , "unexpected concurrent ZK update" ) ; createZkNode ( getTimestamp ( ) . getTxTimestamp ( ) ) ; } allocationsInProgress ++ ; } try { Stamp ts = getTimestamp ( ) ; synchronized ( this ) { timestamps . add ( ts . getTxTimestamp ( ) ) ; } return ts ; } catch ( RuntimeException re ) { synchronized ( this ) { allocationsInProgress -- ; } throw re ; } }
Allocate a timestamp
172
4
150,385
private static boolean waitTillNoNotifications ( Environment env , TableRange range ) throws TableNotFoundException { boolean sawNotifications = false ; long retryTime = MIN_SLEEP_MS ; log . debug ( "Scanning tablet {} for notifications" , range ) ; long start = System . currentTimeMillis ( ) ; while ( hasNotifications ( env , range ) ) { sawNotifications = true ; long sleepTime = Math . max ( System . currentTimeMillis ( ) - start , retryTime ) ; log . debug ( "Tablet {} had notfications, will rescan in {}ms" , range , sleepTime ) ; UtilWaitThread . sleep ( sleepTime ) ; retryTime = Math . min ( MAX_SLEEP_MS , ( long ) ( retryTime * 1.5 ) ) ; start = System . currentTimeMillis ( ) ; } return sawNotifications ; }
Wait until a range has no notifications .
199
8
150,386
private static void waitUntilFinished ( FluoConfiguration config ) { try ( Environment env = new Environment ( config ) ) { List < TableRange > ranges = getRanges ( env ) ; outer : while ( true ) { long ts1 = env . getSharedResources ( ) . getOracleClient ( ) . getStamp ( ) . getTxTimestamp ( ) ; for ( TableRange range : ranges ) { boolean sawNotifications = waitTillNoNotifications ( env , range ) ; if ( sawNotifications ) { ranges = getRanges ( env ) ; // This range had notifications. Processing those notifications may have created // notifications in previously scanned ranges, so start over. continue outer ; } } long ts2 = env . getSharedResources ( ) . getOracleClient ( ) . getStamp ( ) . getTxTimestamp ( ) ; // Check to ensure the Oracle issued no timestamps during the scan for notifications. if ( ts2 - ts1 == 1 ) { break ; } } } catch ( Exception e ) { log . error ( "An exception was thrown -" , e ) ; System . exit ( - 1 ) ; } }
Wait until a scan of the table completes without seeing notifications AND without the Oracle issuing any timestamps during the scan .
245
24
150,387
public static Range toRange ( Span span ) { return new Range ( toKey ( span . getStart ( ) ) , span . isStartInclusive ( ) , toKey ( span . getEnd ( ) ) , span . isEndInclusive ( ) ) ; }
Converts a Fluo Span to Accumulo Range
56
11
150,388
public static Key toKey ( RowColumn rc ) { if ( ( rc == null ) || ( rc . getRow ( ) . equals ( Bytes . EMPTY ) ) ) { return null ; } Text row = ByteUtil . toText ( rc . getRow ( ) ) ; if ( ( rc . getColumn ( ) . equals ( Column . EMPTY ) ) || ! rc . getColumn ( ) . isFamilySet ( ) ) { return new Key ( row ) ; } Text cf = ByteUtil . toText ( rc . getColumn ( ) . getFamily ( ) ) ; if ( ! rc . getColumn ( ) . isQualifierSet ( ) ) { return new Key ( row , cf ) ; } Text cq = ByteUtil . toText ( rc . getColumn ( ) . getQualifier ( ) ) ; if ( ! rc . getColumn ( ) . isVisibilitySet ( ) ) { return new Key ( row , cf , cq ) ; } Text cv = ByteUtil . toText ( rc . getColumn ( ) . getVisibility ( ) ) ; return new Key ( row , cf , cq , cv ) ; }
Converts from a Fluo RowColumn to a Accumulo Key
250
14
150,389
public static Span toSpan ( Range range ) { return new Span ( toRowColumn ( range . getStartKey ( ) ) , range . isStartKeyInclusive ( ) , toRowColumn ( range . getEndKey ( ) ) , range . isEndKeyInclusive ( ) ) ; }
Converts an Accumulo Range to a Fluo Span
63
12
150,390
public static RowColumn toRowColumn ( Key key ) { if ( key == null ) { return RowColumn . EMPTY ; } if ( ( key . getRow ( ) == null ) || key . getRow ( ) . getLength ( ) == 0 ) { return RowColumn . EMPTY ; } Bytes row = ByteUtil . toBytes ( key . getRow ( ) ) ; if ( ( key . getColumnFamily ( ) == null ) || key . getColumnFamily ( ) . getLength ( ) == 0 ) { return new RowColumn ( row ) ; } Bytes cf = ByteUtil . toBytes ( key . getColumnFamily ( ) ) ; if ( ( key . getColumnQualifier ( ) == null ) || key . getColumnQualifier ( ) . getLength ( ) == 0 ) { return new RowColumn ( row , new Column ( cf ) ) ; } Bytes cq = ByteUtil . toBytes ( key . getColumnQualifier ( ) ) ; if ( ( key . getColumnVisibility ( ) == null ) || key . getColumnVisibility ( ) . getLength ( ) == 0 ) { return new RowColumn ( row , new Column ( cf , cq ) ) ; } Bytes cv = ByteUtil . toBytes ( key . getColumnVisibility ( ) ) ; return new RowColumn ( row , new Column ( cf , cq , cv ) ) ; }
Converts from an Accumulo Key to a Fluo RowColumn
303
14
150,391
public FluoKeyValueGenerator set ( RowColumnValue rcv ) { setRow ( rcv . getRow ( ) ) ; setColumn ( rcv . getColumn ( ) ) ; setValue ( rcv . getValue ( ) ) ; return this ; }
Set the row column and value
56
6
150,392
public FluoKeyValue [ ] getKeyValues ( ) { FluoKeyValue kv = keyVals [ 0 ] ; kv . setKey ( new Key ( row , fam , qual , vis , ColumnType . WRITE . encode ( 1 ) ) ) ; kv . getValue ( ) . set ( WriteValue . encode ( 0 , false , false ) ) ; kv = keyVals [ 1 ] ; kv . setKey ( new Key ( row , fam , qual , vis , ColumnType . DATA . encode ( 0 ) ) ) ; kv . getValue ( ) . set ( val ) ; return keyVals ; }
Translates the Fluo row column and value set into the persistent format that is stored in Accumulo .
137
23
150,393
public RowColumn following ( ) { if ( row . equals ( Bytes . EMPTY ) ) { return RowColumn . EMPTY ; } else if ( col . equals ( Column . EMPTY ) ) { return new RowColumn ( followingBytes ( row ) ) ; } else if ( ! col . isQualifierSet ( ) ) { return new RowColumn ( row , new Column ( followingBytes ( col . getFamily ( ) ) ) ) ; } else if ( ! col . isVisibilitySet ( ) ) { return new RowColumn ( row , new Column ( col . getFamily ( ) , followingBytes ( col . getQualifier ( ) ) ) ) ; } else { return new RowColumn ( row , new Column ( col . getFamily ( ) , col . getQualifier ( ) , followingBytes ( col . getVisibility ( ) ) ) ) ; } }
Returns a RowColumn following the current one
183
8
150,394
public FluoMutationGenerator put ( Column col , CharSequence value ) { return put ( col , value . toString ( ) . getBytes ( StandardCharsets . UTF_8 ) ) ; }
Puts value at given column
45
6
150,395
public static CuratorFramework newAppCurator ( FluoConfiguration config ) { return newCurator ( config . getAppZookeepers ( ) , config . getZookeeperTimeout ( ) , config . getZookeeperSecret ( ) ) ; }
Creates a curator built using Application s zookeeper connection string . Root path will start at Fluo application chroot .
58
25
150,396
public static CuratorFramework newFluoCurator ( FluoConfiguration config ) { return newCurator ( config . getInstanceZookeepers ( ) , config . getZookeeperTimeout ( ) , config . getZookeeperSecret ( ) ) ; }
Creates a curator built using Fluo s zookeeper connection string . Root path will start at Fluo chroot .
60
25
150,397
public static CuratorFramework newCurator ( String zookeepers , int timeout , String secret ) { final ExponentialBackoffRetry retry = new ExponentialBackoffRetry ( 1000 , 10 ) ; if ( secret . isEmpty ( ) ) { return CuratorFrameworkFactory . newClient ( zookeepers , timeout , timeout , retry ) ; } else { return CuratorFrameworkFactory . builder ( ) . connectString ( zookeepers ) . connectionTimeoutMs ( timeout ) . sessionTimeoutMs ( timeout ) . retryPolicy ( retry ) . authorization ( "digest" , ( "fluo:" + secret ) . getBytes ( StandardCharsets . UTF_8 ) ) . aclProvider ( new ACLProvider ( ) { @ Override public List < ACL > getDefaultAcl ( ) { return CREATOR_ALL_ACL ; } @ Override public List < ACL > getAclForPath ( String path ) { switch ( path ) { case ZookeeperPath . ORACLE_GC_TIMESTAMP : // The garbage collection iterator running in Accumulo tservers needs to read this // value w/o authenticating. return PUBLICLY_READABLE_ACL ; default : return CREATOR_ALL_ACL ; } } } ) . build ( ) ; } }
Creates a curator built using the given zookeeper connection string and timeout
286
15
150,398
public static void startAndWait ( PersistentNode node , int maxWaitSec ) { node . start ( ) ; int waitTime = 0 ; try { while ( node . waitForInitialCreate ( 1 , TimeUnit . SECONDS ) == false ) { waitTime += 1 ; log . info ( "Waited " + waitTime + " sec for ephemeral node to be created" ) ; if ( waitTime > maxWaitSec ) { throw new IllegalStateException ( "Failed to create ephemeral node" ) ; } } } catch ( InterruptedException e ) { throw new IllegalStateException ( e ) ; } }
Starts the ephemeral node and waits for it to be created
134
14
150,399
public static NodeCache startAppIdWatcher ( Environment env ) { try { CuratorFramework curator = env . getSharedResources ( ) . getCurator ( ) ; byte [ ] uuidBytes = curator . getData ( ) . forPath ( ZookeeperPath . CONFIG_FLUO_APPLICATION_ID ) ; if ( uuidBytes == null ) { Halt . halt ( "Fluo Application UUID not found" ) ; throw new RuntimeException ( ) ; // make findbugs happy } final String uuid = new String ( uuidBytes , StandardCharsets . UTF_8 ) ; final NodeCache nodeCache = new NodeCache ( curator , ZookeeperPath . CONFIG_FLUO_APPLICATION_ID ) ; nodeCache . getListenable ( ) . addListener ( ( ) -> { ChildData node = nodeCache . getCurrentData ( ) ; if ( node == null || ! uuid . equals ( new String ( node . getData ( ) , StandardCharsets . UTF_8 ) ) ) { Halt . halt ( "Fluo Application UUID has changed or disappeared" ) ; } } ) ; nodeCache . start ( ) ; return nodeCache ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Start watching the fluo app uuid . If it changes or goes away then halt the process .
277
20