idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
25,800
private static String convertPattern ( ProxyRule bean ) { String str = bean . getPattern ( ) . replaceAll ( "\\{.+?\\}" , "([^/&?]*)" ) ; return str . endsWith ( "$" ) ? str : str + ".*" ; }
slash ampersand or question mark .
25,801
public static final void validateSearchCriteria ( SearchCriteriaBean criteria ) throws InvalidSearchCriteriaException { if ( criteria . getPaging ( ) != null ) { if ( criteria . getPaging ( ) . getPage ( ) < 1 ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingPage" ) ) ; } if ( criteria . getPaging ( ) . getPageSize ( ) < 1 ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingPageSize" ) ) ; } } int count = 1 ; for ( SearchCriteriaFilterBean filter : criteria . getFilters ( ) ) { if ( filter . getName ( ) == null || filter . getName ( ) . trim ( ) . length ( ) == 0 ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingSearchFilterName" , count ) ) ; } if ( filter . getValue ( ) == null || filter . getValue ( ) . trim ( ) . length ( ) == 0 ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingSearchFilterValue" , count ) ) ; } if ( filter . getOperator ( ) == null || ! validOperators . contains ( filter . getOperator ( ) ) ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingSearchFilterOperator" , count ) ) ; } count ++ ; } if ( criteria . getOrderBy ( ) != null && ( criteria . getOrderBy ( ) . getName ( ) == null || criteria . getOrderBy ( ) . getName ( ) . trim ( ) . length ( ) == 0 ) ) { throw new InvalidSearchCriteriaException ( Messages . i18n . format ( "SearchCriteriaUtil.MissingOrderByName" ) ) ; } }
Validates that the search criteria bean is complete and makes sense .
25,802
public static < T > void callIfExists ( T object , String methodName ) throws SecurityException , IllegalAccessException , IllegalArgumentException , InvocationTargetException { try { Method method = object . getClass ( ) . getMethod ( methodName ) ; method . invoke ( object ) ; } catch ( NoSuchMethodException e ) { } }
Call a method if it exists . Use very sparingly and generally prefer interfaces .
25,803
public static Class < ? > loadClass ( String classname ) { Class < ? > c = null ; try { c = Class . forName ( classname ) ; } catch ( ClassNotFoundException e ) { } if ( c == null ) { try { c = ReflectionUtils . class . getClassLoader ( ) . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { } } if ( c == null ) { try { c = Thread . currentThread ( ) . getContextClassLoader ( ) . loadClass ( classname ) ; } catch ( ClassNotFoundException e ) { } } return c ; }
Loads a class .
25,804
public static Method findSetter ( Class < ? > onClass , Class < ? > targetClass ) { Method [ ] methods = onClass . getMethods ( ) ; for ( Method method : methods ) { Class < ? > [ ] ptypes = method . getParameterTypes ( ) ; if ( method . getName ( ) . startsWith ( "set" ) && ptypes . length == 1 && ptypes [ 0 ] == targetClass ) { return method ; } } return null ; }
Squishy way to find a setter method .
25,805
private IJdbcClient createClient ( IPolicyContext context , JDBCIdentitySource config ) throws Throwable { IJdbcComponent jdbcComponent = context . getComponent ( IJdbcComponent . class ) ; if ( config . getType ( ) == JDBCType . datasource || config . getType ( ) == null ) { DataSource ds = lookupDatasource ( config ) ; return jdbcComponent . create ( ds ) ; } if ( config . getType ( ) == JDBCType . url ) { JdbcOptionsBean options = new JdbcOptionsBean ( ) ; options . setJdbcUrl ( config . getJdbcUrl ( ) ) ; options . setUsername ( config . getUsername ( ) ) ; options . setPassword ( config . getPassword ( ) ) ; options . setAutoCommit ( true ) ; return jdbcComponent . createStandalone ( options ) ; } throw new Exception ( "Unknown JDBC options." ) ; }
Creates the appropriate jdbc client .
25,806
@ SuppressWarnings ( "javadoc" ) public static < T > T getSingleService ( Class < T > serviceInterface ) throws IllegalStateException { T rval = null ; Set < T > services = getServices ( serviceInterface ) ; if ( services . size ( ) > 1 ) { throw new IllegalStateException ( "Multiple implementations found of " + serviceInterface ) ; } else if ( ! services . isEmpty ( ) ) { rval = services . iterator ( ) . next ( ) ; } return rval ; }
Gets a single service by its interface .
25,807
@ SuppressWarnings ( "unchecked" ) public static < T > Set < T > getServices ( Class < T > serviceInterface ) { synchronized ( servicesCache ) { if ( servicesCache . containsKey ( serviceInterface ) ) { return ( Set < T > ) servicesCache . get ( serviceInterface ) ; } Set < T > services = new LinkedHashSet < > ( ) ; try { for ( T service : ServiceLoader . load ( serviceInterface ) ) { services . add ( service ) ; } } catch ( ServiceConfigurationError sce ) { } servicesCache . put ( serviceInterface , services ) ; return services ; } }
Get a set of service implementations for a given interface .
25,808
protected static URL findConfigUrlInDirectory ( File directory , String configName ) { if ( directory . isDirectory ( ) ) { File cfile = new File ( directory , configName ) ; if ( cfile . isFile ( ) ) { try { return cfile . toURI ( ) . toURL ( ) ; } catch ( MalformedURLException e ) { throw new RuntimeException ( e ) ; } } } return null ; }
Returns a URL to a file with the given name inside the given directory .
25,809
private boolean canProcessRequest ( TimeRestrictedAccessConfig config , String destination ) { if ( destination == null || destination . trim ( ) . length ( ) == 0 ) { destination = "/" ; } List < TimeRestrictedAccess > rulesEnabledForPath = getRulesMatchingPath ( config , destination ) ; if ( rulesEnabledForPath . size ( ) != 0 ) { DateTime currentTime = new DateTime ( DateTimeZone . UTC ) ; for ( TimeRestrictedAccess rule : rulesEnabledForPath ) { boolean matchesDay = matchesDay ( currentTime , rule ) ; if ( matchesDay ) { boolean matchesTime = matchesTime ( rule ) ; if ( matchesTime ) { return true ; } } } return false ; } return true ; }
Evaluates whether the destination provided matches any of the configured pathsToIgnore and matches specified time range .
25,810
protected String getRemoteAddr ( ApiRequest request , IPListConfig config ) { String httpHeader = config . getHttpHeader ( ) ; if ( httpHeader != null && httpHeader . trim ( ) . length ( ) > 0 ) { String value = ( String ) request . getHeaders ( ) . get ( httpHeader ) ; if ( value != null ) { return value ; } } return request . getRemoteAddr ( ) ; }
Gets the remote address for comparison .
25,811
protected boolean isMatch ( IPListConfig config , String remoteAddr ) { if ( config . getIpList ( ) . contains ( remoteAddr ) ) { return true ; } try { String [ ] remoteAddrSplit = remoteAddr . split ( "\\." ) ; for ( String ip : config . getIpList ( ) ) { String [ ] ipSplit = ip . split ( "\\." ) ; if ( remoteAddrSplit . length == ipSplit . length ) { int numParts = ipSplit . length ; boolean matches = true ; for ( int idx = 0 ; idx < numParts ; idx ++ ) { if ( ipSplit [ idx ] . equals ( "*" ) || ipSplit [ idx ] . equals ( remoteAddrSplit [ idx ] ) ) { } else { matches = false ; break ; } } if ( matches ) { return true ; } } } } catch ( Throwable t ) { } return false ; }
Returns true if the remote address is a match for the configured values in the IP List .
25,812
private static File getPluginDir ( ) { String dataDirPath = System . getProperty ( "catalina.home" ) ; File dataDir = new File ( dataDirPath , "data" ) ; if ( ! dataDir . getParentFile ( ) . isDirectory ( ) ) { throw new RuntimeException ( "Failed to find Tomcat home at: " + dataDirPath ) ; } if ( ! dataDir . exists ( ) ) { dataDir . mkdir ( ) ; } File pluginsDir = new File ( dataDir , "apiman/plugins" ) ; return pluginsDir ; }
Creates the directory to use for the plugin registry . The location of the plugin registry is in the tomcat data directory .
25,813
private IAsyncResultHandler < IEngineResult > wrapResultHandler ( final IAsyncResultHandler < IEngineResult > handler ) { return ( IAsyncResult < IEngineResult > result ) -> { boolean doRecord = true ; if ( result . isError ( ) ) { recordErrorMetrics ( result . getError ( ) ) ; } else { IEngineResult engineResult = result . getResult ( ) ; if ( engineResult . isFailure ( ) ) { recordFailureMetrics ( engineResult . getPolicyFailure ( ) ) ; } else { recordSuccessMetrics ( engineResult . getApiResponse ( ) ) ; doRecord = false ; } } requestMetric . setRequestEnd ( new Date ( ) ) ; if ( doRecord ) { metrics . record ( requestMetric ) ; } handler . handle ( result ) ; } ; }
Wraps the result handler so that metrics can be properly recorded .
25,814
protected void recordSuccessMetrics ( ApiResponse response ) { requestMetric . setResponseCode ( response . getCode ( ) ) ; requestMetric . setResponseMessage ( response . getMessage ( ) ) ; }
Record success metrics
25,815
protected void recordFailureMetrics ( PolicyFailure failure ) { requestMetric . setResponseCode ( failure . getResponseCode ( ) ) ; requestMetric . setFailure ( true ) ; requestMetric . setFailureCode ( failure . getFailureCode ( ) ) ; requestMetric . setFailureReason ( failure . getMessage ( ) ) ; }
Record failure metrics
25,816
protected void resolvePropertyReplacements ( Api api ) { if ( api == null ) { return ; } String endpoint = api . getEndpoint ( ) ; endpoint = resolveProperties ( endpoint ) ; api . setEndpoint ( endpoint ) ; Map < String , String > properties = api . getEndpointProperties ( ) ; for ( Entry < String , String > entry : properties . entrySet ( ) ) { String value = entry . getValue ( ) ; value = resolveProperties ( value ) ; entry . setValue ( value ) ; } resolvePropertyReplacements ( api . getApiPolicies ( ) ) ; }
Response API property replacements
25,817
protected void resolvePropertyReplacements ( ApiContract apiContract ) { if ( apiContract == null ) { return ; } Api api = apiContract . getApi ( ) ; if ( api != null ) { resolvePropertyReplacements ( api ) ; } resolvePropertyReplacements ( apiContract . getPolicies ( ) ) ; }
Resolve contract property replacements
25,818
private void resolvePropertyReplacements ( List < Policy > apiPolicies ) { if ( apiPolicies != null ) { for ( Policy policy : apiPolicies ) { String config = policy . getPolicyJsonConfig ( ) ; config = resolveProperties ( config ) ; policy . setPolicyJsonConfig ( config ) ; } } }
Resolve property replacements for list of policies
25,819
private String resolveProperties ( String value ) { if ( value . contains ( "${" ) ) { return PROPERTY_SUBSTITUTOR . replace ( value ) ; } else { return value ; } }
Resolve a property
25,820
protected void validateRequest ( ApiRequest request ) throws InvalidContractException { ApiContract contract = request . getContract ( ) ; boolean matches = true ; if ( ! contract . getApi ( ) . getOrganizationId ( ) . equals ( request . getApiOrgId ( ) ) ) { matches = false ; } if ( ! contract . getApi ( ) . getApiId ( ) . equals ( request . getApiId ( ) ) ) { matches = false ; } if ( ! contract . getApi ( ) . getVersion ( ) . equals ( request . getApiVersion ( ) ) ) { matches = false ; } if ( ! matches ) { throw new InvalidContractException ( Messages . i18n . format ( "EngineImpl.InvalidContractForApi" , request . getApiOrgId ( ) , request . getApiId ( ) , request . getApiVersion ( ) ) ) ; } }
Validates that the contract being used for the request is valid against the api information included in the request . Basically the request includes information indicating which specific api is being invoked . This method ensures that the api information in the contract matches the requested api .
25,821
private IAsyncResultHandler < IApiConnectionResponse > createApiConnectionResponseHandler ( ) { return ( IAsyncResult < IApiConnectionResponse > result ) -> { if ( result . isSuccess ( ) ) { requestMetric . setApiEnd ( new Date ( ) ) ; apiConnectionResponse = result . getResult ( ) ; ApiResponse apiResponse = apiConnectionResponse . getHead ( ) ; context . setAttribute ( "apiman.engine.apiResponse" , apiResponse ) ; responseChain = createResponseChain ( ( ApiResponse response ) -> { final EngineResultImpl engineResult = new EngineResultImpl ( response ) ; engineResult . setConnectorResponseStream ( apiConnectionResponse ) ; resultHandler . handle ( AsyncResultImpl . create ( engineResult ) ) ; responseChain . bodyHandler ( buffer -> { requestMetric . setBytesDownloaded ( requestMetric . getBytesDownloaded ( ) + buffer . length ( ) ) ; engineResult . write ( buffer ) ; } ) ; responseChain . endHandler ( isEnd -> { engineResult . end ( ) ; finished = true ; metrics . record ( requestMetric ) ; } ) ; apiConnectionResponse . transmit ( ) ; } ) ; apiConnectionResponse . bodyHandler ( buffer -> responseChain . write ( buffer ) ) ; apiConnectionResponse . endHandler ( isEnd -> responseChain . end ( ) ) ; responseChain . doApply ( apiResponse ) ; } else { resultHandler . handle ( AsyncResultImpl . create ( result . getError ( ) ) ) ; } } ; }
Creates a response handler that is called by the api connector once a connection to the back end api has been made and a response received .
25,822
protected void handleStream ( ) { inboundStreamHandler . handle ( new ISignalWriteStream ( ) { boolean streamFinished = false ; public void write ( IApimanBuffer buffer ) { if ( streamFinished ) { throw new IllegalStateException ( "Attempted write after #end() was called." ) ; } requestChain . write ( buffer ) ; } public void end ( ) { requestChain . end ( ) ; streamFinished = true ; } public void abort ( Throwable t ) { streamFinished = true ; apiConnection . abort ( t ) ; resultHandler . handle ( AsyncResultImpl . < IEngineResult > create ( new RequestAbortedException ( t ) ) ) ; } public boolean isFinished ( ) { return streamFinished ; } public void drainHandler ( IAsyncHandler < Void > drainHandler ) { apiConnection . drainHandler ( drainHandler ) ; } public boolean isFull ( ) { return apiConnection . isFull ( ) ; } } ) ; }
Called when the api connector is ready to receive data from the inbound client request .
25,823
private Chain < ApiRequest > createRequestChain ( IAsyncHandler < ApiRequest > requestHandler ) { RequestChain chain = new RequestChain ( policyImpls , context ) ; chain . headHandler ( requestHandler ) ; chain . policyFailureHandler ( failure -> { if ( responseChain == null ) { responseChain = createResponseChain ( ( ignored ) -> { } ) ; } responseChain . doFailure ( failure ) ; } ) ; chain . policyErrorHandler ( policyErrorHandler ) ; return chain ; }
Creates the chain used to apply policies in order to the api request .
25,824
private Chain < ApiResponse > createResponseChain ( IAsyncHandler < ApiResponse > responseHandler ) { ResponseChain chain = new ResponseChain ( policyImpls , context ) ; chain . headHandler ( responseHandler ) ; chain . policyFailureHandler ( result -> { if ( apiConnectionResponse != null ) { apiConnectionResponse . abort ( ) ; } policyFailureHandler . handle ( result ) ; } ) ; chain . policyErrorHandler ( result -> { if ( apiConnectionResponse != null ) { apiConnectionResponse . abort ( ) ; } policyErrorHandler . handle ( result ) ; } ) ; return chain ; }
Creates the chain used to apply policies in reverse order to the api response .
25,825
private IAsyncHandler < PolicyFailure > createPolicyFailureHandler ( ) { return policyFailure -> { EngineResultImpl engineResult = new EngineResultImpl ( policyFailure ) ; resultHandler . handle ( AsyncResultImpl . < IEngineResult > create ( engineResult ) ) ; } ; }
Creates the handler to use when a policy failure occurs during processing of a chain .
25,826
private IAsyncHandler < Throwable > createPolicyErrorHandler ( ) { return error -> resultHandler . handle ( AsyncResultImpl . < IEngineResult > create ( error ) ) ; }
Creates the handler to use when an error is detected during the processing of a chain .
25,827
private static File getDataDir ( ) { File rval = null ; String dataDir = System . getProperty ( "apiman.bootstrap.data_dir" ) ; if ( dataDir != null ) { rval = new File ( dataDir ) ; } if ( rval == null ) { dataDir = System . getProperty ( "jboss.server.data.dir" ) ; if ( dataDir != null ) { rval = new File ( dataDir , "bootstrap" ) ; } } if ( rval == null ) { dataDir = System . getProperty ( "catalina.home" ) ; if ( dataDir != null ) { rval = new File ( dataDir , "data/bootstrap" ) ; } } return rval ; }
Get the data directory
25,828
protected void configureBasicAuth ( HttpRequest request ) { try { String username = getConfig ( ) . getUsername ( ) ; String password = getConfig ( ) . getPassword ( ) ; String up = username + ":" + password ; String base64 = new String ( Base64 . encodeBase64 ( up . getBytes ( "UTF-8" ) ) ) ; String authHeader = "Basic " + base64 ; request . setHeader ( "Authorization" , authHeader ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } }
Configures BASIC authentication for the request .
25,829
public void addFilter ( String name , String value , SearchCriteriaFilterOperator operator ) { SearchCriteriaFilterBean filter = new SearchCriteriaFilterBean ( ) ; filter . setName ( name ) ; filter . setValue ( value ) ; filter . setOperator ( operator ) ; filters . add ( filter ) ; }
Adds a single filter to the criteria .
25,830
public static Map < String , String > getSubmap ( Map < String , String > mapIn , String subkey ) { if ( mapIn == null || mapIn . isEmpty ( ) ) { return Collections . emptyMap ( ) ; } return mapIn . entrySet ( ) . stream ( ) . filter ( entry -> entry . getKey ( ) . toLowerCase ( ) . startsWith ( subkey . toLowerCase ( ) ) ) . map ( entry -> { String newKey = entry . getKey ( ) . substring ( subkey . length ( ) , entry . getKey ( ) . length ( ) ) ; return new AbstractMap . SimpleImmutableEntry < > ( newKey , entry . getValue ( ) ) ; } ) . collect ( Collectors . toMap ( Entry :: getKey , Entry :: getValue ) ) ; }
Takes map and produces a submap using a key .
25,831
public static boolean valueChanged ( Set < ? > before , Set < ? > after ) { if ( ( before == null && after == null ) || after == null ) { return false ; } if ( before == null ) { if ( after . isEmpty ( ) ) { return false ; } else { return true ; } } else { if ( before . size ( ) != after . size ( ) ) { return true ; } for ( Object bean : after ) { if ( ! before . contains ( bean ) ) { return true ; } } } return false ; }
Returns true only if the set has changed .
25,832
public static boolean valueChanged ( Map < String , String > before , Map < String , String > after ) { if ( ( before == null && after == null ) || after == null ) { return false ; } if ( before == null ) { if ( after . isEmpty ( ) ) { return false ; } else { return true ; } } else { if ( before . size ( ) != after . size ( ) ) { return true ; } for ( Entry < String , String > entry : after . entrySet ( ) ) { String key = entry . getKey ( ) ; String afterValue = entry . getValue ( ) ; if ( ! before . containsKey ( key ) ) { return true ; } String beforeValue = before . get ( key ) ; if ( valueChanged ( beforeValue , afterValue ) ) { return true ; } } } return false ; }
Returns true only if the map has changed .
25,833
public static AuditEntryBean organizationUpdated ( OrganizationBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getId ( ) , AuditEntityType . Organization , securityContext ) ; entry . setEntityId ( null ) ; entry . setEntityVersion ( null ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the organization updated event .
25,834
public static AuditEntryBean membershipGranted ( String organizationId , MembershipData data , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( organizationId , AuditEntityType . Organization , securityContext ) ; entry . setEntityId ( null ) ; entry . setEntityVersion ( null ) ; entry . setWhat ( AuditEntryType . Grant ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the membership granted even .
25,835
public static AuditEntryBean apiCreated ( ApiBean bean , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( bean . getOrganization ( ) . getId ( ) , AuditEntityType . Api , securityContext ) ; entry . setEntityId ( bean . getId ( ) ) ; entry . setEntityVersion ( null ) ; entry . setData ( null ) ; entry . setWhat ( AuditEntryType . Create ) ; return entry ; }
Creates an audit entry for the API created event .
25,836
public static AuditEntryBean apiUpdated ( ApiBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getOrganization ( ) . getId ( ) , AuditEntityType . Api , securityContext ) ; entry . setEntityId ( bean . getId ( ) ) ; entry . setEntityVersion ( null ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the API updated event .
25,837
public static AuditEntryBean apiVersionUpdated ( ApiVersionBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getApi ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Api , securityContext ) ; entry . setEntityId ( bean . getApi ( ) . getId ( ) ) ; entry . setEntityVersion ( bean . getVersion ( ) ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the API version updated event .
25,838
public static AuditEntryBean clientCreated ( ClientBean bean , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( bean . getOrganization ( ) . getId ( ) , AuditEntityType . Client , securityContext ) ; entry . setEntityId ( bean . getId ( ) ) ; entry . setEntityVersion ( null ) ; entry . setData ( null ) ; entry . setWhat ( AuditEntryType . Create ) ; return entry ; }
Creates an audit entry for the client created event .
25,839
public static AuditEntryBean clientUpdated ( ClientBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getOrganization ( ) . getId ( ) , AuditEntityType . Client , securityContext ) ; entry . setEntityId ( bean . getId ( ) ) ; entry . setEntityVersion ( null ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the client updated event .
25,840
public static AuditEntryBean clientVersionUpdated ( ClientVersionBean bean , EntityUpdatedData data , ISecurityContext securityContext ) { if ( data . getChanges ( ) . isEmpty ( ) ) { return null ; } AuditEntryBean entry = newEntry ( bean . getClient ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Client , securityContext ) ; entry . setEntityId ( bean . getClient ( ) . getId ( ) ) ; entry . setEntityVersion ( bean . getVersion ( ) ) ; entry . setWhat ( AuditEntryType . Update ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the client version updated event .
25,841
public static AuditEntryBean contractCreatedToApi ( ContractBean bean , ISecurityContext securityContext ) { AuditEntryBean entry = newEntry ( bean . getApi ( ) . getApi ( ) . getOrganization ( ) . getId ( ) , AuditEntityType . Api , securityContext ) ; entry . setCreatedOn ( new Date ( entry . getCreatedOn ( ) . getTime ( ) + 1 ) ) ; entry . setWhat ( AuditEntryType . CreateContract ) ; entry . setEntityId ( bean . getApi ( ) . getApi ( ) . getId ( ) ) ; entry . setEntityVersion ( bean . getApi ( ) . getVersion ( ) ) ; ContractData data = new ContractData ( bean ) ; entry . setData ( toJSON ( data ) ) ; return entry ; }
Creates an audit entry for the contract created event .
25,842
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 .
25,843
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 .
25,844
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 .
25,845
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 .
25,846
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 .
25,847
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 .
25,848
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 .
25,849
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 .
25,850
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 .
25,851
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 .
25,852
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 .
25,853
private static AuditEntryBean newEntry ( String orgId , AuditEntityType type , ISecurityContext securityContext ) { 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 .
25,854
public static final ClientVersionAlreadyExistsException clientVersionAlreadyExistsException ( String clientName , String version ) { return new ClientVersionAlreadyExistsException ( Messages . i18n . format ( "clientVersionAlreadyExists" , clientName , version ) ) ; }
Creates an exception from an client name .
25,855
public static final ClientVersionNotFoundException clientVersionNotFoundException ( String clientId , String version ) { return new ClientVersionNotFoundException ( Messages . i18n . format ( "clientVersionDoesNotExist" , clientId , version ) ) ; }
Creates an exception from an client id and version .
25,856
public static final ApiVersionAlreadyExistsException apiVersionAlreadyExistsException ( String apiName , String version ) { return new ApiVersionAlreadyExistsException ( Messages . i18n . format ( "ApiVersionAlreadyExists" , apiName , version ) ) ; }
Creates an exception from an API name .
25,857
public static InvalidPlanStatusException invalidPlanStatusException ( List < PlanVersionSummaryBean > lockedPlans ) { return new InvalidPlanStatusException ( Messages . i18n . format ( "InvalidPlanStatus" ) + " " + joinList ( lockedPlans ) ) ; }
Creates an invalid plan status exception .
25,858
public static final PlanVersionAlreadyExistsException planVersionAlreadyExistsException ( String planName , String version ) { return new PlanVersionAlreadyExistsException ( Messages . i18n . format ( "PlanVersionAlreadyExists" , planName , version ) ) ; }
Creates an exception from an plan name .
25,859
public static final PlanVersionNotFoundException planVersionNotFoundException ( String planId , String version ) { return new PlanVersionNotFoundException ( Messages . i18n . format ( "PlanVersionDoesNotExist" , planId , version ) ) ; }
Creates an exception from an plan id and version .
25,860
public static final PluginResourceNotFoundException pluginResourceNotFoundException ( String resourceName , PluginCoordinates coordinates ) { return new PluginResourceNotFoundException ( Messages . i18n . format ( "PluginResourceNotFound" , resourceName , coordinates . toString ( ) ) ) ; }
Creates an exception .
25,861
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 .
25,862
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 ) ) { System . out . println ( AesEncrypter . encrypt ( input ) . substring ( "$CRYPT::" . length ( ) ) ) ; } else if ( "decrypt" . equals ( cmd ) ) { System . out . println ( AesEncrypter . decrypt ( "$CRYPT::" + input ) ) ; } else { printUsage ( ) ; } }
Main entry point for the encrypter . Allows encryption and decryption of text from the command line .
25,863
protected ITokenGenerator getTokenGenerator ( ) throws ServletException { if ( tokenGenerator == null ) { String tokenGeneratorClassName = getConfig ( ) . getManagementApiAuthTokenGenerator ( ) ; if ( tokenGeneratorClassName == null ) throw new ServletException ( "No token generator class specified." ) ; try { Class < ? > c = Class . forName ( tokenGeneratorClassName ) ; tokenGenerator = ( ITokenGenerator ) c . newInstance ( ) ; } catch ( Exception e ) { throw new ServletException ( "Error creating token generator." ) ; } } return tokenGenerator ; }
Gets an instance of the configured token generator .
25,864
public boolean scan ( IApimanBuffer buffer ) throws SoapEnvelopeNotFoundException { if ( this . buffer == null ) { this . buffer = buffer ; } else { this . buffer . append ( buffer ) ; } boolean scanComplete = doScan ( ) ; 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 .
25,865
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 .
25,866
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 .
25,867
public void export ( ) { logger . info ( "----------------------------" ) ; logger . info ( Messages . i18n . format ( "StorageExporter.StartingExport" ) ) ; 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" ) ) ; logger . info ( "------------------------------------------" ) ; } catch ( StorageException e ) { throw new RuntimeException ( e ) ; } }
Called begin the export process .
25,868
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 ( ) ; CompiledTemplate template = templateCache . get ( cacheKey ) ; if ( template == null ) { template = TemplateCompiler . compileTemplate ( templateBean . getTemplate ( ) ) ; templateCache . put ( cacheKey , template ) ; } try { 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 ( ) ; 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 .
25,869
private static PolicyDefinitionTemplateBean getTemplateBean ( PolicyDefinitionBean def ) { Locale currentLocale = Messages . i18n . getLocale ( ) ; String lang = currentLocale . getLanguage ( ) ; String country = lang + "_" + currentLocale . getCountry ( ) ; 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 .
25,870
public static File getUserM2Repository ( ) { String m2Override = System . getProperty ( "apiman.gateway.m2-repository-path" ) ; if ( m2Override != null ) { return new File ( m2Override ) . getAbsoluteFile ( ) ; } String userHome = System . getProperty ( "user.home" ) ; if ( userHome != null ) { File userHomeDir = new File ( userHome ) ; if ( userHomeDir . isDirectory ( ) ) { File m2Dir = new File ( userHome , ".m2/repository" ) ; if ( m2Dir . isDirectory ( ) ) { return m2Dir ; } } } return null ; }
Gets the user s local m2 directory or null if not found .
25,871
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 .
25,872
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 .
25,873
public IApimanLogger createLogger ( Class < ? > klazz ) { delegatedLogger = LogManager . getLogger ( klazz ) ; this . klazz = klazz ; return this ; }
Instantiate a JsonLogger
25,874
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
25,875
public void reset ( ) { if ( nonNull ( client ) ) { synchronized ( mutex ) { if ( nonNull ( client ) ) { client . shutdown ( ) ; client = null ; } } } }
Shut down the Redis client .
25,876
public void handleDeployFailed ( Vertx vertx , String mainVerticle , DeploymentOptions deploymentOptions , Throwable cause ) { vertx . close ( ) ; }
A deployment failure has been encountered . You can override this method to customize the behavior . By default it closes the vertx instance .
25,877
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 .
25,878
protected String getApiKey ( HttpServletRequest request , QueryMap queryParams ) { String apiKey = request . getHeader ( "X-API-Key" ) ; if ( apiKey == null || apiKey . trim ( ) . length ( ) == 0 ) { apiKey = queryParams . get ( "apikey" ) ; } 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 .
25,879
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 .
25,880
protected void writeFailure ( final ApiRequest request , final HttpServletResponse resp , final PolicyFailure policyFailure ) { getFailureWriter ( ) . write ( request , policyFailure , new IApiClientResponse ( ) { public void write ( StringBuffer buffer ) { write ( buffer . toString ( ) ) ; } public void write ( StringBuilder builder ) { write ( builder . toString ( ) ) ; } public void write ( String body ) { try { resp . getOutputStream ( ) . write ( body . getBytes ( "UTF-8" ) ) ; resp . getOutputStream ( ) . flush ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } public void setStatusCode ( int code ) { resp . setStatus ( code ) ; } public void setHeader ( String headerName , String headerValue ) { resp . setHeader ( headerName , headerValue ) ; } } ) ; }
Writes a policy failure to the http response .
25,881
protected void writeError ( final ApiRequest request , final HttpServletResponse resp , final Throwable error ) { getErrorWriter ( ) . write ( request , error , new IApiClientResponse ( ) { public void write ( StringBuffer buffer ) { write ( buffer . toString ( ) ) ; } public void write ( StringBuilder builder ) { write ( builder . toString ( ) ) ; } public void write ( String body ) { try { resp . getOutputStream ( ) . write ( body . getBytes ( "UTF-8" ) ) ; resp . getOutputStream ( ) . flush ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } public void setStatusCode ( int code ) { resp . setStatus ( code ) ; } public void setHeader ( String headerName , String headerValue ) { resp . setHeader ( headerName , headerValue ) ; } } ) ; }
Writes an error to the servlet response object .
25,882
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 .
25,883
protected static final QueryMap parseApiRequestQueryParams ( String queryString ) { QueryMap rval = new QueryMap ( ) ; if ( queryString != null ) { try { String [ ] pairSplit = queryString . split ( "&" ) ; for ( String paramPair : pairSplit ) { int idx = paramPair . indexOf ( "=" ) ; String key , value ; if ( idx != - 1 ) { key = URLDecoder . decode ( paramPair . substring ( 0 , idx ) , "UTF-8" ) ; value = URLDecoder . decode ( paramPair . substring ( idx + 1 ) , "UTF-8" ) ; } else { key = URLDecoder . decode ( paramPair , "UTF-8" ) ; value = null ; } rval . add ( key , value ) ; } } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } } return rval ; }
Parses the query string into a map .
25,884
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 .
25,885
public static void validateName ( String name ) throws InvalidNameException { if ( StringUtils . isEmpty ( name ) ) { throw ExceptionFactory . invalidNameException ( Messages . i18n . format ( "FieldValidator.EmptyNameError" ) ) ; } }
Validates an entity name .
25,886
public static void validateVersion ( String name ) throws InvalidNameException { if ( StringUtils . isEmpty ( name ) ) { throw ExceptionFactory . invalidVersionException ( Messages . i18n . format ( "FieldValidator.EmptyVersionError" ) ) ; } }
Validates an version .
25,887
private void saveBuckets ( ) { if ( lastModifiedOn > lastSavedOn ) { System . out . println ( "Persisting current rates to: " + savedRates ) ; Properties props = new Properties ( ) ; for ( Entry < String , RateLimiterBucket > entry : buckets . entrySet ( ) ) { String value = entry . getValue ( ) . getCount ( ) + "|" + entry . getValue ( ) . getLast ( ) ; props . setProperty ( entry . getKey ( ) , value ) ; } try ( FileWriter writer = new FileWriter ( savedRates ) ) { props . store ( writer , "All apiman rate limits" ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } lastSavedOn = System . currentTimeMillis ( ) ; } }
Saves the current list of buckets into a file .
25,888
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 ( "=" ) ; 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 .
25,889
private String formatDn ( String dnPattern , String username , ApiRequest request ) { Map < String , String > valuesMap = request . getHeaders ( ) . toMap ( ) ; valuesMap . put ( "username" , username ) ; StrSubstitutor sub = new StrSubstitutor ( valuesMap ) ; return sub . replace ( dnPattern ) ; }
Formats the configured DN by replacing any properties it finds .
25,890
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 .
25,891
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" ) ) ; } if ( versionBean . getStatus ( ) != ApiStatus . Published ) { throw ExceptionFactory . actionException ( Messages . i18n . format ( "InvalidApiStatus" ) ) ; } Api gatewayApi = new Api ( ) ; gatewayApi . setOrganizationId ( versionBean . getApi ( ) . getOrganization ( ) . getId ( ) ) ; gatewayApi . setApiId ( versionBean . getApi ( ) . getId ( ) ) ; gatewayApi . setVersion ( versionBean . getVersion ( ) ) ; try { storage . beginTx ( ) ; Set < ApiGatewayBean > gateways = versionBean . getGateways ( ) ; if ( gateways == null ) { throw new PublishingException ( "No gateways specified for API!" ) ; } 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 ( ) ) ; } 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 ) ; } catch ( Exception e ) { storage . rollbackTx ( ) ; throw ExceptionFactory . actionException ( Messages . i18n . format ( "RetireError" ) , e ) ; } log . debug ( String . format ( "Successfully retired API %s on specified gateways: %s" , versionBean . getApi ( ) . getName ( ) , versionBean . getApi ( ) ) ) ; }
Retires an API that is currently published to the Gateway .
25,892
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!" ) ; } } 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 ) ; } }
Aggregates the API client and plan policies into a single ordered list .
25,893
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" ) ) ; } if ( versionBean . getStatus ( ) == PlanStatus . Locked ) { throw ExceptionFactory . actionException ( Messages . i18n . format ( "InvalidPlanStatus" ) ) ; } 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 ) ; } log . debug ( String . format ( "Successfully locked Plan %s: %s" , versionBean . getPlan ( ) . getName ( ) , versionBean . getPlan ( ) ) ) ; }
Locks the plan .
25,894
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 ) ) ; } else { PluginSpec spec = PluginUtils . readPluginSpecFile ( specFile ) ; Plugin plugin = new Plugin ( spec , coordinates , pluginClassLoader ) ; System . out . println ( "Read apiman plugin: " + spec ) ; return plugin ; } } catch ( Exception e ) { throw new Exception ( Messages . i18n . format ( "DefaultPluginRegistry.InvalidPlugin" , pluginFile . getAbsolutePath ( ) ) , e ) ; } }
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 .
25,895
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 .
25,896
public static void init ( ) { config = new WarEngineConfig ( ) ; 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 .
25,897
private void validateClient ( Client client ) throws RegistrationException { Set < Contract > contracts = client . getContracts ( ) ; if ( contracts . isEmpty ( ) ) { throw new NoContractFoundException ( Messages . i18n . format ( "ESRegistry.NoContracts" ) ) ; } for ( Contract contract : contracts ) { validateContract ( contract ) ; } }
Validate that the client should be registered .
25,898
protected Api getApi ( String id ) throws IOException { Get get = new Get . Builder ( getIndexName ( ) , id ) . type ( "api" ) . build ( ) ; JestResult result = getClient ( ) . execute ( get ) ; if ( result . isSucceeded ( ) ) { Api api = result . getSourceAsObject ( Api . class ) ; return api ; } else { return null ; } }
Gets the api synchronously .
25,899
protected Client getClient ( String id ) throws IOException { Get get = new Get . Builder ( getIndexName ( ) , id ) . type ( "client" ) . build ( ) ; JestResult result = getClient ( ) . execute ( get ) ; if ( result . isSucceeded ( ) ) { Client client = result . getSourceAsObject ( Client . class ) ; return client ; } else { return null ; } }
Gets the client synchronously .