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
148,100
fuinorg/objects4j
src/main/java/org/fuin/objects4j/vo/LocaleConverter.java
LocaleConverter.asLocale
public static Locale asLocale(final String value) { final Locale locale; final int p = value.indexOf("__"); if (p > -1) { locale = new Locale(value.substring(0, p), null, value.substring(p + 2)); } else { final StringTokenizer tok = new StringTokenizer(value, "_"); if (tok.countTokens() == 1) { locale = new Locale(value); } else if (tok.countTokens() == 2) { locale = new Locale(tok.nextToken(), tok.nextToken()); } else if (tok.countTokens() == 3) { locale = new Locale(tok.nextToken(), tok.nextToken(), tok.nextToken()); } else { throw new IllegalArgumentException("Cannot convert: '" + value + "'"); } } return locale; }
java
public static Locale asLocale(final String value) { final Locale locale; final int p = value.indexOf("__"); if (p > -1) { locale = new Locale(value.substring(0, p), null, value.substring(p + 2)); } else { final StringTokenizer tok = new StringTokenizer(value, "_"); if (tok.countTokens() == 1) { locale = new Locale(value); } else if (tok.countTokens() == 2) { locale = new Locale(tok.nextToken(), tok.nextToken()); } else if (tok.countTokens() == 3) { locale = new Locale(tok.nextToken(), tok.nextToken(), tok.nextToken()); } else { throw new IllegalArgumentException("Cannot convert: '" + value + "'"); } } return locale; }
[ "public", "static", "Locale", "asLocale", "(", "final", "String", "value", ")", "{", "final", "Locale", "locale", ";", "final", "int", "p", "=", "value", ".", "indexOf", "(", "\"__\"", ")", ";", "if", "(", "p", ">", "-", "1", ")", "{", "locale", "=", "new", "Locale", "(", "value", ".", "substring", "(", "0", ",", "p", ")", ",", "null", ",", "value", ".", "substring", "(", "p", "+", "2", ")", ")", ";", "}", "else", "{", "final", "StringTokenizer", "tok", "=", "new", "StringTokenizer", "(", "value", ",", "\"_\"", ")", ";", "if", "(", "tok", ".", "countTokens", "(", ")", "==", "1", ")", "{", "locale", "=", "new", "Locale", "(", "value", ")", ";", "}", "else", "if", "(", "tok", ".", "countTokens", "(", ")", "==", "2", ")", "{", "locale", "=", "new", "Locale", "(", "tok", ".", "nextToken", "(", ")", ",", "tok", ".", "nextToken", "(", ")", ")", ";", "}", "else", "if", "(", "tok", ".", "countTokens", "(", ")", "==", "3", ")", "{", "locale", "=", "new", "Locale", "(", "tok", ".", "nextToken", "(", ")", ",", "tok", ".", "nextToken", "(", ")", ",", "tok", ".", "nextToken", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Cannot convert: '\"", "+", "value", "+", "\"'\"", ")", ";", "}", "}", "return", "locale", ";", "}" ]
Returns the given string as locale. The locale is NOT checked against the Java list of avilable locales. @param value Value to convert into a locale. @return Locale.
[ "Returns", "the", "given", "string", "as", "locale", ".", "The", "locale", "is", "NOT", "checked", "against", "the", "Java", "list", "of", "avilable", "locales", "." ]
e7f278b5bae073ebb6a76053650571c718f36246
https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/vo/LocaleConverter.java#L67-L85
148,101
fuinorg/objects4j
src/main/java/org/fuin/objects4j/vo/LocaleConverter.java
LocaleConverter.validLocale
public static boolean validLocale(final Locale locale) { for (final Locale found : Locale.getAvailableLocales()) { if (found.equals(locale)) { return true; } } return false; }
java
public static boolean validLocale(final Locale locale) { for (final Locale found : Locale.getAvailableLocales()) { if (found.equals(locale)) { return true; } } return false; }
[ "public", "static", "boolean", "validLocale", "(", "final", "Locale", "locale", ")", "{", "for", "(", "final", "Locale", "found", ":", "Locale", ".", "getAvailableLocales", "(", ")", ")", "{", "if", "(", "found", ".", "equals", "(", "locale", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Verifies if the give locale is in the Java list of known locales. @param locale Locale to verify. @return TRUE if the locale is known else FALSE.
[ "Verifies", "if", "the", "give", "locale", "is", "in", "the", "Java", "list", "of", "known", "locales", "." ]
e7f278b5bae073ebb6a76053650571c718f36246
https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/vo/LocaleConverter.java#L95-L102
148,102
nuun-io/kernel
core/src/main/java/io/nuun/kernel/core/NuunCore.java
NuunCore.createKernel
public static Kernel createKernel(KernelConfiguration configuration) { KernelCoreFactory factory = new KernelCoreFactory(); return factory.create(configuration); }
java
public static Kernel createKernel(KernelConfiguration configuration) { KernelCoreFactory factory = new KernelCoreFactory(); return factory.create(configuration); }
[ "public", "static", "Kernel", "createKernel", "(", "KernelConfiguration", "configuration", ")", "{", "KernelCoreFactory", "factory", "=", "new", "KernelCoreFactory", "(", ")", ";", "return", "factory", ".", "create", "(", "configuration", ")", ";", "}" ]
Creates a kernel with the given configuration. @param configuration the kernel configuration @return the kernel
[ "Creates", "a", "kernel", "with", "the", "given", "configuration", "." ]
116a7664fe2a9323e280574803d273699a333732
https://github.com/nuun-io/kernel/blob/116a7664fe2a9323e280574803d273699a333732/core/src/main/java/io/nuun/kernel/core/NuunCore.java#L48-L52
148,103
projectodd/wunderboss-release
web-undertow/src/main/java/org/projectodd/wunderboss/web/undertow/async/websocket/UndertowWebsocket.java
UndertowWebsocket.toArray
protected static byte[] toArray(ByteBuffer... payload) { if (payload.length == 1) { ByteBuffer buf = payload[0]; if (buf.hasArray() && buf.arrayOffset() == 0 && buf.position() == 0) { return buf.array(); } } int size = (int) Buffers.remaining(payload); byte[] data = new byte[size]; for (ByteBuffer buf : payload) { buf.get(data); } return data; }
java
protected static byte[] toArray(ByteBuffer... payload) { if (payload.length == 1) { ByteBuffer buf = payload[0]; if (buf.hasArray() && buf.arrayOffset() == 0 && buf.position() == 0) { return buf.array(); } } int size = (int) Buffers.remaining(payload); byte[] data = new byte[size]; for (ByteBuffer buf : payload) { buf.get(data); } return data; }
[ "protected", "static", "byte", "[", "]", "toArray", "(", "ByteBuffer", "...", "payload", ")", "{", "if", "(", "payload", ".", "length", "==", "1", ")", "{", "ByteBuffer", "buf", "=", "payload", "[", "0", "]", ";", "if", "(", "buf", ".", "hasArray", "(", ")", "&&", "buf", ".", "arrayOffset", "(", ")", "==", "0", "&&", "buf", ".", "position", "(", ")", "==", "0", ")", "{", "return", "buf", ".", "array", "(", ")", ";", "}", "}", "int", "size", "=", "(", "int", ")", "Buffers", ".", "remaining", "(", "payload", ")", ";", "byte", "[", "]", "data", "=", "new", "byte", "[", "size", "]", ";", "for", "(", "ByteBuffer", "buf", ":", "payload", ")", "{", "buf", ".", "get", "(", "data", ")", ";", "}", "return", "data", ";", "}" ]
Lifted from Undertow's FrameHandler.java
[ "Lifted", "from", "Undertow", "s", "FrameHandler", ".", "java" ]
f67c68e80c5798169e3a9b2015e278239dbf005d
https://github.com/projectodd/wunderboss-release/blob/f67c68e80c5798169e3a9b2015e278239dbf005d/web-undertow/src/main/java/org/projectodd/wunderboss/web/undertow/async/websocket/UndertowWebsocket.java#L120-L133
148,104
fuinorg/objects4j
src/main/java/org/fuin/objects4j/vo/HourRange.java
HourRange.overlaps
public final boolean overlaps(@NotNull final HourRange other) { Contract.requireArgNotNull("other", other); if (this.equals(other)) { return true; } final int otherFrom = other.from.toMinutes(); final int thisFrom = from.toMinutes(); final int otherTo = other.to.toMinutes(); final int thisTo = to.toMinutes(); if (otherFrom <= thisTo && otherFrom >= thisFrom) { return true; } if (otherTo <= thisTo && otherTo >= thisFrom) { return true; } if (thisFrom <= otherTo && thisFrom >= otherFrom) { return true; } return (thisTo <= otherTo && thisTo >= otherFrom); }
java
public final boolean overlaps(@NotNull final HourRange other) { Contract.requireArgNotNull("other", other); if (this.equals(other)) { return true; } final int otherFrom = other.from.toMinutes(); final int thisFrom = from.toMinutes(); final int otherTo = other.to.toMinutes(); final int thisTo = to.toMinutes(); if (otherFrom <= thisTo && otherFrom >= thisFrom) { return true; } if (otherTo <= thisTo && otherTo >= thisFrom) { return true; } if (thisFrom <= otherTo && thisFrom >= otherFrom) { return true; } return (thisTo <= otherTo && thisTo >= otherFrom); }
[ "public", "final", "boolean", "overlaps", "(", "@", "NotNull", "final", "HourRange", "other", ")", "{", "Contract", ".", "requireArgNotNull", "(", "\"other\"", ",", "other", ")", ";", "if", "(", "this", ".", "equals", "(", "other", ")", ")", "{", "return", "true", ";", "}", "final", "int", "otherFrom", "=", "other", ".", "from", ".", "toMinutes", "(", ")", ";", "final", "int", "thisFrom", "=", "from", ".", "toMinutes", "(", ")", ";", "final", "int", "otherTo", "=", "other", ".", "to", ".", "toMinutes", "(", ")", ";", "final", "int", "thisTo", "=", "to", ".", "toMinutes", "(", ")", ";", "if", "(", "otherFrom", "<=", "thisTo", "&&", "otherFrom", ">=", "thisFrom", ")", "{", "return", "true", ";", "}", "if", "(", "otherTo", "<=", "thisTo", "&&", "otherTo", ">=", "thisFrom", ")", "{", "return", "true", ";", "}", "if", "(", "thisFrom", "<=", "otherTo", "&&", "thisFrom", ">=", "otherFrom", ")", "{", "return", "true", ";", "}", "return", "(", "thisTo", "<=", "otherTo", "&&", "thisTo", ">=", "otherFrom", ")", ";", "}" ]
Determines if this range and the given range overlap. @param other Range to compare with. @return {@literal true} if the two ranges overlap, else {@literal false}.
[ "Determines", "if", "this", "range", "and", "the", "given", "range", "overlap", "." ]
e7f278b5bae073ebb6a76053650571c718f36246
https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/vo/HourRange.java#L166-L185
148,105
fuinorg/objects4j
src/main/java/org/fuin/objects4j/vo/HourRange.java
HourRange.isValid
public static boolean isValid(@Nullable final String hourRange) { if (hourRange == null) { return true; } final int p = hourRange.indexOf('-'); if (p != 5) { return false; } final String fromStr = hourRange.substring(0, 5); final String toStr = hourRange.substring(6); if (!(Hour.isValid(fromStr) && Hour.isValid(toStr))) { return false; } final Hour from = new Hour(fromStr); final Hour to = new Hour(toStr); if (from.equals(to)) { return false; } if (from.equals(new Hour(24, 0))) { return false; } return !to.equals(new Hour(0, 0)); }
java
public static boolean isValid(@Nullable final String hourRange) { if (hourRange == null) { return true; } final int p = hourRange.indexOf('-'); if (p != 5) { return false; } final String fromStr = hourRange.substring(0, 5); final String toStr = hourRange.substring(6); if (!(Hour.isValid(fromStr) && Hour.isValid(toStr))) { return false; } final Hour from = new Hour(fromStr); final Hour to = new Hour(toStr); if (from.equals(to)) { return false; } if (from.equals(new Hour(24, 0))) { return false; } return !to.equals(new Hour(0, 0)); }
[ "public", "static", "boolean", "isValid", "(", "@", "Nullable", "final", "String", "hourRange", ")", "{", "if", "(", "hourRange", "==", "null", ")", "{", "return", "true", ";", "}", "final", "int", "p", "=", "hourRange", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "p", "!=", "5", ")", "{", "return", "false", ";", "}", "final", "String", "fromStr", "=", "hourRange", ".", "substring", "(", "0", ",", "5", ")", ";", "final", "String", "toStr", "=", "hourRange", ".", "substring", "(", "6", ")", ";", "if", "(", "!", "(", "Hour", ".", "isValid", "(", "fromStr", ")", "&&", "Hour", ".", "isValid", "(", "toStr", ")", ")", ")", "{", "return", "false", ";", "}", "final", "Hour", "from", "=", "new", "Hour", "(", "fromStr", ")", ";", "final", "Hour", "to", "=", "new", "Hour", "(", "toStr", ")", ";", "if", "(", "from", ".", "equals", "(", "to", ")", ")", "{", "return", "false", ";", "}", "if", "(", "from", ".", "equals", "(", "new", "Hour", "(", "24", ",", "0", ")", ")", ")", "{", "return", "false", ";", "}", "return", "!", "to", ".", "equals", "(", "new", "Hour", "(", "0", ",", "0", ")", ")", ";", "}" ]
Verifies if the string is a valid hour range. @param hourRange Hour range string to test. @return {@literal true} if the string is a valid range, else {@literal false}.
[ "Verifies", "if", "the", "string", "is", "a", "valid", "hour", "range", "." ]
e7f278b5bae073ebb6a76053650571c718f36246
https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/vo/HourRange.java#L266-L288
148,106
RestComm/jain-slee.xcap
enablers/xdm-client/sbb/src/main/java/org/restcomm/slee/enabler/xdmc/XDMClientChildSbb.java
XDMClientChildSbb.onDeleteResponseEvent
public void onDeleteResponseEvent(ResponseEvent event, ActivityContextInterface aci) { if (event.getException() != null) { if (tracer.isInfoEnabled()) { tracer.info("Failed to delete " + event.getURI(), event.getException()); } getParent().deleteResponse(event.getURI(), 500, null, null); } else { final XcapResponse response = event.getResponse(); if (tracer.isInfoEnabled()) { if (response.getCode() == 200) { tracer.info("Deleted " + event.getURI() + ". ETag:" + response.getETag()); } else { tracer.info("Failed to delete " + event.getURI() + ". Response: " + response); } } getParent().deleteResponse(event.getURI(), response.getCode(), response.getEntity().getContentAsString(), response.getETag()); } }
java
public void onDeleteResponseEvent(ResponseEvent event, ActivityContextInterface aci) { if (event.getException() != null) { if (tracer.isInfoEnabled()) { tracer.info("Failed to delete " + event.getURI(), event.getException()); } getParent().deleteResponse(event.getURI(), 500, null, null); } else { final XcapResponse response = event.getResponse(); if (tracer.isInfoEnabled()) { if (response.getCode() == 200) { tracer.info("Deleted " + event.getURI() + ". ETag:" + response.getETag()); } else { tracer.info("Failed to delete " + event.getURI() + ". Response: " + response); } } getParent().deleteResponse(event.getURI(), response.getCode(), response.getEntity().getContentAsString(), response.getETag()); } }
[ "public", "void", "onDeleteResponseEvent", "(", "ResponseEvent", "event", ",", "ActivityContextInterface", "aci", ")", "{", "if", "(", "event", ".", "getException", "(", ")", "!=", "null", ")", "{", "if", "(", "tracer", ".", "isInfoEnabled", "(", ")", ")", "{", "tracer", ".", "info", "(", "\"Failed to delete \"", "+", "event", ".", "getURI", "(", ")", ",", "event", ".", "getException", "(", ")", ")", ";", "}", "getParent", "(", ")", ".", "deleteResponse", "(", "event", ".", "getURI", "(", ")", ",", "500", ",", "null", ",", "null", ")", ";", "}", "else", "{", "final", "XcapResponse", "response", "=", "event", ".", "getResponse", "(", ")", ";", "if", "(", "tracer", ".", "isInfoEnabled", "(", ")", ")", "{", "if", "(", "response", ".", "getCode", "(", ")", "==", "200", ")", "{", "tracer", ".", "info", "(", "\"Deleted \"", "+", "event", ".", "getURI", "(", ")", "+", "\". ETag:\"", "+", "response", ".", "getETag", "(", ")", ")", ";", "}", "else", "{", "tracer", ".", "info", "(", "\"Failed to delete \"", "+", "event", ".", "getURI", "(", ")", "+", "\". Response: \"", "+", "response", ")", ";", "}", "}", "getParent", "(", ")", ".", "deleteResponse", "(", "event", ".", "getURI", "(", ")", ",", "response", ".", "getCode", "(", ")", ",", "response", ".", "getEntity", "(", ")", ".", "getContentAsString", "(", ")", ",", "response", ".", "getETag", "(", ")", ")", ";", "}", "}" ]
Handles XCAP DELETE response events. @param event @param aci
[ "Handles", "XCAP", "DELETE", "response", "events", "." ]
0caa9ab481a545e52c31401f19e99bdfbbfb7bf0
https://github.com/RestComm/jain-slee.xcap/blob/0caa9ab481a545e52c31401f19e99bdfbbfb7bf0/enablers/xdm-client/sbb/src/main/java/org/restcomm/slee/enabler/xdmc/XDMClientChildSbb.java#L397-L421
148,107
RestComm/jain-slee.xcap
enablers/xdm-client/sbb/src/main/java/org/restcomm/slee/enabler/xdmc/XDMClientChildSbb.java
XDMClientChildSbb.unsubscribeFailed
public void unsubscribeFailed(int arg0, SubscriptionClientChildSbbLocalObject subscriptionChild) { try { final String notifier = subscriptionChild.getSubscriptionData().getNotifierURI(); subscriptionChild.remove(); getParent().unsubscribeFailed( arg0, (XDMClientChildSbbLocalObject) this.sbbContext .getSbbLocalObject(), notifier); } catch (Exception e) { tracer.severe("Unexpected exception on callback!", e); } }
java
public void unsubscribeFailed(int arg0, SubscriptionClientChildSbbLocalObject subscriptionChild) { try { final String notifier = subscriptionChild.getSubscriptionData().getNotifierURI(); subscriptionChild.remove(); getParent().unsubscribeFailed( arg0, (XDMClientChildSbbLocalObject) this.sbbContext .getSbbLocalObject(), notifier); } catch (Exception e) { tracer.severe("Unexpected exception on callback!", e); } }
[ "public", "void", "unsubscribeFailed", "(", "int", "arg0", ",", "SubscriptionClientChildSbbLocalObject", "subscriptionChild", ")", "{", "try", "{", "final", "String", "notifier", "=", "subscriptionChild", ".", "getSubscriptionData", "(", ")", ".", "getNotifierURI", "(", ")", ";", "subscriptionChild", ".", "remove", "(", ")", ";", "getParent", "(", ")", ".", "unsubscribeFailed", "(", "arg0", ",", "(", "XDMClientChildSbbLocalObject", ")", "this", ".", "sbbContext", ".", "getSbbLocalObject", "(", ")", ",", "notifier", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "tracer", ".", "severe", "(", "\"Unexpected exception on callback!\"", ",", "e", ")", ";", "}", "}" ]
two easy cases.
[ "two", "easy", "cases", "." ]
0caa9ab481a545e52c31401f19e99bdfbbfb7bf0
https://github.com/RestComm/jain-slee.xcap/blob/0caa9ab481a545e52c31401f19e99bdfbbfb7bf0/enablers/xdm-client/sbb/src/main/java/org/restcomm/slee/enabler/xdmc/XDMClientChildSbb.java#L603-L615
148,108
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericMultiBoJdbcDao.java
GenericMultiBoJdbcDao.lookupDelegateDao
@SuppressWarnings("unchecked") protected <T> IGenericBoDao<T> lookupDelegateDao(Class<T> clazz) throws DelegateDaoNotFound { IGenericBoDao<?> result = delegateDaos.get(clazz); if (result == null) { throw new DelegateDaoNotFound("Delegate dao for [" + clazz + "] not found!"); } return (IGenericBoDao<T>) result; }
java
@SuppressWarnings("unchecked") protected <T> IGenericBoDao<T> lookupDelegateDao(Class<T> clazz) throws DelegateDaoNotFound { IGenericBoDao<?> result = delegateDaos.get(clazz); if (result == null) { throw new DelegateDaoNotFound("Delegate dao for [" + clazz + "] not found!"); } return (IGenericBoDao<T>) result; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "<", "T", ">", "IGenericBoDao", "<", "T", ">", "lookupDelegateDao", "(", "Class", "<", "T", ">", "clazz", ")", "throws", "DelegateDaoNotFound", "{", "IGenericBoDao", "<", "?", ">", "result", "=", "delegateDaos", ".", "get", "(", "clazz", ")", ";", "if", "(", "result", "==", "null", ")", "{", "throw", "new", "DelegateDaoNotFound", "(", "\"Delegate dao for [\"", "+", "clazz", "+", "\"] not found!\"", ")", ";", "}", "return", "(", "IGenericBoDao", "<", "T", ">", ")", "result", ";", "}" ]
Lookup the delegate dao. @param clazz @return
[ "Lookup", "the", "delegate", "dao", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericMultiBoJdbcDao.java#L59-L66
148,109
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericMultiBoJdbcDao.java
GenericMultiBoJdbcDao.setDelegateDaos
public GenericMultiBoJdbcDao setDelegateDaos(Map<?, IGenericBoDao<?>> daoMappings) throws ClassNotFoundException { delegateDaos.clear(); for (Entry<?, IGenericBoDao<?>> entry : daoMappings.entrySet()) { Object cl = entry.getKey(); IGenericBoDao<?> dao = entry.getValue(); if (cl instanceof Class) { delegateDaos.put((Class<?>) cl, dao); } else { addDelegateDao(cl.toString(), dao); } } return this; }
java
public GenericMultiBoJdbcDao setDelegateDaos(Map<?, IGenericBoDao<?>> daoMappings) throws ClassNotFoundException { delegateDaos.clear(); for (Entry<?, IGenericBoDao<?>> entry : daoMappings.entrySet()) { Object cl = entry.getKey(); IGenericBoDao<?> dao = entry.getValue(); if (cl instanceof Class) { delegateDaos.put((Class<?>) cl, dao); } else { addDelegateDao(cl.toString(), dao); } } return this; }
[ "public", "GenericMultiBoJdbcDao", "setDelegateDaos", "(", "Map", "<", "?", ",", "IGenericBoDao", "<", "?", ">", ">", "daoMappings", ")", "throws", "ClassNotFoundException", "{", "delegateDaos", ".", "clear", "(", ")", ";", "for", "(", "Entry", "<", "?", ",", "IGenericBoDao", "<", "?", ">", ">", "entry", ":", "daoMappings", ".", "entrySet", "(", ")", ")", "{", "Object", "cl", "=", "entry", ".", "getKey", "(", ")", ";", "IGenericBoDao", "<", "?", ">", "dao", "=", "entry", ".", "getValue", "(", ")", ";", "if", "(", "cl", "instanceof", "Class", ")", "{", "delegateDaos", ".", "put", "(", "(", "Class", "<", "?", ">", ")", "cl", ",", "dao", ")", ";", "}", "else", "{", "addDelegateDao", "(", "cl", ".", "toString", "(", ")", ",", "dao", ")", ";", "}", "}", "return", "this", ";", "}" ]
Set delegate dao mappings. @param daoMappings @return
[ "Set", "delegate", "dao", "mappings", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericMultiBoJdbcDao.java#L101-L114
148,110
nuun-io/kernel
core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java
ExtensionManager.initializing
public void initializing() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { Collection<Plugin> plugins = kernelExtensions.get(kernelExtension); kernelExtension.initializing(plugins); } }
java
public void initializing() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { Collection<Plugin> plugins = kernelExtensions.get(kernelExtension); kernelExtension.initializing(plugins); } }
[ "public", "void", "initializing", "(", ")", "{", "for", "(", "KernelExtension", "kernelExtension", ":", "kernelExtensions", ".", "keySet", "(", ")", ")", "{", "Collection", "<", "Plugin", ">", "plugins", "=", "kernelExtensions", ".", "get", "(", "kernelExtension", ")", ";", "kernelExtension", ".", "initializing", "(", "plugins", ")", ";", "}", "}" ]
Notifies the extensions that the kernel is initializing
[ "Notifies", "the", "extensions", "that", "the", "kernel", "is", "initializing" ]
116a7664fe2a9323e280574803d273699a333732
https://github.com/nuun-io/kernel/blob/116a7664fe2a9323e280574803d273699a333732/core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java#L82-L89
148,111
nuun-io/kernel
core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java
ExtensionManager.initialized
public void initialized() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { kernelExtension.initialized(kernelExtensions.get(kernelExtension)); } }
java
public void initialized() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { kernelExtension.initialized(kernelExtensions.get(kernelExtension)); } }
[ "public", "void", "initialized", "(", ")", "{", "for", "(", "KernelExtension", "kernelExtension", ":", "kernelExtensions", ".", "keySet", "(", ")", ")", "{", "kernelExtension", ".", "initialized", "(", "kernelExtensions", ".", "get", "(", "kernelExtension", ")", ")", ";", "}", "}" ]
Notifies the extensions that the kernel is initialized
[ "Notifies", "the", "extensions", "that", "the", "kernel", "is", "initialized" ]
116a7664fe2a9323e280574803d273699a333732
https://github.com/nuun-io/kernel/blob/116a7664fe2a9323e280574803d273699a333732/core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java#L94-L100
148,112
nuun-io/kernel
core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java
ExtensionManager.starting
public void starting() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { kernelExtension.starting(kernelExtensions.get(kernelExtension)); } }
java
public void starting() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { kernelExtension.starting(kernelExtensions.get(kernelExtension)); } }
[ "public", "void", "starting", "(", ")", "{", "for", "(", "KernelExtension", "kernelExtension", ":", "kernelExtensions", ".", "keySet", "(", ")", ")", "{", "kernelExtension", ".", "starting", "(", "kernelExtensions", ".", "get", "(", "kernelExtension", ")", ")", ";", "}", "}" ]
Notifies the extensions that the kernel is starting
[ "Notifies", "the", "extensions", "that", "the", "kernel", "is", "starting" ]
116a7664fe2a9323e280574803d273699a333732
https://github.com/nuun-io/kernel/blob/116a7664fe2a9323e280574803d273699a333732/core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java#L105-L111
148,113
nuun-io/kernel
core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java
ExtensionManager.started
public void started() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { kernelExtension.started(kernelExtensions.get(kernelExtension)); } }
java
public void started() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { kernelExtension.started(kernelExtensions.get(kernelExtension)); } }
[ "public", "void", "started", "(", ")", "{", "for", "(", "KernelExtension", "kernelExtension", ":", "kernelExtensions", ".", "keySet", "(", ")", ")", "{", "kernelExtension", ".", "started", "(", "kernelExtensions", ".", "get", "(", "kernelExtension", ")", ")", ";", "}", "}" ]
Notifies the extensions that the kernel is started
[ "Notifies", "the", "extensions", "that", "the", "kernel", "is", "started" ]
116a7664fe2a9323e280574803d273699a333732
https://github.com/nuun-io/kernel/blob/116a7664fe2a9323e280574803d273699a333732/core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java#L116-L122
148,114
nuun-io/kernel
core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java
ExtensionManager.stopping
public void stopping() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { kernelExtension.stopping(kernelExtensions.get(kernelExtension)); } }
java
public void stopping() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { kernelExtension.stopping(kernelExtensions.get(kernelExtension)); } }
[ "public", "void", "stopping", "(", ")", "{", "for", "(", "KernelExtension", "kernelExtension", ":", "kernelExtensions", ".", "keySet", "(", ")", ")", "{", "kernelExtension", ".", "stopping", "(", "kernelExtensions", ".", "get", "(", "kernelExtension", ")", ")", ";", "}", "}" ]
Notifies the extensions that the kernel is stopping
[ "Notifies", "the", "extensions", "that", "the", "kernel", "is", "stopping" ]
116a7664fe2a9323e280574803d273699a333732
https://github.com/nuun-io/kernel/blob/116a7664fe2a9323e280574803d273699a333732/core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java#L127-L133
148,115
nuun-io/kernel
core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java
ExtensionManager.stopped
public void stopped() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { kernelExtension.stopped(kernelExtensions.get(kernelExtension)); } }
java
public void stopped() { for (KernelExtension kernelExtension : kernelExtensions.keySet()) { kernelExtension.stopped(kernelExtensions.get(kernelExtension)); } }
[ "public", "void", "stopped", "(", ")", "{", "for", "(", "KernelExtension", "kernelExtension", ":", "kernelExtensions", ".", "keySet", "(", ")", ")", "{", "kernelExtension", ".", "stopped", "(", "kernelExtensions", ".", "get", "(", "kernelExtension", ")", ")", ";", "}", "}" ]
Notifies the extensions that the kernel is stopped
[ "Notifies", "the", "extensions", "that", "the", "kernel", "is", "stopped" ]
116a7664fe2a9323e280574803d273699a333732
https://github.com/nuun-io/kernel/blob/116a7664fe2a9323e280574803d273699a333732/core/src/main/java/io/nuun/kernel/core/internal/ExtensionManager.java#L138-L144
148,116
nuun-io/kernel
core/src/main/java/io/nuun/kernel/core/internal/DependenciesAsserter.java
DependenciesAsserter.assertDependencies
void assertDependencies(final Plugin plugin) { Collection<Class<?>> expectedDependencies = new ArrayList<>(); Collection<Class<?>> requiredPlugins = plugin.requiredPlugins(); if (requiredPlugins != null) { expectedDependencies.addAll(requiredPlugins); } Collection<Class<?>> dependentPlugins = plugin.dependentPlugins(); if (dependentPlugins != null) { expectedDependencies.addAll(dependentPlugins); } for (Class<?> dependencyClass : expectedDependencies) { List<?> facets = facetRegistry.getFacets(dependencyClass); if (facets.isEmpty()) { throw new KernelException("Plugin %s misses the following dependency: %s", plugin.name(), dependencyClass.getCanonicalName()); } } }
java
void assertDependencies(final Plugin plugin) { Collection<Class<?>> expectedDependencies = new ArrayList<>(); Collection<Class<?>> requiredPlugins = plugin.requiredPlugins(); if (requiredPlugins != null) { expectedDependencies.addAll(requiredPlugins); } Collection<Class<?>> dependentPlugins = plugin.dependentPlugins(); if (dependentPlugins != null) { expectedDependencies.addAll(dependentPlugins); } for (Class<?> dependencyClass : expectedDependencies) { List<?> facets = facetRegistry.getFacets(dependencyClass); if (facets.isEmpty()) { throw new KernelException("Plugin %s misses the following dependency: %s", plugin.name(), dependencyClass.getCanonicalName()); } } }
[ "void", "assertDependencies", "(", "final", "Plugin", "plugin", ")", "{", "Collection", "<", "Class", "<", "?", ">", ">", "expectedDependencies", "=", "new", "ArrayList", "<>", "(", ")", ";", "Collection", "<", "Class", "<", "?", ">", ">", "requiredPlugins", "=", "plugin", ".", "requiredPlugins", "(", ")", ";", "if", "(", "requiredPlugins", "!=", "null", ")", "{", "expectedDependencies", ".", "addAll", "(", "requiredPlugins", ")", ";", "}", "Collection", "<", "Class", "<", "?", ">", ">", "dependentPlugins", "=", "plugin", ".", "dependentPlugins", "(", ")", ";", "if", "(", "dependentPlugins", "!=", "null", ")", "{", "expectedDependencies", ".", "addAll", "(", "dependentPlugins", ")", ";", "}", "for", "(", "Class", "<", "?", ">", "dependencyClass", ":", "expectedDependencies", ")", "{", "List", "<", "?", ">", "facets", "=", "facetRegistry", ".", "getFacets", "(", "dependencyClass", ")", ";", "if", "(", "facets", ".", "isEmpty", "(", ")", ")", "{", "throw", "new", "KernelException", "(", "\"Plugin %s misses the following dependency: %s\"", ",", "plugin", ".", "name", "(", ")", ",", "dependencyClass", ".", "getCanonicalName", "(", ")", ")", ";", "}", "}", "}" ]
Verifies that the plugin dependencies are present in the plugin list. The list should contains both dependent and required plugins. @param plugin the plugin to check
[ "Verifies", "that", "the", "plugin", "dependencies", "are", "present", "in", "the", "plugin", "list", ".", "The", "list", "should", "contains", "both", "dependent", "and", "required", "plugins", "." ]
116a7664fe2a9323e280574803d273699a333732
https://github.com/nuun-io/kernel/blob/116a7664fe2a9323e280574803d273699a333732/core/src/main/java/io/nuun/kernel/core/internal/DependenciesAsserter.java#L42-L67
148,117
grycap/coreutils
coreutils-common/src/main/java/es/upv/grycap/coreutils/common/concurrent/TaskRunner.java
TaskRunner.submit
public <T> CompletableFuture<T> submit(final Supplier<T> supplier) { requireNonNull(supplier, "A non-null supplier expected"); CompletableFuture<T> future = null; if (isRunning.get()) { future = supplyAsync(supplier, executor); } else { future = new CompletableFuture<>(); future.completeExceptionally(new IllegalStateException("This task runner is not active")); } return future; }
java
public <T> CompletableFuture<T> submit(final Supplier<T> supplier) { requireNonNull(supplier, "A non-null supplier expected"); CompletableFuture<T> future = null; if (isRunning.get()) { future = supplyAsync(supplier, executor); } else { future = new CompletableFuture<>(); future.completeExceptionally(new IllegalStateException("This task runner is not active")); } return future; }
[ "public", "<", "T", ">", "CompletableFuture", "<", "T", ">", "submit", "(", "final", "Supplier", "<", "T", ">", "supplier", ")", "{", "requireNonNull", "(", "supplier", ",", "\"A non-null supplier expected\"", ")", ";", "CompletableFuture", "<", "T", ">", "future", "=", "null", ";", "if", "(", "isRunning", ".", "get", "(", ")", ")", "{", "future", "=", "supplyAsync", "(", "supplier", ",", "executor", ")", ";", "}", "else", "{", "future", "=", "new", "CompletableFuture", "<>", "(", ")", ";", "future", ".", "completeExceptionally", "(", "new", "IllegalStateException", "(", "\"This task runner is not active\"", ")", ")", ";", "}", "return", "future", ";", "}" ]
Submits a new task for execution to the pool of threads managed by this class. @param <T> - specific type of supplier @param supplier - a function returning the value to be used to complete the returned {@link CompletableFuture} @return a {@link CompletableFuture} that the caller can use to track the execution of the task and to register a callback function.
[ "Submits", "a", "new", "task", "for", "execution", "to", "the", "pool", "of", "threads", "managed", "by", "this", "class", "." ]
e6db61dc50b49ea7276c0c29c7401204681a10c2
https://github.com/grycap/coreutils/blob/e6db61dc50b49ea7276c0c29c7401204681a10c2/coreutils-common/src/main/java/es/upv/grycap/coreutils/common/concurrent/TaskRunner.java#L93-L103
148,118
RestComm/jain-slee.xcap
resources/xcap-client/api/src/main/java/org/restcomm/xcap/client/uri/encoding/UriComponentEncoder.java
UriComponentEncoder.encodePath
public static String encodePath(String path) throws NullPointerException { return new String(encode(path, UriComponentEncoderBitSets.allowed_abs_path)); }
java
public static String encodePath(String path) throws NullPointerException { return new String(encode(path, UriComponentEncoderBitSets.allowed_abs_path)); }
[ "public", "static", "String", "encodePath", "(", "String", "path", ")", "throws", "NullPointerException", "{", "return", "new", "String", "(", "encode", "(", "path", ",", "UriComponentEncoderBitSets", ".", "allowed_abs_path", ")", ")", ";", "}" ]
Encodes an HTTP URI Path. @param path @return @throws NullPointerException
[ "Encodes", "an", "HTTP", "URI", "Path", "." ]
0caa9ab481a545e52c31401f19e99bdfbbfb7bf0
https://github.com/RestComm/jain-slee.xcap/blob/0caa9ab481a545e52c31401f19e99bdfbbfb7bf0/resources/xcap-client/api/src/main/java/org/restcomm/xcap/client/uri/encoding/UriComponentEncoder.java#L58-L60
148,119
RestComm/jain-slee.xcap
resources/xcap-client/api/src/main/java/org/restcomm/xcap/client/uri/encoding/UriComponentEncoder.java
UriComponentEncoder.encodeQuery
public static String encodeQuery(String query) throws NullPointerException { return new String(encode(query, UriComponentEncoderBitSets.allowed_query)); }
java
public static String encodeQuery(String query) throws NullPointerException { return new String(encode(query, UriComponentEncoderBitSets.allowed_query)); }
[ "public", "static", "String", "encodeQuery", "(", "String", "query", ")", "throws", "NullPointerException", "{", "return", "new", "String", "(", "encode", "(", "query", ",", "UriComponentEncoderBitSets", ".", "allowed_query", ")", ")", ";", "}" ]
Encodes an HTTP URI Query. @param query @return @throws NullPointerException
[ "Encodes", "an", "HTTP", "URI", "Query", "." ]
0caa9ab481a545e52c31401f19e99bdfbbfb7bf0
https://github.com/RestComm/jain-slee.xcap/blob/0caa9ab481a545e52c31401f19e99bdfbbfb7bf0/resources/xcap-client/api/src/main/java/org/restcomm/xcap/client/uri/encoding/UriComponentEncoder.java#L68-L70
148,120
fuinorg/objects4j
src/main/java/org/fuin/objects4j/vo/Hour.java
Hour.isValid
public static boolean isValid(@Nullable final String hour) { if (hour == null) { return true; } return PATTERN.matcher(hour).matches(); }
java
public static boolean isValid(@Nullable final String hour) { if (hour == null) { return true; } return PATTERN.matcher(hour).matches(); }
[ "public", "static", "boolean", "isValid", "(", "@", "Nullable", "final", "String", "hour", ")", "{", "if", "(", "hour", "==", "null", ")", "{", "return", "true", ";", "}", "return", "PATTERN", ".", "matcher", "(", "hour", ")", ".", "matches", "(", ")", ";", "}" ]
Verifies if the string is a valid hour. @param hour Hour string to test. @return {@literal true} if the string is a valid number, else {@literal false}.
[ "Verifies", "if", "the", "string", "is", "a", "valid", "hour", "." ]
e7f278b5bae073ebb6a76053650571c718f36246
https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/vo/Hour.java#L150-L155
148,121
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/config/PropertyConfigLoader.java
PropertyConfigLoader.get
public static Object get(String filePath, String configKey) { if (propertiesMap.containsKey(filePath) == false) { loadProperty(filePath); } Properties properties = propertiesMap.get(filePath); if (properties == null) { return null; } Object resultConfig = properties.getProperty(configKey); return resultConfig; }
java
public static Object get(String filePath, String configKey) { if (propertiesMap.containsKey(filePath) == false) { loadProperty(filePath); } Properties properties = propertiesMap.get(filePath); if (properties == null) { return null; } Object resultConfig = properties.getProperty(configKey); return resultConfig; }
[ "public", "static", "Object", "get", "(", "String", "filePath", ",", "String", "configKey", ")", "{", "if", "(", "propertiesMap", ".", "containsKey", "(", "filePath", ")", "==", "false", ")", "{", "loadProperty", "(", "filePath", ")", ";", "}", "Properties", "properties", "=", "propertiesMap", ".", "get", "(", "filePath", ")", ";", "if", "(", "properties", "==", "null", ")", "{", "return", "null", ";", "}", "Object", "resultConfig", "=", "properties", ".", "getProperty", "(", "configKey", ")", ";", "return", "resultConfig", ";", "}" ]
Get from config defined property files in classpath. @param filePath property file path in classpath @param configKey configkey @return config value defined in property file
[ "Get", "from", "config", "defined", "property", "files", "in", "classpath", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/config/PropertyConfigLoader.java#L55-L70
148,122
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/config/PropertyConfigLoader.java
PropertyConfigLoader.loadProperty
private static void loadProperty(String filePath) { try (InputStream propertyStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( filePath); Reader propertyReader = new InputStreamReader(propertyStream, DEFAULT_CHARSET);) { Properties properties = new Properties(); properties.load(propertyReader); propertiesMap.put(filePath, properties); } catch (Exception ex) { String errorPattern = "Property file load failed. Skip load. : PropertyFile={0}"; logger.warn(MessageFormat.format(errorPattern, filePath), ex); } }
java
private static void loadProperty(String filePath) { try (InputStream propertyStream = Thread.currentThread().getContextClassLoader().getResourceAsStream( filePath); Reader propertyReader = new InputStreamReader(propertyStream, DEFAULT_CHARSET);) { Properties properties = new Properties(); properties.load(propertyReader); propertiesMap.put(filePath, properties); } catch (Exception ex) { String errorPattern = "Property file load failed. Skip load. : PropertyFile={0}"; logger.warn(MessageFormat.format(errorPattern, filePath), ex); } }
[ "private", "static", "void", "loadProperty", "(", "String", "filePath", ")", "{", "try", "(", "InputStream", "propertyStream", "=", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ".", "getResourceAsStream", "(", "filePath", ")", ";", "Reader", "propertyReader", "=", "new", "InputStreamReader", "(", "propertyStream", ",", "DEFAULT_CHARSET", ")", ";", ")", "{", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "properties", ".", "load", "(", "propertyReader", ")", ";", "propertiesMap", ".", "put", "(", "filePath", ",", "properties", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "String", "errorPattern", "=", "\"Property file load failed. Skip load. : PropertyFile={0}\"", ";", "logger", ".", "warn", "(", "MessageFormat", ".", "format", "(", "errorPattern", ",", "filePath", ")", ",", "ex", ")", ";", "}", "}" ]
Load property file. @param filePath property file path in classpath
[ "Load", "property", "file", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/config/PropertyConfigLoader.java#L77-L92
148,123
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/utils/JdbcHelper.java
JdbcHelper.buildBindValues
private static Object[] buildBindValues(Object bindValue) { if (bindValue instanceof boolean[]) { boolean[] bools = (boolean[]) bindValue; return bools.length > 0 ? ArrayUtils.toObject(bools) : null; } else if (bindValue instanceof short[]) { short[] shorts = (short[]) bindValue; return shorts.length > 0 ? ArrayUtils.toObject(shorts) : null; } else if (bindValue instanceof int[]) { int[] ints = (int[]) bindValue; return ints.length > 0 ? ArrayUtils.toObject(ints) : null; } else if (bindValue instanceof long[]) { long[] longs = (long[]) bindValue; return longs.length > 0 ? ArrayUtils.toObject(longs) : null; } else if (bindValue instanceof float[]) { float[] floats = (float[]) bindValue; return floats.length > 0 ? ArrayUtils.toObject(floats) : null; } else if (bindValue instanceof double[]) { double[] doubles = (double[]) bindValue; return doubles.length > 0 ? ArrayUtils.toObject(doubles) : null; } else if (bindValue instanceof char[]) { char[] chars = (char[]) bindValue; return chars.length > 0 ? ArrayUtils.toObject(chars) : null; } else if (bindValue instanceof Object[]) { Object[] objs = (Object[]) bindValue; return objs.length > 0 ? objs : null; } else if (bindValue instanceof List<?>) { List<?> list = (List<?>) bindValue; return list.size() > 0 ? list.toArray() : null; } return new Object[] { bindValue }; } private static String buildStatementAndValues(String sql, Map<String, ?> bindValues, List<Object> outValues) { if (bindValues == null) { bindValues = new HashMap<>(); } StringBuffer sb = new StringBuffer(); Matcher m = PATTERN_NAMED_PARAM.matcher(sql); while (m.find()) { String namedParam = m.group(1); Object bindValue = bindValues.get(namedParam); Object[] bindList = buildBindValues(bindValue); m.appendReplacement(sb, StringUtils.repeat("?", ",", bindList.length)); for (Object bind : bindList) { outValues.add(bind); } } m.appendTail(sb); return sb.toString(); } /** * Prepare and bind parameter values a named-parameter statement. * * @param conn * @param sql * @param bindValues * name-based bind values * @return * @since 0.8.2 * @throws SQLException */ public static PreparedStatement prepareAndBindNamedParamsStatement(Connection conn, String sql, Map<String, ?> bindValues) throws SQLException { List<Object> indexBindValues = new ArrayList<>(); String finalSql = buildStatementAndValues(sql, bindValues, indexBindValues); PreparedStatement pstm = conn.prepareStatement(finalSql); bindParams(pstm, indexBindValues.toArray()); return pstm; } /** * Prepare and bind parameter values a named-parameter statement. * * @param conn * @param sql * @param resultSetType * @param resultSetConcurrency * @param bindValues * name-based bind values * @return * @since 0.8.2 * @throws SQLException */ public static PreparedStatement prepareAndBindNamedParamsStatement(Connection conn, String sql, int resultSetType, int resultSetConcurrency, Map<String, ?> bindValues) throws SQLException { List<Object> indexBindValues = new ArrayList<>(); String finalSql = buildStatementAndValues(sql, bindValues, indexBindValues); PreparedStatement pstm = conn.prepareStatement(finalSql, resultSetType, resultSetConcurrency); bindParams(pstm, indexBindValues.toArray()); return pstm; } /** * Prepare and bind parameter values a named-parameter statement. * * @param conn * @param sql * @param resultSetType * @param resultSetConcurrency * @param resultSetHoldability * @param bindValues * name-based bind values * @return * @since 0.8.2 * @throws SQLException */ public static PreparedStatement prepareAndBindNamedParamsStatement(Connection conn, String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability, Map<String, ?> bindValues) throws SQLException { List<Object> indexBindValues = new ArrayList<>(); String finalSql = buildStatementAndValues(sql, bindValues, indexBindValues); PreparedStatement pstm = conn.prepareStatement(finalSql, resultSetType, resultSetConcurrency, resultSetHoldability); bindParams(pstm, indexBindValues.toArray()); return pstm; }
java
private static Object[] buildBindValues(Object bindValue) { if (bindValue instanceof boolean[]) { boolean[] bools = (boolean[]) bindValue; return bools.length > 0 ? ArrayUtils.toObject(bools) : null; } else if (bindValue instanceof short[]) { short[] shorts = (short[]) bindValue; return shorts.length > 0 ? ArrayUtils.toObject(shorts) : null; } else if (bindValue instanceof int[]) { int[] ints = (int[]) bindValue; return ints.length > 0 ? ArrayUtils.toObject(ints) : null; } else if (bindValue instanceof long[]) { long[] longs = (long[]) bindValue; return longs.length > 0 ? ArrayUtils.toObject(longs) : null; } else if (bindValue instanceof float[]) { float[] floats = (float[]) bindValue; return floats.length > 0 ? ArrayUtils.toObject(floats) : null; } else if (bindValue instanceof double[]) { double[] doubles = (double[]) bindValue; return doubles.length > 0 ? ArrayUtils.toObject(doubles) : null; } else if (bindValue instanceof char[]) { char[] chars = (char[]) bindValue; return chars.length > 0 ? ArrayUtils.toObject(chars) : null; } else if (bindValue instanceof Object[]) { Object[] objs = (Object[]) bindValue; return objs.length > 0 ? objs : null; } else if (bindValue instanceof List<?>) { List<?> list = (List<?>) bindValue; return list.size() > 0 ? list.toArray() : null; } return new Object[] { bindValue }; } private static String buildStatementAndValues(String sql, Map<String, ?> bindValues, List<Object> outValues) { if (bindValues == null) { bindValues = new HashMap<>(); } StringBuffer sb = new StringBuffer(); Matcher m = PATTERN_NAMED_PARAM.matcher(sql); while (m.find()) { String namedParam = m.group(1); Object bindValue = bindValues.get(namedParam); Object[] bindList = buildBindValues(bindValue); m.appendReplacement(sb, StringUtils.repeat("?", ",", bindList.length)); for (Object bind : bindList) { outValues.add(bind); } } m.appendTail(sb); return sb.toString(); } /** * Prepare and bind parameter values a named-parameter statement. * * @param conn * @param sql * @param bindValues * name-based bind values * @return * @since 0.8.2 * @throws SQLException */ public static PreparedStatement prepareAndBindNamedParamsStatement(Connection conn, String sql, Map<String, ?> bindValues) throws SQLException { List<Object> indexBindValues = new ArrayList<>(); String finalSql = buildStatementAndValues(sql, bindValues, indexBindValues); PreparedStatement pstm = conn.prepareStatement(finalSql); bindParams(pstm, indexBindValues.toArray()); return pstm; } /** * Prepare and bind parameter values a named-parameter statement. * * @param conn * @param sql * @param resultSetType * @param resultSetConcurrency * @param bindValues * name-based bind values * @return * @since 0.8.2 * @throws SQLException */ public static PreparedStatement prepareAndBindNamedParamsStatement(Connection conn, String sql, int resultSetType, int resultSetConcurrency, Map<String, ?> bindValues) throws SQLException { List<Object> indexBindValues = new ArrayList<>(); String finalSql = buildStatementAndValues(sql, bindValues, indexBindValues); PreparedStatement pstm = conn.prepareStatement(finalSql, resultSetType, resultSetConcurrency); bindParams(pstm, indexBindValues.toArray()); return pstm; } /** * Prepare and bind parameter values a named-parameter statement. * * @param conn * @param sql * @param resultSetType * @param resultSetConcurrency * @param resultSetHoldability * @param bindValues * name-based bind values * @return * @since 0.8.2 * @throws SQLException */ public static PreparedStatement prepareAndBindNamedParamsStatement(Connection conn, String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability, Map<String, ?> bindValues) throws SQLException { List<Object> indexBindValues = new ArrayList<>(); String finalSql = buildStatementAndValues(sql, bindValues, indexBindValues); PreparedStatement pstm = conn.prepareStatement(finalSql, resultSetType, resultSetConcurrency, resultSetHoldability); bindParams(pstm, indexBindValues.toArray()); return pstm; }
[ "private", "static", "Object", "[", "]", "buildBindValues", "(", "Object", "bindValue", ")", "{", "if", "(", "bindValue", "instanceof", "boolean", "[", "]", ")", "{", "boolean", "[", "]", "bools", "=", "(", "boolean", "[", "]", ")", "bindValue", ";", "return", "bools", ".", "length", ">", "0", "?", "ArrayUtils", ".", "toObject", "(", "bools", ")", ":", "null", ";", "}", "else", "if", "(", "bindValue", "instanceof", "short", "[", "]", ")", "{", "short", "[", "]", "shorts", "=", "(", "short", "[", "]", ")", "bindValue", ";", "return", "shorts", ".", "length", ">", "0", "?", "ArrayUtils", ".", "toObject", "(", "shorts", ")", ":", "null", ";", "}", "else", "if", "(", "bindValue", "instanceof", "int", "[", "]", ")", "{", "int", "[", "]", "ints", "=", "(", "int", "[", "]", ")", "bindValue", ";", "return", "ints", ".", "length", ">", "0", "?", "ArrayUtils", ".", "toObject", "(", "ints", ")", ":", "null", ";", "}", "else", "if", "(", "bindValue", "instanceof", "long", "[", "]", ")", "{", "long", "[", "]", "longs", "=", "(", "long", "[", "]", ")", "bindValue", ";", "return", "longs", ".", "length", ">", "0", "?", "ArrayUtils", ".", "toObject", "(", "longs", ")", ":", "null", ";", "}", "else", "if", "(", "bindValue", "instanceof", "float", "[", "]", ")", "{", "float", "[", "]", "floats", "=", "(", "float", "[", "]", ")", "bindValue", ";", "return", "floats", ".", "length", ">", "0", "?", "ArrayUtils", ".", "toObject", "(", "floats", ")", ":", "null", ";", "}", "else", "if", "(", "bindValue", "instanceof", "double", "[", "]", ")", "{", "double", "[", "]", "doubles", "=", "(", "double", "[", "]", ")", "bindValue", ";", "return", "doubles", ".", "length", ">", "0", "?", "ArrayUtils", ".", "toObject", "(", "doubles", ")", ":", "null", ";", "}", "else", "if", "(", "bindValue", "instanceof", "char", "[", "]", ")", "{", "char", "[", "]", "chars", "=", "(", "char", "[", "]", ")", "bindValue", ";", "return", "chars", ".", "length", ">", "0", "?", "ArrayUtils", ".", "toObject", "(", "chars", ")", ":", "null", ";", "}", "else", "if", "(", "bindValue", "instanceof", "Object", "[", "]", ")", "{", "Object", "[", "]", "objs", "=", "(", "Object", "[", "]", ")", "bindValue", ";", "return", "objs", ".", "length", ">", "0", "?", "objs", ":", "null", ";", "}", "else", "if", "(", "bindValue", "instanceof", "List", "<", "?", ">", ")", "{", "List", "<", "?", ">", "list", "=", "(", "List", "<", "?", ">", ")", "bindValue", ";", "return", "list", ".", "size", "(", ")", ">", "0", "?", "list", ".", "toArray", "(", ")", ":", "null", ";", "}", "return", "new", "Object", "[", "]", "{", "bindValue", "}", ";", "}", "private", "static", "String", "buildStatementAndValues", "(", "String", "sql", ",", "Map", "<", "String", ",", "?", ">", "bindValues", ",", "List", "<", "Object", ">", "outValues", ")", "{", "if", "(", "bindValues", "==", "null", ")", "{", "bindValues", "=", "new", "HashMap", "<>", "(", ")", ";", "}", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "Matcher", "m", "=", "PATTERN_NAMED_PARAM", ".", "matcher", "(", "sql", ")", ";", "while", "(", "m", ".", "find", "(", ")", ")", "{", "String", "namedParam", "=", "m", ".", "group", "(", "1", ")", ";", "Object", "bindValue", "=", "bindValues", ".", "get", "(", "namedParam", ")", ";", "Object", "[", "]", "bindList", "=", "buildBindValues", "(", "bindValue", ")", ";", "m", ".", "appendReplacement", "(", "sb", ",", "StringUtils", ".", "repeat", "(", "\"", "?", "\"", ",", "\"", ",", "\"", ",", "bindList", ".", "length", ")", ")", ";", "for", "(", "Object", "bind", ":", "bindList", ")", "{", "outValues", ".", "(", "bind", ")", ";", "}", "}", "m", ".", "appendTail", "(", "sb", ")", ";", "return", "sb", ".", "toString", "(", ")", ";", "}", "/**\n * Prepare and bind parameter values a named-parameter statement.\n * \n * @param conn\n * @param sql\n * @param bindValues\n * name-based bind values\n * @return\n * @since 0.8.2\n * @throws SQLException\n */", "public", "static", "PreparedStatement", "prepareAndBindNamedParamsStatement", "(", "Connection", "conn", ",", "String", "sql", ",", "Map", "<", "String", ",", "?", ">", "bindValues", ")", "throws", "SQLException", "{", "List", "<", "Object", ">", "indexBindValues", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "finalSql", "=", "buildStatementAndValues", "(", "sql", ",", "bindValues", ",", "indexBindValues", ")", ";", "PreparedStatement", "pstm", "=", "conn", ".", "prepareStatement", "(", "finalSql", ")", ";", "bindParams", "(", "pstm", ",", "indexBindValues", ".", "toArray", "(", ")", ")", ";", "return", "pstm", ";", "}", "/**\n * Prepare and bind parameter values a named-parameter statement.\n * \n * @param conn\n * @param sql\n * @param resultSetType\n * @param resultSetConcurrency\n * @param bindValues\n * name-based bind values\n * @return\n * @since 0.8.2\n * @throws SQLException\n */", "public", "static", "PreparedStatement", "prepareAndBindNamedParamsStatement", "(", "Connection", "conn", ",", "String", "sql", ",", "int", "resultSetType", ",", "int", "resultSetConcurrency", ",", "Map", "<", "String", ",", "?", ">", "bindValues", ")", "throws", "SQLException", "{", "List", "<", "Object", ">", "indexBindValues", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "finalSql", "=", "buildStatementAndValues", "(", "sql", ",", "bindValues", ",", "indexBindValues", ")", ";", "PreparedStatement", "pstm", "=", "conn", ".", "prepareStatement", "(", "finalSql", ",", "resultSetType", ",", "resultSetConcurrency", ")", ";", "bindParams", "(", "pstm", ",", "indexBindValues", ".", "toArray", "(", ")", ")", ";", "return", "pstm", ";", "}", "/**\n * Prepare and bind parameter values a named-parameter statement.\n * \n * @param conn\n * @param sql\n * @param resultSetType\n * @param resultSetConcurrency\n * @param resultSetHoldability\n * @param bindValues\n * name-based bind values\n * @return\n * @since 0.8.2\n * @throws SQLException\n */", "public", "static", "PreparedStatement", "prepareAndBindNamedParamsStatement", "(", "Connection", "conn", ",", "String", "sql", ",", "int", "resultSetType", ",", "int", "resultSetConcurrency", ",", "int", "resultSetHoldability", ",", "Map", "<", "String", ",", "?", ">", "bindValues", ")", "throws", "SQLException", "{", "List", "<", "Object", ">", "indexBindValues", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "finalSql", "=", "buildStatementAndValues", "(", "sql", ",", "bindValues", ",", "indexBindValues", ")", ";", "PreparedStatement", "pstm", "=", "conn", ".", "prepareStatement", "(", "finalSql", ",", "resultSetType", ",", "resultSetConcurrency", ",", "resultSetHoldability", ")", ";", "bindParams", "(", "pstm", ",", "indexBindValues", ".", "toArray", "(", ")", ")", ";", "return", "pstm", ";", "}" ]
Build array of final build values according the supplied build value. @param bindValue @return
[ "Build", "array", "of", "final", "build", "values", "according", "the", "supplied", "build", "value", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/utils/JdbcHelper.java#L170-L289
148,124
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractJdbcHelper.java
AbstractJdbcHelper.calcFetchSizeForStream
protected int calcFetchSizeForStream(int hintFetchSize, Connection conn) throws SQLException { DatabaseVendor dbVendor = DbcHelper.detectDbVendor(conn); switch (dbVendor) { case MYSQL: return Integer.MIN_VALUE; default: return hintFetchSize < 0 ? 1 : hintFetchSize; } }
java
protected int calcFetchSizeForStream(int hintFetchSize, Connection conn) throws SQLException { DatabaseVendor dbVendor = DbcHelper.detectDbVendor(conn); switch (dbVendor) { case MYSQL: return Integer.MIN_VALUE; default: return hintFetchSize < 0 ? 1 : hintFetchSize; } }
[ "protected", "int", "calcFetchSizeForStream", "(", "int", "hintFetchSize", ",", "Connection", "conn", ")", "throws", "SQLException", "{", "DatabaseVendor", "dbVendor", "=", "DbcHelper", ".", "detectDbVendor", "(", "conn", ")", ";", "switch", "(", "dbVendor", ")", "{", "case", "MYSQL", ":", "return", "Integer", ".", "MIN_VALUE", ";", "default", ":", "return", "hintFetchSize", "<", "0", "?", "1", ":", "hintFetchSize", ";", "}", "}" ]
Calculate fetch size used for streaming. @param hintFetchSize @param conn @return @throws SQLException
[ "Calculate", "fetch", "size", "used", "for", "streaming", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractJdbcHelper.java#L549-L557
148,125
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java
AbstractGenericRowMapper.generateSqlSelect
public String generateSqlSelect(String tableName) { try { return cacheSQLs.get("SELECT:" + tableName, () -> { return MessageFormat.format("SELECT {2} FROM {0} WHERE {1}", tableName, strWherePkClause, strAllColumns); }); } catch (ExecutionException e) { throw new DaoException(e); } }
java
public String generateSqlSelect(String tableName) { try { return cacheSQLs.get("SELECT:" + tableName, () -> { return MessageFormat.format("SELECT {2} FROM {0} WHERE {1}", tableName, strWherePkClause, strAllColumns); }); } catch (ExecutionException e) { throw new DaoException(e); } }
[ "public", "String", "generateSqlSelect", "(", "String", "tableName", ")", "{", "try", "{", "return", "cacheSQLs", ".", "get", "(", "\"SELECT:\"", "+", "tableName", ",", "(", ")", "->", "{", "return", "MessageFormat", ".", "format", "(", "\"SELECT {2} FROM {0} WHERE {1}\"", ",", "tableName", ",", "strWherePkClause", ",", "strAllColumns", ")", ";", "}", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "new", "DaoException", "(", "e", ")", ";", "}", "}" ]
Generate SELECT statement to select a BO. <p> The generated SQL will look like this {@code SELECT all-columns FROM table WHERE pk-1=? AND pk-2=?...} </p> @param tableName @return @since 0.8.5
[ "Generate", "SELECT", "statement", "to", "select", "a", "BO", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java#L65-L74
148,126
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java
AbstractGenericRowMapper.generateSqlSelectAll
public String generateSqlSelectAll(String tableName) { try { return cacheSQLs.get("SELECT-ALL:" + tableName, () -> { return MessageFormat.format("SELECT {2} FROM {0} ORDER BY {1}", tableName, strPkColumns, strAllColumns); }); } catch (ExecutionException e) { throw new DaoException(e); } }
java
public String generateSqlSelectAll(String tableName) { try { return cacheSQLs.get("SELECT-ALL:" + tableName, () -> { return MessageFormat.format("SELECT {2} FROM {0} ORDER BY {1}", tableName, strPkColumns, strAllColumns); }); } catch (ExecutionException e) { throw new DaoException(e); } }
[ "public", "String", "generateSqlSelectAll", "(", "String", "tableName", ")", "{", "try", "{", "return", "cacheSQLs", ".", "get", "(", "\"SELECT-ALL:\"", "+", "tableName", ",", "(", ")", "->", "{", "return", "MessageFormat", ".", "format", "(", "\"SELECT {2} FROM {0} ORDER BY {1}\"", ",", "tableName", ",", "strPkColumns", ",", "strAllColumns", ")", ";", "}", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "new", "DaoException", "(", "e", ")", ";", "}", "}" ]
Generate SELECT statement to SELECT all BOs, ordered by promary keys. <p> The generated SQL will look like this {@code SELECT all-columns FROM table ORDER BY pk-1, pk-2...} </p> @param tableName @return @since 0.8.5
[ "Generate", "SELECT", "statement", "to", "SELECT", "all", "BOs", "ordered", "by", "promary", "keys", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java#L88-L97
148,127
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java
AbstractGenericRowMapper.generateSqlInsert
public String generateSqlInsert(String tableName) { try { return cacheSQLs.get("INSERT:" + tableName, () -> { return MessageFormat.format("INSERT INTO {0} ({1}) VALUES ({2})", tableName, strAllColumns, StringUtils.repeat("?", ",", getAllColumns().length)); }); } catch (ExecutionException e) { throw new DaoException(e); } }
java
public String generateSqlInsert(String tableName) { try { return cacheSQLs.get("INSERT:" + tableName, () -> { return MessageFormat.format("INSERT INTO {0} ({1}) VALUES ({2})", tableName, strAllColumns, StringUtils.repeat("?", ",", getAllColumns().length)); }); } catch (ExecutionException e) { throw new DaoException(e); } }
[ "public", "String", "generateSqlInsert", "(", "String", "tableName", ")", "{", "try", "{", "return", "cacheSQLs", ".", "get", "(", "\"INSERT:\"", "+", "tableName", ",", "(", ")", "->", "{", "return", "MessageFormat", ".", "format", "(", "\"INSERT INTO {0} ({1}) VALUES ({2})\"", ",", "tableName", ",", "strAllColumns", ",", "StringUtils", ".", "repeat", "(", "\"?\"", ",", "\",\"", ",", "getAllColumns", "(", ")", ".", "length", ")", ")", ";", "}", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "new", "DaoException", "(", "e", ")", ";", "}", "}" ]
Generate INSERT statement to insert a BO. <p> The generated SQL will look like this {@code INSERT INTO table (all-columns) VALUES (?,?,...)} </p> @param tableName @return @since 0.8.5
[ "Generate", "INSERT", "statement", "to", "insert", "a", "BO", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java#L111-L120
148,128
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java
AbstractGenericRowMapper.generateSqlDelete
public String generateSqlDelete(String tableName) { try { return cacheSQLs.get("DELETE:" + tableName, () -> { return MessageFormat.format("DELETE FROM {0} WHERE {1}", tableName, strWherePkClause); }); } catch (ExecutionException e) { throw new DaoException(e); } }
java
public String generateSqlDelete(String tableName) { try { return cacheSQLs.get("DELETE:" + tableName, () -> { return MessageFormat.format("DELETE FROM {0} WHERE {1}", tableName, strWherePkClause); }); } catch (ExecutionException e) { throw new DaoException(e); } }
[ "public", "String", "generateSqlDelete", "(", "String", "tableName", ")", "{", "try", "{", "return", "cacheSQLs", ".", "get", "(", "\"DELETE:\"", "+", "tableName", ",", "(", ")", "->", "{", "return", "MessageFormat", ".", "format", "(", "\"DELETE FROM {0} WHERE {1}\"", ",", "tableName", ",", "strWherePkClause", ")", ";", "}", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "new", "DaoException", "(", "e", ")", ";", "}", "}" ]
Generate DELETE statement to delete an existing BO. <p> The generated SQL will look like this {@code DELETE FROM table WHERE pk-1=? AND pk-2=?...} </p> @param tableName @return @since 0.8.5
[ "Generate", "DELETE", "statement", "to", "delete", "an", "existing", "BO", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java#L133-L142
148,129
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java
AbstractGenericRowMapper.generateSqlUpdate
public String generateSqlUpdate(String tableName) { try { return cacheSQLs.get("UPDATE:" + tableName, () -> { return MessageFormat.format("UPDATE {0} SET {2} WHERE {1}", tableName, strWherePkClause, strUpdateSetClause); }); } catch (ExecutionException e) { throw new RuntimeException(e); } }
java
public String generateSqlUpdate(String tableName) { try { return cacheSQLs.get("UPDATE:" + tableName, () -> { return MessageFormat.format("UPDATE {0} SET {2} WHERE {1}", tableName, strWherePkClause, strUpdateSetClause); }); } catch (ExecutionException e) { throw new RuntimeException(e); } }
[ "public", "String", "generateSqlUpdate", "(", "String", "tableName", ")", "{", "try", "{", "return", "cacheSQLs", ".", "get", "(", "\"UPDATE:\"", "+", "tableName", ",", "(", ")", "->", "{", "return", "MessageFormat", ".", "format", "(", "\"UPDATE {0} SET {2} WHERE {1}\"", ",", "tableName", ",", "strWherePkClause", ",", "strUpdateSetClause", ")", ";", "}", ")", ";", "}", "catch", "(", "ExecutionException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Generate UPDATE statement to update an existing BO. <p> The generated SQL will look like this {@code UPDATE table SET col1=?, col2=?...WHERE pk-1=? AND pk-2=?...} </p> @param tableName @return @since 0.8.5
[ "Generate", "UPDATE", "statement", "to", "update", "an", "existing", "BO", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java#L156-L165
148,130
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java
AbstractGenericRowMapper.valuesForColumns
public Object[] valuesForColumns(T bo, String... columns) { Map<String, ColAttrMapping> columnAttributeMappings = getColumnAttributeMappings(); Object[] result = new Object[columns.length]; for (int i = 0; i < columns.length; i++) { ColAttrMapping colAttrMapping = columnAttributeMappings.get(columns[i]); try { result[i] = colAttrMapping != null ? colAttrMapping.extractAttrValue(bo) : null; } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } } return result; }
java
public Object[] valuesForColumns(T bo, String... columns) { Map<String, ColAttrMapping> columnAttributeMappings = getColumnAttributeMappings(); Object[] result = new Object[columns.length]; for (int i = 0; i < columns.length; i++) { ColAttrMapping colAttrMapping = columnAttributeMappings.get(columns[i]); try { result[i] = colAttrMapping != null ? colAttrMapping.extractAttrValue(bo) : null; } catch (Exception e) { throw e instanceof RuntimeException ? (RuntimeException) e : new RuntimeException(e); } } return result; }
[ "public", "Object", "[", "]", "valuesForColumns", "(", "T", "bo", ",", "String", "...", "columns", ")", "{", "Map", "<", "String", ",", "ColAttrMapping", ">", "columnAttributeMappings", "=", "getColumnAttributeMappings", "(", ")", ";", "Object", "[", "]", "result", "=", "new", "Object", "[", "columns", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "columns", ".", "length", ";", "i", "++", ")", "{", "ColAttrMapping", "colAttrMapping", "=", "columnAttributeMappings", ".", "get", "(", "columns", "[", "i", "]", ")", ";", "try", "{", "result", "[", "i", "]", "=", "colAttrMapping", "!=", "null", "?", "colAttrMapping", ".", "extractAttrValue", "(", "bo", ")", ":", "null", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "e", "instanceof", "RuntimeException", "?", "(", "RuntimeException", ")", "e", ":", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", "return", "result", ";", "}" ]
Extract attribute values from a BO for corresponding DB table columns @param bo @return
[ "Extract", "attribute", "values", "from", "a", "BO", "for", "corresponding", "DB", "table", "columns" ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java#L392-L405
148,131
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java
AbstractGenericRowMapper.getAllColumns
public String[] getAllColumns() { if (cachedAllColumns == null) { cachedAllColumns = new ArrayList<String>(getColumnAttributeMappings().keySet()) .toArray(ArrayUtils.EMPTY_STRING_ARRAY); } return cachedAllColumns; }
java
public String[] getAllColumns() { if (cachedAllColumns == null) { cachedAllColumns = new ArrayList<String>(getColumnAttributeMappings().keySet()) .toArray(ArrayUtils.EMPTY_STRING_ARRAY); } return cachedAllColumns; }
[ "public", "String", "[", "]", "getAllColumns", "(", ")", "{", "if", "(", "cachedAllColumns", "==", "null", ")", "{", "cachedAllColumns", "=", "new", "ArrayList", "<", "String", ">", "(", "getColumnAttributeMappings", "(", ")", ".", "keySet", "(", ")", ")", ".", "toArray", "(", "ArrayUtils", ".", "EMPTY_STRING_ARRAY", ")", ";", "}", "return", "cachedAllColumns", ";", "}" ]
Get all DB table column names. @return
[ "Get", "all", "DB", "table", "column", "names", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/AbstractGenericRowMapper.java#L414-L420
148,132
tehuti-io/tehuti
src/main/java/io/tehuti/metrics/Sensor.java
Sensor.checkForest
private void checkForest(Set<Sensor> sensors) { if (!sensors.add(this)) throw new IllegalArgumentException("Circular dependency in sensors: " + name() + " is its own parent."); for (int i = 0; i < parents.length; i++) parents[i].checkForest(sensors); }
java
private void checkForest(Set<Sensor> sensors) { if (!sensors.add(this)) throw new IllegalArgumentException("Circular dependency in sensors: " + name() + " is its own parent."); for (int i = 0; i < parents.length; i++) parents[i].checkForest(sensors); }
[ "private", "void", "checkForest", "(", "Set", "<", "Sensor", ">", "sensors", ")", "{", "if", "(", "!", "sensors", ".", "add", "(", "this", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Circular dependency in sensors: \"", "+", "name", "(", ")", "+", "\" is its own parent.\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parents", ".", "length", ";", "i", "++", ")", "parents", "[", "i", "]", ".", "checkForest", "(", "sensors", ")", ";", "}" ]
Validate that this sensor doesn't end up referencing itself
[ "Validate", "that", "this", "sensor", "doesn", "t", "end", "up", "referencing", "itself" ]
c28a2f838eac775660efb270aafd2a464d712948
https://github.com/tehuti-io/tehuti/blob/c28a2f838eac775660efb270aafd2a464d712948/src/main/java/io/tehuti/metrics/Sensor.java#L59-L64
148,133
tehuti-io/tehuti
src/main/java/io/tehuti/metrics/Sensor.java
Sensor.checkQuotas
private void checkQuotas(long timeMs, boolean preCheck, double requestedValue) { for (int i = 0; i < this.metrics.size(); i++) { TehutiMetric metric = this.metrics.get(i); MetricConfig config = metric.config(); if (config != null) { Quota quota = config.quota(); if (quota != null) { // Only check the quota on the right time. If quota is set to check quota before recording, // only verify the usage in pre-check round. if (quota.isCheckQuotaBeforeRecording() ^ preCheck) { continue; } // If we check quota before recording, we should count on the value of the current request. // So we could prevent the usage of current request exceeding the quota. double value = preCheck? metric.extraValue(timeMs, requestedValue): metric.value(timeMs); if (!quota.acceptable(value)) { throw new QuotaViolationException( "Metric " + metric.name() + " is in violation of its " + quota.toString(), value); } } } } }
java
private void checkQuotas(long timeMs, boolean preCheck, double requestedValue) { for (int i = 0; i < this.metrics.size(); i++) { TehutiMetric metric = this.metrics.get(i); MetricConfig config = metric.config(); if (config != null) { Quota quota = config.quota(); if (quota != null) { // Only check the quota on the right time. If quota is set to check quota before recording, // only verify the usage in pre-check round. if (quota.isCheckQuotaBeforeRecording() ^ preCheck) { continue; } // If we check quota before recording, we should count on the value of the current request. // So we could prevent the usage of current request exceeding the quota. double value = preCheck? metric.extraValue(timeMs, requestedValue): metric.value(timeMs); if (!quota.acceptable(value)) { throw new QuotaViolationException( "Metric " + metric.name() + " is in violation of its " + quota.toString(), value); } } } } }
[ "private", "void", "checkQuotas", "(", "long", "timeMs", ",", "boolean", "preCheck", ",", "double", "requestedValue", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "metrics", ".", "size", "(", ")", ";", "i", "++", ")", "{", "TehutiMetric", "metric", "=", "this", ".", "metrics", ".", "get", "(", "i", ")", ";", "MetricConfig", "config", "=", "metric", ".", "config", "(", ")", ";", "if", "(", "config", "!=", "null", ")", "{", "Quota", "quota", "=", "config", ".", "quota", "(", ")", ";", "if", "(", "quota", "!=", "null", ")", "{", "// Only check the quota on the right time. If quota is set to check quota before recording,", "// only verify the usage in pre-check round.", "if", "(", "quota", ".", "isCheckQuotaBeforeRecording", "(", ")", "^", "preCheck", ")", "{", "continue", ";", "}", "// If we check quota before recording, we should count on the value of the current request.", "// So we could prevent the usage of current request exceeding the quota.", "double", "value", "=", "preCheck", "?", "metric", ".", "extraValue", "(", "timeMs", ",", "requestedValue", ")", ":", "metric", ".", "value", "(", "timeMs", ")", ";", "if", "(", "!", "quota", ".", "acceptable", "(", "value", ")", ")", "{", "throw", "new", "QuotaViolationException", "(", "\"Metric \"", "+", "metric", ".", "name", "(", ")", "+", "\" is in violation of its \"", "+", "quota", ".", "toString", "(", ")", ",", "value", ")", ";", "}", "}", "}", "}", "}" ]
Check if we have violated our quota for any metric that has a configured quota @param timeMs The current POSIX time in milliseconds
[ "Check", "if", "we", "have", "violated", "our", "quota", "for", "any", "metric", "that", "has", "a", "configured", "quota" ]
c28a2f838eac775660efb270aafd2a464d712948
https://github.com/tehuti-io/tehuti/blob/c28a2f838eac775660efb270aafd2a464d712948/src/main/java/io/tehuti/metrics/Sensor.java#L117-L139
148,134
tehuti-io/tehuti
src/main/java/io/tehuti/metrics/Sensor.java
Sensor.add
public synchronized Metric add(String name, String description, MeasurableStat stat, MetricConfig config) { MetricConfig statConfig = (config == null ? this.config : config); TehutiMetric metric = new TehutiMetric(this, Utils.notNull(name), Utils.notNull(description), Utils.notNull(stat), statConfig, time); this.registry.registerMetric(metric); this.metrics.add(metric); this.stats.add(stat); this.statConfigs.put(stat, statConfig); return metric; }
java
public synchronized Metric add(String name, String description, MeasurableStat stat, MetricConfig config) { MetricConfig statConfig = (config == null ? this.config : config); TehutiMetric metric = new TehutiMetric(this, Utils.notNull(name), Utils.notNull(description), Utils.notNull(stat), statConfig, time); this.registry.registerMetric(metric); this.metrics.add(metric); this.stats.add(stat); this.statConfigs.put(stat, statConfig); return metric; }
[ "public", "synchronized", "Metric", "add", "(", "String", "name", ",", "String", "description", ",", "MeasurableStat", "stat", ",", "MetricConfig", "config", ")", "{", "MetricConfig", "statConfig", "=", "(", "config", "==", "null", "?", "this", ".", "config", ":", "config", ")", ";", "TehutiMetric", "metric", "=", "new", "TehutiMetric", "(", "this", ",", "Utils", ".", "notNull", "(", "name", ")", ",", "Utils", ".", "notNull", "(", "description", ")", ",", "Utils", ".", "notNull", "(", "stat", ")", ",", "statConfig", ",", "time", ")", ";", "this", ".", "registry", ".", "registerMetric", "(", "metric", ")", ";", "this", ".", "metrics", ".", "add", "(", "metric", ")", ";", "this", ".", "stats", ".", "add", "(", "stat", ")", ";", "this", ".", "statConfigs", ".", "put", "(", "stat", ",", "statConfig", ")", ";", "return", "metric", ";", "}" ]
Register a metric with this sensor @param name The name of the metric @param description A description used when reporting the value @param stat The statistic to keep @param config A special configuration for this metric. If null use the sensor default configuration. @return a {@link Metric} instance representing the registered metric
[ "Register", "a", "metric", "with", "this", "sensor" ]
c28a2f838eac775660efb270aafd2a464d712948
https://github.com/tehuti-io/tehuti/blob/c28a2f838eac775660efb270aafd2a464d712948/src/main/java/io/tehuti/metrics/Sensor.java#L204-L217
148,135
bernardladenthin/streambuffer
src/main/java/net/ladenthin/streambuffer/StreamBuffer.java
StreamBuffer.trim
private void trim() throws IOException { if (isTrimShouldBeExecuted()) { /** * Need to store more bufs, may it is not possible to read out all * data at once. The available method only returns an int value * instead a long value. Store all read parts of the full buffer in * a deque. */ final Deque<byte[]> tmpBuffer = new LinkedList<>(); int available; // empty the current buffer, read out all bytes while ((available = is.available()) > 0) { final byte[] buf = new byte[available]; // read out of the buffer // and store the result to the tmpBuffer int read = is.read(buf); // should never happen assert read == available : "Read not enough bytes from buffer."; tmpBuffer.add(buf); } /** * Write all previously read parts back to the buffer. The buffer is * clean and contains no elements because all parts are read out. */ try { /** * The reference to the buffer deque is not reachable out of the * trim method. It is possible to ignore the safeWrite flag to * prevent not necessary clone operations. */ ignoreSafeWrite = true; while (!tmpBuffer.isEmpty()) { // pollFirst returns always a non null value, tmpBuffer is only filled with non null values os.write(tmpBuffer.pollFirst()); } } finally { ignoreSafeWrite = false; } } }
java
private void trim() throws IOException { if (isTrimShouldBeExecuted()) { /** * Need to store more bufs, may it is not possible to read out all * data at once. The available method only returns an int value * instead a long value. Store all read parts of the full buffer in * a deque. */ final Deque<byte[]> tmpBuffer = new LinkedList<>(); int available; // empty the current buffer, read out all bytes while ((available = is.available()) > 0) { final byte[] buf = new byte[available]; // read out of the buffer // and store the result to the tmpBuffer int read = is.read(buf); // should never happen assert read == available : "Read not enough bytes from buffer."; tmpBuffer.add(buf); } /** * Write all previously read parts back to the buffer. The buffer is * clean and contains no elements because all parts are read out. */ try { /** * The reference to the buffer deque is not reachable out of the * trim method. It is possible to ignore the safeWrite flag to * prevent not necessary clone operations. */ ignoreSafeWrite = true; while (!tmpBuffer.isEmpty()) { // pollFirst returns always a non null value, tmpBuffer is only filled with non null values os.write(tmpBuffer.pollFirst()); } } finally { ignoreSafeWrite = false; } } }
[ "private", "void", "trim", "(", ")", "throws", "IOException", "{", "if", "(", "isTrimShouldBeExecuted", "(", ")", ")", "{", "/**\n * Need to store more bufs, may it is not possible to read out all\n * data at once. The available method only returns an int value\n * instead a long value. Store all read parts of the full buffer in\n * a deque.\n */", "final", "Deque", "<", "byte", "[", "]", ">", "tmpBuffer", "=", "new", "LinkedList", "<>", "(", ")", ";", "int", "available", ";", "// empty the current buffer, read out all bytes", "while", "(", "(", "available", "=", "is", ".", "available", "(", ")", ")", ">", "0", ")", "{", "final", "byte", "[", "]", "buf", "=", "new", "byte", "[", "available", "]", ";", "// read out of the buffer", "// and store the result to the tmpBuffer", "int", "read", "=", "is", ".", "read", "(", "buf", ")", ";", "// should never happen", "assert", "read", "==", "available", ":", "\"Read not enough bytes from buffer.\"", ";", "tmpBuffer", ".", "add", "(", "buf", ")", ";", "}", "/**\n * Write all previously read parts back to the buffer. The buffer is\n * clean and contains no elements because all parts are read out.\n */", "try", "{", "/**\n * The reference to the buffer deque is not reachable out of the\n * trim method. It is possible to ignore the safeWrite flag to\n * prevent not necessary clone operations.\n */", "ignoreSafeWrite", "=", "true", ";", "while", "(", "!", "tmpBuffer", ".", "isEmpty", "(", ")", ")", "{", "// pollFirst returns always a non null value, tmpBuffer is only filled with non null values", "os", ".", "write", "(", "tmpBuffer", ".", "pollFirst", "(", ")", ")", ";", "}", "}", "finally", "{", "ignoreSafeWrite", "=", "false", ";", "}", "}", "}" ]
This method trims the buffer. This method can be invoked after every write operation. The method checks itself if the buffer should be trimmed or not.
[ "This", "method", "trims", "the", "buffer", ".", "This", "method", "can", "be", "invoked", "after", "every", "write", "operation", ".", "The", "method", "checks", "itself", "if", "the", "buffer", "should", "be", "trimmed", "or", "not", "." ]
46d586c95fc3316c7a92b76a556c932b9346015d
https://github.com/bernardladenthin/streambuffer/blob/46d586c95fc3316c7a92b76a556c932b9346015d/src/main/java/net/ladenthin/streambuffer/StreamBuffer.java#L239-L280
148,136
bernardladenthin/streambuffer
src/main/java/net/ladenthin/streambuffer/StreamBuffer.java
StreamBuffer.tryWaitForEnoughBytes
private long tryWaitForEnoughBytes(final long bytes) throws IOException { // we can only wait for a positive number of bytes assert bytes > 0 : "Number of bytes are negative or zero : " + bytes; // if we haven't enough bytes, the loop starts and wait for enough bytes while (bytes > availableBytes) { try { // first of all, check for a closed stream if (streamClosed) { // is the stream closed, return only the current available bytes return availableBytes; } // wait for a next loop run and block until a modification is signalized signalModification.acquire(); } catch (InterruptedException ex) { throw new IOException(ex); } } // return the available bytes (maybe higher as the required bytes) return availableBytes; }
java
private long tryWaitForEnoughBytes(final long bytes) throws IOException { // we can only wait for a positive number of bytes assert bytes > 0 : "Number of bytes are negative or zero : " + bytes; // if we haven't enough bytes, the loop starts and wait for enough bytes while (bytes > availableBytes) { try { // first of all, check for a closed stream if (streamClosed) { // is the stream closed, return only the current available bytes return availableBytes; } // wait for a next loop run and block until a modification is signalized signalModification.acquire(); } catch (InterruptedException ex) { throw new IOException(ex); } } // return the available bytes (maybe higher as the required bytes) return availableBytes; }
[ "private", "long", "tryWaitForEnoughBytes", "(", "final", "long", "bytes", ")", "throws", "IOException", "{", "// we can only wait for a positive number of bytes", "assert", "bytes", ">", "0", ":", "\"Number of bytes are negative or zero : \"", "+", "bytes", ";", "// if we haven't enough bytes, the loop starts and wait for enough bytes", "while", "(", "bytes", ">", "availableBytes", ")", "{", "try", "{", "// first of all, check for a closed stream", "if", "(", "streamClosed", ")", "{", "// is the stream closed, return only the current available bytes", "return", "availableBytes", ";", "}", "// wait for a next loop run and block until a modification is signalized", "signalModification", ".", "acquire", "(", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "throw", "new", "IOException", "(", "ex", ")", ";", "}", "}", "// return the available bytes (maybe higher as the required bytes)", "return", "availableBytes", ";", "}" ]
This method blocks until the stream is closed or enough bytes are available, which can be read from the buffer. @param bytes the number of bytes waiting for. @throws IOException If the thread is interrupted. @return The available bytes.
[ "This", "method", "blocks", "until", "the", "stream", "is", "closed", "or", "enough", "bytes", "are", "available", "which", "can", "be", "read", "from", "the", "buffer", "." ]
46d586c95fc3316c7a92b76a556c932b9346015d
https://github.com/bernardladenthin/streambuffer/blob/46d586c95fc3316c7a92b76a556c932b9346015d/src/main/java/net/ladenthin/streambuffer/StreamBuffer.java#L313-L333
148,137
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/nosql/lucene/LuceneKdStorage.java
LuceneKdStorage.createIndexField
protected Field createIndexField(String key, Object value) { if (key == null || value == null) { return null; } if (value instanceof Boolean) { return new IntPoint(key, ((Boolean) value).booleanValue() ? 1 : 0); } if (value instanceof Character) { return new StringField(key, value.toString(), Store.NO); } if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) { Number v = (Number) value; return new LongPoint(key, v.longValue()); } if (value instanceof Float || value instanceof Double) { Number v = (Number) value; return new DoublePoint(key, v.doubleValue()); } if (value instanceof Date) { return new StringField(key, DateFormatUtils.toString((Date) value, DATETIME_FORMAT), Store.NO); } if (value instanceof String) { String v = value.toString().trim(); return v.indexOf(' ') >= 0 ? new TextField(key, v, Store.NO) : new StringField(key, v, Store.NO); } return null; }
java
protected Field createIndexField(String key, Object value) { if (key == null || value == null) { return null; } if (value instanceof Boolean) { return new IntPoint(key, ((Boolean) value).booleanValue() ? 1 : 0); } if (value instanceof Character) { return new StringField(key, value.toString(), Store.NO); } if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) { Number v = (Number) value; return new LongPoint(key, v.longValue()); } if (value instanceof Float || value instanceof Double) { Number v = (Number) value; return new DoublePoint(key, v.doubleValue()); } if (value instanceof Date) { return new StringField(key, DateFormatUtils.toString((Date) value, DATETIME_FORMAT), Store.NO); } if (value instanceof String) { String v = value.toString().trim(); return v.indexOf(' ') >= 0 ? new TextField(key, v, Store.NO) : new StringField(key, v, Store.NO); } return null; }
[ "protected", "Field", "createIndexField", "(", "String", "key", ",", "Object", "value", ")", "{", "if", "(", "key", "==", "null", "||", "value", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "value", "instanceof", "Boolean", ")", "{", "return", "new", "IntPoint", "(", "key", ",", "(", "(", "Boolean", ")", "value", ")", ".", "booleanValue", "(", ")", "?", "1", ":", "0", ")", ";", "}", "if", "(", "value", "instanceof", "Character", ")", "{", "return", "new", "StringField", "(", "key", ",", "value", ".", "toString", "(", ")", ",", "Store", ".", "NO", ")", ";", "}", "if", "(", "value", "instanceof", "Byte", "||", "value", "instanceof", "Short", "||", "value", "instanceof", "Integer", "||", "value", "instanceof", "Long", ")", "{", "Number", "v", "=", "(", "Number", ")", "value", ";", "return", "new", "LongPoint", "(", "key", ",", "v", ".", "longValue", "(", ")", ")", ";", "}", "if", "(", "value", "instanceof", "Float", "||", "value", "instanceof", "Double", ")", "{", "Number", "v", "=", "(", "Number", ")", "value", ";", "return", "new", "DoublePoint", "(", "key", ",", "v", ".", "doubleValue", "(", ")", ")", ";", "}", "if", "(", "value", "instanceof", "Date", ")", "{", "return", "new", "StringField", "(", "key", ",", "DateFormatUtils", ".", "toString", "(", "(", "Date", ")", "value", ",", "DATETIME_FORMAT", ")", ",", "Store", ".", "NO", ")", ";", "}", "if", "(", "value", "instanceof", "String", ")", "{", "String", "v", "=", "value", ".", "toString", "(", ")", ".", "trim", "(", ")", ";", "return", "v", ".", "indexOf", "(", "'", "'", ")", ">=", "0", "?", "new", "TextField", "(", "key", ",", "v", ",", "Store", ".", "NO", ")", ":", "new", "StringField", "(", "key", ",", "v", ",", "Store", ".", "NO", ")", ";", "}", "return", "null", ";", "}" ]
Create index field for a document's field value. <ul> <li>Boolean: indexed as a {@link IntPoint} with value {@code 1=true/0=false}</li> <li>Character: indexed as a {@link StringField}</li> <li>Byte, Short, Integer, Long: indexed as a {@link LongPoint}</li> <li>Float, Double: indexed as a {@link DoublePoint}</li> <li>String: indexed as a {@link StringField} if value contains no space, {@link TextField} otherwise</li> <li>Date: indexed as a {@link StringField}, {@code Date} is converted to {@code String} with format {@link #DATETIME_FORMAT}.</li> </ul> @param key @param value @return
[ "Create", "index", "field", "for", "a", "document", "s", "field", "value", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/nosql/lucene/LuceneKdStorage.java#L190-L219
148,138
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/hook/AmLogServerAdapter.java
AmLogServerAdapter.init
public synchronized void init(int serverPort) { if (this.initialized) { return; } String hostname = null; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ex) { logger.warn("Get host failed. Use localhost.", ex); } logger.info("WebSocket server initialize. : HostName={}, Port={}, Path={}, Object={}", hostname, serverPort, "/", this.toString()); this.server = new Server(hostname, serverPort, "/", null, AmLogServerEndPoint.class); try { this.server.start(); } catch (DeploymentException ex) { logger.warn("WebSocket server initialize failed. Skip initialize.", ex); } this.initialized = true; }
java
public synchronized void init(int serverPort) { if (this.initialized) { return; } String hostname = null; try { hostname = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException ex) { logger.warn("Get host failed. Use localhost.", ex); } logger.info("WebSocket server initialize. : HostName={}, Port={}, Path={}, Object={}", hostname, serverPort, "/", this.toString()); this.server = new Server(hostname, serverPort, "/", null, AmLogServerEndPoint.class); try { this.server.start(); } catch (DeploymentException ex) { logger.warn("WebSocket server initialize failed. Skip initialize.", ex); } this.initialized = true; }
[ "public", "synchronized", "void", "init", "(", "int", "serverPort", ")", "{", "if", "(", "this", ".", "initialized", ")", "{", "return", ";", "}", "String", "hostname", "=", "null", ";", "try", "{", "hostname", "=", "InetAddress", ".", "getLocalHost", "(", ")", ".", "getHostName", "(", ")", ";", "}", "catch", "(", "UnknownHostException", "ex", ")", "{", "logger", ".", "warn", "(", "\"Get host failed. Use localhost.\"", ",", "ex", ")", ";", "}", "logger", ".", "info", "(", "\"WebSocket server initialize. : HostName={}, Port={}, Path={}, Object={}\"", ",", "hostname", ",", "serverPort", ",", "\"/\"", ",", "this", ".", "toString", "(", ")", ")", ";", "this", ".", "server", "=", "new", "Server", "(", "hostname", ",", "serverPort", ",", "\"/\"", ",", "null", ",", "AmLogServerEndPoint", ".", "class", ")", ";", "try", "{", "this", ".", "server", ".", "start", "(", ")", ";", "}", "catch", "(", "DeploymentException", "ex", ")", "{", "logger", ".", "warn", "(", "\"WebSocket server initialize failed. Skip initialize.\"", ",", "ex", ")", ";", "}", "this", ".", "initialized", "=", "true", ";", "}" ]
Initialize WebSocket server. @param serverPort serverPort
[ "Initialize", "WebSocket", "server", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/hook/AmLogServerAdapter.java#L104-L135
148,139
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/hook/AmLogServerAdapter.java
AmLogServerAdapter.emit
public void emit(ComponentInfo componentInfo, EmitInfo info) { if (this.sessions.size() == 0) { return; } Date nowTime = new Date(); DateFormat format = new SimpleDateFormat(DATE_PATTERN); String nowTimeStr = format.format(nowTime); Map<String, Object> objectMap = Maps.newHashMap(); objectMap.put("time", nowTimeStr); objectMap.put("component", componentInfo); objectMap.put("emitinfo", info); String logInfo; try { logInfo = this.mapper.writeValueAsString(objectMap); } catch (JsonProcessingException ex) { String msgFormat = "Event convert failed. Skip log output. : ComponentInfo={0}, EmitInfo={1}"; String message = MessageFormat.format(msgFormat, componentInfo, ToStringBuilder.reflectionToString(info, ToStringStyle.SHORT_PREFIX_STYLE)); logger.warn(message, ex); return; } for (Entry<String, Session> entry : this.sessions.entrySet()) { entry.getValue().getAsyncRemote().sendText(logInfo, this.handler); } }
java
public void emit(ComponentInfo componentInfo, EmitInfo info) { if (this.sessions.size() == 0) { return; } Date nowTime = new Date(); DateFormat format = new SimpleDateFormat(DATE_PATTERN); String nowTimeStr = format.format(nowTime); Map<String, Object> objectMap = Maps.newHashMap(); objectMap.put("time", nowTimeStr); objectMap.put("component", componentInfo); objectMap.put("emitinfo", info); String logInfo; try { logInfo = this.mapper.writeValueAsString(objectMap); } catch (JsonProcessingException ex) { String msgFormat = "Event convert failed. Skip log output. : ComponentInfo={0}, EmitInfo={1}"; String message = MessageFormat.format(msgFormat, componentInfo, ToStringBuilder.reflectionToString(info, ToStringStyle.SHORT_PREFIX_STYLE)); logger.warn(message, ex); return; } for (Entry<String, Session> entry : this.sessions.entrySet()) { entry.getValue().getAsyncRemote().sendText(logInfo, this.handler); } }
[ "public", "void", "emit", "(", "ComponentInfo", "componentInfo", ",", "EmitInfo", "info", ")", "{", "if", "(", "this", ".", "sessions", ".", "size", "(", ")", "==", "0", ")", "{", "return", ";", "}", "Date", "nowTime", "=", "new", "Date", "(", ")", ";", "DateFormat", "format", "=", "new", "SimpleDateFormat", "(", "DATE_PATTERN", ")", ";", "String", "nowTimeStr", "=", "format", ".", "format", "(", "nowTime", ")", ";", "Map", "<", "String", ",", "Object", ">", "objectMap", "=", "Maps", ".", "newHashMap", "(", ")", ";", "objectMap", ".", "put", "(", "\"time\"", ",", "nowTimeStr", ")", ";", "objectMap", ".", "put", "(", "\"component\"", ",", "componentInfo", ")", ";", "objectMap", ".", "put", "(", "\"emitinfo\"", ",", "info", ")", ";", "String", "logInfo", ";", "try", "{", "logInfo", "=", "this", ".", "mapper", ".", "writeValueAsString", "(", "objectMap", ")", ";", "}", "catch", "(", "JsonProcessingException", "ex", ")", "{", "String", "msgFormat", "=", "\"Event convert failed. Skip log output. : ComponentInfo={0}, EmitInfo={1}\"", ";", "String", "message", "=", "MessageFormat", ".", "format", "(", "msgFormat", ",", "componentInfo", ",", "ToStringBuilder", ".", "reflectionToString", "(", "info", ",", "ToStringStyle", ".", "SHORT_PREFIX_STYLE", ")", ")", ";", "logger", ".", "warn", "(", "message", ",", "ex", ")", ";", "return", ";", "}", "for", "(", "Entry", "<", "String", ",", "Session", ">", "entry", ":", "this", ".", "sessions", ".", "entrySet", "(", ")", ")", "{", "entry", ".", "getValue", "(", ")", ".", "getAsyncRemote", "(", ")", ".", "sendText", "(", "logInfo", ",", "this", ".", "handler", ")", ";", "}", "}" ]
Log emit info. @param componentInfo component info @param info emit info
[ "Log", "emit", "info", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/hook/AmLogServerAdapter.java#L175-L209
148,140
f2prateek/bundler
bundler/src/main/java/com/f2prateek/bundler/FragmentBundlerCompat.java
FragmentBundlerCompat.create
public static <F extends Fragment> FragmentBundlerCompat<F> create(F fragment) { return new FragmentBundlerCompat<F>(fragment); }
java
public static <F extends Fragment> FragmentBundlerCompat<F> create(F fragment) { return new FragmentBundlerCompat<F>(fragment); }
[ "public", "static", "<", "F", "extends", "Fragment", ">", "FragmentBundlerCompat", "<", "F", ">", "create", "(", "F", "fragment", ")", "{", "return", "new", "FragmentBundlerCompat", "<", "F", ">", "(", "fragment", ")", ";", "}" ]
Constructs a FragmentBundlerCompat for the provided Fragment instance @param fragment the fragment instance @return this bundler instance to chain method calls
[ "Constructs", "a", "FragmentBundlerCompat", "for", "the", "provided", "Fragment", "instance" ]
7efaba0541e5b564d5f3de2e7121c53512f5df45
https://github.com/f2prateek/bundler/blob/7efaba0541e5b564d5f3de2e7121c53512f5df45/bundler/src/main/java/com/f2prateek/bundler/FragmentBundlerCompat.java#L32-L34
148,141
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/util/RequestUtil.java
RequestUtil.convertHexDigit
private static byte convertHexDigit( final byte b ) { if ( ( b >= '0' ) && ( b <= '9' ) ) { return (byte) ( b - '0' ); } if ( ( b >= 'a' ) && ( b <= 'f' ) ) { return (byte) ( b - 'a' + 10 ); } if ( ( b >= 'A' ) && ( b <= 'F' ) ) { return (byte) ( b - 'A' + 10 ); } return 0; }
java
private static byte convertHexDigit( final byte b ) { if ( ( b >= '0' ) && ( b <= '9' ) ) { return (byte) ( b - '0' ); } if ( ( b >= 'a' ) && ( b <= 'f' ) ) { return (byte) ( b - 'a' + 10 ); } if ( ( b >= 'A' ) && ( b <= 'F' ) ) { return (byte) ( b - 'A' + 10 ); } return 0; }
[ "private", "static", "byte", "convertHexDigit", "(", "final", "byte", "b", ")", "{", "if", "(", "(", "b", ">=", "'", "'", ")", "&&", "(", "b", "<=", "'", "'", ")", ")", "{", "return", "(", "byte", ")", "(", "b", "-", "'", "'", ")", ";", "}", "if", "(", "(", "b", ">=", "'", "'", ")", "&&", "(", "b", "<=", "'", "'", ")", ")", "{", "return", "(", "byte", ")", "(", "b", "-", "'", "'", "+", "10", ")", ";", "}", "if", "(", "(", "b", ">=", "'", "'", ")", "&&", "(", "b", "<=", "'", "'", ")", ")", "{", "return", "(", "byte", ")", "(", "b", "-", "'", "'", "+", "10", ")", ";", "}", "return", "0", ";", "}" ]
Convert a byte character value to hexidecimal digit value. @param b the character value byte
[ "Convert", "a", "byte", "character", "value", "to", "hexidecimal", "digit", "value", "." ]
39bb7032fc75c1b67d3f2440dd1c234ead96cb9d
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/util/RequestUtil.java#L644-L659
148,142
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/util/RequestUtil.java
RequestUtil.putMapEntry
private static void putMapEntry( final Map<String, String[]> map, final String name, final String value ) { String[] newValues = null; final String[] oldValues = map.get( name ); if ( oldValues == null ) { newValues = new String[1]; newValues[0] = value; } else { newValues = new String[oldValues.length + 1]; System.arraycopy( oldValues, 0, newValues, 0, oldValues.length ); newValues[oldValues.length] = value; } map.put( name, newValues ); }
java
private static void putMapEntry( final Map<String, String[]> map, final String name, final String value ) { String[] newValues = null; final String[] oldValues = map.get( name ); if ( oldValues == null ) { newValues = new String[1]; newValues[0] = value; } else { newValues = new String[oldValues.length + 1]; System.arraycopy( oldValues, 0, newValues, 0, oldValues.length ); newValues[oldValues.length] = value; } map.put( name, newValues ); }
[ "private", "static", "void", "putMapEntry", "(", "final", "Map", "<", "String", ",", "String", "[", "]", ">", "map", ",", "final", "String", "name", ",", "final", "String", "value", ")", "{", "String", "[", "]", "newValues", "=", "null", ";", "final", "String", "[", "]", "oldValues", "=", "map", ".", "get", "(", "name", ")", ";", "if", "(", "oldValues", "==", "null", ")", "{", "newValues", "=", "new", "String", "[", "1", "]", ";", "newValues", "[", "0", "]", "=", "value", ";", "}", "else", "{", "newValues", "=", "new", "String", "[", "oldValues", ".", "length", "+", "1", "]", ";", "System", ".", "arraycopy", "(", "oldValues", ",", "0", ",", "newValues", ",", "0", ",", "oldValues", ".", "length", ")", ";", "newValues", "[", "oldValues", ".", "length", "]", "=", "value", ";", "}", "map", ".", "put", "(", "name", ",", "newValues", ")", ";", "}" ]
Put name and value pair in map. When name already exist, add value to array of values. @param map The map to populate @param name The parameter name @param value The parameter value
[ "Put", "name", "and", "value", "pair", "in", "map", ".", "When", "name", "already", "exist", "add", "value", "to", "array", "of", "values", "." ]
39bb7032fc75c1b67d3f2440dd1c234ead96cb9d
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/util/RequestUtil.java#L672-L688
148,143
sematext/ActionGenerator
ag-player-es/src/main/java/com/sematext/ag/es/sink/BulkJSONDataESSink.java
BulkJSONDataESSink.getBulkData
protected String getBulkData(List<SimpleDataEvent> events) { StringBuilder builder = new StringBuilder(); for (SimpleDataEvent event : events) { builder.append(JSONUtils.getElasticSearchBulkHeader(event, this.indexName, this.typeName)); builder.append("\n"); builder.append(JSONUtils.getElasticSearchAddDocument(event.pairs())); builder.append("\n"); } return builder.toString(); }
java
protected String getBulkData(List<SimpleDataEvent> events) { StringBuilder builder = new StringBuilder(); for (SimpleDataEvent event : events) { builder.append(JSONUtils.getElasticSearchBulkHeader(event, this.indexName, this.typeName)); builder.append("\n"); builder.append(JSONUtils.getElasticSearchAddDocument(event.pairs())); builder.append("\n"); } return builder.toString(); }
[ "protected", "String", "getBulkData", "(", "List", "<", "SimpleDataEvent", ">", "events", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "SimpleDataEvent", "event", ":", "events", ")", "{", "builder", ".", "append", "(", "JSONUtils", ".", "getElasticSearchBulkHeader", "(", "event", ",", "this", ".", "indexName", ",", "this", ".", "typeName", ")", ")", ";", "builder", ".", "append", "(", "\"\\n\"", ")", ";", "builder", ".", "append", "(", "JSONUtils", ".", "getElasticSearchAddDocument", "(", "event", ".", "pairs", "(", ")", ")", ")", ";", "builder", ".", "append", "(", "\"\\n\"", ")", ";", "}", "return", "builder", ".", "toString", "(", ")", ";", "}" ]
Returns ES bulk data. @return ES bulk data
[ "Returns", "ES", "bulk", "data", "." ]
10f4a3e680f20d7d151f5d40e6758aeb072d474f
https://github.com/sematext/ActionGenerator/blob/10f4a3e680f20d7d151f5d40e6758aeb072d474f/ag-player-es/src/main/java/com/sematext/ag/es/sink/BulkJSONDataESSink.java#L100-L109
148,144
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/BaseDataJsonFieldBo.java
BaseDataJsonFieldBo.setDataAttr
public BaseDataJsonFieldBo setDataAttr(String dPath, Object value) { if (value == null) { return removeDataAttr(dPath); } Lock lock = lockForWrite(); try { if (dataJson == null || dataJson instanceof MissingNode || dataJson instanceof NullNode) { // initialize the "data" String[] paths = DPathUtils.splitDpath(dPath); if (paths[0].matches("^\\[(.*?)\\]$")) { dataJson = JsonNodeFactory.instance.arrayNode(); } else { dataJson = JsonNodeFactory.instance.objectNode(); } } JacksonUtils.setValue(dataJson, dPath, value, true); return (BaseDataJsonFieldBo) setAttribute(ATTR_DATA, SerializationUtils.toJsonString(dataJson), false); } finally { lock.unlock(); } }
java
public BaseDataJsonFieldBo setDataAttr(String dPath, Object value) { if (value == null) { return removeDataAttr(dPath); } Lock lock = lockForWrite(); try { if (dataJson == null || dataJson instanceof MissingNode || dataJson instanceof NullNode) { // initialize the "data" String[] paths = DPathUtils.splitDpath(dPath); if (paths[0].matches("^\\[(.*?)\\]$")) { dataJson = JsonNodeFactory.instance.arrayNode(); } else { dataJson = JsonNodeFactory.instance.objectNode(); } } JacksonUtils.setValue(dataJson, dPath, value, true); return (BaseDataJsonFieldBo) setAttribute(ATTR_DATA, SerializationUtils.toJsonString(dataJson), false); } finally { lock.unlock(); } }
[ "public", "BaseDataJsonFieldBo", "setDataAttr", "(", "String", "dPath", ",", "Object", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "removeDataAttr", "(", "dPath", ")", ";", "}", "Lock", "lock", "=", "lockForWrite", "(", ")", ";", "try", "{", "if", "(", "dataJson", "==", "null", "||", "dataJson", "instanceof", "MissingNode", "||", "dataJson", "instanceof", "NullNode", ")", "{", "// initialize the \"data\"", "String", "[", "]", "paths", "=", "DPathUtils", ".", "splitDpath", "(", "dPath", ")", ";", "if", "(", "paths", "[", "0", "]", ".", "matches", "(", "\"^\\\\[(.*?)\\\\]$\"", ")", ")", "{", "dataJson", "=", "JsonNodeFactory", ".", "instance", ".", "arrayNode", "(", ")", ";", "}", "else", "{", "dataJson", "=", "JsonNodeFactory", ".", "instance", ".", "objectNode", "(", ")", ";", "}", "}", "JacksonUtils", ".", "setValue", "(", "dataJson", ",", "dPath", ",", "value", ",", "true", ")", ";", "return", "(", "BaseDataJsonFieldBo", ")", "setAttribute", "(", "ATTR_DATA", ",", "SerializationUtils", ".", "toJsonString", "(", "dataJson", ")", ",", "false", ")", ";", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "}" ]
Set a "data"'s sub-attribute using d-path. @param dPath @param value @return @see DPathUtils
[ "Set", "a", "data", "s", "sub", "-", "attribute", "using", "d", "-", "path", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/BaseDataJsonFieldBo.java#L187-L209
148,145
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/BaseDataJsonFieldBo.java
BaseDataJsonFieldBo.removeDataAttr
public BaseDataJsonFieldBo removeDataAttr(String dPath) { Lock lock = lockForWrite(); try { JacksonUtils.deleteValue(dataJson, dPath); return (BaseDataJsonFieldBo) setAttribute(ATTR_DATA, SerializationUtils.toJsonString(dataJson), false); } finally { lock.unlock(); } }
java
public BaseDataJsonFieldBo removeDataAttr(String dPath) { Lock lock = lockForWrite(); try { JacksonUtils.deleteValue(dataJson, dPath); return (BaseDataJsonFieldBo) setAttribute(ATTR_DATA, SerializationUtils.toJsonString(dataJson), false); } finally { lock.unlock(); } }
[ "public", "BaseDataJsonFieldBo", "removeDataAttr", "(", "String", "dPath", ")", "{", "Lock", "lock", "=", "lockForWrite", "(", ")", ";", "try", "{", "JacksonUtils", ".", "deleteValue", "(", "dataJson", ",", "dPath", ")", ";", "return", "(", "BaseDataJsonFieldBo", ")", "setAttribute", "(", "ATTR_DATA", ",", "SerializationUtils", ".", "toJsonString", "(", "dataJson", ")", ",", "false", ")", ";", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "}" ]
Remove a "data"'s sub-attribute using d-path. @param dPath @return @since 0.10.0
[ "Remove", "a", "data", "s", "sub", "-", "attribute", "using", "d", "-", "path", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/BaseDataJsonFieldBo.java#L218-L227
148,146
tehuti-io/tehuti
src/main/java/io/tehuti/metrics/stats/SampledStat.java
SampledStat.checkInit
private void checkInit(MetricConfig config, long now) { if (samples.size() == 0) { this.samples.add(newSample(now)); this.samples.add(newSample(now - config.timeWindowMs())); } }
java
private void checkInit(MetricConfig config, long now) { if (samples.size() == 0) { this.samples.add(newSample(now)); this.samples.add(newSample(now - config.timeWindowMs())); } }
[ "private", "void", "checkInit", "(", "MetricConfig", "config", ",", "long", "now", ")", "{", "if", "(", "samples", ".", "size", "(", ")", "==", "0", ")", "{", "this", ".", "samples", ".", "add", "(", "newSample", "(", "now", ")", ")", ";", "this", ".", "samples", ".", "add", "(", "newSample", "(", "now", "-", "config", ".", "timeWindowMs", "(", ")", ")", ")", ";", "}", "}" ]
Checks that the sample windows are properly initialized. In case there are no initialized sample yet, this creates two windows: one that begins now, as well as the previous window before that. This ensures that any measurement won't be calculated over an elapsed time of zero or few milliseconds. This is particularly significant for {@link io.tehuti.metrics.stats.Rate}, which can otherwise report disproportionately high values in those conditions. The downside of this approach is that Rates will under-report their values initially by virtue of carrying one empty window in their samples.
[ "Checks", "that", "the", "sample", "windows", "are", "properly", "initialized", "." ]
c28a2f838eac775660efb270aafd2a464d712948
https://github.com/tehuti-io/tehuti/blob/c28a2f838eac775660efb270aafd2a464d712948/src/main/java/io/tehuti/metrics/stats/SampledStat.java#L111-L116
148,147
tehuti-io/tehuti
src/main/java/io/tehuti/metrics/stats/SampledStat.java
SampledStat.purgeObsoleteSamples
protected void purgeObsoleteSamples(MetricConfig config, long now) { long expireAge = config.samples() * config.timeWindowMs(); for (int i = 0; i < samples.size(); i++) { Sample sample = this.samples.get(i); if (now - sample.lastWindowMs >= expireAge) { // The samples array is used as a circular list. The rank represents how many spots behind the current // window is window #i at. The current sample is rank 0, the next older sample is 1 and so on until // the oldest sample, which has a rank equal to samples.size() - 1. int rank = current - i; if (rank < 0) { rank += samples.size(); } // Here we reset the expired window to a time in the past that is offset proportionally to its rank. sample.reset(now - rank * config.timeWindowMs()); } } }
java
protected void purgeObsoleteSamples(MetricConfig config, long now) { long expireAge = config.samples() * config.timeWindowMs(); for (int i = 0; i < samples.size(); i++) { Sample sample = this.samples.get(i); if (now - sample.lastWindowMs >= expireAge) { // The samples array is used as a circular list. The rank represents how many spots behind the current // window is window #i at. The current sample is rank 0, the next older sample is 1 and so on until // the oldest sample, which has a rank equal to samples.size() - 1. int rank = current - i; if (rank < 0) { rank += samples.size(); } // Here we reset the expired window to a time in the past that is offset proportionally to its rank. sample.reset(now - rank * config.timeWindowMs()); } } }
[ "protected", "void", "purgeObsoleteSamples", "(", "MetricConfig", "config", ",", "long", "now", ")", "{", "long", "expireAge", "=", "config", ".", "samples", "(", ")", "*", "config", ".", "timeWindowMs", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "samples", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Sample", "sample", "=", "this", ".", "samples", ".", "get", "(", "i", ")", ";", "if", "(", "now", "-", "sample", ".", "lastWindowMs", ">=", "expireAge", ")", "{", "// The samples array is used as a circular list. The rank represents how many spots behind the current", "// window is window #i at. The current sample is rank 0, the next older sample is 1 and so on until", "// the oldest sample, which has a rank equal to samples.size() - 1.", "int", "rank", "=", "current", "-", "i", ";", "if", "(", "rank", "<", "0", ")", "{", "rank", "+=", "samples", ".", "size", "(", ")", ";", "}", "// Here we reset the expired window to a time in the past that is offset proportionally to its rank.", "sample", ".", "reset", "(", "now", "-", "rank", "*", "config", ".", "timeWindowMs", "(", ")", ")", ";", "}", "}", "}" ]
Timeout any windows that have expired in the absence of any events
[ "Timeout", "any", "windows", "that", "have", "expired", "in", "the", "absence", "of", "any", "events" ]
c28a2f838eac775660efb270aafd2a464d712948
https://github.com/tehuti-io/tehuti/blob/c28a2f838eac775660efb270aafd2a464d712948/src/main/java/io/tehuti/metrics/stats/SampledStat.java#L125-L141
148,148
fuinorg/objects4j
src/main/java/org/fuin/objects4j/ui/TableColumnInfo.java
TableColumnInfo.create
public static List<TableColumnInfo> create(@NotNull final Class<?> clasz, @NotNull final Locale locale) { Contract.requireArgNotNull("clasz", clasz); Contract.requireArgNotNull("locale", locale); final List<TableColumnInfo> list = new ArrayList<TableColumnInfo>(); final Field[] fields = clasz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { final TableColumnInfo tableColumnInfo = create(fields[i], locale); if (tableColumnInfo != null) { list.add(tableColumnInfo); } } Collections.sort(list); return list; }
java
public static List<TableColumnInfo> create(@NotNull final Class<?> clasz, @NotNull final Locale locale) { Contract.requireArgNotNull("clasz", clasz); Contract.requireArgNotNull("locale", locale); final List<TableColumnInfo> list = new ArrayList<TableColumnInfo>(); final Field[] fields = clasz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { final TableColumnInfo tableColumnInfo = create(fields[i], locale); if (tableColumnInfo != null) { list.add(tableColumnInfo); } } Collections.sort(list); return list; }
[ "public", "static", "List", "<", "TableColumnInfo", ">", "create", "(", "@", "NotNull", "final", "Class", "<", "?", ">", "clasz", ",", "@", "NotNull", "final", "Locale", "locale", ")", "{", "Contract", ".", "requireArgNotNull", "(", "\"clasz\"", ",", "clasz", ")", ";", "Contract", ".", "requireArgNotNull", "(", "\"locale\"", ",", "locale", ")", ";", "final", "List", "<", "TableColumnInfo", ">", "list", "=", "new", "ArrayList", "<", "TableColumnInfo", ">", "(", ")", ";", "final", "Field", "[", "]", "fields", "=", "clasz", ".", "getDeclaredFields", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "fields", ".", "length", ";", "i", "++", ")", "{", "final", "TableColumnInfo", "tableColumnInfo", "=", "create", "(", "fields", "[", "i", "]", ",", "locale", ")", ";", "if", "(", "tableColumnInfo", "!=", "null", ")", "{", "list", ".", "add", "(", "tableColumnInfo", ")", ";", "}", "}", "Collections", ".", "sort", "(", "list", ")", ";", "return", "list", ";", "}" ]
Return a list of table column informations for the given class. @param clasz Class to check for <code>@TableColumn</code> and <code>@Label</code> annotations. @param locale Locale to use. @return List of table columns sorted by the position.
[ "Return", "a", "list", "of", "table", "column", "informations", "for", "the", "given", "class", "." ]
e7f278b5bae073ebb6a76053650571c718f36246
https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/ui/TableColumnInfo.java#L214-L229
148,149
fuinorg/objects4j
src/main/java/org/fuin/objects4j/ui/TableColumnInfo.java
TableColumnInfo.create
public static TableColumnInfo create(@NotNull final Field field, @NotNull final Locale locale) { Contract.requireArgNotNull("field", field); Contract.requireArgNotNull("locale", locale); final TableColumn tableColumn = field.getAnnotation(TableColumn.class); if (tableColumn == null) { return null; } final AnnotationAnalyzer analyzer = new AnnotationAnalyzer(); final FieldTextInfo labelInfo = analyzer.createFieldInfo(field, locale, Label.class); final FieldTextInfo shortLabelInfo = analyzer.createFieldInfo(field, locale, ShortLabel.class); final FieldTextInfo tooltipInfo = analyzer.createFieldInfo(field, locale, Tooltip.class); final int pos = tableColumn.pos(); final FontSize fontSize = new FontSize(tableColumn.width(), tableColumn.unit()); final String getter = getGetter(tableColumn, field.getName()); final String labelText; if (labelInfo == null) { labelText = null; } else { labelText = labelInfo.getTextOrField(); } final String shortLabelText; if (shortLabelInfo == null) { shortLabelText = null; } else { shortLabelText = shortLabelInfo.getText(); } final String tooltipText; if (tooltipInfo == null) { tooltipText = null; } else { tooltipText = tooltipInfo.getText(); } return new TableColumnInfo(field, labelText, shortLabelText, tooltipText, pos, fontSize, getter); }
java
public static TableColumnInfo create(@NotNull final Field field, @NotNull final Locale locale) { Contract.requireArgNotNull("field", field); Contract.requireArgNotNull("locale", locale); final TableColumn tableColumn = field.getAnnotation(TableColumn.class); if (tableColumn == null) { return null; } final AnnotationAnalyzer analyzer = new AnnotationAnalyzer(); final FieldTextInfo labelInfo = analyzer.createFieldInfo(field, locale, Label.class); final FieldTextInfo shortLabelInfo = analyzer.createFieldInfo(field, locale, ShortLabel.class); final FieldTextInfo tooltipInfo = analyzer.createFieldInfo(field, locale, Tooltip.class); final int pos = tableColumn.pos(); final FontSize fontSize = new FontSize(tableColumn.width(), tableColumn.unit()); final String getter = getGetter(tableColumn, field.getName()); final String labelText; if (labelInfo == null) { labelText = null; } else { labelText = labelInfo.getTextOrField(); } final String shortLabelText; if (shortLabelInfo == null) { shortLabelText = null; } else { shortLabelText = shortLabelInfo.getText(); } final String tooltipText; if (tooltipInfo == null) { tooltipText = null; } else { tooltipText = tooltipInfo.getText(); } return new TableColumnInfo(field, labelText, shortLabelText, tooltipText, pos, fontSize, getter); }
[ "public", "static", "TableColumnInfo", "create", "(", "@", "NotNull", "final", "Field", "field", ",", "@", "NotNull", "final", "Locale", "locale", ")", "{", "Contract", ".", "requireArgNotNull", "(", "\"field\"", ",", "field", ")", ";", "Contract", ".", "requireArgNotNull", "(", "\"locale\"", ",", "locale", ")", ";", "final", "TableColumn", "tableColumn", "=", "field", ".", "getAnnotation", "(", "TableColumn", ".", "class", ")", ";", "if", "(", "tableColumn", "==", "null", ")", "{", "return", "null", ";", "}", "final", "AnnotationAnalyzer", "analyzer", "=", "new", "AnnotationAnalyzer", "(", ")", ";", "final", "FieldTextInfo", "labelInfo", "=", "analyzer", ".", "createFieldInfo", "(", "field", ",", "locale", ",", "Label", ".", "class", ")", ";", "final", "FieldTextInfo", "shortLabelInfo", "=", "analyzer", ".", "createFieldInfo", "(", "field", ",", "locale", ",", "ShortLabel", ".", "class", ")", ";", "final", "FieldTextInfo", "tooltipInfo", "=", "analyzer", ".", "createFieldInfo", "(", "field", ",", "locale", ",", "Tooltip", ".", "class", ")", ";", "final", "int", "pos", "=", "tableColumn", ".", "pos", "(", ")", ";", "final", "FontSize", "fontSize", "=", "new", "FontSize", "(", "tableColumn", ".", "width", "(", ")", ",", "tableColumn", ".", "unit", "(", ")", ")", ";", "final", "String", "getter", "=", "getGetter", "(", "tableColumn", ",", "field", ".", "getName", "(", ")", ")", ";", "final", "String", "labelText", ";", "if", "(", "labelInfo", "==", "null", ")", "{", "labelText", "=", "null", ";", "}", "else", "{", "labelText", "=", "labelInfo", ".", "getTextOrField", "(", ")", ";", "}", "final", "String", "shortLabelText", ";", "if", "(", "shortLabelInfo", "==", "null", ")", "{", "shortLabelText", "=", "null", ";", "}", "else", "{", "shortLabelText", "=", "shortLabelInfo", ".", "getText", "(", ")", ";", "}", "final", "String", "tooltipText", ";", "if", "(", "tooltipInfo", "==", "null", ")", "{", "tooltipText", "=", "null", ";", "}", "else", "{", "tooltipText", "=", "tooltipInfo", ".", "getText", "(", ")", ";", "}", "return", "new", "TableColumnInfo", "(", "field", ",", "labelText", ",", "shortLabelText", ",", "tooltipText", ",", "pos", ",", "fontSize", ",", "getter", ")", ";", "}" ]
Return the table column information for a given field. @param field Field to check for <code>@TableColumn</code> and <code>@Label</code> annotations. @param locale Locale to use. @return Information or <code>null</code>.
[ "Return", "the", "table", "column", "information", "for", "a", "given", "field", "." ]
e7f278b5bae073ebb6a76053650571c718f36246
https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/ui/TableColumnInfo.java#L241-L281
148,150
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/methods/DoCopy.java
DoCopy.parseDestinationHeader
private String parseDestinationHeader( final WebdavRequest req, final WebdavResponse resp ) throws IOException { String destinationPath = req.getHeader( "Destination" ); if ( destinationPath == null ) { resp.sendError( WebdavStatus.SC_BAD_REQUEST ); return null; } // Remove url encoding from destination destinationPath = RequestUtil.URLDecode( destinationPath, "UTF8" ); final int protocolIndex = destinationPath.indexOf( "://" ); if ( protocolIndex >= 0 ) { // if the Destination URL contains the protocol, we can safely // trim everything upto the first "/" character after "://" final int firstSeparator = destinationPath.indexOf( "/", protocolIndex + 4 ); if ( firstSeparator < 0 ) { destinationPath = "/"; } else { destinationPath = destinationPath.substring( firstSeparator ); } } else { final String hostName = req.getServerName(); if ( ( hostName != null ) && ( destinationPath.startsWith( hostName ) ) ) { destinationPath = destinationPath.substring( hostName.length() ); } final int portIndex = destinationPath.indexOf( ":" ); if ( portIndex >= 0 ) { destinationPath = destinationPath.substring( portIndex ); } if ( destinationPath.startsWith( ":" ) ) { final int firstSeparator = destinationPath.indexOf( "/" ); if ( firstSeparator < 0 ) { destinationPath = "/"; } else { destinationPath = destinationPath.substring( firstSeparator ); } } } // Normalize destination path (remove '.' and' ..') destinationPath = normalize( destinationPath ); final String contextPath = req.getContextPath(); if ( ( contextPath != null ) && ( destinationPath.startsWith( contextPath ) ) ) { destinationPath = destinationPath.substring( contextPath.length() ); } final String pathInfo = req.getPathInfo(); if ( pathInfo != null ) { final String servletPath = req.getServicePath(); if ( ( servletPath != null ) && ( destinationPath.startsWith( servletPath ) ) ) { destinationPath = destinationPath.substring( servletPath.length() ); } } return destinationPath; }
java
private String parseDestinationHeader( final WebdavRequest req, final WebdavResponse resp ) throws IOException { String destinationPath = req.getHeader( "Destination" ); if ( destinationPath == null ) { resp.sendError( WebdavStatus.SC_BAD_REQUEST ); return null; } // Remove url encoding from destination destinationPath = RequestUtil.URLDecode( destinationPath, "UTF8" ); final int protocolIndex = destinationPath.indexOf( "://" ); if ( protocolIndex >= 0 ) { // if the Destination URL contains the protocol, we can safely // trim everything upto the first "/" character after "://" final int firstSeparator = destinationPath.indexOf( "/", protocolIndex + 4 ); if ( firstSeparator < 0 ) { destinationPath = "/"; } else { destinationPath = destinationPath.substring( firstSeparator ); } } else { final String hostName = req.getServerName(); if ( ( hostName != null ) && ( destinationPath.startsWith( hostName ) ) ) { destinationPath = destinationPath.substring( hostName.length() ); } final int portIndex = destinationPath.indexOf( ":" ); if ( portIndex >= 0 ) { destinationPath = destinationPath.substring( portIndex ); } if ( destinationPath.startsWith( ":" ) ) { final int firstSeparator = destinationPath.indexOf( "/" ); if ( firstSeparator < 0 ) { destinationPath = "/"; } else { destinationPath = destinationPath.substring( firstSeparator ); } } } // Normalize destination path (remove '.' and' ..') destinationPath = normalize( destinationPath ); final String contextPath = req.getContextPath(); if ( ( contextPath != null ) && ( destinationPath.startsWith( contextPath ) ) ) { destinationPath = destinationPath.substring( contextPath.length() ); } final String pathInfo = req.getPathInfo(); if ( pathInfo != null ) { final String servletPath = req.getServicePath(); if ( ( servletPath != null ) && ( destinationPath.startsWith( servletPath ) ) ) { destinationPath = destinationPath.substring( servletPath.length() ); } } return destinationPath; }
[ "private", "String", "parseDestinationHeader", "(", "final", "WebdavRequest", "req", ",", "final", "WebdavResponse", "resp", ")", "throws", "IOException", "{", "String", "destinationPath", "=", "req", ".", "getHeader", "(", "\"Destination\"", ")", ";", "if", "(", "destinationPath", "==", "null", ")", "{", "resp", ".", "sendError", "(", "WebdavStatus", ".", "SC_BAD_REQUEST", ")", ";", "return", "null", ";", "}", "// Remove url encoding from destination", "destinationPath", "=", "RequestUtil", ".", "URLDecode", "(", "destinationPath", ",", "\"UTF8\"", ")", ";", "final", "int", "protocolIndex", "=", "destinationPath", ".", "indexOf", "(", "\"://\"", ")", ";", "if", "(", "protocolIndex", ">=", "0", ")", "{", "// if the Destination URL contains the protocol, we can safely", "// trim everything upto the first \"/\" character after \"://\"", "final", "int", "firstSeparator", "=", "destinationPath", ".", "indexOf", "(", "\"/\"", ",", "protocolIndex", "+", "4", ")", ";", "if", "(", "firstSeparator", "<", "0", ")", "{", "destinationPath", "=", "\"/\"", ";", "}", "else", "{", "destinationPath", "=", "destinationPath", ".", "substring", "(", "firstSeparator", ")", ";", "}", "}", "else", "{", "final", "String", "hostName", "=", "req", ".", "getServerName", "(", ")", ";", "if", "(", "(", "hostName", "!=", "null", ")", "&&", "(", "destinationPath", ".", "startsWith", "(", "hostName", ")", ")", ")", "{", "destinationPath", "=", "destinationPath", ".", "substring", "(", "hostName", ".", "length", "(", ")", ")", ";", "}", "final", "int", "portIndex", "=", "destinationPath", ".", "indexOf", "(", "\":\"", ")", ";", "if", "(", "portIndex", ">=", "0", ")", "{", "destinationPath", "=", "destinationPath", ".", "substring", "(", "portIndex", ")", ";", "}", "if", "(", "destinationPath", ".", "startsWith", "(", "\":\"", ")", ")", "{", "final", "int", "firstSeparator", "=", "destinationPath", ".", "indexOf", "(", "\"/\"", ")", ";", "if", "(", "firstSeparator", "<", "0", ")", "{", "destinationPath", "=", "\"/\"", ";", "}", "else", "{", "destinationPath", "=", "destinationPath", ".", "substring", "(", "firstSeparator", ")", ";", "}", "}", "}", "// Normalize destination path (remove '.' and' ..')", "destinationPath", "=", "normalize", "(", "destinationPath", ")", ";", "final", "String", "contextPath", "=", "req", ".", "getContextPath", "(", ")", ";", "if", "(", "(", "contextPath", "!=", "null", ")", "&&", "(", "destinationPath", ".", "startsWith", "(", "contextPath", ")", ")", ")", "{", "destinationPath", "=", "destinationPath", ".", "substring", "(", "contextPath", ".", "length", "(", ")", ")", ";", "}", "final", "String", "pathInfo", "=", "req", ".", "getPathInfo", "(", ")", ";", "if", "(", "pathInfo", "!=", "null", ")", "{", "final", "String", "servletPath", "=", "req", ".", "getServicePath", "(", ")", ";", "if", "(", "(", "servletPath", "!=", "null", ")", "&&", "(", "destinationPath", ".", "startsWith", "(", "servletPath", ")", ")", ")", "{", "destinationPath", "=", "destinationPath", ".", "substring", "(", "servletPath", ".", "length", "(", ")", ")", ";", "}", "}", "return", "destinationPath", ";", "}" ]
Parses and normalizes the destination header. @param req Servlet request @param resp Servlet response @return destinationPath @throws IOException if an error occurs while sending response
[ "Parses", "and", "normalizes", "the", "destination", "header", "." ]
39bb7032fc75c1b67d3f2440dd1c234ead96cb9d
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/methods/DoCopy.java#L416-L493
148,151
f2prateek/bundler
bundler/src/main/java/com/f2prateek/bundler/FragmentBundler.java
FragmentBundler.create
public static <F extends Fragment> FragmentBundler<F> create(F fragment) { return new FragmentBundler<F>(fragment); }
java
public static <F extends Fragment> FragmentBundler<F> create(F fragment) { return new FragmentBundler<F>(fragment); }
[ "public", "static", "<", "F", "extends", "Fragment", ">", "FragmentBundler", "<", "F", ">", "create", "(", "F", "fragment", ")", "{", "return", "new", "FragmentBundler", "<", "F", ">", "(", "fragment", ")", ";", "}" ]
Constructs a FragmentBundler for the provided Fragment instance @param fragment the fragment instance @return this bundler instance to chain method calls
[ "Constructs", "a", "FragmentBundler", "for", "the", "provided", "Fragment", "instance" ]
7efaba0541e5b564d5f3de2e7121c53512f5df45
https://github.com/f2prateek/bundler/blob/7efaba0541e5b564d5f3de2e7121c53512f5df45/bundler/src/main/java/com/f2prateek/bundler/FragmentBundler.java#L31-L33
148,152
f2prateek/bundler
bundler/src/main/java/com/f2prateek/bundler/FragmentBundler.java
FragmentBundler.create
public static <F extends Fragment> FragmentBundler<F> create(Class<F> klass) { try { return create(klass.newInstance()); } catch (InstantiationException e) { throw new IllegalArgumentException("Class must have a no-arguments constructor."); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Class must have a no-arguments constructor."); } }
java
public static <F extends Fragment> FragmentBundler<F> create(Class<F> klass) { try { return create(klass.newInstance()); } catch (InstantiationException e) { throw new IllegalArgumentException("Class must have a no-arguments constructor."); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Class must have a no-arguments constructor."); } }
[ "public", "static", "<", "F", "extends", "Fragment", ">", "FragmentBundler", "<", "F", ">", "create", "(", "Class", "<", "F", ">", "klass", ")", "{", "try", "{", "return", "create", "(", "klass", ".", "newInstance", "(", ")", ")", ";", "}", "catch", "(", "InstantiationException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Class must have a no-arguments constructor.\"", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Class must have a no-arguments constructor.\"", ")", ";", "}", "}" ]
Constructs a FragmentBundler for the provided Fragment class @param klass the fragment class @return this bundler instance to chain method calls
[ "Constructs", "a", "FragmentBundler", "for", "the", "provided", "Fragment", "class" ]
7efaba0541e5b564d5f3de2e7121c53512f5df45
https://github.com/f2prateek/bundler/blob/7efaba0541e5b564d5f3de2e7121c53512f5df45/bundler/src/main/java/com/f2prateek/bundler/FragmentBundler.java#L41-L49
148,153
sematext/ActionGenerator
ag-player/src/main/java/com/sematext/ag/config/Configurable.java
Configurable.init
public void init() { String fileName = null; try { fileName = System.getProperty(SYSTEM_PROPERTY); if (fileName == null) { LOG.info("User file configuration not provided, reading default file."); readConfiguration(getClass().getResourceAsStream(DEFAULT_FILE_NAME)); } else { try { FileInputStream stream = new FileInputStream(fileName); LOG.info("Reading configuration file: " + fileName); readConfiguration(stream); } catch (FileNotFoundException fnfe) { LOG.info("Error using user provided configuration file, reading default file."); readConfiguration(getClass().getResourceAsStream(DEFAULT_FILE_NAME)); } } } catch (IOException ioe) { LOG.error("Error reading provided " + fileName + " file"); } }
java
public void init() { String fileName = null; try { fileName = System.getProperty(SYSTEM_PROPERTY); if (fileName == null) { LOG.info("User file configuration not provided, reading default file."); readConfiguration(getClass().getResourceAsStream(DEFAULT_FILE_NAME)); } else { try { FileInputStream stream = new FileInputStream(fileName); LOG.info("Reading configuration file: " + fileName); readConfiguration(stream); } catch (FileNotFoundException fnfe) { LOG.info("Error using user provided configuration file, reading default file."); readConfiguration(getClass().getResourceAsStream(DEFAULT_FILE_NAME)); } } } catch (IOException ioe) { LOG.error("Error reading provided " + fileName + " file"); } }
[ "public", "void", "init", "(", ")", "{", "String", "fileName", "=", "null", ";", "try", "{", "fileName", "=", "System", ".", "getProperty", "(", "SYSTEM_PROPERTY", ")", ";", "if", "(", "fileName", "==", "null", ")", "{", "LOG", ".", "info", "(", "\"User file configuration not provided, reading default file.\"", ")", ";", "readConfiguration", "(", "getClass", "(", ")", ".", "getResourceAsStream", "(", "DEFAULT_FILE_NAME", ")", ")", ";", "}", "else", "{", "try", "{", "FileInputStream", "stream", "=", "new", "FileInputStream", "(", "fileName", ")", ";", "LOG", ".", "info", "(", "\"Reading configuration file: \"", "+", "fileName", ")", ";", "readConfiguration", "(", "stream", ")", ";", "}", "catch", "(", "FileNotFoundException", "fnfe", ")", "{", "LOG", ".", "info", "(", "\"Error using user provided configuration file, reading default file.\"", ")", ";", "readConfiguration", "(", "getClass", "(", ")", ".", "getResourceAsStream", "(", "DEFAULT_FILE_NAME", ")", ")", ";", "}", "}", "}", "catch", "(", "IOException", "ioe", ")", "{", "LOG", ".", "error", "(", "\"Error reading provided \"", "+", "fileName", "+", "\" file\"", ")", ";", "}", "}" ]
Initializes configuration. @throws IOException thrown when initialization error occurs
[ "Initializes", "configuration", "." ]
10f4a3e680f20d7d151f5d40e6758aeb072d474f
https://github.com/sematext/ActionGenerator/blob/10f4a3e680f20d7d151f5d40e6758aeb072d474f/ag-player/src/main/java/com/sematext/ag/config/Configurable.java#L45-L65
148,154
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/entity/StreamMessage.java
StreamMessage.addField
@SuppressWarnings({"unchecked", "rawtypes"}) public void addField(String key, Object value) { if (this.body == null || Map.class.isAssignableFrom(this.body.getClass()) == false) { this.body = Maps.newLinkedHashMap(); } ((Map) this.body).put(key, value); }
java
@SuppressWarnings({"unchecked", "rawtypes"}) public void addField(String key, Object value) { if (this.body == null || Map.class.isAssignableFrom(this.body.getClass()) == false) { this.body = Maps.newLinkedHashMap(); } ((Map) this.body).put(key, value); }
[ "@", "SuppressWarnings", "(", "{", "\"unchecked\"", ",", "\"rawtypes\"", "}", ")", "public", "void", "addField", "(", "String", "key", ",", "Object", "value", ")", "{", "if", "(", "this", ".", "body", "==", "null", "||", "Map", ".", "class", ".", "isAssignableFrom", "(", "this", ".", "body", ".", "getClass", "(", ")", ")", "==", "false", ")", "{", "this", ".", "body", "=", "Maps", ".", "newLinkedHashMap", "(", ")", ";", "}", "(", "(", "Map", ")", "this", ".", "body", ")", ".", "put", "(", "key", ",", "value", ")", ";", "}" ]
Add field to message body. @param key key @param value value
[ "Add", "field", "to", "message", "body", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/entity/StreamMessage.java#L94-L103
148,155
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/entity/StreamMessage.java
StreamMessage.getField
@SuppressWarnings("rawtypes") public Object getField(String key) { if (this.body == null || Map.class.isAssignableFrom(this.body.getClass()) == false) { return null; } return ((Map) this.body).get(key); }
java
@SuppressWarnings("rawtypes") public Object getField(String key) { if (this.body == null || Map.class.isAssignableFrom(this.body.getClass()) == false) { return null; } return ((Map) this.body).get(key); }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "public", "Object", "getField", "(", "String", "key", ")", "{", "if", "(", "this", ".", "body", "==", "null", "||", "Map", ".", "class", ".", "isAssignableFrom", "(", "this", ".", "body", ".", "getClass", "(", ")", ")", "==", "false", ")", "{", "return", "null", ";", "}", "return", "(", "(", "Map", ")", "this", ".", "body", ")", ".", "get", "(", "key", ")", ";", "}" ]
Get field from message body. @param key key @return field mapped key
[ "Get", "field", "from", "message", "body", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/entity/StreamMessage.java#L111-L120
148,156
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/util/XMLWriter.java
XMLWriter.writeProperty
public void writeProperty(String name, String value) { writeElement(name, OPENING); _buffer.append(value); writeElement(name, CLOSING); }
java
public void writeProperty(String name, String value) { writeElement(name, OPENING); _buffer.append(value); writeElement(name, CLOSING); }
[ "public", "void", "writeProperty", "(", "String", "name", ",", "String", "value", ")", "{", "writeElement", "(", "name", ",", "OPENING", ")", ";", "_buffer", ".", "append", "(", "value", ")", ";", "writeElement", "(", "name", ",", "CLOSING", ")", ";", "}" ]
Write property to the XML. @param name Property name @param value Property value
[ "Write", "property", "to", "the", "XML", "." ]
39bb7032fc75c1b67d3f2440dd1c234ead96cb9d
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/util/XMLWriter.java#L106-L110
148,157
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/util/XMLWriter.java
XMLWriter.writeData
public void writeData(String data) { _buffer.append("<![CDATA["); _buffer.append( data); _buffer.append( "]]>"); }
java
public void writeData(String data) { _buffer.append("<![CDATA["); _buffer.append( data); _buffer.append( "]]>"); }
[ "public", "void", "writeData", "(", "String", "data", ")", "{", "_buffer", ".", "append", "(", "\"<![CDATA[\"", ")", ";", "_buffer", ".", "append", "(", "data", ")", ";", "_buffer", ".", "append", "(", "\"]]>\"", ")", ";", "}" ]
Write data. @param data Data to append
[ "Write", "data", "." ]
39bb7032fc75c1b67d3f2440dd1c234ead96cb9d
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/util/XMLWriter.java#L200-L204
148,158
RestComm/jain-slee.xcap
resources/xcap-client/ra/src/main/java/org/restcomm/slee/resource/xcapclient/XCAPClientResourceAdaptor.java
XCAPClientResourceAdaptor.processResponseEvent
public void processResponseEvent(FireableEventType eventType, ResponseEvent event, XCAPResourceAdaptorActivityHandle handle){ if (tracer.isFineEnabled()) { tracer.fine("NEW RESPONSE EVENT"); } try { sleeEndpoint.fireEvent(handle,eventType, event, null, null); } catch (Exception e) { tracer.severe("unable to fire event",e); } }
java
public void processResponseEvent(FireableEventType eventType, ResponseEvent event, XCAPResourceAdaptorActivityHandle handle){ if (tracer.isFineEnabled()) { tracer.fine("NEW RESPONSE EVENT"); } try { sleeEndpoint.fireEvent(handle,eventType, event, null, null); } catch (Exception e) { tracer.severe("unable to fire event",e); } }
[ "public", "void", "processResponseEvent", "(", "FireableEventType", "eventType", ",", "ResponseEvent", "event", ",", "XCAPResourceAdaptorActivityHandle", "handle", ")", "{", "if", "(", "tracer", ".", "isFineEnabled", "(", ")", ")", "{", "tracer", ".", "fine", "(", "\"NEW RESPONSE EVENT\"", ")", ";", "}", "try", "{", "sleeEndpoint", ".", "fireEvent", "(", "handle", ",", "eventType", ",", "event", ",", "null", ",", "null", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "tracer", ".", "severe", "(", "\"unable to fire event\"", ",", "e", ")", ";", "}", "}" ]
Receives an Event and sends it to the SLEE @param event @param handle
[ "Receives", "an", "Event", "and", "sends", "it", "to", "the", "SLEE" ]
0caa9ab481a545e52c31401f19e99bdfbbfb7bf0
https://github.com/RestComm/jain-slee.xcap/blob/0caa9ab481a545e52c31401f19e99bdfbbfb7bf0/resources/xcap-client/ra/src/main/java/org/restcomm/slee/resource/xcapclient/XCAPClientResourceAdaptor.java#L184-L195
148,159
Lucas3oo/jicunit
src/jicunit-framework/src/main/java/org/jicunit/framework/internal/webrunner/ViewBase.java
ViewBase.run
protected void run(List<TestDescription> selectedTests) { mRunning = true; mTotalTestCount = selectedTests.size(); mRunnerBean.run(this, selectedTests); }
java
protected void run(List<TestDescription> selectedTests) { mRunning = true; mTotalTestCount = selectedTests.size(); mRunnerBean.run(this, selectedTests); }
[ "protected", "void", "run", "(", "List", "<", "TestDescription", ">", "selectedTests", ")", "{", "mRunning", "=", "true", ";", "mTotalTestCount", "=", "selectedTests", ".", "size", "(", ")", ";", "mRunnerBean", ".", "run", "(", "this", ",", "selectedTests", ")", ";", "}" ]
Start running the tests @param selectedTests
[ "Start", "running", "the", "tests" ]
1ed41891ccf8e5c6068c6b544d214280bb93945b
https://github.com/Lucas3oo/jicunit/blob/1ed41891ccf8e5c6068c6b544d214280bb93945b/src/jicunit-framework/src/main/java/org/jicunit/framework/internal/webrunner/ViewBase.java#L123-L127
148,160
Lucas3oo/jicunit
src/jicunit-framework/src/main/java/org/jicunit/framework/internal/webrunner/ViewBase.java
ViewBase.runSelected
protected void runSelected() { List<TestDescription> selectedTests = getSelectedTests(); if (selectedTests != null) { List<TestDescription> selectedTestsIncludedLeafs = new ArrayList<>(); for (TestDescription desc : selectedTests) { includeAllLeafs(desc, selectedTestsIncludedLeafs); } // run all tests in selectedTestsIncludedLeafs run(selectedTestsIncludedLeafs); } }
java
protected void runSelected() { List<TestDescription> selectedTests = getSelectedTests(); if (selectedTests != null) { List<TestDescription> selectedTestsIncludedLeafs = new ArrayList<>(); for (TestDescription desc : selectedTests) { includeAllLeafs(desc, selectedTestsIncludedLeafs); } // run all tests in selectedTestsIncludedLeafs run(selectedTestsIncludedLeafs); } }
[ "protected", "void", "runSelected", "(", ")", "{", "List", "<", "TestDescription", ">", "selectedTests", "=", "getSelectedTests", "(", ")", ";", "if", "(", "selectedTests", "!=", "null", ")", "{", "List", "<", "TestDescription", ">", "selectedTestsIncludedLeafs", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "TestDescription", "desc", ":", "selectedTests", ")", "{", "includeAllLeafs", "(", "desc", ",", "selectedTestsIncludedLeafs", ")", ";", "}", "// run all tests in selectedTestsIncludedLeafs", "run", "(", "selectedTestsIncludedLeafs", ")", ";", "}", "}" ]
Execute the selected tests
[ "Execute", "the", "selected", "tests" ]
1ed41891ccf8e5c6068c6b544d214280bb93945b
https://github.com/Lucas3oo/jicunit/blob/1ed41891ccf8e5c6068c6b544d214280bb93945b/src/jicunit-framework/src/main/java/org/jicunit/framework/internal/webrunner/ViewBase.java#L139-L149
148,161
fuinorg/objects4j
src/main/java/org/fuin/objects4j/vo/EmailAddressStrValidator.java
EmailAddressStrValidator.isValid
public static boolean isValid(final String value) { if (value == null) { return true; } if (value.length() == 0) { return false; } try { InternetAddress.parse(value, false); return true; } catch (final AddressException ex) { return false; } }
java
public static boolean isValid(final String value) { if (value == null) { return true; } if (value.length() == 0) { return false; } try { InternetAddress.parse(value, false); return true; } catch (final AddressException ex) { return false; } }
[ "public", "static", "boolean", "isValid", "(", "final", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "true", ";", "}", "if", "(", "value", ".", "length", "(", ")", "==", "0", ")", "{", "return", "false", ";", "}", "try", "{", "InternetAddress", ".", "parse", "(", "value", ",", "false", ")", ";", "return", "true", ";", "}", "catch", "(", "final", "AddressException", "ex", ")", "{", "return", "false", ";", "}", "}" ]
Check that a given string is a well-formed email address. @param value Value to check. @return Returns <code>true</code> if it's a valid email address else <code>false</code> is returned.
[ "Check", "that", "a", "given", "string", "is", "a", "well", "-", "formed", "email", "address", "." ]
e7f278b5bae073ebb6a76053650571c718f36246
https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/vo/EmailAddressStrValidator.java#L51-L64
148,162
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/BaseJsonBo.java
BaseJsonBo.setSubAttr
public BaseJsonBo setSubAttr(String attrName, String dPath, Object value) { if (value == null) { return removeSubAttr(attrName, dPath); } Lock lock = lockForWrite(); try { JsonNode attr = cacheJsonObjs.get(attrName); if (attr == null) { // initialize the first chunk String[] paths = DPathUtils.splitDpath(dPath); if (paths[0].matches("^\\[(.*?)\\]$")) { setAttribute(attrName, "[]"); } else { setAttribute(attrName, "{}"); } attr = cacheJsonObjs.get(attrName); } JacksonUtils.setValue(attr, dPath, value, true); return (BaseJsonBo) setAttribute(attrName, SerializationUtils.toJsonString(attr), false); } finally { lock.unlock(); } }
java
public BaseJsonBo setSubAttr(String attrName, String dPath, Object value) { if (value == null) { return removeSubAttr(attrName, dPath); } Lock lock = lockForWrite(); try { JsonNode attr = cacheJsonObjs.get(attrName); if (attr == null) { // initialize the first chunk String[] paths = DPathUtils.splitDpath(dPath); if (paths[0].matches("^\\[(.*?)\\]$")) { setAttribute(attrName, "[]"); } else { setAttribute(attrName, "{}"); } attr = cacheJsonObjs.get(attrName); } JacksonUtils.setValue(attr, dPath, value, true); return (BaseJsonBo) setAttribute(attrName, SerializationUtils.toJsonString(attr), false); } finally { lock.unlock(); } }
[ "public", "BaseJsonBo", "setSubAttr", "(", "String", "attrName", ",", "String", "dPath", ",", "Object", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "removeSubAttr", "(", "attrName", ",", "dPath", ")", ";", "}", "Lock", "lock", "=", "lockForWrite", "(", ")", ";", "try", "{", "JsonNode", "attr", "=", "cacheJsonObjs", ".", "get", "(", "attrName", ")", ";", "if", "(", "attr", "==", "null", ")", "{", "// initialize the first chunk", "String", "[", "]", "paths", "=", "DPathUtils", ".", "splitDpath", "(", "dPath", ")", ";", "if", "(", "paths", "[", "0", "]", ".", "matches", "(", "\"^\\\\[(.*?)\\\\]$\"", ")", ")", "{", "setAttribute", "(", "attrName", ",", "\"[]\"", ")", ";", "}", "else", "{", "setAttribute", "(", "attrName", ",", "\"{}\"", ")", ";", "}", "attr", "=", "cacheJsonObjs", ".", "get", "(", "attrName", ")", ";", "}", "JacksonUtils", ".", "setValue", "(", "attr", ",", "dPath", ",", "value", ",", "true", ")", ";", "return", "(", "BaseJsonBo", ")", "setAttribute", "(", "attrName", ",", "SerializationUtils", ".", "toJsonString", "(", "attr", ")", ",", "false", ")", ";", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "}" ]
Set a sub-attribute. @param attrName @param value @return
[ "Set", "a", "sub", "-", "attribute", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/BaseJsonBo.java#L201-L224
148,163
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/BaseJsonBo.java
BaseJsonBo.removeSubAttr
public BaseJsonBo removeSubAttr(String attrName, String dPath) { Lock lock = lockForWrite(); try { JsonNode attr = cacheJsonObjs.get(attrName); JacksonUtils.deleteValue(attr, dPath); return (BaseJsonBo) setAttribute(attrName, SerializationUtils.toJsonString(attr), false); } finally { lock.unlock(); } }
java
public BaseJsonBo removeSubAttr(String attrName, String dPath) { Lock lock = lockForWrite(); try { JsonNode attr = cacheJsonObjs.get(attrName); JacksonUtils.deleteValue(attr, dPath); return (BaseJsonBo) setAttribute(attrName, SerializationUtils.toJsonString(attr), false); } finally { lock.unlock(); } }
[ "public", "BaseJsonBo", "removeSubAttr", "(", "String", "attrName", ",", "String", "dPath", ")", "{", "Lock", "lock", "=", "lockForWrite", "(", ")", ";", "try", "{", "JsonNode", "attr", "=", "cacheJsonObjs", ".", "get", "(", "attrName", ")", ";", "JacksonUtils", ".", "deleteValue", "(", "attr", ",", "dPath", ")", ";", "return", "(", "BaseJsonBo", ")", "setAttribute", "(", "attrName", ",", "SerializationUtils", ".", "toJsonString", "(", "attr", ")", ",", "false", ")", ";", "}", "finally", "{", "lock", ".", "unlock", "(", ")", ";", "}", "}" ]
Remove a sub-attribute. @param attrName @param dPath @return
[ "Remove", "a", "sub", "-", "attribute", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/BaseJsonBo.java#L233-L243
148,164
cryptomator/native-functions
JNI/src/main/java/org/cryptomator/jni/MacKeychainAccess.java
MacKeychainAccess.storePassword
public void storePassword(String account, CharSequence password) { ByteBuffer pwBuf = UTF_8.encode(CharBuffer.wrap(password)); byte[] pwBytes = new byte[pwBuf.remaining()]; pwBuf.get(pwBytes); int errorCode = storePassword0(account.getBytes(UTF_8), pwBytes); Arrays.fill(pwBytes, (byte) 0x00); Arrays.fill(pwBuf.array(), (byte) 0x00); if (errorCode != OSSTATUS_SUCCESS) { throw new JniException("Failed to store password. Error code " + errorCode); } }
java
public void storePassword(String account, CharSequence password) { ByteBuffer pwBuf = UTF_8.encode(CharBuffer.wrap(password)); byte[] pwBytes = new byte[pwBuf.remaining()]; pwBuf.get(pwBytes); int errorCode = storePassword0(account.getBytes(UTF_8), pwBytes); Arrays.fill(pwBytes, (byte) 0x00); Arrays.fill(pwBuf.array(), (byte) 0x00); if (errorCode != OSSTATUS_SUCCESS) { throw new JniException("Failed to store password. Error code " + errorCode); } }
[ "public", "void", "storePassword", "(", "String", "account", ",", "CharSequence", "password", ")", "{", "ByteBuffer", "pwBuf", "=", "UTF_8", ".", "encode", "(", "CharBuffer", ".", "wrap", "(", "password", ")", ")", ";", "byte", "[", "]", "pwBytes", "=", "new", "byte", "[", "pwBuf", ".", "remaining", "(", ")", "]", ";", "pwBuf", ".", "get", "(", "pwBytes", ")", ";", "int", "errorCode", "=", "storePassword0", "(", "account", ".", "getBytes", "(", "UTF_8", ")", ",", "pwBytes", ")", ";", "Arrays", ".", "fill", "(", "pwBytes", ",", "(", "byte", ")", "0x00", ")", ";", "Arrays", ".", "fill", "(", "pwBuf", ".", "array", "(", ")", ",", "(", "byte", ")", "0x00", ")", ";", "if", "(", "errorCode", "!=", "OSSTATUS_SUCCESS", ")", "{", "throw", "new", "JniException", "(", "\"Failed to store password. Error code \"", "+", "errorCode", ")", ";", "}", "}" ]
Associates the specified password with the specified key in the system keychain. @param account Unique account identifier @param password Passphrase to store
[ "Associates", "the", "specified", "password", "with", "the", "specified", "key", "in", "the", "system", "keychain", "." ]
764cb1edbffbc2a4129c71011941adcbd4c12292
https://github.com/cryptomator/native-functions/blob/764cb1edbffbc2a4129c71011941adcbd4c12292/JNI/src/main/java/org/cryptomator/jni/MacKeychainAccess.java#L28-L38
148,165
cryptomator/native-functions
JNI/src/main/java/org/cryptomator/jni/MacKeychainAccess.java
MacKeychainAccess.loadPassword
public char[] loadPassword(String account) { byte[] pwBytes = loadPassword0(account.getBytes(UTF_8)); if (pwBytes == null) { return null; } else { CharBuffer pwBuf = UTF_8.decode(ByteBuffer.wrap(pwBytes)); char[] pw = new char[pwBuf.remaining()]; pwBuf.get(pw); Arrays.fill(pwBytes, (byte) 0x00); Arrays.fill(pwBuf.array(), (char) 0x00); return pw; } }
java
public char[] loadPassword(String account) { byte[] pwBytes = loadPassword0(account.getBytes(UTF_8)); if (pwBytes == null) { return null; } else { CharBuffer pwBuf = UTF_8.decode(ByteBuffer.wrap(pwBytes)); char[] pw = new char[pwBuf.remaining()]; pwBuf.get(pw); Arrays.fill(pwBytes, (byte) 0x00); Arrays.fill(pwBuf.array(), (char) 0x00); return pw; } }
[ "public", "char", "[", "]", "loadPassword", "(", "String", "account", ")", "{", "byte", "[", "]", "pwBytes", "=", "loadPassword0", "(", "account", ".", "getBytes", "(", "UTF_8", ")", ")", ";", "if", "(", "pwBytes", "==", "null", ")", "{", "return", "null", ";", "}", "else", "{", "CharBuffer", "pwBuf", "=", "UTF_8", ".", "decode", "(", "ByteBuffer", ".", "wrap", "(", "pwBytes", ")", ")", ";", "char", "[", "]", "pw", "=", "new", "char", "[", "pwBuf", ".", "remaining", "(", ")", "]", ";", "pwBuf", ".", "get", "(", "pw", ")", ";", "Arrays", ".", "fill", "(", "pwBytes", ",", "(", "byte", ")", "0x00", ")", ";", "Arrays", ".", "fill", "(", "pwBuf", ".", "array", "(", ")", ",", "(", "char", ")", "0x00", ")", ";", "return", "pw", ";", "}", "}" ]
Loads the password associated with the specified key from the system keychain. @param account Unique account identifier @return password or <code>null</code> if no such keychain entry could be loaded from the keychain.
[ "Loads", "the", "password", "associated", "with", "the", "specified", "key", "from", "the", "system", "keychain", "." ]
764cb1edbffbc2a4129c71011941adcbd4c12292
https://github.com/cryptomator/native-functions/blob/764cb1edbffbc2a4129c71011941adcbd4c12292/JNI/src/main/java/org/cryptomator/jni/MacKeychainAccess.java#L48-L60
148,166
cryptomator/native-functions
JNI/src/main/java/org/cryptomator/jni/MacKeychainAccess.java
MacKeychainAccess.deletePassword
public boolean deletePassword(String account) { int errorCode = deletePassword0(account.getBytes(UTF_8)); if (errorCode == OSSTATUS_SUCCESS) { return true; } else if (errorCode == OSSTATUS_NOT_FOUND) { return false; } else { throw new JniException("Failed to delete password. Error code " + errorCode); } }
java
public boolean deletePassword(String account) { int errorCode = deletePassword0(account.getBytes(UTF_8)); if (errorCode == OSSTATUS_SUCCESS) { return true; } else if (errorCode == OSSTATUS_NOT_FOUND) { return false; } else { throw new JniException("Failed to delete password. Error code " + errorCode); } }
[ "public", "boolean", "deletePassword", "(", "String", "account", ")", "{", "int", "errorCode", "=", "deletePassword0", "(", "account", ".", "getBytes", "(", "UTF_8", ")", ")", ";", "if", "(", "errorCode", "==", "OSSTATUS_SUCCESS", ")", "{", "return", "true", ";", "}", "else", "if", "(", "errorCode", "==", "OSSTATUS_NOT_FOUND", ")", "{", "return", "false", ";", "}", "else", "{", "throw", "new", "JniException", "(", "\"Failed to delete password. Error code \"", "+", "errorCode", ")", ";", "}", "}" ]
Deletes the password associated with the specified key from the system keychain. @param account Unique account identifier @return <code>true</code> if the passwords has been deleted, <code>false</code> if no entry for the given key exists.
[ "Deletes", "the", "password", "associated", "with", "the", "specified", "key", "from", "the", "system", "keychain", "." ]
764cb1edbffbc2a4129c71011941adcbd4c12292
https://github.com/cryptomator/native-functions/blob/764cb1edbffbc2a4129c71011941adcbd4c12292/JNI/src/main/java/org/cryptomator/jni/MacKeychainAccess.java#L70-L79
148,167
nuun-io/kernel
core/src/main/java/io/nuun/kernel/core/internal/scanner/inmemory/ClasspathScannerInMemory.java
ClasspathScannerInMemory.actualInitReflections
private void actualInitReflections() { ConfigurationBuilder configurationBuilder = configurationBuilder() .setScanners(getScanners()) .setMetadataAdapter(new MetadataAdapterInMemory()); InMemoryFactory factory = new InMemoryFactory(); for (ClasspathAbstractContainer<?> i : this.classpath.entries()) { String name = i.name(); try { configurationBuilder.addUrls(factory.createInMemoryResource(name)); } catch (MalformedURLException e) { throw new KernelException("Malformed URL Exception", e); } } urls.addAll(configurationBuilder.getUrls()); reflections = new Reflections(configurationBuilder); }
java
private void actualInitReflections() { ConfigurationBuilder configurationBuilder = configurationBuilder() .setScanners(getScanners()) .setMetadataAdapter(new MetadataAdapterInMemory()); InMemoryFactory factory = new InMemoryFactory(); for (ClasspathAbstractContainer<?> i : this.classpath.entries()) { String name = i.name(); try { configurationBuilder.addUrls(factory.createInMemoryResource(name)); } catch (MalformedURLException e) { throw new KernelException("Malformed URL Exception", e); } } urls.addAll(configurationBuilder.getUrls()); reflections = new Reflections(configurationBuilder); }
[ "private", "void", "actualInitReflections", "(", ")", "{", "ConfigurationBuilder", "configurationBuilder", "=", "configurationBuilder", "(", ")", ".", "setScanners", "(", "getScanners", "(", ")", ")", ".", "setMetadataAdapter", "(", "new", "MetadataAdapterInMemory", "(", ")", ")", ";", "InMemoryFactory", "factory", "=", "new", "InMemoryFactory", "(", ")", ";", "for", "(", "ClasspathAbstractContainer", "<", "?", ">", "i", ":", "this", ".", "classpath", ".", "entries", "(", ")", ")", "{", "String", "name", "=", "i", ".", "name", "(", ")", ";", "try", "{", "configurationBuilder", ".", "addUrls", "(", "factory", ".", "createInMemoryResource", "(", "name", ")", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "throw", "new", "KernelException", "(", "\"Malformed URL Exception\"", ",", "e", ")", ";", "}", "}", "urls", ".", "addAll", "(", "configurationBuilder", ".", "getUrls", "(", ")", ")", ";", "reflections", "=", "new", "Reflections", "(", "configurationBuilder", ")", ";", "}" ]
Its too soon to create reflections in the constructor
[ "Its", "too", "soon", "to", "create", "reflections", "in", "the", "constructor" ]
116a7664fe2a9323e280574803d273699a333732
https://github.com/nuun-io/kernel/blob/116a7664fe2a9323e280574803d273699a333732/core/src/main/java/io/nuun/kernel/core/internal/scanner/inmemory/ClasspathScannerInMemory.java#L47-L67
148,168
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/methods/DoLock.java
DoLock.executeLock
private void executeLock( final ITransaction transaction, final WebdavRequest req, final WebdavResponse resp ) throws LockFailedException, IOException, WebdavException { // Mac OS lock request workaround if ( _macLockRequest ) { LOG.trace( "DoLock.execute() : do workaround for user agent '" + _userAgent + "'" ); doMacLockRequestWorkaround( transaction, req, resp ); } else { // Getting LockInformation from request if ( getLockInformation( transaction, req, resp ) ) { final int depth = getDepth( req ); final int lockDuration = getTimeout( transaction, req ); boolean lockSuccess = false; if ( _exclusive ) { lockSuccess = _resourceLocks.exclusiveLock( transaction, _path, _lockOwner, depth, lockDuration ); } else { lockSuccess = _resourceLocks.sharedLock( transaction, _path, _lockOwner, depth, lockDuration ); } if ( lockSuccess ) { // Locks successfully placed - return information about final LockedObject lo = _resourceLocks.getLockedObjectByPath( transaction, _path ); if ( lo != null ) { generateXMLReport( transaction, resp, lo ); } else { resp.sendError( SC_INTERNAL_SERVER_ERROR ); } } else { sendLockFailError( transaction, req, resp ); throw new LockFailedException(); } } else { // information for LOCK could not be read successfully resp.setContentType( "text/xml; charset=UTF-8" ); resp.sendError( SC_BAD_REQUEST ); } } }
java
private void executeLock( final ITransaction transaction, final WebdavRequest req, final WebdavResponse resp ) throws LockFailedException, IOException, WebdavException { // Mac OS lock request workaround if ( _macLockRequest ) { LOG.trace( "DoLock.execute() : do workaround for user agent '" + _userAgent + "'" ); doMacLockRequestWorkaround( transaction, req, resp ); } else { // Getting LockInformation from request if ( getLockInformation( transaction, req, resp ) ) { final int depth = getDepth( req ); final int lockDuration = getTimeout( transaction, req ); boolean lockSuccess = false; if ( _exclusive ) { lockSuccess = _resourceLocks.exclusiveLock( transaction, _path, _lockOwner, depth, lockDuration ); } else { lockSuccess = _resourceLocks.sharedLock( transaction, _path, _lockOwner, depth, lockDuration ); } if ( lockSuccess ) { // Locks successfully placed - return information about final LockedObject lo = _resourceLocks.getLockedObjectByPath( transaction, _path ); if ( lo != null ) { generateXMLReport( transaction, resp, lo ); } else { resp.sendError( SC_INTERNAL_SERVER_ERROR ); } } else { sendLockFailError( transaction, req, resp ); throw new LockFailedException(); } } else { // information for LOCK could not be read successfully resp.setContentType( "text/xml; charset=UTF-8" ); resp.sendError( SC_BAD_REQUEST ); } } }
[ "private", "void", "executeLock", "(", "final", "ITransaction", "transaction", ",", "final", "WebdavRequest", "req", ",", "final", "WebdavResponse", "resp", ")", "throws", "LockFailedException", ",", "IOException", ",", "WebdavException", "{", "// Mac OS lock request workaround", "if", "(", "_macLockRequest", ")", "{", "LOG", ".", "trace", "(", "\"DoLock.execute() : do workaround for user agent '\"", "+", "_userAgent", "+", "\"'\"", ")", ";", "doMacLockRequestWorkaround", "(", "transaction", ",", "req", ",", "resp", ")", ";", "}", "else", "{", "// Getting LockInformation from request", "if", "(", "getLockInformation", "(", "transaction", ",", "req", ",", "resp", ")", ")", "{", "final", "int", "depth", "=", "getDepth", "(", "req", ")", ";", "final", "int", "lockDuration", "=", "getTimeout", "(", "transaction", ",", "req", ")", ";", "boolean", "lockSuccess", "=", "false", ";", "if", "(", "_exclusive", ")", "{", "lockSuccess", "=", "_resourceLocks", ".", "exclusiveLock", "(", "transaction", ",", "_path", ",", "_lockOwner", ",", "depth", ",", "lockDuration", ")", ";", "}", "else", "{", "lockSuccess", "=", "_resourceLocks", ".", "sharedLock", "(", "transaction", ",", "_path", ",", "_lockOwner", ",", "depth", ",", "lockDuration", ")", ";", "}", "if", "(", "lockSuccess", ")", "{", "// Locks successfully placed - return information about", "final", "LockedObject", "lo", "=", "_resourceLocks", ".", "getLockedObjectByPath", "(", "transaction", ",", "_path", ")", ";", "if", "(", "lo", "!=", "null", ")", "{", "generateXMLReport", "(", "transaction", ",", "resp", ",", "lo", ")", ";", "}", "else", "{", "resp", ".", "sendError", "(", "SC_INTERNAL_SERVER_ERROR", ")", ";", "}", "}", "else", "{", "sendLockFailError", "(", "transaction", ",", "req", ",", "resp", ")", ";", "throw", "new", "LockFailedException", "(", ")", ";", "}", "}", "else", "{", "// information for LOCK could not be read successfully", "resp", ".", "setContentType", "(", "\"text/xml; charset=UTF-8\"", ")", ";", "resp", ".", "sendError", "(", "SC_BAD_REQUEST", ")", ";", "}", "}", "}" ]
Executes the LOCK
[ "Executes", "the", "LOCK" ]
39bb7032fc75c1b67d3f2440dd1c234ead96cb9d
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/methods/DoLock.java#L328-L384
148,169
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/methods/DoLock.java
DoLock.getTimeout
private int getTimeout( final ITransaction transaction, final WebdavRequest req ) { int lockDuration = DEFAULT_TIMEOUT; String lockDurationStr = req.getHeader( "Timeout" ); if ( lockDurationStr == null ) { lockDuration = DEFAULT_TIMEOUT; } else { final int commaPos = lockDurationStr.indexOf( ',' ); // if multiple timeouts, just use the first one if ( commaPos != -1 ) { lockDurationStr = lockDurationStr.substring( 0, commaPos ); } if ( lockDurationStr.startsWith( "Second-" ) ) { lockDuration = new Integer( lockDurationStr.substring( 7 ) ).intValue(); } else { if ( lockDurationStr.equalsIgnoreCase( "infinity" ) ) { lockDuration = MAX_TIMEOUT; } else { try { lockDuration = new Integer( lockDurationStr ).intValue(); } catch ( final NumberFormatException e ) { lockDuration = MAX_TIMEOUT; } } } if ( lockDuration <= 0 ) { lockDuration = DEFAULT_TIMEOUT; } if ( lockDuration > MAX_TIMEOUT ) { lockDuration = MAX_TIMEOUT; } } return lockDuration; }
java
private int getTimeout( final ITransaction transaction, final WebdavRequest req ) { int lockDuration = DEFAULT_TIMEOUT; String lockDurationStr = req.getHeader( "Timeout" ); if ( lockDurationStr == null ) { lockDuration = DEFAULT_TIMEOUT; } else { final int commaPos = lockDurationStr.indexOf( ',' ); // if multiple timeouts, just use the first one if ( commaPos != -1 ) { lockDurationStr = lockDurationStr.substring( 0, commaPos ); } if ( lockDurationStr.startsWith( "Second-" ) ) { lockDuration = new Integer( lockDurationStr.substring( 7 ) ).intValue(); } else { if ( lockDurationStr.equalsIgnoreCase( "infinity" ) ) { lockDuration = MAX_TIMEOUT; } else { try { lockDuration = new Integer( lockDurationStr ).intValue(); } catch ( final NumberFormatException e ) { lockDuration = MAX_TIMEOUT; } } } if ( lockDuration <= 0 ) { lockDuration = DEFAULT_TIMEOUT; } if ( lockDuration > MAX_TIMEOUT ) { lockDuration = MAX_TIMEOUT; } } return lockDuration; }
[ "private", "int", "getTimeout", "(", "final", "ITransaction", "transaction", ",", "final", "WebdavRequest", "req", ")", "{", "int", "lockDuration", "=", "DEFAULT_TIMEOUT", ";", "String", "lockDurationStr", "=", "req", ".", "getHeader", "(", "\"Timeout\"", ")", ";", "if", "(", "lockDurationStr", "==", "null", ")", "{", "lockDuration", "=", "DEFAULT_TIMEOUT", ";", "}", "else", "{", "final", "int", "commaPos", "=", "lockDurationStr", ".", "indexOf", "(", "'", "'", ")", ";", "// if multiple timeouts, just use the first one", "if", "(", "commaPos", "!=", "-", "1", ")", "{", "lockDurationStr", "=", "lockDurationStr", ".", "substring", "(", "0", ",", "commaPos", ")", ";", "}", "if", "(", "lockDurationStr", ".", "startsWith", "(", "\"Second-\"", ")", ")", "{", "lockDuration", "=", "new", "Integer", "(", "lockDurationStr", ".", "substring", "(", "7", ")", ")", ".", "intValue", "(", ")", ";", "}", "else", "{", "if", "(", "lockDurationStr", ".", "equalsIgnoreCase", "(", "\"infinity\"", ")", ")", "{", "lockDuration", "=", "MAX_TIMEOUT", ";", "}", "else", "{", "try", "{", "lockDuration", "=", "new", "Integer", "(", "lockDurationStr", ")", ".", "intValue", "(", ")", ";", "}", "catch", "(", "final", "NumberFormatException", "e", ")", "{", "lockDuration", "=", "MAX_TIMEOUT", ";", "}", "}", "}", "if", "(", "lockDuration", "<=", "0", ")", "{", "lockDuration", "=", "DEFAULT_TIMEOUT", ";", "}", "if", "(", "lockDuration", ">", "MAX_TIMEOUT", ")", "{", "lockDuration", "=", "MAX_TIMEOUT", ";", "}", "}", "return", "lockDuration", ";", "}" ]
Ties to read the timeout from request
[ "Ties", "to", "read", "the", "timeout", "from", "request" ]
39bb7032fc75c1b67d3f2440dd1c234ead96cb9d
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/methods/DoLock.java#L551-L601
148,170
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/methods/DoLock.java
DoLock.generateXMLReport
private void generateXMLReport( final ITransaction transaction, final WebdavResponse resp, final LockedObject lo ) throws IOException { final HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put( "DAV:", "D" ); resp.setStatus( SC_OK ); resp.setContentType( "text/xml; charset=UTF-8" ); final XMLWriter generatedXML = new XMLWriter( resp.getWriter(), namespaces ); generatedXML.writeXMLHeader(); generatedXML.writeElement( "DAV::prop", XMLWriter.OPENING ); generatedXML.writeElement( "DAV::lockdiscovery", XMLWriter.OPENING ); generatedXML.writeElement( "DAV::activelock", XMLWriter.OPENING ); generatedXML.writeElement( "DAV::locktype", XMLWriter.OPENING ); generatedXML.writeProperty( "DAV::" + _type ); generatedXML.writeElement( "DAV::locktype", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::lockscope", XMLWriter.OPENING ); if ( _exclusive ) { generatedXML.writeProperty( "DAV::exclusive" ); } else { generatedXML.writeProperty( "DAV::shared" ); } generatedXML.writeElement( "DAV::lockscope", XMLWriter.CLOSING ); final int depth = lo.getLockDepth(); generatedXML.writeElement( "DAV::depth", XMLWriter.OPENING ); if ( depth == INFINITY ) { generatedXML.writeText( "Infinity" ); } else { generatedXML.writeText( String.valueOf( depth ) ); } generatedXML.writeElement( "DAV::depth", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::owner", XMLWriter.OPENING ); generatedXML.writeElement( "DAV::href", XMLWriter.OPENING ); generatedXML.writeText( _lockOwner ); generatedXML.writeElement( "DAV::href", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::owner", XMLWriter.CLOSING ); final long timeout = lo.getTimeoutMillis(); generatedXML.writeElement( "DAV::timeout", XMLWriter.OPENING ); generatedXML.writeText( "Second-" + timeout / 1000 ); generatedXML.writeElement( "DAV::timeout", XMLWriter.CLOSING ); final String lockToken = lo.getID(); generatedXML.writeElement( "DAV::locktoken", XMLWriter.OPENING ); generatedXML.writeElement( "DAV::href", XMLWriter.OPENING ); generatedXML.writeText( "opaquelocktoken:" + lockToken ); generatedXML.writeElement( "DAV::href", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::locktoken", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::activelock", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::lockdiscovery", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::prop", XMLWriter.CLOSING ); resp.addHeader( "Lock-Token", "<opaquelocktoken:" + lockToken + ">" ); generatedXML.sendData(); }
java
private void generateXMLReport( final ITransaction transaction, final WebdavResponse resp, final LockedObject lo ) throws IOException { final HashMap<String, String> namespaces = new HashMap<String, String>(); namespaces.put( "DAV:", "D" ); resp.setStatus( SC_OK ); resp.setContentType( "text/xml; charset=UTF-8" ); final XMLWriter generatedXML = new XMLWriter( resp.getWriter(), namespaces ); generatedXML.writeXMLHeader(); generatedXML.writeElement( "DAV::prop", XMLWriter.OPENING ); generatedXML.writeElement( "DAV::lockdiscovery", XMLWriter.OPENING ); generatedXML.writeElement( "DAV::activelock", XMLWriter.OPENING ); generatedXML.writeElement( "DAV::locktype", XMLWriter.OPENING ); generatedXML.writeProperty( "DAV::" + _type ); generatedXML.writeElement( "DAV::locktype", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::lockscope", XMLWriter.OPENING ); if ( _exclusive ) { generatedXML.writeProperty( "DAV::exclusive" ); } else { generatedXML.writeProperty( "DAV::shared" ); } generatedXML.writeElement( "DAV::lockscope", XMLWriter.CLOSING ); final int depth = lo.getLockDepth(); generatedXML.writeElement( "DAV::depth", XMLWriter.OPENING ); if ( depth == INFINITY ) { generatedXML.writeText( "Infinity" ); } else { generatedXML.writeText( String.valueOf( depth ) ); } generatedXML.writeElement( "DAV::depth", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::owner", XMLWriter.OPENING ); generatedXML.writeElement( "DAV::href", XMLWriter.OPENING ); generatedXML.writeText( _lockOwner ); generatedXML.writeElement( "DAV::href", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::owner", XMLWriter.CLOSING ); final long timeout = lo.getTimeoutMillis(); generatedXML.writeElement( "DAV::timeout", XMLWriter.OPENING ); generatedXML.writeText( "Second-" + timeout / 1000 ); generatedXML.writeElement( "DAV::timeout", XMLWriter.CLOSING ); final String lockToken = lo.getID(); generatedXML.writeElement( "DAV::locktoken", XMLWriter.OPENING ); generatedXML.writeElement( "DAV::href", XMLWriter.OPENING ); generatedXML.writeText( "opaquelocktoken:" + lockToken ); generatedXML.writeElement( "DAV::href", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::locktoken", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::activelock", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::lockdiscovery", XMLWriter.CLOSING ); generatedXML.writeElement( "DAV::prop", XMLWriter.CLOSING ); resp.addHeader( "Lock-Token", "<opaquelocktoken:" + lockToken + ">" ); generatedXML.sendData(); }
[ "private", "void", "generateXMLReport", "(", "final", "ITransaction", "transaction", ",", "final", "WebdavResponse", "resp", ",", "final", "LockedObject", "lo", ")", "throws", "IOException", "{", "final", "HashMap", "<", "String", ",", "String", ">", "namespaces", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "namespaces", ".", "put", "(", "\"DAV:\"", ",", "\"D\"", ")", ";", "resp", ".", "setStatus", "(", "SC_OK", ")", ";", "resp", ".", "setContentType", "(", "\"text/xml; charset=UTF-8\"", ")", ";", "final", "XMLWriter", "generatedXML", "=", "new", "XMLWriter", "(", "resp", ".", "getWriter", "(", ")", ",", "namespaces", ")", ";", "generatedXML", ".", "writeXMLHeader", "(", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::prop\"", ",", "XMLWriter", ".", "OPENING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::lockdiscovery\"", ",", "XMLWriter", ".", "OPENING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::activelock\"", ",", "XMLWriter", ".", "OPENING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::locktype\"", ",", "XMLWriter", ".", "OPENING", ")", ";", "generatedXML", ".", "writeProperty", "(", "\"DAV::\"", "+", "_type", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::locktype\"", ",", "XMLWriter", ".", "CLOSING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::lockscope\"", ",", "XMLWriter", ".", "OPENING", ")", ";", "if", "(", "_exclusive", ")", "{", "generatedXML", ".", "writeProperty", "(", "\"DAV::exclusive\"", ")", ";", "}", "else", "{", "generatedXML", ".", "writeProperty", "(", "\"DAV::shared\"", ")", ";", "}", "generatedXML", ".", "writeElement", "(", "\"DAV::lockscope\"", ",", "XMLWriter", ".", "CLOSING", ")", ";", "final", "int", "depth", "=", "lo", ".", "getLockDepth", "(", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::depth\"", ",", "XMLWriter", ".", "OPENING", ")", ";", "if", "(", "depth", "==", "INFINITY", ")", "{", "generatedXML", ".", "writeText", "(", "\"Infinity\"", ")", ";", "}", "else", "{", "generatedXML", ".", "writeText", "(", "String", ".", "valueOf", "(", "depth", ")", ")", ";", "}", "generatedXML", ".", "writeElement", "(", "\"DAV::depth\"", ",", "XMLWriter", ".", "CLOSING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::owner\"", ",", "XMLWriter", ".", "OPENING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::href\"", ",", "XMLWriter", ".", "OPENING", ")", ";", "generatedXML", ".", "writeText", "(", "_lockOwner", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::href\"", ",", "XMLWriter", ".", "CLOSING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::owner\"", ",", "XMLWriter", ".", "CLOSING", ")", ";", "final", "long", "timeout", "=", "lo", ".", "getTimeoutMillis", "(", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::timeout\"", ",", "XMLWriter", ".", "OPENING", ")", ";", "generatedXML", ".", "writeText", "(", "\"Second-\"", "+", "timeout", "/", "1000", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::timeout\"", ",", "XMLWriter", ".", "CLOSING", ")", ";", "final", "String", "lockToken", "=", "lo", ".", "getID", "(", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::locktoken\"", ",", "XMLWriter", ".", "OPENING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::href\"", ",", "XMLWriter", ".", "OPENING", ")", ";", "generatedXML", ".", "writeText", "(", "\"opaquelocktoken:\"", "+", "lockToken", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::href\"", ",", "XMLWriter", ".", "CLOSING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::locktoken\"", ",", "XMLWriter", ".", "CLOSING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::activelock\"", ",", "XMLWriter", ".", "CLOSING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::lockdiscovery\"", ",", "XMLWriter", ".", "CLOSING", ")", ";", "generatedXML", ".", "writeElement", "(", "\"DAV::prop\"", ",", "XMLWriter", ".", "CLOSING", ")", ";", "resp", ".", "addHeader", "(", "\"Lock-Token\"", ",", "\"<opaquelocktoken:\"", "+", "lockToken", "+", "\">\"", ")", ";", "generatedXML", ".", "sendData", "(", ")", ";", "}" ]
Generates the response XML with all lock information
[ "Generates", "the", "response", "XML", "with", "all", "lock", "information" ]
39bb7032fc75c1b67d3f2440dd1c234ead96cb9d
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/methods/DoLock.java#L606-L676
148,171
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/methods/DoLock.java
DoLock.doMacLockRequestWorkaround
private void doMacLockRequestWorkaround( final ITransaction transaction, final WebdavRequest req, final WebdavResponse resp ) throws LockFailedException, IOException { LockedObject lo; final int depth = getDepth( req ); int lockDuration = getTimeout( transaction, req ); if ( lockDuration < 0 || lockDuration > MAX_TIMEOUT ) { lockDuration = DEFAULT_TIMEOUT; } boolean lockSuccess = false; lockSuccess = _resourceLocks.exclusiveLock( transaction, _path, _lockOwner, depth, lockDuration ); if ( lockSuccess ) { // Locks successfully placed - return information about lo = _resourceLocks.getLockedObjectByPath( transaction, _path ); if ( lo != null ) { generateXMLReport( transaction, resp, lo ); } else { resp.sendError( SC_INTERNAL_SERVER_ERROR ); } } else { // Locking was not successful sendLockFailError( transaction, req, resp ); } }
java
private void doMacLockRequestWorkaround( final ITransaction transaction, final WebdavRequest req, final WebdavResponse resp ) throws LockFailedException, IOException { LockedObject lo; final int depth = getDepth( req ); int lockDuration = getTimeout( transaction, req ); if ( lockDuration < 0 || lockDuration > MAX_TIMEOUT ) { lockDuration = DEFAULT_TIMEOUT; } boolean lockSuccess = false; lockSuccess = _resourceLocks.exclusiveLock( transaction, _path, _lockOwner, depth, lockDuration ); if ( lockSuccess ) { // Locks successfully placed - return information about lo = _resourceLocks.getLockedObjectByPath( transaction, _path ); if ( lo != null ) { generateXMLReport( transaction, resp, lo ); } else { resp.sendError( SC_INTERNAL_SERVER_ERROR ); } } else { // Locking was not successful sendLockFailError( transaction, req, resp ); } }
[ "private", "void", "doMacLockRequestWorkaround", "(", "final", "ITransaction", "transaction", ",", "final", "WebdavRequest", "req", ",", "final", "WebdavResponse", "resp", ")", "throws", "LockFailedException", ",", "IOException", "{", "LockedObject", "lo", ";", "final", "int", "depth", "=", "getDepth", "(", "req", ")", ";", "int", "lockDuration", "=", "getTimeout", "(", "transaction", ",", "req", ")", ";", "if", "(", "lockDuration", "<", "0", "||", "lockDuration", ">", "MAX_TIMEOUT", ")", "{", "lockDuration", "=", "DEFAULT_TIMEOUT", ";", "}", "boolean", "lockSuccess", "=", "false", ";", "lockSuccess", "=", "_resourceLocks", ".", "exclusiveLock", "(", "transaction", ",", "_path", ",", "_lockOwner", ",", "depth", ",", "lockDuration", ")", ";", "if", "(", "lockSuccess", ")", "{", "// Locks successfully placed - return information about", "lo", "=", "_resourceLocks", ".", "getLockedObjectByPath", "(", "transaction", ",", "_path", ")", ";", "if", "(", "lo", "!=", "null", ")", "{", "generateXMLReport", "(", "transaction", ",", "resp", ",", "lo", ")", ";", "}", "else", "{", "resp", ".", "sendError", "(", "SC_INTERNAL_SERVER_ERROR", ")", ";", "}", "}", "else", "{", "// Locking was not successful", "sendLockFailError", "(", "transaction", ",", "req", ",", "resp", ")", ";", "}", "}" ]
Executes the lock for a Mac OS Finder client
[ "Executes", "the", "lock", "for", "a", "Mac", "OS", "Finder", "client" ]
39bb7032fc75c1b67d3f2440dd1c234ead96cb9d
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/methods/DoLock.java#L681-L713
148,172
Commonjava/webdav-handler
common/src/main/java/net/sf/webdav/methods/DoLock.java
DoLock.sendLockFailError
private void sendLockFailError( final ITransaction transaction, final WebdavRequest req, final WebdavResponse resp ) throws IOException { final Hashtable<String, WebdavStatus> errorList = new Hashtable<String, WebdavStatus>(); errorList.put( _path, SC_LOCKED ); sendReport( req, resp, errorList ); }
java
private void sendLockFailError( final ITransaction transaction, final WebdavRequest req, final WebdavResponse resp ) throws IOException { final Hashtable<String, WebdavStatus> errorList = new Hashtable<String, WebdavStatus>(); errorList.put( _path, SC_LOCKED ); sendReport( req, resp, errorList ); }
[ "private", "void", "sendLockFailError", "(", "final", "ITransaction", "transaction", ",", "final", "WebdavRequest", "req", ",", "final", "WebdavResponse", "resp", ")", "throws", "IOException", "{", "final", "Hashtable", "<", "String", ",", "WebdavStatus", ">", "errorList", "=", "new", "Hashtable", "<", "String", ",", "WebdavStatus", ">", "(", ")", ";", "errorList", ".", "put", "(", "_path", ",", "SC_LOCKED", ")", ";", "sendReport", "(", "req", ",", "resp", ",", "errorList", ")", ";", "}" ]
Sends an error report to the client
[ "Sends", "an", "error", "report", "to", "the", "client" ]
39bb7032fc75c1b67d3f2440dd1c234ead96cb9d
https://github.com/Commonjava/webdav-handler/blob/39bb7032fc75c1b67d3f2440dd1c234ead96cb9d/common/src/main/java/net/sf/webdav/methods/DoLock.java#L718-L724
148,173
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java
GenericBoJdbcDao.invalidateCache
protected void invalidateCache(T bo, CacheInvalidationReason reason) { final String cacheKey = cacheKey(bo); switch (reason) { case CREATE: case UPDATE: putToCache(getCacheName(), cacheKey, bo); case DELETE: removeFromCache(getCacheName(), cacheKey); } }
java
protected void invalidateCache(T bo, CacheInvalidationReason reason) { final String cacheKey = cacheKey(bo); switch (reason) { case CREATE: case UPDATE: putToCache(getCacheName(), cacheKey, bo); case DELETE: removeFromCache(getCacheName(), cacheKey); } }
[ "protected", "void", "invalidateCache", "(", "T", "bo", ",", "CacheInvalidationReason", "reason", ")", "{", "final", "String", "cacheKey", "=", "cacheKey", "(", "bo", ")", ";", "switch", "(", "reason", ")", "{", "case", "CREATE", ":", "case", "UPDATE", ":", "putToCache", "(", "getCacheName", "(", ")", ",", "cacheKey", ",", "bo", ")", ";", "case", "DELETE", ":", "removeFromCache", "(", "getCacheName", "(", ")", ",", "cacheKey", ")", ";", "}", "}" ]
Invalidate a BO from cache. @param bo @param reason
[ "Invalidate", "a", "BO", "from", "cache", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java#L414-L423
148,174
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java
GenericBoJdbcDao.delete
protected DaoResult delete(Connection conn, T bo) { if (bo == null) { return new DaoResult(DaoOperationStatus.NOT_FOUND); } int numRows = execute(conn, calcSqlDeleteOne(bo), rowMapper.valuesForColumns(bo, rowMapper.getPrimaryKeyColumns())); DaoResult result = numRows > 0 ? new DaoResult(DaoOperationStatus.SUCCESSFUL, bo) : new DaoResult(DaoOperationStatus.NOT_FOUND); if (numRows > 0) { invalidateCache(bo, CacheInvalidationReason.DELETE); } return result; }
java
protected DaoResult delete(Connection conn, T bo) { if (bo == null) { return new DaoResult(DaoOperationStatus.NOT_FOUND); } int numRows = execute(conn, calcSqlDeleteOne(bo), rowMapper.valuesForColumns(bo, rowMapper.getPrimaryKeyColumns())); DaoResult result = numRows > 0 ? new DaoResult(DaoOperationStatus.SUCCESSFUL, bo) : new DaoResult(DaoOperationStatus.NOT_FOUND); if (numRows > 0) { invalidateCache(bo, CacheInvalidationReason.DELETE); } return result; }
[ "protected", "DaoResult", "delete", "(", "Connection", "conn", ",", "T", "bo", ")", "{", "if", "(", "bo", "==", "null", ")", "{", "return", "new", "DaoResult", "(", "DaoOperationStatus", ".", "NOT_FOUND", ")", ";", "}", "int", "numRows", "=", "execute", "(", "conn", ",", "calcSqlDeleteOne", "(", "bo", ")", ",", "rowMapper", ".", "valuesForColumns", "(", "bo", ",", "rowMapper", ".", "getPrimaryKeyColumns", "(", ")", ")", ")", ";", "DaoResult", "result", "=", "numRows", ">", "0", "?", "new", "DaoResult", "(", "DaoOperationStatus", ".", "SUCCESSFUL", ",", "bo", ")", ":", "new", "DaoResult", "(", "DaoOperationStatus", ".", "NOT_FOUND", ")", ";", "if", "(", "numRows", ">", "0", ")", "{", "invalidateCache", "(", "bo", ",", "CacheInvalidationReason", ".", "DELETE", ")", ";", "}", "return", "result", ";", "}" ]
Delete an existing BO from storage. @param conn @param bo @return @since 0.8.1
[ "Delete", "an", "existing", "BO", "from", "storage", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java#L485-L497
148,175
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java
GenericBoJdbcDao.get
protected T get(Connection conn, BoId id) { if (id == null || id.values == null || id.values.length == 0) { return null; } final String cacheKey = cacheKey(id); T bo = getFromCache(getCacheName(), cacheKey, typeClass); if (bo == null) { bo = executeSelectOne(rowMapper, conn, calcSqlSelectOne(id), id.values); putToCache(getCacheName(), cacheKey, bo); } return bo; }
java
protected T get(Connection conn, BoId id) { if (id == null || id.values == null || id.values.length == 0) { return null; } final String cacheKey = cacheKey(id); T bo = getFromCache(getCacheName(), cacheKey, typeClass); if (bo == null) { bo = executeSelectOne(rowMapper, conn, calcSqlSelectOne(id), id.values); putToCache(getCacheName(), cacheKey, bo); } return bo; }
[ "protected", "T", "get", "(", "Connection", "conn", ",", "BoId", "id", ")", "{", "if", "(", "id", "==", "null", "||", "id", ".", "values", "==", "null", "||", "id", ".", "values", ".", "length", "==", "0", ")", "{", "return", "null", ";", "}", "final", "String", "cacheKey", "=", "cacheKey", "(", "id", ")", ";", "T", "bo", "=", "getFromCache", "(", "getCacheName", "(", ")", ",", "cacheKey", ",", "typeClass", ")", ";", "if", "(", "bo", "==", "null", ")", "{", "bo", "=", "executeSelectOne", "(", "rowMapper", ",", "conn", ",", "calcSqlSelectOne", "(", "id", ")", ",", "id", ".", "values", ")", ";", "putToCache", "(", "getCacheName", "(", ")", ",", "cacheKey", ",", "bo", ")", ";", "}", "return", "bo", ";", "}" ]
Fetch an existing BO from storage by id. @param conn @param id @return
[ "Fetch", "an", "existing", "BO", "from", "storage", "by", "id", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java#L521-L532
148,176
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java
GenericBoJdbcDao.get
@SuppressWarnings("unchecked") protected T[] get(Connection conn, BoId... idList) { T[] result = (T[]) Array.newInstance(typeClass, idList != null ? idList.length : 0); if (idList != null) { for (int i = 0; i < idList.length; i++) { result[i] = get(conn, idList[i]); } } return result; }
java
@SuppressWarnings("unchecked") protected T[] get(Connection conn, BoId... idList) { T[] result = (T[]) Array.newInstance(typeClass, idList != null ? idList.length : 0); if (idList != null) { for (int i = 0; i < idList.length; i++) { result[i] = get(conn, idList[i]); } } return result; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "T", "[", "]", "get", "(", "Connection", "conn", ",", "BoId", "...", "idList", ")", "{", "T", "[", "]", "result", "=", "(", "T", "[", "]", ")", "Array", ".", "newInstance", "(", "typeClass", ",", "idList", "!=", "null", "?", "idList", ".", "length", ":", "0", ")", ";", "if", "(", "idList", "!=", "null", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "idList", ".", "length", ";", "i", "++", ")", "{", "result", "[", "i", "]", "=", "get", "(", "conn", ",", "idList", "[", "i", "]", ")", ";", "}", "}", "return", "result", ";", "}" ]
Fetch list of existing BOs from storage by id. @param conn @param idList @return @since 0.8.1
[ "Fetch", "list", "of", "existing", "BOs", "from", "storage", "by", "id", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java#L562-L571
148,177
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java
GenericBoJdbcDao.getAll
protected Stream<T> getAll(Connection conn) { return executeSelectAsStream(rowMapper, conn, true, calcSqlSelectAll()); }
java
protected Stream<T> getAll(Connection conn) { return executeSelectAsStream(rowMapper, conn, true, calcSqlSelectAll()); }
[ "protected", "Stream", "<", "T", ">", "getAll", "(", "Connection", "conn", ")", "{", "return", "executeSelectAsStream", "(", "rowMapper", ",", "conn", ",", "true", ",", "calcSqlSelectAll", "(", ")", ")", ";", "}" ]
Fetch all existing BOs from storage and return the result as a stream. @param conn @return @since 0.9.0
[ "Fetch", "all", "existing", "BOs", "from", "storage", "and", "return", "the", "result", "as", "a", "stream", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java#L596-L598
148,178
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java
GenericBoJdbcDao.update
protected DaoResult update(Connection conn, T bo) { if (bo == null) { return new DaoResult(DaoOperationStatus.NOT_FOUND); } Savepoint savepoint = null; try { try { String[] bindColumns = ArrayUtils.addAll(rowMapper.getUpdateColumns(), rowMapper.getPrimaryKeyColumns()); String colChecksum = rowMapper.getChecksumColumn(); if (!StringUtils.isBlank(colChecksum)) { bindColumns = ArrayUtils.add(bindColumns, colChecksum); } savepoint = conn.getAutoCommit() ? null : conn.setSavepoint(); int numRows = execute(conn, calcSqlUpdateOne(bo), rowMapper.valuesForColumns(bo, bindColumns)); DaoResult result = numRows > 0 ? new DaoResult(DaoOperationStatus.SUCCESSFUL, bo) : new DaoResult(DaoOperationStatus.NOT_FOUND); if (numRows > 0) { invalidateCache(bo, CacheInvalidationReason.UPDATE); } return result; } catch (DuplicatedValueException dke) { if (savepoint != null) { conn.rollback(savepoint); } return new DaoResult(DaoOperationStatus.DUPLICATED_VALUE); } } catch (SQLException e) { throw new DaoException(e); } }
java
protected DaoResult update(Connection conn, T bo) { if (bo == null) { return new DaoResult(DaoOperationStatus.NOT_FOUND); } Savepoint savepoint = null; try { try { String[] bindColumns = ArrayUtils.addAll(rowMapper.getUpdateColumns(), rowMapper.getPrimaryKeyColumns()); String colChecksum = rowMapper.getChecksumColumn(); if (!StringUtils.isBlank(colChecksum)) { bindColumns = ArrayUtils.add(bindColumns, colChecksum); } savepoint = conn.getAutoCommit() ? null : conn.setSavepoint(); int numRows = execute(conn, calcSqlUpdateOne(bo), rowMapper.valuesForColumns(bo, bindColumns)); DaoResult result = numRows > 0 ? new DaoResult(DaoOperationStatus.SUCCESSFUL, bo) : new DaoResult(DaoOperationStatus.NOT_FOUND); if (numRows > 0) { invalidateCache(bo, CacheInvalidationReason.UPDATE); } return result; } catch (DuplicatedValueException dke) { if (savepoint != null) { conn.rollback(savepoint); } return new DaoResult(DaoOperationStatus.DUPLICATED_VALUE); } } catch (SQLException e) { throw new DaoException(e); } }
[ "protected", "DaoResult", "update", "(", "Connection", "conn", ",", "T", "bo", ")", "{", "if", "(", "bo", "==", "null", ")", "{", "return", "new", "DaoResult", "(", "DaoOperationStatus", ".", "NOT_FOUND", ")", ";", "}", "Savepoint", "savepoint", "=", "null", ";", "try", "{", "try", "{", "String", "[", "]", "bindColumns", "=", "ArrayUtils", ".", "addAll", "(", "rowMapper", ".", "getUpdateColumns", "(", ")", ",", "rowMapper", ".", "getPrimaryKeyColumns", "(", ")", ")", ";", "String", "colChecksum", "=", "rowMapper", ".", "getChecksumColumn", "(", ")", ";", "if", "(", "!", "StringUtils", ".", "isBlank", "(", "colChecksum", ")", ")", "{", "bindColumns", "=", "ArrayUtils", ".", "add", "(", "bindColumns", ",", "colChecksum", ")", ";", "}", "savepoint", "=", "conn", ".", "getAutoCommit", "(", ")", "?", "null", ":", "conn", ".", "setSavepoint", "(", ")", ";", "int", "numRows", "=", "execute", "(", "conn", ",", "calcSqlUpdateOne", "(", "bo", ")", ",", "rowMapper", ".", "valuesForColumns", "(", "bo", ",", "bindColumns", ")", ")", ";", "DaoResult", "result", "=", "numRows", ">", "0", "?", "new", "DaoResult", "(", "DaoOperationStatus", ".", "SUCCESSFUL", ",", "bo", ")", ":", "new", "DaoResult", "(", "DaoOperationStatus", ".", "NOT_FOUND", ")", ";", "if", "(", "numRows", ">", "0", ")", "{", "invalidateCache", "(", "bo", ",", "CacheInvalidationReason", ".", "UPDATE", ")", ";", "}", "return", "result", ";", "}", "catch", "(", "DuplicatedValueException", "dke", ")", "{", "if", "(", "savepoint", "!=", "null", ")", "{", "conn", ".", "rollback", "(", "savepoint", ")", ";", "}", "return", "new", "DaoResult", "(", "DaoOperationStatus", ".", "DUPLICATED_VALUE", ")", ";", "}", "}", "catch", "(", "SQLException", "e", ")", "{", "throw", "new", "DaoException", "(", "e", ")", ";", "}", "}" ]
Update an existing BO. @param conn @param bo @return @since 0.8.1
[ "Update", "an", "existing", "BO", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java#L636-L667
148,179
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java
GenericBoJdbcDao.createOrUpdate
protected DaoResult createOrUpdate(Connection conn, T bo) { if (bo == null) { return null; } DaoResult result = create(conn, bo); DaoOperationStatus status = result.getStatus(); if (status == DaoOperationStatus.DUPLICATED_VALUE || status == DaoOperationStatus.DUPLICATED_UNIQUE) { result = update(conn, bo); } return result; }
java
protected DaoResult createOrUpdate(Connection conn, T bo) { if (bo == null) { return null; } DaoResult result = create(conn, bo); DaoOperationStatus status = result.getStatus(); if (status == DaoOperationStatus.DUPLICATED_VALUE || status == DaoOperationStatus.DUPLICATED_UNIQUE) { result = update(conn, bo); } return result; }
[ "protected", "DaoResult", "createOrUpdate", "(", "Connection", "conn", ",", "T", "bo", ")", "{", "if", "(", "bo", "==", "null", ")", "{", "return", "null", ";", "}", "DaoResult", "result", "=", "create", "(", "conn", ",", "bo", ")", ";", "DaoOperationStatus", "status", "=", "result", ".", "getStatus", "(", ")", ";", "if", "(", "status", "==", "DaoOperationStatus", ".", "DUPLICATED_VALUE", "||", "status", "==", "DaoOperationStatus", ".", "DUPLICATED_UNIQUE", ")", "{", "result", "=", "update", "(", "conn", ",", "bo", ")", ";", "}", "return", "result", ";", "}" ]
Create a new BO or update an existing one. @param conn @param bo @return @since 0.8.1
[ "Create", "a", "new", "BO", "or", "update", "an", "existing", "one", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java#L692-L703
148,180
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java
GenericBoJdbcDao.updateOrCreate
protected DaoResult updateOrCreate(Connection conn, T bo) { if (bo == null) { return new DaoResult(DaoOperationStatus.NOT_FOUND); } DaoResult result = update(conn, bo); DaoOperationStatus status = result.getStatus(); if (status == DaoOperationStatus.NOT_FOUND) { result = create(conn, bo); } return result; }
java
protected DaoResult updateOrCreate(Connection conn, T bo) { if (bo == null) { return new DaoResult(DaoOperationStatus.NOT_FOUND); } DaoResult result = update(conn, bo); DaoOperationStatus status = result.getStatus(); if (status == DaoOperationStatus.NOT_FOUND) { result = create(conn, bo); } return result; }
[ "protected", "DaoResult", "updateOrCreate", "(", "Connection", "conn", ",", "T", "bo", ")", "{", "if", "(", "bo", "==", "null", ")", "{", "return", "new", "DaoResult", "(", "DaoOperationStatus", ".", "NOT_FOUND", ")", ";", "}", "DaoResult", "result", "=", "update", "(", "conn", ",", "bo", ")", ";", "DaoOperationStatus", "status", "=", "result", ".", "getStatus", "(", ")", ";", "if", "(", "status", "==", "DaoOperationStatus", ".", "NOT_FOUND", ")", "{", "result", "=", "create", "(", "conn", ",", "bo", ")", ";", "}", "return", "result", ";", "}" ]
Update an existing BO or create a new one. @param conn @param bo @return @since 0.8.1
[ "Update", "an", "existing", "BO", "or", "create", "a", "new", "one", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/jdbc/GenericBoJdbcDao.java#L730-L740
148,181
lisicnu/droidUtil
src/main/java/com/github/lisicnu/libDroid/util/BitmapUtils.java
BitmapUtils.load
public synchronized static Bitmap load(InputStream is, int width, int height) { BitmapFactory.Options opt = null; try { opt = new BitmapFactory.Options(); if (width > 0 && height > 0) { if (is.markSupported()) { is.mark(is.available()); opt.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, opt); opt.inSampleSize = calculateInSampleSize(opt, width, height); is.reset(); } } opt.inJustDecodeBounds = false; opt.inPurgeable = true; opt.inInputShareable = true; return BitmapFactory.decodeStream(new FlushedInputStream(is), null, opt); } catch (Exception e) { Log.e(TAG, "", e); return null; } finally { if (is != null) { try { is.close(); } catch (IOException e) { System.out.print(e.toString()); } } opt = null; } }
java
public synchronized static Bitmap load(InputStream is, int width, int height) { BitmapFactory.Options opt = null; try { opt = new BitmapFactory.Options(); if (width > 0 && height > 0) { if (is.markSupported()) { is.mark(is.available()); opt.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, opt); opt.inSampleSize = calculateInSampleSize(opt, width, height); is.reset(); } } opt.inJustDecodeBounds = false; opt.inPurgeable = true; opt.inInputShareable = true; return BitmapFactory.decodeStream(new FlushedInputStream(is), null, opt); } catch (Exception e) { Log.e(TAG, "", e); return null; } finally { if (is != null) { try { is.close(); } catch (IOException e) { System.out.print(e.toString()); } } opt = null; } }
[ "public", "synchronized", "static", "Bitmap", "load", "(", "InputStream", "is", ",", "int", "width", ",", "int", "height", ")", "{", "BitmapFactory", ".", "Options", "opt", "=", "null", ";", "try", "{", "opt", "=", "new", "BitmapFactory", ".", "Options", "(", ")", ";", "if", "(", "width", ">", "0", "&&", "height", ">", "0", ")", "{", "if", "(", "is", ".", "markSupported", "(", ")", ")", "{", "is", ".", "mark", "(", "is", ".", "available", "(", ")", ")", ";", "opt", ".", "inJustDecodeBounds", "=", "true", ";", "BitmapFactory", ".", "decodeStream", "(", "is", ",", "null", ",", "opt", ")", ";", "opt", ".", "inSampleSize", "=", "calculateInSampleSize", "(", "opt", ",", "width", ",", "height", ")", ";", "is", ".", "reset", "(", ")", ";", "}", "}", "opt", ".", "inJustDecodeBounds", "=", "false", ";", "opt", ".", "inPurgeable", "=", "true", ";", "opt", ".", "inInputShareable", "=", "true", ";", "return", "BitmapFactory", ".", "decodeStream", "(", "new", "FlushedInputStream", "(", "is", ")", ",", "null", ",", "opt", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"\"", ",", "e", ")", ";", "return", "null", ";", "}", "finally", "{", "if", "(", "is", "!=", "null", ")", "{", "try", "{", "is", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "System", ".", "out", ".", "print", "(", "e", ".", "toString", "(", ")", ")", ";", "}", "}", "opt", "=", "null", ";", "}", "}" ]
BitmapFactory fails to decode the InputStream.
[ "BitmapFactory", "fails", "to", "decode", "the", "InputStream", "." ]
e4d6cf3e3f60e5efb5a75672607ded94d1725519
https://github.com/lisicnu/droidUtil/blob/e4d6cf3e3f60e5efb5a75672607ded94d1725519/src/main/java/com/github/lisicnu/libDroid/util/BitmapUtils.java#L117-L150
148,182
lisicnu/droidUtil
src/main/java/com/github/lisicnu/libDroid/util/BitmapUtils.java
BitmapUtils.writeToFile
public static boolean writeToFile(Bitmap bmp, String fileName) { if (bmp == null || StringUtils.isNullOrEmpty(fileName)) return false; FileOutputStream fos = null; try { fos = new FileOutputStream(fileName); bmp.compress(CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } catch (Exception e) { return false; } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return true; }
java
public static boolean writeToFile(Bitmap bmp, String fileName) { if (bmp == null || StringUtils.isNullOrEmpty(fileName)) return false; FileOutputStream fos = null; try { fos = new FileOutputStream(fileName); bmp.compress(CompressFormat.PNG, 100, fos); fos.flush(); fos.close(); } catch (Exception e) { return false; } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return true; }
[ "public", "static", "boolean", "writeToFile", "(", "Bitmap", "bmp", ",", "String", "fileName", ")", "{", "if", "(", "bmp", "==", "null", "||", "StringUtils", ".", "isNullOrEmpty", "(", "fileName", ")", ")", "return", "false", ";", "FileOutputStream", "fos", "=", "null", ";", "try", "{", "fos", "=", "new", "FileOutputStream", "(", "fileName", ")", ";", "bmp", ".", "compress", "(", "CompressFormat", ".", "PNG", ",", "100", ",", "fos", ")", ";", "fos", ".", "flush", "(", ")", ";", "fos", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "false", ";", "}", "finally", "{", "if", "(", "fos", "!=", "null", ")", "{", "try", "{", "fos", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// TODO Auto-generated catch block", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "}", "return", "true", ";", "}" ]
write bitmap to file. @param bmp @param fileName @return whether the file has been created success.
[ "write", "bitmap", "to", "file", "." ]
e4d6cf3e3f60e5efb5a75672607ded94d1725519
https://github.com/lisicnu/droidUtil/blob/e4d6cf3e3f60e5efb5a75672607ded94d1725519/src/main/java/com/github/lisicnu/libDroid/util/BitmapUtils.java#L218-L240
148,183
fuinorg/objects4j
src/main/java/org/fuin/objects4j/vo/PasswordStrValidator.java
PasswordStrValidator.isValid
public static final boolean isValid(final String value) { if (value == null) { return true; } if ((value.length() < 8) || (value.length() > 20)) { return false; } return true; }
java
public static final boolean isValid(final String value) { if (value == null) { return true; } if ((value.length() < 8) || (value.length() > 20)) { return false; } return true; }
[ "public", "static", "final", "boolean", "isValid", "(", "final", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "true", ";", "}", "if", "(", "(", "value", ".", "length", "(", ")", "<", "8", ")", "||", "(", "value", ".", "length", "(", ")", ">", "20", ")", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check that a given string is an allowed password. @param value Value to check. @return Returns <code>true</code> if it's an allowed password else <code>false</code> is returned.
[ "Check", "that", "a", "given", "string", "is", "an", "allowed", "password", "." ]
e7f278b5bae073ebb6a76053650571c718f36246
https://github.com/fuinorg/objects4j/blob/e7f278b5bae073ebb6a76053650571c718f36246/src/main/java/org/fuin/objects4j/vo/PasswordStrValidator.java#L48-L56
148,184
jriecken/gae-java-mini-profiler
src/main/java/ca/jimr/gae/profiler/MiniProfilerServlet.java
MiniProfilerServlet.doResource
private void doResource(HttpServletRequest req, HttpServletResponse resp) throws IOException { boolean success = true; String resource = (String) req.getParameter("id"); if (!isEmpty(resource)) { if (resource.endsWith(".js")) { resp.setContentType("text/javascript"); } else if (resource.endsWith(".css")) { resp.setContentType("text/css"); } else if (resource.endsWith(".html")) { resp.setContentType("text/html"); } else { resp.setContentType("text/plain"); } String contents = resourceLoader.getResource(resource, resourceReplacements); if (contents != null) { if (resourceCacheHours > 0) { Calendar c = Calendar.getInstance(); c.add(Calendar.HOUR, resourceCacheHours); resp.setHeader("Cache-Control", "public, must-revalidate"); resp.setHeader("Expires", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(c.getTime())); } else { resp.setHeader("Cache-Control", "no-cache"); } PrintWriter w = resp.getWriter(); w.print(contents); } else { success = false; } } if (!success) { resp.sendError(404); } }
java
private void doResource(HttpServletRequest req, HttpServletResponse resp) throws IOException { boolean success = true; String resource = (String) req.getParameter("id"); if (!isEmpty(resource)) { if (resource.endsWith(".js")) { resp.setContentType("text/javascript"); } else if (resource.endsWith(".css")) { resp.setContentType("text/css"); } else if (resource.endsWith(".html")) { resp.setContentType("text/html"); } else { resp.setContentType("text/plain"); } String contents = resourceLoader.getResource(resource, resourceReplacements); if (contents != null) { if (resourceCacheHours > 0) { Calendar c = Calendar.getInstance(); c.add(Calendar.HOUR, resourceCacheHours); resp.setHeader("Cache-Control", "public, must-revalidate"); resp.setHeader("Expires", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(c.getTime())); } else { resp.setHeader("Cache-Control", "no-cache"); } PrintWriter w = resp.getWriter(); w.print(contents); } else { success = false; } } if (!success) { resp.sendError(404); } }
[ "private", "void", "doResource", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "resp", ")", "throws", "IOException", "{", "boolean", "success", "=", "true", ";", "String", "resource", "=", "(", "String", ")", "req", ".", "getParameter", "(", "\"id\"", ")", ";", "if", "(", "!", "isEmpty", "(", "resource", ")", ")", "{", "if", "(", "resource", ".", "endsWith", "(", "\".js\"", ")", ")", "{", "resp", ".", "setContentType", "(", "\"text/javascript\"", ")", ";", "}", "else", "if", "(", "resource", ".", "endsWith", "(", "\".css\"", ")", ")", "{", "resp", ".", "setContentType", "(", "\"text/css\"", ")", ";", "}", "else", "if", "(", "resource", ".", "endsWith", "(", "\".html\"", ")", ")", "{", "resp", ".", "setContentType", "(", "\"text/html\"", ")", ";", "}", "else", "{", "resp", ".", "setContentType", "(", "\"text/plain\"", ")", ";", "}", "String", "contents", "=", "resourceLoader", ".", "getResource", "(", "resource", ",", "resourceReplacements", ")", ";", "if", "(", "contents", "!=", "null", ")", "{", "if", "(", "resourceCacheHours", ">", "0", ")", "{", "Calendar", "c", "=", "Calendar", ".", "getInstance", "(", ")", ";", "c", ".", "add", "(", "Calendar", ".", "HOUR", ",", "resourceCacheHours", ")", ";", "resp", ".", "setHeader", "(", "\"Cache-Control\"", ",", "\"public, must-revalidate\"", ")", ";", "resp", ".", "setHeader", "(", "\"Expires\"", ",", "new", "SimpleDateFormat", "(", "\"EEE, dd MMM yyyy HH:mm:ss zzz\"", ")", ".", "format", "(", "c", ".", "getTime", "(", ")", ")", ")", ";", "}", "else", "{", "resp", ".", "setHeader", "(", "\"Cache-Control\"", ",", "\"no-cache\"", ")", ";", "}", "PrintWriter", "w", "=", "resp", ".", "getWriter", "(", ")", ";", "w", ".", "print", "(", "contents", ")", ";", "}", "else", "{", "success", "=", "false", ";", "}", "}", "if", "(", "!", "success", ")", "{", "resp", ".", "sendError", "(", "404", ")", ";", "}", "}" ]
Serve one of the static resources for the profiler UI.
[ "Serve", "one", "of", "the", "static", "resources", "for", "the", "profiler", "UI", "." ]
184e3d2470104e066919960d6fbfe0cdc05921d5
https://github.com/jriecken/gae-java-mini-profiler/blob/184e3d2470104e066919960d6fbfe0cdc05921d5/src/main/java/ca/jimr/gae/profiler/MiniProfilerServlet.java#L124-L169
148,185
jriecken/gae-java-mini-profiler
src/main/java/ca/jimr/gae/profiler/MiniProfilerServlet.java
MiniProfilerServlet.doResults
private void doResults(HttpServletRequest req, HttpServletResponse resp) throws IOException, JsonGenerationException, JsonMappingException { Map<String, Object> result = new HashMap<String, Object>(); String requestIds = req.getParameter("ids"); if (!isEmpty(requestIds)) { List<Map<String, Object>> requests = new ArrayList<Map<String, Object>>(); for (String requestId : requestIds.split(",")) { requestId = requestId.trim(); @SuppressWarnings("unchecked") Map<String, Object> requestData = (Map<String, Object>) ms.get(String.format(MiniProfilerFilter.MEMCACHE_KEY_FORMAT_STRING, requestId)); if (requestData != null) { Map<String, Object> request = new HashMap<String, Object>(); request.put("id", requestId); request.put("redirect", requestData.get("redirect")); request.put("requestURL", requestData.get("requestURL")); request.put("timestamp", requestData.get("timestamp")); request.put("profile", requestData.get("profile")); if (requestData.containsKey("appstatsId")) { Map<String, Object> appstatsMap = MiniProfilerAppstats.getAppstatsDataFor((String) requestData.get("appstatsId"), maxStackFrames); request.put("appstats", appstatsMap != null ? appstatsMap : null); } else { request.put("appstats", null); } requests.add(request); } } result.put("ok", true); result.put("requests", requests); } else { result.put("ok", false); } resp.setContentType("application/json"); resp.setHeader("Cache-Control", "no-cache"); ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.writeValue(resp.getOutputStream(), result); }
java
private void doResults(HttpServletRequest req, HttpServletResponse resp) throws IOException, JsonGenerationException, JsonMappingException { Map<String, Object> result = new HashMap<String, Object>(); String requestIds = req.getParameter("ids"); if (!isEmpty(requestIds)) { List<Map<String, Object>> requests = new ArrayList<Map<String, Object>>(); for (String requestId : requestIds.split(",")) { requestId = requestId.trim(); @SuppressWarnings("unchecked") Map<String, Object> requestData = (Map<String, Object>) ms.get(String.format(MiniProfilerFilter.MEMCACHE_KEY_FORMAT_STRING, requestId)); if (requestData != null) { Map<String, Object> request = new HashMap<String, Object>(); request.put("id", requestId); request.put("redirect", requestData.get("redirect")); request.put("requestURL", requestData.get("requestURL")); request.put("timestamp", requestData.get("timestamp")); request.put("profile", requestData.get("profile")); if (requestData.containsKey("appstatsId")) { Map<String, Object> appstatsMap = MiniProfilerAppstats.getAppstatsDataFor((String) requestData.get("appstatsId"), maxStackFrames); request.put("appstats", appstatsMap != null ? appstatsMap : null); } else { request.put("appstats", null); } requests.add(request); } } result.put("ok", true); result.put("requests", requests); } else { result.put("ok", false); } resp.setContentType("application/json"); resp.setHeader("Cache-Control", "no-cache"); ObjectMapper jsonMapper = new ObjectMapper(); jsonMapper.writeValue(resp.getOutputStream(), result); }
[ "private", "void", "doResults", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "resp", ")", "throws", "IOException", ",", "JsonGenerationException", ",", "JsonMappingException", "{", "Map", "<", "String", ",", "Object", ">", "result", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "String", "requestIds", "=", "req", ".", "getParameter", "(", "\"ids\"", ")", ";", "if", "(", "!", "isEmpty", "(", "requestIds", ")", ")", "{", "List", "<", "Map", "<", "String", ",", "Object", ">", ">", "requests", "=", "new", "ArrayList", "<", "Map", "<", "String", ",", "Object", ">", ">", "(", ")", ";", "for", "(", "String", "requestId", ":", "requestIds", ".", "split", "(", "\",\"", ")", ")", "{", "requestId", "=", "requestId", ".", "trim", "(", ")", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Map", "<", "String", ",", "Object", ">", "requestData", "=", "(", "Map", "<", "String", ",", "Object", ">", ")", "ms", ".", "get", "(", "String", ".", "format", "(", "MiniProfilerFilter", ".", "MEMCACHE_KEY_FORMAT_STRING", ",", "requestId", ")", ")", ";", "if", "(", "requestData", "!=", "null", ")", "{", "Map", "<", "String", ",", "Object", ">", "request", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "request", ".", "put", "(", "\"id\"", ",", "requestId", ")", ";", "request", ".", "put", "(", "\"redirect\"", ",", "requestData", ".", "get", "(", "\"redirect\"", ")", ")", ";", "request", ".", "put", "(", "\"requestURL\"", ",", "requestData", ".", "get", "(", "\"requestURL\"", ")", ")", ";", "request", ".", "put", "(", "\"timestamp\"", ",", "requestData", ".", "get", "(", "\"timestamp\"", ")", ")", ";", "request", ".", "put", "(", "\"profile\"", ",", "requestData", ".", "get", "(", "\"profile\"", ")", ")", ";", "if", "(", "requestData", ".", "containsKey", "(", "\"appstatsId\"", ")", ")", "{", "Map", "<", "String", ",", "Object", ">", "appstatsMap", "=", "MiniProfilerAppstats", ".", "getAppstatsDataFor", "(", "(", "String", ")", "requestData", ".", "get", "(", "\"appstatsId\"", ")", ",", "maxStackFrames", ")", ";", "request", ".", "put", "(", "\"appstats\"", ",", "appstatsMap", "!=", "null", "?", "appstatsMap", ":", "null", ")", ";", "}", "else", "{", "request", ".", "put", "(", "\"appstats\"", ",", "null", ")", ";", "}", "requests", ".", "add", "(", "request", ")", ";", "}", "}", "result", ".", "put", "(", "\"ok\"", ",", "true", ")", ";", "result", ".", "put", "(", "\"requests\"", ",", "requests", ")", ";", "}", "else", "{", "result", ".", "put", "(", "\"ok\"", ",", "false", ")", ";", "}", "resp", ".", "setContentType", "(", "\"application/json\"", ")", ";", "resp", ".", "setHeader", "(", "\"Cache-Control\"", ",", "\"no-cache\"", ")", ";", "ObjectMapper", "jsonMapper", "=", "new", "ObjectMapper", "(", ")", ";", "jsonMapper", ".", "writeValue", "(", "resp", ".", "getOutputStream", "(", ")", ",", "result", ")", ";", "}" ]
Generate the results for a set of requests in JSON format.
[ "Generate", "the", "results", "for", "a", "set", "of", "requests", "in", "JSON", "format", "." ]
184e3d2470104e066919960d6fbfe0cdc05921d5
https://github.com/jriecken/gae-java-mini-profiler/blob/184e3d2470104e066919960d6fbfe0cdc05921d5/src/main/java/ca/jimr/gae/profiler/MiniProfilerServlet.java#L174-L218
148,186
grycap/coreutils
coreutils-fiber/src/main/java/es/upv/grycap/coreutils/fiber/net/UrlBuilder.java
UrlBuilder.getUrlBuilder
public static UrlBuilder getUrlBuilder(final URL baseUrl) { URL url = null; try { url = new URL(decode(requireNonNull(baseUrl).toString(), defaultCharset().name())); } catch (MalformedURLException | UnsupportedEncodingException e) { throw new IllegalArgumentException(new StringBuilder("Cannot create a URI from the provided URL: ") .append(baseUrl != null ? baseUrl.toString() : "null").toString(), e); } return new UrlBuilder(url); }
java
public static UrlBuilder getUrlBuilder(final URL baseUrl) { URL url = null; try { url = new URL(decode(requireNonNull(baseUrl).toString(), defaultCharset().name())); } catch (MalformedURLException | UnsupportedEncodingException e) { throw new IllegalArgumentException(new StringBuilder("Cannot create a URI from the provided URL: ") .append(baseUrl != null ? baseUrl.toString() : "null").toString(), e); } return new UrlBuilder(url); }
[ "public", "static", "UrlBuilder", "getUrlBuilder", "(", "final", "URL", "baseUrl", ")", "{", "URL", "url", "=", "null", ";", "try", "{", "url", "=", "new", "URL", "(", "decode", "(", "requireNonNull", "(", "baseUrl", ")", ".", "toString", "(", ")", ",", "defaultCharset", "(", ")", ".", "name", "(", ")", ")", ")", ";", "}", "catch", "(", "MalformedURLException", "|", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "new", "StringBuilder", "(", "\"Cannot create a URI from the provided URL: \"", ")", ".", "append", "(", "baseUrl", "!=", "null", "?", "baseUrl", ".", "toString", "(", ")", ":", "\"null\"", ")", ".", "toString", "(", ")", ",", "e", ")", ";", "}", "return", "new", "UrlBuilder", "(", "url", ")", ";", "}" ]
Convenient factory method that creates a new instance of this class. @param baseUrl - base URL that will be used to create new URLs @return A new instance of this class, allowing callers to use the methods of this class to create new URLs from the base URL provided as argument.
[ "Convenient", "factory", "method", "that", "creates", "a", "new", "instance", "of", "this", "class", "." ]
e6db61dc50b49ea7276c0c29c7401204681a10c2
https://github.com/grycap/coreutils/blob/e6db61dc50b49ea7276c0c29c7401204681a10c2/coreutils-fiber/src/main/java/es/upv/grycap/coreutils/fiber/net/UrlBuilder.java#L69-L78
148,187
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/config/StormConfigGenerator.java
StormConfigGenerator.loadStormConfig
public static Config loadStormConfig(File targetFile) throws IOException { Map<String, Object> yamlConfig = readYaml(targetFile); Config stormConf = convertYamlToStormConf(yamlConfig); // For track update config, has init file path. if (stormConf.containsKey(INIT_CONFIG_KEY) == false) { String absolutePath = targetFile.getAbsolutePath(); stormConf.put(INIT_CONFIG_KEY, absolutePath); } return stormConf; }
java
public static Config loadStormConfig(File targetFile) throws IOException { Map<String, Object> yamlConfig = readYaml(targetFile); Config stormConf = convertYamlToStormConf(yamlConfig); // For track update config, has init file path. if (stormConf.containsKey(INIT_CONFIG_KEY) == false) { String absolutePath = targetFile.getAbsolutePath(); stormConf.put(INIT_CONFIG_KEY, absolutePath); } return stormConf; }
[ "public", "static", "Config", "loadStormConfig", "(", "File", "targetFile", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "Object", ">", "yamlConfig", "=", "readYaml", "(", "targetFile", ")", ";", "Config", "stormConf", "=", "convertYamlToStormConf", "(", "yamlConfig", ")", ";", "// For track update config, has init file path.\r", "if", "(", "stormConf", ".", "containsKey", "(", "INIT_CONFIG_KEY", ")", "==", "false", ")", "{", "String", "absolutePath", "=", "targetFile", ".", "getAbsolutePath", "(", ")", ";", "stormConf", ".", "put", "(", "INIT_CONFIG_KEY", ",", "absolutePath", ")", ";", "}", "return", "stormConf", ";", "}" ]
Generate storm config object from the yaml file at specified file. @param targetFile target file @return Storm config object @throws IOException Fail read yaml file or convert to storm config object.
[ "Generate", "storm", "config", "object", "from", "the", "yaml", "file", "at", "specified", "file", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/config/StormConfigGenerator.java#L75-L88
148,188
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/config/StormConfigGenerator.java
StormConfigGenerator.convertYamlToStormConf
public static Config convertYamlToStormConf(Map<String, Object> yamlConf) { Config stormConf = new Config(); for (Entry<String, Object> targetConfigEntry : yamlConf.entrySet()) { stormConf.put(targetConfigEntry.getKey(), targetConfigEntry.getValue()); } return stormConf; }
java
public static Config convertYamlToStormConf(Map<String, Object> yamlConf) { Config stormConf = new Config(); for (Entry<String, Object> targetConfigEntry : yamlConf.entrySet()) { stormConf.put(targetConfigEntry.getKey(), targetConfigEntry.getValue()); } return stormConf; }
[ "public", "static", "Config", "convertYamlToStormConf", "(", "Map", "<", "String", ",", "Object", ">", "yamlConf", ")", "{", "Config", "stormConf", "=", "new", "Config", "(", ")", ";", "for", "(", "Entry", "<", "String", ",", "Object", ">", "targetConfigEntry", ":", "yamlConf", ".", "entrySet", "(", ")", ")", "{", "stormConf", ".", "put", "(", "targetConfigEntry", ".", "getKey", "(", ")", ",", "targetConfigEntry", ".", "getValue", "(", ")", ")", ";", "}", "return", "stormConf", ";", "}" ]
Convert config read from yaml file config to storm config object. @param yamlConf config read from yaml @return Storm config object
[ "Convert", "config", "read", "from", "yaml", "file", "config", "to", "storm", "config", "object", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/config/StormConfigGenerator.java#L96-L106
148,189
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/config/StormConfigGenerator.java
StormConfigGenerator.readYaml
public static Map<String, Object> readYaml(String filePath) throws IOException { File targetFile = new File(filePath); Map<String, Object> configObject = readYaml(targetFile); return configObject; }
java
public static Map<String, Object> readYaml(String filePath) throws IOException { File targetFile = new File(filePath); Map<String, Object> configObject = readYaml(targetFile); return configObject; }
[ "public", "static", "Map", "<", "String", ",", "Object", ">", "readYaml", "(", "String", "filePath", ")", "throws", "IOException", "{", "File", "targetFile", "=", "new", "File", "(", "filePath", ")", ";", "Map", "<", "String", ",", "Object", ">", "configObject", "=", "readYaml", "(", "targetFile", ")", ";", "return", "configObject", ";", "}" ]
Read yaml config object from the yaml file at specified path. @param filePath target file path @return config read from yaml @throws IOException Fail read yaml file or convert to config object.
[ "Read", "yaml", "config", "object", "from", "the", "yaml", "file", "at", "specified", "path", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/config/StormConfigGenerator.java#L115-L120
148,190
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/config/StormConfigGenerator.java
StormConfigGenerator.readYaml
@SuppressWarnings("unchecked") public static Map<String, Object> readYaml(File targetFile) throws IOException { Map<String, Object> configObject = null; Yaml yaml = new Yaml(); InputStream inputStream = null; InputStreamReader steamReader = null; try { inputStream = new FileInputStream(targetFile); steamReader = new InputStreamReader(inputStream, "UTF-8"); configObject = (Map<String, Object>) yaml.load(steamReader); } catch (ScannerException ex) { // ScannerException/IOException are occured. // throw IOException because handling is same. throw new IOException(ex); } finally { IOUtils.closeQuietly(inputStream); } return configObject; }
java
@SuppressWarnings("unchecked") public static Map<String, Object> readYaml(File targetFile) throws IOException { Map<String, Object> configObject = null; Yaml yaml = new Yaml(); InputStream inputStream = null; InputStreamReader steamReader = null; try { inputStream = new FileInputStream(targetFile); steamReader = new InputStreamReader(inputStream, "UTF-8"); configObject = (Map<String, Object>) yaml.load(steamReader); } catch (ScannerException ex) { // ScannerException/IOException are occured. // throw IOException because handling is same. throw new IOException(ex); } finally { IOUtils.closeQuietly(inputStream); } return configObject; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "Map", "<", "String", ",", "Object", ">", "readYaml", "(", "File", "targetFile", ")", "throws", "IOException", "{", "Map", "<", "String", ",", "Object", ">", "configObject", "=", "null", ";", "Yaml", "yaml", "=", "new", "Yaml", "(", ")", ";", "InputStream", "inputStream", "=", "null", ";", "InputStreamReader", "steamReader", "=", "null", ";", "try", "{", "inputStream", "=", "new", "FileInputStream", "(", "targetFile", ")", ";", "steamReader", "=", "new", "InputStreamReader", "(", "inputStream", ",", "\"UTF-8\"", ")", ";", "configObject", "=", "(", "Map", "<", "String", ",", "Object", ">", ")", "yaml", ".", "load", "(", "steamReader", ")", ";", "}", "catch", "(", "ScannerException", "ex", ")", "{", "// ScannerException/IOException are occured.\r", "// throw IOException because handling is same.\r", "throw", "new", "IOException", "(", "ex", ")", ";", "}", "finally", "{", "IOUtils", ".", "closeQuietly", "(", "inputStream", ")", ";", "}", "return", "configObject", ";", "}" ]
Read yaml config object from the yaml file at specified file. @param targetFile target file @return config read from yaml @throws IOException Fail read yaml file or convert to config object.
[ "Read", "yaml", "config", "object", "from", "the", "yaml", "file", "at", "specified", "file", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/config/StormConfigGenerator.java#L129-L156
148,191
jriecken/gae-java-mini-profiler
src/main/java/ca/jimr/gae/profiler/MiniProfilerFilter.java
MiniProfilerFilter.doFilter
@Override public void doFilter(ServletRequest sReq, ServletResponse sRes, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) sReq; HttpServletResponse res = (HttpServletResponse) sRes; if (shouldProfile(req.getRequestURI())) { String queryString = req.getQueryString(); String requestId = String.valueOf(counter.incrementAndGet()); String redirectRequestIds = null; if (!isEmpty(queryString)) { String[] parts = queryString.split("&"); for (String part : parts) { String[] nameValue = part.split("="); if (REQUEST_ID_PARAM_REDIRECT.equals(nameValue[0])) { redirectRequestIds = nameValue[1]; break; } } } req.setAttribute(REQUEST_ID_ATTRIBUTE, requestId); res.addHeader(REQUEST_ID_HEADER, redirectRequestIds != null ? redirectRequestIds + "," + requestId : requestId); addIncludes(req); ResponseWrapper resWrapper = new ResponseWrapper(res, requestId, redirectRequestIds); MiniProfiler.Profile profile = null; long startTime = System.currentTimeMillis(); MiniProfiler.start(); try { chain.doFilter(sReq, resWrapper); } finally { profile = MiniProfiler.stop(); } Map<String, Object> requestData = new HashMap<String, Object>(); requestData.put("requestURL", req.getRequestURI() + ((req.getQueryString() != null) ? "?" + req.getQueryString() : "")); requestData.put("timestamp", startTime); requestData.put("redirect", resWrapper.getDidRedirect()); String appstatsId = resWrapper.getAppstatsId(); if (appstatsId != null) { requestData.put("appstatsId", appstatsId); } requestData.put("profile", profile); ms.put(String.format(MEMCACHE_KEY_FORMAT_STRING, requestId), requestData, Expiration.byDeltaSeconds(dataExpiry)); } else { chain.doFilter(sReq, sRes); } }
java
@Override public void doFilter(ServletRequest sReq, ServletResponse sRes, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) sReq; HttpServletResponse res = (HttpServletResponse) sRes; if (shouldProfile(req.getRequestURI())) { String queryString = req.getQueryString(); String requestId = String.valueOf(counter.incrementAndGet()); String redirectRequestIds = null; if (!isEmpty(queryString)) { String[] parts = queryString.split("&"); for (String part : parts) { String[] nameValue = part.split("="); if (REQUEST_ID_PARAM_REDIRECT.equals(nameValue[0])) { redirectRequestIds = nameValue[1]; break; } } } req.setAttribute(REQUEST_ID_ATTRIBUTE, requestId); res.addHeader(REQUEST_ID_HEADER, redirectRequestIds != null ? redirectRequestIds + "," + requestId : requestId); addIncludes(req); ResponseWrapper resWrapper = new ResponseWrapper(res, requestId, redirectRequestIds); MiniProfiler.Profile profile = null; long startTime = System.currentTimeMillis(); MiniProfiler.start(); try { chain.doFilter(sReq, resWrapper); } finally { profile = MiniProfiler.stop(); } Map<String, Object> requestData = new HashMap<String, Object>(); requestData.put("requestURL", req.getRequestURI() + ((req.getQueryString() != null) ? "?" + req.getQueryString() : "")); requestData.put("timestamp", startTime); requestData.put("redirect", resWrapper.getDidRedirect()); String appstatsId = resWrapper.getAppstatsId(); if (appstatsId != null) { requestData.put("appstatsId", appstatsId); } requestData.put("profile", profile); ms.put(String.format(MEMCACHE_KEY_FORMAT_STRING, requestId), requestData, Expiration.byDeltaSeconds(dataExpiry)); } else { chain.doFilter(sReq, sRes); } }
[ "@", "Override", "public", "void", "doFilter", "(", "ServletRequest", "sReq", ",", "ServletResponse", "sRes", ",", "FilterChain", "chain", ")", "throws", "IOException", ",", "ServletException", "{", "HttpServletRequest", "req", "=", "(", "HttpServletRequest", ")", "sReq", ";", "HttpServletResponse", "res", "=", "(", "HttpServletResponse", ")", "sRes", ";", "if", "(", "shouldProfile", "(", "req", ".", "getRequestURI", "(", ")", ")", ")", "{", "String", "queryString", "=", "req", ".", "getQueryString", "(", ")", ";", "String", "requestId", "=", "String", ".", "valueOf", "(", "counter", ".", "incrementAndGet", "(", ")", ")", ";", "String", "redirectRequestIds", "=", "null", ";", "if", "(", "!", "isEmpty", "(", "queryString", ")", ")", "{", "String", "[", "]", "parts", "=", "queryString", ".", "split", "(", "\"&\"", ")", ";", "for", "(", "String", "part", ":", "parts", ")", "{", "String", "[", "]", "nameValue", "=", "part", ".", "split", "(", "\"=\"", ")", ";", "if", "(", "REQUEST_ID_PARAM_REDIRECT", ".", "equals", "(", "nameValue", "[", "0", "]", ")", ")", "{", "redirectRequestIds", "=", "nameValue", "[", "1", "]", ";", "break", ";", "}", "}", "}", "req", ".", "setAttribute", "(", "REQUEST_ID_ATTRIBUTE", ",", "requestId", ")", ";", "res", ".", "addHeader", "(", "REQUEST_ID_HEADER", ",", "redirectRequestIds", "!=", "null", "?", "redirectRequestIds", "+", "\",\"", "+", "requestId", ":", "requestId", ")", ";", "addIncludes", "(", "req", ")", ";", "ResponseWrapper", "resWrapper", "=", "new", "ResponseWrapper", "(", "res", ",", "requestId", ",", "redirectRequestIds", ")", ";", "MiniProfiler", ".", "Profile", "profile", "=", "null", ";", "long", "startTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "MiniProfiler", ".", "start", "(", ")", ";", "try", "{", "chain", ".", "doFilter", "(", "sReq", ",", "resWrapper", ")", ";", "}", "finally", "{", "profile", "=", "MiniProfiler", ".", "stop", "(", ")", ";", "}", "Map", "<", "String", ",", "Object", ">", "requestData", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "requestData", ".", "put", "(", "\"requestURL\"", ",", "req", ".", "getRequestURI", "(", ")", "+", "(", "(", "req", ".", "getQueryString", "(", ")", "!=", "null", ")", "?", "\"?\"", "+", "req", ".", "getQueryString", "(", ")", ":", "\"\"", ")", ")", ";", "requestData", ".", "put", "(", "\"timestamp\"", ",", "startTime", ")", ";", "requestData", ".", "put", "(", "\"redirect\"", ",", "resWrapper", ".", "getDidRedirect", "(", ")", ")", ";", "String", "appstatsId", "=", "resWrapper", ".", "getAppstatsId", "(", ")", ";", "if", "(", "appstatsId", "!=", "null", ")", "{", "requestData", ".", "put", "(", "\"appstatsId\"", ",", "appstatsId", ")", ";", "}", "requestData", ".", "put", "(", "\"profile\"", ",", "profile", ")", ";", "ms", ".", "put", "(", "String", ".", "format", "(", "MEMCACHE_KEY_FORMAT_STRING", ",", "requestId", ")", ",", "requestData", ",", "Expiration", ".", "byDeltaSeconds", "(", "dataExpiry", ")", ")", ";", "}", "else", "{", "chain", ".", "doFilter", "(", "sReq", ",", "sRes", ")", ";", "}", "}" ]
If profiling is supposed to occur for the current request, profile the request. Otherwise this filter does nothing.
[ "If", "profiling", "is", "supposed", "to", "occur", "for", "the", "current", "request", "profile", "the", "request", ".", "Otherwise", "this", "filter", "does", "nothing", "." ]
184e3d2470104e066919960d6fbfe0cdc05921d5
https://github.com/jriecken/gae-java-mini-profiler/blob/184e3d2470104e066919960d6fbfe0cdc05921d5/src/main/java/ca/jimr/gae/profiler/MiniProfilerFilter.java#L177-L234
148,192
jriecken/gae-java-mini-profiler
src/main/java/ca/jimr/gae/profiler/MiniProfilerFilter.java
MiniProfilerFilter.shouldProfile
public boolean shouldProfile(String url) { // Don't profile requests to to results servlet if (url.startsWith(servletURL)) { return false; } if (!restrictedURLs.isEmpty()) { boolean matches = false; for (Pattern p : restrictedURLs) { if (p.matcher(url).find()) { matches = true; } } if (!matches) { return false; } } if (restricted) { if (us.isUserLoggedIn()) { if (restrictedToAdmins && !us.isUserAdmin()) { return false; } if (!restrictedEmails.isEmpty() && !restrictedEmails.contains(us.getCurrentUser().getEmail())) { return false; } } else { return false; } } return true; }
java
public boolean shouldProfile(String url) { // Don't profile requests to to results servlet if (url.startsWith(servletURL)) { return false; } if (!restrictedURLs.isEmpty()) { boolean matches = false; for (Pattern p : restrictedURLs) { if (p.matcher(url).find()) { matches = true; } } if (!matches) { return false; } } if (restricted) { if (us.isUserLoggedIn()) { if (restrictedToAdmins && !us.isUserAdmin()) { return false; } if (!restrictedEmails.isEmpty() && !restrictedEmails.contains(us.getCurrentUser().getEmail())) { return false; } } else { return false; } } return true; }
[ "public", "boolean", "shouldProfile", "(", "String", "url", ")", "{", "// Don't profile requests to to results servlet", "if", "(", "url", ".", "startsWith", "(", "servletURL", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "restrictedURLs", ".", "isEmpty", "(", ")", ")", "{", "boolean", "matches", "=", "false", ";", "for", "(", "Pattern", "p", ":", "restrictedURLs", ")", "{", "if", "(", "p", ".", "matcher", "(", "url", ")", ".", "find", "(", ")", ")", "{", "matches", "=", "true", ";", "}", "}", "if", "(", "!", "matches", ")", "{", "return", "false", ";", "}", "}", "if", "(", "restricted", ")", "{", "if", "(", "us", ".", "isUserLoggedIn", "(", ")", ")", "{", "if", "(", "restrictedToAdmins", "&&", "!", "us", ".", "isUserAdmin", "(", ")", ")", "{", "return", "false", ";", "}", "if", "(", "!", "restrictedEmails", ".", "isEmpty", "(", ")", "&&", "!", "restrictedEmails", ".", "contains", "(", "us", ".", "getCurrentUser", "(", ")", ".", "getEmail", "(", ")", ")", ")", "{", "return", "false", ";", "}", "}", "else", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Whether the specified URL should be profiled given the current configuration of the filter. @param url The URL to check. @return Whether the URL should be profiled.
[ "Whether", "the", "specified", "URL", "should", "be", "profiled", "given", "the", "current", "configuration", "of", "the", "filter", "." ]
184e3d2470104e066919960d6fbfe0cdc05921d5
https://github.com/jriecken/gae-java-mini-profiler/blob/184e3d2470104e066919960d6fbfe0cdc05921d5/src/main/java/ca/jimr/gae/profiler/MiniProfilerFilter.java#L269-L311
148,193
lisicnu/droidUtil
src/main/java/com/github/lisicnu/libDroid/util/DateUtils.java
DateUtils.getShortDateString
public static String getShortDateString(long time, String format) { if (format == null || format.isEmpty()) { format = "yyyy-MM-dd"; } SimpleDateFormat smpf = new SimpleDateFormat(format); return smpf.format(new Date(time)); }
java
public static String getShortDateString(long time, String format) { if (format == null || format.isEmpty()) { format = "yyyy-MM-dd"; } SimpleDateFormat smpf = new SimpleDateFormat(format); return smpf.format(new Date(time)); }
[ "public", "static", "String", "getShortDateString", "(", "long", "time", ",", "String", "format", ")", "{", "if", "(", "format", "==", "null", "||", "format", ".", "isEmpty", "(", ")", ")", "{", "format", "=", "\"yyyy-MM-dd\"", ";", "}", "SimpleDateFormat", "smpf", "=", "new", "SimpleDateFormat", "(", "format", ")", ";", "return", "smpf", ".", "format", "(", "new", "Date", "(", "time", ")", ")", ";", "}" ]
get formated date String @param time @param format if is null or empty, will use "yyyy-MM-dd"
[ "get", "formated", "date", "String" ]
e4d6cf3e3f60e5efb5a75672607ded94d1725519
https://github.com/lisicnu/droidUtil/blob/e4d6cf3e3f60e5efb5a75672607ded94d1725519/src/main/java/com/github/lisicnu/libDroid/util/DateUtils.java#L23-L30
148,194
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/bolt/AmBaseBolt.java
AmBaseBolt.onMessage
@Override public void onMessage(StreamMessage received) { if (this.reloadConfig && this.watcher != null) { Map<String, Object> reloadedConfig = null; try { reloadedConfig = this.watcher.readIfUpdated(); } catch (IOException ex) { String logFormat = "Config file reload failed. Skip reload config."; logger.warn(logFormat, ex); } if (reloadedConfig != null) { onUpdate(reloadedConfig); } } this.executingKeyHistory = received.getHeader().getHistory(); this.responsed = false; // Execute message processing. // This class not handles exceptions. // Because if throws exception, this class not need ack. try { onExecute(received); } finally { clearExecuteStatus(); } // If not responsed, auto ack if (this.responsed == false) { super.ack(); } }
java
@Override public void onMessage(StreamMessage received) { if (this.reloadConfig && this.watcher != null) { Map<String, Object> reloadedConfig = null; try { reloadedConfig = this.watcher.readIfUpdated(); } catch (IOException ex) { String logFormat = "Config file reload failed. Skip reload config."; logger.warn(logFormat, ex); } if (reloadedConfig != null) { onUpdate(reloadedConfig); } } this.executingKeyHistory = received.getHeader().getHistory(); this.responsed = false; // Execute message processing. // This class not handles exceptions. // Because if throws exception, this class not need ack. try { onExecute(received); } finally { clearExecuteStatus(); } // If not responsed, auto ack if (this.responsed == false) { super.ack(); } }
[ "@", "Override", "public", "void", "onMessage", "(", "StreamMessage", "received", ")", "{", "if", "(", "this", ".", "reloadConfig", "&&", "this", ".", "watcher", "!=", "null", ")", "{", "Map", "<", "String", ",", "Object", ">", "reloadedConfig", "=", "null", ";", "try", "{", "reloadedConfig", "=", "this", ".", "watcher", ".", "readIfUpdated", "(", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "String", "logFormat", "=", "\"Config file reload failed. Skip reload config.\"", ";", "logger", ".", "warn", "(", "logFormat", ",", "ex", ")", ";", "}", "if", "(", "reloadedConfig", "!=", "null", ")", "{", "onUpdate", "(", "reloadedConfig", ")", ";", "}", "}", "this", ".", "executingKeyHistory", "=", "received", ".", "getHeader", "(", ")", ".", "getHistory", "(", ")", ";", "this", ".", "responsed", "=", "false", ";", "// Execute message processing.", "// This class not handles exceptions.", "// Because if throws exception, this class not need ack.", "try", "{", "onExecute", "(", "received", ")", ";", "}", "finally", "{", "clearExecuteStatus", "(", ")", ";", "}", "// If not responsed, auto ack", "if", "(", "this", ".", "responsed", "==", "false", ")", "{", "super", ".", "ack", "(", ")", ";", "}", "}" ]
Execute when receive message. @param received received message
[ "Execute", "when", "receive", "message", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/bolt/AmBaseBolt.java#L137-L180
148,195
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/bolt/AmBaseBolt.java
AmBaseBolt.createKeyRecorededHistory
protected KeyHistory createKeyRecorededHistory(KeyHistory history, Object messageKey) { KeyHistory result = null; if (history == null) { result = new KeyHistory(); } else { // For adjust message splited, use keyhistory's deepcopy. result = history.createDeepCopy(); } result.addKey(messageKey.toString()); return result; }
java
protected KeyHistory createKeyRecorededHistory(KeyHistory history, Object messageKey) { KeyHistory result = null; if (history == null) { result = new KeyHistory(); } else { // For adjust message splited, use keyhistory's deepcopy. result = history.createDeepCopy(); } result.addKey(messageKey.toString()); return result; }
[ "protected", "KeyHistory", "createKeyRecorededHistory", "(", "KeyHistory", "history", ",", "Object", "messageKey", ")", "{", "KeyHistory", "result", "=", "null", ";", "if", "(", "history", "==", "null", ")", "{", "result", "=", "new", "KeyHistory", "(", ")", ";", "}", "else", "{", "// For adjust message splited, use keyhistory's deepcopy.", "result", "=", "history", ".", "createDeepCopy", "(", ")", ";", "}", "result", ".", "addKey", "(", "messageKey", ".", "toString", "(", ")", ")", ";", "return", "result", ";", "}" ]
Create keyhistory from original key history and current message key. @param history original key history @param messageKey current message key @return created key history
[ "Create", "keyhistory", "from", "original", "key", "history", "and", "current", "message", "key", "." ]
65b1f335d771d657c5640a2056ab5c8546eddec9
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/bolt/AmBaseBolt.java#L295-L312
148,196
lisicnu/droidUtil
src/main/java/com/github/lisicnu/libDroid/util/ShellUtils.java
ShellUtils.execCommand
public static CommandResult execCommand(String command, boolean isRoot) { return execCommand(new String[]{command}, isRoot, true); }
java
public static CommandResult execCommand(String command, boolean isRoot) { return execCommand(new String[]{command}, isRoot, true); }
[ "public", "static", "CommandResult", "execCommand", "(", "String", "command", ",", "boolean", "isRoot", ")", "{", "return", "execCommand", "(", "new", "String", "[", "]", "{", "command", "}", ",", "isRoot", ",", "true", ")", ";", "}" ]
execute shell command, default return result msg @param command command @param isRoot whether need to run with root @return @see ShellUtils#execCommand(String[], boolean, boolean)
[ "execute", "shell", "command", "default", "return", "result", "msg" ]
e4d6cf3e3f60e5efb5a75672607ded94d1725519
https://github.com/lisicnu/droidUtil/blob/e4d6cf3e3f60e5efb5a75672607ded94d1725519/src/main/java/com/github/lisicnu/libDroid/util/ShellUtils.java#L44-L46
148,197
lisicnu/droidUtil
src/main/java/com/github/lisicnu/libDroid/util/ShellUtils.java
ShellUtils.execCommand
public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) { return execCommand(new String[]{command}, isRoot, isNeedResultMsg); }
java
public static CommandResult execCommand(String command, boolean isRoot, boolean isNeedResultMsg) { return execCommand(new String[]{command}, isRoot, isNeedResultMsg); }
[ "public", "static", "CommandResult", "execCommand", "(", "String", "command", ",", "boolean", "isRoot", ",", "boolean", "isNeedResultMsg", ")", "{", "return", "execCommand", "(", "new", "String", "[", "]", "{", "command", "}", ",", "isRoot", ",", "isNeedResultMsg", ")", ";", "}" ]
execute shell command @param command command @param isRoot whether need to run with root @param isNeedResultMsg whether need result msg @return @see ShellUtils#execCommand(String[], boolean, boolean)
[ "execute", "shell", "command" ]
e4d6cf3e3f60e5efb5a75672607ded94d1725519
https://github.com/lisicnu/droidUtil/blob/e4d6cf3e3f60e5efb5a75672607ded94d1725519/src/main/java/com/github/lisicnu/libDroid/util/ShellUtils.java#L81-L83
148,198
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/nosql/BaseNoSqlDao.java
BaseNoSqlDao.invalidateCacheEntry
protected void invalidateCacheEntry(String spaceId, String key) { if (isCacheEnabled()) { removeFromCache(getCacheName(), calcCacheKey(spaceId, key)); } }
java
protected void invalidateCacheEntry(String spaceId, String key) { if (isCacheEnabled()) { removeFromCache(getCacheName(), calcCacheKey(spaceId, key)); } }
[ "protected", "void", "invalidateCacheEntry", "(", "String", "spaceId", ",", "String", "key", ")", "{", "if", "(", "isCacheEnabled", "(", ")", ")", "{", "removeFromCache", "(", "getCacheName", "(", ")", ",", "calcCacheKey", "(", "spaceId", ",", "key", ")", ")", ";", "}", "}" ]
Invalidate a cache entry. @param spaceId @param key
[ "Invalidate", "a", "cache", "entry", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/nosql/BaseNoSqlDao.java#L51-L55
148,199
DDTH/ddth-dao
ddth-dao-core/src/main/java/com/github/ddth/dao/nosql/BaseNoSqlDao.java
BaseNoSqlDao.invalidateCacheEntry
protected void invalidateCacheEntry(String spaceId, String key, Object data) { if (isCacheEnabled()) { putToCache(getCacheName(), calcCacheKey(spaceId, key), data); } }
java
protected void invalidateCacheEntry(String spaceId, String key, Object data) { if (isCacheEnabled()) { putToCache(getCacheName(), calcCacheKey(spaceId, key), data); } }
[ "protected", "void", "invalidateCacheEntry", "(", "String", "spaceId", ",", "String", "key", ",", "Object", "data", ")", "{", "if", "(", "isCacheEnabled", "(", ")", ")", "{", "putToCache", "(", "getCacheName", "(", ")", ",", "calcCacheKey", "(", "spaceId", ",", "key", ")", ",", "data", ")", ";", "}", "}" ]
Invalidate a cache entry due to updated content. @param spaceId @param key @param data
[ "Invalidate", "a", "cache", "entry", "due", "to", "updated", "content", "." ]
8d059ddf641a1629aa53851f9d1b41abf175a180
https://github.com/DDTH/ddth-dao/blob/8d059ddf641a1629aa53851f9d1b41abf175a180/ddth-dao-core/src/main/java/com/github/ddth/dao/nosql/BaseNoSqlDao.java#L64-L68