idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
25,900
private String getApiId ( Contract contract ) { return getApiId ( contract . getApiOrgId ( ) , contract . getApiId ( ) , contract . getApiVersion ( ) ) ; }
Generates a valid document ID for a api referenced by a contract used to retrieve the api from ES .
25,901
public static final String produceToken ( String principal , Set < String > roles , int expiresInMillis ) { AuthToken authToken = createAuthToken ( principal , roles , expiresInMillis ) ; String json = toJSON ( authToken ) ; return StringUtils . newStringUtf8 ( Base64 . encodeBase64 ( StringUtils . getBytesUtf8 ( json ) ) ) ; }
Produce a token suitable for transmission . This will generate the auth token then serialize it to a JSON string then Base64 encode the JSON .
25,902
public static final void validateToken ( AuthToken token ) throws IllegalArgumentException { if ( token . getExpiresOn ( ) . before ( new Date ( ) ) ) { throw new IllegalArgumentException ( "Authentication token expired: " + token . getExpiresOn ( ) ) ; } String validSig = generateSignature ( token ) ; if ( token . getSignature ( ) == null || ! token . getSignature ( ) . equals ( validSig ) ) { throw new IllegalArgumentException ( "Missing or invalid signature on the auth token." ) ; } }
Validates an auth token . This checks the expiration time of the token against the current system time . It also checks the validity of the signature .
25,903
public static final AuthToken createAuthToken ( String principal , Set < String > roles , int expiresInMillis ) { AuthToken token = new AuthToken ( ) ; token . setIssuedOn ( new Date ( ) ) ; token . setExpiresOn ( new Date ( System . currentTimeMillis ( ) + expiresInMillis ) ) ; token . setPrincipal ( principal ) ; token . setRoles ( roles ) ; signAuthToken ( token ) ; return token ; }
Creates an auth token .
25,904
public static final void signAuthToken ( AuthToken token ) { String signature = generateSignature ( token ) ; token . setSignature ( signature ) ; }
Adds a digital signature to the auth token .
25,905
private static String generateSignature ( AuthToken token ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( token . getPrincipal ( ) ) ; builder . append ( "||" ) ; builder . append ( token . getExpiresOn ( ) . getTime ( ) ) ; builder . append ( "||" ) ; builder . append ( token . getIssuedOn ( ) . getTime ( ) ) ; builder . append ( "||" ) ; TreeSet < String > roles = new TreeSet < > ( token . getRoles ( ) ) ; boolean first = true ; for ( String role : roles ) { if ( first ) { first = false ; } else { builder . append ( "," ) ; } builder . append ( role ) ; } builder . append ( "||" ) ; builder . append ( sharedSecretSource . getSharedSecret ( ) ) ; return DigestUtils . sha256Hex ( builder . toString ( ) ) ; }
Generates a signature for the given token .
25,906
public static final String toJSON ( AuthToken token ) { try { return mapper . writer ( ) . writeValueAsString ( token ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Convert the auth token to a JSON string .
25,907
public static final AuthToken fromJSON ( String json ) { try { return mapper . reader ( AuthToken . class ) . readValue ( json ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Read the auth token from the JSON string .
25,908
public final IEngine createEngine ( ) { IPluginRegistry pluginRegistry = createPluginRegistry ( ) ; IDataEncrypter encrypter = createDataEncrypter ( pluginRegistry ) ; CurrentDataEncrypter . instance = encrypter ; IRegistry registry = createRegistry ( pluginRegistry , encrypter ) ; IComponentRegistry componentRegistry = createComponentRegistry ( pluginRegistry ) ; IConnectorFactory cfactory = createConnectorFactory ( pluginRegistry ) ; IPolicyFactory pfactory = createPolicyFactory ( pluginRegistry ) ; IMetrics metrics = createMetrics ( pluginRegistry ) ; IDelegateFactory logFactory = createLoggerFactory ( pluginRegistry ) ; IApiRequestPathParser pathParser = createRequestPathParser ( pluginRegistry ) ; List < IGatewayInitializer > initializers = createInitializers ( pluginRegistry ) ; for ( IGatewayInitializer initializer : initializers ) { initializer . initialize ( ) ; } complete ( ) ; return new EngineImpl ( registry , pluginRegistry , componentRegistry , cfactory , pfactory , metrics , logFactory , pathParser ) ; }
Call this to create a new engine . This method uses the engine config singleton to create the engine .
25,909
protected Map < String , String > getPrefixedProperties ( String prefix ) { Map < String , String > rval = new HashMap < > ( ) ; Iterator < String > keys = getConfig ( ) . getKeys ( ) ; while ( keys . hasNext ( ) ) { String key = keys . next ( ) ; if ( key . startsWith ( prefix ) ) { String value = getConfig ( ) . getString ( key ) ; key = key . substring ( prefix . length ( ) ) ; rval . put ( key , value ) ; } } return rval ; }
Gets a map of properties prefixed by the given string .
25,910
protected static RateBucketPeriod getPeriod ( RateLimitingConfig config ) { RateLimitingPeriod period = config . getPeriod ( ) ; switch ( period ) { case Second : return RateBucketPeriod . Second ; case Day : return RateBucketPeriod . Day ; case Hour : return RateBucketPeriod . Hour ; case Minute : return RateBucketPeriod . Minute ; case Month : return RateBucketPeriod . Month ; case Year : return RateBucketPeriod . Year ; default : return RateBucketPeriod . Month ; } }
Gets the appropriate bucket period from the config .
25,911
private void setConnectTimeout ( HttpURLConnection connection ) { try { Map < String , String > endpointProperties = this . api . getEndpointProperties ( ) ; if ( endpointProperties . containsKey ( "timeouts.connect" ) ) { int connectTimeoutMs = new Integer ( endpointProperties . get ( "timeouts.connect" ) ) ; connection . setConnectTimeout ( connectTimeoutMs ) ; } } catch ( Throwable t ) { } }
If the endpoint properties includes a connect timeout override then set it here .
25,912
public static final void main ( String [ ] args ) throws Exception { ManagerApiMicroService microService = new ManagerApiMicroService ( ) ; microService . start ( ) ; microService . join ( ) ; }
Main entry point for the API Manager micro service .
25,913
public static int length ( String ... args ) { if ( args == null ) return 0 ; int acc = 0 ; for ( String arg : args ) { acc += arg . length ( ) ; } return acc ; }
Cumulative length of strings in varargs
25,914
private static void outputMessages ( TreeMap < String , String > strings , File outputFile ) throws FileNotFoundException { PrintWriter writer = new PrintWriter ( new FileOutputStream ( outputFile ) ) ; for ( Entry < String , String > entry : strings . entrySet ( ) ) { String key = entry . getKey ( ) ; String val = entry . getValue ( ) ; writer . append ( key ) ; writer . append ( '=' ) ; writer . append ( val ) ; writer . append ( "\n" ) ; } writer . flush ( ) ; writer . close ( ) ; }
Output the sorted map of strings to the specified output file .
25,915
private static File getPluginDir ( ) { String dataDirPath = System . getProperty ( "jboss.server.data.dir" ) ; File dataDir = new File ( dataDirPath ) ; if ( ! dataDir . isDirectory ( ) ) { throw new RuntimeException ( "Failed to find WildFly data directory at: " + dataDirPath ) ; } File pluginsDir = new File ( dataDir , "apiman/plugins" ) ; return pluginsDir ; }
Creates the directory to use for the plugin registry . The location of the plugin registry is in the Wildfly data directory .
25,916
public JestClient createClient ( Map < String , String > config , String defaultIndexName ) { JestClient client ; String indexName = config . get ( "client.index" ) ; if ( indexName == null ) { indexName = defaultIndexName ; } client = createLocalClient ( config , indexName , defaultIndexName ) ; return client ; }
Creates a client from information in the config map .
25,917
public JestClient createLocalClient ( Map < String , String > config , String indexName , String defaultIndexName ) { String clientLocClassName = config . get ( "client.class" ) ; String clientLocFieldName = config . get ( "client.field" ) ; return createLocalClient ( clientLocClassName , clientLocFieldName , indexName , defaultIndexName ) ; }
Creates a local client from a configuration map .
25,918
public JestClient createLocalClient ( String className , String fieldName , String indexName , String defaultIndexName ) { String clientKey = "local:" + className + '/' + fieldName ; synchronized ( clients ) { if ( clients . containsKey ( clientKey ) ) { return clients . get ( clientKey ) ; } else { try { Class < ? > clientLocClass = Class . forName ( className ) ; Field field = clientLocClass . getField ( fieldName ) ; JestClient client = ( JestClient ) field . get ( null ) ; clients . put ( clientKey , client ) ; initializeClient ( client , indexName , defaultIndexName ) ; return client ; } catch ( ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e ) { throw new RuntimeException ( "Error using local elasticsearch client." , e ) ; } } } }
Creates a cache by looking it up in a static field . Typically used for testing .
25,919
protected ClientVersionBean createClientVersionInternal ( NewClientVersionBean bean , ClientBean client ) throws StorageException { if ( ! BeanUtils . isValidVersion ( bean . getVersion ( ) ) ) { throw new StorageException ( "Invalid/illegal client version: " + bean . getVersion ( ) ) ; } ClientVersionBean newVersion = new ClientVersionBean ( ) ; newVersion . setClient ( client ) ; newVersion . setCreatedBy ( securityContext . getCurrentUser ( ) ) ; newVersion . setCreatedOn ( new Date ( ) ) ; newVersion . setModifiedBy ( securityContext . getCurrentUser ( ) ) ; newVersion . setModifiedOn ( new Date ( ) ) ; newVersion . setStatus ( ClientStatus . Created ) ; newVersion . setVersion ( bean . getVersion ( ) ) ; newVersion . setApikey ( bean . getApiKey ( ) ) ; if ( newVersion . getApikey ( ) == null ) { newVersion . setApikey ( apiKeyGenerator . generate ( ) ) ; } storage . createClientVersion ( newVersion ) ; storage . createAuditEntry ( AuditUtils . clientVersionCreated ( newVersion , securityContext ) ) ; log . debug ( String . format ( "Created new client version %s: %s" , newVersion . getClient ( ) . getName ( ) , newVersion ) ) ; return newVersion ; }
Creates a new client version .
25,920
protected ContractBean createContractInternal ( String organizationId , String clientId , String version , NewContractBean bean ) throws StorageException , Exception { ContractBean contract ; ClientVersionBean cvb ; cvb = storage . getClientVersion ( organizationId , clientId , version ) ; if ( cvb == null ) { throw ExceptionFactory . clientVersionNotFoundException ( clientId , version ) ; } if ( cvb . getStatus ( ) == ClientStatus . Retired ) { throw ExceptionFactory . invalidClientStatusException ( ) ; } ApiVersionBean avb = storage . getApiVersion ( bean . getApiOrgId ( ) , bean . getApiId ( ) , bean . getApiVersion ( ) ) ; if ( avb == null ) { throw ExceptionFactory . apiNotFoundException ( bean . getApiId ( ) ) ; } if ( avb . getStatus ( ) != ApiStatus . Published ) { throw ExceptionFactory . invalidApiStatusException ( ) ; } Set < ApiPlanBean > plans = avb . getPlans ( ) ; String planVersion = null ; if ( plans != null ) { for ( ApiPlanBean apiPlanBean : plans ) { if ( apiPlanBean . getPlanId ( ) . equals ( bean . getPlanId ( ) ) ) { planVersion = apiPlanBean . getVersion ( ) ; } } } if ( planVersion == null ) { throw ExceptionFactory . planNotFoundException ( bean . getPlanId ( ) ) ; } PlanVersionBean pvb = storage . getPlanVersion ( bean . getApiOrgId ( ) , bean . getPlanId ( ) , planVersion ) ; if ( pvb == null ) { throw ExceptionFactory . planNotFoundException ( bean . getPlanId ( ) ) ; } if ( pvb . getStatus ( ) != PlanStatus . Locked ) { throw ExceptionFactory . invalidPlanStatusException ( ) ; } contract = new ContractBean ( ) ; contract . setClient ( cvb ) ; contract . setApi ( avb ) ; contract . setPlan ( pvb ) ; contract . setCreatedBy ( securityContext . getCurrentUser ( ) ) ; contract . setCreatedOn ( new Date ( ) ) ; if ( cvb . getStatus ( ) == ClientStatus . Created && clientValidator . isReady ( cvb , true ) ) { cvb . setStatus ( ClientStatus . Ready ) ; } storage . createContract ( contract ) ; storage . createAuditEntry ( AuditUtils . contractCreatedFromClient ( contract , securityContext ) ) ; storage . createAuditEntry ( AuditUtils . contractCreatedToApi ( contract , securityContext ) ) ; cvb . setModifiedBy ( securityContext . getCurrentUser ( ) ) ; cvb . setModifiedOn ( new Date ( ) ) ; storage . updateClientVersion ( cvb ) ; return contract ; }
Creates a contract .
25,921
private boolean contractAlreadyExists ( String organizationId , String clientId , String version , NewContractBean bean ) { try { List < ContractSummaryBean > contracts = query . getClientContracts ( organizationId , clientId , version ) ; for ( ContractSummaryBean contract : contracts ) { if ( contract . getApiOrganizationId ( ) . equals ( bean . getApiOrgId ( ) ) && contract . getApiId ( ) . equals ( bean . getApiId ( ) ) && contract . getApiVersion ( ) . equals ( bean . getApiVersion ( ) ) && contract . getPlanId ( ) . equals ( bean . getPlanId ( ) ) ) { return true ; } } return false ; } catch ( StorageException e ) { return false ; } }
Check to see if the contract already exists by getting a list of all the client s contracts and comparing with the one being created .
25,922
protected ApiRegistryBean getApiRegistry ( String organizationId , String clientId , String version , boolean hasPermission ) throws ClientNotFoundException , NotAuthorizedException { ClientVersionBean clientVersion = getClientVersionInternal ( organizationId , clientId , version , hasPermission ) ; Map < String , IGatewayLink > gatewayLinks = new HashMap < > ( ) ; Map < String , GatewayBean > gateways = new HashMap < > ( ) ; boolean txStarted = false ; try { ApiRegistryBean apiRegistry = query . getApiRegistry ( organizationId , clientId , version ) ; if ( hasPermission ) { apiRegistry . setApiKey ( clientVersion . getApikey ( ) ) ; } List < ApiEntryBean > apis = apiRegistry . getApis ( ) ; storage . beginTx ( ) ; txStarted = true ; for ( ApiEntryBean api : apis ) { String gatewayId = api . getGatewayId ( ) ; api . setGatewayId ( null ) ; GatewayBean gateway = gateways . get ( gatewayId ) ; if ( gateway == null ) { gateway = storage . getGateway ( gatewayId ) ; gateways . put ( gatewayId , gateway ) ; } IGatewayLink link = gatewayLinks . get ( gatewayId ) ; if ( link == null ) { link = gatewayLinkFactory . create ( gateway ) ; gatewayLinks . put ( gatewayId , link ) ; } ApiEndpoint se = link . getApiEndpoint ( api . getApiOrgId ( ) , api . getApiId ( ) , api . getApiVersion ( ) ) ; String apiEndpoint = se . getEndpoint ( ) ; api . setHttpEndpoint ( apiEndpoint ) ; } return apiRegistry ; } catch ( StorageException | GatewayAuthenticationException e ) { throw new SystemErrorException ( e ) ; } finally { if ( txStarted ) { storage . rollbackTx ( ) ; } for ( IGatewayLink link : gatewayLinks . values ( ) ) { link . close ( ) ; } } }
Gets the API registry .
25,923
protected PlanVersionBean createPlanVersionInternal ( NewPlanVersionBean bean , PlanBean plan ) throws StorageException { if ( ! BeanUtils . isValidVersion ( bean . getVersion ( ) ) ) { throw new StorageException ( "Invalid/illegal plan version: " + bean . getVersion ( ) ) ; } PlanVersionBean newVersion = new PlanVersionBean ( ) ; newVersion . setCreatedBy ( securityContext . getCurrentUser ( ) ) ; newVersion . setCreatedOn ( new Date ( ) ) ; newVersion . setModifiedBy ( securityContext . getCurrentUser ( ) ) ; newVersion . setModifiedOn ( new Date ( ) ) ; newVersion . setStatus ( PlanStatus . Created ) ; newVersion . setPlan ( plan ) ; newVersion . setVersion ( bean . getVersion ( ) ) ; storage . createPlanVersion ( newVersion ) ; storage . createAuditEntry ( AuditUtils . planVersionCreated ( newVersion , securityContext ) ) ; return newVersion ; }
Creates a plan version .
25,924
protected PolicyBean doGetPolicy ( PolicyType type , String organizationId , String entityId , String entityVersion , long policyId ) throws PolicyNotFoundException { try { storage . beginTx ( ) ; PolicyBean policy = storage . getPolicy ( type , organizationId , entityId , entityVersion , policyId ) ; if ( policy == null ) { throw ExceptionFactory . policyNotFoundException ( policyId ) ; } storage . commitTx ( ) ; if ( policy . getType ( ) != type ) { throw ExceptionFactory . policyNotFoundException ( policyId ) ; } if ( ! policy . getOrganizationId ( ) . equals ( organizationId ) ) { throw ExceptionFactory . policyNotFoundException ( policyId ) ; } if ( ! policy . getEntityId ( ) . equals ( entityId ) ) { throw ExceptionFactory . policyNotFoundException ( policyId ) ; } if ( ! policy . getEntityVersion ( ) . equals ( entityVersion ) ) { throw ExceptionFactory . policyNotFoundException ( policyId ) ; } PolicyTemplateUtil . generatePolicyDescription ( policy ) ; return policy ; } catch ( AbstractRestException e ) { storage . rollbackTx ( ) ; throw e ; } catch ( Exception e ) { storage . rollbackTx ( ) ; throw new SystemErrorException ( e ) ; } }
Gets a policy by its id . Also verifies that the policy really does belong to the entity indicated .
25,925
private void decryptEndpointProperties ( ApiVersionBean versionBean ) { Map < String , String > endpointProperties = versionBean . getEndpointProperties ( ) ; if ( endpointProperties != null ) { for ( Entry < String , String > entry : endpointProperties . entrySet ( ) ) { DataEncryptionContext ctx = new DataEncryptionContext ( versionBean . getApi ( ) . getOrganization ( ) . getId ( ) , versionBean . getApi ( ) . getId ( ) , versionBean . getVersion ( ) , EntityType . Api ) ; entry . setValue ( encrypter . decrypt ( entry . getValue ( ) , ctx ) ) ; } } }
Decrypt the endpoint properties
25,926
private DateTime parseFromDate ( String fromDate ) { DateTime defaultFrom = new DateTime ( ) . withZone ( DateTimeZone . UTC ) . minusDays ( 30 ) . withHourOfDay ( 0 ) . withMinuteOfHour ( 0 ) . withSecondOfMinute ( 0 ) . withMillisOfSecond ( 0 ) ; return parseDate ( fromDate , defaultFrom , true ) ; }
Parse the to date query param .
25,927
private DateTime parseToDate ( String toDate ) { return parseDate ( toDate , new DateTime ( ) . withZone ( DateTimeZone . UTC ) , false ) ; }
Parse the from date query param .
25,928
private static DateTime parseDate ( String dateStr , DateTime defaultDate , boolean floor ) { if ( "now" . equals ( dateStr ) ) { return new DateTime ( ) ; } if ( dateStr . length ( ) == 10 ) { DateTime parsed = ISODateTimeFormat . date ( ) . withZone ( DateTimeZone . UTC ) . parseDateTime ( dateStr ) ; if ( ! floor ) { parsed = parsed . plusDays ( 1 ) . minusMillis ( 1 ) ; } return parsed ; } if ( dateStr . length ( ) == 20 ) { return ISODateTimeFormat . dateTimeNoMillis ( ) . withZone ( DateTimeZone . UTC ) . parseDateTime ( dateStr ) ; } if ( dateStr . length ( ) == 24 ) { return ISODateTimeFormat . dateTime ( ) . withZone ( DateTimeZone . UTC ) . parseDateTime ( dateStr ) ; } return defaultDate ; }
Parses a query param representing a date into an actual date object .
25,929
private void validateMetricRange ( DateTime from , DateTime to ) throws InvalidMetricCriteriaException { if ( from . isAfter ( to ) ) { throw ExceptionFactory . invalidMetricCriteriaException ( Messages . i18n . format ( "OrganizationResourceImpl.InvalidMetricDateRange" ) ) ; } }
Ensures that the given date range is valid .
25,930
private void validateTimeSeriesMetric ( DateTime from , DateTime to , HistogramIntervalType interval ) throws InvalidMetricCriteriaException { long millis = to . getMillis ( ) - from . getMillis ( ) ; long divBy = ONE_DAY_MILLIS ; switch ( interval ) { case day : divBy = ONE_DAY_MILLIS ; break ; case hour : divBy = ONE_HOUR_MILLIS ; break ; case minute : divBy = ONE_MINUTE_MILLIS ; break ; case month : divBy = ONE_MONTH_MILLIS ; break ; case week : divBy = ONE_WEEK_MILLIS ; break ; default : break ; } long totalDataPoints = millis / divBy ; if ( totalDataPoints > 5000 ) { throw ExceptionFactory . invalidMetricCriteriaException ( Messages . i18n . format ( "OrganizationResourceImpl.MetricDataSetTooLarge" ) ) ; } }
Ensures that a time series can be created for the given date range and interval and that the
25,931
private void validateEndpoint ( String endpoint ) { try { new URL ( endpoint ) ; } catch ( MalformedURLException e ) { throw new InvalidParameterException ( Messages . i18n . format ( "OrganizationResourceImpl.InvalidEndpointURL" ) ) ; } }
Make sure we ve got a valid URL .
25,932
public < T > void delete ( T bean ) throws StorageException { EntityManager entityManager = getActiveEntityManager ( ) ; try { entityManager . remove ( bean ) ; } catch ( Throwable t ) { logger . error ( t . getMessage ( ) , t ) ; throw new StorageException ( t ) ; } }
Delete using bean
25,933
protected < T > SearchResultsBean < T > find ( SearchCriteriaBean criteria , Class < T > type ) throws StorageException { SearchResultsBean < T > results = new SearchResultsBean < > ( ) ; EntityManager entityManager = getActiveEntityManager ( ) ; try { PagingBean paging = criteria . getPaging ( ) ; if ( paging == null ) { paging = new PagingBean ( ) ; paging . setPage ( 1 ) ; paging . setPageSize ( 20 ) ; } int page = paging . getPage ( ) ; int pageSize = paging . getPageSize ( ) ; int start = ( page - 1 ) * pageSize ; CriteriaBuilder builder = entityManager . getCriteriaBuilder ( ) ; CriteriaQuery < T > criteriaQuery = builder . createQuery ( type ) ; Root < T > from = criteriaQuery . from ( type ) ; applySearchCriteriaToQuery ( criteria , builder , criteriaQuery , from , false ) ; TypedQuery < T > typedQuery = entityManager . createQuery ( criteriaQuery ) ; typedQuery . setFirstResult ( start ) ; typedQuery . setMaxResults ( pageSize + 1 ) ; boolean hasMore = false ; List < T > resultList = typedQuery . getResultList ( ) ; if ( resultList . size ( ) > pageSize ) { resultList . remove ( resultList . size ( ) - 1 ) ; hasMore = true ; } int totalSize = start + resultList . size ( ) ; if ( hasMore ) { totalSize = executeCountQuery ( criteria , entityManager , type ) ; } results . setTotalSize ( totalSize ) ; results . setBeans ( resultList ) ; return results ; } catch ( Throwable t ) { logger . error ( t . getMessage ( ) , t ) ; throw new StorageException ( t ) ; } }
Get a list of entities based on the provided criteria and entity type .
25,934
protected < T > int executeCountQuery ( SearchCriteriaBean criteria , EntityManager entityManager , Class < T > type ) { CriteriaBuilder builder = entityManager . getCriteriaBuilder ( ) ; CriteriaQuery < Long > countQuery = builder . createQuery ( Long . class ) ; Root < T > from = countQuery . from ( type ) ; countQuery . select ( builder . count ( from ) ) ; applySearchCriteriaToQuery ( criteria , builder , countQuery , from , true ) ; TypedQuery < Long > query = entityManager . createQuery ( countQuery ) ; return query . getSingleResult ( ) . intValue ( ) ; }
Gets a count of the number of rows that would be returned by the search .
25,935
public boolean hasQualifiedPermission ( PermissionType permissionName , String orgQualifier ) { String key = createQualifiedPermissionKey ( permissionName , orgQualifier ) ; return qualifiedPermissions . contains ( key ) ; }
Returns true if the qualified permission exists .
25,936
public Set < String > getOrgQualifiers ( PermissionType permissionName ) { Set < String > orgs = permissionToOrgsMap . get ( permissionName ) ; if ( orgs == null ) orgs = Collections . EMPTY_SET ; return Collections . unmodifiableSet ( orgs ) ; }
Given a permission name returns all organization qualifiers .
25,937
private void index ( Set < PermissionBean > permissions ) { for ( PermissionBean permissionBean : permissions ) { PermissionType permissionName = permissionBean . getName ( ) ; String orgQualifier = permissionBean . getOrganizationId ( ) ; String qualifiedPermission = createQualifiedPermissionKey ( permissionName , orgQualifier ) ; organizations . add ( orgQualifier ) ; qualifiedPermissions . add ( qualifiedPermission ) ; Set < String > orgs = permissionToOrgsMap . get ( permissionName ) ; if ( orgs == null ) { orgs = new HashSet < > ( ) ; permissionToOrgsMap . put ( permissionName , orgs ) ; } orgs . add ( orgQualifier ) ; } }
Index the permissions .
25,938
public boolean isOverwrite ( ) { Boolean booleanObject = BooleanUtils . toBooleanObject ( System . getProperty ( OVERWRITE ) ) ; if ( booleanObject == null ) { booleanObject = Boolean . FALSE ; } return booleanObject ; }
apiman . migrate . overwrite =
25,939
public void start ( ) { logger . info ( "----------------------------" ) ; logger . info ( Messages . i18n . format ( "StorageImportDispatcher.StartingImport" ) ) ; policyDefIndex . clear ( ) ; currentOrg = null ; currentPlan = null ; currentApi = null ; currentClient = null ; currentClientVersion = null ; contracts . clear ( ) ; apisToPublish . clear ( ) ; clientsToRegister . clear ( ) ; gatewayLinkCache . clear ( ) ; try { this . storage . beginTx ( ) ; } catch ( StorageException e ) { throw new RuntimeException ( e ) ; } }
Starts the import .
25,940
private PolicyDefinitionBean updatePluginIdInPolicyDefinition ( PolicyDefinitionBean policyDef ) { if ( pluginBeanIdMap . containsKey ( policyDef . getPluginId ( ) ) ) { try { Map . Entry < String , String > pluginCoordinates = pluginBeanIdMap . get ( policyDef . getPluginId ( ) ) ; PluginBean plugin = storage . getPlugin ( pluginCoordinates . getKey ( ) , pluginCoordinates . getValue ( ) ) ; policyDef . setPluginId ( plugin . getId ( ) ) ; } catch ( StorageException e ) { error ( e ) ; } } return policyDef ; }
Update the pluginID in the policyDefinition to the new generated pluginID
25,941
private void publishApis ( ) throws StorageException { logger . info ( Messages . i18n . format ( "StorageExporter.PublishingApis" ) ) ; try { for ( EntityInfo info : apisToPublish ) { logger . info ( Messages . i18n . format ( "StorageExporter.PublishingApi" , info ) ) ; ApiVersionBean versionBean = storage . getApiVersion ( info . organizationId , info . id , info . version ) ; Api gatewayApi = new Api ( ) ; gatewayApi . setEndpoint ( versionBean . getEndpoint ( ) ) ; gatewayApi . setEndpointType ( versionBean . getEndpointType ( ) . toString ( ) ) ; gatewayApi . setEndpointProperties ( versionBean . getEndpointProperties ( ) ) ; gatewayApi . setOrganizationId ( versionBean . getApi ( ) . getOrganization ( ) . getId ( ) ) ; gatewayApi . setApiId ( versionBean . getApi ( ) . getId ( ) ) ; gatewayApi . setVersion ( versionBean . getVersion ( ) ) ; gatewayApi . setPublicAPI ( versionBean . isPublicAPI ( ) ) ; gatewayApi . setParsePayload ( versionBean . isParsePayload ( ) ) ; if ( versionBean . isPublicAPI ( ) ) { List < Policy > policiesToPublish = new ArrayList < > ( ) ; Iterator < PolicyBean > apiPolicies = storage . getAllPolicies ( info . organizationId , info . id , info . version , PolicyType . Api ) ; while ( apiPolicies . hasNext ( ) ) { PolicyBean apiPolicy = apiPolicies . next ( ) ; Policy policyToPublish = new Policy ( ) ; policyToPublish . setPolicyJsonConfig ( apiPolicy . getConfiguration ( ) ) ; policyToPublish . setPolicyImpl ( apiPolicy . getDefinition ( ) . getPolicyImpl ( ) ) ; policiesToPublish . add ( policyToPublish ) ; } gatewayApi . setApiPolicies ( policiesToPublish ) ; } Set < ApiGatewayBean > gateways = versionBean . getGateways ( ) ; if ( gateways == null ) { throw new RuntimeException ( "No gateways specified for api!" ) ; } for ( ApiGatewayBean apiGatewayBean : gateways ) { IGatewayLink gatewayLink = createGatewayLink ( apiGatewayBean . getGatewayId ( ) ) ; gatewayLink . publishApi ( gatewayApi ) ; } } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Publishes any apis that were imported in the Published state .
25,942
private List < Policy > aggregateContractPolicies ( ContractBean contractBean , EntityInfo clientInfo ) throws StorageException { List < Policy > policies = new ArrayList < > ( ) ; PolicyType [ ] types = new PolicyType [ ] { PolicyType . Client , PolicyType . Plan , PolicyType . Api } ; for ( PolicyType policyType : types ) { String org , id , ver ; switch ( policyType ) { case Client : { org = clientInfo . organizationId ; id = clientInfo . id ; ver = clientInfo . version ; break ; } case Plan : { org = contractBean . getApi ( ) . getApi ( ) . getOrganization ( ) . getId ( ) ; id = contractBean . getPlan ( ) . getPlan ( ) . getId ( ) ; ver = contractBean . getPlan ( ) . getVersion ( ) ; break ; } case Api : { org = contractBean . getApi ( ) . getApi ( ) . getOrganization ( ) . getId ( ) ; id = contractBean . getApi ( ) . getApi ( ) . getId ( ) ; ver = contractBean . getApi ( ) . getVersion ( ) ; break ; } default : { throw new RuntimeException ( "Missing case for switch!" ) ; } } Iterator < PolicyBean > clientPolicies = storage . getAllPolicies ( org , id , ver , policyType ) ; while ( clientPolicies . hasNext ( ) ) { PolicyBean policyBean = clientPolicies . next ( ) ; Policy policy = new Policy ( ) ; policy . setPolicyJsonConfig ( policyBean . getConfiguration ( ) ) ; policy . setPolicyImpl ( policyBean . getDefinition ( ) . getPolicyImpl ( ) ) ; policies . add ( policy ) ; } } return policies ; }
Aggregates the api client and plan policies into a single ordered list .
25,943
protected void doLoadFromClasspath ( String policyImpl , IAsyncResultHandler < IPolicy > handler ) { IPolicy rval ; String classname = policyImpl . substring ( 6 ) ; Class < ? > c = null ; try { c = Class . forName ( classname ) ; } catch ( ClassNotFoundException e ) { } if ( c == null ) { try { c = getClass ( ) . getClassLoader ( ) . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { } } if ( c == null ) { try { c = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { } } if ( c == null ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( classname ) ) ) ; return ; } try { rval = ( IPolicy ) c . newInstance ( ) ; } catch ( InstantiationException | IllegalAccessException e ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( policyImpl , e ) ) ) ; return ; } policyCache . put ( policyImpl , rval ) ; handler . handle ( AsyncResultImpl . create ( rval ) ) ; return ; }
Loads a policy from a class on the classpath .
25,944
private void doLoadFromPlugin ( final String policyImpl , final IAsyncResultHandler < IPolicy > handler ) { PluginCoordinates coordinates = PluginCoordinates . fromPolicySpec ( policyImpl ) ; if ( coordinates == null ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( policyImpl ) ) ) ; return ; } int ssidx = policyImpl . indexOf ( '/' ) ; if ( ssidx == - 1 ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( policyImpl ) ) ) ; return ; } final String classname = policyImpl . substring ( ssidx + 1 ) ; this . pluginRegistry . loadPlugin ( coordinates , new IAsyncResultHandler < Plugin > ( ) { public void handle ( IAsyncResult < Plugin > result ) { if ( result . isSuccess ( ) ) { IPolicy rval ; Plugin plugin = result . getResult ( ) ; PluginClassLoader pluginClassLoader = plugin . getLoader ( ) ; ClassLoader oldCtxLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; try { Thread . currentThread ( ) . setContextClassLoader ( pluginClassLoader ) ; Class < ? > c = pluginClassLoader . loadClass ( classname ) ; rval = ( IPolicy ) c . newInstance ( ) ; } catch ( Exception e ) { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( policyImpl , e ) ) ) ; return ; } finally { Thread . currentThread ( ) . setContextClassLoader ( oldCtxLoader ) ; } policyCache . put ( policyImpl , rval ) ; handler . handle ( AsyncResultImpl . create ( rval ) ) ; } else { handler . handle ( AsyncResultImpl . < IPolicy > create ( new PolicyNotFoundException ( policyImpl , result . getError ( ) ) ) ) ; } } } ) ; }
Loads a policy from a plugin .
25,945
private < T > T unmarshalAs ( String valueAsString , Class < T > asClass ) throws IOException { return mapper . reader ( asClass ) . readValue ( valueAsString ) ; }
Unmarshall the given type of object .
25,946
protected void doApply ( ApiResponse response , IPolicyContext context , C config , IPolicyChain < ApiResponse > chain ) { chain . doApply ( response ) ; }
Apply the policy to the response .
25,947
protected void doProcessFailure ( PolicyFailure failure , IPolicyContext context , C config , IPolicyFailureChain chain ) { chain . doFailure ( failure ) ; }
Override if you wish to modify a failure .
25,948
protected SecurityHandler createSecurityHandler ( ) throws Exception { HashLoginService l = new HashLoginService ( ) ; UserStore userStore = new UserStore ( ) ; l . setUserStore ( userStore ) ; for ( User user : Users . getUsers ( ) ) { userStore . addUser ( user . getId ( ) , Credential . getCredential ( user . getPassword ( ) ) , user . getRolesAsArray ( ) ) ; } l . setName ( "apimanrealm" ) ; ConstraintSecurityHandler csh = new ConstraintSecurityHandler ( ) ; csh . setAuthenticator ( new BasicAuthenticator ( ) ) ; csh . setRealmName ( "apimanrealm" ) ; csh . setLoginService ( l ) ; return csh ; }
Creates a basic auth security handler .
25,949
private static BucketSizeType bucketSizeFromInterval ( HistogramIntervalType interval ) { BucketSizeType bucketSize ; switch ( interval ) { case minute : bucketSize = BucketSizeType . Minute ; break ; case hour : bucketSize = BucketSizeType . Hour ; break ; case day : bucketSize = BucketSizeType . Day ; break ; case week : bucketSize = BucketSizeType . Week ; break ; case month : bucketSize = BucketSizeType . Month ; break ; default : bucketSize = BucketSizeType . Day ; break ; } return bucketSize ; }
Converts an interval into a bucket size .
25,950
@ SuppressWarnings ( "nls" ) private void doInit ( ) { QueryRunner run = new QueryRunner ( ds ) ; Boolean isInitialized ; try { isInitialized = run . query ( "SELECT * FROM gw_apis" , new ResultSetHandler < Boolean > ( ) { public Boolean handle ( ResultSet rs ) throws SQLException { return true ; } } ) ; } catch ( SQLException e ) { isInitialized = false ; } if ( isInitialized ) { System . out . println ( "============================================" ) ; System . out . println ( "Apiman Gateway database already initialized." ) ; System . out . println ( "============================================" ) ; return ; } ClassLoader cl = JdbcInitializer . class . getClassLoader ( ) ; URL resource = cl . getResource ( "ddls/apiman-gateway_" + dbType + ".ddl" ) ; try ( InputStream is = resource . openStream ( ) ) { System . out . println ( "=======================================" ) ; System . out . println ( "Initializing apiman Gateway database." ) ; DdlParser ddlParser = new DdlParser ( ) ; List < String > statements = ddlParser . parse ( is ) ; for ( String sql : statements ) { System . out . println ( sql ) ; run . update ( sql ) ; } System . out . println ( "=======================================" ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Do the initialization work .
25,951
private boolean satisfiesAnyPath ( IgnoredResourcesConfig config , String destination , String verb ) { if ( destination == null || destination . trim ( ) . length ( ) == 0 ) { destination = "/" ; } for ( IgnoredResource resource : config . getRules ( ) ) { String resourceVerb = resource . getVerb ( ) ; boolean verbMatches = verb == null || IgnoredResource . VERB_MATCH_ALL . equals ( resourceVerb ) || verb . equalsIgnoreCase ( resourceVerb ) ; boolean destinationMatches = destination . matches ( resource . getPathPattern ( ) ) ; if ( verbMatches && destinationMatches ) { return true ; } } return false ; }
Evaluates whether the destination provided matches any of the configured rules
25,952
private PublishingException readPublishingException ( HttpResponse response ) { InputStream is = null ; PublishingException exception ; try { is = response . getEntity ( ) . getContent ( ) ; GatewayApiErrorBean error = mapper . reader ( GatewayApiErrorBean . class ) . readValue ( is ) ; exception = new PublishingException ( error . getMessage ( ) ) ; StackTraceElement [ ] stack = parseStackTrace ( error . getStacktrace ( ) ) ; if ( stack != null ) { exception . setStackTrace ( stack ) ; } } catch ( Exception e ) { exception = new PublishingException ( e . getMessage ( ) , e ) ; } finally { IOUtils . closeQuietly ( is ) ; } return exception ; }
Reads a publishing exception from the response .
25,953
protected static StackTraceElement [ ] parseStackTrace ( String stacktrace ) { try ( BufferedReader reader = new BufferedReader ( new StringReader ( stacktrace ) ) ) { List < StackTraceElement > elements = new ArrayList < > ( ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { if ( line . startsWith ( "\tat " ) ) { int openParenIdx = line . indexOf ( '(' ) ; int closeParenIdx = line . indexOf ( ')' ) ; String classAndMethod = line . substring ( 4 , openParenIdx ) ; String fileAndLineNum = line . substring ( openParenIdx + 1 , closeParenIdx ) ; String className = classAndMethod . substring ( 0 , classAndMethod . lastIndexOf ( '.' ) ) ; String methodName = classAndMethod . substring ( classAndMethod . lastIndexOf ( '.' ) + 1 ) ; String [ ] split = fileAndLineNum . split ( ":" ) ; if ( split . length == 1 ) { elements . add ( new StackTraceElement ( className , methodName , fileAndLineNum , - 1 ) ) ; } else { String fileName = split [ 0 ] ; String lineNum = split [ 1 ] ; elements . add ( new StackTraceElement ( className , methodName , fileName , new Integer ( lineNum ) ) ) ; } } } return elements . toArray ( new StackTraceElement [ elements . size ( ) ] ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } }
Parses a stack trace from the given string .
25,954
protected < T extends IComponent > void addComponent ( Class < T > componentType , T component ) { components . put ( componentType , component ) ; }
Adds a component to the registry .
25,955
public static final void main ( String [ ] args ) throws Exception { GatewayMicroService microService = new GatewayMicroService ( ) ; microService . start ( ) ; microService . join ( ) ; }
Main entry point for the API Gateway micro service .
25,956
public IApiConnector createConnector ( ApiRequest req , Api api , RequiredAuthType authType , boolean hasDataPolicy , IConnectorConfig connectorConfig ) { return ( request , resultHandler ) -> { ApimanHttpConnectorOptions httpOptions = new ApimanHttpConnectorOptions ( config ) . setHasDataPolicy ( hasDataPolicy ) . setRequiredAuthType ( authType ) . setTlsOptions ( tlsOptions ) . setUri ( parseApiEndpoint ( api ) ) . setSsl ( api . getEndpoint ( ) . toLowerCase ( ) . startsWith ( "https" ) ) ; setAttributesFromApiEndpointProperties ( api , httpOptions ) ; HttpClient client = clientFromCache ( httpOptions ) ; return new HttpConnector ( vertx , client , request , api , httpOptions , connectorConfig , resultHandler ) . connect ( ) ; } ; }
In the future we can switch to different back - end implementations here!
25,957
private void setAttributesFromApiEndpointProperties ( Api api , ApimanHttpConnectorOptions options ) { try { Map < String , String > endpointProperties = api . getEndpointProperties ( ) ; if ( endpointProperties . containsKey ( "timeouts.read" ) ) { int connectTimeoutMs = Integer . parseInt ( endpointProperties . get ( "timeouts.read" ) ) ; options . setRequestTimeout ( connectTimeoutMs ) ; } if ( endpointProperties . containsKey ( "timeouts.connect" ) ) { int connectTimeoutMs = Integer . parseInt ( endpointProperties . get ( "timeouts.connect" ) ) ; options . setConnectionTimeout ( connectTimeoutMs ) ; } } catch ( NumberFormatException e ) { throw new RuntimeException ( e ) ; } }
If the endpoint properties includes a read timeout override then set it here .
25,958
public < T extends IComponent > T createAndRegisterComponent ( Class < T > componentType ) throws ComponentNotFoundException { try { synchronized ( components ) { Class < ? extends T > componentClass = engineConfig . getComponentClass ( componentType , pluginRegistry ) ; Map < String , String > componentConfig = engineConfig . getComponentConfig ( componentType ) ; T component = create ( componentClass , componentConfig ) ; components . put ( componentType , component ) ; DependsOnComponents annotation = componentClass . getAnnotation ( DependsOnComponents . class ) ; if ( annotation != null ) { Class < ? extends IComponent > [ ] value = annotation . value ( ) ; for ( Class < ? extends IComponent > theC : value ) { Method setter = ReflectionUtils . findSetter ( componentClass , theC ) ; if ( setter != null ) { IComponent injectedComponent = getComponent ( theC ) ; try { setter . invoke ( component , new Object [ ] { injectedComponent } ) ; } catch ( IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { throw new RuntimeException ( e ) ; } } } } if ( component instanceof IRequiresInitialization ) { ( ( IRequiresInitialization ) component ) . initialize ( ) ; } return component ; } } catch ( Exception e ) { throw new ComponentNotFoundException ( componentType . getName ( ) ) ; } }
Creates the component and registers it in the registry .
25,959
protected void addComponentMapping ( Class < ? extends IComponent > klazz , IComponent component ) { components . put ( klazz , component ) ; }
Add a component that may have been instantiated elsewhere .
25,960
protected void registerRateLimiterComponent ( ) { String componentPropName = GatewayConfigProperties . COMPONENT_PREFIX + IRateLimiterComponent . class . getSimpleName ( ) ; setConfigProperty ( componentPropName , ESRateLimiterComponent . class . getName ( ) ) ; setConfigProperty ( componentPropName + ".client.type" , "jest" ) ; setConfigProperty ( componentPropName + ".client.protocol" , "${apiman.es.protocol}" ) ; setConfigProperty ( componentPropName + ".client.host" , "${apiman.es.host}" ) ; setConfigProperty ( componentPropName + ".client.port" , "${apiman.es.port}" ) ; setConfigProperty ( componentPropName + ".client.username" , "${apiman.es.username}" ) ; setConfigProperty ( componentPropName + ".client.password" , "${apiman.es.password}" ) ; }
The rate limiter component .
25,961
protected void registerSharedStateComponent ( ) { String componentPropName = GatewayConfigProperties . COMPONENT_PREFIX + ISharedStateComponent . class . getSimpleName ( ) ; setConfigProperty ( componentPropName , ESSharedStateComponent . class . getName ( ) ) ; setConfigProperty ( componentPropName + ".client.type" , "jest" ) ; setConfigProperty ( componentPropName + ".client.protocol" , "${apiman.es.protocol}" ) ; setConfigProperty ( componentPropName + ".client.host" , "${apiman.es.host}" ) ; setConfigProperty ( componentPropName + ".client.port" , "${apiman.es.port}" ) ; setConfigProperty ( componentPropName + ".client.username" , "${apiman.es.username}" ) ; setConfigProperty ( componentPropName + ".client.password" , "${apiman.es.password}" ) ; }
The shared state component .
25,962
protected void registerCacheStoreComponent ( ) { String componentPropName = GatewayConfigProperties . COMPONENT_PREFIX + ICacheStoreComponent . class . getSimpleName ( ) ; setConfigProperty ( componentPropName , ESCacheStoreComponent . class . getName ( ) ) ; setConfigProperty ( componentPropName + ".client.type" , "jest" ) ; setConfigProperty ( componentPropName + ".client.protocol" , "${apiman.es.protocol}" ) ; setConfigProperty ( componentPropName + ".client.host" , "${apiman.es.host}" ) ; setConfigProperty ( componentPropName + ".client.port" , "${apiman.es.port}" ) ; setConfigProperty ( componentPropName + ".client.index" , "apiman_cache" ) ; setConfigProperty ( componentPropName + ".client.username" , "${apiman.es.username}" ) ; setConfigProperty ( componentPropName + ".client.password" , "${apiman.es.password}" ) ; }
The cache store component .
25,963
protected void registerJdbcComponent ( ) { String componentPropName = GatewayConfigProperties . COMPONENT_PREFIX + IJdbcComponent . class . getSimpleName ( ) ; setConfigProperty ( componentPropName , DefaultJdbcComponent . class . getName ( ) ) ; }
The jdbc component .
25,964
protected void registerLdapComponent ( ) { String componentPropName = GatewayConfigProperties . COMPONENT_PREFIX + ILdapComponent . class . getSimpleName ( ) ; setConfigProperty ( componentPropName , DefaultLdapComponent . class . getName ( ) ) ; }
The ldap component .
25,965
protected void configureConnectorFactory ( ) { setConfigProperty ( GatewayConfigProperties . CONNECTOR_FACTORY_CLASS , HttpConnectorFactory . class . getName ( ) ) ; setConfigProperty ( GatewayConfigProperties . CONNECTOR_FACTORY_CLASS + ".http.timeouts.read" , "25" ) ; setConfigProperty ( GatewayConfigProperties . CONNECTOR_FACTORY_CLASS + ".http.timeouts.write" , "25" ) ; setConfigProperty ( GatewayConfigProperties . CONNECTOR_FACTORY_CLASS + ".http.timeouts.connect" , "10" ) ; setConfigProperty ( GatewayConfigProperties . CONNECTOR_FACTORY_CLASS + ".http.followRedirects" , "true" ) ; }
The connector factory .
25,966
protected void configureRegistry ( ) { setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS , PollCachingESRegistry . class . getName ( ) ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.type" , "jest" ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.protocol" , "${apiman.es.protocol}" ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.host" , "${apiman.es.host}" ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.port" , "${apiman.es.port}" ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.username" , "${apiman.es.username}" ) ; setConfigProperty ( GatewayConfigProperties . REGISTRY_CLASS + ".client.password" , "${apiman.es.password}" ) ; }
The registry .
25,967
protected void configureMetrics ( ) { setConfigProperty ( GatewayConfigProperties . METRICS_CLASS , ESMetrics . class . getName ( ) ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.type" , "jest" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.protocol" , "${apiman.es.protocol}" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.host" , "${apiman.es.host}" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.port" , "${apiman.es.port}" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.username" , "${apiman.es.username}" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.password" , "${apiman.es.password}" ) ; setConfigProperty ( GatewayConfigProperties . METRICS_CLASS + ".client.index" , "apiman_metrics" ) ; }
Configure the metrics system .
25,968
protected void setConfigProperty ( String propName , String propValue ) { if ( System . getProperty ( propName ) == null ) { System . setProperty ( propName , propValue ) ; } }
Sets a system property if it s not already set .
25,969
public boolean resetIfNecessary ( RateBucketPeriod period ) { long periodBoundary = getLastPeriodBoundary ( period ) ; if ( System . currentTimeMillis ( ) >= periodBoundary ) { setCount ( 0 ) ; return true ; } return false ; }
Resets the count if the period boundary has been crossed . Returns true if the count was reset to 0 or false otherwise .
25,970
public long getResetMillis ( RateBucketPeriod period ) { long now = System . currentTimeMillis ( ) ; long periodBoundary = getPeriodBoundary ( now , period ) ; return periodBoundary - now ; }
Returns the number of millis until the period resets .
25,971
private static long getPeriodBoundary ( long timestamp , RateBucketPeriod period ) { Calendar lastCal = Calendar . getInstance ( ) ; lastCal . setTimeInMillis ( timestamp ) ; switch ( period ) { case Second : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . add ( Calendar . SECOND , 1 ) ; return lastCal . getTimeInMillis ( ) ; case Minute : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . set ( Calendar . SECOND , 0 ) ; lastCal . add ( Calendar . MINUTE , 1 ) ; return lastCal . getTimeInMillis ( ) ; case Hour : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . set ( Calendar . SECOND , 0 ) ; lastCal . set ( Calendar . MINUTE , 0 ) ; lastCal . add ( Calendar . HOUR_OF_DAY , 1 ) ; return lastCal . getTimeInMillis ( ) ; case Day : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . set ( Calendar . SECOND , 0 ) ; lastCal . set ( Calendar . MINUTE , 0 ) ; lastCal . set ( Calendar . HOUR_OF_DAY , 0 ) ; lastCal . add ( Calendar . DAY_OF_YEAR , 1 ) ; return lastCal . getTimeInMillis ( ) ; case Month : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . set ( Calendar . SECOND , 0 ) ; lastCal . set ( Calendar . MINUTE , 0 ) ; lastCal . set ( Calendar . HOUR_OF_DAY , 0 ) ; lastCal . set ( Calendar . DAY_OF_MONTH , 1 ) ; lastCal . add ( Calendar . MONTH , 1 ) ; return lastCal . getTimeInMillis ( ) ; case Year : lastCal . set ( Calendar . MILLISECOND , 0 ) ; lastCal . set ( Calendar . SECOND , 0 ) ; lastCal . set ( Calendar . MINUTE , 0 ) ; lastCal . set ( Calendar . HOUR_OF_DAY , 0 ) ; lastCal . set ( Calendar . DAY_OF_YEAR , 1 ) ; lastCal . add ( Calendar . YEAR , 1 ) ; return lastCal . getTimeInMillis ( ) ; } return Long . MAX_VALUE ; }
Gets the boundary timestamp for the given rate bucket period . In other words returns the timestamp associated with when the rate period will reset .
25,972
private PluginRegistryBean loadRegistry ( URI registryUrl ) { PluginRegistryBean fromCache = registryCache . get ( registryUrl ) ; if ( fromCache != null ) { return fromCache ; } try { PluginRegistryBean registry = mapper . reader ( PluginRegistryBean . class ) . readValue ( registryUrl . toURL ( ) ) ; registryCache . put ( registryUrl , registry ) ; return registry ; } catch ( IOException e ) { return null ; } }
Loads a plugin registry from its URL . Will use the value in the cache if it exists . If not it will connect to the remote URL and grab the registry JSON file .
25,973
public static final PoliciesBean from ( PolicyBean policy ) { PoliciesBean rval = new PoliciesBean ( ) ; rval . setType ( policy . getType ( ) ) ; rval . setOrganizationId ( policy . getOrganizationId ( ) ) ; rval . setEntityId ( policy . getEntityId ( ) ) ; rval . setEntityVersion ( policy . getEntityVersion ( ) ) ; rval . getPolicies ( ) . add ( policy ) ; return rval ; }
Create a new Policies object from the given policy bean instance .
25,974
public static VersionMigratorChain chain ( String fromVersion , String toVersion ) { List < IVersionMigrator > matchedMigrators = new ArrayList < > ( ) ; for ( Entry entry : migrators ) { if ( entry . isBetween ( fromVersion , toVersion ) ) { matchedMigrators . add ( entry . migrator ) ; } } return new VersionMigratorChain ( matchedMigrators ) ; }
Gets the chain of migrators to use when migrating from version X to version Y .
25,975
public void createTenant ( String tenantId ) { TenantBean tenant = new TenantBean ( tenantId ) ; try { URL endpoint = serverUrl . toURI ( ) . resolve ( "tenants" ) . toURL ( ) ; Request request = new Request . Builder ( ) . url ( endpoint ) . post ( toBody ( tenant ) ) . header ( "Hawkular-Tenant" , tenantId ) . build ( ) ; Response response = httpClient . newCall ( request ) . execute ( ) ; if ( response . code ( ) >= 400 ) { throw hawkularMetricsError ( response ) ; } } catch ( URISyntaxException | IOException e ) { throw new RuntimeException ( e ) ; } }
Creates a new tenant .
25,976
public List < MetricBean > listCounterMetrics ( String tenantId ) { try { URL endpoint = serverUrl . toURI ( ) . resolve ( "counters" ) . toURL ( ) ; Request request = new Request . Builder ( ) . url ( endpoint ) . header ( "Accept" , "application/json" ) . header ( "Hawkular-Tenant" , tenantId ) . build ( ) ; Response response = httpClient . newCall ( request ) . execute ( ) ; if ( response . code ( ) >= 400 ) { throw hawkularMetricsError ( response ) ; } if ( response . code ( ) == 204 ) { return Collections . EMPTY_LIST ; } String responseBody = response . body ( ) . string ( ) ; return readMapper . reader ( new TypeReference < List < MetricBean > > ( ) { } ) . readValue ( responseBody ) ; } catch ( URISyntaxException | IOException e ) { throw new RuntimeException ( e ) ; } }
Get a list of all counter metrics for a given tenant .
25,977
public DataPointLongBean addCounterDataPoint ( String tenantId , String counterId , Date timestamp , long value ) { List < DataPointLongBean > dataPoints = new ArrayList < > ( ) ; DataPointLongBean dataPoint = new DataPointLongBean ( timestamp , value ) ; dataPoints . add ( dataPoint ) ; addCounterDataPoints ( tenantId , counterId , dataPoints ) ; return dataPoint ; }
Adds a single data point to the given counter .
25,978
public void addMultipleCounterDataPoints ( String tenantId , List < MetricLongBean > data ) { try { URL endpoint = serverUrl . toURI ( ) . resolve ( "counters/raw" ) . toURL ( ) ; Request request = new Request . Builder ( ) . url ( endpoint ) . post ( toBody ( data ) ) . header ( "Hawkular-Tenant" , tenantId ) . build ( ) ; Response response = httpClient . newCall ( request ) . execute ( ) ; if ( response . code ( ) >= 400 ) { throw hawkularMetricsError ( response ) ; } } catch ( URISyntaxException | IOException e ) { throw new RuntimeException ( e ) ; } }
Adds one or more data points for multiple counters all at once!
25,979
public static Map < String , String > tags ( String ... strings ) { Map < String , String > tags = new HashMap < > ( ) ; for ( int i = 0 ; i < strings . length - 1 ; i += 2 ) { String key = strings [ i ] ; String value = strings [ i + 1 ] ; if ( key != null && value != null ) { tags . put ( key , value ) ; } } return tags ; }
Simple method to create some tags .
25,980
protected static String encodeTags ( Map < String , String > tags ) { if ( tags == null ) { return null ; } try { StringBuilder builder = new StringBuilder ( ) ; boolean first = true ; for ( Entry < String , String > entry : tags . entrySet ( ) ) { if ( ! first ) { builder . append ( ',' ) ; } builder . append ( URLEncoder . encode ( entry . getKey ( ) , "UTF-8" ) ) ; builder . append ( ':' ) ; builder . append ( URLEncoder . encode ( entry . getValue ( ) , "UTF-8" ) ) ; first = false ; } return builder . toString ( ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; return "" ; } }
Encodes the tags into the format expected by HM .
25,981
protected void startCacheInvalidator ( ) { polling = true ; Thread thread = new Thread ( new Runnable ( ) { public void run ( ) { try { Thread . sleep ( startupDelayMillis ) ; } catch ( InterruptedException e1 ) { e1 . printStackTrace ( ) ; } while ( polling ) { try { Thread . sleep ( pollIntervalMillis ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } checkCacheVersion ( ) ; } } } , "ESRegistryCacheInvalidator" ) ; thread . setDaemon ( true ) ; thread . start ( ) ; }
Starts up a thread that polls the ES store for updates .
25,982
public void chainPolicyHandlers ( ) { IReadWriteStream < H > previousHandler = null ; Iterator < PolicyWithConfiguration > iterator = iterator ( ) ; while ( iterator . hasNext ( ) ) { final PolicyWithConfiguration pwc = iterator . next ( ) ; final IPolicy policy = pwc . getPolicy ( ) ; final IReadWriteStream < H > handler = getApiHandler ( policy , pwc . getConfiguration ( ) ) ; if ( handler == null ) { continue ; } if ( headPolicyHandler == null ) { headPolicyHandler = handler ; } if ( previousHandler != null ) { previousHandler . bodyHandler ( new IAsyncHandler < IApimanBuffer > ( ) { public void handle ( IApimanBuffer result ) { handler . write ( result ) ; } } ) ; previousHandler . endHandler ( new IAsyncHandler < Void > ( ) { public void handle ( Void result ) { handler . end ( ) ; } } ) ; } previousHandler = handler ; } IReadWriteStream < H > tailPolicyHandler = previousHandler ; if ( headPolicyHandler != null && tailPolicyHandler != null ) { tailPolicyHandler . bodyHandler ( new IAsyncHandler < IApimanBuffer > ( ) { public void handle ( IApimanBuffer chunk ) { handleBody ( chunk ) ; } } ) ; tailPolicyHandler . endHandler ( new IAsyncHandler < Void > ( ) { public void handle ( Void result ) { handleEnd ( ) ; } } ) ; } }
Chain together the body handlers .
25,983
public static KeyManager [ ] getKeyManagers ( Info pathInfo ) throws Exception { if ( pathInfo . store == null ) { return null ; } File clientKeyStoreFile = new File ( pathInfo . store ) ; if ( ! clientKeyStoreFile . isFile ( ) ) { throw new Exception ( "No KeyManager: " + pathInfo . store + " does not exist or is not a file." ) ; } String clientKeyStorePassword = pathInfo . password ; KeyManagerFactory kmf = KeyManagerFactory . getInstance ( KeyManagerFactory . getDefaultAlgorithm ( ) ) ; KeyStore keyStore = KeyStore . getInstance ( "JKS" ) ; FileInputStream clientFis = new FileInputStream ( pathInfo . store ) ; keyStore . load ( clientFis , clientKeyStorePassword . toCharArray ( ) ) ; clientFis . close ( ) ; kmf . init ( keyStore , clientKeyStorePassword . toCharArray ( ) ) ; return kmf . getKeyManagers ( ) ; }
Gets the array of key managers for a given info store + info .
25,984
public static TrustManager [ ] getTrustManagers ( Info pathInfo ) throws Exception { File trustStoreFile = new File ( pathInfo . store ) ; if ( ! trustStoreFile . isFile ( ) ) { throw new Exception ( "No TrustManager: " + pathInfo . store + " does not exist." ) ; } String trustStorePassword = pathInfo . password ; TrustManagerFactory tmf = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; KeyStore truststore = KeyStore . getInstance ( "JKS" ) ; FileInputStream fis = new FileInputStream ( pathInfo . store ) ; truststore . load ( fis , trustStorePassword . toCharArray ( ) ) ; fis . close ( ) ; tmf . init ( truststore ) ; return tmf . getTrustManagers ( ) ; }
Gets an array of trust managers for a given store + password .
25,985
private void popLastItem ( ) { KeyValue < K , V > lastKV = items . last ( ) ; items . remove ( lastKV ) ; index . remove ( lastKV . key ) ; }
Removes the last item in the list .
25,986
private void validateCredentials ( String username , String password , ApiRequest request , IPolicyContext context , BasicAuthenticationConfig config , IAsyncResultHandler < Boolean > handler ) { if ( config . getStaticIdentity ( ) != null ) { staticIdentityValidator . validate ( username , password , request , context , config . getStaticIdentity ( ) , handler ) ; } else if ( config . getLdapIdentity ( ) != null ) { ldapIdentityValidator . validate ( username , password , request , context , config . getLdapIdentity ( ) , handler ) ; } else if ( config . getJdbcIdentity ( ) != null ) { jdbcIdentityValidator . validate ( username , password , request , context , config . getJdbcIdentity ( ) , handler ) ; } else { handler . handle ( AsyncResultImpl . create ( Boolean . FALSE ) ) ; } }
Validate the inbound authentication credentials .
25,987
protected void sendAuthFailure ( IPolicyContext context , IPolicyChain < ? > chain , BasicAuthenticationConfig config , int reason ) { IPolicyFailureFactoryComponent pff = context . getComponent ( IPolicyFailureFactoryComponent . class ) ; PolicyFailure failure = pff . createFailure ( PolicyFailureType . Authentication , reason , Messages . i18n . format ( "BasicAuthenticationPolicy.AuthenticationFailed" ) ) ; String realm = config . getRealm ( ) ; if ( realm == null || realm . trim ( ) . isEmpty ( ) ) { realm = "Apiman" ; } failure . getHeaders ( ) . put ( "WWW-Authenticate" , String . format ( "Basic realm=\"%1$s\"" , realm ) ) ; chain . doFailure ( failure ) ; }
Sends the unauthenticated response as a policy failure .
25,988
private String getApiIdx ( String orgId , String apiId , String version ) { return "API::" + orgId + "|" + apiId + "|" + version ; }
Generates an in - memory key for an API used to index the app for later quick retrieval .
25,989
protected void unregisterApiContracts ( Client client , Connection connection ) throws SQLException { QueryRunner run = new QueryRunner ( ) ; run . update ( connection , "DELETE FROM contracts WHERE client_org_id = ? AND client_id = ? AND client_version = ?" , client . getOrganizationId ( ) , client . getClientId ( ) , client . getVersion ( ) ) ; }
Removes all of the api contracts from the database .
25,990
protected Api getApiInternal ( String organizationId , String apiId , String apiVersion ) throws SQLException { QueryRunner run = new QueryRunner ( ds ) ; return run . query ( "SELECT bean FROM gw_apis WHERE org_id = ? AND id = ? AND version = ?" , Handlers . API_HANDLER , organizationId , apiId , apiVersion ) ; }
Gets an api from the DB .
25,991
protected Client getClientInternal ( String apiKey ) throws SQLException { QueryRunner run = new QueryRunner ( ds ) ; return run . query ( "SELECT bean FROM gw_clients WHERE api_key = ?" , Handlers . CLIENT_HANDLER , apiKey ) ; }
Simply pull the client from storage .
25,992
protected void doBasicAuth ( Creds credentials , HttpServletRequest request , HttpServletResponse response , FilterChain chain ) throws IOException , ServletException { try { if ( credentials . username . equals ( request . getRemoteUser ( ) ) ) { } else if ( request . getRemoteUser ( ) != null ) { request . logout ( ) ; request . login ( credentials . username , credentials . password ) ; } else { request . login ( credentials . username , credentials . password ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; sendAuthResponse ( response ) ; return ; } doFilterChain ( request , response , chain , null ) ; }
Handle BASIC authentication . Delegates this to the container by invoking login on the inbound http servlet request object .
25,993
protected void doFilterChain ( ServletRequest request , ServletResponse response , FilterChain chain , AuthPrincipal principal ) throws IOException , ServletException { if ( principal == null ) { chain . doFilter ( request , response ) ; } else { HttpServletRequest hsr ; hsr = wrapTheRequest ( request , principal ) ; chain . doFilter ( hsr , response ) ; } }
Further process the filter chain .
25,994
private HttpServletRequest wrapTheRequest ( final ServletRequest request , final AuthPrincipal principal ) { HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper ( ( HttpServletRequest ) request ) { public Principal getUserPrincipal ( ) { return principal ; } public boolean isUserInRole ( String role ) { return principal . getRoles ( ) . contains ( role ) ; } public String getRemoteUser ( ) { return principal . getName ( ) ; } } ; return wrapper ; }
Wrap the request to provide the principal .
25,995
private Creds parseAuthorizationBasic ( String authHeader ) { String userpassEncoded = authHeader . substring ( 6 ) ; String data = StringUtils . newStringUtf8 ( Base64 . decodeBase64 ( userpassEncoded ) ) ; int sepIdx = data . indexOf ( ':' ) ; if ( sepIdx > 0 ) { String username = data . substring ( 0 , sepIdx ) ; String password = data . substring ( sepIdx + 1 ) ; return new Creds ( username , password ) ; } else { return new Creds ( data , null ) ; } }
Parses the Authorization request header into a username and password .
25,996
private AuthToken parseAuthorizationToken ( String authHeader ) { try { String tokenEncoded = authHeader . substring ( 11 ) ; return AuthTokenUtil . consumeToken ( tokenEncoded ) ; } catch ( IllegalArgumentException e ) { return null ; } }
Parses the Authorization request to retrieve the Base64 encoded auth token .
25,997
private void sendAuthResponse ( HttpServletResponse response ) throws IOException { response . setHeader ( "WWW-Authenticate" , String . format ( "Basic realm=\"%1$s\"" , realm ) ) ; response . sendError ( HttpServletResponse . SC_UNAUTHORIZED ) ; }
Sends a response that tells the client that authentication is required .
25,998
private void replaceHeaders ( URLRewritingConfig config , HeaderMap headers ) { for ( Entry < String , String > entry : headers ) { String key = entry . getKey ( ) ; String value = entry . getValue ( ) ; value = doHeaderReplaceAll ( value , config . getFromRegex ( ) , config . getToReplacement ( ) ) ; if ( value != null ) { headers . put ( key , value ) ; } } }
Perform replacement .
25,999
private String doHeaderReplaceAll ( String headerValue , String fromRegex , String toReplacement ) { return headerValue . replaceAll ( fromRegex , toReplacement ) ; }
Finds all matching instances of the regular expression and replaces them with the replacement value .