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
155,300
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/net/HttpCallUtils.java
HttpCallUtils.doHttpCall
public HttpResponse doHttpCall(final String urlString, final String stringToSend) throws IOException { return this.doHttpCall(urlString, stringToSend, "", "", "", 0, Collections.<String, String> emptyMap()); }
java
public HttpResponse doHttpCall(final String urlString, final String stringToSend) throws IOException { return this.doHttpCall(urlString, stringToSend, "", "", "", 0, Collections.<String, String> emptyMap()); }
[ "public", "HttpResponse", "doHttpCall", "(", "final", "String", "urlString", ",", "final", "String", "stringToSend", ")", "throws", "IOException", "{", "return", "this", ".", "doHttpCall", "(", "urlString", ",", "stringToSend", ",", "\"\"", ",", "\"\"", ",", "\"\"", ",", "0", ",", "Collections", ".", "<", "String", ",", "String", ">", "emptyMap", "(", ")", ")", ";", "}" ]
Sends a string to a URL. This is very helpful when SOAP web services are involved or you just want to post a XML message to a URL. @param urlString the URL to post to @param stringToSend the string that will be post to the URL @return a {@link HttpResponse} object containing the response code and the response string @throws IOException if a I/O error occurs
[ "Sends", "a", "string", "to", "a", "URL", ".", "This", "is", "very", "helpful", "when", "SOAP", "web", "services", "are", "involved", "or", "you", "just", "want", "to", "post", "a", "XML", "message", "to", "a", "URL", "." ]
f89d91c59f686114f94624bfc55712f278005bfa
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/net/HttpCallUtils.java#L163-L167
155,301
JM-Lab/utils-java8
src/main/java/kr/jm/utils/exception/JMExceptionManager.java
JMExceptionManager.logException
@Deprecated public static void logException(Logger log, Throwable throwable, String methodName, Object... params) { handleException(log, throwable, methodName, params); }
java
@Deprecated public static void logException(Logger log, Throwable throwable, String methodName, Object... params) { handleException(log, throwable, methodName, params); }
[ "@", "Deprecated", "public", "static", "void", "logException", "(", "Logger", "log", ",", "Throwable", "throwable", ",", "String", "methodName", ",", "Object", "...", "params", ")", "{", "handleException", "(", "log", ",", "throwable", ",", "methodName", ",", "params", ")", ";", "}" ]
Log exception. @param log the log @param throwable the throwable @param methodName the method name @param params the params
[ "Log", "exception", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/exception/JMExceptionManager.java#L54-L58
155,302
JM-Lab/utils-java8
src/main/java/kr/jm/utils/exception/JMExceptionManager.java
JMExceptionManager.handleExceptionAndReturnNull
public static <T> T handleExceptionAndReturnNull(Logger log, Throwable throwable, String method, Object... params) { handleException(log, throwable, method, params); return null; }
java
public static <T> T handleExceptionAndReturnNull(Logger log, Throwable throwable, String method, Object... params) { handleException(log, throwable, method, params); return null; }
[ "public", "static", "<", "T", ">", "T", "handleExceptionAndReturnNull", "(", "Logger", "log", ",", "Throwable", "throwable", ",", "String", "method", ",", "Object", "...", "params", ")", "{", "handleException", "(", "log", ",", "throwable", ",", "method", ",", "params", ")", ";", "return", "null", ";", "}" ]
Handle exception and return null t. @param <T> the type parameter @param log the log @param throwable the throwable @param method the method @param params the params @return the t
[ "Handle", "exception", "and", "return", "null", "t", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/exception/JMExceptionManager.java#L136-L140
155,303
JM-Lab/utils-java8
src/main/java/kr/jm/utils/exception/JMExceptionManager.java
JMExceptionManager.handleExceptionAndReturnFalse
public static boolean handleExceptionAndReturnFalse(Logger log, Throwable throwable, String method, Object... params) { handleException(log, throwable, method, params); return false; }
java
public static boolean handleExceptionAndReturnFalse(Logger log, Throwable throwable, String method, Object... params) { handleException(log, throwable, method, params); return false; }
[ "public", "static", "boolean", "handleExceptionAndReturnFalse", "(", "Logger", "log", ",", "Throwable", "throwable", ",", "String", "method", ",", "Object", "...", "params", ")", "{", "handleException", "(", "log", ",", "throwable", ",", "method", ",", "params", ")", ";", "return", "false", ";", "}" ]
Handle exception and return false boolean. @param log the log @param throwable the throwable @param method the method @param params the params @return the boolean
[ "Handle", "exception", "and", "return", "false", "boolean", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/exception/JMExceptionManager.java#L151-L155
155,304
JM-Lab/utils-java8
src/main/java/kr/jm/utils/exception/JMExceptionManager.java
JMExceptionManager.handleExceptionAndReturn
public static <T> T handleExceptionAndReturn(Logger log, Throwable throwable, String method, Supplier<T> returnSupplier, Object... params) { handleException(log, throwable, method, params); return returnSupplier.get(); }
java
public static <T> T handleExceptionAndReturn(Logger log, Throwable throwable, String method, Supplier<T> returnSupplier, Object... params) { handleException(log, throwable, method, params); return returnSupplier.get(); }
[ "public", "static", "<", "T", ">", "T", "handleExceptionAndReturn", "(", "Logger", "log", ",", "Throwable", "throwable", ",", "String", "method", ",", "Supplier", "<", "T", ">", "returnSupplier", ",", "Object", "...", "params", ")", "{", "handleException", "(", "log", ",", "throwable", ",", "method", ",", "params", ")", ";", "return", "returnSupplier", ".", "get", "(", ")", ";", "}" ]
Handle exception and return t. @param <T> the type parameter @param log the log @param throwable the throwable @param method the method @param returnSupplier the return supplier @param params the params @return the t
[ "Handle", "exception", "and", "return", "t", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/exception/JMExceptionManager.java#L168-L173
155,305
JM-Lab/utils-java8
src/main/java/kr/jm/utils/exception/JMExceptionManager.java
JMExceptionManager.handleExceptionAndThrowRuntimeEx
public static <T> T handleExceptionAndThrowRuntimeEx(Logger log, Throwable throwable, String method, Object... params) { handleException(log, throwable, method, params); throw new RuntimeException(throwable); }
java
public static <T> T handleExceptionAndThrowRuntimeEx(Logger log, Throwable throwable, String method, Object... params) { handleException(log, throwable, method, params); throw new RuntimeException(throwable); }
[ "public", "static", "<", "T", ">", "T", "handleExceptionAndThrowRuntimeEx", "(", "Logger", "log", ",", "Throwable", "throwable", ",", "String", "method", ",", "Object", "...", "params", ")", "{", "handleException", "(", "log", ",", "throwable", ",", "method", ",", "params", ")", ";", "throw", "new", "RuntimeException", "(", "throwable", ")", ";", "}" ]
Handle exception and throw runtime ex t. @param <T> the type parameter @param log the log @param throwable the throwable @param method the method @param params the params @return the t
[ "Handle", "exception", "and", "throw", "runtime", "ex", "t", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/exception/JMExceptionManager.java#L185-L189
155,306
JM-Lab/utils-java8
src/main/java/kr/jm/utils/exception/JMExceptionManager.java
JMExceptionManager.handleExceptionAndReturnRuntimeEx
public static RuntimeException handleExceptionAndReturnRuntimeEx(Logger log, Throwable throwable, String method, Object... params) { handleException(log, throwable, method, params); return new RuntimeException(throwable); }
java
public static RuntimeException handleExceptionAndReturnRuntimeEx(Logger log, Throwable throwable, String method, Object... params) { handleException(log, throwable, method, params); return new RuntimeException(throwable); }
[ "public", "static", "RuntimeException", "handleExceptionAndReturnRuntimeEx", "(", "Logger", "log", ",", "Throwable", "throwable", ",", "String", "method", ",", "Object", "...", "params", ")", "{", "handleException", "(", "log", ",", "throwable", ",", "method", ",", "params", ")", ";", "return", "new", "RuntimeException", "(", "throwable", ")", ";", "}" ]
Handle exception and return runtime ex runtime exception. @param log the log @param throwable the throwable @param method the method @param params the params @return the runtime exception
[ "Handle", "exception", "and", "return", "runtime", "ex", "runtime", "exception", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/exception/JMExceptionManager.java#L200-L204
155,307
JM-Lab/utils-java8
src/main/java/kr/jm/utils/exception/JMExceptionManager.java
JMExceptionManager.handleExceptionAndReturnEmptyOptional
public static <T> Optional<T> handleExceptionAndReturnEmptyOptional( Logger log, Throwable throwable, String method, Object... params) { handleException(log, throwable, method, params); return Optional.empty(); }
java
public static <T> Optional<T> handleExceptionAndReturnEmptyOptional( Logger log, Throwable throwable, String method, Object... params) { handleException(log, throwable, method, params); return Optional.empty(); }
[ "public", "static", "<", "T", ">", "Optional", "<", "T", ">", "handleExceptionAndReturnEmptyOptional", "(", "Logger", "log", ",", "Throwable", "throwable", ",", "String", "method", ",", "Object", "...", "params", ")", "{", "handleException", "(", "log", ",", "throwable", ",", "method", ",", "params", ")", ";", "return", "Optional", ".", "empty", "(", ")", ";", "}" ]
Handle exception and return empty optional optional. @param <T> the type parameter @param log the log @param throwable the throwable @param method the method @param params the params @return the optional
[ "Handle", "exception", "and", "return", "empty", "optional", "optional", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/exception/JMExceptionManager.java#L216-L220
155,308
JM-Lab/utils-java8
src/main/java/kr/jm/utils/exception/JMExceptionManager.java
JMExceptionManager.logRuntimeException
public static void logRuntimeException(Logger log, String exceptionMessage, String method, Object... params) { handleException(log, newRunTimeException(exceptionMessage), method, params); }
java
public static void logRuntimeException(Logger log, String exceptionMessage, String method, Object... params) { handleException(log, newRunTimeException(exceptionMessage), method, params); }
[ "public", "static", "void", "logRuntimeException", "(", "Logger", "log", ",", "String", "exceptionMessage", ",", "String", "method", ",", "Object", "...", "params", ")", "{", "handleException", "(", "log", ",", "newRunTimeException", "(", "exceptionMessage", ")", ",", "method", ",", "params", ")", ";", "}" ]
Log runtime exception. @param log the log @param exceptionMessage the exception message @param method the method @param params the params
[ "Log", "runtime", "exception", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/exception/JMExceptionManager.java#L242-L246
155,309
JM-Lab/utils-java8
src/main/java/kr/jm/utils/JMWordSplitter.java
JMWordSplitter.splitAsStream
public static Stream<String> splitAsStream(Pattern splitPattern, String text) { return splitPattern.splitAsStream(text); }
java
public static Stream<String> splitAsStream(Pattern splitPattern, String text) { return splitPattern.splitAsStream(text); }
[ "public", "static", "Stream", "<", "String", ">", "splitAsStream", "(", "Pattern", "splitPattern", ",", "String", "text", ")", "{", "return", "splitPattern", ".", "splitAsStream", "(", "text", ")", ";", "}" ]
Split as stream stream. @param splitPattern the split pattern @param text the text @return the stream
[ "Split", "as", "stream", "stream", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/JMWordSplitter.java#L26-L29
155,310
JM-Lab/utils-java8
src/main/java/kr/jm/utils/JMWordSplitter.java
JMWordSplitter.splitAsList
public static List<String> splitAsList(Pattern splitPattern, String text) { return splitAsStream(splitPattern, text).collect(toList()); }
java
public static List<String> splitAsList(Pattern splitPattern, String text) { return splitAsStream(splitPattern, text).collect(toList()); }
[ "public", "static", "List", "<", "String", ">", "splitAsList", "(", "Pattern", "splitPattern", ",", "String", "text", ")", "{", "return", "splitAsStream", "(", "splitPattern", ",", "text", ")", ".", "collect", "(", "toList", "(", ")", ")", ";", "}" ]
Split as list list. @param splitPattern the split pattern @param text the text @return the list
[ "Split", "as", "list", "list", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/JMWordSplitter.java#L38-L40
155,311
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ResultSetUtility.java
ResultSetUtility.convertToMap
public Map<String, Object> convertToMap(ResultSet rs) throws SQLException{ return convertToMap(rs, null); }
java
public Map<String, Object> convertToMap(ResultSet rs) throws SQLException{ return convertToMap(rs, null); }
[ "public", "Map", "<", "String", ",", "Object", ">", "convertToMap", "(", "ResultSet", "rs", ")", "throws", "SQLException", "{", "return", "convertToMap", "(", "rs", ",", "null", ")", ";", "}" ]
Convert current row of the ResultSet to a Map. The keys of the Map are property names transformed from column names. @param rs the result set @return a Map representation of current row @throws SQLException
[ "Convert", "current", "row", "of", "the", "ResultSet", "to", "a", "Map", ".", "The", "keys", "of", "the", "Map", "are", "property", "names", "transformed", "from", "column", "names", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ResultSetUtility.java#L60-L62
155,312
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ResultSetUtility.java
ResultSetUtility.convertToDynamicBean
public Object convertToDynamicBean(ResultSet rs) throws SQLException{ ResultSetMetaData rsmd = rs.getMetaData(); Map<String, ColumnMetaData> columnToPropertyMappings = createColumnToPropertyMappings(rsmd); Class<?> beanClass = reuseOrBuildBeanClass(rsmd, columnToPropertyMappings); BeanProcessor beanProcessor = new BeanProcessor(simpleColumnToPropertyMappings(columnToPropertyMappings)); return beanProcessor.toBean(rs, beanClass); }
java
public Object convertToDynamicBean(ResultSet rs) throws SQLException{ ResultSetMetaData rsmd = rs.getMetaData(); Map<String, ColumnMetaData> columnToPropertyMappings = createColumnToPropertyMappings(rsmd); Class<?> beanClass = reuseOrBuildBeanClass(rsmd, columnToPropertyMappings); BeanProcessor beanProcessor = new BeanProcessor(simpleColumnToPropertyMappings(columnToPropertyMappings)); return beanProcessor.toBean(rs, beanClass); }
[ "public", "Object", "convertToDynamicBean", "(", "ResultSet", "rs", ")", "throws", "SQLException", "{", "ResultSetMetaData", "rsmd", "=", "rs", ".", "getMetaData", "(", ")", ";", "Map", "<", "String", ",", "ColumnMetaData", ">", "columnToPropertyMappings", "=", "createColumnToPropertyMappings", "(", "rsmd", ")", ";", "Class", "<", "?", ">", "beanClass", "=", "reuseOrBuildBeanClass", "(", "rsmd", ",", "columnToPropertyMappings", ")", ";", "BeanProcessor", "beanProcessor", "=", "new", "BeanProcessor", "(", "simpleColumnToPropertyMappings", "(", "columnToPropertyMappings", ")", ")", ";", "return", "beanProcessor", ".", "toBean", "(", "rs", ",", "beanClass", ")", ";", "}" ]
Convert current row of the ResultSet to a bean of a dynamically generated class. It requires CGLIB. @param rs the ResultSet @return a bean of a dynamically generated class @throws SQLException
[ "Convert", "current", "row", "of", "the", "ResultSet", "to", "a", "bean", "of", "a", "dynamically", "generated", "class", ".", "It", "requires", "CGLIB", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ResultSetUtility.java#L125-L133
155,313
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ResultSetUtility.java
ResultSetUtility.convertAllToDynamicBeans
public List<?> convertAllToDynamicBeans(ResultSet rs) throws SQLException{ ResultSetMetaData rsmd = rs.getMetaData(); Map<String, ColumnMetaData> columnToPropertyMappings = createColumnToPropertyMappings(rsmd); Class<?> beanClass = reuseOrBuildBeanClass(rsmd, columnToPropertyMappings); BeanProcessor beanProcessor = new BeanProcessor(simpleColumnToPropertyMappings(columnToPropertyMappings)); return beanProcessor.toBeanList(rs, beanClass); }
java
public List<?> convertAllToDynamicBeans(ResultSet rs) throws SQLException{ ResultSetMetaData rsmd = rs.getMetaData(); Map<String, ColumnMetaData> columnToPropertyMappings = createColumnToPropertyMappings(rsmd); Class<?> beanClass = reuseOrBuildBeanClass(rsmd, columnToPropertyMappings); BeanProcessor beanProcessor = new BeanProcessor(simpleColumnToPropertyMappings(columnToPropertyMappings)); return beanProcessor.toBeanList(rs, beanClass); }
[ "public", "List", "<", "?", ">", "convertAllToDynamicBeans", "(", "ResultSet", "rs", ")", "throws", "SQLException", "{", "ResultSetMetaData", "rsmd", "=", "rs", ".", "getMetaData", "(", ")", ";", "Map", "<", "String", ",", "ColumnMetaData", ">", "columnToPropertyMappings", "=", "createColumnToPropertyMappings", "(", "rsmd", ")", ";", "Class", "<", "?", ">", "beanClass", "=", "reuseOrBuildBeanClass", "(", "rsmd", ",", "columnToPropertyMappings", ")", ";", "BeanProcessor", "beanProcessor", "=", "new", "BeanProcessor", "(", "simpleColumnToPropertyMappings", "(", "columnToPropertyMappings", ")", ")", ";", "return", "beanProcessor", ".", "toBeanList", "(", "rs", ",", "beanClass", ")", ";", "}" ]
Convert all rows of the ResultSet to a list of beans of a dynamically generated class. It requires CGLIB. @param rs the ResultSet @return a list of beans @throws SQLException
[ "Convert", "all", "rows", "of", "the", "ResultSet", "to", "a", "list", "of", "beans", "of", "a", "dynamically", "generated", "class", ".", "It", "requires", "CGLIB", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ResultSetUtility.java#L141-L149
155,314
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ResultSetUtility.java
ResultSetUtility.simpleColumnToPropertyMappings
private Map<String, String> simpleColumnToPropertyMappings(Map<String, ColumnMetaData> cm){ Map<String, String> result = new HashMap<String, String>(cm.size()); for (Entry<String, ColumnMetaData> entry: cm.entrySet()){ result.put(entry.getKey(), entry.getValue().getPropertyName()); } return result; }
java
private Map<String, String> simpleColumnToPropertyMappings(Map<String, ColumnMetaData> cm){ Map<String, String> result = new HashMap<String, String>(cm.size()); for (Entry<String, ColumnMetaData> entry: cm.entrySet()){ result.put(entry.getKey(), entry.getValue().getPropertyName()); } return result; }
[ "private", "Map", "<", "String", ",", "String", ">", "simpleColumnToPropertyMappings", "(", "Map", "<", "String", ",", "ColumnMetaData", ">", "cm", ")", "{", "Map", "<", "String", ",", "String", ">", "result", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", "cm", ".", "size", "(", ")", ")", ";", "for", "(", "Entry", "<", "String", ",", "ColumnMetaData", ">", "entry", ":", "cm", ".", "entrySet", "(", ")", ")", "{", "result", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ".", "getPropertyName", "(", ")", ")", ";", "}", "return", "result", ";", "}" ]
Convert Map&lt;String, ColumnMetaData&gt; to Map&lt;String, String&gt; with only the propertyName in value @param cm @return
[ "Convert", "Map&lt", ";", "String", "ColumnMetaData&gt", ";", "to", "Map&lt", ";", "String", "String&gt", ";", "with", "only", "the", "propertyName", "in", "value" ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ResultSetUtility.java#L156-L162
155,315
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ResultSetUtility.java
ResultSetUtility.createColumnToPropertyMappings
public Map<String, ColumnMetaData> createColumnToPropertyMappings(final ResultSetMetaData rsmd) throws SQLException{ Map<String, ColumnMetaData> columnToPropertyMappings = ColumnMetaData.createMapByLabelOrName(rsmd); for (ColumnMetaData cm: columnToPropertyMappings.values()) { // property name String propertyName = null; propertyName = columnToPropertyOverrides.get(cm.getLabelOrName()); if (propertyName == null){ propertyName = columnNameToPropertyName(cm.getLabelOrName()); } cm.setPropertyName(propertyName); } return columnToPropertyMappings; }
java
public Map<String, ColumnMetaData> createColumnToPropertyMappings(final ResultSetMetaData rsmd) throws SQLException{ Map<String, ColumnMetaData> columnToPropertyMappings = ColumnMetaData.createMapByLabelOrName(rsmd); for (ColumnMetaData cm: columnToPropertyMappings.values()) { // property name String propertyName = null; propertyName = columnToPropertyOverrides.get(cm.getLabelOrName()); if (propertyName == null){ propertyName = columnNameToPropertyName(cm.getLabelOrName()); } cm.setPropertyName(propertyName); } return columnToPropertyMappings; }
[ "public", "Map", "<", "String", ",", "ColumnMetaData", ">", "createColumnToPropertyMappings", "(", "final", "ResultSetMetaData", "rsmd", ")", "throws", "SQLException", "{", "Map", "<", "String", ",", "ColumnMetaData", ">", "columnToPropertyMappings", "=", "ColumnMetaData", ".", "createMapByLabelOrName", "(", "rsmd", ")", ";", "for", "(", "ColumnMetaData", "cm", ":", "columnToPropertyMappings", ".", "values", "(", ")", ")", "{", "// property name\r", "String", "propertyName", "=", "null", ";", "propertyName", "=", "columnToPropertyOverrides", ".", "get", "(", "cm", ".", "getLabelOrName", "(", ")", ")", ";", "if", "(", "propertyName", "==", "null", ")", "{", "propertyName", "=", "columnNameToPropertyName", "(", "cm", ".", "getLabelOrName", "(", ")", ")", ";", "}", "cm", ".", "setPropertyName", "(", "propertyName", ")", ";", "}", "return", "columnToPropertyMappings", ";", "}" ]
To determine the final column to property mappings. @param rsmd @return the mapping that already applied overridden @throws SQLException
[ "To", "determine", "the", "final", "column", "to", "property", "mappings", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ResultSetUtility.java#L259-L273
155,316
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ResultSetUtility.java
ResultSetUtility.columnLabelOrName
public String columnLabelOrName(ResultSetMetaData rsmd, int col) throws SQLException{ String columnName = rsmd.getColumnLabel(col); if (null == columnName || 0 == columnName.length()) { columnName = rsmd.getColumnName(col); } return columnName; }
java
public String columnLabelOrName(ResultSetMetaData rsmd, int col) throws SQLException{ String columnName = rsmd.getColumnLabel(col); if (null == columnName || 0 == columnName.length()) { columnName = rsmd.getColumnName(col); } return columnName; }
[ "public", "String", "columnLabelOrName", "(", "ResultSetMetaData", "rsmd", ",", "int", "col", ")", "throws", "SQLException", "{", "String", "columnName", "=", "rsmd", ".", "getColumnLabel", "(", "col", ")", ";", "if", "(", "null", "==", "columnName", "||", "0", "==", "columnName", ".", "length", "(", ")", ")", "{", "columnName", "=", "rsmd", ".", "getColumnName", "(", "col", ")", ";", "}", "return", "columnName", ";", "}" ]
Get the label or name of a column @param rsmd @param col @return label or name of the column @throws SQLException
[ "Get", "the", "label", "or", "name", "of", "a", "column" ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ResultSetUtility.java#L309-L315
155,317
bushidowallet/bushido-java-service
bushido-wallet-service/src/main/java/com/bitcoin/blockchain/api/service/v2wallet/V2WalletServiceImpl.java
V2WalletServiceImpl.getTransactionsKeys
public Response getTransactionsKeys(String key, int account) { Response operation = new Response(); if (walletDAO.hasWallet(key)) { V2Wallet wallet = wallets.getWallet(key); if (wallet == null) { wallet = init(key); } operation.setPayload(wallet.getTransactionsKeys(account)); } else { operation.addError(new Error(3)); } return operation; }
java
public Response getTransactionsKeys(String key, int account) { Response operation = new Response(); if (walletDAO.hasWallet(key)) { V2Wallet wallet = wallets.getWallet(key); if (wallet == null) { wallet = init(key); } operation.setPayload(wallet.getTransactionsKeys(account)); } else { operation.addError(new Error(3)); } return operation; }
[ "public", "Response", "getTransactionsKeys", "(", "String", "key", ",", "int", "account", ")", "{", "Response", "operation", "=", "new", "Response", "(", ")", ";", "if", "(", "walletDAO", ".", "hasWallet", "(", "key", ")", ")", "{", "V2Wallet", "wallet", "=", "wallets", ".", "getWallet", "(", "key", ")", ";", "if", "(", "wallet", "==", "null", ")", "{", "wallet", "=", "init", "(", "key", ")", ";", "}", "operation", ".", "setPayload", "(", "wallet", ".", "getTransactionsKeys", "(", "account", ")", ")", ";", "}", "else", "{", "operation", ".", "addError", "(", "new", "Error", "(", "3", ")", ")", ";", "}", "return", "operation", ";", "}" ]
Gets public keys with transactions associated with them @param key @param account @return
[ "Gets", "public", "keys", "with", "transactions", "associated", "with", "them" ]
e1a0157527e57459b509718044d2df44084876a2
https://github.com/bushidowallet/bushido-java-service/blob/e1a0157527e57459b509718044d2df44084876a2/bushido-wallet-service/src/main/java/com/bitcoin/blockchain/api/service/v2wallet/V2WalletServiceImpl.java#L172-L184
155,318
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/refer/Referencer.java
Referencer.setReferencesForOne
public static void setReferencesForOne(IReferences references, Object component) throws ReferenceException, ConfigException { if (component instanceof IReferenceable) ((IReferenceable) component).setReferences(references); }
java
public static void setReferencesForOne(IReferences references, Object component) throws ReferenceException, ConfigException { if (component instanceof IReferenceable) ((IReferenceable) component).setReferences(references); }
[ "public", "static", "void", "setReferencesForOne", "(", "IReferences", "references", ",", "Object", "component", ")", "throws", "ReferenceException", ",", "ConfigException", "{", "if", "(", "component", "instanceof", "IReferenceable", ")", "(", "(", "IReferenceable", ")", "component", ")", ".", "setReferences", "(", "references", ")", ";", "}" ]
Sets references to specific component. To set references components must implement IReferenceable interface. If they don't the call to this method has no effect. @param references the references to be set. @param component the component to set references to. @throws ReferenceException when no references found. @throws ConfigException when configuration is wrong. @see IReferenceable
[ "Sets", "references", "to", "specific", "component", "." ]
a8a0c3e5ec58f0663c295aa855c6b3afad2af86a
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/refer/Referencer.java#L25-L30
155,319
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/io/FileUtils.java
FileUtils.buildupPropertiesBundles
private void buildupPropertiesBundles(final File file) throws IOException { File[] files = file.listFiles(); for (File f : files) { if (f.getName().endsWith("properties")) { String bundleName = f.getName().substring(0, f.getName().indexOf("properties") - 1); LOG.info("Loading: " + bundleName); ResourceBundle bundle = new PropertyResourceBundle( new FileInputStream(f)); bundles.put(bundleName, bundle); } } }
java
private void buildupPropertiesBundles(final File file) throws IOException { File[] files = file.listFiles(); for (File f : files) { if (f.getName().endsWith("properties")) { String bundleName = f.getName().substring(0, f.getName().indexOf("properties") - 1); LOG.info("Loading: " + bundleName); ResourceBundle bundle = new PropertyResourceBundle( new FileInputStream(f)); bundles.put(bundleName, bundle); } } }
[ "private", "void", "buildupPropertiesBundles", "(", "final", "File", "file", ")", "throws", "IOException", "{", "File", "[", "]", "files", "=", "file", ".", "listFiles", "(", ")", ";", "for", "(", "File", "f", ":", "files", ")", "{", "if", "(", "f", ".", "getName", "(", ")", ".", "endsWith", "(", "\"properties\"", ")", ")", "{", "String", "bundleName", "=", "f", ".", "getName", "(", ")", ".", "substring", "(", "0", ",", "f", ".", "getName", "(", ")", ".", "indexOf", "(", "\"properties\"", ")", "-", "1", ")", ";", "LOG", ".", "info", "(", "\"Loading: \"", "+", "bundleName", ")", ";", "ResourceBundle", "bundle", "=", "new", "PropertyResourceBundle", "(", "new", "FileInputStream", "(", "f", ")", ")", ";", "bundles", ".", "put", "(", "bundleName", ",", "bundle", ")", ";", "}", "}", "}" ]
Loads all properties files into a bundle cache. @param file the folder where the properties files can be found @throws IOException if something goes wrong while reading the file
[ "Loads", "all", "properties", "files", "into", "a", "bundle", "cache", "." ]
f89d91c59f686114f94624bfc55712f278005bfa
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/io/FileUtils.java#L106-L120
155,320
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/io/FileUtils.java
FileUtils.loadPropertiesBundle
public void loadPropertiesBundle(final String bundleName, final Locale locale) { LOG.info("Loading properties bundle: " + bundleName); ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale); bundles.put(bundleName, bundle); }
java
public void loadPropertiesBundle(final String bundleName, final Locale locale) { LOG.info("Loading properties bundle: " + bundleName); ResourceBundle bundle = ResourceBundle.getBundle(bundleName, locale); bundles.put(bundleName, bundle); }
[ "public", "void", "loadPropertiesBundle", "(", "final", "String", "bundleName", ",", "final", "Locale", "locale", ")", "{", "LOG", ".", "info", "(", "\"Loading properties bundle: \"", "+", "bundleName", ")", ";", "ResourceBundle", "bundle", "=", "ResourceBundle", ".", "getBundle", "(", "bundleName", ",", "locale", ")", ";", "bundles", ".", "put", "(", "bundleName", ",", "bundle", ")", ";", "}" ]
Loads a locale specific bundle. @param bundleName Name of the bundle to be loaded. This name must be fully qualified. @param locale Locale for which the resource bundle will be loaded.
[ "Loads", "a", "locale", "specific", "bundle", "." ]
f89d91c59f686114f94624bfc55712f278005bfa
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/io/FileUtils.java#L131-L136
155,321
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/io/FileUtils.java
FileUtils.loadPropertiesFromFile
public void loadPropertiesFromFile(final String propertiesFile) throws IOException { LOG.info("Loading properties from file: " + propertiesFile); File file = new File(propertiesFile); String bundleName = file.getPath().substring(0, file.getPath().indexOf("properties") - 1); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); ResourceBundle bundle = new PropertyResourceBundle(inputStream); LOG.info("Adding to bunlde: " + bundleName); bundles.put(bundleName, bundle); } finally { if (inputStream != null) { inputStream.close(); } } }
java
public void loadPropertiesFromFile(final String propertiesFile) throws IOException { LOG.info("Loading properties from file: " + propertiesFile); File file = new File(propertiesFile); String bundleName = file.getPath().substring(0, file.getPath().indexOf("properties") - 1); FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); ResourceBundle bundle = new PropertyResourceBundle(inputStream); LOG.info("Adding to bunlde: " + bundleName); bundles.put(bundleName, bundle); } finally { if (inputStream != null) { inputStream.close(); } } }
[ "public", "void", "loadPropertiesFromFile", "(", "final", "String", "propertiesFile", ")", "throws", "IOException", "{", "LOG", ".", "info", "(", "\"Loading properties from file: \"", "+", "propertiesFile", ")", ";", "File", "file", "=", "new", "File", "(", "propertiesFile", ")", ";", "String", "bundleName", "=", "file", ".", "getPath", "(", ")", ".", "substring", "(", "0", ",", "file", ".", "getPath", "(", ")", ".", "indexOf", "(", "\"properties\"", ")", "-", "1", ")", ";", "FileInputStream", "inputStream", "=", "null", ";", "try", "{", "inputStream", "=", "new", "FileInputStream", "(", "file", ")", ";", "ResourceBundle", "bundle", "=", "new", "PropertyResourceBundle", "(", "inputStream", ")", ";", "LOG", ".", "info", "(", "\"Adding to bunlde: \"", "+", "bundleName", ")", ";", "bundles", ".", "put", "(", "bundleName", ",", "bundle", ")", ";", "}", "finally", "{", "if", "(", "inputStream", "!=", "null", ")", "{", "inputStream", ".", "close", "(", ")", ";", "}", "}", "}" ]
Loads the properties from a file specified as a parameter. @param propertiesFile Path to the properties file. @throws IOException is something goes wrong while reading the file
[ "Loads", "the", "properties", "from", "a", "file", "specified", "as", "a", "parameter", "." ]
f89d91c59f686114f94624bfc55712f278005bfa
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/io/FileUtils.java#L159-L179
155,322
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/io/FileUtils.java
FileUtils.getBundle
public ResourceBundle getBundle(final String bundleName) { LOG.info("Getting bundle: " + bundleName); return bundles.get(bundleName); }
java
public ResourceBundle getBundle(final String bundleName) { LOG.info("Getting bundle: " + bundleName); return bundles.get(bundleName); }
[ "public", "ResourceBundle", "getBundle", "(", "final", "String", "bundleName", ")", "{", "LOG", ".", "info", "(", "\"Getting bundle: \"", "+", "bundleName", ")", ";", "return", "bundles", ".", "get", "(", "bundleName", ")", ";", "}" ]
Returns a single bundle from the bundles map. @param bundleName The name of the bundle to be retrieved. @return returns the specified bundle from the cache
[ "Returns", "a", "single", "bundle", "from", "the", "bundles", "map", "." ]
f89d91c59f686114f94624bfc55712f278005bfa
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/io/FileUtils.java#L188-L191
155,323
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/io/FileUtils.java
FileUtils.getNumberOfRows
public int getNumberOfRows(final String fileName, final String sheetName) throws IOException { LOG.info("Getting the number of rows from:" + fileName + " sheet: " + sheetName); Workbook workbook = getWorkbook(fileName); Sheet sheets = workbook.getSheet(sheetName); return sheets.getPhysicalNumberOfRows(); }
java
public int getNumberOfRows(final String fileName, final String sheetName) throws IOException { LOG.info("Getting the number of rows from:" + fileName + " sheet: " + sheetName); Workbook workbook = getWorkbook(fileName); Sheet sheets = workbook.getSheet(sheetName); return sheets.getPhysicalNumberOfRows(); }
[ "public", "int", "getNumberOfRows", "(", "final", "String", "fileName", ",", "final", "String", "sheetName", ")", "throws", "IOException", "{", "LOG", ".", "info", "(", "\"Getting the number of rows from:\"", "+", "fileName", "+", "\" sheet: \"", "+", "sheetName", ")", ";", "Workbook", "workbook", "=", "getWorkbook", "(", "fileName", ")", ";", "Sheet", "sheets", "=", "workbook", ".", "getSheet", "(", "sheetName", ")", ";", "return", "sheets", ".", "getPhysicalNumberOfRows", "(", ")", ";", "}" ]
Gets the number of rows populated within the supplied file and sheet name. @param fileName the name of the file @param sheetName the sheet name @return the number of rows @throws IOException if something goes wrong while reading the file
[ "Gets", "the", "number", "of", "rows", "populated", "within", "the", "supplied", "file", "and", "sheet", "name", "." ]
f89d91c59f686114f94624bfc55712f278005bfa
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/io/FileUtils.java#L490-L497
155,324
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/io/FileUtils.java
FileUtils.parseCSV
public Map<String, List<String>> parseCSV(final String headers, final String file, final String separator, final String encoding) throws IOException { LOG.info("Parsing CSVs from file: " + file + " with headers: " + headers + " separator: " + separator); Map<String, List<String>> result = new HashMap<String, List<String>>(); BufferedReader reader = null; try { String[] headersArr = headers.split(","); reader = new BufferedReader(new InputStreamReader( new FileInputStream(file), encoding)); String line = null; while ((line = reader.readLine()) != null) { String[] lines = line.split(separator); if (lines.length != headersArr.length) { throw new IOException("Too many or too little theaders!"); } for (int i = 0; i < lines.length; i++) { List<String> currentHeader = result.get(headersArr[i] .trim()); if (currentHeader == null) { currentHeader = new ArrayList<String>(); result.put(headersArr[i].trim(), currentHeader); } currentHeader.add(lines[i].trim()); } } } finally { if (reader != null) { reader.close(); } } LOG.info("Result of parsing CSV: " + result); return result; }
java
public Map<String, List<String>> parseCSV(final String headers, final String file, final String separator, final String encoding) throws IOException { LOG.info("Parsing CSVs from file: " + file + " with headers: " + headers + " separator: " + separator); Map<String, List<String>> result = new HashMap<String, List<String>>(); BufferedReader reader = null; try { String[] headersArr = headers.split(","); reader = new BufferedReader(new InputStreamReader( new FileInputStream(file), encoding)); String line = null; while ((line = reader.readLine()) != null) { String[] lines = line.split(separator); if (lines.length != headersArr.length) { throw new IOException("Too many or too little theaders!"); } for (int i = 0; i < lines.length; i++) { List<String> currentHeader = result.get(headersArr[i] .trim()); if (currentHeader == null) { currentHeader = new ArrayList<String>(); result.put(headersArr[i].trim(), currentHeader); } currentHeader.add(lines[i].trim()); } } } finally { if (reader != null) { reader.close(); } } LOG.info("Result of parsing CSV: " + result); return result; }
[ "public", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "parseCSV", "(", "final", "String", "headers", ",", "final", "String", "file", ",", "final", "String", "separator", ",", "final", "String", "encoding", ")", "throws", "IOException", "{", "LOG", ".", "info", "(", "\"Parsing CSVs from file: \"", "+", "file", "+", "\" with headers: \"", "+", "headers", "+", "\" separator: \"", "+", "separator", ")", ";", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "result", "=", "new", "HashMap", "<", "String", ",", "List", "<", "String", ">", ">", "(", ")", ";", "BufferedReader", "reader", "=", "null", ";", "try", "{", "String", "[", "]", "headersArr", "=", "headers", ".", "split", "(", "\",\"", ")", ";", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "new", "FileInputStream", "(", "file", ")", ",", "encoding", ")", ")", ";", "String", "line", "=", "null", ";", "while", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "String", "[", "]", "lines", "=", "line", ".", "split", "(", "separator", ")", ";", "if", "(", "lines", ".", "length", "!=", "headersArr", ".", "length", ")", "{", "throw", "new", "IOException", "(", "\"Too many or too little theaders!\"", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "List", "<", "String", ">", "currentHeader", "=", "result", ".", "get", "(", "headersArr", "[", "i", "]", ".", "trim", "(", ")", ")", ";", "if", "(", "currentHeader", "==", "null", ")", "{", "currentHeader", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "result", ".", "put", "(", "headersArr", "[", "i", "]", ".", "trim", "(", ")", ",", "currentHeader", ")", ";", "}", "currentHeader", ".", "add", "(", "lines", "[", "i", "]", ".", "trim", "(", ")", ")", ";", "}", "}", "}", "finally", "{", "if", "(", "reader", "!=", "null", ")", "{", "reader", ".", "close", "(", ")", ";", "}", "}", "LOG", ".", "info", "(", "\"Result of parsing CSV: \"", "+", "result", ")", ";", "return", "result", ";", "}" ]
Parses a CSV file based on the header received. @param headers a comma separated list of headers @param file the file to read from @param separator the separator used in the CSV file @param encoding the file encoding. Examples: "UTF-8", "UTF-16". @return a Map having the Headers as keys and a corresponding list for each value @throws IOException if something goes wrong while reading the file
[ "Parses", "a", "CSV", "file", "based", "on", "the", "header", "received", "." ]
f89d91c59f686114f94624bfc55712f278005bfa
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/io/FileUtils.java#L584-L626
155,325
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/io/FileUtils.java
FileUtils.getFileAsList
public List<String> getFileAsList(final String fileName, final String encoding) throws IOException { LOG.info("Get file as list. file: " + fileName); List<String> result = new ArrayList<String>(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader( new FileInputStream(fileName), encoding)); String line = null; while ((line = reader.readLine()) != null) { result.add(line); } } finally { if (reader != null) { reader.close(); } } LOG.info("Returning: " + result); return result; }
java
public List<String> getFileAsList(final String fileName, final String encoding) throws IOException { LOG.info("Get file as list. file: " + fileName); List<String> result = new ArrayList<String>(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader( new FileInputStream(fileName), encoding)); String line = null; while ((line = reader.readLine()) != null) { result.add(line); } } finally { if (reader != null) { reader.close(); } } LOG.info("Returning: " + result); return result; }
[ "public", "List", "<", "String", ">", "getFileAsList", "(", "final", "String", "fileName", ",", "final", "String", "encoding", ")", "throws", "IOException", "{", "LOG", ".", "info", "(", "\"Get file as list. file: \"", "+", "fileName", ")", ";", "List", "<", "String", ">", "result", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "BufferedReader", "reader", "=", "null", ";", "try", "{", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "new", "FileInputStream", "(", "fileName", ")", ",", "encoding", ")", ")", ";", "String", "line", "=", "null", ";", "while", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "result", ".", "add", "(", "line", ")", ";", "}", "}", "finally", "{", "if", "(", "reader", "!=", "null", ")", "{", "reader", ".", "close", "(", ")", ";", "}", "}", "LOG", ".", "info", "(", "\"Returning: \"", "+", "result", ")", ";", "return", "result", ";", "}" ]
This method returns the content of a file into a list of strings. Each file line will correspond to an element in the list. Please be careful when using this method as it is not intended to be used with large files @param fileName the name of the file @param encoding the file encoding. Examples: "UTF-8", "UTF-16". @return a list of Strings contains the lines of the file @throws IOException if something goes wrong while reading the file
[ "This", "method", "returns", "the", "content", "of", "a", "file", "into", "a", "list", "of", "strings", ".", "Each", "file", "line", "will", "correspond", "to", "an", "element", "in", "the", "list", ".", "Please", "be", "careful", "when", "using", "this", "method", "as", "it", "is", "not", "intended", "to", "be", "used", "with", "large", "files" ]
f89d91c59f686114f94624bfc55712f278005bfa
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/io/FileUtils.java#L662-L681
155,326
ludovicianul/selenium-on-steroids
src/main/java/com/insidecoding/sos/io/FileUtils.java
FileUtils.readFromFile
public List<String> readFromFile(final String filePath, final int lineToStart, final int lineToEnd, final String encoding) throws IOException { if (lineToStart > lineToEnd) { throw new IllegalArgumentException( "Line to start must be lower than line to end"); } LOG.info("Reading from file: " + filePath); List<String> result = new ArrayList<String>(); BufferedReader reader = null; int i = 0; try { reader = new BufferedReader(new InputStreamReader( new FileInputStream(filePath), encoding)); String line = reader.readLine(); while (line != null && i >= lineToStart && i <= lineToEnd) { result.add(line); i++; line = reader.readLine(); } } finally { if (reader != null) { reader.close(); } } LOG.info("Returning: " + result); return result; }
java
public List<String> readFromFile(final String filePath, final int lineToStart, final int lineToEnd, final String encoding) throws IOException { if (lineToStart > lineToEnd) { throw new IllegalArgumentException( "Line to start must be lower than line to end"); } LOG.info("Reading from file: " + filePath); List<String> result = new ArrayList<String>(); BufferedReader reader = null; int i = 0; try { reader = new BufferedReader(new InputStreamReader( new FileInputStream(filePath), encoding)); String line = reader.readLine(); while (line != null && i >= lineToStart && i <= lineToEnd) { result.add(line); i++; line = reader.readLine(); } } finally { if (reader != null) { reader.close(); } } LOG.info("Returning: " + result); return result; }
[ "public", "List", "<", "String", ">", "readFromFile", "(", "final", "String", "filePath", ",", "final", "int", "lineToStart", ",", "final", "int", "lineToEnd", ",", "final", "String", "encoding", ")", "throws", "IOException", "{", "if", "(", "lineToStart", ">", "lineToEnd", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Line to start must be lower than line to end\"", ")", ";", "}", "LOG", ".", "info", "(", "\"Reading from file: \"", "+", "filePath", ")", ";", "List", "<", "String", ">", "result", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "BufferedReader", "reader", "=", "null", ";", "int", "i", "=", "0", ";", "try", "{", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "new", "FileInputStream", "(", "filePath", ")", ",", "encoding", ")", ")", ";", "String", "line", "=", "reader", ".", "readLine", "(", ")", ";", "while", "(", "line", "!=", "null", "&&", "i", ">=", "lineToStart", "&&", "i", "<=", "lineToEnd", ")", "{", "result", ".", "add", "(", "line", ")", ";", "i", "++", ";", "line", "=", "reader", ".", "readLine", "(", ")", ";", "}", "}", "finally", "{", "if", "(", "reader", "!=", "null", ")", "{", "reader", ".", "close", "(", ")", ";", "}", "}", "LOG", ".", "info", "(", "\"Returning: \"", "+", "result", ")", ";", "return", "result", ";", "}" ]
Reads the content of the file between the specific line numbers. @param filePath the path to the file @param lineToStart the line number to start with @param lineToEnd the line number to end with @param encoding the file encoding. Examples: "UTF-8", "UTF-16". @return a list of strings for each line between {@code LineToStart} and {@code lineToEnd} @throws IOException if something goes wrong while reading the file
[ "Reads", "the", "content", "of", "the", "file", "between", "the", "specific", "line", "numbers", "." ]
f89d91c59f686114f94624bfc55712f278005bfa
https://github.com/ludovicianul/selenium-on-steroids/blob/f89d91c59f686114f94624bfc55712f278005bfa/src/main/java/com/insidecoding/sos/io/FileUtils.java#L787-L814
155,327
konvergeio/cofoja
src/main/java/com/google/java/contract/core/runtime/ContractRuntime.java
ContractRuntime.magicCast
@SuppressWarnings("unchecked") public static <T> T magicCast(Object obj, T dummy) { return (T) obj; }
java
@SuppressWarnings("unchecked") public static <T> T magicCast(Object obj, T dummy) { return (T) obj; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "magicCast", "(", "Object", "obj", ",", "T", "dummy", ")", "{", "return", "(", "T", ")", "obj", ";", "}" ]
Magically casts the first argument to the type of the second argument. <p>This method is part of the old value type inference trick. It is called at run time to cast the old value variable (first argument) to the type of an unevaluated version of the old value expression (second argument). The "unevaluation" is achieved through a constant conditional (for example, {@code true ? null : oldExpression}).
[ "Magically", "casts", "the", "first", "argument", "to", "the", "type", "of", "the", "second", "argument", "." ]
6ded58fa05eb5bf85f16353c8dd4c70bee59121a
https://github.com/konvergeio/cofoja/blob/6ded58fa05eb5bf85f16353c8dd4c70bee59121a/src/main/java/com/google/java/contract/core/runtime/ContractRuntime.java#L57-L60
155,328
grails/grails-gdoc-engine
src/main/java/org/radeox/macro/Preserved.java
Preserved.addSpecial
protected void addSpecial(String c, String replacement) { specialString += c; special.put(c, replacement); }
java
protected void addSpecial(String c, String replacement) { specialString += c; special.put(c, replacement); }
[ "protected", "void", "addSpecial", "(", "String", "c", ",", "String", "replacement", ")", "{", "specialString", "+=", "c", ";", "special", ".", "put", "(", "c", ",", "replacement", ")", ";", "}" ]
Add a replacement for the special character c which may be a string @param c the character to replace @param replacement the new string
[ "Add", "a", "replacement", "for", "the", "special", "character", "c", "which", "may", "be", "a", "string" ]
e52aa09eaa61510dc48b27603bd9ea116cd6531a
https://github.com/grails/grails-gdoc-engine/blob/e52aa09eaa61510dc48b27603bd9ea116cd6531a/src/main/java/org/radeox/macro/Preserved.java#L53-L56
155,329
grails/grails-gdoc-engine
src/main/java/org/radeox/macro/Preserved.java
Preserved.replace
protected String replace(String source) { StringBuffer tmp = new StringBuffer(); StringTokenizer stringTokenizer = new StringTokenizer(source, specialString, true); String previous = ""; while (stringTokenizer.hasMoreTokens()) { String current = stringTokenizer.nextToken(); if (special.containsKey(current) && !previous.endsWith("&")) { current = (String) special.get(current); } tmp.append(current); previous = current; } return tmp.toString(); }
java
protected String replace(String source) { StringBuffer tmp = new StringBuffer(); StringTokenizer stringTokenizer = new StringTokenizer(source, specialString, true); String previous = ""; while (stringTokenizer.hasMoreTokens()) { String current = stringTokenizer.nextToken(); if (special.containsKey(current) && !previous.endsWith("&")) { current = (String) special.get(current); } tmp.append(current); previous = current; } return tmp.toString(); }
[ "protected", "String", "replace", "(", "String", "source", ")", "{", "StringBuffer", "tmp", "=", "new", "StringBuffer", "(", ")", ";", "StringTokenizer", "stringTokenizer", "=", "new", "StringTokenizer", "(", "source", ",", "specialString", ",", "true", ")", ";", "String", "previous", "=", "\"\"", ";", "while", "(", "stringTokenizer", ".", "hasMoreTokens", "(", ")", ")", "{", "String", "current", "=", "stringTokenizer", ".", "nextToken", "(", ")", ";", "if", "(", "special", ".", "containsKey", "(", "current", ")", "&&", "!", "previous", ".", "endsWith", "(", "\"&\"", ")", ")", "{", "current", "=", "(", "String", ")", "special", ".", "get", "(", "current", ")", ";", "}", "tmp", ".", "append", "(", "current", ")", ";", "previous", "=", "current", ";", "}", "return", "tmp", ".", "toString", "(", ")", ";", "}" ]
Actually replace specials in source. This method can be used by subclassing macros. @param source String to encode @return encoded Encoded string
[ "Actually", "replace", "specials", "in", "source", ".", "This", "method", "can", "be", "used", "by", "subclassing", "macros", "." ]
e52aa09eaa61510dc48b27603bd9ea116cd6531a
https://github.com/grails/grails-gdoc-engine/blob/e52aa09eaa61510dc48b27603bd9ea116cd6531a/src/main/java/org/radeox/macro/Preserved.java#L66-L79
155,330
morimekta/utils
io-util/src/main/java/net/morimekta/util/Binary.java
Binary.copy
public static Binary copy(byte[] bytes, int off, int len) { byte[] cpy = new byte[len]; System.arraycopy(bytes, off, cpy, 0, len); return wrap(cpy); }
java
public static Binary copy(byte[] bytes, int off, int len) { byte[] cpy = new byte[len]; System.arraycopy(bytes, off, cpy, 0, len); return wrap(cpy); }
[ "public", "static", "Binary", "copy", "(", "byte", "[", "]", "bytes", ",", "int", "off", ",", "int", "len", ")", "{", "byte", "[", "]", "cpy", "=", "new", "byte", "[", "len", "]", ";", "System", ".", "arraycopy", "(", "bytes", ",", "off", ",", "cpy", ",", "0", ",", "len", ")", ";", "return", "wrap", "(", "cpy", ")", ";", "}" ]
Convenience method to copy a part of a byte array into a byte sequence. @param bytes Bytes to wrap. @param off Offset in source bytes to start reading from. @param len Number of bytes to copy. @return The wrapped byte sequence.
[ "Convenience", "method", "to", "copy", "a", "part", "of", "a", "byte", "array", "into", "a", "byte", "sequence", "." ]
dc987485902f1a7d58169c89c61db97425a6226d
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/Binary.java#L88-L92
155,331
morimekta/utils
io-util/src/main/java/net/morimekta/util/Binary.java
Binary.fromBase64
public static Binary fromBase64(String base64) { byte[] arr = Base64.decode(base64); return Binary.wrap(arr); }
java
public static Binary fromBase64(String base64) { byte[] arr = Base64.decode(base64); return Binary.wrap(arr); }
[ "public", "static", "Binary", "fromBase64", "(", "String", "base64", ")", "{", "byte", "[", "]", "arr", "=", "Base64", ".", "decode", "(", "base64", ")", ";", "return", "Binary", ".", "wrap", "(", "arr", ")", ";", "}" ]
Decode base64 string and wrap the result in a byte sequence. @param base64 The string to decode. @return The resulting sequence.
[ "Decode", "base64", "string", "and", "wrap", "the", "result", "in", "a", "byte", "sequence", "." ]
dc987485902f1a7d58169c89c61db97425a6226d
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/Binary.java#L141-L144
155,332
morimekta/utils
io-util/src/main/java/net/morimekta/util/Binary.java
Binary.fromHexString
public static Binary fromHexString(String hex) { if (hex.length() % 2 != 0) { throw new IllegalArgumentException("Illegal hex string length: " + hex.length()); } final int len = hex.length() / 2; final byte[] out = new byte[len]; for (int i = 0; i < len; ++i) { int pos = i * 2; String part = hex.substring(pos, pos + 2); out[i] = (byte) Integer.parseInt(part, 16); } return Binary.wrap(out); }
java
public static Binary fromHexString(String hex) { if (hex.length() % 2 != 0) { throw new IllegalArgumentException("Illegal hex string length: " + hex.length()); } final int len = hex.length() / 2; final byte[] out = new byte[len]; for (int i = 0; i < len; ++i) { int pos = i * 2; String part = hex.substring(pos, pos + 2); out[i] = (byte) Integer.parseInt(part, 16); } return Binary.wrap(out); }
[ "public", "static", "Binary", "fromHexString", "(", "String", "hex", ")", "{", "if", "(", "hex", ".", "length", "(", ")", "%", "2", "!=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Illegal hex string length: \"", "+", "hex", ".", "length", "(", ")", ")", ";", "}", "final", "int", "len", "=", "hex", ".", "length", "(", ")", "/", "2", ";", "final", "byte", "[", "]", "out", "=", "new", "byte", "[", "len", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "len", ";", "++", "i", ")", "{", "int", "pos", "=", "i", "*", "2", ";", "String", "part", "=", "hex", ".", "substring", "(", "pos", ",", "pos", "+", "2", ")", ";", "out", "[", "i", "]", "=", "(", "byte", ")", "Integer", ".", "parseInt", "(", "part", ",", "16", ")", ";", "}", "return", "Binary", ".", "wrap", "(", "out", ")", ";", "}" ]
Parse a hex string as bytes. @param hex The hex string. @return The corresponding bytes.
[ "Parse", "a", "hex", "string", "as", "bytes", "." ]
dc987485902f1a7d58169c89c61db97425a6226d
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/Binary.java#L208-L220
155,333
morimekta/utils
io-util/src/main/java/net/morimekta/util/Binary.java
Binary.toHexString
public String toHexString() { StringBuilder builder = new StringBuilder(); for (byte b : bytes) { builder.append(String.format("%02x", b)); } return builder.toString(); }
java
public String toHexString() { StringBuilder builder = new StringBuilder(); for (byte b : bytes) { builder.append(String.format("%02x", b)); } return builder.toString(); }
[ "public", "String", "toHexString", "(", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "byte", "b", ":", "bytes", ")", "{", "builder", ".", "append", "(", "String", ".", "format", "(", "\"%02x\"", ",", "b", ")", ")", ";", "}", "return", "builder", ".", "toString", "(", ")", ";", "}" ]
Make a hex string from a byte array. @return The hex string.
[ "Make", "a", "hex", "string", "from", "a", "byte", "array", "." ]
dc987485902f1a7d58169c89c61db97425a6226d
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/Binary.java#L227-L233
155,334
morimekta/utils
io-util/src/main/java/net/morimekta/util/Binary.java
Binary.read
public static Binary read(InputStream in, int len) throws IOException { byte[] bytes = new byte[len]; int pos = 0; while (pos < len) { int i = in.read(bytes, pos, len - pos); if (i <= 0) { throw new IOException("End of stream before complete buffer read."); } pos += i; } return wrap(bytes); }
java
public static Binary read(InputStream in, int len) throws IOException { byte[] bytes = new byte[len]; int pos = 0; while (pos < len) { int i = in.read(bytes, pos, len - pos); if (i <= 0) { throw new IOException("End of stream before complete buffer read."); } pos += i; } return wrap(bytes); }
[ "public", "static", "Binary", "read", "(", "InputStream", "in", ",", "int", "len", ")", "throws", "IOException", "{", "byte", "[", "]", "bytes", "=", "new", "byte", "[", "len", "]", ";", "int", "pos", "=", "0", ";", "while", "(", "pos", "<", "len", ")", "{", "int", "i", "=", "in", ".", "read", "(", "bytes", ",", "pos", ",", "len", "-", "pos", ")", ";", "if", "(", "i", "<=", "0", ")", "{", "throw", "new", "IOException", "(", "\"End of stream before complete buffer read.\"", ")", ";", "}", "pos", "+=", "i", ";", "}", "return", "wrap", "(", "bytes", ")", ";", "}" ]
Read a binary buffer from input stream. @param in Input stream to read. @param len Number of bytes to read. @return The read bytes. @throws IOException If unable to read completely what's expected.
[ "Read", "a", "binary", "buffer", "from", "input", "stream", "." ]
dc987485902f1a7d58169c89c61db97425a6226d
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/io-util/src/main/java/net/morimekta/util/Binary.java#L262-L273
155,335
JM-Lab/utils-java8
src/main/java/kr/jm/utils/collections/JMListMap.java
JMListMap.addAll
public boolean addAll(K key, List<V> list) { return getOrPutGetNewList(key).addAll(list); }
java
public boolean addAll(K key, List<V> list) { return getOrPutGetNewList(key).addAll(list); }
[ "public", "boolean", "addAll", "(", "K", "key", ",", "List", "<", "V", ">", "list", ")", "{", "return", "getOrPutGetNewList", "(", "key", ")", ".", "addAll", "(", "list", ")", ";", "}" ]
Add all boolean. @param key the key @param list the list @return the boolean
[ "Add", "all", "boolean", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/collections/JMListMap.java#L102-L104
155,336
JM-Lab/utils-java8
src/main/java/kr/jm/utils/collections/JMListMap.java
JMListMap.merge
public JMListMap<K, V> merge(JMListMap<K, V> jmListMap) { jmListMap.forEach(this::addAll); return this; }
java
public JMListMap<K, V> merge(JMListMap<K, V> jmListMap) { jmListMap.forEach(this::addAll); return this; }
[ "public", "JMListMap", "<", "K", ",", "V", ">", "merge", "(", "JMListMap", "<", "K", ",", "V", ">", "jmListMap", ")", "{", "jmListMap", ".", "forEach", "(", "this", "::", "addAll", ")", ";", "return", "this", ";", "}" ]
Merge jm list map. @param jmListMap the jm list map @return the jm list map
[ "Merge", "jm", "list", "map", "." ]
9e407b3f28a7990418a1e877229fa8344f4d78a5
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/collections/JMListMap.java#L112-L115
155,337
PureSolTechnologies/commons
types/src/main/java/com/puresoltechnologies/commons/types/StringUtils.java
StringUtils.wrapLinesByWords
public static String wrapLinesByWords(String text, int maxLen) { StringBuffer buffer = new StringBuffer(); int lineLength = 0; for (String token : text.split(" ")) { if (lineLength + token.length() + 1 > maxLen) { buffer.append("\n"); lineLength = 0; } else if (lineLength > 0) { buffer.append(" "); lineLength++; } buffer.append(token); lineLength += token.length(); } text = buffer.toString(); return text; }
java
public static String wrapLinesByWords(String text, int maxLen) { StringBuffer buffer = new StringBuffer(); int lineLength = 0; for (String token : text.split(" ")) { if (lineLength + token.length() + 1 > maxLen) { buffer.append("\n"); lineLength = 0; } else if (lineLength > 0) { buffer.append(" "); lineLength++; } buffer.append(token); lineLength += token.length(); } text = buffer.toString(); return text; }
[ "public", "static", "String", "wrapLinesByWords", "(", "String", "text", ",", "int", "maxLen", ")", "{", "StringBuffer", "buffer", "=", "new", "StringBuffer", "(", ")", ";", "int", "lineLength", "=", "0", ";", "for", "(", "String", "token", ":", "text", ".", "split", "(", "\" \"", ")", ")", "{", "if", "(", "lineLength", "+", "token", ".", "length", "(", ")", "+", "1", ">", "maxLen", ")", "{", "buffer", ".", "append", "(", "\"\\n\"", ")", ";", "lineLength", "=", "0", ";", "}", "else", "if", "(", "lineLength", ">", "0", ")", "{", "buffer", ".", "append", "(", "\" \"", ")", ";", "lineLength", "++", ";", "}", "buffer", ".", "append", "(", "token", ")", ";", "lineLength", "+=", "token", ".", "length", "(", ")", ";", "}", "text", "=", "buffer", ".", "toString", "(", ")", ";", "return", "text", ";", "}" ]
This methods auto breaks a long line of text into several lines by adding line breaks. @param text is the {@link String} to be broken down into several line. @param maxLen is the maximum number of characters per line. @return Returned is the original text with additional line breaks.
[ "This", "methods", "auto", "breaks", "a", "long", "line", "of", "text", "into", "several", "lines", "by", "adding", "line", "breaks", "." ]
f98c23d8841a1ff61632ff17fe7d24f99dbc1d44
https://github.com/PureSolTechnologies/commons/blob/f98c23d8841a1ff61632ff17fe7d24f99dbc1d44/types/src/main/java/com/puresoltechnologies/commons/types/StringUtils.java#L21-L37
155,338
james-hu/jabb-core
src/main/java/net/sf/jabb/util/stat/NumberGenerator.java
NumberGenerator.randomLongs
static public long[] randomLongs(long start, long end, int size){ Preconditions.checkArgument(start < end, "Start must be less than end."); Random random = new Random(); random.setSeed(System.currentTimeMillis()); long[] result = new long[size]; for (int i = 0; i < size; i ++){ long l = random.nextLong(); double d = (double)(end - start) / (Long.MAX_VALUE - Long.MIN_VALUE) * l + start; if (d <= start){ l = start; }else if (d >= end){ l = end; }else{ l = (long)d; } result[i] = l; } return result; }
java
static public long[] randomLongs(long start, long end, int size){ Preconditions.checkArgument(start < end, "Start must be less than end."); Random random = new Random(); random.setSeed(System.currentTimeMillis()); long[] result = new long[size]; for (int i = 0; i < size; i ++){ long l = random.nextLong(); double d = (double)(end - start) / (Long.MAX_VALUE - Long.MIN_VALUE) * l + start; if (d <= start){ l = start; }else if (d >= end){ l = end; }else{ l = (long)d; } result[i] = l; } return result; }
[ "static", "public", "long", "[", "]", "randomLongs", "(", "long", "start", ",", "long", "end", ",", "int", "size", ")", "{", "Preconditions", ".", "checkArgument", "(", "start", "<", "end", ",", "\"Start must be less than end.\"", ")", ";", "Random", "random", "=", "new", "Random", "(", ")", ";", "random", ".", "setSeed", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "long", "[", "]", "result", "=", "new", "long", "[", "size", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "long", "l", "=", "random", ".", "nextLong", "(", ")", ";", "double", "d", "=", "(", "double", ")", "(", "end", "-", "start", ")", "/", "(", "Long", ".", "MAX_VALUE", "-", "Long", ".", "MIN_VALUE", ")", "*", "l", "+", "start", ";", "if", "(", "d", "<=", "start", ")", "{", "l", "=", "start", ";", "}", "else", "if", "(", "d", ">=", "end", ")", "{", "l", "=", "end", ";", "}", "else", "{", "l", "=", "(", "long", ")", "d", ";", "}", "result", "[", "i", "]", "=", "l", ";", "}", "return", "result", ";", "}" ]
Generate random long values @param start the minimum value of the generated numbers, inclusive @param end the maximum value of the generated numbers, inclusive @param size number of random numbers to return. a.k.a. the size of the returned array. @return the random values in an array. The values are guaranteed to be within [start, end] range.
[ "Generate", "random", "long", "values" ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/stat/NumberGenerator.java#L27-L46
155,339
james-hu/jabb-core
src/main/java/net/sf/jabb/util/stat/NumberGenerator.java
NumberGenerator.randomIntegers
static public int[] randomIntegers(int start, int end, int size){ Preconditions.checkArgument(start < end, "Start must be less than end."); Random random = new Random(); random.setSeed(System.currentTimeMillis()); int[] result = new int[size]; for (int i = 0; i < size; i ++){ int l = random.nextInt(); double d = (double)(end - start) / (Integer.MAX_VALUE - Integer.MIN_VALUE) * l + start; if (d <= start){ l = start; }else if (d >= end){ l = end; }else{ l = (int)d; } result[i] = l; } return result; }
java
static public int[] randomIntegers(int start, int end, int size){ Preconditions.checkArgument(start < end, "Start must be less than end."); Random random = new Random(); random.setSeed(System.currentTimeMillis()); int[] result = new int[size]; for (int i = 0; i < size; i ++){ int l = random.nextInt(); double d = (double)(end - start) / (Integer.MAX_VALUE - Integer.MIN_VALUE) * l + start; if (d <= start){ l = start; }else if (d >= end){ l = end; }else{ l = (int)d; } result[i] = l; } return result; }
[ "static", "public", "int", "[", "]", "randomIntegers", "(", "int", "start", ",", "int", "end", ",", "int", "size", ")", "{", "Preconditions", ".", "checkArgument", "(", "start", "<", "end", ",", "\"Start must be less than end.\"", ")", ";", "Random", "random", "=", "new", "Random", "(", ")", ";", "random", ".", "setSeed", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "int", "[", "]", "result", "=", "new", "int", "[", "size", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "int", "l", "=", "random", ".", "nextInt", "(", ")", ";", "double", "d", "=", "(", "double", ")", "(", "end", "-", "start", ")", "/", "(", "Integer", ".", "MAX_VALUE", "-", "Integer", ".", "MIN_VALUE", ")", "*", "l", "+", "start", ";", "if", "(", "d", "<=", "start", ")", "{", "l", "=", "start", ";", "}", "else", "if", "(", "d", ">=", "end", ")", "{", "l", "=", "end", ";", "}", "else", "{", "l", "=", "(", "int", ")", "d", ";", "}", "result", "[", "i", "]", "=", "l", ";", "}", "return", "result", ";", "}" ]
Generate random int values @param start the minimum value of the generated numbers, inclusive @param end the maximum value of the generated numbers, inclusive @param size number of random numbers to return. a.k.a. the size of the returned array. @return the random values in an array. The values are guaranteed to be within [start, end] range.
[ "Generate", "random", "int", "values" ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/stat/NumberGenerator.java#L55-L74
155,340
james-hu/jabb-core
src/main/java/net/sf/jabb/util/stat/NumberGenerator.java
NumberGenerator.randomBigIntegers
static public BigInteger[] randomBigIntegers(double start, double end, int size){ Preconditions.checkArgument(start < end, "Start must be less than end."); Random random = new Random(); random.setSeed(System.currentTimeMillis()); BigInteger[] result = new BigInteger[size]; for (int i = 0; i < size; i ++){ double l = random.nextDouble(); double d = (double)(end - start) * l + start; BigInteger b = new BigDecimal(d).toBigInteger(); result[i] = b; } return result; }
java
static public BigInteger[] randomBigIntegers(double start, double end, int size){ Preconditions.checkArgument(start < end, "Start must be less than end."); Random random = new Random(); random.setSeed(System.currentTimeMillis()); BigInteger[] result = new BigInteger[size]; for (int i = 0; i < size; i ++){ double l = random.nextDouble(); double d = (double)(end - start) * l + start; BigInteger b = new BigDecimal(d).toBigInteger(); result[i] = b; } return result; }
[ "static", "public", "BigInteger", "[", "]", "randomBigIntegers", "(", "double", "start", ",", "double", "end", ",", "int", "size", ")", "{", "Preconditions", ".", "checkArgument", "(", "start", "<", "end", ",", "\"Start must be less than end.\"", ")", ";", "Random", "random", "=", "new", "Random", "(", ")", ";", "random", ".", "setSeed", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "BigInteger", "[", "]", "result", "=", "new", "BigInteger", "[", "size", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "double", "l", "=", "random", ".", "nextDouble", "(", ")", ";", "double", "d", "=", "(", "double", ")", "(", "end", "-", "start", ")", "*", "l", "+", "start", ";", "BigInteger", "b", "=", "new", "BigDecimal", "(", "d", ")", ".", "toBigInteger", "(", ")", ";", "result", "[", "i", "]", "=", "b", ";", "}", "return", "result", ";", "}" ]
Generate random BigInteger values in double range @param start the minimum value of the generated numbers, inclusive @param end the maximum value of the generated numbers, inclusive @param size number of random numbers to return. a.k.a. the size of the returned array. @return the random values in an array. The values are not guaranteed to be exactly within [start, end] range because double type can not always represent numbers exactly.
[ "Generate", "random", "BigInteger", "values", "in", "double", "range" ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/stat/NumberGenerator.java#L84-L97
155,341
bushidowallet/bushido-java-service
bushido-wallet-service/src/main/java/com/bitcoin/blockchain/api/service/v2wallet/V2Wallet.java
V2Wallet.newTransactionHandler
public void newTransactionHandler(PersistedTransaction tx, PersistedV2Key key) throws Exception { listenForUpdates(tx); tx.keyId = key.getId(); tx.walletId = this.descriptor.getKey(); tx.account = key.account; System.out.println("Incoming transaction captured in API service: " + tx.toString()); transactionDAO.create(tx); WalletChange change = new WalletChange(tx.value, getBalance(), createKey(key.account).address, tx); WalletChangeMessage out = new WalletChangeMessage(); out.setCommand(Command.BALANCE_CHANGE_RECEIVED); out.setKey(this.descriptor.key); out.setPayload(change); router.sendUpdate(this.descriptor.key, out); }
java
public void newTransactionHandler(PersistedTransaction tx, PersistedV2Key key) throws Exception { listenForUpdates(tx); tx.keyId = key.getId(); tx.walletId = this.descriptor.getKey(); tx.account = key.account; System.out.println("Incoming transaction captured in API service: " + tx.toString()); transactionDAO.create(tx); WalletChange change = new WalletChange(tx.value, getBalance(), createKey(key.account).address, tx); WalletChangeMessage out = new WalletChangeMessage(); out.setCommand(Command.BALANCE_CHANGE_RECEIVED); out.setKey(this.descriptor.key); out.setPayload(change); router.sendUpdate(this.descriptor.key, out); }
[ "public", "void", "newTransactionHandler", "(", "PersistedTransaction", "tx", ",", "PersistedV2Key", "key", ")", "throws", "Exception", "{", "listenForUpdates", "(", "tx", ")", ";", "tx", ".", "keyId", "=", "key", ".", "getId", "(", ")", ";", "tx", ".", "walletId", "=", "this", ".", "descriptor", ".", "getKey", "(", ")", ";", "tx", ".", "account", "=", "key", ".", "account", ";", "System", ".", "out", ".", "println", "(", "\"Incoming transaction captured in API service: \"", "+", "tx", ".", "toString", "(", ")", ")", ";", "transactionDAO", ".", "create", "(", "tx", ")", ";", "WalletChange", "change", "=", "new", "WalletChange", "(", "tx", ".", "value", ",", "getBalance", "(", ")", ",", "createKey", "(", "key", ".", "account", ")", ".", "address", ",", "tx", ")", ";", "WalletChangeMessage", "out", "=", "new", "WalletChangeMessage", "(", ")", ";", "out", ".", "setCommand", "(", "Command", ".", "BALANCE_CHANGE_RECEIVED", ")", ";", "out", ".", "setKey", "(", "this", ".", "descriptor", ".", "key", ")", ";", "out", ".", "setPayload", "(", "change", ")", ";", "router", ".", "sendUpdate", "(", "this", ".", "descriptor", ".", "key", ",", "out", ")", ";", "}" ]
New transaction handler, incoming funds only based on BIP32 derived key @param tx - incoming funds transaction @param key - related V2Key @throws Exception
[ "New", "transaction", "handler", "incoming", "funds", "only", "based", "on", "BIP32", "derived", "key" ]
e1a0157527e57459b509718044d2df44084876a2
https://github.com/bushidowallet/bushido-java-service/blob/e1a0157527e57459b509718044d2df44084876a2/bushido-wallet-service/src/main/java/com/bitcoin/blockchain/api/service/v2wallet/V2Wallet.java#L206-L219
155,342
bushidowallet/bushido-java-service
bushido-wallet-service/src/main/java/com/bitcoin/blockchain/api/service/v2wallet/V2Wallet.java
V2Wallet.spend
public Response spend(List<SpendDescriptor> spendings) throws Exception { final boolean checkPin = Boolean.parseBoolean(pinEnabled); final UserPin pin = pinRegistry.get(this.descriptor.owner); final V2WalletSetting seed = this.descriptor.getSetting(V2WalletSetting.PASSPHRASE); final V2WalletSetting compressed = this.descriptor.getSetting(V2WalletSetting.COMPRESSED_KEYS); final Response response = new Response(); final Map<String, TransactionOutputList> unspents = getUnspent(); final Balance balance = new Balance(unspents.get(TransactionStatus.CONFIRMED).total, unspents.get(TransactionStatus.PENDING).total); long fee = STANDARD_FEE; final long toSpend = balance.confirmed + balance.unconfirmed - fee; if (balance.confirmed + balance.unconfirmed > 0) { //Receive change on 0 account final V2Key key = createKey(0); response.setPayload(new TransactionBuilder(unspents, balance, spendings, key, V2WalletCrypto.decrypt((String) seed.value, checkPin, pin.pin, pinSalt), (Boolean) compressed.value, fee).build()); } else { response.addError(new Error(15)); } return response; }
java
public Response spend(List<SpendDescriptor> spendings) throws Exception { final boolean checkPin = Boolean.parseBoolean(pinEnabled); final UserPin pin = pinRegistry.get(this.descriptor.owner); final V2WalletSetting seed = this.descriptor.getSetting(V2WalletSetting.PASSPHRASE); final V2WalletSetting compressed = this.descriptor.getSetting(V2WalletSetting.COMPRESSED_KEYS); final Response response = new Response(); final Map<String, TransactionOutputList> unspents = getUnspent(); final Balance balance = new Balance(unspents.get(TransactionStatus.CONFIRMED).total, unspents.get(TransactionStatus.PENDING).total); long fee = STANDARD_FEE; final long toSpend = balance.confirmed + balance.unconfirmed - fee; if (balance.confirmed + balance.unconfirmed > 0) { //Receive change on 0 account final V2Key key = createKey(0); response.setPayload(new TransactionBuilder(unspents, balance, spendings, key, V2WalletCrypto.decrypt((String) seed.value, checkPin, pin.pin, pinSalt), (Boolean) compressed.value, fee).build()); } else { response.addError(new Error(15)); } return response; }
[ "public", "Response", "spend", "(", "List", "<", "SpendDescriptor", ">", "spendings", ")", "throws", "Exception", "{", "final", "boolean", "checkPin", "=", "Boolean", ".", "parseBoolean", "(", "pinEnabled", ")", ";", "final", "UserPin", "pin", "=", "pinRegistry", ".", "get", "(", "this", ".", "descriptor", ".", "owner", ")", ";", "final", "V2WalletSetting", "seed", "=", "this", ".", "descriptor", ".", "getSetting", "(", "V2WalletSetting", ".", "PASSPHRASE", ")", ";", "final", "V2WalletSetting", "compressed", "=", "this", ".", "descriptor", ".", "getSetting", "(", "V2WalletSetting", ".", "COMPRESSED_KEYS", ")", ";", "final", "Response", "response", "=", "new", "Response", "(", ")", ";", "final", "Map", "<", "String", ",", "TransactionOutputList", ">", "unspents", "=", "getUnspent", "(", ")", ";", "final", "Balance", "balance", "=", "new", "Balance", "(", "unspents", ".", "get", "(", "TransactionStatus", ".", "CONFIRMED", ")", ".", "total", ",", "unspents", ".", "get", "(", "TransactionStatus", ".", "PENDING", ")", ".", "total", ")", ";", "long", "fee", "=", "STANDARD_FEE", ";", "final", "long", "toSpend", "=", "balance", ".", "confirmed", "+", "balance", ".", "unconfirmed", "-", "fee", ";", "if", "(", "balance", ".", "confirmed", "+", "balance", ".", "unconfirmed", ">", "0", ")", "{", "//Receive change on 0 account", "final", "V2Key", "key", "=", "createKey", "(", "0", ")", ";", "response", ".", "setPayload", "(", "new", "TransactionBuilder", "(", "unspents", ",", "balance", ",", "spendings", ",", "key", ",", "V2WalletCrypto", ".", "decrypt", "(", "(", "String", ")", "seed", ".", "value", ",", "checkPin", ",", "pin", ".", "pin", ",", "pinSalt", ")", ",", "(", "Boolean", ")", "compressed", ".", "value", ",", "fee", ")", ".", "build", "(", ")", ")", ";", "}", "else", "{", "response", ".", "addError", "(", "new", "Error", "(", "15", ")", ")", ";", "}", "return", "response", ";", "}" ]
Method implementation incomplete and unused @param spendings @return @throws Exception
[ "Method", "implementation", "incomplete", "and", "unused" ]
e1a0157527e57459b509718044d2df44084876a2
https://github.com/bushidowallet/bushido-java-service/blob/e1a0157527e57459b509718044d2df44084876a2/bushido-wallet-service/src/main/java/com/bitcoin/blockchain/api/service/v2wallet/V2Wallet.java#L227-L245
155,343
G2G3Digital/substeps-framework
core/src/main/java/com/technophobia/substeps/model/ParentStep.java
ParentStep.initialiseParamValues
public void initialiseParamValues(final Step step) { final HashMap<String, String> map = new HashMap<String, String>(); final String[] paramValues = Util.getArgs(this.parent.getPattern(), step.getLine(), null); if (paramValues != null) { for (int i = 0; i < paramValues.length; i++) { map.put(this.parent.getParamNames().get(i), paramValues[i]); } } this.paramValueMap = new ExampleParameter(step.getSourceLineNumber(), map); }
java
public void initialiseParamValues(final Step step) { final HashMap<String, String> map = new HashMap<String, String>(); final String[] paramValues = Util.getArgs(this.parent.getPattern(), step.getLine(), null); if (paramValues != null) { for (int i = 0; i < paramValues.length; i++) { map.put(this.parent.getParamNames().get(i), paramValues[i]); } } this.paramValueMap = new ExampleParameter(step.getSourceLineNumber(), map); }
[ "public", "void", "initialiseParamValues", "(", "final", "Step", "step", ")", "{", "final", "HashMap", "<", "String", ",", "String", ">", "map", "=", "new", "HashMap", "<", "String", ",", "String", ">", "(", ")", ";", "final", "String", "[", "]", "paramValues", "=", "Util", ".", "getArgs", "(", "this", ".", "parent", ".", "getPattern", "(", ")", ",", "step", ".", "getLine", "(", ")", ",", "null", ")", ";", "if", "(", "paramValues", "!=", "null", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "paramValues", ".", "length", ";", "i", "++", ")", "{", "map", ".", "put", "(", "this", ".", "parent", ".", "getParamNames", "(", ")", ".", "get", "(", "i", ")", ",", "paramValues", "[", "i", "]", ")", ";", "}", "}", "this", ".", "paramValueMap", "=", "new", "ExampleParameter", "(", "step", ".", "getSourceLineNumber", "(", ")", ",", "map", ")", ";", "}" ]
only called by tests
[ "only", "called", "by", "tests" ]
c1ec6487e1673a7dae54b5e7b62a96f602cd280a
https://github.com/G2G3Digital/substeps-framework/blob/c1ec6487e1673a7dae54b5e7b62a96f602cd280a/core/src/main/java/com/technophobia/substeps/model/ParentStep.java#L74-L87
155,344
foundation-runtime/service-directory
2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/exception/ErrorCodeConfig.java
ErrorCodeConfig.getStringProperty
public static String getStringProperty(String name) { try { if (resourceBundle == null) { resourceBundle = ResourceBundle.getBundle(ERRORCODE_FILE, Locale.getDefault(), ErrorCodeConfig.class.getClassLoader()); } String tagValue = resourceBundle.getString(name); if (tagValue == null || tagValue.isEmpty()) { return DEFAULT_STRING_VALUE; } return tagValue.trim(); } catch (Exception ex) { LOGGER.error("Get exception in ErrorCodeConfig.getStringProperty, propertyName=" + name + "."); return DEFAULT_STRING_VALUE; } }
java
public static String getStringProperty(String name) { try { if (resourceBundle == null) { resourceBundle = ResourceBundle.getBundle(ERRORCODE_FILE, Locale.getDefault(), ErrorCodeConfig.class.getClassLoader()); } String tagValue = resourceBundle.getString(name); if (tagValue == null || tagValue.isEmpty()) { return DEFAULT_STRING_VALUE; } return tagValue.trim(); } catch (Exception ex) { LOGGER.error("Get exception in ErrorCodeConfig.getStringProperty, propertyName=" + name + "."); return DEFAULT_STRING_VALUE; } }
[ "public", "static", "String", "getStringProperty", "(", "String", "name", ")", "{", "try", "{", "if", "(", "resourceBundle", "==", "null", ")", "{", "resourceBundle", "=", "ResourceBundle", ".", "getBundle", "(", "ERRORCODE_FILE", ",", "Locale", ".", "getDefault", "(", ")", ",", "ErrorCodeConfig", ".", "class", ".", "getClassLoader", "(", ")", ")", ";", "}", "String", "tagValue", "=", "resourceBundle", ".", "getString", "(", "name", ")", ";", "if", "(", "tagValue", "==", "null", "||", "tagValue", ".", "isEmpty", "(", ")", ")", "{", "return", "DEFAULT_STRING_VALUE", ";", "}", "return", "tagValue", ".", "trim", "(", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "LOGGER", ".", "error", "(", "\"Get exception in ErrorCodeConfig.getStringProperty, propertyName=\"", "+", "name", "+", "\".\"", ")", ";", "return", "DEFAULT_STRING_VALUE", ";", "}", "}" ]
Get the String value by the property name. When the property name not exits, get exception, it always return the default String value DEFAULT_STRING_VALUE. @param name The property name @return The String value
[ "Get", "the", "String", "value", "by", "the", "property", "name", ".", "When", "the", "property", "name", "not", "exits", "get", "exception", "it", "always", "return", "the", "default", "String", "value", "DEFAULT_STRING_VALUE", "." ]
a7bdefe173dc99e75eff4a24e07e6407e62f2ed4
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/exception/ErrorCodeConfig.java#L58-L74
155,345
ansell/restlet-utils
src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java
FixedRedirectCookieAuthenticator.authenticated
@Override protected int authenticated(final Request request, final Response response) { try { final CookieSetting credentialsCookie = this.getCredentialsCookie(request, response); credentialsCookie.setValue(this.formatCredentials(request.getChallengeResponse())); credentialsCookie.setMaxAge(this.getMaxCookieAge()); } catch(final GeneralSecurityException e) { this.log.error("Could not format credentials cookie", e); } // log.info("calling super.authenticated"); // return super.authenticated(request, response); // Modified copy of Authenticator.authenticated if(this.log.isDebugEnabled()) { this.log.debug("The authentication succeeded for the identifer \"{}\" using the {} scheme.", request .getChallengeResponse().getIdentifier(), request.getChallengeResponse().getScheme()); } // Update the client info accordingly if(request.getClientInfo() != null) { request.getClientInfo().setAuthenticated(true); } // Clear previous challenge requests response.getChallengeRequests().clear(); // Add the roles for the authenticated subject if(this.getEnroler() != null) { this.getEnroler().enrole(request.getClientInfo()); } // Return STOP here works for login but not for subsequent requests that expect a response // return STOP; return Filter.CONTINUE; }
java
@Override protected int authenticated(final Request request, final Response response) { try { final CookieSetting credentialsCookie = this.getCredentialsCookie(request, response); credentialsCookie.setValue(this.formatCredentials(request.getChallengeResponse())); credentialsCookie.setMaxAge(this.getMaxCookieAge()); } catch(final GeneralSecurityException e) { this.log.error("Could not format credentials cookie", e); } // log.info("calling super.authenticated"); // return super.authenticated(request, response); // Modified copy of Authenticator.authenticated if(this.log.isDebugEnabled()) { this.log.debug("The authentication succeeded for the identifer \"{}\" using the {} scheme.", request .getChallengeResponse().getIdentifier(), request.getChallengeResponse().getScheme()); } // Update the client info accordingly if(request.getClientInfo() != null) { request.getClientInfo().setAuthenticated(true); } // Clear previous challenge requests response.getChallengeRequests().clear(); // Add the roles for the authenticated subject if(this.getEnroler() != null) { this.getEnroler().enrole(request.getClientInfo()); } // Return STOP here works for login but not for subsequent requests that expect a response // return STOP; return Filter.CONTINUE; }
[ "@", "Override", "protected", "int", "authenticated", "(", "final", "Request", "request", ",", "final", "Response", "response", ")", "{", "try", "{", "final", "CookieSetting", "credentialsCookie", "=", "this", ".", "getCredentialsCookie", "(", "request", ",", "response", ")", ";", "credentialsCookie", ".", "setValue", "(", "this", ".", "formatCredentials", "(", "request", ".", "getChallengeResponse", "(", ")", ")", ")", ";", "credentialsCookie", ".", "setMaxAge", "(", "this", ".", "getMaxCookieAge", "(", ")", ")", ";", "}", "catch", "(", "final", "GeneralSecurityException", "e", ")", "{", "this", ".", "log", ".", "error", "(", "\"Could not format credentials cookie\"", ",", "e", ")", ";", "}", "// log.info(\"calling super.authenticated\");", "// return super.authenticated(request, response);", "// Modified copy of Authenticator.authenticated", "if", "(", "this", ".", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "this", ".", "log", ".", "debug", "(", "\"The authentication succeeded for the identifer \\\"{}\\\" using the {} scheme.\"", ",", "request", ".", "getChallengeResponse", "(", ")", ".", "getIdentifier", "(", ")", ",", "request", ".", "getChallengeResponse", "(", ")", ".", "getScheme", "(", ")", ")", ";", "}", "// Update the client info accordingly", "if", "(", "request", ".", "getClientInfo", "(", ")", "!=", "null", ")", "{", "request", ".", "getClientInfo", "(", ")", ".", "setAuthenticated", "(", "true", ")", ";", "}", "// Clear previous challenge requests", "response", ".", "getChallengeRequests", "(", ")", ".", "clear", "(", ")", ";", "// Add the roles for the authenticated subject", "if", "(", "this", ".", "getEnroler", "(", ")", "!=", "null", ")", "{", "this", ".", "getEnroler", "(", ")", ".", "enrole", "(", "request", ".", "getClientInfo", "(", ")", ")", ";", "}", "// Return STOP here works for login but not for subsequent requests that expect a response", "// return STOP;", "return", "Filter", ".", "CONTINUE", ";", "}" ]
Sets or update the credentials cookie.
[ "Sets", "or", "update", "the", "credentials", "cookie", "." ]
6c39a3e91aa8295936af1dbfccd6ba27230c40a9
https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java#L256-L298
155,346
ansell/restlet-utils
src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java
FixedRedirectCookieAuthenticator.challenge
@Override public void challenge(final Response response, final boolean stale) { this.log.debug("Calling super.challenge"); super.challenge(response, stale); }
java
@Override public void challenge(final Response response, final boolean stale) { this.log.debug("Calling super.challenge"); super.challenge(response, stale); }
[ "@", "Override", "public", "void", "challenge", "(", "final", "Response", "response", ",", "final", "boolean", "stale", ")", "{", "this", ".", "log", ".", "debug", "(", "\"Calling super.challenge\"", ")", ";", "super", ".", "challenge", "(", "response", ",", "stale", ")", ";", "}" ]
This method should be overridden to return a login form representation.
[ "This", "method", "should", "be", "overridden", "to", "return", "a", "login", "form", "representation", "." ]
6c39a3e91aa8295936af1dbfccd6ba27230c40a9
https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java#L364-L369
155,347
ansell/restlet-utils
src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java
FixedRedirectCookieAuthenticator.formatCredentials
protected String formatCredentials(final ChallengeResponse challenge) throws GeneralSecurityException { // Data buffer final StringBuffer sb = new StringBuffer(); // Indexes buffer final StringBuffer isb = new StringBuffer(); final String timeIssued = Long.toString(System.currentTimeMillis()); int i = timeIssued.length(); sb.append(timeIssued); isb.append(i); final String identifier = challenge.getIdentifier(); sb.append('/'); sb.append(identifier); i += identifier.length() + 1; isb.append(',').append(i); sb.append('/'); sb.append(challenge.getSecret()); // Store indexes at the end of the string sb.append('/'); sb.append(isb); return Base64.encode( CryptoUtils.encrypt(this.getEncryptAlgorithm(), this.getEncryptSecretKey(), sb.toString()), false); }
java
protected String formatCredentials(final ChallengeResponse challenge) throws GeneralSecurityException { // Data buffer final StringBuffer sb = new StringBuffer(); // Indexes buffer final StringBuffer isb = new StringBuffer(); final String timeIssued = Long.toString(System.currentTimeMillis()); int i = timeIssued.length(); sb.append(timeIssued); isb.append(i); final String identifier = challenge.getIdentifier(); sb.append('/'); sb.append(identifier); i += identifier.length() + 1; isb.append(',').append(i); sb.append('/'); sb.append(challenge.getSecret()); // Store indexes at the end of the string sb.append('/'); sb.append(isb); return Base64.encode( CryptoUtils.encrypt(this.getEncryptAlgorithm(), this.getEncryptSecretKey(), sb.toString()), false); }
[ "protected", "String", "formatCredentials", "(", "final", "ChallengeResponse", "challenge", ")", "throws", "GeneralSecurityException", "{", "// Data buffer", "final", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "// Indexes buffer", "final", "StringBuffer", "isb", "=", "new", "StringBuffer", "(", ")", ";", "final", "String", "timeIssued", "=", "Long", ".", "toString", "(", "System", ".", "currentTimeMillis", "(", ")", ")", ";", "int", "i", "=", "timeIssued", ".", "length", "(", ")", ";", "sb", ".", "append", "(", "timeIssued", ")", ";", "isb", ".", "append", "(", "i", ")", ";", "final", "String", "identifier", "=", "challenge", ".", "getIdentifier", "(", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "sb", ".", "append", "(", "identifier", ")", ";", "i", "+=", "identifier", ".", "length", "(", ")", "+", "1", ";", "isb", ".", "append", "(", "'", "'", ")", ".", "append", "(", "i", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "sb", ".", "append", "(", "challenge", ".", "getSecret", "(", ")", ")", ";", "// Store indexes at the end of the string", "sb", ".", "append", "(", "'", "'", ")", ";", "sb", ".", "append", "(", "isb", ")", ";", "return", "Base64", ".", "encode", "(", "CryptoUtils", ".", "encrypt", "(", "this", ".", "getEncryptAlgorithm", "(", ")", ",", "this", ".", "getEncryptSecretKey", "(", ")", ",", "sb", ".", "toString", "(", ")", ")", ",", "false", ")", ";", "}" ]
Formats the raws credentials to store in the cookie. @param challenge The challenge response to format. @return The raw credentials. @throws GeneralSecurityException If the credentials cannot be encrypted.
[ "Formats", "the", "raws", "credentials", "to", "store", "in", "the", "cookie", "." ]
6c39a3e91aa8295936af1dbfccd6ba27230c40a9
https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java#L380-L409
155,348
ansell/restlet-utils
src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java
FixedRedirectCookieAuthenticator.getCredentialsCookie
protected CookieSetting getCredentialsCookie(final Request request, final Response response) { CookieSetting credentialsCookie = response.getCookieSettings().getFirst(this.getCookieName()); if(credentialsCookie == null) { credentialsCookie = new CookieSetting(this.getCookieName(), null); credentialsCookie.setAccessRestricted(true); // authCookie.setVersion(1); if(request.getRootRef() != null) { final String p = request.getRootRef().getPath(); credentialsCookie.setPath(p == null ? "/" : p); } else { // authCookie.setPath("/"); } response.getCookieSettings().add(credentialsCookie); } return credentialsCookie; }
java
protected CookieSetting getCredentialsCookie(final Request request, final Response response) { CookieSetting credentialsCookie = response.getCookieSettings().getFirst(this.getCookieName()); if(credentialsCookie == null) { credentialsCookie = new CookieSetting(this.getCookieName(), null); credentialsCookie.setAccessRestricted(true); // authCookie.setVersion(1); if(request.getRootRef() != null) { final String p = request.getRootRef().getPath(); credentialsCookie.setPath(p == null ? "/" : p); } else { // authCookie.setPath("/"); } response.getCookieSettings().add(credentialsCookie); } return credentialsCookie; }
[ "protected", "CookieSetting", "getCredentialsCookie", "(", "final", "Request", "request", ",", "final", "Response", "response", ")", "{", "CookieSetting", "credentialsCookie", "=", "response", ".", "getCookieSettings", "(", ")", ".", "getFirst", "(", "this", ".", "getCookieName", "(", ")", ")", ";", "if", "(", "credentialsCookie", "==", "null", ")", "{", "credentialsCookie", "=", "new", "CookieSetting", "(", "this", ".", "getCookieName", "(", ")", ",", "null", ")", ";", "credentialsCookie", ".", "setAccessRestricted", "(", "true", ")", ";", "// authCookie.setVersion(1);", "if", "(", "request", ".", "getRootRef", "(", ")", "!=", "null", ")", "{", "final", "String", "p", "=", "request", ".", "getRootRef", "(", ")", ".", "getPath", "(", ")", ";", "credentialsCookie", ".", "setPath", "(", "p", "==", "null", "?", "\"/\"", ":", "p", ")", ";", "}", "else", "{", "// authCookie.setPath(\"/\");", "}", "response", ".", "getCookieSettings", "(", ")", ".", "add", "(", "credentialsCookie", ")", ";", "}", "return", "credentialsCookie", ";", "}" ]
Returns the credentials cookie setting. It first try to find an existing cookie. If necessary, it creates a new one. @param request The current request. @param response The current response. @return The credentials cookie setting.
[ "Returns", "the", "credentials", "cookie", "setting", ".", "It", "first", "try", "to", "find", "an", "existing", "cookie", ".", "If", "necessary", "it", "creates", "a", "new", "one", "." ]
6c39a3e91aa8295936af1dbfccd6ba27230c40a9
https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java#L432-L456
155,349
ansell/restlet-utils
src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java
FixedRedirectCookieAuthenticator.isLoggingIn
protected boolean isLoggingIn(final Request request, final Response response) { return this.isInterceptingLogin() && this.getLoginPath().equals(request.getResourceRef().getRemainingPart(false, false)) && Method.POST.equals(request.getMethod()); }
java
protected boolean isLoggingIn(final Request request, final Response response) { return this.isInterceptingLogin() && this.getLoginPath().equals(request.getResourceRef().getRemainingPart(false, false)) && Method.POST.equals(request.getMethod()); }
[ "protected", "boolean", "isLoggingIn", "(", "final", "Request", "request", ",", "final", "Response", "response", ")", "{", "return", "this", ".", "isInterceptingLogin", "(", ")", "&&", "this", ".", "getLoginPath", "(", ")", ".", "equals", "(", "request", ".", "getResourceRef", "(", ")", ".", "getRemainingPart", "(", "false", ",", "false", ")", ")", "&&", "Method", ".", "POST", ".", "equals", "(", "request", ".", "getMethod", "(", ")", ")", ";", "}" ]
Indicates if the request is an attempt to log in and should be intercepted. @param request The current request. @param response The current response. @return True if the request is an attempt to log in and should be intercepted.
[ "Indicates", "if", "the", "request", "is", "an", "attempt", "to", "log", "in", "and", "should", "be", "intercepted", "." ]
6c39a3e91aa8295936af1dbfccd6ba27230c40a9
https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java#L592-L597
155,350
ansell/restlet-utils
src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java
FixedRedirectCookieAuthenticator.isLoggingOut
protected boolean isLoggingOut(final Request request, final Response response) { return this.isInterceptingLogout() && this.getLogoutPath().equals(request.getResourceRef().getRemainingPart(false, false)) && (Method.GET.equals(request.getMethod()) || Method.POST.equals(request.getMethod())); }
java
protected boolean isLoggingOut(final Request request, final Response response) { return this.isInterceptingLogout() && this.getLogoutPath().equals(request.getResourceRef().getRemainingPart(false, false)) && (Method.GET.equals(request.getMethod()) || Method.POST.equals(request.getMethod())); }
[ "protected", "boolean", "isLoggingOut", "(", "final", "Request", "request", ",", "final", "Response", "response", ")", "{", "return", "this", ".", "isInterceptingLogout", "(", ")", "&&", "this", ".", "getLogoutPath", "(", ")", ".", "equals", "(", "request", ".", "getResourceRef", "(", ")", ".", "getRemainingPart", "(", "false", ",", "false", ")", ")", "&&", "(", "Method", ".", "GET", ".", "equals", "(", "request", ".", "getMethod", "(", ")", ")", "||", "Method", ".", "POST", ".", "equals", "(", "request", ".", "getMethod", "(", ")", ")", ")", ";", "}" ]
Indicates if the request is an attempt to log out and should be intercepted. @param request The current request. @param response The current response. @return True if the request is an attempt to log out and should be intercepted.
[ "Indicates", "if", "the", "request", "is", "an", "attempt", "to", "log", "out", "and", "should", "be", "intercepted", "." ]
6c39a3e91aa8295936af1dbfccd6ba27230c40a9
https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java#L608-L613
155,351
ansell/restlet-utils
src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java
FixedRedirectCookieAuthenticator.login
protected void login(final Request request, final Response response) { // Login detected final Form form = new Form(request.getEntity()); final Parameter identifier = form.getFirst(this.getIdentifierFormName()); final Parameter secret = form.getFirst(this.getSecretFormName()); // Set credentials final ChallengeResponse cr = new ChallengeResponse(this.getScheme(), identifier != null ? identifier.getValue() : null, secret != null ? secret.getValue() : null); request.setChallengeResponse(cr); this.log.info("calling attemptRedirect after login"); // Attempt to redirect this.attemptRedirect(request, response, form); }
java
protected void login(final Request request, final Response response) { // Login detected final Form form = new Form(request.getEntity()); final Parameter identifier = form.getFirst(this.getIdentifierFormName()); final Parameter secret = form.getFirst(this.getSecretFormName()); // Set credentials final ChallengeResponse cr = new ChallengeResponse(this.getScheme(), identifier != null ? identifier.getValue() : null, secret != null ? secret.getValue() : null); request.setChallengeResponse(cr); this.log.info("calling attemptRedirect after login"); // Attempt to redirect this.attemptRedirect(request, response, form); }
[ "protected", "void", "login", "(", "final", "Request", "request", ",", "final", "Response", "response", ")", "{", "// Login detected", "final", "Form", "form", "=", "new", "Form", "(", "request", ".", "getEntity", "(", ")", ")", ";", "final", "Parameter", "identifier", "=", "form", ".", "getFirst", "(", "this", ".", "getIdentifierFormName", "(", ")", ")", ";", "final", "Parameter", "secret", "=", "form", ".", "getFirst", "(", "this", ".", "getSecretFormName", "(", ")", ")", ";", "// Set credentials", "final", "ChallengeResponse", "cr", "=", "new", "ChallengeResponse", "(", "this", ".", "getScheme", "(", ")", ",", "identifier", "!=", "null", "?", "identifier", ".", "getValue", "(", ")", ":", "null", ",", "secret", "!=", "null", "?", "secret", ".", "getValue", "(", ")", ":", "null", ")", ";", "request", ".", "setChallengeResponse", "(", "cr", ")", ";", "this", ".", "log", ".", "info", "(", "\"calling attemptRedirect after login\"", ")", ";", "// Attempt to redirect", "this", ".", "attemptRedirect", "(", "request", ",", "response", ",", "form", ")", ";", "}" ]
Processes the login request. @param request The current request. @param response The current response.
[ "Processes", "the", "login", "request", "." ]
6c39a3e91aa8295936af1dbfccd6ba27230c40a9
https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java#L623-L639
155,352
ansell/restlet-utils
src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java
FixedRedirectCookieAuthenticator.logout
protected int logout(final Request request, final Response response) { // Clears the credentials request.setChallengeResponse(null); final CookieSetting credentialsCookie = this.getCredentialsCookie(request, response); credentialsCookie.setMaxAge(0); this.log.debug("calling attemptRedirect after logout"); // Attempt to redirect this.attemptRedirect(request, response, null); return Filter.STOP; }
java
protected int logout(final Request request, final Response response) { // Clears the credentials request.setChallengeResponse(null); final CookieSetting credentialsCookie = this.getCredentialsCookie(request, response); credentialsCookie.setMaxAge(0); this.log.debug("calling attemptRedirect after logout"); // Attempt to redirect this.attemptRedirect(request, response, null); return Filter.STOP; }
[ "protected", "int", "logout", "(", "final", "Request", "request", ",", "final", "Response", "response", ")", "{", "// Clears the credentials", "request", ".", "setChallengeResponse", "(", "null", ")", ";", "final", "CookieSetting", "credentialsCookie", "=", "this", ".", "getCredentialsCookie", "(", "request", ",", "response", ")", ";", "credentialsCookie", ".", "setMaxAge", "(", "0", ")", ";", "this", ".", "log", ".", "debug", "(", "\"calling attemptRedirect after logout\"", ")", ";", "// Attempt to redirect", "this", ".", "attemptRedirect", "(", "request", ",", "response", ",", "null", ")", ";", "return", "Filter", ".", "STOP", ";", "}" ]
Processes the logout request. @param request The current request. @param response The current response. @return Return {@link Filter#STOP}.
[ "Processes", "the", "logout", "request", "." ]
6c39a3e91aa8295936af1dbfccd6ba27230c40a9
https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/FixedRedirectCookieAuthenticator.java#L650-L662
155,353
greese/dasein-cloud-cloudstack
src/main/java/org/dasein/cloud/cloudstack/CSCloud.java
CSCloud.getTextValue
static public String getTextValue(Node node) { if( node.getChildNodes().getLength() == 0 ) { return null; } return node.getFirstChild().getNodeValue(); }
java
static public String getTextValue(Node node) { if( node.getChildNodes().getLength() == 0 ) { return null; } return node.getFirstChild().getNodeValue(); }
[ "static", "public", "String", "getTextValue", "(", "Node", "node", ")", "{", "if", "(", "node", ".", "getChildNodes", "(", ")", ".", "getLength", "(", ")", "==", "0", ")", "{", "return", "null", ";", "}", "return", "node", ".", "getFirstChild", "(", ")", ".", "getNodeValue", "(", ")", ";", "}" ]
Returns the text from the given node. @param node the node to extract the value from @return the text from the node
[ "Returns", "the", "text", "from", "the", "given", "node", "." ]
d86d42abbe4f277290b2c6b5d38ced506c57fee6
https://github.com/greese/dasein-cloud-cloudstack/blob/d86d42abbe4f277290b2c6b5d38ced506c57fee6/src/main/java/org/dasein/cloud/cloudstack/CSCloud.java#L735-L740
155,354
SimiaCryptus/utilities
java-util/src/main/java/com/simiacryptus/util/binary/BitOutputStream.java
BitOutputStream.writeBoundedLong
public Bits writeBoundedLong(final long value, final long max) throws IOException { final int bits = 0 >= max ? 0 : (int) (Math .floor(Math.log(max) / Math.log(2)) + 1); if (0 < bits) { Bits toWrite = new Bits(value, bits); this.write(toWrite); return toWrite; } else { return Bits.NULL; } }
java
public Bits writeBoundedLong(final long value, final long max) throws IOException { final int bits = 0 >= max ? 0 : (int) (Math .floor(Math.log(max) / Math.log(2)) + 1); if (0 < bits) { Bits toWrite = new Bits(value, bits); this.write(toWrite); return toWrite; } else { return Bits.NULL; } }
[ "public", "Bits", "writeBoundedLong", "(", "final", "long", "value", ",", "final", "long", "max", ")", "throws", "IOException", "{", "final", "int", "bits", "=", "0", ">=", "max", "?", "0", ":", "(", "int", ")", "(", "Math", ".", "floor", "(", "Math", ".", "log", "(", "max", ")", "/", "Math", ".", "log", "(", "2", ")", ")", "+", "1", ")", ";", "if", "(", "0", "<", "bits", ")", "{", "Bits", "toWrite", "=", "new", "Bits", "(", "value", ",", "bits", ")", ";", "this", ".", "write", "(", "toWrite", ")", ";", "return", "toWrite", ";", "}", "else", "{", "return", "Bits", ".", "NULL", ";", "}", "}" ]
Write bounded long bits. @param value the value @param max the max @return the bits @throws IOException the io exception
[ "Write", "bounded", "long", "bits", "." ]
b5a5e73449aae57de7dbfca2ed7a074432c5b17e
https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/util/binary/BitOutputStream.java#L180-L192
155,355
SimiaCryptus/utilities
java-util/src/main/java/com/simiacryptus/util/binary/BitOutputStream.java
BitOutputStream.writeVarLong
public void writeVarLong(final long value) throws IOException { final int bitLength = new Bits(value).bitLength; int type = Arrays.binarySearch(varLongDepths, bitLength); if (type < 0) { type = -type - 1; } this.write(new Bits(type, 2)); this.write(new Bits(value, varLongDepths[type])); }
java
public void writeVarLong(final long value) throws IOException { final int bitLength = new Bits(value).bitLength; int type = Arrays.binarySearch(varLongDepths, bitLength); if (type < 0) { type = -type - 1; } this.write(new Bits(type, 2)); this.write(new Bits(value, varLongDepths[type])); }
[ "public", "void", "writeVarLong", "(", "final", "long", "value", ")", "throws", "IOException", "{", "final", "int", "bitLength", "=", "new", "Bits", "(", "value", ")", ".", "bitLength", ";", "int", "type", "=", "Arrays", ".", "binarySearch", "(", "varLongDepths", ",", "bitLength", ")", ";", "if", "(", "type", "<", "0", ")", "{", "type", "=", "-", "type", "-", "1", ";", "}", "this", ".", "write", "(", "new", "Bits", "(", "type", ",", "2", ")", ")", ";", "this", ".", "write", "(", "new", "Bits", "(", "value", ",", "varLongDepths", "[", "type", "]", ")", ")", ";", "}" ]
Write var long. @param value the value @throws IOException the io exception
[ "Write", "var", "long", "." ]
b5a5e73449aae57de7dbfca2ed7a074432c5b17e
https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/util/binary/BitOutputStream.java#L200-L208
155,356
SimiaCryptus/utilities
java-util/src/main/java/com/simiacryptus/util/binary/BitOutputStream.java
BitOutputStream.writeVarShort
public void writeVarShort(final short value, int optimal) throws IOException { if (value < 0) throw new IllegalArgumentException(); int[] varShortDepths = {optimal, 16}; final int bitLength = new Bits(value).bitLength; int type = Arrays.binarySearch(varShortDepths, bitLength); if (type < 0) { type = -type - 1; } this.write(new Bits(type, 1)); this.write(new Bits(value, varShortDepths[type])); }
java
public void writeVarShort(final short value, int optimal) throws IOException { if (value < 0) throw new IllegalArgumentException(); int[] varShortDepths = {optimal, 16}; final int bitLength = new Bits(value).bitLength; int type = Arrays.binarySearch(varShortDepths, bitLength); if (type < 0) { type = -type - 1; } this.write(new Bits(type, 1)); this.write(new Bits(value, varShortDepths[type])); }
[ "public", "void", "writeVarShort", "(", "final", "short", "value", ",", "int", "optimal", ")", "throws", "IOException", "{", "if", "(", "value", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", ")", ";", "int", "[", "]", "varShortDepths", "=", "{", "optimal", ",", "16", "}", ";", "final", "int", "bitLength", "=", "new", "Bits", "(", "value", ")", ".", "bitLength", ";", "int", "type", "=", "Arrays", ".", "binarySearch", "(", "varShortDepths", ",", "bitLength", ")", ";", "if", "(", "type", "<", "0", ")", "{", "type", "=", "-", "type", "-", "1", ";", "}", "this", ".", "write", "(", "new", "Bits", "(", "type", ",", "1", ")", ")", ";", "this", ".", "write", "(", "new", "Bits", "(", "value", ",", "varShortDepths", "[", "type", "]", ")", ")", ";", "}" ]
Write var short. @param value the value @param optimal the optimal @throws IOException the io exception
[ "Write", "var", "short", "." ]
b5a5e73449aae57de7dbfca2ed7a074432c5b17e
https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/util/binary/BitOutputStream.java#L227-L237
155,357
james-hu/jabb-core
src/main/java/net/sf/jabb/util/net/SocketUtility.java
SocketUtility.isServerPortFree
static public boolean isServerPortFree(int port){ ServerSocket s; try { s = new ServerSocket(port); s.close(); } catch (IOException e) { return false; } return true; }
java
static public boolean isServerPortFree(int port){ ServerSocket s; try { s = new ServerSocket(port); s.close(); } catch (IOException e) { return false; } return true; }
[ "static", "public", "boolean", "isServerPortFree", "(", "int", "port", ")", "{", "ServerSocket", "s", ";", "try", "{", "s", "=", "new", "ServerSocket", "(", "port", ")", ";", "s", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}" ]
Check whether the specified server socket port is free or not. Be aware that this method is not safe if there are so many programs trying to open server sockets. @param port the port number to be checked @return true if the port is free, or false if it is being used by other program.
[ "Check", "whether", "the", "specified", "server", "socket", "port", "is", "free", "or", "not", ".", "Be", "aware", "that", "this", "method", "is", "not", "safe", "if", "there", "are", "so", "many", "programs", "trying", "to", "open", "server", "sockets", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/net/SocketUtility.java#L60-L69
155,358
james-hu/jabb-core
src/main/java/net/sf/jabb/util/net/SocketUtility.java
SocketUtility.getFreeServerPort
static public int getFreeServerPort(int port){ int resultPort = 0; ServerSocket s; try { s = new ServerSocket(port); resultPort = s.getLocalPort(); s.close(); } catch (IOException e) { resultPort = 0; } return resultPort; }
java
static public int getFreeServerPort(int port){ int resultPort = 0; ServerSocket s; try { s = new ServerSocket(port); resultPort = s.getLocalPort(); s.close(); } catch (IOException e) { resultPort = 0; } return resultPort; }
[ "static", "public", "int", "getFreeServerPort", "(", "int", "port", ")", "{", "int", "resultPort", "=", "0", ";", "ServerSocket", "s", ";", "try", "{", "s", "=", "new", "ServerSocket", "(", "port", ")", ";", "resultPort", "=", "s", ".", "getLocalPort", "(", ")", ";", "s", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "resultPort", "=", "0", ";", "}", "return", "resultPort", ";", "}" ]
Get a free server port that can be used. A preferred port number can be specified. Be aware that this method is not safe if there are so many programs trying to open server sockets. @param port preferred port number, or zero if no preference. @return the preferred port or any other free port, or zero if any exception occurred.
[ "Get", "a", "free", "server", "port", "that", "can", "be", "used", ".", "A", "preferred", "port", "number", "can", "be", "specified", ".", "Be", "aware", "that", "this", "method", "is", "not", "safe", "if", "there", "are", "so", "many", "programs", "trying", "to", "open", "server", "sockets", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/net/SocketUtility.java#L78-L89
155,359
james-hu/jabb-core
src/main/java/net/sf/jabb/util/net/SocketUtility.java
SocketUtility.getFreeServerPort
static public int getFreeServerPort(boolean tryOthers, int... ports){ for (int port: ports){ if (isServerPortFree(port)){ return port; } } return tryOthers? getFreeServerPort() : 0; }
java
static public int getFreeServerPort(boolean tryOthers, int... ports){ for (int port: ports){ if (isServerPortFree(port)){ return port; } } return tryOthers? getFreeServerPort() : 0; }
[ "static", "public", "int", "getFreeServerPort", "(", "boolean", "tryOthers", ",", "int", "...", "ports", ")", "{", "for", "(", "int", "port", ":", "ports", ")", "{", "if", "(", "isServerPortFree", "(", "port", ")", ")", "{", "return", "port", ";", "}", "}", "return", "tryOthers", "?", "getFreeServerPort", "(", ")", ":", "0", ";", "}" ]
Get a free server port that can be used. Several preferred port numbers can be specified. @param tryOthers If all preferred ports are occupied, try other free ports or not. @param ports preferred port numbers @return A free port number, or zero if not found or exception occurred.
[ "Get", "a", "free", "server", "port", "that", "can", "be", "used", ".", "Several", "preferred", "port", "numbers", "can", "be", "specified", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/net/SocketUtility.java#L107-L114
155,360
james-hu/jabb-core
src/main/java/net/sf/jabb/util/net/SocketUtility.java
SocketUtility.getExternalIpAddress
static public String getExternalIpAddress(){ String ip = null; URL url = null; BufferedReader in = null; for (int i = 0; !isIPv4Address(ip) && i < CHECK_IP_ENDPOINTS.length; i ++, url = null, in = null){ try{ url = new URL(CHECK_IP_ENDPOINTS[i]); in = new BufferedReader(new InputStreamReader(url.openStream())); ip = in.readLine(); //you get the IP as a String }catch(Exception e){ System.err.println("Unable to find out external IP address through end point '" + CHECK_IP_ENDPOINTS[i] + "': " + e.getMessage()); if (in != null){ try{ in.close(); }catch(Exception e2){ // ignore } } } } return ip; }
java
static public String getExternalIpAddress(){ String ip = null; URL url = null; BufferedReader in = null; for (int i = 0; !isIPv4Address(ip) && i < CHECK_IP_ENDPOINTS.length; i ++, url = null, in = null){ try{ url = new URL(CHECK_IP_ENDPOINTS[i]); in = new BufferedReader(new InputStreamReader(url.openStream())); ip = in.readLine(); //you get the IP as a String }catch(Exception e){ System.err.println("Unable to find out external IP address through end point '" + CHECK_IP_ENDPOINTS[i] + "': " + e.getMessage()); if (in != null){ try{ in.close(); }catch(Exception e2){ // ignore } } } } return ip; }
[ "static", "public", "String", "getExternalIpAddress", "(", ")", "{", "String", "ip", "=", "null", ";", "URL", "url", "=", "null", ";", "BufferedReader", "in", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", "!", "isIPv4Address", "(", "ip", ")", "&&", "i", "<", "CHECK_IP_ENDPOINTS", ".", "length", ";", "i", "++", ",", "url", "=", "null", ",", "in", "=", "null", ")", "{", "try", "{", "url", "=", "new", "URL", "(", "CHECK_IP_ENDPOINTS", "[", "i", "]", ")", ";", "in", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "url", ".", "openStream", "(", ")", ")", ")", ";", "ip", "=", "in", ".", "readLine", "(", ")", ";", "//you get the IP as a String\r", "}", "catch", "(", "Exception", "e", ")", "{", "System", ".", "err", ".", "println", "(", "\"Unable to find out external IP address through end point '\"", "+", "CHECK_IP_ENDPOINTS", "[", "i", "]", "+", "\"': \"", "+", "e", ".", "getMessage", "(", ")", ")", ";", "if", "(", "in", "!=", "null", ")", "{", "try", "{", "in", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e2", ")", "{", "// ignore\r", "}", "}", "}", "}", "return", "ip", ";", "}" ]
Get external ip address that the machine is exposed to internet @return the ip address or null if unable to determin
[ "Get", "external", "ip", "address", "that", "the", "machine", "is", "exposed", "to", "internet" ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/net/SocketUtility.java#L131-L154
155,361
SimiaCryptus/utilities
java-util/src/main/java/com/simiacryptus/util/io/TeeOutputStream.java
TeeOutputStream.newInputStream
@javax.annotation.Nonnull public PipedInputStream newInputStream() throws IOException { @javax.annotation.Nonnull final com.simiacryptus.util.io.TeeOutputStream outTee = this; @javax.annotation.Nonnull final AtomicReference<Runnable> onClose = new AtomicReference<>(); @javax.annotation.Nonnull final PipedOutputStream outPipe = new PipedOutputStream(); @javax.annotation.Nonnull final PipedInputStream in = new PipedInputStream() { @Override public void close() throws IOException { outPipe.close(); super.close(); } }; outPipe.connect(in); @javax.annotation.Nonnull final OutputStream outAsync = new AsyncOutputStream(outPipe); new Thread(() -> { try { if (null != heapBuffer) { outAsync.write(heapBuffer.toByteArray()); outAsync.flush(); } outTee.branches.add(outAsync); } catch (@javax.annotation.Nonnull final IOException e) { e.printStackTrace(); } }).start(); onClose.set(() -> { outTee.branches.remove(outAsync); System.err.println("END HTTP Session"); }); return in; }
java
@javax.annotation.Nonnull public PipedInputStream newInputStream() throws IOException { @javax.annotation.Nonnull final com.simiacryptus.util.io.TeeOutputStream outTee = this; @javax.annotation.Nonnull final AtomicReference<Runnable> onClose = new AtomicReference<>(); @javax.annotation.Nonnull final PipedOutputStream outPipe = new PipedOutputStream(); @javax.annotation.Nonnull final PipedInputStream in = new PipedInputStream() { @Override public void close() throws IOException { outPipe.close(); super.close(); } }; outPipe.connect(in); @javax.annotation.Nonnull final OutputStream outAsync = new AsyncOutputStream(outPipe); new Thread(() -> { try { if (null != heapBuffer) { outAsync.write(heapBuffer.toByteArray()); outAsync.flush(); } outTee.branches.add(outAsync); } catch (@javax.annotation.Nonnull final IOException e) { e.printStackTrace(); } }).start(); onClose.set(() -> { outTee.branches.remove(outAsync); System.err.println("END HTTP Session"); }); return in; }
[ "@", "javax", ".", "annotation", ".", "Nonnull", "public", "PipedInputStream", "newInputStream", "(", ")", "throws", "IOException", "{", "@", "javax", ".", "annotation", ".", "Nonnull", "final", "com", ".", "simiacryptus", ".", "util", ".", "io", ".", "TeeOutputStream", "outTee", "=", "this", ";", "@", "javax", ".", "annotation", ".", "Nonnull", "final", "AtomicReference", "<", "Runnable", ">", "onClose", "=", "new", "AtomicReference", "<>", "(", ")", ";", "@", "javax", ".", "annotation", ".", "Nonnull", "final", "PipedOutputStream", "outPipe", "=", "new", "PipedOutputStream", "(", ")", ";", "@", "javax", ".", "annotation", ".", "Nonnull", "final", "PipedInputStream", "in", "=", "new", "PipedInputStream", "(", ")", "{", "@", "Override", "public", "void", "close", "(", ")", "throws", "IOException", "{", "outPipe", ".", "close", "(", ")", ";", "super", ".", "close", "(", ")", ";", "}", "}", ";", "outPipe", ".", "connect", "(", "in", ")", ";", "@", "javax", ".", "annotation", ".", "Nonnull", "final", "OutputStream", "outAsync", "=", "new", "AsyncOutputStream", "(", "outPipe", ")", ";", "new", "Thread", "(", "(", ")", "->", "{", "try", "{", "if", "(", "null", "!=", "heapBuffer", ")", "{", "outAsync", ".", "write", "(", "heapBuffer", ".", "toByteArray", "(", ")", ")", ";", "outAsync", ".", "flush", "(", ")", ";", "}", "outTee", ".", "branches", ".", "add", "(", "outAsync", ")", ";", "}", "catch", "(", "@", "javax", ".", "annotation", ".", "Nonnull", "final", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", ")", ".", "start", "(", ")", ";", "onClose", ".", "set", "(", "(", ")", "->", "{", "outTee", ".", "branches", ".", "remove", "(", "outAsync", ")", ";", "System", ".", "err", ".", "println", "(", "\"END HTTP Session\"", ")", ";", "}", ")", ";", "return", "in", ";", "}" ]
New input stream piped input stream. @return the piped input stream @throws IOException the io exception
[ "New", "input", "stream", "piped", "input", "stream", "." ]
b5a5e73449aae57de7dbfca2ed7a074432c5b17e
https://github.com/SimiaCryptus/utilities/blob/b5a5e73449aae57de7dbfca2ed7a074432c5b17e/java-util/src/main/java/com/simiacryptus/util/io/TeeOutputStream.java#L89-L119
155,362
greese/dasein-cloud-cloudstack
src/main/java/org/dasein/cloud/cloudstack/network/LoadBalancers.java
LoadBalancers.uploadSslCertificate
private Document uploadSslCertificate(SSLCertificateCreateOptions opts, boolean cs44hack) throws InternalException, CloudException { // TODO: add trace final List<Param> params = new ArrayList<Param>(); try { params.add(new Param("certificate", cs44hack ? URLEncoder.encode(opts.getCertificateBody(), "UTF-8") : opts.getCertificateBody())); params.add(new Param("privatekey", cs44hack ? URLEncoder.encode(opts.getPrivateKey(), "UTF-8") : opts.getPrivateKey())); if( opts.getCertificateChain() != null ) { params.add(new Param("certchain", cs44hack ? URLEncoder.encode(opts.getCertificateChain(), "UTF-8") : opts.getCertificateChain())); } } catch (UnsupportedEncodingException e) { throw new InternalException(e); } return new CSMethod(getProvider()).get(UPLOAD_SSL_CERTIFICATE, params); }
java
private Document uploadSslCertificate(SSLCertificateCreateOptions opts, boolean cs44hack) throws InternalException, CloudException { // TODO: add trace final List<Param> params = new ArrayList<Param>(); try { params.add(new Param("certificate", cs44hack ? URLEncoder.encode(opts.getCertificateBody(), "UTF-8") : opts.getCertificateBody())); params.add(new Param("privatekey", cs44hack ? URLEncoder.encode(opts.getPrivateKey(), "UTF-8") : opts.getPrivateKey())); if( opts.getCertificateChain() != null ) { params.add(new Param("certchain", cs44hack ? URLEncoder.encode(opts.getCertificateChain(), "UTF-8") : opts.getCertificateChain())); } } catch (UnsupportedEncodingException e) { throw new InternalException(e); } return new CSMethod(getProvider()).get(UPLOAD_SSL_CERTIFICATE, params); }
[ "private", "Document", "uploadSslCertificate", "(", "SSLCertificateCreateOptions", "opts", ",", "boolean", "cs44hack", ")", "throws", "InternalException", ",", "CloudException", "{", "// TODO: add trace", "final", "List", "<", "Param", ">", "params", "=", "new", "ArrayList", "<", "Param", ">", "(", ")", ";", "try", "{", "params", ".", "add", "(", "new", "Param", "(", "\"certificate\"", ",", "cs44hack", "?", "URLEncoder", ".", "encode", "(", "opts", ".", "getCertificateBody", "(", ")", ",", "\"UTF-8\"", ")", ":", "opts", ".", "getCertificateBody", "(", ")", ")", ")", ";", "params", ".", "add", "(", "new", "Param", "(", "\"privatekey\"", ",", "cs44hack", "?", "URLEncoder", ".", "encode", "(", "opts", ".", "getPrivateKey", "(", ")", ",", "\"UTF-8\"", ")", ":", "opts", ".", "getPrivateKey", "(", ")", ")", ")", ";", "if", "(", "opts", ".", "getCertificateChain", "(", ")", "!=", "null", ")", "{", "params", ".", "add", "(", "new", "Param", "(", "\"certchain\"", ",", "cs44hack", "?", "URLEncoder", ".", "encode", "(", "opts", ".", "getCertificateChain", "(", ")", ",", "\"UTF-8\"", ")", ":", "opts", ".", "getCertificateChain", "(", ")", ")", ")", ";", "}", "}", "catch", "(", "UnsupportedEncodingException", "e", ")", "{", "throw", "new", "InternalException", "(", "e", ")", ";", "}", "return", "new", "CSMethod", "(", "getProvider", "(", ")", ")", ".", "get", "(", "UPLOAD_SSL_CERTIFICATE", ",", "params", ")", ";", "}" ]
Upload SSL certificate, optionally using parameter double encoding to address CLOUDSTACK-6864 found in 4.4 @param opts @param cs44hack @return Document
[ "Upload", "SSL", "certificate", "optionally", "using", "parameter", "double", "encoding", "to", "address", "CLOUDSTACK", "-", "6864", "found", "in", "4", ".", "4" ]
d86d42abbe4f277290b2c6b5d38ced506c57fee6
https://github.com/greese/dasein-cloud-cloudstack/blob/d86d42abbe4f277290b2c6b5d38ced506c57fee6/src/main/java/org/dasein/cloud/cloudstack/network/LoadBalancers.java#L788-L804
155,363
foundation-runtime/service-directory
2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DefaultServiceDirectoryManagerFactory.java
DefaultServiceDirectoryManagerFactory.getRegistrationManager
@Override public RegistrationManager getRegistrationManager(){ if(registrationManager == null){ synchronized(this){ if(registrationManager == null){ RegistrationManagerImpl registration = new RegistrationManagerImpl(getDirectoryServiceClientManager()); registration.start(); registrationManager = registration; } } } return registrationManager; }
java
@Override public RegistrationManager getRegistrationManager(){ if(registrationManager == null){ synchronized(this){ if(registrationManager == null){ RegistrationManagerImpl registration = new RegistrationManagerImpl(getDirectoryServiceClientManager()); registration.start(); registrationManager = registration; } } } return registrationManager; }
[ "@", "Override", "public", "RegistrationManager", "getRegistrationManager", "(", ")", "{", "if", "(", "registrationManager", "==", "null", ")", "{", "synchronized", "(", "this", ")", "{", "if", "(", "registrationManager", "==", "null", ")", "{", "RegistrationManagerImpl", "registration", "=", "new", "RegistrationManagerImpl", "(", "getDirectoryServiceClientManager", "(", ")", ")", ";", "registration", ".", "start", "(", ")", ";", "registrationManager", "=", "registration", ";", "}", "}", "}", "return", "registrationManager", ";", "}" ]
Get RegistrationManager. It is thread safe in lazy initializing. @return the RegistrationManager implementation instance.
[ "Get", "RegistrationManager", "." ]
a7bdefe173dc99e75eff4a24e07e6407e62f2ed4
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/impl/DefaultServiceDirectoryManagerFactory.java#L65-L77
155,364
james-hu/jabb-core
src/main/java/net/sf/jabb/spring/profile/ActiveProfilesChooser.java
ActiveProfilesChooser.getHostname
private String getHostname(){ String hostname = null; try { // Use the OS hostname first. hostname = InetAddress.getLocalHost().getHostName().toLowerCase(); } catch (UnknownHostException e) { logger.warn("Cannot find hostname.", e); } // Override by a system property second. Sometimes set when running in a container. String hostnameOverride = System.getProperty(hostnamePropertyName); if (hostnameOverride != null && hostnameOverride.length() > 0){ hostname = hostnameOverride; logger.info("Overriden hostname '{}' defined in system property '{}' will be used to choose Spring profile", hostname, hostnamePropertyName); }else{ hostnameOverride = System.getenv(hostnamePropertyName.toUpperCase()); if (hostnameOverride != null && hostnameOverride.length() > 0){ hostname = hostnameOverride; logger.info("Overriden hostname '{}' defined in environment variable '{}' will be used to choose Spring profile", hostname, hostnamePropertyName.toUpperCase()); }else{ logger.info("The hostname '{}' will be used to choose Spring profile", hostname); } } String subHostnameOverride = System.getProperty(subHostnamePropertyName); if (subHostnameOverride != null && subHostnameOverride.length() > 0){ hostname += "/" + subHostnameOverride; logger.info("Sub-hostname defined in system property '{}' appended. The full hostname that will be used to choose Spring profile is: {}", subHostnamePropertyName, hostname); }else{ subHostnameOverride = System.getenv(subHostnamePropertyName.toUpperCase()); if (subHostnameOverride != null && subHostnameOverride.length() > 0){ hostname += "/" + subHostnameOverride; logger.info("Sub-hostname defined in environment variable '{}' appended. The full hostname that will be used to choose Spring profile is: {}", subHostnamePropertyName.toUpperCase(), hostname); } } return hostname; }
java
private String getHostname(){ String hostname = null; try { // Use the OS hostname first. hostname = InetAddress.getLocalHost().getHostName().toLowerCase(); } catch (UnknownHostException e) { logger.warn("Cannot find hostname.", e); } // Override by a system property second. Sometimes set when running in a container. String hostnameOverride = System.getProperty(hostnamePropertyName); if (hostnameOverride != null && hostnameOverride.length() > 0){ hostname = hostnameOverride; logger.info("Overriden hostname '{}' defined in system property '{}' will be used to choose Spring profile", hostname, hostnamePropertyName); }else{ hostnameOverride = System.getenv(hostnamePropertyName.toUpperCase()); if (hostnameOverride != null && hostnameOverride.length() > 0){ hostname = hostnameOverride; logger.info("Overriden hostname '{}' defined in environment variable '{}' will be used to choose Spring profile", hostname, hostnamePropertyName.toUpperCase()); }else{ logger.info("The hostname '{}' will be used to choose Spring profile", hostname); } } String subHostnameOverride = System.getProperty(subHostnamePropertyName); if (subHostnameOverride != null && subHostnameOverride.length() > 0){ hostname += "/" + subHostnameOverride; logger.info("Sub-hostname defined in system property '{}' appended. The full hostname that will be used to choose Spring profile is: {}", subHostnamePropertyName, hostname); }else{ subHostnameOverride = System.getenv(subHostnamePropertyName.toUpperCase()); if (subHostnameOverride != null && subHostnameOverride.length() > 0){ hostname += "/" + subHostnameOverride; logger.info("Sub-hostname defined in environment variable '{}' appended. The full hostname that will be used to choose Spring profile is: {}", subHostnamePropertyName.toUpperCase(), hostname); } } return hostname; }
[ "private", "String", "getHostname", "(", ")", "{", "String", "hostname", "=", "null", ";", "try", "{", "// Use the OS hostname first.", "hostname", "=", "InetAddress", ".", "getLocalHost", "(", ")", ".", "getHostName", "(", ")", ".", "toLowerCase", "(", ")", ";", "}", "catch", "(", "UnknownHostException", "e", ")", "{", "logger", ".", "warn", "(", "\"Cannot find hostname.\"", ",", "e", ")", ";", "}", "// Override by a system property second. Sometimes set when running in a container. ", "String", "hostnameOverride", "=", "System", ".", "getProperty", "(", "hostnamePropertyName", ")", ";", "if", "(", "hostnameOverride", "!=", "null", "&&", "hostnameOverride", ".", "length", "(", ")", ">", "0", ")", "{", "hostname", "=", "hostnameOverride", ";", "logger", ".", "info", "(", "\"Overriden hostname '{}' defined in system property '{}' will be used to choose Spring profile\"", ",", "hostname", ",", "hostnamePropertyName", ")", ";", "}", "else", "{", "hostnameOverride", "=", "System", ".", "getenv", "(", "hostnamePropertyName", ".", "toUpperCase", "(", ")", ")", ";", "if", "(", "hostnameOverride", "!=", "null", "&&", "hostnameOverride", ".", "length", "(", ")", ">", "0", ")", "{", "hostname", "=", "hostnameOverride", ";", "logger", ".", "info", "(", "\"Overriden hostname '{}' defined in environment variable '{}' will be used to choose Spring profile\"", ",", "hostname", ",", "hostnamePropertyName", ".", "toUpperCase", "(", ")", ")", ";", "}", "else", "{", "logger", ".", "info", "(", "\"The hostname '{}' will be used to choose Spring profile\"", ",", "hostname", ")", ";", "}", "}", "String", "subHostnameOverride", "=", "System", ".", "getProperty", "(", "subHostnamePropertyName", ")", ";", "if", "(", "subHostnameOverride", "!=", "null", "&&", "subHostnameOverride", ".", "length", "(", ")", ">", "0", ")", "{", "hostname", "+=", "\"/\"", "+", "subHostnameOverride", ";", "logger", ".", "info", "(", "\"Sub-hostname defined in system property '{}' appended. The full hostname that will be used to choose Spring profile is: {}\"", ",", "subHostnamePropertyName", ",", "hostname", ")", ";", "}", "else", "{", "subHostnameOverride", "=", "System", ".", "getenv", "(", "subHostnamePropertyName", ".", "toUpperCase", "(", ")", ")", ";", "if", "(", "subHostnameOverride", "!=", "null", "&&", "subHostnameOverride", ".", "length", "(", ")", ">", "0", ")", "{", "hostname", "+=", "\"/\"", "+", "subHostnameOverride", ";", "logger", ".", "info", "(", "\"Sub-hostname defined in environment variable '{}' appended. The full hostname that will be used to choose Spring profile is: {}\"", ",", "subHostnamePropertyName", ".", "toUpperCase", "(", ")", ",", "hostname", ")", ";", "}", "}", "return", "hostname", ";", "}" ]
Get the final host name that will be used to choose the active profiles. @return the (overridden) host name or the (overriden) host name + / + the (overriden) sub host name
[ "Get", "the", "final", "host", "name", "that", "will", "be", "used", "to", "choose", "the", "active", "profiles", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/spring/profile/ActiveProfilesChooser.java#L64-L100
155,365
james-hu/jabb-core
src/main/java/net/sf/jabb/spring/profile/ActiveProfilesChooser.java
ActiveProfilesChooser.loadConfiguration
private List<StringKeyValueBean> loadConfiguration(){ List<StringKeyValueBean> result = new LinkedList<StringKeyValueBean>(); Resource resource = null; if (primaryConfigFileLocation == null){ return result; // fail silently because we must be in test }else{ resource = new ClassPathResource(primaryConfigFileLocation); if (!resource.exists()){ if (secondaryConfigFileLocation == null){ return result; // fail silently because we must be in test } resource = new ClassPathResource(secondaryConfigFileLocation); } } Properties properties = null; try { properties = PropertiesLoaderUtils.loadProperties(resource); // sort them, make the more specific ones at the top, and "*"/".*" at the bottom List<StringKeyValueBean> sorted = new ArrayList<StringKeyValueBean>(properties.size()); for (Entry<Object, Object> entry: properties.entrySet()){ sorted.add(new StringKeyValueBean(entry.getKey().toString(), entry.getValue().toString())); } Collections.sort(sorted, new Comparator<StringKeyValueBean>(){ @Override public int compare(StringKeyValueBean b0, StringKeyValueBean b1) { if (b0.getKey().equals(b1.getKey())){ return 0; } if ("*".equals(b0.getKey()) || ".*".equals(b0.getKey())){ return 1; }else if ("*".equals(b1.getKey()) || ".*".equals(b1.getKey())){ return -1; } return b1.getKey().compareTo(b0.getKey()); } }); result.addAll(sorted); } catch (Exception e) { logger.warn("Cannot load environments configuration file from class path: " + (resource == null ? "<null>" : resource.getDescription()), e); } return result; }
java
private List<StringKeyValueBean> loadConfiguration(){ List<StringKeyValueBean> result = new LinkedList<StringKeyValueBean>(); Resource resource = null; if (primaryConfigFileLocation == null){ return result; // fail silently because we must be in test }else{ resource = new ClassPathResource(primaryConfigFileLocation); if (!resource.exists()){ if (secondaryConfigFileLocation == null){ return result; // fail silently because we must be in test } resource = new ClassPathResource(secondaryConfigFileLocation); } } Properties properties = null; try { properties = PropertiesLoaderUtils.loadProperties(resource); // sort them, make the more specific ones at the top, and "*"/".*" at the bottom List<StringKeyValueBean> sorted = new ArrayList<StringKeyValueBean>(properties.size()); for (Entry<Object, Object> entry: properties.entrySet()){ sorted.add(new StringKeyValueBean(entry.getKey().toString(), entry.getValue().toString())); } Collections.sort(sorted, new Comparator<StringKeyValueBean>(){ @Override public int compare(StringKeyValueBean b0, StringKeyValueBean b1) { if (b0.getKey().equals(b1.getKey())){ return 0; } if ("*".equals(b0.getKey()) || ".*".equals(b0.getKey())){ return 1; }else if ("*".equals(b1.getKey()) || ".*".equals(b1.getKey())){ return -1; } return b1.getKey().compareTo(b0.getKey()); } }); result.addAll(sorted); } catch (Exception e) { logger.warn("Cannot load environments configuration file from class path: " + (resource == null ? "<null>" : resource.getDescription()), e); } return result; }
[ "private", "List", "<", "StringKeyValueBean", ">", "loadConfiguration", "(", ")", "{", "List", "<", "StringKeyValueBean", ">", "result", "=", "new", "LinkedList", "<", "StringKeyValueBean", ">", "(", ")", ";", "Resource", "resource", "=", "null", ";", "if", "(", "primaryConfigFileLocation", "==", "null", ")", "{", "return", "result", ";", "// fail silently because we must be in test", "}", "else", "{", "resource", "=", "new", "ClassPathResource", "(", "primaryConfigFileLocation", ")", ";", "if", "(", "!", "resource", ".", "exists", "(", ")", ")", "{", "if", "(", "secondaryConfigFileLocation", "==", "null", ")", "{", "return", "result", ";", "// fail silently because we must be in test", "}", "resource", "=", "new", "ClassPathResource", "(", "secondaryConfigFileLocation", ")", ";", "}", "}", "Properties", "properties", "=", "null", ";", "try", "{", "properties", "=", "PropertiesLoaderUtils", ".", "loadProperties", "(", "resource", ")", ";", "// sort them, make the more specific ones at the top, and \"*\"/\".*\" at the bottom", "List", "<", "StringKeyValueBean", ">", "sorted", "=", "new", "ArrayList", "<", "StringKeyValueBean", ">", "(", "properties", ".", "size", "(", ")", ")", ";", "for", "(", "Entry", "<", "Object", ",", "Object", ">", "entry", ":", "properties", ".", "entrySet", "(", ")", ")", "{", "sorted", ".", "add", "(", "new", "StringKeyValueBean", "(", "entry", ".", "getKey", "(", ")", ".", "toString", "(", ")", ",", "entry", ".", "getValue", "(", ")", ".", "toString", "(", ")", ")", ")", ";", "}", "Collections", ".", "sort", "(", "sorted", ",", "new", "Comparator", "<", "StringKeyValueBean", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "StringKeyValueBean", "b0", ",", "StringKeyValueBean", "b1", ")", "{", "if", "(", "b0", ".", "getKey", "(", ")", ".", "equals", "(", "b1", ".", "getKey", "(", ")", ")", ")", "{", "return", "0", ";", "}", "if", "(", "\"*\"", ".", "equals", "(", "b0", ".", "getKey", "(", ")", ")", "||", "\".*\"", ".", "equals", "(", "b0", ".", "getKey", "(", ")", ")", ")", "{", "return", "1", ";", "}", "else", "if", "(", "\"*\"", ".", "equals", "(", "b1", ".", "getKey", "(", ")", ")", "||", "\".*\"", ".", "equals", "(", "b1", ".", "getKey", "(", ")", ")", ")", "{", "return", "-", "1", ";", "}", "return", "b1", ".", "getKey", "(", ")", ".", "compareTo", "(", "b0", ".", "getKey", "(", ")", ")", ";", "}", "}", ")", ";", "result", ".", "addAll", "(", "sorted", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "logger", ".", "warn", "(", "\"Cannot load environments configuration file from class path: \"", "+", "(", "resource", "==", "null", "?", "\"<null>\"", ":", "resource", ".", "getDescription", "(", ")", ")", ",", "e", ")", ";", "}", "return", "result", ";", "}" ]
Load hostname - profiles mapping configuration @return the configuration with all-matching wild card at the bottom.
[ "Load", "hostname", "-", "profiles", "mapping", "configuration" ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/spring/profile/ActiveProfilesChooser.java#L106-L151
155,366
james-hu/jabb-core
src/main/java/net/sf/jabb/spring/profile/ActiveProfilesChooser.java
ActiveProfilesChooser.getActiveProfiles
public String[] getActiveProfiles(){ String hostname = getHostname(); List<StringKeyValueBean> config = loadConfiguration(); for (StringKeyValueBean entry: config){ String pattern = entry.getKey(); if ("*".equals(pattern) || !(pattern.contains("\\.") || pattern.contains(".+") || pattern.contains(".*") || StringUtils.containsAny(pattern, '[', '^', '$', '(', '|'))){ // it is not regular expression but with widecards String widecard = pattern; pattern = widecard.replace(".", "\\.") .replace("?", ".") .replace("*", ".*"); if (!pattern.contains("/")){ pattern += "/?.*"; } logger.debug("Widecard '" + widecard + "' converted to regular expression: '" + pattern + "'."); }else{ if (!pattern.contains("/")){ pattern += "/?.*"; } logger.debug("Regular expression: '" + pattern + "'."); } if (Pattern.matches(pattern, hostname)){ String profiles = (String) entry.getValue(); logger.debug("Hostname '" + hostname + "' matched by '" + pattern + "'"); return profiles.split("[ ,\t]+"); } } // matching not found logger.warn("No matching profiles can be found for '" + hostname + "', a profile derived from hostname will be activated."); String firstPart = StringUtils.substringBefore(hostname, "."); String profile = firstPart.replaceAll("[0-9-]+$", ""); return new String[]{profile}; }
java
public String[] getActiveProfiles(){ String hostname = getHostname(); List<StringKeyValueBean> config = loadConfiguration(); for (StringKeyValueBean entry: config){ String pattern = entry.getKey(); if ("*".equals(pattern) || !(pattern.contains("\\.") || pattern.contains(".+") || pattern.contains(".*") || StringUtils.containsAny(pattern, '[', '^', '$', '(', '|'))){ // it is not regular expression but with widecards String widecard = pattern; pattern = widecard.replace(".", "\\.") .replace("?", ".") .replace("*", ".*"); if (!pattern.contains("/")){ pattern += "/?.*"; } logger.debug("Widecard '" + widecard + "' converted to regular expression: '" + pattern + "'."); }else{ if (!pattern.contains("/")){ pattern += "/?.*"; } logger.debug("Regular expression: '" + pattern + "'."); } if (Pattern.matches(pattern, hostname)){ String profiles = (String) entry.getValue(); logger.debug("Hostname '" + hostname + "' matched by '" + pattern + "'"); return profiles.split("[ ,\t]+"); } } // matching not found logger.warn("No matching profiles can be found for '" + hostname + "', a profile derived from hostname will be activated."); String firstPart = StringUtils.substringBefore(hostname, "."); String profile = firstPart.replaceAll("[0-9-]+$", ""); return new String[]{profile}; }
[ "public", "String", "[", "]", "getActiveProfiles", "(", ")", "{", "String", "hostname", "=", "getHostname", "(", ")", ";", "List", "<", "StringKeyValueBean", ">", "config", "=", "loadConfiguration", "(", ")", ";", "for", "(", "StringKeyValueBean", "entry", ":", "config", ")", "{", "String", "pattern", "=", "entry", ".", "getKey", "(", ")", ";", "if", "(", "\"*\"", ".", "equals", "(", "pattern", ")", "||", "!", "(", "pattern", ".", "contains", "(", "\"\\\\.\"", ")", "||", "pattern", ".", "contains", "(", "\".+\"", ")", "||", "pattern", ".", "contains", "(", "\".*\"", ")", "||", "StringUtils", ".", "containsAny", "(", "pattern", ",", "'", "'", ",", "'", "'", ",", "'", "'", ",", "'", "'", ",", "'", "'", ")", ")", ")", "{", "// it is not regular expression but with widecards", "String", "widecard", "=", "pattern", ";", "pattern", "=", "widecard", ".", "replace", "(", "\".\"", ",", "\"\\\\.\"", ")", ".", "replace", "(", "\"?\"", ",", "\".\"", ")", ".", "replace", "(", "\"*\"", ",", "\".*\"", ")", ";", "if", "(", "!", "pattern", ".", "contains", "(", "\"/\"", ")", ")", "{", "pattern", "+=", "\"/?.*\"", ";", "}", "logger", ".", "debug", "(", "\"Widecard '\"", "+", "widecard", "+", "\"' converted to regular expression: '\"", "+", "pattern", "+", "\"'.\"", ")", ";", "}", "else", "{", "if", "(", "!", "pattern", ".", "contains", "(", "\"/\"", ")", ")", "{", "pattern", "+=", "\"/?.*\"", ";", "}", "logger", ".", "debug", "(", "\"Regular expression: '\"", "+", "pattern", "+", "\"'.\"", ")", ";", "}", "if", "(", "Pattern", ".", "matches", "(", "pattern", ",", "hostname", ")", ")", "{", "String", "profiles", "=", "(", "String", ")", "entry", ".", "getValue", "(", ")", ";", "logger", ".", "debug", "(", "\"Hostname '\"", "+", "hostname", "+", "\"' matched by '\"", "+", "pattern", "+", "\"'\"", ")", ";", "return", "profiles", ".", "split", "(", "\"[ ,\\t]+\"", ")", ";", "}", "}", "// matching not found", "logger", ".", "warn", "(", "\"No matching profiles can be found for '\"", "+", "hostname", "+", "\"', a profile derived from hostname will be activated.\"", ")", ";", "String", "firstPart", "=", "StringUtils", ".", "substringBefore", "(", "hostname", ",", "\".\"", ")", ";", "String", "profile", "=", "firstPart", ".", "replaceAll", "(", "\"[0-9-]+$\"", ",", "\"\"", ")", ";", "return", "new", "String", "[", "]", "{", "profile", "}", ";", "}" ]
Get active profiles according to all the factors. @return the active profiles
[ "Get", "active", "profiles", "according", "to", "all", "the", "factors", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/spring/profile/ActiveProfilesChooser.java#L157-L190
155,367
app55/app55-java
src/support/java/com/googlecode/openbeans/Beans.java
Beans.instantiate
public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext) throws IOException, ClassNotFoundException { return internalInstantiate(cls, beanName, beanContext, null); }
java
public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext) throws IOException, ClassNotFoundException { return internalInstantiate(cls, beanName, beanContext, null); }
[ "public", "static", "Object", "instantiate", "(", "ClassLoader", "cls", ",", "String", "beanName", ",", "BeanContext", "beanContext", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "return", "internalInstantiate", "(", "cls", ",", "beanName", ",", "beanContext", ",", "null", ")", ";", "}" ]
Obtains an instance of a JavaBean specified the bean name using the specified class loader, and adds the instance into the specified bean context. <p> If the specified class loader is null, the system class loader is used. </p> @param cls the specified class loader. It can be null. @param beanName the name of the JavaBean @param beanContext the beancontext in which the bean instance will be added. @return an instance of the specified JavaBean. @throws IOException @throws ClassNotFoundException
[ "Obtains", "an", "instance", "of", "a", "JavaBean", "specified", "the", "bean", "name", "using", "the", "specified", "class", "loader", "and", "adds", "the", "instance", "into", "the", "specified", "bean", "context", "." ]
73e51d0f3141a859dfbd37ca9becef98477e553e
https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/Beans.java#L166-L170
155,368
app55/app55-java
src/support/java/com/googlecode/openbeans/Beans.java
Beans.isInstanceOf
public static boolean isInstanceOf(Object bean, Class<?> targetType) { if (bean == null) { throw new NullPointerException(Messages.getString("beans.1D")); //$NON-NLS-1$ } return targetType == null ? false : targetType.isInstance(bean); }
java
public static boolean isInstanceOf(Object bean, Class<?> targetType) { if (bean == null) { throw new NullPointerException(Messages.getString("beans.1D")); //$NON-NLS-1$ } return targetType == null ? false : targetType.isInstance(bean); }
[ "public", "static", "boolean", "isInstanceOf", "(", "Object", "bean", ",", "Class", "<", "?", ">", "targetType", ")", "{", "if", "(", "bean", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "Messages", ".", "getString", "(", "\"beans.1D\"", ")", ")", ";", "//$NON-NLS-1$", "}", "return", "targetType", "==", "null", "?", "false", ":", "targetType", ".", "isInstance", "(", "bean", ")", ";", "}" ]
Determine if the the specified bean object can be viewed as the specified type. @param bean the specified bean object. @param targetType the specifed view type. @return true if the specified bean object can be viewed as the specified type; otherwise, return false;
[ "Determine", "if", "the", "the", "specified", "bean", "object", "can", "be", "viewed", "as", "the", "specified", "type", "." ]
73e51d0f3141a859dfbd37ca9becef98477e553e
https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/Beans.java#L241-L249
155,369
app55/app55-java
src/support/java/com/googlecode/openbeans/Beans.java
Beans.safeURL
private static URL safeURL(String urlString) throws ClassNotFoundException { try { return new URL(urlString); } catch (MalformedURLException exception) { throw new ClassNotFoundException(exception.getMessage()); } }
java
private static URL safeURL(String urlString) throws ClassNotFoundException { try { return new URL(urlString); } catch (MalformedURLException exception) { throw new ClassNotFoundException(exception.getMessage()); } }
[ "private", "static", "URL", "safeURL", "(", "String", "urlString", ")", "throws", "ClassNotFoundException", "{", "try", "{", "return", "new", "URL", "(", "urlString", ")", ";", "}", "catch", "(", "MalformedURLException", "exception", ")", "{", "throw", "new", "ClassNotFoundException", "(", "exception", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Maps malformed URL exception to ClassNotFoundException
[ "Maps", "malformed", "URL", "exception", "to", "ClassNotFoundException" ]
73e51d0f3141a859dfbd37ca9becef98477e553e
https://github.com/app55/app55-java/blob/73e51d0f3141a859dfbd37ca9becef98477e553e/src/support/java/com/googlecode/openbeans/Beans.java#L474-L484
155,370
foundation-runtime/service-directory
1.1/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/JsonSerializer.java
JsonSerializer.deserialize
public static <T> T deserialize(byte[] input, Class<T> classType) throws JsonParseException, JsonMappingException, IOException { return mapper.readValue(input, classType); }
java
public static <T> T deserialize(byte[] input, Class<T> classType) throws JsonParseException, JsonMappingException, IOException { return mapper.readValue(input, classType); }
[ "public", "static", "<", "T", ">", "T", "deserialize", "(", "byte", "[", "]", "input", ",", "Class", "<", "T", ">", "classType", ")", "throws", "JsonParseException", ",", "JsonMappingException", ",", "IOException", "{", "return", "mapper", ".", "readValue", "(", "input", ",", "classType", ")", ";", "}" ]
Deserialize from byte array. @param input the JSON String byte array. @param classType the target Object class type. @return the target Object instance. @throws JsonParseException @throws JsonMappingException @throws IOException
[ "Deserialize", "from", "byte", "array", "." ]
a7bdefe173dc99e75eff4a24e07e6407e62f2ed4
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.1/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/JsonSerializer.java#L57-L60
155,371
foundation-runtime/service-directory
1.1/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/JsonSerializer.java
JsonSerializer.serialize
public static byte[] serialize(Object instance) throws JsonGenerationException, JsonMappingException, IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); mapper.writeValue(out, instance); return out.toByteArray(); }
java
public static byte[] serialize(Object instance) throws JsonGenerationException, JsonMappingException, IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); mapper.writeValue(out, instance); return out.toByteArray(); }
[ "public", "static", "byte", "[", "]", "serialize", "(", "Object", "instance", ")", "throws", "JsonGenerationException", ",", "JsonMappingException", ",", "IOException", "{", "ByteArrayOutputStream", "out", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "mapper", ".", "writeValue", "(", "out", ",", "instance", ")", ";", "return", "out", ".", "toByteArray", "(", ")", ";", "}" ]
Serialize the Object to JSON String. @param instance the Object instance. @return the JSON String byte array. @throws JsonGenerationException @throws JsonMappingException @throws IOException
[ "Serialize", "the", "Object", "to", "JSON", "String", "." ]
a7bdefe173dc99e75eff4a24e07e6407e62f2ed4
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.1/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/JsonSerializer.java#L89-L94
155,372
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ConnectionUtility.java
ConnectionUtility.createDataSource
public static DataSource createDataSource(String source, String jndiName){ DataSource ds = createDataSource(source); if (ds != null && jndiName != null){ InitialContext ic; try { ic = new InitialContext(); ic.bind(jndiName, ds); } catch (NamingException e) { log.error("Failed to bind data source '" + source + "' to JNDI name: " + jndiName, e); } } return ds; }
java
public static DataSource createDataSource(String source, String jndiName){ DataSource ds = createDataSource(source); if (ds != null && jndiName != null){ InitialContext ic; try { ic = new InitialContext(); ic.bind(jndiName, ds); } catch (NamingException e) { log.error("Failed to bind data source '" + source + "' to JNDI name: " + jndiName, e); } } return ds; }
[ "public", "static", "DataSource", "createDataSource", "(", "String", "source", ",", "String", "jndiName", ")", "{", "DataSource", "ds", "=", "createDataSource", "(", "source", ")", ";", "if", "(", "ds", "!=", "null", "&&", "jndiName", "!=", "null", ")", "{", "InitialContext", "ic", ";", "try", "{", "ic", "=", "new", "InitialContext", "(", ")", ";", "ic", ".", "bind", "(", "jndiName", ",", "ds", ")", ";", "}", "catch", "(", "NamingException", "e", ")", "{", "log", ".", "error", "(", "\"Failed to bind data source '\"", "+", "source", "+", "\"' to JNDI name: \"", "+", "jndiName", ",", "e", ")", ";", "}", "}", "return", "ds", ";", "}" ]
Create DataSource and bind it to JNDI @param source configuration @param jndiName JNDI name that the DataSource needs to be bind to @return The DataSource created
[ "Create", "DataSource", "and", "bind", "it", "to", "JNDI" ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ConnectionUtility.java#L246-L258
155,373
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ConnectionUtility.java
ConnectionUtility.destroyDataSource
public static void destroyDataSource(DataSource dataSource, boolean force){ synchronized (dataSourcesStructureLock){ String dsName = null; for (Map.Entry<String, DataSource> dsEntry: dataSources.entrySet()){ DataSource ds = dsEntry.getValue(); if (ds == dataSource){ dsName = dsEntry.getKey(); break; } } if (force || dsName != null){ for (Map.Entry<String, DataSourceProvider> dspEntry: dataSourceProviders.entrySet()){ // try them one by one String dspName = dspEntry.getKey(); DataSourceProvider dsp = dspEntry.getValue(); try{ if (dsp.destroyDataSource(dataSource)){ if (dsName != null){ dataSources.remove(dsName); } break; } }catch(NoClassDefFoundError e){ // ignore }catch(Throwable e){ log.error("Error when destroying data source '" + dsName + "' using provider '" + dspName + "'", e); } } } } }
java
public static void destroyDataSource(DataSource dataSource, boolean force){ synchronized (dataSourcesStructureLock){ String dsName = null; for (Map.Entry<String, DataSource> dsEntry: dataSources.entrySet()){ DataSource ds = dsEntry.getValue(); if (ds == dataSource){ dsName = dsEntry.getKey(); break; } } if (force || dsName != null){ for (Map.Entry<String, DataSourceProvider> dspEntry: dataSourceProviders.entrySet()){ // try them one by one String dspName = dspEntry.getKey(); DataSourceProvider dsp = dspEntry.getValue(); try{ if (dsp.destroyDataSource(dataSource)){ if (dsName != null){ dataSources.remove(dsName); } break; } }catch(NoClassDefFoundError e){ // ignore }catch(Throwable e){ log.error("Error when destroying data source '" + dsName + "' using provider '" + dspName + "'", e); } } } } }
[ "public", "static", "void", "destroyDataSource", "(", "DataSource", "dataSource", ",", "boolean", "force", ")", "{", "synchronized", "(", "dataSourcesStructureLock", ")", "{", "String", "dsName", "=", "null", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "DataSource", ">", "dsEntry", ":", "dataSources", ".", "entrySet", "(", ")", ")", "{", "DataSource", "ds", "=", "dsEntry", ".", "getValue", "(", ")", ";", "if", "(", "ds", "==", "dataSource", ")", "{", "dsName", "=", "dsEntry", ".", "getKey", "(", ")", ";", "break", ";", "}", "}", "if", "(", "force", "||", "dsName", "!=", "null", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "DataSourceProvider", ">", "dspEntry", ":", "dataSourceProviders", ".", "entrySet", "(", ")", ")", "{", "// try them one by one\r", "String", "dspName", "=", "dspEntry", ".", "getKey", "(", ")", ";", "DataSourceProvider", "dsp", "=", "dspEntry", ".", "getValue", "(", ")", ";", "try", "{", "if", "(", "dsp", ".", "destroyDataSource", "(", "dataSource", ")", ")", "{", "if", "(", "dsName", "!=", "null", ")", "{", "dataSources", ".", "remove", "(", "dsName", ")", ";", "}", "break", ";", "}", "}", "catch", "(", "NoClassDefFoundError", "e", ")", "{", "// ignore\r", "}", "catch", "(", "Throwable", "e", ")", "{", "log", ".", "error", "(", "\"Error when destroying data source '\"", "+", "dsName", "+", "\"' using provider '\"", "+", "dspName", "+", "\"'\"", ",", "e", ")", ";", "}", "}", "}", "}", "}" ]
Destroy a data source got from or created by ConnectionUtility before. If any exception occurred, it will be logged but never propagated. @param dataSource the data source to be destroyed @param force Whether try to destroy the data source even if it was created using createDataSource(...) method rather than getDataSource(...) method. If it is true, the data source will always be destroyed, if it is false, the data source will be destroyed only if it was got using getDataSource(...) method.
[ "Destroy", "a", "data", "source", "got", "from", "or", "created", "by", "ConnectionUtility", "before", ".", "If", "any", "exception", "occurred", "it", "will", "be", "logged", "but", "never", "propagated", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ConnectionUtility.java#L279-L308
155,374
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ConnectionUtility.java
ConnectionUtility.destroyDataSources
public static void destroyDataSources(){ synchronized (dataSourcesStructureLock){ for (Map.Entry<String, DataSource> dsEntry: dataSources.entrySet()){ String dsName = dsEntry.getKey(); DataSource ds = dsEntry.getValue(); for (Map.Entry<String, DataSourceProvider> dspEntry: dataSourceProviders.entrySet()){ // try them one by one String dspName = dspEntry.getKey(); DataSourceProvider dsp = dspEntry.getValue(); try{ if (dsp.destroyDataSource(ds)){ break; } }catch(NoClassDefFoundError e){ // ignore }catch(Throwable e){ log.error("Error when destroying data source '" + dsName + "' using provider '" + dspName + "'", e); } } } dataSources.clear(); } }
java
public static void destroyDataSources(){ synchronized (dataSourcesStructureLock){ for (Map.Entry<String, DataSource> dsEntry: dataSources.entrySet()){ String dsName = dsEntry.getKey(); DataSource ds = dsEntry.getValue(); for (Map.Entry<String, DataSourceProvider> dspEntry: dataSourceProviders.entrySet()){ // try them one by one String dspName = dspEntry.getKey(); DataSourceProvider dsp = dspEntry.getValue(); try{ if (dsp.destroyDataSource(ds)){ break; } }catch(NoClassDefFoundError e){ // ignore }catch(Throwable e){ log.error("Error when destroying data source '" + dsName + "' using provider '" + dspName + "'", e); } } } dataSources.clear(); } }
[ "public", "static", "void", "destroyDataSources", "(", ")", "{", "synchronized", "(", "dataSourcesStructureLock", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "DataSource", ">", "dsEntry", ":", "dataSources", ".", "entrySet", "(", ")", ")", "{", "String", "dsName", "=", "dsEntry", ".", "getKey", "(", ")", ";", "DataSource", "ds", "=", "dsEntry", ".", "getValue", "(", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "DataSourceProvider", ">", "dspEntry", ":", "dataSourceProviders", ".", "entrySet", "(", ")", ")", "{", "// try them one by one\r", "String", "dspName", "=", "dspEntry", ".", "getKey", "(", ")", ";", "DataSourceProvider", "dsp", "=", "dspEntry", ".", "getValue", "(", ")", ";", "try", "{", "if", "(", "dsp", ".", "destroyDataSource", "(", "ds", ")", ")", "{", "break", ";", "}", "}", "catch", "(", "NoClassDefFoundError", "e", ")", "{", "// ignore\r", "}", "catch", "(", "Throwable", "e", ")", "{", "log", ".", "error", "(", "\"Error when destroying data source '\"", "+", "dsName", "+", "\"' using provider '\"", "+", "dspName", "+", "\"'\"", ",", "e", ")", ";", "}", "}", "}", "dataSources", ".", "clear", "(", ")", ";", "}", "}" ]
Destroy all the data sources created before. If any exception occurred, it will be logged but never propagated.
[ "Destroy", "all", "the", "data", "sources", "created", "before", ".", "If", "any", "exception", "occurred", "it", "will", "be", "logged", "but", "never", "propagated", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ConnectionUtility.java#L314-L335
155,375
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ConnectionUtility.java
ConnectionUtility.closeConnection
public static void closeConnection(Connection conn){ if (conn != null) { try { conn.close(); } catch (Exception e) { log.warn("Exception when closing database connection.", e); } } }
java
public static void closeConnection(Connection conn){ if (conn != null) { try { conn.close(); } catch (Exception e) { log.warn("Exception when closing database connection.", e); } } }
[ "public", "static", "void", "closeConnection", "(", "Connection", "conn", ")", "{", "if", "(", "conn", "!=", "null", ")", "{", "try", "{", "conn", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "warn", "(", "\"Exception when closing database connection.\"", ",", "e", ")", ";", "}", "}", "}" ]
Closes database Connection. No exception will be thrown even if occurred during closing, instead, the exception will be logged at warning level. @param conn database connection that need to be closed
[ "Closes", "database", "Connection", ".", "No", "exception", "will", "be", "thrown", "even", "if", "occurred", "during", "closing", "instead", "the", "exception", "will", "be", "logged", "at", "warning", "level", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ConnectionUtility.java#L366-L374
155,376
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ConnectionUtility.java
ConnectionUtility.closeStatement
public static void closeStatement(Statement st){ if (st != null) { try { st.close(); } catch (Exception e) { log.warn("Exception when closing database statement.", e); } } }
java
public static void closeStatement(Statement st){ if (st != null) { try { st.close(); } catch (Exception e) { log.warn("Exception when closing database statement.", e); } } }
[ "public", "static", "void", "closeStatement", "(", "Statement", "st", ")", "{", "if", "(", "st", "!=", "null", ")", "{", "try", "{", "st", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "warn", "(", "\"Exception when closing database statement.\"", ",", "e", ")", ";", "}", "}", "}" ]
Closes database Statement. No exception will be thrown even if occurred during closing, instead, the exception will be logged at warning level. @param st the Statement that need to be closed
[ "Closes", "database", "Statement", ".", "No", "exception", "will", "be", "thrown", "even", "if", "occurred", "during", "closing", "instead", "the", "exception", "will", "be", "logged", "at", "warning", "level", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ConnectionUtility.java#L383-L391
155,377
james-hu/jabb-core
src/main/java/net/sf/jabb/util/db/ConnectionUtility.java
ConnectionUtility.closeResultSet
public static void closeResultSet(ResultSet rs){ if (rs != null) { try { rs.close(); } catch (Exception e) { log.warn("Exception when closing database result set.", e); } } }
java
public static void closeResultSet(ResultSet rs){ if (rs != null) { try { rs.close(); } catch (Exception e) { log.warn("Exception when closing database result set.", e); } } }
[ "public", "static", "void", "closeResultSet", "(", "ResultSet", "rs", ")", "{", "if", "(", "rs", "!=", "null", ")", "{", "try", "{", "rs", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "warn", "(", "\"Exception when closing database result set.\"", ",", "e", ")", ";", "}", "}", "}" ]
Closes database ResultSet No exception will be thrown even if occurred during closing, instead, the exception will be logged at warning level. @param rs the ResultSet that need to be closed
[ "Closes", "database", "ResultSet", "No", "exception", "will", "be", "thrown", "even", "if", "occurred", "during", "closing", "instead", "the", "exception", "will", "be", "logged", "at", "warning", "level", "." ]
bceed441595c5e5195a7418795f03b69fa7b61e4
https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/util/db/ConnectionUtility.java#L400-L408
155,378
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/run/Closer.java
Closer.closeOne
public static void closeOne(String correlationId, Object component) throws ApplicationException { if (component instanceof IClosable) ((IClosable) component).close(correlationId); }
java
public static void closeOne(String correlationId, Object component) throws ApplicationException { if (component instanceof IClosable) ((IClosable) component).close(correlationId); }
[ "public", "static", "void", "closeOne", "(", "String", "correlationId", ",", "Object", "component", ")", "throws", "ApplicationException", "{", "if", "(", "component", "instanceof", "IClosable", ")", "(", "(", "IClosable", ")", "component", ")", ".", "close", "(", "correlationId", ")", ";", "}" ]
Closes specific component. To be closed components must implement ICloseable interface. If they don't the call to this method has no effect. @param correlationId (optional) transaction id to trace execution through call chain. @param component the component that is to be closed. @throws ApplicationException when error or null no errors occured. @see IClosable
[ "Closes", "specific", "component", "." ]
a8a0c3e5ec58f0663c295aa855c6b3afad2af86a
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/run/Closer.java#L24-L28
155,379
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/run/Closer.java
Closer.close
public static void close(String correlationId, Iterable<Object> components) throws ApplicationException { if (components == null) return; for (Object component : components) closeOne(correlationId, component); }
java
public static void close(String correlationId, Iterable<Object> components) throws ApplicationException { if (components == null) return; for (Object component : components) closeOne(correlationId, component); }
[ "public", "static", "void", "close", "(", "String", "correlationId", ",", "Iterable", "<", "Object", ">", "components", ")", "throws", "ApplicationException", "{", "if", "(", "components", "==", "null", ")", "return", ";", "for", "(", "Object", "component", ":", "components", ")", "closeOne", "(", "correlationId", ",", "component", ")", ";", "}" ]
Closes multiple components. To be closed components must implement ICloseable interface. If they don't the call to this method has no effect. @param correlationId (optional) transaction id to trace execution through call chain. @param components the list of components that are to be closed. @throws ApplicationException when error or null no errors occured. @see #closeOne(String, Object) @see IClosable
[ "Closes", "multiple", "components", "." ]
a8a0c3e5ec58f0663c295aa855c6b3afad2af86a
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/run/Closer.java#L44-L51
155,380
bushidowallet/bushido-java-service
bushido-service-lib/src/main/java/com/bccapi/bitlib/crypto/PrivateKeyRing.java
PrivateKeyRing.addPrivateKey
public void addPrivateKey(PrivateKey key, NetworkParameters network) { _privateKeys.put(key.getPublicKey(), key); addPublicKey(key.getPublicKey(), network); }
java
public void addPrivateKey(PrivateKey key, NetworkParameters network) { _privateKeys.put(key.getPublicKey(), key); addPublicKey(key.getPublicKey(), network); }
[ "public", "void", "addPrivateKey", "(", "PrivateKey", "key", ",", "NetworkParameters", "network", ")", "{", "_privateKeys", ".", "put", "(", "key", ".", "getPublicKey", "(", ")", ",", "key", ")", ";", "addPublicKey", "(", "key", ".", "getPublicKey", "(", ")", ",", "network", ")", ";", "}" ]
Add a private key to the key ring. @param key private key @param network bitcoin network to talk to
[ "Add", "a", "private", "key", "to", "the", "key", "ring", "." ]
e1a0157527e57459b509718044d2df44084876a2
https://github.com/bushidowallet/bushido-java-service/blob/e1a0157527e57459b509718044d2df44084876a2/bushido-service-lib/src/main/java/com/bccapi/bitlib/crypto/PrivateKeyRing.java#L22-L25
155,381
bushidowallet/bushido-java-service
bushido-service-lib/src/main/java/com/bccapi/bitlib/crypto/PrivateKeyRing.java
PrivateKeyRing.findKeyExporterByPublicKey
public KeyExporter findKeyExporterByPublicKey(PublicKey publicKey) { PrivateKey key = _privateKeys.get(publicKey); if (key instanceof KeyExporter) { return (KeyExporter) key; } return null; }
java
public KeyExporter findKeyExporterByPublicKey(PublicKey publicKey) { PrivateKey key = _privateKeys.get(publicKey); if (key instanceof KeyExporter) { return (KeyExporter) key; } return null; }
[ "public", "KeyExporter", "findKeyExporterByPublicKey", "(", "PublicKey", "publicKey", ")", "{", "PrivateKey", "key", "=", "_privateKeys", ".", "get", "(", "publicKey", ")", ";", "if", "(", "key", "instanceof", "KeyExporter", ")", "{", "return", "(", "KeyExporter", ")", "key", ";", "}", "return", "null", ";", "}" ]
Find a KeyExporter by public key @return key exporter
[ "Find", "a", "KeyExporter", "by", "public", "key" ]
e1a0157527e57459b509718044d2df44084876a2
https://github.com/bushidowallet/bushido-java-service/blob/e1a0157527e57459b509718044d2df44084876a2/bushido-service-lib/src/main/java/com/bccapi/bitlib/crypto/PrivateKeyRing.java#L43-L49
155,382
pierre/eventtracker
scribe/src/main/java/com/ning/metrics/eventtracker/ScribeSender.java
ScribeSender.createConnection
public synchronized void createConnection() { if (scribeClient != null) { try { connectionRetries.incrementAndGet(); scribeClient.closeLogger(); scribeClient.openLogger(); isClosed.set(false); log.info("Connection to Scribe established"); } catch (TTransportException e) { log.warn("Unable to connect to Scribe: {}", e.getLocalizedMessage()); scribeClient.closeLogger(); } } else { log.warn("Scribe client has not been set up correctly."); } }
java
public synchronized void createConnection() { if (scribeClient != null) { try { connectionRetries.incrementAndGet(); scribeClient.closeLogger(); scribeClient.openLogger(); isClosed.set(false); log.info("Connection to Scribe established"); } catch (TTransportException e) { log.warn("Unable to connect to Scribe: {}", e.getLocalizedMessage()); scribeClient.closeLogger(); } } else { log.warn("Scribe client has not been set up correctly."); } }
[ "public", "synchronized", "void", "createConnection", "(", ")", "{", "if", "(", "scribeClient", "!=", "null", ")", "{", "try", "{", "connectionRetries", ".", "incrementAndGet", "(", ")", ";", "scribeClient", ".", "closeLogger", "(", ")", ";", "scribeClient", ".", "openLogger", "(", ")", ";", "isClosed", ".", "set", "(", "false", ")", ";", "log", ".", "info", "(", "\"Connection to Scribe established\"", ")", ";", "}", "catch", "(", "TTransportException", "e", ")", "{", "log", ".", "warn", "(", "\"Unable to connect to Scribe: {}\"", ",", "e", ".", "getLocalizedMessage", "(", ")", ")", ";", "scribeClient", ".", "closeLogger", "(", ")", ";", "}", "}", "else", "{", "log", ".", "warn", "(", "\"Scribe client has not been set up correctly.\"", ")", ";", "}", "}" ]
Re-initialize the connection with the Scribe endpoint.
[ "Re", "-", "initialize", "the", "connection", "with", "the", "Scribe", "endpoint", "." ]
d47e74f11b05500fc31eeb43448aa6316a1318f6
https://github.com/pierre/eventtracker/blob/d47e74f11b05500fc31eeb43448aa6316a1318f6/scribe/src/main/java/com/ning/metrics/eventtracker/ScribeSender.java#L88-L107
155,383
pierre/eventtracker
scribe/src/main/java/com/ning/metrics/eventtracker/ScribeSender.java
ScribeSender.close
@Override public synchronized void close() { if (scribeClient != null && !isClosed.get()) { scribeClient.closeLogger(); isClosed.set(true); } }
java
@Override public synchronized void close() { if (scribeClient != null && !isClosed.get()) { scribeClient.closeLogger(); isClosed.set(true); } }
[ "@", "Override", "public", "synchronized", "void", "close", "(", ")", "{", "if", "(", "scribeClient", "!=", "null", "&&", "!", "isClosed", ".", "get", "(", ")", ")", "{", "scribeClient", ".", "closeLogger", "(", ")", ";", "isClosed", ".", "set", "(", "true", ")", ";", "}", "}" ]
Disconnect from Scribe for good.
[ "Disconnect", "from", "Scribe", "for", "good", "." ]
d47e74f11b05500fc31eeb43448aa6316a1318f6
https://github.com/pierre/eventtracker/blob/d47e74f11b05500fc31eeb43448aa6316a1318f6/scribe/src/main/java/com/ning/metrics/eventtracker/ScribeSender.java#L112-L119
155,384
pierre/eventtracker
scribe/src/main/java/com/ning/metrics/eventtracker/ScribeSender.java
ScribeSender.createScribePayload
private List<LogEntry> createScribePayload(final File file, final CallbackHandler handler) { try { final List<Event> events = Events.fromFile(file); final List<LogEntry> list = new ArrayList<LogEntry>(events.size()); for (final Event event : events) { final String logEntryMessage = eventToLogEntryMessage(event); list.add(new LogEntry(event.getName(), logEntryMessage)); } return list; } catch (ClassNotFoundException e) { handler.onError(new Throwable(e), file); return null; } catch (IOException e) { handler.onError(new Throwable(e), file); return null; } }
java
private List<LogEntry> createScribePayload(final File file, final CallbackHandler handler) { try { final List<Event> events = Events.fromFile(file); final List<LogEntry> list = new ArrayList<LogEntry>(events.size()); for (final Event event : events) { final String logEntryMessage = eventToLogEntryMessage(event); list.add(new LogEntry(event.getName(), logEntryMessage)); } return list; } catch (ClassNotFoundException e) { handler.onError(new Throwable(e), file); return null; } catch (IOException e) { handler.onError(new Throwable(e), file); return null; } }
[ "private", "List", "<", "LogEntry", ">", "createScribePayload", "(", "final", "File", "file", ",", "final", "CallbackHandler", "handler", ")", "{", "try", "{", "final", "List", "<", "Event", ">", "events", "=", "Events", ".", "fromFile", "(", "file", ")", ";", "final", "List", "<", "LogEntry", ">", "list", "=", "new", "ArrayList", "<", "LogEntry", ">", "(", "events", ".", "size", "(", ")", ")", ";", "for", "(", "final", "Event", "event", ":", "events", ")", "{", "final", "String", "logEntryMessage", "=", "eventToLogEntryMessage", "(", "event", ")", ";", "list", ".", "add", "(", "new", "LogEntry", "(", "event", ".", "getName", "(", ")", ",", "logEntryMessage", ")", ")", ";", "}", "return", "list", ";", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "handler", ".", "onError", "(", "new", "Throwable", "(", "e", ")", ",", "file", ")", ";", "return", "null", ";", "}", "catch", "(", "IOException", "e", ")", "{", "handler", ".", "onError", "(", "new", "Throwable", "(", "e", ")", ",", "file", ")", ";", "return", "null", ";", "}", "}" ]
Give a file of events, generate LogEntry messages for Scribe @param file File containing events @param handler notifier for the serialization-writer library @return list of Scirbe-ready events on success, null otherwise
[ "Give", "a", "file", "of", "events", "generate", "LogEntry", "messages", "for", "Scribe" ]
d47e74f11b05500fc31eeb43448aa6316a1318f6
https://github.com/pierre/eventtracker/blob/d47e74f11b05500fc31eeb43448aa6316a1318f6/scribe/src/main/java/com/ning/metrics/eventtracker/ScribeSender.java#L169-L190
155,385
foundation-runtime/service-directory
1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/lookup/LookupManagerImpl.java
LookupManagerImpl.addInstanceChangeListener
@Override public void addInstanceChangeListener(String serviceName, ServiceInstanceChangeListener listener) throws ServiceException { ServiceInstanceUtils.validateManagerIsStarted(isStarted.get()); ServiceInstanceUtils.validateServiceName(serviceName); if (listener == null) { throw new ServiceException(ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR, ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR.getMessageTemplate(), "ServiceInstanceChangeListener"); } ModelService service = getLookupService().getModelService(serviceName); if (service == null) { throw new ServiceException(ErrorCode.SERVICE_DOES_NOT_EXIST,ErrorCode.SERVICE_DOES_NOT_EXIST.getMessageTemplate(),serviceName); } getLookupService().addServiceInstanceChangeListener(serviceName, listener); }
java
@Override public void addInstanceChangeListener(String serviceName, ServiceInstanceChangeListener listener) throws ServiceException { ServiceInstanceUtils.validateManagerIsStarted(isStarted.get()); ServiceInstanceUtils.validateServiceName(serviceName); if (listener == null) { throw new ServiceException(ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR, ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR.getMessageTemplate(), "ServiceInstanceChangeListener"); } ModelService service = getLookupService().getModelService(serviceName); if (service == null) { throw new ServiceException(ErrorCode.SERVICE_DOES_NOT_EXIST,ErrorCode.SERVICE_DOES_NOT_EXIST.getMessageTemplate(),serviceName); } getLookupService().addServiceInstanceChangeListener(serviceName, listener); }
[ "@", "Override", "public", "void", "addInstanceChangeListener", "(", "String", "serviceName", ",", "ServiceInstanceChangeListener", "listener", ")", "throws", "ServiceException", "{", "ServiceInstanceUtils", ".", "validateManagerIsStarted", "(", "isStarted", ".", "get", "(", ")", ")", ";", "ServiceInstanceUtils", ".", "validateServiceName", "(", "serviceName", ")", ";", "if", "(", "listener", "==", "null", ")", "{", "throw", "new", "ServiceException", "(", "ErrorCode", ".", "SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR", ",", "ErrorCode", ".", "SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR", ".", "getMessageTemplate", "(", ")", ",", "\"ServiceInstanceChangeListener\"", ")", ";", "}", "ModelService", "service", "=", "getLookupService", "(", ")", ".", "getModelService", "(", "serviceName", ")", ";", "if", "(", "service", "==", "null", ")", "{", "throw", "new", "ServiceException", "(", "ErrorCode", ".", "SERVICE_DOES_NOT_EXIST", ",", "ErrorCode", ".", "SERVICE_DOES_NOT_EXIST", ".", "getMessageTemplate", "(", ")", ",", "serviceName", ")", ";", "}", "getLookupService", "(", ")", ".", "addServiceInstanceChangeListener", "(", "serviceName", ",", "listener", ")", ";", "}" ]
Add a ServiceInstanceChangeListener to the Service. This method will check the duplicated listener for the serviceName, if the listener already exists for the serviceName, do nothing. Throws IllegalArgumentException if serviceName or listener is null. @param serviceName the service name @param listener the ServiceInstanceChangeListener for the service @throws ServiceException
[ "Add", "a", "ServiceInstanceChangeListener", "to", "the", "Service", "." ]
a7bdefe173dc99e75eff4a24e07e6407e62f2ed4
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/lookup/LookupManagerImpl.java#L413-L427
155,386
foundation-runtime/service-directory
1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/lookup/LookupManagerImpl.java
LookupManagerImpl.removeInstanceChangeListener
@Override public void removeInstanceChangeListener(String serviceName, ServiceInstanceChangeListener listener) throws ServiceException { ServiceInstanceUtils.validateManagerIsStarted(isStarted.get()); ServiceInstanceUtils.validateServiceName(serviceName); if (listener == null) { throw new ServiceException(ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR, ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR.getMessageTemplate(), "ServiceInstanceChangeListener"); } getLookupService().removeServiceInstanceChangeListener(serviceName, listener); }
java
@Override public void removeInstanceChangeListener(String serviceName, ServiceInstanceChangeListener listener) throws ServiceException { ServiceInstanceUtils.validateManagerIsStarted(isStarted.get()); ServiceInstanceUtils.validateServiceName(serviceName); if (listener == null) { throw new ServiceException(ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR, ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR.getMessageTemplate(), "ServiceInstanceChangeListener"); } getLookupService().removeServiceInstanceChangeListener(serviceName, listener); }
[ "@", "Override", "public", "void", "removeInstanceChangeListener", "(", "String", "serviceName", ",", "ServiceInstanceChangeListener", "listener", ")", "throws", "ServiceException", "{", "ServiceInstanceUtils", ".", "validateManagerIsStarted", "(", "isStarted", ".", "get", "(", ")", ")", ";", "ServiceInstanceUtils", ".", "validateServiceName", "(", "serviceName", ")", ";", "if", "(", "listener", "==", "null", ")", "{", "throw", "new", "ServiceException", "(", "ErrorCode", ".", "SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR", ",", "ErrorCode", ".", "SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR", ".", "getMessageTemplate", "(", ")", ",", "\"ServiceInstanceChangeListener\"", ")", ";", "}", "getLookupService", "(", ")", ".", "removeServiceInstanceChangeListener", "(", "serviceName", ",", "listener", ")", ";", "}" ]
Remove a ServiceInstanceChangeListener from the Service. Throws IllegalArgumentException if serviceName or listener is null. @param serviceName the service name @param listener the ServiceInstanceChangeListener for the service @throws ServiceException
[ "Remove", "a", "ServiceInstanceChangeListener", "from", "the", "Service", "." ]
a7bdefe173dc99e75eff4a24e07e6407e62f2ed4
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/lookup/LookupManagerImpl.java#L439-L450
155,387
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/validate/ObjectComparator.java
ObjectComparator.compare
public static boolean compare(Object value1, String operation, Object value2) { if (operation == null) return false; operation = operation.toUpperCase(); if (operation.equals("=") || operation.equals("==") || operation.equals("EQ")) return areEqual(value1, value2); if (operation.equals("!=") || operation.equals("<>") || operation.equals("NE")) return areNotEqual(value1, value2); if (operation.equals("<") || operation.equals("LT")) return less(value1, value2); if (operation.equals("<=") || operation.equals("LE")) return areEqual(value1, value2) || less(value1, value2); if (operation.equals(">") || operation.equals("GT")) return more(value1, value2); if (operation.equals(">=") || operation.equals("GE")) return areEqual(value1, value2) || more(value1, value2); if (operation.equals("LIKE")) return match(value1, value2); return true; }
java
public static boolean compare(Object value1, String operation, Object value2) { if (operation == null) return false; operation = operation.toUpperCase(); if (operation.equals("=") || operation.equals("==") || operation.equals("EQ")) return areEqual(value1, value2); if (operation.equals("!=") || operation.equals("<>") || operation.equals("NE")) return areNotEqual(value1, value2); if (operation.equals("<") || operation.equals("LT")) return less(value1, value2); if (operation.equals("<=") || operation.equals("LE")) return areEqual(value1, value2) || less(value1, value2); if (operation.equals(">") || operation.equals("GT")) return more(value1, value2); if (operation.equals(">=") || operation.equals("GE")) return areEqual(value1, value2) || more(value1, value2); if (operation.equals("LIKE")) return match(value1, value2); return true; }
[ "public", "static", "boolean", "compare", "(", "Object", "value1", ",", "String", "operation", ",", "Object", "value2", ")", "{", "if", "(", "operation", "==", "null", ")", "return", "false", ";", "operation", "=", "operation", ".", "toUpperCase", "(", ")", ";", "if", "(", "operation", ".", "equals", "(", "\"=\"", ")", "||", "operation", ".", "equals", "(", "\"==\"", ")", "||", "operation", ".", "equals", "(", "\"EQ\"", ")", ")", "return", "areEqual", "(", "value1", ",", "value2", ")", ";", "if", "(", "operation", ".", "equals", "(", "\"!=\"", ")", "||", "operation", ".", "equals", "(", "\"<>\"", ")", "||", "operation", ".", "equals", "(", "\"NE\"", ")", ")", "return", "areNotEqual", "(", "value1", ",", "value2", ")", ";", "if", "(", "operation", ".", "equals", "(", "\"<\"", ")", "||", "operation", ".", "equals", "(", "\"LT\"", ")", ")", "return", "less", "(", "value1", ",", "value2", ")", ";", "if", "(", "operation", ".", "equals", "(", "\"<=\"", ")", "||", "operation", ".", "equals", "(", "\"LE\"", ")", ")", "return", "areEqual", "(", "value1", ",", "value2", ")", "||", "less", "(", "value1", ",", "value2", ")", ";", "if", "(", "operation", ".", "equals", "(", "\">\"", ")", "||", "operation", ".", "equals", "(", "\"GT\"", ")", ")", "return", "more", "(", "value1", ",", "value2", ")", ";", "if", "(", "operation", ".", "equals", "(", "\">=\"", ")", "||", "operation", ".", "equals", "(", "\"GE\"", ")", ")", "return", "areEqual", "(", "value1", ",", "value2", ")", "||", "more", "(", "value1", ",", "value2", ")", ";", "if", "(", "operation", ".", "equals", "(", "\"LIKE\"", ")", ")", "return", "match", "(", "value1", ",", "value2", ")", ";", "return", "true", ";", "}" ]
Perform comparison operation over two arguments. The operation can be performed over values of any type. @param value1 the first argument to compare @param operation the comparison operation @param value2 the second argument to compare @return result of the comparison operation
[ "Perform", "comparison", "operation", "over", "two", "arguments", ".", "The", "operation", "can", "be", "performed", "over", "values", "of", "any", "type", "." ]
a8a0c3e5ec58f0663c295aa855c6b3afad2af86a
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/validate/ObjectComparator.java#L27-L49
155,388
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/validate/ObjectComparator.java
ObjectComparator.areEqual
public static boolean areEqual(Object value1, Object value2) { if (value1 == null && value2 == null) return true; if (value1 == null || value2 == null) return false; return value1.equals(value2); }
java
public static boolean areEqual(Object value1, Object value2) { if (value1 == null && value2 == null) return true; if (value1 == null || value2 == null) return false; return value1.equals(value2); }
[ "public", "static", "boolean", "areEqual", "(", "Object", "value1", ",", "Object", "value2", ")", "{", "if", "(", "value1", "==", "null", "&&", "value2", "==", "null", ")", "return", "true", ";", "if", "(", "value1", "==", "null", "||", "value2", "==", "null", ")", "return", "false", ";", "return", "value1", ".", "equals", "(", "value2", ")", ";", "}" ]
Checks if two values are equal. The operation can be performed over values of any type. @param value1 the first value to compare @param value2 the second value to compare @return true if values are equal and false otherwise
[ "Checks", "if", "two", "values", "are", "equal", ".", "The", "operation", "can", "be", "performed", "over", "values", "of", "any", "type", "." ]
a8a0c3e5ec58f0663c295aa855c6b3afad2af86a
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/validate/ObjectComparator.java#L59-L65
155,389
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/validate/ObjectComparator.java
ObjectComparator.less
public static boolean less(Object value1, Object value2) { Double number1 = DoubleConverter.toNullableDouble(value1); Double number2 = DoubleConverter.toNullableDouble(value2); if (number1 == null || number2 == null) return false; return number1.doubleValue() < number2.doubleValue(); }
java
public static boolean less(Object value1, Object value2) { Double number1 = DoubleConverter.toNullableDouble(value1); Double number2 = DoubleConverter.toNullableDouble(value2); if (number1 == null || number2 == null) return false; return number1.doubleValue() < number2.doubleValue(); }
[ "public", "static", "boolean", "less", "(", "Object", "value1", ",", "Object", "value2", ")", "{", "Double", "number1", "=", "DoubleConverter", ".", "toNullableDouble", "(", "value1", ")", ";", "Double", "number2", "=", "DoubleConverter", ".", "toNullableDouble", "(", "value2", ")", ";", "if", "(", "number1", "==", "null", "||", "number2", "==", "null", ")", "return", "false", ";", "return", "number1", ".", "doubleValue", "(", ")", "<", "number2", ".", "doubleValue", "(", ")", ";", "}" ]
Checks if first value is less than the second one. The operation can be performed over numbers or strings. @param value1 the first value to compare @param value2 the second value to compare @return true if the first value is less than second and false otherwise.
[ "Checks", "if", "first", "value", "is", "less", "than", "the", "second", "one", ".", "The", "operation", "can", "be", "performed", "over", "numbers", "or", "strings", "." ]
a8a0c3e5ec58f0663c295aa855c6b3afad2af86a
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/validate/ObjectComparator.java#L87-L95
155,390
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/validate/ObjectComparator.java
ObjectComparator.match
public static boolean match(Object value1, Object value2) { if (value1 == null && value2 == null) return true; if (value1 == null || value2 == null) return false; String string1 = value1.toString(); String string2 = value2.toString(); return string1.matches(string2); }
java
public static boolean match(Object value1, Object value2) { if (value1 == null && value2 == null) return true; if (value1 == null || value2 == null) return false; String string1 = value1.toString(); String string2 = value2.toString(); return string1.matches(string2); }
[ "public", "static", "boolean", "match", "(", "Object", "value1", ",", "Object", "value2", ")", "{", "if", "(", "value1", "==", "null", "&&", "value2", "==", "null", ")", "return", "true", ";", "if", "(", "value1", "==", "null", "||", "value2", "==", "null", ")", "return", "false", ";", "String", "string1", "=", "value1", ".", "toString", "(", ")", ";", "String", "string2", "=", "value2", ".", "toString", "(", ")", ";", "return", "string1", ".", "matches", "(", "string2", ")", ";", "}" ]
Checks if string matches a regular expression @param value1 a string value to match @param value2 a regular expression string @return true if the value matches regular expression and false otherwise.
[ "Checks", "if", "string", "matches", "a", "regular", "expression" ]
a8a0c3e5ec58f0663c295aa855c6b3afad2af86a
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/validate/ObjectComparator.java#L122-L131
155,391
pierre/eventtracker
simple/src/main/java/com/ning/metrics/eventtracker/SimpleHttpSender.java
SimpleHttpSender.send
public Future<Boolean> send(final String eventPayload) { if (client == null || client.isClosed()) { client = new AsyncHttpClient(clientConfig); } try { final AsyncHttpClient.BoundRequestBuilder requestBuilder = client .prepareGet(collectorURI + eventPayload); log.debug("Sending event to collector: {}", eventPayload); activeRequests.incrementAndGet(); return client.executeRequest(requestBuilder.build(), new AsyncCompletionHandler<Boolean>() { @Override public Boolean onCompleted(final Response response) { activeRequests.decrementAndGet(); if (response.getStatusCode() == 202) { return true; } else { log.warn("Received response from collector {}: {}", response.getStatusCode(), response.getStatusText()); return false; } } @Override public void onThrowable(final Throwable t) { activeRequests.decrementAndGet(); } }); } catch (IOException e) { // Recycle the client client.close(); return null; } }
java
public Future<Boolean> send(final String eventPayload) { if (client == null || client.isClosed()) { client = new AsyncHttpClient(clientConfig); } try { final AsyncHttpClient.BoundRequestBuilder requestBuilder = client .prepareGet(collectorURI + eventPayload); log.debug("Sending event to collector: {}", eventPayload); activeRequests.incrementAndGet(); return client.executeRequest(requestBuilder.build(), new AsyncCompletionHandler<Boolean>() { @Override public Boolean onCompleted(final Response response) { activeRequests.decrementAndGet(); if (response.getStatusCode() == 202) { return true; } else { log.warn("Received response from collector {}: {}", response.getStatusCode(), response.getStatusText()); return false; } } @Override public void onThrowable(final Throwable t) { activeRequests.decrementAndGet(); } }); } catch (IOException e) { // Recycle the client client.close(); return null; } }
[ "public", "Future", "<", "Boolean", ">", "send", "(", "final", "String", "eventPayload", ")", "{", "if", "(", "client", "==", "null", "||", "client", ".", "isClosed", "(", ")", ")", "{", "client", "=", "new", "AsyncHttpClient", "(", "clientConfig", ")", ";", "}", "try", "{", "final", "AsyncHttpClient", ".", "BoundRequestBuilder", "requestBuilder", "=", "client", ".", "prepareGet", "(", "collectorURI", "+", "eventPayload", ")", ";", "log", ".", "debug", "(", "\"Sending event to collector: {}\"", ",", "eventPayload", ")", ";", "activeRequests", ".", "incrementAndGet", "(", ")", ";", "return", "client", ".", "executeRequest", "(", "requestBuilder", ".", "build", "(", ")", ",", "new", "AsyncCompletionHandler", "<", "Boolean", ">", "(", ")", "{", "@", "Override", "public", "Boolean", "onCompleted", "(", "final", "Response", "response", ")", "{", "activeRequests", ".", "decrementAndGet", "(", ")", ";", "if", "(", "response", ".", "getStatusCode", "(", ")", "==", "202", ")", "{", "return", "true", ";", "}", "else", "{", "log", ".", "warn", "(", "\"Received response from collector {}: {}\"", ",", "response", ".", "getStatusCode", "(", ")", ",", "response", ".", "getStatusText", "(", ")", ")", ";", "return", "false", ";", "}", "}", "@", "Override", "public", "void", "onThrowable", "(", "final", "Throwable", "t", ")", "{", "activeRequests", ".", "decrementAndGet", "(", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "// Recycle the client", "client", ".", "close", "(", ")", ";", "return", "null", ";", "}", "}" ]
Send a single event to the collector @param eventPayload Event to sent, created by the EventBuilder @return true on success (collector got the event), false otherwise (event was lost)
[ "Send", "a", "single", "event", "to", "the", "collector" ]
d47e74f11b05500fc31eeb43448aa6316a1318f6
https://github.com/pierre/eventtracker/blob/d47e74f11b05500fc31eeb43448aa6316a1318f6/simple/src/main/java/com/ning/metrics/eventtracker/SimpleHttpSender.java#L62-L103
155,392
gnagy/webhejj-commons
src/main/java/hu/webhejj/commons/collections/ArrayUtils.java
ArrayUtils.removeFromIntArray
public static int[] removeFromIntArray(int[] a, int value) { if(a == null) { throw new NullPointerException("Array was null"); } int index = -1; for(int i = 0; i < a.length; i++) { if(a[i] == value) { index = i; break; } } if(index < 0) { throw new IllegalArgumentException(String.format("Element %d not found in array", value)); } int[] array = new int[a.length - 1]; if(index > 0) { System.arraycopy(a, 0, array, 0, index); } if(index < a.length) { System.arraycopy(a, index + 1, array, index, array.length - index); } return array; }
java
public static int[] removeFromIntArray(int[] a, int value) { if(a == null) { throw new NullPointerException("Array was null"); } int index = -1; for(int i = 0; i < a.length; i++) { if(a[i] == value) { index = i; break; } } if(index < 0) { throw new IllegalArgumentException(String.format("Element %d not found in array", value)); } int[] array = new int[a.length - 1]; if(index > 0) { System.arraycopy(a, 0, array, 0, index); } if(index < a.length) { System.arraycopy(a, index + 1, array, index, array.length - index); } return array; }
[ "public", "static", "int", "[", "]", "removeFromIntArray", "(", "int", "[", "]", "a", ",", "int", "value", ")", "{", "if", "(", "a", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Array was null\"", ")", ";", "}", "int", "index", "=", "-", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "a", ".", "length", ";", "i", "++", ")", "{", "if", "(", "a", "[", "i", "]", "==", "value", ")", "{", "index", "=", "i", ";", "break", ";", "}", "}", "if", "(", "index", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Element %d not found in array\"", ",", "value", ")", ")", ";", "}", "int", "[", "]", "array", "=", "new", "int", "[", "a", ".", "length", "-", "1", "]", ";", "if", "(", "index", ">", "0", ")", "{", "System", ".", "arraycopy", "(", "a", ",", "0", ",", "array", ",", "0", ",", "index", ")", ";", "}", "if", "(", "index", "<", "a", ".", "length", ")", "{", "System", ".", "arraycopy", "(", "a", ",", "index", "+", "1", ",", "array", ",", "index", ",", "array", ".", "length", "-", "index", ")", ";", "}", "return", "array", ";", "}" ]
removes first value found by linear search from array a @param a array to remove from @param value value to remove from array @return new array with value removed
[ "removes", "first", "value", "found", "by", "linear", "search", "from", "array", "a" ]
270bc6f111ec5761af31d39bd38c40fd914d2eba
https://github.com/gnagy/webhejj-commons/blob/270bc6f111ec5761af31d39bd38c40fd914d2eba/src/main/java/hu/webhejj/commons/collections/ArrayUtils.java#L80-L106
155,393
morimekta/utils
console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java
ArgumentParser.add
public <O extends BaseOption> ArgumentParser add(O option) { if (option.getName() != null) { if (longNameOptions.containsKey(option.getName())) { throw new IllegalArgumentException("Option " + option.getName() + " already exists"); } if (parent != null && parent.longNameOptions.containsKey(option.getName())) { throw new IllegalArgumentException("Option " + option.getName() + " already exists in parent"); } longNameOptions.put(option.getName(), option); } if (option instanceof Flag) { String negate = ((Flag) option).getNegateName(); if (negate != null) { if (longNameOptions.containsKey(negate)) { throw new IllegalArgumentException("Flag " + negate + " already exists"); } if (parent != null && parent.longNameOptions.containsKey(negate)) { throw new IllegalArgumentException("Flag " + negate + " already exists in parent"); } longNameOptions.put(negate, option); } } if (option.getShortNames() .length() > 0) { for (char s : option.getShortNames() .toCharArray()) { if (shortOptions.containsKey(s)) { throw new IllegalArgumentException("Short option -" + s + " already exists"); } if (parent != null && parent.shortOptions.containsKey(s)) { throw new IllegalArgumentException("Short option -" + s + " already exists in parent"); } shortOptions.put(s, option); } } this.options.add(option); return this; }
java
public <O extends BaseOption> ArgumentParser add(O option) { if (option.getName() != null) { if (longNameOptions.containsKey(option.getName())) { throw new IllegalArgumentException("Option " + option.getName() + " already exists"); } if (parent != null && parent.longNameOptions.containsKey(option.getName())) { throw new IllegalArgumentException("Option " + option.getName() + " already exists in parent"); } longNameOptions.put(option.getName(), option); } if (option instanceof Flag) { String negate = ((Flag) option).getNegateName(); if (negate != null) { if (longNameOptions.containsKey(negate)) { throw new IllegalArgumentException("Flag " + negate + " already exists"); } if (parent != null && parent.longNameOptions.containsKey(negate)) { throw new IllegalArgumentException("Flag " + negate + " already exists in parent"); } longNameOptions.put(negate, option); } } if (option.getShortNames() .length() > 0) { for (char s : option.getShortNames() .toCharArray()) { if (shortOptions.containsKey(s)) { throw new IllegalArgumentException("Short option -" + s + " already exists"); } if (parent != null && parent.shortOptions.containsKey(s)) { throw new IllegalArgumentException("Short option -" + s + " already exists in parent"); } shortOptions.put(s, option); } } this.options.add(option); return this; }
[ "public", "<", "O", "extends", "BaseOption", ">", "ArgumentParser", "add", "(", "O", "option", ")", "{", "if", "(", "option", ".", "getName", "(", ")", "!=", "null", ")", "{", "if", "(", "longNameOptions", ".", "containsKey", "(", "option", ".", "getName", "(", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Option \"", "+", "option", ".", "getName", "(", ")", "+", "\" already exists\"", ")", ";", "}", "if", "(", "parent", "!=", "null", "&&", "parent", ".", "longNameOptions", ".", "containsKey", "(", "option", ".", "getName", "(", ")", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Option \"", "+", "option", ".", "getName", "(", ")", "+", "\" already exists in parent\"", ")", ";", "}", "longNameOptions", ".", "put", "(", "option", ".", "getName", "(", ")", ",", "option", ")", ";", "}", "if", "(", "option", "instanceof", "Flag", ")", "{", "String", "negate", "=", "(", "(", "Flag", ")", "option", ")", ".", "getNegateName", "(", ")", ";", "if", "(", "negate", "!=", "null", ")", "{", "if", "(", "longNameOptions", ".", "containsKey", "(", "negate", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Flag \"", "+", "negate", "+", "\" already exists\"", ")", ";", "}", "if", "(", "parent", "!=", "null", "&&", "parent", ".", "longNameOptions", ".", "containsKey", "(", "negate", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Flag \"", "+", "negate", "+", "\" already exists in parent\"", ")", ";", "}", "longNameOptions", ".", "put", "(", "negate", ",", "option", ")", ";", "}", "}", "if", "(", "option", ".", "getShortNames", "(", ")", ".", "length", "(", ")", ">", "0", ")", "{", "for", "(", "char", "s", ":", "option", ".", "getShortNames", "(", ")", ".", "toCharArray", "(", ")", ")", "{", "if", "(", "shortOptions", ".", "containsKey", "(", "s", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Short option -\"", "+", "s", "+", "\" already exists\"", ")", ";", "}", "if", "(", "parent", "!=", "null", "&&", "parent", ".", "shortOptions", ".", "containsKey", "(", "s", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Short option -\"", "+", "s", "+", "\" already exists in parent\"", ")", ";", "}", "shortOptions", ".", "put", "(", "s", ",", "option", ")", ";", "}", "}", "this", ".", "options", ".", "add", "(", "option", ")", ";", "return", "this", ";", "}" ]
Add a command line option. @param option The option to add. @param <O> The base option type. @return The argument argumentParser.
[ "Add", "a", "command", "line", "option", "." ]
dc987485902f1a7d58169c89c61db97425a6226d
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java#L146-L189
155,394
morimekta/utils
console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java
ArgumentParser.add
public <A extends BaseArgument> ArgumentParser add(A arg) { if (arg instanceof BaseOption) { return add((BaseOption) arg); } // No arguments can be added after a sub-command-set. if (arguments.size() > 0 && arguments.get(arguments.size() - 1) instanceof SubCommandSet) { throw new IllegalArgumentException("No arguments can be added after a sub-command set"); } arguments.add(arg); return this; }
java
public <A extends BaseArgument> ArgumentParser add(A arg) { if (arg instanceof BaseOption) { return add((BaseOption) arg); } // No arguments can be added after a sub-command-set. if (arguments.size() > 0 && arguments.get(arguments.size() - 1) instanceof SubCommandSet) { throw new IllegalArgumentException("No arguments can be added after a sub-command set"); } arguments.add(arg); return this; }
[ "public", "<", "A", "extends", "BaseArgument", ">", "ArgumentParser", "add", "(", "A", "arg", ")", "{", "if", "(", "arg", "instanceof", "BaseOption", ")", "{", "return", "add", "(", "(", "BaseOption", ")", "arg", ")", ";", "}", "// No arguments can be added after a sub-command-set.", "if", "(", "arguments", ".", "size", "(", ")", ">", "0", "&&", "arguments", ".", "get", "(", "arguments", ".", "size", "(", ")", "-", "1", ")", "instanceof", "SubCommandSet", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"No arguments can be added after a sub-command set\"", ")", ";", "}", "arguments", ".", "add", "(", "arg", ")", ";", "return", "this", ";", "}" ]
Add a sub-command. @param arg The command to add. @param <A> The base argument type. @return The argument argumentParser.
[ "Add", "a", "sub", "-", "command", "." ]
dc987485902f1a7d58169c89c61db97425a6226d
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java#L198-L210
155,395
morimekta/utils
console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java
ArgumentParser.parse
public void parse(ArgumentList args) { try { parseInternal(args); } catch (ArgumentException e) { if (e.getParser() == null) { e.setParser(this); } throw e; } }
java
public void parse(ArgumentList args) { try { parseInternal(args); } catch (ArgumentException e) { if (e.getParser() == null) { e.setParser(this); } throw e; } }
[ "public", "void", "parse", "(", "ArgumentList", "args", ")", "{", "try", "{", "parseInternal", "(", "args", ")", ";", "}", "catch", "(", "ArgumentException", "e", ")", "{", "if", "(", "e", ".", "getParser", "(", ")", "==", "null", ")", "{", "e", ".", "setParser", "(", "this", ")", ";", "}", "throw", "e", ";", "}", "}" ]
Parse arguments from the main method. @param args The argument list.
[ "Parse", "arguments", "from", "the", "main", "method", "." ]
dc987485902f1a7d58169c89c61db97425a6226d
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java#L226-L235
155,396
morimekta/utils
console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java
ArgumentParser.getSingleLineUsage
public String getSingleLineUsage() { StringBuilder writer = new StringBuilder(); writer.append(program); // first just list up all the unary short opts. StringBuilder sh = new StringBuilder(); // Only include the first short name form the flag. options.stream() .filter(opt -> opt instanceof Flag) .filter(opt -> opt.getShortNames().length() > 0) .forEachOrdered(opt -> sh.append(opt.getShortNames().charAt(0))); if (sh.length() > 0) { writer.append(" [-").append(sh.toString()).append(']'); } for (BaseOption opt : options) { if (opt instanceof Flag && opt.getShortNames().length() > 0) { // already included as short opt. continue; } String usage = opt.getSingleLineUsage(); if (usage != null) { writer.append(' ').append(usage); } } for (BaseArgument arg : arguments) { String usage = arg.getSingleLineUsage(); if (usage != null) { writer.append(' ').append(usage); } } return writer.toString(); }
java
public String getSingleLineUsage() { StringBuilder writer = new StringBuilder(); writer.append(program); // first just list up all the unary short opts. StringBuilder sh = new StringBuilder(); // Only include the first short name form the flag. options.stream() .filter(opt -> opt instanceof Flag) .filter(opt -> opt.getShortNames().length() > 0) .forEachOrdered(opt -> sh.append(opt.getShortNames().charAt(0))); if (sh.length() > 0) { writer.append(" [-").append(sh.toString()).append(']'); } for (BaseOption opt : options) { if (opt instanceof Flag && opt.getShortNames().length() > 0) { // already included as short opt. continue; } String usage = opt.getSingleLineUsage(); if (usage != null) { writer.append(' ').append(usage); } } for (BaseArgument arg : arguments) { String usage = arg.getSingleLineUsage(); if (usage != null) { writer.append(' ').append(usage); } } return writer.toString(); }
[ "public", "String", "getSingleLineUsage", "(", ")", "{", "StringBuilder", "writer", "=", "new", "StringBuilder", "(", ")", ";", "writer", ".", "append", "(", "program", ")", ";", "// first just list up all the unary short opts.", "StringBuilder", "sh", "=", "new", "StringBuilder", "(", ")", ";", "// Only include the first short name form the flag.", "options", ".", "stream", "(", ")", ".", "filter", "(", "opt", "->", "opt", "instanceof", "Flag", ")", ".", "filter", "(", "opt", "->", "opt", ".", "getShortNames", "(", ")", ".", "length", "(", ")", ">", "0", ")", ".", "forEachOrdered", "(", "opt", "->", "sh", ".", "append", "(", "opt", ".", "getShortNames", "(", ")", ".", "charAt", "(", "0", ")", ")", ")", ";", "if", "(", "sh", ".", "length", "(", ")", ">", "0", ")", "{", "writer", ".", "append", "(", "\" [-\"", ")", ".", "append", "(", "sh", ".", "toString", "(", ")", ")", ".", "append", "(", "'", "'", ")", ";", "}", "for", "(", "BaseOption", "opt", ":", "options", ")", "{", "if", "(", "opt", "instanceof", "Flag", "&&", "opt", ".", "getShortNames", "(", ")", ".", "length", "(", ")", ">", "0", ")", "{", "// already included as short opt.", "continue", ";", "}", "String", "usage", "=", "opt", ".", "getSingleLineUsage", "(", ")", ";", "if", "(", "usage", "!=", "null", ")", "{", "writer", ".", "append", "(", "'", "'", ")", ".", "append", "(", "usage", ")", ";", "}", "}", "for", "(", "BaseArgument", "arg", ":", "arguments", ")", "{", "String", "usage", "=", "arg", ".", "getSingleLineUsage", "(", ")", ";", "if", "(", "usage", "!=", "null", ")", "{", "writer", ".", "append", "(", "'", "'", ")", ".", "append", "(", "usage", ")", ";", "}", "}", "return", "writer", ".", "toString", "(", ")", ";", "}" ]
Get the single line usage string for the parser. Contains essentially the line "program options args". @return The single line usage.
[ "Get", "the", "single", "line", "usage", "string", "for", "the", "parser", ".", "Contains", "essentially", "the", "line", "program", "options", "args", "." ]
dc987485902f1a7d58169c89c61db97425a6226d
https://github.com/morimekta/utils/blob/dc987485902f1a7d58169c89c61db97425a6226d/console-util/src/main/java/net/morimekta/console/args/ArgumentParser.java#L436-L470
155,397
grails/grails-gdoc-engine
src/main/java/org/radeox/macro/table/Table.java
Table.addCell
public void addCell(String content) { content = content.trim(); if (content.startsWith("=")) { //Logger.debug("Table.addCell: function found."); if (null == functionOccurences) { functionOccurences = new ArrayList(); } functionOccurences.add(new int[]{indexCol, indexRow}); // function } currentRow.add(content); indexCol++; }
java
public void addCell(String content) { content = content.trim(); if (content.startsWith("=")) { //Logger.debug("Table.addCell: function found."); if (null == functionOccurences) { functionOccurences = new ArrayList(); } functionOccurences.add(new int[]{indexCol, indexRow}); // function } currentRow.add(content); indexCol++; }
[ "public", "void", "addCell", "(", "String", "content", ")", "{", "content", "=", "content", ".", "trim", "(", ")", ";", "if", "(", "content", ".", "startsWith", "(", "\"=\"", ")", ")", "{", "//Logger.debug(\"Table.addCell: function found.\");", "if", "(", "null", "==", "functionOccurences", ")", "{", "functionOccurences", "=", "new", "ArrayList", "(", ")", ";", "}", "functionOccurences", ".", "add", "(", "new", "int", "[", "]", "{", "indexCol", ",", "indexRow", "}", ")", ";", "// function", "}", "currentRow", ".", "add", "(", "content", ")", ";", "indexCol", "++", ";", "}" ]
Add a cell to the current row of the table @param content Content of the cell
[ "Add", "a", "cell", "to", "the", "current", "row", "of", "the", "table" ]
e52aa09eaa61510dc48b27603bd9ea116cd6531a
https://github.com/grails/grails-gdoc-engine/blob/e52aa09eaa61510dc48b27603bd9ea116cd6531a/src/main/java/org/radeox/macro/table/Table.java#L69-L81
155,398
grails/grails-gdoc-engine
src/main/java/org/radeox/macro/table/Table.java
Table.calc
public void calc() { if (null != functionOccurences) { Iterator iterator = functionOccurences.iterator(); while (iterator.hasNext()) { int[] position = (int[]) iterator.next(); String functionString = ((String) getXY(position[0], position[1])).trim(); // better use RegEx String name = functionString.substring(1, functionString.indexOf("(")).trim().toLowerCase(); String range = functionString.substring(functionString.indexOf("(") + 1, functionString.indexOf(")")); int colon = range.indexOf(":"); String start = range.substring(0, colon).trim(); String end = range.substring(colon + 1).trim(); int startX = start.charAt(0) - 'A'; int startY = Integer.parseInt(start.substring(1)) - 1; int endX = end.charAt(0) - 'A'; int endY = Integer.parseInt(end.substring(1)) - 1; // normalize range, start is left top, end is bottom right if (startX > endX) { int tmp = startX; startX = endX; endX = tmp; } if (startY > endY) { int tmp = startY; startY = endY; endY = tmp; } //Logger.debug("Calc: " + position[0] + " " + position[1] + " " + function + " " + start + " " + end); //Logger.debug("Calc: " + startX+","+startY+" - "+endX+","+endY); if (functions.containsKey(name)) { Function function = (Function) functions.get(name); function.execute(this, position[0], position[1], startX,startY,endX,endY); } } } return; }
java
public void calc() { if (null != functionOccurences) { Iterator iterator = functionOccurences.iterator(); while (iterator.hasNext()) { int[] position = (int[]) iterator.next(); String functionString = ((String) getXY(position[0], position[1])).trim(); // better use RegEx String name = functionString.substring(1, functionString.indexOf("(")).trim().toLowerCase(); String range = functionString.substring(functionString.indexOf("(") + 1, functionString.indexOf(")")); int colon = range.indexOf(":"); String start = range.substring(0, colon).trim(); String end = range.substring(colon + 1).trim(); int startX = start.charAt(0) - 'A'; int startY = Integer.parseInt(start.substring(1)) - 1; int endX = end.charAt(0) - 'A'; int endY = Integer.parseInt(end.substring(1)) - 1; // normalize range, start is left top, end is bottom right if (startX > endX) { int tmp = startX; startX = endX; endX = tmp; } if (startY > endY) { int tmp = startY; startY = endY; endY = tmp; } //Logger.debug("Calc: " + position[0] + " " + position[1] + " " + function + " " + start + " " + end); //Logger.debug("Calc: " + startX+","+startY+" - "+endX+","+endY); if (functions.containsKey(name)) { Function function = (Function) functions.get(name); function.execute(this, position[0], position[1], startX,startY,endX,endY); } } } return; }
[ "public", "void", "calc", "(", ")", "{", "if", "(", "null", "!=", "functionOccurences", ")", "{", "Iterator", "iterator", "=", "functionOccurences", ".", "iterator", "(", ")", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "int", "[", "]", "position", "=", "(", "int", "[", "]", ")", "iterator", ".", "next", "(", ")", ";", "String", "functionString", "=", "(", "(", "String", ")", "getXY", "(", "position", "[", "0", "]", ",", "position", "[", "1", "]", ")", ")", ".", "trim", "(", ")", ";", "// better use RegEx", "String", "name", "=", "functionString", ".", "substring", "(", "1", ",", "functionString", ".", "indexOf", "(", "\"(\"", ")", ")", ".", "trim", "(", ")", ".", "toLowerCase", "(", ")", ";", "String", "range", "=", "functionString", ".", "substring", "(", "functionString", ".", "indexOf", "(", "\"(\"", ")", "+", "1", ",", "functionString", ".", "indexOf", "(", "\")\"", ")", ")", ";", "int", "colon", "=", "range", ".", "indexOf", "(", "\":\"", ")", ";", "String", "start", "=", "range", ".", "substring", "(", "0", ",", "colon", ")", ".", "trim", "(", ")", ";", "String", "end", "=", "range", ".", "substring", "(", "colon", "+", "1", ")", ".", "trim", "(", ")", ";", "int", "startX", "=", "start", ".", "charAt", "(", "0", ")", "-", "'", "'", ";", "int", "startY", "=", "Integer", ".", "parseInt", "(", "start", ".", "substring", "(", "1", ")", ")", "-", "1", ";", "int", "endX", "=", "end", ".", "charAt", "(", "0", ")", "-", "'", "'", ";", "int", "endY", "=", "Integer", ".", "parseInt", "(", "end", ".", "substring", "(", "1", ")", ")", "-", "1", ";", "// normalize range, start is left top, end is bottom right", "if", "(", "startX", ">", "endX", ")", "{", "int", "tmp", "=", "startX", ";", "startX", "=", "endX", ";", "endX", "=", "tmp", ";", "}", "if", "(", "startY", ">", "endY", ")", "{", "int", "tmp", "=", "startY", ";", "startY", "=", "endY", ";", "endY", "=", "tmp", ";", "}", "//Logger.debug(\"Calc: \" + position[0] + \" \" + position[1] + \" \" + function + \" \" + start + \" \" + end);", "//Logger.debug(\"Calc: \" + startX+\",\"+startY+\" - \"+endX+\",\"+endY);", "if", "(", "functions", ".", "containsKey", "(", "name", ")", ")", "{", "Function", "function", "=", "(", "Function", ")", "functions", ".", "get", "(", "name", ")", ";", "function", ".", "execute", "(", "this", ",", "position", "[", "0", "]", ",", "position", "[", "1", "]", ",", "startX", ",", "startY", ",", "endX", ",", "endY", ")", ";", "}", "}", "}", "return", ";", "}" ]
Recalculate all cells. Currently does nothing.
[ "Recalculate", "all", "cells", ".", "Currently", "does", "nothing", "." ]
e52aa09eaa61510dc48b27603bd9ea116cd6531a
https://github.com/grails/grails-gdoc-engine/blob/e52aa09eaa61510dc48b27603bd9ea116cd6531a/src/main/java/org/radeox/macro/table/Table.java#L98-L141
155,399
grails/grails-gdoc-engine
src/main/java/org/radeox/macro/table/Table.java
Table.appendTo
public Writer appendTo(Writer writer) throws IOException { writer.write("<table class=\"wiki-table\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">"); List[] outputRows = (List[]) rows.toArray(new List[0]); int rowSize = outputRows.length; boolean odd = true; for (int i = 0; i < rowSize; i++) { writer.write("<tr"); if (i == 0) { writer.write(">"); } else if (odd) { writer.write(" class=\"table-odd\">"); odd = false; } else { writer.write(" class=\"table-even\">"); odd = true; } String[] outputCols = (String[]) outputRows[i].toArray(new String[0]); int colSize = outputCols.length; for (int j = 0; j < colSize; j++) { writer.write(i == 0 ? "<th>" : "<td>"); if (outputCols[j] == null || outputCols[j].trim().length() == 0) { writer.write("&#160;"); } else { writer.write(outputCols[j]); } writer.write(i == 0 ? "</th>" : "</td>"); } writer.write("</tr>"); } writer.write("</table>"); return writer; }
java
public Writer appendTo(Writer writer) throws IOException { writer.write("<table class=\"wiki-table\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\">"); List[] outputRows = (List[]) rows.toArray(new List[0]); int rowSize = outputRows.length; boolean odd = true; for (int i = 0; i < rowSize; i++) { writer.write("<tr"); if (i == 0) { writer.write(">"); } else if (odd) { writer.write(" class=\"table-odd\">"); odd = false; } else { writer.write(" class=\"table-even\">"); odd = true; } String[] outputCols = (String[]) outputRows[i].toArray(new String[0]); int colSize = outputCols.length; for (int j = 0; j < colSize; j++) { writer.write(i == 0 ? "<th>" : "<td>"); if (outputCols[j] == null || outputCols[j].trim().length() == 0) { writer.write("&#160;"); } else { writer.write(outputCols[j]); } writer.write(i == 0 ? "</th>" : "</td>"); } writer.write("</tr>"); } writer.write("</table>"); return writer; }
[ "public", "Writer", "appendTo", "(", "Writer", "writer", ")", "throws", "IOException", "{", "writer", ".", "write", "(", "\"<table class=\\\"wiki-table\\\" cellpadding=\\\"0\\\" cellspacing=\\\"0\\\" border=\\\"0\\\">\"", ")", ";", "List", "[", "]", "outputRows", "=", "(", "List", "[", "]", ")", "rows", ".", "toArray", "(", "new", "List", "[", "0", "]", ")", ";", "int", "rowSize", "=", "outputRows", ".", "length", ";", "boolean", "odd", "=", "true", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "rowSize", ";", "i", "++", ")", "{", "writer", ".", "write", "(", "\"<tr\"", ")", ";", "if", "(", "i", "==", "0", ")", "{", "writer", ".", "write", "(", "\">\"", ")", ";", "}", "else", "if", "(", "odd", ")", "{", "writer", ".", "write", "(", "\" class=\\\"table-odd\\\">\"", ")", ";", "odd", "=", "false", ";", "}", "else", "{", "writer", ".", "write", "(", "\" class=\\\"table-even\\\">\"", ")", ";", "odd", "=", "true", ";", "}", "String", "[", "]", "outputCols", "=", "(", "String", "[", "]", ")", "outputRows", "[", "i", "]", ".", "toArray", "(", "new", "String", "[", "0", "]", ")", ";", "int", "colSize", "=", "outputCols", ".", "length", ";", "for", "(", "int", "j", "=", "0", ";", "j", "<", "colSize", ";", "j", "++", ")", "{", "writer", ".", "write", "(", "i", "==", "0", "?", "\"<th>\"", ":", "\"<td>\"", ")", ";", "if", "(", "outputCols", "[", "j", "]", "==", "null", "||", "outputCols", "[", "j", "]", ".", "trim", "(", ")", ".", "length", "(", ")", "==", "0", ")", "{", "writer", ".", "write", "(", "\"&#160;\"", ")", ";", "}", "else", "{", "writer", ".", "write", "(", "outputCols", "[", "j", "]", ")", ";", "}", "writer", ".", "write", "(", "i", "==", "0", "?", "\"</th>\"", ":", "\"</td>\"", ")", ";", "}", "writer", ".", "write", "(", "\"</tr>\"", ")", ";", "}", "writer", ".", "write", "(", "\"</table>\"", ")", ";", "return", "writer", ";", "}" ]
Serialize table by appending it to a writer. The output format is HTML. @param writer Writer to append the table object to @return writer Writer the table object appended itself to
[ "Serialize", "table", "by", "appending", "it", "to", "a", "writer", ".", "The", "output", "format", "is", "HTML", "." ]
e52aa09eaa61510dc48b27603bd9ea116cd6531a
https://github.com/grails/grails-gdoc-engine/blob/e52aa09eaa61510dc48b27603bd9ea116cd6531a/src/main/java/org/radeox/macro/table/Table.java#L151-L182