Input: Searches ( asynchronously ) for some text in a facet values . [CODESPLIT] public Request searchForFacetValuesAsync ( @ NonNull String facetName , @ NonNull String text , @ NonNull final CompletionHandler handler ) throws AlgoliaException { return searchForFacetValuesAsync ( facetName , text , /* requestOptions: */ null , handler ) ; }


Input: Searches for some text in a facet values optionally restricting the returned values to those contained in objects matching other ( regular ) search criteria . [CODESPLIT] public Request searchForFacetValuesAsync ( @ NonNull String facetName , @ NonNull String facetText , @ Nullable Query query , @ NonNull final CompletionHandler handler ) { return searchForFacetValuesAsync ( facetName , facetText , query , /* requestOptions: */ null , handler ) ; }


Input: Searches for some text in a facet values optionally restricting the returned values to those contained in objects matching other ( regular ) search criteria . [CODESPLIT] @ Override public Request searchForFacetValuesAsync ( @ NonNull String facetName , @ NonNull String facetText , @ Nullable Query query , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler handler ) { try { final String path = "/1/indexes/" + getEncodedIndexName ( ) + "/facets/" + URLEncoder . encode ( facetName , "UTF-8" ) + "/query" ; final Query params = ( query != null ? new Query ( query ) : new Query ( ) ) ; params . set ( "facetQuery" , facetText ) ; final JSONObject requestBody = new JSONObject ( ) . put ( "params" , params . build ( ) ) ; final Client client = getClient ( ) ; return client . new AsyncTaskRequest ( handler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return client . postRequest ( path , /* urlParameters: */ null , requestBody . toString ( ) , true , requestOptions ) ; } } . start ( ) ; } catch ( UnsupportedEncodingException | JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }


Input: Adds an object to this index ( asynchronously ) . <p > WARNING : For performance reasons the arguments are not cloned . Since the method is executed in the background you should not modify the object after it has been passed . < / p > [CODESPLIT] public Request addObjectAsync ( final @ NonNull JSONObject object , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return addObject ( object , /* requestOptions: */ null ) ; } } . start ( ) ; }


Input: Adds an object to this index assigning it the specified object ID ( asynchronously ) . If an object already exists with the same object ID the existing object will be overwritten . <p > WARNING : For performance reasons the arguments are not cloned . Since the method is executed in the background you should not modify the object after it has been passed . < / p > [CODESPLIT] public Request addObjectAsync ( final @ NonNull JSONObject object , final @ NonNull String objectID , @ Nullable CompletionHandler completionHandler ) { return addObjectAsync ( object , objectID , /* requestOptions: */ null , completionHandler ) ; }


Input: Adds an object to this index assigning it the specified object ID ( asynchronously ) . If an object already exists with the same object ID the existing object will be overwritten . <p > WARNING : For performance reasons the arguments are not cloned . Since the method is executed in the background you should not modify the object after it has been passed . < / p > [CODESPLIT] public Request addObjectAsync ( final @ NonNull JSONObject object , final @ NonNull String objectID , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return addObject ( object , objectID , requestOptions ) ; } } . start ( ) ; }


Input: Adds several objects to this index ( asynchronously ) . [CODESPLIT] public Request addObjectsAsync ( final @ NonNull JSONArray objects , @ Nullable CompletionHandler completionHandler ) { return addObjectsAsync ( objects , /* requestOptions: */ null , completionHandler ) ; }


Input: Update several objects ( asynchronously ) . [CODESPLIT] public Request saveObjectsAsync ( final @ NonNull JSONArray objects , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return saveObjects ( objects , requestOptions ) ; } } . start ( ) ; }


Input: Partially update an object ( asynchronously ) . <p > ** Note : ** This method will create the object if it does not exist already . If you don t wish to you can use { @link #partialUpdateObjectAsync ( JSONObject String boolean CompletionHandler ) } and specify false for the createIfNotExists argument . [CODESPLIT] public Request partialUpdateObjectAsync ( final @ NonNull JSONObject partialObject , final @ NonNull String objectID , @ Nullable CompletionHandler completionHandler ) { return partialUpdateObjectAsync ( partialObject , objectID , /* createIfNotExists: */ true , /* requestOptions: */ null , completionHandler ) ; }


Input: Partially update an object ( asynchronously ) . [CODESPLIT] public Request partialUpdateObjectAsync ( final @ NonNull JSONObject partialObject , final @ NonNull String objectID , final boolean createIfNotExists , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return partialUpdateObject ( partialObject , objectID , createIfNotExists , requestOptions ) ; } } . start ( ) ; }


Input: Partially update several objects ( asynchronously ) . <p > ** Note : ** This method will create the objects if they do not exist already . If you don t wish to you can use { @link #partialUpdateObjectsAsync ( JSONArray boolean CompletionHandler ) } and specify false for the createIfNotExists argument . [CODESPLIT] public Request partialUpdateObjectsAsync ( final @ NonNull JSONArray partialObjects , @ Nullable CompletionHandler completionHandler ) { return partialUpdateObjectsAsync ( partialObjects , /* createIfNotExists: */ true , /* requestOptions: */ null , completionHandler ) ; }


Input: Partially update several objects ( asynchronously ) . [CODESPLIT] public Request partialUpdateObjectsAsync ( final @ NonNull JSONArray partialObjects , final boolean createIfNotExists , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return partialUpdateObjects ( partialObjects , createIfNotExists , requestOptions ) ; } } . start ( ) ; }


Input: Gets an object from this index optionally restricting the retrieved content ( asynchronously ) . [CODESPLIT] public Request getObjectAsync ( final @ NonNull String objectID , final Collection < String > attributesToRetrieve , @ Nullable CompletionHandler completionHandler ) { return getObjectAsync ( objectID , attributesToRetrieve , /* requestOptions: */ null , completionHandler ) ; }


Input: Gets an object from this index optionally restricting the retrieved content ( asynchronously ) . [CODESPLIT] public Request getObjectAsync ( final @ NonNull String objectID , final Collection < String > attributesToRetrieve , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getObject ( objectID , attributesToRetrieve , requestOptions ) ; } } . start ( ) ; }


Input: Gets several objects from this index ( asynchronously ) . [CODESPLIT] public Request getObjectsAsync ( final @ NonNull Collection < String > objectIDs , @ Nullable CompletionHandler completionHandler ) { return getObjectsAsync ( objectIDs , /* attributesToRetrieve: */ null , /* requestOptions: */ null , completionHandler ) ; }


Input: Gets several objects from this index ( asynchronously ) optionally restricting the retrieved content ( asynchronously ) . [CODESPLIT] public Request getObjectsAsync ( final @ NonNull Collection < String > objectIDs , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getObjects ( objectIDs , null , requestOptions ) ; } } . start ( ) ; }


Input: Wait until the publication of a task on the server ( helper ) . All server tasks are asynchronous . This method helps you check that a task is published . [CODESPLIT] public Request waitTaskAsync ( final @ NonNull String taskID , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return waitTask ( taskID ) ; } } . start ( ) ; }


Input: Deletes an object from this index ( asynchronously ) . [CODESPLIT] public Request deleteObjectAsync ( final @ NonNull String objectID , @ Nullable CompletionHandler completionHandler ) { return deleteObjectAsync ( objectID , /* requestOptions: */ null , completionHandler ) ; }


Input: Deletes an object from this index ( asynchronously ) . [CODESPLIT] public Request deleteObjectAsync ( final @ NonNull String objectID , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return deleteObject ( objectID , requestOptions ) ; } } . start ( ) ; }


Input: Deletes several objects from this index ( asynchronously ) . [CODESPLIT] public Request deleteObjectsAsync ( final @ NonNull Collection < String > objectIDs , @ Nullable CompletionHandler completionHandler ) { return deleteObjectsAsync ( objectIDs , /* requestOptions: */ null , completionHandler ) ; }


Input: Deletes several objects from this index ( asynchronously ) . [CODESPLIT] public Request deleteObjectsAsync ( final @ NonNull Collection < String > objectIDs , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return deleteObjects ( objectIDs , requestOptions ) ; } } . start ( ) ; }


Input: Deletes all objects matching a query ( helper ) using browse and deleteObjects . [CODESPLIT] public Request deleteByQueryAsync ( @ NonNull Query query , @ Nullable CompletionHandler completionHandler ) { return deleteByQueryAsync ( query , /* requestOptions: */ null , completionHandler ) ; }


Input: Gets this index s settings ( asynchronously ) . [CODESPLIT] public Request getSettingsAsync ( @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getSettings ( 2 , requestOptions ) ; } } . start ( ) ; }


Input: Set this index s settings ( asynchronously ) . <p > Please refer to our <a href = https : // www . algolia . com / doc / android#index - settings > API documentation< / a > for the list of supported settings . [CODESPLIT] public Request setSettingsAsync ( final @ NonNull JSONObject settings , @ Nullable CompletionHandler completionHandler ) { return setSettingsAsync ( settings , /* forwardToReplicas: */ false , /* requestOptions: */ null , completionHandler ) ; }


Input: Set this index s settings ( asynchronously ) . <p > Please refer to our <a href = https : // www . algolia . com / doc / android#index - settings > API documentation< / a > for the list of supported settings . [CODESPLIT] public Request setSettingsAsync ( final @ NonNull JSONObject settings , final boolean forwardToReplicas , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return setSettings ( settings , forwardToReplicas , requestOptions ) ; } } . start ( ) ; }


Input: Browse the index from a cursor . This method should be called after an initial call to browseAsync () . It returns a cursor unless the end of the index has been reached . [CODESPLIT] public Request browseFromAsync ( final @ NonNull String cursor , @ Nullable CompletionHandler completionHandler ) { return browseFromAsync ( cursor , /* requestOptions: */ null , completionHandler ) ; }


Input: Browse the index from a cursor . This method should be called after an initial call to browseAsync () . It returns a cursor unless the end of the index has been reached . [CODESPLIT] public Request browseFromAsync ( final @ NonNull String cursor , @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return browseFrom ( cursor , requestOptions ) ; } } . start ( ) ; }


Input: Clear this index . [CODESPLIT] public Request clearIndexAsync ( @ Nullable final RequestOptions requestOptions , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return clearIndex ( requestOptions ) ; } } . start ( ) ; }


Input: Adds an object in this index . [CODESPLIT] public JSONObject addObject ( JSONObject obj , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { return client . postRequest ( "/1/indexes/" + encodedIndexName , /* urlParameters: */ null , obj . toString ( ) , false , requestOptions ) ; }


Input: Custom batch . [CODESPLIT] protected JSONObject batch ( JSONArray actions , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { JSONObject content = new JSONObject ( ) ; content . put ( "requests" , actions ) ; return client . postRequest ( "/1/indexes/" + encodedIndexName + "/batch" , /* urlParameters: */ null , content . toString ( ) , false , requestOptions ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }


Input: Gets an object from this index . [CODESPLIT] public JSONObject getObject ( String objectID , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { return client . getRequest ( "/1/indexes/" + encodedIndexName + "/" + URLEncoder . encode ( objectID , "UTF-8" ) , /* urlParameters: */ null , false , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }


Input: Gets an object from this index . [CODESPLIT] public JSONObject getObject ( String objectID , Collection < String > attributesToRetrieve , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { String path = "/1/indexes/" + encodedIndexName + "/" + URLEncoder . encode ( objectID , "UTF-8" ) ; Map < String , String > urlParameters = new HashMap <> ( ) ; if ( attributesToRetrieve != null ) { urlParameters . put ( "attributesToRetrieve" , AbstractQuery . buildCommaArray ( attributesToRetrieve . toArray ( new String [ attributesToRetrieve . size ( ) ] ) ) ) ; } return client . getRequest ( path , urlParameters , false , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }


Input: Gets several objects from this index . [CODESPLIT] public JSONObject getObjects ( Collection < String > objectIDs ) throws AlgoliaException { return getObjects ( objectIDs , /* attributesToRetrieve: */ null , /* requestOptions: */ null ) ; }


Input: Gets several objects from this index . [CODESPLIT] public JSONObject getObjects ( @ NonNull Collection < String > objectIDs , @ Nullable Collection < String > attributesToRetrieve , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { JSONArray requests = new JSONArray ( ) ; for ( String id : objectIDs ) { JSONObject request = new JSONObject ( ) ; request . put ( "indexName" , this . rawIndexName ) ; request . put ( "objectID" , id ) ; if ( attributesToRetrieve != null ) { request . put ( "attributesToRetrieve" , new JSONArray ( attributesToRetrieve ) ) ; } requests . put ( request ) ; } JSONObject body = new JSONObject ( ) ; body . put ( "requests" , requests ) ; return client . postRequest ( "/1/indexes/*/objects" , /* urlParameters: */ null , body . toString ( ) , true , requestOptions ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }


Input: Update partially an object ( only update attributes passed in argument ) . [CODESPLIT] public JSONObject partialUpdateObject ( JSONObject partialObject , String objectID , Boolean createIfNotExists , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { String path = "/1/indexes/" + encodedIndexName + "/" + URLEncoder . encode ( objectID , "UTF-8" ) + "/partial" ; Map < String , String > urlParameters = new HashMap <> ( ) ; if ( createIfNotExists != null ) { urlParameters . put ( "createIfNotExists" , createIfNotExists . toString ( ) ) ; } return client . postRequest ( path , urlParameters , partialObject . toString ( ) , false , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }


Input: Partially Override the content of several objects . [CODESPLIT] public JSONObject partialUpdateObjects ( JSONArray inputArray , boolean createIfNotExists , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { final String action = createIfNotExists ? "partialUpdateObject" : "partialUpdateObjectNoCreate" ; JSONArray array = new JSONArray ( ) ; for ( int n = 0 ; n < inputArray . length ( ) ; n ++ ) { JSONObject obj = inputArray . getJSONObject ( n ) ; JSONObject operation = new JSONObject ( ) ; operation . put ( "action" , action ) ; operation . put ( "objectID" , obj . getString ( "objectID" ) ) ; operation . put ( "body" , obj ) ; array . put ( operation ) ; } return batch ( array , requestOptions ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }


Input: Override the content of object . [CODESPLIT] public JSONObject saveObject ( JSONObject object , String objectID , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { return client . putRequest ( "/1/indexes/" + encodedIndexName + "/" + URLEncoder . encode ( objectID , "UTF-8" ) , /* urlParameters: */ null , object . toString ( ) , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }


Input: Override the content of several objects . [CODESPLIT] public JSONObject saveObjects ( JSONArray inputArray , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { JSONArray array = new JSONArray ( ) ; for ( int n = 0 ; n < inputArray . length ( ) ; n ++ ) { JSONObject obj = inputArray . getJSONObject ( n ) ; JSONObject action = new JSONObject ( ) ; action . put ( "action" , "updateObject" ) ; action . put ( "objectID" , obj . getString ( "objectID" ) ) ; action . put ( "body" , obj ) ; array . put ( action ) ; } return batch ( array , requestOptions ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }


Input: Deletes all objects matching a query using browse and deleteObjects . [CODESPLIT] @ Deprecated public void deleteByQuery ( @ NonNull Query query , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { boolean hasMore ; do { // Browse index for the next batch of objects. // WARNING: Since deletion invalidates cursors, we always browse from the start. List < String > objectIDs = new ArrayList <> ( 1000 ) ; JSONObject content = browse ( query , requestOptions ) ; JSONArray hits = content . getJSONArray ( "hits" ) ; for ( int i = 0 ; i < hits . length ( ) ; ++ i ) { JSONObject hit = hits . getJSONObject ( i ) ; objectIDs . add ( hit . getString ( "objectID" ) ) ; } hasMore = content . optString ( "cursor" , null ) != null ; // Delete objects. JSONObject task = this . deleteObjects ( objectIDs , /* requestOptions: */ null ) ; this . waitTask ( task . getString ( "taskID" ) ) ; } while ( hasMore ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }


Input: Deletes all records matching the query . [CODESPLIT] public JSONObject deleteBy ( @ NonNull Query query , RequestOptions requestOptions ) throws AlgoliaException { try { return client . postRequest ( "/1/indexes/" + encodedIndexName + "/deleteByQuery" , query . getParameters ( ) , new JSONObject ( ) . put ( "params" , query . build ( ) ) . toString ( ) , false , requestOptions ) ; } catch ( JSONException e ) { e . printStackTrace ( ) ; return null ; } }


Input: Searches inside the index . [CODESPLIT] public JSONObject search ( @ Nullable Query query , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { if ( query == null ) { query = new Query ( ) ; } String cacheKey = null ; byte [ ] rawResponse = null ; if ( isCacheEnabled ) { cacheKey = query . build ( ) ; rawResponse = searchCache . get ( cacheKey ) ; } try { if ( rawResponse == null ) { rawResponse = searchRaw ( query , requestOptions ) ; if ( isCacheEnabled ) { searchCache . put ( cacheKey , rawResponse ) ; } } return Client . _getJSONObject ( rawResponse ) ; } catch ( UnsupportedEncodingException | JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }


Input: Searches inside the index . [CODESPLIT] protected byte [ ] searchRaw ( @ Nullable Query query , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { if ( query == null ) { query = new Query ( ) ; } try { String paramsString = query . build ( ) ; if ( paramsString . length ( ) > 0 ) { JSONObject body = new JSONObject ( ) ; body . put ( "params" , paramsString ) ; return client . postRequestRaw ( "/1/indexes/" + encodedIndexName + "/query" , /* urlParameters: */ null , body . toString ( ) , true , requestOptions ) ; } else { return client . getRequestRaw ( "/1/indexes/" + encodedIndexName , /* urlParameters: */ null , true , requestOptions ) ; } } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }


Input: Wait the publication of a task on the server . All server task are asynchronous and you can check with this method that the task is published . [CODESPLIT] public JSONObject waitTask ( String taskID , long timeToWait ) throws AlgoliaException { try { while ( true ) { JSONObject obj = client . getRequest ( "/1/indexes/" + encodedIndexName + "/task/" + URLEncoder . encode ( taskID , "UTF-8" ) , /* urlParameters: */ null , false , /* requestOptions: */ null ) ; if ( obj . getString ( "status" ) . equals ( "published" ) ) { return obj ; } try { Thread . sleep ( timeToWait >= MAX_TIME_MS_TO_WAIT ? MAX_TIME_MS_TO_WAIT : timeToWait ) ; } catch ( InterruptedException e ) { continue ; } final long newTimeout = timeToWait * 2 ; timeToWait = ( newTimeout <= 0 || newTimeout >= MAX_TIME_MS_TO_WAIT ) ? MAX_TIME_MS_TO_WAIT : newTimeout ; } } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }


Input: Gets the settings of this index . [CODESPLIT] public JSONObject getSettings ( @ Nullable RequestOptions requestOptions ) throws AlgoliaException { Map < String , String > urlParameters = new HashMap <> ( ) ; urlParameters . put ( "getVersion" , Integer . toString ( DEFAULT_SETTINGS_VERSION ) ) ; return client . getRequest ( "/1/indexes/" + encodedIndexName + "/settings" , urlParameters , false , requestOptions ) ; }


Input: Set settings for this index . [CODESPLIT] public JSONObject setSettings ( JSONObject settings , boolean forwardToReplicas , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { Map < String , String > urlParameters = new HashMap <> ( ) ; urlParameters . put ( "forwardToReplicas" , Boolean . toString ( forwardToReplicas ) ) ; return client . putRequest ( "/1/indexes/" + encodedIndexName + "/settings" , urlParameters , settings . toString ( ) , requestOptions ) ; }


Input: Deletes the index content without removing settings and index specific API keys . [CODESPLIT] public JSONObject clearIndex ( @ Nullable RequestOptions requestOptions ) throws AlgoliaException { return client . postRequest ( "/1/indexes/" + encodedIndexName + "/clear" , /* urlParameters: */ null , "" , false , requestOptions ) ; }


Input: Run multiple queries on this index with one API call . A variant of { @link Client#multipleQueries ( List String RequestOptions ) } where all queries target this index . [CODESPLIT] protected JSONObject multipleQueries ( @ NonNull Collection < Query > queries , String strategy , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { List < IndexQuery > requests = new ArrayList <> ( queries . size ( ) ) ; for ( Query query : queries ) { requests . add ( new IndexQuery ( this , query ) ) ; } return client . multipleQueries ( requests , strategy , requestOptions ) ; }


Input: Build a query string from a map of URL parameters . [CODESPLIT] static @ NonNull String build ( @ NonNull Map < String , String > parameters ) { StringBuilder stringBuilder = new StringBuilder ( ) ; try { for ( Map . Entry < String , String > entry : parameters . entrySet ( ) ) { String key = entry . getKey ( ) ; if ( stringBuilder . length ( ) > 0 ) stringBuilder . append ( ' ' ) ; stringBuilder . append ( urlEncode ( key ) ) ; String value = entry . getValue ( ) ; if ( value != null ) { stringBuilder . append ( ' ' ) ; stringBuilder . append ( urlEncode ( value ) ) ; } } } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; // should never happen: UTF-8 is always supported } return stringBuilder . toString ( ) ; }


Input: Parse a URL query parameter string and store the resulting parameters into this query . [CODESPLIT] public void parseFrom ( @ NonNull String queryParameters ) { try { String [ ] parameters = queryParameters . split ( "&" ) ; for ( String parameter : parameters ) { String [ ] components = parameter . split ( "=" ) ; if ( components . length < 1 || components . length > 2 ) continue ; // ignore invalid values String name = URLDecoder . decode ( components [ 0 ] , "UTF-8" ) ; String value = components . length >= 2 ? URLDecoder . decode ( components [ 1 ] , "UTF-8" ) : null ; set ( name , value ) ; } // for each parameter } catch ( UnsupportedEncodingException e ) { // Should never happen since UTF-8 is one of the default encodings. throw new RuntimeException ( e ) ; } }


Input: Set a parameter in an untyped fashion . This low - level accessor is intended to access parameters that this client does not yet support . [CODESPLIT] public @ NonNull AbstractQuery set ( @ NonNull String name , @ Nullable Object value ) { if ( value == null ) { parameters . remove ( name ) ; } else { parameters . put ( name , value . toString ( ) ) ; } return this ; }


Input: Search for entries around a given latitude / longitude . [CODESPLIT] public @ NonNull Query setAroundLatLng ( @ Nullable LatLng location ) { if ( location == null ) { return set ( KEY_AROUND_LAT_LNG , null ) ; } else { return set ( KEY_AROUND_LAT_LNG , location . lat + "," + location . lng ) ; } }


Input: Change the radius for around latitude / longitude queries . [CODESPLIT] public @ NonNull Query setAroundRadius ( Integer radius ) { if ( radius == Query . RADIUS_ALL ) { return set ( KEY_AROUND_RADIUS , "all" ) ; } return set ( KEY_AROUND_RADIUS , radius ) ; }


Input: Deprecated use { [CODESPLIT] @ Deprecated public @ NonNull Query setAttributesToHighlight ( List < String > attributes ) { return set ( KEY_ATTRIBUTES_TO_HIGHLIGHT , buildJSONArray ( ( String [ ] ) attributes . toArray ( ) ) ) ; }


Input: Deprecated use { [CODESPLIT] @ Deprecated public @ NonNull Query setAttributesToRetrieve ( List < String > attributes ) { return set ( KEY_ATTRIBUTES_TO_RETRIEVE , buildJSONArray ( ( String [ ] ) attributes . toArray ( ) ) ) ; }


Input: Get the value of <b > deprecated< / b > { @code facetFilters } parameter . [CODESPLIT] public @ Nullable JSONArray getFacetFilters ( ) { try { String value = get ( KEY_FACET_FILTERS ) ; if ( value != null ) { return new JSONArray ( value ) ; } } catch ( JSONException e ) { // Will return null } return null ; }


Input: A list of language codes for which plural won t be considered as a typo ( for example car / cars will be considered as equals ) . If empty or null this disables the feature . [CODESPLIT] public @ NonNull Query setIgnorePlurals ( @ Nullable Collection < String > languageISOCodes ) { return set ( KEY_IGNORE_PLURALS , new IgnorePlurals ( languageISOCodes ) ) ; }


Input: Search for entries inside one area or the union of several areas defined by the two extreme points of a rectangle . [CODESPLIT] public @ NonNull Query setInsideBoundingBox ( @ Nullable GeoRect ... boxes ) { if ( boxes == null ) { set ( KEY_INSIDE_BOUNDING_BOX , null ) ; } else { StringBuilder sb = new StringBuilder ( ) ; for ( GeoRect box : boxes ) { if ( sb . length ( ) != 0 ) { sb . append ( ' ' ) ; } sb . append ( box . p1 . lat ) ; sb . append ( ' ' ) ; sb . append ( box . p1 . lng ) ; sb . append ( ' ' ) ; sb . append ( box . p2 . lat ) ; sb . append ( ' ' ) ; sb . append ( box . p2 . lng ) ; } set ( KEY_INSIDE_BOUNDING_BOX , sb . toString ( ) ) ; } return this ; }


Input: Search for entries inside a given area defined by the points of a polygon . [CODESPLIT] public @ NonNull Query setInsidePolygon ( @ Nullable LatLng ... points ) { set ( KEY_INSIDE_POLYGON , points == null ? null : new Polygon ( points ) . toString ( ) ) ; return this ; }


Input: Search for entries inside a given area defined by several polygons . [CODESPLIT] public @ NonNull Query setInsidePolygon ( @ Nullable Polygon ... polygons ) { String insidePolygon = null ; if ( polygons == null ) { insidePolygon = null ; } else if ( polygons . length == 1 ) { insidePolygon = polygons [ 0 ] . toString ( ) ; } else { for ( Polygon polygon : polygons ) { String polygonStr = "[" + polygon + "]" ; if ( insidePolygon == null ) { insidePolygon = "[" ; } else { insidePolygon += "," ; } insidePolygon += polygonStr ; } insidePolygon += "]" ; } set ( KEY_INSIDE_POLYGON , insidePolygon ) ; return this ; }


Input: Get the value of <b > deprecated< / b > { @code facetFilters } parameter . [CODESPLIT] public @ Nullable JSONArray getNumericFilters ( ) { try { String value = get ( KEY_NUMERIC_FILTERS ) ; if ( value != null ) { return new JSONArray ( value ) ; } } catch ( JSONException e ) { // Will return null } return null ; }


Input: Select how the query words are interpreted : [CODESPLIT] public @ NonNull Query setQueryType ( @ Nullable QueryType type ) { set ( KEY_QUERY_TYPE , type == null ? null : type . toString ( ) ) ; return this ; }


Input: Enable the removal of stop words disabled by default . In most use - cases we don’t recommend enabling this option . [CODESPLIT] public @ NonNull Query setRemoveStopWords ( Object removeStopWords ) throws AlgoliaException { if ( removeStopWords instanceof Boolean || removeStopWords instanceof String ) { return set ( KEY_REMOVE_STOP_WORDS , removeStopWords ) ; } throw new AlgoliaException ( "removeStopWords should be a Boolean or a String." ) ; }


Input: Select the strategy to adopt when a query does not return any result . [CODESPLIT] public @ NonNull Query setRemoveWordsIfNoResults ( @ Nullable RemoveWordsIfNoResults type ) { set ( KEY_REMOVE_WORDS_IF_NO_RESULT , type == null ? null : type . toString ( ) ) ; return this ; }


Input: Parse a query object from a URL query parameter string . [CODESPLIT] protected static @ NonNull Query parse ( @ NonNull String queryParameters ) { Query query = new Query ( ) ; query . parseFrom ( queryParameters ) ; return query ; }


Input: Perform a search with disjunctive facets generating as many queries as number of disjunctive facets . [CODESPLIT] public < T extends Collection < String > > Request searchDisjunctiveFacetingAsync ( @ NonNull Query query , @ NonNull final Collection < String > disjunctiveFacets , @ NonNull final Map < String , T > refinements , @ NonNull final CompletionHandler completionHandler ) { final List < Query > queries = computeDisjunctiveFacetingQueries ( query , disjunctiveFacets , refinements ) ; return multipleQueriesAsync ( queries , new CompletionHandler ( ) { @ Override public void requestCompleted ( JSONObject content , AlgoliaException error ) { JSONObject aggregatedResults = null ; try { if ( content != null ) { aggregatedResults = aggregateDisjunctiveFacetingResults ( content , disjunctiveFacets , refinements ) ; } } catch ( AlgoliaException e ) { error = e ; } completionHandler . requestCompleted ( aggregatedResults , error ) ; } } ) ; }


Input: Filter disjunctive refinements from generic refinements and a list of disjunctive facets . [CODESPLIT] static private @ NonNull < T extends Collection < String > > Map < String , T > filterDisjunctiveRefinements ( @ NonNull Collection < String > disjunctiveFacets , @ NonNull Map < String , T > refinements ) { Map < String , T > disjunctiveRefinements = new HashMap <> ( ) ; for ( Map . Entry < String , T > elt : refinements . entrySet ( ) ) { if ( disjunctiveFacets . contains ( elt . getKey ( ) ) ) { disjunctiveRefinements . put ( elt . getKey ( ) , elt . getValue ( ) ) ; } } return disjunctiveRefinements ; }


Input: Compute the queries to run to implement disjunctive faceting . [CODESPLIT] static private @ NonNull < T extends Collection < String > > List < Query > computeDisjunctiveFacetingQueries ( @ NonNull Query query , @ NonNull Collection < String > disjunctiveFacets , @ NonNull Map < String , T > refinements ) { // Retain only refinements corresponding to the disjunctive facets. Map < String , ? extends Collection < String > > disjunctiveRefinements = filterDisjunctiveRefinements ( disjunctiveFacets , refinements ) ; // build queries List < Query > queries = new ArrayList <> ( ) ; // first query: hits + regular facets JSONArray facetFilters = new JSONArray ( ) ; for ( Map . Entry < String , T > elt : refinements . entrySet ( ) ) { JSONArray orFilters = new JSONArray ( ) ; for ( String val : elt . getValue ( ) ) { // When already refined facet, or with existing refinements if ( disjunctiveRefinements . containsKey ( elt . getKey ( ) ) ) { orFilters . put ( formatFilter ( elt , val ) ) ; } else { facetFilters . put ( formatFilter ( elt , val ) ) ; } } // Add or if ( disjunctiveRefinements . containsKey ( elt . getKey ( ) ) ) { facetFilters . put ( orFilters ) ; } } //noinspection deprecation Deprecated for end-users queries . add ( new Query ( query ) . setFacetFilters ( facetFilters ) ) ; // one query per disjunctive facet (use all refinements but the current one + hitsPerPage=1 + single facet for ( String disjunctiveFacet : disjunctiveFacets ) { facetFilters = new JSONArray ( ) ; for ( Map . Entry < String , T > elt : refinements . entrySet ( ) ) { if ( disjunctiveFacet . equals ( elt . getKey ( ) ) ) { continue ; } JSONArray orFilters = new JSONArray ( ) ; for ( String val : elt . getValue ( ) ) { if ( disjunctiveRefinements . containsKey ( elt . getKey ( ) ) ) { orFilters . put ( formatFilter ( elt , val ) ) ; } else { facetFilters . put ( formatFilter ( elt , val ) ) ; } } // Add or if ( disjunctiveRefinements . containsKey ( elt . getKey ( ) ) ) { facetFilters . put ( orFilters ) ; } } String [ ] facets = new String [ ] { disjunctiveFacet } ; //noinspection deprecation Deprecated for end-users queries . add ( new Query ( query ) . setHitsPerPage ( 0 ) . setAnalytics ( false ) . setAttributesToRetrieve ( ) . setAttributesToHighlight ( ) . setAttributesToSnippet ( ) . setFacets ( facets ) . setFacetFilters ( facetFilters ) ) ; } return queries ; }


Input: Aggregate results from multiple queries into disjunctive faceting results . [CODESPLIT] static private < T extends Collection < String > > JSONObject aggregateDisjunctiveFacetingResults ( @ NonNull JSONObject answers , @ NonNull Collection < String > disjunctiveFacets , @ NonNull Map < String , T > refinements ) throws AlgoliaException { Map < String , T > disjunctiveRefinements = filterDisjunctiveRefinements ( disjunctiveFacets , refinements ) ; // aggregate answers // first answer stores the hits + regular facets try { boolean nonExhaustiveFacetsCount = false ; JSONArray results = answers . getJSONArray ( "results" ) ; JSONObject aggregatedAnswer = results . getJSONObject ( 0 ) ; JSONObject disjunctiveFacetsJSON = new JSONObject ( ) ; for ( int i = 1 ; i < results . length ( ) ; ++ i ) { if ( ! results . getJSONObject ( i ) . optBoolean ( "exhaustiveFacetsCount" ) ) { nonExhaustiveFacetsCount = true ; } JSONObject facets = results . getJSONObject ( i ) . getJSONObject ( "facets" ) ; @ SuppressWarnings ( "unchecked" ) Iterator < String > keys = facets . keys ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; // Add the facet to the disjunctive facet hash disjunctiveFacetsJSON . put ( key , facets . getJSONObject ( key ) ) ; // concatenate missing refinements if ( ! disjunctiveRefinements . containsKey ( key ) ) { continue ; } for ( String refine : disjunctiveRefinements . get ( key ) ) { if ( ! disjunctiveFacetsJSON . getJSONObject ( key ) . has ( refine ) ) { disjunctiveFacetsJSON . getJSONObject ( key ) . put ( refine , 0 ) ; } } } } aggregatedAnswer . put ( "disjunctiveFacets" , disjunctiveFacetsJSON ) ; if ( nonExhaustiveFacetsCount ) { aggregatedAnswer . put ( "exhaustiveFacetsCount" , false ) ; } return aggregatedAnswer ; } catch ( JSONException e ) { throw new AlgoliaException ( "Failed to aggregate results" , e ) ; } }


Input: Search inside this index ( asynchronously ) . [CODESPLIT] public Request searchAsync ( @ NonNull Query query , @ NonNull CompletionHandler completionHandler ) { final Query queryCopy = new Query ( query ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return searchSync ( queryCopy ) ; } } . start ( ) ; }


Input: Search inside this index ( synchronously ) . [CODESPLIT] private JSONObject searchSync ( @ NonNull Query query ) throws AlgoliaException { return OfflineClient . parseSearchResults ( localIndex . search ( query . build ( ) ) ) ; }


Input: Run multiple queries on this index with one API call . A variant of { @link Client#multipleQueriesAsync ( List Client . MultipleQueriesStrategy CompletionHandler ) } where the targeted index is always the receiver . [CODESPLIT] public Request multipleQueriesAsync ( final @ NonNull List < Query > queries , @ Nullable final Client . MultipleQueriesStrategy strategy , @ NonNull CompletionHandler completionHandler ) { final List < Query > queriesCopy = new ArrayList <> ( queries ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return multipleQueriesSync ( queriesCopy , strategy ) ; } } . start ( ) ; }


Input: Get an object from this index optionally restricting the retrieved content ( asynchronously ) . [CODESPLIT] public Request getObjectAsync ( final @ NonNull String objectID , final List < String > attributesToRetrieve , @ NonNull CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getObjectSync ( objectID , attributesToRetrieve ) ; } } . start ( ) ; }


Input: Get several objects from this index ( asynchronously ) . [CODESPLIT] public Request getObjectsAsync ( final @ NonNull List < String > objectIDs , @ NonNull CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getObjectsSync ( objectIDs , null ) ; } } . start ( ) ; }


Input: Get this index s settings ( asynchronously ) . [CODESPLIT] public Request getSettingsAsync ( @ NonNull CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return getSettingsSync ( ) ; } } . start ( ) ; }


Input: Browse all index content ( initial call ) . This method should be called once to initiate a browse . It will return the first page of results and a cursor unless the end of the index has been reached . To retrieve subsequent pages call browseFromAsync with that cursor . [CODESPLIT] public Request browseAsync ( @ NonNull Query query , @ NonNull CompletionHandler completionHandler ) { final Query queryCopy = new Query ( query ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return browseSync ( queryCopy ) ; } } . start ( ) ; }


Input: Browse the index from a cursor . This method should be called after an initial call to browseAsync () . It returns a cursor unless the end of the index has been reached . [CODESPLIT] public Request browseFromAsync ( final @ NonNull String cursor , @ NonNull CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return browseFromSync ( cursor ) ; } } . start ( ) ; }


Input: Search for facet values ( asynchronously ) . Same parameters as { [CODESPLIT] public Request searchForFacetValuesAsync ( final @ NonNull String facetName , final @ NonNull String facetQuery , @ Nullable Query query , @ NonNull CompletionHandler completionHandler ) { final Query queryCopy = query != null ? new Query ( query ) : null ; return getClient ( ) . new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return searchForFacetValuesSync ( facetName , facetQuery , queryCopy ) ; } } . start ( ) ; }


Input: Search for facet values ( synchronously ) . [CODESPLIT] private JSONObject searchForFacetValuesSync ( @ NonNull String facetName , @ NonNull String facetQuery , @ Nullable Query query ) throws AlgoliaException { return OfflineClient . parseSearchResults ( localIndex . searchForFacetValues ( facetName , facetQuery , query != null ? query . build ( ) : null ) ) ; }


Input: Build the index from local data stored on the filesystem . [CODESPLIT] public Request buildFromFiles ( @ NonNull final File settingsFile , @ NonNull final File [ ] objectFiles , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localBuildExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _build ( settingsFile , objectFiles ) ; } } . start ( ) ; }


Input: Build the index from local data stored in raw resources . [CODESPLIT] public Request buildFromRawResources ( @ NonNull final Resources resources , @ NonNull final int settingsResId , @ NonNull final int [ ] objectsResIds , @ Nullable CompletionHandler completionHandler ) { return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . localBuildExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return _buildFromRawResources ( resources , settingsResId , objectsResIds ) ; } } . start ( ) ; }


Input: Perform a search with disjunctive facets generating as many queries as number of disjunctive facets ( helper ) . [CODESPLIT] public Request searchDisjunctiveFacetingAsync ( @ NonNull Query query , @ NonNull final List < String > disjunctiveFacets , @ NonNull final Map < String , List < String > > refinements , @ NonNull final CompletionHandler completionHandler ) { return new DisjunctiveFaceting ( ) { @ Override protected Request multipleQueriesAsync ( @ NonNull Collection < Query > queries , @ NonNull CompletionHandler completionHandler ) { return OfflineIndex . this . multipleQueriesAsync ( new ArrayList ( queries ) , null , completionHandler ) ; } } . searchDisjunctiveFacetingAsync ( query , disjunctiveFacets , refinements , completionHandler ) ; }


Input: Delete all objects matching a query ( helper ) . [CODESPLIT] public Request deleteByQueryAsync ( @ NonNull Query query , CompletionHandler completionHandler ) { final WriteTransaction transaction = newTransaction ( ) ; final Query queryCopy = new Query ( query ) ; return getClient ( ) . new AsyncTaskRequest ( completionHandler , getClient ( ) . transactionExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { try { Collection < String > deletedObjectIDs = deleteByQuerySync ( queryCopy , transaction ) ; transaction . commitSync ( ) ; return new JSONObject ( ) . put ( "objectIDs" , new JSONArray ( deletedObjectIDs ) ) . put ( "updatedAt" , DateUtils . iso8601String ( new Date ( ) ) ) . put ( "taskID" , transaction . id ) ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } } } . start ( ) ; }


Input: Create a copy of a JSON object with a specific <code > objectID< / code > attribute . [CODESPLIT] private static JSONObject objectWithID ( @ NonNull JSONObject object , @ NonNull String objectID ) { try { // WARNING: Could not find a better way to clone the object. JSONObject patchedObject = new JSONObject ( object . toString ( ) ) ; patchedObject . put ( "objectID" , objectID ) ; return patchedObject ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }


Input: Write a temporary file containing a JSON object . [CODESPLIT] private @ NonNull File writeTmpJSONFile ( @ NonNull JSONObject object ) throws AlgoliaException { return writeTempFile ( object . toString ( ) ) ; }


Input: Write a temporary file containing JSON objects . The files are written as an array . [CODESPLIT] private File writeTmpJSONFile ( @ NonNull Collection < JSONObject > objects ) throws AlgoliaException { // TODO: Maybe split in several files if too big? // TODO: Stream writing. JSONArray array = new JSONArray ( ) ; for ( JSONObject object : objects ) { array . put ( object ) ; } return writeTempFile ( array . toString ( ) ) ; }


Input: Write a temporary file containing textual data in UTF - 8 encoding . [CODESPLIT] private File writeTempFile ( @ NonNull String data ) throws AlgoliaException { try { // Create temporary file. File tmpDir = client . getTempDir ( ) ; File tmpFile = File . createTempFile ( "algolia." , ".json" , tmpDir ) ; // Write to file. Writer writer = new OutputStreamWriter ( new FileOutputStream ( tmpFile ) , "UTF-8" ) ; writer . write ( data ) ; writer . close ( ) ; return tmpFile ; } catch ( IOException e ) { throw new AlgoliaException ( "Could not create temporary file" , e ) ; } }


Input: Obtain a mirrored index . Although this will always be an instance of { @link MirroredIndex } mirroring is deactivated by default . [CODESPLIT] @ Override public @ NonNull MirroredIndex getIndex ( @ NonNull String indexName ) { MirroredIndex index = null ; WeakReference < Object > existingIndex = indices . get ( indexName ) ; if ( existingIndex != null ) { index = ( MirroredIndex ) existingIndex . get ( ) ; } if ( index == null ) { index = new MirroredIndex ( this , indexName ) ; indices . put ( indexName , new WeakReference < Object > ( index ) ) ; } return index ; }


Input: Obtain a purely offline index . [CODESPLIT] public OfflineIndex getOfflineIndex ( @ NonNull String indexName ) { OfflineIndex index = null ; WeakReference < Object > existingIndex = indices . get ( indexName ) ; if ( existingIndex != null ) { index = ( OfflineIndex ) existingIndex . get ( ) ; } if ( index == null ) { index = new OfflineIndex ( this , indexName ) ; indices . put ( indexName , new WeakReference < Object > ( index ) ) ; } return index ; }


Input: Test if an index has offline data on disk . [CODESPLIT] public boolean hasOfflineData ( @ NonNull String name ) { // TODO: Suboptimal; we should be able to test existence without instantiating a `LocalIndex`. return new LocalIndex ( getRootDataDir ( ) . getAbsolutePath ( ) , getApplicationID ( ) , name ) . exists ( ) ; }


Input: List existing offline indices . Only indices that * actually exist * on disk are listed . If an instance was created but never synced or written to it will not appear in the list . [CODESPLIT] public Request listIndexesOfflineAsync ( @ NonNull CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return listIndexesOfflineSync ( ) ; } } . start ( ) ; }


Input: List existing offline indices . [CODESPLIT] private JSONObject listIndexesOfflineSync ( ) throws AlgoliaException { try { final String rootDataPath = getRootDataDir ( ) . getAbsolutePath ( ) ; final File appDir = getAppDir ( ) ; final File [ ] directories = appDir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File pathname ) { return pathname . isDirectory ( ) ; } } ) ; JSONObject response = new JSONObject ( ) ; JSONArray items = new JSONArray ( ) ; if ( directories != null ) { for ( File directory : directories ) { final String name = directory . getName ( ) ; if ( hasOfflineData ( name ) ) { items . put ( new JSONObject ( ) . put ( "name" , name ) ) ; // TODO: Do we need other data as in the online API? } } } response . put ( "items" , items ) ; return response ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }


Input: Delete an offline index . This deletes the data on disk . If the index does not exist this method does nothing . [CODESPLIT] public Request deleteIndexOfflineAsync ( final @ NonNull String indexName , CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler , localBuildExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return deleteIndexOfflineSync ( indexName ) ; } } . start ( ) ; }


Input: Delete an offline index . This deletes the data on disk . If the index does not exist this method does nothing . [CODESPLIT] private JSONObject deleteIndexOfflineSync ( final @ NonNull String indexName ) throws AlgoliaException { try { FileUtils . deleteRecursive ( getIndexDir ( indexName ) ) ; return new JSONObject ( ) . put ( "deletedAt" , DateUtils . iso8601String ( new Date ( ) ) ) ; } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }


Input: Move an existing offline index . [CODESPLIT] public Request moveIndexOfflineAsync ( final @ NonNull String srcIndexName , final @ NonNull String dstIndexName , CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler , localBuildExecutorService ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return moveIndexOfflineSync ( srcIndexName , dstIndexName ) ; } } . start ( ) ; }


Input: Move an existing offline index . [CODESPLIT] private JSONObject moveIndexOfflineSync ( final @ NonNull String srcIndexName , final @ NonNull String dstIndexName ) throws AlgoliaException { try { final File srcDir = getIndexDir ( srcIndexName ) ; final File dstDir = getIndexDir ( dstIndexName ) ; if ( dstDir . exists ( ) ) { FileUtils . deleteRecursive ( dstDir ) ; } if ( srcDir . renameTo ( dstDir ) ) { return new JSONObject ( ) . put ( "updatedAt" , DateUtils . iso8601String ( new Date ( ) ) ) ; } else { throw new AlgoliaException ( "Could not move index" ) ; } } catch ( JSONException e ) { throw new RuntimeException ( e ) ; // should never happen } }


Input: ---------------------------------------------------------------------- [CODESPLIT] static protected JSONObject parseSearchResults ( Response searchResults ) throws AlgoliaException { try { if ( searchResults . getStatusCode ( ) == 200 ) { if ( searchResults . getData ( ) != null ) { String jsonString = new String ( searchResults . getData ( ) , "UTF-8" ) ; return new JSONObject ( jsonString ) ; } else { // may happen when building: no output return new JSONObject ( ) ; } } else { throw new AlgoliaException ( searchResults . getErrorMessage ( ) , searchResults . getStatusCode ( ) ) ; } } catch ( JSONException | UnsupportedEncodingException e ) { throw new AlgoliaException ( "Offline Core returned invalid JSON" , e ) ; } }


Input: Delete a file or directory recursively deleting any descendant files / directories if it s a directory . [CODESPLIT] public static boolean deleteRecursive ( @ NonNull File item ) { boolean ok = true ; if ( item . isDirectory ( ) ) { for ( File child : item . listFiles ( ) ) { ok = ok && deleteRecursive ( child ) ; } } ok = ok && item . delete ( ) ; return ok ; }


Input: Write a stream of bytes to a file . [CODESPLIT] public static void writeFile ( @ NonNull File destinationFile , @ NonNull InputStream content ) throws IOException { byte [ ] buffer = new byte [ 64 * 1024 ] ; // 64 kB buffer FileOutputStream outputStream = new FileOutputStream ( destinationFile ) ; try { int bytesRead ; while ( ( bytesRead = content . read ( buffer ) ) >= 0 ) { outputStream . write ( buffer , 0 , bytesRead ) ; } } finally { content . close ( ) ; outputStream . close ( ) ; } }


Input: Set a URL parameter ( untyped version ) . Whenever possible you should use a typed accessor . [CODESPLIT] public RequestOptions setUrlParameter ( @ NonNull String name , @ Nullable String value ) { if ( value == null ) { urlParameters . remove ( name ) ; } else { urlParameters . put ( name , value ) ; } return this ; }


Input: Set an HTTP header that will be sent with every request . [CODESPLIT] public void setHeader ( @ NonNull String name , @ Nullable String value ) { if ( value == null ) { headers . remove ( name ) ; } else { headers . put ( name , value ) ; } }


Input: Add a software library to the list of user agents . [CODESPLIT] public void addUserAgent ( @ NonNull LibraryVersion userAgent ) { if ( ! userAgents . contains ( userAgent ) ) { userAgents . add ( userAgent ) ; } updateUserAgents ( ) ; }


Input: Reads the InputStream as UTF - 8 [CODESPLIT] private static String _toCharArray ( InputStream stream ) throws IOException { InputStreamReader is = new InputStreamReader ( stream , "UTF-8" ) ; StringBuilder builder = new StringBuilder ( ) ; char [ ] buf = new char [ 1000 ] ; int l = 0 ; while ( l >= 0 ) { builder . append ( buf , 0 , l ) ; l = is . read ( buf ) ; } is . close ( ) ; return builder . toString ( ) ; }


Input: Reads the InputStream into a byte array [CODESPLIT] private static byte [ ] _toByteArray ( InputStream stream ) throws AlgoliaException { ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; int read ; byte [ ] buffer = new byte [ 1024 ] ; try { while ( ( read = stream . read ( buffer , 0 , buffer . length ) ) != - 1 ) { out . write ( buffer , 0 , read ) ; } out . flush ( ) ; return out . toByteArray ( ) ; } catch ( IOException e ) { throw new AlgoliaException ( "Error while reading stream: " + e . getMessage ( ) ) ; } }


Input: Send the query according to parameters and returns its result as a JSONObject [CODESPLIT] private JSONObject _request ( @ NonNull Method m , @ NonNull String url , @ Nullable Map < String , String > urlParameters , @ Nullable String json , @ NonNull List < String > hostsArray , int connectTimeout , int readTimeout , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { return _getJSONObject ( _requestRaw ( m , url , urlParameters , json , hostsArray , connectTimeout , readTimeout , requestOptions ) ) ; } catch ( JSONException e ) { throw new AlgoliaException ( "JSON decode error:" + e . getMessage ( ) ) ; } catch ( UnsupportedEncodingException e ) { throw new AlgoliaException ( "UTF-8 decode error:" + e . getMessage ( ) ) ; } }


Input: Send the query according to parameters and returns its result as a JSONObject [CODESPLIT] private byte [ ] _requestRaw ( @ NonNull Method m , @ NonNull String url , @ Nullable Map < String , String > urlParameters , @ Nullable String json , @ NonNull List < String > hostsArray , int connectTimeout , int readTimeout , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { String requestMethod ; List < Exception > errors = new ArrayList <> ( hostsArray . size ( ) ) ; // for each host for ( String host : hostsArray ) { switch ( m ) { case DELETE : requestMethod = "DELETE" ; break ; case GET : requestMethod = "GET" ; break ; case POST : requestMethod = "POST" ; break ; case PUT : requestMethod = "PUT" ; break ; default : throw new IllegalArgumentException ( "Method " + m + " is not supported" ) ; } InputStream stream = null ; HttpURLConnection hostConnection = null ; try { // Compute final URL parameters. final Map < String , String > parameters = new HashMap <> ( ) ; if ( urlParameters != null ) { parameters . putAll ( urlParameters ) ; } if ( requestOptions != null ) { parameters . putAll ( requestOptions . urlParameters ) ; } // Build URL. String urlString = "https://" + host + url ; if ( ! parameters . isEmpty ( ) ) { urlString += "?" + AbstractQuery . build ( parameters ) ; } URL hostURL = new URL ( urlString ) ; // Open connection. hostConnection = ( HttpURLConnection ) hostURL . openConnection ( ) ; //set timeouts hostConnection . setRequestMethod ( requestMethod ) ; hostConnection . setConnectTimeout ( connectTimeout ) ; hostConnection . setReadTimeout ( readTimeout ) ; // Headers hostConnection . setRequestProperty ( "Accept-Encoding" , "gzip" ) ; hostConnection . setRequestProperty ( "X-Algolia-Application-Id" , this . applicationID ) ; // If API key is too big, send it in the request's body (if applicable). if ( this . apiKey != null && this . apiKey . length ( ) > MAX_API_KEY_LENGTH && json != null ) { try { final JSONObject body = new JSONObject ( json ) ; body . put ( "apiKey" , this . apiKey ) ; json = body . toString ( ) ; } catch ( JSONException e ) { throw new AlgoliaException ( "Failed to patch JSON body" ) ; } } else { hostConnection . setRequestProperty ( "X-Algolia-API-Key" , this . apiKey ) ; } // Client-level headers for ( Map . Entry < String , String > entry : this . headers . entrySet ( ) ) { hostConnection . setRequestProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } // Request-level headers if ( requestOptions != null ) { for ( Map . Entry < String , String > entry : requestOptions . headers . entrySet ( ) ) { hostConnection . setRequestProperty ( entry . getKey ( ) , entry . getValue ( ) ) ; } } // set user agent hostConnection . setRequestProperty ( "User-Agent" , userAgentRaw ) ; // write JSON entity if ( json != null ) { if ( ! ( requestMethod . equals ( "PUT" ) || requestMethod . equals ( "POST" ) ) ) { throw new IllegalArgumentException ( "Method " + m + " cannot enclose entity" ) ; } hostConnection . setRequestProperty ( "Content-type" , "application/json; charset=UTF-8" ) ; hostConnection . setDoOutput ( true ) ; OutputStreamWriter writer = new OutputStreamWriter ( hostConnection . getOutputStream ( ) , "UTF-8" ) ; writer . write ( json ) ; writer . close ( ) ; } // read response int code = hostConnection . getResponseCode ( ) ; final boolean codeIsError = code / 100 != 2 ; stream = codeIsError ? hostConnection . getErrorStream ( ) : hostConnection . getInputStream ( ) ; // As per the official Java docs (not the Android docs): // - `getErrorStream()` may return null => we have to handle this case. //   See <https://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html#getErrorStream()>. // - `getInputStream()` should never return null... but let's err on the side of caution. //   See <https://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getInputStream()>. if ( stream == null ) { throw new IOException ( String . format ( "Null stream when reading connection (status %d)" , code ) ) ; } hostStatuses . put ( host , new HostStatus ( true ) ) ; final byte [ ] rawResponse ; String encoding = hostConnection . getContentEncoding ( ) ; if ( encoding != null && encoding . equals ( "gzip" ) ) { rawResponse = _toByteArray ( new GZIPInputStream ( stream ) ) ; } else { rawResponse = _toByteArray ( stream ) ; } // handle http errors if ( codeIsError ) { if ( code / 100 == 4 ) { consumeQuietly ( hostConnection ) ; throw new AlgoliaException ( _getJSONObject ( rawResponse ) . getString ( "message" ) , code ) ; } else { consumeQuietly ( hostConnection ) ; errors . add ( new AlgoliaException ( _toCharArray ( stream ) , code ) ) ; continue ; } } return rawResponse ; } catch ( JSONException e ) { // fatal consumeQuietly ( hostConnection ) ; throw new AlgoliaException ( "Invalid JSON returned by server" , e ) ; } catch ( UnsupportedEncodingException e ) { // fatal consumeQuietly ( hostConnection ) ; throw new AlgoliaException ( "Invalid encoding returned by server" , e ) ; } catch ( IOException e ) { // host error, continue on the next host hostStatuses . put ( host , new HostStatus ( false ) ) ; consumeQuietly ( hostConnection ) ; errors . add ( e ) ; } finally { if ( stream != null ) { try { stream . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } String errorMessage = "All hosts failed: " + Arrays . toString ( errors . toArray ( ) ) ; // When several errors occurred, use the last one as the cause for the returned exception. Throwable lastError = errors . get ( errors . size ( ) - 1 ) ; throw new AlgoliaException ( errorMessage , lastError ) ; }


Input: Ensures that the entity content is fully consumed and the content stream if exists is closed . [CODESPLIT] private static void consumeQuietly ( final HttpURLConnection connection ) { try { int read = 0 ; while ( read != - 1 ) { read = connection . getInputStream ( ) . read ( ) ; } connection . getInputStream ( ) . close ( ) ; read = 0 ; while ( read != - 1 ) { read = connection . getErrorStream ( ) . read ( ) ; } connection . getErrorStream ( ) . close ( ) ; connection . disconnect ( ) ; } catch ( IOException e ) { // no inputStream to close } }


Input: Get the hosts that are not considered down in a given list . [CODESPLIT] private List < String > hostsThatAreUp ( List < String > hosts ) { List < String > upHosts = new ArrayList <> ( ) ; for ( String host : hosts ) { if ( isUpOrCouldBeRetried ( host ) ) { upHosts . add ( host ) ; } } return upHosts . isEmpty ( ) ? hosts : upHosts ; }


Input: Force to * first * search around a specific latitude / longitude . The default is to search around the location of the user determined via his IP address ( geoip ) . [CODESPLIT] public @ NonNull PlacesQuery setAroundLatLng ( LatLng location ) { if ( location == null ) { return set ( KEY_AROUND_LAT_LNG , null ) ; } else { return set ( KEY_AROUND_LAT_LNG , location . lat + "," + location . lng ) ; } }


Input: Change the radius for around latitude / longitude queries . [CODESPLIT] public @ NonNull PlacesQuery setAroundRadius ( Integer radius ) { if ( radius == PlacesQuery . RADIUS_ALL ) { return set ( KEY_AROUND_RADIUS , "all" ) ; } return set ( KEY_AROUND_RADIUS , radius ) ; }


Input: Get the current radius for around latitude / longitude queries . [CODESPLIT] public Integer getAroundRadius ( ) { final String value = get ( KEY_AROUND_RADIUS ) ; if ( value != null && value . equals ( "all" ) ) { return PlacesQuery . RADIUS_ALL ; } return parseInt ( value ) ; }


Input: Set the type of place to search for . [CODESPLIT] public @ NonNull PlacesQuery setType ( Type type ) { if ( type == null ) { set ( KEY_TYPE , null ) ; } else { switch ( type ) { case CITY : set ( KEY_TYPE , "city" ) ; break ; case COUNTRY : set ( KEY_TYPE , "country" ) ; break ; case ADDRESS : set ( KEY_TYPE , "address" ) ; break ; case BUS_STOP : set ( KEY_TYPE , "busStop" ) ; break ; case TRAIN_STATION : set ( KEY_TYPE , "trainStation" ) ; break ; case TOWN_HALL : set ( KEY_TYPE , "townhall" ) ; break ; case AIRPORT : set ( KEY_TYPE , "airport" ) ; break ; } } return this ; }


Input: Parse a query object from a URL query parameter string . [CODESPLIT] protected static @ NonNull PlacesQuery parse ( @ NonNull String queryParameters ) { PlacesQuery query = new PlacesQuery ( ) ; query . parseFrom ( queryParameters ) ; return query ; }


Input: Set a parameter in an untyped fashion . This low - level accessor is intended to access parameters that this client does not yet support . [CODESPLIT] @ Override public @ NonNull PlacesQuery set ( @ NonNull String name , @ Nullable Object value ) { return ( PlacesQuery ) super . set ( name , value ) ; }


Input: Start the iteration . [CODESPLIT] public void start ( ) { if ( started ) { throw new IllegalStateException ( ) ; } started = true ; request = index . browseAsync ( query , requestOptions , completionHandler ) ; }


Input: Search inside this index ( asynchronously ) . [CODESPLIT] public Request searchAsync ( @ Nullable Query query , @ Nullable CompletionHandler completionHandler ) { return searchAsync ( query , /* requestOptions: */ null , completionHandler ) ; }


Input: Perform a search with disjunctive facets generating as many queries as number of disjunctive facets ( helper ) . [CODESPLIT] public Request searchDisjunctiveFacetingAsync ( @ NonNull Query query , @ NonNull final Collection < String > disjunctiveFacets , @ NonNull final Map < String , ? extends Collection < String > > refinements , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler completionHandler ) { throw new UnsupportedOperationException ( "make sure to override searchDisjunctiveFacetingAsync for custom backend" ) ; }


Input: Search for some text in a facet values optionally restricting the returned values to those contained in objects matching other ( regular ) search criteria . [CODESPLIT] public Request searchForFacetValuesAsync ( @ NonNull String facetName , @ NonNull String facetText , @ Nullable Query query , @ Nullable final RequestOptions requestOptions , @ NonNull final CompletionHandler handler ) { throw new UnsupportedOperationException ( "make sure to override searchForFacetValuesAsync for custom backend" ) ; }


Input: List existing indexes . [CODESPLIT] public Request listIndexesAsync ( @ Nullable final RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return listIndexes ( requestOptions ) ; } } . start ( ) ; }


Input: Delete an index . [CODESPLIT] public Request deleteIndexAsync ( final @ NonNull String indexName , @ Nullable final RequestOptions requestOptions , CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return deleteIndex ( indexName , requestOptions ) ; } } . start ( ) ; }


Input: Delete an index . [CODESPLIT] public Request deleteIndexAsync ( final @ NonNull String indexName , CompletionHandler completionHandler ) { return deleteIndexAsync ( indexName , /* requestOptions: */ null , completionHandler ) ; }


Input: Move an existing index . If the destination index already exists its specific API keys will be preserved and the source index specific API keys will be added . [CODESPLIT] public Request moveIndexAsync ( final @ NonNull String srcIndexName , final @ NonNull String dstIndexName , @ Nullable final RequestOptions requestOptions , CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return moveIndex ( srcIndexName , dstIndexName , requestOptions ) ; } } . start ( ) ; }


Input: Move an existing index . If the destination index already exists its specific API keys will be preserved and the source index specific API keys will be added . [CODESPLIT] public Request moveIndexAsync ( final @ NonNull String srcIndexName , final @ NonNull String dstIndexName , CompletionHandler completionHandler ) { return moveIndexAsync ( srcIndexName , dstIndexName , /* requestOptions: */ null , completionHandler ) ; }


Input: Run multiple queries potentially targeting multiple indexes with one API call . [CODESPLIT] public Request multipleQueriesAsync ( final @ NonNull List < IndexQuery > queries , final MultipleQueriesStrategy strategy , @ Nullable final RequestOptions requestOptions , @ NonNull CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return multipleQueries ( queries , strategy == null ? null : strategy . toString ( ) , requestOptions ) ; } } . start ( ) ; }


Input: Run multiple queries potentially targeting multiple indexes with one API call . [CODESPLIT] public Request multipleQueriesAsync ( final @ NonNull List < IndexQuery > queries , final MultipleQueriesStrategy strategy , @ NonNull CompletionHandler completionHandler ) { return multipleQueriesAsync ( queries , strategy , /* requestOptions: */ null , completionHandler ) ; }


Input: Batch operations . [CODESPLIT] public Request batchAsync ( final @ NonNull JSONArray operations , @ Nullable final RequestOptions requestOptions , CompletionHandler completionHandler ) { return new AsyncTaskRequest ( completionHandler ) { @ NonNull @ Override protected JSONObject run ( ) throws AlgoliaException { return batch ( operations , requestOptions ) ; } } . start ( ) ; }


Input: Batch operations . [CODESPLIT] public Request batchAsync ( final @ NonNull JSONArray operations , CompletionHandler completionHandler ) { return batchAsync ( operations , /* requestOptions: */ null , completionHandler ) ; }


Input: List all existing indexes [CODESPLIT] protected JSONObject listIndexes ( @ Nullable RequestOptions requestOptions ) throws AlgoliaException { return getRequest ( "/1/indexes/" , /* urlParameters: */ null , false , requestOptions ) ; }


Input: Delete an index [CODESPLIT] protected JSONObject deleteIndex ( String indexName , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { return deleteRequest ( "/1/indexes/" + URLEncoder . encode ( indexName , "UTF-8" ) , /* urlParameters: */ null , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }


Input: Move an existing index . [CODESPLIT] protected JSONObject moveIndex ( String srcIndexName , String dstIndexName , @ Nullable RequestOptions requestOptions ) throws AlgoliaException { try { JSONObject content = new JSONObject ( ) ; content . put ( "operation" , "move" ) ; content . put ( "destination" , dstIndexName ) ; return postRequest ( "/1/indexes/" + URLEncoder . encode ( srcIndexName , "UTF-8" ) + "/operation" , /* urlParameters: */ null , content . toString ( ) , false , requestOptions ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } catch ( JSONException e ) { throw new AlgoliaException ( e . getMessage ( ) ) ; } }


Input: Puts a value in the cache computing an expiration time [CODESPLIT] public V put ( K key , V value ) { V previous = null ; synchronized ( this ) { long timeout = System . currentTimeMillis ( ) + TimeUnit . MILLISECONDS . convert ( expirationTimeout , expirationTimeUnit ) ; final Pair < V , Long > previousPair = lruCache . put ( key , new Pair <> ( value , timeout ) ) ; if ( previousPair != null ) { previous = previousPair . first ; } } return previous ; }


Input: Get a value from the cache [CODESPLIT] synchronized public V get ( K key ) { final Pair < V , Long > cachePair = lruCache . get ( key ) ; if ( cachePair != null && cachePair . first != null ) { if ( cachePair . second > System . currentTimeMillis ( ) ) { return cachePair . first ; } else { lruCache . remove ( key ) ; } } return null ; }


Input: Run the log processor with the currently provided arguments . [CODESPLIT] @ Override public void run ( ) { PrintStream timeIntervalLog = null ; PrintStream histogramPercentileLog = System . out ; Double firstStartTime = 0.0 ; boolean timeIntervalLogLegendWritten = false ; if ( config . listTags ) { Set < String > tags = new TreeSet < String > ( ) ; EncodableHistogram histogram ; boolean nullTagFound = false ; while ( ( histogram = getIntervalHistogram ( ) ) != null ) { String tag = histogram . getTag ( ) ; if ( tag != null ) { tags . add ( histogram . getTag ( ) ) ; } else { nullTagFound = true ; } } System . out . println ( "Tags found in input file: " ) ; if ( nullTagFound ) { System . out . println ( "[NO TAG (default)]" ) ; } for ( String tag : tags ) { System . out . println ( tag ) ; } // listtags does nothing other than list tags: return ; } final String logFormat = buildLogFormat ( config . logFormatCsv ) ; try { if ( config . outputFileName != null ) { try { timeIntervalLog = new PrintStream ( new FileOutputStream ( config . outputFileName ) , false , "UTF-8" ) ; outputTimeRange ( timeIntervalLog , "Interval percentile log" ) ; } catch ( FileNotFoundException ex ) { System . err . println ( "Failed to open output file " + config . outputFileName ) ; } catch ( UnsupportedEncodingException e ) { System . err . println ( "Unsupported encoding: UTF-8" ) ; } String hgrmOutputFileName = config . outputFileName + ".hgrm" ; try { histogramPercentileLog = new PrintStream ( new FileOutputStream ( hgrmOutputFileName ) , false , "UTF-8" ) ; outputTimeRange ( histogramPercentileLog , "Overall percentile distribution" ) ; } catch ( FileNotFoundException ex ) { System . err . println ( "Failed to open percentiles histogram output file " + hgrmOutputFileName ) ; } catch ( UnsupportedEncodingException e ) { System . err . println ( "Unsupported encoding: UTF-8" ) ; } } EncodableHistogram intervalHistogram = getIntervalHistogram ( config . tag ) ; Histogram accumulatedRegularHistogram = null ; DoubleHistogram accumulatedDoubleHistogram = null ; if ( intervalHistogram != null ) { // Shape the accumulated histogram like the histograms in the log file (but clear their contents): if ( intervalHistogram instanceof DoubleHistogram ) { accumulatedDoubleHistogram = ( ( DoubleHistogram ) intervalHistogram ) . copy ( ) ; accumulatedDoubleHistogram . reset ( ) ; accumulatedDoubleHistogram . setAutoResize ( true ) ; } else { accumulatedRegularHistogram = ( ( Histogram ) intervalHistogram ) . copy ( ) ; accumulatedRegularHistogram . reset ( ) ; accumulatedRegularHistogram . setAutoResize ( true ) ; } } while ( intervalHistogram != null ) { if ( intervalHistogram instanceof DoubleHistogram ) { if ( accumulatedDoubleHistogram == null ) { throw new IllegalStateException ( "Encountered a DoubleHistogram line in a log of Histograms." ) ; } accumulatedDoubleHistogram . add ( ( DoubleHistogram ) intervalHistogram ) ; } else { if ( accumulatedRegularHistogram == null ) { throw new IllegalStateException ( "Encountered a Histogram line in a log of DoubleHistograms." ) ; } accumulatedRegularHistogram . add ( ( Histogram ) intervalHistogram ) ; } if ( ( firstStartTime == 0.0 ) && ( logReader . getStartTimeSec ( ) != 0.0 ) ) { firstStartTime = logReader . getStartTimeSec ( ) ; outputStartTime ( histogramPercentileLog , firstStartTime ) ; if ( timeIntervalLog != null ) { outputStartTime ( timeIntervalLog , firstStartTime ) ; } } if ( timeIntervalLog != null ) { if ( ! timeIntervalLogLegendWritten ) { timeIntervalLogLegendWritten = true ; timeIntervalLog . println ( buildLegend ( config . logFormatCsv ) ) ; } Object [ ] statistics = intervalHistogram instanceof DoubleHistogram ? buildDoubleHistogramStatistics ( ( DoubleHistogram ) intervalHistogram , accumulatedDoubleHistogram ) : buildRegularHistogramStatistics ( ( Histogram ) intervalHistogram , accumulatedRegularHistogram ) ; timeIntervalLog . format ( Locale . US , logFormat , statistics ) ; } intervalHistogram = getIntervalHistogram ( config . tag ) ; } if ( accumulatedDoubleHistogram != null ) { accumulatedDoubleHistogram . outputPercentileDistribution ( histogramPercentileLog , config . percentilesOutputTicksPerHalf , config . outputValueUnitRatio , config . logFormatCsv ) ; } else { if ( accumulatedRegularHistogram == null ) { // If there were no histograms in the log file, we still need an empty histogram for the // one line output (shape/range doesn't matter because it is empty): accumulatedRegularHistogram = new Histogram ( 1000000L , 2 ) ; } accumulatedRegularHistogram . outputPercentileDistribution ( histogramPercentileLog , config . percentilesOutputTicksPerHalf , config . outputValueUnitRatio , config . logFormatCsv ) ; } } finally { if ( config . outputFileName != null ) { closeQuietly ( timeIntervalLog ) ; closeQuietly ( histogramPercentileLog ) ; } } }


Input: Combines { @link PerformanceStats } instances e . g . from different Simulator Workers . <p > For the real - time performance monitor during the { @link TestPhase#RUN } the maximum value should be set so we get the maximum operation count and throughput values of all { @link PerformanceStats } instances of the last interval . <p > For the total performance number and the performance per Simulator Agent the added values should be set so we get the summed up operation count and throughput values . <p > The method always sets the maximum values for latency . [CODESPLIT] public void add ( PerformanceStats other , boolean addOperationCountAndThroughput ) { if ( other . isEmpty ( ) ) { return ; } if ( isEmpty ( ) ) { operationCount = other . operationCount ; intervalThroughput = other . intervalThroughput ; totalThroughput = other . totalThroughput ; intervalLatencyAvgNanos = other . intervalLatencyAvgNanos ; intervalLatency999PercentileNanos = other . intervalLatency999PercentileNanos ; intervalLatencyMaxNanos = other . intervalLatencyMaxNanos ; } else { if ( addOperationCountAndThroughput ) { operationCount += other . operationCount ; intervalThroughput += other . intervalThroughput ; totalThroughput += other . totalThroughput ; } else { operationCount = max ( operationCount , other . operationCount ) ; intervalThroughput = max ( intervalThroughput , other . intervalThroughput ) ; totalThroughput = max ( totalThroughput , other . totalThroughput ) ; } intervalLatencyAvgNanos = max ( intervalLatencyAvgNanos , other . intervalLatencyAvgNanos ) ; intervalLatency999PercentileNanos = max ( intervalLatency999PercentileNanos , other . intervalLatency999PercentileNanos ) ; intervalLatencyMaxNanos = max ( intervalLatencyMaxNanos , other . intervalLatencyMaxNanos ) ; } }


Input: Spawns a new thread for the given { @link Runnable } . [CODESPLIT] public Thread spawn ( String namePrefix , Runnable runnable ) { checkNotNull ( namePrefix , "namePrefix can't be null" ) ; checkNotNull ( runnable , "runnable can't be null" ) ; String name = newName ( namePrefix ) ; Thread thread ; if ( throwException ) { thread = new ThrowExceptionThread ( name , runnable ) ; thread . setUncaughtExceptionHandler ( exceptionHandler ) ; } else { thread = new ReportExceptionThread ( testId , name , runnable ) ; } threads . add ( thread ) ; thread . start ( ) ; return thread ; }


Input: Waits for all threads to finish . [CODESPLIT] public void awaitCompletion ( ) { for ( Thread thread : threads ) { try { thread . join ( ) ; } catch ( InterruptedException e ) { throw rethrow ( e ) ; } } if ( caughtException != null ) { throw rethrow ( caughtException ) ; } }


Input: Compares two version strings . [CODESPLIT] public static int versionCompare ( String firstVersionString , String secondVersionString ) { String [ ] firstVersion = parseVersionString ( firstVersionString ) ; String [ ] secondVersion = parseVersionString ( secondVersionString ) ; int i = 0 ; // set index to first non-equal ordinal or length of shortest version string while ( i < firstVersion . length && i < secondVersion . length && firstVersion [ i ] . equals ( secondVersion [ i ] ) ) { i ++ ; } if ( i < firstVersion . length && i < secondVersion . length ) { // compare first non-equal ordinal number int diff = Integer . valueOf ( firstVersion [ i ] ) . compareTo ( Integer . valueOf ( secondVersion [ i ] ) ) ; return Integer . signum ( diff ) ; } else { // the strings are equal or one string is a substring of the other // e.g. "1.2.3" = "1.2.3" or "1.2.3" < "1.2.3.4" return Integer . signum ( firstVersion . length - secondVersion . length ) ; } }


Input: Writes the cause to file . [CODESPLIT] public static void report ( String testId , Throwable cause ) { if ( cause == null ) { LOGGER . fatal ( "Can't call report with a null exception" ) ; return ; } long exceptionCount = FAILURE_ID . incrementAndGet ( ) ; if ( exceptionCount > MAX_EXCEPTION_COUNT ) { LOGGER . warn ( "Exception #" + exceptionCount + " detected. The maximum number of exceptions has been exceeded, so it" + " won't be reported to the Agent." , cause ) ; return ; } LOGGER . warn ( "Exception #" + exceptionCount + " detected" , cause ) ; String targetFileName = exceptionCount + ".exception" ; File dir = getUserDir ( ) ; File tmpFile = new File ( dir , targetFileName + ".tmp" ) ; try { if ( ! tmpFile . createNewFile ( ) ) { throw new IOException ( "Could not create tmp file: " + tmpFile . getAbsolutePath ( ) ) ; } } catch ( IOException e ) { LOGGER . fatal ( "Could not report exception; this means that this exception is not visible to the coordinator" , e ) ; return ; } writeText ( testId + NEW_LINE + throwableToString ( cause ) , tmpFile ) ; File file = new File ( dir , targetFileName ) ; LOGGER . info ( file . getAbsolutePath ( ) ) ; rename ( tmpFile , file ) ; }


Input: Copies a directory recursively . [CODESPLIT] public static void copyDirectory ( File src , File target ) { checkNotNull ( src , "src can't be null" ) ; checkNotNull ( target , "target can't be null" ) ; File [ ] files = src . listFiles ( ) ; if ( files == null ) { return ; } for ( File srcFile : files ) { if ( srcFile . isDirectory ( ) ) { File targetChild = new File ( target , srcFile . getName ( ) ) ; ensureExistingDirectory ( targetChild ) ; copyDirectory ( srcFile , targetChild ) ; } else { copyFileToDirectory ( srcFile , target ) ; } } }


Input: Initializes the SimulatorProperties with additional properties . [CODESPLIT] public SimulatorProperties init ( File file ) { if ( file == null ) { // if no file is explicitly given, we look in the working directory file = new File ( getUserDir ( ) , PROPERTIES_FILE_NAME ) ; if ( ! file . exists ( ) ) { LOGGER . info ( format ( "Found no %s in working directory, relying on default properties" , PROPERTIES_FILE_NAME ) ) ; return null ; } } LOGGER . info ( format ( "Loading additional %s: %s" , PROPERTIES_FILE_NAME , file . getAbsolutePath ( ) ) ) ; check ( file ) ; load ( file , false ) ; return this ; }


Input: Binds a single property contained in the { @link TestCase } instance onto the object instance . [CODESPLIT] public static boolean bind ( Object instance , TestCase testCase , String propertyName ) { String value = getValue ( testCase , propertyName ) ; if ( value == null ) { return false ; } return bind0 ( instance , propertyName , value ) ; }


Input: Returns a single property contained in the { @link TestCase } instance . [CODESPLIT] private static String getValue ( TestCase testCase , String propertyName ) { if ( testCase == null ) { return null ; } String propertyValue = testCase . getProperty ( propertyName ) ; if ( propertyValue == null || propertyValue . isEmpty ( ) ) { return null ; } return propertyValue ; }


Input: Gets the value for a static field . [CODESPLIT] public static < E > E getStaticFieldValue ( Class clazz , String fieldName , Class fieldType ) { Field field = getField ( clazz , fieldName , fieldType ) ; if ( field == null ) { throw new ReflectionException ( format ( "Field %s.%s is not found" , clazz . getName ( ) , fieldName ) ) ; } field . setAccessible ( true ) ; return getFieldValue0 ( null , field , clazz . getName ( ) , fieldName ) ; }


Input: Searches a method by name . [CODESPLIT] public static Method getMethodByName ( Class clazz , String methodName ) { for ( Method method : clazz . getDeclaredMethods ( ) ) { if ( method . getName ( ) . equals ( methodName ) ) { return method ; } } return null ; }


Input: launching is done asynchronous so we don t block the calling thread ( messaging thread ) [CODESPLIT] public void launch ( CreateWorkerOperation op , Promise promise ) { WorkerParameters workerParameters = op . getWorkerParameters ( ) ; // we add the pid to the worker-parameters so the worker can check if the agent is still alive. workerParameters . set ( "agent.pid" , getPID ( ) ) ; WorkerProcessLauncher launcher = new WorkerProcessLauncher ( WorkerProcessManager . this , workerParameters ) ; LaunchSingleWorkerTask task = new LaunchSingleWorkerTask ( launcher , workerParameters , promise ) ; executorService . schedule ( task , op . getDelayMs ( ) , MILLISECONDS ) ; }


Input: http : // stackoverflow . com / questions / 35842 / how - can - a - java - program - get - its - own - process - id [CODESPLIT] public static int getPID ( ) { Integer pid = getPidFromManagementBean ( ) ; if ( pid != null ) { return pid ; } pid = getPidViaReflection ( ) ; if ( pid != null ) { return pid ; } return - 1 ; }


Input: Sleeps a random amount of time . <p > The call is ignored if maxDelayNanos equals or smaller than zero . [CODESPLIT] public static void sleepRandomNanos ( Random random , long maxDelayNanos ) { if ( maxDelayNanos <= 0 ) { return ; } long randomValue = Math . abs ( random . nextLong ( ) + 1 ) ; sleepNanos ( randomValue % maxDelayNanos ) ; }


Input: Formats a percentage of two numbers and adds padding to the left . [CODESPLIT] public static String formatPercentage ( long value , long baseValue ) { double percentage = ( baseValue > 0 ? ( ONE_HUNDRED * value ) / baseValue : 0 ) ; return formatDouble ( percentage , PERCENTAGE_FORMAT_LENGTH ) ; }


Input: Formats a double number and adds padding to the left . [CODESPLIT] public static String formatDouble ( double number , int length ) { return padLeft ( format ( Locale . US , "%,.2f" , number ) , length ) ; }


Input: Formats a long number and adds padding to the left . [CODESPLIT] public static String formatLong ( long number , int length ) { return padLeft ( format ( Locale . US , "%,d" , number ) , length ) ; }


Input: Prepares the key store and our keys for encrypting / decrypting . Keys will be generated if we haven t done so yet and keys will be re - generated if the old ones have been invalidated . In both cases our K / V store will be cleared before continuing . [CODESPLIT] void prepareKeyStore ( ) { try { Key key = keyStore . getKey ( keyAlias , null ) ; Certificate certificate = keyStore . getCertificate ( keyAlias ) ; if ( key != null && certificate != null ) { try { createCipher ( ) . init ( Cipher . DECRYPT_MODE , key ) ; // We have a keys in the store and they're still valid. return ; } catch ( KeyPermanentlyInvalidatedException e ) { Log . d ( TAG , "Key invalidated." ) ; } } storage . clear ( ) ; keyGenerator . initialize ( new KeyGenParameterSpec . Builder ( keyAlias , KeyProperties . PURPOSE_ENCRYPT | KeyProperties . PURPOSE_DECRYPT ) // . setBlockModes ( KeyProperties . BLOCK_MODE_ECB ) // . setUserAuthenticationRequired ( true ) // . setEncryptionPaddings ( KeyProperties . ENCRYPTION_PADDING_RSA_PKCS1 ) // . build ( ) ) ; keyGenerator . generateKeyPair ( ) ; } catch ( GeneralSecurityException e ) { throw new RuntimeException ( e ) ; } }


Input: and JsonPairContext . read [CODESPLIT] protected void readJsonSyntaxChar ( byte [ ] b ) throws IOException { byte ch = reader . read ( ) ; if ( ch != b [ 0 ] ) { throw new ProtocolException ( "Unexpected character:" + ( char ) ch ) ; } }


Input: corresponding hex value [CODESPLIT] private static byte hexVal ( byte ch ) throws IOException { if ( ( ch >= ' ' ) && ( ch <= ' ' ) ) { return ( byte ) ( ( char ) ch - ' ' ) ; } else if ( ( ch >= ' ' ) && ( ch <= ' ' ) ) { return ( byte ) ( ( char ) ch - ' ' + 10 ) ; } else { throw new ProtocolException ( "Expected hex character" ) ; } }


Input: Write the bytes in array buf as a Json characters escaping as needed [CODESPLIT] private void writeJsonString ( byte [ ] b ) throws IOException { context . write ( ) ; transport . write ( QUOTE ) ; int len = b . length ; for ( int i = 0 ; i < len ; i ++ ) { if ( ( b [ i ] & 0x00FF ) >= 0x30 ) { if ( b [ i ] == BACKSLASH [ 0 ] ) { transport . write ( BACKSLASH ) ; transport . write ( BACKSLASH ) ; } else { transport . write ( b , i , 1 ) ; } } else { tmpbuf [ 0 ] = JSON_CHAR_TABLE [ b [ i ] ] ; if ( tmpbuf [ 0 ] == 1 ) { transport . write ( b , i , 1 ) ; } else if ( tmpbuf [ 0 ] > 1 ) { transport . write ( BACKSLASH ) ; transport . write ( tmpbuf , 0 , 1 ) ; } else { transport . write ( ESCSEQ ) ; tmpbuf [ 0 ] = hexChar ( ( byte ) ( b [ i ] >> 4 ) ) ; tmpbuf [ 1 ] = hexChar ( b [ i ] ) ; transport . write ( tmpbuf , 0 , 2 ) ; } } } transport . write ( QUOTE ) ; }


Input: wrapped in quotes to output as a Json string . [CODESPLIT] private void writeJsonInteger ( long num ) throws IOException { context . write ( ) ; String str = Long . toString ( num ) ; boolean escapeNum = context . escapeNum ( ) ; if ( escapeNum ) { transport . write ( QUOTE ) ; } try { byte [ ] buf = str . getBytes ( "UTF-8" ) ; transport . write ( buf ) ; } catch ( UnsupportedEncodingException e ) { throw new AssertionError ( e ) ; } if ( escapeNum ) { transport . write ( QUOTE ) ; } }


Input: context dictates escaping write out as Json string . [CODESPLIT] private void writeJsonDouble ( double num ) throws IOException { context . write ( ) ; String str = Double . toString ( num ) ; boolean special = false ; switch ( str . charAt ( 0 ) ) { case ' ' : // NaN case ' ' : // Infinity special = true ; break ; case ' ' : if ( str . charAt ( 1 ) == ' ' ) { // -Infinity special = true ; } break ; default : break ; } boolean escapeNum = special || context . escapeNum ( ) ; if ( escapeNum ) { transport . write ( QUOTE ) ; } try { byte [ ] b = str . getBytes ( "UTF-8" ) ; transport . write ( b , 0 , b . length ) ; } catch ( UnsupportedEncodingException e ) { throw new AssertionError ( e ) ; } if ( escapeNum ) { transport . write ( QUOTE ) ; } }


Input: context if skipContext is true . [CODESPLIT] private ByteString readJsonString ( boolean skipContext ) throws IOException { Buffer buffer = new Buffer ( ) ; ArrayList < Character > codeunits = new ArrayList <> ( ) ; if ( ! skipContext ) { context . read ( ) ; } readJsonSyntaxChar ( QUOTE ) ; while ( true ) { byte ch = reader . read ( ) ; if ( ch == QUOTE [ 0 ] ) { break ; } if ( ch == ESCSEQ [ 0 ] ) { ch = reader . read ( ) ; if ( ch == ESCSEQ [ 1 ] ) { transport . read ( tmpbuf , 0 , 4 ) ; short cu = ( short ) ( ( ( short ) hexVal ( tmpbuf [ 0 ] ) << 12 ) + ( ( short ) hexVal ( tmpbuf [ 1 ] ) << 8 ) + ( ( short ) hexVal ( tmpbuf [ 2 ] ) << 4 ) + ( short ) hexVal ( tmpbuf [ 3 ] ) ) ; try { if ( Character . isHighSurrogate ( ( char ) cu ) ) { if ( codeunits . size ( ) > 0 ) { throw new ProtocolException ( "Expected low surrogate char" ) ; } codeunits . add ( ( char ) cu ) ; } else if ( Character . isLowSurrogate ( ( char ) cu ) ) { if ( codeunits . size ( ) == 0 ) { throw new ProtocolException ( "Expected high surrogate char" ) ; } codeunits . add ( ( char ) cu ) ; buffer . write ( new String ( new int [ ] { codeunits . get ( 0 ) , codeunits . get ( 1 ) } , 0 , 2 ) . getBytes ( "UTF-8" ) ) ; codeunits . clear ( ) ; } else { buffer . write ( new String ( new int [ ] { cu } , 0 , 1 ) . getBytes ( "UTF-8" ) ) ; } continue ; } catch ( UnsupportedEncodingException e ) { throw new AssertionError ( e ) ; } catch ( IOException ex ) { throw new ProtocolException ( "Invalid unicode sequence" ) ; } } else { int off = ESCAPE_CHARS . indexOf ( ch ) ; if ( off == - 1 ) { throw new ProtocolException ( "Expected control char" ) ; } ch = ESCAPE_CHAR_VALS [ off ] ; } } buffer . write ( new byte [ ] { ch } ) ; } return buffer . readByteString ( ) ; }


Input: not do a complete regex check to validate that this is actually a number . [CODESPLIT] private String readJsonNumericChars ( ) throws IOException { StringBuilder strbld = new StringBuilder ( ) ; while ( true ) { byte ch = reader . peek ( ) ; if ( ! isJsonNumeric ( ch ) ) { break ; } strbld . append ( ( char ) reader . read ( ) ) ; } return strbld . toString ( ) ; }


Input: Read in a Json number . If the context dictates read in enclosing quotes . [CODESPLIT] private long readJsonInteger ( ) throws IOException { context . read ( ) ; if ( context . escapeNum ( ) ) { readJsonSyntaxChar ( QUOTE ) ; } String str = readJsonNumericChars ( ) ; if ( context . escapeNum ( ) ) { readJsonSyntaxChar ( QUOTE ) ; } try { return Long . valueOf ( str ) ; } catch ( NumberFormatException ex ) { throw new ProtocolException ( "Bad data encountered in numeric data" ) ; } }


Input: when expected or if wrapped in quotes when not expected . [CODESPLIT] private double readJsonDouble ( ) throws IOException { context . read ( ) ; if ( reader . peek ( ) == QUOTE [ 0 ] ) { ByteString str = readJsonString ( true ) ; double dub = Double . valueOf ( str . utf8 ( ) ) ; if ( ! context . escapeNum ( ) && ! Double . isNaN ( dub ) && ! Double . isInfinite ( dub ) ) { // Throw exception -- we should not be in a string in this case throw new ProtocolException ( "Numeric data unexpectedly quoted" ) ; } return dub ; } else { if ( context . escapeNum ( ) ) { // This will throw - we should have had a quote if escapeNum == true readJsonSyntaxChar ( QUOTE ) ; } try { return Double . valueOf ( readJsonNumericChars ( ) ) ; } catch ( NumberFormatException ex ) { throw new ProtocolException ( "Bad data encountered in numeric data" ) ; } } }


Input: Read in a Json string containing base - 64 encoded data and decode it . [CODESPLIT] private ByteString readJsonBase64 ( ) throws IOException { ByteString str = readJsonString ( false ) ; return ByteString . decodeBase64 ( str . utf8 ( ) ) ; }


Input: When invoked by a derived instance sends the given call to the server . [CODESPLIT] protected final Object execute ( MethodCall < ? > methodCall ) throws Exception { if ( ! running . get ( ) ) { throw new IllegalStateException ( "Cannot write to a closed service client" ) ; } try { return invokeRequest ( methodCall ) ; } catch ( ServerException e ) { throw e . thriftException ; } }


Input: Send the given call to the server . [CODESPLIT] final Object invokeRequest ( MethodCall < ? > call ) throws Exception { boolean isOneWay = call . callTypeId == TMessageType . ONEWAY ; int sid = seqId . incrementAndGet ( ) ; protocol . writeMessageBegin ( call . name , call . callTypeId , sid ) ; call . send ( protocol ) ; protocol . writeMessageEnd ( ) ; protocol . flush ( ) ; if ( isOneWay ) { // No response will be received return null ; } MessageMetadata metadata = protocol . readMessageBegin ( ) ; if ( metadata . seqId != sid ) { throw new ThriftException ( ThriftException . Kind . BAD_SEQUENCE_ID , "Unrecognized sequence ID" ) ; } if ( metadata . type == TMessageType . EXCEPTION ) { ThriftException e = ThriftException . read ( protocol ) ; protocol . readMessageEnd ( ) ; throw new ServerException ( e ) ; } else if ( metadata . type != TMessageType . REPLY ) { throw new ThriftException ( ThriftException . Kind . INVALID_MESSAGE_TYPE , "Invalid message type: " + metadata . type ) ; } if ( metadata . seqId != seqId . get ( ) ) { throw new ThriftException ( ThriftException . Kind . BAD_SEQUENCE_ID , "Out-of-order response" ) ; } if ( ! metadata . name . equals ( call . name ) ) { throw new ThriftException ( ThriftException . Kind . WRONG_METHOD_NAME , "Unexpected method name in reply; expected " + call . name + " but received " + metadata . name ) ; } try { Object result = call . receive ( protocol , metadata ) ; protocol . readMessageEnd ( ) ; return result ; } catch ( Exception e ) { if ( e instanceof Struct ) { // Business as usual protocol . readMessageEnd ( ) ; } throw e ; } }


Input: //////////////////// [CODESPLIT] @ Override public MessageMetadata readMessageBegin ( ) throws IOException { int size = readI32 ( ) ; if ( size < 0 ) { int version = size & VERSION_MASK ; if ( version != VERSION_1 ) { throw new ProtocolException ( "Bad version in readMessageBegin" ) ; } return new MessageMetadata ( readString ( ) , ( byte ) ( size & 0xff ) , readI32 ( ) ) ; } else { if ( strictRead ) { throw new ProtocolException ( "Missing version in readMessageBegin" ) ; } return new MessageMetadata ( readStringWithSize ( size ) , readByte ( ) , readI32 ( ) ) ; } }


Input: When invoked by a derived instance places the given call in a queue to be sent to the server . [CODESPLIT] protected void enqueue ( MethodCall < ? > methodCall ) { if ( ! running . get ( ) ) { throw new IllegalStateException ( "Cannot write to a closed service client" ) ; } if ( ! pendingCalls . offer ( methodCall ) ) { // This should never happen with an unbounded queue throw new IllegalStateException ( "Call queue is full" ) ; } }


Input: Resolves a file system location to an Eclipse workspace resource . [CODESPLIT] public static IFile getResourceFromFSPath ( String location ) { return Activator . getDefault ( ) . getWorkspace ( ) . getRoot ( ) . getFileForLocation ( new Path ( location ) ) ; }


Input: Causes the platform to update Guvnor decoration notions . [CODESPLIT] public static void updateDecoration ( ) { final IWorkbench workbench = Activator . getDefault ( ) . getWorkbench ( ) ; workbench . getDisplay ( ) . syncExec ( new Runnable ( ) { public void run ( ) { IDecoratorManager manager = workbench . getDecoratorManager ( ) ; manager . update ( GuvnorDecorator . DECORATOR_ID ) ; } } ) ; }


Input: Causes the Repository view to refresh if it is open . [CODESPLIT] public static void refreshRepositoryView ( ) { IWorkbenchWindow activeWindow = Activator . getDefault ( ) . getWorkbench ( ) . getActiveWorkbenchWindow ( ) ; // If there is no active workbench window, then there can be no Repository view if ( activeWindow == null ) { return ; } // If there is no active workbench page, then there can be no Repository view IWorkbenchPage page = activeWindow . getActivePage ( ) ; if ( page == null ) { return ; } RepositoryView view = ( RepositoryView ) page . findView ( IGuvnorConstants . REPVIEW_ID ) ; if ( view != null ) { view . refresh ( ) ; } }