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" ) )...
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 == ...
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 ] == targ...
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 )...
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 " + servic...
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 < > ( ) ; tr...
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 ) ;...
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 . siz...
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 ...
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 ( remoteAddrSpli...
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 ( ...
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 = res...
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 : p...
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 ...
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 = apiConnec...
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 ) ; } publ...
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 ( ( ...
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 . ab...
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 ,...
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 = "Basi...
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 ( ...
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 ; } ...
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 . s...
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 . setEntit...
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 (...
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 ) ; e...
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 (...
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 , securityContex...
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 ( n...
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 . setE...
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 , se...
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 ( ) . getTi...
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 . setEnt...
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 ) ...
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 . setEntityI...
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 . setEntityVe...
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 , securityCo...
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 ( be...
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 . setEn...
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 ( ...
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...
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 ( ) ) ;...
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 . setEnti...
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 == nul...
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...
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 < ...
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 SoapEnv...
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 ( ) ; expor...
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 . getLangua...
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 ; PolicyDefiniti...
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 F...
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 ( ) ) ; artifactSubP...
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_...
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 ( String...
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 ) { writ...
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 != -...
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 ( ) + "|" + ...
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 ( ) ....
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 . getOrganiza...
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 ; swi...
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 . getOrgani...
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 ( ...
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 ) { Http...
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 ( GatewayC...
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...
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 ; } ...
Gets the client synchronously .