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 . get...
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 ) ; tok...
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 ( ) ....
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 ...
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 ( ) . getS...
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 RateBucketPer...
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" ) ) ; connecti...
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 = ent...
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...
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...
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 < ? > c...
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 =...
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 Ex...
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 . getApiOrganiz...
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 , IGat...
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 PlanVersi...
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 == nu...
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 DataEncryptionC...
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 ) ...
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...
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 ...
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 ) ; countQue...
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 , org...
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 . ...
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 . getPlu...
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 . getApiVe...
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 : ty...
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 ( ) . getC...
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 ...
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 . getPas...
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 we...
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 ( SQLE...
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 verbMat...
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 PublishingExcept...
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 ...
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 ) . set...
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 (...
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 = engine...
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" , ...
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" , ...
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" , "je...
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 . CON...
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.protoco...
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.e...
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 . getTi...
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 . ...
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 ( ) ) ; r...
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 VersionMigratorC...
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 ...
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...
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...
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 ...
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 t...
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 ( URLEnc...
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 ( E...
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 > hand...
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 ...
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 ; Trus...
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...
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...
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 ( ) ,...
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 ( )...
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 ) ; c...
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 ) { r...
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 ) ; St...
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 != nul...
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 .