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
134,800
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/MapperFactory.java
MapperFactory.createCustomMapper
private Mapper createCustomMapper(Field field, PropertyMapper propertyMapperAnnotation) { Class<? extends Mapper> mapperClass = propertyMapperAnnotation.value(); Constructor<? extends Mapper> constructor = IntrospectionUtils.getConstructor(mapperClass, Field.class); if (constructor != null) { try { return constructor.newInstance(field); } catch (Exception exp) { throw new EntityManagerException(exp); } } throw new EntityManagerException( String.format("Mapper class %s must have a public constructor with a parameter type of %s", mapperClass.getName(), Field.class.getName())); }
java
private Mapper createCustomMapper(Field field, PropertyMapper propertyMapperAnnotation) { Class<? extends Mapper> mapperClass = propertyMapperAnnotation.value(); Constructor<? extends Mapper> constructor = IntrospectionUtils.getConstructor(mapperClass, Field.class); if (constructor != null) { try { return constructor.newInstance(field); } catch (Exception exp) { throw new EntityManagerException(exp); } } throw new EntityManagerException( String.format("Mapper class %s must have a public constructor with a parameter type of %s", mapperClass.getName(), Field.class.getName())); }
[ "private", "Mapper", "createCustomMapper", "(", "Field", "field", ",", "PropertyMapper", "propertyMapperAnnotation", ")", "{", "Class", "<", "?", "extends", "Mapper", ">", "mapperClass", "=", "propertyMapperAnnotation", ".", "value", "(", ")", ";", "Constructor", ...
Creates and returns a custom mapper for the given field. @param field the field @param propertyMapperAnnotation property mapper annotation that specifies the mapper class @return custom mapper for the given field
[ "Creates", "and", "returns", "a", "custom", "mapper", "for", "the", "given", "field", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/MapperFactory.java#L297-L312
134,801
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/AbstractListenerMetadata.java
AbstractListenerMetadata.putListener
public void putListener(CallbackType callbackType, Method method) { if (callbacks == null) { callbacks = new EnumMap<>(CallbackType.class); } Method oldMethod = callbacks.put(callbackType, method); if (oldMethod != null) { String format = "Class %s has at least two methods, %s and %s, with annotation of %s. " + "At most one method is allowed for a given callback type. "; String message = String.format(format, listenerClass.getName(), oldMethod.getName(), method.getName(), callbackType.getAnnotationClass().getName()); throw new EntityManagerException(message); } }
java
public void putListener(CallbackType callbackType, Method method) { if (callbacks == null) { callbacks = new EnumMap<>(CallbackType.class); } Method oldMethod = callbacks.put(callbackType, method); if (oldMethod != null) { String format = "Class %s has at least two methods, %s and %s, with annotation of %s. " + "At most one method is allowed for a given callback type. "; String message = String.format(format, listenerClass.getName(), oldMethod.getName(), method.getName(), callbackType.getAnnotationClass().getName()); throw new EntityManagerException(message); } }
[ "public", "void", "putListener", "(", "CallbackType", "callbackType", ",", "Method", "method", ")", "{", "if", "(", "callbacks", "==", "null", ")", "{", "callbacks", "=", "new", "EnumMap", "<>", "(", "CallbackType", ".", "class", ")", ";", "}", "Method", ...
Registers the given method as the callback method for the given event type. @param callbackType the callback type @param method the callback method @throws EntityManagerException if there was already a callback method for the given event type.
[ "Registers", "the", "given", "method", "as", "the", "callback", "method", "for", "the", "given", "event", "type", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/AbstractListenerMetadata.java#L67-L79
134,802
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java
DefaultDatastoreReader.load
public <E> E load(Class<E> entityClass, DatastoreKey parentKey, long id) { EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); Key nativeKey; if (parentKey == null) { nativeKey = entityManager.newNativeKeyFactory().setKind(entityMetadata.getKind()).newKey(id); } else { nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build(); } return fetch(entityClass, nativeKey); }
java
public <E> E load(Class<E> entityClass, DatastoreKey parentKey, long id) { EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); Key nativeKey; if (parentKey == null) { nativeKey = entityManager.newNativeKeyFactory().setKind(entityMetadata.getKind()).newKey(id); } else { nativeKey = Key.newBuilder(parentKey.nativeKey(), entityMetadata.getKind(), id).build(); } return fetch(entityClass, nativeKey); }
[ "public", "<", "E", ">", "E", "load", "(", "Class", "<", "E", ">", "entityClass", ",", "DatastoreKey", "parentKey", ",", "long", "id", ")", "{", "EntityMetadata", "entityMetadata", "=", "EntityIntrospector", ".", "introspect", "(", "entityClass", ")", ";", ...
Loads and returns the entity with the given ID. The entity kind is determined from the supplied class. @param entityClass the entity class @param parentKey the parent key of the entity. @param id the ID of the entity @return the Entity object or <code>null</code>, if the the entity with the given ID does not exist in the Cloud Datastore. @throws EntityManagerException if any error occurs while inserting.
[ "Loads", "and", "returns", "the", "entity", "with", "the", "given", "ID", ".", "The", "entity", "kind", "is", "determined", "from", "the", "supplied", "class", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java#L125-L134
134,803
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java
DefaultDatastoreReader.load
public <E> E load(Class<E> entityClass, DatastoreKey key) { return fetch(entityClass, key.nativeKey()); }
java
public <E> E load(Class<E> entityClass, DatastoreKey key) { return fetch(entityClass, key.nativeKey()); }
[ "public", "<", "E", ">", "E", "load", "(", "Class", "<", "E", ">", "entityClass", ",", "DatastoreKey", "key", ")", "{", "return", "fetch", "(", "entityClass", ",", "key", ".", "nativeKey", "(", ")", ")", ";", "}" ]
Retrieves and returns the entity with the given key. @param entityClass the expected result type @param key the entity key @return the entity with the given key, or <code>null</code>, if no entity exists with the given key. @throws EntityManagerException if any error occurs while accessing the Datastore.
[ "Retrieves", "and", "returns", "the", "entity", "with", "the", "given", "key", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java#L191-L193
134,804
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java
DefaultDatastoreReader.loadByKey
public <E> List<E> loadByKey(Class<E> entityClass, List<DatastoreKey> keys) { Key[] nativeKeys = DatastoreUtils.toNativeKeys(keys); return fetch(entityClass, nativeKeys); }
java
public <E> List<E> loadByKey(Class<E> entityClass, List<DatastoreKey> keys) { Key[] nativeKeys = DatastoreUtils.toNativeKeys(keys); return fetch(entityClass, nativeKeys); }
[ "public", "<", "E", ">", "List", "<", "E", ">", "loadByKey", "(", "Class", "<", "E", ">", "entityClass", ",", "List", "<", "DatastoreKey", ">", "keys", ")", "{", "Key", "[", "]", "nativeKeys", "=", "DatastoreUtils", ".", "toNativeKeys", "(", "keys", ...
Retrieves and returns the entities for the given keys. @param entityClass the expected result type @param keys the entity keys @return the entities for the given keys. If one or more requested keys do not exist in the Cloud Datastore, the corresponding item in the returned list be <code>null</code>. @throws EntityManagerException if any error occurs while accessing the Datastore.
[ "Retrieves", "and", "returns", "the", "entities", "for", "the", "given", "keys", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java#L246-L249
134,805
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java
DefaultDatastoreReader.fetch
private <E> E fetch(Class<E> entityClass, Key nativeKey) { try { Entity nativeEntity = nativeReader.get(nativeKey); E entity = Unmarshaller.unmarshal(nativeEntity, entityClass); entityManager.executeEntityListeners(CallbackType.POST_LOAD, entity); return entity; } catch (DatastoreException exp) { throw new EntityManagerException(exp); } }
java
private <E> E fetch(Class<E> entityClass, Key nativeKey) { try { Entity nativeEntity = nativeReader.get(nativeKey); E entity = Unmarshaller.unmarshal(nativeEntity, entityClass); entityManager.executeEntityListeners(CallbackType.POST_LOAD, entity); return entity; } catch (DatastoreException exp) { throw new EntityManagerException(exp); } }
[ "private", "<", "E", ">", "E", "fetch", "(", "Class", "<", "E", ">", "entityClass", ",", "Key", "nativeKey", ")", "{", "try", "{", "Entity", "nativeEntity", "=", "nativeReader", ".", "get", "(", "nativeKey", ")", ";", "E", "entity", "=", "Unmarshaller"...
Fetches the entity given the native key. @param entityClass the expected result type @param nativeKey the native key @return the entity with the given key, or <code>null</code>, if no entity exists with the given key.
[ "Fetches", "the", "entity", "given", "the", "native", "key", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java#L261-L270
134,806
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java
DefaultDatastoreReader.fetch
private <E> List<E> fetch(Class<E> entityClass, Key[] nativeKeys) { try { List<Entity> nativeEntities = nativeReader.fetch(nativeKeys); List<E> entities = DatastoreUtils.toEntities(entityClass, nativeEntities); entityManager.executeEntityListeners(CallbackType.POST_LOAD, entities); return entities; } catch (DatastoreException exp) { throw new EntityManagerException(exp); } }
java
private <E> List<E> fetch(Class<E> entityClass, Key[] nativeKeys) { try { List<Entity> nativeEntities = nativeReader.fetch(nativeKeys); List<E> entities = DatastoreUtils.toEntities(entityClass, nativeEntities); entityManager.executeEntityListeners(CallbackType.POST_LOAD, entities); return entities; } catch (DatastoreException exp) { throw new EntityManagerException(exp); } }
[ "private", "<", "E", ">", "List", "<", "E", ">", "fetch", "(", "Class", "<", "E", ">", "entityClass", ",", "Key", "[", "]", "nativeKeys", ")", "{", "try", "{", "List", "<", "Entity", ">", "nativeEntities", "=", "nativeReader", ".", "fetch", "(", "n...
Fetches a list of entities for the given native keys. @param entityClass the expected result type @param nativeKeys the native keys of the entities @return the list of entities. If one or more keys do not exist, the corresponding item in the returned list will be <code>null</code>.
[ "Fetches", "a", "list", "of", "entities", "for", "the", "given", "native", "keys", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java#L282-L291
134,807
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java
DefaultDatastoreReader.longListToNativeKeys
private Key[] longListToNativeKeys(Class<?> entityClass, List<Long> identifiers) { if (identifiers == null || identifiers.isEmpty()) { return new Key[0]; } EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); Key[] nativeKeys = new Key[identifiers.size()]; KeyFactory keyFactory = entityManager.newNativeKeyFactory(); keyFactory.setKind(entityMetadata.getKind()); for (int i = 0; i < identifiers.size(); i++) { long id = identifiers.get(i); nativeKeys[i] = keyFactory.newKey(id); } return nativeKeys; }
java
private Key[] longListToNativeKeys(Class<?> entityClass, List<Long> identifiers) { if (identifiers == null || identifiers.isEmpty()) { return new Key[0]; } EntityMetadata entityMetadata = EntityIntrospector.introspect(entityClass); Key[] nativeKeys = new Key[identifiers.size()]; KeyFactory keyFactory = entityManager.newNativeKeyFactory(); keyFactory.setKind(entityMetadata.getKind()); for (int i = 0; i < identifiers.size(); i++) { long id = identifiers.get(i); nativeKeys[i] = keyFactory.newKey(id); } return nativeKeys; }
[ "private", "Key", "[", "]", "longListToNativeKeys", "(", "Class", "<", "?", ">", "entityClass", ",", "List", "<", "Long", ">", "identifiers", ")", "{", "if", "(", "identifiers", "==", "null", "||", "identifiers", ".", "isEmpty", "(", ")", ")", "{", "re...
Converts the given list of identifiers into an array of native Key objects. @param entityClass the entity class to which these identifiers belong to. @param identifiers the list of identifiers to convert. @return an array of Key objects
[ "Converts", "the", "given", "list", "of", "identifiers", "into", "an", "array", "of", "native", "Key", "objects", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultDatastoreReader.java#L460-L473
134,808
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java
DefaultEntityManager.getIncompleteKey
private IncompleteKey getIncompleteKey(Object entity) { EntityMetadata entityMetadata = EntityIntrospector.introspect(entity.getClass()); String kind = entityMetadata.getKind(); ParentKeyMetadata parentKeyMetadata = entityMetadata.getParentKeyMetadata(); DatastoreKey parentKey = null; IncompleteKey incompleteKey = null; if (parentKeyMetadata != null) { parentKey = (DatastoreKey) IntrospectionUtils.getFieldValue(parentKeyMetadata, entity); } if (parentKey != null) { incompleteKey = IncompleteKey.newBuilder(parentKey.nativeKey(), kind).build(); } else { incompleteKey = IncompleteKey.newBuilder(datastore.getOptions().getProjectId(), kind) .setNamespace(getEffectiveNamespace()).build(); } return incompleteKey; }
java
private IncompleteKey getIncompleteKey(Object entity) { EntityMetadata entityMetadata = EntityIntrospector.introspect(entity.getClass()); String kind = entityMetadata.getKind(); ParentKeyMetadata parentKeyMetadata = entityMetadata.getParentKeyMetadata(); DatastoreKey parentKey = null; IncompleteKey incompleteKey = null; if (parentKeyMetadata != null) { parentKey = (DatastoreKey) IntrospectionUtils.getFieldValue(parentKeyMetadata, entity); } if (parentKey != null) { incompleteKey = IncompleteKey.newBuilder(parentKey.nativeKey(), kind).build(); } else { incompleteKey = IncompleteKey.newBuilder(datastore.getOptions().getProjectId(), kind) .setNamespace(getEffectiveNamespace()).build(); } return incompleteKey; }
[ "private", "IncompleteKey", "getIncompleteKey", "(", "Object", "entity", ")", "{", "EntityMetadata", "entityMetadata", "=", "EntityIntrospector", ".", "introspect", "(", "entity", ".", "getClass", "(", ")", ")", ";", "String", "kind", "=", "entityMetadata", ".", ...
Returns an IncompleteKey of the given entity. @param entity the entity @return the incomplete key
[ "Returns", "an", "IncompleteKey", "of", "the", "given", "entity", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java#L378-L394
134,809
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java
DefaultEntityManager.executeEntityListeners
public void executeEntityListeners(CallbackType callbackType, Object entity) { // We may get null entities here. For example loading a nonexistent ID // or IDs. if (entity == null) { return; } EntityListenersMetadata entityListenersMetadata = EntityIntrospector .getEntityListenersMetadata(entity); List<CallbackMetadata> callbacks = entityListenersMetadata.getCallbacks(callbackType); if (!entityListenersMetadata.isExcludeDefaultListeners()) { executeGlobalListeners(callbackType, entity); } if (callbacks == null) { return; } for (CallbackMetadata callback : callbacks) { switch (callback.getListenerType()) { case EXTERNAL: Object listener = ListenerFactory.getInstance().getListener(callback.getListenerClass()); invokeCallbackMethod(callback.getCallbackMethod(), listener, entity); break; case INTERNAL: invokeCallbackMethod(callback.getCallbackMethod(), entity); break; default: String message = String.format("Unknown or unimplemented callback listener type: %s", callback.getListenerType()); throw new EntityManagerException(message); } } }
java
public void executeEntityListeners(CallbackType callbackType, Object entity) { // We may get null entities here. For example loading a nonexistent ID // or IDs. if (entity == null) { return; } EntityListenersMetadata entityListenersMetadata = EntityIntrospector .getEntityListenersMetadata(entity); List<CallbackMetadata> callbacks = entityListenersMetadata.getCallbacks(callbackType); if (!entityListenersMetadata.isExcludeDefaultListeners()) { executeGlobalListeners(callbackType, entity); } if (callbacks == null) { return; } for (CallbackMetadata callback : callbacks) { switch (callback.getListenerType()) { case EXTERNAL: Object listener = ListenerFactory.getInstance().getListener(callback.getListenerClass()); invokeCallbackMethod(callback.getCallbackMethod(), listener, entity); break; case INTERNAL: invokeCallbackMethod(callback.getCallbackMethod(), entity); break; default: String message = String.format("Unknown or unimplemented callback listener type: %s", callback.getListenerType()); throw new EntityManagerException(message); } } }
[ "public", "void", "executeEntityListeners", "(", "CallbackType", "callbackType", ",", "Object", "entity", ")", "{", "// We may get null entities here. For example loading a nonexistent ID", "// or IDs.", "if", "(", "entity", "==", "null", ")", "{", "return", ";", "}", "...
Executes the entity listeners associated with the given entity. @param callbackType the event type @param entity the entity that produced the event
[ "Executes", "the", "entity", "listeners", "associated", "with", "the", "given", "entity", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java#L440-L470
134,810
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java
DefaultEntityManager.executeEntityListeners
public void executeEntityListeners(CallbackType callbackType, List<?> entities) { for (Object entity : entities) { executeEntityListeners(callbackType, entity); } }
java
public void executeEntityListeners(CallbackType callbackType, List<?> entities) { for (Object entity : entities) { executeEntityListeners(callbackType, entity); } }
[ "public", "void", "executeEntityListeners", "(", "CallbackType", "callbackType", ",", "List", "<", "?", ">", "entities", ")", "{", "for", "(", "Object", "entity", ":", "entities", ")", "{", "executeEntityListeners", "(", "callbackType", ",", "entity", ")", ";"...
Executes the entity listeners associated with the given list of entities. @param callbackType the callback type @param entities the entities
[ "Executes", "the", "entity", "listeners", "associated", "with", "the", "given", "list", "of", "entities", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java#L480-L484
134,811
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java
DefaultEntityManager.executeGlobalListeners
private void executeGlobalListeners(CallbackType callbackType, Object entity) { if (globalCallbacks == null) { return; } List<CallbackMetadata> callbacks = globalCallbacks.get(callbackType); if (callbacks == null) { return; } for (CallbackMetadata callback : callbacks) { Object listener = ListenerFactory.getInstance().getListener(callback.getListenerClass()); invokeCallbackMethod(callback.getCallbackMethod(), listener, entity); } }
java
private void executeGlobalListeners(CallbackType callbackType, Object entity) { if (globalCallbacks == null) { return; } List<CallbackMetadata> callbacks = globalCallbacks.get(callbackType); if (callbacks == null) { return; } for (CallbackMetadata callback : callbacks) { Object listener = ListenerFactory.getInstance().getListener(callback.getListenerClass()); invokeCallbackMethod(callback.getCallbackMethod(), listener, entity); } }
[ "private", "void", "executeGlobalListeners", "(", "CallbackType", "callbackType", ",", "Object", "entity", ")", "{", "if", "(", "globalCallbacks", "==", "null", ")", "{", "return", ";", "}", "List", "<", "CallbackMetadata", ">", "callbacks", "=", "globalCallback...
Executes the global listeners for the given event type for the given entity. @param callbackType the event type @param entity the entity
[ "Executes", "the", "global", "listeners", "for", "the", "given", "event", "type", "for", "the", "given", "entity", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java#L494-L506
134,812
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java
DefaultEntityManager.invokeCallbackMethod
private static void invokeCallbackMethod(Method callbackMethod, Object listener, Object entity) { try { callbackMethod.invoke(listener, entity); } catch (Exception exp) { String message = String.format("Failed to execute callback method %s of class %s", callbackMethod.getName(), callbackMethod.getDeclaringClass().getName()); throw new EntityManagerException(message, exp); } }
java
private static void invokeCallbackMethod(Method callbackMethod, Object listener, Object entity) { try { callbackMethod.invoke(listener, entity); } catch (Exception exp) { String message = String.format("Failed to execute callback method %s of class %s", callbackMethod.getName(), callbackMethod.getDeclaringClass().getName()); throw new EntityManagerException(message, exp); } }
[ "private", "static", "void", "invokeCallbackMethod", "(", "Method", "callbackMethod", ",", "Object", "listener", ",", "Object", "entity", ")", "{", "try", "{", "callbackMethod", ".", "invoke", "(", "listener", ",", "entity", ")", ";", "}", "catch", "(", "Exc...
Invokes the given callback method on the given target object. @param callbackMethod the callback method @param listener the listener object on which to invoke the method @param entity the entity for which the callback is being invoked.
[ "Invokes", "the", "given", "callback", "method", "on", "the", "given", "target", "object", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/impl/DefaultEntityManager.java#L518-L527
134,813
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/IndexerFactory.java
IndexerFactory.createIndexer
@SuppressWarnings("unchecked") private <T extends Indexer> T createIndexer(Class<T> indexerClass) { synchronized (indexerClass) { Indexer indexer = cache.get(indexerClass); if (indexer == null) { indexer = (Indexer) IntrospectionUtils.instantiateObject(indexerClass); cache.put(indexerClass, indexer); } return (T) indexer; } }
java
@SuppressWarnings("unchecked") private <T extends Indexer> T createIndexer(Class<T> indexerClass) { synchronized (indexerClass) { Indexer indexer = cache.get(indexerClass); if (indexer == null) { indexer = (Indexer) IntrospectionUtils.instantiateObject(indexerClass); cache.put(indexerClass, indexer); } return (T) indexer; } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "<", "T", "extends", "Indexer", ">", "T", "createIndexer", "(", "Class", "<", "T", ">", "indexerClass", ")", "{", "synchronized", "(", "indexerClass", ")", "{", "Indexer", "indexer", "=", "cache"...
Creates the Indexer of the given class. @param indexerClass the indexer implementation class @return the Indexer.
[ "Creates", "the", "Indexer", "of", "the", "given", "class", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/IndexerFactory.java#L106-L116
134,814
sai-pullabhotla/catatumbo
src/main/java/com/jmethods/catatumbo/IndexerFactory.java
IndexerFactory.getDefaultIndexer
private Indexer getDefaultIndexer(Field field) { Type type = field.getGenericType(); if (type instanceof Class && type.equals(String.class)) { return getIndexer(LowerCaseStringIndexer.class); } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Class<?> rawType = (Class<?>) parameterizedType.getRawType(); if (List.class.isAssignableFrom(rawType) || Set.class.isAssignableFrom(rawType)) { Class<?>[] collectionType = IntrospectionUtils.resolveCollectionType(type); if (String.class.equals(collectionType[1])) { return getIndexer(LowerCaseStringListIndexer.class); } } } String message = String.format("No default indexer found for field %s in class %s", field.getName(), field.getDeclaringClass().getName()); throw new NoSuitableIndexerException(message); }
java
private Indexer getDefaultIndexer(Field field) { Type type = field.getGenericType(); if (type instanceof Class && type.equals(String.class)) { return getIndexer(LowerCaseStringIndexer.class); } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Class<?> rawType = (Class<?>) parameterizedType.getRawType(); if (List.class.isAssignableFrom(rawType) || Set.class.isAssignableFrom(rawType)) { Class<?>[] collectionType = IntrospectionUtils.resolveCollectionType(type); if (String.class.equals(collectionType[1])) { return getIndexer(LowerCaseStringListIndexer.class); } } } String message = String.format("No default indexer found for field %s in class %s", field.getName(), field.getDeclaringClass().getName()); throw new NoSuitableIndexerException(message); }
[ "private", "Indexer", "getDefaultIndexer", "(", "Field", "field", ")", "{", "Type", "type", "=", "field", ".", "getGenericType", "(", ")", ";", "if", "(", "type", "instanceof", "Class", "&&", "type", ".", "equals", "(", "String", ".", "class", ")", ")", ...
Returns the default indexer for the given field. @param field the field. @return the default indexer.
[ "Returns", "the", "default", "indexer", "for", "the", "given", "field", "." ]
96d4c6dce3a5009624f7112a398406914dd19165
https://github.com/sai-pullabhotla/catatumbo/blob/96d4c6dce3a5009624f7112a398406914dd19165/src/main/java/com/jmethods/catatumbo/IndexerFactory.java#L125-L142
134,815
greengerong/prerender-java
src/main/java/com/github/greengerong/PrerenderSeoService.java
PrerenderSeoService.copyRequestHeaders
private void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) throws URISyntaxException { // Get an Enumeration of all of the header names sent by the client Enumeration<?> enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = (String) enumerationOfHeaderNames.nextElement(); //Instead the content-length is effectively set via InputStreamEntity if (!headerName.equalsIgnoreCase(CONTENT_LENGTH) && !hopByHopHeaders.containsHeader(headerName)) { Enumeration<?> headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) {//sometimes more than one value String headerValue = (String) headers.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (headerName.equalsIgnoreCase(HOST)) { HttpHost host = URIUtils.extractHost(new URI(prerenderConfig.getPrerenderServiceUrl())); headerValue = host.getHostName(); if (host.getPort() != -1) { headerValue += ":" + host.getPort(); } } proxyRequest.addHeader(headerName, headerValue); } } } }
java
private void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) throws URISyntaxException { // Get an Enumeration of all of the header names sent by the client Enumeration<?> enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = (String) enumerationOfHeaderNames.nextElement(); //Instead the content-length is effectively set via InputStreamEntity if (!headerName.equalsIgnoreCase(CONTENT_LENGTH) && !hopByHopHeaders.containsHeader(headerName)) { Enumeration<?> headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) {//sometimes more than one value String headerValue = (String) headers.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (headerName.equalsIgnoreCase(HOST)) { HttpHost host = URIUtils.extractHost(new URI(prerenderConfig.getPrerenderServiceUrl())); headerValue = host.getHostName(); if (host.getPort() != -1) { headerValue += ":" + host.getPort(); } } proxyRequest.addHeader(headerName, headerValue); } } } }
[ "private", "void", "copyRequestHeaders", "(", "HttpServletRequest", "servletRequest", ",", "HttpRequest", "proxyRequest", ")", "throws", "URISyntaxException", "{", "// Get an Enumeration of all of the header names sent by the client", "Enumeration", "<", "?", ">", "enumerationOfH...
Copy request headers from the servlet client to the proxy request. @throws java.net.URISyntaxException
[ "Copy", "request", "headers", "from", "the", "servlet", "client", "to", "the", "proxy", "request", "." ]
f7fc7a5e9adea8cf556c653a87bbac2cfcac3d06
https://github.com/greengerong/prerender-java/blob/f7fc7a5e9adea8cf556c653a87bbac2cfcac3d06/src/main/java/com/github/greengerong/PrerenderSeoService.java#L159-L184
134,816
greengerong/prerender-java
src/main/java/com/github/greengerong/PrerenderSeoService.java
PrerenderSeoService.copyResponseHeaders
private void copyResponseHeaders(HttpResponse proxyResponse, final HttpServletResponse servletResponse) { servletResponse.setCharacterEncoding(getContentCharSet(proxyResponse.getEntity())); from(Arrays.asList(proxyResponse.getAllHeaders())).filter(new Predicate<Header>() { @Override public boolean apply(Header header) { return !hopByHopHeaders.containsHeader(header.getName()); } }).transform(new Function<Header, Boolean>() { @Override public Boolean apply(Header header) { servletResponse.addHeader(header.getName(), header.getValue()); return true; } }).toList(); }
java
private void copyResponseHeaders(HttpResponse proxyResponse, final HttpServletResponse servletResponse) { servletResponse.setCharacterEncoding(getContentCharSet(proxyResponse.getEntity())); from(Arrays.asList(proxyResponse.getAllHeaders())).filter(new Predicate<Header>() { @Override public boolean apply(Header header) { return !hopByHopHeaders.containsHeader(header.getName()); } }).transform(new Function<Header, Boolean>() { @Override public Boolean apply(Header header) { servletResponse.addHeader(header.getName(), header.getValue()); return true; } }).toList(); }
[ "private", "void", "copyResponseHeaders", "(", "HttpResponse", "proxyResponse", ",", "final", "HttpServletResponse", "servletResponse", ")", "{", "servletResponse", ".", "setCharacterEncoding", "(", "getContentCharSet", "(", "proxyResponse", ".", "getEntity", "(", ")", ...
Copy proxied response headers back to the servlet client.
[ "Copy", "proxied", "response", "headers", "back", "to", "the", "servlet", "client", "." ]
f7fc7a5e9adea8cf556c653a87bbac2cfcac3d06
https://github.com/greengerong/prerender-java/blob/f7fc7a5e9adea8cf556c653a87bbac2cfcac3d06/src/main/java/com/github/greengerong/PrerenderSeoService.java#L211-L225
134,817
greengerong/prerender-java
src/main/java/com/github/greengerong/PrerenderSeoService.java
PrerenderSeoService.getContentCharSet
private String getContentCharSet(final HttpEntity entity) throws ParseException { if (entity == null) { return null; } String charset = null; if (entity.getContentType() != null) { HeaderElement values[] = entity.getContentType().getElements(); if (values.length > 0) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } return charset; }
java
private String getContentCharSet(final HttpEntity entity) throws ParseException { if (entity == null) { return null; } String charset = null; if (entity.getContentType() != null) { HeaderElement values[] = entity.getContentType().getElements(); if (values.length > 0) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } return charset; }
[ "private", "String", "getContentCharSet", "(", "final", "HttpEntity", "entity", ")", "throws", "ParseException", "{", "if", "(", "entity", "==", "null", ")", "{", "return", "null", ";", "}", "String", "charset", "=", "null", ";", "if", "(", "entity", ".", ...
Get the charset used to encode the http entity.
[ "Get", "the", "charset", "used", "to", "encode", "the", "http", "entity", "." ]
f7fc7a5e9adea8cf556c653a87bbac2cfcac3d06
https://github.com/greengerong/prerender-java/blob/f7fc7a5e9adea8cf556c653a87bbac2cfcac3d06/src/main/java/com/github/greengerong/PrerenderSeoService.java#L230-L245
134,818
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/NvlModel.java
NvlModel.getDefaultObject
@SuppressWarnings("unchecked") public T getDefaultObject() { if(defaultValue instanceof IModel) { return ((IModel<T>)defaultValue).getObject(); } else { return (T) defaultValue; } }
java
@SuppressWarnings("unchecked") public T getDefaultObject() { if(defaultValue instanceof IModel) { return ((IModel<T>)defaultValue).getObject(); } else { return (T) defaultValue; } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "T", "getDefaultObject", "(", ")", "{", "if", "(", "defaultValue", "instanceof", "IModel", ")", "{", "return", "(", "(", "IModel", "<", "T", ">", ")", "defaultValue", ")", ".", "getObject", "(",...
Returns default value @return default value
[ "Returns", "default", "value" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/NvlModel.java#L41-L48
134,819
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.getEmail
public JsonResponse getEmail(String email) throws IOException { Email emailObj = new Email(); emailObj.setEmail(email); return apiGet(emailObj); }
java
public JsonResponse getEmail(String email) throws IOException { Email emailObj = new Email(); emailObj.setEmail(email); return apiGet(emailObj); }
[ "public", "JsonResponse", "getEmail", "(", "String", "email", ")", "throws", "IOException", "{", "Email", "emailObj", "=", "new", "Email", "(", ")", ";", "emailObj", ".", "setEmail", "(", "email", ")", ";", "return", "apiGet", "(", "emailObj", ")", ";", ...
Get information about one of your users. @param email @throws IOException
[ "Get", "information", "about", "one", "of", "your", "users", "." ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L83-L87
134,820
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.getSend
public JsonResponse getSend(String sendId) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Send.PARAM_SEND_ID, sendId); return apiGet(ApiAction.send, data); }
java
public JsonResponse getSend(String sendId) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Send.PARAM_SEND_ID, sendId); return apiGet(ApiAction.send, data); }
[ "public", "JsonResponse", "getSend", "(", "String", "sendId", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "Object", ">", "data", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "data", ".", "put", "(", "Send",...
Get the status of a transational send @param sendId Unique send id @throws IOException
[ "Get", "the", "status", "of", "a", "transational", "send" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L103-L107
134,821
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.cancelSend
public JsonResponse cancelSend(String sendId) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Send.PARAM_SEND_ID, sendId); return apiDelete(ApiAction.send, data); }
java
public JsonResponse cancelSend(String sendId) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Send.PARAM_SEND_ID, sendId); return apiDelete(ApiAction.send, data); }
[ "public", "JsonResponse", "cancelSend", "(", "String", "sendId", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "Object", ">", "data", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "data", ".", "put", "(", "Sen...
Cancel a send that was scheduled for a future time. @param sendId @return JsonResponse @throws IOException
[ "Cancel", "a", "send", "that", "was", "scheduled", "for", "a", "future", "time", "." ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L133-L137
134,822
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.getBlast
public JsonResponse getBlast(Integer blastId) throws IOException { Blast blast = new Blast(); blast.setBlastId(blastId); return apiGet(blast); }
java
public JsonResponse getBlast(Integer blastId) throws IOException { Blast blast = new Blast(); blast.setBlastId(blastId); return apiGet(blast); }
[ "public", "JsonResponse", "getBlast", "(", "Integer", "blastId", ")", "throws", "IOException", "{", "Blast", "blast", "=", "new", "Blast", "(", ")", ";", "blast", ".", "setBlastId", "(", "blastId", ")", ";", "return", "apiGet", "(", "blast", ")", ";", "}...
get information about a blast @param blastId @return JsonResponse @throws IOException
[ "get", "information", "about", "a", "blast" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L155-L159
134,823
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.scheduleBlastFromTemplate
public JsonResponse scheduleBlastFromTemplate(String template, String list, Date scheduleTime, Blast blast) throws IOException { blast.setCopyTemplate(template); blast.setList(list); blast.setScheduleTime(scheduleTime); return apiPost(blast); }
java
public JsonResponse scheduleBlastFromTemplate(String template, String list, Date scheduleTime, Blast blast) throws IOException { blast.setCopyTemplate(template); blast.setList(list); blast.setScheduleTime(scheduleTime); return apiPost(blast); }
[ "public", "JsonResponse", "scheduleBlastFromTemplate", "(", "String", "template", ",", "String", "list", ",", "Date", "scheduleTime", ",", "Blast", "blast", ")", "throws", "IOException", "{", "blast", ".", "setCopyTemplate", "(", "template", ")", ";", "blast", "...
Schedule a mass mail from a template @param template template name @param list list name @param scheduleTime schedule time for the blast @param blast Blast Object @throws IOException
[ "Schedule", "a", "mass", "mail", "from", "a", "template" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L179-L184
134,824
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.scheduleBlastFromBlast
public JsonResponse scheduleBlastFromBlast(Integer blastId, Date scheduleTime, Blast blast) throws IOException { blast.setCopyBlast(blastId); blast.setScheduleTime(scheduleTime); return apiPost(blast); }
java
public JsonResponse scheduleBlastFromBlast(Integer blastId, Date scheduleTime, Blast blast) throws IOException { blast.setCopyBlast(blastId); blast.setScheduleTime(scheduleTime); return apiPost(blast); }
[ "public", "JsonResponse", "scheduleBlastFromBlast", "(", "Integer", "blastId", ",", "Date", "scheduleTime", ",", "Blast", "blast", ")", "throws", "IOException", "{", "blast", ".", "setCopyBlast", "(", "blastId", ")", ";", "blast", ".", "setScheduleTime", "(", "s...
Schedule a mass mail blast from previous blast @param blastId blast ID @param scheduleTime schedule time for the blast @param blast Blast object @return JsonResponse @throws IOException
[ "Schedule", "a", "mass", "mail", "blast", "from", "previous", "blast" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L210-L214
134,825
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.updateBlast
public JsonResponse updateBlast(Integer blastId) throws IOException { Blast blast = new Blast(); blast.setBlastId(blastId); return apiPost(blast); }
java
public JsonResponse updateBlast(Integer blastId) throws IOException { Blast blast = new Blast(); blast.setBlastId(blastId); return apiPost(blast); }
[ "public", "JsonResponse", "updateBlast", "(", "Integer", "blastId", ")", "throws", "IOException", "{", "Blast", "blast", "=", "new", "Blast", "(", ")", ";", "blast", ".", "setBlastId", "(", "blastId", ")", ";", "return", "apiPost", "(", "blast", ")", ";", ...
Update existing blast @param blastId @throws IOException
[ "Update", "existing", "blast" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L234-L238
134,826
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.deleteBlast
public JsonResponse deleteBlast(Integer blastId) throws IOException { Blast blast = new Blast(); blast.setBlastId(blastId); return apiDelete(blast); }
java
public JsonResponse deleteBlast(Integer blastId) throws IOException { Blast blast = new Blast(); blast.setBlastId(blastId); return apiDelete(blast); }
[ "public", "JsonResponse", "deleteBlast", "(", "Integer", "blastId", ")", "throws", "IOException", "{", "Blast", "blast", "=", "new", "Blast", "(", ")", ";", "blast", ".", "setBlastId", "(", "blastId", ")", ";", "return", "apiDelete", "(", "blast", ")", ";"...
Delete existing blast @param blastId @throws IOException
[ "Delete", "existing", "blast" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L256-L260
134,827
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.cancelBlast
public JsonResponse cancelBlast(Integer blastId) throws IOException { Blast blast = new Blast(); Date d = null; blast .setBlastId(blastId) .setScheduleTime(d); return apiPost(blast); }
java
public JsonResponse cancelBlast(Integer blastId) throws IOException { Blast blast = new Blast(); Date d = null; blast .setBlastId(blastId) .setScheduleTime(d); return apiPost(blast); }
[ "public", "JsonResponse", "cancelBlast", "(", "Integer", "blastId", ")", "throws", "IOException", "{", "Blast", "blast", "=", "new", "Blast", "(", ")", ";", "Date", "d", "=", "null", ";", "blast", ".", "setBlastId", "(", "blastId", ")", ".", "setScheduleTi...
Cancel a scheduled Blast @param blastId Unique Blast ID @throws IOException
[ "Cancel", "a", "scheduled", "Blast" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L267-L274
134,828
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.getTemplate
public JsonResponse getTemplate(String template) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Template.PARAM_TEMPLATE, template); return apiGet(ApiAction.template, data); }
java
public JsonResponse getTemplate(String template) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Template.PARAM_TEMPLATE, template); return apiGet(ApiAction.template, data); }
[ "public", "JsonResponse", "getTemplate", "(", "String", "template", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "Object", ">", "data", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "data", ".", "put", "(", "...
Get template information @param template template name @throws IOException
[ "Get", "template", "information" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L281-L285
134,829
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.deleteTemplate
public JsonResponse deleteTemplate(String template) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Template.PARAM_TEMPLATE, template); return apiDelete(ApiAction.template, data); }
java
public JsonResponse deleteTemplate(String template) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Template.PARAM_TEMPLATE, template); return apiDelete(ApiAction.template, data); }
[ "public", "JsonResponse", "deleteTemplate", "(", "String", "template", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "Object", ">", "data", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "data", ".", "put", "(", ...
Delete existing template @param template template name @throws IOException
[ "Delete", "existing", "template" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L301-L305
134,830
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.getAlert
public JsonResponse getAlert(String email) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Alert.PARAM_EMAIL, email); return apiGet(ApiAction.alert, data); }
java
public JsonResponse getAlert(String email) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Alert.PARAM_EMAIL, email); return apiGet(ApiAction.alert, data); }
[ "public", "JsonResponse", "getAlert", "(", "String", "email", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "Object", ">", "data", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "data", ".", "put", "(", "Alert"...
Retrieve a user's alert settings @param email @return JsonResponse @throws IOException
[ "Retrieve", "a", "user", "s", "alert", "settings" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L331-L335
134,831
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.deleteAlert
public JsonResponse deleteAlert(String email, String alertId) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Alert.PARAM_EMAIL, email); data.put(Alert.PARAM_ALERT_ID, alertId); return apiDelete(ApiAction.alert, data); }
java
public JsonResponse deleteAlert(String email, String alertId) throws IOException { Map<String, Object> data = new HashMap<String, Object>(); data.put(Alert.PARAM_EMAIL, email); data.put(Alert.PARAM_ALERT_ID, alertId); return apiDelete(ApiAction.alert, data); }
[ "public", "JsonResponse", "deleteAlert", "(", "String", "email", ",", "String", "alertId", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "Object", ">", "data", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "data...
Delete existing user alert @param email User.java Email @param alertId Alert ID @throws IOException
[ "Delete", "existing", "user", "alert" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L353-L358
134,832
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.listStats
public Map<String, Object> listStats(ListStat stat) throws IOException { return (Map<String, Object>)this.stats(stat); }
java
public Map<String, Object> listStats(ListStat stat) throws IOException { return (Map<String, Object>)this.stats(stat); }
[ "public", "Map", "<", "String", ",", "Object", ">", "listStats", "(", "ListStat", "stat", ")", "throws", "IOException", "{", "return", "(", "Map", "<", "String", ",", "Object", ">", ")", "this", ".", "stats", "(", "stat", ")", ";", "}" ]
get list stats information @param stat @return JsonResponse @throws IOException
[ "get", "list", "stats", "information" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L384-L386
134,833
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.blastStats
public Map<String, Object> blastStats(BlastStat stat) throws IOException { return (Map<String, Object>)this.stats(stat); }
java
public Map<String, Object> blastStats(BlastStat stat) throws IOException { return (Map<String, Object>)this.stats(stat); }
[ "public", "Map", "<", "String", ",", "Object", ">", "blastStats", "(", "BlastStat", "stat", ")", "throws", "IOException", "{", "return", "(", "Map", "<", "String", ",", "Object", ">", ")", "this", ".", "stats", "(", "stat", ")", ";", "}" ]
get blast stats information @param stat @return JsonResponse @throws IOException
[ "get", "blast", "stats", "information" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L394-L396
134,834
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruClient.java
SailthruClient.getJobStatus
public JsonResponse getJobStatus(String jobId) throws IOException { Map<String, Object> params = new HashMap<String, Object>(); params.put(Job.JOB_ID, jobId); return apiGet(ApiAction.job, params); }
java
public JsonResponse getJobStatus(String jobId) throws IOException { Map<String, Object> params = new HashMap<String, Object>(); params.put(Job.JOB_ID, jobId); return apiGet(ApiAction.job, params); }
[ "public", "JsonResponse", "getJobStatus", "(", "String", "jobId", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "Object", ">", "params", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "params", ".", "put", "(", ...
Get status of a job @param jobId @return JsonResponse @throws IOException
[ "Get", "status", "of", "a", "job" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L405-L409
134,835
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java
OSchemaHelper.linkedClass
public OSchemaHelper linkedClass(String className) { checkOProperty(); OClass linkedToClass = schema.getClass(className); if(linkedToClass==null) throw new IllegalArgumentException("Target OClass '"+className+"' to link to not found"); if(!Objects.equal(linkedToClass, lastProperty.getLinkedClass())) { lastProperty.setLinkedClass(linkedToClass); } return this; }
java
public OSchemaHelper linkedClass(String className) { checkOProperty(); OClass linkedToClass = schema.getClass(className); if(linkedToClass==null) throw new IllegalArgumentException("Target OClass '"+className+"' to link to not found"); if(!Objects.equal(linkedToClass, lastProperty.getLinkedClass())) { lastProperty.setLinkedClass(linkedToClass); } return this; }
[ "public", "OSchemaHelper", "linkedClass", "(", "String", "className", ")", "{", "checkOProperty", "(", ")", ";", "OClass", "linkedToClass", "=", "schema", ".", "getClass", "(", "className", ")", ";", "if", "(", "linkedToClass", "==", "null", ")", "throw", "n...
Set linked class to a current property @param className class name to set as a linked class @return this helper
[ "Set", "linked", "class", "to", "a", "current", "property" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java#L148-L158
134,836
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java
OSchemaHelper.linkedType
public OSchemaHelper linkedType(OType linkedType) { checkOProperty(); if(!Objects.equal(linkedType, lastProperty.getLinkedType())) { lastProperty.setLinkedType(linkedType); } return this; }
java
public OSchemaHelper linkedType(OType linkedType) { checkOProperty(); if(!Objects.equal(linkedType, lastProperty.getLinkedType())) { lastProperty.setLinkedType(linkedType); } return this; }
[ "public", "OSchemaHelper", "linkedType", "(", "OType", "linkedType", ")", "{", "checkOProperty", "(", ")", ";", "if", "(", "!", "Objects", ".", "equal", "(", "linkedType", ",", "lastProperty", ".", "getLinkedType", "(", ")", ")", ")", "{", "lastProperty", ...
Set linked type to a current property @param linkedType {@link OType} to set as a linked type @return this helper
[ "Set", "linked", "type", "to", "a", "current", "property" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java#L165-L173
134,837
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java
OSchemaHelper.field
public OSchemaHelper field(String field, Object value) { checkODocument(); lastDocument.field(field, value); return this; }
java
public OSchemaHelper field(String field, Object value) { checkODocument(); lastDocument.field(field, value); return this; }
[ "public", "OSchemaHelper", "field", "(", "String", "field", ",", "Object", "value", ")", "{", "checkODocument", "(", ")", ";", "lastDocument", ".", "field", "(", "field", ",", "value", ")", ";", "return", "this", ";", "}" ]
Sets a field value for a current document @param field field name @param value value to set @return this helper
[ "Sets", "a", "field", "value", "for", "a", "current", "document" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/OSchemaHelper.java#L345-L350
134,838
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/DBClosure.java
DBClosure.sudo
public static <R> R sudo(Function<ODatabaseDocument, R> func) { return new DBClosure<R>() { @Override protected R execute(ODatabaseDocument db) { return func.apply(db); } }.execute(); }
java
public static <R> R sudo(Function<ODatabaseDocument, R> func) { return new DBClosure<R>() { @Override protected R execute(ODatabaseDocument db) { return func.apply(db); } }.execute(); }
[ "public", "static", "<", "R", ">", "R", "sudo", "(", "Function", "<", "ODatabaseDocument", ",", "R", ">", "func", ")", "{", "return", "new", "DBClosure", "<", "R", ">", "(", ")", "{", "@", "Override", "protected", "R", "execute", "(", "ODatabaseDocumen...
Simplified function to execute under admin @param func function to be executed @param <R> type of returned value @return result of a function
[ "Simplified", "function", "to", "execute", "under", "admin" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/DBClosure.java#L97-L104
134,839
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/DBClosure.java
DBClosure.sudoConsumer
public static void sudoConsumer(Consumer<ODatabaseDocument> consumer) { new DBClosure<Void>() { @Override protected Void execute(ODatabaseDocument db) { consumer.accept(db); return null; } }.execute(); }
java
public static void sudoConsumer(Consumer<ODatabaseDocument> consumer) { new DBClosure<Void>() { @Override protected Void execute(ODatabaseDocument db) { consumer.accept(db); return null; } }.execute(); }
[ "public", "static", "void", "sudoConsumer", "(", "Consumer", "<", "ODatabaseDocument", ">", "consumer", ")", "{", "new", "DBClosure", "<", "Void", ">", "(", ")", "{", "@", "Override", "protected", "Void", "execute", "(", "ODatabaseDocument", "db", ")", "{", ...
Simplified consumer to execute under admin @param consumer - consumer to be executed
[ "Simplified", "consumer", "to", "execute", "under", "admin" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/DBClosure.java#L110-L118
134,840
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/DBClosure.java
DBClosure.sudoSave
public static void sudoSave(final ODocument... docs) { if(docs==null || docs.length==0) return; new DBClosure<Boolean>() { @Override protected Boolean execute(ODatabaseDocument db) { db.begin(); for (ODocument doc : docs) { db.save(doc); } db.commit(); return true; } }.execute(); }
java
public static void sudoSave(final ODocument... docs) { if(docs==null || docs.length==0) return; new DBClosure<Boolean>() { @Override protected Boolean execute(ODatabaseDocument db) { db.begin(); for (ODocument doc : docs) { db.save(doc); } db.commit(); return true; } }.execute(); }
[ "public", "static", "void", "sudoSave", "(", "final", "ODocument", "...", "docs", ")", "{", "if", "(", "docs", "==", "null", "||", "docs", ".", "length", "==", "0", ")", "return", ";", "new", "DBClosure", "<", "Boolean", ">", "(", ")", "{", "@", "O...
Allow to save set of document under admin @param docs set of document to be saved
[ "Allow", "to", "save", "set", "of", "document", "under", "admin" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/DBClosure.java#L125-L139
134,841
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/DBClosure.java
DBClosure.sudoSave
public static void sudoSave(final ODocumentWrapper... dws) { if(dws==null || dws.length==0) return; new DBClosure<Boolean>() { @Override protected Boolean execute(ODatabaseDocument db) { db.begin(); for (ODocumentWrapper dw : dws) { dw.save(); } db.commit(); return true; } }.execute(); }
java
public static void sudoSave(final ODocumentWrapper... dws) { if(dws==null || dws.length==0) return; new DBClosure<Boolean>() { @Override protected Boolean execute(ODatabaseDocument db) { db.begin(); for (ODocumentWrapper dw : dws) { dw.save(); } db.commit(); return true; } }.execute(); }
[ "public", "static", "void", "sudoSave", "(", "final", "ODocumentWrapper", "...", "dws", ")", "{", "if", "(", "dws", "==", "null", "||", "dws", ".", "length", "==", "0", ")", "return", ";", "new", "DBClosure", "<", "Boolean", ">", "(", ")", "{", "@", ...
Allow to save set of document wrappers under admin @param dws set of document to be saved
[ "Allow", "to", "save", "set", "of", "document", "wrappers", "under", "admin" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/utils/DBClosure.java#L145-L159
134,842
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/AbstractNamingModel.java
AbstractNamingModel.buitify
public static String buitify(String string) { char[] chars = string.toCharArray(); StringBuilder sb = new StringBuilder(); int lastApplied=0; for(int i=0; i<chars.length;i++) { char pCh = i>0?chars[i-1]:0; char ch = chars[i]; if(ch=='_' || ch=='-' || Character.isWhitespace(ch)) { sb.append(chars, lastApplied, i-lastApplied); lastApplied=i+1; } else if(i==0 && Character.isLowerCase(ch)) { sb.append(Character.toUpperCase(ch)); lastApplied=i+1; } else if(i>0 && Character.isUpperCase(ch) && !(Character.isWhitespace(pCh) || pCh=='_' || pCh=='-')&& !Character.isUpperCase(pCh)) { sb.append(chars, lastApplied, i-lastApplied).append(' ').append(ch); lastApplied=i+1; } else if(i>0 && Character.isLowerCase(ch) && (Character.isWhitespace(pCh) || pCh=='_' || pCh=='-')) { sb.append(chars, lastApplied, i-lastApplied); if(sb.length()>0) sb.append(' '); sb.append(Character.toUpperCase(ch)); lastApplied=i+1; } } sb.append(chars, lastApplied, chars.length-lastApplied); return sb.toString(); }
java
public static String buitify(String string) { char[] chars = string.toCharArray(); StringBuilder sb = new StringBuilder(); int lastApplied=0; for(int i=0; i<chars.length;i++) { char pCh = i>0?chars[i-1]:0; char ch = chars[i]; if(ch=='_' || ch=='-' || Character.isWhitespace(ch)) { sb.append(chars, lastApplied, i-lastApplied); lastApplied=i+1; } else if(i==0 && Character.isLowerCase(ch)) { sb.append(Character.toUpperCase(ch)); lastApplied=i+1; } else if(i>0 && Character.isUpperCase(ch) && !(Character.isWhitespace(pCh) || pCh=='_' || pCh=='-')&& !Character.isUpperCase(pCh)) { sb.append(chars, lastApplied, i-lastApplied).append(' ').append(ch); lastApplied=i+1; } else if(i>0 && Character.isLowerCase(ch) && (Character.isWhitespace(pCh) || pCh=='_' || pCh=='-')) { sb.append(chars, lastApplied, i-lastApplied); if(sb.length()>0) sb.append(' '); sb.append(Character.toUpperCase(ch)); lastApplied=i+1; } } sb.append(chars, lastApplied, chars.length-lastApplied); return sb.toString(); }
[ "public", "static", "String", "buitify", "(", "String", "string", ")", "{", "char", "[", "]", "chars", "=", "string", ".", "toCharArray", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "int", "lastApplied", "=", "0", ...
Utility method to make source string more human readable @param string source string @return buitified source string
[ "Utility", "method", "to", "make", "source", "string", "more", "human", "readable" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/AbstractNamingModel.java#L94-L128
134,843
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/proto/AbstractPrototyper.java
AbstractPrototyper.getDefaultValue
protected Object getDefaultValue(String propName, Class<?> returnType) { Object ret = null; if(returnType.isPrimitive()) { if(returnType.equals(boolean.class)) { return false; } else if(returnType.equals(char.class)) { return '\0'; } else { try { Class<?> wrapperClass = Primitives.wrap(returnType); return wrapperClass.getMethod("valueOf", String.class).invoke(null, "0"); } catch (Throwable e) { throw new WicketRuntimeException("Can't create default value for '"+propName+"' which should have type '"+returnType.getName()+"'"); } } } return ret; }
java
protected Object getDefaultValue(String propName, Class<?> returnType) { Object ret = null; if(returnType.isPrimitive()) { if(returnType.equals(boolean.class)) { return false; } else if(returnType.equals(char.class)) { return '\0'; } else { try { Class<?> wrapperClass = Primitives.wrap(returnType); return wrapperClass.getMethod("valueOf", String.class).invoke(null, "0"); } catch (Throwable e) { throw new WicketRuntimeException("Can't create default value for '"+propName+"' which should have type '"+returnType.getName()+"'"); } } } return ret; }
[ "protected", "Object", "getDefaultValue", "(", "String", "propName", ",", "Class", "<", "?", ">", "returnType", ")", "{", "Object", "ret", "=", "null", ";", "if", "(", "returnType", ".", "isPrimitive", "(", ")", ")", "{", "if", "(", "returnType", ".", ...
Method for obtaining default value of required property @param propName name of a property @param returnType type of a property @return default value for particular property
[ "Method", "for", "obtaining", "default", "value", "of", "required", "property" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/proto/AbstractPrototyper.java#L265-L291
134,844
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/security/OSecurityHelper.java
OSecurityHelper.isAllowed
public static boolean isAllowed(ORule.ResourceGeneric resource, String specific, OrientPermission... permissions) { return OrientDbWebSession.get().getEffectiveUser() .checkIfAllowed(resource, specific, OrientPermission.combinedPermission(permissions))!=null; }
java
public static boolean isAllowed(ORule.ResourceGeneric resource, String specific, OrientPermission... permissions) { return OrientDbWebSession.get().getEffectiveUser() .checkIfAllowed(resource, specific, OrientPermission.combinedPermission(permissions))!=null; }
[ "public", "static", "boolean", "isAllowed", "(", "ORule", ".", "ResourceGeneric", "resource", ",", "String", "specific", ",", "OrientPermission", "...", "permissions", ")", "{", "return", "OrientDbWebSession", ".", "get", "(", ")", ".", "getEffectiveUser", "(", ...
Check that all required permissions present for specified resource and specific @param resource specific resource to secure @param specific specific resource to secure @param permissions {@link OrientPermission}s to check @return true of require resource if allowed for current user
[ "Check", "that", "all", "required", "permissions", "present", "for", "specified", "resource", "and", "specific" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/security/OSecurityHelper.java#L213-L217
134,845
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/security/OSecurityHelper.java
OSecurityHelper.getResourceSpecific
public static String getResourceSpecific(String name) { ORule.ResourceGeneric generic = getResourceGeneric(name); String specific = generic!=null?Strings.afterFirst(name, '.'):name; return Strings.isEmpty(specific)?null:specific; }
java
public static String getResourceSpecific(String name) { ORule.ResourceGeneric generic = getResourceGeneric(name); String specific = generic!=null?Strings.afterFirst(name, '.'):name; return Strings.isEmpty(specific)?null:specific; }
[ "public", "static", "String", "getResourceSpecific", "(", "String", "name", ")", "{", "ORule", ".", "ResourceGeneric", "generic", "=", "getResourceGeneric", "(", "name", ")", ";", "String", "specific", "=", "generic", "!=", "null", "?", "Strings", ".", "afterF...
Extract specific from resource string @param name name to transform @return specific resource or null
[ "Extract", "specific", "from", "resource", "string" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/security/OSecurityHelper.java#L270-L275
134,846
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/OrientDbSettings.java
OrientDbSettings.resolveOrientDBRestApiUrl
public String resolveOrientDBRestApiUrl() { OrientDbWebApplication app = OrientDbWebApplication.get(); OServer server = app.getServer(); if(server!=null) { OServerNetworkListener http = server.getListenerByProtocol(ONetworkProtocolHttpAbstract.class); if(http!=null) { return "http://"+http.getListeningAddress(true); } } return null; }
java
public String resolveOrientDBRestApiUrl() { OrientDbWebApplication app = OrientDbWebApplication.get(); OServer server = app.getServer(); if(server!=null) { OServerNetworkListener http = server.getListenerByProtocol(ONetworkProtocolHttpAbstract.class); if(http!=null) { return "http://"+http.getListeningAddress(true); } } return null; }
[ "public", "String", "resolveOrientDBRestApiUrl", "(", ")", "{", "OrientDbWebApplication", "app", "=", "OrientDbWebApplication", ".", "get", "(", ")", ";", "OServer", "server", "=", "app", ".", "getServer", "(", ")", ";", "if", "(", "server", "!=", "null", ")...
Resolve OrientDB REST API URL to be used for OrientDb REST bridge @return OrientDB REST API URL
[ "Resolve", "OrientDB", "REST", "API", "URL", "to", "be", "used", "for", "OrientDb", "REST", "bridge" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/OrientDbSettings.java#L138-L151
134,847
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/AbstractContentAwareTransactionRequestCycleListener.java
AbstractContentAwareTransactionRequestCycleListener.isInProgress
public boolean isInProgress(RequestCycle cycle) { Boolean inProgress = cycle.getMetaData(IN_PROGRESS_KEY); return inProgress!=null?inProgress:false; }
java
public boolean isInProgress(RequestCycle cycle) { Boolean inProgress = cycle.getMetaData(IN_PROGRESS_KEY); return inProgress!=null?inProgress:false; }
[ "public", "boolean", "isInProgress", "(", "RequestCycle", "cycle", ")", "{", "Boolean", "inProgress", "=", "cycle", ".", "getMetaData", "(", "IN_PROGRESS_KEY", ")", ";", "return", "inProgress", "!=", "null", "?", "inProgress", ":", "false", ";", "}" ]
Is current 'transaction' in progress? @param cycle {@link RequestCycle} @return true - if we are within a transaction, false - if not
[ "Is", "current", "transaction", "in", "progress?" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/AbstractContentAwareTransactionRequestCycleListener.java#L40-L44
134,848
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/OQueryModel.java
OQueryModel.probeOClass
public OClass probeOClass(int probeLimit) { Iterator<ODocument> it = iterator(0, probeLimit, null); return OSchemaUtils.probeOClass(it, probeLimit); }
java
public OClass probeOClass(int probeLimit) { Iterator<ODocument> it = iterator(0, probeLimit, null); return OSchemaUtils.probeOClass(it, probeLimit); }
[ "public", "OClass", "probeOClass", "(", "int", "probeLimit", ")", "{", "Iterator", "<", "ODocument", ">", "it", "=", "iterator", "(", "0", ",", "probeLimit", ",", "null", ")", ";", "return", "OSchemaUtils", ".", "probeOClass", "(", "it", ",", "probeLimit",...
Probe the dataset and returns upper OClass for sample @param probeLimit size of a probe @return OClass or null if there is no common parent for {@link ODocument}'s in a sample
[ "Probe", "the", "dataset", "and", "returns", "upper", "OClass", "for", "sample" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/OQueryModel.java#L234-L237
134,849
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/OQueryModel.java
OQueryModel.size
public long size() { if(size==null) { ODatabaseDocument db = OrientDbWebSession.get().getDatabase(); OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(queryManager.getCountSql()); List<ODocument> ret = db.query(enhanceContextByVariables(query), prepareParams()); if(ret!=null && ret.size()>0) { Number sizeNumber = ret.get(0).field("count"); size = sizeNumber!=null?sizeNumber.longValue():0; } else { size = 0L; } } return size; }
java
public long size() { if(size==null) { ODatabaseDocument db = OrientDbWebSession.get().getDatabase(); OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<ODocument>(queryManager.getCountSql()); List<ODocument> ret = db.query(enhanceContextByVariables(query), prepareParams()); if(ret!=null && ret.size()>0) { Number sizeNumber = ret.get(0).field("count"); size = sizeNumber!=null?sizeNumber.longValue():0; } else { size = 0L; } } return size; }
[ "public", "long", "size", "(", ")", "{", "if", "(", "size", "==", "null", ")", "{", "ODatabaseDocument", "db", "=", "OrientDbWebSession", ".", "get", "(", ")", ".", "getDatabase", "(", ")", ";", "OSQLSynchQuery", "<", "ODocument", ">", "query", "=", "n...
Get the size of the data @return results size
[ "Get", "the", "size", "of", "the", "data" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/OQueryModel.java#L248-L266
134,850
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/OQueryModel.java
OQueryModel.setSort
public OQueryModel<K> setSort(String sortableParameter, SortOrder order) { setSortableParameter(sortableParameter); setAscending(SortOrder.ASCENDING.equals(order)); return this; }
java
public OQueryModel<K> setSort(String sortableParameter, SortOrder order) { setSortableParameter(sortableParameter); setAscending(SortOrder.ASCENDING.equals(order)); return this; }
[ "public", "OQueryModel", "<", "K", ">", "setSort", "(", "String", "sortableParameter", ",", "SortOrder", "order", ")", "{", "setSortableParameter", "(", "sortableParameter", ")", ";", "setAscending", "(", "SortOrder", ".", "ASCENDING", ".", "equals", "(", "order...
Set sorting configration @param sortableParameter sortable parameter to sort on @param order {@link SortOrder} to sort on @return this {@link OQueryModel}
[ "Set", "sorting", "configration" ]
eb1d94f00a6bff9e266c5c032baa6043afc1db92
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/model/OQueryModel.java#L325-L330
134,851
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruUtil.java
SailthruUtil.md5
public static String md5(String data) { try { return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return DigestUtils.md5Hex(data.toString()); } }
java
public static String md5(String data) { try { return DigestUtils.md5Hex(data.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { return DigestUtils.md5Hex(data.toString()); } }
[ "public", "static", "String", "md5", "(", "String", "data", ")", "{", "try", "{", "return", "DigestUtils", ".", "md5Hex", "(", "data", ".", "toString", "(", ")", ".", "getBytes", "(", "\"UTF-8\"", ")", ")", ";", "}", "catch", "(", "UnsupportedEncodingExc...
generates MD5 Hash @param data parameter data @return MD5 hashed string
[ "generates", "MD5", "Hash" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruUtil.java#L24-L31
134,852
sailthru/sailthru-java-client
src/main/com/sailthru/client/SailthruUtil.java
SailthruUtil.arrayListToCSV
public static String arrayListToCSV(List<String> list) { StringBuilder csv = new StringBuilder(); for (String str : list) { csv.append(str); csv.append(","); } int lastIndex = csv.length() - 1; char last = csv.charAt(lastIndex); if (last == ',') { return csv.substring(0, lastIndex); } return csv.toString(); }
java
public static String arrayListToCSV(List<String> list) { StringBuilder csv = new StringBuilder(); for (String str : list) { csv.append(str); csv.append(","); } int lastIndex = csv.length() - 1; char last = csv.charAt(lastIndex); if (last == ',') { return csv.substring(0, lastIndex); } return csv.toString(); }
[ "public", "static", "String", "arrayListToCSV", "(", "List", "<", "String", ">", "list", ")", "{", "StringBuilder", "csv", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "str", ":", "list", ")", "{", "csv", ".", "append", "(", "str",...
Converts String ArrayList to CSV string @param list List of String to create a CSV string @return CSV string
[ "Converts", "String", "ArrayList", "to", "CSV", "string" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruUtil.java#L38-L50
134,853
sailthru/sailthru-java-client
src/main/com/sailthru/client/AbstractSailthruClient.java
AbstractSailthruClient.getScheme
protected Scheme getScheme() { String scheme; try { URI uri = new URI(this.apiUrl); scheme = uri.getScheme(); } catch (URISyntaxException e) { scheme = "http"; } if (scheme.equals("https")) { return new Scheme(scheme, DEFAULT_HTTPS_PORT, SSLSocketFactory.getSocketFactory()); } else { return new Scheme(scheme, DEFAULT_HTTP_PORT, PlainSocketFactory.getSocketFactory()); } }
java
protected Scheme getScheme() { String scheme; try { URI uri = new URI(this.apiUrl); scheme = uri.getScheme(); } catch (URISyntaxException e) { scheme = "http"; } if (scheme.equals("https")) { return new Scheme(scheme, DEFAULT_HTTPS_PORT, SSLSocketFactory.getSocketFactory()); } else { return new Scheme(scheme, DEFAULT_HTTP_PORT, PlainSocketFactory.getSocketFactory()); } }
[ "protected", "Scheme", "getScheme", "(", ")", "{", "String", "scheme", ";", "try", "{", "URI", "uri", "=", "new", "URI", "(", "this", ".", "apiUrl", ")", ";", "scheme", "=", "uri", ".", "getScheme", "(", ")", ";", "}", "catch", "(", "URISyntaxExcepti...
Get Scheme Object
[ "Get", "Scheme", "Object" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/AbstractSailthruClient.java#L129-L142
134,854
sailthru/sailthru-java-client
src/main/com/sailthru/client/AbstractSailthruClient.java
AbstractSailthruClient.httpRequest
protected Object httpRequest(ApiAction action, HttpRequestMethod method, Map<String, Object> data) throws IOException { String url = this.apiUrl + "/" + action.toString().toLowerCase(); Type type = new TypeToken<Map<String, Object>>() {}.getType(); String json = GSON.toJson(data, type); Map<String, String> params = buildPayload(json); Object response = httpClient.executeHttpRequest(url, method, params, handler, customHeaders); recordRateLimitInfo(action, method, response); return response; }
java
protected Object httpRequest(ApiAction action, HttpRequestMethod method, Map<String, Object> data) throws IOException { String url = this.apiUrl + "/" + action.toString().toLowerCase(); Type type = new TypeToken<Map<String, Object>>() {}.getType(); String json = GSON.toJson(data, type); Map<String, String> params = buildPayload(json); Object response = httpClient.executeHttpRequest(url, method, params, handler, customHeaders); recordRateLimitInfo(action, method, response); return response; }
[ "protected", "Object", "httpRequest", "(", "ApiAction", "action", ",", "HttpRequestMethod", "method", ",", "Map", "<", "String", ",", "Object", ">", "data", ")", "throws", "IOException", "{", "String", "url", "=", "this", ".", "apiUrl", "+", "\"/\"", "+", ...
Make Http request to Sailthru API for given resource with given method and data @param action @param method @param data parameter data @return Object @throws IOException
[ "Make", "Http", "request", "to", "Sailthru", "API", "for", "given", "resource", "with", "given", "method", "and", "data" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/AbstractSailthruClient.java#L153-L161
134,855
sailthru/sailthru-java-client
src/main/com/sailthru/client/AbstractSailthruClient.java
AbstractSailthruClient.httpRequest
protected Object httpRequest(HttpRequestMethod method, ApiParams apiParams) throws IOException { ApiAction action = apiParams.getApiCall(); String url = apiUrl + "/" + action.toString().toLowerCase(); String json = GSON.toJson(apiParams, apiParams.getType()); Map<String, String> params = buildPayload(json); Object response = httpClient.executeHttpRequest(url, method, params, handler, customHeaders); recordRateLimitInfo(action, method, response); return response; }
java
protected Object httpRequest(HttpRequestMethod method, ApiParams apiParams) throws IOException { ApiAction action = apiParams.getApiCall(); String url = apiUrl + "/" + action.toString().toLowerCase(); String json = GSON.toJson(apiParams, apiParams.getType()); Map<String, String> params = buildPayload(json); Object response = httpClient.executeHttpRequest(url, method, params, handler, customHeaders); recordRateLimitInfo(action, method, response); return response; }
[ "protected", "Object", "httpRequest", "(", "HttpRequestMethod", "method", ",", "ApiParams", "apiParams", ")", "throws", "IOException", "{", "ApiAction", "action", "=", "apiParams", ".", "getApiCall", "(", ")", ";", "String", "url", "=", "apiUrl", "+", "\"/\"", ...
Make HTTP Request to Sailthru API but with Api Params rather than generalized Map, this is recommended way to make request if data structure is complex @param method HTTP method @param apiParams @return Object @throws IOException
[ "Make", "HTTP", "Request", "to", "Sailthru", "API", "but", "with", "Api", "Params", "rather", "than", "generalized", "Map", "this", "is", "recommended", "way", "to", "make", "request", "if", "data", "structure", "is", "complex" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/AbstractSailthruClient.java#L170-L178
134,856
sailthru/sailthru-java-client
src/main/com/sailthru/client/AbstractSailthruClient.java
AbstractSailthruClient.buildPayload
private Map<String, String> buildPayload(String jsonPayload) { Map<String, String> params = new HashMap<String, String>(); params.put("api_key", apiKey); params.put("format", handler.getSailthruResponseHandler().getFormat()); params.put("json", jsonPayload); params.put("sig", getSignatureHash(params)); return params; }
java
private Map<String, String> buildPayload(String jsonPayload) { Map<String, String> params = new HashMap<String, String>(); params.put("api_key", apiKey); params.put("format", handler.getSailthruResponseHandler().getFormat()); params.put("json", jsonPayload); params.put("sig", getSignatureHash(params)); return params; }
[ "private", "Map", "<", "String", ",", "String", ">", "buildPayload", "(", "String", "jsonPayload", ")", "{", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "params", ".", "...
Build HTTP Request Payload @param jsonPayload JSON payload @return Map Object
[ "Build", "HTTP", "Request", "Payload" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/AbstractSailthruClient.java#L215-L222
134,857
sailthru/sailthru-java-client
src/main/com/sailthru/client/AbstractSailthruClient.java
AbstractSailthruClient.getSignatureHash
protected String getSignatureHash(Map<String, String> parameters) { List<String> values = new ArrayList<String>(); StringBuilder data = new StringBuilder(); data.append(this.apiSecret); for (Entry<String, String> entry : parameters.entrySet()) { values.add(entry.getValue()); } Collections.sort(values); for( String value:values ) { data.append(value); } return SailthruUtil.md5(data.toString()); }
java
protected String getSignatureHash(Map<String, String> parameters) { List<String> values = new ArrayList<String>(); StringBuilder data = new StringBuilder(); data.append(this.apiSecret); for (Entry<String, String> entry : parameters.entrySet()) { values.add(entry.getValue()); } Collections.sort(values); for( String value:values ) { data.append(value); } return SailthruUtil.md5(data.toString()); }
[ "protected", "String", "getSignatureHash", "(", "Map", "<", "String", ",", "String", ">", "parameters", ")", "{", "List", "<", "String", ">", "values", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "StringBuilder", "data", "=", "new", "Stri...
Get Signature Hash from given Map
[ "Get", "Signature", "Hash", "from", "given", "Map" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/AbstractSailthruClient.java#L227-L243
134,858
sailthru/sailthru-java-client
src/main/com/sailthru/client/AbstractSailthruClient.java
AbstractSailthruClient.apiGet
public JsonResponse apiGet(ApiAction action, Map<String, Object> data) throws IOException { return httpRequestJson(action, HttpRequestMethod.GET, data); }
java
public JsonResponse apiGet(ApiAction action, Map<String, Object> data) throws IOException { return httpRequestJson(action, HttpRequestMethod.GET, data); }
[ "public", "JsonResponse", "apiGet", "(", "ApiAction", "action", ",", "Map", "<", "String", ",", "Object", ">", "data", ")", "throws", "IOException", "{", "return", "httpRequestJson", "(", "action", ",", "HttpRequestMethod", ".", "GET", ",", "data", ")", ";",...
HTTP GET Request with Map @param action API action @param data Parameter data @throws IOException
[ "HTTP", "GET", "Request", "with", "Map" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/AbstractSailthruClient.java#L252-L254
134,859
sailthru/sailthru-java-client
src/main/com/sailthru/client/AbstractSailthruClient.java
AbstractSailthruClient.apiPost
public JsonResponse apiPost(ApiAction action, Map<String, Object> data) throws IOException { return httpRequestJson(action, HttpRequestMethod.POST, data); }
java
public JsonResponse apiPost(ApiAction action, Map<String, Object> data) throws IOException { return httpRequestJson(action, HttpRequestMethod.POST, data); }
[ "public", "JsonResponse", "apiPost", "(", "ApiAction", "action", ",", "Map", "<", "String", ",", "Object", ">", "data", ")", "throws", "IOException", "{", "return", "httpRequestJson", "(", "action", ",", "HttpRequestMethod", ".", "POST", ",", "data", ")", ";...
HTTP POST Request with Map @param action @param data @throws IOException
[ "HTTP", "POST", "Request", "with", "Map" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/AbstractSailthruClient.java#L271-L273
134,860
sailthru/sailthru-java-client
src/main/com/sailthru/client/AbstractSailthruClient.java
AbstractSailthruClient.apiPost
public JsonResponse apiPost(ApiParams data, ApiFileParams fileParams) throws IOException { return httpRequestJson(HttpRequestMethod.POST, data, fileParams); }
java
public JsonResponse apiPost(ApiParams data, ApiFileParams fileParams) throws IOException { return httpRequestJson(HttpRequestMethod.POST, data, fileParams); }
[ "public", "JsonResponse", "apiPost", "(", "ApiParams", "data", ",", "ApiFileParams", "fileParams", ")", "throws", "IOException", "{", "return", "httpRequestJson", "(", "HttpRequestMethod", ".", "POST", ",", "data", ",", "fileParams", ")", ";", "}" ]
HTTP POST Request with Interface implementation of ApiParams and ApiFileParams @param data @param fileParams @throws IOException
[ "HTTP", "POST", "Request", "with", "Interface", "implementation", "of", "ApiParams", "and", "ApiFileParams" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/AbstractSailthruClient.java#L291-L293
134,861
sailthru/sailthru-java-client
src/main/com/sailthru/client/AbstractSailthruClient.java
AbstractSailthruClient.apiDelete
public JsonResponse apiDelete(ApiAction action, Map<String, Object> data) throws IOException { return httpRequestJson(action, HttpRequestMethod.DELETE, data); }
java
public JsonResponse apiDelete(ApiAction action, Map<String, Object> data) throws IOException { return httpRequestJson(action, HttpRequestMethod.DELETE, data); }
[ "public", "JsonResponse", "apiDelete", "(", "ApiAction", "action", ",", "Map", "<", "String", ",", "Object", ">", "data", ")", "throws", "IOException", "{", "return", "httpRequestJson", "(", "action", ",", "HttpRequestMethod", ".", "DELETE", ",", "data", ")", ...
HTTP DELETE Request @param action @param data @throws IOException
[ "HTTP", "DELETE", "Request" ]
62b491f6a39b41b836bfc021779200d29b6d2069
https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/AbstractSailthruClient.java#L302-L304
134,862
GCRC/nunaliit
nunaliit2-dbSec/src/main/java/ca/carleton/gcrc/dbSec/impl/ColumnDataUtils.java
ColumnDataUtils.obtainNextIncrementInteger
static public int obtainNextIncrementInteger(Connection connection, ColumnData autoIncrementIntegerColumn) throws Exception { try { String sqlQuery = "SELECT nextval(?);"; // Create SQL command PreparedStatement pstmt = null; { pstmt = connection.prepareStatement(sqlQuery); // Populate prepared statement pstmt.setString(1, autoIncrementIntegerColumn.getAutoIncrementSequence()); } if( pstmt.execute() ) { ResultSet rs = pstmt.getResultSet(); if( rs.next() ) { int nextValue = rs.getInt(1); return nextValue; } else { throw new Exception("Empty result returned by SQL: "+sqlQuery); } } else { throw new Exception("No result returned by SQL: "+sqlQuery); } } catch( Exception e ) { throw new Exception("Error while attempting to get a auto increment integer value for: "+ autoIncrementIntegerColumn.getColumnName()+ " ("+autoIncrementIntegerColumn.getAutoIncrementSequence()+")",e); } }
java
static public int obtainNextIncrementInteger(Connection connection, ColumnData autoIncrementIntegerColumn) throws Exception { try { String sqlQuery = "SELECT nextval(?);"; // Create SQL command PreparedStatement pstmt = null; { pstmt = connection.prepareStatement(sqlQuery); // Populate prepared statement pstmt.setString(1, autoIncrementIntegerColumn.getAutoIncrementSequence()); } if( pstmt.execute() ) { ResultSet rs = pstmt.getResultSet(); if( rs.next() ) { int nextValue = rs.getInt(1); return nextValue; } else { throw new Exception("Empty result returned by SQL: "+sqlQuery); } } else { throw new Exception("No result returned by SQL: "+sqlQuery); } } catch( Exception e ) { throw new Exception("Error while attempting to get a auto increment integer value for: "+ autoIncrementIntegerColumn.getColumnName()+ " ("+autoIncrementIntegerColumn.getAutoIncrementSequence()+")",e); } }
[ "static", "public", "int", "obtainNextIncrementInteger", "(", "Connection", "connection", ",", "ColumnData", "autoIncrementIntegerColumn", ")", "throws", "Exception", "{", "try", "{", "String", "sqlQuery", "=", "\"SELECT nextval(?);\"", ";", "// Create SQL command", "Prep...
Performs a database query to find the next integer in the sequence reserved for the given column. @param autoIncrementIntegerColumn Column data where a new integer is required @return The next integer in sequence @throws Exception
[ "Performs", "a", "database", "query", "to", "find", "the", "next", "integer", "in", "the", "sequence", "reserved", "for", "the", "given", "column", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-dbSec/src/main/java/ca/carleton/gcrc/dbSec/impl/ColumnDataUtils.java#L355-L386
134,863
GCRC/nunaliit
nunaliit2-json/src/main/java/org/json/XMLTokener.java
XMLTokener.unescapeEntity
static String unescapeEntity(String e) { // validate if (e == null || e.isEmpty()) { return ""; } // if our entity is an encoded unicode point, parse it. if (e.charAt(0) == '#') { int cp; if (e.charAt(1) == 'x') { // hex encoded unicode cp = Integer.parseInt(e.substring(2), 16); } else { // decimal encoded unicode cp = Integer.parseInt(e.substring(1)); } return new String(new int[] {cp},0,1); } Character knownEntity = entity.get(e); if(knownEntity==null) { // we don't know the entity so keep it encoded return '&' + e + ';'; } return knownEntity.toString(); }
java
static String unescapeEntity(String e) { // validate if (e == null || e.isEmpty()) { return ""; } // if our entity is an encoded unicode point, parse it. if (e.charAt(0) == '#') { int cp; if (e.charAt(1) == 'x') { // hex encoded unicode cp = Integer.parseInt(e.substring(2), 16); } else { // decimal encoded unicode cp = Integer.parseInt(e.substring(1)); } return new String(new int[] {cp},0,1); } Character knownEntity = entity.get(e); if(knownEntity==null) { // we don't know the entity so keep it encoded return '&' + e + ';'; } return knownEntity.toString(); }
[ "static", "String", "unescapeEntity", "(", "String", "e", ")", "{", "// validate", "if", "(", "e", "==", "null", "||", "e", ".", "isEmpty", "(", ")", ")", "{", "return", "\"\"", ";", "}", "// if our entity is an encoded unicode point, parse it.", "if", "(", ...
Unescapes an XML entity encoding; @param e entity (only the actual entity value, not the preceding & or ending ; @return
[ "Unescapes", "an", "XML", "entity", "encoding", ";" ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-json/src/main/java/org/json/XMLTokener.java#L159-L182
134,864
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/client/impl/CouchDbChangeMonitorThread.java
CouchDbChangeMonitorThread.convertLastSeqObj
private String convertLastSeqObj(Object lastSeqObj) throws Exception { if( null == lastSeqObj ) { return null; } else if( lastSeqObj instanceof String ) { return (String)lastSeqObj; } else if( lastSeqObj instanceof Number ) { // Convert to string return "" + lastSeqObj; } else { throw new Exception("Do not know how to handle parameter 'last_seq' in change feed: "+lastSeqObj.getClass()); } }
java
private String convertLastSeqObj(Object lastSeqObj) throws Exception { if( null == lastSeqObj ) { return null; } else if( lastSeqObj instanceof String ) { return (String)lastSeqObj; } else if( lastSeqObj instanceof Number ) { // Convert to string return "" + lastSeqObj; } else { throw new Exception("Do not know how to handle parameter 'last_seq' in change feed: "+lastSeqObj.getClass()); } }
[ "private", "String", "convertLastSeqObj", "(", "Object", "lastSeqObj", ")", "throws", "Exception", "{", "if", "(", "null", "==", "lastSeqObj", ")", "{", "return", "null", ";", "}", "else", "if", "(", "lastSeqObj", "instanceof", "String", ")", "{", "return", ...
Converts the object "last_seq" found in the change feed to a String. In CouchDB 1.x, last_seq is an integer. In CouchDB 2.x, last_seq is a string. @param lastSeqObj Object retrieved from the change feed @return A string representing the object @throws Exception
[ "Converts", "the", "object", "last_seq", "found", "in", "the", "change", "feed", "to", "a", "String", ".", "In", "CouchDB", "1", ".", "x", "last_seq", "is", "an", "integer", ".", "In", "CouchDB", "2", ".", "x", "last_seq", "is", "a", "string", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/client/impl/CouchDbChangeMonitorThread.java#L180-L191
134,865
GCRC/nunaliit
nunaliit2-couch-onUpload/src/main/java/ca/carleton/gcrc/couch/onUpload/conversion/AttachmentDescriptor.java
AttachmentDescriptor.renameAttachmentTo
public void renameAttachmentTo(String newAttachmentName) throws Exception { JSONObject doc = documentDescriptor.getJson(); JSONObject _attachments = doc.optJSONObject("_attachments"); JSONObject nunaliit_attachments = doc.getJSONObject(UploadConstants.KEY_DOC_ATTACHMENTS); JSONObject files = nunaliit_attachments.getJSONObject("files"); // Verify no collision within nunaliit_attachments.files { Object obj = files.opt(newAttachmentName); if( null != obj ){ throw new Exception("Can not rename attachment because of name collision"); } } // Verify no collision within _attachments if( null != _attachments ){ Object obj = _attachments.opt(newAttachmentName); if( null != obj ){ throw new Exception("Can not rename attachment because of name collision"); } } // Not allowed to move a stub if( null != _attachments ){ JSONObject att = _attachments.optJSONObject(attName); if( null != att ){ throw new Exception("Can not rename attachment descriptor because file is already attached"); } } // Move descriptor to new name String oldAttachmentName = attName; JSONObject descriptor = files.getJSONObject(oldAttachmentName); files.remove(oldAttachmentName); files.put(newAttachmentName, descriptor); attName = newAttachmentName; setStringAttribute(UploadConstants.ATTACHMENT_NAME_KEY,newAttachmentName); // Loop through all attachment descriptors, updating "source", "thumbnail" // and "original" attributes { Iterator<?> it = files.keys(); while( it.hasNext() ){ Object objKey = it.next(); if( objKey instanceof String ){ String key = (String)objKey; JSONObject att = files.getJSONObject(key); { String value = att.optString("source", null); if( oldAttachmentName.equals(value) ){ att.put("source", newAttachmentName); } } { String value = att.optString("thumbnail", null); if( oldAttachmentName.equals(value) ){ att.put("thumbnail", newAttachmentName); } } { String value = att.optString("originalAttachment", null); if( oldAttachmentName.equals(value) ){ att.put("original", newAttachmentName); } } } } } }
java
public void renameAttachmentTo(String newAttachmentName) throws Exception { JSONObject doc = documentDescriptor.getJson(); JSONObject _attachments = doc.optJSONObject("_attachments"); JSONObject nunaliit_attachments = doc.getJSONObject(UploadConstants.KEY_DOC_ATTACHMENTS); JSONObject files = nunaliit_attachments.getJSONObject("files"); // Verify no collision within nunaliit_attachments.files { Object obj = files.opt(newAttachmentName); if( null != obj ){ throw new Exception("Can not rename attachment because of name collision"); } } // Verify no collision within _attachments if( null != _attachments ){ Object obj = _attachments.opt(newAttachmentName); if( null != obj ){ throw new Exception("Can not rename attachment because of name collision"); } } // Not allowed to move a stub if( null != _attachments ){ JSONObject att = _attachments.optJSONObject(attName); if( null != att ){ throw new Exception("Can not rename attachment descriptor because file is already attached"); } } // Move descriptor to new name String oldAttachmentName = attName; JSONObject descriptor = files.getJSONObject(oldAttachmentName); files.remove(oldAttachmentName); files.put(newAttachmentName, descriptor); attName = newAttachmentName; setStringAttribute(UploadConstants.ATTACHMENT_NAME_KEY,newAttachmentName); // Loop through all attachment descriptors, updating "source", "thumbnail" // and "original" attributes { Iterator<?> it = files.keys(); while( it.hasNext() ){ Object objKey = it.next(); if( objKey instanceof String ){ String key = (String)objKey; JSONObject att = files.getJSONObject(key); { String value = att.optString("source", null); if( oldAttachmentName.equals(value) ){ att.put("source", newAttachmentName); } } { String value = att.optString("thumbnail", null); if( oldAttachmentName.equals(value) ){ att.put("thumbnail", newAttachmentName); } } { String value = att.optString("originalAttachment", null); if( oldAttachmentName.equals(value) ){ att.put("original", newAttachmentName); } } } } } }
[ "public", "void", "renameAttachmentTo", "(", "String", "newAttachmentName", ")", "throws", "Exception", "{", "JSONObject", "doc", "=", "documentDescriptor", ".", "getJson", "(", ")", ";", "JSONObject", "_attachments", "=", "doc", ".", "optJSONObject", "(", "\"_att...
Renames an attachment. This ensures that there is no collision and that all references to this attachment are updated properly, within this document. @param newAttachmentName The new attachment name. @throws Exception
[ "Renames", "an", "attachment", ".", "This", "ensures", "that", "there", "is", "no", "collision", "and", "that", "all", "references", "to", "this", "attachment", "are", "updated", "properly", "within", "this", "document", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-onUpload/src/main/java/ca/carleton/gcrc/couch/onUpload/conversion/AttachmentDescriptor.java#L65-L136
134,866
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntryFile.java
FSEntryFile.getPositionedFile
static public FSEntry getPositionedFile(String path, File file) throws Exception { List<String> pathFrags = FSEntrySupport.interpretPath(path); // Start at leaf and work our way back int index = pathFrags.size() - 1; FSEntry root = new FSEntryFile(pathFrags.get(index), file); --index; while(index >= 0){ FSEntryVirtualDirectory parent = new FSEntryVirtualDirectory(pathFrags.get(index)); parent.addChildEntry(root); root = parent; --index; } return root; }
java
static public FSEntry getPositionedFile(String path, File file) throws Exception { List<String> pathFrags = FSEntrySupport.interpretPath(path); // Start at leaf and work our way back int index = pathFrags.size() - 1; FSEntry root = new FSEntryFile(pathFrags.get(index), file); --index; while(index >= 0){ FSEntryVirtualDirectory parent = new FSEntryVirtualDirectory(pathFrags.get(index)); parent.addChildEntry(root); root = parent; --index; } return root; }
[ "static", "public", "FSEntry", "getPositionedFile", "(", "String", "path", ",", "File", "file", ")", "throws", "Exception", "{", "List", "<", "String", ">", "pathFrags", "=", "FSEntrySupport", ".", "interpretPath", "(", "path", ")", ";", "// Start at leaf and wo...
Create a virtual tree hierarchy with a file supporting the leaf. @param path Position of the file in the hierarchy, including its name @param file The actual file, or directory , abcking the end leaf @return The FSEntry root for this hierarchy @throws Exception Invalid parameter
[ "Create", "a", "virtual", "tree", "hierarchy", "with", "a", "file", "supporting", "the", "leaf", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntryFile.java#L23-L39
134,867
GCRC/nunaliit
nunaliit2-search/src/main/java/ca/carleton/gcrc/search/Searches.java
Searches.computeSelectScore
private String computeSelectScore(List<String> searchFields) throws Exception { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); if( 0 == searchFields.size() ) { throw new Exception("Must supply at least one search field"); } else if( 1 == searchFields.size() ) { pw.print("coalesce(nullif(position(lower(?) IN lower("); pw.print(searchFields.get(0)); pw.print(")), 0), 9999)"); } else { int loop; for(loop=0; loop<searchFields.size()-1;++loop) { pw.print("least(coalesce(nullif(position(lower(?) IN lower("); pw.print(searchFields.get(loop)); pw.print(")), 0), 9999),"); } pw.print("coalesce(nullif(position(lower(?) IN lower("); pw.print(searchFields.get(loop)); pw.print(")), 0), 9999)"); for(loop=0; loop<searchFields.size()-1;++loop) { pw.print(")"); } } pw.flush(); return sw.toString(); }
java
private String computeSelectScore(List<String> searchFields) throws Exception { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); if( 0 == searchFields.size() ) { throw new Exception("Must supply at least one search field"); } else if( 1 == searchFields.size() ) { pw.print("coalesce(nullif(position(lower(?) IN lower("); pw.print(searchFields.get(0)); pw.print(")), 0), 9999)"); } else { int loop; for(loop=0; loop<searchFields.size()-1;++loop) { pw.print("least(coalesce(nullif(position(lower(?) IN lower("); pw.print(searchFields.get(loop)); pw.print(")), 0), 9999),"); } pw.print("coalesce(nullif(position(lower(?) IN lower("); pw.print(searchFields.get(loop)); pw.print(")), 0), 9999)"); for(loop=0; loop<searchFields.size()-1;++loop) { pw.print(")"); } } pw.flush(); return sw.toString(); }
[ "private", "String", "computeSelectScore", "(", "List", "<", "String", ">", "searchFields", ")", "throws", "Exception", "{", "StringWriter", "sw", "=", "new", "StringWriter", "(", ")", ";", "PrintWriter", "pw", "=", "new", "PrintWriter", "(", "sw", ")", ";",...
Create a SQL fragment that can be used to compute a score based on a search. For one search field: coalesce(nullif(position(lower(?) IN lower(X)), 0), 9999) for multiple fields: least(coalesce(nullif(position(lower(?) IN lower(X)), 0), 9999),...) @param searchFields Columns to search in column @return SQL fragment to select score @throws Exception
[ "Create", "a", "SQL", "fragment", "that", "can", "be", "used", "to", "compute", "a", "score", "based", "on", "a", "search", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-search/src/main/java/ca/carleton/gcrc/search/Searches.java#L419-L450
134,868
GCRC/nunaliit
nunaliit2-search/src/main/java/ca/carleton/gcrc/search/Searches.java
Searches.computeWhereFragment
private String computeWhereFragment(List<String> searchFields) throws Exception { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); boolean first = true; for(int loop=0; loop<searchFields.size(); ++loop) { if( first ) { first = false; pw.print(" WHERE "); } else { pw.print(" OR "); } pw.print("lower("); pw.print(searchFields.get(loop)); pw.print(") LIKE lower(?)"); } pw.flush(); return sw.toString(); }
java
private String computeWhereFragment(List<String> searchFields) throws Exception { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); boolean first = true; for(int loop=0; loop<searchFields.size(); ++loop) { if( first ) { first = false; pw.print(" WHERE "); } else { pw.print(" OR "); } pw.print("lower("); pw.print(searchFields.get(loop)); pw.print(") LIKE lower(?)"); } pw.flush(); return sw.toString(); }
[ "private", "String", "computeWhereFragment", "(", "List", "<", "String", ">", "searchFields", ")", "throws", "Exception", "{", "StringWriter", "sw", "=", "new", "StringWriter", "(", ")", ";", "PrintWriter", "pw", "=", "new", "PrintWriter", "(", "sw", ")", ";...
Given a number of search fields, compute the SQL fragment used to filter the searched rows WHERE lower(X) LIKE lower(?) OR lower(Y) LIKE lower(?)... @param searchFields Columns to search @return @throws Exception
[ "Given", "a", "number", "of", "search", "fields", "compute", "the", "SQL", "fragment", "used", "to", "filter", "the", "searched", "rows" ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-search/src/main/java/ca/carleton/gcrc/search/Searches.java#L463-L482
134,869
GCRC/nunaliit
nunaliit2-search/src/main/java/ca/carleton/gcrc/search/Searches.java
Searches.executeStatementToJson
private JSONArray executeStatementToJson( PreparedStatement stmt, List<SelectedColumn> selectFields) throws Exception { //logger.info("about to execute: " + stmt.toString()); if( stmt.execute() ) { // There's a ResultSet to be had ResultSet rs = stmt.getResultSet(); JSONArray array = new JSONArray(); try { Map<Integer,JSONObject> contributorMap = new HashMap<Integer,JSONObject>(); while (rs.next()) { JSONObject obj = new JSONObject(); int index = 1; for(int loop=0; loop<selectFields.size(); ++loop) { SelectedColumn selCol = selectFields.get(loop); //logger.info("field: " + selCol.getName() + " (" + selCol.getType() + ")"); if (! "contributor_id".equalsIgnoreCase(selCol.getName())) { if( SelectedColumn.Type.INTEGER == selCol.getType() ) { obj.put(selCol.getName(),rs.getInt(index)); ++index; } else if( SelectedColumn.Type.STRING == selCol.getType() ) { obj.put(selCol.getName(),rs.getString(index)); ++index; } else if ( SelectedColumn.Type.DATE == selCol.getType() ) { Date date = rs.getDate(index); if (null != date) { String dateString = dateFormatter.format(date); obj.put(selCol.getName(), dateString); } ++index; } else { throw new Exception("Unkown selected column type"); } } else { // Convert contributor id into user info int contribId = rs.getInt(index); JSONObject userInfo = fetchContributorFromIdWithCache( contribId, contributorMap); if (null != userInfo) { obj.put("contributor", userInfo); } ++index; } } array.put(obj); } } catch (Exception je) { throw new ServletException("Error while executing statement",je); } return array; } else { // indicates an update count or no results - this must be no results throw new Exception("Query returned no results"); } }
java
private JSONArray executeStatementToJson( PreparedStatement stmt, List<SelectedColumn> selectFields) throws Exception { //logger.info("about to execute: " + stmt.toString()); if( stmt.execute() ) { // There's a ResultSet to be had ResultSet rs = stmt.getResultSet(); JSONArray array = new JSONArray(); try { Map<Integer,JSONObject> contributorMap = new HashMap<Integer,JSONObject>(); while (rs.next()) { JSONObject obj = new JSONObject(); int index = 1; for(int loop=0; loop<selectFields.size(); ++loop) { SelectedColumn selCol = selectFields.get(loop); //logger.info("field: " + selCol.getName() + " (" + selCol.getType() + ")"); if (! "contributor_id".equalsIgnoreCase(selCol.getName())) { if( SelectedColumn.Type.INTEGER == selCol.getType() ) { obj.put(selCol.getName(),rs.getInt(index)); ++index; } else if( SelectedColumn.Type.STRING == selCol.getType() ) { obj.put(selCol.getName(),rs.getString(index)); ++index; } else if ( SelectedColumn.Type.DATE == selCol.getType() ) { Date date = rs.getDate(index); if (null != date) { String dateString = dateFormatter.format(date); obj.put(selCol.getName(), dateString); } ++index; } else { throw new Exception("Unkown selected column type"); } } else { // Convert contributor id into user info int contribId = rs.getInt(index); JSONObject userInfo = fetchContributorFromIdWithCache( contribId, contributorMap); if (null != userInfo) { obj.put("contributor", userInfo); } ++index; } } array.put(obj); } } catch (Exception je) { throw new ServletException("Error while executing statement",je); } return array; } else { // indicates an update count or no results - this must be no results throw new Exception("Query returned no results"); } }
[ "private", "JSONArray", "executeStatementToJson", "(", "PreparedStatement", "stmt", ",", "List", "<", "SelectedColumn", ">", "selectFields", ")", "throws", "Exception", "{", "//logger.info(\"about to execute: \" + stmt.toString());", "if", "(", "stmt", ".", "execute", "("...
This method executes a prepared SQL statement and returns a JSON array that contains the result. @param stmt Prepared SQL statement to execute @param selectFields Column to return in results @return A JSONArray containing the requested information @throws Exception
[ "This", "method", "executes", "a", "prepared", "SQL", "statement", "and", "returns", "a", "JSON", "array", "that", "contains", "the", "result", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-search/src/main/java/ca/carleton/gcrc/search/Searches.java#L511-L574
134,870
GCRC/nunaliit
nunaliit2-search/src/main/java/ca/carleton/gcrc/search/Searches.java
Searches.getAudioMediaFromPlaceId
public JSONObject getAudioMediaFromPlaceId(String place_id) throws Exception { List<SelectedColumn> selectFields = new Vector<SelectedColumn>(); selectFields.add( new SelectedColumn(SelectedColumn.Type.INTEGER, "id") ); selectFields.add( new SelectedColumn(SelectedColumn.Type.INTEGER, "place_id") ); selectFields.add( new SelectedColumn(SelectedColumn.Type.STRING, "filename") ); selectFields.add( new SelectedColumn(SelectedColumn.Type.STRING, "mimetype") ); selectFields.add( new SelectedColumn(SelectedColumn.Type.STRING, "title") ); PreparedStatement stmt = connection.prepareStatement( "SELECT id,place_id,filename,mimetype,title " + "FROM contributions " + "WHERE mimetype LIKE 'audio/%' AND place_id = ?;" ); stmt.setInt(1, Integer.parseInt(place_id)); JSONArray array = executeStatementToJson(stmt, selectFields); JSONObject result = new JSONObject(); result.put("media", array); return result; }
java
public JSONObject getAudioMediaFromPlaceId(String place_id) throws Exception { List<SelectedColumn> selectFields = new Vector<SelectedColumn>(); selectFields.add( new SelectedColumn(SelectedColumn.Type.INTEGER, "id") ); selectFields.add( new SelectedColumn(SelectedColumn.Type.INTEGER, "place_id") ); selectFields.add( new SelectedColumn(SelectedColumn.Type.STRING, "filename") ); selectFields.add( new SelectedColumn(SelectedColumn.Type.STRING, "mimetype") ); selectFields.add( new SelectedColumn(SelectedColumn.Type.STRING, "title") ); PreparedStatement stmt = connection.prepareStatement( "SELECT id,place_id,filename,mimetype,title " + "FROM contributions " + "WHERE mimetype LIKE 'audio/%' AND place_id = ?;" ); stmt.setInt(1, Integer.parseInt(place_id)); JSONArray array = executeStatementToJson(stmt, selectFields); JSONObject result = new JSONObject(); result.put("media", array); return result; }
[ "public", "JSONObject", "getAudioMediaFromPlaceId", "(", "String", "place_id", ")", "throws", "Exception", "{", "List", "<", "SelectedColumn", ">", "selectFields", "=", "new", "Vector", "<", "SelectedColumn", ">", "(", ")", ";", "selectFields", ".", "add", "(", ...
Finds and returns all audio media associated with a place id. @param place_id Id of associated place @return A JSON object containing all audio media @throws Exception
[ "Finds", "and", "returns", "all", "audio", "media", "associated", "with", "a", "place", "id", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-search/src/main/java/ca/carleton/gcrc/search/Searches.java#L663-L685
134,871
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/app/impl/DocumentManifest.java
DocumentManifest.hasDocumentBeenModified
static public boolean hasDocumentBeenModified( JSONObject targetDoc ) { JSONObject targetManifest = targetDoc.optJSONObject(MANIFEST_KEY); if( null == targetManifest ) { // Can not verify digest on target document. Let's assume it has // been modified return true; } String targetDigest = targetManifest.optString("digest"); if( null == targetDigest ) { // Can not verify digest on target document, let's assume it // has changed return true; } // Check type DigestComputer digestComputer = null; { String type = targetManifest.optString("type"); if( null == type ){ // Has been modified sine type is missing return true; } else if( DigestComputerSha1.DIGEST_COMPUTER_TYPE.equals(type) ) { digestComputer = sha1DigestComputer; } else { // Unrecognized type. Assume it was changed return true; } } try { String computedDigest = digestComputer.computeDigestFromJsonObject(targetDoc); if( false == computedDigest.equals(targetDigest) ) { // Digests are different. It was changed return true; } } catch(Exception e) { // Error computing digest, let's assume it was changed return true; } // Verify attachments by checking each attachment in manifest and verifying // each attachment has not changed Set<String> attachmentNamesInManifest = new HashSet<String>(); JSONObject targetAttachmentManifests = targetManifest.optJSONObject("attachments"); if( null != targetAttachmentManifests ){ Iterator<?> it = targetAttachmentManifests.keys(); while( it.hasNext() ){ Object keyObj = it.next(); if( keyObj instanceof String ){ String attachmentName = (String)keyObj; attachmentNamesInManifest.add(attachmentName); JSONObject attachmentManifest = targetAttachmentManifests.optJSONObject(attachmentName); if( null == attachmentManifest ) { // Error. Must have been changed return true; } else if( false == JSONSupport.containsKey(attachmentManifest,"revpos") ) { // revpos is gone, document must have been modified return true; } else { int revpos = attachmentManifest.optInt("revpos",0); Integer actualRevPos = getAttachmentPosition(targetDoc,attachmentName); if( null == actualRevPos ) { // Attachment is gone return true; } else if( revpos != actualRevPos.intValue() ){ // Attachment has changed return true; } } } } } // Verify that each attachment has a manifest declared for it JSONObject targetAttachments = targetDoc.optJSONObject("_attachments"); if( null != targetAttachments ) { Iterator<?> it = targetAttachments.keys(); while( it.hasNext() ){ Object keyObj = it.next(); if( keyObj instanceof String ){ String attachmentName = (String)keyObj; if( false == attachmentNamesInManifest.contains(attachmentName) ){ // This attachment was added since manifest was computed return true; } } } } // If we make it here, the document has not changed according to the manifest return false; }
java
static public boolean hasDocumentBeenModified( JSONObject targetDoc ) { JSONObject targetManifest = targetDoc.optJSONObject(MANIFEST_KEY); if( null == targetManifest ) { // Can not verify digest on target document. Let's assume it has // been modified return true; } String targetDigest = targetManifest.optString("digest"); if( null == targetDigest ) { // Can not verify digest on target document, let's assume it // has changed return true; } // Check type DigestComputer digestComputer = null; { String type = targetManifest.optString("type"); if( null == type ){ // Has been modified sine type is missing return true; } else if( DigestComputerSha1.DIGEST_COMPUTER_TYPE.equals(type) ) { digestComputer = sha1DigestComputer; } else { // Unrecognized type. Assume it was changed return true; } } try { String computedDigest = digestComputer.computeDigestFromJsonObject(targetDoc); if( false == computedDigest.equals(targetDigest) ) { // Digests are different. It was changed return true; } } catch(Exception e) { // Error computing digest, let's assume it was changed return true; } // Verify attachments by checking each attachment in manifest and verifying // each attachment has not changed Set<String> attachmentNamesInManifest = new HashSet<String>(); JSONObject targetAttachmentManifests = targetManifest.optJSONObject("attachments"); if( null != targetAttachmentManifests ){ Iterator<?> it = targetAttachmentManifests.keys(); while( it.hasNext() ){ Object keyObj = it.next(); if( keyObj instanceof String ){ String attachmentName = (String)keyObj; attachmentNamesInManifest.add(attachmentName); JSONObject attachmentManifest = targetAttachmentManifests.optJSONObject(attachmentName); if( null == attachmentManifest ) { // Error. Must have been changed return true; } else if( false == JSONSupport.containsKey(attachmentManifest,"revpos") ) { // revpos is gone, document must have been modified return true; } else { int revpos = attachmentManifest.optInt("revpos",0); Integer actualRevPos = getAttachmentPosition(targetDoc,attachmentName); if( null == actualRevPos ) { // Attachment is gone return true; } else if( revpos != actualRevPos.intValue() ){ // Attachment has changed return true; } } } } } // Verify that each attachment has a manifest declared for it JSONObject targetAttachments = targetDoc.optJSONObject("_attachments"); if( null != targetAttachments ) { Iterator<?> it = targetAttachments.keys(); while( it.hasNext() ){ Object keyObj = it.next(); if( keyObj instanceof String ){ String attachmentName = (String)keyObj; if( false == attachmentNamesInManifest.contains(attachmentName) ){ // This attachment was added since manifest was computed return true; } } } } // If we make it here, the document has not changed according to the manifest return false; }
[ "static", "public", "boolean", "hasDocumentBeenModified", "(", "JSONObject", "targetDoc", ")", "{", "JSONObject", "targetManifest", "=", "targetDoc", ".", "optJSONObject", "(", "MANIFEST_KEY", ")", ";", "if", "(", "null", "==", "targetManifest", ")", "{", "// Can ...
Analyzes a document and determines if the document has been modified since the time the manifest was computed. @param targetDoc Remote JSON document to test for modification @param digestComputer Digest computer used to verify the compute intermediate digest and verify authenticity of given manifest. @return True, if remote document appears to have been modified since the manifest was computed.
[ "Analyzes", "a", "document", "and", "determines", "if", "the", "document", "has", "been", "modified", "since", "the", "time", "the", "manifest", "was", "computed", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/app/impl/DocumentManifest.java#L28-L127
134,872
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/app/impl/DocumentManifest.java
DocumentManifest.getAttachmentPosition
static public Integer getAttachmentPosition( JSONObject targetDoc ,String attachmentName ) { JSONObject targetAttachments = targetDoc.optJSONObject("_attachments"); if( null == targetAttachments ) { // No attachment on target doc return null; } JSONObject targetAttachment = targetAttachments.optJSONObject(attachmentName); if( null == targetAttachment ) { // Target document does not have an attachment with this name return null; } if( JSONSupport.containsKey(targetAttachment,"revpos") ){ int revPos = targetAttachment.optInt("revpos",-1); if( revPos < 0 ){ return null; } return revPos; } return null; }
java
static public Integer getAttachmentPosition( JSONObject targetDoc ,String attachmentName ) { JSONObject targetAttachments = targetDoc.optJSONObject("_attachments"); if( null == targetAttachments ) { // No attachment on target doc return null; } JSONObject targetAttachment = targetAttachments.optJSONObject(attachmentName); if( null == targetAttachment ) { // Target document does not have an attachment with this name return null; } if( JSONSupport.containsKey(targetAttachment,"revpos") ){ int revPos = targetAttachment.optInt("revpos",-1); if( revPos < 0 ){ return null; } return revPos; } return null; }
[ "static", "public", "Integer", "getAttachmentPosition", "(", "JSONObject", "targetDoc", ",", "String", "attachmentName", ")", "{", "JSONObject", "targetAttachments", "=", "targetDoc", ".", "optJSONObject", "(", "\"_attachments\"", ")", ";", "if", "(", "null", "==", ...
Given a JSON document and an attachment name, returns the revision position associated with the attachment. @param targetDoc @param attachmentName @return
[ "Given", "a", "JSON", "document", "and", "an", "attachment", "name", "returns", "the", "revision", "position", "associated", "with", "the", "attachment", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/app/impl/DocumentManifest.java#L136-L162
134,873
GCRC/nunaliit
nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/TIFFUtil.java
TIFFUtil.setCompressionType
public static void setCompressionType(ImageWriteParam param, BufferedImage image) { // avoid error: first compression type is RLE, not optimal and incorrect for color images // TODO expose this choice to the user? if (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1) { param.setCompressionType("CCITT T.6"); } else { param.setCompressionType("LZW"); } }
java
public static void setCompressionType(ImageWriteParam param, BufferedImage image) { // avoid error: first compression type is RLE, not optimal and incorrect for color images // TODO expose this choice to the user? if (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1) { param.setCompressionType("CCITT T.6"); } else { param.setCompressionType("LZW"); } }
[ "public", "static", "void", "setCompressionType", "(", "ImageWriteParam", "param", ",", "BufferedImage", "image", ")", "{", "// avoid error: first compression type is RLE, not optimal and incorrect for color images", "// TODO expose this choice to the user?", "if", "(", "image", "....
Sets the ImageIO parameter compression type based on the given image. @param image buffered image used to decide compression type @param param ImageIO write parameter to update
[ "Sets", "the", "ImageIO", "parameter", "compression", "type", "based", "on", "the", "given", "image", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/TIFFUtil.java#L48-L61
134,874
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntryResource.java
FSEntryResource.getPositionedResource
static public FSEntry getPositionedResource(String path, ClassLoader classLoader, String resourceName) throws Exception { List<String> pathFrags = FSEntrySupport.interpretPath(path); // Start at leaf and work our way back int index = pathFrags.size() - 1; FSEntry root = create(pathFrags.get(index), classLoader, resourceName); --index; while(index >= 0){ FSEntryVirtualDirectory parent = new FSEntryVirtualDirectory(pathFrags.get(index)); parent.addChildEntry(root); root = parent; --index; } return root; }
java
static public FSEntry getPositionedResource(String path, ClassLoader classLoader, String resourceName) throws Exception { List<String> pathFrags = FSEntrySupport.interpretPath(path); // Start at leaf and work our way back int index = pathFrags.size() - 1; FSEntry root = create(pathFrags.get(index), classLoader, resourceName); --index; while(index >= 0){ FSEntryVirtualDirectory parent = new FSEntryVirtualDirectory(pathFrags.get(index)); parent.addChildEntry(root); root = parent; --index; } return root; }
[ "static", "public", "FSEntry", "getPositionedResource", "(", "String", "path", ",", "ClassLoader", "classLoader", ",", "String", "resourceName", ")", "throws", "Exception", "{", "List", "<", "String", ">", "pathFrags", "=", "FSEntrySupport", ".", "interpretPath", ...
Create a virtual tree hierarchy with a resource supporting the leaf. @param path Position of the file in the hierarchy, including its name @param classLoader Class loader used to find the needed resource @param resourceName Name of the actual resource to obtain using class loader @return The FSEntry root for this hierarchy @throws Exception Invalid parameter
[ "Create", "a", "virtual", "tree", "hierarchy", "with", "a", "resource", "supporting", "the", "leaf", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntryResource.java#L24-L40
134,875
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntryResource.java
FSEntryResource.create
static public FSEntryResource create(ClassLoader classLoader, String resourceName) throws Exception { return create(null, classLoader, resourceName); }
java
static public FSEntryResource create(ClassLoader classLoader, String resourceName) throws Exception { return create(null, classLoader, resourceName); }
[ "static", "public", "FSEntryResource", "create", "(", "ClassLoader", "classLoader", ",", "String", "resourceName", ")", "throws", "Exception", "{", "return", "create", "(", "null", ",", "classLoader", ",", "resourceName", ")", ";", "}" ]
Creates an instance of FSEntryResource to represent an entry based on the resource specified by the classLoader and resource name. @param classLoader Class loader used to find the resource @param resourceName Actual name of resource @return An entry representing the specified resource. @throws Exception Invalid request
[ "Creates", "an", "instance", "of", "FSEntryResource", "to", "represent", "an", "entry", "based", "on", "the", "resource", "specified", "by", "the", "classLoader", "and", "resource", "name", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntryResource.java#L50-L52
134,876
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntryResource.java
FSEntryResource.create
static public FSEntryResource create(String name, ClassLoader classLoader, String resourceName) throws Exception { URL url = classLoader.getResource(resourceName); if( "jar".equals( url.getProtocol() ) ) { String path = url.getPath(); if( path.startsWith("file:") ) { int bangIndex = path.indexOf('!'); if( bangIndex >= 0 ) { String jarFileName = path.substring("file:".length(), bangIndex); String resourceNameFile = path.substring(bangIndex+2); String resourceNameDir = resourceNameFile; if( false == resourceNameDir.endsWith("/") ) { resourceNameDir = resourceNameFile + "/"; } JarFile jarFile = new JarFile(URLDecoder.decode(jarFileName, "UTF-8")); Enumeration<JarEntry> entries = jarFile.entries(); while(entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); String entryName = jarEntry.getName(); if( entryName.equals(resourceNameFile) || entryName.equals(resourceNameDir) ) { // Compute name if required if( null == name ){ name = nameFromJarEntry(jarEntry); } return new FSEntryResource(name, jarFile, jarEntry); } } } } throw new Exception("Unable to find resource: "+resourceName); } else if( "file".equals( url.getProtocol() ) ) { File file = new File( url.getFile() ); if( null == name ){ name = file.getName(); } return new FSEntryResource(name, file); } else { throw new Exception("Unable to create resource entry for protocol: "+url.getProtocol()); } }
java
static public FSEntryResource create(String name, ClassLoader classLoader, String resourceName) throws Exception { URL url = classLoader.getResource(resourceName); if( "jar".equals( url.getProtocol() ) ) { String path = url.getPath(); if( path.startsWith("file:") ) { int bangIndex = path.indexOf('!'); if( bangIndex >= 0 ) { String jarFileName = path.substring("file:".length(), bangIndex); String resourceNameFile = path.substring(bangIndex+2); String resourceNameDir = resourceNameFile; if( false == resourceNameDir.endsWith("/") ) { resourceNameDir = resourceNameFile + "/"; } JarFile jarFile = new JarFile(URLDecoder.decode(jarFileName, "UTF-8")); Enumeration<JarEntry> entries = jarFile.entries(); while(entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); String entryName = jarEntry.getName(); if( entryName.equals(resourceNameFile) || entryName.equals(resourceNameDir) ) { // Compute name if required if( null == name ){ name = nameFromJarEntry(jarEntry); } return new FSEntryResource(name, jarFile, jarEntry); } } } } throw new Exception("Unable to find resource: "+resourceName); } else if( "file".equals( url.getProtocol() ) ) { File file = new File( url.getFile() ); if( null == name ){ name = file.getName(); } return new FSEntryResource(name, file); } else { throw new Exception("Unable to create resource entry for protocol: "+url.getProtocol()); } }
[ "static", "public", "FSEntryResource", "create", "(", "String", "name", ",", "ClassLoader", "classLoader", ",", "String", "resourceName", ")", "throws", "Exception", "{", "URL", "url", "=", "classLoader", ".", "getResource", "(", "resourceName", ")", ";", "if", ...
Creates an instance of FSEntryResource to represent an entry based on the resource specified by the classLoader and resource name. This resource can be a file or a directory. Furthermore, this resource can be located on file system or inside a JAR file. @param name Name that the resource claims as its own. Useful to impersonate. @param classLoader Class loader used to find the resource @param resourceName Actual name of resource @return An entry representing the specified resource. @throws Exception Invalid request
[ "Creates", "an", "instance", "of", "FSEntryResource", "to", "represent", "an", "entry", "based", "on", "the", "resource", "specified", "by", "the", "classLoader", "and", "resource", "name", ".", "This", "resource", "can", "be", "a", "file", "or", "a", "direc...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntryResource.java#L65-L113
134,877
GCRC/nunaliit
nunaliit2-auth-cookie/src/main/java/ca/carleton/gcrc/auth/cookie/AuthServlet.java
AuthServlet.performAdjustCookies
private void performAdjustCookies(HttpServletRequest request, HttpServletResponse response) throws Exception { boolean loggedIn = false; User user = null; try { Cookie cookie = getCookieFromRequest(request); if( null != cookie ) { user = CookieAuthentication.verifyCookieString(userRepository, cookie.getValue()); loggedIn = true; } } catch(Exception e) { // Ignore } if( null == user ) { user = userRepository.getDefaultUser(); } acceptRequest(response, loggedIn, user); }
java
private void performAdjustCookies(HttpServletRequest request, HttpServletResponse response) throws Exception { boolean loggedIn = false; User user = null; try { Cookie cookie = getCookieFromRequest(request); if( null != cookie ) { user = CookieAuthentication.verifyCookieString(userRepository, cookie.getValue()); loggedIn = true; } } catch(Exception e) { // Ignore } if( null == user ) { user = userRepository.getDefaultUser(); } acceptRequest(response, loggedIn, user); }
[ "private", "void", "performAdjustCookies", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "Exception", "{", "boolean", "loggedIn", "=", "false", ";", "User", "user", "=", "null", ";", "try", "{", "Cookie", "cookie", ...
Adjusts the information cookie based on the authentication token @param request @param response @throws ServletException @throws IOException
[ "Adjusts", "the", "information", "cookie", "based", "on", "the", "authentication", "token" ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-auth-cookie/src/main/java/ca/carleton/gcrc/auth/cookie/AuthServlet.java#L186-L205
134,878
GCRC/nunaliit
nunaliit2-couch-date/src/main/java/ca/carleton/gcrc/couch/date/cluster/TreeRebalanceProcess.java
TreeRebalanceProcess.createTree
static public TreeRebalanceProcess.Result createTree(List<? extends TreeElement> elements) throws Exception { Result results = new Result(); // Compute full interval, next cluster id and legacy nodes TimeInterval fullRegularInterval = null; TimeInterval fullOngoingInterval = null; results.nextClusterId = 1; Map<Integer,TreeNodeRegular> legacyRegularNodes = new HashMap<Integer,TreeNodeRegular>(); Map<Integer,TreeNodeOngoing> legacyOngoingNodes = new HashMap<Integer,TreeNodeOngoing>(); for(TreeElement element : elements){ Integer clusterId = element.getClusterId(); // Accumulate full intervals if( element.getInterval().isOngoing() ){ if( null == fullOngoingInterval ){ fullOngoingInterval = element.getInterval(); } else { fullOngoingInterval = fullOngoingInterval.extendTo(element.getInterval()); } } else { if( null == fullRegularInterval ){ fullRegularInterval = element.getInterval(); } else { fullRegularInterval = fullRegularInterval.extendTo(element.getInterval()); } } // Figure out next cluster id if( null != clusterId ){ if( clusterId >= results.nextClusterId ){ results.nextClusterId = clusterId + 1; } } // Accumulate legacy nodes if( null != clusterId ){ TimeInterval elementInterval = element.getInterval(); if( elementInterval.isOngoing() ){ TreeNodeOngoing legacyNode = legacyOngoingNodes.get(clusterId); if( null == legacyNode ){ legacyNode = new TreeNodeOngoing(clusterId, element.getInterval()); legacyOngoingNodes.put(clusterId, legacyNode); } else { legacyNode.extendTo(element.getInterval()); } } else { TreeNodeRegular legacyNode = legacyRegularNodes.get(clusterId); if( null == legacyNode ){ legacyNode = new TreeNodeRegular(clusterId, element.getInterval()); legacyRegularNodes.put(clusterId, legacyNode); } else { legacyNode.extendTo(element.getInterval()); } } } } // Need a full interval if( null == fullRegularInterval ){ // Create a default one fullRegularInterval = new TimeInterval(0, 1500000000000L); } if( null == fullOngoingInterval ){ // Create a default one fullOngoingInterval = new TimeInterval(0, (NowReference)null); } // Create root node for tree TreeNodeRegular regularRootNode = new TreeNodeRegular(results.nextClusterId, fullRegularInterval); results.nextClusterId++; TreeNodeOngoing ongoingRootNode = new TreeNodeOngoing(results.nextClusterId, fullOngoingInterval); results.nextClusterId++; // Install root node in results results.regularRootNode = regularRootNode; results.ongoingRootNode = ongoingRootNode; // Install legacy nodes in results results.legacyNodes.addAll( legacyRegularNodes.values() ); results.legacyNodes.addAll( legacyOngoingNodes.values() ); return results; }
java
static public TreeRebalanceProcess.Result createTree(List<? extends TreeElement> elements) throws Exception { Result results = new Result(); // Compute full interval, next cluster id and legacy nodes TimeInterval fullRegularInterval = null; TimeInterval fullOngoingInterval = null; results.nextClusterId = 1; Map<Integer,TreeNodeRegular> legacyRegularNodes = new HashMap<Integer,TreeNodeRegular>(); Map<Integer,TreeNodeOngoing> legacyOngoingNodes = new HashMap<Integer,TreeNodeOngoing>(); for(TreeElement element : elements){ Integer clusterId = element.getClusterId(); // Accumulate full intervals if( element.getInterval().isOngoing() ){ if( null == fullOngoingInterval ){ fullOngoingInterval = element.getInterval(); } else { fullOngoingInterval = fullOngoingInterval.extendTo(element.getInterval()); } } else { if( null == fullRegularInterval ){ fullRegularInterval = element.getInterval(); } else { fullRegularInterval = fullRegularInterval.extendTo(element.getInterval()); } } // Figure out next cluster id if( null != clusterId ){ if( clusterId >= results.nextClusterId ){ results.nextClusterId = clusterId + 1; } } // Accumulate legacy nodes if( null != clusterId ){ TimeInterval elementInterval = element.getInterval(); if( elementInterval.isOngoing() ){ TreeNodeOngoing legacyNode = legacyOngoingNodes.get(clusterId); if( null == legacyNode ){ legacyNode = new TreeNodeOngoing(clusterId, element.getInterval()); legacyOngoingNodes.put(clusterId, legacyNode); } else { legacyNode.extendTo(element.getInterval()); } } else { TreeNodeRegular legacyNode = legacyRegularNodes.get(clusterId); if( null == legacyNode ){ legacyNode = new TreeNodeRegular(clusterId, element.getInterval()); legacyRegularNodes.put(clusterId, legacyNode); } else { legacyNode.extendTo(element.getInterval()); } } } } // Need a full interval if( null == fullRegularInterval ){ // Create a default one fullRegularInterval = new TimeInterval(0, 1500000000000L); } if( null == fullOngoingInterval ){ // Create a default one fullOngoingInterval = new TimeInterval(0, (NowReference)null); } // Create root node for tree TreeNodeRegular regularRootNode = new TreeNodeRegular(results.nextClusterId, fullRegularInterval); results.nextClusterId++; TreeNodeOngoing ongoingRootNode = new TreeNodeOngoing(results.nextClusterId, fullOngoingInterval); results.nextClusterId++; // Install root node in results results.regularRootNode = regularRootNode; results.ongoingRootNode = ongoingRootNode; // Install legacy nodes in results results.legacyNodes.addAll( legacyRegularNodes.values() ); results.legacyNodes.addAll( legacyOngoingNodes.values() ); return results; }
[ "static", "public", "TreeRebalanceProcess", ".", "Result", "createTree", "(", "List", "<", "?", "extends", "TreeElement", ">", "elements", ")", "throws", "Exception", "{", "Result", "results", "=", "new", "Result", "(", ")", ";", "// Compute full interval, next cl...
Creates a new cluster tree given the provided elements. If these elements were already part of a cluster, then legacy cluster nodes are created to account for those elements. This is the perfect process in case the previous tree was lost. @param elements Elements to be considered for the new tree. @return Results of creating a new tree. @throws Exception
[ "Creates", "a", "new", "cluster", "tree", "given", "the", "provided", "elements", ".", "If", "these", "elements", "were", "already", "part", "of", "a", "cluster", "then", "legacy", "cluster", "nodes", "are", "created", "to", "account", "for", "those", "eleme...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-date/src/main/java/ca/carleton/gcrc/couch/date/cluster/TreeRebalanceProcess.java#L34-L115
134,879
GCRC/nunaliit
nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcConnections.java
JdbcConnections.getDb
synchronized public Connection getDb(String db) throws Exception { Connection con = null; if (nameToConnection.containsKey(db)) { con = nameToConnection.get(db); } else { ConnectionInfo info = nameToInfo.get(db); if( null == info ) { throw new Exception("No information provided for database named: "+db); } try { Class.forName(info.getJdbcClass()); //load the driver con = DriverManager.getConnection(info.getConnectionString(), info.getUserName(), info.getPassword()); //connect to the db DatabaseMetaData dbmd = con.getMetaData(); //get MetaData to confirm connection logger.info("Connection to "+dbmd.getDatabaseProductName()+" "+ dbmd.getDatabaseProductVersion()+" successful.\n"); nameToConnection.put(db, con); } catch(Exception e) { throw new Exception("Couldn't get db connection: "+db,e); } } return(con); }
java
synchronized public Connection getDb(String db) throws Exception { Connection con = null; if (nameToConnection.containsKey(db)) { con = nameToConnection.get(db); } else { ConnectionInfo info = nameToInfo.get(db); if( null == info ) { throw new Exception("No information provided for database named: "+db); } try { Class.forName(info.getJdbcClass()); //load the driver con = DriverManager.getConnection(info.getConnectionString(), info.getUserName(), info.getPassword()); //connect to the db DatabaseMetaData dbmd = con.getMetaData(); //get MetaData to confirm connection logger.info("Connection to "+dbmd.getDatabaseProductName()+" "+ dbmd.getDatabaseProductVersion()+" successful.\n"); nameToConnection.put(db, con); } catch(Exception e) { throw new Exception("Couldn't get db connection: "+db,e); } } return(con); }
[ "synchronized", "public", "Connection", "getDb", "(", "String", "db", ")", "throws", "Exception", "{", "Connection", "con", "=", "null", ";", "if", "(", "nameToConnection", ".", "containsKey", "(", "db", ")", ")", "{", "con", "=", "nameToConnection", ".", ...
This method checks for the presence of a Connection associated with the input db parameter. It attempts to create the Connection and adds it to the connection map if it does not already exist. If the Connection exists or is created, it is returned. @param db database name. @return Returns the desired Connection instance, or null.
[ "This", "method", "checks", "for", "the", "presence", "of", "a", "Connection", "associated", "with", "the", "input", "db", "parameter", ".", "It", "attempts", "to", "create", "the", "Connection", "and", "adds", "it", "to", "the", "connection", "map", "if", ...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcConnections.java#L149-L175
134,880
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/client/impl/ConnectionUtils.java
ConnectionUtils.captureReponseErrors
static public void captureReponseErrors(Object response, String errorMessage) throws Exception { if( null == response ) { throw new Exception("Capturing errors from null response"); } if( false == (response instanceof JSONObject) ) { // Not an error return; } JSONObject obj = (JSONObject)response; if( JSONSupport.containsKey(obj,"error") ) { String serverMessage; try { serverMessage = obj.getString("error"); } catch (Exception e) { serverMessage = "Unable to parse error response"; } if( null == errorMessage ) { errorMessage = "Error returned by database: "; } throw new Exception(errorMessage+serverMessage); } }
java
static public void captureReponseErrors(Object response, String errorMessage) throws Exception { if( null == response ) { throw new Exception("Capturing errors from null response"); } if( false == (response instanceof JSONObject) ) { // Not an error return; } JSONObject obj = (JSONObject)response; if( JSONSupport.containsKey(obj,"error") ) { String serverMessage; try { serverMessage = obj.getString("error"); } catch (Exception e) { serverMessage = "Unable to parse error response"; } if( null == errorMessage ) { errorMessage = "Error returned by database: "; } throw new Exception(errorMessage+serverMessage); } }
[ "static", "public", "void", "captureReponseErrors", "(", "Object", "response", ",", "String", "errorMessage", ")", "throws", "Exception", "{", "if", "(", "null", "==", "response", ")", "{", "throw", "new", "Exception", "(", "\"Capturing errors from null response\"",...
Analyze a CouchDb response and raises an exception if an error was returned in the response. @param response JSON response sent by server @param errorMessage Message of top exception @throws Exception If error is returned in response
[ "Analyze", "a", "CouchDb", "response", "and", "raises", "an", "exception", "if", "an", "error", "was", "returned", "in", "the", "response", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/client/impl/ConnectionUtils.java#L427-L449
134,881
GCRC/nunaliit
nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java
PathComputer.computeAtlasDir
static public File computeAtlasDir(String name) { File atlasDir = null; if( null == name ) { // Current dir atlasDir = new File("."); } else { atlasDir = new File(name); } // Force absolute if( false == atlasDir.isAbsolute() ){ atlasDir = atlasDir.getAbsoluteFile(); } return atlasDir; }
java
static public File computeAtlasDir(String name) { File atlasDir = null; if( null == name ) { // Current dir atlasDir = new File("."); } else { atlasDir = new File(name); } // Force absolute if( false == atlasDir.isAbsolute() ){ atlasDir = atlasDir.getAbsoluteFile(); } return atlasDir; }
[ "static", "public", "File", "computeAtlasDir", "(", "String", "name", ")", "{", "File", "atlasDir", "=", "null", ";", "if", "(", "null", "==", "name", ")", "{", "// Current dir", "atlasDir", "=", "new", "File", "(", "\".\"", ")", ";", "}", "else", "{",...
Computes the directory where the atlas resides given a command-line argument provided by the user. If the argument is not given, then this method should be called with a null argument. @param name Path given by user at the command-line to refer to the atlas @return Directory where atlas resides, based on the given argument
[ "Computes", "the", "directory", "where", "the", "atlas", "resides", "given", "a", "command", "-", "line", "argument", "provided", "by", "the", "user", ".", "If", "the", "argument", "is", "not", "given", "then", "this", "method", "should", "be", "called", "...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java#L17-L33
134,882
GCRC/nunaliit
nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java
PathComputer.computeInstallDir
static public File computeInstallDir() { File installDir = null; // Try to find the path of a known resource file File knownResourceFile = null; { URL url = Main.class.getClassLoader().getResource("commandResourceDummy.txt"); if( null == url ){ // Nothing we can do since the resource is not found } else if( "jar".equals( url.getProtocol() ) ) { // The tool is called from an "app assembly". Find the // parent of the "repo" directory String path = url.getPath(); if( path.startsWith("file:") ) { int bangIndex = path.indexOf('!'); if( bangIndex >= 0 ) { String jarFileName = path.substring("file:".length(), bangIndex); knownResourceFile = new File(jarFileName); } } } else if( "file".equals( url.getProtocol() ) ) { knownResourceFile = new File( url.getFile() ); } } // Try to find the package installation directory. This should be the parent // of a sub-directory called "repo". This is the directory where all the // JAR files are stored in the command-line tool if( null == installDir && null != knownResourceFile ){ File tempFile = knownResourceFile; boolean found = false; while( !found && null != tempFile ){ if( "repo".equals( tempFile.getName() ) ){ found = true; // Parent of "repo" is where the command-line tool is installed installDir = tempFile.getParentFile(); } else { // Go to parent tempFile = tempFile.getParentFile(); } } } // If the "repo" directory is not found, then look for the root // of the nunaliit2 project. In a development environment, this is what // we use to look for other directories. if( null == installDir && null != knownResourceFile ){ installDir = computeNunaliitDir(knownResourceFile); } return installDir; }
java
static public File computeInstallDir() { File installDir = null; // Try to find the path of a known resource file File knownResourceFile = null; { URL url = Main.class.getClassLoader().getResource("commandResourceDummy.txt"); if( null == url ){ // Nothing we can do since the resource is not found } else if( "jar".equals( url.getProtocol() ) ) { // The tool is called from an "app assembly". Find the // parent of the "repo" directory String path = url.getPath(); if( path.startsWith("file:") ) { int bangIndex = path.indexOf('!'); if( bangIndex >= 0 ) { String jarFileName = path.substring("file:".length(), bangIndex); knownResourceFile = new File(jarFileName); } } } else if( "file".equals( url.getProtocol() ) ) { knownResourceFile = new File( url.getFile() ); } } // Try to find the package installation directory. This should be the parent // of a sub-directory called "repo". This is the directory where all the // JAR files are stored in the command-line tool if( null == installDir && null != knownResourceFile ){ File tempFile = knownResourceFile; boolean found = false; while( !found && null != tempFile ){ if( "repo".equals( tempFile.getName() ) ){ found = true; // Parent of "repo" is where the command-line tool is installed installDir = tempFile.getParentFile(); } else { // Go to parent tempFile = tempFile.getParentFile(); } } } // If the "repo" directory is not found, then look for the root // of the nunaliit2 project. In a development environment, this is what // we use to look for other directories. if( null == installDir && null != knownResourceFile ){ installDir = computeNunaliitDir(knownResourceFile); } return installDir; }
[ "static", "public", "File", "computeInstallDir", "(", ")", "{", "File", "installDir", "=", "null", ";", "// Try to find the path of a known resource file", "File", "knownResourceFile", "=", "null", ";", "{", "URL", "url", "=", "Main", ".", "class", ".", "getClassL...
Computes the installation directory for the command line tool. This is done by looking for a known resource in a JAR file that ships with the command-line tool. When the resource is found, the location of the associated JAR file is derived. From there, the root directory of the installation is deduced. If the command-line tool is used in a development environment, then the known resource is found either as a file or within a JAR that lives within the project directory. In that case, return the root directory of the project. @return Directory of the command-line installed packaged or the root directory of the nunaliit2 project. If neither can be computed, return null.
[ "Computes", "the", "installation", "directory", "for", "the", "command", "line", "tool", ".", "This", "is", "done", "by", "looking", "for", "a", "known", "resource", "in", "a", "JAR", "file", "that", "ships", "with", "the", "command", "-", "line", "tool", ...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java#L48-L103
134,883
GCRC/nunaliit
nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java
PathComputer.computeContentDir
static public File computeContentDir(File installDir) { if( null != installDir ) { // Command-line package File contentDir = new File(installDir, "content"); if( contentDir.exists() && contentDir.isDirectory() ) { return contentDir; } // Development environment File nunaliit2Dir = computeNunaliitDir(installDir); contentDir = new File(nunaliit2Dir, "nunaliit2-couch-sdk/src/main/content"); if( contentDir.exists() && contentDir.isDirectory() ) { return contentDir; } } return null; }
java
static public File computeContentDir(File installDir) { if( null != installDir ) { // Command-line package File contentDir = new File(installDir, "content"); if( contentDir.exists() && contentDir.isDirectory() ) { return contentDir; } // Development environment File nunaliit2Dir = computeNunaliitDir(installDir); contentDir = new File(nunaliit2Dir, "nunaliit2-couch-sdk/src/main/content"); if( contentDir.exists() && contentDir.isDirectory() ) { return contentDir; } } return null; }
[ "static", "public", "File", "computeContentDir", "(", "File", "installDir", ")", "{", "if", "(", "null", "!=", "installDir", ")", "{", "// Command-line package", "File", "contentDir", "=", "new", "File", "(", "installDir", ",", "\"content\"", ")", ";", "if", ...
Finds the "content" directory from the installation location and returns it. If the command-line tool is packaged and deployed, then the "content" directory is found at the root of the installation. If the command-line tool is run from the development environment, then the "content" directory is found in the SDK sub-project. @param installDir Directory where the command-line tool is run from. @return Directory where content is located or null if not found.
[ "Finds", "the", "content", "directory", "from", "the", "installation", "location", "and", "returns", "it", ".", "If", "the", "command", "-", "line", "tool", "is", "packaged", "and", "deployed", "then", "the", "content", "directory", "is", "found", "at", "the...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java#L145-L162
134,884
GCRC/nunaliit
nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java
PathComputer.computeBinDir
static public File computeBinDir(File installDir) { if( null != installDir ) { // Command-line package File binDir = new File(installDir, "bin"); if( binDir.exists() && binDir.isDirectory() ) { return binDir; } // Development environment File nunaliit2Dir = computeNunaliitDir(installDir); binDir = new File(nunaliit2Dir, "nunaliit2-couch-sdk/target/appassembler/bin"); if( binDir.exists() && binDir.isDirectory() ) { return binDir; } } return null; }
java
static public File computeBinDir(File installDir) { if( null != installDir ) { // Command-line package File binDir = new File(installDir, "bin"); if( binDir.exists() && binDir.isDirectory() ) { return binDir; } // Development environment File nunaliit2Dir = computeNunaliitDir(installDir); binDir = new File(nunaliit2Dir, "nunaliit2-couch-sdk/target/appassembler/bin"); if( binDir.exists() && binDir.isDirectory() ) { return binDir; } } return null; }
[ "static", "public", "File", "computeBinDir", "(", "File", "installDir", ")", "{", "if", "(", "null", "!=", "installDir", ")", "{", "// Command-line package", "File", "binDir", "=", "new", "File", "(", "installDir", ",", "\"bin\"", ")", ";", "if", "(", "bin...
Finds the "bin" directory from the installation location and returns it. If the command-line tool is packaged and deployed, then the "bin" directory is found at the root of the installation. If the command-line tool is run from the development environment, then the "bin" directory is found in the SDK sub-project. @param installDir Directory where the command-line tool is run from. @return Directory where binaries are located or null if not found.
[ "Finds", "the", "bin", "directory", "from", "the", "installation", "location", "and", "returns", "it", ".", "If", "the", "command", "-", "line", "tool", "is", "packaged", "and", "deployed", "then", "the", "bin", "directory", "is", "found", "at", "the", "ro...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java#L174-L191
134,885
GCRC/nunaliit
nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java
PathComputer.computeSiteDesignDir
static public File computeSiteDesignDir(File installDir) { if( null != installDir ) { // Command-line package File templatesDir = new File(installDir, "internal/siteDesign"); if( templatesDir.exists() && templatesDir.isDirectory() ) { return templatesDir; } // Development environment File nunaliit2Dir = computeNunaliitDir(installDir); templatesDir = new File(nunaliit2Dir, "nunaliit2-couch-sdk/src/main/internal/siteDesign"); if( templatesDir.exists() && templatesDir.isDirectory() ) { return templatesDir; } } return null; }
java
static public File computeSiteDesignDir(File installDir) { if( null != installDir ) { // Command-line package File templatesDir = new File(installDir, "internal/siteDesign"); if( templatesDir.exists() && templatesDir.isDirectory() ) { return templatesDir; } // Development environment File nunaliit2Dir = computeNunaliitDir(installDir); templatesDir = new File(nunaliit2Dir, "nunaliit2-couch-sdk/src/main/internal/siteDesign"); if( templatesDir.exists() && templatesDir.isDirectory() ) { return templatesDir; } } return null; }
[ "static", "public", "File", "computeSiteDesignDir", "(", "File", "installDir", ")", "{", "if", "(", "null", "!=", "installDir", ")", "{", "// Command-line package", "File", "templatesDir", "=", "new", "File", "(", "installDir", ",", "\"internal/siteDesign\"", ")",...
Finds the "siteDesign" directory from the installation location and returns it. If the command-line tool is packaged and deployed, then the "siteDesign" directory is found at the root of the installation. If the command-line tool is run from the development environment, then the "siteDesign" directory is found in the SDK sub-project. @param installDir Directory where the command-line tool is run from. @return Directory where the site design document is located or null if not found.
[ "Finds", "the", "siteDesign", "directory", "from", "the", "installation", "location", "and", "returns", "it", ".", "If", "the", "command", "-", "line", "tool", "is", "packaged", "and", "deployed", "then", "the", "siteDesign", "directory", "is", "found", "at", ...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java#L203-L220
134,886
GCRC/nunaliit
nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java
PathComputer.computeNunaliitDir
static public File computeNunaliitDir(File installDir) { while( null != installDir ){ // The root of the nunalii2 project contains "nunaliit2-couch-command", // "nunaliit2-couch-sdk" and "nunaliit2-js" boolean commandExists = (new File(installDir, "nunaliit2-couch-command")).exists(); boolean sdkExists = (new File(installDir, "nunaliit2-couch-sdk")).exists(); boolean jsExists = (new File(installDir, "nunaliit2-js")).exists(); if( commandExists && sdkExists && jsExists ){ return installDir; } else { // Go to parent installDir = installDir.getParentFile(); } } return null; }
java
static public File computeNunaliitDir(File installDir) { while( null != installDir ){ // The root of the nunalii2 project contains "nunaliit2-couch-command", // "nunaliit2-couch-sdk" and "nunaliit2-js" boolean commandExists = (new File(installDir, "nunaliit2-couch-command")).exists(); boolean sdkExists = (new File(installDir, "nunaliit2-couch-sdk")).exists(); boolean jsExists = (new File(installDir, "nunaliit2-js")).exists(); if( commandExists && sdkExists && jsExists ){ return installDir; } else { // Go to parent installDir = installDir.getParentFile(); } } return null; }
[ "static", "public", "File", "computeNunaliitDir", "(", "File", "installDir", ")", "{", "while", "(", "null", "!=", "installDir", ")", "{", "// The root of the nunalii2 project contains \"nunaliit2-couch-command\",", "// \"nunaliit2-couch-sdk\" and \"nunaliit2-js\"", "boolean", ...
Given an installation directory, find the root directory for the nunaliit2 project. This makes sense only in the context that the command-line tool is run from a development environment. @param installDir Computed install directory where command-line is run @return Root directory where nunaliit2 project is located, or null if not found.
[ "Given", "an", "installation", "directory", "find", "the", "root", "directory", "for", "the", "nunaliit2", "project", ".", "This", "makes", "sense", "only", "in", "the", "context", "that", "the", "command", "-", "line", "tool", "is", "run", "from", "a", "d...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-command/src/main/java/ca/carleton/gcrc/couch/command/impl/PathComputer.java#L439-L456
134,887
GCRC/nunaliit
nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/Files.java
Files.getDescendantPathNames
static public Set<String> getDescendantPathNames(File dir, boolean includeDirectories) { Set<String> paths = new HashSet<String>(); if( dir.exists() && dir.isDirectory() ) { String[] names = dir.list(); for(String name : names){ File child = new File(dir,name); getPathNames(child, paths, null, includeDirectories); } } return paths; }
java
static public Set<String> getDescendantPathNames(File dir, boolean includeDirectories) { Set<String> paths = new HashSet<String>(); if( dir.exists() && dir.isDirectory() ) { String[] names = dir.list(); for(String name : names){ File child = new File(dir,name); getPathNames(child, paths, null, includeDirectories); } } return paths; }
[ "static", "public", "Set", "<", "String", ">", "getDescendantPathNames", "(", "File", "dir", ",", "boolean", "includeDirectories", ")", "{", "Set", "<", "String", ">", "paths", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "if", "(", "dir", ...
Given a directory, returns a set of strings which are the paths to all elements within the directory. This process recurses through all sub-directories. @param dir The directory to be traversed @param includeDirectories If set, the name of the paths to directories are included in the result. @return A set of paths to all elements in the given directory
[ "Given", "a", "directory", "returns", "a", "set", "of", "strings", "which", "are", "the", "paths", "to", "all", "elements", "within", "the", "directory", ".", "This", "process", "recurses", "through", "all", "sub", "-", "directories", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/Files.java#L85-L95
134,888
GCRC/nunaliit
nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/Files.java
Files.emptyDirectory
static public void emptyDirectory(File dir) throws Exception { String[] fileNames = dir.list(); if( null != fileNames ) { for(String fileName : fileNames){ File file = new File(dir,fileName); if( file.isDirectory() ) { emptyDirectory(file); } boolean deleted = false; try { deleted = file.delete(); } catch(Exception e) { throw new Exception("Unable to delete: "+file.getAbsolutePath(),e); } if( !deleted ){ throw new Exception("Unable to delete: "+file.getAbsolutePath()); } } } }
java
static public void emptyDirectory(File dir) throws Exception { String[] fileNames = dir.list(); if( null != fileNames ) { for(String fileName : fileNames){ File file = new File(dir,fileName); if( file.isDirectory() ) { emptyDirectory(file); } boolean deleted = false; try { deleted = file.delete(); } catch(Exception e) { throw new Exception("Unable to delete: "+file.getAbsolutePath(),e); } if( !deleted ){ throw new Exception("Unable to delete: "+file.getAbsolutePath()); } } } }
[ "static", "public", "void", "emptyDirectory", "(", "File", "dir", ")", "throws", "Exception", "{", "String", "[", "]", "fileNames", "=", "dir", ".", "list", "(", ")", ";", "if", "(", "null", "!=", "fileNames", ")", "{", "for", "(", "String", "fileName"...
Given a directory, removes all the content found in the directory. @param dir The directory to be emptied @throws Exception
[ "Given", "a", "directory", "removes", "all", "the", "content", "found", "in", "the", "directory", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/Files.java#L157-L176
134,889
GCRC/nunaliit
nunaliit2-couch-onUpload/src/main/java/ca/carleton/gcrc/couch/onUpload/mail/MailVetterDailyNotificationTask.java
MailVetterDailyNotificationTask.scheduleTask
static public MailVetterDailyNotificationTask scheduleTask( CouchDesignDocument serverDesignDoc ,MailNotification mailNotification ){ Timer timer = new Timer(); MailVetterDailyNotificationTask installedTask = new MailVetterDailyNotificationTask( timer ,serverDesignDoc ,mailNotification ); Calendar calendar = Calendar.getInstance(); // now Date now = calendar.getTime(); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); Date start = calendar.getTime(); while( start.getTime() < now.getTime() ){ start = new Date( start.getTime() + DAILY_PERIOD ); } if( true ) { timer.schedule(installedTask, start, DAILY_PERIOD); // } else { // This code to test with a shorter period // start = new Date( now.getTime() + (1000*30) ); // timer.schedule(installedTask, start, 1000 * 30); } // Log { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String startString = sdf.format(start); logger.info("Vetter daily notifications set to start at: "+startString); } return installedTask; }
java
static public MailVetterDailyNotificationTask scheduleTask( CouchDesignDocument serverDesignDoc ,MailNotification mailNotification ){ Timer timer = new Timer(); MailVetterDailyNotificationTask installedTask = new MailVetterDailyNotificationTask( timer ,serverDesignDoc ,mailNotification ); Calendar calendar = Calendar.getInstance(); // now Date now = calendar.getTime(); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); Date start = calendar.getTime(); while( start.getTime() < now.getTime() ){ start = new Date( start.getTime() + DAILY_PERIOD ); } if( true ) { timer.schedule(installedTask, start, DAILY_PERIOD); // } else { // This code to test with a shorter period // start = new Date( now.getTime() + (1000*30) ); // timer.schedule(installedTask, start, 1000 * 30); } // Log { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String startString = sdf.format(start); logger.info("Vetter daily notifications set to start at: "+startString); } return installedTask; }
[ "static", "public", "MailVetterDailyNotificationTask", "scheduleTask", "(", "CouchDesignDocument", "serverDesignDoc", ",", "MailNotification", "mailNotification", ")", "{", "Timer", "timer", "=", "new", "Timer", "(", ")", ";", "MailVetterDailyNotificationTask", "installedTa...
24 hours in ms
[ "24", "hours", "in", "ms" ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-onUpload/src/main/java/ca/carleton/gcrc/couch/onUpload/mail/MailVetterDailyNotificationTask.java#L22-L66
134,890
GCRC/nunaliit
nunaliit2-couch-onUpload/src/main/java/ca/carleton/gcrc/couch/onUpload/simplifyGeoms/GeometrySimplificationProcessImpl.java
GeometrySimplificationProcessImpl.simplifyGeometryAtResolution
public Geometry simplifyGeometryAtResolution(Geometry geometry, double resolution) throws Exception { double inverseRes = 1/resolution; double p = Math.log10(inverseRes); double exp = Math.ceil( p ); if( exp < 0 ) exp = 0; double factor = Math.pow(10,exp); Geometry simplifiedGeometry = simplify(geometry, resolution, factor); return simplifiedGeometry; }
java
public Geometry simplifyGeometryAtResolution(Geometry geometry, double resolution) throws Exception { double inverseRes = 1/resolution; double p = Math.log10(inverseRes); double exp = Math.ceil( p ); if( exp < 0 ) exp = 0; double factor = Math.pow(10,exp); Geometry simplifiedGeometry = simplify(geometry, resolution, factor); return simplifiedGeometry; }
[ "public", "Geometry", "simplifyGeometryAtResolution", "(", "Geometry", "geometry", ",", "double", "resolution", ")", "throws", "Exception", "{", "double", "inverseRes", "=", "1", "/", "resolution", ";", "double", "p", "=", "Math", ".", "log10", "(", "inverseRes"...
Accepts a geometry and a resolution. Returns a version of the geometry which is simplified for the given resolution. If the initial geometry is already simplified enough, then return null. @param geometry Geometry to simplify @param resolution Resolution at which the geometry should be simplified @return The simplified geometry. Null, if no simplification is possible. @throws Exception
[ "Accepts", "a", "geometry", "and", "a", "resolution", ".", "Returns", "a", "version", "of", "the", "geometry", "which", "is", "simplified", "for", "the", "given", "resolution", ".", "If", "the", "initial", "geometry", "is", "already", "simplified", "enough", ...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-onUpload/src/main/java/ca/carleton/gcrc/couch/onUpload/simplifyGeoms/GeometrySimplificationProcessImpl.java#L100-L110
134,891
GCRC/nunaliit
nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java
DbWebServlet.performQuery
private void performQuery(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = AuthenticationUtils.getUserFromRequest(request); String tableName = getTableNameFromRequest(request); DbTableAccess tableAccess = DbTableAccess.getAccess(dbSecurity, tableName, new DbUserAdaptor(user)); List<RecordSelector> whereMap = getRecordSelectorsFromRequest(request); List<FieldSelector> selectSpecifiers = getFieldSelectorsFromRequest(request); List<FieldSelector> groupByColumnNames = getGroupByFromRequest(request); List<OrderSpecifier> orderBy = getOrderByList(request); Integer limit = getLimitFromRequest(request); Integer offset = getOffsetFromRequest(request); JSONArray queriedObjects = tableAccess.query( whereMap ,selectSpecifiers ,groupByColumnNames ,orderBy ,limit ,offset ); JSONObject obj = new JSONObject(); obj.put("queried", queriedObjects); sendJsonResponse(response, obj); }
java
private void performQuery(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = AuthenticationUtils.getUserFromRequest(request); String tableName = getTableNameFromRequest(request); DbTableAccess tableAccess = DbTableAccess.getAccess(dbSecurity, tableName, new DbUserAdaptor(user)); List<RecordSelector> whereMap = getRecordSelectorsFromRequest(request); List<FieldSelector> selectSpecifiers = getFieldSelectorsFromRequest(request); List<FieldSelector> groupByColumnNames = getGroupByFromRequest(request); List<OrderSpecifier> orderBy = getOrderByList(request); Integer limit = getLimitFromRequest(request); Integer offset = getOffsetFromRequest(request); JSONArray queriedObjects = tableAccess.query( whereMap ,selectSpecifiers ,groupByColumnNames ,orderBy ,limit ,offset ); JSONObject obj = new JSONObject(); obj.put("queried", queriedObjects); sendJsonResponse(response, obj); }
[ "private", "void", "performQuery", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "Exception", "{", "User", "user", "=", "AuthenticationUtils", ".", "getUserFromRequest", "(", "request", ")", ";", "String", "tableName", ...
Perform a SQL query of a specified table, that must be accessible via dbSec. The http parms must include: table=<tableName> specifying a valid and accessible table. the http parms may include one or more (each) of: select=<e1>[,<e2>[,...]] where each <ei> is the name of a valid and accessible column or is an expression of one of the forms: sum(<c>), max(<c>), min(<c>) where <c> is the name of a valid and accessible column. groupBy=<c1>[,<c2>[,...]] where each <ci> is the name of a valid and accessible column. where=<whereclause> where multiple where clauses are combined using logical AND and <whereClause> is of the form: <c>,<comparator> where <c> is the name of a valid and accessible column, and <comparator> is one of: eq(<value>) where value is a valid comparison value for the column's data type. ne(<value>) where value is a valid comparison value for the column's data type. ge(<value>) where value is a valid comparison value for the column's data type. le(<value>) where value is a valid comparison value for the column's data type. gt(<value>) where value is a valid comparison value for the column's data type. lt(<value>) where value is a valid comparison value for the column's data type. isNull. isNotNull. @param request http request containing the query parameters. @param response http response to be sent. @throws Exception (for a variety of reasons detected while parsing and validating the http parms).
[ "Perform", "a", "SQL", "query", "of", "a", "specified", "table", "that", "must", "be", "accessible", "via", "dbSec", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java#L231-L257
134,892
GCRC/nunaliit
nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java
DbWebServlet.performMultiQuery
private void performMultiQuery(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = AuthenticationUtils.getUserFromRequest(request); String[] queriesStrings = request.getParameterValues("queries"); if( 1 != queriesStrings.length ) { throw new Exception("Parameter 'queries' must be specified exactly oncce"); } // Create list of Query instances List<Query> queries = parseQueriesJson(queriesStrings[0]); // Perform queries JSONObject result = new JSONObject(); { Map<String, DbTableAccess> tableAccessCache = new HashMap<String, DbTableAccess>(); for(Query query : queries) { String tableName = query.getTableName(); List<RecordSelector> whereMap = query.getWhereExpressions(); List<FieldSelector> fieldSelectors = query.getFieldSelectors(); List<FieldSelector> groupByColumnNames = query.getGroupByColumnNames(); List<OrderSpecifier> orderSpecifiers = query.getOrderBySpecifiers(); Integer limit = query.getLimit(); Integer offset = query.getOffset(); DbTableAccess tableAccess = tableAccessCache.get(tableName); if( null == tableAccess ) { tableAccess = DbTableAccess.getAccess(dbSecurity, tableName, new DbUserAdaptor(user)); tableAccessCache.put(tableName, tableAccess); } try { JSONArray queriedObjects = tableAccess.query( whereMap ,fieldSelectors ,groupByColumnNames ,orderSpecifiers ,limit ,offset ); result.put(query.getQueryKey(), queriedObjects); } catch(Exception e) { result.put(query.getQueryKey(), errorToJson(e)); } } } sendJsonResponse(response, result); }
java
private void performMultiQuery(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = AuthenticationUtils.getUserFromRequest(request); String[] queriesStrings = request.getParameterValues("queries"); if( 1 != queriesStrings.length ) { throw new Exception("Parameter 'queries' must be specified exactly oncce"); } // Create list of Query instances List<Query> queries = parseQueriesJson(queriesStrings[0]); // Perform queries JSONObject result = new JSONObject(); { Map<String, DbTableAccess> tableAccessCache = new HashMap<String, DbTableAccess>(); for(Query query : queries) { String tableName = query.getTableName(); List<RecordSelector> whereMap = query.getWhereExpressions(); List<FieldSelector> fieldSelectors = query.getFieldSelectors(); List<FieldSelector> groupByColumnNames = query.getGroupByColumnNames(); List<OrderSpecifier> orderSpecifiers = query.getOrderBySpecifiers(); Integer limit = query.getLimit(); Integer offset = query.getOffset(); DbTableAccess tableAccess = tableAccessCache.get(tableName); if( null == tableAccess ) { tableAccess = DbTableAccess.getAccess(dbSecurity, tableName, new DbUserAdaptor(user)); tableAccessCache.put(tableName, tableAccess); } try { JSONArray queriedObjects = tableAccess.query( whereMap ,fieldSelectors ,groupByColumnNames ,orderSpecifiers ,limit ,offset ); result.put(query.getQueryKey(), queriedObjects); } catch(Exception e) { result.put(query.getQueryKey(), errorToJson(e)); } } } sendJsonResponse(response, result); }
[ "private", "void", "performMultiQuery", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "throws", "Exception", "{", "User", "user", "=", "AuthenticationUtils", ".", "getUserFromRequest", "(", "request", ")", ";", "String", "[", "]"...
Perform multiple SQL queries via dbSec. queries = { key1: { table: <table name> ,select: [ <selectExpression> ,... ] ,where: [ '<columnName>,<comparator>' ,'<columnName>,<comparator>' ,... ] ,groupBy: [ <columnName> ,... ] } ,key2: { ... } , ... } <selectExpression> : <columnName> sum(<columnName>) min(<columnName>) max(<columnName>) <comparator> : eq(<value>) where value is a valid comparison value for the column's data type. ne(<value>) where value is a valid comparison value for the column's data type. ge(<value>) where value is a valid comparison value for the column's data type. le(<value>) where value is a valid comparison value for the column's data type. gt(<value>) where value is a valid comparison value for the column's data type. lt(<value>) where value is a valid comparison value for the column's data type. isNull. isNotNull. response = { key1: [ { c1: 1, c2: 2 } ,{ c1: 4, c2: 5 } ,... ] ,key2: { error: 'Error message' } ,... } @param request http request containing the query parameters. @param response http response to be sent. @throws Exception (for a variety of reasons detected while parsing and validating the http parms).
[ "Perform", "multiple", "SQL", "queries", "via", "dbSec", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java#L316-L363
134,893
GCRC/nunaliit
nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java
DbWebServlet.getFieldSelectorsFromRequest
private List<FieldSelector> getFieldSelectorsFromRequest(HttpServletRequest request) throws Exception { String[] fieldSelectorStrings = request.getParameterValues("select"); if( null == fieldSelectorStrings ) { return null; } if( 0 == fieldSelectorStrings.length ) { return null; } List<FieldSelector> result = new Vector<FieldSelector>(); for(String fieldSelectorString : fieldSelectorStrings) { FieldSelector fieldSelector = parseFieldSelectorString(fieldSelectorString); result.add(fieldSelector); } return result; }
java
private List<FieldSelector> getFieldSelectorsFromRequest(HttpServletRequest request) throws Exception { String[] fieldSelectorStrings = request.getParameterValues("select"); if( null == fieldSelectorStrings ) { return null; } if( 0 == fieldSelectorStrings.length ) { return null; } List<FieldSelector> result = new Vector<FieldSelector>(); for(String fieldSelectorString : fieldSelectorStrings) { FieldSelector fieldSelector = parseFieldSelectorString(fieldSelectorString); result.add(fieldSelector); } return result; }
[ "private", "List", "<", "FieldSelector", ">", "getFieldSelectorsFromRequest", "(", "HttpServletRequest", "request", ")", "throws", "Exception", "{", "String", "[", "]", "fieldSelectorStrings", "=", "request", ".", "getParameterValues", "(", "\"select\"", ")", ";", "...
Return a list of column names to be included in a select clause. @param request http request containing a (possibly empty) set of 'select' parms. Each select parm may contain a comma-separated list of column names. @return List of column names specified by those select parameters @throws Exception
[ "Return", "a", "list", "of", "column", "names", "to", "be", "included", "in", "a", "select", "clause", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java#L719-L736
134,894
GCRC/nunaliit
nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java
DbWebServlet.getOrderByList
private List<OrderSpecifier> getOrderByList(HttpServletRequest request) throws Exception { String[] orderByStrings = request.getParameterValues("orderBy"); if( null == orderByStrings ) { return null; } if( 0 == orderByStrings.length ) { return null; } List<OrderSpecifier> result = new Vector<OrderSpecifier>(); for(String orderByString : orderByStrings) { OrderSpecifier orderSpecifier = parseOrderSpecifier(orderByString); result.add(orderSpecifier); } return result; }
java
private List<OrderSpecifier> getOrderByList(HttpServletRequest request) throws Exception { String[] orderByStrings = request.getParameterValues("orderBy"); if( null == orderByStrings ) { return null; } if( 0 == orderByStrings.length ) { return null; } List<OrderSpecifier> result = new Vector<OrderSpecifier>(); for(String orderByString : orderByStrings) { OrderSpecifier orderSpecifier = parseOrderSpecifier(orderByString); result.add(orderSpecifier); } return result; }
[ "private", "List", "<", "OrderSpecifier", ">", "getOrderByList", "(", "HttpServletRequest", "request", ")", "throws", "Exception", "{", "String", "[", "]", "orderByStrings", "=", "request", ".", "getParameterValues", "(", "\"orderBy\"", ")", ";", "if", "(", "nul...
Return a list of order specifiers found in request @param request http request containing a (possibly empty) set of 'orderBy' parms. @return List of order specifiers given by those orderBy parameters @throws Exception
[ "Return", "a", "list", "of", "order", "specifiers", "found", "in", "request" ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-dbWeb/src/main/java/ca/carleton/gcrc/dbWeb/DbWebServlet.java#L857-L874
134,895
GCRC/nunaliit
nunaliit2-dbSec/src/main/java/ca/carleton/gcrc/dbSec/DbSecurity.java
DbSecurity.getTableSchemaFromName
public TableSchema getTableSchemaFromName(String tableName, DbUser user) throws Exception { List<String> tableNames = new Vector<String>(); tableNames.add(tableName); Map<String,TableSchemaImpl> nameToTableMap = getTableDataFromGroups(user,tableNames); if( false == nameToTableMap.containsKey(tableName) ) { throw new Exception("A table named '"+tableName+"' does not exist or is not available"); } return nameToTableMap.get(tableName); }
java
public TableSchema getTableSchemaFromName(String tableName, DbUser user) throws Exception { List<String> tableNames = new Vector<String>(); tableNames.add(tableName); Map<String,TableSchemaImpl> nameToTableMap = getTableDataFromGroups(user,tableNames); if( false == nameToTableMap.containsKey(tableName) ) { throw new Exception("A table named '"+tableName+"' does not exist or is not available"); } return nameToTableMap.get(tableName); }
[ "public", "TableSchema", "getTableSchemaFromName", "(", "String", "tableName", ",", "DbUser", "user", ")", "throws", "Exception", "{", "List", "<", "String", ">", "tableNames", "=", "new", "Vector", "<", "String", ">", "(", ")", ";", "tableNames", ".", "add"...
Computes from the database the access to a table for a given user. In this call, a user is represented by the set of groups it belongs to. @param tableName Name of the table to be queried @param user User requesting access to the schema @return An object that represents available access to a table. Null if the table not available. @throws Exception
[ "Computes", "from", "the", "database", "the", "access", "to", "a", "table", "for", "a", "given", "user", ".", "In", "this", "call", "a", "user", "is", "represented", "by", "the", "set", "of", "groups", "it", "belongs", "to", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-dbSec/src/main/java/ca/carleton/gcrc/dbSec/DbSecurity.java#L87-L98
134,896
GCRC/nunaliit
nunaliit2-dbSec/src/main/java/ca/carleton/gcrc/dbSec/DbSecurity.java
DbSecurity.getAvailableTablesFromGroups
public List<TableSchema> getAvailableTablesFromGroups(DbUser user) throws Exception { Map<String,TableSchemaImpl> nameToTableMap = getTableDataFromGroups(user,null); List<TableSchema> result = new Vector<TableSchema>(); result.addAll(nameToTableMap.values()); return result; }
java
public List<TableSchema> getAvailableTablesFromGroups(DbUser user) throws Exception { Map<String,TableSchemaImpl> nameToTableMap = getTableDataFromGroups(user,null); List<TableSchema> result = new Vector<TableSchema>(); result.addAll(nameToTableMap.values()); return result; }
[ "public", "List", "<", "TableSchema", ">", "getAvailableTablesFromGroups", "(", "DbUser", "user", ")", "throws", "Exception", "{", "Map", "<", "String", ",", "TableSchemaImpl", ">", "nameToTableMap", "=", "getTableDataFromGroups", "(", "user", ",", "null", ")", ...
Computes from the database the access to all tables for a given user. In this call, a user is represented by the set of groups it belongs to. @param user User requesting access to the database @return An list that represents available access to all visible tables. @throws Exception
[ "Computes", "from", "the", "database", "the", "access", "to", "all", "tables", "for", "a", "given", "user", ".", "In", "this", "call", "a", "user", "is", "represented", "by", "the", "set", "of", "groups", "it", "belongs", "to", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-dbSec/src/main/java/ca/carleton/gcrc/dbSec/DbSecurity.java#L107-L113
134,897
GCRC/nunaliit
nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/CommandUtils.java
CommandUtils.breakUpCommand
static public List<String> breakUpCommand(String command) throws Exception{ try { List<String> commandTokens = new Vector<String>(); StringBuilder currentToken = null; boolean isTokenQuoted = false; StringReader sr = new StringReader(command); int b = sr.read(); while( b >= 0 ){ char c = (char)b; if( null == currentToken ){ // At token is not in progress // Skipping spaces if( ' ' == c || '\t' == c ){ } else if( '"' == c ) { // Starting a quoted token currentToken = new StringBuilder(); //currentToken.append(c); isTokenQuoted = true; } else { // Starting a non-quoted token currentToken = new StringBuilder(); currentToken.append(c); isTokenQuoted = false; } } else if( isTokenQuoted ) { // A quoted token is in progress. It ends with a quote if( '"' == c ){ //currentToken.append(c); String token = currentToken.toString(); currentToken = null; commandTokens.add(token); } else { // Continuation currentToken.append(c); } } else { // A non-quoted token is in progress. It ends with a space if( ' ' == c || '\t' == c ){ String token = currentToken.toString(); currentToken = null; commandTokens.add(token); } else { // Continuation currentToken.append(c); } } b = sr.read(); } if( null != currentToken ){ String token = currentToken.toString(); commandTokens.add(token); } return commandTokens; } catch (IOException e) { throw new Exception("Error while breaking up command into tokens: "+command,e); } }
java
static public List<String> breakUpCommand(String command) throws Exception{ try { List<String> commandTokens = new Vector<String>(); StringBuilder currentToken = null; boolean isTokenQuoted = false; StringReader sr = new StringReader(command); int b = sr.read(); while( b >= 0 ){ char c = (char)b; if( null == currentToken ){ // At token is not in progress // Skipping spaces if( ' ' == c || '\t' == c ){ } else if( '"' == c ) { // Starting a quoted token currentToken = new StringBuilder(); //currentToken.append(c); isTokenQuoted = true; } else { // Starting a non-quoted token currentToken = new StringBuilder(); currentToken.append(c); isTokenQuoted = false; } } else if( isTokenQuoted ) { // A quoted token is in progress. It ends with a quote if( '"' == c ){ //currentToken.append(c); String token = currentToken.toString(); currentToken = null; commandTokens.add(token); } else { // Continuation currentToken.append(c); } } else { // A non-quoted token is in progress. It ends with a space if( ' ' == c || '\t' == c ){ String token = currentToken.toString(); currentToken = null; commandTokens.add(token); } else { // Continuation currentToken.append(c); } } b = sr.read(); } if( null != currentToken ){ String token = currentToken.toString(); commandTokens.add(token); } return commandTokens; } catch (IOException e) { throw new Exception("Error while breaking up command into tokens: "+command,e); } }
[ "static", "public", "List", "<", "String", ">", "breakUpCommand", "(", "String", "command", ")", "throws", "Exception", "{", "try", "{", "List", "<", "String", ">", "commandTokens", "=", "new", "Vector", "<", "String", ">", "(", ")", ";", "StringBuilder", ...
Takes a single line command as a string and breaks it up in tokens acceptable for the java.lang.ProcessBuilder.ProcessBuilder @param command Complete command as a single string @return Array of strings that are acceptable tokens for ProcessBuilder @throws Exception
[ "Takes", "a", "single", "line", "command", "as", "a", "string", "and", "breaks", "it", "up", "in", "tokens", "acceptable", "for", "the", "java", ".", "lang", ".", "ProcessBuilder", ".", "ProcessBuilder" ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/CommandUtils.java#L29-L97
134,898
GCRC/nunaliit
nunaliit2-auth-common/src/main/java/ca/carleton/gcrc/auth/common/UserRepositoryDb.java
UserRepositoryDb.executeStatementToUser
private UserAndPassword executeStatementToUser(PreparedStatement preparedStmt) throws Exception { if( preparedStmt.execute() ) { // There's a ResultSet to be had ResultSet rs = preparedStmt.getResultSet(); ResultSetMetaData rsmd = rs.getMetaData(); int numColumns = rsmd.getColumnCount(); if( numColumns != 5 ) { throw new Exception("Unexpected number of columns returned"); } if( false == rs.next() ) { throw new Exception("Result set empty"); } int userId = JdbcUtils.extractIntResult(rs,rsmd,1); String email = JdbcUtils.extractStringResult(rs,rsmd,2); String displayName = JdbcUtils.extractStringResult(rs,rsmd,3); String dbPassword = JdbcUtils.extractStringResult(rs,rsmd,4); int groupId = JdbcUtils.extractIntResult(rs,rsmd,5); if( true == rs.next() ) { throw new Exception("Result set had more than one result"); } // Return user UserAndPassword user = new UserAndPassword(); user.setId(userId); user.setUser(email); user.setDisplayName(displayName); user.setPassword(dbPassword); if( 0 == groupId ) { user.setAnonymous(true); } else if( 1 == groupId ) { user.setAdmin(true); } Vector<Integer> groups = new Vector<Integer>(); groups.add( new Integer(groupId) ); user.setGroups(groups); return user; } else { // indicates an update count or no results - this must be no results throw new Exception("Query returned no results"); } }
java
private UserAndPassword executeStatementToUser(PreparedStatement preparedStmt) throws Exception { if( preparedStmt.execute() ) { // There's a ResultSet to be had ResultSet rs = preparedStmt.getResultSet(); ResultSetMetaData rsmd = rs.getMetaData(); int numColumns = rsmd.getColumnCount(); if( numColumns != 5 ) { throw new Exception("Unexpected number of columns returned"); } if( false == rs.next() ) { throw new Exception("Result set empty"); } int userId = JdbcUtils.extractIntResult(rs,rsmd,1); String email = JdbcUtils.extractStringResult(rs,rsmd,2); String displayName = JdbcUtils.extractStringResult(rs,rsmd,3); String dbPassword = JdbcUtils.extractStringResult(rs,rsmd,4); int groupId = JdbcUtils.extractIntResult(rs,rsmd,5); if( true == rs.next() ) { throw new Exception("Result set had more than one result"); } // Return user UserAndPassword user = new UserAndPassword(); user.setId(userId); user.setUser(email); user.setDisplayName(displayName); user.setPassword(dbPassword); if( 0 == groupId ) { user.setAnonymous(true); } else if( 1 == groupId ) { user.setAdmin(true); } Vector<Integer> groups = new Vector<Integer>(); groups.add( new Integer(groupId) ); user.setGroups(groups); return user; } else { // indicates an update count or no results - this must be no results throw new Exception("Query returned no results"); } }
[ "private", "UserAndPassword", "executeStatementToUser", "(", "PreparedStatement", "preparedStmt", ")", "throws", "Exception", "{", "if", "(", "preparedStmt", ".", "execute", "(", ")", ")", "{", "// There's a ResultSet to be had", "ResultSet", "rs", "=", "preparedStmt", ...
This method executes a prepared SQL statement against the user table and returns a User. @param stmt Prepared SQL statement to execute @return An instance of User based on the information found in the database @throws Exception
[ "This", "method", "executes", "a", "prepared", "SQL", "statement", "against", "the", "user", "table", "and", "returns", "a", "User", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-auth-common/src/main/java/ca/carleton/gcrc/auth/common/UserRepositoryDb.java#L126-L171
134,899
GCRC/nunaliit
nunaliit2-geom/src/main/java/ca/carleton/gcrc/geom/wkt/WktWriter.java
WktWriter.writeNumber
private void writeNumber(PrintWriter pw, NumberFormat numFormat, Number num){ if( num.doubleValue() == Math.round(num.doubleValue()) ){ // Integer if( null != numFormat ){ pw.print( numFormat.format(num.intValue()) ); } else { pw.print( num.intValue() ); } } else { if( null != numFormat ){ pw.print( numFormat.format(num) ); } else { pw.print( num ); } } }
java
private void writeNumber(PrintWriter pw, NumberFormat numFormat, Number num){ if( num.doubleValue() == Math.round(num.doubleValue()) ){ // Integer if( null != numFormat ){ pw.print( numFormat.format(num.intValue()) ); } else { pw.print( num.intValue() ); } } else { if( null != numFormat ){ pw.print( numFormat.format(num) ); } else { pw.print( num ); } } }
[ "private", "void", "writeNumber", "(", "PrintWriter", "pw", ",", "NumberFormat", "numFormat", ",", "Number", "num", ")", "{", "if", "(", "num", ".", "doubleValue", "(", ")", "==", "Math", ".", "round", "(", "num", ".", "doubleValue", "(", ")", ")", ")"...
Writes a number to the print writer. If the number is an integer, do not write the decimal points. @param pw @param num
[ "Writes", "a", "number", "to", "the", "print", "writer", ".", "If", "the", "number", "is", "an", "integer", "do", "not", "write", "the", "decimal", "points", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-geom/src/main/java/ca/carleton/gcrc/geom/wkt/WktWriter.java#L284-L300