repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
apiman/apiman
gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/ESRegistry.java
ESRegistry.getApiId
private String getApiId(Contract contract) { return getApiId(contract.getApiOrgId(), contract.getApiId(), contract.getApiVersion()); }
java
private String getApiId(Contract contract) { return getApiId(contract.getApiOrgId(), contract.getApiId(), contract.getApiVersion()); }
[ "private", "String", "getApiId", "(", "Contract", "contract", ")", "{", "return", "getApiId", "(", "contract", ".", "getApiOrgId", "(", ")", ",", "contract", ".", "getApiId", "(", ")", ",", "contract", ".", "getApiVersion", "(", ")", ")", ";", "}" ]
Generates a valid document ID for a api referenced by a contract, used to retrieve the api from ES. @param contract
[ "Generates", "a", "valid", "document", "ID", "for", "a", "api", "referenced", "by", "a", "contract", "used", "to", "retrieve", "the", "api", "from", "ES", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/ESRegistry.java#L617-L619
train
apiman/apiman
common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java
AuthTokenUtil.produceToken
public static final String produceToken(String principal, Set<String> roles, int expiresInMillis) { AuthToken authToken = createAuthToken(principal, roles, expiresInMillis); String json = toJSON(authToken); return StringUtils.newStringUtf8(Base64.encodeBase64(StringUtils.getBytesUtf8(json))); }
java
public static final String produceToken(String principal, Set<String> roles, int expiresInMillis) { AuthToken authToken = createAuthToken(principal, roles, expiresInMillis); String json = toJSON(authToken); return StringUtils.newStringUtf8(Base64.encodeBase64(StringUtils.getBytesUtf8(json))); }
[ "public", "static", "final", "String", "produceToken", "(", "String", "principal", ",", "Set", "<", "String", ">", "roles", ",", "int", "expiresInMillis", ")", "{", "AuthToken", "authToken", "=", "createAuthToken", "(", "principal", ",", "roles", ",", "expires...
Produce a token suitable for transmission. This will generate the auth token, then serialize it to a JSON string, then Base64 encode the JSON. @param principal the auth principal @param roles the auth roles @param expiresInMillis the number of millis to expiry @return the token
[ "Produce", "a", "token", "suitable", "for", "transmission", ".", "This", "will", "generate", "the", "auth", "token", "then", "serialize", "it", "to", "a", "JSON", "string", "then", "Base64", "encode", "the", "JSON", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java#L74-L78
train
apiman/apiman
common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java
AuthTokenUtil.validateToken
public static final void validateToken(AuthToken token) throws IllegalArgumentException { if (token.getExpiresOn().before(new Date())) { throw new IllegalArgumentException("Authentication token expired: " + token.getExpiresOn()); //$NON-NLS-1$ } String validSig = generateSignature(token); if (token.getSignature() == null || !token.getSignature().equals(validSig)) { throw new IllegalArgumentException("Missing or invalid signature on the auth token."); //$NON-NLS-1$ } }
java
public static final void validateToken(AuthToken token) throws IllegalArgumentException { if (token.getExpiresOn().before(new Date())) { throw new IllegalArgumentException("Authentication token expired: " + token.getExpiresOn()); //$NON-NLS-1$ } String validSig = generateSignature(token); if (token.getSignature() == null || !token.getSignature().equals(validSig)) { throw new IllegalArgumentException("Missing or invalid signature on the auth token."); //$NON-NLS-1$ } }
[ "public", "static", "final", "void", "validateToken", "(", "AuthToken", "token", ")", "throws", "IllegalArgumentException", "{", "if", "(", "token", ".", "getExpiresOn", "(", ")", ".", "before", "(", "new", "Date", "(", ")", ")", ")", "{", "throw", "new", ...
Validates an auth token. This checks the expiration time of the token against the current system time. It also checks the validity of the signature. @param token the authentication token @throws IllegalArgumentException when the token is invalid
[ "Validates", "an", "auth", "token", ".", "This", "checks", "the", "expiration", "time", "of", "the", "token", "against", "the", "current", "system", "time", ".", "It", "also", "checks", "the", "validity", "of", "the", "signature", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java#L103-L111
train
apiman/apiman
common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java
AuthTokenUtil.createAuthToken
public static final AuthToken createAuthToken(String principal, Set<String> roles, int expiresInMillis) { AuthToken token = new AuthToken(); token.setIssuedOn(new Date()); token.setExpiresOn(new Date(System.currentTimeMillis() + expiresInMillis)); token.setPrincipal(principal); token.setRoles(roles); signAuthToken(token); return token; }
java
public static final AuthToken createAuthToken(String principal, Set<String> roles, int expiresInMillis) { AuthToken token = new AuthToken(); token.setIssuedOn(new Date()); token.setExpiresOn(new Date(System.currentTimeMillis() + expiresInMillis)); token.setPrincipal(principal); token.setRoles(roles); signAuthToken(token); return token; }
[ "public", "static", "final", "AuthToken", "createAuthToken", "(", "String", "principal", ",", "Set", "<", "String", ">", "roles", ",", "int", "expiresInMillis", ")", "{", "AuthToken", "token", "=", "new", "AuthToken", "(", ")", ";", "token", ".", "setIssuedO...
Creates an auth token. @param principal the auth principal @param roles the auth roles @param expiresInMillis the number of millis to expiry @return the auth token
[ "Creates", "an", "auth", "token", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java#L120-L128
train
apiman/apiman
common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java
AuthTokenUtil.signAuthToken
public static final void signAuthToken(AuthToken token) { String signature = generateSignature(token); token.setSignature(signature); }
java
public static final void signAuthToken(AuthToken token) { String signature = generateSignature(token); token.setSignature(signature); }
[ "public", "static", "final", "void", "signAuthToken", "(", "AuthToken", "token", ")", "{", "String", "signature", "=", "generateSignature", "(", "token", ")", ";", "token", ".", "setSignature", "(", "signature", ")", ";", "}" ]
Adds a digital signature to the auth token. @param token the auth token
[ "Adds", "a", "digital", "signature", "to", "the", "auth", "token", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java#L134-L137
train
apiman/apiman
common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java
AuthTokenUtil.generateSignature
private static String generateSignature(AuthToken token) { StringBuilder builder = new StringBuilder(); builder.append(token.getPrincipal()); builder.append("||"); //$NON-NLS-1$ builder.append(token.getExpiresOn().getTime()); builder.append("||"); //$NON-NLS-1$ builder.append(token.getIssuedOn().getTime()); builder.append("||"); //$NON-NLS-1$ TreeSet<String> roles = new TreeSet<>(token.getRoles()); boolean first = true; for (String role : roles) { if (first) { first = false; } else { builder.append(","); //$NON-NLS-1$ } builder.append(role); } builder.append("||"); //$NON-NLS-1$ builder.append(sharedSecretSource.getSharedSecret()); return DigestUtils.sha256Hex(builder.toString()); }
java
private static String generateSignature(AuthToken token) { StringBuilder builder = new StringBuilder(); builder.append(token.getPrincipal()); builder.append("||"); //$NON-NLS-1$ builder.append(token.getExpiresOn().getTime()); builder.append("||"); //$NON-NLS-1$ builder.append(token.getIssuedOn().getTime()); builder.append("||"); //$NON-NLS-1$ TreeSet<String> roles = new TreeSet<>(token.getRoles()); boolean first = true; for (String role : roles) { if (first) { first = false; } else { builder.append(","); //$NON-NLS-1$ } builder.append(role); } builder.append("||"); //$NON-NLS-1$ builder.append(sharedSecretSource.getSharedSecret()); return DigestUtils.sha256Hex(builder.toString()); }
[ "private", "static", "String", "generateSignature", "(", "AuthToken", "token", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "builder", ".", "append", "(", "token", ".", "getPrincipal", "(", ")", ")", ";", "builder", ".", ...
Generates a signature for the given token. @param token
[ "Generates", "a", "signature", "for", "the", "given", "token", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java#L143-L164
train
apiman/apiman
common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java
AuthTokenUtil.toJSON
public static final String toJSON(AuthToken token) { try { return mapper.writer().writeValueAsString(token); } catch (Exception e) { throw new RuntimeException(e); } }
java
public static final String toJSON(AuthToken token) { try { return mapper.writer().writeValueAsString(token); } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "final", "String", "toJSON", "(", "AuthToken", "token", ")", "{", "try", "{", "return", "mapper", ".", "writer", "(", ")", ".", "writeValueAsString", "(", "token", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "n...
Convert the auth token to a JSON string. @param token the auth token @return the token as json
[ "Convert", "the", "auth", "token", "to", "a", "JSON", "string", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java#L171-L177
train
apiman/apiman
common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java
AuthTokenUtil.fromJSON
public static final AuthToken fromJSON(String json) { try { return mapper.reader(AuthToken.class).readValue(json); } catch (Exception e) { throw new RuntimeException(e); } }
java
public static final AuthToken fromJSON(String json) { try { return mapper.reader(AuthToken.class).readValue(json); } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "final", "AuthToken", "fromJSON", "(", "String", "json", ")", "{", "try", "{", "return", "mapper", ".", "reader", "(", "AuthToken", ".", "class", ")", ".", "readValue", "(", "json", ")", ";", "}", "catch", "(", "Exception", "e", ")"...
Read the auth token from the JSON string. @param json the token as a json string @return the token
[ "Read", "the", "auth", "token", "from", "the", "JSON", "string", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/auth/src/main/java/io/apiman/common/auth/AuthTokenUtil.java#L184-L190
train
apiman/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/AbstractEngineFactory.java
AbstractEngineFactory.createEngine
@Override public final IEngine createEngine() { IPluginRegistry pluginRegistry = createPluginRegistry(); IDataEncrypter encrypter = createDataEncrypter(pluginRegistry); CurrentDataEncrypter.instance = encrypter; IRegistry registry = createRegistry(pluginRegistry, encrypter); IComponentRegistry componentRegistry = createComponentRegistry(pluginRegistry); IConnectorFactory cfactory = createConnectorFactory(pluginRegistry); IPolicyFactory pfactory = createPolicyFactory(pluginRegistry); IMetrics metrics = createMetrics(pluginRegistry); IDelegateFactory logFactory = createLoggerFactory(pluginRegistry); IApiRequestPathParser pathParser = createRequestPathParser(pluginRegistry); List<IGatewayInitializer> initializers = createInitializers(pluginRegistry); for (IGatewayInitializer initializer : initializers) { initializer.initialize(); } complete(); return new EngineImpl(registry, pluginRegistry, componentRegistry, cfactory, pfactory, metrics, logFactory, pathParser); }
java
@Override public final IEngine createEngine() { IPluginRegistry pluginRegistry = createPluginRegistry(); IDataEncrypter encrypter = createDataEncrypter(pluginRegistry); CurrentDataEncrypter.instance = encrypter; IRegistry registry = createRegistry(pluginRegistry, encrypter); IComponentRegistry componentRegistry = createComponentRegistry(pluginRegistry); IConnectorFactory cfactory = createConnectorFactory(pluginRegistry); IPolicyFactory pfactory = createPolicyFactory(pluginRegistry); IMetrics metrics = createMetrics(pluginRegistry); IDelegateFactory logFactory = createLoggerFactory(pluginRegistry); IApiRequestPathParser pathParser = createRequestPathParser(pluginRegistry); List<IGatewayInitializer> initializers = createInitializers(pluginRegistry); for (IGatewayInitializer initializer : initializers) { initializer.initialize(); } complete(); return new EngineImpl(registry, pluginRegistry, componentRegistry, cfactory, pfactory, metrics, logFactory, pathParser); }
[ "@", "Override", "public", "final", "IEngine", "createEngine", "(", ")", "{", "IPluginRegistry", "pluginRegistry", "=", "createPluginRegistry", "(", ")", ";", "IDataEncrypter", "encrypter", "=", "createDataEncrypter", "(", "pluginRegistry", ")", ";", "CurrentDataEncry...
Call this to create a new engine. This method uses the engine config singleton to create the engine.
[ "Call", "this", "to", "create", "a", "new", "engine", ".", "This", "method", "uses", "the", "engine", "config", "singleton", "to", "create", "the", "engine", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/AbstractEngineFactory.java#L51-L71
train
apiman/apiman
manager/api/core/src/main/java/io/apiman/manager/api/core/config/ApiManagerConfig.java
ApiManagerConfig.getPrefixedProperties
protected Map<String, String> getPrefixedProperties(String prefix) { Map<String, String> rval = new HashMap<>(); Iterator<String> keys = getConfig().getKeys(); while (keys.hasNext()) { String key = keys.next(); if (key.startsWith(prefix)) { String value = getConfig().getString(key); key = key.substring(prefix.length()); rval.put(key, value); } } return rval; }
java
protected Map<String, String> getPrefixedProperties(String prefix) { Map<String, String> rval = new HashMap<>(); Iterator<String> keys = getConfig().getKeys(); while (keys.hasNext()) { String key = keys.next(); if (key.startsWith(prefix)) { String value = getConfig().getString(key); key = key.substring(prefix.length()); rval.put(key, value); } } return rval; }
[ "protected", "Map", "<", "String", ",", "String", ">", "getPrefixedProperties", "(", "String", "prefix", ")", "{", "Map", "<", "String", ",", "String", ">", "rval", "=", "new", "HashMap", "<>", "(", ")", ";", "Iterator", "<", "String", ">", "keys", "="...
Gets a map of properties prefixed by the given string.
[ "Gets", "a", "map", "of", "properties", "prefixed", "by", "the", "given", "string", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/core/src/main/java/io/apiman/manager/api/core/config/ApiManagerConfig.java#L335-L347
train
apiman/apiman
gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/RateLimitingPolicy.java
RateLimitingPolicy.getPeriod
protected static RateBucketPeriod getPeriod(RateLimitingConfig config) { RateLimitingPeriod period = config.getPeriod(); switch (period) { case Second: return RateBucketPeriod.Second; case Day: return RateBucketPeriod.Day; case Hour: return RateBucketPeriod.Hour; case Minute: return RateBucketPeriod.Minute; case Month: return RateBucketPeriod.Month; case Year: return RateBucketPeriod.Year; default: return RateBucketPeriod.Month; } }
java
protected static RateBucketPeriod getPeriod(RateLimitingConfig config) { RateLimitingPeriod period = config.getPeriod(); switch (period) { case Second: return RateBucketPeriod.Second; case Day: return RateBucketPeriod.Day; case Hour: return RateBucketPeriod.Hour; case Minute: return RateBucketPeriod.Minute; case Month: return RateBucketPeriod.Month; case Year: return RateBucketPeriod.Year; default: return RateBucketPeriod.Month; } }
[ "protected", "static", "RateBucketPeriod", "getPeriod", "(", "RateLimitingConfig", "config", ")", "{", "RateLimitingPeriod", "period", "=", "config", ".", "getPeriod", "(", ")", ";", "switch", "(", "period", ")", "{", "case", "Second", ":", "return", "RateBucket...
Gets the appropriate bucket period from the config. @param config
[ "Gets", "the", "appropriate", "bucket", "period", "from", "the", "config", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/RateLimitingPolicy.java#L211-L229
train
apiman/apiman
gateway/platforms/servlet/src/main/java/io/apiman/gateway/platforms/servlet/connectors/HttpApiConnection.java
HttpApiConnection.setConnectTimeout
private void setConnectTimeout(HttpURLConnection connection) { try { Map<String, String> endpointProperties = this.api.getEndpointProperties(); if (endpointProperties.containsKey("timeouts.connect")) { //$NON-NLS-1$ int connectTimeoutMs = new Integer(endpointProperties.get("timeouts.connect")); //$NON-NLS-1$ connection.setConnectTimeout(connectTimeoutMs); } } catch (Throwable t) { } }
java
private void setConnectTimeout(HttpURLConnection connection) { try { Map<String, String> endpointProperties = this.api.getEndpointProperties(); if (endpointProperties.containsKey("timeouts.connect")) { //$NON-NLS-1$ int connectTimeoutMs = new Integer(endpointProperties.get("timeouts.connect")); //$NON-NLS-1$ connection.setConnectTimeout(connectTimeoutMs); } } catch (Throwable t) { } }
[ "private", "void", "setConnectTimeout", "(", "HttpURLConnection", "connection", ")", "{", "try", "{", "Map", "<", "String", ",", "String", ">", "endpointProperties", "=", "this", ".", "api", ".", "getEndpointProperties", "(", ")", ";", "if", "(", "endpointProp...
If the endpoint properties includes a connect timeout override, then set it here. @param connection
[ "If", "the", "endpoint", "properties", "includes", "a", "connect", "timeout", "override", "then", "set", "it", "here", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/servlet/src/main/java/io/apiman/gateway/platforms/servlet/connectors/HttpApiConnection.java#L212-L221
train
apiman/apiman
manager/api/micro/src/main/java/io/apiman/manager/api/micro/Starter.java
Starter.main
public static final void main(String [] args) throws Exception { ManagerApiMicroService microService = new ManagerApiMicroService(); microService.start(); microService.join(); }
java
public static final void main(String [] args) throws Exception { ManagerApiMicroService microService = new ManagerApiMicroService(); microService.start(); microService.join(); }
[ "public", "static", "final", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "ManagerApiMicroService", "microService", "=", "new", "ManagerApiMicroService", "(", ")", ";", "microService", ".", "start", "(", ")", ";", "microSer...
Main entry point for the API Manager micro service. @param args the arguments @throws Exception when any unhandled exception occurs
[ "Main", "entry", "point", "for", "the", "API", "Manager", "micro", "service", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/micro/src/main/java/io/apiman/manager/api/micro/Starter.java#L30-L34
train
apiman/apiman
common/util/src/main/java/io/apiman/common/util/SimpleStringUtils.java
SimpleStringUtils.length
public static int length(String... args) { if (args == null) return 0; int acc = 0; for (String arg : args) { acc += arg.length(); } return acc; }
java
public static int length(String... args) { if (args == null) return 0; int acc = 0; for (String arg : args) { acc += arg.length(); } return acc; }
[ "public", "static", "int", "length", "(", "String", "...", "args", ")", "{", "if", "(", "args", "==", "null", ")", "return", "0", ";", "int", "acc", "=", "0", ";", "for", "(", "String", "arg", ":", "args", ")", "{", "acc", "+=", "arg", ".", "le...
Cumulative length of strings in varargs @param args vararg strings @return cumulative length of strings
[ "Cumulative", "length", "of", "strings", "in", "varargs" ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/util/src/main/java/io/apiman/common/util/SimpleStringUtils.java#L69-L78
train
apiman/apiman
tools/i18n/src/main/java/io/apiman/tools/i18n/TemplateScanner.java
TemplateScanner.outputMessages
private static void outputMessages(TreeMap<String, String> strings, File outputFile) throws FileNotFoundException { PrintWriter writer = new PrintWriter(new FileOutputStream(outputFile)); for (Entry<String, String> entry : strings.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); writer.append(key); writer.append('='); writer.append(val); writer.append("\n"); } writer.flush(); writer.close(); }
java
private static void outputMessages(TreeMap<String, String> strings, File outputFile) throws FileNotFoundException { PrintWriter writer = new PrintWriter(new FileOutputStream(outputFile)); for (Entry<String, String> entry : strings.entrySet()) { String key = entry.getKey(); String val = entry.getValue(); writer.append(key); writer.append('='); writer.append(val); writer.append("\n"); } writer.flush(); writer.close(); }
[ "private", "static", "void", "outputMessages", "(", "TreeMap", "<", "String", ",", "String", ">", "strings", ",", "File", "outputFile", ")", "throws", "FileNotFoundException", "{", "PrintWriter", "writer", "=", "new", "PrintWriter", "(", "new", "FileOutputStream",...
Output the sorted map of strings to the specified output file. @param strings @param outputFile @throws FileNotFoundException
[ "Output", "the", "sorted", "map", "of", "strings", "to", "the", "specified", "output", "file", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/tools/i18n/src/main/java/io/apiman/tools/i18n/TemplateScanner.java#L220-L232
train
apiman/apiman
manager/api/war/wildfly8/src/main/java/io/apiman/manager/api/war/wildfly8/Wildfly8PluginRegistry.java
Wildfly8PluginRegistry.getPluginDir
private static File getPluginDir() { String dataDirPath = System.getProperty("jboss.server.data.dir"); //$NON-NLS-1$ File dataDir = new File(dataDirPath); if (!dataDir.isDirectory()) { throw new RuntimeException("Failed to find WildFly data directory at: " + dataDirPath); //$NON-NLS-1$ } File pluginsDir = new File(dataDir, "apiman/plugins"); //$NON-NLS-1$ return pluginsDir; }
java
private static File getPluginDir() { String dataDirPath = System.getProperty("jboss.server.data.dir"); //$NON-NLS-1$ File dataDir = new File(dataDirPath); if (!dataDir.isDirectory()) { throw new RuntimeException("Failed to find WildFly data directory at: " + dataDirPath); //$NON-NLS-1$ } File pluginsDir = new File(dataDir, "apiman/plugins"); //$NON-NLS-1$ return pluginsDir; }
[ "private", "static", "File", "getPluginDir", "(", ")", "{", "String", "dataDirPath", "=", "System", ".", "getProperty", "(", "\"jboss.server.data.dir\"", ")", ";", "//$NON-NLS-1$", "File", "dataDir", "=", "new", "File", "(", "dataDirPath", ")", ";", "if", "(",...
Creates the directory to use for the plugin registry. The location of the plugin registry is in the Wildfly data directory.
[ "Creates", "the", "directory", "to", "use", "for", "the", "plugin", "registry", ".", "The", "location", "of", "the", "plugin", "registry", "is", "in", "the", "Wildfly", "data", "directory", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/war/wildfly8/src/main/java/io/apiman/manager/api/war/wildfly8/Wildfly8PluginRegistry.java#L48-L56
train
apiman/apiman
gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/LocalClientFactory.java
LocalClientFactory.createClient
public JestClient createClient(Map<String, String> config, String defaultIndexName) { JestClient client; String indexName = config.get("client.index"); //$NON-NLS-1$ if (indexName == null) { indexName = defaultIndexName; } client = createLocalClient(config, indexName, defaultIndexName); return client; }
java
public JestClient createClient(Map<String, String> config, String defaultIndexName) { JestClient client; String indexName = config.get("client.index"); //$NON-NLS-1$ if (indexName == null) { indexName = defaultIndexName; } client = createLocalClient(config, indexName, defaultIndexName); return client; }
[ "public", "JestClient", "createClient", "(", "Map", "<", "String", ",", "String", ">", "config", ",", "String", "defaultIndexName", ")", "{", "JestClient", "client", ";", "String", "indexName", "=", "config", ".", "get", "(", "\"client.index\"", ")", ";", "/...
Creates a client from information in the config map. @param config the configuration @param defaultIndexName the default index to use if not specified in the config @return the ES client
[ "Creates", "a", "client", "from", "information", "in", "the", "config", "map", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/LocalClientFactory.java#L42-L50
train
apiman/apiman
gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/LocalClientFactory.java
LocalClientFactory.createLocalClient
public JestClient createLocalClient(Map<String, String> config, String indexName, String defaultIndexName) { String clientLocClassName = config.get("client.class"); //$NON-NLS-1$ String clientLocFieldName = config.get("client.field"); //$NON-NLS-1$ return createLocalClient(clientLocClassName, clientLocFieldName, indexName, defaultIndexName); }
java
public JestClient createLocalClient(Map<String, String> config, String indexName, String defaultIndexName) { String clientLocClassName = config.get("client.class"); //$NON-NLS-1$ String clientLocFieldName = config.get("client.field"); //$NON-NLS-1$ return createLocalClient(clientLocClassName, clientLocFieldName, indexName, defaultIndexName); }
[ "public", "JestClient", "createLocalClient", "(", "Map", "<", "String", ",", "String", ">", "config", ",", "String", "indexName", ",", "String", "defaultIndexName", ")", "{", "String", "clientLocClassName", "=", "config", ".", "get", "(", "\"client.class\"", ")"...
Creates a local client from a configuration map. @param config the config from apiman.properties @param indexName the name of the ES index @param defaultIndexName the default ES index name @return the ES client
[ "Creates", "a", "local", "client", "from", "a", "configuration", "map", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/LocalClientFactory.java#L59-L63
train
apiman/apiman
gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/LocalClientFactory.java
LocalClientFactory.createLocalClient
public JestClient createLocalClient(String className, String fieldName, String indexName, String defaultIndexName) { String clientKey = "local:" + className + '/' + fieldName; //$NON-NLS-1$ synchronized (clients) { if (clients.containsKey(clientKey)) { return clients.get(clientKey); } else { try { Class<?> clientLocClass = Class.forName(className); Field field = clientLocClass.getField(fieldName); JestClient client = (JestClient) field.get(null); clients.put(clientKey, client); initializeClient(client, indexName, defaultIndexName); return client; } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("Error using local elasticsearch client.", e); //$NON-NLS-1$ } } } }
java
public JestClient createLocalClient(String className, String fieldName, String indexName, String defaultIndexName) { String clientKey = "local:" + className + '/' + fieldName; //$NON-NLS-1$ synchronized (clients) { if (clients.containsKey(clientKey)) { return clients.get(clientKey); } else { try { Class<?> clientLocClass = Class.forName(className); Field field = clientLocClass.getField(fieldName); JestClient client = (JestClient) field.get(null); clients.put(clientKey, client); initializeClient(client, indexName, defaultIndexName); return client; } catch (ClassNotFoundException | NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("Error using local elasticsearch client.", e); //$NON-NLS-1$ } } } }
[ "public", "JestClient", "createLocalClient", "(", "String", "className", ",", "String", "fieldName", ",", "String", "indexName", ",", "String", "defaultIndexName", ")", "{", "String", "clientKey", "=", "\"local:\"", "+", "className", "+", "'", "'", "+", "fieldNa...
Creates a cache by looking it up in a static field. Typically used for testing. @param className the class name @param fieldName the field name @param indexName the name of the ES index @param defaultIndexName the name of the default ES index @return the ES client
[ "Creates", "a", "cache", "by", "looking", "it", "up", "in", "a", "static", "field", ".", "Typically", "used", "for", "testing", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/LocalClientFactory.java#L74-L93
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.createClientVersionInternal
protected ClientVersionBean createClientVersionInternal(NewClientVersionBean bean, ClientBean client) throws StorageException { if (!BeanUtils.isValidVersion(bean.getVersion())) { throw new StorageException("Invalid/illegal client version: " + bean.getVersion()); //$NON-NLS-1$ } ClientVersionBean newVersion = new ClientVersionBean(); newVersion.setClient(client); newVersion.setCreatedBy(securityContext.getCurrentUser()); newVersion.setCreatedOn(new Date()); newVersion.setModifiedBy(securityContext.getCurrentUser()); newVersion.setModifiedOn(new Date()); newVersion.setStatus(ClientStatus.Created); newVersion.setVersion(bean.getVersion()); newVersion.setApikey(bean.getApiKey()); if (newVersion.getApikey() == null) { newVersion.setApikey(apiKeyGenerator.generate()); } storage.createClientVersion(newVersion); storage.createAuditEntry(AuditUtils.clientVersionCreated(newVersion, securityContext)); log.debug(String.format("Created new client version %s: %s", newVersion.getClient().getName(), newVersion)); //$NON-NLS-1$ return newVersion; }
java
protected ClientVersionBean createClientVersionInternal(NewClientVersionBean bean, ClientBean client) throws StorageException { if (!BeanUtils.isValidVersion(bean.getVersion())) { throw new StorageException("Invalid/illegal client version: " + bean.getVersion()); //$NON-NLS-1$ } ClientVersionBean newVersion = new ClientVersionBean(); newVersion.setClient(client); newVersion.setCreatedBy(securityContext.getCurrentUser()); newVersion.setCreatedOn(new Date()); newVersion.setModifiedBy(securityContext.getCurrentUser()); newVersion.setModifiedOn(new Date()); newVersion.setStatus(ClientStatus.Created); newVersion.setVersion(bean.getVersion()); newVersion.setApikey(bean.getApiKey()); if (newVersion.getApikey() == null) { newVersion.setApikey(apiKeyGenerator.generate()); } storage.createClientVersion(newVersion); storage.createAuditEntry(AuditUtils.clientVersionCreated(newVersion, securityContext)); log.debug(String.format("Created new client version %s: %s", newVersion.getClient().getName(), newVersion)); //$NON-NLS-1$ return newVersion; }
[ "protected", "ClientVersionBean", "createClientVersionInternal", "(", "NewClientVersionBean", "bean", ",", "ClientBean", "client", ")", "throws", "StorageException", "{", "if", "(", "!", "BeanUtils", ".", "isValidVersion", "(", "bean", ".", "getVersion", "(", ")", "...
Creates a new client version. @param bean @param client @throws StorageException
[ "Creates", "a", "new", "client", "version", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L786-L810
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.createContractInternal
protected ContractBean createContractInternal(String organizationId, String clientId, String version, NewContractBean bean) throws StorageException, Exception { ContractBean contract; ClientVersionBean cvb; cvb = storage.getClientVersion(organizationId, clientId, version); if (cvb == null) { throw ExceptionFactory.clientVersionNotFoundException(clientId, version); } if (cvb.getStatus() == ClientStatus.Retired) { throw ExceptionFactory.invalidClientStatusException(); } ApiVersionBean avb = storage.getApiVersion(bean.getApiOrgId(), bean.getApiId(), bean.getApiVersion()); if (avb == null) { throw ExceptionFactory.apiNotFoundException(bean.getApiId()); } if (avb.getStatus() != ApiStatus.Published) { throw ExceptionFactory.invalidApiStatusException(); } Set<ApiPlanBean> plans = avb.getPlans(); String planVersion = null; if (plans != null) { for (ApiPlanBean apiPlanBean : plans) { if (apiPlanBean.getPlanId().equals(bean.getPlanId())) { planVersion = apiPlanBean.getVersion(); } } } if (planVersion == null) { throw ExceptionFactory.planNotFoundException(bean.getPlanId()); } PlanVersionBean pvb = storage.getPlanVersion(bean.getApiOrgId(), bean.getPlanId(), planVersion); if (pvb == null) { throw ExceptionFactory.planNotFoundException(bean.getPlanId()); } if (pvb.getStatus() != PlanStatus.Locked) { throw ExceptionFactory.invalidPlanStatusException(); } contract = new ContractBean(); contract.setClient(cvb); contract.setApi(avb); contract.setPlan(pvb); contract.setCreatedBy(securityContext.getCurrentUser()); contract.setCreatedOn(new Date()); // Move the client to the "Ready" state if necessary. if (cvb.getStatus() == ClientStatus.Created && clientValidator.isReady(cvb, true)) { cvb.setStatus(ClientStatus.Ready); } storage.createContract(contract); storage.createAuditEntry(AuditUtils.contractCreatedFromClient(contract, securityContext)); storage.createAuditEntry(AuditUtils.contractCreatedToApi(contract, securityContext)); // Update the version with new meta-data (e.g. modified-by) cvb.setModifiedBy(securityContext.getCurrentUser()); cvb.setModifiedOn(new Date()); storage.updateClientVersion(cvb); return contract; }
java
protected ContractBean createContractInternal(String organizationId, String clientId, String version, NewContractBean bean) throws StorageException, Exception { ContractBean contract; ClientVersionBean cvb; cvb = storage.getClientVersion(organizationId, clientId, version); if (cvb == null) { throw ExceptionFactory.clientVersionNotFoundException(clientId, version); } if (cvb.getStatus() == ClientStatus.Retired) { throw ExceptionFactory.invalidClientStatusException(); } ApiVersionBean avb = storage.getApiVersion(bean.getApiOrgId(), bean.getApiId(), bean.getApiVersion()); if (avb == null) { throw ExceptionFactory.apiNotFoundException(bean.getApiId()); } if (avb.getStatus() != ApiStatus.Published) { throw ExceptionFactory.invalidApiStatusException(); } Set<ApiPlanBean> plans = avb.getPlans(); String planVersion = null; if (plans != null) { for (ApiPlanBean apiPlanBean : plans) { if (apiPlanBean.getPlanId().equals(bean.getPlanId())) { planVersion = apiPlanBean.getVersion(); } } } if (planVersion == null) { throw ExceptionFactory.planNotFoundException(bean.getPlanId()); } PlanVersionBean pvb = storage.getPlanVersion(bean.getApiOrgId(), bean.getPlanId(), planVersion); if (pvb == null) { throw ExceptionFactory.planNotFoundException(bean.getPlanId()); } if (pvb.getStatus() != PlanStatus.Locked) { throw ExceptionFactory.invalidPlanStatusException(); } contract = new ContractBean(); contract.setClient(cvb); contract.setApi(avb); contract.setPlan(pvb); contract.setCreatedBy(securityContext.getCurrentUser()); contract.setCreatedOn(new Date()); // Move the client to the "Ready" state if necessary. if (cvb.getStatus() == ClientStatus.Created && clientValidator.isReady(cvb, true)) { cvb.setStatus(ClientStatus.Ready); } storage.createContract(contract); storage.createAuditEntry(AuditUtils.contractCreatedFromClient(contract, securityContext)); storage.createAuditEntry(AuditUtils.contractCreatedToApi(contract, securityContext)); // Update the version with new meta-data (e.g. modified-by) cvb.setModifiedBy(securityContext.getCurrentUser()); cvb.setModifiedOn(new Date()); storage.updateClientVersion(cvb); return contract; }
[ "protected", "ContractBean", "createContractInternal", "(", "String", "organizationId", ",", "String", "clientId", ",", "String", "version", ",", "NewContractBean", "bean", ")", "throws", "StorageException", ",", "Exception", "{", "ContractBean", "contract", ";", "Cli...
Creates a contract. @param organizationId @param clientId @param version @param bean @throws StorageException @throws Exception
[ "Creates", "a", "contract", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L976-L1036
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.contractAlreadyExists
private boolean contractAlreadyExists(String organizationId, String clientId, String version, NewContractBean bean) { try { List<ContractSummaryBean> contracts = query.getClientContracts(organizationId, clientId, version); for (ContractSummaryBean contract : contracts) { if (contract.getApiOrganizationId().equals(bean.getApiOrgId()) && contract.getApiId().equals(bean.getApiId()) && contract.getApiVersion().equals(bean.getApiVersion()) && contract.getPlanId().equals(bean.getPlanId())) { return true; } } return false; } catch (StorageException e) { return false; } }
java
private boolean contractAlreadyExists(String organizationId, String clientId, String version, NewContractBean bean) { try { List<ContractSummaryBean> contracts = query.getClientContracts(organizationId, clientId, version); for (ContractSummaryBean contract : contracts) { if (contract.getApiOrganizationId().equals(bean.getApiOrgId()) && contract.getApiId().equals(bean.getApiId()) && contract.getApiVersion().equals(bean.getApiVersion()) && contract.getPlanId().equals(bean.getPlanId())) { return true; } } return false; } catch (StorageException e) { return false; } }
[ "private", "boolean", "contractAlreadyExists", "(", "String", "organizationId", ",", "String", "clientId", ",", "String", "version", ",", "NewContractBean", "bean", ")", "{", "try", "{", "List", "<", "ContractSummaryBean", ">", "contracts", "=", "query", ".", "g...
Check to see if the contract already exists, by getting a list of all the client's contracts and comparing with the one being created. @param organizationId @param clientId @param version @param bean
[ "Check", "to", "see", "if", "the", "contract", "already", "exists", "by", "getting", "a", "list", "of", "all", "the", "client", "s", "contracts", "and", "comparing", "with", "the", "one", "being", "created", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L1046-L1063
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.getApiRegistry
protected ApiRegistryBean getApiRegistry(String organizationId, String clientId, String version, boolean hasPermission) throws ClientNotFoundException, NotAuthorizedException { // Try to get the client first - will throw a ClientNotFoundException if not found. ClientVersionBean clientVersion = getClientVersionInternal(organizationId, clientId, version, hasPermission); Map<String, IGatewayLink> gatewayLinks = new HashMap<>(); Map<String, GatewayBean> gateways = new HashMap<>(); boolean txStarted = false; try { ApiRegistryBean apiRegistry = query.getApiRegistry(organizationId, clientId, version); // Hide some stuff if the user doesn't have the clientView permission if (hasPermission) { apiRegistry.setApiKey(clientVersion.getApikey()); } List<ApiEntryBean> apis = apiRegistry.getApis(); storage.beginTx(); txStarted = true; for (ApiEntryBean api : apis) { String gatewayId = api.getGatewayId(); // Don't return the gateway id. api.setGatewayId(null); GatewayBean gateway = gateways.get(gatewayId); if (gateway == null) { gateway = storage.getGateway(gatewayId); gateways.put(gatewayId, gateway); } IGatewayLink link = gatewayLinks.get(gatewayId); if (link == null) { link = gatewayLinkFactory.create(gateway); gatewayLinks.put(gatewayId, link); } ApiEndpoint se = link.getApiEndpoint(api.getApiOrgId(), api.getApiId(), api.getApiVersion()); String apiEndpoint = se.getEndpoint(); api.setHttpEndpoint(apiEndpoint); } return apiRegistry; } catch (StorageException|GatewayAuthenticationException e) { throw new SystemErrorException(e); } finally { if (txStarted) { storage.rollbackTx(); } for (IGatewayLink link : gatewayLinks.values()) { link.close(); } } }
java
protected ApiRegistryBean getApiRegistry(String organizationId, String clientId, String version, boolean hasPermission) throws ClientNotFoundException, NotAuthorizedException { // Try to get the client first - will throw a ClientNotFoundException if not found. ClientVersionBean clientVersion = getClientVersionInternal(organizationId, clientId, version, hasPermission); Map<String, IGatewayLink> gatewayLinks = new HashMap<>(); Map<String, GatewayBean> gateways = new HashMap<>(); boolean txStarted = false; try { ApiRegistryBean apiRegistry = query.getApiRegistry(organizationId, clientId, version); // Hide some stuff if the user doesn't have the clientView permission if (hasPermission) { apiRegistry.setApiKey(clientVersion.getApikey()); } List<ApiEntryBean> apis = apiRegistry.getApis(); storage.beginTx(); txStarted = true; for (ApiEntryBean api : apis) { String gatewayId = api.getGatewayId(); // Don't return the gateway id. api.setGatewayId(null); GatewayBean gateway = gateways.get(gatewayId); if (gateway == null) { gateway = storage.getGateway(gatewayId); gateways.put(gatewayId, gateway); } IGatewayLink link = gatewayLinks.get(gatewayId); if (link == null) { link = gatewayLinkFactory.create(gateway); gatewayLinks.put(gatewayId, link); } ApiEndpoint se = link.getApiEndpoint(api.getApiOrgId(), api.getApiId(), api.getApiVersion()); String apiEndpoint = se.getEndpoint(); api.setHttpEndpoint(apiEndpoint); } return apiRegistry; } catch (StorageException|GatewayAuthenticationException e) { throw new SystemErrorException(e); } finally { if (txStarted) { storage.rollbackTx(); } for (IGatewayLink link : gatewayLinks.values()) { link.close(); } } }
[ "protected", "ApiRegistryBean", "getApiRegistry", "(", "String", "organizationId", ",", "String", "clientId", ",", "String", "version", ",", "boolean", "hasPermission", ")", "throws", "ClientNotFoundException", ",", "NotAuthorizedException", "{", "// Try to get the client f...
Gets the API registry. @param organizationId @param clientId @param version @param hasPermission @throws ClientNotFoundException @throws NotAuthorizedException
[ "Gets", "the", "API", "registry", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L1245-L1296
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.createPlanVersionInternal
protected PlanVersionBean createPlanVersionInternal(NewPlanVersionBean bean, PlanBean plan) throws StorageException { if (!BeanUtils.isValidVersion(bean.getVersion())) { throw new StorageException("Invalid/illegal plan version: " + bean.getVersion()); //$NON-NLS-1$ } PlanVersionBean newVersion = new PlanVersionBean(); newVersion.setCreatedBy(securityContext.getCurrentUser()); newVersion.setCreatedOn(new Date()); newVersion.setModifiedBy(securityContext.getCurrentUser()); newVersion.setModifiedOn(new Date()); newVersion.setStatus(PlanStatus.Created); newVersion.setPlan(plan); newVersion.setVersion(bean.getVersion()); storage.createPlanVersion(newVersion); storage.createAuditEntry(AuditUtils.planVersionCreated(newVersion, securityContext)); return newVersion; }
java
protected PlanVersionBean createPlanVersionInternal(NewPlanVersionBean bean, PlanBean plan) throws StorageException { if (!BeanUtils.isValidVersion(bean.getVersion())) { throw new StorageException("Invalid/illegal plan version: " + bean.getVersion()); //$NON-NLS-1$ } PlanVersionBean newVersion = new PlanVersionBean(); newVersion.setCreatedBy(securityContext.getCurrentUser()); newVersion.setCreatedOn(new Date()); newVersion.setModifiedBy(securityContext.getCurrentUser()); newVersion.setModifiedOn(new Date()); newVersion.setStatus(PlanStatus.Created); newVersion.setPlan(plan); newVersion.setVersion(bean.getVersion()); storage.createPlanVersion(newVersion); storage.createAuditEntry(AuditUtils.planVersionCreated(newVersion, securityContext)); return newVersion; }
[ "protected", "PlanVersionBean", "createPlanVersionInternal", "(", "NewPlanVersionBean", "bean", ",", "PlanBean", "plan", ")", "throws", "StorageException", "{", "if", "(", "!", "BeanUtils", ".", "isValidVersion", "(", "bean", ".", "getVersion", "(", ")", ")", ")",...
Creates a plan version. @param bean @param plan @throws StorageException
[ "Creates", "a", "plan", "version", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L2892-L2909
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.doGetPolicy
protected PolicyBean doGetPolicy(PolicyType type, String organizationId, String entityId, String entityVersion, long policyId) throws PolicyNotFoundException { try { storage.beginTx(); PolicyBean policy = storage.getPolicy(type, organizationId, entityId, entityVersion, policyId); if (policy == null) { throw ExceptionFactory.policyNotFoundException(policyId); } storage.commitTx(); if (policy.getType() != type) { throw ExceptionFactory.policyNotFoundException(policyId); } if (!policy.getOrganizationId().equals(organizationId)) { throw ExceptionFactory.policyNotFoundException(policyId); } if (!policy.getEntityId().equals(entityId)) { throw ExceptionFactory.policyNotFoundException(policyId); } if (!policy.getEntityVersion().equals(entityVersion)) { throw ExceptionFactory.policyNotFoundException(policyId); } PolicyTemplateUtil.generatePolicyDescription(policy); return policy; } catch (AbstractRestException e) { storage.rollbackTx(); throw e; } catch (Exception e) { storage.rollbackTx(); throw new SystemErrorException(e); } }
java
protected PolicyBean doGetPolicy(PolicyType type, String organizationId, String entityId, String entityVersion, long policyId) throws PolicyNotFoundException { try { storage.beginTx(); PolicyBean policy = storage.getPolicy(type, organizationId, entityId, entityVersion, policyId); if (policy == null) { throw ExceptionFactory.policyNotFoundException(policyId); } storage.commitTx(); if (policy.getType() != type) { throw ExceptionFactory.policyNotFoundException(policyId); } if (!policy.getOrganizationId().equals(organizationId)) { throw ExceptionFactory.policyNotFoundException(policyId); } if (!policy.getEntityId().equals(entityId)) { throw ExceptionFactory.policyNotFoundException(policyId); } if (!policy.getEntityVersion().equals(entityVersion)) { throw ExceptionFactory.policyNotFoundException(policyId); } PolicyTemplateUtil.generatePolicyDescription(policy); return policy; } catch (AbstractRestException e) { storage.rollbackTx(); throw e; } catch (Exception e) { storage.rollbackTx(); throw new SystemErrorException(e); } }
[ "protected", "PolicyBean", "doGetPolicy", "(", "PolicyType", "type", ",", "String", "organizationId", ",", "String", "entityId", ",", "String", "entityVersion", ",", "long", "policyId", ")", "throws", "PolicyNotFoundException", "{", "try", "{", "storage", ".", "be...
Gets a policy by its id. Also verifies that the policy really does belong to the entity indicated. @param type the policy type @param organizationId the org id @param entityId the entity id @param entityVersion the entity version @param policyId the policy id @return a policy bean @throws PolicyNotFoundException
[ "Gets", "a", "policy", "by", "its", "id", ".", "Also", "verifies", "that", "the", "policy", "really", "does", "belong", "to", "the", "entity", "indicated", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L3443-L3473
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.decryptEndpointProperties
private void decryptEndpointProperties(ApiVersionBean versionBean) { Map<String, String> endpointProperties = versionBean.getEndpointProperties(); if (endpointProperties != null) { for (Entry<String, String> entry : endpointProperties.entrySet()) { DataEncryptionContext ctx = new DataEncryptionContext( versionBean.getApi().getOrganization().getId(), versionBean.getApi().getId(), versionBean.getVersion(), EntityType.Api); entry.setValue(encrypter.decrypt(entry.getValue(), ctx)); } } }
java
private void decryptEndpointProperties(ApiVersionBean versionBean) { Map<String, String> endpointProperties = versionBean.getEndpointProperties(); if (endpointProperties != null) { for (Entry<String, String> entry : endpointProperties.entrySet()) { DataEncryptionContext ctx = new DataEncryptionContext( versionBean.getApi().getOrganization().getId(), versionBean.getApi().getId(), versionBean.getVersion(), EntityType.Api); entry.setValue(encrypter.decrypt(entry.getValue(), ctx)); } } }
[ "private", "void", "decryptEndpointProperties", "(", "ApiVersionBean", "versionBean", ")", "{", "Map", "<", "String", ",", "String", ">", "endpointProperties", "=", "versionBean", ".", "getEndpointProperties", "(", ")", ";", "if", "(", "endpointProperties", "!=", ...
Decrypt the endpoint properties
[ "Decrypt", "the", "endpoint", "properties" ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L3491-L3503
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.parseFromDate
private DateTime parseFromDate(String fromDate) { // Default to the last 30 days DateTime defaultFrom = new DateTime().withZone(DateTimeZone.UTC).minusDays(30).withHourOfDay(0) .withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0); return parseDate(fromDate, defaultFrom, true); }
java
private DateTime parseFromDate(String fromDate) { // Default to the last 30 days DateTime defaultFrom = new DateTime().withZone(DateTimeZone.UTC).minusDays(30).withHourOfDay(0) .withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0); return parseDate(fromDate, defaultFrom, true); }
[ "private", "DateTime", "parseFromDate", "(", "String", "fromDate", ")", "{", "// Default to the last 30 days", "DateTime", "defaultFrom", "=", "new", "DateTime", "(", ")", ".", "withZone", "(", "DateTimeZone", ".", "UTC", ")", ".", "minusDays", "(", "30", ")", ...
Parse the to date query param.
[ "Parse", "the", "to", "date", "query", "param", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L3651-L3656
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.parseToDate
private DateTime parseToDate(String toDate) { // Default to now return parseDate(toDate, new DateTime().withZone(DateTimeZone.UTC), false); }
java
private DateTime parseToDate(String toDate) { // Default to now return parseDate(toDate, new DateTime().withZone(DateTimeZone.UTC), false); }
[ "private", "DateTime", "parseToDate", "(", "String", "toDate", ")", "{", "// Default to now", "return", "parseDate", "(", "toDate", ",", "new", "DateTime", "(", ")", ".", "withZone", "(", "DateTimeZone", ".", "UTC", ")", ",", "false", ")", ";", "}" ]
Parse the from date query param.
[ "Parse", "the", "from", "date", "query", "param", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L3661-L3664
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.parseDate
private static DateTime parseDate(String dateStr, DateTime defaultDate, boolean floor) { if ("now".equals(dateStr)) { //$NON-NLS-1$ return new DateTime(); } if (dateStr.length() == 10) { DateTime parsed = ISODateTimeFormat.date().withZone(DateTimeZone.UTC).parseDateTime(dateStr); // If what we want is the floor, then just return it. But if we want the // ceiling of the date, then we need to set the right params. if (!floor) { parsed = parsed.plusDays(1).minusMillis(1); } return parsed; } if (dateStr.length() == 20) { return ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime(dateStr); } if (dateStr.length() == 24) { return ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC).parseDateTime(dateStr); } return defaultDate; }
java
private static DateTime parseDate(String dateStr, DateTime defaultDate, boolean floor) { if ("now".equals(dateStr)) { //$NON-NLS-1$ return new DateTime(); } if (dateStr.length() == 10) { DateTime parsed = ISODateTimeFormat.date().withZone(DateTimeZone.UTC).parseDateTime(dateStr); // If what we want is the floor, then just return it. But if we want the // ceiling of the date, then we need to set the right params. if (!floor) { parsed = parsed.plusDays(1).minusMillis(1); } return parsed; } if (dateStr.length() == 20) { return ISODateTimeFormat.dateTimeNoMillis().withZone(DateTimeZone.UTC).parseDateTime(dateStr); } if (dateStr.length() == 24) { return ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC).parseDateTime(dateStr); } return defaultDate; }
[ "private", "static", "DateTime", "parseDate", "(", "String", "dateStr", ",", "DateTime", "defaultDate", ",", "boolean", "floor", ")", "{", "if", "(", "\"now\"", ".", "equals", "(", "dateStr", ")", ")", "{", "//$NON-NLS-1$", "return", "new", "DateTime", "(", ...
Parses a query param representing a date into an actual date object.
[ "Parses", "a", "query", "param", "representing", "a", "date", "into", "an", "actual", "date", "object", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L3669-L3689
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.validateMetricRange
private void validateMetricRange(DateTime from, DateTime to) throws InvalidMetricCriteriaException { if (from.isAfter(to)) { throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("OrganizationResourceImpl.InvalidMetricDateRange")); //$NON-NLS-1$ } }
java
private void validateMetricRange(DateTime from, DateTime to) throws InvalidMetricCriteriaException { if (from.isAfter(to)) { throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("OrganizationResourceImpl.InvalidMetricDateRange")); //$NON-NLS-1$ } }
[ "private", "void", "validateMetricRange", "(", "DateTime", "from", ",", "DateTime", "to", ")", "throws", "InvalidMetricCriteriaException", "{", "if", "(", "from", ".", "isAfter", "(", "to", ")", ")", "{", "throw", "ExceptionFactory", ".", "invalidMetricCriteriaExc...
Ensures that the given date range is valid.
[ "Ensures", "that", "the", "given", "date", "range", "is", "valid", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L3694-L3698
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.validateTimeSeriesMetric
private void validateTimeSeriesMetric(DateTime from, DateTime to, HistogramIntervalType interval) throws InvalidMetricCriteriaException { long millis = to.getMillis() - from.getMillis(); long divBy = ONE_DAY_MILLIS; switch (interval) { case day: divBy = ONE_DAY_MILLIS; break; case hour: divBy = ONE_HOUR_MILLIS; break; case minute: divBy = ONE_MINUTE_MILLIS; break; case month: divBy = ONE_MONTH_MILLIS; break; case week: divBy = ONE_WEEK_MILLIS; break; default: break; } long totalDataPoints = millis / divBy; if (totalDataPoints > 5000) { throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("OrganizationResourceImpl.MetricDataSetTooLarge")); //$NON-NLS-1$ } }
java
private void validateTimeSeriesMetric(DateTime from, DateTime to, HistogramIntervalType interval) throws InvalidMetricCriteriaException { long millis = to.getMillis() - from.getMillis(); long divBy = ONE_DAY_MILLIS; switch (interval) { case day: divBy = ONE_DAY_MILLIS; break; case hour: divBy = ONE_HOUR_MILLIS; break; case minute: divBy = ONE_MINUTE_MILLIS; break; case month: divBy = ONE_MONTH_MILLIS; break; case week: divBy = ONE_WEEK_MILLIS; break; default: break; } long totalDataPoints = millis / divBy; if (totalDataPoints > 5000) { throw ExceptionFactory.invalidMetricCriteriaException(Messages.i18n.format("OrganizationResourceImpl.MetricDataSetTooLarge")); //$NON-NLS-1$ } }
[ "private", "void", "validateTimeSeriesMetric", "(", "DateTime", "from", ",", "DateTime", "to", ",", "HistogramIntervalType", "interval", ")", "throws", "InvalidMetricCriteriaException", "{", "long", "millis", "=", "to", ".", "getMillis", "(", ")", "-", "from", "."...
Ensures that a time series can be created for the given date range and interval, and that the
[ "Ensures", "that", "a", "time", "series", "can", "be", "created", "for", "the", "given", "date", "range", "and", "interval", "and", "that", "the" ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L3704-L3731
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java
OrganizationResourceImpl.validateEndpoint
private void validateEndpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException e) { throw new InvalidParameterException(Messages.i18n.format("OrganizationResourceImpl.InvalidEndpointURL")); //$NON-NLS-1$ } }
java
private void validateEndpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException e) { throw new InvalidParameterException(Messages.i18n.format("OrganizationResourceImpl.InvalidEndpointURL")); //$NON-NLS-1$ } }
[ "private", "void", "validateEndpoint", "(", "String", "endpoint", ")", "{", "try", "{", "new", "URL", "(", "endpoint", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "throw", "new", "InvalidParameterException", "(", "Messages", ".", "i1...
Make sure we've got a valid URL.
[ "Make", "sure", "we", "ve", "got", "a", "valid", "URL", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/OrganizationResourceImpl.java#L3736-L3742
train
apiman/apiman
manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/AbstractJpaStorage.java
AbstractJpaStorage.delete
public <T> void delete(T bean) throws StorageException { EntityManager entityManager = getActiveEntityManager(); try { entityManager.remove(bean); } catch (Throwable t) { logger.error(t.getMessage(), t); throw new StorageException(t); } }
java
public <T> void delete(T bean) throws StorageException { EntityManager entityManager = getActiveEntityManager(); try { entityManager.remove(bean); } catch (Throwable t) { logger.error(t.getMessage(), t); throw new StorageException(t); } }
[ "public", "<", "T", ">", "void", "delete", "(", "T", "bean", ")", "throws", "StorageException", "{", "EntityManager", "entityManager", "=", "getActiveEntityManager", "(", ")", ";", "try", "{", "entityManager", ".", "remove", "(", "bean", ")", ";", "}", "ca...
Delete using bean @param bean the bean to delete @throws StorageException if a storage problem occurs while storing a bean
[ "Delete", "using", "bean" ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/AbstractJpaStorage.java#L175-L183
train
apiman/apiman
manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/AbstractJpaStorage.java
AbstractJpaStorage.find
protected <T> SearchResultsBean<T> find(SearchCriteriaBean criteria, Class<T> type) throws StorageException { SearchResultsBean<T> results = new SearchResultsBean<>(); EntityManager entityManager = getActiveEntityManager(); try { // Set some default in the case that paging information was not included in the request. PagingBean paging = criteria.getPaging(); if (paging == null) { paging = new PagingBean(); paging.setPage(1); paging.setPageSize(20); } int page = paging.getPage(); int pageSize = paging.getPageSize(); int start = (page - 1) * pageSize; CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<T> criteriaQuery = builder.createQuery(type); Root<T> from = criteriaQuery.from(type); applySearchCriteriaToQuery(criteria, builder, criteriaQuery, from, false); TypedQuery<T> typedQuery = entityManager.createQuery(criteriaQuery); typedQuery.setFirstResult(start); typedQuery.setMaxResults(pageSize+1); boolean hasMore = false; // Now query for the actual results List<T> resultList = typedQuery.getResultList(); // Check if we got back more than we actually needed. if (resultList.size() > pageSize) { resultList.remove(resultList.size() - 1); hasMore = true; } // If there are more results than we needed, then we will need to do another // query to determine how many rows there are in total int totalSize = start + resultList.size(); if (hasMore) { totalSize = executeCountQuery(criteria, entityManager, type); } results.setTotalSize(totalSize); results.setBeans(resultList); return results; } catch (Throwable t) { logger.error(t.getMessage(), t); throw new StorageException(t); } }
java
protected <T> SearchResultsBean<T> find(SearchCriteriaBean criteria, Class<T> type) throws StorageException { SearchResultsBean<T> results = new SearchResultsBean<>(); EntityManager entityManager = getActiveEntityManager(); try { // Set some default in the case that paging information was not included in the request. PagingBean paging = criteria.getPaging(); if (paging == null) { paging = new PagingBean(); paging.setPage(1); paging.setPageSize(20); } int page = paging.getPage(); int pageSize = paging.getPageSize(); int start = (page - 1) * pageSize; CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<T> criteriaQuery = builder.createQuery(type); Root<T> from = criteriaQuery.from(type); applySearchCriteriaToQuery(criteria, builder, criteriaQuery, from, false); TypedQuery<T> typedQuery = entityManager.createQuery(criteriaQuery); typedQuery.setFirstResult(start); typedQuery.setMaxResults(pageSize+1); boolean hasMore = false; // Now query for the actual results List<T> resultList = typedQuery.getResultList(); // Check if we got back more than we actually needed. if (resultList.size() > pageSize) { resultList.remove(resultList.size() - 1); hasMore = true; } // If there are more results than we needed, then we will need to do another // query to determine how many rows there are in total int totalSize = start + resultList.size(); if (hasMore) { totalSize = executeCountQuery(criteria, entityManager, type); } results.setTotalSize(totalSize); results.setBeans(resultList); return results; } catch (Throwable t) { logger.error(t.getMessage(), t); throw new StorageException(t); } }
[ "protected", "<", "T", ">", "SearchResultsBean", "<", "T", ">", "find", "(", "SearchCriteriaBean", "criteria", ",", "Class", "<", "T", ">", "type", ")", "throws", "StorageException", "{", "SearchResultsBean", "<", "T", ">", "results", "=", "new", "SearchResu...
Get a list of entities based on the provided criteria and entity type. @param criteria @param type @throws StorageException if a storage problem occurs while storing a bean
[ "Get", "a", "list", "of", "entities", "based", "on", "the", "provided", "criteria", "and", "entity", "type", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/AbstractJpaStorage.java#L259-L305
train
apiman/apiman
manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/AbstractJpaStorage.java
AbstractJpaStorage.executeCountQuery
protected <T> int executeCountQuery(SearchCriteriaBean criteria, EntityManager entityManager, Class<T> type) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> countQuery = builder.createQuery(Long.class); Root<T> from = countQuery.from(type); countQuery.select(builder.count(from)); applySearchCriteriaToQuery(criteria, builder, countQuery, from, true); TypedQuery<Long> query = entityManager.createQuery(countQuery); return query.getSingleResult().intValue(); }
java
protected <T> int executeCountQuery(SearchCriteriaBean criteria, EntityManager entityManager, Class<T> type) { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> countQuery = builder.createQuery(Long.class); Root<T> from = countQuery.from(type); countQuery.select(builder.count(from)); applySearchCriteriaToQuery(criteria, builder, countQuery, from, true); TypedQuery<Long> query = entityManager.createQuery(countQuery); return query.getSingleResult().intValue(); }
[ "protected", "<", "T", ">", "int", "executeCountQuery", "(", "SearchCriteriaBean", "criteria", ",", "EntityManager", "entityManager", ",", "Class", "<", "T", ">", "type", ")", "{", "CriteriaBuilder", "builder", "=", "entityManager", ".", "getCriteriaBuilder", "(",...
Gets a count of the number of rows that would be returned by the search. @param criteria @param entityManager @param type
[ "Gets", "a", "count", "of", "the", "number", "of", "rows", "that", "would", "be", "returned", "by", "the", "search", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/jpa/src/main/java/io/apiman/manager/api/jpa/AbstractJpaStorage.java#L313-L321
train
apiman/apiman
manager/api/security/src/main/java/io/apiman/manager/api/security/impl/IndexedPermissions.java
IndexedPermissions.hasQualifiedPermission
public boolean hasQualifiedPermission(PermissionType permissionName, String orgQualifier) { String key = createQualifiedPermissionKey(permissionName, orgQualifier); return qualifiedPermissions.contains(key); }
java
public boolean hasQualifiedPermission(PermissionType permissionName, String orgQualifier) { String key = createQualifiedPermissionKey(permissionName, orgQualifier); return qualifiedPermissions.contains(key); }
[ "public", "boolean", "hasQualifiedPermission", "(", "PermissionType", "permissionName", ",", "String", "orgQualifier", ")", "{", "String", "key", "=", "createQualifiedPermissionKey", "(", "permissionName", ",", "orgQualifier", ")", ";", "return", "qualifiedPermissions", ...
Returns true if the qualified permission exists. @param permissionName the permission name @param orgQualifier the org qualifier @return true if has qualified permission
[ "Returns", "true", "if", "the", "qualified", "permission", "exists", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/security/src/main/java/io/apiman/manager/api/security/impl/IndexedPermissions.java#L55-L58
train
apiman/apiman
manager/api/security/src/main/java/io/apiman/manager/api/security/impl/IndexedPermissions.java
IndexedPermissions.getOrgQualifiers
public Set<String> getOrgQualifiers(PermissionType permissionName) { Set<String> orgs = permissionToOrgsMap.get(permissionName); if (orgs == null) orgs = Collections.EMPTY_SET; return Collections.unmodifiableSet(orgs); }
java
public Set<String> getOrgQualifiers(PermissionType permissionName) { Set<String> orgs = permissionToOrgsMap.get(permissionName); if (orgs == null) orgs = Collections.EMPTY_SET; return Collections.unmodifiableSet(orgs); }
[ "public", "Set", "<", "String", ">", "getOrgQualifiers", "(", "PermissionType", "permissionName", ")", "{", "Set", "<", "String", ">", "orgs", "=", "permissionToOrgsMap", ".", "get", "(", "permissionName", ")", ";", "if", "(", "orgs", "==", "null", ")", "o...
Given a permission name, returns all organization qualifiers. @param permissionName the permission type @return set of org qualifiers
[ "Given", "a", "permission", "name", "returns", "all", "organization", "qualifiers", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/security/src/main/java/io/apiman/manager/api/security/impl/IndexedPermissions.java#L73-L78
train
apiman/apiman
manager/api/security/src/main/java/io/apiman/manager/api/security/impl/IndexedPermissions.java
IndexedPermissions.index
private void index(Set<PermissionBean> permissions) { for (PermissionBean permissionBean : permissions) { PermissionType permissionName = permissionBean.getName(); String orgQualifier = permissionBean.getOrganizationId(); String qualifiedPermission = createQualifiedPermissionKey(permissionName, orgQualifier); organizations.add(orgQualifier); qualifiedPermissions.add(qualifiedPermission); Set<String> orgs = permissionToOrgsMap.get(permissionName); if (orgs == null) { orgs = new HashSet<>(); permissionToOrgsMap.put(permissionName, orgs); } orgs.add(orgQualifier); } }
java
private void index(Set<PermissionBean> permissions) { for (PermissionBean permissionBean : permissions) { PermissionType permissionName = permissionBean.getName(); String orgQualifier = permissionBean.getOrganizationId(); String qualifiedPermission = createQualifiedPermissionKey(permissionName, orgQualifier); organizations.add(orgQualifier); qualifiedPermissions.add(qualifiedPermission); Set<String> orgs = permissionToOrgsMap.get(permissionName); if (orgs == null) { orgs = new HashSet<>(); permissionToOrgsMap.put(permissionName, orgs); } orgs.add(orgQualifier); } }
[ "private", "void", "index", "(", "Set", "<", "PermissionBean", ">", "permissions", ")", "{", "for", "(", "PermissionBean", "permissionBean", ":", "permissions", ")", "{", "PermissionType", "permissionName", "=", "permissionBean", ".", "getName", "(", ")", ";", ...
Index the permissions. @param bean
[ "Index", "the", "permissions", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/security/src/main/java/io/apiman/manager/api/security/impl/IndexedPermissions.java#L84-L98
train
apiman/apiman
manager/api/export-import/src/main/java/io/apiman/manager/api/exportimport/manager/ExportImportConfigParser.java
ExportImportConfigParser.isOverwrite
public boolean isOverwrite() { Boolean booleanObject = BooleanUtils.toBooleanObject(System.getProperty(OVERWRITE)); if (booleanObject == null) { booleanObject = Boolean.FALSE; } return booleanObject; }
java
public boolean isOverwrite() { Boolean booleanObject = BooleanUtils.toBooleanObject(System.getProperty(OVERWRITE)); if (booleanObject == null) { booleanObject = Boolean.FALSE; } return booleanObject; }
[ "public", "boolean", "isOverwrite", "(", ")", "{", "Boolean", "booleanObject", "=", "BooleanUtils", ".", "toBooleanObject", "(", "System", ".", "getProperty", "(", "OVERWRITE", ")", ")", ";", "if", "(", "booleanObject", "==", "null", ")", "{", "booleanObject",...
apiman.migrate.overwrite=
[ "apiman", ".", "migrate", ".", "overwrite", "=" ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/export-import/src/main/java/io/apiman/manager/api/exportimport/manager/ExportImportConfigParser.java#L101-L107
train
apiman/apiman
manager/api/export-import/src/main/java/io/apiman/manager/api/exportimport/manager/StorageImportDispatcher.java
StorageImportDispatcher.start
public void start() { logger.info("----------------------------"); //$NON-NLS-1$ logger.info(Messages.i18n.format("StorageImportDispatcher.StartingImport")); //$NON-NLS-1$ policyDefIndex.clear(); currentOrg = null; currentPlan = null; currentApi = null; currentClient = null; currentClientVersion = null; contracts.clear(); apisToPublish.clear(); clientsToRegister.clear(); gatewayLinkCache.clear(); try { this.storage.beginTx(); } catch (StorageException e) { throw new RuntimeException(e); } }
java
public void start() { logger.info("----------------------------"); //$NON-NLS-1$ logger.info(Messages.i18n.format("StorageImportDispatcher.StartingImport")); //$NON-NLS-1$ policyDefIndex.clear(); currentOrg = null; currentPlan = null; currentApi = null; currentClient = null; currentClientVersion = null; contracts.clear(); apisToPublish.clear(); clientsToRegister.clear(); gatewayLinkCache.clear(); try { this.storage.beginTx(); } catch (StorageException e) { throw new RuntimeException(e); } }
[ "public", "void", "start", "(", ")", "{", "logger", ".", "info", "(", "\"----------------------------\"", ")", ";", "//$NON-NLS-1$", "logger", ".", "info", "(", "Messages", ".", "i18n", ".", "format", "(", "\"StorageImportDispatcher.StartingImport\"", ")", ")", ...
Starts the import.
[ "Starts", "the", "import", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/export-import/src/main/java/io/apiman/manager/api/exportimport/manager/StorageImportDispatcher.java#L115-L135
train
apiman/apiman
manager/api/export-import/src/main/java/io/apiman/manager/api/exportimport/manager/StorageImportDispatcher.java
StorageImportDispatcher.updatePluginIdInPolicyDefinition
private PolicyDefinitionBean updatePluginIdInPolicyDefinition(PolicyDefinitionBean policyDef) { if (pluginBeanIdMap.containsKey(policyDef.getPluginId())){ try { Map.Entry<String, String> pluginCoordinates = pluginBeanIdMap.get(policyDef.getPluginId()); PluginBean plugin = storage.getPlugin(pluginCoordinates.getKey(), pluginCoordinates.getValue()); policyDef.setPluginId(plugin.getId()); } catch (StorageException e) { error(e); } } return policyDef; }
java
private PolicyDefinitionBean updatePluginIdInPolicyDefinition(PolicyDefinitionBean policyDef) { if (pluginBeanIdMap.containsKey(policyDef.getPluginId())){ try { Map.Entry<String, String> pluginCoordinates = pluginBeanIdMap.get(policyDef.getPluginId()); PluginBean plugin = storage.getPlugin(pluginCoordinates.getKey(), pluginCoordinates.getValue()); policyDef.setPluginId(plugin.getId()); } catch (StorageException e) { error(e); } } return policyDef; }
[ "private", "PolicyDefinitionBean", "updatePluginIdInPolicyDefinition", "(", "PolicyDefinitionBean", "policyDef", ")", "{", "if", "(", "pluginBeanIdMap", ".", "containsKey", "(", "policyDef", ".", "getPluginId", "(", ")", ")", ")", "{", "try", "{", "Map", ".", "Ent...
Update the pluginID in the policyDefinition to the new generated pluginID @param policyDef @return updated PolicyDefinitionBean policyDef
[ "Update", "the", "pluginID", "in", "the", "policyDefinition", "to", "the", "new", "generated", "pluginID" ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/export-import/src/main/java/io/apiman/manager/api/exportimport/manager/StorageImportDispatcher.java#L245-L256
train
apiman/apiman
manager/api/export-import/src/main/java/io/apiman/manager/api/exportimport/manager/StorageImportDispatcher.java
StorageImportDispatcher.publishApis
private void publishApis() throws StorageException { logger.info(Messages.i18n.format("StorageExporter.PublishingApis")); //$NON-NLS-1$ try { for (EntityInfo info : apisToPublish) { logger.info(Messages.i18n.format("StorageExporter.PublishingApi", info)); //$NON-NLS-1$ ApiVersionBean versionBean = storage.getApiVersion(info.organizationId, info.id, info.version); Api gatewayApi = new Api(); gatewayApi.setEndpoint(versionBean.getEndpoint()); gatewayApi.setEndpointType(versionBean.getEndpointType().toString()); gatewayApi.setEndpointProperties(versionBean.getEndpointProperties()); gatewayApi.setOrganizationId(versionBean.getApi().getOrganization().getId()); gatewayApi.setApiId(versionBean.getApi().getId()); gatewayApi.setVersion(versionBean.getVersion()); gatewayApi.setPublicAPI(versionBean.isPublicAPI()); gatewayApi.setParsePayload(versionBean.isParsePayload()); if (versionBean.isPublicAPI()) { List<Policy> policiesToPublish = new ArrayList<>(); Iterator<PolicyBean> apiPolicies = storage.getAllPolicies(info.organizationId, info.id, info.version, PolicyType.Api); while (apiPolicies.hasNext()) { PolicyBean apiPolicy = apiPolicies.next(); Policy policyToPublish = new Policy(); policyToPublish.setPolicyJsonConfig(apiPolicy.getConfiguration()); policyToPublish.setPolicyImpl(apiPolicy.getDefinition().getPolicyImpl()); policiesToPublish.add(policyToPublish); } gatewayApi.setApiPolicies(policiesToPublish); } // Publish the api to all relevant gateways Set<ApiGatewayBean> gateways = versionBean.getGateways(); if (gateways == null) { throw new RuntimeException("No gateways specified for api!"); //$NON-NLS-1$ } for (ApiGatewayBean apiGatewayBean : gateways) { IGatewayLink gatewayLink = createGatewayLink(apiGatewayBean.getGatewayId()); gatewayLink.publishApi(gatewayApi); } } } catch (Exception e) { throw new RuntimeException(e); } }
java
private void publishApis() throws StorageException { logger.info(Messages.i18n.format("StorageExporter.PublishingApis")); //$NON-NLS-1$ try { for (EntityInfo info : apisToPublish) { logger.info(Messages.i18n.format("StorageExporter.PublishingApi", info)); //$NON-NLS-1$ ApiVersionBean versionBean = storage.getApiVersion(info.organizationId, info.id, info.version); Api gatewayApi = new Api(); gatewayApi.setEndpoint(versionBean.getEndpoint()); gatewayApi.setEndpointType(versionBean.getEndpointType().toString()); gatewayApi.setEndpointProperties(versionBean.getEndpointProperties()); gatewayApi.setOrganizationId(versionBean.getApi().getOrganization().getId()); gatewayApi.setApiId(versionBean.getApi().getId()); gatewayApi.setVersion(versionBean.getVersion()); gatewayApi.setPublicAPI(versionBean.isPublicAPI()); gatewayApi.setParsePayload(versionBean.isParsePayload()); if (versionBean.isPublicAPI()) { List<Policy> policiesToPublish = new ArrayList<>(); Iterator<PolicyBean> apiPolicies = storage.getAllPolicies(info.organizationId, info.id, info.version, PolicyType.Api); while (apiPolicies.hasNext()) { PolicyBean apiPolicy = apiPolicies.next(); Policy policyToPublish = new Policy(); policyToPublish.setPolicyJsonConfig(apiPolicy.getConfiguration()); policyToPublish.setPolicyImpl(apiPolicy.getDefinition().getPolicyImpl()); policiesToPublish.add(policyToPublish); } gatewayApi.setApiPolicies(policiesToPublish); } // Publish the api to all relevant gateways Set<ApiGatewayBean> gateways = versionBean.getGateways(); if (gateways == null) { throw new RuntimeException("No gateways specified for api!"); //$NON-NLS-1$ } for (ApiGatewayBean apiGatewayBean : gateways) { IGatewayLink gatewayLink = createGatewayLink(apiGatewayBean.getGatewayId()); gatewayLink.publishApi(gatewayApi); } } } catch (Exception e) { throw new RuntimeException(e); } }
[ "private", "void", "publishApis", "(", ")", "throws", "StorageException", "{", "logger", ".", "info", "(", "Messages", ".", "i18n", ".", "format", "(", "\"StorageExporter.PublishingApis\"", ")", ")", ";", "//$NON-NLS-1$", "try", "{", "for", "(", "EntityInfo", ...
Publishes any apis that were imported in the "Published" state. @throws StorageException
[ "Publishes", "any", "apis", "that", "were", "imported", "in", "the", "Published", "state", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/export-import/src/main/java/io/apiman/manager/api/exportimport/manager/StorageImportDispatcher.java#L485-L529
train
apiman/apiman
manager/api/export-import/src/main/java/io/apiman/manager/api/exportimport/manager/StorageImportDispatcher.java
StorageImportDispatcher.aggregateContractPolicies
private List<Policy> aggregateContractPolicies(ContractBean contractBean, EntityInfo clientInfo) throws StorageException { List<Policy> policies = new ArrayList<>(); PolicyType [] types = new PolicyType[] { PolicyType.Client, PolicyType.Plan, PolicyType.Api }; for (PolicyType policyType : types) { String org, id, ver; switch (policyType) { case Client: { org = clientInfo.organizationId; id = clientInfo.id; ver = clientInfo.version; break; } case Plan: { org = contractBean.getApi().getApi().getOrganization().getId(); id = contractBean.getPlan().getPlan().getId(); ver = contractBean.getPlan().getVersion(); break; } case Api: { org = contractBean.getApi().getApi().getOrganization().getId(); id = contractBean.getApi().getApi().getId(); ver = contractBean.getApi().getVersion(); break; } default: { throw new RuntimeException("Missing case for switch!"); //$NON-NLS-1$ } } Iterator<PolicyBean> clientPolicies = storage.getAllPolicies(org, id, ver, policyType); while (clientPolicies.hasNext()) { PolicyBean policyBean = clientPolicies.next(); Policy policy = new Policy(); policy.setPolicyJsonConfig(policyBean.getConfiguration()); policy.setPolicyImpl(policyBean.getDefinition().getPolicyImpl()); policies.add(policy); } } return policies; }
java
private List<Policy> aggregateContractPolicies(ContractBean contractBean, EntityInfo clientInfo) throws StorageException { List<Policy> policies = new ArrayList<>(); PolicyType [] types = new PolicyType[] { PolicyType.Client, PolicyType.Plan, PolicyType.Api }; for (PolicyType policyType : types) { String org, id, ver; switch (policyType) { case Client: { org = clientInfo.organizationId; id = clientInfo.id; ver = clientInfo.version; break; } case Plan: { org = contractBean.getApi().getApi().getOrganization().getId(); id = contractBean.getPlan().getPlan().getId(); ver = contractBean.getPlan().getVersion(); break; } case Api: { org = contractBean.getApi().getApi().getOrganization().getId(); id = contractBean.getApi().getApi().getId(); ver = contractBean.getApi().getVersion(); break; } default: { throw new RuntimeException("Missing case for switch!"); //$NON-NLS-1$ } } Iterator<PolicyBean> clientPolicies = storage.getAllPolicies(org, id, ver, policyType); while (clientPolicies.hasNext()) { PolicyBean policyBean = clientPolicies.next(); Policy policy = new Policy(); policy.setPolicyJsonConfig(policyBean.getConfiguration()); policy.setPolicyImpl(policyBean.getDefinition().getPolicyImpl()); policies.add(policy); } } return policies; }
[ "private", "List", "<", "Policy", ">", "aggregateContractPolicies", "(", "ContractBean", "contractBean", ",", "EntityInfo", "clientInfo", ")", "throws", "StorageException", "{", "List", "<", "Policy", ">", "policies", "=", "new", "ArrayList", "<>", "(", ")", ";"...
Aggregates the api, client, and plan policies into a single ordered list. @param contractBean @param clientInfo
[ "Aggregates", "the", "api", "client", "and", "plan", "policies", "into", "a", "single", "ordered", "list", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/export-import/src/main/java/io/apiman/manager/api/exportimport/manager/StorageImportDispatcher.java#L601-L642
train
apiman/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/policy/PolicyFactoryImpl.java
PolicyFactoryImpl.doLoadFromClasspath
protected void doLoadFromClasspath(String policyImpl, IAsyncResultHandler<IPolicy> handler) { IPolicy rval; String classname = policyImpl.substring(6); Class<?> c = null; // First try a simple Class.forName() try { c = Class.forName(classname); } catch (ClassNotFoundException e) { } // Didn't work? Try using this class's classloader. if (c == null) { try { c = getClass().getClassLoader().loadClass(classname); } catch (ClassNotFoundException e) { } } // Still didn't work? Try the thread's context classloader. if (c == null) { try { c = Thread.currentThread().getContextClassLoader().loadClass(classname); } catch (ClassNotFoundException e) { } } if (c == null) { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(classname))); return; } try { rval = (IPolicy) c.newInstance(); } catch (InstantiationException | IllegalAccessException e) { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl, e))); return; } policyCache.put(policyImpl, rval); handler.handle(AsyncResultImpl.create(rval)); return; }
java
protected void doLoadFromClasspath(String policyImpl, IAsyncResultHandler<IPolicy> handler) { IPolicy rval; String classname = policyImpl.substring(6); Class<?> c = null; // First try a simple Class.forName() try { c = Class.forName(classname); } catch (ClassNotFoundException e) { } // Didn't work? Try using this class's classloader. if (c == null) { try { c = getClass().getClassLoader().loadClass(classname); } catch (ClassNotFoundException e) { } } // Still didn't work? Try the thread's context classloader. if (c == null) { try { c = Thread.currentThread().getContextClassLoader().loadClass(classname); } catch (ClassNotFoundException e) { } } if (c == null) { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(classname))); return; } try { rval = (IPolicy) c.newInstance(); } catch (InstantiationException | IllegalAccessException e) { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl, e))); return; } policyCache.put(policyImpl, rval); handler.handle(AsyncResultImpl.create(rval)); return; }
[ "protected", "void", "doLoadFromClasspath", "(", "String", "policyImpl", ",", "IAsyncResultHandler", "<", "IPolicy", ">", "handler", ")", "{", "IPolicy", "rval", ";", "String", "classname", "=", "policyImpl", ".", "substring", "(", "6", ")", ";", "Class", "<",...
Loads a policy from a class on the classpath. @param policyImpl @param handler
[ "Loads", "a", "policy", "from", "a", "class", "on", "the", "classpath", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/policy/PolicyFactoryImpl.java#L115-L145
train
apiman/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/policy/PolicyFactoryImpl.java
PolicyFactoryImpl.doLoadFromPlugin
private void doLoadFromPlugin(final String policyImpl, final IAsyncResultHandler<IPolicy> handler) { PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(policyImpl); if (coordinates == null) { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl))); return; } int ssidx = policyImpl.indexOf('/'); if (ssidx == -1) { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl))); return; } final String classname = policyImpl.substring(ssidx + 1); this.pluginRegistry.loadPlugin(coordinates, new IAsyncResultHandler<Plugin>() { @Override public void handle(IAsyncResult<Plugin> result) { if (result.isSuccess()) { IPolicy rval; Plugin plugin = result.getResult(); PluginClassLoader pluginClassLoader = plugin.getLoader(); ClassLoader oldCtxLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(pluginClassLoader); Class<?> c = pluginClassLoader.loadClass(classname); rval = (IPolicy) c.newInstance(); } catch (Exception e) { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl, e))); return; } finally { Thread.currentThread().setContextClassLoader(oldCtxLoader); } policyCache.put(policyImpl, rval); handler.handle(AsyncResultImpl.create(rval)); } else { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl, result.getError()))); } } }); }
java
private void doLoadFromPlugin(final String policyImpl, final IAsyncResultHandler<IPolicy> handler) { PluginCoordinates coordinates = PluginCoordinates.fromPolicySpec(policyImpl); if (coordinates == null) { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl))); return; } int ssidx = policyImpl.indexOf('/'); if (ssidx == -1) { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl))); return; } final String classname = policyImpl.substring(ssidx + 1); this.pluginRegistry.loadPlugin(coordinates, new IAsyncResultHandler<Plugin>() { @Override public void handle(IAsyncResult<Plugin> result) { if (result.isSuccess()) { IPolicy rval; Plugin plugin = result.getResult(); PluginClassLoader pluginClassLoader = plugin.getLoader(); ClassLoader oldCtxLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(pluginClassLoader); Class<?> c = pluginClassLoader.loadClass(classname); rval = (IPolicy) c.newInstance(); } catch (Exception e) { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl, e))); return; } finally { Thread.currentThread().setContextClassLoader(oldCtxLoader); } policyCache.put(policyImpl, rval); handler.handle(AsyncResultImpl.create(rval)); } else { handler.handle(AsyncResultImpl.<IPolicy>create(new PolicyNotFoundException(policyImpl, result.getError()))); } } }); }
[ "private", "void", "doLoadFromPlugin", "(", "final", "String", "policyImpl", ",", "final", "IAsyncResultHandler", "<", "IPolicy", ">", "handler", ")", "{", "PluginCoordinates", "coordinates", "=", "PluginCoordinates", ".", "fromPolicySpec", "(", "policyImpl", ")", "...
Loads a policy from a plugin. @param policyImpl @param handler
[ "Loads", "a", "policy", "from", "a", "plugin", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/policy/PolicyFactoryImpl.java#L152-L190
train
apiman/apiman
gateway/engine/ispn/src/main/java/io/apiman/gateway/engine/ispn/io/RegistryCacheMapWrapper.java
RegistryCacheMapWrapper.unmarshalAs
private <T> T unmarshalAs(String valueAsString, Class<T> asClass) throws IOException { return mapper.reader(asClass).readValue(valueAsString); }
java
private <T> T unmarshalAs(String valueAsString, Class<T> asClass) throws IOException { return mapper.reader(asClass).readValue(valueAsString); }
[ "private", "<", "T", ">", "T", "unmarshalAs", "(", "String", "valueAsString", ",", "Class", "<", "T", ">", "asClass", ")", "throws", "IOException", "{", "return", "mapper", ".", "reader", "(", "asClass", ")", ".", "readValue", "(", "valueAsString", ")", ...
Unmarshall the given type of object. @param valueAsString @param asClass @throws IOException
[ "Unmarshall", "the", "given", "type", "of", "object", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/ispn/src/main/java/io/apiman/gateway/engine/ispn/io/RegistryCacheMapWrapper.java#L188-L190
train
apiman/apiman
gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/AbstractMappedPolicy.java
AbstractMappedPolicy.doApply
protected void doApply(ApiResponse response, IPolicyContext context, C config, IPolicyChain<ApiResponse> chain) { chain.doApply(response); }
java
protected void doApply(ApiResponse response, IPolicyContext context, C config, IPolicyChain<ApiResponse> chain) { chain.doApply(response); }
[ "protected", "void", "doApply", "(", "ApiResponse", "response", ",", "IPolicyContext", "context", ",", "C", "config", ",", "IPolicyChain", "<", "ApiResponse", ">", "chain", ")", "{", "chain", ".", "doApply", "(", "response", ")", ";", "}" ]
Apply the policy to the response. @param response @param context @param config @param chain
[ "Apply", "the", "policy", "to", "the", "response", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/AbstractMappedPolicy.java#L101-L103
train
apiman/apiman
gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/AbstractMappedPolicy.java
AbstractMappedPolicy.doProcessFailure
protected void doProcessFailure(PolicyFailure failure, IPolicyContext context, C config, IPolicyFailureChain chain) { chain.doFailure(failure); }
java
protected void doProcessFailure(PolicyFailure failure, IPolicyContext context, C config, IPolicyFailureChain chain) { chain.doFailure(failure); }
[ "protected", "void", "doProcessFailure", "(", "PolicyFailure", "failure", ",", "IPolicyContext", "context", ",", "C", "config", ",", "IPolicyFailureChain", "chain", ")", "{", "chain", ".", "doFailure", "(", "failure", ")", ";", "}" ]
Override if you wish to modify a failure. @see IPolicy#processFailure(PolicyFailure, IPolicyContext, Object)
[ "Override", "if", "you", "wish", "to", "modify", "a", "failure", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/AbstractMappedPolicy.java#L116-L118
train
apiman/apiman
manager/api/micro/src/main/java/io/apiman/manager/api/micro/ManagerApiMicroService.java
ManagerApiMicroService.createSecurityHandler
protected SecurityHandler createSecurityHandler() throws Exception { HashLoginService l = new HashLoginService(); // UserStore is now separate store entity and must be added to HashLoginService UserStore userStore = new UserStore(); l.setUserStore(userStore); for (User user : Users.getUsers()) { userStore.addUser(user.getId(), Credential.getCredential(user.getPassword()), user.getRolesAsArray()); } l.setName("apimanrealm"); ConstraintSecurityHandler csh = new ConstraintSecurityHandler(); csh.setAuthenticator(new BasicAuthenticator()); csh.setRealmName("apimanrealm"); csh.setLoginService(l); return csh; }
java
protected SecurityHandler createSecurityHandler() throws Exception { HashLoginService l = new HashLoginService(); // UserStore is now separate store entity and must be added to HashLoginService UserStore userStore = new UserStore(); l.setUserStore(userStore); for (User user : Users.getUsers()) { userStore.addUser(user.getId(), Credential.getCredential(user.getPassword()), user.getRolesAsArray()); } l.setName("apimanrealm"); ConstraintSecurityHandler csh = new ConstraintSecurityHandler(); csh.setAuthenticator(new BasicAuthenticator()); csh.setRealmName("apimanrealm"); csh.setLoginService(l); return csh; }
[ "protected", "SecurityHandler", "createSecurityHandler", "(", ")", "throws", "Exception", "{", "HashLoginService", "l", "=", "new", "HashLoginService", "(", ")", ";", "// UserStore is now separate store entity and must be added to HashLoginService", "UserStore", "userStore", "=...
Creates a basic auth security handler. @throws Exception
[ "Creates", "a", "basic", "auth", "security", "handler", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/micro/src/main/java/io/apiman/manager/api/micro/ManagerApiMicroService.java#L217-L233
train
apiman/apiman
manager/api/hawkular/src/main/java/io/apiman/manager/api/hawkular/HawkularMetricsAccessor.java
HawkularMetricsAccessor.bucketSizeFromInterval
private static BucketSizeType bucketSizeFromInterval(HistogramIntervalType interval) { BucketSizeType bucketSize; switch (interval) { case minute: bucketSize = BucketSizeType.Minute; break; case hour: bucketSize = BucketSizeType.Hour; break; case day: bucketSize = BucketSizeType.Day; break; case week: bucketSize = BucketSizeType.Week; break; case month: bucketSize = BucketSizeType.Month; break; default: bucketSize = BucketSizeType.Day; break; } return bucketSize; }
java
private static BucketSizeType bucketSizeFromInterval(HistogramIntervalType interval) { BucketSizeType bucketSize; switch (interval) { case minute: bucketSize = BucketSizeType.Minute; break; case hour: bucketSize = BucketSizeType.Hour; break; case day: bucketSize = BucketSizeType.Day; break; case week: bucketSize = BucketSizeType.Week; break; case month: bucketSize = BucketSizeType.Month; break; default: bucketSize = BucketSizeType.Day; break; } return bucketSize; }
[ "private", "static", "BucketSizeType", "bucketSizeFromInterval", "(", "HistogramIntervalType", "interval", ")", "{", "BucketSizeType", "bucketSize", ";", "switch", "(", "interval", ")", "{", "case", "minute", ":", "bucketSize", "=", "BucketSizeType", ".", "Minute", ...
Converts an interval into a bucket size. @param interval
[ "Converts", "an", "interval", "into", "a", "bucket", "size", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/hawkular/src/main/java/io/apiman/manager/api/hawkular/HawkularMetricsAccessor.java#L313-L336
train
apiman/apiman
gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/JdbcInitializer.java
JdbcInitializer.doInit
@SuppressWarnings("nls") private void doInit() { QueryRunner run = new QueryRunner(ds); Boolean isInitialized; try { isInitialized = run.query("SELECT * FROM gw_apis", new ResultSetHandler<Boolean>() { @Override public Boolean handle(ResultSet rs) throws SQLException { return true; } }); } catch (SQLException e) { isInitialized = false; } if (isInitialized) { System.out.println("============================================"); System.out.println("Apiman Gateway database already initialized."); System.out.println("============================================"); return; } ClassLoader cl = JdbcInitializer.class.getClassLoader(); URL resource = cl.getResource("ddls/apiman-gateway_" + dbType + ".ddl"); try (InputStream is = resource.openStream()) { System.out.println("======================================="); System.out.println("Initializing apiman Gateway database."); DdlParser ddlParser = new DdlParser(); List<String> statements = ddlParser.parse(is); for (String sql : statements){ System.out.println(sql); run.update(sql); } System.out.println("======================================="); } catch (Exception e) { throw new RuntimeException(e); } }
java
@SuppressWarnings("nls") private void doInit() { QueryRunner run = new QueryRunner(ds); Boolean isInitialized; try { isInitialized = run.query("SELECT * FROM gw_apis", new ResultSetHandler<Boolean>() { @Override public Boolean handle(ResultSet rs) throws SQLException { return true; } }); } catch (SQLException e) { isInitialized = false; } if (isInitialized) { System.out.println("============================================"); System.out.println("Apiman Gateway database already initialized."); System.out.println("============================================"); return; } ClassLoader cl = JdbcInitializer.class.getClassLoader(); URL resource = cl.getResource("ddls/apiman-gateway_" + dbType + ".ddl"); try (InputStream is = resource.openStream()) { System.out.println("======================================="); System.out.println("Initializing apiman Gateway database."); DdlParser ddlParser = new DdlParser(); List<String> statements = ddlParser.parse(is); for (String sql : statements){ System.out.println(sql); run.update(sql); } System.out.println("======================================="); } catch (Exception e) { throw new RuntimeException(e); } }
[ "@", "SuppressWarnings", "(", "\"nls\"", ")", "private", "void", "doInit", "(", ")", "{", "QueryRunner", "run", "=", "new", "QueryRunner", "(", "ds", ")", ";", "Boolean", "isInitialized", ";", "try", "{", "isInitialized", "=", "run", ".", "query", "(", "...
Do the initialization work.
[ "Do", "the", "initialization", "work", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/JdbcInitializer.java#L72-L110
train
apiman/apiman
gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/IgnoredResourcesPolicy.java
IgnoredResourcesPolicy.satisfiesAnyPath
private boolean satisfiesAnyPath(IgnoredResourcesConfig config, String destination, String verb) { if (destination == null || destination.trim().length() == 0) { destination = "/"; //$NON-NLS-1$ } for (IgnoredResource resource : config.getRules()) { String resourceVerb = resource.getVerb(); boolean verbMatches = verb == null || IgnoredResource.VERB_MATCH_ALL.equals(resourceVerb) || verb.equalsIgnoreCase(resourceVerb); // $NON-NLS-1$ boolean destinationMatches = destination.matches(resource.getPathPattern()); if (verbMatches && destinationMatches) { return true; } } return false; }
java
private boolean satisfiesAnyPath(IgnoredResourcesConfig config, String destination, String verb) { if (destination == null || destination.trim().length() == 0) { destination = "/"; //$NON-NLS-1$ } for (IgnoredResource resource : config.getRules()) { String resourceVerb = resource.getVerb(); boolean verbMatches = verb == null || IgnoredResource.VERB_MATCH_ALL.equals(resourceVerb) || verb.equalsIgnoreCase(resourceVerb); // $NON-NLS-1$ boolean destinationMatches = destination.matches(resource.getPathPattern()); if (verbMatches && destinationMatches) { return true; } } return false; }
[ "private", "boolean", "satisfiesAnyPath", "(", "IgnoredResourcesConfig", "config", ",", "String", "destination", ",", "String", "verb", ")", "{", "if", "(", "destination", "==", "null", "||", "destination", ".", "trim", "(", ")", ".", "length", "(", ")", "==...
Evaluates whether the destination provided matches any of the configured rules @param config The {@link IgnoredResourcesConfig} containing the rules @param destination The destination to evaluate @param verb HTTP verb or '*' for all verbs @return true if any path matches the destination. false otherwise
[ "Evaluates", "whether", "the", "destination", "provided", "matches", "any", "of", "the", "configured", "rules" ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/IgnoredResourcesPolicy.java#L85-L99
train
apiman/apiman
manager/api/gateway/src/main/java/io/apiman/manager/api/gateway/rest/GatewayClient.java
GatewayClient.readPublishingException
private PublishingException readPublishingException(HttpResponse response) { InputStream is = null; PublishingException exception; try { is = response.getEntity().getContent(); GatewayApiErrorBean error = mapper.reader(GatewayApiErrorBean.class).readValue(is); exception = new PublishingException(error.getMessage()); StackTraceElement[] stack = parseStackTrace(error.getStacktrace()); if (stack != null) { exception.setStackTrace(stack); } } catch (Exception e) { exception = new PublishingException(e.getMessage(), e); } finally { IOUtils.closeQuietly(is); } return exception; }
java
private PublishingException readPublishingException(HttpResponse response) { InputStream is = null; PublishingException exception; try { is = response.getEntity().getContent(); GatewayApiErrorBean error = mapper.reader(GatewayApiErrorBean.class).readValue(is); exception = new PublishingException(error.getMessage()); StackTraceElement[] stack = parseStackTrace(error.getStacktrace()); if (stack != null) { exception.setStackTrace(stack); } } catch (Exception e) { exception = new PublishingException(e.getMessage(), e); } finally { IOUtils.closeQuietly(is); } return exception; }
[ "private", "PublishingException", "readPublishingException", "(", "HttpResponse", "response", ")", "{", "InputStream", "is", "=", "null", ";", "PublishingException", "exception", ";", "try", "{", "is", "=", "response", ".", "getEntity", "(", ")", ".", "getContent"...
Reads a publishing exception from the response. @param response
[ "Reads", "a", "publishing", "exception", "from", "the", "response", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/gateway/src/main/java/io/apiman/manager/api/gateway/rest/GatewayClient.java#L263-L280
train
apiman/apiman
manager/api/gateway/src/main/java/io/apiman/manager/api/gateway/rest/GatewayClient.java
GatewayClient.parseStackTrace
protected static StackTraceElement[] parseStackTrace(String stacktrace) { try (BufferedReader reader = new BufferedReader(new StringReader(stacktrace))) { List<StackTraceElement> elements = new ArrayList<>(); String line; // Example lines: // \tat io.apiman.gateway.engine.es.ESRegistry$1.completed(ESRegistry.java:79) // \tat org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:81)\r\n while ( (line = reader.readLine()) != null) { if (line.startsWith("\tat ")) { //$NON-NLS-1$ int openParenIdx = line.indexOf('('); int closeParenIdx = line.indexOf(')'); String classAndMethod = line.substring(4, openParenIdx); String fileAndLineNum = line.substring(openParenIdx + 1, closeParenIdx); String className = classAndMethod.substring(0, classAndMethod.lastIndexOf('.')); String methodName = classAndMethod.substring(classAndMethod.lastIndexOf('.') + 1); String [] split = fileAndLineNum.split(":"); //$NON-NLS-1$ if (split.length == 1) { elements.add(new StackTraceElement(className, methodName, fileAndLineNum, -1)); } else { String fileName = split[0]; String lineNum = split[1]; elements.add(new StackTraceElement(className, methodName, fileName, new Integer(lineNum))); } } } return elements.toArray(new StackTraceElement[elements.size()]); } catch (Exception e) { e.printStackTrace(); return null; } }
java
protected static StackTraceElement[] parseStackTrace(String stacktrace) { try (BufferedReader reader = new BufferedReader(new StringReader(stacktrace))) { List<StackTraceElement> elements = new ArrayList<>(); String line; // Example lines: // \tat io.apiman.gateway.engine.es.ESRegistry$1.completed(ESRegistry.java:79) // \tat org.apache.http.impl.nio.client.InternalIODispatch.onInputReady(InternalIODispatch.java:81)\r\n while ( (line = reader.readLine()) != null) { if (line.startsWith("\tat ")) { //$NON-NLS-1$ int openParenIdx = line.indexOf('('); int closeParenIdx = line.indexOf(')'); String classAndMethod = line.substring(4, openParenIdx); String fileAndLineNum = line.substring(openParenIdx + 1, closeParenIdx); String className = classAndMethod.substring(0, classAndMethod.lastIndexOf('.')); String methodName = classAndMethod.substring(classAndMethod.lastIndexOf('.') + 1); String [] split = fileAndLineNum.split(":"); //$NON-NLS-1$ if (split.length == 1) { elements.add(new StackTraceElement(className, methodName, fileAndLineNum, -1)); } else { String fileName = split[0]; String lineNum = split[1]; elements.add(new StackTraceElement(className, methodName, fileName, new Integer(lineNum))); } } } return elements.toArray(new StackTraceElement[elements.size()]); } catch (Exception e) { e.printStackTrace(); return null; } }
[ "protected", "static", "StackTraceElement", "[", "]", "parseStackTrace", "(", "String", "stacktrace", ")", "{", "try", "(", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "StringReader", "(", "stacktrace", ")", ")", ")", "{", "List", "<"...
Parses a stack trace from the given string. @param stacktrace
[ "Parses", "a", "stack", "trace", "from", "the", "given", "string", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/gateway/src/main/java/io/apiman/manager/api/gateway/rest/GatewayClient.java#L309-L339
train
apiman/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/DefaultComponentRegistry.java
DefaultComponentRegistry.addComponent
protected <T extends IComponent> void addComponent(Class<T> componentType, T component) { components.put(componentType, component); }
java
protected <T extends IComponent> void addComponent(Class<T> componentType, T component) { components.put(componentType, component); }
[ "protected", "<", "T", "extends", "IComponent", ">", "void", "addComponent", "(", "Class", "<", "T", ">", "componentType", ",", "T", "component", ")", "{", "components", ".", "put", "(", "componentType", ",", "component", ")", ";", "}" ]
Adds a component to the registry. @param componentType @param component
[ "Adds", "a", "component", "to", "the", "registry", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/DefaultComponentRegistry.java#L107-L109
train
apiman/apiman
gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/Starter.java
Starter.main
public static final void main(String [] args) throws Exception { GatewayMicroService microService = new GatewayMicroService(); microService.start(); microService.join(); }
java
public static final void main(String [] args) throws Exception { GatewayMicroService microService = new GatewayMicroService(); microService.start(); microService.join(); }
[ "public", "static", "final", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "GatewayMicroService", "microService", "=", "new", "GatewayMicroService", "(", ")", ";", "microService", ".", "start", "(", ")", ";", "microService",...
Main entry point for the API Gateway micro service. @param args the arguments @throws Exception when any unhandled exception occurs
[ "Main", "entry", "point", "for", "the", "API", "Gateway", "micro", "service", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/Starter.java#L32-L36
train
apiman/apiman
gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/connector/ConnectorFactory.java
ConnectorFactory.createConnector
@Override public IApiConnector createConnector(ApiRequest req, Api api, RequiredAuthType authType, boolean hasDataPolicy, IConnectorConfig connectorConfig) { return (request, resultHandler) -> { // Apply options from config as our base case ApimanHttpConnectorOptions httpOptions = new ApimanHttpConnectorOptions(config) .setHasDataPolicy(hasDataPolicy) .setRequiredAuthType(authType) .setTlsOptions(tlsOptions) .setUri(parseApiEndpoint(api)) .setSsl(api.getEndpoint().toLowerCase().startsWith("https")); //$NON-NLS-1$ // If API has endpoint properties indicating timeouts, then override config. setAttributesFromApiEndpointProperties(api, httpOptions); // Get from cache HttpClient client = clientFromCache(httpOptions); return new HttpConnector(vertx, client, request, api, httpOptions, connectorConfig, resultHandler).connect(); }; }
java
@Override public IApiConnector createConnector(ApiRequest req, Api api, RequiredAuthType authType, boolean hasDataPolicy, IConnectorConfig connectorConfig) { return (request, resultHandler) -> { // Apply options from config as our base case ApimanHttpConnectorOptions httpOptions = new ApimanHttpConnectorOptions(config) .setHasDataPolicy(hasDataPolicy) .setRequiredAuthType(authType) .setTlsOptions(tlsOptions) .setUri(parseApiEndpoint(api)) .setSsl(api.getEndpoint().toLowerCase().startsWith("https")); //$NON-NLS-1$ // If API has endpoint properties indicating timeouts, then override config. setAttributesFromApiEndpointProperties(api, httpOptions); // Get from cache HttpClient client = clientFromCache(httpOptions); return new HttpConnector(vertx, client, request, api, httpOptions, connectorConfig, resultHandler).connect(); }; }
[ "@", "Override", "public", "IApiConnector", "createConnector", "(", "ApiRequest", "req", ",", "Api", "api", ",", "RequiredAuthType", "authType", ",", "boolean", "hasDataPolicy", ",", "IConnectorConfig", "connectorConfig", ")", "{", "return", "(", "request", ",", "...
In the future we can switch to different back-end implementations here!
[ "In", "the", "future", "we", "can", "switch", "to", "different", "back", "-", "end", "implementations", "here!" ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/connector/ConnectorFactory.java#L87-L103
train
apiman/apiman
gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/connector/ConnectorFactory.java
ConnectorFactory.setAttributesFromApiEndpointProperties
private void setAttributesFromApiEndpointProperties(Api api, ApimanHttpConnectorOptions options) { try { Map<String, String> endpointProperties = api.getEndpointProperties(); if (endpointProperties.containsKey("timeouts.read")) { //$NON-NLS-1$ int connectTimeoutMs = Integer.parseInt(endpointProperties.get("timeouts.read")); //$NON-NLS-1$ options.setRequestTimeout(connectTimeoutMs); } if (endpointProperties.containsKey("timeouts.connect")) { //$NON-NLS-1$ int connectTimeoutMs = Integer.parseInt(endpointProperties.get("timeouts.connect")); //$NON-NLS-1$ options.setConnectionTimeout(connectTimeoutMs); } } catch (NumberFormatException e) { throw new RuntimeException(e); } }
java
private void setAttributesFromApiEndpointProperties(Api api, ApimanHttpConnectorOptions options) { try { Map<String, String> endpointProperties = api.getEndpointProperties(); if (endpointProperties.containsKey("timeouts.read")) { //$NON-NLS-1$ int connectTimeoutMs = Integer.parseInt(endpointProperties.get("timeouts.read")); //$NON-NLS-1$ options.setRequestTimeout(connectTimeoutMs); } if (endpointProperties.containsKey("timeouts.connect")) { //$NON-NLS-1$ int connectTimeoutMs = Integer.parseInt(endpointProperties.get("timeouts.connect")); //$NON-NLS-1$ options.setConnectionTimeout(connectTimeoutMs); } } catch (NumberFormatException e) { throw new RuntimeException(e); } }
[ "private", "void", "setAttributesFromApiEndpointProperties", "(", "Api", "api", ",", "ApimanHttpConnectorOptions", "options", ")", "{", "try", "{", "Map", "<", "String", ",", "String", ">", "endpointProperties", "=", "api", ".", "getEndpointProperties", "(", ")", ...
If the endpoint properties includes a read timeout override, then set it here. @param connection
[ "If", "the", "endpoint", "properties", "includes", "a", "read", "timeout", "override", "then", "set", "it", "here", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/vertx3/vertx3/src/main/java/io/apiman/gateway/platforms/vertx3/connector/ConnectorFactory.java#L126-L140
train
apiman/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/ConfigDrivenComponentRegistry.java
ConfigDrivenComponentRegistry.createAndRegisterComponent
public <T extends IComponent> T createAndRegisterComponent(Class<T> componentType) throws ComponentNotFoundException { try { synchronized (components) { Class<? extends T> componentClass = engineConfig.getComponentClass(componentType, pluginRegistry); Map<String, String> componentConfig = engineConfig.getComponentConfig(componentType); T component = create(componentClass, componentConfig); components.put(componentType, component); // Because components are lazily created, we need to initialize them here // if necessary. DependsOnComponents annotation = componentClass.getAnnotation(DependsOnComponents.class); if (annotation != null) { Class<? extends IComponent>[] value = annotation.value(); for (Class<? extends IComponent> theC : value) { Method setter = ReflectionUtils.findSetter(componentClass, theC); if (setter != null) { IComponent injectedComponent = getComponent(theC); try { setter.invoke(component, new Object[] { injectedComponent }); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } } } if (component instanceof IRequiresInitialization) { ((IRequiresInitialization) component).initialize(); } return component; } } catch (Exception e) { throw new ComponentNotFoundException(componentType.getName()); } }
java
public <T extends IComponent> T createAndRegisterComponent(Class<T> componentType) throws ComponentNotFoundException { try { synchronized (components) { Class<? extends T> componentClass = engineConfig.getComponentClass(componentType, pluginRegistry); Map<String, String> componentConfig = engineConfig.getComponentConfig(componentType); T component = create(componentClass, componentConfig); components.put(componentType, component); // Because components are lazily created, we need to initialize them here // if necessary. DependsOnComponents annotation = componentClass.getAnnotation(DependsOnComponents.class); if (annotation != null) { Class<? extends IComponent>[] value = annotation.value(); for (Class<? extends IComponent> theC : value) { Method setter = ReflectionUtils.findSetter(componentClass, theC); if (setter != null) { IComponent injectedComponent = getComponent(theC); try { setter.invoke(component, new Object[] { injectedComponent }); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } } } if (component instanceof IRequiresInitialization) { ((IRequiresInitialization) component).initialize(); } return component; } } catch (Exception e) { throw new ComponentNotFoundException(componentType.getName()); } }
[ "public", "<", "T", "extends", "IComponent", ">", "T", "createAndRegisterComponent", "(", "Class", "<", "T", ">", "componentType", ")", "throws", "ComponentNotFoundException", "{", "try", "{", "synchronized", "(", "components", ")", "{", "Class", "<", "?", "ex...
Creates the component and registers it in the registry. @param componentType the component type @return the component @throws ComponentNotFoundException when a policy tries to get a component from the context but the component doesn't exist or is otherwise not available.
[ "Creates", "the", "component", "and", "registers", "it", "in", "the", "registry", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/ConfigDrivenComponentRegistry.java#L83-L118
train
apiman/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/ConfigDrivenComponentRegistry.java
ConfigDrivenComponentRegistry.addComponentMapping
protected void addComponentMapping(Class<? extends IComponent> klazz, IComponent component) { components.put(klazz, component); }
java
protected void addComponentMapping(Class<? extends IComponent> klazz, IComponent component) { components.put(klazz, component); }
[ "protected", "void", "addComponentMapping", "(", "Class", "<", "?", "extends", "IComponent", ">", "klazz", ",", "IComponent", "component", ")", "{", "components", ".", "put", "(", "klazz", ",", "component", ")", ";", "}" ]
Add a component that may have been instantiated elsewhere. @param klazz component class @param component instantiated component of same class
[ "Add", "a", "component", "that", "may", "have", "been", "instantiated", "elsewhere", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/ConfigDrivenComponentRegistry.java#L125-L127
train
apiman/apiman
gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java
GatewayMicroService.registerRateLimiterComponent
protected void registerRateLimiterComponent() { String componentPropName = GatewayConfigProperties.COMPONENT_PREFIX + IRateLimiterComponent.class.getSimpleName(); setConfigProperty(componentPropName, ESRateLimiterComponent.class.getName()); setConfigProperty(componentPropName + ".client.type", "jest"); setConfigProperty(componentPropName + ".client.protocol", "${apiman.es.protocol}"); setConfigProperty(componentPropName + ".client.host", "${apiman.es.host}"); setConfigProperty(componentPropName + ".client.port", "${apiman.es.port}"); setConfigProperty(componentPropName + ".client.username", "${apiman.es.username}"); setConfigProperty(componentPropName + ".client.password", "${apiman.es.password}"); }
java
protected void registerRateLimiterComponent() { String componentPropName = GatewayConfigProperties.COMPONENT_PREFIX + IRateLimiterComponent.class.getSimpleName(); setConfigProperty(componentPropName, ESRateLimiterComponent.class.getName()); setConfigProperty(componentPropName + ".client.type", "jest"); setConfigProperty(componentPropName + ".client.protocol", "${apiman.es.protocol}"); setConfigProperty(componentPropName + ".client.host", "${apiman.es.host}"); setConfigProperty(componentPropName + ".client.port", "${apiman.es.port}"); setConfigProperty(componentPropName + ".client.username", "${apiman.es.username}"); setConfigProperty(componentPropName + ".client.password", "${apiman.es.password}"); }
[ "protected", "void", "registerRateLimiterComponent", "(", ")", "{", "String", "componentPropName", "=", "GatewayConfigProperties", ".", "COMPONENT_PREFIX", "+", "IRateLimiterComponent", ".", "class", ".", "getSimpleName", "(", ")", ";", "setConfigProperty", "(", "compon...
The rate limiter component.
[ "The", "rate", "limiter", "component", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java#L142-L152
train
apiman/apiman
gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java
GatewayMicroService.registerSharedStateComponent
protected void registerSharedStateComponent() { String componentPropName = GatewayConfigProperties.COMPONENT_PREFIX + ISharedStateComponent.class.getSimpleName(); setConfigProperty(componentPropName, ESSharedStateComponent.class.getName()); setConfigProperty(componentPropName + ".client.type", "jest"); setConfigProperty(componentPropName + ".client.protocol", "${apiman.es.protocol}"); setConfigProperty(componentPropName + ".client.host", "${apiman.es.host}"); setConfigProperty(componentPropName + ".client.port", "${apiman.es.port}"); setConfigProperty(componentPropName + ".client.username", "${apiman.es.username}"); setConfigProperty(componentPropName + ".client.password", "${apiman.es.password}"); }
java
protected void registerSharedStateComponent() { String componentPropName = GatewayConfigProperties.COMPONENT_PREFIX + ISharedStateComponent.class.getSimpleName(); setConfigProperty(componentPropName, ESSharedStateComponent.class.getName()); setConfigProperty(componentPropName + ".client.type", "jest"); setConfigProperty(componentPropName + ".client.protocol", "${apiman.es.protocol}"); setConfigProperty(componentPropName + ".client.host", "${apiman.es.host}"); setConfigProperty(componentPropName + ".client.port", "${apiman.es.port}"); setConfigProperty(componentPropName + ".client.username", "${apiman.es.username}"); setConfigProperty(componentPropName + ".client.password", "${apiman.es.password}"); }
[ "protected", "void", "registerSharedStateComponent", "(", ")", "{", "String", "componentPropName", "=", "GatewayConfigProperties", ".", "COMPONENT_PREFIX", "+", "ISharedStateComponent", ".", "class", ".", "getSimpleName", "(", ")", ";", "setConfigProperty", "(", "compon...
The shared state component.
[ "The", "shared", "state", "component", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java#L157-L167
train
apiman/apiman
gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java
GatewayMicroService.registerCacheStoreComponent
protected void registerCacheStoreComponent() { String componentPropName = GatewayConfigProperties.COMPONENT_PREFIX + ICacheStoreComponent.class.getSimpleName(); setConfigProperty(componentPropName, ESCacheStoreComponent.class.getName()); setConfigProperty(componentPropName + ".client.type", "jest"); setConfigProperty(componentPropName + ".client.protocol", "${apiman.es.protocol}"); setConfigProperty(componentPropName + ".client.host", "${apiman.es.host}"); setConfigProperty(componentPropName + ".client.port", "${apiman.es.port}"); setConfigProperty(componentPropName + ".client.index", "apiman_cache"); setConfigProperty(componentPropName + ".client.username", "${apiman.es.username}"); setConfigProperty(componentPropName + ".client.password", "${apiman.es.password}"); }
java
protected void registerCacheStoreComponent() { String componentPropName = GatewayConfigProperties.COMPONENT_PREFIX + ICacheStoreComponent.class.getSimpleName(); setConfigProperty(componentPropName, ESCacheStoreComponent.class.getName()); setConfigProperty(componentPropName + ".client.type", "jest"); setConfigProperty(componentPropName + ".client.protocol", "${apiman.es.protocol}"); setConfigProperty(componentPropName + ".client.host", "${apiman.es.host}"); setConfigProperty(componentPropName + ".client.port", "${apiman.es.port}"); setConfigProperty(componentPropName + ".client.index", "apiman_cache"); setConfigProperty(componentPropName + ".client.username", "${apiman.es.username}"); setConfigProperty(componentPropName + ".client.password", "${apiman.es.password}"); }
[ "protected", "void", "registerCacheStoreComponent", "(", ")", "{", "String", "componentPropName", "=", "GatewayConfigProperties", ".", "COMPONENT_PREFIX", "+", "ICacheStoreComponent", ".", "class", ".", "getSimpleName", "(", ")", ";", "setConfigProperty", "(", "componen...
The cache store component.
[ "The", "cache", "store", "component", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java#L172-L183
train
apiman/apiman
gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java
GatewayMicroService.registerJdbcComponent
protected void registerJdbcComponent() { String componentPropName = GatewayConfigProperties.COMPONENT_PREFIX + IJdbcComponent.class.getSimpleName(); setConfigProperty(componentPropName, DefaultJdbcComponent.class.getName()); }
java
protected void registerJdbcComponent() { String componentPropName = GatewayConfigProperties.COMPONENT_PREFIX + IJdbcComponent.class.getSimpleName(); setConfigProperty(componentPropName, DefaultJdbcComponent.class.getName()); }
[ "protected", "void", "registerJdbcComponent", "(", ")", "{", "String", "componentPropName", "=", "GatewayConfigProperties", ".", "COMPONENT_PREFIX", "+", "IJdbcComponent", ".", "class", ".", "getSimpleName", "(", ")", ";", "setConfigProperty", "(", "componentPropName", ...
The jdbc component.
[ "The", "jdbc", "component", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java#L188-L191
train
apiman/apiman
gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java
GatewayMicroService.registerLdapComponent
protected void registerLdapComponent() { String componentPropName = GatewayConfigProperties.COMPONENT_PREFIX + ILdapComponent.class.getSimpleName(); setConfigProperty(componentPropName, DefaultLdapComponent.class.getName()); }
java
protected void registerLdapComponent() { String componentPropName = GatewayConfigProperties.COMPONENT_PREFIX + ILdapComponent.class.getSimpleName(); setConfigProperty(componentPropName, DefaultLdapComponent.class.getName()); }
[ "protected", "void", "registerLdapComponent", "(", ")", "{", "String", "componentPropName", "=", "GatewayConfigProperties", ".", "COMPONENT_PREFIX", "+", "ILdapComponent", ".", "class", ".", "getSimpleName", "(", ")", ";", "setConfigProperty", "(", "componentPropName", ...
The ldap component.
[ "The", "ldap", "component", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java#L196-L199
train
apiman/apiman
gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java
GatewayMicroService.configureConnectorFactory
protected void configureConnectorFactory() { setConfigProperty(GatewayConfigProperties.CONNECTOR_FACTORY_CLASS, HttpConnectorFactory.class.getName()); setConfigProperty(GatewayConfigProperties.CONNECTOR_FACTORY_CLASS + ".http.timeouts.read", "25"); setConfigProperty(GatewayConfigProperties.CONNECTOR_FACTORY_CLASS + ".http.timeouts.write", "25"); setConfigProperty(GatewayConfigProperties.CONNECTOR_FACTORY_CLASS + ".http.timeouts.connect", "10"); setConfigProperty(GatewayConfigProperties.CONNECTOR_FACTORY_CLASS + ".http.followRedirects", "true"); }
java
protected void configureConnectorFactory() { setConfigProperty(GatewayConfigProperties.CONNECTOR_FACTORY_CLASS, HttpConnectorFactory.class.getName()); setConfigProperty(GatewayConfigProperties.CONNECTOR_FACTORY_CLASS + ".http.timeouts.read", "25"); setConfigProperty(GatewayConfigProperties.CONNECTOR_FACTORY_CLASS + ".http.timeouts.write", "25"); setConfigProperty(GatewayConfigProperties.CONNECTOR_FACTORY_CLASS + ".http.timeouts.connect", "10"); setConfigProperty(GatewayConfigProperties.CONNECTOR_FACTORY_CLASS + ".http.followRedirects", "true"); }
[ "protected", "void", "configureConnectorFactory", "(", ")", "{", "setConfigProperty", "(", "GatewayConfigProperties", ".", "CONNECTOR_FACTORY_CLASS", ",", "HttpConnectorFactory", ".", "class", ".", "getName", "(", ")", ")", ";", "setConfigProperty", "(", "GatewayConfigP...
The connector factory.
[ "The", "connector", "factory", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java#L211-L217
train
apiman/apiman
gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java
GatewayMicroService.configureRegistry
protected void configureRegistry() { setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS, PollCachingESRegistry.class.getName()); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.type", "jest"); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.protocol", "${apiman.es.protocol}"); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.host", "${apiman.es.host}"); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.port", "${apiman.es.port}"); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.username", "${apiman.es.username}"); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.password", "${apiman.es.password}"); }
java
protected void configureRegistry() { setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS, PollCachingESRegistry.class.getName()); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.type", "jest"); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.protocol", "${apiman.es.protocol}"); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.host", "${apiman.es.host}"); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.port", "${apiman.es.port}"); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.username", "${apiman.es.username}"); setConfigProperty(GatewayConfigProperties.REGISTRY_CLASS + ".client.password", "${apiman.es.password}"); }
[ "protected", "void", "configureRegistry", "(", ")", "{", "setConfigProperty", "(", "GatewayConfigProperties", ".", "REGISTRY_CLASS", ",", "PollCachingESRegistry", ".", "class", ".", "getName", "(", ")", ")", ";", "setConfigProperty", "(", "GatewayConfigProperties", "....
The registry.
[ "The", "registry", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java#L229-L237
train
apiman/apiman
gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java
GatewayMicroService.configureMetrics
protected void configureMetrics() { setConfigProperty(GatewayConfigProperties.METRICS_CLASS, ESMetrics.class.getName()); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.type", "jest"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.protocol", "${apiman.es.protocol}"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.host", "${apiman.es.host}"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.port", "${apiman.es.port}"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.username", "${apiman.es.username}"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.password", "${apiman.es.password}"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.index", "apiman_metrics"); }
java
protected void configureMetrics() { setConfigProperty(GatewayConfigProperties.METRICS_CLASS, ESMetrics.class.getName()); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.type", "jest"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.protocol", "${apiman.es.protocol}"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.host", "${apiman.es.host}"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.port", "${apiman.es.port}"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.username", "${apiman.es.username}"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.password", "${apiman.es.password}"); setConfigProperty(GatewayConfigProperties.METRICS_CLASS + ".client.index", "apiman_metrics"); }
[ "protected", "void", "configureMetrics", "(", ")", "{", "setConfigProperty", "(", "GatewayConfigProperties", ".", "METRICS_CLASS", ",", "ESMetrics", ".", "class", ".", "getName", "(", ")", ")", ";", "setConfigProperty", "(", "GatewayConfigProperties", ".", "METRICS_...
Configure the metrics system.
[ "Configure", "the", "metrics", "system", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java#L242-L251
train
apiman/apiman
gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java
GatewayMicroService.setConfigProperty
protected void setConfigProperty(String propName, String propValue) { if (System.getProperty(propName) == null) { System.setProperty(propName, propValue); } }
java
protected void setConfigProperty(String propName, String propValue) { if (System.getProperty(propName) == null) { System.setProperty(propName, propValue); } }
[ "protected", "void", "setConfigProperty", "(", "String", "propName", ",", "String", "propValue", ")", "{", "if", "(", "System", ".", "getProperty", "(", "propName", ")", "==", "null", ")", "{", "System", ".", "setProperty", "(", "propName", ",", "propValue",...
Sets a system property if it's not already set. @param propName @param propValue
[ "Sets", "a", "system", "property", "if", "it", "s", "not", "already", "set", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/platforms/war/micro/src/main/java/io/apiman/gateway/platforms/war/micro/GatewayMicroService.java#L258-L262
train
apiman/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/rates/RateLimiterBucket.java
RateLimiterBucket.resetIfNecessary
public boolean resetIfNecessary(RateBucketPeriod period) { long periodBoundary = getLastPeriodBoundary(period); if (System.currentTimeMillis() >= periodBoundary) { setCount(0); return true; } return false; }
java
public boolean resetIfNecessary(RateBucketPeriod period) { long periodBoundary = getLastPeriodBoundary(period); if (System.currentTimeMillis() >= periodBoundary) { setCount(0); return true; } return false; }
[ "public", "boolean", "resetIfNecessary", "(", "RateBucketPeriod", "period", ")", "{", "long", "periodBoundary", "=", "getLastPeriodBoundary", "(", "period", ")", ";", "if", "(", "System", ".", "currentTimeMillis", "(", ")", ">=", "periodBoundary", ")", "{", "set...
Resets the count if the period boundary has been crossed. Returns true if the count was reset to 0 or false otherwise. @param period the period
[ "Resets", "the", "count", "if", "the", "period", "boundary", "has", "been", "crossed", ".", "Returns", "true", "if", "the", "count", "was", "reset", "to", "0", "or", "false", "otherwise", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/rates/RateLimiterBucket.java#L46-L53
train
apiman/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/rates/RateLimiterBucket.java
RateLimiterBucket.getResetMillis
public long getResetMillis(RateBucketPeriod period) { long now = System.currentTimeMillis(); long periodBoundary = getPeriodBoundary(now, period); return periodBoundary - now; }
java
public long getResetMillis(RateBucketPeriod period) { long now = System.currentTimeMillis(); long periodBoundary = getPeriodBoundary(now, period); return periodBoundary - now; }
[ "public", "long", "getResetMillis", "(", "RateBucketPeriod", "period", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "long", "periodBoundary", "=", "getPeriodBoundary", "(", "now", ",", "period", ")", ";", "return", "periodBo...
Returns the number of millis until the period resets. @param period the period @return millis until period resets
[ "Returns", "the", "number", "of", "millis", "until", "the", "period", "resets", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/rates/RateLimiterBucket.java#L60-L64
train
apiman/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/rates/RateLimiterBucket.java
RateLimiterBucket.getPeriodBoundary
private static long getPeriodBoundary(long timestamp, RateBucketPeriod period) { Calendar lastCal = Calendar.getInstance(); lastCal.setTimeInMillis(timestamp); switch (period) { case Second: lastCal.set(Calendar.MILLISECOND, 0); lastCal.add(Calendar.SECOND, 1); return lastCal.getTimeInMillis(); case Minute: lastCal.set(Calendar.MILLISECOND, 0); lastCal.set(Calendar.SECOND, 0); lastCal.add(Calendar.MINUTE, 1); return lastCal.getTimeInMillis(); case Hour: lastCal.set(Calendar.MILLISECOND, 0); lastCal.set(Calendar.SECOND, 0); lastCal.set(Calendar.MINUTE, 0); lastCal.add(Calendar.HOUR_OF_DAY, 1); return lastCal.getTimeInMillis(); case Day: lastCal.set(Calendar.MILLISECOND, 0); lastCal.set(Calendar.SECOND, 0); lastCal.set(Calendar.MINUTE, 0); lastCal.set(Calendar.HOUR_OF_DAY, 0); lastCal.add(Calendar.DAY_OF_YEAR, 1); return lastCal.getTimeInMillis(); case Month: lastCal.set(Calendar.MILLISECOND, 0); lastCal.set(Calendar.SECOND, 0); lastCal.set(Calendar.MINUTE, 0); lastCal.set(Calendar.HOUR_OF_DAY, 0); lastCal.set(Calendar.DAY_OF_MONTH, 1); lastCal.add(Calendar.MONTH, 1); return lastCal.getTimeInMillis(); case Year: lastCal.set(Calendar.MILLISECOND, 0); lastCal.set(Calendar.SECOND, 0); lastCal.set(Calendar.MINUTE, 0); lastCal.set(Calendar.HOUR_OF_DAY, 0); lastCal.set(Calendar.DAY_OF_YEAR, 1); lastCal.add(Calendar.YEAR, 1); return lastCal.getTimeInMillis(); } return Long.MAX_VALUE; }
java
private static long getPeriodBoundary(long timestamp, RateBucketPeriod period) { Calendar lastCal = Calendar.getInstance(); lastCal.setTimeInMillis(timestamp); switch (period) { case Second: lastCal.set(Calendar.MILLISECOND, 0); lastCal.add(Calendar.SECOND, 1); return lastCal.getTimeInMillis(); case Minute: lastCal.set(Calendar.MILLISECOND, 0); lastCal.set(Calendar.SECOND, 0); lastCal.add(Calendar.MINUTE, 1); return lastCal.getTimeInMillis(); case Hour: lastCal.set(Calendar.MILLISECOND, 0); lastCal.set(Calendar.SECOND, 0); lastCal.set(Calendar.MINUTE, 0); lastCal.add(Calendar.HOUR_OF_DAY, 1); return lastCal.getTimeInMillis(); case Day: lastCal.set(Calendar.MILLISECOND, 0); lastCal.set(Calendar.SECOND, 0); lastCal.set(Calendar.MINUTE, 0); lastCal.set(Calendar.HOUR_OF_DAY, 0); lastCal.add(Calendar.DAY_OF_YEAR, 1); return lastCal.getTimeInMillis(); case Month: lastCal.set(Calendar.MILLISECOND, 0); lastCal.set(Calendar.SECOND, 0); lastCal.set(Calendar.MINUTE, 0); lastCal.set(Calendar.HOUR_OF_DAY, 0); lastCal.set(Calendar.DAY_OF_MONTH, 1); lastCal.add(Calendar.MONTH, 1); return lastCal.getTimeInMillis(); case Year: lastCal.set(Calendar.MILLISECOND, 0); lastCal.set(Calendar.SECOND, 0); lastCal.set(Calendar.MINUTE, 0); lastCal.set(Calendar.HOUR_OF_DAY, 0); lastCal.set(Calendar.DAY_OF_YEAR, 1); lastCal.add(Calendar.YEAR, 1); return lastCal.getTimeInMillis(); } return Long.MAX_VALUE; }
[ "private", "static", "long", "getPeriodBoundary", "(", "long", "timestamp", ",", "RateBucketPeriod", "period", ")", "{", "Calendar", "lastCal", "=", "Calendar", ".", "getInstance", "(", ")", ";", "lastCal", ".", "setTimeInMillis", "(", "timestamp", ")", ";", "...
Gets the boundary timestamp for the given rate bucket period. In other words, returns the timestamp associated with when the rate period will reset. @param timestamp @param period
[ "Gets", "the", "boundary", "timestamp", "for", "the", "given", "rate", "bucket", "period", ".", "In", "other", "words", "returns", "the", "timestamp", "associated", "with", "when", "the", "rate", "period", "will", "reset", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/rates/RateLimiterBucket.java#L81-L125
train
apiman/apiman
manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/PluginResourceImpl.java
PluginResourceImpl.loadRegistry
private PluginRegistryBean loadRegistry(URI registryUrl) { PluginRegistryBean fromCache = registryCache.get(registryUrl); if (fromCache != null) { return fromCache; } try { PluginRegistryBean registry = mapper.reader(PluginRegistryBean.class).readValue(registryUrl.toURL()); registryCache.put(registryUrl, registry); return registry; } catch (IOException e) { return null; } }
java
private PluginRegistryBean loadRegistry(URI registryUrl) { PluginRegistryBean fromCache = registryCache.get(registryUrl); if (fromCache != null) { return fromCache; } try { PluginRegistryBean registry = mapper.reader(PluginRegistryBean.class).readValue(registryUrl.toURL()); registryCache.put(registryUrl, registry); return registry; } catch (IOException e) { return null; } }
[ "private", "PluginRegistryBean", "loadRegistry", "(", "URI", "registryUrl", ")", "{", "PluginRegistryBean", "fromCache", "=", "registryCache", ".", "get", "(", "registryUrl", ")", ";", "if", "(", "fromCache", "!=", "null", ")", "{", "return", "fromCache", ";", ...
Loads a plugin registry from its URL. Will use the value in the cache if it exists. If not, it will connect to the remote URL and grab the registry JSON file. @param registryUrl the URL of the registry
[ "Loads", "a", "plugin", "registry", "from", "its", "URL", ".", "Will", "use", "the", "value", "in", "the", "cache", "if", "it", "exists", ".", "If", "not", "it", "will", "connect", "to", "the", "remote", "URL", "and", "grab", "the", "registry", "JSON",...
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/PluginResourceImpl.java#L417-L429
train
apiman/apiman
manager/api/es/src/main/java/io/apiman/manager/api/es/beans/PoliciesBean.java
PoliciesBean.from
public static final PoliciesBean from(PolicyBean policy) { PoliciesBean rval = new PoliciesBean(); rval.setType(policy.getType()); rval.setOrganizationId(policy.getOrganizationId()); rval.setEntityId(policy.getEntityId()); rval.setEntityVersion(policy.getEntityVersion()); rval.getPolicies().add(policy); return rval; }
java
public static final PoliciesBean from(PolicyBean policy) { PoliciesBean rval = new PoliciesBean(); rval.setType(policy.getType()); rval.setOrganizationId(policy.getOrganizationId()); rval.setEntityId(policy.getEntityId()); rval.setEntityVersion(policy.getEntityVersion()); rval.getPolicies().add(policy); return rval; }
[ "public", "static", "final", "PoliciesBean", "from", "(", "PolicyBean", "policy", ")", "{", "PoliciesBean", "rval", "=", "new", "PoliciesBean", "(", ")", ";", "rval", ".", "setType", "(", "policy", ".", "getType", "(", ")", ")", ";", "rval", ".", "setOrg...
Create a new Policies object from the given policy bean instance. @param policy the policy @return the policies
[ "Create", "a", "new", "Policies", "object", "from", "the", "given", "policy", "bean", "instance", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/es/src/main/java/io/apiman/manager/api/es/beans/PoliciesBean.java#L50-L58
train
apiman/apiman
manager/api/migrator/src/main/java/io/apiman/manager/api/migrator/VersionMigrators.java
VersionMigrators.chain
public static VersionMigratorChain chain(String fromVersion, String toVersion) { List<IVersionMigrator> matchedMigrators = new ArrayList<>(); for (Entry entry : migrators) { if (entry.isBetween(fromVersion, toVersion)) { matchedMigrators.add(entry.migrator); } } return new VersionMigratorChain(matchedMigrators); }
java
public static VersionMigratorChain chain(String fromVersion, String toVersion) { List<IVersionMigrator> matchedMigrators = new ArrayList<>(); for (Entry entry : migrators) { if (entry.isBetween(fromVersion, toVersion)) { matchedMigrators.add(entry.migrator); } } return new VersionMigratorChain(matchedMigrators); }
[ "public", "static", "VersionMigratorChain", "chain", "(", "String", "fromVersion", ",", "String", "toVersion", ")", "{", "List", "<", "IVersionMigrator", ">", "matchedMigrators", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Entry", "entry", ":", ...
Gets the chain of migrators to use when migrating from version X to version Y. @param fromVersion @param toVersion
[ "Gets", "the", "chain", "of", "migrators", "to", "use", "when", "migrating", "from", "version", "X", "to", "version", "Y", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/migrator/src/main/java/io/apiman/manager/api/migrator/VersionMigrators.java#L41-L49
train
apiman/apiman
common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java
HawkularMetricsClient.createTenant
public void createTenant(String tenantId) { TenantBean tenant = new TenantBean(tenantId); try { URL endpoint = serverUrl.toURI().resolve("tenants").toURL(); //$NON-NLS-1$ Request request = new Request.Builder() .url(endpoint) .post(toBody(tenant)) .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$ .build(); Response response = httpClient.newCall(request).execute(); if (response.code() >= 400) { throw hawkularMetricsError(response); } } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } }
java
public void createTenant(String tenantId) { TenantBean tenant = new TenantBean(tenantId); try { URL endpoint = serverUrl.toURI().resolve("tenants").toURL(); //$NON-NLS-1$ Request request = new Request.Builder() .url(endpoint) .post(toBody(tenant)) .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$ .build(); Response response = httpClient.newCall(request).execute(); if (response.code() >= 400) { throw hawkularMetricsError(response); } } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } }
[ "public", "void", "createTenant", "(", "String", "tenantId", ")", "{", "TenantBean", "tenant", "=", "new", "TenantBean", "(", "tenantId", ")", ";", "try", "{", "URL", "endpoint", "=", "serverUrl", ".", "toURI", "(", ")", ".", "resolve", "(", "\"tenants\"",...
Creates a new tenant. @param tenantId
[ "Creates", "a", "new", "tenant", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java#L168-L184
train
apiman/apiman
common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java
HawkularMetricsClient.listCounterMetrics
public List<MetricBean> listCounterMetrics(String tenantId) { try { URL endpoint = serverUrl.toURI().resolve("counters").toURL(); //$NON-NLS-1$ Request request = new Request.Builder() .url(endpoint) .header("Accept", "application/json") //$NON-NLS-1$ //$NON-NLS-2$ .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$ .build(); Response response = httpClient.newCall(request).execute(); if (response.code() >= 400) { throw hawkularMetricsError(response); } if (response.code() == 204) { return Collections.EMPTY_LIST; } String responseBody = response.body().string(); return readMapper.reader(new TypeReference<List<MetricBean>>() {}).readValue(responseBody); } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } }
java
public List<MetricBean> listCounterMetrics(String tenantId) { try { URL endpoint = serverUrl.toURI().resolve("counters").toURL(); //$NON-NLS-1$ Request request = new Request.Builder() .url(endpoint) .header("Accept", "application/json") //$NON-NLS-1$ //$NON-NLS-2$ .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$ .build(); Response response = httpClient.newCall(request).execute(); if (response.code() >= 400) { throw hawkularMetricsError(response); } if (response.code() == 204) { return Collections.EMPTY_LIST; } String responseBody = response.body().string(); return readMapper.reader(new TypeReference<List<MetricBean>>() {}).readValue(responseBody); } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } }
[ "public", "List", "<", "MetricBean", ">", "listCounterMetrics", "(", "String", "tenantId", ")", "{", "try", "{", "URL", "endpoint", "=", "serverUrl", ".", "toURI", "(", ")", ".", "resolve", "(", "\"counters\"", ")", ".", "toURL", "(", ")", ";", "//$NON-N...
Get a list of all counter metrics for a given tenant. @param tenantId
[ "Get", "a", "list", "of", "all", "counter", "metrics", "for", "a", "given", "tenant", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java#L190-L210
train
apiman/apiman
common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java
HawkularMetricsClient.addCounterDataPoint
public DataPointLongBean addCounterDataPoint(String tenantId, String counterId, Date timestamp, long value) { List<DataPointLongBean> dataPoints = new ArrayList<>(); DataPointLongBean dataPoint = new DataPointLongBean(timestamp, value); dataPoints.add(dataPoint); addCounterDataPoints(tenantId, counterId, dataPoints); return dataPoint; }
java
public DataPointLongBean addCounterDataPoint(String tenantId, String counterId, Date timestamp, long value) { List<DataPointLongBean> dataPoints = new ArrayList<>(); DataPointLongBean dataPoint = new DataPointLongBean(timestamp, value); dataPoints.add(dataPoint); addCounterDataPoints(tenantId, counterId, dataPoints); return dataPoint; }
[ "public", "DataPointLongBean", "addCounterDataPoint", "(", "String", "tenantId", ",", "String", "counterId", ",", "Date", "timestamp", ",", "long", "value", ")", "{", "List", "<", "DataPointLongBean", ">", "dataPoints", "=", "new", "ArrayList", "<>", "(", ")", ...
Adds a single data point to the given counter. @param tenantId @param counterId @param timestamp @param value
[ "Adds", "a", "single", "data", "point", "to", "the", "given", "counter", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java#L219-L225
train
apiman/apiman
common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java
HawkularMetricsClient.addMultipleCounterDataPoints
public void addMultipleCounterDataPoints(String tenantId, List<MetricLongBean> data) { try { URL endpoint = serverUrl.toURI().resolve("counters/raw").toURL(); //$NON-NLS-1$ Request request = new Request.Builder() .url(endpoint) .post(toBody(data)) .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$ .build(); Response response = httpClient.newCall(request).execute(); if (response.code() >= 400) { throw hawkularMetricsError(response); } } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } }
java
public void addMultipleCounterDataPoints(String tenantId, List<MetricLongBean> data) { try { URL endpoint = serverUrl.toURI().resolve("counters/raw").toURL(); //$NON-NLS-1$ Request request = new Request.Builder() .url(endpoint) .post(toBody(data)) .header("Hawkular-Tenant", tenantId) //$NON-NLS-1$ .build(); Response response = httpClient.newCall(request).execute(); if (response.code() >= 400) { throw hawkularMetricsError(response); } } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } }
[ "public", "void", "addMultipleCounterDataPoints", "(", "String", "tenantId", ",", "List", "<", "MetricLongBean", ">", "data", ")", "{", "try", "{", "URL", "endpoint", "=", "serverUrl", ".", "toURI", "(", ")", ".", "resolve", "(", "\"counters/raw\"", ")", "."...
Adds one or more data points for multiple counters all at once! @param tenantId @param data
[ "Adds", "one", "or", "more", "data", "points", "for", "multiple", "counters", "all", "at", "once!" ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java#L272-L287
train
apiman/apiman
common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java
HawkularMetricsClient.tags
public static Map<String, String> tags(String ... strings) { Map<String, String> tags = new HashMap<>(); for (int i = 0; i < strings.length - 1; i+=2) { String key = strings[i]; String value = strings[i + 1]; if (key != null && value != null) { tags.put(key, value); } } return tags; }
java
public static Map<String, String> tags(String ... strings) { Map<String, String> tags = new HashMap<>(); for (int i = 0; i < strings.length - 1; i+=2) { String key = strings[i]; String value = strings[i + 1]; if (key != null && value != null) { tags.put(key, value); } } return tags; }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "tags", "(", "String", "...", "strings", ")", "{", "Map", "<", "String", ",", "String", ">", "tags", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", ...
Simple method to create some tags. @param strings @return
[ "Simple", "method", "to", "create", "some", "tags", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java#L418-L428
train
apiman/apiman
common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java
HawkularMetricsClient.encodeTags
protected static String encodeTags(Map<String, String> tags) { if (tags == null) { return null; } try { StringBuilder builder = new StringBuilder(); boolean first = true; for (Entry<String, String> entry : tags.entrySet()) { if (!first) { builder.append(','); } builder.append(URLEncoder.encode(entry.getKey(), "UTF-8")); //$NON-NLS-1$ builder.append(':'); builder.append(URLEncoder.encode(entry.getValue(), "UTF-8")); //$NON-NLS-1$ first = false; } return builder.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; //$NON-NLS-1$ } }
java
protected static String encodeTags(Map<String, String> tags) { if (tags == null) { return null; } try { StringBuilder builder = new StringBuilder(); boolean first = true; for (Entry<String, String> entry : tags.entrySet()) { if (!first) { builder.append(','); } builder.append(URLEncoder.encode(entry.getKey(), "UTF-8")); //$NON-NLS-1$ builder.append(':'); builder.append(URLEncoder.encode(entry.getValue(), "UTF-8")); //$NON-NLS-1$ first = false; } return builder.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; //$NON-NLS-1$ } }
[ "protected", "static", "String", "encodeTags", "(", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "if", "(", "tags", "==", "null", ")", "{", "return", "null", ";", "}", "try", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", ...
Encodes the tags into the format expected by HM. @param tags
[ "Encodes", "the", "tags", "into", "the", "format", "expected", "by", "HM", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/net/src/main/java/io/apiman/common/net/hawkular/HawkularMetricsClient.java#L442-L463
train
apiman/apiman
gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/PollCachingESRegistry.java
PollCachingESRegistry.startCacheInvalidator
protected void startCacheInvalidator() { polling = true; Thread thread = new Thread(new Runnable() { @Override public void run() { // Wait for 30s on startup before starting to poll. try { Thread.sleep(startupDelayMillis); } catch (InterruptedException e1) { e1.printStackTrace(); } while (polling) { try { Thread.sleep(pollIntervalMillis); } catch (Exception e) { e.printStackTrace(); } checkCacheVersion(); } } }, "ESRegistryCacheInvalidator"); //$NON-NLS-1$ thread.setDaemon(true); thread.start(); }
java
protected void startCacheInvalidator() { polling = true; Thread thread = new Thread(new Runnable() { @Override public void run() { // Wait for 30s on startup before starting to poll. try { Thread.sleep(startupDelayMillis); } catch (InterruptedException e1) { e1.printStackTrace(); } while (polling) { try { Thread.sleep(pollIntervalMillis); } catch (Exception e) { e.printStackTrace(); } checkCacheVersion(); } } }, "ESRegistryCacheInvalidator"); //$NON-NLS-1$ thread.setDaemon(true); thread.start(); }
[ "protected", "void", "startCacheInvalidator", "(", ")", "{", "polling", "=", "true", ";", "Thread", "thread", "=", "new", "Thread", "(", "new", "Runnable", "(", ")", "{", "@", "Override", "public", "void", "run", "(", ")", "{", "// Wait for 30s on startup be...
Starts up a thread that polls the ES store for updates.
[ "Starts", "up", "a", "thread", "that", "polls", "the", "ES", "store", "for", "updates", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/PollCachingESRegistry.java#L174-L190
train
apiman/apiman
gateway/engine/core/src/main/java/io/apiman/gateway/engine/policy/Chain.java
Chain.chainPolicyHandlers
public void chainPolicyHandlers() { IReadWriteStream<H> previousHandler = null; Iterator<PolicyWithConfiguration> iterator = iterator(); while (iterator.hasNext()) { final PolicyWithConfiguration pwc = iterator.next(); final IPolicy policy = pwc.getPolicy(); final IReadWriteStream<H> handler = getApiHandler(policy, pwc.getConfiguration()); if (handler == null) { continue; } if (headPolicyHandler == null) { headPolicyHandler = handler; } if (previousHandler != null) { previousHandler.bodyHandler(new IAsyncHandler<IApimanBuffer>() { @Override public void handle(IApimanBuffer result) { handler.write(result); } }); previousHandler.endHandler(new IAsyncHandler<Void>() { @Override public void handle(Void result) { handler.end(); } }); } previousHandler = handler; } IReadWriteStream<H> tailPolicyHandler = previousHandler; // If no policy handlers were found, then just make ourselves the head, // otherwise connect the last policy handler in the chain to ourselves // Leave the head and tail policy handlers null - the write() and end() methods // will deal with that case. if (headPolicyHandler != null && tailPolicyHandler != null) { tailPolicyHandler.bodyHandler(new IAsyncHandler<IApimanBuffer>() { @Override public void handle(IApimanBuffer chunk) { handleBody(chunk); } }); tailPolicyHandler.endHandler(new IAsyncHandler<Void>() { @Override public void handle(Void result) { handleEnd(); } }); } }
java
public void chainPolicyHandlers() { IReadWriteStream<H> previousHandler = null; Iterator<PolicyWithConfiguration> iterator = iterator(); while (iterator.hasNext()) { final PolicyWithConfiguration pwc = iterator.next(); final IPolicy policy = pwc.getPolicy(); final IReadWriteStream<H> handler = getApiHandler(policy, pwc.getConfiguration()); if (handler == null) { continue; } if (headPolicyHandler == null) { headPolicyHandler = handler; } if (previousHandler != null) { previousHandler.bodyHandler(new IAsyncHandler<IApimanBuffer>() { @Override public void handle(IApimanBuffer result) { handler.write(result); } }); previousHandler.endHandler(new IAsyncHandler<Void>() { @Override public void handle(Void result) { handler.end(); } }); } previousHandler = handler; } IReadWriteStream<H> tailPolicyHandler = previousHandler; // If no policy handlers were found, then just make ourselves the head, // otherwise connect the last policy handler in the chain to ourselves // Leave the head and tail policy handlers null - the write() and end() methods // will deal with that case. if (headPolicyHandler != null && tailPolicyHandler != null) { tailPolicyHandler.bodyHandler(new IAsyncHandler<IApimanBuffer>() { @Override public void handle(IApimanBuffer chunk) { handleBody(chunk); } }); tailPolicyHandler.endHandler(new IAsyncHandler<Void>() { @Override public void handle(Void result) { handleEnd(); } }); } }
[ "public", "void", "chainPolicyHandlers", "(", ")", "{", "IReadWriteStream", "<", "H", ">", "previousHandler", "=", "null", ";", "Iterator", "<", "PolicyWithConfiguration", ">", "iterator", "=", "iterator", "(", ")", ";", "while", "(", "iterator", ".", "hasNext...
Chain together the body handlers.
[ "Chain", "together", "the", "body", "handlers", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/policy/Chain.java#L78-L134
train
apiman/apiman
common/util/src/main/java/io/apiman/common/util/ssl/KeyStoreUtil.java
KeyStoreUtil.getKeyManagers
public static KeyManager[] getKeyManagers(Info pathInfo) throws Exception { if (pathInfo.store == null) { return null; } File clientKeyStoreFile = new File(pathInfo.store); if (!clientKeyStoreFile.isFile()) { throw new Exception("No KeyManager: " + pathInfo.store + " does not exist or is not a file."); } String clientKeyStorePassword = pathInfo.password; KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("JKS"); FileInputStream clientFis = new FileInputStream(pathInfo.store); keyStore.load(clientFis, clientKeyStorePassword.toCharArray()); clientFis.close(); kmf.init(keyStore, clientKeyStorePassword.toCharArray()); return kmf.getKeyManagers(); }
java
public static KeyManager[] getKeyManagers(Info pathInfo) throws Exception { if (pathInfo.store == null) { return null; } File clientKeyStoreFile = new File(pathInfo.store); if (!clientKeyStoreFile.isFile()) { throw new Exception("No KeyManager: " + pathInfo.store + " does not exist or is not a file."); } String clientKeyStorePassword = pathInfo.password; KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance("JKS"); FileInputStream clientFis = new FileInputStream(pathInfo.store); keyStore.load(clientFis, clientKeyStorePassword.toCharArray()); clientFis.close(); kmf.init(keyStore, clientKeyStorePassword.toCharArray()); return kmf.getKeyManagers(); }
[ "public", "static", "KeyManager", "[", "]", "getKeyManagers", "(", "Info", "pathInfo", ")", "throws", "Exception", "{", "if", "(", "pathInfo", ".", "store", "==", "null", ")", "{", "return", "null", ";", "}", "File", "clientKeyStoreFile", "=", "new", "File...
Gets the array of key managers for a given info store+info. @param pathInfo @throws Exception
[ "Gets", "the", "array", "of", "key", "managers", "for", "a", "given", "info", "store", "+", "info", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/util/src/main/java/io/apiman/common/util/ssl/KeyStoreUtil.java#L37-L54
train
apiman/apiman
common/util/src/main/java/io/apiman/common/util/ssl/KeyStoreUtil.java
KeyStoreUtil.getTrustManagers
public static TrustManager[] getTrustManagers(Info pathInfo) throws Exception { File trustStoreFile = new File(pathInfo.store); if (!trustStoreFile.isFile()) { throw new Exception("No TrustManager: " + pathInfo.store + " does not exist."); } String trustStorePassword = pathInfo.password; TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore truststore = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream(pathInfo.store); truststore.load(fis, trustStorePassword.toCharArray()); fis.close(); tmf.init(truststore); return tmf.getTrustManagers(); }
java
public static TrustManager[] getTrustManagers(Info pathInfo) throws Exception { File trustStoreFile = new File(pathInfo.store); if (!trustStoreFile.isFile()) { throw new Exception("No TrustManager: " + pathInfo.store + " does not exist."); } String trustStorePassword = pathInfo.password; TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore truststore = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream(pathInfo.store); truststore.load(fis, trustStorePassword.toCharArray()); fis.close(); tmf.init(truststore); return tmf.getTrustManagers(); }
[ "public", "static", "TrustManager", "[", "]", "getTrustManagers", "(", "Info", "pathInfo", ")", "throws", "Exception", "{", "File", "trustStoreFile", "=", "new", "File", "(", "pathInfo", ".", "store", ")", ";", "if", "(", "!", "trustStoreFile", ".", "isFile"...
Gets an array of trust managers for a given store+password. @param pathInfo @return @throws Exception
[ "Gets", "an", "array", "of", "trust", "managers", "for", "a", "given", "store", "+", "password", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/util/src/main/java/io/apiman/common/util/ssl/KeyStoreUtil.java#L63-L77
train
apiman/apiman
manager/api/hawkular/src/main/java/io/apiman/manager/api/hawkular/TopNSortedMap.java
TopNSortedMap.popLastItem
private void popLastItem() { KeyValue<K,V> lastKV = items.last(); items.remove(lastKV); index.remove(lastKV.key); }
java
private void popLastItem() { KeyValue<K,V> lastKV = items.last(); items.remove(lastKV); index.remove(lastKV.key); }
[ "private", "void", "popLastItem", "(", ")", "{", "KeyValue", "<", "K", ",", "V", ">", "lastKV", "=", "items", ".", "last", "(", ")", ";", "items", ".", "remove", "(", "lastKV", ")", ";", "index", ".", "remove", "(", "lastKV", ".", "key", ")", ";"...
Removes the last item in the list.
[ "Removes", "the", "last", "item", "in", "the", "list", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/hawkular/src/main/java/io/apiman/manager/api/hawkular/TopNSortedMap.java#L102-L106
train
apiman/apiman
gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/BasicAuthenticationPolicy.java
BasicAuthenticationPolicy.validateCredentials
private void validateCredentials(String username, String password, ApiRequest request, IPolicyContext context, BasicAuthenticationConfig config, IAsyncResultHandler<Boolean> handler) { if (config.getStaticIdentity() != null) { staticIdentityValidator.validate(username, password, request, context, config.getStaticIdentity(), handler); } else if (config.getLdapIdentity() != null) { ldapIdentityValidator.validate(username, password, request, context, config.getLdapIdentity(), handler); } else if (config.getJdbcIdentity() != null) { jdbcIdentityValidator.validate(username, password, request, context, config.getJdbcIdentity(), handler); } else { handler.handle(AsyncResultImpl.create(Boolean.FALSE)); } }
java
private void validateCredentials(String username, String password, ApiRequest request, IPolicyContext context, BasicAuthenticationConfig config, IAsyncResultHandler<Boolean> handler) { if (config.getStaticIdentity() != null) { staticIdentityValidator.validate(username, password, request, context, config.getStaticIdentity(), handler); } else if (config.getLdapIdentity() != null) { ldapIdentityValidator.validate(username, password, request, context, config.getLdapIdentity(), handler); } else if (config.getJdbcIdentity() != null) { jdbcIdentityValidator.validate(username, password, request, context, config.getJdbcIdentity(), handler); } else { handler.handle(AsyncResultImpl.create(Boolean.FALSE)); } }
[ "private", "void", "validateCredentials", "(", "String", "username", ",", "String", "password", ",", "ApiRequest", "request", ",", "IPolicyContext", "context", ",", "BasicAuthenticationConfig", "config", ",", "IAsyncResultHandler", "<", "Boolean", ">", "handler", ")",...
Validate the inbound authentication credentials. @param username @param password @param request @param context @param config @param handler
[ "Validate", "the", "inbound", "authentication", "credentials", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/BasicAuthenticationPolicy.java#L162-L173
train
apiman/apiman
gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/BasicAuthenticationPolicy.java
BasicAuthenticationPolicy.sendAuthFailure
protected void sendAuthFailure(IPolicyContext context, IPolicyChain<?> chain, BasicAuthenticationConfig config, int reason) { IPolicyFailureFactoryComponent pff = context.getComponent(IPolicyFailureFactoryComponent.class); PolicyFailure failure = pff.createFailure(PolicyFailureType.Authentication, reason, Messages.i18n.format("BasicAuthenticationPolicy.AuthenticationFailed")); //$NON-NLS-1$ String realm = config.getRealm(); if (realm == null || realm.trim().isEmpty()) { realm = "Apiman"; //$NON-NLS-1$ } failure.getHeaders().put("WWW-Authenticate", String.format("Basic realm=\"%1$s\"", realm)); //$NON-NLS-1$ //$NON-NLS-2$ chain.doFailure(failure); }
java
protected void sendAuthFailure(IPolicyContext context, IPolicyChain<?> chain, BasicAuthenticationConfig config, int reason) { IPolicyFailureFactoryComponent pff = context.getComponent(IPolicyFailureFactoryComponent.class); PolicyFailure failure = pff.createFailure(PolicyFailureType.Authentication, reason, Messages.i18n.format("BasicAuthenticationPolicy.AuthenticationFailed")); //$NON-NLS-1$ String realm = config.getRealm(); if (realm == null || realm.trim().isEmpty()) { realm = "Apiman"; //$NON-NLS-1$ } failure.getHeaders().put("WWW-Authenticate", String.format("Basic realm=\"%1$s\"", realm)); //$NON-NLS-1$ //$NON-NLS-2$ chain.doFailure(failure); }
[ "protected", "void", "sendAuthFailure", "(", "IPolicyContext", "context", ",", "IPolicyChain", "<", "?", ">", "chain", ",", "BasicAuthenticationConfig", "config", ",", "int", "reason", ")", "{", "IPolicyFailureFactoryComponent", "pff", "=", "context", ".", "getCompo...
Sends the 'unauthenticated' response as a policy failure. @param context @param chain @param config @param reason
[ "Sends", "the", "unauthenticated", "response", "as", "a", "policy", "failure", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/BasicAuthenticationPolicy.java#L182-L191
train
apiman/apiman
gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/CachingESRegistry.java
CachingESRegistry.getApiIdx
private String getApiIdx(String orgId, String apiId, String version) { return "API::" + orgId + "|" + apiId + "|" + version; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ }
java
private String getApiIdx(String orgId, String apiId, String version) { return "API::" + orgId + "|" + apiId + "|" + version; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ }
[ "private", "String", "getApiIdx", "(", "String", "orgId", ",", "String", "apiId", ",", "String", "version", ")", "{", "return", "\"API::\"", "+", "orgId", "+", "\"|\"", "+", "apiId", "+", "\"|\"", "+", "version", ";", "//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$",...
Generates an in-memory key for an API, used to index the app for later quick retrieval. @param orgId @param apiId @param version @return a API key
[ "Generates", "an", "in", "-", "memory", "key", "for", "an", "API", "used", "to", "index", "the", "app", "for", "later", "quick", "retrieval", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/es/src/main/java/io/apiman/gateway/engine/es/CachingESRegistry.java#L196-L198
train
apiman/apiman
gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/JdbcRegistry.java
JdbcRegistry.unregisterApiContracts
protected void unregisterApiContracts(Client client, Connection connection) throws SQLException { QueryRunner run = new QueryRunner(); run.update(connection, "DELETE FROM contracts WHERE client_org_id = ? AND client_id = ? AND client_version = ?", //$NON-NLS-1$ client.getOrganizationId(), client.getClientId(), client.getVersion()); }
java
protected void unregisterApiContracts(Client client, Connection connection) throws SQLException { QueryRunner run = new QueryRunner(); run.update(connection, "DELETE FROM contracts WHERE client_org_id = ? AND client_id = ? AND client_version = ?", //$NON-NLS-1$ client.getOrganizationId(), client.getClientId(), client.getVersion()); }
[ "protected", "void", "unregisterApiContracts", "(", "Client", "client", ",", "Connection", "connection", ")", "throws", "SQLException", "{", "QueryRunner", "run", "=", "new", "QueryRunner", "(", ")", ";", "run", ".", "update", "(", "connection", ",", "\"DELETE F...
Removes all of the api contracts from the database. @param client @param connection @throws SQLException
[ "Removes", "all", "of", "the", "api", "contracts", "from", "the", "database", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/JdbcRegistry.java#L139-L143
train
apiman/apiman
gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/JdbcRegistry.java
JdbcRegistry.getApiInternal
protected Api getApiInternal(String organizationId, String apiId, String apiVersion) throws SQLException { QueryRunner run = new QueryRunner(ds); return run.query("SELECT bean FROM gw_apis WHERE org_id = ? AND id = ? AND version = ?", //$NON-NLS-1$ Handlers.API_HANDLER, organizationId, apiId, apiVersion); }
java
protected Api getApiInternal(String organizationId, String apiId, String apiVersion) throws SQLException { QueryRunner run = new QueryRunner(ds); return run.query("SELECT bean FROM gw_apis WHERE org_id = ? AND id = ? AND version = ?", //$NON-NLS-1$ Handlers.API_HANDLER, organizationId, apiId, apiVersion); }
[ "protected", "Api", "getApiInternal", "(", "String", "organizationId", ",", "String", "apiId", ",", "String", "apiVersion", ")", "throws", "SQLException", "{", "QueryRunner", "run", "=", "new", "QueryRunner", "(", "ds", ")", ";", "return", "run", ".", "query",...
Gets an api from the DB. @param organizationId @param apiId @param apiVersion @throws SQLException
[ "Gets", "an", "api", "from", "the", "DB", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/JdbcRegistry.java#L247-L251
train
apiman/apiman
gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/JdbcRegistry.java
JdbcRegistry.getClientInternal
protected Client getClientInternal(String apiKey) throws SQLException { QueryRunner run = new QueryRunner(ds); return run.query("SELECT bean FROM gw_clients WHERE api_key = ?", //$NON-NLS-1$ Handlers.CLIENT_HANDLER, apiKey); }
java
protected Client getClientInternal(String apiKey) throws SQLException { QueryRunner run = new QueryRunner(ds); return run.query("SELECT bean FROM gw_clients WHERE api_key = ?", //$NON-NLS-1$ Handlers.CLIENT_HANDLER, apiKey); }
[ "protected", "Client", "getClientInternal", "(", "String", "apiKey", ")", "throws", "SQLException", "{", "QueryRunner", "run", "=", "new", "QueryRunner", "(", "ds", ")", ";", "return", "run", ".", "query", "(", "\"SELECT bean FROM gw_clients WHERE api_key = ?\"", ",...
Simply pull the client from storage. @param apiKey @throws SQLException
[ "Simply", "pull", "the", "client", "from", "storage", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/jdbc/src/main/java/io/apiman/gateway/engine/jdbc/JdbcRegistry.java#L271-L275
train
apiman/apiman
common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java
AuthenticationFilter.doBasicAuth
protected void doBasicAuth(Creds credentials, HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { try { if (credentials.username.equals(request.getRemoteUser())) { // Already logged in as this user - do nothing. This can happen // in some app servers if the app server processes the BASIC auth // credentials before this filter gets a crack at them. WildFly 8 // works this way, for example (despite the web.xml not specifying // any login config!). } else if (request.getRemoteUser() != null) { // switch user request.logout(); request.login(credentials.username, credentials.password); } else { request.login(credentials.username, credentials.password); } } catch (Exception e) { // TODO log this error? e.printStackTrace(); sendAuthResponse(response); return; } doFilterChain(request, response, chain, null); }
java
protected void doBasicAuth(Creds credentials, HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { try { if (credentials.username.equals(request.getRemoteUser())) { // Already logged in as this user - do nothing. This can happen // in some app servers if the app server processes the BASIC auth // credentials before this filter gets a crack at them. WildFly 8 // works this way, for example (despite the web.xml not specifying // any login config!). } else if (request.getRemoteUser() != null) { // switch user request.logout(); request.login(credentials.username, credentials.password); } else { request.login(credentials.username, credentials.password); } } catch (Exception e) { // TODO log this error? e.printStackTrace(); sendAuthResponse(response); return; } doFilterChain(request, response, chain, null); }
[ "protected", "void", "doBasicAuth", "(", "Creds", "credentials", ",", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ",", "FilterChain", "chain", ")", "throws", "IOException", ",", "ServletException", "{", "try", "{", "if", "(", "credential...
Handle BASIC authentication. Delegates this to the container by invoking 'login' on the inbound http servlet request object. @param credentials the credentials @param request the http servlet request @param response the http servlet respose @param chain the filter chain @throws IOException when I/O failure occurs in filter chain @throws ServletException when servlet exception occurs during auth
[ "Handle", "BASIC", "authentication", ".", "Delegates", "this", "to", "the", "container", "by", "invoking", "login", "on", "the", "inbound", "http", "servlet", "request", "object", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java#L218-L241
train
apiman/apiman
common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java
AuthenticationFilter.doFilterChain
protected void doFilterChain(ServletRequest request, ServletResponse response, FilterChain chain, AuthPrincipal principal) throws IOException, ServletException { if (principal == null) { chain.doFilter(request, response); } else { HttpServletRequest hsr; hsr = wrapTheRequest(request, principal); chain.doFilter(hsr, response); } }
java
protected void doFilterChain(ServletRequest request, ServletResponse response, FilterChain chain, AuthPrincipal principal) throws IOException, ServletException { if (principal == null) { chain.doFilter(request, response); } else { HttpServletRequest hsr; hsr = wrapTheRequest(request, principal); chain.doFilter(hsr, response); } }
[ "protected", "void", "doFilterChain", "(", "ServletRequest", "request", ",", "ServletResponse", "response", ",", "FilterChain", "chain", ",", "AuthPrincipal", "principal", ")", "throws", "IOException", ",", "ServletException", "{", "if", "(", "principal", "==", "nul...
Further process the filter chain. @param request the request @param response the response @param chain the filter chain @param principal the auth principal @throws IOException when I/O failure occurs in filter chain @throws ServletException when servlet exception occurs during auth
[ "Further", "process", "the", "filter", "chain", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java#L269-L278
train
apiman/apiman
common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java
AuthenticationFilter.wrapTheRequest
private HttpServletRequest wrapTheRequest(final ServletRequest request, final AuthPrincipal principal) { HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper((HttpServletRequest) request) { @Override public Principal getUserPrincipal() { return principal; } @Override public boolean isUserInRole(String role) { return principal.getRoles().contains(role); } @Override public String getRemoteUser() { return principal.getName(); } }; return wrapper; }
java
private HttpServletRequest wrapTheRequest(final ServletRequest request, final AuthPrincipal principal) { HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper((HttpServletRequest) request) { @Override public Principal getUserPrincipal() { return principal; } @Override public boolean isUserInRole(String role) { return principal.getRoles().contains(role); } @Override public String getRemoteUser() { return principal.getName(); } }; return wrapper; }
[ "private", "HttpServletRequest", "wrapTheRequest", "(", "final", "ServletRequest", "request", ",", "final", "AuthPrincipal", "principal", ")", "{", "HttpServletRequestWrapper", "wrapper", "=", "new", "HttpServletRequestWrapper", "(", "(", "HttpServletRequest", ")", "reque...
Wrap the request to provide the principal. @param request the request @param principal the principal
[ "Wrap", "the", "request", "to", "provide", "the", "principal", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java#L285-L303
train
apiman/apiman
common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java
AuthenticationFilter.parseAuthorizationBasic
private Creds parseAuthorizationBasic(String authHeader) { String userpassEncoded = authHeader.substring(6); String data = StringUtils.newStringUtf8(Base64.decodeBase64(userpassEncoded)); int sepIdx = data.indexOf(':'); if (sepIdx > 0) { String username = data.substring(0, sepIdx); String password = data.substring(sepIdx + 1); return new Creds(username, password); } else { return new Creds(data, null); } }
java
private Creds parseAuthorizationBasic(String authHeader) { String userpassEncoded = authHeader.substring(6); String data = StringUtils.newStringUtf8(Base64.decodeBase64(userpassEncoded)); int sepIdx = data.indexOf(':'); if (sepIdx > 0) { String username = data.substring(0, sepIdx); String password = data.substring(sepIdx + 1); return new Creds(username, password); } else { return new Creds(data, null); } }
[ "private", "Creds", "parseAuthorizationBasic", "(", "String", "authHeader", ")", "{", "String", "userpassEncoded", "=", "authHeader", ".", "substring", "(", "6", ")", ";", "String", "data", "=", "StringUtils", ".", "newStringUtf8", "(", "Base64", ".", "decodeBas...
Parses the Authorization request header into a username and password. @param authHeader the auth header
[ "Parses", "the", "Authorization", "request", "header", "into", "a", "username", "and", "password", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java#L309-L320
train
apiman/apiman
common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java
AuthenticationFilter.parseAuthorizationToken
private AuthToken parseAuthorizationToken(String authHeader) { try { String tokenEncoded = authHeader.substring(11); return AuthTokenUtil.consumeToken(tokenEncoded); } catch (IllegalArgumentException e) { // TODO log this error return null; } }
java
private AuthToken parseAuthorizationToken(String authHeader) { try { String tokenEncoded = authHeader.substring(11); return AuthTokenUtil.consumeToken(tokenEncoded); } catch (IllegalArgumentException e) { // TODO log this error return null; } }
[ "private", "AuthToken", "parseAuthorizationToken", "(", "String", "authHeader", ")", "{", "try", "{", "String", "tokenEncoded", "=", "authHeader", ".", "substring", "(", "11", ")", ";", "return", "AuthTokenUtil", ".", "consumeToken", "(", "tokenEncoded", ")", ";...
Parses the Authorization request to retrieve the Base64 encoded auth token. @param authHeader the auth header
[ "Parses", "the", "Authorization", "request", "to", "retrieve", "the", "Base64", "encoded", "auth", "token", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java#L326-L334
train
apiman/apiman
common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java
AuthenticationFilter.sendAuthResponse
private void sendAuthResponse(HttpServletResponse response) throws IOException { response.setHeader("WWW-Authenticate", String.format("Basic realm=\"%1$s\"", realm)); //$NON-NLS-1$ //$NON-NLS-2$ response.sendError(HttpServletResponse.SC_UNAUTHORIZED); }
java
private void sendAuthResponse(HttpServletResponse response) throws IOException { response.setHeader("WWW-Authenticate", String.format("Basic realm=\"%1$s\"", realm)); //$NON-NLS-1$ //$NON-NLS-2$ response.sendError(HttpServletResponse.SC_UNAUTHORIZED); }
[ "private", "void", "sendAuthResponse", "(", "HttpServletResponse", "response", ")", "throws", "IOException", "{", "response", ".", "setHeader", "(", "\"WWW-Authenticate\"", ",", "String", ".", "format", "(", "\"Basic realm=\\\"%1$s\\\"\"", ",", "realm", ")", ")", ";...
Sends a response that tells the client that authentication is required. @param response the response @throws IOException when an error cannot be sent
[ "Sends", "a", "response", "that", "tells", "the", "client", "that", "authentication", "is", "required", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/servlet/src/main/java/io/apiman/common/servlet/AuthenticationFilter.java#L341-L344
train
apiman/apiman
gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/URLRewritingPolicy.java
URLRewritingPolicy.replaceHeaders
private void replaceHeaders(URLRewritingConfig config, HeaderMap headers) { for (Entry<String, String> entry : headers) { String key = entry.getKey(); String value = entry.getValue(); value = doHeaderReplaceAll(value, config.getFromRegex(), config.getToReplacement()); if (value != null) { headers.put(key, value); } } }
java
private void replaceHeaders(URLRewritingConfig config, HeaderMap headers) { for (Entry<String, String> entry : headers) { String key = entry.getKey(); String value = entry.getValue(); value = doHeaderReplaceAll(value, config.getFromRegex(), config.getToReplacement()); if (value != null) { headers.put(key, value); } } }
[ "private", "void", "replaceHeaders", "(", "URLRewritingConfig", "config", ",", "HeaderMap", "headers", ")", "{", "for", "(", "Entry", "<", "String", ",", "String", ">", "entry", ":", "headers", ")", "{", "String", "key", "=", "entry", ".", "getKey", "(", ...
Perform replacement. @param config @param headers
[ "Perform", "replacement", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/URLRewritingPolicy.java#L91-L100
train
apiman/apiman
gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/URLRewritingPolicy.java
URLRewritingPolicy.doHeaderReplaceAll
private String doHeaderReplaceAll(String headerValue, String fromRegex, String toReplacement) { return headerValue.replaceAll(fromRegex, toReplacement); }
java
private String doHeaderReplaceAll(String headerValue, String fromRegex, String toReplacement) { return headerValue.replaceAll(fromRegex, toReplacement); }
[ "private", "String", "doHeaderReplaceAll", "(", "String", "headerValue", ",", "String", "fromRegex", ",", "String", "toReplacement", ")", "{", "return", "headerValue", ".", "replaceAll", "(", "fromRegex", ",", "toReplacement", ")", ";", "}" ]
Finds all matching instances of the regular expression and replaces them with the replacement value. @param headerValue @param fromRegex @param toReplacement
[ "Finds", "all", "matching", "instances", "of", "the", "regular", "expression", "and", "replaces", "them", "with", "the", "replacement", "value", "." ]
8c049c2a2f2e4a69bbb6125686a15edd26f29c21
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/policies/src/main/java/io/apiman/gateway/engine/policies/URLRewritingPolicy.java#L109-L111
train