id
int32
0
165k
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
4,300
seedstack/seed
security/specs/src/main/java/org/seedstack/seed/security/principals/Principals.java
Principals.getSimplePrincipalByName
public static SimplePrincipalProvider getSimplePrincipalByName(Collection<PrincipalProvider<?>> principalProviders, String principalName) { for (SimplePrincipalProvider principal : getSimplePrincipals(principalProviders)) { if (principal.getName().equals(principalName)) { return principal; } } return null; }
java
public static SimplePrincipalProvider getSimplePrincipalByName(Collection<PrincipalProvider<?>> principalProviders, String principalName) { for (SimplePrincipalProvider principal : getSimplePrincipals(principalProviders)) { if (principal.getName().equals(principalName)) { return principal; } } return null; }
[ "public", "static", "SimplePrincipalProvider", "getSimplePrincipalByName", "(", "Collection", "<", "PrincipalProvider", "<", "?", ">", ">", "principalProviders", ",", "String", "principalName", ")", "{", "for", "(", "SimplePrincipalProvider", "principal", ":", "getSimplePrincipals", "(", "principalProviders", ")", ")", "{", "if", "(", "principal", ".", "getName", "(", ")", ".", "equals", "(", "principalName", ")", ")", "{", "return", "principal", ";", "}", "}", "return", "null", ";", "}" ]
Gives the simple principal with the given name from the given collection of principals @param principalProviders the principals to search @param principalName the name to search @return the simple principal with the name
[ "Gives", "the", "simple", "principal", "with", "the", "given", "name", "from", "the", "given", "collection", "of", "principals" ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/security/specs/src/main/java/org/seedstack/seed/security/principals/Principals.java#L171-L179
4,301
seedstack/seed
core/src/main/java/org/seedstack/seed/core/internal/guice/ProxyUtils.java
ProxyUtils.cleanProxy
public static Class<?> cleanProxy(Class<?> toClean) { if (ProxyUtils.isProxy(toClean)) { return toClean.getSuperclass(); } return toClean; }
java
public static Class<?> cleanProxy(Class<?> toClean) { if (ProxyUtils.isProxy(toClean)) { return toClean.getSuperclass(); } return toClean; }
[ "public", "static", "Class", "<", "?", ">", "cleanProxy", "(", "Class", "<", "?", ">", "toClean", ")", "{", "if", "(", "ProxyUtils", ".", "isProxy", "(", "toClean", ")", ")", "{", "return", "toClean", ".", "getSuperclass", "(", ")", ";", "}", "return", "toClean", ";", "}" ]
Return the non proxy class if needed. @param toClean The class to clean. @return the cleaned class.
[ "Return", "the", "non", "proxy", "class", "if", "needed", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/core/src/main/java/org/seedstack/seed/core/internal/guice/ProxyUtils.java#L34-L39
4,302
seedstack/seed
rest/jersey2/src/main/java/org/seedstack/seed/rest/jersey2/internal/GuiceComponentProvider.java
GuiceComponentProvider.newFactoryBinder
private static <T> ServiceBindingBuilder<T> newFactoryBinder(final Factory<T> factory) { return BindingBuilderFactory.newFactoryBinder(factory); }
java
private static <T> ServiceBindingBuilder<T> newFactoryBinder(final Factory<T> factory) { return BindingBuilderFactory.newFactoryBinder(factory); }
[ "private", "static", "<", "T", ">", "ServiceBindingBuilder", "<", "T", ">", "newFactoryBinder", "(", "final", "Factory", "<", "T", ">", "factory", ")", "{", "return", "BindingBuilderFactory", ".", "newFactoryBinder", "(", "factory", ")", ";", "}" ]
Get a new factory instance-based service binding builder. @param <T> service type. @param factory service instance. @return initialized binding builder.
[ "Get", "a", "new", "factory", "instance", "-", "based", "service", "binding", "builder", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/jersey2/src/main/java/org/seedstack/seed/rest/jersey2/internal/GuiceComponentProvider.java#L133-L135
4,303
seedstack/seed
security/specs/src/main/java/org/seedstack/seed/security/SimpleScope.java
SimpleScope.includes
@Override public boolean includes(Scope scope) { if (scope == null) { return true; } if (scope instanceof SimpleScope) { SimpleScope simpleScope = (SimpleScope) scope; return this.value.equals(simpleScope.value); } return false; }
java
@Override public boolean includes(Scope scope) { if (scope == null) { return true; } if (scope instanceof SimpleScope) { SimpleScope simpleScope = (SimpleScope) scope; return this.value.equals(simpleScope.value); } return false; }
[ "@", "Override", "public", "boolean", "includes", "(", "Scope", "scope", ")", "{", "if", "(", "scope", "==", "null", ")", "{", "return", "true", ";", "}", "if", "(", "scope", "instanceof", "SimpleScope", ")", "{", "SimpleScope", "simpleScope", "=", "(", "SimpleScope", ")", "scope", ";", "return", "this", ".", "value", ".", "equals", "(", "simpleScope", ".", "value", ")", ";", "}", "return", "false", ";", "}" ]
Checks if the current simple scope equals the verified simple scope.
[ "Checks", "if", "the", "current", "simple", "scope", "equals", "the", "verified", "simple", "scope", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/security/specs/src/main/java/org/seedstack/seed/security/SimpleScope.java#L38-L48
4,304
hyunjun19/axu4j
axu4j-tag/src/main/java/com/axisj/axu4j/config/ConfigReader.java
ConfigReader.load
public static void load(String confingFilename) { try { if (config == null) { config = new AXUConfig(); logger.debug("create new AXUConfig instance"); } // DEV ๋ชจ๋“œ์ธ ๊ฒฝ์šฐ ๊ฐ ํƒœ๊ทธ๋งˆ๋‹ค config๋ฅผ ์š”์ฒญํ•˜๋ฏ€๋กœ 3์ดˆ์— ํ•œ ๋ฒˆ์”ฉ๋งŒ ์„ค์ •์„ ๋กœ๋”ฉํ•˜๋„๋ก ํ•œ๋‹ค. long nowTime = (new Date()).getTime(); if (nowTime - lastLoadTime < 3000) { return; } else { lastLoadTime = nowTime; } Serializer serializer = new Persister(); URL configUrl = config.getClass().getClassLoader().getResource(confingFilename); if (configUrl == null) { configUrl = ClassLoader.getSystemClassLoader().getResource(confingFilename); } File configFile = new File(configUrl.toURI()); serializer.read(config, configFile); logger.info("load config from {}", configFile.getAbsolutePath()); if (logger.isDebugEnabled()) { logger.debug("axu4j.xml\n{}", config); } } catch(Exception e) { logger.error("Fail to load axu4j.xml", e); } }
java
public static void load(String confingFilename) { try { if (config == null) { config = new AXUConfig(); logger.debug("create new AXUConfig instance"); } // DEV ๋ชจ๋“œ์ธ ๊ฒฝ์šฐ ๊ฐ ํƒœ๊ทธ๋งˆ๋‹ค config๋ฅผ ์š”์ฒญํ•˜๋ฏ€๋กœ 3์ดˆ์— ํ•œ ๋ฒˆ์”ฉ๋งŒ ์„ค์ •์„ ๋กœ๋”ฉํ•˜๋„๋ก ํ•œ๋‹ค. long nowTime = (new Date()).getTime(); if (nowTime - lastLoadTime < 3000) { return; } else { lastLoadTime = nowTime; } Serializer serializer = new Persister(); URL configUrl = config.getClass().getClassLoader().getResource(confingFilename); if (configUrl == null) { configUrl = ClassLoader.getSystemClassLoader().getResource(confingFilename); } File configFile = new File(configUrl.toURI()); serializer.read(config, configFile); logger.info("load config from {}", configFile.getAbsolutePath()); if (logger.isDebugEnabled()) { logger.debug("axu4j.xml\n{}", config); } } catch(Exception e) { logger.error("Fail to load axu4j.xml", e); } }
[ "public", "static", "void", "load", "(", "String", "confingFilename", ")", "{", "try", "{", "if", "(", "config", "==", "null", ")", "{", "config", "=", "new", "AXUConfig", "(", ")", ";", "logger", ".", "debug", "(", "\"create new AXUConfig instance\"", ")", ";", "}", "// DEV ๋ชจ๋“œ์ธ ๊ฒฝ์šฐ ๊ฐ ํƒœ๊ทธ๋งˆ๋‹ค config๋ฅผ ์š”์ฒญํ•˜๋ฏ€๋กœ 3์ดˆ์— ํ•œ ๋ฒˆ์”ฉ๋งŒ ์„ค์ •์„ ๋กœ๋”ฉํ•˜๋„๋ก ํ•œ๋‹ค.", "long", "nowTime", "=", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", ";", "if", "(", "nowTime", "-", "lastLoadTime", "<", "3000", ")", "{", "return", ";", "}", "else", "{", "lastLoadTime", "=", "nowTime", ";", "}", "Serializer", "serializer", "=", "new", "Persister", "(", ")", ";", "URL", "configUrl", "=", "config", ".", "getClass", "(", ")", ".", "getClassLoader", "(", ")", ".", "getResource", "(", "confingFilename", ")", ";", "if", "(", "configUrl", "==", "null", ")", "{", "configUrl", "=", "ClassLoader", ".", "getSystemClassLoader", "(", ")", ".", "getResource", "(", "confingFilename", ")", ";", "}", "File", "configFile", "=", "new", "File", "(", "configUrl", ".", "toURI", "(", ")", ")", ";", "serializer", ".", "read", "(", "config", ",", "configFile", ")", ";", "logger", ".", "info", "(", "\"load config from {}\"", ",", "configFile", ".", "getAbsolutePath", "(", ")", ")", ";", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"axu4j.xml\\n{}\"", ",", "config", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "error", "(", "\"Fail to load axu4j.xml\"", ",", "e", ")", ";", "}", "}" ]
read config from confingPath @param confingFilename like axu4j.xml
[ "read", "config", "from", "confingPath" ]
a7eaf698a4ebe160b4ba22789fc543cdc50b3d64
https://github.com/hyunjun19/axu4j/blob/a7eaf698a4ebe160b4ba22789fc543cdc50b3d64/axu4j-tag/src/main/java/com/axisj/axu4j/config/ConfigReader.java#L41-L72
4,305
seedstack/seed
core/src/main/java/org/seedstack/seed/core/internal/crypto/SSLLoader.java
SSLLoader.getSSLContext
SSLContext getSSLContext(String protocol, KeyManager[] keyManagers, TrustManager[] trustManagers) { try { SSLContext sslContext = SSLContext.getInstance(protocol); sslContext.init(keyManagers, trustManagers, null); return sslContext; } catch (NoSuchAlgorithmException e) { throw SeedException.wrap(e, CryptoErrorCode.ALGORITHM_CANNOT_BE_FOUND); } catch (Exception e) { throw SeedException.wrap(e, CryptoErrorCode.UNEXPECTED_EXCEPTION); } }
java
SSLContext getSSLContext(String protocol, KeyManager[] keyManagers, TrustManager[] trustManagers) { try { SSLContext sslContext = SSLContext.getInstance(protocol); sslContext.init(keyManagers, trustManagers, null); return sslContext; } catch (NoSuchAlgorithmException e) { throw SeedException.wrap(e, CryptoErrorCode.ALGORITHM_CANNOT_BE_FOUND); } catch (Exception e) { throw SeedException.wrap(e, CryptoErrorCode.UNEXPECTED_EXCEPTION); } }
[ "SSLContext", "getSSLContext", "(", "String", "protocol", ",", "KeyManager", "[", "]", "keyManagers", ",", "TrustManager", "[", "]", "trustManagers", ")", "{", "try", "{", "SSLContext", "sslContext", "=", "SSLContext", ".", "getInstance", "(", "protocol", ")", ";", "sslContext", ".", "init", "(", "keyManagers", ",", "trustManagers", ",", "null", ")", ";", "return", "sslContext", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "throw", "SeedException", ".", "wrap", "(", "e", ",", "CryptoErrorCode", ".", "ALGORITHM_CANNOT_BE_FOUND", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "SeedException", ".", "wrap", "(", "e", ",", "CryptoErrorCode", ".", "UNEXPECTED_EXCEPTION", ")", ";", "}", "}" ]
Gets an SSLContext configured and initialized. <p>If no keyStore is configured, a default keyStore will be generated. <b>The generated keyStore is not intended to be used in production !</b> It won't work on JRE which don't include sun.* packages like the IBM JRE. </p> @return SSLContext
[ "Gets", "an", "SSLContext", "configured", "and", "initialized", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/core/src/main/java/org/seedstack/seed/core/internal/crypto/SSLLoader.java#L79-L90
4,306
seedstack/seed
rest/specs/src/main/java/org/seedstack/seed/rest/hal/HalRepresentation.java
HalRepresentation.link
public HalRepresentation link(String rel, String href) { addLink(rel, new Link(href)); return this; }
java
public HalRepresentation link(String rel, String href) { addLink(rel, new Link(href)); return this; }
[ "public", "HalRepresentation", "link", "(", "String", "rel", ",", "String", "href", ")", "{", "addLink", "(", "rel", ",", "new", "Link", "(", "href", ")", ")", ";", "return", "this", ";", "}" ]
Adds a link with the specified rel and href. @param rel the rel @param href the href @return itself
[ "Adds", "a", "link", "with", "the", "specified", "rel", "and", "href", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/specs/src/main/java/org/seedstack/seed/rest/hal/HalRepresentation.java#L102-L105
4,307
seedstack/seed
rest/specs/src/main/java/org/seedstack/seed/rest/hal/HalRepresentation.java
HalRepresentation.embedded
public HalRepresentation embedded(String rel, Object embedded) { this.embedded.put(rel, embedded); return this; }
java
public HalRepresentation embedded(String rel, Object embedded) { this.embedded.put(rel, embedded); return this; }
[ "public", "HalRepresentation", "embedded", "(", "String", "rel", ",", "Object", "embedded", ")", "{", "this", ".", "embedded", ".", "put", "(", "rel", ",", "embedded", ")", ";", "return", "this", ";", "}" ]
Adds an embedded resource or array of resources. @param rel the relation type @param embedded the resource (can be an array of resources) @return itself
[ "Adds", "an", "embedded", "resource", "or", "array", "of", "resources", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/specs/src/main/java/org/seedstack/seed/rest/hal/HalRepresentation.java#L162-L165
4,308
seedstack/seed
rest/core/src/main/java/org/seedstack/seed/rest/internal/ResourceScanner.java
ResourceScanner.scan
ResourceScanner scan(final Collection<Class<?>> classes) { for (Class<?> aClass : classes) { collectHttpMethodsWithRel(aClass); } buildJsonHomeResources(); buildHalLink(); return this; }
java
ResourceScanner scan(final Collection<Class<?>> classes) { for (Class<?> aClass : classes) { collectHttpMethodsWithRel(aClass); } buildJsonHomeResources(); buildHalLink(); return this; }
[ "ResourceScanner", "scan", "(", "final", "Collection", "<", "Class", "<", "?", ">", ">", "classes", ")", "{", "for", "(", "Class", "<", "?", ">", "aClass", ":", "classes", ")", "{", "collectHttpMethodsWithRel", "(", "aClass", ")", ";", "}", "buildJsonHomeResources", "(", ")", ";", "buildHalLink", "(", ")", ";", "return", "this", ";", "}" ]
Scans a collection of resources. @param classes the resource to scan @return itself
[ "Scans", "a", "collection", "of", "resources", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/core/src/main/java/org/seedstack/seed/rest/internal/ResourceScanner.java#L54-L61
4,309
seedstack/seed
core/src/main/java/org/seedstack/seed/core/internal/crypto/EncryptionServiceBindingFactory.java
EncryptionServiceBindingFactory.createBindings
Map<Key<EncryptionService>, EncryptionService> createBindings(CryptoConfig cryptoConfig, List<KeyPairConfig> keyPairConfigurations, Map<String, KeyStore> keyStores) { Map<Key<EncryptionService>, EncryptionService> encryptionServices = new HashMap<>(); Map<String, EncryptionServiceFactory> encryptionServiceFactories = new HashMap<>(); if (keyPairConfigurations != null && keyStores != null) { for (KeyPairConfig keyPairConfig : keyPairConfigurations) { String keyStoreName = keyPairConfig.getKeyStoreName(); if (!encryptionServiceFactories.containsKey(keyStoreName)) { EncryptionServiceFactory factory = new EncryptionServiceFactory(cryptoConfig, keyStores.get(keyStoreName)); encryptionServiceFactories.put(keyStoreName, factory); } EncryptionServiceFactory serviceFactory = encryptionServiceFactories.get(keyStoreName); EncryptionService encryptionService; if (keyPairConfig.getPassword() != null) { encryptionService = serviceFactory.create(keyPairConfig.getAlias(), keyPairConfig.getPassword().toCharArray()); } else { encryptionService = serviceFactory.create(keyPairConfig.getAlias()); } if (keyPairConfig.getQualifier() != null) { encryptionServices.put(createKeyFromQualifier(keyPairConfig.getQualifier()), encryptionService); } else { encryptionServices.put(Key.get(EncryptionService.class, Names.named(keyPairConfig.getAlias())), encryptionService); } } } return encryptionServices; }
java
Map<Key<EncryptionService>, EncryptionService> createBindings(CryptoConfig cryptoConfig, List<KeyPairConfig> keyPairConfigurations, Map<String, KeyStore> keyStores) { Map<Key<EncryptionService>, EncryptionService> encryptionServices = new HashMap<>(); Map<String, EncryptionServiceFactory> encryptionServiceFactories = new HashMap<>(); if (keyPairConfigurations != null && keyStores != null) { for (KeyPairConfig keyPairConfig : keyPairConfigurations) { String keyStoreName = keyPairConfig.getKeyStoreName(); if (!encryptionServiceFactories.containsKey(keyStoreName)) { EncryptionServiceFactory factory = new EncryptionServiceFactory(cryptoConfig, keyStores.get(keyStoreName)); encryptionServiceFactories.put(keyStoreName, factory); } EncryptionServiceFactory serviceFactory = encryptionServiceFactories.get(keyStoreName); EncryptionService encryptionService; if (keyPairConfig.getPassword() != null) { encryptionService = serviceFactory.create(keyPairConfig.getAlias(), keyPairConfig.getPassword().toCharArray()); } else { encryptionService = serviceFactory.create(keyPairConfig.getAlias()); } if (keyPairConfig.getQualifier() != null) { encryptionServices.put(createKeyFromQualifier(keyPairConfig.getQualifier()), encryptionService); } else { encryptionServices.put(Key.get(EncryptionService.class, Names.named(keyPairConfig.getAlias())), encryptionService); } } } return encryptionServices; }
[ "Map", "<", "Key", "<", "EncryptionService", ">", ",", "EncryptionService", ">", "createBindings", "(", "CryptoConfig", "cryptoConfig", ",", "List", "<", "KeyPairConfig", ">", "keyPairConfigurations", ",", "Map", "<", "String", ",", "KeyStore", ">", "keyStores", ")", "{", "Map", "<", "Key", "<", "EncryptionService", ">", ",", "EncryptionService", ">", "encryptionServices", "=", "new", "HashMap", "<>", "(", ")", ";", "Map", "<", "String", ",", "EncryptionServiceFactory", ">", "encryptionServiceFactories", "=", "new", "HashMap", "<>", "(", ")", ";", "if", "(", "keyPairConfigurations", "!=", "null", "&&", "keyStores", "!=", "null", ")", "{", "for", "(", "KeyPairConfig", "keyPairConfig", ":", "keyPairConfigurations", ")", "{", "String", "keyStoreName", "=", "keyPairConfig", ".", "getKeyStoreName", "(", ")", ";", "if", "(", "!", "encryptionServiceFactories", ".", "containsKey", "(", "keyStoreName", ")", ")", "{", "EncryptionServiceFactory", "factory", "=", "new", "EncryptionServiceFactory", "(", "cryptoConfig", ",", "keyStores", ".", "get", "(", "keyStoreName", ")", ")", ";", "encryptionServiceFactories", ".", "put", "(", "keyStoreName", ",", "factory", ")", ";", "}", "EncryptionServiceFactory", "serviceFactory", "=", "encryptionServiceFactories", ".", "get", "(", "keyStoreName", ")", ";", "EncryptionService", "encryptionService", ";", "if", "(", "keyPairConfig", ".", "getPassword", "(", ")", "!=", "null", ")", "{", "encryptionService", "=", "serviceFactory", ".", "create", "(", "keyPairConfig", ".", "getAlias", "(", ")", ",", "keyPairConfig", ".", "getPassword", "(", ")", ".", "toCharArray", "(", ")", ")", ";", "}", "else", "{", "encryptionService", "=", "serviceFactory", ".", "create", "(", "keyPairConfig", ".", "getAlias", "(", ")", ")", ";", "}", "if", "(", "keyPairConfig", ".", "getQualifier", "(", ")", "!=", "null", ")", "{", "encryptionServices", ".", "put", "(", "createKeyFromQualifier", "(", "keyPairConfig", ".", "getQualifier", "(", ")", ")", ",", "encryptionService", ")", ";", "}", "else", "{", "encryptionServices", ".", "put", "(", "Key", ".", "get", "(", "EncryptionService", ".", "class", ",", "Names", ".", "named", "(", "keyPairConfig", ".", "getAlias", "(", ")", ")", ")", ",", "encryptionService", ")", ";", "}", "}", "}", "return", "encryptionServices", ";", "}" ]
Creates the encryption service bindings. @param cryptoConfig crypto cryptoConfig @param keyPairConfigurations the key pairs configurations @param keyStores the key stores instances @return the map of Guice Key and EncryptionService instances.
[ "Creates", "the", "encryption", "service", "bindings", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/core/src/main/java/org/seedstack/seed/core/internal/crypto/EncryptionServiceBindingFactory.java#L37-L70
4,310
seedstack/seed
security/specs/src/main/java/org/seedstack/seed/security/Role.java
Role.getScopesByType
@SuppressWarnings("unchecked") public <S extends Scope> Set<S> getScopesByType(Class<S> scopeType) { Set<S> typedScopes = new HashSet<>(); for (Scope scope : getScopes()) { if (scopeType.isInstance(scope)) { typedScopes.add((S) scope); } } return typedScopes; }
java
@SuppressWarnings("unchecked") public <S extends Scope> Set<S> getScopesByType(Class<S> scopeType) { Set<S> typedScopes = new HashSet<>(); for (Scope scope : getScopes()) { if (scopeType.isInstance(scope)) { typedScopes.add((S) scope); } } return typedScopes; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "S", "extends", "Scope", ">", "Set", "<", "S", ">", "getScopesByType", "(", "Class", "<", "S", ">", "scopeType", ")", "{", "Set", "<", "S", ">", "typedScopes", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "Scope", "scope", ":", "getScopes", "(", ")", ")", "{", "if", "(", "scopeType", ".", "isInstance", "(", "scope", ")", ")", "{", "typedScopes", ".", "add", "(", "(", "S", ")", "scope", ")", ";", "}", "}", "return", "typedScopes", ";", "}" ]
Filters the scopes corresponding to a type @param <S> the type of the scope to filter. @param scopeType the type of scope @return the scopes of the given type
[ "Filters", "the", "scopes", "corresponding", "to", "a", "type" ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/security/specs/src/main/java/org/seedstack/seed/security/Role.java#L74-L83
4,311
seedstack/seed
specs/src/main/java/org/seedstack/seed/ClassConfiguration.java
ClassConfiguration.empty
public static <T> ClassConfiguration<T> empty(Class<T> targetClass) { return new ClassConfiguration<T>(targetClass, new HashMap<>()) {}; }
java
public static <T> ClassConfiguration<T> empty(Class<T> targetClass) { return new ClassConfiguration<T>(targetClass, new HashMap<>()) {}; }
[ "public", "static", "<", "T", ">", "ClassConfiguration", "<", "T", ">", "empty", "(", "Class", "<", "T", ">", "targetClass", ")", "{", "return", "new", "ClassConfiguration", "<", "T", ">", "(", "targetClass", ",", "new", "HashMap", "<>", "(", ")", ")", "{", "}", ";", "}" ]
Create an empty class configuration for the specified class. @param targetClass the class this configuration refers to. @param <T> the type of the target object. @return the class configuration object.
[ "Create", "an", "empty", "class", "configuration", "for", "the", "specified", "class", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/specs/src/main/java/org/seedstack/seed/ClassConfiguration.java#L68-L70
4,312
seedstack/seed
specs/src/main/java/org/seedstack/seed/ClassConfiguration.java
ClassConfiguration.merge
public ClassConfiguration<T> merge(ClassConfiguration<T> other) { if (!targetClass.isAssignableFrom(other.targetClass)) { throw new IllegalArgumentException( "Cannot merge class configurations: " + targetClass.getName() + " is not assignable to " + other .targetClass.getName()); } map.putAll(other.map); map.values().removeIf(Objects::isNull); return this; }
java
public ClassConfiguration<T> merge(ClassConfiguration<T> other) { if (!targetClass.isAssignableFrom(other.targetClass)) { throw new IllegalArgumentException( "Cannot merge class configurations: " + targetClass.getName() + " is not assignable to " + other .targetClass.getName()); } map.putAll(other.map); map.values().removeIf(Objects::isNull); return this; }
[ "public", "ClassConfiguration", "<", "T", ">", "merge", "(", "ClassConfiguration", "<", "T", ">", "other", ")", "{", "if", "(", "!", "targetClass", ".", "isAssignableFrom", "(", "other", ".", "targetClass", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot merge class configurations: \"", "+", "targetClass", ".", "getName", "(", ")", "+", "\" is not assignable to \"", "+", "other", ".", "targetClass", ".", "getName", "(", ")", ")", ";", "}", "map", ".", "putAll", "(", "other", ".", "map", ")", ";", "map", ".", "values", "(", ")", ".", "removeIf", "(", "Objects", "::", "isNull", ")", ";", "return", "this", ";", "}" ]
Merge the class configuration with another one, overriding the existing values having an identical key. If a key with a null value is merged, the key is completely removed from the resulting configuration. @param other the other class configuration. @return the merge class configuration.
[ "Merge", "the", "class", "configuration", "with", "another", "one", "overriding", "the", "existing", "values", "having", "an", "identical", "key", ".", "If", "a", "key", "with", "a", "null", "value", "is", "merged", "the", "key", "is", "completely", "removed", "from", "the", "resulting", "configuration", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/specs/src/main/java/org/seedstack/seed/ClassConfiguration.java#L173-L182
4,313
seedstack/seed
rest/core/src/main/java/org/seedstack/seed/rest/internal/RESTReflect.java
RESTReflect.findRel
static Rel findRel(Method method) { Rel rootRel = method.getDeclaringClass().getAnnotation(Rel.class); Rel rel = method.getAnnotation(Rel.class); if (rel != null) { return rel; } else if (rootRel != null) { return rootRel; } return null; }
java
static Rel findRel(Method method) { Rel rootRel = method.getDeclaringClass().getAnnotation(Rel.class); Rel rel = method.getAnnotation(Rel.class); if (rel != null) { return rel; } else if (rootRel != null) { return rootRel; } return null; }
[ "static", "Rel", "findRel", "(", "Method", "method", ")", "{", "Rel", "rootRel", "=", "method", ".", "getDeclaringClass", "(", ")", ".", "getAnnotation", "(", "Rel", ".", "class", ")", ";", "Rel", "rel", "=", "method", ".", "getAnnotation", "(", "Rel", ".", "class", ")", ";", "if", "(", "rel", "!=", "null", ")", "{", "return", "rel", ";", "}", "else", "if", "(", "rootRel", "!=", "null", ")", "{", "return", "rootRel", ";", "}", "return", "null", ";", "}" ]
Finds a the rel of a method. The rel can be found on the declaring class, but the rel on the method will have the precedence. @param method the method to scan @return the rel annotation
[ "Finds", "a", "the", "rel", "of", "a", "method", ".", "The", "rel", "can", "be", "found", "on", "the", "declaring", "class", "but", "the", "rel", "on", "the", "method", "will", "have", "the", "precedence", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/core/src/main/java/org/seedstack/seed/rest/internal/RESTReflect.java#L40-L49
4,314
seedstack/seed
rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/Hints.java
Hints.merge
public void merge(Hints hints) { this.allow.addAll(hints.getAllow()); this.formats.putAll(hints.getFormats()); this.acceptPath.addAll(hints.getAcceptPath()); this.acceptPost.addAll(hints.getAcceptPost()); this.acceptRanges.addAll(hints.getAcceptRanges()); this.acceptPrefer.addAll(hints.getAcceptPrefer()); mergeDocs(hints); preconditionReq.addAll(hints.getPreconditionReq()); authReq.addAll(hints.getAuthReq()); mergeStatus(hints); }
java
public void merge(Hints hints) { this.allow.addAll(hints.getAllow()); this.formats.putAll(hints.getFormats()); this.acceptPath.addAll(hints.getAcceptPath()); this.acceptPost.addAll(hints.getAcceptPost()); this.acceptRanges.addAll(hints.getAcceptRanges()); this.acceptPrefer.addAll(hints.getAcceptPrefer()); mergeDocs(hints); preconditionReq.addAll(hints.getPreconditionReq()); authReq.addAll(hints.getAuthReq()); mergeStatus(hints); }
[ "public", "void", "merge", "(", "Hints", "hints", ")", "{", "this", ".", "allow", ".", "addAll", "(", "hints", ".", "getAllow", "(", ")", ")", ";", "this", ".", "formats", ".", "putAll", "(", "hints", ".", "getFormats", "(", ")", ")", ";", "this", ".", "acceptPath", ".", "addAll", "(", "hints", ".", "getAcceptPath", "(", ")", ")", ";", "this", ".", "acceptPost", ".", "addAll", "(", "hints", ".", "getAcceptPost", "(", ")", ")", ";", "this", ".", "acceptRanges", ".", "addAll", "(", "hints", ".", "getAcceptRanges", "(", ")", ")", ";", "this", ".", "acceptPrefer", ".", "addAll", "(", "hints", ".", "getAcceptPrefer", "(", ")", ")", ";", "mergeDocs", "(", "hints", ")", ";", "preconditionReq", ".", "addAll", "(", "hints", ".", "getPreconditionReq", "(", ")", ")", ";", "authReq", ".", "addAll", "(", "hints", ".", "getAuthReq", "(", ")", ")", ";", "mergeStatus", "(", "hints", ")", ";", "}" ]
Merges the current hints with hints comming from another method of the resource. @param hints the hints to merge
[ "Merges", "the", "current", "hints", "with", "hints", "comming", "from", "another", "method", "of", "the", "resource", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/Hints.java#L53-L64
4,315
seedstack/seed
specs/src/main/java/org/seedstack/seed/crypto/Hash.java
Hash.bytesToHex
private static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { int v = bytes[i] & 0xFF; hexChars[i * 2] = hexArray[v >>> 4]; hexChars[i * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); }
java
private static String bytesToHex(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for (int i = 0; i < bytes.length; i++) { int v = bytes[i] & 0xFF; hexChars[i * 2] = hexArray[v >>> 4]; hexChars[i * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); }
[ "private", "static", "String", "bytesToHex", "(", "byte", "[", "]", "bytes", ")", "{", "char", "[", "]", "hexChars", "=", "new", "char", "[", "bytes", ".", "length", "*", "2", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bytes", ".", "length", ";", "i", "++", ")", "{", "int", "v", "=", "bytes", "[", "i", "]", "&", "0xFF", ";", "hexChars", "[", "i", "*", "2", "]", "=", "hexArray", "[", "v", ">>>", "4", "]", ";", "hexChars", "[", "i", "*", "2", "+", "1", "]", "=", "hexArray", "[", "v", "&", "0x0F", "]", ";", "}", "return", "new", "String", "(", "hexChars", ")", ";", "}" ]
We don't have Guava here
[ "We", "don", "t", "have", "Guava", "here" ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/specs/src/main/java/org/seedstack/seed/crypto/Hash.java#L87-L95
4,316
seedstack/seed
web/security/src/main/java/org/seedstack/seed/web/security/internal/WebSecurityModule.java
WebSecurityModule.toNameConfigPair
private String[] toNameConfigPair(String token) throws ConfigurationException { String[] pair = token.split("\\[", 2); String name = StringUtils.clean(pair[0]); if (name == null) { throw new IllegalArgumentException("Filter name not found for filter chain definition token: " + token); } String config = null; if (pair.length == 2) { config = StringUtils.clean(pair[1]); //if there was an open bracket, it assumed there is a closing bracket, so strip it too: config = config.substring(0, config.length() - 1); config = StringUtils.clean(config); //backwards compatibility prior to implementing SHIRO-205: //prior to SHIRO-205 being implemented, it was common for end-users to quote the config inside brackets //if that config required commas. We need to strip those quotes to get to the interior quoted definition //to ensure any existing quoted definitions still function for end users: if (config != null && config.startsWith("\"") && config.endsWith("\"")) { String stripped = config.substring(1, config.length() - 1); stripped = StringUtils.clean(stripped); //if the stripped value does not have any internal quotes, we can assume that the entire config was //quoted and we can use the stripped value. if (stripped != null && stripped.indexOf('"') == -1) { config = stripped; } //else: //the remaining config does have internal quotes, so we need to assume that each comma delimited //pair might be quoted, in which case we need the leading and trailing quotes that we stripped //So we ignore the stripped value. } } return new String[]{name, config}; }
java
private String[] toNameConfigPair(String token) throws ConfigurationException { String[] pair = token.split("\\[", 2); String name = StringUtils.clean(pair[0]); if (name == null) { throw new IllegalArgumentException("Filter name not found for filter chain definition token: " + token); } String config = null; if (pair.length == 2) { config = StringUtils.clean(pair[1]); //if there was an open bracket, it assumed there is a closing bracket, so strip it too: config = config.substring(0, config.length() - 1); config = StringUtils.clean(config); //backwards compatibility prior to implementing SHIRO-205: //prior to SHIRO-205 being implemented, it was common for end-users to quote the config inside brackets //if that config required commas. We need to strip those quotes to get to the interior quoted definition //to ensure any existing quoted definitions still function for end users: if (config != null && config.startsWith("\"") && config.endsWith("\"")) { String stripped = config.substring(1, config.length() - 1); stripped = StringUtils.clean(stripped); //if the stripped value does not have any internal quotes, we can assume that the entire config was //quoted and we can use the stripped value. if (stripped != null && stripped.indexOf('"') == -1) { config = stripped; } //else: //the remaining config does have internal quotes, so we need to assume that each comma delimited //pair might be quoted, in which case we need the leading and trailing quotes that we stripped //So we ignore the stripped value. } } return new String[]{name, config}; }
[ "private", "String", "[", "]", "toNameConfigPair", "(", "String", "token", ")", "throws", "ConfigurationException", "{", "String", "[", "]", "pair", "=", "token", ".", "split", "(", "\"\\\\[\"", ",", "2", ")", ";", "String", "name", "=", "StringUtils", ".", "clean", "(", "pair", "[", "0", "]", ")", ";", "if", "(", "name", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Filter name not found for filter chain definition token: \"", "+", "token", ")", ";", "}", "String", "config", "=", "null", ";", "if", "(", "pair", ".", "length", "==", "2", ")", "{", "config", "=", "StringUtils", ".", "clean", "(", "pair", "[", "1", "]", ")", ";", "//if there was an open bracket, it assumed there is a closing bracket, so strip it too:", "config", "=", "config", ".", "substring", "(", "0", ",", "config", ".", "length", "(", ")", "-", "1", ")", ";", "config", "=", "StringUtils", ".", "clean", "(", "config", ")", ";", "//backwards compatibility prior to implementing SHIRO-205:", "//prior to SHIRO-205 being implemented, it was common for end-users to quote the config inside brackets", "//if that config required commas. We need to strip those quotes to get to the interior quoted definition", "//to ensure any existing quoted definitions still function for end users:", "if", "(", "config", "!=", "null", "&&", "config", ".", "startsWith", "(", "\"\\\"\"", ")", "&&", "config", ".", "endsWith", "(", "\"\\\"\"", ")", ")", "{", "String", "stripped", "=", "config", ".", "substring", "(", "1", ",", "config", ".", "length", "(", ")", "-", "1", ")", ";", "stripped", "=", "StringUtils", ".", "clean", "(", "stripped", ")", ";", "//if the stripped value does not have any internal quotes, we can assume that the entire config was", "//quoted and we can use the stripped value.", "if", "(", "stripped", "!=", "null", "&&", "stripped", ".", "indexOf", "(", "'", "'", ")", "==", "-", "1", ")", "{", "config", "=", "stripped", ";", "}", "//else:", "//the remaining config does have internal quotes, so we need to assume that each comma delimited", "//pair might be quoted, in which case we need the leading and trailing quotes that we stripped", "//So we ignore the stripped value.", "}", "}", "return", "new", "String", "[", "]", "{", "name", ",", "config", "}", ";", "}" ]
This method is copied from the same method in Shiro in class DefaultFilterChainManager.
[ "This", "method", "is", "copied", "from", "the", "same", "method", "in", "Shiro", "in", "class", "DefaultFilterChainManager", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/web/security/src/main/java/org/seedstack/seed/web/security/internal/WebSecurityModule.java#L153-L190
4,317
seedstack/seed
security/core/src/main/java/org/seedstack/seed/security/internal/securityexpr/SecurityExpressionUtils.java
SecurityExpressionUtils.hasRoleOn
public static boolean hasRoleOn(String role, String simpleScope) { return securitySupport.hasRole(role, new SimpleScope(simpleScope)); }
java
public static boolean hasRoleOn(String role, String simpleScope) { return securitySupport.hasRole(role, new SimpleScope(simpleScope)); }
[ "public", "static", "boolean", "hasRoleOn", "(", "String", "role", ",", "String", "simpleScope", ")", "{", "return", "securitySupport", ".", "hasRole", "(", "role", ",", "new", "SimpleScope", "(", "simpleScope", ")", ")", ";", "}" ]
Checks the current user role in the given scopes. @param role the role to check @param simpleScope the simple scope to check this role on. @return true if the user has the role for the given simple scope.
[ "Checks", "the", "current", "user", "role", "in", "the", "given", "scopes", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/security/core/src/main/java/org/seedstack/seed/security/internal/securityexpr/SecurityExpressionUtils.java#L45-L47
4,318
seedstack/seed
security/core/src/main/java/org/seedstack/seed/security/internal/securityexpr/SecurityExpressionUtils.java
SecurityExpressionUtils.hasPermissionOn
public static boolean hasPermissionOn(String permission, String simpleScope) { return securitySupport.isPermitted(permission, new SimpleScope(simpleScope)); }
java
public static boolean hasPermissionOn(String permission, String simpleScope) { return securitySupport.isPermitted(permission, new SimpleScope(simpleScope)); }
[ "public", "static", "boolean", "hasPermissionOn", "(", "String", "permission", ",", "String", "simpleScope", ")", "{", "return", "securitySupport", ".", "isPermitted", "(", "permission", ",", "new", "SimpleScope", "(", "simpleScope", ")", ")", ";", "}" ]
Checks the current user permission. @param permission the permission to check @param simpleScope the simple scope to check this permission on. @return true if user has the given permission for the given simple scope.
[ "Checks", "the", "current", "user", "permission", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/security/core/src/main/java/org/seedstack/seed/security/internal/securityexpr/SecurityExpressionUtils.java#L66-L68
4,319
seedstack/seed
core/src/main/java/org/seedstack/seed/core/internal/init/ProxyManager.java
ProxyManager.parseCredentials
private Optional<String[]> parseCredentials(String url) { if (!Strings.isNullOrEmpty(url)) { int p; if ((p = url.indexOf("://")) != -1) { url = url.substring(p + 3); } if ((p = url.indexOf('@')) != -1) { String[] result = new String[2]; String credentials = url.substring(0, p); if ((p = credentials.indexOf(':')) != -1) { result[0] = credentials.substring(0, p); result[1] = credentials.substring(p + 1); } else { result[0] = credentials; result[1] = ""; } return Optional.of(result); } } return Optional.empty(); }
java
private Optional<String[]> parseCredentials(String url) { if (!Strings.isNullOrEmpty(url)) { int p; if ((p = url.indexOf("://")) != -1) { url = url.substring(p + 3); } if ((p = url.indexOf('@')) != -1) { String[] result = new String[2]; String credentials = url.substring(0, p); if ((p = credentials.indexOf(':')) != -1) { result[0] = credentials.substring(0, p); result[1] = credentials.substring(p + 1); } else { result[0] = credentials; result[1] = ""; } return Optional.of(result); } } return Optional.empty(); }
[ "private", "Optional", "<", "String", "[", "]", ">", "parseCredentials", "(", "String", "url", ")", "{", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "url", ")", ")", "{", "int", "p", ";", "if", "(", "(", "p", "=", "url", ".", "indexOf", "(", "\"://\"", ")", ")", "!=", "-", "1", ")", "{", "url", "=", "url", ".", "substring", "(", "p", "+", "3", ")", ";", "}", "if", "(", "(", "p", "=", "url", ".", "indexOf", "(", "'", "'", ")", ")", "!=", "-", "1", ")", "{", "String", "[", "]", "result", "=", "new", "String", "[", "2", "]", ";", "String", "credentials", "=", "url", ".", "substring", "(", "0", ",", "p", ")", ";", "if", "(", "(", "p", "=", "credentials", ".", "indexOf", "(", "'", "'", ")", ")", "!=", "-", "1", ")", "{", "result", "[", "0", "]", "=", "credentials", ".", "substring", "(", "0", ",", "p", ")", ";", "result", "[", "1", "]", "=", "credentials", ".", "substring", "(", "p", "+", "1", ")", ";", "}", "else", "{", "result", "[", "0", "]", "=", "credentials", ";", "result", "[", "1", "]", "=", "\"\"", ";", "}", "return", "Optional", ".", "of", "(", "result", ")", ";", "}", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}" ]
Given a proxy URL returns a two element arrays containing the user name and the password. The second component of the array is null if no password is specified. @param url The proxy host URL. @return An optional containing an array of the user name and the password or empty when none are present or the url is empty.
[ "Given", "a", "proxy", "URL", "returns", "a", "two", "element", "arrays", "containing", "the", "user", "name", "and", "the", "password", ".", "The", "second", "component", "of", "the", "array", "is", "null", "if", "no", "password", "is", "specified", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/core/src/main/java/org/seedstack/seed/core/internal/init/ProxyManager.java#L159-L179
4,320
seedstack/seed
core/src/main/java/org/seedstack/seed/core/internal/init/ProxyManager.java
ProxyManager.parseProxy
private Optional<String[]> parseProxy(String url, String defPort) { if (!Strings.isNullOrEmpty(url)) { String[] result = new String[2]; int p = url.indexOf("://"); if (p != -1) url = url.substring(p + 3); if ((p = url.indexOf('@')) != -1) url = url.substring(p + 1); if ((p = url.indexOf(':')) != -1) { result[0] = url.substring(0, p); result[1] = url.substring(p + 1); } else { result[0] = url; result[1] = defPort; } // remove trailing slash from the host name p = result[0].indexOf('/'); if (p != -1) { result[0] = result[0].substring(0, p); } // remove trailing slash from the port number p = result[1].indexOf('/'); if (p != -1) { result[1] = result[1].substring(0, p); } return Optional.of(result); } return Optional.empty(); }
java
private Optional<String[]> parseProxy(String url, String defPort) { if (!Strings.isNullOrEmpty(url)) { String[] result = new String[2]; int p = url.indexOf("://"); if (p != -1) url = url.substring(p + 3); if ((p = url.indexOf('@')) != -1) url = url.substring(p + 1); if ((p = url.indexOf(':')) != -1) { result[0] = url.substring(0, p); result[1] = url.substring(p + 1); } else { result[0] = url; result[1] = defPort; } // remove trailing slash from the host name p = result[0].indexOf('/'); if (p != -1) { result[0] = result[0].substring(0, p); } // remove trailing slash from the port number p = result[1].indexOf('/'); if (p != -1) { result[1] = result[1].substring(0, p); } return Optional.of(result); } return Optional.empty(); }
[ "private", "Optional", "<", "String", "[", "]", ">", "parseProxy", "(", "String", "url", ",", "String", "defPort", ")", "{", "if", "(", "!", "Strings", ".", "isNullOrEmpty", "(", "url", ")", ")", "{", "String", "[", "]", "result", "=", "new", "String", "[", "2", "]", ";", "int", "p", "=", "url", ".", "indexOf", "(", "\"://\"", ")", ";", "if", "(", "p", "!=", "-", "1", ")", "url", "=", "url", ".", "substring", "(", "p", "+", "3", ")", ";", "if", "(", "(", "p", "=", "url", ".", "indexOf", "(", "'", "'", ")", ")", "!=", "-", "1", ")", "url", "=", "url", ".", "substring", "(", "p", "+", "1", ")", ";", "if", "(", "(", "p", "=", "url", ".", "indexOf", "(", "'", "'", ")", ")", "!=", "-", "1", ")", "{", "result", "[", "0", "]", "=", "url", ".", "substring", "(", "0", ",", "p", ")", ";", "result", "[", "1", "]", "=", "url", ".", "substring", "(", "p", "+", "1", ")", ";", "}", "else", "{", "result", "[", "0", "]", "=", "url", ";", "result", "[", "1", "]", "=", "defPort", ";", "}", "// remove trailing slash from the host name", "p", "=", "result", "[", "0", "]", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "p", "!=", "-", "1", ")", "{", "result", "[", "0", "]", "=", "result", "[", "0", "]", ".", "substring", "(", "0", ",", "p", ")", ";", "}", "// remove trailing slash from the port number", "p", "=", "result", "[", "1", "]", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "p", "!=", "-", "1", ")", "{", "result", "[", "1", "]", "=", "result", "[", "1", "]", ".", "substring", "(", "0", ",", "p", ")", ";", "}", "return", "Optional", ".", "of", "(", "result", ")", ";", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}" ]
Given a proxy URL returns a two element arrays containing the host name and the port @param url The proxy host URL. @param defPort The default proxy port @return An optional containing an array of the host name and the proxy port or empty when url is empty.
[ "Given", "a", "proxy", "URL", "returns", "a", "two", "element", "arrays", "containing", "the", "host", "name", "and", "the", "port" ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/core/src/main/java/org/seedstack/seed/core/internal/init/ProxyManager.java#L188-L220
4,321
seedstack/seed
core/src/main/java/org/seedstack/seed/core/internal/init/ProxyManager.java
ProxyManager.makePattern
private Pattern makePattern(String noProxy) { String regex = noProxy.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*"); if (!regex.startsWith(".*")) { regex = ".*" + regex; } regex = "^" + regex + "$"; return Pattern.compile(regex); }
java
private Pattern makePattern(String noProxy) { String regex = noProxy.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*"); if (!regex.startsWith(".*")) { regex = ".*" + regex; } regex = "^" + regex + "$"; return Pattern.compile(regex); }
[ "private", "Pattern", "makePattern", "(", "String", "noProxy", ")", "{", "String", "regex", "=", "noProxy", ".", "replaceAll", "(", "\"\\\\.\"", ",", "\"\\\\\\\\.\"", ")", ".", "replaceAll", "(", "\"\\\\*\"", ",", "\".*\"", ")", ";", "if", "(", "!", "regex", ".", "startsWith", "(", "\".*\"", ")", ")", "{", "regex", "=", "\".*\"", "+", "regex", ";", "}", "regex", "=", "\"^\"", "+", "regex", "+", "\"$\"", ";", "return", "Pattern", ".", "compile", "(", "regex", ")", ";", "}" ]
Creates a regexp pattern equivalent to the classic noProxy wildcard expression. @param noProxy the noProxy expression. @return the regexp pattern.
[ "Creates", "a", "regexp", "pattern", "equivalent", "to", "the", "classic", "noProxy", "wildcard", "expression", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/core/src/main/java/org/seedstack/seed/core/internal/init/ProxyManager.java#L228-L235
4,322
seedstack/seed
core/src/main/java/org/seedstack/seed/core/internal/transaction/AbstractTransactionManager.java
AbstractTransactionManager.doInvocation
protected Object doInvocation(TransactionLogger transactionLogger, MethodInvocation invocation, TransactionMetadata transactionMetadata, Object currentTransaction) throws Throwable { Object result = null; try { transactionLogger.log("invocation started", transactionLogger); result = invocation.proceed(); transactionLogger.log("invocation ended", transactionLogger); } catch (Exception exception) { doHandleException(transactionLogger, exception, transactionMetadata, currentTransaction); } return result; }
java
protected Object doInvocation(TransactionLogger transactionLogger, MethodInvocation invocation, TransactionMetadata transactionMetadata, Object currentTransaction) throws Throwable { Object result = null; try { transactionLogger.log("invocation started", transactionLogger); result = invocation.proceed(); transactionLogger.log("invocation ended", transactionLogger); } catch (Exception exception) { doHandleException(transactionLogger, exception, transactionMetadata, currentTransaction); } return result; }
[ "protected", "Object", "doInvocation", "(", "TransactionLogger", "transactionLogger", ",", "MethodInvocation", "invocation", ",", "TransactionMetadata", "transactionMetadata", ",", "Object", "currentTransaction", ")", "throws", "Throwable", "{", "Object", "result", "=", "null", ";", "try", "{", "transactionLogger", ".", "log", "(", "\"invocation started\"", ",", "transactionLogger", ")", ";", "result", "=", "invocation", ".", "proceed", "(", ")", ";", "transactionLogger", ".", "log", "(", "\"invocation ended\"", ",", "transactionLogger", ")", ";", "}", "catch", "(", "Exception", "exception", ")", "{", "doHandleException", "(", "transactionLogger", ",", "exception", ",", "transactionMetadata", ",", "currentTransaction", ")", ";", "}", "return", "result", ";", "}" ]
This method call the wrapped transactional method. @param transactionLogger The object that must be used to log transaction progress. @param invocation the {@link MethodInvocation} denoting the transactional method. @param transactionMetadata the current transaction metadata. @param currentTransaction the current transaction object if any. @return the return value of the transactional method. @throws Throwable if an exception occurs during the method invocation.
[ "This", "method", "call", "the", "wrapped", "transactional", "method", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/core/src/main/java/org/seedstack/seed/core/internal/transaction/AbstractTransactionManager.java#L73-L84
4,323
seedstack/seed
core/src/main/java/org/seedstack/seed/core/internal/guice/BindingUtils.java
BindingUtils.isBindable
public static boolean isBindable(Class<?> subClass) { return !subClass.isInterface() && !Modifier.isAbstract( subClass.getModifiers()) && subClass.getTypeParameters().length == 0; }
java
public static boolean isBindable(Class<?> subClass) { return !subClass.isInterface() && !Modifier.isAbstract( subClass.getModifiers()) && subClass.getTypeParameters().length == 0; }
[ "public", "static", "boolean", "isBindable", "(", "Class", "<", "?", ">", "subClass", ")", "{", "return", "!", "subClass", ".", "isInterface", "(", ")", "&&", "!", "Modifier", ".", "isAbstract", "(", "subClass", ".", "getModifiers", "(", ")", ")", "&&", "subClass", ".", "getTypeParameters", "(", ")", ".", "length", "==", "0", ";", "}" ]
Checks if the class is not an interface, an abstract class or a class with unresolved generics. @param subClass the class to check @return true if the class verify the condition, false otherwise
[ "Checks", "if", "the", "class", "is", "not", "an", "interface", "an", "abstract", "class", "or", "a", "class", "with", "unresolved", "generics", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/core/src/main/java/org/seedstack/seed/core/internal/guice/BindingUtils.java#L143-L146
4,324
seedstack/seed
rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/Resource.java
Resource.hrefTemplate
public String hrefTemplate() { UriTemplateBuilder uriTemplateBuilder = UriTemplate.buildFromTemplate(hrefTemplate); if (!queryParams.isEmpty()) { uriTemplateBuilder = uriTemplateBuilder.query( queryParams.keySet().toArray(new String[queryParams.keySet().size()])); } return uriTemplateBuilder.build().getTemplate(); }
java
public String hrefTemplate() { UriTemplateBuilder uriTemplateBuilder = UriTemplate.buildFromTemplate(hrefTemplate); if (!queryParams.isEmpty()) { uriTemplateBuilder = uriTemplateBuilder.query( queryParams.keySet().toArray(new String[queryParams.keySet().size()])); } return uriTemplateBuilder.build().getTemplate(); }
[ "public", "String", "hrefTemplate", "(", ")", "{", "UriTemplateBuilder", "uriTemplateBuilder", "=", "UriTemplate", ".", "buildFromTemplate", "(", "hrefTemplate", ")", ";", "if", "(", "!", "queryParams", ".", "isEmpty", "(", ")", ")", "{", "uriTemplateBuilder", "=", "uriTemplateBuilder", ".", "query", "(", "queryParams", ".", "keySet", "(", ")", ".", "toArray", "(", "new", "String", "[", "queryParams", ".", "keySet", "(", ")", ".", "size", "(", ")", "]", ")", ")", ";", "}", "return", "uriTemplateBuilder", ".", "build", "(", ")", ".", "getTemplate", "(", ")", ";", "}" ]
Return the href template. It's empty unless the path is templated. @return hrefTemplate
[ "Return", "the", "href", "template", ".", "It", "s", "empty", "unless", "the", "path", "is", "templated", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/Resource.java#L92-L99
4,325
seedstack/seed
rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/Resource.java
Resource.hrefVars
public Map<String, String> hrefVars() { Map<String, String> map = new HashMap<>(pathParams); map.putAll(queryParams); return map; }
java
public Map<String, String> hrefVars() { Map<String, String> map = new HashMap<>(pathParams); map.putAll(queryParams); return map; }
[ "public", "Map", "<", "String", ",", "String", ">", "hrefVars", "(", ")", "{", "Map", "<", "String", ",", "String", ">", "map", "=", "new", "HashMap", "<>", "(", "pathParams", ")", ";", "map", ".", "putAll", "(", "queryParams", ")", ";", "return", "map", ";", "}" ]
Return the hrefVars. It's empty unless the path is templated. @return hrefVars
[ "Return", "the", "hrefVars", ".", "It", "s", "empty", "unless", "the", "path", "is", "templated", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/Resource.java#L106-L110
4,326
seedstack/seed
rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/Resource.java
Resource.merge
public void merge(Resource resource) { if (resource == null) { return; } checkRel(resource); checkHrefs(resource); if (resource.templated()) { this.pathParams.putAll(resource.pathParams); this.queryParams.putAll(resource.queryParams); } if (resource.hints() != null) { this.hints.merge(resource.hints()); } }
java
public void merge(Resource resource) { if (resource == null) { return; } checkRel(resource); checkHrefs(resource); if (resource.templated()) { this.pathParams.putAll(resource.pathParams); this.queryParams.putAll(resource.queryParams); } if (resource.hints() != null) { this.hints.merge(resource.hints()); } }
[ "public", "void", "merge", "(", "Resource", "resource", ")", "{", "if", "(", "resource", "==", "null", ")", "{", "return", ";", "}", "checkRel", "(", "resource", ")", ";", "checkHrefs", "(", "resource", ")", ";", "if", "(", "resource", ".", "templated", "(", ")", ")", "{", "this", ".", "pathParams", ".", "putAll", "(", "resource", ".", "pathParams", ")", ";", "this", ".", "queryParams", ".", "putAll", "(", "resource", ".", "queryParams", ")", ";", "}", "if", "(", "resource", ".", "hints", "(", ")", "!=", "null", ")", "{", "this", ".", "hints", ".", "merge", "(", "resource", ".", "hints", "(", ")", ")", ";", "}", "}" ]
Merges the current resource with another resource instance. The merge objects must represent the same resource but can come from multiple methods. @param resource the resource object to merge
[ "Merges", "the", "current", "resource", "with", "another", "resource", "instance", ".", "The", "merge", "objects", "must", "represent", "the", "same", "resource", "but", "can", "come", "from", "multiple", "methods", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/Resource.java#L137-L152
4,327
seedstack/seed
rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/Resource.java
Resource.toRepresentation
public Map<String, Object> toRepresentation() { Map<String, Object> representation = new HashMap<>(); if (templated()) { representation.put("href-template", hrefTemplate); representation.put("href-vars", hrefVars()); } else { representation.put("href", href); } if (hints != null) { Map<String, Object> hintsRepresentation = hints.toRepresentation(); if (!hintsRepresentation.isEmpty()) { representation.put("hints", hintsRepresentation); } } return representation; }
java
public Map<String, Object> toRepresentation() { Map<String, Object> representation = new HashMap<>(); if (templated()) { representation.put("href-template", hrefTemplate); representation.put("href-vars", hrefVars()); } else { representation.put("href", href); } if (hints != null) { Map<String, Object> hintsRepresentation = hints.toRepresentation(); if (!hintsRepresentation.isEmpty()) { representation.put("hints", hintsRepresentation); } } return representation; }
[ "public", "Map", "<", "String", ",", "Object", ">", "toRepresentation", "(", ")", "{", "Map", "<", "String", ",", "Object", ">", "representation", "=", "new", "HashMap", "<>", "(", ")", ";", "if", "(", "templated", "(", ")", ")", "{", "representation", ".", "put", "(", "\"href-template\"", ",", "hrefTemplate", ")", ";", "representation", ".", "put", "(", "\"href-vars\"", ",", "hrefVars", "(", ")", ")", ";", "}", "else", "{", "representation", ".", "put", "(", "\"href\"", ",", "href", ")", ";", "}", "if", "(", "hints", "!=", "null", ")", "{", "Map", "<", "String", ",", "Object", ">", "hintsRepresentation", "=", "hints", ".", "toRepresentation", "(", ")", ";", "if", "(", "!", "hintsRepresentation", ".", "isEmpty", "(", ")", ")", "{", "representation", ".", "put", "(", "\"hints\"", ",", "hintsRepresentation", ")", ";", "}", "}", "return", "representation", ";", "}" ]
Serializes the resource into a map. @return the resource map
[ "Serializes", "the", "resource", "into", "a", "map", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/Resource.java#L196-L211
4,328
seedstack/seed
security/core/src/main/java/org/seedstack/seed/security/internal/authorization/SeedAuthorizationInfo.java
SeedAuthorizationInfo.addRole
public void addRole(Role role) { apiRoles.add(role); roles.add(role.getName()); for (org.seedstack.seed.security.Permission permission : role.getPermissions()) { if (!role.getScopes().isEmpty()) { for (Scope scope : role.getScopes()) { ScopePermission sp = new ScopePermission(permission.getPermission(), scope); scopePermissions.add(sp); } } else { stringPermissions.add(permission.getPermission()); } } }
java
public void addRole(Role role) { apiRoles.add(role); roles.add(role.getName()); for (org.seedstack.seed.security.Permission permission : role.getPermissions()) { if (!role.getScopes().isEmpty()) { for (Scope scope : role.getScopes()) { ScopePermission sp = new ScopePermission(permission.getPermission(), scope); scopePermissions.add(sp); } } else { stringPermissions.add(permission.getPermission()); } } }
[ "public", "void", "addRole", "(", "Role", "role", ")", "{", "apiRoles", ".", "add", "(", "role", ")", ";", "roles", ".", "add", "(", "role", ".", "getName", "(", ")", ")", ";", "for", "(", "org", ".", "seedstack", ".", "seed", ".", "security", ".", "Permission", "permission", ":", "role", ".", "getPermissions", "(", ")", ")", "{", "if", "(", "!", "role", ".", "getScopes", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "for", "(", "Scope", "scope", ":", "role", ".", "getScopes", "(", ")", ")", "{", "ScopePermission", "sp", "=", "new", "ScopePermission", "(", "permission", ".", "getPermission", "(", ")", ",", "scope", ")", ";", "scopePermissions", ".", "add", "(", "sp", ")", ";", "}", "}", "else", "{", "stringPermissions", ".", "add", "(", "permission", ".", "getPermission", "(", ")", ")", ";", "}", "}", "}" ]
Adds a role and its permissions to the authorization info. @param role the role to add.
[ "Adds", "a", "role", "and", "its", "permissions", "to", "the", "authorization", "info", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/security/core/src/main/java/org/seedstack/seed/security/internal/authorization/SeedAuthorizationInfo.java#L56-L69
4,329
seedstack/seed
rest/core/src/main/java/org/seedstack/seed/rest/internal/UriBuilder.java
UriBuilder.stripLeadingSlash
static String stripLeadingSlash(String path) { if (path.endsWith("/")) { return path.substring(0, path.length() - 1); } else { return path; } }
java
static String stripLeadingSlash(String path) { if (path.endsWith("/")) { return path.substring(0, path.length() - 1); } else { return path; } }
[ "static", "String", "stripLeadingSlash", "(", "String", "path", ")", "{", "if", "(", "path", ".", "endsWith", "(", "\"/\"", ")", ")", "{", "return", "path", ".", "substring", "(", "0", ",", "path", ".", "length", "(", ")", "-", "1", ")", ";", "}", "else", "{", "return", "path", ";", "}", "}" ]
Removes the leading slash in the given path. @param path the path @return the new path
[ "Removes", "the", "leading", "slash", "in", "the", "given", "path", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/core/src/main/java/org/seedstack/seed/rest/internal/UriBuilder.java#L54-L60
4,330
seedstack/seed
rest/core/src/main/java/org/seedstack/seed/rest/internal/UriBuilder.java
UriBuilder.jaxTemplate
static boolean jaxTemplate(String href) { Matcher m = JAX_RS_TEMPLATE.matcher(href); return m.matches(); }
java
static boolean jaxTemplate(String href) { Matcher m = JAX_RS_TEMPLATE.matcher(href); return m.matches(); }
[ "static", "boolean", "jaxTemplate", "(", "String", "href", ")", "{", "Matcher", "m", "=", "JAX_RS_TEMPLATE", ".", "matcher", "(", "href", ")", ";", "return", "m", ".", "matches", "(", ")", ";", "}" ]
Returns whether the href is a JAX-RS template. @param href the href to check @return true if the href is templated, false otherwise
[ "Returns", "whether", "the", "href", "is", "a", "JAX", "-", "RS", "template", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/core/src/main/java/org/seedstack/seed/rest/internal/UriBuilder.java#L93-L96
4,331
seedstack/seed
core/src/main/java/org/seedstack/seed/core/Seed.java
Seed.translateException
public static BaseException translateException(Exception exception) { if (exception instanceof BaseException) { return (BaseException) exception; } else { for (SeedExceptionTranslator exceptionTranslator : exceptionTranslators) { if (exceptionTranslator.canTranslate(exception)) { return exceptionTranslator.translate(exception); } } return SeedException.wrap(exception, CoreErrorCode.UNEXPECTED_EXCEPTION); } }
java
public static BaseException translateException(Exception exception) { if (exception instanceof BaseException) { return (BaseException) exception; } else { for (SeedExceptionTranslator exceptionTranslator : exceptionTranslators) { if (exceptionTranslator.canTranslate(exception)) { return exceptionTranslator.translate(exception); } } return SeedException.wrap(exception, CoreErrorCode.UNEXPECTED_EXCEPTION); } }
[ "public", "static", "BaseException", "translateException", "(", "Exception", "exception", ")", "{", "if", "(", "exception", "instanceof", "BaseException", ")", "{", "return", "(", "BaseException", ")", "exception", ";", "}", "else", "{", "for", "(", "SeedExceptionTranslator", "exceptionTranslator", ":", "exceptionTranslators", ")", "{", "if", "(", "exceptionTranslator", ".", "canTranslate", "(", "exception", ")", ")", "{", "return", "exceptionTranslator", ".", "translate", "(", "exception", ")", ";", "}", "}", "return", "SeedException", ".", "wrap", "(", "exception", ",", "CoreErrorCode", ".", "UNEXPECTED_EXCEPTION", ")", ";", "}", "}" ]
Translates any exception that occurred in the application using an extensible exception mechanism. @param exception the exception to handle. @return the translated exception.
[ "Translates", "any", "exception", "that", "occurred", "in", "the", "application", "using", "an", "extensible", "exception", "mechanism", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/core/src/main/java/org/seedstack/seed/core/Seed.java#L240-L251
4,332
seedstack/seed
core/src/main/java/org/seedstack/seed/core/internal/jndi/JndiPlugin.java
JndiPlugin.getJndiContexts
public Map<String, Context> getJndiContexts() { Map<String, Context> jndiContexts = new HashMap<>(); jndiContexts.putAll(additionalJndiContexts); jndiContexts.put("default", defaultJndiContext); return jndiContexts; }
java
public Map<String, Context> getJndiContexts() { Map<String, Context> jndiContexts = new HashMap<>(); jndiContexts.putAll(additionalJndiContexts); jndiContexts.put("default", defaultJndiContext); return jndiContexts; }
[ "public", "Map", "<", "String", ",", "Context", ">", "getJndiContexts", "(", ")", "{", "Map", "<", "String", ",", "Context", ">", "jndiContexts", "=", "new", "HashMap", "<>", "(", ")", ";", "jndiContexts", ".", "putAll", "(", "additionalJndiContexts", ")", ";", "jndiContexts", ".", "put", "(", "\"default\"", ",", "defaultJndiContext", ")", ";", "return", "jndiContexts", ";", "}" ]
Retrieve all configured JNDI contexts. @return the map of all configured JNDI contexts.
[ "Retrieve", "all", "configured", "JNDI", "contexts", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/core/src/main/java/org/seedstack/seed/core/internal/jndi/JndiPlugin.java#L95-L100
4,333
seedstack/seed
rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/HintScanner.java
HintScanner.findHint
public Hints findHint(Method method) { Hints hints = new Hints(); for (Annotation annotation : method.getDeclaredAnnotations()) { findAllow(hints, annotation); findFormats(hints, annotation); } return hints; }
java
public Hints findHint(Method method) { Hints hints = new Hints(); for (Annotation annotation : method.getDeclaredAnnotations()) { findAllow(hints, annotation); findFormats(hints, annotation); } return hints; }
[ "public", "Hints", "findHint", "(", "Method", "method", ")", "{", "Hints", "hints", "=", "new", "Hints", "(", ")", ";", "for", "(", "Annotation", "annotation", ":", "method", ".", "getDeclaredAnnotations", "(", ")", ")", "{", "findAllow", "(", "hints", ",", "annotation", ")", ";", "findFormats", "(", "hints", ",", "annotation", ")", ";", "}", "return", "hints", ";", "}" ]
Finds the JSON-HOME hints on the given method. @param method the method to scan @return the hints
[ "Finds", "the", "JSON", "-", "HOME", "hints", "on", "the", "given", "method", "." ]
d9cf33bfb2fffcdbb0976f4726e943acda90e828
https://github.com/seedstack/seed/blob/d9cf33bfb2fffcdbb0976f4726e943acda90e828/rest/core/src/main/java/org/seedstack/seed/rest/internal/jsonhome/HintScanner.java#L27-L34
4,334
twotoasters/JazzyListView
library/src/main/java/com/twotoasters/jazzylistview/JazzyHelper.java
JazzyHelper.setVelocity
private void setVelocity(int firstVisibleItem, int totalItemCount) { if (mMaxVelocity > MAX_VELOCITY_OFF && mPreviousFirstVisibleItem != firstVisibleItem) { long currTime = System.currentTimeMillis(); long timeToScrollOneItem = currTime - mPreviousEventTime; if (timeToScrollOneItem < 1) { double newSpeed = ((1.0d / timeToScrollOneItem) * 1000); // We need to normalize velocity so different size item don't // give largely different velocities. if (newSpeed < (0.9f * mSpeed)) { mSpeed *= 0.9f; } else if (newSpeed > (1.1f * mSpeed)) { mSpeed *= 1.1f; } else { mSpeed = newSpeed; } } else { mSpeed = ((1.0d / timeToScrollOneItem) * 1000); } mPreviousFirstVisibleItem = firstVisibleItem; mPreviousEventTime = currTime; } }
java
private void setVelocity(int firstVisibleItem, int totalItemCount) { if (mMaxVelocity > MAX_VELOCITY_OFF && mPreviousFirstVisibleItem != firstVisibleItem) { long currTime = System.currentTimeMillis(); long timeToScrollOneItem = currTime - mPreviousEventTime; if (timeToScrollOneItem < 1) { double newSpeed = ((1.0d / timeToScrollOneItem) * 1000); // We need to normalize velocity so different size item don't // give largely different velocities. if (newSpeed < (0.9f * mSpeed)) { mSpeed *= 0.9f; } else if (newSpeed > (1.1f * mSpeed)) { mSpeed *= 1.1f; } else { mSpeed = newSpeed; } } else { mSpeed = ((1.0d / timeToScrollOneItem) * 1000); } mPreviousFirstVisibleItem = firstVisibleItem; mPreviousEventTime = currTime; } }
[ "private", "void", "setVelocity", "(", "int", "firstVisibleItem", ",", "int", "totalItemCount", ")", "{", "if", "(", "mMaxVelocity", ">", "MAX_VELOCITY_OFF", "&&", "mPreviousFirstVisibleItem", "!=", "firstVisibleItem", ")", "{", "long", "currTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "long", "timeToScrollOneItem", "=", "currTime", "-", "mPreviousEventTime", ";", "if", "(", "timeToScrollOneItem", "<", "1", ")", "{", "double", "newSpeed", "=", "(", "(", "1.0d", "/", "timeToScrollOneItem", ")", "*", "1000", ")", ";", "// We need to normalize velocity so different size item don't", "// give largely different velocities.", "if", "(", "newSpeed", "<", "(", "0.9f", "*", "mSpeed", ")", ")", "{", "mSpeed", "*=", "0.9f", ";", "}", "else", "if", "(", "newSpeed", ">", "(", "1.1f", "*", "mSpeed", ")", ")", "{", "mSpeed", "*=", "1.1f", ";", "}", "else", "{", "mSpeed", "=", "newSpeed", ";", "}", "}", "else", "{", "mSpeed", "=", "(", "(", "1.0d", "/", "timeToScrollOneItem", ")", "*", "1000", ")", ";", "}", "mPreviousFirstVisibleItem", "=", "firstVisibleItem", ";", "mPreviousEventTime", "=", "currTime", ";", "}", "}" ]
Should be called in onScroll to keep take of current Velocity. @param firstVisibleItem The index of the first visible item in the ListView.
[ "Should", "be", "called", "in", "onScroll", "to", "keep", "take", "of", "current", "Velocity", "." ]
4a69239f90374a71e7d4073448ca049bd074f7fe
https://github.com/twotoasters/JazzyListView/blob/4a69239f90374a71e7d4073448ca049bd074f7fe/library/src/main/java/com/twotoasters/jazzylistview/JazzyHelper.java#L156-L178
4,335
twotoasters/JazzyListView
library/src/main/java/com/twotoasters/jazzylistview/JazzyHelper.java
JazzyHelper.doJazziness
private void doJazziness(View item, int position, int scrollDirection) { if (mIsScrolling) { if (mOnlyAnimateNewItems && mAlreadyAnimatedItems.contains(position)) return; if (mOnlyAnimateOnFling && !mIsFlingEvent) return; if (mMaxVelocity > MAX_VELOCITY_OFF && mMaxVelocity < mSpeed) return; if (mSimulateGridWithList) { ViewGroup itemRow = (ViewGroup) item; for (int i = 0; i < itemRow.getChildCount(); i++) doJazzinessImpl(itemRow.getChildAt(i), position, scrollDirection); } else { doJazzinessImpl(item, position, scrollDirection); } mAlreadyAnimatedItems.add(position); } }
java
private void doJazziness(View item, int position, int scrollDirection) { if (mIsScrolling) { if (mOnlyAnimateNewItems && mAlreadyAnimatedItems.contains(position)) return; if (mOnlyAnimateOnFling && !mIsFlingEvent) return; if (mMaxVelocity > MAX_VELOCITY_OFF && mMaxVelocity < mSpeed) return; if (mSimulateGridWithList) { ViewGroup itemRow = (ViewGroup) item; for (int i = 0; i < itemRow.getChildCount(); i++) doJazzinessImpl(itemRow.getChildAt(i), position, scrollDirection); } else { doJazzinessImpl(item, position, scrollDirection); } mAlreadyAnimatedItems.add(position); } }
[ "private", "void", "doJazziness", "(", "View", "item", ",", "int", "position", ",", "int", "scrollDirection", ")", "{", "if", "(", "mIsScrolling", ")", "{", "if", "(", "mOnlyAnimateNewItems", "&&", "mAlreadyAnimatedItems", ".", "contains", "(", "position", ")", ")", "return", ";", "if", "(", "mOnlyAnimateOnFling", "&&", "!", "mIsFlingEvent", ")", "return", ";", "if", "(", "mMaxVelocity", ">", "MAX_VELOCITY_OFF", "&&", "mMaxVelocity", "<", "mSpeed", ")", "return", ";", "if", "(", "mSimulateGridWithList", ")", "{", "ViewGroup", "itemRow", "=", "(", "ViewGroup", ")", "item", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "itemRow", ".", "getChildCount", "(", ")", ";", "i", "++", ")", "doJazzinessImpl", "(", "itemRow", ".", "getChildAt", "(", "i", ")", "", ",", "position", ",", "scrollDirection", ")", ";", "}", "else", "{", "doJazzinessImpl", "(", "item", ",", "position", ",", "scrollDirection", ")", ";", "}", "mAlreadyAnimatedItems", ".", "add", "(", "position", ")", ";", "}", "}" ]
Initializes the item view and triggers the animation. @param item The view to be animated. @param position The index of the view in the list. @param scrollDirection Positive number indicating scrolling down, or negative number indicating scrolling up.
[ "Initializes", "the", "item", "view", "and", "triggers", "the", "animation", "." ]
4a69239f90374a71e7d4073448ca049bd074f7fe
https://github.com/twotoasters/JazzyListView/blob/4a69239f90374a71e7d4073448ca049bd074f7fe/library/src/main/java/com/twotoasters/jazzylistview/JazzyHelper.java#L188-L209
4,336
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/result/MultiAnalysisResult.java
MultiAnalysisResult.getResultFor
public QueryResult getResultFor(String subAnalysisLabel) { if (!this.analysesResults.containsKey(subAnalysisLabel)) { throw new IllegalArgumentException("No results for a sub-analysis with that label."); } return this.analysesResults.get(subAnalysisLabel); }
java
public QueryResult getResultFor(String subAnalysisLabel) { if (!this.analysesResults.containsKey(subAnalysisLabel)) { throw new IllegalArgumentException("No results for a sub-analysis with that label."); } return this.analysesResults.get(subAnalysisLabel); }
[ "public", "QueryResult", "getResultFor", "(", "String", "subAnalysisLabel", ")", "{", "if", "(", "!", "this", ".", "analysesResults", ".", "containsKey", "(", "subAnalysisLabel", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No results for a sub-analysis with that label.\"", ")", ";", "}", "return", "this", ".", "analysesResults", ".", "get", "(", "subAnalysisLabel", ")", ";", "}" ]
Provides the result for a sub-analysis. @param subAnalysisLabel The label that was assigned to this sub-analysis in the MultiAnalysis request. @return The result of the given sub-analysis.
[ "Provides", "the", "result", "for", "a", "sub", "-", "analysis", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/query/src/main/java/io/keen/client/java/result/MultiAnalysisResult.java#L30-L36
4,337
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.initialize
public static void initialize(KeenClient client) { if (client == null) { throw new IllegalArgumentException("Client must not be null"); } if (ClientSingleton.INSTANCE.client != null) { // Do nothing. return; } ClientSingleton.INSTANCE.client = client; }
java
public static void initialize(KeenClient client) { if (client == null) { throw new IllegalArgumentException("Client must not be null"); } if (ClientSingleton.INSTANCE.client != null) { // Do nothing. return; } ClientSingleton.INSTANCE.client = client; }
[ "public", "static", "void", "initialize", "(", "KeenClient", "client", ")", "{", "if", "(", "client", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Client must not be null\"", ")", ";", "}", "if", "(", "ClientSingleton", ".", "INSTANCE", ".", "client", "!=", "null", ")", "{", "// Do nothing.", "return", ";", "}", "ClientSingleton", ".", "INSTANCE", ".", "client", "=", "client", ";", "}" ]
Initializes the static Keen client. Only the first call to this method has any effect. All subsequent calls are ignored. @param client The {@link io.keen.client.java.KeenClient} implementation to use as the singleton client for the library.
[ "Initializes", "the", "static", "Keen", "client", ".", "Only", "the", "first", "call", "to", "this", "method", "has", "any", "effect", ".", "All", "subsequent", "calls", "are", "ignored", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L81-L92
4,338
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.addEvent
public void addEvent(KeenProject project, String eventCollection, Map<String, Object> event, Map<String, Object> keenProperties, KeenCallback callback) { if (!isActive) { handleLibraryInactive(callback); return; } if (project == null && defaultProject == null) { handleFailure(null, project, eventCollection, event, keenProperties, new IllegalStateException("No project specified, but no default project found")); return; } KeenProject useProject = (project == null ? defaultProject : project); try { // Build the event. Map<String, Object> newEvent = validateAndBuildEvent(useProject, eventCollection, event, keenProperties); // Publish the event. publish(useProject, eventCollection, newEvent); handleSuccess(callback, project, eventCollection, event, keenProperties); } catch (Exception e) { handleFailure(callback, project, eventCollection, event, keenProperties, e); } }
java
public void addEvent(KeenProject project, String eventCollection, Map<String, Object> event, Map<String, Object> keenProperties, KeenCallback callback) { if (!isActive) { handleLibraryInactive(callback); return; } if (project == null && defaultProject == null) { handleFailure(null, project, eventCollection, event, keenProperties, new IllegalStateException("No project specified, but no default project found")); return; } KeenProject useProject = (project == null ? defaultProject : project); try { // Build the event. Map<String, Object> newEvent = validateAndBuildEvent(useProject, eventCollection, event, keenProperties); // Publish the event. publish(useProject, eventCollection, newEvent); handleSuccess(callback, project, eventCollection, event, keenProperties); } catch (Exception e) { handleFailure(callback, project, eventCollection, event, keenProperties, e); } }
[ "public", "void", "addEvent", "(", "KeenProject", "project", ",", "String", "eventCollection", ",", "Map", "<", "String", ",", "Object", ">", "event", ",", "Map", "<", "String", ",", "Object", ">", "keenProperties", ",", "KeenCallback", "callback", ")", "{", "if", "(", "!", "isActive", ")", "{", "handleLibraryInactive", "(", "callback", ")", ";", "return", ";", "}", "if", "(", "project", "==", "null", "&&", "defaultProject", "==", "null", ")", "{", "handleFailure", "(", "null", ",", "project", ",", "eventCollection", ",", "event", ",", "keenProperties", ",", "new", "IllegalStateException", "(", "\"No project specified, but no default project found\"", ")", ")", ";", "return", ";", "}", "KeenProject", "useProject", "=", "(", "project", "==", "null", "?", "defaultProject", ":", "project", ")", ";", "try", "{", "// Build the event.", "Map", "<", "String", ",", "Object", ">", "newEvent", "=", "validateAndBuildEvent", "(", "useProject", ",", "eventCollection", ",", "event", ",", "keenProperties", ")", ";", "// Publish the event.", "publish", "(", "useProject", ",", "eventCollection", ",", "newEvent", ")", ";", "handleSuccess", "(", "callback", ",", "project", ",", "eventCollection", ",", "event", ",", "keenProperties", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "handleFailure", "(", "callback", ",", "project", ",", "eventCollection", ",", "event", ",", "keenProperties", ",", "e", ")", ";", "}", "}" ]
Synchronously adds an event to the specified collection. This method will immediately publish the event to the Keen server in the current thread. @param project The project in which to publish the event. If a default project has been set on the client, this parameter may be null, in which case the default project will be used. @param eventCollection The name of the collection in which to publish the event. @param event A Map that consists of key/value pairs. Keen naming conventions apply (see docs). Nested Maps and lists are acceptable (and encouraged!). @param keenProperties A Map that consists of key/value pairs to override default properties. ex: "timestamp" -&gt; Calendar.getInstance() @param callback An optional callback to receive notification of success or failure.
[ "Synchronously", "adds", "an", "event", "to", "the", "specified", "collection", ".", "This", "method", "will", "immediately", "publish", "the", "event", "to", "the", "Keen", "server", "in", "the", "current", "thread", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L146-L176
4,339
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.queueEvent
public void queueEvent(String eventCollection, Map<String, Object> event) { queueEvent(eventCollection, event, null); }
java
public void queueEvent(String eventCollection, Map<String, Object> event) { queueEvent(eventCollection, event, null); }
[ "public", "void", "queueEvent", "(", "String", "eventCollection", ",", "Map", "<", "String", ",", "Object", ">", "event", ")", "{", "queueEvent", "(", "eventCollection", ",", "event", ",", "null", ")", ";", "}" ]
Queues an event in the default project with default Keen properties and no callbacks. @see #queueEvent(KeenProject, String, java.util.Map, java.util.Map, KeenCallback) @param eventCollection The name of the collection in which to publish the event. @param event A Map that consists of key/value pairs. Keen naming conventions apply (see docs). Nested Maps and lists are acceptable (and encouraged!).
[ "Queues", "an", "event", "in", "the", "default", "project", "with", "default", "Keen", "properties", "and", "no", "callbacks", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L262-L264
4,340
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.queueEvent
public void queueEvent(String eventCollection, Map<String, Object> event, Map<String, Object> keenProperties) { queueEvent(null, eventCollection, event, keenProperties, null); }
java
public void queueEvent(String eventCollection, Map<String, Object> event, Map<String, Object> keenProperties) { queueEvent(null, eventCollection, event, keenProperties, null); }
[ "public", "void", "queueEvent", "(", "String", "eventCollection", ",", "Map", "<", "String", ",", "Object", ">", "event", ",", "Map", "<", "String", ",", "Object", ">", "keenProperties", ")", "{", "queueEvent", "(", "null", ",", "eventCollection", ",", "event", ",", "keenProperties", ",", "null", ")", ";", "}" ]
Queues an event in the default project with no callbacks. @see #queueEvent(KeenProject, String, java.util.Map, java.util.Map, KeenCallback) @param eventCollection The name of the collection in which to publish the event. @param event A Map that consists of key/value pairs. Keen naming conventions apply (see docs). Nested Maps and lists are acceptable (and encouraged!). @param keenProperties A Map that consists of key/value pairs to override default properties. ex: "timestamp" -&gt; Calendar.getInstance()
[ "Queues", "an", "event", "in", "the", "default", "project", "with", "no", "callbacks", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L276-L279
4,341
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.sendQueuedEvents
public synchronized void sendQueuedEvents(KeenProject project, KeenCallback callback) { if (!isActive) { handleLibraryInactive(callback); return; } if (project == null && defaultProject == null) { handleFailure(null, new IllegalStateException("No project specified, but no default project found")); return; } if (!isNetworkConnected()) { KeenLogging.log("Not sending events because there is no network connection. " + "Events will be retried next time `sendQueuedEvents` is called."); handleFailure(callback, new Exception("Network not connected.")); return; } KeenProject useProject = (project == null ? defaultProject : project); try { String projectId = useProject.getProjectId(); Map<String, List<Object>> eventHandles = eventStore.getHandles(projectId); Map<String, List<Map<String, Object>>> events = buildEventMap(projectId, eventHandles); String response = publishAll(useProject, events); if (response != null) { try { handleAddEventsResponse(eventHandles, response); } catch (Exception e) { // Errors handling the response are non-fatal; just log them. KeenLogging.log("Error handling response to batch publish: " + e.getMessage()); } } handleSuccess(callback); } catch (Exception e) { handleFailure(callback, e); } }
java
public synchronized void sendQueuedEvents(KeenProject project, KeenCallback callback) { if (!isActive) { handleLibraryInactive(callback); return; } if (project == null && defaultProject == null) { handleFailure(null, new IllegalStateException("No project specified, but no default project found")); return; } if (!isNetworkConnected()) { KeenLogging.log("Not sending events because there is no network connection. " + "Events will be retried next time `sendQueuedEvents` is called."); handleFailure(callback, new Exception("Network not connected.")); return; } KeenProject useProject = (project == null ? defaultProject : project); try { String projectId = useProject.getProjectId(); Map<String, List<Object>> eventHandles = eventStore.getHandles(projectId); Map<String, List<Map<String, Object>>> events = buildEventMap(projectId, eventHandles); String response = publishAll(useProject, events); if (response != null) { try { handleAddEventsResponse(eventHandles, response); } catch (Exception e) { // Errors handling the response are non-fatal; just log them. KeenLogging.log("Error handling response to batch publish: " + e.getMessage()); } } handleSuccess(callback); } catch (Exception e) { handleFailure(callback, e); } }
[ "public", "synchronized", "void", "sendQueuedEvents", "(", "KeenProject", "project", ",", "KeenCallback", "callback", ")", "{", "if", "(", "!", "isActive", ")", "{", "handleLibraryInactive", "(", "callback", ")", ";", "return", ";", "}", "if", "(", "project", "==", "null", "&&", "defaultProject", "==", "null", ")", "{", "handleFailure", "(", "null", ",", "new", "IllegalStateException", "(", "\"No project specified, but no default project found\"", ")", ")", ";", "return", ";", "}", "if", "(", "!", "isNetworkConnected", "(", ")", ")", "{", "KeenLogging", ".", "log", "(", "\"Not sending events because there is no network connection. \"", "+", "\"Events will be retried next time `sendQueuedEvents` is called.\"", ")", ";", "handleFailure", "(", "callback", ",", "new", "Exception", "(", "\"Network not connected.\"", ")", ")", ";", "return", ";", "}", "KeenProject", "useProject", "=", "(", "project", "==", "null", "?", "defaultProject", ":", "project", ")", ";", "try", "{", "String", "projectId", "=", "useProject", ".", "getProjectId", "(", ")", ";", "Map", "<", "String", ",", "List", "<", "Object", ">", ">", "eventHandles", "=", "eventStore", ".", "getHandles", "(", "projectId", ")", ";", "Map", "<", "String", ",", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", ">", "events", "=", "buildEventMap", "(", "projectId", ",", "eventHandles", ")", ";", "String", "response", "=", "publishAll", "(", "useProject", ",", "events", ")", ";", "if", "(", "response", "!=", "null", ")", "{", "try", "{", "handleAddEventsResponse", "(", "eventHandles", ",", "response", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// Errors handling the response are non-fatal; just log them.", "KeenLogging", ".", "log", "(", "\"Error handling response to batch publish: \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}", "handleSuccess", "(", "callback", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "handleFailure", "(", "callback", ",", "e", ")", ";", "}", "}" ]
Synchronously sends all queued events for the given project. This method will immediately publish the events to the Keen server in the current thread. @param project The project for which to send queued events. If a default project has been set on the client this parameter may be null, in which case the default project will be used. @param callback An optional callback to receive notification of success or failure.
[ "Synchronously", "sends", "all", "queued", "events", "for", "the", "given", "project", ".", "This", "method", "will", "immediately", "publish", "the", "events", "to", "the", "Keen", "server", "in", "the", "current", "thread", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L378-L416
4,342
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.setProxy
public void setProxy(String proxyHost, int proxyPort) { this.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); }
java
public void setProxy(String proxyHost, int proxyPort) { this.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); }
[ "public", "void", "setProxy", "(", "String", "proxyHost", ",", "int", "proxyPort", ")", "{", "this", ".", "proxy", "=", "new", "Proxy", "(", "Proxy", ".", "Type", ".", "HTTP", ",", "new", "InetSocketAddress", "(", "proxyHost", ",", "proxyPort", ")", ")", ";", "}" ]
Sets an HTTP proxy server configuration for this client. @param proxyHost The proxy hostname or IP address. @param proxyPort The proxy port number.
[ "Sets", "an", "HTTP", "proxy", "server", "configuration", "for", "this", "client", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L688-L690
4,343
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.validateAndBuildEvent
protected Map<String, Object> validateAndBuildEvent(KeenProject project, String eventCollection, Map<String, Object> event, Map<String, Object> keenProperties) { if (project.getWriteKey() == null) { throw new NoWriteKeyException("You can't send events to Keen if you haven't set a write key."); } validateEventCollection(eventCollection); validateEvent(event); KeenLogging.log(String.format(Locale.US, "Adding event to collection: %s", eventCollection)); // Create maps to aggregate keen & non-keen properties Map<String, Object> newEvent = new HashMap<String, Object>(); Map<String, Object> mergedKeenProperties = new HashMap<String, Object>(); // separate keen & non-keen properties from static globals and merge them into separate maps if (null != globalProperties) { mergeGlobalProperties(getGlobalProperties(), mergedKeenProperties, newEvent); } // separate keen & non-keen properties from dynamic globals and merge them into separate maps GlobalPropertiesEvaluator globalPropertiesEvaluator = getGlobalPropertiesEvaluator(); if (globalPropertiesEvaluator != null) { mergeGlobalProperties(globalPropertiesEvaluator.getGlobalProperties(eventCollection), mergedKeenProperties, newEvent); } // merge any per-event keen properties if (keenProperties != null) { mergedKeenProperties.putAll(keenProperties); } // if no keen.timestamp was provided by globals or event, add one now if (!mergedKeenProperties.containsKey("timestamp")) { Calendar currentTime = Calendar.getInstance(); String timestamp = ISO_8601_FORMAT.format(currentTime.getTime()); mergedKeenProperties.put("timestamp", timestamp); } // add merged keen properties to event newEvent.put("keen", mergedKeenProperties); // merge any per-event non-keen properties newEvent.putAll(event); return newEvent; }
java
protected Map<String, Object> validateAndBuildEvent(KeenProject project, String eventCollection, Map<String, Object> event, Map<String, Object> keenProperties) { if (project.getWriteKey() == null) { throw new NoWriteKeyException("You can't send events to Keen if you haven't set a write key."); } validateEventCollection(eventCollection); validateEvent(event); KeenLogging.log(String.format(Locale.US, "Adding event to collection: %s", eventCollection)); // Create maps to aggregate keen & non-keen properties Map<String, Object> newEvent = new HashMap<String, Object>(); Map<String, Object> mergedKeenProperties = new HashMap<String, Object>(); // separate keen & non-keen properties from static globals and merge them into separate maps if (null != globalProperties) { mergeGlobalProperties(getGlobalProperties(), mergedKeenProperties, newEvent); } // separate keen & non-keen properties from dynamic globals and merge them into separate maps GlobalPropertiesEvaluator globalPropertiesEvaluator = getGlobalPropertiesEvaluator(); if (globalPropertiesEvaluator != null) { mergeGlobalProperties(globalPropertiesEvaluator.getGlobalProperties(eventCollection), mergedKeenProperties, newEvent); } // merge any per-event keen properties if (keenProperties != null) { mergedKeenProperties.putAll(keenProperties); } // if no keen.timestamp was provided by globals or event, add one now if (!mergedKeenProperties.containsKey("timestamp")) { Calendar currentTime = Calendar.getInstance(); String timestamp = ISO_8601_FORMAT.format(currentTime.getTime()); mergedKeenProperties.put("timestamp", timestamp); } // add merged keen properties to event newEvent.put("keen", mergedKeenProperties); // merge any per-event non-keen properties newEvent.putAll(event); return newEvent; }
[ "protected", "Map", "<", "String", ",", "Object", ">", "validateAndBuildEvent", "(", "KeenProject", "project", ",", "String", "eventCollection", ",", "Map", "<", "String", ",", "Object", ">", "event", ",", "Map", "<", "String", ",", "Object", ">", "keenProperties", ")", "{", "if", "(", "project", ".", "getWriteKey", "(", ")", "==", "null", ")", "{", "throw", "new", "NoWriteKeyException", "(", "\"You can't send events to Keen if you haven't set a write key.\"", ")", ";", "}", "validateEventCollection", "(", "eventCollection", ")", ";", "validateEvent", "(", "event", ")", ";", "KeenLogging", ".", "log", "(", "String", ".", "format", "(", "Locale", ".", "US", ",", "\"Adding event to collection: %s\"", ",", "eventCollection", ")", ")", ";", "// Create maps to aggregate keen & non-keen properties", "Map", "<", "String", ",", "Object", ">", "newEvent", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "Map", "<", "String", ",", "Object", ">", "mergedKeenProperties", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "// separate keen & non-keen properties from static globals and merge them into separate maps", "if", "(", "null", "!=", "globalProperties", ")", "{", "mergeGlobalProperties", "(", "getGlobalProperties", "(", ")", ",", "mergedKeenProperties", ",", "newEvent", ")", ";", "}", "// separate keen & non-keen properties from dynamic globals and merge them into separate maps", "GlobalPropertiesEvaluator", "globalPropertiesEvaluator", "=", "getGlobalPropertiesEvaluator", "(", ")", ";", "if", "(", "globalPropertiesEvaluator", "!=", "null", ")", "{", "mergeGlobalProperties", "(", "globalPropertiesEvaluator", ".", "getGlobalProperties", "(", "eventCollection", ")", ",", "mergedKeenProperties", ",", "newEvent", ")", ";", "}", "// merge any per-event keen properties", "if", "(", "keenProperties", "!=", "null", ")", "{", "mergedKeenProperties", ".", "putAll", "(", "keenProperties", ")", ";", "}", "// if no keen.timestamp was provided by globals or event, add one now", "if", "(", "!", "mergedKeenProperties", ".", "containsKey", "(", "\"timestamp\"", ")", ")", "{", "Calendar", "currentTime", "=", "Calendar", ".", "getInstance", "(", ")", ";", "String", "timestamp", "=", "ISO_8601_FORMAT", ".", "format", "(", "currentTime", ".", "getTime", "(", ")", ")", ";", "mergedKeenProperties", ".", "put", "(", "\"timestamp\"", ",", "timestamp", ")", ";", "}", "// add merged keen properties to event", "newEvent", ".", "put", "(", "\"keen\"", ",", "mergedKeenProperties", ")", ";", "// merge any per-event non-keen properties", "newEvent", ".", "putAll", "(", "event", ")", ";", "return", "newEvent", ";", "}" ]
Validates an event and inserts global properties, producing a new event object which is ready to be published to the Keen service. @param project The project in which the event will be published. @param eventCollection The name of the collection in which the event will be published. @param event A Map that consists of key/value pairs. @param keenProperties A Map that consists of key/value pairs to override default properties. @return A new event Map containing Keen properties and global properties.
[ "Validates", "an", "event", "and", "inserts", "global", "properties", "producing", "a", "new", "event", "object", "which", "is", "ready", "to", "be", "published", "to", "the", "Keen", "service", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1112-L1158
4,344
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.mergeGlobalProperties
private void mergeGlobalProperties(Map<String, Object> globalProperties, Map<String, Object> keenProperties, Map<String, Object> newEvent) { if (globalProperties != null) { // Clone globals so we don't modify the original globalProperties = new HashMap<String, Object>(globalProperties); Object keen = globalProperties.remove("keen"); if (keen instanceof Map) { keenProperties.putAll((Map)keen); } newEvent.putAll(globalProperties); } }
java
private void mergeGlobalProperties(Map<String, Object> globalProperties, Map<String, Object> keenProperties, Map<String, Object> newEvent) { if (globalProperties != null) { // Clone globals so we don't modify the original globalProperties = new HashMap<String, Object>(globalProperties); Object keen = globalProperties.remove("keen"); if (keen instanceof Map) { keenProperties.putAll((Map)keen); } newEvent.putAll(globalProperties); } }
[ "private", "void", "mergeGlobalProperties", "(", "Map", "<", "String", ",", "Object", ">", "globalProperties", ",", "Map", "<", "String", ",", "Object", ">", "keenProperties", ",", "Map", "<", "String", ",", "Object", ">", "newEvent", ")", "{", "if", "(", "globalProperties", "!=", "null", ")", "{", "// Clone globals so we don't modify the original", "globalProperties", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", "globalProperties", ")", ";", "Object", "keen", "=", "globalProperties", ".", "remove", "(", "\"keen\"", ")", ";", "if", "(", "keen", "instanceof", "Map", ")", "{", "keenProperties", ".", "putAll", "(", "(", "Map", ")", "keen", ")", ";", "}", "newEvent", ".", "putAll", "(", "globalProperties", ")", ";", "}", "}" ]
Removes the "keen" key from the globalProperties map and, if a map was removed, then all of its pairs are added to the keenProperties map. Anything left in the globalProperties map is then added to the newEvent map. @param globalProperties @param keenProperties @param newEvent
[ "Removes", "the", "keen", "key", "from", "the", "globalProperties", "map", "and", "if", "a", "map", "was", "removed", "then", "all", "of", "its", "pairs", "are", "added", "to", "the", "keenProperties", "map", ".", "Anything", "left", "in", "the", "globalProperties", "map", "is", "then", "added", "to", "the", "newEvent", "map", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1168-L1179
4,345
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.validateEventCollection
private void validateEventCollection(String eventCollection) { if (eventCollection == null || eventCollection.length() == 0) { throw new InvalidEventCollectionException("You must specify a non-null, " + "non-empty event collection: " + eventCollection); } if (eventCollection.length() > 256) { throw new InvalidEventCollectionException("An event collection name cannot be longer than 256 characters."); } }
java
private void validateEventCollection(String eventCollection) { if (eventCollection == null || eventCollection.length() == 0) { throw new InvalidEventCollectionException("You must specify a non-null, " + "non-empty event collection: " + eventCollection); } if (eventCollection.length() > 256) { throw new InvalidEventCollectionException("An event collection name cannot be longer than 256 characters."); } }
[ "private", "void", "validateEventCollection", "(", "String", "eventCollection", ")", "{", "if", "(", "eventCollection", "==", "null", "||", "eventCollection", ".", "length", "(", ")", "==", "0", ")", "{", "throw", "new", "InvalidEventCollectionException", "(", "\"You must specify a non-null, \"", "+", "\"non-empty event collection: \"", "+", "eventCollection", ")", ";", "}", "if", "(", "eventCollection", ".", "length", "(", ")", ">", "256", ")", "{", "throw", "new", "InvalidEventCollectionException", "(", "\"An event collection name cannot be longer than 256 characters.\"", ")", ";", "}", "}" ]
Validates the name of an event collection. @param eventCollection An event collection name to be validated. @throws io.keen.client.java.exceptions.InvalidEventCollectionException If the event collection name is invalid. See Keen documentation for details.
[ "Validates", "the", "name", "of", "an", "event", "collection", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1224-L1232
4,346
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.validateEvent
@SuppressWarnings("unchecked") // cast to generic Map will always be okay in this case private void validateEvent(Map<String, Object> event, int depth) { if (depth == 0) { if (event == null || event.size() == 0) { throw new InvalidEventException("You must specify a non-null, non-empty event."); } if (event.containsKey("keen")) { throw new InvalidEventException("An event cannot contain a root-level property named 'keen'."); } } else if (depth > KeenConstants.MAX_EVENT_DEPTH) { throw new InvalidEventException("An event's depth (i.e. layers of nesting) cannot exceed " + KeenConstants.MAX_EVENT_DEPTH); } for (Map.Entry<String, Object> entry : event.entrySet()) { String key = entry.getKey(); if (key.contains(".")) { throw new InvalidEventException("An event cannot contain a property with the period (.) character in " + "it."); } if (key.length() > 256) { throw new InvalidEventException("An event cannot contain a property name longer than 256 characters."); } validateEventValue(entry.getValue(), depth); } }
java
@SuppressWarnings("unchecked") // cast to generic Map will always be okay in this case private void validateEvent(Map<String, Object> event, int depth) { if (depth == 0) { if (event == null || event.size() == 0) { throw new InvalidEventException("You must specify a non-null, non-empty event."); } if (event.containsKey("keen")) { throw new InvalidEventException("An event cannot contain a root-level property named 'keen'."); } } else if (depth > KeenConstants.MAX_EVENT_DEPTH) { throw new InvalidEventException("An event's depth (i.e. layers of nesting) cannot exceed " + KeenConstants.MAX_EVENT_DEPTH); } for (Map.Entry<String, Object> entry : event.entrySet()) { String key = entry.getKey(); if (key.contains(".")) { throw new InvalidEventException("An event cannot contain a property with the period (.) character in " + "it."); } if (key.length() > 256) { throw new InvalidEventException("An event cannot contain a property name longer than 256 characters."); } validateEventValue(entry.getValue(), depth); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "// cast to generic Map will always be okay in this case", "private", "void", "validateEvent", "(", "Map", "<", "String", ",", "Object", ">", "event", ",", "int", "depth", ")", "{", "if", "(", "depth", "==", "0", ")", "{", "if", "(", "event", "==", "null", "||", "event", ".", "size", "(", ")", "==", "0", ")", "{", "throw", "new", "InvalidEventException", "(", "\"You must specify a non-null, non-empty event.\"", ")", ";", "}", "if", "(", "event", ".", "containsKey", "(", "\"keen\"", ")", ")", "{", "throw", "new", "InvalidEventException", "(", "\"An event cannot contain a root-level property named 'keen'.\"", ")", ";", "}", "}", "else", "if", "(", "depth", ">", "KeenConstants", ".", "MAX_EVENT_DEPTH", ")", "{", "throw", "new", "InvalidEventException", "(", "\"An event's depth (i.e. layers of nesting) cannot exceed \"", "+", "KeenConstants", ".", "MAX_EVENT_DEPTH", ")", ";", "}", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "event", ".", "entrySet", "(", ")", ")", "{", "String", "key", "=", "entry", ".", "getKey", "(", ")", ";", "if", "(", "key", ".", "contains", "(", "\".\"", ")", ")", "{", "throw", "new", "InvalidEventException", "(", "\"An event cannot contain a property with the period (.) character in \"", "+", "\"it.\"", ")", ";", "}", "if", "(", "key", ".", "length", "(", ")", ">", "256", ")", "{", "throw", "new", "InvalidEventException", "(", "\"An event cannot contain a property name longer than 256 characters.\"", ")", ";", "}", "validateEventValue", "(", "entry", ".", "getValue", "(", ")", ",", "depth", ")", ";", "}", "}" ]
Validates an event. @param event The event to validate. @param depth The number of layers of the map structure that have already been traversed; this should be 0 for the initial call and will increment on each recursive call.
[ "Validates", "an", "event", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1249-L1275
4,347
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.validateEventValue
@SuppressWarnings("unchecked") // cast to generic Map will always be okay in this case private void validateEventValue(Object value, int depth) { if (value instanceof String) { String strValue = (String) value; if (strValue.length() >= 10000) { throw new InvalidEventException("An event cannot contain a string property value longer than 10," + "000 characters."); } } else if (value instanceof Map) { validateEvent((Map<String, Object>) value, depth + 1); } else if (value instanceof Iterable) { for (Object listElement : (Iterable) value) { validateEventValue(listElement, depth); } } }
java
@SuppressWarnings("unchecked") // cast to generic Map will always be okay in this case private void validateEventValue(Object value, int depth) { if (value instanceof String) { String strValue = (String) value; if (strValue.length() >= 10000) { throw new InvalidEventException("An event cannot contain a string property value longer than 10," + "000 characters."); } } else if (value instanceof Map) { validateEvent((Map<String, Object>) value, depth + 1); } else if (value instanceof Iterable) { for (Object listElement : (Iterable) value) { validateEventValue(listElement, depth); } } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "// cast to generic Map will always be okay in this case", "private", "void", "validateEventValue", "(", "Object", "value", ",", "int", "depth", ")", "{", "if", "(", "value", "instanceof", "String", ")", "{", "String", "strValue", "=", "(", "String", ")", "value", ";", "if", "(", "strValue", ".", "length", "(", ")", ">=", "10000", ")", "{", "throw", "new", "InvalidEventException", "(", "\"An event cannot contain a string property value longer than 10,\"", "+", "\"000 characters.\"", ")", ";", "}", "}", "else", "if", "(", "value", "instanceof", "Map", ")", "{", "validateEvent", "(", "(", "Map", "<", "String", ",", "Object", ">", ")", "value", ",", "depth", "+", "1", ")", ";", "}", "else", "if", "(", "value", "instanceof", "Iterable", ")", "{", "for", "(", "Object", "listElement", ":", "(", "Iterable", ")", "value", ")", "{", "validateEventValue", "(", "listElement", ",", "depth", ")", ";", "}", "}", "}" ]
Validates a value within an event structure. This method will handle validating each element in a list, as well as recursively validating nested maps. @param value The value to validate. @param depth The current depth of validation.
[ "Validates", "a", "value", "within", "an", "event", "structure", ".", "This", "method", "will", "handle", "validating", "each", "element", "in", "a", "list", "as", "well", "as", "recursively", "validating", "nested", "maps", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1284-L1299
4,348
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.buildEventMap
private Map<String, List<Map<String, Object>>> buildEventMap(String projectId, Map<String, List<Object>> eventHandles) throws IOException { Map<String, List<Map<String, Object>>> result = new HashMap<String, List<Map<String, Object>>>(); for (Map.Entry<String, List<Object>> entry : eventHandles.entrySet()) { String eventCollection = entry.getKey(); List<Object> handles = entry.getValue(); // Skip event collections that don't contain any events. if (handles == null || handles.size() == 0) { continue; } // Build the event list by retrieving events from the store. List<Map<String, Object>> events = new ArrayList<Map<String, Object>>(handles.size()); Map<String, Integer> attempts; if (eventStore instanceof KeenAttemptCountingEventStore) { synchronized (attemptsLock) { try { attempts = getAttemptsMap(projectId, eventCollection); } catch (IOException ex) { // setting this to a fresh map will effectively declare this the "last attempt" for // these events. attempts = new HashMap<String, Integer>(); KeenLogging.log("Failed to read attempt counts map. Events will still be POSTed. " + "Exception: " + ex); } for (Object handle : handles) { Map<String, Object> event = getEvent(handle); String attemptsKey = "" + handle.hashCode(); Integer remainingAttempts = attempts.get(attemptsKey); if (remainingAttempts == null) { // treat null as "this is the last attempt" remainingAttempts = 1; } // decrement the remaining attempts count and put the new value on the map remainingAttempts--; attempts.put(attemptsKey, remainingAttempts); if (remainingAttempts >= 0) { // if we had some remaining attempts, then try again events.add(event); } else { // otherwise remove it from the store eventStore.remove(handle); // iff eventStore.remove succeeds we can do some housekeeping and remove the // key from the attempts hash. attempts.remove(attemptsKey); } } try { setAttemptsMap(projectId, eventCollection, attempts); } catch(IOException ex) { KeenLogging.log("Failed to update event POST attempts counts while sending queued " + "events. Events will still be POSTed. Exception: " + ex); } } } else { for (Object handle : handles) { events.add(getEvent(handle)); } } result.put(eventCollection, events); } return result; }
java
private Map<String, List<Map<String, Object>>> buildEventMap(String projectId, Map<String, List<Object>> eventHandles) throws IOException { Map<String, List<Map<String, Object>>> result = new HashMap<String, List<Map<String, Object>>>(); for (Map.Entry<String, List<Object>> entry : eventHandles.entrySet()) { String eventCollection = entry.getKey(); List<Object> handles = entry.getValue(); // Skip event collections that don't contain any events. if (handles == null || handles.size() == 0) { continue; } // Build the event list by retrieving events from the store. List<Map<String, Object>> events = new ArrayList<Map<String, Object>>(handles.size()); Map<String, Integer> attempts; if (eventStore instanceof KeenAttemptCountingEventStore) { synchronized (attemptsLock) { try { attempts = getAttemptsMap(projectId, eventCollection); } catch (IOException ex) { // setting this to a fresh map will effectively declare this the "last attempt" for // these events. attempts = new HashMap<String, Integer>(); KeenLogging.log("Failed to read attempt counts map. Events will still be POSTed. " + "Exception: " + ex); } for (Object handle : handles) { Map<String, Object> event = getEvent(handle); String attemptsKey = "" + handle.hashCode(); Integer remainingAttempts = attempts.get(attemptsKey); if (remainingAttempts == null) { // treat null as "this is the last attempt" remainingAttempts = 1; } // decrement the remaining attempts count and put the new value on the map remainingAttempts--; attempts.put(attemptsKey, remainingAttempts); if (remainingAttempts >= 0) { // if we had some remaining attempts, then try again events.add(event); } else { // otherwise remove it from the store eventStore.remove(handle); // iff eventStore.remove succeeds we can do some housekeeping and remove the // key from the attempts hash. attempts.remove(attemptsKey); } } try { setAttemptsMap(projectId, eventCollection, attempts); } catch(IOException ex) { KeenLogging.log("Failed to update event POST attempts counts while sending queued " + "events. Events will still be POSTed. Exception: " + ex); } } } else { for (Object handle : handles) { events.add(getEvent(handle)); } } result.put(eventCollection, events); } return result; }
[ "private", "Map", "<", "String", ",", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", ">", "buildEventMap", "(", "String", "projectId", ",", "Map", "<", "String", ",", "List", "<", "Object", ">", ">", "eventHandles", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", ">", "result", "=", "new", "HashMap", "<", "String", ",", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", ">", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "List", "<", "Object", ">", ">", "entry", ":", "eventHandles", ".", "entrySet", "(", ")", ")", "{", "String", "eventCollection", "=", "entry", ".", "getKey", "(", ")", ";", "List", "<", "Object", ">", "handles", "=", "entry", ".", "getValue", "(", ")", ";", "// Skip event collections that don't contain any events.", "if", "(", "handles", "==", "null", "||", "handles", ".", "size", "(", ")", "==", "0", ")", "{", "continue", ";", "}", "// Build the event list by retrieving events from the store.", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", "events", "=", "new", "ArrayList", "<", "Map", "<", "String", ",", "Object", ">", ">", "(", "handles", ".", "size", "(", ")", ")", ";", "Map", "<", "String", ",", "Integer", ">", "attempts", ";", "if", "(", "eventStore", "instanceof", "KeenAttemptCountingEventStore", ")", "{", "synchronized", "(", "attemptsLock", ")", "{", "try", "{", "attempts", "=", "getAttemptsMap", "(", "projectId", ",", "eventCollection", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "// setting this to a fresh map will effectively declare this the \"last attempt\" for", "// these events.", "attempts", "=", "new", "HashMap", "<", "String", ",", "Integer", ">", "(", ")", ";", "KeenLogging", ".", "log", "(", "\"Failed to read attempt counts map. Events will still be POSTed. \"", "+", "\"Exception: \"", "+", "ex", ")", ";", "}", "for", "(", "Object", "handle", ":", "handles", ")", "{", "Map", "<", "String", ",", "Object", ">", "event", "=", "getEvent", "(", "handle", ")", ";", "String", "attemptsKey", "=", "\"\"", "+", "handle", ".", "hashCode", "(", ")", ";", "Integer", "remainingAttempts", "=", "attempts", ".", "get", "(", "attemptsKey", ")", ";", "if", "(", "remainingAttempts", "==", "null", ")", "{", "// treat null as \"this is the last attempt\"", "remainingAttempts", "=", "1", ";", "}", "// decrement the remaining attempts count and put the new value on the map", "remainingAttempts", "--", ";", "attempts", ".", "put", "(", "attemptsKey", ",", "remainingAttempts", ")", ";", "if", "(", "remainingAttempts", ">=", "0", ")", "{", "// if we had some remaining attempts, then try again", "events", ".", "add", "(", "event", ")", ";", "}", "else", "{", "// otherwise remove it from the store", "eventStore", ".", "remove", "(", "handle", ")", ";", "// iff eventStore.remove succeeds we can do some housekeeping and remove the", "// key from the attempts hash.", "attempts", ".", "remove", "(", "attemptsKey", ")", ";", "}", "}", "try", "{", "setAttemptsMap", "(", "projectId", ",", "eventCollection", ",", "attempts", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "KeenLogging", ".", "log", "(", "\"Failed to update event POST attempts counts while sending queued \"", "+", "\"events. Events will still be POSTed. Exception: \"", "+", "ex", ")", ";", "}", "}", "}", "else", "{", "for", "(", "Object", "handle", ":", "handles", ")", "{", "events", ".", "add", "(", "getEvent", "(", "handle", ")", ")", ";", "}", "}", "result", ".", "put", "(", "eventCollection", ",", "events", ")", ";", "}", "return", "result", ";", "}" ]
Builds a map from collection name to a list of event maps, given a map from collection name to a list of event handles. This method just uses the event store to retrieve each event by its handle. @param eventHandles A map from collection name to a list of event handles in the event store. @return A map from collection name to a list of event maps. @throws IOException If there is an error retrieving events from the store.
[ "Builds", "a", "map", "from", "collection", "name", "to", "a", "list", "of", "event", "maps", "given", "a", "map", "from", "collection", "name", "to", "a", "list", "of", "event", "handles", ".", "This", "method", "just", "uses", "the", "event", "store", "to", "retrieve", "each", "event", "by", "its", "handle", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1310-L1383
4,349
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.publish
private String publish(KeenProject project, String eventCollection, Map<String, Object> event) throws IOException { URL url = createURL(project, eventCollection); if (url == null) { throw new IllegalStateException("URL address is empty"); } return publishObject(project, url, event); }
java
private String publish(KeenProject project, String eventCollection, Map<String, Object> event) throws IOException { URL url = createURL(project, eventCollection); if (url == null) { throw new IllegalStateException("URL address is empty"); } return publishObject(project, url, event); }
[ "private", "String", "publish", "(", "KeenProject", "project", ",", "String", "eventCollection", ",", "Map", "<", "String", ",", "Object", ">", "event", ")", "throws", "IOException", "{", "URL", "url", "=", "createURL", "(", "project", ",", "eventCollection", ")", ";", "if", "(", "url", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"URL address is empty\"", ")", ";", "}", "return", "publishObject", "(", "project", ",", "url", ",", "event", ")", ";", "}" ]
Publishes a single event to the Keen service. @param project The project in which to publish the event. @param eventCollection The name of the collection in which to publish the event. @param event The event to publish. @return The response from the server. @throws IOException If there was an error communicating with the server.
[ "Publishes", "a", "single", "event", "to", "the", "Keen", "service", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1394-L1400
4,350
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.publishAll
private String publishAll(KeenProject project, Map<String, List<Map<String, Object>>> events) throws IOException { // just using basic JDK HTTP library String urlString = String.format(Locale.US, "%s/%s/projects/%s/events", getBaseUrl(), KeenConstants.API_VERSION, project.getProjectId()); URL url = new URL(urlString); return publishObject(project, url, events); }
java
private String publishAll(KeenProject project, Map<String, List<Map<String, Object>>> events) throws IOException { // just using basic JDK HTTP library String urlString = String.format(Locale.US, "%s/%s/projects/%s/events", getBaseUrl(), KeenConstants.API_VERSION, project.getProjectId()); URL url = new URL(urlString); return publishObject(project, url, events); }
[ "private", "String", "publishAll", "(", "KeenProject", "project", ",", "Map", "<", "String", ",", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", ">", "events", ")", "throws", "IOException", "{", "// just using basic JDK HTTP library", "String", "urlString", "=", "String", ".", "format", "(", "Locale", ".", "US", ",", "\"%s/%s/projects/%s/events\"", ",", "getBaseUrl", "(", ")", ",", "KeenConstants", ".", "API_VERSION", ",", "project", ".", "getProjectId", "(", ")", ")", ";", "URL", "url", "=", "new", "URL", "(", "urlString", ")", ";", "return", "publishObject", "(", "project", ",", "url", ",", "events", ")", ";", "}" ]
Publishes a batch of events to the Keen service. @param project The project in which to publish the event. @param events A map from collection name to a list of event maps. @return The response from the server. @throws IOException If there was an error communicating with the server.
[ "Publishes", "a", "batch", "of", "events", "to", "the", "Keen", "service", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1425-L1432
4,351
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.handleSuccess
private void handleSuccess(KeenCallback callback, KeenProject project, String eventCollection, Map<String, Object> event, Map<String, Object> keenProperties) { handleSuccess(callback); if (callback != null) { try { if (callback instanceof KeenDetailedCallback){ ((KeenDetailedCallback)callback).onSuccess(project, eventCollection, event, keenProperties); } } catch (Exception userException) { // Do nothing. Issue #98 } } }
java
private void handleSuccess(KeenCallback callback, KeenProject project, String eventCollection, Map<String, Object> event, Map<String, Object> keenProperties) { handleSuccess(callback); if (callback != null) { try { if (callback instanceof KeenDetailedCallback){ ((KeenDetailedCallback)callback).onSuccess(project, eventCollection, event, keenProperties); } } catch (Exception userException) { // Do nothing. Issue #98 } } }
[ "private", "void", "handleSuccess", "(", "KeenCallback", "callback", ",", "KeenProject", "project", ",", "String", "eventCollection", ",", "Map", "<", "String", ",", "Object", ">", "event", ",", "Map", "<", "String", ",", "Object", ">", "keenProperties", ")", "{", "handleSuccess", "(", "callback", ")", ";", "if", "(", "callback", "!=", "null", ")", "{", "try", "{", "if", "(", "callback", "instanceof", "KeenDetailedCallback", ")", "{", "(", "(", "KeenDetailedCallback", ")", "callback", ")", ".", "onSuccess", "(", "project", ",", "eventCollection", ",", "event", ",", "keenProperties", ")", ";", "}", "}", "catch", "(", "Exception", "userException", ")", "{", "// Do nothing. Issue #98", "}", "}", "}" ]
Reports success to a callback. If the callback is null, this is a no-op. Any exceptions thrown by the callback are silently ignored. @param callback A callback; may be null. @param project The project in which the event was published. If a default project has been set on the client, this parameter may be null, in which case the default project was used. @param eventCollection The name of the collection in which the event was published @param event A Map that consists of key/value pairs. Keen naming conventions apply (see docs). Nested Maps and lists are acceptable (and encouraged!). @param keenProperties A Map that consists of key/value pairs to override default properties. ex: "timestamp" -&gt; Calendar.getInstance()
[ "Reports", "success", "to", "a", "callback", ".", "If", "the", "callback", "is", "null", "this", "is", "a", "no", "-", "op", ".", "Any", "exceptions", "thrown", "by", "the", "callback", "are", "silently", "ignored", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1613-L1631
4,352
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.getEvent
private Map<String, Object> getEvent(Object handle) throws IOException { // Get the event from the store. String jsonEvent = eventStore.get(handle); // De-serialize the event from its JSON. StringReader reader = new StringReader(jsonEvent); Map<String, Object> event = jsonHandler.readJson(reader); KeenUtils.closeQuietly(reader); return event; }
java
private Map<String, Object> getEvent(Object handle) throws IOException { // Get the event from the store. String jsonEvent = eventStore.get(handle); // De-serialize the event from its JSON. StringReader reader = new StringReader(jsonEvent); Map<String, Object> event = jsonHandler.readJson(reader); KeenUtils.closeQuietly(reader); return event; }
[ "private", "Map", "<", "String", ",", "Object", ">", "getEvent", "(", "Object", "handle", ")", "throws", "IOException", "{", "// Get the event from the store.", "String", "jsonEvent", "=", "eventStore", ".", "get", "(", "handle", ")", ";", "// De-serialize the event from its JSON.", "StringReader", "reader", "=", "new", "StringReader", "(", "jsonEvent", ")", ";", "Map", "<", "String", ",", "Object", ">", "event", "=", "jsonHandler", ".", "readJson", "(", "reader", ")", ";", "KeenUtils", ".", "closeQuietly", "(", "reader", ")", ";", "return", "event", ";", "}" ]
Get an event object from the eventStore. @param handle the handle object @return the event object for handle @throws IOException
[ "Get", "an", "event", "object", "from", "the", "eventStore", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1728-L1737
4,353
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.getAttemptsMap
private Map<String, Integer> getAttemptsMap(String projectId, String eventCollection) throws IOException { Map<String, Integer> attempts = new HashMap<String, Integer>(); if (eventStore instanceof KeenAttemptCountingEventStore) { KeenAttemptCountingEventStore res = (KeenAttemptCountingEventStore)eventStore; String attemptsJSON = res.getAttempts(projectId, eventCollection); if (attemptsJSON != null) { StringReader reader = new StringReader(attemptsJSON); Map<String, Object> attemptTmp = jsonHandler.readJson(reader); for (Entry<String, Object> entry : attemptTmp.entrySet()) { if (entry.getValue() instanceof Number) { attempts.put(entry.getKey(), ((Number)entry.getValue()).intValue()); } } } } return attempts; }
java
private Map<String, Integer> getAttemptsMap(String projectId, String eventCollection) throws IOException { Map<String, Integer> attempts = new HashMap<String, Integer>(); if (eventStore instanceof KeenAttemptCountingEventStore) { KeenAttemptCountingEventStore res = (KeenAttemptCountingEventStore)eventStore; String attemptsJSON = res.getAttempts(projectId, eventCollection); if (attemptsJSON != null) { StringReader reader = new StringReader(attemptsJSON); Map<String, Object> attemptTmp = jsonHandler.readJson(reader); for (Entry<String, Object> entry : attemptTmp.entrySet()) { if (entry.getValue() instanceof Number) { attempts.put(entry.getKey(), ((Number)entry.getValue()).intValue()); } } } } return attempts; }
[ "private", "Map", "<", "String", ",", "Integer", ">", "getAttemptsMap", "(", "String", "projectId", ",", "String", "eventCollection", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "Integer", ">", "attempts", "=", "new", "HashMap", "<", "String", ",", "Integer", ">", "(", ")", ";", "if", "(", "eventStore", "instanceof", "KeenAttemptCountingEventStore", ")", "{", "KeenAttemptCountingEventStore", "res", "=", "(", "KeenAttemptCountingEventStore", ")", "eventStore", ";", "String", "attemptsJSON", "=", "res", ".", "getAttempts", "(", "projectId", ",", "eventCollection", ")", ";", "if", "(", "attemptsJSON", "!=", "null", ")", "{", "StringReader", "reader", "=", "new", "StringReader", "(", "attemptsJSON", ")", ";", "Map", "<", "String", ",", "Object", ">", "attemptTmp", "=", "jsonHandler", ".", "readJson", "(", "reader", ")", ";", "for", "(", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "attemptTmp", ".", "entrySet", "(", ")", ")", "{", "if", "(", "entry", ".", "getValue", "(", ")", "instanceof", "Number", ")", "{", "attempts", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "(", "(", "Number", ")", "entry", ".", "getValue", "(", ")", ")", ".", "intValue", "(", ")", ")", ";", "}", "}", "}", "}", "return", "attempts", ";", "}" ]
Gets the map of attempt counts from the eventStore @param projectId the project id @param eventCollection the collection name @return a Map of event hashCodes to attempt counts @throws IOException
[ "Gets", "the", "map", "of", "attempt", "counts", "from", "the", "eventStore" ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1747-L1764
4,354
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/KeenClient.java
KeenClient.setAttemptsMap
private void setAttemptsMap(String projectId, String eventCollection, Map<String, Integer> attempts) throws IOException { if (eventStore instanceof KeenAttemptCountingEventStore) { KeenAttemptCountingEventStore res = (KeenAttemptCountingEventStore)eventStore; StringWriter writer = null; try { writer = new StringWriter(); jsonHandler.writeJson(writer, attempts); String attemptsJSON = writer.toString(); res.setAttempts(projectId, eventCollection, attemptsJSON); } finally { KeenUtils.closeQuietly(writer); } } }
java
private void setAttemptsMap(String projectId, String eventCollection, Map<String, Integer> attempts) throws IOException { if (eventStore instanceof KeenAttemptCountingEventStore) { KeenAttemptCountingEventStore res = (KeenAttemptCountingEventStore)eventStore; StringWriter writer = null; try { writer = new StringWriter(); jsonHandler.writeJson(writer, attempts); String attemptsJSON = writer.toString(); res.setAttempts(projectId, eventCollection, attemptsJSON); } finally { KeenUtils.closeQuietly(writer); } } }
[ "private", "void", "setAttemptsMap", "(", "String", "projectId", ",", "String", "eventCollection", ",", "Map", "<", "String", ",", "Integer", ">", "attempts", ")", "throws", "IOException", "{", "if", "(", "eventStore", "instanceof", "KeenAttemptCountingEventStore", ")", "{", "KeenAttemptCountingEventStore", "res", "=", "(", "KeenAttemptCountingEventStore", ")", "eventStore", ";", "StringWriter", "writer", "=", "null", ";", "try", "{", "writer", "=", "new", "StringWriter", "(", ")", ";", "jsonHandler", ".", "writeJson", "(", "writer", ",", "attempts", ")", ";", "String", "attemptsJSON", "=", "writer", ".", "toString", "(", ")", ";", "res", ".", "setAttempts", "(", "projectId", ",", "eventCollection", ",", "attemptsJSON", ")", ";", "}", "finally", "{", "KeenUtils", ".", "closeQuietly", "(", "writer", ")", ";", "}", "}", "}" ]
Set the attempts Map in the eventStore @param projectId the project id @param eventCollection the collection name @param attempts the current attempts Map @throws IOException
[ "Set", "the", "attempts", "Map", "in", "the", "eventStore" ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/KeenClient.java#L1774-L1787
4,355
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/Query.java
Query.areParamsValid
public boolean areParamsValid() { if (queryType == QueryType.COUNT) { if (eventCollection == null || eventCollection.isEmpty()) { return false; } } if (queryType == QueryType.COUNT_UNIQUE || queryType == QueryType.MINIMUM || queryType == QueryType.MAXIMUM || queryType == QueryType.AVERAGE || queryType == QueryType.MEDIAN || queryType == QueryType.PERCENTILE || queryType == QueryType.SUM || queryType == QueryType.SELECT_UNIQUE || queryType == QueryType.STANDARD_DEVIATION) { if (eventCollection == null || eventCollection.isEmpty() || targetProperty == null || targetProperty.isEmpty()) { return false; } } if (queryType == QueryType.PERCENTILE) { return percentile != null; } return true; }
java
public boolean areParamsValid() { if (queryType == QueryType.COUNT) { if (eventCollection == null || eventCollection.isEmpty()) { return false; } } if (queryType == QueryType.COUNT_UNIQUE || queryType == QueryType.MINIMUM || queryType == QueryType.MAXIMUM || queryType == QueryType.AVERAGE || queryType == QueryType.MEDIAN || queryType == QueryType.PERCENTILE || queryType == QueryType.SUM || queryType == QueryType.SELECT_UNIQUE || queryType == QueryType.STANDARD_DEVIATION) { if (eventCollection == null || eventCollection.isEmpty() || targetProperty == null || targetProperty.isEmpty()) { return false; } } if (queryType == QueryType.PERCENTILE) { return percentile != null; } return true; }
[ "public", "boolean", "areParamsValid", "(", ")", "{", "if", "(", "queryType", "==", "QueryType", ".", "COUNT", ")", "{", "if", "(", "eventCollection", "==", "null", "||", "eventCollection", ".", "isEmpty", "(", ")", ")", "{", "return", "false", ";", "}", "}", "if", "(", "queryType", "==", "QueryType", ".", "COUNT_UNIQUE", "||", "queryType", "==", "QueryType", ".", "MINIMUM", "||", "queryType", "==", "QueryType", ".", "MAXIMUM", "||", "queryType", "==", "QueryType", ".", "AVERAGE", "||", "queryType", "==", "QueryType", ".", "MEDIAN", "||", "queryType", "==", "QueryType", ".", "PERCENTILE", "||", "queryType", "==", "QueryType", ".", "SUM", "||", "queryType", "==", "QueryType", ".", "SELECT_UNIQUE", "||", "queryType", "==", "QueryType", ".", "STANDARD_DEVIATION", ")", "{", "if", "(", "eventCollection", "==", "null", "||", "eventCollection", ".", "isEmpty", "(", ")", "||", "targetProperty", "==", "null", "||", "targetProperty", ".", "isEmpty", "(", ")", ")", "{", "return", "false", ";", "}", "}", "if", "(", "queryType", "==", "QueryType", ".", "PERCENTILE", ")", "{", "return", "percentile", "!=", "null", ";", "}", "return", "true", ";", "}" ]
Verifies whether the parameters are valid, based on the input query name. @return whether the parameters are valid.
[ "Verifies", "whether", "the", "parameters", "are", "valid", "based", "on", "the", "input", "query", "name", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/query/src/main/java/io/keen/client/java/Query.java#L111-L134
4,356
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/RefreshRate.java
RefreshRate.fromHours
public static int fromHours(int hours) { int refreshRate = hours * RefreshRate.SECONDS_PER_HOUR; RefreshRate.validateRefreshRate(refreshRate); return refreshRate; }
java
public static int fromHours(int hours) { int refreshRate = hours * RefreshRate.SECONDS_PER_HOUR; RefreshRate.validateRefreshRate(refreshRate); return refreshRate; }
[ "public", "static", "int", "fromHours", "(", "int", "hours", ")", "{", "int", "refreshRate", "=", "hours", "*", "RefreshRate", ".", "SECONDS_PER_HOUR", ";", "RefreshRate", ".", "validateRefreshRate", "(", "refreshRate", ")", ";", "return", "refreshRate", ";", "}" ]
Maximum is 24 hrs
[ "Maximum", "is", "24", "hrs" ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/query/src/main/java/io/keen/client/java/RefreshRate.java#L22-L28
4,357
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/http/UrlConnectionHttpHandler.java
UrlConnectionHttpHandler.openConnection
protected HttpURLConnection openConnection(Request request) throws IOException { HttpURLConnection result; if (request.proxy != null) { result = (HttpURLConnection) request.url.openConnection(request.proxy); } else { result = (HttpURLConnection) request.url.openConnection(); } result.setConnectTimeout(request.connectTimeout); result.setReadTimeout(request.readTimeout); return result; }
java
protected HttpURLConnection openConnection(Request request) throws IOException { HttpURLConnection result; if (request.proxy != null) { result = (HttpURLConnection) request.url.openConnection(request.proxy); } else { result = (HttpURLConnection) request.url.openConnection(); } result.setConnectTimeout(request.connectTimeout); result.setReadTimeout(request.readTimeout); return result; }
[ "protected", "HttpURLConnection", "openConnection", "(", "Request", "request", ")", "throws", "IOException", "{", "HttpURLConnection", "result", ";", "if", "(", "request", ".", "proxy", "!=", "null", ")", "{", "result", "=", "(", "HttpURLConnection", ")", "request", ".", "url", ".", "openConnection", "(", "request", ".", "proxy", ")", ";", "}", "else", "{", "result", "=", "(", "HttpURLConnection", ")", "request", ".", "url", ".", "openConnection", "(", ")", ";", "}", "result", ".", "setConnectTimeout", "(", "request", ".", "connectTimeout", ")", ";", "result", ".", "setReadTimeout", "(", "request", ".", "readTimeout", ")", ";", "return", "result", ";", "}" ]
Opens a connection based on the URL in the given request. Subclasses can override this method to use a different implementation of {@link HttpURLConnection}. @param request The {@link Request}. @return A new {@link HttpURLConnection}. @throws IOException If there is an error opening the connection.
[ "Opens", "a", "connection", "based", "on", "the", "URL", "in", "the", "given", "request", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/http/UrlConnectionHttpHandler.java#L46-L56
4,358
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/http/UrlConnectionHttpHandler.java
UrlConnectionHttpHandler.sendRequest
protected void sendRequest(HttpURLConnection connection, Request request) throws IOException { // Set up the request. connection.setRequestMethod(request.method); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Authorization", request.authorization); // If a different HttpHandler is used, we won't get this header. We would need to refactor // to a delegation pattern to give the client code's HttpHandler a chance to process the // Request first, then attach our custom headers, which would likely be a breaking change. connection.setRequestProperty("Keen-Sdk", "java-" + KeenVersion.getSdkVersion()); // If the request has a body, send it. Otherwise just connect. if (request.body != null) { if (HttpMethods.GET.equals(request.method) || HttpMethods.DELETE.equals(request.method)) { throw new IllegalStateException("Trying to send a GET request with a request " + "body, which would result in sending a POST."); } connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); request.body.writeTo(connection.getOutputStream()); } else { connection.connect(); } }
java
protected void sendRequest(HttpURLConnection connection, Request request) throws IOException { // Set up the request. connection.setRequestMethod(request.method); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Authorization", request.authorization); // If a different HttpHandler is used, we won't get this header. We would need to refactor // to a delegation pattern to give the client code's HttpHandler a chance to process the // Request first, then attach our custom headers, which would likely be a breaking change. connection.setRequestProperty("Keen-Sdk", "java-" + KeenVersion.getSdkVersion()); // If the request has a body, send it. Otherwise just connect. if (request.body != null) { if (HttpMethods.GET.equals(request.method) || HttpMethods.DELETE.equals(request.method)) { throw new IllegalStateException("Trying to send a GET request with a request " + "body, which would result in sending a POST."); } connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/json"); request.body.writeTo(connection.getOutputStream()); } else { connection.connect(); } }
[ "protected", "void", "sendRequest", "(", "HttpURLConnection", "connection", ",", "Request", "request", ")", "throws", "IOException", "{", "// Set up the request.", "connection", ".", "setRequestMethod", "(", "request", ".", "method", ")", ";", "connection", ".", "setRequestProperty", "(", "\"Accept\"", ",", "\"application/json\"", ")", ";", "connection", ".", "setRequestProperty", "(", "\"Authorization\"", ",", "request", ".", "authorization", ")", ";", "// If a different HttpHandler is used, we won't get this header. We would need to refactor", "// to a delegation pattern to give the client code's HttpHandler a chance to process the", "// Request first, then attach our custom headers, which would likely be a breaking change.", "connection", ".", "setRequestProperty", "(", "\"Keen-Sdk\"", ",", "\"java-\"", "+", "KeenVersion", ".", "getSdkVersion", "(", ")", ")", ";", "// If the request has a body, send it. Otherwise just connect.", "if", "(", "request", ".", "body", "!=", "null", ")", "{", "if", "(", "HttpMethods", ".", "GET", ".", "equals", "(", "request", ".", "method", ")", "||", "HttpMethods", ".", "DELETE", ".", "equals", "(", "request", ".", "method", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Trying to send a GET request with a request \"", "+", "\"body, which would result in sending a POST.\"", ")", ";", "}", "connection", ".", "setDoOutput", "(", "true", ")", ";", "connection", ".", "setRequestProperty", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", ";", "request", ".", "body", ".", "writeTo", "(", "connection", ".", "getOutputStream", "(", ")", ")", ";", "}", "else", "{", "connection", ".", "connect", "(", ")", ";", "}", "}" ]
Sends a request over a given connection. @param connection The connection over which to send the request. @param request The request to send. @throws IOException If there is an error sending the request.
[ "Sends", "a", "request", "over", "a", "given", "connection", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/http/UrlConnectionHttpHandler.java#L65-L90
4,359
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/KeenQueryClient.java
KeenQueryClient.constructFunnelResult
private static FunnelResult constructFunnelResult(Map<String, Object> responseMap) { // Create a result for the 'result' field of the funnel response. FunnelResult won't contain // intervals or groups, as those parameters aren't supported for Funnel. QueryResult funnelResult = constructQueryResult( responseMap.get(KeenQueryConstants.RESULT), false, false); if (!(funnelResult instanceof ListResult)) { throw new KeenQueryClientException("'result' property of response contained data of an unexpected format."); } ListResult actorsResult = null; // Check for any additional result data that has been returned and include it with the result. if (responseMap.containsKey(KeenQueryConstants.ACTORS)) { QueryResult genericActorsResult = constructQueryResult( responseMap.get(KeenQueryConstants.ACTORS), false, false); if (!(genericActorsResult instanceof ListResult)) { throw new KeenQueryClientException("'actors' property of response contained data of an unexpected format."); } actorsResult = (ListResult)genericActorsResult; } return new FunnelResult((ListResult)funnelResult, actorsResult); }
java
private static FunnelResult constructFunnelResult(Map<String, Object> responseMap) { // Create a result for the 'result' field of the funnel response. FunnelResult won't contain // intervals or groups, as those parameters aren't supported for Funnel. QueryResult funnelResult = constructQueryResult( responseMap.get(KeenQueryConstants.RESULT), false, false); if (!(funnelResult instanceof ListResult)) { throw new KeenQueryClientException("'result' property of response contained data of an unexpected format."); } ListResult actorsResult = null; // Check for any additional result data that has been returned and include it with the result. if (responseMap.containsKey(KeenQueryConstants.ACTORS)) { QueryResult genericActorsResult = constructQueryResult( responseMap.get(KeenQueryConstants.ACTORS), false, false); if (!(genericActorsResult instanceof ListResult)) { throw new KeenQueryClientException("'actors' property of response contained data of an unexpected format."); } actorsResult = (ListResult)genericActorsResult; } return new FunnelResult((ListResult)funnelResult, actorsResult); }
[ "private", "static", "FunnelResult", "constructFunnelResult", "(", "Map", "<", "String", ",", "Object", ">", "responseMap", ")", "{", "// Create a result for the 'result' field of the funnel response. FunnelResult won't contain", "// intervals or groups, as those parameters aren't supported for Funnel.", "QueryResult", "funnelResult", "=", "constructQueryResult", "(", "responseMap", ".", "get", "(", "KeenQueryConstants", ".", "RESULT", ")", ",", "false", ",", "false", ")", ";", "if", "(", "!", "(", "funnelResult", "instanceof", "ListResult", ")", ")", "{", "throw", "new", "KeenQueryClientException", "(", "\"'result' property of response contained data of an unexpected format.\"", ")", ";", "}", "ListResult", "actorsResult", "=", "null", ";", "// Check for any additional result data that has been returned and include it with the result.", "if", "(", "responseMap", ".", "containsKey", "(", "KeenQueryConstants", ".", "ACTORS", ")", ")", "{", "QueryResult", "genericActorsResult", "=", "constructQueryResult", "(", "responseMap", ".", "get", "(", "KeenQueryConstants", ".", "ACTORS", ")", ",", "false", ",", "false", ")", ";", "if", "(", "!", "(", "genericActorsResult", "instanceof", "ListResult", ")", ")", "{", "throw", "new", "KeenQueryClientException", "(", "\"'actors' property of response contained data of an unexpected format.\"", ")", ";", "}", "actorsResult", "=", "(", "ListResult", ")", "genericActorsResult", ";", "}", "return", "new", "FunnelResult", "(", "(", "ListResult", ")", "funnelResult", ",", "actorsResult", ")", ";", "}" ]
Constructs a FunnelResult from a response object map. This map should include a 'result' key and may include an optional 'actors' key as well. @param responseMap The server response, deserialized to a Map<String, Object> @return A FunnelResult instance.
[ "Constructs", "a", "FunnelResult", "from", "a", "response", "object", "map", ".", "This", "map", "should", "include", "a", "result", "key", "and", "may", "include", "an", "optional", "actors", "key", "as", "well", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/query/src/main/java/io/keen/client/java/KeenQueryClient.java#L632-L661
4,360
keenlabs/KeenClient-Java
android/src/main/java/io/keen/client/android/AndroidJsonHandler.java
AndroidJsonHandler.readerToString
private static String readerToString(Reader reader) throws IOException { StringWriter writer = new StringWriter(); try { char[] buffer = new char[COPY_BUFFER_SIZE]; while (true) { int bytesRead = reader.read(buffer); if (bytesRead == -1) { break; } else { writer.write(buffer, 0, bytesRead); } } return writer.toString(); } finally { reader.close(); } }
java
private static String readerToString(Reader reader) throws IOException { StringWriter writer = new StringWriter(); try { char[] buffer = new char[COPY_BUFFER_SIZE]; while (true) { int bytesRead = reader.read(buffer); if (bytesRead == -1) { break; } else { writer.write(buffer, 0, bytesRead); } } return writer.toString(); } finally { reader.close(); } }
[ "private", "static", "String", "readerToString", "(", "Reader", "reader", ")", "throws", "IOException", "{", "StringWriter", "writer", "=", "new", "StringWriter", "(", ")", ";", "try", "{", "char", "[", "]", "buffer", "=", "new", "char", "[", "COPY_BUFFER_SIZE", "]", ";", "while", "(", "true", ")", "{", "int", "bytesRead", "=", "reader", ".", "read", "(", "buffer", ")", ";", "if", "(", "bytesRead", "==", "-", "1", ")", "{", "break", ";", "}", "else", "{", "writer", ".", "write", "(", "buffer", ",", "0", ",", "bytesRead", ")", ";", "}", "}", "return", "writer", ".", "toString", "(", ")", ";", "}", "finally", "{", "reader", ".", "close", "(", ")", ";", "}", "}" ]
Converts a Reader to a String by copying the Reader's contents into a StringWriter via a buffer. @param reader The Reader from which to extract a String. @return The String contained in the Reader. @throws IOException If there is an error reading from the input Reader.
[ "Converts", "a", "Reader", "to", "a", "String", "by", "copying", "the", "Reader", "s", "contents", "into", "a", "StringWriter", "via", "a", "buffer", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/android/src/main/java/io/keen/client/android/AndroidJsonHandler.java#L277-L293
4,361
keenlabs/KeenClient-Java
android/src/main/java/io/keen/client/android/AndroidJsonHandler.java
AndroidJsonHandler.requiresWrap
private static boolean requiresWrap(Map map) { for (Object value : map.values()) { if (value instanceof Collection || value instanceof Map || value instanceof Object[]) { return true; } } return false; }
java
private static boolean requiresWrap(Map map) { for (Object value : map.values()) { if (value instanceof Collection || value instanceof Map || value instanceof Object[]) { return true; } } return false; }
[ "private", "static", "boolean", "requiresWrap", "(", "Map", "map", ")", "{", "for", "(", "Object", "value", ":", "map", ".", "values", "(", ")", ")", "{", "if", "(", "value", "instanceof", "Collection", "||", "value", "instanceof", "Map", "||", "value", "instanceof", "Object", "[", "]", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether a map requires any wrapping. This is used to avoid creating a copy of a map if all of its fields can be handled natively. @param map The map to check for values that require wrapping. @return {@code true} if the map contains values that need to be wrapped (i.e. maps or collections), otherwise {@code false}.
[ "Checks", "whether", "a", "map", "requires", "any", "wrapping", ".", "This", "is", "used", "to", "avoid", "creating", "a", "copy", "of", "a", "map", "if", "all", "of", "its", "fields", "can", "be", "handled", "natively", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/android/src/main/java/io/keen/client/android/AndroidJsonHandler.java#L303-L310
4,362
keenlabs/KeenClient-Java
android/src/main/java/io/keen/client/android/AndroidJsonHandler.java
AndroidJsonHandler.requiresWrap
private static boolean requiresWrap(Collection collection) { for (Object value : collection) { if (value instanceof Collection || value instanceof Map) { return true; } } return false; }
java
private static boolean requiresWrap(Collection collection) { for (Object value : collection) { if (value instanceof Collection || value instanceof Map) { return true; } } return false; }
[ "private", "static", "boolean", "requiresWrap", "(", "Collection", "collection", ")", "{", "for", "(", "Object", "value", ":", "collection", ")", "{", "if", "(", "value", "instanceof", "Collection", "||", "value", "instanceof", "Map", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks whether a collection requires any wrapping. This is used to avoid creating a copy of a collection if all of its fields can be handled natively. @param collection The collection to check for values that require wrapping. @return {@code true} if the collection contains values that need to be wrapped (i.e. maps or collections), otherwise {@code false}.
[ "Checks", "whether", "a", "collection", "requires", "any", "wrapping", ".", "This", "is", "used", "to", "avoid", "creating", "a", "copy", "of", "a", "collection", "if", "all", "of", "its", "fields", "can", "be", "handled", "natively", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/android/src/main/java/io/keen/client/android/AndroidJsonHandler.java#L320-L327
4,363
keenlabs/KeenClient-Java
query/src/main/java/io/keen/client/java/RequestUrlBuilder.java
RequestUrlBuilder.getAnalysisUrl
URL getAnalysisUrl(String projectId, String analysisPath) throws KeenQueryClientException { try { return new URL(String.format(Locale.US, "%s/%s/projects/%s/queries/%s", this.baseUrl, this.apiVersion, projectId, analysisPath )); } catch (MalformedURLException ex) { Logger.getLogger(RequestUrlBuilder.class.getName()) .log(Level.SEVERE, "Failed to format query URL.", ex); throw new KeenQueryClientException("Failed to format query URL.", ex); } }
java
URL getAnalysisUrl(String projectId, String analysisPath) throws KeenQueryClientException { try { return new URL(String.format(Locale.US, "%s/%s/projects/%s/queries/%s", this.baseUrl, this.apiVersion, projectId, analysisPath )); } catch (MalformedURLException ex) { Logger.getLogger(RequestUrlBuilder.class.getName()) .log(Level.SEVERE, "Failed to format query URL.", ex); throw new KeenQueryClientException("Failed to format query URL.", ex); } }
[ "URL", "getAnalysisUrl", "(", "String", "projectId", ",", "String", "analysisPath", ")", "throws", "KeenQueryClientException", "{", "try", "{", "return", "new", "URL", "(", "String", ".", "format", "(", "Locale", ".", "US", ",", "\"%s/%s/projects/%s/queries/%s\"", ",", "this", ".", "baseUrl", ",", "this", ".", "apiVersion", ",", "projectId", ",", "analysisPath", ")", ")", ";", "}", "catch", "(", "MalformedURLException", "ex", ")", "{", "Logger", ".", "getLogger", "(", "RequestUrlBuilder", ".", "class", ".", "getName", "(", ")", ")", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"Failed to format query URL.\"", ",", "ex", ")", ";", "throw", "new", "KeenQueryClientException", "(", "\"Failed to format query URL.\"", ",", "ex", ")", ";", "}", "}" ]
Get a formatted URL for an analysis request. @param projectId The project id @param analysisPath The analysis url sub-path @return The complete URL. @throws KeenQueryClientException
[ "Get", "a", "formatted", "URL", "for", "an", "analysis", "request", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/query/src/main/java/io/keen/client/java/RequestUrlBuilder.java#L48-L63
4,364
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/FileEventStore.java
FileEventStore.getHandlesFromProjectDirectory
private Map<String, List<Object>> getHandlesFromProjectDirectory(File projectDir) throws IOException { File[] collectionDirs = getSubDirectories(projectDir); Map<String, List<Object>> handleMap = new HashMap<String, List<Object>>(); if (collectionDirs != null) { // iterate through the directories for (File directory : collectionDirs) { String collectionName = directory.getName(); File[] files = getFilesInDir(directory); if (files != null) { List<Object> handleList = new ArrayList<Object>(); handleList.addAll(Arrays.asList(files)); handleMap.put(collectionName, handleList); } else { KeenLogging.log("Directory was null while getting event handles: " + collectionName); } } } return handleMap; }
java
private Map<String, List<Object>> getHandlesFromProjectDirectory(File projectDir) throws IOException { File[] collectionDirs = getSubDirectories(projectDir); Map<String, List<Object>> handleMap = new HashMap<String, List<Object>>(); if (collectionDirs != null) { // iterate through the directories for (File directory : collectionDirs) { String collectionName = directory.getName(); File[] files = getFilesInDir(directory); if (files != null) { List<Object> handleList = new ArrayList<Object>(); handleList.addAll(Arrays.asList(files)); handleMap.put(collectionName, handleList); } else { KeenLogging.log("Directory was null while getting event handles: " + collectionName); } } } return handleMap; }
[ "private", "Map", "<", "String", ",", "List", "<", "Object", ">", ">", "getHandlesFromProjectDirectory", "(", "File", "projectDir", ")", "throws", "IOException", "{", "File", "[", "]", "collectionDirs", "=", "getSubDirectories", "(", "projectDir", ")", ";", "Map", "<", "String", ",", "List", "<", "Object", ">", ">", "handleMap", "=", "new", "HashMap", "<", "String", ",", "List", "<", "Object", ">", ">", "(", ")", ";", "if", "(", "collectionDirs", "!=", "null", ")", "{", "// iterate through the directories", "for", "(", "File", "directory", ":", "collectionDirs", ")", "{", "String", "collectionName", "=", "directory", ".", "getName", "(", ")", ";", "File", "[", "]", "files", "=", "getFilesInDir", "(", "directory", ")", ";", "if", "(", "files", "!=", "null", ")", "{", "List", "<", "Object", ">", "handleList", "=", "new", "ArrayList", "<", "Object", ">", "(", ")", ";", "handleList", ".", "addAll", "(", "Arrays", ".", "asList", "(", "files", ")", ")", ";", "handleMap", ".", "put", "(", "collectionName", ",", "handleList", ")", ";", "}", "else", "{", "KeenLogging", ".", "log", "(", "\"Directory was null while getting event handles: \"", "+", "collectionName", ")", ";", "}", "}", "}", "return", "handleMap", ";", "}" ]
Gets the handle map for all collections in the specified project cache directory. @param projectDir The cache directory for the project. @return The handle map. See {@link #getHandles(String)} for details. @throws IOException If there is an error reading the event files.
[ "Gets", "the", "handle", "map", "for", "all", "collections", "in", "the", "specified", "project", "cache", "directory", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/FileEventStore.java#L197-L218
4,365
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/FileEventStore.java
FileEventStore.getKeenCacheDirectory
private File getKeenCacheDirectory() throws IOException { File file = new File(root, "keen"); if (!file.exists()) { boolean dirMade = file.mkdir(); if (!dirMade) { throw new IOException("Could not make keen cache directory at: " + file.getAbsolutePath()); } } return file; }
java
private File getKeenCacheDirectory() throws IOException { File file = new File(root, "keen"); if (!file.exists()) { boolean dirMade = file.mkdir(); if (!dirMade) { throw new IOException("Could not make keen cache directory at: " + file.getAbsolutePath()); } } return file; }
[ "private", "File", "getKeenCacheDirectory", "(", ")", "throws", "IOException", "{", "File", "file", "=", "new", "File", "(", "root", ",", "\"keen\"", ")", ";", "if", "(", "!", "file", ".", "exists", "(", ")", ")", "{", "boolean", "dirMade", "=", "file", ".", "mkdir", "(", ")", ";", "if", "(", "!", "dirMade", ")", "{", "throw", "new", "IOException", "(", "\"Could not make keen cache directory at: \"", "+", "file", ".", "getAbsolutePath", "(", ")", ")", ";", "}", "}", "return", "file", ";", "}" ]
Gets the root directory of the Keen cache, based on the root directory passed to the constructor of this file store. If necessary, this method will attempt to create the directory. @return The root directory of the cache.
[ "Gets", "the", "root", "directory", "of", "the", "Keen", "cache", "based", "on", "the", "root", "directory", "passed", "to", "the", "constructor", "of", "this", "file", "store", ".", "If", "necessary", "this", "method", "will", "attempt", "to", "create", "the", "directory", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/FileEventStore.java#L227-L236
4,366
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/FileEventStore.java
FileEventStore.getSubDirectories
private File[] getSubDirectories(File parent) throws IOException { return parent.listFiles(new FileFilter() { // Can return null if there are no events public boolean accept(File file) { return file.isDirectory(); } }); }
java
private File[] getSubDirectories(File parent) throws IOException { return parent.listFiles(new FileFilter() { // Can return null if there are no events public boolean accept(File file) { return file.isDirectory(); } }); }
[ "private", "File", "[", "]", "getSubDirectories", "(", "File", "parent", ")", "throws", "IOException", "{", "return", "parent", ".", "listFiles", "(", "new", "FileFilter", "(", ")", "{", "// Can return null if there are no events", "public", "boolean", "accept", "(", "File", "file", ")", "{", "return", "file", ".", "isDirectory", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets an array containing all of the sub-directories in the given parent directory. @param parent The directory from which to get sub-directories. @return An array of sub-directories. @throws IOException If there is an error listing the files in the directory.
[ "Gets", "an", "array", "containing", "all", "of", "the", "sub", "-", "directories", "in", "the", "given", "parent", "directory", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/FileEventStore.java#L245-L251
4,367
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/FileEventStore.java
FileEventStore.getFilesInDir
private File[] getFilesInDir(File dir) { return dir.listFiles(new FileFilter() { public boolean accept(File file) { return file.isFile() && !file.getName().equals(ATTEMPTS_JSON_FILE_NAME); } }); }
java
private File[] getFilesInDir(File dir) { return dir.listFiles(new FileFilter() { public boolean accept(File file) { return file.isFile() && !file.getName().equals(ATTEMPTS_JSON_FILE_NAME); } }); }
[ "private", "File", "[", "]", "getFilesInDir", "(", "File", "dir", ")", "{", "return", "dir", ".", "listFiles", "(", "new", "FileFilter", "(", ")", "{", "public", "boolean", "accept", "(", "File", "file", ")", "{", "return", "file", ".", "isFile", "(", ")", "&&", "!", "file", ".", "getName", "(", ")", ".", "equals", "(", "ATTEMPTS_JSON_FILE_NAME", ")", ";", "}", "}", ")", ";", "}" ]
Gets an array containing all of the files in the given directory. @param dir A directory. @return An array containing all of the files in the given directory.
[ "Gets", "an", "array", "containing", "all", "of", "the", "files", "in", "the", "given", "directory", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/FileEventStore.java#L259-L265
4,368
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/FileEventStore.java
FileEventStore.getProjectDir
private File getProjectDir(String projectId, boolean create) throws IOException { File projectDir = new File(getKeenCacheDirectory(), projectId); if (create && !projectDir.exists()) { KeenLogging.log("Cache directory for project '" + projectId + "' doesn't exist. " + "Creating it."); if (!projectDir.mkdirs()) { throw new IOException("Could not create project cache directory '" + projectDir.getAbsolutePath() + "'"); } } return projectDir; }
java
private File getProjectDir(String projectId, boolean create) throws IOException { File projectDir = new File(getKeenCacheDirectory(), projectId); if (create && !projectDir.exists()) { KeenLogging.log("Cache directory for project '" + projectId + "' doesn't exist. " + "Creating it."); if (!projectDir.mkdirs()) { throw new IOException("Could not create project cache directory '" + projectDir.getAbsolutePath() + "'"); } } return projectDir; }
[ "private", "File", "getProjectDir", "(", "String", "projectId", ",", "boolean", "create", ")", "throws", "IOException", "{", "File", "projectDir", "=", "new", "File", "(", "getKeenCacheDirectory", "(", ")", ",", "projectId", ")", ";", "if", "(", "create", "&&", "!", "projectDir", ".", "exists", "(", ")", ")", "{", "KeenLogging", ".", "log", "(", "\"Cache directory for project '\"", "+", "projectId", "+", "\"' doesn't exist. \"", "+", "\"Creating it.\"", ")", ";", "if", "(", "!", "projectDir", ".", "mkdirs", "(", ")", ")", "{", "throw", "new", "IOException", "(", "\"Could not create project cache directory '\"", "+", "projectDir", ".", "getAbsolutePath", "(", ")", "+", "\"'\"", ")", ";", "}", "}", "return", "projectDir", ";", "}" ]
Gets the cache directory for the given project. Optionally creates the directory if it doesn't exist. @param projectId The project ID. @return The cache directory for the project. @throws IOException
[ "Gets", "the", "cache", "directory", "for", "the", "given", "project", ".", "Optionally", "creates", "the", "directory", "if", "it", "doesn", "t", "exist", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/FileEventStore.java#L275-L286
4,369
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/FileEventStore.java
FileEventStore.getFileForEvent
private File getFileForEvent(File collectionDir, Calendar timestamp) throws IOException { int counter = 0; File eventFile = getNextFileForEvent(collectionDir, timestamp, counter); while (eventFile.exists()) { eventFile = getNextFileForEvent(collectionDir, timestamp, counter); counter++; } return eventFile; }
java
private File getFileForEvent(File collectionDir, Calendar timestamp) throws IOException { int counter = 0; File eventFile = getNextFileForEvent(collectionDir, timestamp, counter); while (eventFile.exists()) { eventFile = getNextFileForEvent(collectionDir, timestamp, counter); counter++; } return eventFile; }
[ "private", "File", "getFileForEvent", "(", "File", "collectionDir", ",", "Calendar", "timestamp", ")", "throws", "IOException", "{", "int", "counter", "=", "0", ";", "File", "eventFile", "=", "getNextFileForEvent", "(", "collectionDir", ",", "timestamp", ",", "counter", ")", ";", "while", "(", "eventFile", ".", "exists", "(", ")", ")", "{", "eventFile", "=", "getNextFileForEvent", "(", "collectionDir", ",", "timestamp", ",", "counter", ")", ";", "counter", "++", ";", "}", "return", "eventFile", ";", "}" ]
Gets the file to use for a new event in the given collection with the given timestamp. If there are multiple events with identical timestamps, this method will use a counter to create a unique file name for each. @param collectionDir The cache directory for the event collection. @param timestamp The timestamp of the event. @return The file to use for the new event.
[ "Gets", "the", "file", "to", "use", "for", "a", "new", "event", "in", "the", "given", "collection", "with", "the", "given", "timestamp", ".", "If", "there", "are", "multiple", "events", "with", "identical", "timestamps", "this", "method", "will", "use", "a", "counter", "to", "create", "a", "unique", "file", "name", "for", "each", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/FileEventStore.java#L318-L326
4,370
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/FileEventStore.java
FileEventStore.getNextFileForEvent
private File getNextFileForEvent(File dir, Calendar timestamp, int counter) { long timestampInMillis = timestamp.getTimeInMillis(); String name = Long.toString(timestampInMillis); return new File(dir, name + "." + counter); }
java
private File getNextFileForEvent(File dir, Calendar timestamp, int counter) { long timestampInMillis = timestamp.getTimeInMillis(); String name = Long.toString(timestampInMillis); return new File(dir, name + "." + counter); }
[ "private", "File", "getNextFileForEvent", "(", "File", "dir", ",", "Calendar", "timestamp", ",", "int", "counter", ")", "{", "long", "timestampInMillis", "=", "timestamp", ".", "getTimeInMillis", "(", ")", ";", "String", "name", "=", "Long", ".", "toString", "(", "timestampInMillis", ")", ";", "return", "new", "File", "(", "dir", ",", "name", "+", "\".\"", "+", "counter", ")", ";", "}" ]
Gets the file to use for a new event in the given collection with the given timestamp, using the provided counter. @param dir The directory in which the file should be created. @param timestamp The timestamp to use as the base file name. @param counter The counter to append to the file name. @return The file to use.
[ "Gets", "the", "file", "to", "use", "for", "a", "new", "event", "in", "the", "given", "collection", "with", "the", "given", "timestamp", "using", "the", "provided", "counter", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/FileEventStore.java#L337-L341
4,371
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/FileEventStore.java
FileEventStore.prepareCollectionDir
private File prepareCollectionDir(String projectId, String eventCollection) throws IOException { File collectionDir = getCollectionDir(projectId, eventCollection); // Make sure the max number of events has not been exceeded in this collection. If it has, // delete events to make room. File[] eventFiles = getFilesInDir(collectionDir); if (eventFiles.length >= getMaxEventsPerCollection()) { // need to age out old data so the cache doesn't grow too large KeenLogging.log(String.format(Locale.US, "Too many events in cache for %s, " + "aging out old data", eventCollection)); KeenLogging.log(String.format(Locale.US, "Count: %d and Max: %d", eventFiles.length, getMaxEventsPerCollection())); // delete the eldest (i.e. first we have to sort the list by name) List<File> fileList = Arrays.asList(eventFiles); Collections.sort(fileList, new Comparator<File>() { @Override public int compare(File file, File file1) { return file.getAbsolutePath().compareToIgnoreCase(file1.getAbsolutePath()); } }); for (int i = 0; i < getNumberEventsToForget(); i++) { File f = fileList.get(i); if (!f.delete()) { KeenLogging.log(String.format(Locale.US, "CRITICAL: can't delete file %s, cache is going to be too big", f.getAbsolutePath())); } } } return collectionDir; }
java
private File prepareCollectionDir(String projectId, String eventCollection) throws IOException { File collectionDir = getCollectionDir(projectId, eventCollection); // Make sure the max number of events has not been exceeded in this collection. If it has, // delete events to make room. File[] eventFiles = getFilesInDir(collectionDir); if (eventFiles.length >= getMaxEventsPerCollection()) { // need to age out old data so the cache doesn't grow too large KeenLogging.log(String.format(Locale.US, "Too many events in cache for %s, " + "aging out old data", eventCollection)); KeenLogging.log(String.format(Locale.US, "Count: %d and Max: %d", eventFiles.length, getMaxEventsPerCollection())); // delete the eldest (i.e. first we have to sort the list by name) List<File> fileList = Arrays.asList(eventFiles); Collections.sort(fileList, new Comparator<File>() { @Override public int compare(File file, File file1) { return file.getAbsolutePath().compareToIgnoreCase(file1.getAbsolutePath()); } }); for (int i = 0; i < getNumberEventsToForget(); i++) { File f = fileList.get(i); if (!f.delete()) { KeenLogging.log(String.format(Locale.US, "CRITICAL: can't delete file %s, cache is going to be too big", f.getAbsolutePath())); } } } return collectionDir; }
[ "private", "File", "prepareCollectionDir", "(", "String", "projectId", ",", "String", "eventCollection", ")", "throws", "IOException", "{", "File", "collectionDir", "=", "getCollectionDir", "(", "projectId", ",", "eventCollection", ")", ";", "// Make sure the max number of events has not been exceeded in this collection. If it has,", "// delete events to make room.", "File", "[", "]", "eventFiles", "=", "getFilesInDir", "(", "collectionDir", ")", ";", "if", "(", "eventFiles", ".", "length", ">=", "getMaxEventsPerCollection", "(", ")", ")", "{", "// need to age out old data so the cache doesn't grow too large", "KeenLogging", ".", "log", "(", "String", ".", "format", "(", "Locale", ".", "US", ",", "\"Too many events in cache for %s, \"", "+", "\"aging out old data\"", ",", "eventCollection", ")", ")", ";", "KeenLogging", ".", "log", "(", "String", ".", "format", "(", "Locale", ".", "US", ",", "\"Count: %d and Max: %d\"", ",", "eventFiles", ".", "length", ",", "getMaxEventsPerCollection", "(", ")", ")", ")", ";", "// delete the eldest (i.e. first we have to sort the list by name)", "List", "<", "File", ">", "fileList", "=", "Arrays", ".", "asList", "(", "eventFiles", ")", ";", "Collections", ".", "sort", "(", "fileList", ",", "new", "Comparator", "<", "File", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "File", "file", ",", "File", "file1", ")", "{", "return", "file", ".", "getAbsolutePath", "(", ")", ".", "compareToIgnoreCase", "(", "file1", ".", "getAbsolutePath", "(", ")", ")", ";", "}", "}", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "getNumberEventsToForget", "(", ")", ";", "i", "++", ")", "{", "File", "f", "=", "fileList", ".", "get", "(", "i", ")", ";", "if", "(", "!", "f", ".", "delete", "(", ")", ")", "{", "KeenLogging", ".", "log", "(", "String", ".", "format", "(", "Locale", ".", "US", ",", "\"CRITICAL: can't delete file %s, cache is going to be too big\"", ",", "f", ".", "getAbsolutePath", "(", ")", ")", ")", ";", "}", "}", "}", "return", "collectionDir", ";", "}" ]
Prepares the file cache for the given event collection for another event to be added. This method checks to make sure that the maximum number of events per collection hasn't been exceeded, and if it has, this method discards events to make room. @param projectId The project ID. @param eventCollection The name of the event collection. @return The prepared cache directory for the given project/collection. @throws IOException If there is an error creating the directory or validating/discarding events.
[ "Prepares", "the", "file", "cache", "for", "the", "given", "event", "collection", "for", "another", "event", "to", "be", "added", ".", "This", "method", "checks", "to", "make", "sure", "that", "the", "maximum", "number", "of", "events", "per", "collection", "hasn", "t", "been", "exceeded", "and", "if", "it", "has", "this", "method", "discards", "events", "to", "make", "room", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/FileEventStore.java#L372-L404
4,372
keenlabs/KeenClient-Java
core/src/main/java/io/keen/client/java/RamEventStore.java
RamEventStore.clear
void clear() { nextId = 0; collectionIds = new HashMap<String, List<Long>>(); events = new HashMap<Long, String>(); }
java
void clear() { nextId = 0; collectionIds = new HashMap<String, List<Long>>(); events = new HashMap<Long, String>(); }
[ "void", "clear", "(", ")", "{", "nextId", "=", "0", ";", "collectionIds", "=", "new", "HashMap", "<", "String", ",", "List", "<", "Long", ">", ">", "(", ")", ";", "events", "=", "new", "HashMap", "<", "Long", ",", "String", ">", "(", ")", ";", "}" ]
Clears all events from the store, effectively resetting it to its initial state. This method is intended for use during unit testing, and should generally not be called by production code.
[ "Clears", "all", "events", "from", "the", "store", "effectively", "resetting", "it", "to", "its", "initial", "state", ".", "This", "method", "is", "intended", "for", "use", "during", "unit", "testing", "and", "should", "generally", "not", "be", "called", "by", "production", "code", "." ]
2ea021547b5338257c951a2596bd49749038d018
https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/RamEventStore.java#L174-L178
4,373
RKumsher/utils
src/main/java/com/github/rkumsher/number/RandomNumberUtils.java
RandomNumberUtils.randomInt
public static int randomInt(int startInclusive, int endExclusive) { checkArgument(startInclusive <= endExclusive, "End must be greater than or equal to start"); if (startInclusive == endExclusive) { return startInclusive; } return RANDOM.ints(1, startInclusive, endExclusive).sum(); }
java
public static int randomInt(int startInclusive, int endExclusive) { checkArgument(startInclusive <= endExclusive, "End must be greater than or equal to start"); if (startInclusive == endExclusive) { return startInclusive; } return RANDOM.ints(1, startInclusive, endExclusive).sum(); }
[ "public", "static", "int", "randomInt", "(", "int", "startInclusive", ",", "int", "endExclusive", ")", "{", "checkArgument", "(", "startInclusive", "<=", "endExclusive", ",", "\"End must be greater than or equal to start\"", ")", ";", "if", "(", "startInclusive", "==", "endExclusive", ")", "{", "return", "startInclusive", ";", "}", "return", "RANDOM", ".", "ints", "(", "1", ",", "startInclusive", ",", "endExclusive", ")", ".", "sum", "(", ")", ";", "}" ]
Returns a random int within the specified range. @param startInclusive the earliest int that can be returned @param endExclusive the upper bound (not included) @return the random int @throws IllegalArgumentException if endExclusive is less than startInclusive
[ "Returns", "a", "random", "int", "within", "the", "specified", "range", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L52-L58
4,374
RKumsher/utils
src/main/java/com/github/rkumsher/number/RandomNumberUtils.java
RandomNumberUtils.randomIntGreaterThan
public static int randomIntGreaterThan(int minExclusive) { checkArgument( minExclusive < Integer.MAX_VALUE, "Cannot produce int greater than %s", Integer.MAX_VALUE); return randomInt(minExclusive + 1, Integer.MAX_VALUE); }
java
public static int randomIntGreaterThan(int minExclusive) { checkArgument( minExclusive < Integer.MAX_VALUE, "Cannot produce int greater than %s", Integer.MAX_VALUE); return randomInt(minExclusive + 1, Integer.MAX_VALUE); }
[ "public", "static", "int", "randomIntGreaterThan", "(", "int", "minExclusive", ")", "{", "checkArgument", "(", "minExclusive", "<", "Integer", ".", "MAX_VALUE", ",", "\"Cannot produce int greater than %s\"", ",", "Integer", ".", "MAX_VALUE", ")", ";", "return", "randomInt", "(", "minExclusive", "+", "1", ",", "Integer", ".", "MAX_VALUE", ")", ";", "}" ]
Returns a random int that is greater than the given int. @param minExclusive the value that returned int must be greater than @return the random int @throws IllegalArgumentException if minExclusive is greater than or equal to {@link Integer#MAX_VALUE}
[ "Returns", "a", "random", "int", "that", "is", "greater", "than", "the", "given", "int", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L68-L72
4,375
RKumsher/utils
src/main/java/com/github/rkumsher/number/RandomNumberUtils.java
RandomNumberUtils.randomIntLessThan
public static int randomIntLessThan(int maxExclusive) { checkArgument( maxExclusive > Integer.MIN_VALUE, "Cannot produce int less than %s", Integer.MIN_VALUE); return randomInt(Integer.MIN_VALUE, maxExclusive); }
java
public static int randomIntLessThan(int maxExclusive) { checkArgument( maxExclusive > Integer.MIN_VALUE, "Cannot produce int less than %s", Integer.MIN_VALUE); return randomInt(Integer.MIN_VALUE, maxExclusive); }
[ "public", "static", "int", "randomIntLessThan", "(", "int", "maxExclusive", ")", "{", "checkArgument", "(", "maxExclusive", ">", "Integer", ".", "MIN_VALUE", ",", "\"Cannot produce int less than %s\"", ",", "Integer", ".", "MIN_VALUE", ")", ";", "return", "randomInt", "(", "Integer", ".", "MIN_VALUE", ",", "maxExclusive", ")", ";", "}" ]
Returns a random int that is less than the given int. @param maxExclusive the value that returned int must be less than @return the random int @throws IllegalArgumentException if maxExclusive is less than or equal to {@link Integer#MIN_VALUE}
[ "Returns", "a", "random", "int", "that", "is", "less", "than", "the", "given", "int", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L82-L86
4,376
RKumsher/utils
src/main/java/com/github/rkumsher/number/RandomNumberUtils.java
RandomNumberUtils.randomLong
public static long randomLong(long startInclusive, long endExclusive) { checkArgument(startInclusive <= endExclusive, "End must be greater than or equal to start"); if (startInclusive == endExclusive) { return startInclusive; } return RANDOM.longs(1, startInclusive, endExclusive).sum(); }
java
public static long randomLong(long startInclusive, long endExclusive) { checkArgument(startInclusive <= endExclusive, "End must be greater than or equal to start"); if (startInclusive == endExclusive) { return startInclusive; } return RANDOM.longs(1, startInclusive, endExclusive).sum(); }
[ "public", "static", "long", "randomLong", "(", "long", "startInclusive", ",", "long", "endExclusive", ")", "{", "checkArgument", "(", "startInclusive", "<=", "endExclusive", ",", "\"End must be greater than or equal to start\"", ")", ";", "if", "(", "startInclusive", "==", "endExclusive", ")", "{", "return", "startInclusive", ";", "}", "return", "RANDOM", ".", "longs", "(", "1", ",", "startInclusive", ",", "endExclusive", ")", ".", "sum", "(", ")", ";", "}" ]
Returns a random long within the specified range. @param startInclusive the earliest long that can be returned @param endExclusive the upper bound (not included) @return the random long @throws IllegalArgumentException if endExclusive is less than startInclusive
[ "Returns", "a", "random", "long", "within", "the", "specified", "range", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L123-L129
4,377
RKumsher/utils
src/main/java/com/github/rkumsher/number/RandomNumberUtils.java
RandomNumberUtils.randomLongGreaterThan
public static long randomLongGreaterThan(long minExclusive) { checkArgument( minExclusive < Long.MAX_VALUE, "Cannot produce long greater than %s", Long.MAX_VALUE); return randomLong(minExclusive + 1, Long.MAX_VALUE); }
java
public static long randomLongGreaterThan(long minExclusive) { checkArgument( minExclusive < Long.MAX_VALUE, "Cannot produce long greater than %s", Long.MAX_VALUE); return randomLong(minExclusive + 1, Long.MAX_VALUE); }
[ "public", "static", "long", "randomLongGreaterThan", "(", "long", "minExclusive", ")", "{", "checkArgument", "(", "minExclusive", "<", "Long", ".", "MAX_VALUE", ",", "\"Cannot produce long greater than %s\"", ",", "Long", ".", "MAX_VALUE", ")", ";", "return", "randomLong", "(", "minExclusive", "+", "1", ",", "Long", ".", "MAX_VALUE", ")", ";", "}" ]
Returns a random long that is greater than the given long. @param minExclusive the value that returned long must be greater than @return the random long @throws IllegalArgumentException if minExclusive is greater than or equal to {@link Long#MAX_VALUE}
[ "Returns", "a", "random", "long", "that", "is", "greater", "than", "the", "given", "long", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L139-L143
4,378
RKumsher/utils
src/main/java/com/github/rkumsher/number/RandomNumberUtils.java
RandomNumberUtils.randomLongLessThan
public static long randomLongLessThan(long maxExclusive) { checkArgument( maxExclusive > Long.MIN_VALUE, "Cannot produce long less than %s", Long.MIN_VALUE); return randomLong(Long.MIN_VALUE, maxExclusive); }
java
public static long randomLongLessThan(long maxExclusive) { checkArgument( maxExclusive > Long.MIN_VALUE, "Cannot produce long less than %s", Long.MIN_VALUE); return randomLong(Long.MIN_VALUE, maxExclusive); }
[ "public", "static", "long", "randomLongLessThan", "(", "long", "maxExclusive", ")", "{", "checkArgument", "(", "maxExclusive", ">", "Long", ".", "MIN_VALUE", ",", "\"Cannot produce long less than %s\"", ",", "Long", ".", "MIN_VALUE", ")", ";", "return", "randomLong", "(", "Long", ".", "MIN_VALUE", ",", "maxExclusive", ")", ";", "}" ]
Returns a random long that is less than the given long. @param maxExclusive the value that returned long must be less than @return the random long @throws IllegalArgumentException if maxExclusive is less than or equal to {@link Long#MIN_VALUE}
[ "Returns", "a", "random", "long", "that", "is", "less", "than", "the", "given", "long", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L153-L157
4,379
RKumsher/utils
src/main/java/com/github/rkumsher/number/RandomNumberUtils.java
RandomNumberUtils.randomDouble
public static double randomDouble(double startInclusive, double endExclusive) { checkArgument(startInclusive <= endExclusive, "End must be greater than or equal to start"); if (startInclusive == endExclusive) { return startInclusive; } return RANDOM.doubles(1, startInclusive, endExclusive).sum(); }
java
public static double randomDouble(double startInclusive, double endExclusive) { checkArgument(startInclusive <= endExclusive, "End must be greater than or equal to start"); if (startInclusive == endExclusive) { return startInclusive; } return RANDOM.doubles(1, startInclusive, endExclusive).sum(); }
[ "public", "static", "double", "randomDouble", "(", "double", "startInclusive", ",", "double", "endExclusive", ")", "{", "checkArgument", "(", "startInclusive", "<=", "endExclusive", ",", "\"End must be greater than or equal to start\"", ")", ";", "if", "(", "startInclusive", "==", "endExclusive", ")", "{", "return", "startInclusive", ";", "}", "return", "RANDOM", ".", "doubles", "(", "1", ",", "startInclusive", ",", "endExclusive", ")", ".", "sum", "(", ")", ";", "}" ]
Returns a random double within the specified range. @param startInclusive the earliest double that can be returned @param endExclusive the upper bound (not included) @return the random double @throws IllegalArgumentException if endExclusive is less than startInclusive
[ "Returns", "a", "random", "double", "within", "the", "specified", "range", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L194-L200
4,380
RKumsher/utils
src/main/java/com/github/rkumsher/number/RandomNumberUtils.java
RandomNumberUtils.randomDoubleGreaterThan
public static double randomDoubleGreaterThan(double minExclusive) { checkArgument( minExclusive < Double.MAX_VALUE, "Cannot produce double greater than %s", Double.MAX_VALUE); return randomDouble(minExclusive + 1, Double.MAX_VALUE); }
java
public static double randomDoubleGreaterThan(double minExclusive) { checkArgument( minExclusive < Double.MAX_VALUE, "Cannot produce double greater than %s", Double.MAX_VALUE); return randomDouble(minExclusive + 1, Double.MAX_VALUE); }
[ "public", "static", "double", "randomDoubleGreaterThan", "(", "double", "minExclusive", ")", "{", "checkArgument", "(", "minExclusive", "<", "Double", ".", "MAX_VALUE", ",", "\"Cannot produce double greater than %s\"", ",", "Double", ".", "MAX_VALUE", ")", ";", "return", "randomDouble", "(", "minExclusive", "+", "1", ",", "Double", ".", "MAX_VALUE", ")", ";", "}" ]
Returns a random double that is greater than the given double. @param minExclusive the value that returned double must be greater than @return the random double @throws IllegalArgumentException if minExclusive is greater than or equal to {@link Double#MAX_VALUE}
[ "Returns", "a", "random", "double", "that", "is", "greater", "than", "the", "given", "double", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L210-L214
4,381
RKumsher/utils
src/main/java/com/github/rkumsher/number/RandomNumberUtils.java
RandomNumberUtils.randomDoubleLessThan
public static double randomDoubleLessThan(double maxExclusive) { checkArgument( maxExclusive > -Double.MAX_VALUE, "Cannot produce double less than %s", -Double.MAX_VALUE); return randomDouble(-Double.MAX_VALUE, maxExclusive); }
java
public static double randomDoubleLessThan(double maxExclusive) { checkArgument( maxExclusive > -Double.MAX_VALUE, "Cannot produce double less than %s", -Double.MAX_VALUE); return randomDouble(-Double.MAX_VALUE, maxExclusive); }
[ "public", "static", "double", "randomDoubleLessThan", "(", "double", "maxExclusive", ")", "{", "checkArgument", "(", "maxExclusive", ">", "-", "Double", ".", "MAX_VALUE", ",", "\"Cannot produce double less than %s\"", ",", "-", "Double", ".", "MAX_VALUE", ")", ";", "return", "randomDouble", "(", "-", "Double", ".", "MAX_VALUE", ",", "maxExclusive", ")", ";", "}" ]
Returns a random double that is less than the given double. @param maxExclusive the value that returned double must be less than @return the random double @throws IllegalArgumentException if maxExclusive is less than or equal to negative {@link Double#MAX_VALUE}
[ "Returns", "a", "random", "double", "that", "is", "less", "than", "the", "given", "double", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/number/RandomNumberUtils.java#L224-L228
4,382
RKumsher/utils
src/main/java/com/github/rkumsher/enums/RandomEnumUtils.java
RandomEnumUtils.random
public static <T extends Enum<T>> T random(Class<T> enumClass) { EnumSet<T> enums = EnumSet.allOf(enumClass); return IterableUtils.randomFrom(enums); }
java
public static <T extends Enum<T>> T random(Class<T> enumClass) { EnumSet<T> enums = EnumSet.allOf(enumClass); return IterableUtils.randomFrom(enums); }
[ "public", "static", "<", "T", "extends", "Enum", "<", "T", ">", ">", "T", "random", "(", "Class", "<", "T", ">", "enumClass", ")", "{", "EnumSet", "<", "T", ">", "enums", "=", "EnumSet", ".", "allOf", "(", "enumClass", ")", ";", "return", "IterableUtils", ".", "randomFrom", "(", "enums", ")", ";", "}" ]
Returns a random element from the given enum class. @param enumClass enum class to return random element from @param <T> the type of the given enum class @return random element from the given enum class @throws IllegalArgumentException if the given enumClass has no values
[ "Returns", "a", "random", "element", "from", "the", "given", "enum", "class", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/enums/RandomEnumUtils.java#L21-L24
4,383
RKumsher/utils
src/main/java/com/github/rkumsher/collection/RandomArrayUtils.java
RandomArrayUtils.randomArrayFrom
@SuppressWarnings("unchecked") public static <T> T[] randomArrayFrom(Supplier<T> elementSupplier, int size) { checkArgument(size >= 0, "Size must be greater than or equal to zero"); return (T[]) Stream.generate(elementSupplier).limit(size).toArray(Object[]::new); }
java
@SuppressWarnings("unchecked") public static <T> T[] randomArrayFrom(Supplier<T> elementSupplier, int size) { checkArgument(size >= 0, "Size must be greater than or equal to zero"); return (T[]) Stream.generate(elementSupplier).limit(size).toArray(Object[]::new); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "[", "]", "randomArrayFrom", "(", "Supplier", "<", "T", ">", "elementSupplier", ",", "int", "size", ")", "{", "checkArgument", "(", "size", ">=", "0", ",", "\"Size must be greater than or equal to zero\"", ")", ";", "return", "(", "T", "[", "]", ")", "Stream", ".", "generate", "(", "elementSupplier", ")", ".", "limit", "(", "size", ")", ".", "toArray", "(", "Object", "[", "]", "::", "new", ")", ";", "}" ]
Returns an array filled from the given element supplier. @param elementSupplier element supplier to fill array from @param size of the random array to return @param <T> the type of element the given supplier returns @return array filled from the given elements @throws IllegalArgumentException if the size is negative
[ "Returns", "an", "array", "filled", "from", "the", "given", "element", "supplier", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/collection/RandomArrayUtils.java#L105-L109
4,384
RestComm/sctp
sctp-impl/src/main/java/org/mobicents/protocols/sctp/AssociationImpl.java
AssociationImpl.stop
protected void stop() throws Exception { this.started = false; for (ManagementEventListener lstr : this.management.getManagementEventListeners()) { try { lstr.onAssociationStopped(this); } catch (Throwable ee) { logger.error("Exception while invoking onAssociationStopped", ee); } } if (this.getSocketChannel() != null && this.getSocketChannel().isOpen()) { FastList<ChangeRequest> pendingChanges = this.management.getPendingChanges(); synchronized (pendingChanges) { // Indicate we want the interest ops set changed pendingChanges.add(new ChangeRequest(getSocketChannel(), this, ChangeRequest.CLOSE, -1)); } // Finally, wake up our selecting thread so it can make the required // changes this.management.getSocketSelector().wakeup(); } }
java
protected void stop() throws Exception { this.started = false; for (ManagementEventListener lstr : this.management.getManagementEventListeners()) { try { lstr.onAssociationStopped(this); } catch (Throwable ee) { logger.error("Exception while invoking onAssociationStopped", ee); } } if (this.getSocketChannel() != null && this.getSocketChannel().isOpen()) { FastList<ChangeRequest> pendingChanges = this.management.getPendingChanges(); synchronized (pendingChanges) { // Indicate we want the interest ops set changed pendingChanges.add(new ChangeRequest(getSocketChannel(), this, ChangeRequest.CLOSE, -1)); } // Finally, wake up our selecting thread so it can make the required // changes this.management.getSocketSelector().wakeup(); } }
[ "protected", "void", "stop", "(", ")", "throws", "Exception", "{", "this", ".", "started", "=", "false", ";", "for", "(", "ManagementEventListener", "lstr", ":", "this", ".", "management", ".", "getManagementEventListeners", "(", ")", ")", "{", "try", "{", "lstr", ".", "onAssociationStopped", "(", "this", ")", ";", "}", "catch", "(", "Throwable", "ee", ")", "{", "logger", ".", "error", "(", "\"Exception while invoking onAssociationStopped\"", ",", "ee", ")", ";", "}", "}", "if", "(", "this", ".", "getSocketChannel", "(", ")", "!=", "null", "&&", "this", ".", "getSocketChannel", "(", ")", ".", "isOpen", "(", ")", ")", "{", "FastList", "<", "ChangeRequest", ">", "pendingChanges", "=", "this", ".", "management", ".", "getPendingChanges", "(", ")", ";", "synchronized", "(", "pendingChanges", ")", "{", "// Indicate we want the interest ops set changed", "pendingChanges", ".", "add", "(", "new", "ChangeRequest", "(", "getSocketChannel", "(", ")", ",", "this", ",", "ChangeRequest", ".", "CLOSE", ",", "-", "1", ")", ")", ";", "}", "// Finally, wake up our selecting thread so it can make the required", "// changes", "this", ".", "management", ".", "getSocketSelector", "(", ")", ".", "wakeup", "(", ")", ";", "}", "}" ]
Stops this Association. If the underlying SctpChannel is open, marks the channel for close
[ "Stops", "this", "Association", ".", "If", "the", "underlying", "SctpChannel", "is", "open", "marks", "the", "channel", "for", "close" ]
e92e16f965573ef0e8ced7af5c7e1c99c1ee5d92
https://github.com/RestComm/sctp/blob/e92e16f965573ef0e8ced7af5c7e1c99c1ee5d92/sctp-impl/src/main/java/org/mobicents/protocols/sctp/AssociationImpl.java#L244-L265
4,385
RKumsher/utils
src/main/java/com/github/rkumsher/collection/ArrayUtils.java
ArrayUtils.randomFrom
public static <T> T randomFrom(T[] array) { checkArgument(isNotEmpty(array), "Array cannot be empty"); return IterableUtils.randomFrom(Arrays.asList(array)); }
java
public static <T> T randomFrom(T[] array) { checkArgument(isNotEmpty(array), "Array cannot be empty"); return IterableUtils.randomFrom(Arrays.asList(array)); }
[ "public", "static", "<", "T", ">", "T", "randomFrom", "(", "T", "[", "]", "array", ")", "{", "checkArgument", "(", "isNotEmpty", "(", "array", ")", ",", "\"Array cannot be empty\"", ")", ";", "return", "IterableUtils", ".", "randomFrom", "(", "Arrays", ".", "asList", "(", "array", ")", ")", ";", "}" ]
Returns a random element from the given array. @param array array to return random element from @param <T> the type of elements in the given array @return random element from the given array @throws IllegalArgumentException if the array is empty
[ "Returns", "a", "random", "element", "from", "the", "given", "array", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/collection/ArrayUtils.java#L26-L29
4,386
RKumsher/utils
src/main/java/com/github/rkumsher/collection/RandomCollectionUtils.java
RandomCollectionUtils.randomListFrom
public static <T> List<T> randomListFrom(Iterable<T> elements, Range<Integer> size) { checkArgument(!isEmpty(elements), "Elements to populate from must not be empty"); return randomListFrom(() -> IterableUtils.randomFrom(elements), size); }
java
public static <T> List<T> randomListFrom(Iterable<T> elements, Range<Integer> size) { checkArgument(!isEmpty(elements), "Elements to populate from must not be empty"); return randomListFrom(() -> IterableUtils.randomFrom(elements), size); }
[ "public", "static", "<", "T", ">", "List", "<", "T", ">", "randomListFrom", "(", "Iterable", "<", "T", ">", "elements", ",", "Range", "<", "Integer", ">", "size", ")", "{", "checkArgument", "(", "!", "isEmpty", "(", "elements", ")", ",", "\"Elements to populate from must not be empty\"", ")", ";", "return", "randomListFrom", "(", "(", ")", "->", "IterableUtils", ".", "randomFrom", "(", "elements", ")", ",", "size", ")", ";", "}" ]
Returns a list filled randomly from the given elements. @param elements elements to randomly fill list from @param size range that the size of the list will be randomly chosen from @param <T> the type of elements in the given iterable @return list filled randomly from the given elements @throws IllegalArgumentException if the elements to fill list from is empty or if the size range contains negative integers
[ "Returns", "a", "list", "filled", "randomly", "from", "the", "given", "elements", "." ]
fcdb190569cd0288249bf4b46fd418f8c01d1caf
https://github.com/RKumsher/utils/blob/fcdb190569cd0288249bf4b46fd418f8c01d1caf/src/main/java/com/github/rkumsher/collection/RandomCollectionUtils.java#L97-L100
4,387
ReactiveX/RxJavaDebug
src/main/java/rx/plugins/SimpleDebugNotificationListener.java
SimpleDebugNotificationListener.getNotificationsByObservable
public SortedSet<NotificationsByObservable<?>> getNotificationsByObservable() { SortedSet<NotificationsByObservable<?>> notificationsByObservableSnapshot = new TreeSet<NotificationsByObservable<?>>(); for (Entry<Subscriber<?>, Queue<SimpleContext<?>>> notificationsForObservable : notificationsByObservable.entrySet()) { notificationsByObservableSnapshot.add(new NotificationsByObservable(notificationsForObservable)); } return notificationsByObservableSnapshot; }
java
public SortedSet<NotificationsByObservable<?>> getNotificationsByObservable() { SortedSet<NotificationsByObservable<?>> notificationsByObservableSnapshot = new TreeSet<NotificationsByObservable<?>>(); for (Entry<Subscriber<?>, Queue<SimpleContext<?>>> notificationsForObservable : notificationsByObservable.entrySet()) { notificationsByObservableSnapshot.add(new NotificationsByObservable(notificationsForObservable)); } return notificationsByObservableSnapshot; }
[ "public", "SortedSet", "<", "NotificationsByObservable", "<", "?", ">", ">", "getNotificationsByObservable", "(", ")", "{", "SortedSet", "<", "NotificationsByObservable", "<", "?", ">", ">", "notificationsByObservableSnapshot", "=", "new", "TreeSet", "<", "NotificationsByObservable", "<", "?", ">", ">", "(", ")", ";", "for", "(", "Entry", "<", "Subscriber", "<", "?", ">", ",", "Queue", "<", "SimpleContext", "<", "?", ">", ">", ">", "notificationsForObservable", ":", "notificationsByObservable", ".", "entrySet", "(", ")", ")", "{", "notificationsByObservableSnapshot", ".", "add", "(", "new", "NotificationsByObservable", "(", "notificationsForObservable", ")", ")", ";", "}", "return", "notificationsByObservableSnapshot", ";", "}" ]
a copy sorted by time of the all the state useful for analysis. @return
[ "a", "copy", "sorted", "by", "time", "of", "the", "all", "the", "state", "useful", "for", "analysis", "." ]
4bb9b0b4e9f68038698eb416402f0a1162ff85ae
https://github.com/ReactiveX/RxJavaDebug/blob/4bb9b0b4e9f68038698eb416402f0a1162ff85ae/src/main/java/rx/plugins/SimpleDebugNotificationListener.java#L115-L121
4,388
hibernate/hibernate-metamodelgen
src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java
XmlMetaEntity.getType
private String getType(String propertyName, String explicitTargetEntity, ElementKind expectedElementKind) { for ( Element elem : element.getEnclosedElements() ) { if ( !expectedElementKind.equals( elem.getKind() ) ) { continue; } TypeMirror mirror; String name = elem.getSimpleName().toString(); if ( ElementKind.METHOD.equals( elem.getKind() ) ) { name = StringUtil.getPropertyName( name ); mirror = ( (ExecutableElement) elem ).getReturnType(); } else { mirror = elem.asType(); } if ( name == null || !name.equals( propertyName ) ) { continue; } if ( explicitTargetEntity != null ) { // TODO should there be a check of the target entity class and if it is loadable? return explicitTargetEntity; } switch ( mirror.getKind() ) { case INT: { return "java.lang.Integer"; } case LONG: { return "java.lang.Long"; } case BOOLEAN: { return "java.lang.Boolean"; } case BYTE: { return "java.lang.Byte"; } case SHORT: { return "java.lang.Short"; } case CHAR: { return "java.lang.Char"; } case FLOAT: { return "java.lang.Float"; } case DOUBLE: { return "java.lang.Double"; } case DECLARED: { return mirror.toString(); } case TYPEVAR: { return mirror.toString(); } default: { } } } context.logMessage( Diagnostic.Kind.WARNING, "Unable to determine type for property " + propertyName + " of class " + getQualifiedName() + " using access type " + accessTypeInfo.getDefaultAccessType() ); return null; }
java
private String getType(String propertyName, String explicitTargetEntity, ElementKind expectedElementKind) { for ( Element elem : element.getEnclosedElements() ) { if ( !expectedElementKind.equals( elem.getKind() ) ) { continue; } TypeMirror mirror; String name = elem.getSimpleName().toString(); if ( ElementKind.METHOD.equals( elem.getKind() ) ) { name = StringUtil.getPropertyName( name ); mirror = ( (ExecutableElement) elem ).getReturnType(); } else { mirror = elem.asType(); } if ( name == null || !name.equals( propertyName ) ) { continue; } if ( explicitTargetEntity != null ) { // TODO should there be a check of the target entity class and if it is loadable? return explicitTargetEntity; } switch ( mirror.getKind() ) { case INT: { return "java.lang.Integer"; } case LONG: { return "java.lang.Long"; } case BOOLEAN: { return "java.lang.Boolean"; } case BYTE: { return "java.lang.Byte"; } case SHORT: { return "java.lang.Short"; } case CHAR: { return "java.lang.Char"; } case FLOAT: { return "java.lang.Float"; } case DOUBLE: { return "java.lang.Double"; } case DECLARED: { return mirror.toString(); } case TYPEVAR: { return mirror.toString(); } default: { } } } context.logMessage( Diagnostic.Kind.WARNING, "Unable to determine type for property " + propertyName + " of class " + getQualifiedName() + " using access type " + accessTypeInfo.getDefaultAccessType() ); return null; }
[ "private", "String", "getType", "(", "String", "propertyName", ",", "String", "explicitTargetEntity", ",", "ElementKind", "expectedElementKind", ")", "{", "for", "(", "Element", "elem", ":", "element", ".", "getEnclosedElements", "(", ")", ")", "{", "if", "(", "!", "expectedElementKind", ".", "equals", "(", "elem", ".", "getKind", "(", ")", ")", ")", "{", "continue", ";", "}", "TypeMirror", "mirror", ";", "String", "name", "=", "elem", ".", "getSimpleName", "(", ")", ".", "toString", "(", ")", ";", "if", "(", "ElementKind", ".", "METHOD", ".", "equals", "(", "elem", ".", "getKind", "(", ")", ")", ")", "{", "name", "=", "StringUtil", ".", "getPropertyName", "(", "name", ")", ";", "mirror", "=", "(", "(", "ExecutableElement", ")", "elem", ")", ".", "getReturnType", "(", ")", ";", "}", "else", "{", "mirror", "=", "elem", ".", "asType", "(", ")", ";", "}", "if", "(", "name", "==", "null", "||", "!", "name", ".", "equals", "(", "propertyName", ")", ")", "{", "continue", ";", "}", "if", "(", "explicitTargetEntity", "!=", "null", ")", "{", "// TODO should there be a check of the target entity class and if it is loadable?", "return", "explicitTargetEntity", ";", "}", "switch", "(", "mirror", ".", "getKind", "(", ")", ")", "{", "case", "INT", ":", "{", "return", "\"java.lang.Integer\"", ";", "}", "case", "LONG", ":", "{", "return", "\"java.lang.Long\"", ";", "}", "case", "BOOLEAN", ":", "{", "return", "\"java.lang.Boolean\"", ";", "}", "case", "BYTE", ":", "{", "return", "\"java.lang.Byte\"", ";", "}", "case", "SHORT", ":", "{", "return", "\"java.lang.Short\"", ";", "}", "case", "CHAR", ":", "{", "return", "\"java.lang.Char\"", ";", "}", "case", "FLOAT", ":", "{", "return", "\"java.lang.Float\"", ";", "}", "case", "DOUBLE", ":", "{", "return", "\"java.lang.Double\"", ";", "}", "case", "DECLARED", ":", "{", "return", "mirror", ".", "toString", "(", ")", ";", "}", "case", "TYPEVAR", ":", "{", "return", "mirror", ".", "toString", "(", ")", ";", "}", "default", ":", "{", "}", "}", "}", "context", ".", "logMessage", "(", "Diagnostic", ".", "Kind", ".", "WARNING", ",", "\"Unable to determine type for property \"", "+", "propertyName", "+", "\" of class \"", "+", "getQualifiedName", "(", ")", "+", "\" using access type \"", "+", "accessTypeInfo", ".", "getDefaultAccessType", "(", ")", ")", ";", "return", "null", ";", "}" ]
Returns the entity type for a property. @param propertyName The property name @param explicitTargetEntity The explicitly specified target entity type or {@code null}. @param expectedElementKind Determines property vs field access type @return The entity type for this property or {@code null} if the property with the name and the matching access type does not exist.
[ "Returns", "the", "entity", "type", "for", "a", "property", "." ]
2c87b262bc03b1a5a541789fc00c54e0531a36b2
https://github.com/hibernate/hibernate-metamodelgen/blob/2c87b262bc03b1a5a541789fc00c54e0531a36b2/src/main/java/org/hibernate/jpamodelgen/xml/XmlMetaEntity.java#L301-L368
4,389
hibernate/hibernate-metamodelgen
src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java
TypeUtils.getAccessTypeInCaseElementIsRoot
private static AccessType getAccessTypeInCaseElementIsRoot(TypeElement searchedElement, Context context) { List<? extends Element> myMembers = searchedElement.getEnclosedElements(); for ( Element subElement : myMembers ) { List<? extends AnnotationMirror> entityAnnotations = context.getElementUtils().getAllAnnotationMirrors( subElement ); for ( Object entityAnnotation : entityAnnotations ) { AnnotationMirror annotationMirror = (AnnotationMirror) entityAnnotation; if ( isIdAnnotation( annotationMirror ) ) { return getAccessTypeOfIdAnnotation( subElement ); } } } return null; }
java
private static AccessType getAccessTypeInCaseElementIsRoot(TypeElement searchedElement, Context context) { List<? extends Element> myMembers = searchedElement.getEnclosedElements(); for ( Element subElement : myMembers ) { List<? extends AnnotationMirror> entityAnnotations = context.getElementUtils().getAllAnnotationMirrors( subElement ); for ( Object entityAnnotation : entityAnnotations ) { AnnotationMirror annotationMirror = (AnnotationMirror) entityAnnotation; if ( isIdAnnotation( annotationMirror ) ) { return getAccessTypeOfIdAnnotation( subElement ); } } } return null; }
[ "private", "static", "AccessType", "getAccessTypeInCaseElementIsRoot", "(", "TypeElement", "searchedElement", ",", "Context", "context", ")", "{", "List", "<", "?", "extends", "Element", ">", "myMembers", "=", "searchedElement", ".", "getEnclosedElements", "(", ")", ";", "for", "(", "Element", "subElement", ":", "myMembers", ")", "{", "List", "<", "?", "extends", "AnnotationMirror", ">", "entityAnnotations", "=", "context", ".", "getElementUtils", "(", ")", ".", "getAllAnnotationMirrors", "(", "subElement", ")", ";", "for", "(", "Object", "entityAnnotation", ":", "entityAnnotations", ")", "{", "AnnotationMirror", "annotationMirror", "=", "(", "AnnotationMirror", ")", "entityAnnotation", ";", "if", "(", "isIdAnnotation", "(", "annotationMirror", ")", ")", "{", "return", "getAccessTypeOfIdAnnotation", "(", "subElement", ")", ";", "}", "}", "}", "return", "null", ";", "}" ]
Iterates all elements of a type to check whether they contain the id annotation. If so the placement of this annotation determines the access type @param searchedElement the type to be searched @param context The global execution context @return returns the access type of the element annotated with the id annotation. If no element is annotated {@code null} is returned.
[ "Iterates", "all", "elements", "of", "a", "type", "to", "check", "whether", "they", "contain", "the", "id", "annotation", ".", "If", "so", "the", "placement", "of", "this", "annotation", "determines", "the", "access", "type" ]
2c87b262bc03b1a5a541789fc00c54e0531a36b2
https://github.com/hibernate/hibernate-metamodelgen/blob/2c87b262bc03b1a5a541789fc00c54e0531a36b2/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java#L340-L353
4,390
hibernate/hibernate-metamodelgen
src/main/java/org/hibernate/jpamodelgen/ClassWriter.java
ClassWriter.generateBody
private static StringBuffer generateBody(MetaEntity entity, Context context) { StringWriter sw = new StringWriter(); PrintWriter pw = null; try { pw = new PrintWriter( sw ); if ( context.addGeneratedAnnotation() ) { pw.println( writeGeneratedAnnotation( entity, context ) ); } if ( context.isAddSuppressWarningsAnnotation() ) { pw.println( writeSuppressWarnings() ); } pw.println( writeStaticMetaModelAnnotation( entity ) ); printClassDeclaration( entity, pw, context ); pw.println(); List<MetaAttribute> members = entity.getMembers(); for ( MetaAttribute metaMember : members ) { pw.println( " " + metaMember.getDeclarationString() ); } pw.println(); pw.println( "}" ); return sw.getBuffer(); } finally { if ( pw != null ) { pw.close(); } } }
java
private static StringBuffer generateBody(MetaEntity entity, Context context) { StringWriter sw = new StringWriter(); PrintWriter pw = null; try { pw = new PrintWriter( sw ); if ( context.addGeneratedAnnotation() ) { pw.println( writeGeneratedAnnotation( entity, context ) ); } if ( context.isAddSuppressWarningsAnnotation() ) { pw.println( writeSuppressWarnings() ); } pw.println( writeStaticMetaModelAnnotation( entity ) ); printClassDeclaration( entity, pw, context ); pw.println(); List<MetaAttribute> members = entity.getMembers(); for ( MetaAttribute metaMember : members ) { pw.println( " " + metaMember.getDeclarationString() ); } pw.println(); pw.println( "}" ); return sw.getBuffer(); } finally { if ( pw != null ) { pw.close(); } } }
[ "private", "static", "StringBuffer", "generateBody", "(", "MetaEntity", "entity", ",", "Context", "context", ")", "{", "StringWriter", "sw", "=", "new", "StringWriter", "(", ")", ";", "PrintWriter", "pw", "=", "null", ";", "try", "{", "pw", "=", "new", "PrintWriter", "(", "sw", ")", ";", "if", "(", "context", ".", "addGeneratedAnnotation", "(", ")", ")", "{", "pw", ".", "println", "(", "writeGeneratedAnnotation", "(", "entity", ",", "context", ")", ")", ";", "}", "if", "(", "context", ".", "isAddSuppressWarningsAnnotation", "(", ")", ")", "{", "pw", ".", "println", "(", "writeSuppressWarnings", "(", ")", ")", ";", "}", "pw", ".", "println", "(", "writeStaticMetaModelAnnotation", "(", "entity", ")", ")", ";", "printClassDeclaration", "(", "entity", ",", "pw", ",", "context", ")", ";", "pw", ".", "println", "(", ")", ";", "List", "<", "MetaAttribute", ">", "members", "=", "entity", ".", "getMembers", "(", ")", ";", "for", "(", "MetaAttribute", "metaMember", ":", "members", ")", "{", "pw", ".", "println", "(", "\"\t\"", "+", "metaMember", ".", "getDeclarationString", "(", ")", ")", ";", "}", "pw", ".", "println", "(", ")", ";", "pw", ".", "println", "(", "\"}\"", ")", ";", "return", "sw", ".", "getBuffer", "(", ")", ";", "}", "finally", "{", "if", "(", "pw", "!=", "null", ")", "{", "pw", ".", "close", "(", ")", ";", "}", "}", "}" ]
Generate everything after import statements. @param entity The meta entity for which to write the body @param context The processing context @return body content
[ "Generate", "everything", "after", "import", "statements", "." ]
2c87b262bc03b1a5a541789fc00c54e0531a36b2
https://github.com/hibernate/hibernate-metamodelgen/blob/2c87b262bc03b1a5a541789fc00c54e0531a36b2/src/main/java/org/hibernate/jpamodelgen/ClassWriter.java#L103-L136
4,391
JavaMoney/jsr354-ri-bp
src/main/java/org/javamoney/moneta/function/PermilOperator.java
PermilOperator.apply
@Override public MonetaryAmount apply(MonetaryAmount amount) { Objects.requireNonNull(amount, "Amount required."); return amount.multiply(permilValue); }
java
@Override public MonetaryAmount apply(MonetaryAmount amount) { Objects.requireNonNull(amount, "Amount required."); return amount.multiply(permilValue); }
[ "@", "Override", "public", "MonetaryAmount", "apply", "(", "MonetaryAmount", "amount", ")", "{", "Objects", ".", "requireNonNull", "(", "amount", ",", "\"Amount required.\"", ")", ";", "return", "amount", ".", "multiply", "(", "permilValue", ")", ";", "}" ]
Gets the permil of the amount. This returns the monetary amount in permil. For example, for 10% 'EUR 2.35' will return 0.235. This is returned as a {@code MonetaryAmount}. @return the permil result of the amount, never {@code null}
[ "Gets", "the", "permil", "of", "the", "amount", "." ]
9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2
https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/function/PermilOperator.java#L71-L75
4,392
JavaMoney/jsr354-ri-bp
src/main/java/org/javamoney/moneta/spi/base/BaseMonetaryCurrenciesSingletonSpi.java
BaseMonetaryCurrenciesSingletonSpi.getCurrency
public CurrencyUnit getCurrency(CurrencyQuery query) { Set<CurrencyUnit> currencies = getCurrencies(query); if (currencies.isEmpty()) { return null; } if (currencies.size() == 1) { return currencies.iterator().next(); } throw new MonetaryException("Ambiguous request for CurrencyUnit: " + query + ", found: " + currencies); }
java
public CurrencyUnit getCurrency(CurrencyQuery query) { Set<CurrencyUnit> currencies = getCurrencies(query); if (currencies.isEmpty()) { return null; } if (currencies.size() == 1) { return currencies.iterator().next(); } throw new MonetaryException("Ambiguous request for CurrencyUnit: " + query + ", found: " + currencies); }
[ "public", "CurrencyUnit", "getCurrency", "(", "CurrencyQuery", "query", ")", "{", "Set", "<", "CurrencyUnit", ">", "currencies", "=", "getCurrencies", "(", "query", ")", ";", "if", "(", "currencies", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "if", "(", "currencies", ".", "size", "(", ")", "==", "1", ")", "{", "return", "currencies", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "}", "throw", "new", "MonetaryException", "(", "\"Ambiguous request for CurrencyUnit: \"", "+", "query", "+", "\", found: \"", "+", "currencies", ")", ";", "}" ]
Access a single currency by query. @param query The currency query, not null. @return the {@link javax.money.CurrencyUnit} found, never null. @throws javax.money.MonetaryException if multiple currencies match the query.
[ "Access", "a", "single", "currency", "by", "query", "." ]
9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2
https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/spi/base/BaseMonetaryCurrenciesSingletonSpi.java#L144-L153
4,393
JavaMoney/jsr354-ri-bp
src/main/java/org/javamoney/moneta/convert/internal/LocalDate.java
LocalDate.from
public static LocalDate from(Calendar cal) { int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); return new LocalDate(year, month, dayOfMonth); }
java
public static LocalDate from(Calendar cal) { int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH)+1; int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); return new LocalDate(year, month, dayOfMonth); }
[ "public", "static", "LocalDate", "from", "(", "Calendar", "cal", ")", "{", "int", "year", "=", "cal", ".", "get", "(", "Calendar", ".", "YEAR", ")", ";", "int", "month", "=", "cal", ".", "get", "(", "Calendar", ".", "MONTH", ")", "+", "1", ";", "int", "dayOfMonth", "=", "cal", ".", "get", "(", "Calendar", ".", "DAY_OF_MONTH", ")", ";", "return", "new", "LocalDate", "(", "year", ",", "month", ",", "dayOfMonth", ")", ";", "}" ]
Cerates a new instance from the given Calendar. @param cal the Calendar, not null. @return the corresponding LocalDate instance, never null.
[ "Cerates", "a", "new", "instance", "from", "the", "given", "Calendar", "." ]
9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2
https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/convert/internal/LocalDate.java#L74-L79
4,394
JavaMoney/jsr354-ri-bp
src/main/java/org/javamoney/moneta/function/MonetaryFunctions.java
MonetaryFunctions.sortCurrencyUnitDesc
public static Comparator<MonetaryAmount> sortCurrencyUnitDesc(){ return new Comparator<MonetaryAmount>() { @Override public int compare(MonetaryAmount o1, MonetaryAmount o2) { return sortCurrencyUnit().compare(o1, o2) * -1; } }; }
java
public static Comparator<MonetaryAmount> sortCurrencyUnitDesc(){ return new Comparator<MonetaryAmount>() { @Override public int compare(MonetaryAmount o1, MonetaryAmount o2) { return sortCurrencyUnit().compare(o1, o2) * -1; } }; }
[ "public", "static", "Comparator", "<", "MonetaryAmount", ">", "sortCurrencyUnitDesc", "(", ")", "{", "return", "new", "Comparator", "<", "MonetaryAmount", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "MonetaryAmount", "o1", ",", "MonetaryAmount", "o2", ")", "{", "return", "sortCurrencyUnit", "(", ")", ".", "compare", "(", "o1", ",", "o2", ")", "*", "-", "1", ";", "}", "}", ";", "}" ]
Get a comparator for sorting CurrencyUnits descending. @return the Comparator to sort by CurrencyUnit in descending order, not null.
[ "Get", "a", "comparator", "for", "sorting", "CurrencyUnits", "descending", "." ]
9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2
https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/function/MonetaryFunctions.java#L131-L138
4,395
JavaMoney/jsr354-ri-bp
src/main/java/org/javamoney/moneta/function/MonetaryFunctions.java
MonetaryFunctions.sortNumberDesc
public static Comparator<MonetaryAmount> sortNumberDesc(){ return new Comparator<MonetaryAmount>() { @Override public int compare(MonetaryAmount o1, MonetaryAmount o2) { return sortNumber().compare(o1, o2) * -1; } }; }
java
public static Comparator<MonetaryAmount> sortNumberDesc(){ return new Comparator<MonetaryAmount>() { @Override public int compare(MonetaryAmount o1, MonetaryAmount o2) { return sortNumber().compare(o1, o2) * -1; } }; }
[ "public", "static", "Comparator", "<", "MonetaryAmount", ">", "sortNumberDesc", "(", ")", "{", "return", "new", "Comparator", "<", "MonetaryAmount", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "MonetaryAmount", "o1", ",", "MonetaryAmount", "o2", ")", "{", "return", "sortNumber", "(", ")", ".", "compare", "(", "o1", ",", "o2", ")", "*", "-", "1", ";", "}", "}", ";", "}" ]
Get a comparator for sorting amount by number value descending. @return the Comparator to sort by number in descending way, not null.
[ "Get", "a", "comparator", "for", "sorting", "amount", "by", "number", "value", "descending", "." ]
9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2
https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/function/MonetaryFunctions.java#L152-L159
4,396
JavaMoney/jsr354-ri-bp
src/main/java/org/javamoney/moneta/internal/format/ParseContext.java
ParseContext.lookupNextToken
public String lookupNextToken() { skipWhitespace(); int start = index; for (int end = index; end < originalInput.length(); end++) { if (Character.isWhitespace(originalInput.charAt(end))) { if (end > start) { return originalInput.subSequence(start, end).toString(); } return null; } } if (start < originalInput.length()) { return originalInput.subSequence(start, originalInput.length()) .toString(); } return null; }
java
public String lookupNextToken() { skipWhitespace(); int start = index; for (int end = index; end < originalInput.length(); end++) { if (Character.isWhitespace(originalInput.charAt(end))) { if (end > start) { return originalInput.subSequence(start, end).toString(); } return null; } } if (start < originalInput.length()) { return originalInput.subSequence(start, originalInput.length()) .toString(); } return null; }
[ "public", "String", "lookupNextToken", "(", ")", "{", "skipWhitespace", "(", ")", ";", "int", "start", "=", "index", ";", "for", "(", "int", "end", "=", "index", ";", "end", "<", "originalInput", ".", "length", "(", ")", ";", "end", "++", ")", "{", "if", "(", "Character", ".", "isWhitespace", "(", "originalInput", ".", "charAt", "(", "end", ")", ")", ")", "{", "if", "(", "end", ">", "start", ")", "{", "return", "originalInput", ".", "subSequence", "(", "start", ",", "end", ")", ".", "toString", "(", ")", ";", "}", "return", "null", ";", "}", "}", "if", "(", "start", "<", "originalInput", ".", "length", "(", ")", ")", "{", "return", "originalInput", ".", "subSequence", "(", "start", ",", "originalInput", ".", "length", "(", ")", ")", ".", "toString", "(", ")", ";", "}", "return", "null", ";", "}" ]
This method skips all whitespaces and returns the full text, until another whitespace area or the end of the input is reached. The method will not update any index pointers. @return the next token found, or null.
[ "This", "method", "skips", "all", "whitespaces", "and", "returns", "the", "full", "text", "until", "another", "whitespace", "area", "or", "the", "end", "of", "the", "input", "is", "reached", ".", "The", "method", "will", "not", "update", "any", "index", "pointers", "." ]
9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2
https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/internal/format/ParseContext.java#L256-L272
4,397
JavaMoney/jsr354-ri-bp
src/main/java/org/javamoney/moneta/internal/ConfigurableCurrencyUnitProvider.java
ConfigurableCurrencyUnitProvider.registerCurrencyUnit
public static CurrencyUnit registerCurrencyUnit(CurrencyUnit currencyUnit) { Objects.requireNonNull(currencyUnit); return ConfigurableCurrencyUnitProvider.currencyUnits.put(currencyUnit.getCurrencyCode(), currencyUnit); }
java
public static CurrencyUnit registerCurrencyUnit(CurrencyUnit currencyUnit) { Objects.requireNonNull(currencyUnit); return ConfigurableCurrencyUnitProvider.currencyUnits.put(currencyUnit.getCurrencyCode(), currencyUnit); }
[ "public", "static", "CurrencyUnit", "registerCurrencyUnit", "(", "CurrencyUnit", "currencyUnit", ")", "{", "Objects", ".", "requireNonNull", "(", "currencyUnit", ")", ";", "return", "ConfigurableCurrencyUnitProvider", ".", "currencyUnits", ".", "put", "(", "currencyUnit", ".", "getCurrencyCode", "(", ")", ",", "currencyUnit", ")", ";", "}" ]
Registers a bew currency unit under its currency code. @param currencyUnit the new currency to be registered, not null. @return any unit instance registered previously by this instance, or null.
[ "Registers", "a", "bew", "currency", "unit", "under", "its", "currency", "code", "." ]
9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2
https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/internal/ConfigurableCurrencyUnitProvider.java#L78-L81
4,398
JavaMoney/jsr354-ri-bp
src/main/java/org/javamoney/moneta/internal/ConfigurableCurrencyUnitProvider.java
ConfigurableCurrencyUnitProvider.registerCurrencyUnit
public static CurrencyUnit registerCurrencyUnit(CurrencyUnit currencyUnit, Locale locale) { Objects.requireNonNull(locale); Objects.requireNonNull(currencyUnit); return ConfigurableCurrencyUnitProvider.currencyUnitsByLocale.put(locale, currencyUnit); }
java
public static CurrencyUnit registerCurrencyUnit(CurrencyUnit currencyUnit, Locale locale) { Objects.requireNonNull(locale); Objects.requireNonNull(currencyUnit); return ConfigurableCurrencyUnitProvider.currencyUnitsByLocale.put(locale, currencyUnit); }
[ "public", "static", "CurrencyUnit", "registerCurrencyUnit", "(", "CurrencyUnit", "currencyUnit", ",", "Locale", "locale", ")", "{", "Objects", ".", "requireNonNull", "(", "locale", ")", ";", "Objects", ".", "requireNonNull", "(", "currencyUnit", ")", ";", "return", "ConfigurableCurrencyUnitProvider", ".", "currencyUnitsByLocale", ".", "put", "(", "locale", ",", "currencyUnit", ")", ";", "}" ]
Registers a bew currency unit under the given Locale. @param currencyUnit the new currency to be registered, not null. @param locale the Locale, not null. @return any unit instance registered previously by this instance, or null.
[ "Registers", "a", "bew", "currency", "unit", "under", "the", "given", "Locale", "." ]
9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2
https://github.com/JavaMoney/jsr354-ri-bp/blob/9c147ef5623d8032a6dc4c0e5eefdfb41641a9a2/src/main/java/org/javamoney/moneta/internal/ConfigurableCurrencyUnitProvider.java#L90-L94
4,399
zalando-stups/java-sproc-wrapper
src/main/java/de/zalando/typemapper/core/db/DbTypeRegister.java
DbTypeRegister.getRegistry
public static DbTypeRegister getRegistry(final Connection connection) throws SQLException { // if connection URL is null we can't proceed. fail fast Preconditions.checkNotNull(connection); final String connectionURL = connection.getMetaData().getURL(); Preconditions.checkNotNull(connection.getMetaData().getURL(), "connection URL is null"); // check if we have the value in memory DbTypeRegister cachedRegisters = registers.get(connectionURL); // First check (no locking) if (cachedRegisters == null) { synchronized (typeRegisterLock) { cachedRegisters = registers.get(connectionURL); // Second check (with locking) if (cachedRegisters == null) { cachedRegisters = new DbTypeRegister(connection); // read optimization. We are not expecting so many different DBMS URLs, so read is really fast and // the write is a little bit slower which is ok because most of the // times we will use what we have in memory. Copy all previous entries to the new immutable map. // This soudnd't happen very often. registers = ImmutableMap.<String, DbTypeRegister>builder().putAll(registers) .put(connectionURL, cachedRegisters).build(); } } } return cachedRegisters; }
java
public static DbTypeRegister getRegistry(final Connection connection) throws SQLException { // if connection URL is null we can't proceed. fail fast Preconditions.checkNotNull(connection); final String connectionURL = connection.getMetaData().getURL(); Preconditions.checkNotNull(connection.getMetaData().getURL(), "connection URL is null"); // check if we have the value in memory DbTypeRegister cachedRegisters = registers.get(connectionURL); // First check (no locking) if (cachedRegisters == null) { synchronized (typeRegisterLock) { cachedRegisters = registers.get(connectionURL); // Second check (with locking) if (cachedRegisters == null) { cachedRegisters = new DbTypeRegister(connection); // read optimization. We are not expecting so many different DBMS URLs, so read is really fast and // the write is a little bit slower which is ok because most of the // times we will use what we have in memory. Copy all previous entries to the new immutable map. // This soudnd't happen very often. registers = ImmutableMap.<String, DbTypeRegister>builder().putAll(registers) .put(connectionURL, cachedRegisters).build(); } } } return cachedRegisters; }
[ "public", "static", "DbTypeRegister", "getRegistry", "(", "final", "Connection", "connection", ")", "throws", "SQLException", "{", "// if connection URL is null we can't proceed. fail fast", "Preconditions", ".", "checkNotNull", "(", "connection", ")", ";", "final", "String", "connectionURL", "=", "connection", ".", "getMetaData", "(", ")", ".", "getURL", "(", ")", ";", "Preconditions", ".", "checkNotNull", "(", "connection", ".", "getMetaData", "(", ")", ".", "getURL", "(", ")", ",", "\"connection URL is null\"", ")", ";", "// check if we have the value in memory", "DbTypeRegister", "cachedRegisters", "=", "registers", ".", "get", "(", "connectionURL", ")", ";", "// First check (no locking)", "if", "(", "cachedRegisters", "==", "null", ")", "{", "synchronized", "(", "typeRegisterLock", ")", "{", "cachedRegisters", "=", "registers", ".", "get", "(", "connectionURL", ")", ";", "// Second check (with locking)", "if", "(", "cachedRegisters", "==", "null", ")", "{", "cachedRegisters", "=", "new", "DbTypeRegister", "(", "connection", ")", ";", "// read optimization. We are not expecting so many different DBMS URLs, so read is really fast and", "// the write is a little bit slower which is ok because most of the", "// times we will use what we have in memory. Copy all previous entries to the new immutable map.", "// This soudnd't happen very often.", "registers", "=", "ImmutableMap", ".", "<", "String", ",", "DbTypeRegister", ">", "builder", "(", ")", ".", "putAll", "(", "registers", ")", ".", "put", "(", "connectionURL", ",", "cachedRegisters", ")", ".", "build", "(", ")", ";", "}", "}", "}", "return", "cachedRegisters", ";", "}" ]
situation because we are not expecting so many different jdbc urls.
[ "situation", "because", "we", "are", "not", "expecting", "so", "many", "different", "jdbc", "urls", "." ]
b86a6243e83e8ea33d1a46e9dbac8c79082dc0ec
https://github.com/zalando-stups/java-sproc-wrapper/blob/b86a6243e83e8ea33d1a46e9dbac8c79082dc0ec/src/main/java/de/zalando/typemapper/core/db/DbTypeRegister.java#L280-L311