idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
25,800
public static AuditEntryBean policyAdded ( PolicyBean bean , PolicyType type , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( bean . getOrganizationId ( ) , null , securityContext ) ; entry . setWhat ( AuditEntryType . AddPolicy ) ; entry . setEntityId ( bean . getEntityId ( ) ) ; entry . setEntityVersion ( bean . getEntityVersion ( ) ) ; switch ( type ) { case Client : entry . setEntityType ( AuditEntityType . Client ) ; break ; case Plan : entry . setEntityType ( AuditEntityType . Plan ) ; break ; case Api : entry . setEntityType ( AuditEntityType . Api ) ; break ; } PolicyData data = new PolicyData ( ) ; data . setPolicyDefId ( bean . getDefinition ( ) . getId ( ) ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the policy added event . Works for all three kinds of policies .
201
19
25,801
private static String toJSON ( Object data ) { try { return mapper . writeValueAsString ( data ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Writes the data object as a JSON string .
41
10
25,802
public static AuditEntryBean planCreated ( PlanBean bean , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( bean . getOrganization ( ) . getId ( ) , AuditEntityType . Plan , securityContext ) ; entry . setEntityId ( bean . getId ( ) ) ; entry . setEntityVersion ( null ) ; entry . setData ( null ) ; entry . setWhat ( AuditEntryType . Create ) ; return entry ; }
Creates an audit entry for the plan created event .
101
11
25,803
public static AuditEntryBean planUpdated ( PlanBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getOrganization ( ) . getId ( ) , AuditEntityType . Plan , securityContext ) ; entry . setEntityId ( bean . getId ( ) ) ; entry . setEntityVersion ( null ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the plan updated event .
129
11
25,804
public static AuditEntryBean planVersionCreated ( PlanVersionBean bean , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( bean . getPlan ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Plan , securityContext ) ; entry . setEntityId ( bean . getPlan ( ) . getId ( ) ) ; entry . setEntityVersion ( bean . getVersion ( ) ) ; entry . setWhat ( AuditEntryType . Create ) ; return entry ; }
Creates an audit entry for the plan version created event .
110
12
25,805
public static AuditEntryBean planVersionUpdated ( PlanVersionBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getPlan ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Plan , securityContext ) ; entry . setEntityId ( bean . getPlan ( ) . getId ( ) ) ; entry . setEntityVersion ( bean . getVersion ( ) ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the plan version updated event .
146
12
25,806
public static AuditEntryBean apiPublished ( ApiVersionBean bean , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( bean . getApi ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Api , securityContext ) ; entry . setEntityId ( bean . getApi ( ) . getId ( ) ) ; entry . setEntityVersion ( bean . getVersion ( ) ) ; entry . setWhat ( AuditEntryType . Publish ) ; return entry ; }
Creates an audit entry for the API published event .
114
11
25,807
public static AuditEntryBean clientRegistered ( ClientVersionBean bean , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( bean . getClient ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Client , securityContext ) ; entry . setEntityId ( bean . getClient ( ) . getId ( ) ) ; entry . setEntityVersion ( bean . getVersion ( ) ) ; entry . setWhat ( AuditEntryType . Register ) ; return entry ; }
Creates an audit entry for the client registered event .
109
11
25,808
public static AuditEntryBean policiesReordered ( ApiVersionBean apiVersion , PolicyType policyType , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( apiVersion . getApi ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Api , securityContext ) ; entry . setEntityId ( apiVersion . getApi ( ) . getId ( ) ) ; entry . setEntityVersion ( apiVersion . getVersion ( ) ) ; entry . setWhat ( AuditEntryType . ReorderPolicies ) ; return entry ; }
Called when the user reorders the policies in a API .
127
13
25,809
public static AuditEntryBean policiesReordered ( ClientVersionBean cvb , PolicyType policyType , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( cvb . getClient ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Client , securityContext ) ; entry . setEntityId ( cvb . getClient ( ) . getId ( ) ) ; entry . setEntityVersion ( cvb . getVersion ( ) ) ; entry . setWhat ( AuditEntryType . ReorderPolicies ) ; return entry ; }
Called when the user reorders the policies in an client .
127
13
25,810
public static AuditEntryBean policiesReordered ( PlanVersionBean pvb , PolicyType policyType , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( pvb . getPlan ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Plan , securityContext ) ; entry . setEntityId ( pvb . getPlan ( ) . getId ( ) ) ; entry . setEntityVersion ( pvb . getVersion ( ) ) ; entry . setWhat ( AuditEntryType . ReorderPolicies ) ; return entry ; }
Called when the user reorders the policies in a plan .
127
13
25,811
private static AuditEntryBean newEntry ( String orgId , AuditEntityType type , ISecurityContext securityContext ) { // Wait for 1 ms to guarantee that two audit entries are never created at the same moment in time (which would // result in non-deterministic sorting by the storage layer) try { Thread . sleep ( 1 ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } AuditEntryBean entry = new AuditEntryBean ( ) ; entry . setOrganizationId ( orgId ) ; entry . setEntityType ( type ) ; entry . setCreatedOn ( new Date ( ) ) ; entry . setWho ( securityContext . getCurrentUser ( ) ) ; return entry ; }
Creates an audit entry .
155
6
25,812
public static final ClientVersionAlreadyExistsException clientVersionAlreadyExistsException ( String clientName , String version ) { return new ClientVersionAlreadyExistsException ( Messages . i18n . format ( "clientVersionAlreadyExists" , clientName , version ) ) ; //$NON-NLS-1$ }
Creates an exception from an client name .
67
9
25,813
public static final ClientVersionNotFoundException clientVersionNotFoundException ( String clientId , String version ) { return new ClientVersionNotFoundException ( Messages . i18n . format ( "clientVersionDoesNotExist" , clientId , version ) ) ; //$NON-NLS-1$ }
Creates an exception from an client id and version .
65
11
25,814
public static final ApiVersionAlreadyExistsException apiVersionAlreadyExistsException ( String apiName , String version ) { return new ApiVersionAlreadyExistsException ( Messages . i18n . format ( "ApiVersionAlreadyExists" , apiName , version ) ) ; //$NON-NLS-1$ }
Creates an exception from an API name .
70
9
25,815
public static InvalidPlanStatusException invalidPlanStatusException ( List < PlanVersionSummaryBean > lockedPlans ) { return new InvalidPlanStatusException ( Messages . i18n . format ( "InvalidPlanStatus" ) + " " + joinList ( lockedPlans ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ }
Creates an invalid plan status exception .
79
8
25,816
public static final PlanVersionAlreadyExistsException planVersionAlreadyExistsException ( String planName , String version ) { return new PlanVersionAlreadyExistsException ( Messages . i18n . format ( "PlanVersionAlreadyExists" , planName , version ) ) ; //$NON-NLS-1$ }
Creates an exception from an plan name .
67
9
25,817
public static final PlanVersionNotFoundException planVersionNotFoundException ( String planId , String version ) { return new PlanVersionNotFoundException ( Messages . i18n . format ( "PlanVersionDoesNotExist" , planId , version ) ) ; //$NON-NLS-1$ }
Creates an exception from an plan id and version .
65
11
25,818
public static final PluginResourceNotFoundException pluginResourceNotFoundException ( String resourceName , PluginCoordinates coordinates ) { return new PluginResourceNotFoundException ( Messages . i18n . format ( "PluginResourceNotFound" , resourceName , coordinates . toString ( ) ) ) ; //$NON-NLS-1$ }
Creates an exception .
71
5
25,819
protected SSLSessionStrategy getSslStrategy ( RequiredAuthType authType ) { try { if ( authType == RequiredAuthType . MTLS ) { if ( mutualAuthSslStrategy == null ) { mutualAuthSslStrategy = SSLSessionStrategyFactory . buildMutual ( tlsOptions ) ; } return mutualAuthSslStrategy ; } else { if ( standardSslStrategy == null ) { if ( tlsOptions . isDevMode ( ) ) { standardSslStrategy = SSLSessionStrategyFactory . buildUnsafe ( ) ; } else { standardSslStrategy = SSLSessionStrategyFactory . buildStandard ( tlsOptions ) ; } } return standardSslStrategy ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Creates the SSL strategy based on configured TLS options .
175
11
25,820
public static final void main ( String [ ] args ) { if ( args . length != 2 ) { printUsage ( ) ; return ; } String cmd = args [ 0 ] ; String input = args [ 1 ] ; if ( "encrypt" . equals ( cmd ) ) { //$NON-NLS-1$ System . out . println ( AesEncrypter . encrypt ( input ) . substring ( "$CRYPT::" . length ( ) ) ) ; //$NON-NLS-1$ } else if ( "decrypt" . equals ( cmd ) ) { //$NON-NLS-1$ System . out . println ( AesEncrypter . decrypt ( "$CRYPT::" + input ) ) ; //$NON-NLS-1$ } else { printUsage ( ) ; } }
Main entry point for the encrypter . Allows encryption and decryption of text from the command line .
181
21
25,821
protected ITokenGenerator getTokenGenerator ( ) throws ServletException { if ( tokenGenerator == null ) { String tokenGeneratorClassName = getConfig ( ) . getManagementApiAuthTokenGenerator ( ) ; if ( tokenGeneratorClassName == null ) throw new ServletException ( "No token generator class specified." ) ; //$NON-NLS-1$ try { Class < ? > c = Class . forName ( tokenGeneratorClassName ) ; tokenGenerator = ( ITokenGenerator ) c . newInstance ( ) ; } catch ( Exception e ) { throw new ServletException ( "Error creating token generator." ) ; //$NON-NLS-1$ } } return tokenGenerator ; }
Gets an instance of the configured token generator .
159
10
25,822
public boolean scan ( IApimanBuffer buffer ) throws SoapEnvelopeNotFoundException { if ( this . buffer == null ) { this . buffer = buffer ; } else { this . buffer . append ( buffer ) ; } boolean scanComplete = doScan ( ) ; // If our buffer is already "max size" but we haven't found the start of the // soap envelope yet, then we're likely not going to find it. if ( ! scanComplete && this . buffer . length ( ) >= getMaxBufferLength ( ) ) { throw new SoapEnvelopeNotFoundException ( ) ; } return scanComplete ; }
Append the given data to any existing buffer then scan the buffer looking for the soap headers . If scanning is complete this method will return true . If more data is required then the method will return false . If an error condition is detected then an exception will be thrown .
132
54
25,823
private int findFrom ( char c , int index ) { int currentIdx = index ; while ( currentIdx < buffer . length ( ) ) { if ( buffer . get ( currentIdx ) == c ) { return currentIdx ; } currentIdx ++ ; } return - 1 ; }
Search for the given character in the buffer starting at the given index . If not found return - 1 . If found return the index of the character .
63
30
25,824
public int readFrom ( InputStream stream ) throws IOException { int bytesRead = stream . read ( buffer ) ; if ( bytesRead < 0 ) { bytesInBuffer = 0 ; } else { bytesInBuffer = bytesRead ; } return bytesRead ; }
Reads from the input stream .
54
7
25,825
public void export ( ) { logger . info ( "----------------------------" ) ; //$NON-NLS-1$ logger . info ( Messages . i18n . format ( "StorageExporter.StartingExport" ) ) ; //$NON-NLS-1$ try { storage . beginTx ( ) ; try { exportMetadata ( ) ; exportUsers ( ) ; exportGateways ( ) ; exportPlugins ( ) ; exportRoles ( ) ; exportPolicyDefs ( ) ; exportOrgs ( ) ; } finally { storage . rollbackTx ( ) ; try { writer . close ( ) ; } catch ( Exception e ) { } } logger . info ( Messages . i18n . format ( "StorageExporter.ExportComplete" ) ) ; //$NON-NLS-1$ logger . info ( "------------------------------------------" ) ; //$NON-NLS-1$ } catch ( StorageException e ) { throw new RuntimeException ( e ) ; } }
Called begin the export process .
211
7
25,826
public static void generatePolicyDescription ( PolicyBean policy ) throws Exception { PolicyDefinitionBean def = policy . getDefinition ( ) ; PolicyDefinitionTemplateBean templateBean = getTemplateBean ( def ) ; if ( templateBean == null ) { return ; } String cacheKey = def . getId ( ) + "::" + templateBean . getLanguage ( ) ; //$NON-NLS-1$ CompiledTemplate template = templateCache . get ( cacheKey ) ; if ( template == null ) { template = TemplateCompiler . compileTemplate ( templateBean . getTemplate ( ) ) ; templateCache . put ( cacheKey , template ) ; } try { // TODO hack to fix broken descriptions - this util should probably not know about encrypted data String jsonConfig = policy . getConfiguration ( ) ; if ( CurrentDataEncrypter . instance != null ) { EntityType entityType = EntityType . Api ; if ( policy . getType ( ) == PolicyType . Client ) { entityType = EntityType . ClientApp ; } else if ( policy . getType ( ) == PolicyType . Plan ) { entityType = EntityType . Plan ; } DataEncryptionContext ctx = new DataEncryptionContext ( policy . getOrganizationId ( ) , policy . getEntityId ( ) , policy . getEntityVersion ( ) , entityType ) ; jsonConfig = CurrentDataEncrypter . instance . decrypt ( jsonConfig , ctx ) ; } Map < String , Object > configMap = mapper . readValue ( jsonConfig , Map . class ) ; configMap = new PolicyConfigMap ( configMap ) ; String desc = ( String ) TemplateRuntime . execute ( template , configMap ) ; policy . setDescription ( desc ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; // TODO properly log the error policy . setDescription ( templateBean . getTemplate ( ) ) ; } }
Generates a dynamic description for the given policy and stores the result on the policy bean instance . This should be done prior to returning the policybean back to the user for a REST call to the management API .
411
42
25,827
private static PolicyDefinitionTemplateBean getTemplateBean ( PolicyDefinitionBean def ) { Locale currentLocale = Messages . i18n . getLocale ( ) ; String lang = currentLocale . getLanguage ( ) ; String country = lang + "_" + currentLocale . getCountry ( ) ; //$NON-NLS-1$ PolicyDefinitionTemplateBean nullBean = null ; PolicyDefinitionTemplateBean langBean = null ; PolicyDefinitionTemplateBean countryBean = null ; for ( PolicyDefinitionTemplateBean pdtb : def . getTemplates ( ) ) { if ( pdtb . getLanguage ( ) == null ) { nullBean = pdtb ; } else if ( pdtb . getLanguage ( ) . equals ( country ) ) { countryBean = pdtb ; break ; } else if ( pdtb . getLanguage ( ) . equals ( lang ) ) { langBean = pdtb ; } } if ( countryBean != null ) { return countryBean ; } if ( langBean != null ) { return langBean ; } if ( nullBean != null ) { return nullBean ; } return null ; }
Determines the appropriate template bean to use given the current locale .
258
14
25,828
public static File getUserM2Repository ( ) { // if there is m2override system propery, use it. String m2Override = System . getProperty ( "apiman.gateway.m2-repository-path" ) ; //$NON-NLS-1$ if ( m2Override != null ) { return new File ( m2Override ) . getAbsoluteFile ( ) ; } String userHome = System . getProperty ( "user.home" ) ; //$NON-NLS-1$ if ( userHome != null ) { File userHomeDir = new File ( userHome ) ; if ( userHomeDir . isDirectory ( ) ) { File m2Dir = new File ( userHome , ".m2/repository" ) ; //$NON-NLS-1$ if ( m2Dir . isDirectory ( ) ) { return m2Dir ; } } } return null ; }
Gets the user s local m2 directory or null if not found .
204
15
25,829
public static File getM2Path ( File m2Dir , PluginCoordinates coordinates ) { String artifactSubPath = getMavenPath ( coordinates ) ; return new File ( m2Dir , artifactSubPath ) ; }
Find the plugin artifact in the local . m2 directory .
47
12
25,830
public static String getMavenPath ( PluginCoordinates coordinates ) { StringBuilder artifactSubPath = new StringBuilder ( ) ; artifactSubPath . append ( coordinates . getGroupId ( ) . replace ( ' ' , ' ' ) ) ; artifactSubPath . append ( ' ' ) ; artifactSubPath . append ( coordinates . getArtifactId ( ) ) ; artifactSubPath . append ( ' ' ) ; artifactSubPath . append ( coordinates . getVersion ( ) ) ; artifactSubPath . append ( ' ' ) ; artifactSubPath . append ( coordinates . getArtifactId ( ) ) ; artifactSubPath . append ( ' ' ) ; artifactSubPath . append ( coordinates . getVersion ( ) ) ; if ( coordinates . getClassifier ( ) != null ) { artifactSubPath . append ( ' ' ) ; artifactSubPath . append ( coordinates . getClassifier ( ) ) ; } artifactSubPath . append ( ' ' ) ; artifactSubPath . append ( coordinates . getType ( ) ) ; return artifactSubPath . toString ( ) ; }
Calculates the relative path of the artifact from the given coordinates .
225
14
25,831
@ Override public IApimanLogger createLogger ( Class < ? > klazz ) { delegatedLogger = LogManager . getLogger ( klazz ) ; this . klazz = klazz ; return this ; }
Instantiate a JsonLogger
52
7
25,832
private static String buildCacheID ( ApiRequest request ) { StringBuilder req = new StringBuilder ( ) ; if ( request . getContract ( ) != null ) { req . append ( request . getApiKey ( ) ) ; } else { req . append ( request . getApiOrgId ( ) ) . append ( KEY_SEPARATOR ) . append ( request . getApiId ( ) ) . append ( KEY_SEPARATOR ) . append ( request . getApiVersion ( ) ) ; } req . append ( KEY_SEPARATOR ) . append ( request . getType ( ) ) . append ( KEY_SEPARATOR ) . append ( request . getDestination ( ) ) ; return req . toString ( ) ; }
Builds a cached request id composed by the API key followed by the HTTP verb and the destination . In the case where there s no API key the ID will contain ApiOrgId + ApiId + ApiVersion
160
45
25,833
public void reset ( ) { if ( nonNull ( client ) ) { synchronized ( mutex ) { if ( nonNull ( client ) ) { // double-guard client . shutdown ( ) ; client = null ; } } } }
Shut down the Redis client .
48
7
25,834
@ Override public void handleDeployFailed ( Vertx vertx , String mainVerticle , DeploymentOptions deploymentOptions , Throwable cause ) { // Default behaviour is to close Vert.x if the deploy failed vertx . close ( ) ; }
A deployment failure has been encountered . You can override this method to customize the behavior . By default it closes the vertx instance .
52
26
25,835
private static void preMarshall ( Object bean ) { try { Method method = bean . getClass ( ) . getDeclaredMethod ( "encryptData" ) ; if ( method != null ) { method . invoke ( bean ) ; } } catch ( NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e ) { } }
Called before marshalling the bean to a form that will be used for storage in the DB .
79
20
25,836
protected String getApiKey ( HttpServletRequest request , QueryMap queryParams ) { String apiKey = request . getHeader ( "X-API-Key" ) ; //$NON-NLS-1$ if ( apiKey == null || apiKey . trim ( ) . length ( ) == 0 ) { apiKey = queryParams . get ( "apikey" ) ; //$NON-NLS-1$ } return apiKey ; }
Gets the API Key from the request . The API key can be passed either via a custom http request header called X - API - Key or else by a query parameter in the URL called apikey .
102
42
25,837
protected void writeResponse ( HttpServletResponse response , ApiResponse sresponse ) { response . setStatus ( sresponse . getCode ( ) ) ; for ( Entry < String , String > entry : sresponse . getHeaders ( ) ) { response . addHeader ( entry . getKey ( ) , entry . getValue ( ) ) ; } }
Writes the API response to the HTTP servlet response object .
75
13
25,838
protected void writeFailure ( final ApiRequest request , final HttpServletResponse resp , final PolicyFailure policyFailure ) { getFailureWriter ( ) . write ( request , policyFailure , new IApiClientResponse ( ) { @ Override public void write ( StringBuffer buffer ) { write ( buffer . toString ( ) ) ; } @ Override public void write ( StringBuilder builder ) { write ( builder . toString ( ) ) ; } @ Override public void write ( String body ) { try { resp . getOutputStream ( ) . write ( body . getBytes ( "UTF-8" ) ) ; //$NON-NLS-1$ resp . getOutputStream ( ) . flush ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } /** * @see io.apiman.gateway.engine.IApiClientResponse#setStatusCode(int) */ @ Override public void setStatusCode ( int code ) { resp . setStatus ( code ) ; } @ Override public void setHeader ( String headerName , String headerValue ) { resp . setHeader ( headerName , headerValue ) ; } } ) ; }
Writes a policy failure to the http response .
252
10
25,839
protected void writeError ( final ApiRequest request , final HttpServletResponse resp , final Throwable error ) { getErrorWriter ( ) . write ( request , error , new IApiClientResponse ( ) { @ Override public void write ( StringBuffer buffer ) { write ( buffer . toString ( ) ) ; } @ Override public void write ( StringBuilder builder ) { write ( builder . toString ( ) ) ; } @ Override public void write ( String body ) { try { resp . getOutputStream ( ) . write ( body . getBytes ( "UTF-8" ) ) ; //$NON-NLS-1$ resp . getOutputStream ( ) . flush ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } /** * @see io.apiman.gateway.engine.IApiClientResponse#setStatusCode(int) */ @ Override public void setStatusCode ( int code ) { resp . setStatus ( code ) ; } @ Override public void setHeader ( String headerName , String headerValue ) { resp . setHeader ( headerName , headerValue ) ; } } ) ; }
Writes an error to the servlet response object .
250
11
25,840
protected static final ApiRequestPathInfo parseApiRequestPath ( HttpServletRequest request ) { return ApimanPathUtils . parseApiRequestPath ( request . getHeader ( ApimanPathUtils . X_API_VERSION_HEADER ) , request . getHeader ( ApimanPathUtils . ACCEPT_HEADER ) , request . getPathInfo ( ) ) ; }
Parse a API request path from servlet path info .
85
12
25,841
protected static final QueryMap parseApiRequestQueryParams ( String queryString ) { QueryMap rval = new QueryMap ( ) ; if ( queryString != null ) { try { String [ ] pairSplit = queryString . split ( "&" ) ; //$NON-NLS-1$ for ( String paramPair : pairSplit ) { int idx = paramPair . indexOf ( "=" ) ; //$NON-NLS-1$ String key , value ; if ( idx != - 1 ) { key = URLDecoder . decode ( paramPair . substring ( 0 , idx ) , "UTF-8" ) ; //$NON-NLS-1$ value = URLDecoder . decode ( paramPair . substring ( idx + 1 ) , "UTF-8" ) ; //$NON-NLS-1$ } else { key = URLDecoder . decode ( paramPair , "UTF-8" ) ; //$NON-NLS-1$ value = null ; } rval . add ( key , value ) ; } } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } } return rval ; }
Parses the query string into a map .
265
10
25,842
public void reset ( ) { if ( null != hazelcastInstance ) { synchronized ( mutex ) { if ( null == hazelcastInstance ) { hazelcastInstance . shutdown ( ) ; hazelcastInstance = null ; } } } if ( ! stores . isEmpty ( ) ) { synchronized ( mutex ) { stores . clear ( ) ; } } }
Shut down the Hazelcast instance and clear stores references .
77
11
25,843
public static void validateName ( String name ) throws InvalidNameException { if ( StringUtils . isEmpty ( name ) ) { throw ExceptionFactory . invalidNameException ( Messages . i18n . format ( "FieldValidator.EmptyNameError" ) ) ; //$NON-NLS-1$ } }
Validates an entity name .
67
6
25,844
public static void validateVersion ( String name ) throws InvalidNameException { if ( StringUtils . isEmpty ( name ) ) { throw ExceptionFactory . invalidVersionException ( Messages . i18n . format ( "FieldValidator.EmptyVersionError" ) ) ; //$NON-NLS-1$ } }
Validates an version .
67
5
25,845
private void saveBuckets ( ) { if ( lastModifiedOn > lastSavedOn ) { System . out . println ( "Persisting current rates to: " + savedRates ) ; //$NON-NLS-1$ Properties props = new Properties ( ) ; for ( Entry < String , RateLimiterBucket > entry : buckets . entrySet ( ) ) { String value = entry . getValue ( ) . getCount ( ) + "|" + entry . getValue ( ) . getLast ( ) ; //$NON-NLS-1$ props . setProperty ( entry . getKey ( ) , value ) ; } try ( FileWriter writer = new FileWriter ( savedRates ) ) { props . store ( writer , "All apiman rate limits" ) ; //$NON-NLS-1$ } catch ( IOException e ) { e . printStackTrace ( ) ; } lastSavedOn = System . currentTimeMillis ( ) ; } }
Saves the current list of buckets into a file .
214
11
25,846
private void loadBuckets ( ) { Properties props = new Properties ( ) ; try ( FileReader reader = new FileReader ( savedRates ) ) { props . load ( reader ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } for ( Entry < Object , Object > entry : props . entrySet ( ) ) { String key = entry . getKey ( ) . toString ( ) ; String value = entry . getValue ( ) . toString ( ) ; String [ ] split = value . split ( "=" ) ; //$NON-NLS-1$ long count = new Long ( split [ 0 ] ) ; long last = new Long ( split [ 1 ] ) ; RateLimiterBucket bucket = new RateLimiterBucket ( ) ; bucket . setCount ( count ) ; bucket . setLast ( last ) ; this . buckets . put ( key , bucket ) ; } }
Loads the saved rates from a file . Done only on startup .
197
14
25,847
private String formatDn ( String dnPattern , String username , ApiRequest request ) { Map < String , String > valuesMap = request . getHeaders ( ) . toMap ( ) ; valuesMap . put ( "username" , username ) ; //$NON-NLS-1$ StrSubstitutor sub = new StrSubstitutor ( valuesMap ) ; return sub . replace ( dnPattern ) ; }
Formats the configured DN by replacing any properties it finds .
93
12
25,848
public static Throwable rootCause ( Throwable e ) { Throwable cause = e ; while ( cause . getCause ( ) != null ) { cause = e . getCause ( ) ; } return cause ; }
Gets the root cause of an exception .
44
9
25,849
private void retireApi ( ActionBean action ) throws ActionException { if ( ! securityContext . hasPermission ( PermissionType . apiAdmin , action . getOrganizationId ( ) ) ) throw ExceptionFactory . notAuthorizedException ( ) ; ApiVersionBean versionBean ; try { versionBean = orgs . getApiVersion ( action . getOrganizationId ( ) , action . getEntityId ( ) , action . getEntityVersion ( ) ) ; } catch ( ApiVersionNotFoundException e ) { throw ExceptionFactory . actionException ( Messages . i18n . format ( "ApiNotFound" ) ) ; //$NON-NLS-1$ } // Validate that it's ok to perform this action - API must be Published. if ( versionBean . getStatus ( ) != ApiStatus . Published ) { throw ExceptionFactory . actionException ( Messages . i18n . format ( "InvalidApiStatus" ) ) ; //$NON-NLS-1$ } Api gatewayApi = new Api ( ) ; gatewayApi . setOrganizationId ( versionBean . getApi ( ) . getOrganization ( ) . getId ( ) ) ; gatewayApi . setApiId ( versionBean . getApi ( ) . getId ( ) ) ; gatewayApi . setVersion ( versionBean . getVersion ( ) ) ; // Retire the API from all relevant gateways try { storage . beginTx ( ) ; Set < ApiGatewayBean > gateways = versionBean . getGateways ( ) ; if ( gateways == null ) { throw new PublishingException ( "No gateways specified for API!" ) ; //$NON-NLS-1$ } for ( ApiGatewayBean apiGatewayBean : gateways ) { IGatewayLink gatewayLink = createGatewayLink ( apiGatewayBean . getGatewayId ( ) ) ; gatewayLink . retireApi ( gatewayApi ) ; gatewayLink . close ( ) ; } versionBean . setStatus ( ApiStatus . Retired ) ; versionBean . setRetiredOn ( new Date ( ) ) ; ApiBean api = storage . getApi ( action . getOrganizationId ( ) , action . getEntityId ( ) ) ; if ( api == null ) { throw new PublishingException ( "Error: could not find API - " + action . getOrganizationId ( ) + "=>" + action . getEntityId ( ) ) ; //$NON-NLS-1$ //$NON-NLS-2$ } if ( api . getNumPublished ( ) == null || api . getNumPublished ( ) == 0 ) { api . setNumPublished ( 0 ) ; } else { api . setNumPublished ( api . getNumPublished ( ) - 1 ) ; } storage . updateApi ( api ) ; storage . updateApiVersion ( versionBean ) ; storage . createAuditEntry ( AuditUtils . apiRetired ( versionBean , securityContext ) ) ; storage . commitTx ( ) ; } catch ( PublishingException e ) { storage . rollbackTx ( ) ; throw ExceptionFactory . actionException ( Messages . i18n . format ( "RetireError" ) , e ) ; //$NON-NLS-1$ } catch ( Exception e ) { storage . rollbackTx ( ) ; throw ExceptionFactory . actionException ( Messages . i18n . format ( "RetireError" ) , e ) ; //$NON-NLS-1$ } log . debug ( String . format ( "Successfully retired API %s on specified gateways: %s" , //$NON-NLS-1$ versionBean . getApi ( ) . getName ( ) , versionBean . getApi ( ) ) ) ; }
Retires an API that is currently published to the Gateway .
837
12
25,850
private List < Policy > aggregateContractPolicies ( ContractSummaryBean contractBean ) { try { 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 = contractBean . getClientOrganizationId ( ) ; id = contractBean . getClientId ( ) ; ver = contractBean . getClientVersion ( ) ; break ; } case Plan : { org = contractBean . getApiOrganizationId ( ) ; id = contractBean . getPlanId ( ) ; ver = contractBean . getPlanVersion ( ) ; break ; } case Api : { org = contractBean . getApiOrganizationId ( ) ; id = contractBean . getApiId ( ) ; ver = contractBean . getApiVersion ( ) ; break ; } default : { throw new RuntimeException ( "Missing case for switch!" ) ; //$NON-NLS-1$ } } List < PolicySummaryBean > clientPolicies = query . getPolicies ( org , id , ver , policyType ) ; try { storage . beginTx ( ) ; for ( PolicySummaryBean policySummaryBean : clientPolicies ) { PolicyBean policyBean = storage . getPolicy ( policyType , org , id , ver , policySummaryBean . getId ( ) ) ; Policy policy = new Policy ( ) ; policy . setPolicyJsonConfig ( policyBean . getConfiguration ( ) ) ; policy . setPolicyImpl ( policyBean . getDefinition ( ) . getPolicyImpl ( ) ) ; policies . add ( policy ) ; } } finally { storage . rollbackTx ( ) ; } } return policies ; } catch ( Exception e ) { throw ExceptionFactory . actionException ( Messages . i18n . format ( "ErrorAggregatingPolicies" , contractBean . getClientId ( ) + "->" + contractBean . getApiDescription ( ) ) , e ) ; //$NON-NLS-1$ //$NON-NLS-2$ } }
Aggregates the API client and plan policies into a single ordered list .
498
15
25,851
private void lockPlan ( ActionBean action ) throws ActionException { if ( ! securityContext . hasPermission ( PermissionType . planAdmin , action . getOrganizationId ( ) ) ) throw ExceptionFactory . notAuthorizedException ( ) ; PlanVersionBean versionBean ; try { versionBean = orgs . getPlanVersion ( action . getOrganizationId ( ) , action . getEntityId ( ) , action . getEntityVersion ( ) ) ; } catch ( PlanVersionNotFoundException e ) { throw ExceptionFactory . actionException ( Messages . i18n . format ( "PlanNotFound" ) ) ; //$NON-NLS-1$ } // Validate that it's ok to perform this action - plan must not already be locked if ( versionBean . getStatus ( ) == PlanStatus . Locked ) { throw ExceptionFactory . actionException ( Messages . i18n . format ( "InvalidPlanStatus" ) ) ; //$NON-NLS-1$ } versionBean . setStatus ( PlanStatus . Locked ) ; versionBean . setLockedOn ( new Date ( ) ) ; try { storage . beginTx ( ) ; storage . updatePlanVersion ( versionBean ) ; storage . createAuditEntry ( AuditUtils . planLocked ( versionBean , securityContext ) ) ; storage . commitTx ( ) ; } catch ( Exception e ) { storage . rollbackTx ( ) ; throw ExceptionFactory . actionException ( Messages . i18n . format ( "LockError" ) , e ) ; //$NON-NLS-1$ } log . debug ( String . format ( "Successfully locked Plan %s: %s" , //$NON-NLS-1$ versionBean . getPlan ( ) . getName ( ) , versionBean . getPlan ( ) ) ) ; }
Locks the plan .
398
5
25,852
protected Plugin readPluginFile ( PluginCoordinates coordinates , File pluginFile ) throws Exception { try { PluginClassLoader pluginClassLoader = createPluginClassLoader ( pluginFile ) ; URL specFile = pluginClassLoader . getResource ( PluginUtils . PLUGIN_SPEC_PATH ) ; if ( specFile == null ) { throw new Exception ( Messages . i18n . format ( "DefaultPluginRegistry.MissingPluginSpecFile" , PluginUtils . PLUGIN_SPEC_PATH ) ) ; //$NON-NLS-1$ } else { PluginSpec spec = PluginUtils . readPluginSpecFile ( specFile ) ; Plugin plugin = new Plugin ( spec , coordinates , pluginClassLoader ) ; // TODO use logger when available System . out . println ( "Read apiman plugin: " + spec ) ; //$NON-NLS-1$ return plugin ; } } catch ( Exception e ) { throw new Exception ( Messages . i18n . format ( "DefaultPluginRegistry.InvalidPlugin" , pluginFile . getAbsolutePath ( ) ) , e ) ; //$NON-NLS-1$ } }
Reads the plugin into an object . This method will fail if the plugin is not valid . This could happen if the file is not a java archive or if the plugin spec file is missing from the archive etc .
245
43
25,853
protected void downloadArtifactTo ( URL artifactUrl , File pluginFile , IAsyncResultHandler < File > handler ) { InputStream istream = null ; OutputStream ostream = null ; try { URLConnection connection = artifactUrl . openConnection ( ) ; connection . connect ( ) ; if ( connection instanceof HttpURLConnection ) { HttpURLConnection httpConnection = ( HttpURLConnection ) connection ; if ( httpConnection . getResponseCode ( ) != 200 ) { handler . handle ( AsyncResultImpl . create ( null ) ) ; return ; } } istream = connection . getInputStream ( ) ; ostream = new FileOutputStream ( pluginFile ) ; IOUtils . copy ( istream , ostream ) ; ostream . flush ( ) ; handler . handle ( AsyncResultImpl . create ( pluginFile ) ) ; } catch ( Exception e ) { handler . handle ( AsyncResultImpl . < File > create ( e ) ) ; } finally { IOUtils . closeQuietly ( istream ) ; IOUtils . closeQuietly ( ostream ) ; } }
Download the artifact at the given URL and store it locally into the given plugin file path .
240
18
25,854
public static void init ( ) { config = new WarEngineConfig ( ) ; // Surface the max-payload-buffer-size property as a system property, if it exists in the apiman.properties file if ( System . getProperty ( GatewayConfigProperties . MAX_PAYLOAD_BUFFER_SIZE ) == null ) { String propVal = config . getConfigProperty ( GatewayConfigProperties . MAX_PAYLOAD_BUFFER_SIZE , null ) ; if ( propVal != null ) { System . setProperty ( GatewayConfigProperties . MAX_PAYLOAD_BUFFER_SIZE , propVal ) ; } } ConfigDrivenEngineFactory factory = new ConfigDrivenEngineFactory ( config ) ; engine = factory . createEngine ( ) ; failureFormatter = loadFailureFormatter ( ) ; errorFormatter = loadErrorFormatter ( ) ; }
Initialize the gateway .
183
5
25,855
private void validateClient ( Client client ) throws RegistrationException { Set < Contract > contracts = client . getContracts ( ) ; if ( contracts . isEmpty ( ) ) { throw new NoContractFoundException ( Messages . i18n . format ( "ESRegistry.NoContracts" ) ) ; //$NON-NLS-1$ } for ( Contract contract : contracts ) { validateContract ( contract ) ; } }
Validate that the client should be registered .
90
9
25,856
protected Api getApi ( String id ) throws IOException { Get get = new Get . Builder ( getIndexName ( ) , id ) . type ( "api" ) . build ( ) ; //$NON-NLS-1$ JestResult result = getClient ( ) . execute ( get ) ; if ( result . isSucceeded ( ) ) { Api api = result . getSourceAsObject ( Api . class ) ; return api ; } else { return null ; } }
Gets the api synchronously .
108
7
25,857
protected Client getClient ( String id ) throws IOException { Get get = new Get . Builder ( getIndexName ( ) , id ) . type ( "client" ) . build ( ) ; //$NON-NLS-1$ JestResult result = getClient ( ) . execute ( get ) ; if ( result . isSucceeded ( ) ) { Client client = result . getSourceAsObject ( Client . class ) ; return client ; } else { return null ; } }
Gets the client synchronously .
104
7
25,858
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 .
47
21
25,859
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 .
86
29
25,860
public static final void validateToken ( AuthToken token ) throws IllegalArgumentException { if ( token . getExpiresOn ( ) . before ( new Date ( ) ) ) { throw new IllegalArgumentException ( "Authentication token expired: " + token . getExpiresOn ( ) ) ; //$NON-NLS-1$ } String validSig = generateSignature ( token ) ; if ( token . getSignature ( ) == null || ! token . getSignature ( ) . equals ( validSig ) ) { throw new IllegalArgumentException ( "Missing or invalid signature on the auth token." ) ; //$NON-NLS-1$ } }
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 .
145
29
25,861
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 .
103
6
25,862
public static final void signAuthToken ( AuthToken token ) { String signature = generateSignature ( token ) ; token . setSignature ( signature ) ; }
Adds a digital signature to the auth token .
33
9
25,863
private static String generateSignature ( AuthToken token ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( token . getPrincipal ( ) ) ; builder . append ( "||" ) ; //$NON-NLS-1$ builder . append ( token . getExpiresOn ( ) . getTime ( ) ) ; builder . append ( "||" ) ; //$NON-NLS-1$ builder . append ( token . getIssuedOn ( ) . getTime ( ) ) ; builder . append ( "||" ) ; //$NON-NLS-1$ TreeSet < String > roles = new TreeSet <> ( token . getRoles ( ) ) ; boolean first = true ; for ( String role : roles ) { if ( first ) { first = false ; } else { builder . append ( "," ) ; //$NON-NLS-1$ } builder . append ( role ) ; } builder . append ( "||" ) ; //$NON-NLS-1$ builder . append ( sharedSecretSource . getSharedSecret ( ) ) ; return DigestUtils . sha256Hex ( builder . toString ( ) ) ; }
Generates a signature for the given token .
259
9
25,864
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 .
47
10
25,865
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 .
49
9
25,866
@ Override 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 .
253
21
25,867
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 .
126
13
25,868
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 .
123
10
25,869
private void setConnectTimeout ( HttpURLConnection connection ) { try { Map < String , String > endpointProperties = this . api . getEndpointProperties ( ) ; if ( endpointProperties . containsKey ( "timeouts.connect" ) ) { //$NON-NLS-1$ int connectTimeoutMs = new Integer ( endpointProperties . get ( "timeouts.connect" ) ) ; //$NON-NLS-1$ connection . setConnectTimeout ( connectTimeoutMs ) ; } } catch ( Throwable t ) { } }
If the endpoint properties includes a connect timeout override then set it here .
120
14
25,870
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 .
46
10
25,871
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
45
9
25,872
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 .
127
12
25,873
private static File getPluginDir ( ) { String dataDirPath = System . getProperty ( "jboss.server.data.dir" ) ; //$NON-NLS-1$ File dataDir = new File ( dataDirPath ) ; if ( ! dataDir . isDirectory ( ) ) { throw new RuntimeException ( "Failed to find WildFly data directory at: " + dataDirPath ) ; //$NON-NLS-1$ } File pluginsDir = new File ( dataDir , "apiman/plugins" ) ; //$NON-NLS-1$ return pluginsDir ; }
Creates the directory to use for the plugin registry . The location of the plugin registry is in the Wildfly data directory .
132
25
25,874
public JestClient createClient ( Map < String , String > config , String defaultIndexName ) { JestClient client ; String indexName = config . get ( "client.index" ) ; //$NON-NLS-1$ if ( indexName == null ) { indexName = defaultIndexName ; } client = createLocalClient ( config , indexName , defaultIndexName ) ; return client ; }
Creates a client from information in the config map .
87
11
25,875
public JestClient createLocalClient ( Map < String , String > config , String indexName , String defaultIndexName ) { String clientLocClassName = config . get ( "client.class" ) ; //$NON-NLS-1$ String clientLocFieldName = config . get ( "client.field" ) ; //$NON-NLS-1$ return createLocalClient ( clientLocClassName , clientLocFieldName , indexName , defaultIndexName ) ; }
Creates a local client from a configuration map .
104
10
25,876
public JestClient createLocalClient ( String className , String fieldName , String indexName , String defaultIndexName ) { String clientKey = "local:" + className + ' ' + fieldName ; //$NON-NLS-1$ 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 ) ; //$NON-NLS-1$ } } } }
Creates a cache by looking it up in a static field . Typically used for testing .
216
18
25,877
protected ClientVersionBean createClientVersionInternal ( NewClientVersionBean bean , ClientBean client ) throws StorageException { if ( ! BeanUtils . isValidVersion ( bean . getVersion ( ) ) ) { throw new StorageException ( "Invalid/illegal client version: " + bean . getVersion ( ) ) ; //$NON-NLS-1$ } 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 ) ) ; //$NON-NLS-1$ return newVersion ; }
Creates a new client version .
329
7
25,878
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 ( ) ) ; // Move the client to the "Ready" state if necessary. 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 ) ) ; // Update the version with new meta-data (e.g. modified-by) cvb . setModifiedBy ( securityContext . getCurrentUser ( ) ) ; cvb . setModifiedOn ( new Date ( ) ) ; storage . updateClientVersion ( cvb ) ; return contract ; }
Creates a contract .
676
5
25,879
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 .
172
26
25,880
protected ApiRegistryBean getApiRegistry ( String organizationId , String clientId , String version , boolean hasPermission ) throws ClientNotFoundException , NotAuthorizedException { // Try to get the client first - will throw a ClientNotFoundException if not found. 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 ) ; // Hide some stuff if the user doesn't have the clientView permission if ( hasPermission ) { apiRegistry . setApiKey ( clientVersion . getApikey ( ) ) ; } List < ApiEntryBean > apis = apiRegistry . getApis ( ) ; storage . beginTx ( ) ; txStarted = true ; for ( ApiEntryBean api : apis ) { String gatewayId = api . getGatewayId ( ) ; // Don't return the gateway id. 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 .
509
6
25,881
protected PlanVersionBean createPlanVersionInternal ( NewPlanVersionBean bean , PlanBean plan ) throws StorageException { if ( ! BeanUtils . isValidVersion ( bean . getVersion ( ) ) ) { throw new StorageException ( "Invalid/illegal plan version: " + bean . getVersion ( ) ) ; //$NON-NLS-1$ } 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 .
229
6
25,882
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 .
280
22
25,883
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
160
5
25,884
private DateTime parseFromDate ( String fromDate ) { // Default to the last 30 days 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 .
95
8
25,885
private DateTime parseToDate ( String toDate ) { // Default to now return parseDate ( toDate , new DateTime ( ) . withZone ( DateTimeZone . UTC ) , false ) ; }
Parse the from date query param .
43
8
25,886
private static DateTime parseDate ( String dateStr , DateTime defaultDate , boolean floor ) { if ( "now" . equals ( dateStr ) ) { //$NON-NLS-1$ return new DateTime ( ) ; } if ( dateStr . length ( ) == 10 ) { DateTime parsed = ISODateTimeFormat . date ( ) . withZone ( DateTimeZone . UTC ) . parseDateTime ( dateStr ) ; // If what we want is the floor, then just return it. But if we want the // ceiling of the date, then we need to set the right params. 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 .
251
15
25,887
private void validateMetricRange ( DateTime from , DateTime to ) throws InvalidMetricCriteriaException { if ( from . isAfter ( to ) ) { throw ExceptionFactory . invalidMetricCriteriaException ( Messages . i18n . format ( "OrganizationResourceImpl.InvalidMetricDateRange" ) ) ; //$NON-NLS-1$ } }
Ensures that the given date range is valid .
80
11
25,888
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" ) ) ; //$NON-NLS-1$ } }
Ensures that a time series can be created for the given date range and interval and that the
224
20
25,889
private void validateEndpoint ( String endpoint ) { try { new URL ( endpoint ) ; } catch ( MalformedURLException e ) { throw new InvalidParameterException ( Messages . i18n . format ( "OrganizationResourceImpl.InvalidEndpointURL" ) ) ; //$NON-NLS-1$ } }
Make sure we ve got a valid URL .
70
9
25,890
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
68
3
25,891
protected < T > SearchResultsBean < T > find ( SearchCriteriaBean criteria , Class < T > type ) throws StorageException { SearchResultsBean < T > results = new SearchResultsBean <> ( ) ; EntityManager entityManager = getActiveEntityManager ( ) ; try { // Set some default in the case that paging information was not included in the request. 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 ; // Now query for the actual results List < T > resultList = typedQuery . getResultList ( ) ; // Check if we got back more than we actually needed. if ( resultList . size ( ) > pageSize ) { resultList . remove ( resultList . size ( ) - 1 ) ; hasMore = true ; } // If there are more results than we needed, then we will need to do another // query to determine how many rows there are in total 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 .
471
14
25,892
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 .
141
17
25,893
public boolean hasQualifiedPermission ( PermissionType permissionName , String orgQualifier ) { String key = createQualifiedPermissionKey ( permissionName , orgQualifier ) ; return qualifiedPermissions . contains ( key ) ; }
Returns true if the qualified permission exists .
49
8
25,894
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 .
66
9
25,895
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 .
164
4
25,896
public boolean isOverwrite ( ) { Boolean booleanObject = BooleanUtils . toBooleanObject ( System . getProperty ( OVERWRITE ) ) ; if ( booleanObject == null ) { booleanObject = Boolean . FALSE ; } return booleanObject ; }
apiman . migrate . overwrite =
53
7
25,897
public void start ( ) { logger . info ( "----------------------------" ) ; //$NON-NLS-1$ logger . info ( Messages . i18n . format ( "StorageImportDispatcher.StartingImport" ) ) ; //$NON-NLS-1$ 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 .
157
5
25,898
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
141
14
25,899
private void publishApis ( ) throws StorageException { logger . info ( Messages . i18n . format ( "StorageExporter.PublishingApis" ) ) ; //$NON-NLS-1$ try { for ( EntityInfo info : apisToPublish ) { logger . info ( Messages . i18n . format ( "StorageExporter.PublishingApi" , info ) ) ; //$NON-NLS-1$ 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 ) ; } // Publish the api to all relevant gateways Set < ApiGatewayBean > gateways = versionBean . getGateways ( ) ; if ( gateways == null ) { throw new RuntimeException ( "No gateways specified for api!" ) ; //$NON-NLS-1$ } 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 .
649
13