idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
14,200
static JsonArray getArrayFromJsonElement ( JsonElement jsonElement ) { JsonArray jsonArray = null ; if ( jsonElement . isJsonArray ( ) ) { jsonArray = jsonElement . getAsJsonArray ( ) ; } else if ( jsonElement . isJsonObject ( ) && ( ( JsonObject ) jsonElement ) . get ( "results" ) != null && ( ( JsonObject ) jsonElement ) . get ( "results" ) . isJsonArray ( ) ) { jsonArray = ( ( JsonObject ) jsonElement ) . get ( "results" ) . getAsJsonArray ( ) ; } return jsonArray ; }
Analizes a JsonElement and determines if its a result of a api search or loadAll method
145
21
14,201
public MPApiResponse executeRequest ( HttpMethod httpMethod , String uri , PayloadType payloadType , JsonObject payload , Collection < Header > colHeaders , int retries , int connectionTimeout , int socketTimeout ) throws MPRestException { HttpClient httpClient = null ; try { httpClient = getClient ( retries , connectionTimeout , socketTimeout ) ; if ( colHeaders == null ) { colHeaders = new Vector < Header > ( ) ; } HttpEntity entity = normalizePayload ( payloadType , payload , colHeaders ) ; HttpRequestBase request = getRequestMethod ( httpMethod , uri , entity ) ; for ( Header header : colHeaders ) { request . addHeader ( header ) ; } HttpResponse response ; long startMillis = System . currentTimeMillis ( ) ; try { response = httpClient . execute ( request ) ; } catch ( ClientProtocolException e ) { response = new BasicHttpResponse ( new BasicStatusLine ( request . getProtocolVersion ( ) , 400 , null ) ) ; } catch ( SSLPeerUnverifiedException e ) { response = new BasicHttpResponse ( new BasicStatusLine ( request . getProtocolVersion ( ) , 403 , null ) ) ; } catch ( IOException e ) { response = new BasicHttpResponse ( new BasicStatusLine ( request . getProtocolVersion ( ) , 404 , null ) ) ; } long endMillis = System . currentTimeMillis ( ) ; long responseMillis = endMillis - startMillis ; MPApiResponse mapiresponse = new MPApiResponse ( httpMethod , request , payload , response , responseMillis ) ; return mapiresponse ; } catch ( MPRestException restEx ) { throw restEx ; } catch ( Exception ex ) { throw new MPRestException ( ex ) ; } finally { try { if ( httpClient != null ) httpClient . getConnectionManager ( ) . shutdown ( ) ; } catch ( Exception ex ) { //Do Nothing } } }
Executes a http request and returns a response
436
9
14,202
private HttpClient getClient ( int retries , int connectionTimeout , int socketTimeout ) { HttpClient httpClient = new DefaultHttpClient ( ) ; HttpParams httpParams = httpClient . getParams ( ) ; // Retries if ( retries > 0 ) { DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler ( retries , true ) ; ( ( AbstractHttpClient ) httpClient ) . setHttpRequestRetryHandler ( retryHandler ) ; } // Timeouts if ( connectionTimeout > 0 ) { httpParams . setParameter ( CoreConnectionPNames . CONNECTION_TIMEOUT , connectionTimeout ) ; } if ( socketTimeout > 0 ) { httpParams . setParameter ( CoreConnectionPNames . SO_TIMEOUT , socketTimeout ) ; } //Proxy if ( StringUtils . isNotEmpty ( proxyHostName ) ) { HttpHost proxy = new HttpHost ( proxyHostName , proxyPort ) ; httpParams . setParameter ( ConnRoutePNames . DEFAULT_PROXY , proxy ) ; } return httpClient ; }
Returns a DefaultHttpClient instance with retries and timeouts settings If proxy information exists its setted on the client .
236
24
14,203
private HttpEntity normalizePayload ( PayloadType payloadType , JsonObject payload , Collection < Header > colHeaders ) throws MPRestException { BasicHeader header = null ; HttpEntity entity = null ; if ( payload != null ) { if ( payloadType == PayloadType . JSON ) { header = new BasicHeader ( HTTP . CONTENT_TYPE , "application/json" ) ; StringEntity stringEntity = null ; try { stringEntity = new StringEntity ( payload . toString ( ) ) ; } catch ( Exception ex ) { throw new MPRestException ( ex ) ; } stringEntity . setContentType ( header ) ; entity = stringEntity ; } else { Map < String , Object > map = new Gson ( ) . fromJson ( payload . toString ( ) , new TypeToken < Map < String , Object > > ( ) { } . getType ( ) ) ; List < NameValuePair > params = new ArrayList < NameValuePair > ( 2 ) ; for ( Map . Entry < String , Object > entry : map . entrySet ( ) ) { params . add ( new BasicNameValuePair ( entry . getKey ( ) , entry . getValue ( ) . toString ( ) ) ) ; } UrlEncodedFormEntity urlEncodedFormEntity = null ; try { urlEncodedFormEntity = new UrlEncodedFormEntity ( params , "UTF-8" ) ; } catch ( Exception ex ) { throw new MPRestException ( ex ) ; } //if (payloadType == PayloadType.FORM_DATA) // header = new BasicHeader(HTTP.CONTENT_TYPE, "multipart/form-data"); //else if (payloadType == PayloadType.X_WWW_FORM_URLENCODED) header = new BasicHeader ( HTTP . CONTENT_TYPE , "application/x-www-form-urlencoded" ) ; urlEncodedFormEntity . setContentType ( header ) ; entity = urlEncodedFormEntity ; } } if ( header != null ) { colHeaders . add ( header ) ; } return entity ; }
Prepares the payload to be sended in the request .
459
12
14,204
private HttpRequestBase getRequestMethod ( HttpMethod httpMethod , String uri , HttpEntity entity ) throws MPRestException { if ( httpMethod == null ) { throw new MPRestException ( "HttpMethod must be \"GET\", \"POST\", \"PUT\" or \"DELETE\"." ) ; } if ( StringUtils . isEmpty ( uri ) ) throw new MPRestException ( "Uri can not be an empty String." ) ; HttpRequestBase request = null ; if ( httpMethod . equals ( HttpMethod . GET ) ) { if ( entity != null ) { throw new MPRestException ( "Payload not supported for this method." ) ; } request = new HttpGet ( uri ) ; } else if ( httpMethod . equals ( HttpMethod . POST ) ) { if ( entity == null ) { throw new MPRestException ( "Must include payload for this method." ) ; } HttpPost post = new HttpPost ( uri ) ; post . setEntity ( entity ) ; request = post ; } else if ( httpMethod . equals ( HttpMethod . PUT ) ) { if ( entity == null ) { throw new MPRestException ( "Must include payload for this method." ) ; } HttpPut put = new HttpPut ( uri ) ; put . setEntity ( entity ) ; request = put ; } else if ( httpMethod . equals ( HttpMethod . DELETE ) ) { if ( entity != null ) { throw new MPRestException ( "Payload not supported for this method." ) ; } request = new HttpDelete ( uri ) ; } return request ; }
Returns the HttpRequestBase to be used by the HttpClient .
359
15
14,205
private static HashMap < String , MPApiResponse > getMapCache ( ) { if ( cache == null || cache . get ( ) == null ) { cache = new SoftReference ( new HashMap < String , MPApiResponse > ( ) ) ; } return cache . get ( ) ; }
Auxiliar method . It returns a Map with cached responses from the soft references variable . If the map does not exists its instantiated and then returned .
63
31
14,206
static void addToCache ( String key , MPApiResponse response ) { HashMap < String , MPApiResponse > mapCache = getMapCache ( ) ; mapCache . put ( key , response ) ; }
Inserts an entry to the cache .
46
8
14,207
static MPApiResponse getFromCache ( String key ) { HashMap < String , MPApiResponse > mapCache = getMapCache ( ) ; MPApiResponse response = null ; try { response = mapCache . get ( key ) . clone ( ) ; } catch ( Exception ex ) { // Do nothing } if ( response != null ) { response . fromCache = Boolean . TRUE ; } return response ; }
Retrieves an entry from the cache .
88
9
14,208
static void removeFromCache ( String key ) { HashMap < String , MPApiResponse > mapCache = getMapCache ( ) ; mapCache . remove ( key ) ; }
Removes an entry from the cache .
38
8
14,209
private void loadPropFile ( String propFileName ) throws IOException , Error { InputStream inputStream = null ; try { inputStream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( propFileName ) ; if ( inputStream != null ) { this . prop . load ( inputStream ) ; LOGGER . debug ( "properties file " + propFileName + " loaded succesfully" ) ; } else { String errorMsg = "properties file '" + propFileName + "' not found in the classpath" ; LOGGER . error ( errorMsg ) ; throw new Error ( errorMsg , Error . SETTINGS_FILE_NOT_FOUND ) ; } } finally { try { if ( inputStream != null ) { inputStream . close ( ) ; } } catch ( IOException e ) { LOGGER . warn ( "properties file '" + propFileName + "' not closed properly." ) ; } } }
Loads the settings from the properties file
201
8
14,210
private String loadStringProperty ( String propertyKey ) { String propValue = prop . getProperty ( propertyKey ) ; if ( propValue != null ) { propValue = propValue . trim ( ) ; } return propValue ; }
Loads a property of the type String from the Properties object
48
12
14,211
@ SuppressWarnings ( "unused" ) private Boolean loadBooleanProperty ( String propertyKey ) { String booleanPropValue = prop . getProperty ( propertyKey ) ; if ( booleanPropValue != null ) { return Boolean . parseBoolean ( booleanPropValue . trim ( ) ) ; } else { return null ; } }
Loads a property of the type Boolean from the Properties object
71
12
14,212
@ SuppressWarnings ( "unused" ) private List < String > loadListProperty ( String propertyKey ) { String arrayPropValue = prop . getProperty ( propertyKey ) ; if ( arrayPropValue != null && ! arrayPropValue . isEmpty ( ) ) { String [ ] values = arrayPropValue . trim ( ) . split ( "," ) ; for ( int i = 0 ; i < values . length ; i ++ ) { values [ i ] = values [ i ] . trim ( ) ; } return Arrays . asList ( values ) ; } else { return null ; } }
Loads a property of the type List from the Properties object
128
12
14,213
@ SuppressWarnings ( "unused" ) private URL loadURLProperty ( String propertyKey ) { String urlPropValue = prop . getProperty ( propertyKey ) ; if ( urlPropValue == null || urlPropValue . isEmpty ( ) ) { return null ; } else { try { return new URL ( urlPropValue . trim ( ) ) ; } catch ( MalformedURLException e ) { LOGGER . error ( "'" + propertyKey + "' contains malformed url." , e ) ; return null ; } } }
Loads a property of the type URL from the Properties object
115
12
14,214
public String get ( String key ) { try { Field field ; field = this . getClass ( ) . getField ( key ) ; return ( String ) field . get ( this ) ; } catch ( NoSuchFieldException e ) { return ( String ) antifraud_info . get ( key ) ; } catch ( IllegalAccessException e ) { return "" ; } }
Helper method to access line item fields
78
7
14,215
public void getAccessToken ( ) throws OAuthSystemException , OAuthProblemException { cleanError ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; //OAuthClient oAuthClient = new OAuthClient(httpClient); OAuthClientRequest request = OAuthClientRequest . tokenLocation ( settings . getURL ( Constants . TOKEN_REQUEST_URL ) ) . buildBodyMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( false ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "grant_type" , GrantType . CLIENT_CREDENTIALS ) ; String body = JSONUtils . buildJSON ( params ) ; request . setBody ( body ) ; updateTokens ( httpClient , request , headers ) ; }
Generates an access token and refresh token that you may use to call Onelogin s API methods .
189
22
14,216
public void refreshToken ( ) throws OAuthSystemException , OAuthProblemException { cleanError ( ) ; if ( accessToken == null || refreshToken == null ) { throw new OAuthRuntimeException ( "Access token ot Refresh token not provided" ) ; } OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClientRequest request = OAuthClientRequest . tokenLocation ( settings . getURL ( Constants . TOKEN_REFRESH_URL ) ) . buildBodyMessage ( ) ; Map < String , String > headers = new HashMap < String , String > ( ) ; headers . put ( OAuth . HeaderType . CONTENT_TYPE , OAuth . ContentType . JSON ) ; headers . put ( "User-Agent" , this . userAgent ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "grant_type" , GrantType . REFRESH_TOKEN ) ; params . put ( "access_token" , accessToken ) ; params . put ( "refresh_token" , refreshToken ) ; String body = JSONUtils . buildJSON ( params ) ; request . setBody ( body ) ; updateTokens ( httpClient , request , headers ) ; }
Refreshing tokens provides a new set of access and refresh tokens .
276
14
14,217
public void revokeToken ( ) throws OAuthSystemException , OAuthProblemException { cleanError ( ) ; if ( accessToken == null ) { throw new OAuthRuntimeException ( "Access token not provided" ) ; } OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClientRequest request = OAuthClientRequest . tokenLocation ( settings . getURL ( Constants . TOKEN_REVOKE_URL ) ) . buildBodyMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( false ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "access_token" , accessToken ) ; String body = JSONUtils . buildJSON ( params ) ; request . setBody ( body ) ; OneloginOAuthJSONAccessTokenResponse oAuthResponse = ( OneloginOAuthJSONAccessTokenResponse ) httpClient . execute ( request , headers , OAuth . HttpMethod . POST , OneloginOAuthJSONAccessTokenResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) == 200 ) { accessToken = null ; refreshToken = null ; expiration = null ; } else { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; } }
Revokes an access token and refresh token pair .
292
10
14,218
public RateLimit getRateLimit ( ) throws OAuthSystemException , OAuthProblemException { cleanError ( ) ; prepareToken ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( settings . getURL ( Constants . GET_RATE_URL ) ) //.setAccessToken(accessToken) // 'Authorization' => 'Bearer xxxx' not accepted right now . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . GET , OneloginOAuthJSONResourceResponse . class ) ; RateLimit ratelimit = null ; if ( oAuthResponse . getResponseCode ( ) == 200 ) { JSONObject data = oAuthResponse . getData ( ) ; if ( data != null ) { ratelimit = new RateLimit ( data ) ; } } else { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; } return ratelimit ; }
Gets current rate limit details about an access token .
284
11
14,219
public OneLoginResponse < User > getUsersBatch ( int batchSize ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { return getUsersBatch ( batchSize , null ) ; }
Get a batch Users .
46
5
14,220
public List < App > getUserApps ( long id ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . GET_APPS_FOR_USER_URL , Long . toString ( id ) ) ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; List < App > apps = new ArrayList < App > ( ) ; App app = null ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . GET , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) == 200 ) { JSONObject [ ] dataArray = oAuthResponse . getDataArray ( ) ; if ( dataArray != null && dataArray . length > 0 ) { for ( JSONObject data : dataArray ) { app = new App ( data ) ; apps . add ( app ) ; } } } else { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; } return apps ; }
Gets a list of apps accessible by a user not including personal apps .
337
15
14,221
public List < Integer > getUserRoles ( long id ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . GET_ROLES_FOR_USER_URL , Long . toString ( id ) ) ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; List < Integer > roles = null ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . GET , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) == 200 ) { roles = oAuthResponse . getIdsFromData ( ) ; } else { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; } return roles ; }
Gets a list of role IDs that have been assigned to a user .
282
15
14,222
public User createUser ( Map < String , Object > userParams ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . CREATE_USER_URL ) ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; String body = JSONUtils . buildJSON ( userParams ) ; bearerRequest . setBody ( body ) ; User user = null ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . POST , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) == 200 ) { if ( oAuthResponse . getType ( ) . equals ( "success" ) ) { if ( oAuthResponse . getMessage ( ) . equals ( "Success" ) ) { JSONObject data = oAuthResponse . getData ( ) ; user = new User ( data ) ; } } } else { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; errorAttribute = oAuthResponse . getErrorAttribute ( ) ; } return user ; }
Creates an user
352
4
14,223
public Object createSessionLoginToken ( Map < String , Object > queryParams , String allowedOrigin ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . SESSION_LOGIN_TOKEN_URL ) ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; if ( allowedOrigin != null ) { headers . put ( "Custom-Allowed-Origin-Header-1" , allowedOrigin ) ; } bearerRequest . setHeaders ( headers ) ; String body = JSONUtils . buildJSON ( queryParams ) ; bearerRequest . setBody ( body ) ; Object sessionToken = null ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . POST , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) == 200 ) { if ( oAuthResponse . getType ( ) . equals ( "success" ) ) { JSONObject data = oAuthResponse . getData ( ) ; if ( oAuthResponse . getMessage ( ) . equals ( "Success" ) ) { sessionToken = new SessionTokenInfo ( data ) ; } else if ( oAuthResponse . getMessage ( ) . equals ( "MFA is required for this user" ) ) { sessionToken = new SessionTokenMFAInfo ( data ) ; } } } else { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; } return sessionToken ; }
Generates a session login token in scenarios in which MFA may or may not be required . A session login token expires two minutes after creation .
424
29
14,224
public Object createSessionLoginToken ( Map < String , Object > queryParams ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { return createSessionLoginToken ( queryParams , null ) ; }
Generate a session login token in scenarios in which MFA may or may not be required . A session login token expires two minutes after creation .
48
29
14,225
public Boolean assignRoleToUser ( long id , List < Long > roleIds ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . ADD_ROLE_TO_USER_URL , Long . toString ( id ) ) ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; HashMap < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "role_id_array" , roleIds ) ; String body = JSONUtils . buildJSON ( params ) ; bearerRequest . setBody ( body ) ; Boolean success = true ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . PUT , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) != 200 ) { success = false ; error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; errorAttribute = oAuthResponse . getErrorAttribute ( ) ; } return success ; }
Assigns Role to User
343
6
14,226
public Boolean setPasswordUsingHashSalt ( long id , String password , String passwordConfirmation , String passwordAlgorithm ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { return setPasswordUsingHashSalt ( id , password , passwordConfirmation , passwordAlgorithm , null ) ; }
Set Password by ID Using Salt and SHA - 256
64
10
14,227
public Boolean logUserOut ( long id ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . LOG_USER_OUT_URL , Long . toString ( id ) ) ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; Boolean success = true ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . PUT , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) != 200 ) { success = false ; error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; errorAttribute = oAuthResponse . getErrorAttribute ( ) ; } return success ; }
Log a user out of any and all sessions .
272
10
14,228
public List < EventType > getEventTypes ( ) throws URISyntaxException , ClientProtocolException , IOException { URIBuilder url = new URIBuilder ( settings . getURL ( Constants . GET_EVENT_TYPES_URL ) ) ; CloseableHttpClient httpclient = HttpClients . createDefault ( ) ; HttpGet httpGet = new HttpGet ( url . toString ( ) ) ; httpGet . setHeader ( "Accept" , "application/json" ) ; CloseableHttpResponse response = httpclient . execute ( httpGet ) ; String json_string = EntityUtils . toString ( response . getEntity ( ) ) ; JSONObject json_object = new JSONObject ( json_string ) ; JSONArray data = json_object . getJSONArray ( "data" ) ; List < EventType > eventTypes = new ArrayList < EventType > ( ) ; for ( int i = 0 ; i < data . length ( ) ; i ++ ) { JSONObject j_object = data . getJSONObject ( i ) ; EventType eventType = new EventType ( j_object ) ; eventTypes . add ( eventType ) ; } return eventTypes ; }
List of all OneLogin event types available to the Events API .
256
13
14,229
public List < Event > getEvents ( HashMap < String , String > queryParameters , int maxResults ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { ExtractionContext context = getResource ( queryParameters , Constants . GET_EVENTS_URL ) ; OneloginOAuthJSONResourceResponse oAuthResponse = null ; String afterCursor = null ; List < Event > events = new ArrayList < Event > ( maxResults ) ; while ( oAuthResponse == null || ( events . size ( ) < maxResults && afterCursor != null ) ) { oAuthResponse = context . oAuthClient . resource ( context . bearerRequest , OAuth . HttpMethod . GET , OneloginOAuthJSONResourceResponse . class ) ; if ( ( afterCursor = getEventsBatch ( events , context . url , context . bearerRequest , oAuthResponse ) ) == null ) { break ; } } return events ; }
Gets a list of Event resources .
205
8
14,230
public Event getEvent ( long id ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . GET_EVENT_URL , Long . toString ( id ) ) ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; Event event = null ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . GET , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) == 200 ) { JSONObject data = oAuthResponse . getData ( ) ; event = new Event ( data ) ; } else { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; } return event ; }
Gets Event by ID .
276
6
14,231
public void createEvent ( Map < String , Object > eventParams ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . CREATE_EVENT_URL ) ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; String body = JSONUtils . buildJSON ( eventParams ) ; bearerRequest . setBody ( body ) ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . POST , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) != 200 || ! oAuthResponse . getType ( ) . equals ( "success" ) ) { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; errorAttribute = oAuthResponse . getErrorAttribute ( ) ; } }
Create an event in the OneLogin event log .
298
10
14,232
public OneLoginResponse < Group > getGroupsBatch ( HashMap < String , String > queryParameters , int batchSize , String afterCursor ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { ExtractionContext context = extractResourceBatch ( queryParameters , batchSize , afterCursor , Constants . GET_GROUPS_URL ) ; List < Group > groups = new ArrayList < Group > ( batchSize ) ; afterCursor = getGroupsBatch ( groups , context . url , context . bearerRequest , context . oAuthResponse ) ; return new OneLoginResponse < Group > ( groups , afterCursor ) ; }
Get a batch of Groups
143
5
14,233
public List < AuthFactor > getFactors ( long userId ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . GET_FACTORS_URL , userId ) ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; List < AuthFactor > authFactors = new ArrayList < AuthFactor > ( ) ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . GET , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) == 200 ) { JSONObject data = oAuthResponse . getData ( ) ; if ( data . has ( "auth_factors" ) ) { JSONArray dataArray = data . getJSONArray ( "auth_factors" ) ; if ( dataArray != null && dataArray . length ( ) > 0 ) { AuthFactor authFactor ; for ( int i = 0 ; i < dataArray . length ( ) ; i ++ ) { authFactor = new AuthFactor ( dataArray . getJSONObject ( i ) ) ; authFactors . add ( authFactor ) ; } } } } else { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; } return authFactors ; }
Returns a list of authentication factors that are available for user enrollment via API .
393
15
14,234
public OTPDevice enrollFactor ( long userId , long factorId , String displayName , String number ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . ENROLL_FACTOR_URL , userId ) ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; HashMap < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "factor_id" , factorId ) ; params . put ( "display_name" , displayName ) ; params . put ( "number" , number ) ; String body = JSONUtils . buildJSON ( params ) ; bearerRequest . setBody ( body ) ; OTPDevice otpDevice = null ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . POST , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) == 200 ) { JSONObject data = oAuthResponse . getData ( ) ; otpDevice = new OTPDevice ( data ) ; } else { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; } return otpDevice ; }
Enroll a user with a given authentication factor .
382
10
14,235
public Boolean removeFactor ( long userId , long deviceId ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . REMOVE_FACTOR_URL , userId , deviceId ) ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; Boolean success = true ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . DELETE , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) != 200 ) { success = false ; error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; } return success ; }
Remove an enrolled factor from a user .
264
8
14,236
public String generateInviteLink ( String email ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . GENERATE_INVITE_LINK_URL ) ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "email" , email ) ; String body = JSONUtils . buildJSON ( params ) ; bearerRequest . setBody ( body ) ; String urlLink = null ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . POST , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) == 200 ) { if ( oAuthResponse . getType ( ) . equals ( "success" ) ) { if ( oAuthResponse . getMessage ( ) . equals ( "Success" ) ) { Object [ ] objArray = oAuthResponse . getArrayFromData ( ) ; urlLink = ( String ) objArray [ 0 ] ; } } } else { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; } return urlLink ; }
Generates an invite link for a user that you have already created in your OneLogin account .
378
19
14,237
public Boolean sendInviteLink ( String email , String personalEmail ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . SEND_INVITE_LINK_URL ) ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "email" , email ) ; if ( personalEmail != null ) { params . put ( "personal_email" , personalEmail ) ; } String body = JSONUtils . buildJSON ( params ) ; bearerRequest . setBody ( body ) ; Boolean sent = false ; OneloginOAuthJSONResourceResponse oAuthResponse = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . POST , OneloginOAuthJSONResourceResponse . class ) ; if ( oAuthResponse . getResponseCode ( ) == 200 ) { if ( oAuthResponse . getType ( ) . equals ( "success" ) ) { sent = true ; } } else { error = oAuthResponse . getError ( ) ; errorDescription = oAuthResponse . getErrorDescription ( ) ; } return sent ; }
Sends an invite link to a user that you have already created in your OneLogin account .
357
19
14,238
public Boolean sendInviteLink ( String email ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { return sendInviteLink ( email , null ) ; }
Send an invite link to a user that you have already created in your OneLogin account .
39
18
14,239
public List < EmbedApp > getEmbedApps ( String token , String email ) throws URISyntaxException , ClientProtocolException , IOException , ParserConfigurationException , SAXException , XPathExpressionException { cleanError ( ) ; URIBuilder url = new URIBuilder ( Constants . EMBED_APP_URL ) ; url . addParameter ( "token" , token ) ; url . addParameter ( "email" , email ) ; CloseableHttpClient httpclient = HttpClients . createDefault ( ) ; HttpGet httpGet = new HttpGet ( url . toString ( ) ) ; httpGet . setHeader ( "Accept" , "application/json" ) ; CloseableHttpResponse response = httpclient . execute ( httpGet ) ; String xmlString = EntityUtils . toString ( response . getEntity ( ) ) ; List < EmbedApp > embedApps = new ArrayList < EmbedApp > ( ) ; DocumentBuilderFactory docfactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder builder = docfactory . newDocumentBuilder ( ) ; Document doc = builder . parse ( new InputSource ( new StringReader ( xmlString ) ) ) ; XPath xpath = XPathFactory . newInstance ( ) . newXPath ( ) ; NodeList appNodeList = ( NodeList ) xpath . evaluate ( "/apps/app" , doc , XPathConstants . NODESET ) ; if ( appNodeList . getLength ( ) > 0 ) { Node appNode ; NodeList appAttrs ; EmbedApp embedApp ; for ( int i = 0 ; i < appNodeList . getLength ( ) ; i ++ ) { appNode = appNodeList . item ( 0 ) ; appAttrs = appNode . getChildNodes ( ) ; String appAttrName ; JSONObject appJson = new JSONObject ( ) ; Set < String > desiredAttrs = new HashSet < String > ( Arrays . asList ( new String [ ] { "id" , "icon" , "name" , "provisioned" , "extension_required" , "personal" , "login_id" } ) ) ; for ( int j = 0 ; j < appAttrs . getLength ( ) ; j ++ ) { appAttrName = appAttrs . item ( j ) . getNodeName ( ) ; if ( desiredAttrs . contains ( appAttrName ) ) { appJson . put ( appAttrName , appAttrs . item ( j ) . getTextContent ( ) ) ; } } embedApp = new EmbedApp ( appJson ) ; embedApps . add ( embedApp ) ; } } return embedApps ; }
Lists apps accessible by a OneLogin user .
584
10
14,240
public List < Privilege > getPrivileges ( ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . LIST_PRIVILEGES_URL ) ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; List < Privilege > privileges = new ArrayList < Privilege > ( maxResults ) ; OneloginOAuth2JSONResourceResponse oAuth2Response = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . GET , OneloginOAuth2JSONResourceResponse . class ) ; if ( oAuth2Response . getResponseCode ( ) == 200 ) { JSONArray jsonArray = oAuth2Response . getJSONArrayFromContent ( ) ; if ( jsonArray != null && jsonArray . length ( ) > 0 ) { for ( int i = 0 ; i < jsonArray . length ( ) ; i ++ ) { privileges . add ( new Privilege ( jsonArray . getJSONObject ( i ) ) ) ; } } } else { error = oAuth2Response . getError ( ) ; errorDescription = oAuth2Response . getErrorDescription ( ) ; } return privileges ; }
Gets a list of the Privileges created in an account .
350
14
14,241
public Privilege createPrivilege ( String name , String version , List < ? > statements ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . CREATE_PRIVILEGE_URL ) ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; List < HashMap < String , Object > > statementData = new ArrayList < HashMap < String , Object > > ( ) ; if ( ! statements . isEmpty ( ) ) { if ( statements . get ( 0 ) instanceof Statement ) { List < Statement > data = ( List < Statement > ) statements ; HashMap < String , Object > dataObj ; for ( Statement statement : data ) { dataObj = new HashMap < String , Object > ( ) ; dataObj . put ( "Effect" , statement . effect ) ; dataObj . put ( "Action" , statement . actions ) ; dataObj . put ( "Scope" , statement . scopes ) ; statementData . add ( dataObj ) ; } } else if ( statements . get ( 0 ) instanceof HashMap ) { List < HashMap < String , Object > > data = ( List < HashMap < String , Object > > ) statements ; for ( HashMap < String , Object > statement : data ) { statementData . add ( statement ) ; } } } Map < String , Object > privilegeData = new HashMap < String , Object > ( ) ; privilegeData . put ( "Version" , version ) ; privilegeData . put ( "Statement" , statementData ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "name" , name ) ; params . put ( "privilege" , privilegeData ) ; String body = JSONUtils . buildJSON ( params ) ; bearerRequest . setBody ( body ) ; Privilege privilege = null ; OneloginOAuth2JSONResourceResponse oAuth2Response = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . POST , OneloginOAuth2JSONResourceResponse . class ) ; if ( oAuth2Response . getResponseCode ( ) == 201 ) { String id = ( String ) oAuth2Response . getFromContent ( "id" ) ; if ( id != null && ! id . isEmpty ( ) ) { privilege = new Privilege ( id , name , version , statements ) ; } } else { error = oAuth2Response . getError ( ) ; errorDescription = oAuth2Response . getErrorDescription ( ) ; } return privilege ; }
Creates a Privilege
647
5
14,242
public Privilege getPrivilege ( String id ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . GET_PRIVILEGE_URL , id ) ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; Privilege privilege = null ; OneloginOAuth2JSONResourceResponse oAuth2Response = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . GET , OneloginOAuth2JSONResourceResponse . class ) ; if ( oAuth2Response . getResponseCode ( ) == 200 ) { JSONObject data = oAuth2Response . getJSONObjectFromContent ( ) ; privilege = new Privilege ( data ) ; } else { error = oAuth2Response . getError ( ) ; errorDescription = oAuth2Response . getErrorDescription ( ) ; } return privilege ; }
Get a Privilege
286
4
14,243
public Boolean deletePrivilege ( String id ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . DELETE_PRIVILEGE_URL , id ) ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; Boolean removed = false ; OneloginOAuth2JSONResourceResponse oAuth2Response = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . DELETE , OneloginOAuth2JSONResourceResponse . class ) ; if ( oAuth2Response . getResponseCode ( ) == 204 ) { removed = true ; } else { error = oAuth2Response . getError ( ) ; errorDescription = oAuth2Response . getErrorDescription ( ) ; } return removed ; }
Deletes a privilege
266
4
14,244
public List < Long > getRolesAssignedToPrivileges ( String id , int maxResults ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { ExtractionContext context = getResource ( Constants . GET_ROLES_ASSIGNED_TO_PRIVILEGE_URL , id ) ; OneloginOAuth2JSONResourceResponse oAuth2Response = null ; String afterCursor = null ; List < Long > roleIds = new ArrayList < Long > ( maxResults ) ; while ( oAuth2Response == null || ( roleIds . size ( ) < maxResults && afterCursor != null ) ) { oAuth2Response = context . oAuthClient . resource ( context . bearerRequest , OAuth . HttpMethod . GET , OneloginOAuth2JSONResourceResponse . class ) ; if ( ( afterCursor = getRolesAssignedToPrivilegesBatch ( roleIds , context . url , context . bearerRequest , oAuth2Response ) ) == null ) { break ; } } return roleIds ; }
Gets a list of the role ids assigned to a privilege .
237
14
14,245
public OneLoginResponse < Long > getRolesAssignedToPrivilegesBatch ( String id , int batchSize , String afterCursor ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { ExtractionContext context = extractResourceBatch ( ( Object ) id , batchSize , afterCursor , Constants . GET_ROLES_ASSIGNED_TO_PRIVILEGE_URL ) ; List < Long > roleIds = new ArrayList < Long > ( batchSize ) ; afterCursor = getRolesAssignedToPrivilegesBatch ( roleIds , context . url , context . bearerRequest , context . oAuth2Response ) ; return new OneLoginResponse < Long > ( roleIds , afterCursor ) ; }
Get a batch of roles assigned to privilege .
168
9
14,246
public Boolean assignUsersToPrivilege ( String id , List < Long > userIds ) throws OAuthSystemException , OAuthProblemException , URISyntaxException { cleanError ( ) ; prepareToken ( ) ; OneloginURLConnectionClient httpClient = new OneloginURLConnectionClient ( ) ; OAuthClient oAuthClient = new OAuthClient ( httpClient ) ; URIBuilder url = new URIBuilder ( settings . getURL ( Constants . ASSIGN_USERS_TO_PRIVILEGE_URL , id ) ) ; OAuthClientRequest bearerRequest = new OAuthBearerClientRequest ( url . toString ( ) ) . buildHeaderMessage ( ) ; Map < String , String > headers = getAuthorizedHeader ( ) ; bearerRequest . setHeaders ( headers ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "users" , userIds ) ; String body = JSONUtils . buildJSON ( params ) ; bearerRequest . setBody ( body ) ; Boolean added = false ; OneloginOAuth2JSONResourceResponse oAuth2Response = oAuthClient . resource ( bearerRequest , OAuth . HttpMethod . POST , OneloginOAuth2JSONResourceResponse . class ) ; if ( oAuth2Response . getResponseCode ( ) == 201 ) { added = true ; } else { error = oAuth2Response . getError ( ) ; errorDescription = oAuth2Response . getErrorDescription ( ) ; } return added ; }
Assign one or more users to a privilege .
332
10
14,247
public void called ( Matcher < Integer > numberOfCalls ) { Rule rule = ruleBuilder . toRule ( ) ; int matchingCalls = ( int ) requests . stream ( ) . filter ( req -> rule . matches ( req ) ) . count ( ) ; if ( ! numberOfCalls . matches ( matchingCalls ) ) { throw new IllegalStateException ( String . format ( "Expected %s calls, but found %s." , numberOfCalls , matchingCalls ) ) ; } }
Verifies number of request matching defined conditions .
108
9
14,248
public HttpClientResponseBuilder withHeader ( String name , String value ) { Action lastAction = newRule . getLastAction ( ) ; HeaderAction headerAction = new HeaderAction ( lastAction , name , value ) ; newRule . overrideLastAction ( headerAction ) ; return this ; }
Sets response header .
61
5
14,249
public HttpClientResponseBuilder withStatus ( int statusCode ) { Action lastAction = newRule . getLastAction ( ) ; StatusResponse statusAction = new StatusResponse ( lastAction , statusCode ) ; newRule . overrideLastAction ( statusAction ) ; return this ; }
Sets response status code .
58
6
14,250
public HttpClientResponseBuilder withCookie ( String cookieName , String cookieValue ) { Action lastAction = newRule . getLastAction ( ) ; CookieAction cookieAction = new CookieAction ( lastAction , cookieName , cookieValue ) ; newRule . overrideLastAction ( cookieAction ) ; return this ; }
Sets response cookie
66
4
14,251
public HttpClientResponseBuilder doReturn ( int statusCode , String response ) { return doReturn ( statusCode , response , Charset . forName ( "UTF-8" ) ) ; }
Adds action which returns provided response in UTF - 8 with status code .
42
14
14,252
public HttpClientResponseBuilder doThrowException ( IOException exception ) { newRule . addAction ( new ExceptionAction ( exception ) ) ; return new HttpClientResponseBuilder ( newRule ) ; }
Adds action which throws provided exception .
42
7
14,253
static FullEntity < ? > [ ] toNativeFullEntities ( List < ? > entities , DefaultEntityManager entityManager , Marshaller . Intent intent ) { FullEntity < ? > [ ] nativeEntities = new FullEntity [ entities . size ( ) ] ; for ( int i = 0 ; i < entities . size ( ) ; i ++ ) { nativeEntities [ i ] = ( FullEntity < ? > ) Marshaller . marshal ( entityManager , entities . get ( i ) , intent ) ; } return nativeEntities ; }
Converts the given list of model objects to an array of FullEntity objects .
114
16
14,254
static Entity [ ] toNativeEntities ( List < ? > entities , DefaultEntityManager entityManager , Marshaller . Intent intent ) { Entity [ ] nativeEntities = new Entity [ entities . size ( ) ] ; for ( int i = 0 ; i < entities . size ( ) ; i ++ ) { nativeEntities [ i ] = ( Entity ) Marshaller . marshal ( entityManager , entities . get ( i ) , intent ) ; } return nativeEntities ; }
Converts the given list of model objects to an array of native Entity objects .
100
16
14,255
static Entity incrementVersion ( Entity nativeEntity , PropertyMetadata versionMetadata ) { String versionPropertyName = versionMetadata . getMappedName ( ) ; long version = nativeEntity . getLong ( versionPropertyName ) ; return Entity . newBuilder ( nativeEntity ) . set ( versionPropertyName , ++ version ) . build ( ) ; }
Increments the version property of the given entity by one .
72
12
14,256
static void rollbackIfActive ( Transaction transaction ) { try { if ( transaction != null && transaction . isActive ( ) ) { transaction . rollback ( ) ; } } catch ( DatastoreException exp ) { throw new EntityManagerException ( exp ) ; } }
Rolls back the given transaction if it is still active .
56
12
14,257
static void validateDeferredIdAllocation ( Object entity ) { IdentifierMetadata identifierMetadata = EntityIntrospector . getIdentifierMetadata ( entity ) ; if ( identifierMetadata . getDataType ( ) == DataType . STRING ) { throw new EntityManagerException ( "Deferred ID allocation is not applicable for entities with String identifiers. " ) ; } }
Validates if the given entity is valid for deferred ID allocation . Deferred ID allocation is valid for entities using a numeric ID .
80
26
14,258
public Mapper getMapper ( Field field ) { Type genericType = field . getGenericType ( ) ; Property propertyAnnotation = field . getAnnotation ( Property . class ) ; boolean indexed = true ; if ( propertyAnnotation != null ) { indexed = propertyAnnotation . indexed ( ) ; } String cacheKey = computeCacheKey ( genericType , indexed ) ; Mapper mapper = cache . get ( cacheKey ) ; if ( mapper == null ) { mapper = createMapper ( field , indexed ) ; } return mapper ; }
Returns the Mapper for the given field . If a Mapper exists in the cache that can map the given field the cached Mapper will be returned . Otherwise a new Mapper is created and returned .
117
41
14,259
private Mapper createMapper ( Field field , boolean indexed ) { lock . lock ( ) ; try { Mapper mapper ; Class < ? > fieldType = field . getType ( ) ; Type genericType = field . getGenericType ( ) ; String cacheKey = computeCacheKey ( genericType , indexed ) ; mapper = cache . get ( cacheKey ) ; if ( mapper != null ) { return mapper ; } if ( List . class . isAssignableFrom ( fieldType ) ) { mapper = new ListMapper ( genericType , indexed ) ; } else if ( Set . class . isAssignableFrom ( fieldType ) ) { mapper = new SetMapper ( genericType , indexed ) ; } else { // we shouldn't be getting here throw new IllegalArgumentException ( String . format ( "Field type must be List or Set, found %s" , fieldType ) ) ; } cache . put ( cacheKey , mapper ) ; return mapper ; } finally { lock . unlock ( ) ; } }
Creates a new Mapper for the given field .
222
11
14,260
private static Credentials getCredentials ( ConnectionParameters parameters ) throws IOException { if ( parameters . isEmulator ( ) ) { return NoCredentials . getInstance ( ) ; } InputStream jsonCredentialsStream = parameters . getJsonCredentialsStream ( ) ; if ( jsonCredentialsStream != null ) { return ServiceAccountCredentials . fromStream ( jsonCredentialsStream ) ; } File jsonCredentialsFile = parameters . getJsonCredentialsFile ( ) ; if ( jsonCredentialsFile != null ) { return ServiceAccountCredentials . fromStream ( new FileInputStream ( jsonCredentialsFile ) ) ; } return ServiceAccountCredentials . getApplicationDefault ( ) ; }
Creates and returns the credentials from the given connection parameters .
158
12
14,261
private static HttpTransportOptions getHttpTransportOptions ( ConnectionParameters parameters ) { HttpTransportOptions . Builder httpOptionsBuilder = HttpTransportOptions . newBuilder ( ) ; httpOptionsBuilder . setConnectTimeout ( parameters . getConnectionTimeout ( ) ) ; httpOptionsBuilder . setReadTimeout ( parameters . getReadTimeout ( ) ) ; HttpTransportFactory httpTransportFactory = parameters . getHttpTransportFactory ( ) ; if ( httpTransportFactory != null ) { httpOptionsBuilder . setHttpTransportFactory ( httpTransportFactory ) ; } return httpOptionsBuilder . build ( ) ; }
Creates and returns HttpTransportOptions from the given connection parameters .
131
15
14,262
public static EntityMetadata introspect ( Class < ? > entityClass ) { EntityMetadata cachedMetadata = cache . get ( entityClass ) ; if ( cachedMetadata != null ) { return cachedMetadata ; } return loadMetadata ( entityClass ) ; }
Introspects the given entity class and returns the metadata of the entity .
56
16
14,263
private static EntityMetadata loadMetadata ( Class < ? > entityClass ) { synchronized ( entityClass ) { EntityMetadata metadata = cache . get ( entityClass ) ; if ( metadata == null ) { EntityIntrospector introspector = new EntityIntrospector ( entityClass ) ; introspector . process ( ) ; metadata = introspector . entityMetadata ; cache . put ( entityClass , metadata ) ; } return metadata ; } }
Loads the metadata for the given class and puts it in the cache and returns it .
97
18
14,264
private void process ( ) { Entity entity = entityClass . getAnnotation ( Entity . class ) ; ProjectedEntity projectedEntity = entityClass . getAnnotation ( ProjectedEntity . class ) ; if ( entity != null ) { initEntityMetadata ( entity ) ; } else if ( projectedEntity != null ) { initEntityMetadata ( projectedEntity ) ; } else { String message = String . format ( "Class %s must either have %s or %s annotation" , entityClass . getName ( ) , Entity . class . getName ( ) , ProjectedEntity . class . getName ( ) ) ; throw new EntityManagerException ( message ) ; } processPropertyOverrides ( ) ; processFields ( ) ; // If we did not find valid Identifier... if ( entityMetadata . getIdentifierMetadata ( ) == null ) { throw new EntityManagerException ( String . format ( "Class %s requires a field with annotation of %s" , entityClass . getName ( ) , Identifier . class . getName ( ) ) ) ; } entityMetadata . setEntityListenersMetadata ( EntityListenersIntrospector . introspect ( entityClass ) ) ; entityMetadata . ensureUniqueProperties ( ) ; entityMetadata . cleanup ( ) ; }
Processes the entity class using reflection and builds the metadata .
272
12
14,265
private void processPropertyOverrides ( ) { PropertyOverrides propertyOverrides = entityClass . getAnnotation ( PropertyOverrides . class ) ; if ( propertyOverrides == null ) { return ; } PropertyOverride [ ] propertyOverridesArray = propertyOverrides . value ( ) ; for ( PropertyOverride propertyOverride : propertyOverridesArray ) { entityMetadata . putPropertyOverride ( propertyOverride ) ; } }
Processes the property overrides for the embedded objects if any .
94
13
14,266
private void processFields ( ) { List < Field > fields = getAllFields ( ) ; for ( Field field : fields ) { if ( field . isAnnotationPresent ( Identifier . class ) ) { processIdentifierField ( field ) ; } else if ( field . isAnnotationPresent ( Key . class ) ) { processKeyField ( field ) ; } else if ( field . isAnnotationPresent ( ParentKey . class ) ) { processParentKeyField ( field ) ; } else if ( field . isAnnotationPresent ( Embedded . class ) ) { processEmbeddedField ( field ) ; } else { processField ( field ) ; } } }
Processes the fields defined in this entity and updates the metadata .
141
13
14,267
private List < Field > getAllFields ( ) { List < Field > allFields = new ArrayList <> ( ) ; Class < ? > clazz = entityClass ; boolean stop ; do { List < Field > fields = IntrospectionUtils . getPersistableFields ( clazz ) ; allFields . addAll ( fields ) ; clazz = clazz . getSuperclass ( ) ; stop = clazz == null || ! clazz . isAnnotationPresent ( MappedSuperClass . class ) ; } while ( ! stop ) ; return allFields ; }
Processes the entity class and any super classes that are MappedSupperClasses and returns the fields .
124
22
14,268
private void processIdentifierField ( Field field ) { Identifier identifier = field . getAnnotation ( Identifier . class ) ; boolean autoGenerated = identifier . autoGenerated ( ) ; IdentifierMetadata identifierMetadata = new IdentifierMetadata ( field , autoGenerated ) ; entityMetadata . setIdentifierMetadata ( identifierMetadata ) ; }
Processes the identifier field and builds the identifier metadata .
77
11
14,269
private void processKeyField ( Field field ) { String fieldName = field . getName ( ) ; Class < ? > type = field . getType ( ) ; if ( ! type . equals ( DatastoreKey . class ) ) { String message = String . format ( "Invalid type, %s, for Key field %s in class %s. " , type , fieldName , entityClass ) ; throw new EntityManagerException ( message ) ; } KeyMetadata keyMetadata = new KeyMetadata ( field ) ; entityMetadata . setKeyMetadata ( keyMetadata ) ; }
Processes the Key field and builds the entity metadata .
125
11
14,270
private void processParentKeyField ( Field field ) { String fieldName = field . getName ( ) ; Class < ? > type = field . getType ( ) ; if ( ! type . equals ( DatastoreKey . class ) ) { String message = String . format ( "Invalid type, %s, for ParentKey field %s in class %s. " , type , fieldName , entityClass ) ; throw new EntityManagerException ( message ) ; } ParentKeyMetadata parentKeyMetadata = new ParentKeyMetadata ( field ) ; entityMetadata . setParentKetMetadata ( parentKeyMetadata ) ; }
Processes the ParentKey field and builds the entity metadata .
133
12
14,271
private void processField ( Field field ) { PropertyMetadata propertyMetadata = IntrospectionUtils . getPropertyMetadata ( field ) ; if ( propertyMetadata != null ) { // If the field is from a super class, there might be some // overrides, so process those. if ( ! field . getDeclaringClass ( ) . equals ( entityClass ) ) { applyPropertyOverride ( propertyMetadata ) ; } entityMetadata . putPropertyMetadata ( propertyMetadata ) ; if ( field . isAnnotationPresent ( Version . class ) ) { processVersionField ( propertyMetadata ) ; } else if ( field . isAnnotationPresent ( CreatedTimestamp . class ) ) { processCreatedTimestampField ( propertyMetadata ) ; } else if ( field . isAnnotationPresent ( UpdatedTimestamp . class ) ) { processUpdatedTimestampField ( propertyMetadata ) ; } } }
Processes the given field and generates the metadata .
190
10
14,272
private void processVersionField ( PropertyMetadata propertyMetadata ) { Class < ? > dataClass = propertyMetadata . getDeclaredType ( ) ; if ( ! long . class . equals ( dataClass ) ) { String messageFormat = "Field %s in class %s must be of type %s" ; throw new EntityManagerException ( String . format ( messageFormat , propertyMetadata . getField ( ) . getName ( ) , entityClass , long . class ) ) ; } entityMetadata . setVersionMetadata ( propertyMetadata ) ; }
Processes the Version annotation of the field with the given metadata .
118
13
14,273
private void validateAutoTimestampField ( PropertyMetadata propertyMetadata ) { Class < ? > dataClass = propertyMetadata . getDeclaredType ( ) ; if ( Collections . binarySearch ( VALID_TIMESTAMP_TYPES , dataClass . getName ( ) ) < 0 ) { String messageFormat = "Field %s in class %s must be one of the following types - %s" ; throw new EntityManagerException ( String . format ( messageFormat , propertyMetadata . getField ( ) . getName ( ) , entityClass , VALID_TIMESTAMP_TYPES ) ) ; } }
Validates the given property metadata to ensure it is valid for an automatic timestamp field .
135
17
14,274
private void applyPropertyOverride ( PropertyMetadata propertyMetadata ) { String name = propertyMetadata . getName ( ) ; Property override = entityMetadata . getPropertyOverride ( name ) ; if ( override != null ) { String mappedName = override . name ( ) ; if ( mappedName != null && mappedName . trim ( ) . length ( ) > 0 ) { propertyMetadata . setMappedName ( mappedName ) ; } propertyMetadata . setIndexed ( override . indexed ( ) ) ; propertyMetadata . setOptional ( override . optional ( ) ) ; } }
Applies any override information for the property with the given metadata .
123
13
14,275
private void processEmbeddedField ( Field field ) { // First create EmbeddedField so we can maintain the path/depth of the // embedded field EmbeddedField embeddedField = new EmbeddedField ( field ) ; // Introspect the embedded field. EmbeddedMetadata embeddedMetadata = EmbeddedIntrospector . introspect ( embeddedField , entityMetadata ) ; entityMetadata . putEmbeddedMetadata ( embeddedMetadata ) ; }
Processes and gathers the metadata for the given embedded field .
93
12
14,276
private MethodHandle findIdReadMethod ( ) { try { Method readMethod = clazz . getMethod ( READ_METHOD_NAME ) ; Class < ? > dataClass = readMethod . getReturnType ( ) ; DataType dataType = IdentifierMetadata . DataType . forClass ( dataClass ) ; if ( dataType == null ) { String pattern = "Method %s in class %s must have a return type of long, Long or String" ; String error = String . format ( pattern , READ_METHOD_NAME , clazz . getName ( ) ) ; throw new EntityManagerException ( error ) ; } return MethodHandles . lookup ( ) . unreflect ( readMethod ) ; } catch ( NoSuchMethodException | SecurityException | IllegalAccessException exp ) { String error = String . format ( "Class %s must have a public %s method" , clazz . getName ( ) , READ_METHOD_NAME ) ; throw new EntityManagerException ( error , exp ) ; } }
Creates and returns the MethodHandle for reading the underlying ID .
212
13
14,277
private MethodHandle findConstructor ( ) { try { MethodHandle mh = MethodHandles . publicLookup ( ) . findConstructor ( clazz , MethodType . methodType ( void . class , getIdType ( ) ) ) ; return mh ; } catch ( NoSuchMethodException | IllegalAccessException exp ) { String pattern = "Class %s requires a public constructor with one parameter of type %s" ; String error = String . format ( pattern , clazz . getName ( ) , getIdType ( ) ) ; throw new EntityManagerException ( error , exp ) ; } }
Creates and returns the MethodHandle for the constructor .
126
11
14,278
public static Object instantiate ( MetadataBase metadata ) { try { return metadata . getConstructorMetadata ( ) . getConstructorMethodHandle ( ) . invoke ( ) ; } catch ( Throwable t ) { throw new EntityManagerException ( t ) ; } }
Creates and returns a new instance of a persistence class for the given metadata . The returned object will be an instance of the primary persistence class or its Builder .
56
32
14,279
public static PropertyMetadata getPropertyMetadata ( Field field ) { Property property = field . getAnnotation ( Property . class ) ; // For fields that have @Property annotation, we expect both setter and // getter methods. For all other fields, we only treat them as // persistable if we find valid getter and setter methods. try { PropertyMetadata propertyMetadata = new PropertyMetadata ( field ) ; return propertyMetadata ; } catch ( NoAccessorMethodException | NoMutatorMethodException exp ) { if ( property != null ) { throw exp ; } } return null ; }
Returns the metadata for the given field .
127
8
14,280
public static Object instantiateObject ( Class < ? > clazz ) { try { Constructor < ? > constructor = clazz . getConstructor ( ) ; return constructor . newInstance ( ) ; } catch ( Exception exp ) { throw new EntityManagerException ( exp ) ; } }
Creates a new object of given class by invoking the class default public constructor .
59
16
14,281
public static Object getFieldValue ( FieldMetadata fieldMetadata , Object target ) { MethodHandle readMethod = fieldMetadata . getReadMethod ( ) ; try { return readMethod . invoke ( target ) ; } catch ( Throwable t ) { throw new EntityManagerException ( t . getMessage ( ) , t ) ; } }
Returns the value of the field represented by the given metadata .
70
12
14,282
public static MethodHandle findStaticMethod ( Class < ? > clazz , String methodName , Class < ? > expectedReturnType , Class < ? > ... expectedParameterTypes ) { return findMethod ( clazz , methodName , true , expectedReturnType , expectedParameterTypes ) ; }
Finds and returns a MethodHandle for a public static method .
59
13
14,283
public static MethodHandle findInstanceMethod ( Class < ? > clazz , String methodName , Class < ? > expectedReturnType , Class < ? > ... expectedParameterTypes ) { return findMethod ( clazz , methodName , false , expectedReturnType , expectedParameterTypes ) ; }
Finds and returns a MethodHandle for a public instance method .
59
13
14,284
private static MethodHandle findMethod ( Class < ? > clazz , String methodName , boolean staticMethod , Class < ? > expectedReturnType , Class < ? > ... expectedParameterTypes ) { MethodHandle methodHandle = null ; try { Method method = clazz . getMethod ( methodName , expectedParameterTypes ) ; int modifiers = method . getModifiers ( ) ; Class < ? > returnType = method . getReturnType ( ) ; if ( Modifier . isStatic ( modifiers ) != staticMethod ) { throw new NoSuchMethodException ( ) ; } if ( expectedReturnType != null && ! expectedReturnType . isAssignableFrom ( returnType ) ) { throw new NoSuchMethodException ( ) ; } methodHandle = MethodHandles . publicLookup ( ) . unreflect ( method ) ; } catch ( NoSuchMethodException | SecurityException | IllegalAccessException e ) { // Method not found } return methodHandle ; }
Finds and returns a method handle for the given criteria .
197
12
14,285
public void setOptional ( boolean optional ) { if ( field . getType ( ) . isPrimitive ( ) || field . isAnnotationPresent ( Version . class ) || field . isAnnotationPresent ( CreatedTimestamp . class ) || field . isAnnotationPresent ( UpdatedTimestamp . class ) ) { this . optional = false ; } else { this . optional = optional ; } }
Sets whether or not the field represented by this metadata is optional .
82
14
14,286
private void initializeSecondaryIndexer ( ) { SecondaryIndex secondaryIndexAnnotation = field . getAnnotation ( SecondaryIndex . class ) ; if ( secondaryIndexAnnotation == null ) { return ; } String indexName = secondaryIndexAnnotation . name ( ) ; if ( indexName == null || indexName . trim ( ) . length ( ) == 0 ) { indexName = DEFAULT_SECONDARY_INDEX_PREFIX + mappedName ; } this . secondaryIndexName = indexName ; try { secondaryIndexer = IndexerFactory . getInstance ( ) . getIndexer ( field ) ; } catch ( Exception exp ) { String pattern = "No suitable Indexer found or error occurred while creating the indexer " + "for field %s in class %s" ; String message = String . format ( pattern , field . getName ( ) , field . getDeclaringClass ( ) . getName ( ) ) ; throw new EntityManagerException ( message , exp ) ; } }
Initializes the secondary indexer for this property if any .
209
12
14,287
public static EntityListenersMetadata introspect ( Class < ? > entityClass ) { EntityListenersIntrospector introspector = new EntityListenersIntrospector ( entityClass ) ; introspector . introspect ( ) ; return introspector . metadata ; }
Returns the metadata of various registered listeners for the given entity class .
59
13
14,288
private List < Class < ? > > getAllExternalListeners ( ) { Class < ? > clazz = entityClass ; List < Class < ? > > allListeners = new ArrayList <> ( ) ; boolean stop = false ; while ( ! stop ) { EntityListeners entityListenersAnnotation = clazz . getAnnotation ( EntityListeners . class ) ; if ( entityListenersAnnotation != null ) { Class < ? > [ ] listeners = entityListenersAnnotation . value ( ) ; if ( listeners . length > 0 ) { allListeners . addAll ( 0 , Arrays . asList ( listeners ) ) ; } } boolean excludeDefaultListeners = clazz . isAnnotationPresent ( ExcludeDefaultListeners . class ) ; boolean excludeSuperClassListeners = clazz . isAnnotationPresent ( ExcludeSuperclassListeners . class ) ; if ( excludeDefaultListeners ) { metadata . setExcludeDefaultListeners ( true ) ; } if ( excludeSuperClassListeners ) { metadata . setExcludeSuperClassListeners ( true ) ; } clazz = clazz . getSuperclass ( ) ; stop = excludeSuperClassListeners || clazz == null || ! clazz . isAnnotationPresent ( MappedSuperClass . class ) ; } return allListeners ; }
Inspects the entity hierarchy and returns all external listeners .
279
12
14,289
private void processExternalListener ( Class < ? > listenerClass ) { ExternalListenerMetadata listenerMetadata = ExternalListenerIntrospector . introspect ( listenerClass ) ; Map < CallbackType , Method > callbacks = listenerMetadata . getCallbacks ( ) ; if ( callbacks != null ) { for ( Map . Entry < CallbackType , Method > entry : callbacks . entrySet ( ) ) { validateExternalCallback ( entry . getValue ( ) , entry . getKey ( ) ) ; } } }
Introspects the given listener class and finds all methods that should receive callback event notifications .
110
19
14,290
private void validateExternalCallback ( Method method , CallbackType callbackType ) { Class < ? > [ ] parameters = method . getParameterTypes ( ) ; if ( ! parameters [ 0 ] . isAssignableFrom ( entityClass ) ) { String message = String . format ( "Method %s in class %s is not valid for entity %s" , method . getName ( ) , method . getDeclaringClass ( ) . getName ( ) , entityClass . getName ( ) ) ; throw new EntityManagerException ( message ) ; } CallbackMetadata callbackMetadata = new CallbackMetadata ( EntityListenerType . EXTERNAL , callbackType , method ) ; metadata . put ( callbackType , callbackMetadata ) ; }
Validates and registers the given callback method .
156
9
14,291
private void processInternalListeners ( ) { List < Class < ? > > internalListeners = getAllInternalListeners ( ) ; for ( Class < ? > internalListener : internalListeners ) { processInternalListener ( internalListener ) ; } }
Introspects the entity class hierarchy for any internal callback methods and updates the metadata .
52
18
14,292
private List < Class < ? > > getAllInternalListeners ( ) { Class < ? > clazz = entityClass ; List < Class < ? > > allListeners = new ArrayList <> ( ) ; boolean stop = false ; while ( ! stop ) { allListeners . add ( 0 , clazz ) ; boolean excludeSuperClassListeners = clazz . isAnnotationPresent ( ExcludeSuperclassListeners . class ) ; clazz = clazz . getSuperclass ( ) ; stop = excludeSuperClassListeners || clazz == null || ! clazz . isAnnotationPresent ( MappedSuperClass . class ) ; } return allListeners ; }
Traverses up the entity class hierarchy and returns the list of all classes that may potentially have callback listeners .
142
22
14,293
private void processInternalListener ( Class < ? > listenerClass ) { InternalListenerMetadata listenerMetadata = InternalListenerIntrospector . introspect ( listenerClass ) ; Map < CallbackType , Method > callbacks = listenerMetadata . getCallbacks ( ) ; if ( callbacks != null ) { for ( Map . Entry < CallbackType , Method > entry : callbacks . entrySet ( ) ) { CallbackType callbackType = entry . getKey ( ) ; Method callbackMethod = entry . getValue ( ) ; CallbackMetadata callbackMetadata = new CallbackMetadata ( EntityListenerType . INTERNAL , callbackType , callbackMethod ) ; metadata . put ( callbackType , callbackMetadata ) ; } } }
Processes the given class and finds any internal callbacks .
156
12
14,294
public Object getListener ( Class < ? > listenerClass ) { Object listener = listeners . get ( listenerClass ) ; if ( listener == null ) { listener = loadListener ( listenerClass ) ; } return listener ; }
Returns the listener object for the given class .
45
9
14,295
private Object loadListener ( Class < ? > listenerClass ) { synchronized ( listenerClass ) { Object listener = listeners . get ( listenerClass ) ; if ( listener == null ) { listener = IntrospectionUtils . instantiateObject ( listenerClass ) ; listeners . put ( listenerClass , listener ) ; } return listener ; } }
Instantiates the listener of given type and caches it .
68
12
14,296
public static EmbeddableMetadata introspect ( Class < ? > embeddableClass ) { EmbeddableIntrospector introspector = new EmbeddableIntrospector ( embeddableClass ) ; introspector . introspect ( ) ; return introspector . metadata ; }
Introspects the given Embeddable class and returns the metadata .
63
15
14,297
private void introspect ( ) { // Make sure the class is Embeddable if ( ! embeddableClass . isAnnotationPresent ( Embeddable . class ) ) { String message = String . format ( "Class %s must have %s annotation" , embeddableClass . getName ( ) , Embeddable . class . getName ( ) ) ; throw new EntityManagerException ( message ) ; } metadata = new EmbeddableMetadata ( embeddableClass ) ; processFields ( ) ; }
Introspects the Embeddable .
109
9
14,298
private void processFields ( ) { List < Field > fields = IntrospectionUtils . getPersistableFields ( embeddableClass ) ; for ( Field field : fields ) { if ( field . isAnnotationPresent ( Embedded . class ) ) { processEmbeddedField ( field ) ; } else { processSimpleField ( field ) ; } } }
Processes each field in this Embeddable and updates the metadata .
77
14
14,299
public static EmbeddedMetadata introspect ( EmbeddedField field , EntityMetadata entityMetadata ) { EmbeddedIntrospector introspector = new EmbeddedIntrospector ( field , entityMetadata ) ; introspector . process ( ) ; return introspector . metadata ; }
Introspects the given embedded field and returns its metadata .
63
13