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
sequence
docstring
stringlengths
3
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
105
339
3,500
FINRAOS/JTAF-ExtWebDriver
src/main/java/org/finra/jtaf/ewd/impl/DefaultSessionFactory.java
DefaultSessionFactory.removeFolders
private final static void removeFolders(String folder, List<String> folderTemplates, int numberOfDaysToKeepTempFolders) { long dateToRemoveFiledAfter = (new Date()).getTime() - (numberOfDaysToKeepTempFolders * MILLISECONDS_IN_DAY); File tempFolder = new File(folder); File[] folderChildren = tempFolder.listFiles(); if(null == folderChildren) { log.debug("Folder '" + tempFolder.getName() + "' was empty. Nothing to delete"); return; } for (File currentFile : folderChildren) { if (currentFile.isDirectory()) { for (String folderTemplate : folderTemplates) { if (currentFile.getName().contains(folderTemplate) && (currentFile.lastModified() < dateToRemoveFiledAfter)) { try { currentFile.delete(); FileUtils.deleteDirectory(currentFile); log.debug("Folder '" + currentFile.getName() + "' deleted..."); } catch (Exception e) { log.fatal("Error deleting folder '" + currentFile.getName() + "'"); } } } } } }
java
private final static void removeFolders(String folder, List<String> folderTemplates, int numberOfDaysToKeepTempFolders) { long dateToRemoveFiledAfter = (new Date()).getTime() - (numberOfDaysToKeepTempFolders * MILLISECONDS_IN_DAY); File tempFolder = new File(folder); File[] folderChildren = tempFolder.listFiles(); if(null == folderChildren) { log.debug("Folder '" + tempFolder.getName() + "' was empty. Nothing to delete"); return; } for (File currentFile : folderChildren) { if (currentFile.isDirectory()) { for (String folderTemplate : folderTemplates) { if (currentFile.getName().contains(folderTemplate) && (currentFile.lastModified() < dateToRemoveFiledAfter)) { try { currentFile.delete(); FileUtils.deleteDirectory(currentFile); log.debug("Folder '" + currentFile.getName() + "' deleted..."); } catch (Exception e) { log.fatal("Error deleting folder '" + currentFile.getName() + "'"); } } } } } }
[ "private", "final", "static", "void", "removeFolders", "(", "String", "folder", ",", "List", "<", "String", ">", "folderTemplates", ",", "int", "numberOfDaysToKeepTempFolders", ")", "{", "long", "dateToRemoveFiledAfter", "=", "(", "new", "Date", "(", ")", ")", ".", "getTime", "(", ")", "-", "(", "numberOfDaysToKeepTempFolders", "*", "MILLISECONDS_IN_DAY", ")", ";", "File", "tempFolder", "=", "new", "File", "(", "folder", ")", ";", "File", "[", "]", "folderChildren", "=", "tempFolder", ".", "listFiles", "(", ")", ";", "if", "(", "null", "==", "folderChildren", ")", "{", "log", ".", "debug", "(", "\"Folder '\"", "+", "tempFolder", ".", "getName", "(", ")", "+", "\"' was empty. Nothing to delete\"", ")", ";", "return", ";", "}", "for", "(", "File", "currentFile", ":", "folderChildren", ")", "{", "if", "(", "currentFile", ".", "isDirectory", "(", ")", ")", "{", "for", "(", "String", "folderTemplate", ":", "folderTemplates", ")", "{", "if", "(", "currentFile", ".", "getName", "(", ")", ".", "contains", "(", "folderTemplate", ")", "&&", "(", "currentFile", ".", "lastModified", "(", ")", "<", "dateToRemoveFiledAfter", ")", ")", "{", "try", "{", "currentFile", ".", "delete", "(", ")", ";", "FileUtils", ".", "deleteDirectory", "(", "currentFile", ")", ";", "log", ".", "debug", "(", "\"Folder '\"", "+", "currentFile", ".", "getName", "(", ")", "+", "\"' deleted...\"", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "fatal", "(", "\"Error deleting folder '\"", "+", "currentFile", ".", "getName", "(", ")", "+", "\"'\"", ")", ";", "}", "}", "}", "}", "}", "}" ]
This method can be called to remove specific folders or set how long you want to keep the temp information. @param folder which temp folder you want to remove @param folderTemplates the templates of these temp folders @param numberOfDaysToKeepTempFolders how long you want to keep the temp information
[ "This", "method", "can", "be", "called", "to", "remove", "specific", "folders", "or", "set", "how", "long", "you", "want", "to", "keep", "the", "temp", "information", "." ]
78d646def1bf0904f79b19a81df0241e07f2c73a
https://github.com/FINRAOS/JTAF-ExtWebDriver/blob/78d646def1bf0904f79b19a81df0241e07f2c73a/src/main/java/org/finra/jtaf/ewd/impl/DefaultSessionFactory.java#L699-L727
3,501
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/RetryHandler.java
RetryHandler.runChildWithRetry
static void runChildWithRetry(Object runner, final FrameworkMethod method, RunNotifier notifier, int maxRetry) { boolean doRetry = false; Statement statement = invoke(runner, "methodBlock", method); Description description = invoke(runner, "describeChild", method); AtomicInteger count = new AtomicInteger(maxRetry); do { EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); eachNotifier.fireTestStarted(); try { statement.evaluate(); doRetry = false; } catch (AssumptionViolatedException thrown) { doRetry = doRetry(method, thrown, count); if (doRetry) { description = RetriedTest.proxyFor(description, thrown); eachNotifier.fireTestIgnored(); } else { eachNotifier.addFailedAssumption(thrown); } } catch (Throwable thrown) { doRetry = doRetry(method, thrown, count); if (doRetry) { description = RetriedTest.proxyFor(description, thrown); eachNotifier.fireTestIgnored(); } else { eachNotifier.addFailure(thrown); } } finally { eachNotifier.fireTestFinished(); } } while (doRetry); }
java
static void runChildWithRetry(Object runner, final FrameworkMethod method, RunNotifier notifier, int maxRetry) { boolean doRetry = false; Statement statement = invoke(runner, "methodBlock", method); Description description = invoke(runner, "describeChild", method); AtomicInteger count = new AtomicInteger(maxRetry); do { EachTestNotifier eachNotifier = new EachTestNotifier(notifier, description); eachNotifier.fireTestStarted(); try { statement.evaluate(); doRetry = false; } catch (AssumptionViolatedException thrown) { doRetry = doRetry(method, thrown, count); if (doRetry) { description = RetriedTest.proxyFor(description, thrown); eachNotifier.fireTestIgnored(); } else { eachNotifier.addFailedAssumption(thrown); } } catch (Throwable thrown) { doRetry = doRetry(method, thrown, count); if (doRetry) { description = RetriedTest.proxyFor(description, thrown); eachNotifier.fireTestIgnored(); } else { eachNotifier.addFailure(thrown); } } finally { eachNotifier.fireTestFinished(); } } while (doRetry); }
[ "static", "void", "runChildWithRetry", "(", "Object", "runner", ",", "final", "FrameworkMethod", "method", ",", "RunNotifier", "notifier", ",", "int", "maxRetry", ")", "{", "boolean", "doRetry", "=", "false", ";", "Statement", "statement", "=", "invoke", "(", "runner", ",", "\"methodBlock\"", ",", "method", ")", ";", "Description", "description", "=", "invoke", "(", "runner", ",", "\"describeChild\"", ",", "method", ")", ";", "AtomicInteger", "count", "=", "new", "AtomicInteger", "(", "maxRetry", ")", ";", "do", "{", "EachTestNotifier", "eachNotifier", "=", "new", "EachTestNotifier", "(", "notifier", ",", "description", ")", ";", "eachNotifier", ".", "fireTestStarted", "(", ")", ";", "try", "{", "statement", ".", "evaluate", "(", ")", ";", "doRetry", "=", "false", ";", "}", "catch", "(", "AssumptionViolatedException", "thrown", ")", "{", "doRetry", "=", "doRetry", "(", "method", ",", "thrown", ",", "count", ")", ";", "if", "(", "doRetry", ")", "{", "description", "=", "RetriedTest", ".", "proxyFor", "(", "description", ",", "thrown", ")", ";", "eachNotifier", ".", "fireTestIgnored", "(", ")", ";", "}", "else", "{", "eachNotifier", ".", "addFailedAssumption", "(", "thrown", ")", ";", "}", "}", "catch", "(", "Throwable", "thrown", ")", "{", "doRetry", "=", "doRetry", "(", "method", ",", "thrown", ",", "count", ")", ";", "if", "(", "doRetry", ")", "{", "description", "=", "RetriedTest", ".", "proxyFor", "(", "description", ",", "thrown", ")", ";", "eachNotifier", ".", "fireTestIgnored", "(", ")", ";", "}", "else", "{", "eachNotifier", ".", "addFailure", "(", "thrown", ")", ";", "}", "}", "finally", "{", "eachNotifier", ".", "fireTestFinished", "(", ")", ";", "}", "}", "while", "(", "doRetry", ")", ";", "}" ]
Run the specified method, retrying on failure. @param runner JUnit test runner @param method test method to be run @param notifier run notifier through which events are published @param maxRetry maximum number of retry attempts
[ "Run", "the", "specified", "method", "retrying", "on", "failure", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/RetryHandler.java#L43-L76
3,502
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/RetryHandler.java
RetryHandler.doRetry
static boolean doRetry(FrameworkMethod method, Throwable thrown, AtomicInteger retryCounter) { boolean doRetry = false; if ((retryCounter.decrementAndGet() > -1) && isRetriable(method, thrown)) { LOGGER.warn("### RETRY ### {}", method); doRetry = true; } return doRetry; }
java
static boolean doRetry(FrameworkMethod method, Throwable thrown, AtomicInteger retryCounter) { boolean doRetry = false; if ((retryCounter.decrementAndGet() > -1) && isRetriable(method, thrown)) { LOGGER.warn("### RETRY ### {}", method); doRetry = true; } return doRetry; }
[ "static", "boolean", "doRetry", "(", "FrameworkMethod", "method", ",", "Throwable", "thrown", ",", "AtomicInteger", "retryCounter", ")", "{", "boolean", "doRetry", "=", "false", ";", "if", "(", "(", "retryCounter", ".", "decrementAndGet", "(", ")", ">", "-", "1", ")", "&&", "isRetriable", "(", "method", ",", "thrown", ")", ")", "{", "LOGGER", ".", "warn", "(", "\"### RETRY ### {}\"", ",", "method", ")", ";", "doRetry", "=", "true", ";", "}", "return", "doRetry", ";", "}" ]
Determine if the indicated failure should be retried. @param method failed test method @param thrown exception for this failed test @param retryCounter retry counter (remaining attempts) @return {@code true} if failed test should be retried; otherwise {@code false}
[ "Determine", "if", "the", "indicated", "failure", "should", "be", "retried", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/RetryHandler.java#L86-L93
3,503
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/RetryHandler.java
RetryHandler.isRetriable
static boolean isRetriable(final FrameworkMethod method, final Throwable thrown) { synchronized(retryAnalyzerLoader) { for (JUnitRetryAnalyzer analyzer : retryAnalyzerLoader) { if (analyzer.retry(method, thrown)) { return true; } } } return false; }
java
static boolean isRetriable(final FrameworkMethod method, final Throwable thrown) { synchronized(retryAnalyzerLoader) { for (JUnitRetryAnalyzer analyzer : retryAnalyzerLoader) { if (analyzer.retry(method, thrown)) { return true; } } } return false; }
[ "static", "boolean", "isRetriable", "(", "final", "FrameworkMethod", "method", ",", "final", "Throwable", "thrown", ")", "{", "synchronized", "(", "retryAnalyzerLoader", ")", "{", "for", "(", "JUnitRetryAnalyzer", "analyzer", ":", "retryAnalyzerLoader", ")", "{", "if", "(", "analyzer", ".", "retry", "(", "method", ",", "thrown", ")", ")", "{", "return", "true", ";", "}", "}", "}", "return", "false", ";", "}" ]
Determine if the specified failed test should be retried. @param method failed test method @param thrown exception for this failed test @return {@code true} if test should be retried; otherwise {@code false}
[ "Determine", "if", "the", "specified", "failed", "test", "should", "be", "retried", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/RetryHandler.java#L129-L138
3,504
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java
LifecycleHooks.describeChild
public static Description describeChild(Object target, Object child) { Object runner = getRunnerForTarget(target); return invoke(runner, "describeChild", child); }
java
public static Description describeChild(Object target, Object child) { Object runner = getRunnerForTarget(target); return invoke(runner, "describeChild", child); }
[ "public", "static", "Description", "describeChild", "(", "Object", "target", ",", "Object", "child", ")", "{", "Object", "runner", "=", "getRunnerForTarget", "(", "target", ")", ";", "return", "invoke", "(", "runner", ",", "\"describeChild\"", ",", "child", ")", ";", "}" ]
Get the description of the indicated child object from the runner for the specified test class instance. @param target test class instance @param child child object @return {@link Description} object for the indicated child
[ "Get", "the", "description", "of", "the", "indicated", "child", "object", "from", "the", "runner", "for", "the", "specified", "test", "class", "instance", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java#L208-L211
3,505
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java
LifecycleHooks.getInstanceClass
public static Class<?> getInstanceClass(Object instance) { Class<?> clazz = instance.getClass(); return (instance instanceof Hooked) ? clazz.getSuperclass() : clazz; }
java
public static Class<?> getInstanceClass(Object instance) { Class<?> clazz = instance.getClass(); return (instance instanceof Hooked) ? clazz.getSuperclass() : clazz; }
[ "public", "static", "Class", "<", "?", ">", "getInstanceClass", "(", "Object", "instance", ")", "{", "Class", "<", "?", ">", "clazz", "=", "instance", ".", "getClass", "(", ")", ";", "return", "(", "instance", "instanceof", "Hooked", ")", "?", "clazz", ".", "getSuperclass", "(", ")", ":", "clazz", ";", "}" ]
Get class of specified test class instance. @param instance test class instance @return class of test class instance
[ "Get", "class", "of", "specified", "test", "class", "instance", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java#L219-L222
3,506
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java
LifecycleHooks.getSubclassName
static String getSubclassName(Object testObj) { Class<?> testClass = testObj.getClass(); String testClassName = testClass.getSimpleName(); String testPackageName = testClass.getPackage().getName(); ReportsDirectory constant = ReportsDirectory.fromObject(testObj); switch (constant) { case FAILSAFE_2: case FAILSAFE_3: case SUREFIRE_2: case SUREFIRE_3: case SUREFIRE_4: return testPackageName + ".Hooked" + testClassName; default: return testClass.getCanonicalName() + "Hooked"; } }
java
static String getSubclassName(Object testObj) { Class<?> testClass = testObj.getClass(); String testClassName = testClass.getSimpleName(); String testPackageName = testClass.getPackage().getName(); ReportsDirectory constant = ReportsDirectory.fromObject(testObj); switch (constant) { case FAILSAFE_2: case FAILSAFE_3: case SUREFIRE_2: case SUREFIRE_3: case SUREFIRE_4: return testPackageName + ".Hooked" + testClassName; default: return testClass.getCanonicalName() + "Hooked"; } }
[ "static", "String", "getSubclassName", "(", "Object", "testObj", ")", "{", "Class", "<", "?", ">", "testClass", "=", "testObj", ".", "getClass", "(", ")", ";", "String", "testClassName", "=", "testClass", ".", "getSimpleName", "(", ")", ";", "String", "testPackageName", "=", "testClass", ".", "getPackage", "(", ")", ".", "getName", "(", ")", ";", "ReportsDirectory", "constant", "=", "ReportsDirectory", ".", "fromObject", "(", "testObj", ")", ";", "switch", "(", "constant", ")", "{", "case", "FAILSAFE_2", ":", "case", "FAILSAFE_3", ":", "case", "SUREFIRE_2", ":", "case", "SUREFIRE_3", ":", "case", "SUREFIRE_4", ":", "return", "testPackageName", "+", "\".Hooked\"", "+", "testClassName", ";", "default", ":", "return", "testClass", ".", "getCanonicalName", "(", ")", "+", "\"Hooked\"", ";", "}", "}" ]
Get fully-qualified name to use for hooked test class. @param testObj test class object being hooked @return fully-qualified name for hooked subclass
[ "Get", "fully", "-", "qualified", "name", "to", "use", "for", "hooked", "test", "class", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java#L230-L248
3,507
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java
LifecycleHooks.invoke
@SuppressWarnings("unchecked") static <T> T invoke(Object target, String methodName, Object... parameters) { Class<?>[] parameterTypes = new Class<?>[parameters.length]; for (int i = 0; i < parameters.length; i++) { parameterTypes[i] = parameters[i].getClass(); } Throwable thrown = null; for (Class<?> current = target.getClass(); current != null; current = current.getSuperclass()) { try { Method method = current.getDeclaredMethod(methodName, parameterTypes); method.setAccessible(true); return (T) method.invoke(target, parameters); } catch (NoSuchMethodException e) { thrown = e; } catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { thrown = e; break; } } throw UncheckedThrow.throwUnchecked(thrown); }
java
@SuppressWarnings("unchecked") static <T> T invoke(Object target, String methodName, Object... parameters) { Class<?>[] parameterTypes = new Class<?>[parameters.length]; for (int i = 0; i < parameters.length; i++) { parameterTypes[i] = parameters[i].getClass(); } Throwable thrown = null; for (Class<?> current = target.getClass(); current != null; current = current.getSuperclass()) { try { Method method = current.getDeclaredMethod(methodName, parameterTypes); method.setAccessible(true); return (T) method.invoke(target, parameters); } catch (NoSuchMethodException e) { thrown = e; } catch (SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { thrown = e; break; } } throw UncheckedThrow.throwUnchecked(thrown); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "static", "<", "T", ">", "T", "invoke", "(", "Object", "target", ",", "String", "methodName", ",", "Object", "...", "parameters", ")", "{", "Class", "<", "?", ">", "[", "]", "parameterTypes", "=", "new", "Class", "<", "?", ">", "[", "parameters", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "parameters", ".", "length", ";", "i", "++", ")", "{", "parameterTypes", "[", "i", "]", "=", "parameters", "[", "i", "]", ".", "getClass", "(", ")", ";", "}", "Throwable", "thrown", "=", "null", ";", "for", "(", "Class", "<", "?", ">", "current", "=", "target", ".", "getClass", "(", ")", ";", "current", "!=", "null", ";", "current", "=", "current", ".", "getSuperclass", "(", ")", ")", "{", "try", "{", "Method", "method", "=", "current", ".", "getDeclaredMethod", "(", "methodName", ",", "parameterTypes", ")", ";", "method", ".", "setAccessible", "(", "true", ")", ";", "return", "(", "T", ")", "method", ".", "invoke", "(", "target", ",", "parameters", ")", ";", "}", "catch", "(", "NoSuchMethodException", "e", ")", "{", "thrown", "=", "e", ";", "}", "catch", "(", "SecurityException", "|", "IllegalAccessException", "|", "IllegalArgumentException", "|", "InvocationTargetException", "e", ")", "{", "thrown", "=", "e", ";", "break", ";", "}", "}", "throw", "UncheckedThrow", ".", "throwUnchecked", "(", "thrown", ")", ";", "}" ]
Invoke the named method with the specified parameters on the specified target object. @param <T> method return type @param target target object @param methodName name of the desired method @param parameters parameters for the method invocation @return result of method invocation
[ "Invoke", "the", "named", "method", "with", "the", "specified", "parameters", "on", "the", "specified", "target", "object", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java#L259-L282
3,508
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java
LifecycleHooks.getDeclaredField
static Field getDeclaredField(Object target, String name) throws NoSuchFieldException { Throwable thrown = null; for (Class<?> current = target.getClass(); current != null; current = current.getSuperclass()) { try { return current.getDeclaredField(name); } catch (NoSuchFieldException e) { thrown = e; } catch (SecurityException e) { thrown = e; break; } } throw UncheckedThrow.throwUnchecked(thrown); }
java
static Field getDeclaredField(Object target, String name) throws NoSuchFieldException { Throwable thrown = null; for (Class<?> current = target.getClass(); current != null; current = current.getSuperclass()) { try { return current.getDeclaredField(name); } catch (NoSuchFieldException e) { thrown = e; } catch (SecurityException e) { thrown = e; break; } } throw UncheckedThrow.throwUnchecked(thrown); }
[ "static", "Field", "getDeclaredField", "(", "Object", "target", ",", "String", "name", ")", "throws", "NoSuchFieldException", "{", "Throwable", "thrown", "=", "null", ";", "for", "(", "Class", "<", "?", ">", "current", "=", "target", ".", "getClass", "(", ")", ";", "current", "!=", "null", ";", "current", "=", "current", ".", "getSuperclass", "(", ")", ")", "{", "try", "{", "return", "current", ".", "getDeclaredField", "(", "name", ")", ";", "}", "catch", "(", "NoSuchFieldException", "e", ")", "{", "thrown", "=", "e", ";", "}", "catch", "(", "SecurityException", "e", ")", "{", "thrown", "=", "e", ";", "break", ";", "}", "}", "throw", "UncheckedThrow", ".", "throwUnchecked", "(", "thrown", ")", ";", "}" ]
Get the specified field of the supplied object. @param target target object @param name field name @return {@link Field} object for the requested field @throws NoSuchFieldException if a field with the specified name is not found @throws SecurityException if the request is denied
[ "Get", "the", "specified", "field", "of", "the", "supplied", "object", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java#L293-L307
3,509
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java
LifecycleHooks.getFieldValue
@SuppressWarnings("unchecked") static <T> T getFieldValue(Object target, String name) throws IllegalAccessException, NoSuchFieldException, SecurityException { Field field = getDeclaredField(target, name); field.setAccessible(true); return (T) field.get(target); }
java
@SuppressWarnings("unchecked") static <T> T getFieldValue(Object target, String name) throws IllegalAccessException, NoSuchFieldException, SecurityException { Field field = getDeclaredField(target, name); field.setAccessible(true); return (T) field.get(target); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "static", "<", "T", ">", "T", "getFieldValue", "(", "Object", "target", ",", "String", "name", ")", "throws", "IllegalAccessException", ",", "NoSuchFieldException", ",", "SecurityException", "{", "Field", "field", "=", "getDeclaredField", "(", "target", ",", "name", ")", ";", "field", ".", "setAccessible", "(", "true", ")", ";", "return", "(", "T", ")", "field", ".", "get", "(", "target", ")", ";", "}" ]
Get the value of the specified field from the supplied object. @param <T> field value type @param target target object @param name field name @return {@code anything} - the value of the specified field in the supplied object @throws IllegalAccessException if the {@code Field} object is enforcing access control for an inaccessible field @throws NoSuchFieldException if a field with the specified name is not found @throws SecurityException if the request is denied
[ "Get", "the", "value", "of", "the", "specified", "field", "from", "the", "supplied", "object", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java#L320-L325
3,510
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java
LifecycleHooks.setFieldValue
static void setFieldValue(Object target, String name, Object value) throws IllegalAccessException, NoSuchFieldException, SecurityException { Field field = getDeclaredField(target, name); field.setAccessible(true); field.set(target, value); }
java
static void setFieldValue(Object target, String name, Object value) throws IllegalAccessException, NoSuchFieldException, SecurityException { Field field = getDeclaredField(target, name); field.setAccessible(true); field.set(target, value); }
[ "static", "void", "setFieldValue", "(", "Object", "target", ",", "String", "name", ",", "Object", "value", ")", "throws", "IllegalAccessException", ",", "NoSuchFieldException", ",", "SecurityException", "{", "Field", "field", "=", "getDeclaredField", "(", "target", ",", "name", ")", ";", "field", ".", "setAccessible", "(", "true", ")", ";", "field", ".", "set", "(", "target", ",", "value", ")", ";", "}" ]
Set the value of the specified field of the supplied object. @param target target object @param name field name @param value value to set in the specified field of the supplied object @throws IllegalAccessException if the {@code Field} object is enforcing access control for an inaccessible field @throws NoSuchFieldException if a field with the specified name is not found @throws SecurityException if the request is denied
[ "Set", "the", "value", "of", "the", "specified", "field", "of", "the", "supplied", "object", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/LifecycleHooks.java#L337-L341
3,511
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/RuleChainWalker.java
RuleChainWalker.getAttachedRule
@SuppressWarnings("unchecked") public static <T extends TestRule> Optional<T> getAttachedRule(RuleChain ruleChain, Class<T> ruleType) { for (TestRule rule : getRuleList(ruleChain)) { if (rule.getClass() == ruleType) { return Optional.of((T) rule); } } return Optional.absent(); }
java
@SuppressWarnings("unchecked") public static <T extends TestRule> Optional<T> getAttachedRule(RuleChain ruleChain, Class<T> ruleType) { for (TestRule rule : getRuleList(ruleChain)) { if (rule.getClass() == ruleType) { return Optional.of((T) rule); } } return Optional.absent(); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", "extends", "TestRule", ">", "Optional", "<", "T", ">", "getAttachedRule", "(", "RuleChain", "ruleChain", ",", "Class", "<", "T", ">", "ruleType", ")", "{", "for", "(", "TestRule", "rule", ":", "getRuleList", "(", "ruleChain", ")", ")", "{", "if", "(", "rule", ".", "getClass", "(", ")", "==", "ruleType", ")", "{", "return", "Optional", ".", "of", "(", "(", "T", ")", "rule", ")", ";", "}", "}", "return", "Optional", ".", "absent", "(", ")", ";", "}" ]
Get reference to an instance of the specified test rule type on the supplied rule chain. @param <T> test rule type @param ruleChain rule chain to be walked @param ruleType test rule type @return optional test rule instance
[ "Get", "reference", "to", "an", "instance", "of", "the", "specified", "test", "rule", "type", "on", "the", "supplied", "rule", "chain", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/RuleChainWalker.java#L31-L39
3,512
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/RuleChainWalker.java
RuleChainWalker.getRuleList
@SuppressWarnings("unchecked") private static List<TestRule> getRuleList(RuleChain ruleChain) { Field ruleChainList; try { String fieldName = JUnitConfig.getConfig().getString(JUnitSettings.RULE_CHAIN_LIST.key()); ruleChainList = RuleChain.class.getDeclaredField(fieldName); ruleChainList.setAccessible(true); return (List<TestRule>) ruleChainList.get(ruleChain); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw UncheckedThrow.throwUnchecked(e); } }
java
@SuppressWarnings("unchecked") private static List<TestRule> getRuleList(RuleChain ruleChain) { Field ruleChainList; try { String fieldName = JUnitConfig.getConfig().getString(JUnitSettings.RULE_CHAIN_LIST.key()); ruleChainList = RuleChain.class.getDeclaredField(fieldName); ruleChainList.setAccessible(true); return (List<TestRule>) ruleChainList.get(ruleChain); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { throw UncheckedThrow.throwUnchecked(e); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "static", "List", "<", "TestRule", ">", "getRuleList", "(", "RuleChain", "ruleChain", ")", "{", "Field", "ruleChainList", ";", "try", "{", "String", "fieldName", "=", "JUnitConfig", ".", "getConfig", "(", ")", ".", "getString", "(", "JUnitSettings", ".", "RULE_CHAIN_LIST", ".", "key", "(", ")", ")", ";", "ruleChainList", "=", "RuleChain", ".", "class", ".", "getDeclaredField", "(", "fieldName", ")", ";", "ruleChainList", ".", "setAccessible", "(", "true", ")", ";", "return", "(", "List", "<", "TestRule", ">", ")", "ruleChainList", ".", "get", "(", "ruleChain", ")", ";", "}", "catch", "(", "NoSuchFieldException", "|", "SecurityException", "|", "IllegalArgumentException", "|", "IllegalAccessException", "e", ")", "{", "throw", "UncheckedThrow", ".", "throwUnchecked", "(", "e", ")", ";", "}", "}" ]
Get the list of test rules from the specified rule chain. @param ruleChain rule chain @return list of test rules
[ "Get", "the", "list", "of", "test", "rules", "from", "the", "specified", "rule", "chain", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/RuleChainWalker.java#L47-L58
3,513
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/RunChild.java
RunChild.applyTimeout
private static void applyTimeout(FrameworkMethod method) { // if default test timeout is defined if (LifecycleHooks.getConfig().containsKey(JUnitSettings.TEST_TIMEOUT.key())) { // get default test timeout long defaultTimeout = LifecycleHooks.getConfig().getLong(JUnitSettings.TEST_TIMEOUT.key()); // get @Test annotation Test annotation = method.getAnnotation(Test.class); // if annotation declared and current timeout is less than default if ((annotation != null) && (annotation.timeout() < defaultTimeout)) { // set test timeout interval MutableTest.proxyFor(method.getMethod()).setTimeout(defaultTimeout); } } }
java
private static void applyTimeout(FrameworkMethod method) { // if default test timeout is defined if (LifecycleHooks.getConfig().containsKey(JUnitSettings.TEST_TIMEOUT.key())) { // get default test timeout long defaultTimeout = LifecycleHooks.getConfig().getLong(JUnitSettings.TEST_TIMEOUT.key()); // get @Test annotation Test annotation = method.getAnnotation(Test.class); // if annotation declared and current timeout is less than default if ((annotation != null) && (annotation.timeout() < defaultTimeout)) { // set test timeout interval MutableTest.proxyFor(method.getMethod()).setTimeout(defaultTimeout); } } }
[ "private", "static", "void", "applyTimeout", "(", "FrameworkMethod", "method", ")", "{", "// if default test timeout is defined\r", "if", "(", "LifecycleHooks", ".", "getConfig", "(", ")", ".", "containsKey", "(", "JUnitSettings", ".", "TEST_TIMEOUT", ".", "key", "(", ")", ")", ")", "{", "// get default test timeout\r", "long", "defaultTimeout", "=", "LifecycleHooks", ".", "getConfig", "(", ")", ".", "getLong", "(", "JUnitSettings", ".", "TEST_TIMEOUT", ".", "key", "(", ")", ")", ";", "// get @Test annotation\r", "Test", "annotation", "=", "method", ".", "getAnnotation", "(", "Test", ".", "class", ")", ";", "// if annotation declared and current timeout is less than default\r", "if", "(", "(", "annotation", "!=", "null", ")", "&&", "(", "annotation", ".", "timeout", "(", ")", "<", "defaultTimeout", ")", ")", "{", "// set test timeout interval\r", "MutableTest", ".", "proxyFor", "(", "method", ".", "getMethod", "(", ")", ")", ".", "setTimeout", "(", "defaultTimeout", ")", ";", "}", "}", "}" ]
If configured for default test timeout, apply the timeout value to the specified framework method if it doesn't already specify a longer timeout interval. @param method {@link FrameworkMethod} object
[ "If", "configured", "for", "default", "test", "timeout", "apply", "the", "timeout", "value", "to", "the", "specified", "framework", "method", "if", "it", "doesn", "t", "already", "specify", "a", "longer", "timeout", "interval", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/RunChild.java#L93-L106
3,514
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/ArtifactCollector.java
ArtifactCollector.captureArtifact
public Optional<Path> captureArtifact(Throwable reason) { if (! provider.canGetArtifact(getInstance())) { return Optional.absent(); } byte[] artifact = provider.getArtifact(getInstance(), reason); if ((artifact == null) || (artifact.length == 0)) { return Optional.absent(); } Path collectionPath = getCollectionPath(); if (!collectionPath.toFile().exists()) { try { Files.createDirectories(collectionPath); } catch (IOException e) { if (provider.getLogger() != null) { String messageTemplate = "Unable to create collection directory ({}); no artifact was captured"; provider.getLogger().warn(messageTemplate, collectionPath, e); } return Optional.absent(); } } Path artifactPath; try { artifactPath = PathUtils.getNextPath( collectionPath, getArtifactBaseName(), provider.getArtifactExtension()); } catch (IOException e) { if (provider.getLogger() != null) { provider.getLogger().warn("Unable to get output path; no artifact was captured", e); } return Optional.absent(); } try { if (provider.getLogger() != null) { provider.getLogger().info("Saving captured artifact to ({}).", artifactPath); } Files.write(artifactPath, artifact); } catch (IOException e) { if (provider.getLogger() != null) { provider.getLogger().warn("I/O error saving to ({}); no artifact was captured", artifactPath, e); } return Optional.absent(); } recordArtifactPath(artifactPath); return Optional.of(artifactPath); }
java
public Optional<Path> captureArtifact(Throwable reason) { if (! provider.canGetArtifact(getInstance())) { return Optional.absent(); } byte[] artifact = provider.getArtifact(getInstance(), reason); if ((artifact == null) || (artifact.length == 0)) { return Optional.absent(); } Path collectionPath = getCollectionPath(); if (!collectionPath.toFile().exists()) { try { Files.createDirectories(collectionPath); } catch (IOException e) { if (provider.getLogger() != null) { String messageTemplate = "Unable to create collection directory ({}); no artifact was captured"; provider.getLogger().warn(messageTemplate, collectionPath, e); } return Optional.absent(); } } Path artifactPath; try { artifactPath = PathUtils.getNextPath( collectionPath, getArtifactBaseName(), provider.getArtifactExtension()); } catch (IOException e) { if (provider.getLogger() != null) { provider.getLogger().warn("Unable to get output path; no artifact was captured", e); } return Optional.absent(); } try { if (provider.getLogger() != null) { provider.getLogger().info("Saving captured artifact to ({}).", artifactPath); } Files.write(artifactPath, artifact); } catch (IOException e) { if (provider.getLogger() != null) { provider.getLogger().warn("I/O error saving to ({}); no artifact was captured", artifactPath, e); } return Optional.absent(); } recordArtifactPath(artifactPath); return Optional.of(artifactPath); }
[ "public", "Optional", "<", "Path", ">", "captureArtifact", "(", "Throwable", "reason", ")", "{", "if", "(", "!", "provider", ".", "canGetArtifact", "(", "getInstance", "(", ")", ")", ")", "{", "return", "Optional", ".", "absent", "(", ")", ";", "}", "byte", "[", "]", "artifact", "=", "provider", ".", "getArtifact", "(", "getInstance", "(", ")", ",", "reason", ")", ";", "if", "(", "(", "artifact", "==", "null", ")", "||", "(", "artifact", ".", "length", "==", "0", ")", ")", "{", "return", "Optional", ".", "absent", "(", ")", ";", "}", "Path", "collectionPath", "=", "getCollectionPath", "(", ")", ";", "if", "(", "!", "collectionPath", ".", "toFile", "(", ")", ".", "exists", "(", ")", ")", "{", "try", "{", "Files", ".", "createDirectories", "(", "collectionPath", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "if", "(", "provider", ".", "getLogger", "(", ")", "!=", "null", ")", "{", "String", "messageTemplate", "=", "\"Unable to create collection directory ({}); no artifact was captured\"", ";", "provider", ".", "getLogger", "(", ")", ".", "warn", "(", "messageTemplate", ",", "collectionPath", ",", "e", ")", ";", "}", "return", "Optional", ".", "absent", "(", ")", ";", "}", "}", "Path", "artifactPath", ";", "try", "{", "artifactPath", "=", "PathUtils", ".", "getNextPath", "(", "collectionPath", ",", "getArtifactBaseName", "(", ")", ",", "provider", ".", "getArtifactExtension", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "if", "(", "provider", ".", "getLogger", "(", ")", "!=", "null", ")", "{", "provider", ".", "getLogger", "(", ")", ".", "warn", "(", "\"Unable to get output path; no artifact was captured\"", ",", "e", ")", ";", "}", "return", "Optional", ".", "absent", "(", ")", ";", "}", "try", "{", "if", "(", "provider", ".", "getLogger", "(", ")", "!=", "null", ")", "{", "provider", ".", "getLogger", "(", ")", ".", "info", "(", "\"Saving captured artifact to ({}).\"", ",", "artifactPath", ")", ";", "}", "Files", ".", "write", "(", "artifactPath", ",", "artifact", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "if", "(", "provider", ".", "getLogger", "(", ")", "!=", "null", ")", "{", "provider", ".", "getLogger", "(", ")", ".", "warn", "(", "\"I/O error saving to ({}); no artifact was captured\"", ",", "artifactPath", ",", "e", ")", ";", "}", "return", "Optional", ".", "absent", "(", ")", ";", "}", "recordArtifactPath", "(", "artifactPath", ")", ";", "return", "Optional", ".", "of", "(", "artifactPath", ")", ";", "}" ]
Capture artifact from the current test result context. @param reason impetus for capture request; may be 'null' @return (optional) path at which the captured artifact was stored
[ "Capture", "artifact", "from", "the", "current", "test", "result", "context", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/ArtifactCollector.java#L69-L119
3,515
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/ArtifactCollector.java
ArtifactCollector.getCollectionPath
private Path getCollectionPath() { Path collectionPath = PathUtils.ReportsDirectory.getPathForObject(getInstance()); return collectionPath.resolve(provider.getArtifactPath(getInstance())); }
java
private Path getCollectionPath() { Path collectionPath = PathUtils.ReportsDirectory.getPathForObject(getInstance()); return collectionPath.resolve(provider.getArtifactPath(getInstance())); }
[ "private", "Path", "getCollectionPath", "(", ")", "{", "Path", "collectionPath", "=", "PathUtils", ".", "ReportsDirectory", ".", "getPathForObject", "(", "getInstance", "(", ")", ")", ";", "return", "collectionPath", ".", "resolve", "(", "provider", ".", "getArtifactPath", "(", "getInstance", "(", ")", ")", ")", ";", "}" ]
Get path of directory at which to store artifacts. @return path of artifact storage directory
[ "Get", "path", "of", "directory", "at", "which", "to", "store", "artifacts", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/ArtifactCollector.java#L126-L129
3,516
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/ArtifactCollector.java
ArtifactCollector.retrieveArtifactPaths
public Optional<List<Path>> retrieveArtifactPaths() { if (artifactPaths.isEmpty()) { return Optional.absent(); } else { return Optional.of(artifactPaths); } }
java
public Optional<List<Path>> retrieveArtifactPaths() { if (artifactPaths.isEmpty()) { return Optional.absent(); } else { return Optional.of(artifactPaths); } }
[ "public", "Optional", "<", "List", "<", "Path", ">", ">", "retrieveArtifactPaths", "(", ")", "{", "if", "(", "artifactPaths", ".", "isEmpty", "(", ")", ")", "{", "return", "Optional", ".", "absent", "(", ")", ";", "}", "else", "{", "return", "Optional", ".", "of", "(", "artifactPaths", ")", ";", "}", "}" ]
Retrieve the paths of artifacts that were stored in the indicated test result. @return (optional) list of artifact paths
[ "Retrieve", "the", "paths", "of", "artifacts", "that", "were", "stored", "in", "the", "indicated", "test", "result", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/ArtifactCollector.java#L164-L170
3,517
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/ArtifactCollector.java
ArtifactCollector.getWatcher
@SuppressWarnings("unchecked") public static <S extends ArtifactCollector<? extends ArtifactType>> Optional<S> getWatcher(Description description, Class<S> watcherType) { List<ArtifactCollector<? extends ArtifactType>> watcherList = watcherMap.get(description); if (watcherList != null) { for (ArtifactCollector<? extends ArtifactType> watcher : watcherList) { if (watcher.getClass() == watcherType) { return Optional.of((S) watcher); } } } return Optional.absent(); }
java
@SuppressWarnings("unchecked") public static <S extends ArtifactCollector<? extends ArtifactType>> Optional<S> getWatcher(Description description, Class<S> watcherType) { List<ArtifactCollector<? extends ArtifactType>> watcherList = watcherMap.get(description); if (watcherList != null) { for (ArtifactCollector<? extends ArtifactType> watcher : watcherList) { if (watcher.getClass() == watcherType) { return Optional.of((S) watcher); } } } return Optional.absent(); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "S", "extends", "ArtifactCollector", "<", "?", "extends", "ArtifactType", ">", ">", "Optional", "<", "S", ">", "getWatcher", "(", "Description", "description", ",", "Class", "<", "S", ">", "watcherType", ")", "{", "List", "<", "ArtifactCollector", "<", "?", "extends", "ArtifactType", ">", ">", "watcherList", "=", "watcherMap", ".", "get", "(", "description", ")", ";", "if", "(", "watcherList", "!=", "null", ")", "{", "for", "(", "ArtifactCollector", "<", "?", "extends", "ArtifactType", ">", "watcher", ":", "watcherList", ")", "{", "if", "(", "watcher", ".", "getClass", "(", ")", "==", "watcherType", ")", "{", "return", "Optional", ".", "of", "(", "(", "S", ")", "watcher", ")", ";", "}", "}", "}", "return", "Optional", ".", "absent", "(", ")", ";", "}" ]
Get reference to an instance of the specified watcher type associated with the described method. @param <S> type-specific artifact collector class @param description JUnit method description object @param watcherType watcher type @return optional watcher instance
[ "Get", "reference", "to", "an", "instance", "of", "the", "specified", "watcher", "type", "associated", "with", "the", "described", "method", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/ArtifactCollector.java#L189-L201
3,518
Nordstrom/JUnit-Foundation
src/main/java/com/nordstrom/automation/junit/RunReflectiveCall.java
RunReflectiveCall.isParticleMethod
public static boolean isParticleMethod(FrameworkMethod method) { return ((null != method.getAnnotation(Test.class)) || (null != method.getAnnotation(Before.class)) || (null != method.getAnnotation(After.class)) || (null != method.getAnnotation(BeforeClass.class)) || (null != method.getAnnotation(AfterClass.class))); }
java
public static boolean isParticleMethod(FrameworkMethod method) { return ((null != method.getAnnotation(Test.class)) || (null != method.getAnnotation(Before.class)) || (null != method.getAnnotation(After.class)) || (null != method.getAnnotation(BeforeClass.class)) || (null != method.getAnnotation(AfterClass.class))); }
[ "public", "static", "boolean", "isParticleMethod", "(", "FrameworkMethod", "method", ")", "{", "return", "(", "(", "null", "!=", "method", ".", "getAnnotation", "(", "Test", ".", "class", ")", ")", "||", "(", "null", "!=", "method", ".", "getAnnotation", "(", "Before", ".", "class", ")", ")", "||", "(", "null", "!=", "method", ".", "getAnnotation", "(", "After", ".", "class", ")", ")", "||", "(", "null", "!=", "method", ".", "getAnnotation", "(", "BeforeClass", ".", "class", ")", ")", "||", "(", "null", "!=", "method", ".", "getAnnotation", "(", "AfterClass", ".", "class", ")", ")", ")", ";", "}" ]
Determine if the specified method is a test or configuration method. @param method method whose type is in question @return {@code true} if specified method is a particle; otherwise {@code false}
[ "Determine", "if", "the", "specified", "method", "is", "a", "test", "or", "configuration", "method", "." ]
f24d91f8677d262c27d18ef29ed633eaac717be5
https://github.com/Nordstrom/JUnit-Foundation/blob/f24d91f8677d262c27d18ef29ed633eaac717be5/src/main/java/com/nordstrom/automation/junit/RunReflectiveCall.java#L144-L150
3,519
Red5/red5-websocket
src/main/java/org/red5/net/websocket/model/Packet.java
Packet.build
public static Packet build(IoBuffer buffer) { if (buffer.hasArray()) { return new Packet(buffer.array()); } byte[] buf = new byte[buffer.remaining()]; buffer.get(buf); return new Packet(buf); }
java
public static Packet build(IoBuffer buffer) { if (buffer.hasArray()) { return new Packet(buffer.array()); } byte[] buf = new byte[buffer.remaining()]; buffer.get(buf); return new Packet(buf); }
[ "public", "static", "Packet", "build", "(", "IoBuffer", "buffer", ")", "{", "if", "(", "buffer", ".", "hasArray", "(", ")", ")", "{", "return", "new", "Packet", "(", "buffer", ".", "array", "(", ")", ")", ";", "}", "byte", "[", "]", "buf", "=", "new", "byte", "[", "buffer", ".", "remaining", "(", ")", "]", ";", "buffer", ".", "get", "(", "buf", ")", ";", "return", "new", "Packet", "(", "buf", ")", ";", "}" ]
Builds the packet which just wraps the IoBuffer. @param buffer @return packet
[ "Builds", "the", "packet", "which", "just", "wraps", "the", "IoBuffer", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/model/Packet.java#L79-L86
3,520
Red5/red5-websocket
src/main/java/org/red5/net/websocket/model/WSMessage.java
WSMessage.addPayload
public void addPayload(IoBuffer additionalPayload) { if (payload == null) { payload = IoBuffer.allocate(additionalPayload.remaining()); payload.setAutoExpand(true); } this.payload.put(additionalPayload); }
java
public void addPayload(IoBuffer additionalPayload) { if (payload == null) { payload = IoBuffer.allocate(additionalPayload.remaining()); payload.setAutoExpand(true); } this.payload.put(additionalPayload); }
[ "public", "void", "addPayload", "(", "IoBuffer", "additionalPayload", ")", "{", "if", "(", "payload", "==", "null", ")", "{", "payload", "=", "IoBuffer", ".", "allocate", "(", "additionalPayload", ".", "remaining", "(", ")", ")", ";", "payload", ".", "setAutoExpand", "(", "true", ")", ";", "}", "this", ".", "payload", ".", "put", "(", "additionalPayload", ")", ";", "}" ]
Adds additional payload data. @param additionalPayload
[ "Adds", "additional", "payload", "data", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/model/WSMessage.java#L95-L101
3,521
Red5/red5-websocket
src/main/java/org/red5/net/websocket/codec/WebSocketDecoder.java
WebSocketDecoder.buildHandshakeResponse
private HandshakeResponse buildHandshakeResponse(WebSocketConnection conn, String clientKey) throws WebSocketException { if (log.isDebugEnabled()) { log.debug("buildHandshakeResponse: {} client key: {}", conn, clientKey); } byte[] accept; try { // performs the accept creation routine from RFC6455 @see <a href="http://tools.ietf.org/html/rfc6455">RFC6455</a> // concatenate the key and magic string, then SHA1 hash and base64 encode MessageDigest md = MessageDigest.getInstance("SHA1"); accept = Base64.encode(md.digest((clientKey + Constants.WEBSOCKET_MAGIC_STRING).getBytes())); } catch (NoSuchAlgorithmException e) { throw new WebSocketException("Algorithm is missing"); } // make up reply data... IoBuffer buf = IoBuffer.allocate(308); buf.setAutoExpand(true); buf.put("HTTP/1.1 101 Switching Protocols".getBytes()); buf.put(Constants.CRLF); buf.put("Upgrade: websocket".getBytes()); buf.put(Constants.CRLF); buf.put("Connection: Upgrade".getBytes()); buf.put(Constants.CRLF); buf.put("Server: Red5".getBytes()); buf.put(Constants.CRLF); buf.put("Sec-WebSocket-Version-Server: 13".getBytes()); buf.put(Constants.CRLF); buf.put(String.format("Sec-WebSocket-Origin: %s", conn.getOrigin()).getBytes()); buf.put(Constants.CRLF); buf.put(String.format("Sec-WebSocket-Location: %s", conn.getHost()).getBytes()); buf.put(Constants.CRLF); // send back extensions if enabled if (conn.hasExtensions()) { buf.put(String.format("Sec-WebSocket-Extensions: %s", conn.getExtensionsAsString()).getBytes()); buf.put(Constants.CRLF); } // send back protocol if enabled if (conn.hasProtocol()) { buf.put(String.format("Sec-WebSocket-Protocol: %s", conn.getProtocol()).getBytes()); buf.put(Constants.CRLF); } buf.put(String.format("Sec-WebSocket-Accept: %s", new String(accept)).getBytes()); buf.put(Constants.CRLF); buf.put(Constants.CRLF); // if any bytes follow this crlf, the follow-up data will be corrupted if (log.isTraceEnabled()) { log.trace("Handshake response size: {}", buf.limit()); } return new HandshakeResponse(buf); }
java
private HandshakeResponse buildHandshakeResponse(WebSocketConnection conn, String clientKey) throws WebSocketException { if (log.isDebugEnabled()) { log.debug("buildHandshakeResponse: {} client key: {}", conn, clientKey); } byte[] accept; try { // performs the accept creation routine from RFC6455 @see <a href="http://tools.ietf.org/html/rfc6455">RFC6455</a> // concatenate the key and magic string, then SHA1 hash and base64 encode MessageDigest md = MessageDigest.getInstance("SHA1"); accept = Base64.encode(md.digest((clientKey + Constants.WEBSOCKET_MAGIC_STRING).getBytes())); } catch (NoSuchAlgorithmException e) { throw new WebSocketException("Algorithm is missing"); } // make up reply data... IoBuffer buf = IoBuffer.allocate(308); buf.setAutoExpand(true); buf.put("HTTP/1.1 101 Switching Protocols".getBytes()); buf.put(Constants.CRLF); buf.put("Upgrade: websocket".getBytes()); buf.put(Constants.CRLF); buf.put("Connection: Upgrade".getBytes()); buf.put(Constants.CRLF); buf.put("Server: Red5".getBytes()); buf.put(Constants.CRLF); buf.put("Sec-WebSocket-Version-Server: 13".getBytes()); buf.put(Constants.CRLF); buf.put(String.format("Sec-WebSocket-Origin: %s", conn.getOrigin()).getBytes()); buf.put(Constants.CRLF); buf.put(String.format("Sec-WebSocket-Location: %s", conn.getHost()).getBytes()); buf.put(Constants.CRLF); // send back extensions if enabled if (conn.hasExtensions()) { buf.put(String.format("Sec-WebSocket-Extensions: %s", conn.getExtensionsAsString()).getBytes()); buf.put(Constants.CRLF); } // send back protocol if enabled if (conn.hasProtocol()) { buf.put(String.format("Sec-WebSocket-Protocol: %s", conn.getProtocol()).getBytes()); buf.put(Constants.CRLF); } buf.put(String.format("Sec-WebSocket-Accept: %s", new String(accept)).getBytes()); buf.put(Constants.CRLF); buf.put(Constants.CRLF); // if any bytes follow this crlf, the follow-up data will be corrupted if (log.isTraceEnabled()) { log.trace("Handshake response size: {}", buf.limit()); } return new HandshakeResponse(buf); }
[ "private", "HandshakeResponse", "buildHandshakeResponse", "(", "WebSocketConnection", "conn", ",", "String", "clientKey", ")", "throws", "WebSocketException", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"buildHandshakeResponse: {} client key: {}\"", ",", "conn", ",", "clientKey", ")", ";", "}", "byte", "[", "]", "accept", ";", "try", "{", "// performs the accept creation routine from RFC6455 @see <a href=\"http://tools.ietf.org/html/rfc6455\">RFC6455</a>", "// concatenate the key and magic string, then SHA1 hash and base64 encode", "MessageDigest", "md", "=", "MessageDigest", ".", "getInstance", "(", "\"SHA1\"", ")", ";", "accept", "=", "Base64", ".", "encode", "(", "md", ".", "digest", "(", "(", "clientKey", "+", "Constants", ".", "WEBSOCKET_MAGIC_STRING", ")", ".", "getBytes", "(", ")", ")", ")", ";", "}", "catch", "(", "NoSuchAlgorithmException", "e", ")", "{", "throw", "new", "WebSocketException", "(", "\"Algorithm is missing\"", ")", ";", "}", "// make up reply data...", "IoBuffer", "buf", "=", "IoBuffer", ".", "allocate", "(", "308", ")", ";", "buf", ".", "setAutoExpand", "(", "true", ")", ";", "buf", ".", "put", "(", "\"HTTP/1.1 101 Switching Protocols\"", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "buf", ".", "put", "(", "\"Upgrade: websocket\"", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "buf", ".", "put", "(", "\"Connection: Upgrade\"", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "buf", ".", "put", "(", "\"Server: Red5\"", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "buf", ".", "put", "(", "\"Sec-WebSocket-Version-Server: 13\"", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "buf", ".", "put", "(", "String", ".", "format", "(", "\"Sec-WebSocket-Origin: %s\"", ",", "conn", ".", "getOrigin", "(", ")", ")", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "buf", ".", "put", "(", "String", ".", "format", "(", "\"Sec-WebSocket-Location: %s\"", ",", "conn", ".", "getHost", "(", ")", ")", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "// send back extensions if enabled", "if", "(", "conn", ".", "hasExtensions", "(", ")", ")", "{", "buf", ".", "put", "(", "String", ".", "format", "(", "\"Sec-WebSocket-Extensions: %s\"", ",", "conn", ".", "getExtensionsAsString", "(", ")", ")", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "}", "// send back protocol if enabled", "if", "(", "conn", ".", "hasProtocol", "(", ")", ")", "{", "buf", ".", "put", "(", "String", ".", "format", "(", "\"Sec-WebSocket-Protocol: %s\"", ",", "conn", ".", "getProtocol", "(", ")", ")", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "}", "buf", ".", "put", "(", "String", ".", "format", "(", "\"Sec-WebSocket-Accept: %s\"", ",", "new", "String", "(", "accept", ")", ")", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "// if any bytes follow this crlf, the follow-up data will be corrupted", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"Handshake response size: {}\"", ",", "buf", ".", "limit", "(", ")", ")", ";", "}", "return", "new", "HandshakeResponse", "(", "buf", ")", ";", "}" ]
Build a handshake response based on the given client key. @param clientKey @return response @throws WebSocketException
[ "Build", "a", "handshake", "response", "based", "on", "the", "given", "client", "key", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/codec/WebSocketDecoder.java#L390-L438
3,522
Red5/red5-websocket
src/main/java/org/red5/net/websocket/codec/WebSocketDecoder.java
WebSocketDecoder.build400Response
private HandshakeResponse build400Response(WebSocketConnection conn) throws WebSocketException { if (log.isDebugEnabled()) { log.debug("build400Response: {}", conn); } // make up reply data... IoBuffer buf = IoBuffer.allocate(32); buf.setAutoExpand(true); buf.put("HTTP/1.1 400 Bad Request".getBytes()); buf.put(Constants.CRLF); buf.put("Sec-WebSocket-Version-Server: 13".getBytes()); buf.put(Constants.CRLF); buf.put(Constants.CRLF); if (log.isTraceEnabled()) { log.trace("Handshake error response size: {}", buf.limit()); } return new HandshakeResponse(buf); }
java
private HandshakeResponse build400Response(WebSocketConnection conn) throws WebSocketException { if (log.isDebugEnabled()) { log.debug("build400Response: {}", conn); } // make up reply data... IoBuffer buf = IoBuffer.allocate(32); buf.setAutoExpand(true); buf.put("HTTP/1.1 400 Bad Request".getBytes()); buf.put(Constants.CRLF); buf.put("Sec-WebSocket-Version-Server: 13".getBytes()); buf.put(Constants.CRLF); buf.put(Constants.CRLF); if (log.isTraceEnabled()) { log.trace("Handshake error response size: {}", buf.limit()); } return new HandshakeResponse(buf); }
[ "private", "HandshakeResponse", "build400Response", "(", "WebSocketConnection", "conn", ")", "throws", "WebSocketException", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"build400Response: {}\"", ",", "conn", ")", ";", "}", "// make up reply data...", "IoBuffer", "buf", "=", "IoBuffer", ".", "allocate", "(", "32", ")", ";", "buf", ".", "setAutoExpand", "(", "true", ")", ";", "buf", ".", "put", "(", "\"HTTP/1.1 400 Bad Request\"", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "buf", ".", "put", "(", "\"Sec-WebSocket-Version-Server: 13\"", ".", "getBytes", "(", ")", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "buf", ".", "put", "(", "Constants", ".", "CRLF", ")", ";", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"Handshake error response size: {}\"", ",", "buf", ".", "limit", "(", ")", ")", ";", "}", "return", "new", "HandshakeResponse", "(", "buf", ")", ";", "}" ]
Build an HTTP 400 "Bad Request" response. @return response @throws WebSocketException
[ "Build", "an", "HTTP", "400", "Bad", "Request", "response", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/codec/WebSocketDecoder.java#L446-L462
3,523
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketConnection.java
WebSocketConnection.receive
public void receive(WSMessage message) { log.trace("receive message"); if (isConnected()) { WebSocketPlugin plugin = (WebSocketPlugin) PluginRegistry.getPlugin("WebSocketPlugin"); Optional<WebSocketScopeManager> optional = Optional.ofNullable((WebSocketScopeManager) session.getAttribute(Constants.MANAGER)); WebSocketScopeManager manager = optional.isPresent() ? optional.get() : plugin.getManager(path); WebSocketScope scope = manager.getScope(path); scope.onMessage(message); } else { log.warn("Not connected"); } }
java
public void receive(WSMessage message) { log.trace("receive message"); if (isConnected()) { WebSocketPlugin plugin = (WebSocketPlugin) PluginRegistry.getPlugin("WebSocketPlugin"); Optional<WebSocketScopeManager> optional = Optional.ofNullable((WebSocketScopeManager) session.getAttribute(Constants.MANAGER)); WebSocketScopeManager manager = optional.isPresent() ? optional.get() : plugin.getManager(path); WebSocketScope scope = manager.getScope(path); scope.onMessage(message); } else { log.warn("Not connected"); } }
[ "public", "void", "receive", "(", "WSMessage", "message", ")", "{", "log", ".", "trace", "(", "\"receive message\"", ")", ";", "if", "(", "isConnected", "(", ")", ")", "{", "WebSocketPlugin", "plugin", "=", "(", "WebSocketPlugin", ")", "PluginRegistry", ".", "getPlugin", "(", "\"WebSocketPlugin\"", ")", ";", "Optional", "<", "WebSocketScopeManager", ">", "optional", "=", "Optional", ".", "ofNullable", "(", "(", "WebSocketScopeManager", ")", "session", ".", "getAttribute", "(", "Constants", ".", "MANAGER", ")", ")", ";", "WebSocketScopeManager", "manager", "=", "optional", ".", "isPresent", "(", ")", "?", "optional", ".", "get", "(", ")", ":", "plugin", ".", "getManager", "(", "path", ")", ";", "WebSocketScope", "scope", "=", "manager", ".", "getScope", "(", "path", ")", ";", "scope", ".", "onMessage", "(", "message", ")", ";", "}", "else", "{", "log", ".", "warn", "(", "\"Not connected\"", ")", ";", "}", "}" ]
Receive data from a client. @param message
[ "Receive", "data", "from", "a", "client", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketConnection.java#L147-L158
3,524
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketConnection.java
WebSocketConnection.sendHandshakeResponse
public void sendHandshakeResponse(HandshakeResponse wsResponse) { log.debug("Writing handshake on session: {}", session.getId()); // create write future handshakeWriteFuture = session.write(wsResponse); handshakeWriteFuture.addListener(new IoFutureListener<WriteFuture>() { @Override public void operationComplete(WriteFuture future) { IoSession sess = future.getSession(); if (future.isWritten()) { // handshake is finished log.debug("Handshake write success! {}", sess.getId()); // set completed flag sess.setAttribute(Constants.HANDSHAKE_COMPLETE); // set connected state on ws connection if (connected.compareAndSet(false, true)) { try { // send queued packets queue.forEach(entry -> { sess.write(entry); queue.remove(entry); }); } catch (Exception e) { log.warn("Exception draining queued packets on session: {}", sess.getId(), e); } } } else { log.warn("Handshake write failed from: {} to: {}", sess.getLocalAddress(), sess.getRemoteAddress()); } } }); }
java
public void sendHandshakeResponse(HandshakeResponse wsResponse) { log.debug("Writing handshake on session: {}", session.getId()); // create write future handshakeWriteFuture = session.write(wsResponse); handshakeWriteFuture.addListener(new IoFutureListener<WriteFuture>() { @Override public void operationComplete(WriteFuture future) { IoSession sess = future.getSession(); if (future.isWritten()) { // handshake is finished log.debug("Handshake write success! {}", sess.getId()); // set completed flag sess.setAttribute(Constants.HANDSHAKE_COMPLETE); // set connected state on ws connection if (connected.compareAndSet(false, true)) { try { // send queued packets queue.forEach(entry -> { sess.write(entry); queue.remove(entry); }); } catch (Exception e) { log.warn("Exception draining queued packets on session: {}", sess.getId(), e); } } } else { log.warn("Handshake write failed from: {} to: {}", sess.getLocalAddress(), sess.getRemoteAddress()); } } }); }
[ "public", "void", "sendHandshakeResponse", "(", "HandshakeResponse", "wsResponse", ")", "{", "log", ".", "debug", "(", "\"Writing handshake on session: {}\"", ",", "session", ".", "getId", "(", ")", ")", ";", "// create write future", "handshakeWriteFuture", "=", "session", ".", "write", "(", "wsResponse", ")", ";", "handshakeWriteFuture", ".", "addListener", "(", "new", "IoFutureListener", "<", "WriteFuture", ">", "(", ")", "{", "@", "Override", "public", "void", "operationComplete", "(", "WriteFuture", "future", ")", "{", "IoSession", "sess", "=", "future", ".", "getSession", "(", ")", ";", "if", "(", "future", ".", "isWritten", "(", ")", ")", "{", "// handshake is finished", "log", ".", "debug", "(", "\"Handshake write success! {}\"", ",", "sess", ".", "getId", "(", ")", ")", ";", "// set completed flag", "sess", ".", "setAttribute", "(", "Constants", ".", "HANDSHAKE_COMPLETE", ")", ";", "// set connected state on ws connection", "if", "(", "connected", ".", "compareAndSet", "(", "false", ",", "true", ")", ")", "{", "try", "{", "// send queued packets", "queue", ".", "forEach", "(", "entry", "->", "{", "sess", ".", "write", "(", "entry", ")", ";", "queue", ".", "remove", "(", "entry", ")", ";", "}", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "warn", "(", "\"Exception draining queued packets on session: {}\"", ",", "sess", ".", "getId", "(", ")", ",", "e", ")", ";", "}", "}", "}", "else", "{", "log", ".", "warn", "(", "\"Handshake write failed from: {} to: {}\"", ",", "sess", ".", "getLocalAddress", "(", ")", ",", "sess", ".", "getRemoteAddress", "(", ")", ")", ";", "}", "}", "}", ")", ";", "}" ]
Sends the handshake response. @param wsResponse
[ "Sends", "the", "handshake", "response", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketConnection.java#L165-L197
3,525
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketConnection.java
WebSocketConnection.send
public void send(Packet packet) { if (log.isTraceEnabled()) { log.trace("send packet: {}", packet); } // no handshake flag, queue the packet if (session.containsAttribute(Constants.HANDSHAKE_COMPLETE)) { try { // clear any queued items first queue.forEach(entry -> { session.write(entry); queue.remove(entry); }); } catch (Exception e) { log.warn("Exception draining queued packets on session: {}", session.getId(), e); } // process the incoming packet session.write(packet); } else { if (handshakeWriteFuture != null) { log.warn("Handshake is not complete yet on session: {} written? {}", session.getId(), handshakeWriteFuture.isWritten(), handshakeWriteFuture.getException()); } else { log.warn("Handshake is not complete yet on session: {}", session.getId()); } // not queuing pings MessageType type = packet.getType(); if (type != MessageType.PING && type != MessageType.PONG) { log.info("Placing {} message in session: {} queue", type, session.getId()); queue.offer(packet); } } }
java
public void send(Packet packet) { if (log.isTraceEnabled()) { log.trace("send packet: {}", packet); } // no handshake flag, queue the packet if (session.containsAttribute(Constants.HANDSHAKE_COMPLETE)) { try { // clear any queued items first queue.forEach(entry -> { session.write(entry); queue.remove(entry); }); } catch (Exception e) { log.warn("Exception draining queued packets on session: {}", session.getId(), e); } // process the incoming packet session.write(packet); } else { if (handshakeWriteFuture != null) { log.warn("Handshake is not complete yet on session: {} written? {}", session.getId(), handshakeWriteFuture.isWritten(), handshakeWriteFuture.getException()); } else { log.warn("Handshake is not complete yet on session: {}", session.getId()); } // not queuing pings MessageType type = packet.getType(); if (type != MessageType.PING && type != MessageType.PONG) { log.info("Placing {} message in session: {} queue", type, session.getId()); queue.offer(packet); } } }
[ "public", "void", "send", "(", "Packet", "packet", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"send packet: {}\"", ",", "packet", ")", ";", "}", "// no handshake flag, queue the packet", "if", "(", "session", ".", "containsAttribute", "(", "Constants", ".", "HANDSHAKE_COMPLETE", ")", ")", "{", "try", "{", "// clear any queued items first", "queue", ".", "forEach", "(", "entry", "->", "{", "session", ".", "write", "(", "entry", ")", ";", "queue", ".", "remove", "(", "entry", ")", ";", "}", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "warn", "(", "\"Exception draining queued packets on session: {}\"", ",", "session", ".", "getId", "(", ")", ",", "e", ")", ";", "}", "// process the incoming packet", "session", ".", "write", "(", "packet", ")", ";", "}", "else", "{", "if", "(", "handshakeWriteFuture", "!=", "null", ")", "{", "log", ".", "warn", "(", "\"Handshake is not complete yet on session: {} written? {}\"", ",", "session", ".", "getId", "(", ")", ",", "handshakeWriteFuture", ".", "isWritten", "(", ")", ",", "handshakeWriteFuture", ".", "getException", "(", ")", ")", ";", "}", "else", "{", "log", ".", "warn", "(", "\"Handshake is not complete yet on session: {}\"", ",", "session", ".", "getId", "(", ")", ")", ";", "}", "// not queuing pings", "MessageType", "type", "=", "packet", ".", "getType", "(", ")", ";", "if", "(", "type", "!=", "MessageType", ".", "PING", "&&", "type", "!=", "MessageType", ".", "PONG", ")", "{", "log", ".", "info", "(", "\"Placing {} message in session: {} queue\"", ",", "type", ",", "session", ".", "getId", "(", ")", ")", ";", "queue", ".", "offer", "(", "packet", ")", ";", "}", "}", "}" ]
Sends WebSocket packet to the client. @param packet
[ "Sends", "WebSocket", "packet", "to", "the", "client", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketConnection.java#L204-L234
3,526
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketConnection.java
WebSocketConnection.send
public void send(String data) throws UnsupportedEncodingException { log.trace("send message: {}", data); // process the incoming string if (StringUtils.isNotBlank(data)) { send(Packet.build(data.getBytes("UTF8"), MessageType.TEXT)); } else { throw new UnsupportedEncodingException("Cannot send a null string"); } }
java
public void send(String data) throws UnsupportedEncodingException { log.trace("send message: {}", data); // process the incoming string if (StringUtils.isNotBlank(data)) { send(Packet.build(data.getBytes("UTF8"), MessageType.TEXT)); } else { throw new UnsupportedEncodingException("Cannot send a null string"); } }
[ "public", "void", "send", "(", "String", "data", ")", "throws", "UnsupportedEncodingException", "{", "log", ".", "trace", "(", "\"send message: {}\"", ",", "data", ")", ";", "// process the incoming string", "if", "(", "StringUtils", ".", "isNotBlank", "(", "data", ")", ")", "{", "send", "(", "Packet", ".", "build", "(", "data", ".", "getBytes", "(", "\"UTF8\"", ")", ",", "MessageType", ".", "TEXT", ")", ")", ";", "}", "else", "{", "throw", "new", "UnsupportedEncodingException", "(", "\"Cannot send a null string\"", ")", ";", "}", "}" ]
Sends text to the client. @param data string data @throws UnsupportedEncodingException
[ "Sends", "text", "to", "the", "client", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketConnection.java#L243-L251
3,527
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketConnection.java
WebSocketConnection.send
public void send(byte[] buf) { if (log.isTraceEnabled()) { log.trace("send binary: {}", Arrays.toString(buf)); } // send the incoming bytes send(Packet.build(buf)); }
java
public void send(byte[] buf) { if (log.isTraceEnabled()) { log.trace("send binary: {}", Arrays.toString(buf)); } // send the incoming bytes send(Packet.build(buf)); }
[ "public", "void", "send", "(", "byte", "[", "]", "buf", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"send binary: {}\"", ",", "Arrays", ".", "toString", "(", "buf", ")", ")", ";", "}", "// send the incoming bytes", "send", "(", "Packet", ".", "build", "(", "buf", ")", ")", ";", "}" ]
Sends binary data to the client. @param buf
[ "Sends", "binary", "data", "to", "the", "client", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketConnection.java#L258-L264
3,528
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketConnection.java
WebSocketConnection.sendPing
public void sendPing(byte[] buf) { if (log.isTraceEnabled()) { log.trace("send ping: {}", buf); } // send ping send(Packet.build(buf, MessageType.PING)); }
java
public void sendPing(byte[] buf) { if (log.isTraceEnabled()) { log.trace("send ping: {}", buf); } // send ping send(Packet.build(buf, MessageType.PING)); }
[ "public", "void", "sendPing", "(", "byte", "[", "]", "buf", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"send ping: {}\"", ",", "buf", ")", ";", "}", "// send ping", "send", "(", "Packet", ".", "build", "(", "buf", ",", "MessageType", ".", "PING", ")", ")", ";", "}" ]
Sends a ping to the client. @param buf
[ "Sends", "a", "ping", "to", "the", "client", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketConnection.java#L271-L277
3,529
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketConnection.java
WebSocketConnection.sendPong
public void sendPong(byte[] buf) { if (log.isTraceEnabled()) { log.trace("send pong: {}", buf); } // send pong send(Packet.build(buf, MessageType.PONG)); }
java
public void sendPong(byte[] buf) { if (log.isTraceEnabled()) { log.trace("send pong: {}", buf); } // send pong send(Packet.build(buf, MessageType.PONG)); }
[ "public", "void", "sendPong", "(", "byte", "[", "]", "buf", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"send pong: {}\"", ",", "buf", ")", ";", "}", "// send pong", "send", "(", "Packet", ".", "build", "(", "buf", ",", "MessageType", ".", "PONG", ")", ")", ";", "}" ]
Sends a pong back to the client; normally in response to a ping. @param buf
[ "Sends", "a", "pong", "back", "to", "the", "client", ";", "normally", "in", "response", "to", "a", "ping", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketConnection.java#L284-L290
3,530
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketConnection.java
WebSocketConnection.close
public void close(int statusCode, HandshakeResponse errResponse) { log.warn("Closing connection with status: {}", statusCode); // remove handshake flag session.removeAttribute(Constants.HANDSHAKE_COMPLETE); // clear the delay queue queue.clear(); // send http error response session.write(errResponse); // whether to attempt a nice close or a forceful one if (WebSocketTransport.isNiceClose()) { // now send close packet with error code IoBuffer buf = IoBuffer.allocate(16); buf.setAutoExpand(true); // all errors except 403 will use 1002 buf.putUnsigned((short) statusCode); try { if (statusCode == 1008) { // if its a 403 forbidden buf.put("Policy Violation".getBytes("UTF8")); } else { buf.put("Protocol error".getBytes("UTF8")); } } catch (Exception e) { // shouldnt be any text encoding issues... } buf.flip(); byte[] errBytes = new byte[buf.remaining()]; buf.get(errBytes); // construct the packet Packet packet = Packet.build(errBytes, MessageType.CLOSE); WriteFuture writeFuture = session.write(packet); writeFuture.addListener(new IoFutureListener<WriteFuture>() { @Override public void operationComplete(WriteFuture future) { if (future.isWritten()) { log.debug("Close message written"); // only set on success for now to skip boolean check later session.setAttribute(Constants.STATUS_CLOSE_WRITTEN, Boolean.TRUE); } future.removeListener(this); } }); // adjust close routine to allow for flushing CloseFuture closeFuture = session.closeOnFlush(); closeFuture.addListener(new IoFutureListener<CloseFuture>() { public void operationComplete(CloseFuture future) { if (future.isClosed()) { log.debug("Connection is closed"); } else { log.debug("Connection is not yet closed"); } future.removeListener(this); } }); } else { // force close CloseFuture closeFuture = session.closeNow(); closeFuture.addListener(new IoFutureListener<CloseFuture>() { public void operationComplete(CloseFuture future) { if (future.isClosed()) { log.debug("Connection is closed"); } else { log.debug("Connection is not yet closed"); } future.removeListener(this); } }); } log.debug("Close complete"); }
java
public void close(int statusCode, HandshakeResponse errResponse) { log.warn("Closing connection with status: {}", statusCode); // remove handshake flag session.removeAttribute(Constants.HANDSHAKE_COMPLETE); // clear the delay queue queue.clear(); // send http error response session.write(errResponse); // whether to attempt a nice close or a forceful one if (WebSocketTransport.isNiceClose()) { // now send close packet with error code IoBuffer buf = IoBuffer.allocate(16); buf.setAutoExpand(true); // all errors except 403 will use 1002 buf.putUnsigned((short) statusCode); try { if (statusCode == 1008) { // if its a 403 forbidden buf.put("Policy Violation".getBytes("UTF8")); } else { buf.put("Protocol error".getBytes("UTF8")); } } catch (Exception e) { // shouldnt be any text encoding issues... } buf.flip(); byte[] errBytes = new byte[buf.remaining()]; buf.get(errBytes); // construct the packet Packet packet = Packet.build(errBytes, MessageType.CLOSE); WriteFuture writeFuture = session.write(packet); writeFuture.addListener(new IoFutureListener<WriteFuture>() { @Override public void operationComplete(WriteFuture future) { if (future.isWritten()) { log.debug("Close message written"); // only set on success for now to skip boolean check later session.setAttribute(Constants.STATUS_CLOSE_WRITTEN, Boolean.TRUE); } future.removeListener(this); } }); // adjust close routine to allow for flushing CloseFuture closeFuture = session.closeOnFlush(); closeFuture.addListener(new IoFutureListener<CloseFuture>() { public void operationComplete(CloseFuture future) { if (future.isClosed()) { log.debug("Connection is closed"); } else { log.debug("Connection is not yet closed"); } future.removeListener(this); } }); } else { // force close CloseFuture closeFuture = session.closeNow(); closeFuture.addListener(new IoFutureListener<CloseFuture>() { public void operationComplete(CloseFuture future) { if (future.isClosed()) { log.debug("Connection is closed"); } else { log.debug("Connection is not yet closed"); } future.removeListener(this); } }); } log.debug("Close complete"); }
[ "public", "void", "close", "(", "int", "statusCode", ",", "HandshakeResponse", "errResponse", ")", "{", "log", ".", "warn", "(", "\"Closing connection with status: {}\"", ",", "statusCode", ")", ";", "// remove handshake flag", "session", ".", "removeAttribute", "(", "Constants", ".", "HANDSHAKE_COMPLETE", ")", ";", "// clear the delay queue", "queue", ".", "clear", "(", ")", ";", "// send http error response", "session", ".", "write", "(", "errResponse", ")", ";", "// whether to attempt a nice close or a forceful one", "if", "(", "WebSocketTransport", ".", "isNiceClose", "(", ")", ")", "{", "// now send close packet with error code", "IoBuffer", "buf", "=", "IoBuffer", ".", "allocate", "(", "16", ")", ";", "buf", ".", "setAutoExpand", "(", "true", ")", ";", "// all errors except 403 will use 1002", "buf", ".", "putUnsigned", "(", "(", "short", ")", "statusCode", ")", ";", "try", "{", "if", "(", "statusCode", "==", "1008", ")", "{", "// if its a 403 forbidden", "buf", ".", "put", "(", "\"Policy Violation\"", ".", "getBytes", "(", "\"UTF8\"", ")", ")", ";", "}", "else", "{", "buf", ".", "put", "(", "\"Protocol error\"", ".", "getBytes", "(", "\"UTF8\"", ")", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "// shouldnt be any text encoding issues...", "}", "buf", ".", "flip", "(", ")", ";", "byte", "[", "]", "errBytes", "=", "new", "byte", "[", "buf", ".", "remaining", "(", ")", "]", ";", "buf", ".", "get", "(", "errBytes", ")", ";", "// construct the packet", "Packet", "packet", "=", "Packet", ".", "build", "(", "errBytes", ",", "MessageType", ".", "CLOSE", ")", ";", "WriteFuture", "writeFuture", "=", "session", ".", "write", "(", "packet", ")", ";", "writeFuture", ".", "addListener", "(", "new", "IoFutureListener", "<", "WriteFuture", ">", "(", ")", "{", "@", "Override", "public", "void", "operationComplete", "(", "WriteFuture", "future", ")", "{", "if", "(", "future", ".", "isWritten", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Close message written\"", ")", ";", "// only set on success for now to skip boolean check later", "session", ".", "setAttribute", "(", "Constants", ".", "STATUS_CLOSE_WRITTEN", ",", "Boolean", ".", "TRUE", ")", ";", "}", "future", ".", "removeListener", "(", "this", ")", ";", "}", "}", ")", ";", "// adjust close routine to allow for flushing", "CloseFuture", "closeFuture", "=", "session", ".", "closeOnFlush", "(", ")", ";", "closeFuture", ".", "addListener", "(", "new", "IoFutureListener", "<", "CloseFuture", ">", "(", ")", "{", "public", "void", "operationComplete", "(", "CloseFuture", "future", ")", "{", "if", "(", "future", ".", "isClosed", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Connection is closed\"", ")", ";", "}", "else", "{", "log", ".", "debug", "(", "\"Connection is not yet closed\"", ")", ";", "}", "future", ".", "removeListener", "(", "this", ")", ";", "}", "}", ")", ";", "}", "else", "{", "// force close", "CloseFuture", "closeFuture", "=", "session", ".", "closeNow", "(", ")", ";", "closeFuture", ".", "addListener", "(", "new", "IoFutureListener", "<", "CloseFuture", ">", "(", ")", "{", "public", "void", "operationComplete", "(", "CloseFuture", "future", ")", "{", "if", "(", "future", ".", "isClosed", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Connection is closed\"", ")", ";", "}", "else", "{", "log", ".", "debug", "(", "\"Connection is not yet closed\"", ")", ";", "}", "future", ".", "removeListener", "(", "this", ")", ";", "}", "}", ")", ";", "}", "log", ".", "debug", "(", "\"Close complete\"", ")", ";", "}" ]
Close with an associated error status. @param statusCode @param errResponse
[ "Close", "with", "an", "associated", "error", "status", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketConnection.java#L358-L433
3,531
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketConnection.java
WebSocketConnection.getExtensionsAsString
public String getExtensionsAsString() { String extensionsList = null; if (extensions != null) { StringBuilder sb = new StringBuilder(); for (String key : extensions.keySet()) { sb.append(key); sb.append("; "); } extensionsList = sb.toString().trim(); } return extensionsList; }
java
public String getExtensionsAsString() { String extensionsList = null; if (extensions != null) { StringBuilder sb = new StringBuilder(); for (String key : extensions.keySet()) { sb.append(key); sb.append("; "); } extensionsList = sb.toString().trim(); } return extensionsList; }
[ "public", "String", "getExtensionsAsString", "(", ")", "{", "String", "extensionsList", "=", "null", ";", "if", "(", "extensions", "!=", "null", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "key", ":", "extensions", ".", "keySet", "(", ")", ")", "{", "sb", ".", "append", "(", "key", ")", ";", "sb", ".", "append", "(", "\"; \"", ")", ";", "}", "extensionsList", "=", "sb", ".", "toString", "(", ")", ".", "trim", "(", ")", ";", "}", "return", "extensionsList", ";", "}" ]
Returns the extensions list as a comma separated string as specified by the rfc. @return extension list string or null if no extensions are enabled
[ "Returns", "the", "extensions", "list", "as", "a", "comma", "separated", "string", "as", "specified", "by", "the", "rfc", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketConnection.java#L589-L600
3,532
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.isEnabled
public boolean isEnabled(String path) { if (path.startsWith("/")) { // start after the leading slash int roomSlashPos = path.indexOf('/', 1); if (roomSlashPos == -1) { // check application level scope path = path.substring(1); } else { // check room level scope path = path.substring(1, roomSlashPos); } } boolean enabled = activeRooms.contains(path); log.debug("Enabled check on path: {} enabled: {}", path, enabled); return enabled; }
java
public boolean isEnabled(String path) { if (path.startsWith("/")) { // start after the leading slash int roomSlashPos = path.indexOf('/', 1); if (roomSlashPos == -1) { // check application level scope path = path.substring(1); } else { // check room level scope path = path.substring(1, roomSlashPos); } } boolean enabled = activeRooms.contains(path); log.debug("Enabled check on path: {} enabled: {}", path, enabled); return enabled; }
[ "public", "boolean", "isEnabled", "(", "String", "path", ")", "{", "if", "(", "path", ".", "startsWith", "(", "\"/\"", ")", ")", "{", "// start after the leading slash", "int", "roomSlashPos", "=", "path", ".", "indexOf", "(", "'", "'", ",", "1", ")", ";", "if", "(", "roomSlashPos", "==", "-", "1", ")", "{", "// check application level scope", "path", "=", "path", ".", "substring", "(", "1", ")", ";", "}", "else", "{", "// check room level scope", "path", "=", "path", ".", "substring", "(", "1", ",", "roomSlashPos", ")", ";", "}", "}", "boolean", "enabled", "=", "activeRooms", ".", "contains", "(", "path", ")", ";", "log", ".", "debug", "(", "\"Enabled check on path: {} enabled: {}\"", ",", "path", ",", "enabled", ")", ";", "return", "enabled", ";", "}" ]
Returns the enable state of a given path. @param path scope / context path @return enabled if registered as active and false otherwise
[ "Returns", "the", "enable", "state", "of", "a", "given", "path", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L74-L89
3,533
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.addScope
public void addScope(IScope scope) { String app = scope.getName(); // add the name to the collection (no '/' prefix) activeRooms.add(app); // check the context for a predefined websocket scope IContext ctx = scope.getContext(); if (ctx != null && ctx.hasBean("webSocketScopeDefault")) { log.debug("WebSocket scope found in context"); WebSocketScope wsScope = (WebSocketScope) scope.getContext().getBean("webSocketScopeDefault"); if (wsScope != null) { log.trace("Default WebSocketScope has {} listeners", wsScope.getListeners().size()); } // add to scopes scopes.put(String.format("/%s", app), wsScope); } else { log.debug("Creating a new scope"); // add a default scope and listener if none are defined WebSocketScope wsScope = new WebSocketScope(); wsScope.setScope(scope); wsScope.setPath(String.format("/%s", app)); if (wsScope.getListeners().isEmpty()) { log.debug("adding default listener"); wsScope.addListener(new DefaultWebSocketDataListener()); } notifyListeners(WebSocketEvent.SCOPE_CREATED, wsScope); // add to scopes addWebSocketScope(wsScope); } }
java
public void addScope(IScope scope) { String app = scope.getName(); // add the name to the collection (no '/' prefix) activeRooms.add(app); // check the context for a predefined websocket scope IContext ctx = scope.getContext(); if (ctx != null && ctx.hasBean("webSocketScopeDefault")) { log.debug("WebSocket scope found in context"); WebSocketScope wsScope = (WebSocketScope) scope.getContext().getBean("webSocketScopeDefault"); if (wsScope != null) { log.trace("Default WebSocketScope has {} listeners", wsScope.getListeners().size()); } // add to scopes scopes.put(String.format("/%s", app), wsScope); } else { log.debug("Creating a new scope"); // add a default scope and listener if none are defined WebSocketScope wsScope = new WebSocketScope(); wsScope.setScope(scope); wsScope.setPath(String.format("/%s", app)); if (wsScope.getListeners().isEmpty()) { log.debug("adding default listener"); wsScope.addListener(new DefaultWebSocketDataListener()); } notifyListeners(WebSocketEvent.SCOPE_CREATED, wsScope); // add to scopes addWebSocketScope(wsScope); } }
[ "public", "void", "addScope", "(", "IScope", "scope", ")", "{", "String", "app", "=", "scope", ".", "getName", "(", ")", ";", "// add the name to the collection (no '/' prefix)", "activeRooms", ".", "add", "(", "app", ")", ";", "// check the context for a predefined websocket scope", "IContext", "ctx", "=", "scope", ".", "getContext", "(", ")", ";", "if", "(", "ctx", "!=", "null", "&&", "ctx", ".", "hasBean", "(", "\"webSocketScopeDefault\"", ")", ")", "{", "log", ".", "debug", "(", "\"WebSocket scope found in context\"", ")", ";", "WebSocketScope", "wsScope", "=", "(", "WebSocketScope", ")", "scope", ".", "getContext", "(", ")", ".", "getBean", "(", "\"webSocketScopeDefault\"", ")", ";", "if", "(", "wsScope", "!=", "null", ")", "{", "log", ".", "trace", "(", "\"Default WebSocketScope has {} listeners\"", ",", "wsScope", ".", "getListeners", "(", ")", ".", "size", "(", ")", ")", ";", "}", "// add to scopes", "scopes", ".", "put", "(", "String", ".", "format", "(", "\"/%s\"", ",", "app", ")", ",", "wsScope", ")", ";", "}", "else", "{", "log", ".", "debug", "(", "\"Creating a new scope\"", ")", ";", "// add a default scope and listener if none are defined", "WebSocketScope", "wsScope", "=", "new", "WebSocketScope", "(", ")", ";", "wsScope", ".", "setScope", "(", "scope", ")", ";", "wsScope", ".", "setPath", "(", "String", ".", "format", "(", "\"/%s\"", ",", "app", ")", ")", ";", "if", "(", "wsScope", ".", "getListeners", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "log", ".", "debug", "(", "\"adding default listener\"", ")", ";", "wsScope", ".", "addListener", "(", "new", "DefaultWebSocketDataListener", "(", ")", ")", ";", "}", "notifyListeners", "(", "WebSocketEvent", ".", "SCOPE_CREATED", ",", "wsScope", ")", ";", "// add to scopes", "addWebSocketScope", "(", "wsScope", ")", ";", "}", "}" ]
Adds a scope to the enabled applications. @param scope the application scope
[ "Adds", "a", "scope", "to", "the", "enabled", "applications", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L97-L125
3,534
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.addWebSocketScope
public void addWebSocketScope(WebSocketScope webSocketScope) { String path = webSocketScope.getPath(); if (scopes.putIfAbsent(path, webSocketScope) == null) { log.info("addWebSocketScope: {}", webSocketScope); notifyListeners(WebSocketEvent.SCOPE_ADDED, webSocketScope); } }
java
public void addWebSocketScope(WebSocketScope webSocketScope) { String path = webSocketScope.getPath(); if (scopes.putIfAbsent(path, webSocketScope) == null) { log.info("addWebSocketScope: {}", webSocketScope); notifyListeners(WebSocketEvent.SCOPE_ADDED, webSocketScope); } }
[ "public", "void", "addWebSocketScope", "(", "WebSocketScope", "webSocketScope", ")", "{", "String", "path", "=", "webSocketScope", ".", "getPath", "(", ")", ";", "if", "(", "scopes", ".", "putIfAbsent", "(", "path", ",", "webSocketScope", ")", "==", "null", ")", "{", "log", ".", "info", "(", "\"addWebSocketScope: {}\"", ",", "webSocketScope", ")", ";", "notifyListeners", "(", "WebSocketEvent", ".", "SCOPE_ADDED", ",", "webSocketScope", ")", ";", "}", "}" ]
Adds a websocket scope. @param webSocketScope
[ "Adds", "a", "websocket", "scope", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L154-L160
3,535
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.removeWebSocketScope
public void removeWebSocketScope(WebSocketScope webSocketScope) { log.info("removeWebSocketScope: {}", webSocketScope); WebSocketScope wsScope = scopes.remove(webSocketScope.getPath()); if (wsScope != null) { notifyListeners(WebSocketEvent.SCOPE_REMOVED, wsScope); } }
java
public void removeWebSocketScope(WebSocketScope webSocketScope) { log.info("removeWebSocketScope: {}", webSocketScope); WebSocketScope wsScope = scopes.remove(webSocketScope.getPath()); if (wsScope != null) { notifyListeners(WebSocketEvent.SCOPE_REMOVED, wsScope); } }
[ "public", "void", "removeWebSocketScope", "(", "WebSocketScope", "webSocketScope", ")", "{", "log", ".", "info", "(", "\"removeWebSocketScope: {}\"", ",", "webSocketScope", ")", ";", "WebSocketScope", "wsScope", "=", "scopes", ".", "remove", "(", "webSocketScope", ".", "getPath", "(", ")", ")", ";", "if", "(", "wsScope", "!=", "null", ")", "{", "notifyListeners", "(", "WebSocketEvent", ".", "SCOPE_REMOVED", ",", "wsScope", ")", ";", "}", "}" ]
Removes a websocket scope. @param webSocketScope
[ "Removes", "a", "websocket", "scope", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L167-L173
3,536
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.addConnection
public void addConnection(WebSocketConnection conn) { WebSocketScope scope = getScope(conn); scope.addConnection(conn); }
java
public void addConnection(WebSocketConnection conn) { WebSocketScope scope = getScope(conn); scope.addConnection(conn); }
[ "public", "void", "addConnection", "(", "WebSocketConnection", "conn", ")", "{", "WebSocketScope", "scope", "=", "getScope", "(", "conn", ")", ";", "scope", ".", "addConnection", "(", "conn", ")", ";", "}" ]
Add the connection on scope. @param conn WebSocketConnection
[ "Add", "the", "connection", "on", "scope", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L181-L184
3,537
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.addListener
public void addListener(IWebSocketDataListener listener, String path) { log.trace("addListener: {}", listener); WebSocketScope scope = getScope(path); if (scope != null) { scope.addListener(listener); } else { log.info("Scope not found for path: {}", path); } }
java
public void addListener(IWebSocketDataListener listener, String path) { log.trace("addListener: {}", listener); WebSocketScope scope = getScope(path); if (scope != null) { scope.addListener(listener); } else { log.info("Scope not found for path: {}", path); } }
[ "public", "void", "addListener", "(", "IWebSocketDataListener", "listener", ",", "String", "path", ")", "{", "log", ".", "trace", "(", "\"addListener: {}\"", ",", "listener", ")", ";", "WebSocketScope", "scope", "=", "getScope", "(", "path", ")", ";", "if", "(", "scope", "!=", "null", ")", "{", "scope", ".", "addListener", "(", "listener", ")", ";", "}", "else", "{", "log", ".", "info", "(", "\"Scope not found for path: {}\"", ",", "path", ")", ";", "}", "}" ]
Add the listener on scope via its path. @param listener IWebSocketDataListener @param path
[ "Add", "the", "listener", "on", "scope", "via", "its", "path", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L212-L220
3,538
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.removeListener
public void removeListener(IWebSocketDataListener listener, String path) { log.trace("removeListener: {}", listener); WebSocketScope scope = getScope(path); if (scope != null) { scope.removeListener(listener); if (!scope.isValid()) { // scope is not valid. delete this removeWebSocketScope(scope); } } else { log.info("Scope not found for path: {}", path); } }
java
public void removeListener(IWebSocketDataListener listener, String path) { log.trace("removeListener: {}", listener); WebSocketScope scope = getScope(path); if (scope != null) { scope.removeListener(listener); if (!scope.isValid()) { // scope is not valid. delete this removeWebSocketScope(scope); } } else { log.info("Scope not found for path: {}", path); } }
[ "public", "void", "removeListener", "(", "IWebSocketDataListener", "listener", ",", "String", "path", ")", "{", "log", ".", "trace", "(", "\"removeListener: {}\"", ",", "listener", ")", ";", "WebSocketScope", "scope", "=", "getScope", "(", "path", ")", ";", "if", "(", "scope", "!=", "null", ")", "{", "scope", ".", "removeListener", "(", "listener", ")", ";", "if", "(", "!", "scope", ".", "isValid", "(", ")", ")", "{", "// scope is not valid. delete this", "removeWebSocketScope", "(", "scope", ")", ";", "}", "}", "else", "{", "log", ".", "info", "(", "\"Scope not found for path: {}\"", ",", "path", ")", ";", "}", "}" ]
Remove listener from scope via its path. @param listener IWebSocketDataListener @param path
[ "Remove", "listener", "from", "scope", "via", "its", "path", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L229-L241
3,539
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.makeScope
public void makeScope(String path) { log.debug("makeScope: {}", path); WebSocketScope wsScope = null; if (!scopes.containsKey(path)) { // new websocket scope wsScope = new WebSocketScope(); wsScope.setPath(path); notifyListeners(WebSocketEvent.SCOPE_CREATED, wsScope); addWebSocketScope(wsScope); log.debug("Use the IWebSocketScopeListener interface to be notified of new scopes"); } else { log.debug("Scope already exists: {}", path); } }
java
public void makeScope(String path) { log.debug("makeScope: {}", path); WebSocketScope wsScope = null; if (!scopes.containsKey(path)) { // new websocket scope wsScope = new WebSocketScope(); wsScope.setPath(path); notifyListeners(WebSocketEvent.SCOPE_CREATED, wsScope); addWebSocketScope(wsScope); log.debug("Use the IWebSocketScopeListener interface to be notified of new scopes"); } else { log.debug("Scope already exists: {}", path); } }
[ "public", "void", "makeScope", "(", "String", "path", ")", "{", "log", ".", "debug", "(", "\"makeScope: {}\"", ",", "path", ")", ";", "WebSocketScope", "wsScope", "=", "null", ";", "if", "(", "!", "scopes", ".", "containsKey", "(", "path", ")", ")", "{", "// new websocket scope", "wsScope", "=", "new", "WebSocketScope", "(", ")", ";", "wsScope", ".", "setPath", "(", "path", ")", ";", "notifyListeners", "(", "WebSocketEvent", ".", "SCOPE_CREATED", ",", "wsScope", ")", ";", "addWebSocketScope", "(", "wsScope", ")", ";", "log", ".", "debug", "(", "\"Use the IWebSocketScopeListener interface to be notified of new scopes\"", ")", ";", "}", "else", "{", "log", ".", "debug", "(", "\"Scope already exists: {}\"", ",", "path", ")", ";", "}", "}" ]
Create a web socket scope. Use the IWebSocketScopeListener interface to configure the created scope. @param path
[ "Create", "a", "web", "socket", "scope", ".", "Use", "the", "IWebSocketScopeListener", "interface", "to", "configure", "the", "created", "scope", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L248-L261
3,540
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.makeScope
public void makeScope(IScope scope) { log.debug("makeScope: {}", scope); String path = scope.getContextPath(); WebSocketScope wsScope = null; if (!scopes.containsKey(path)) { // add the name to the collection (no '/' prefix) activeRooms.add(scope.getName()); // new websocket scope for the server scope wsScope = new WebSocketScope(); wsScope.setPath(path); wsScope.setScope(scope); notifyListeners(WebSocketEvent.SCOPE_CREATED, wsScope); addWebSocketScope(wsScope); log.debug("Use the IWebSocketScopeListener interface to be notified of new scopes"); } else { log.debug("Scope already exists: {}", path); } }
java
public void makeScope(IScope scope) { log.debug("makeScope: {}", scope); String path = scope.getContextPath(); WebSocketScope wsScope = null; if (!scopes.containsKey(path)) { // add the name to the collection (no '/' prefix) activeRooms.add(scope.getName()); // new websocket scope for the server scope wsScope = new WebSocketScope(); wsScope.setPath(path); wsScope.setScope(scope); notifyListeners(WebSocketEvent.SCOPE_CREATED, wsScope); addWebSocketScope(wsScope); log.debug("Use the IWebSocketScopeListener interface to be notified of new scopes"); } else { log.debug("Scope already exists: {}", path); } }
[ "public", "void", "makeScope", "(", "IScope", "scope", ")", "{", "log", ".", "debug", "(", "\"makeScope: {}\"", ",", "scope", ")", ";", "String", "path", "=", "scope", ".", "getContextPath", "(", ")", ";", "WebSocketScope", "wsScope", "=", "null", ";", "if", "(", "!", "scopes", ".", "containsKey", "(", "path", ")", ")", "{", "// add the name to the collection (no '/' prefix)", "activeRooms", ".", "add", "(", "scope", ".", "getName", "(", ")", ")", ";", "// new websocket scope for the server scope", "wsScope", "=", "new", "WebSocketScope", "(", ")", ";", "wsScope", ".", "setPath", "(", "path", ")", ";", "wsScope", ".", "setScope", "(", "scope", ")", ";", "notifyListeners", "(", "WebSocketEvent", ".", "SCOPE_CREATED", ",", "wsScope", ")", ";", "addWebSocketScope", "(", "wsScope", ")", ";", "log", ".", "debug", "(", "\"Use the IWebSocketScopeListener interface to be notified of new scopes\"", ")", ";", "}", "else", "{", "log", ".", "debug", "(", "\"Scope already exists: {}\"", ",", "path", ")", ";", "}", "}" ]
Create a web socket scope from a server IScope. Use the IWebSocketScopeListener interface to configure the created scope. @param scope
[ "Create", "a", "web", "socket", "scope", "from", "a", "server", "IScope", ".", "Use", "the", "IWebSocketScopeListener", "interface", "to", "configure", "the", "created", "scope", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L268-L285
3,541
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.getScope
public WebSocketScope getScope(String path) { log.debug("getScope: {}", path); WebSocketScope scope = scopes.get(path); // if we dont find a scope, go for default if (scope == null) { scope = scopes.get("default"); } log.debug("Returning: {}", scope); return scope; }
java
public WebSocketScope getScope(String path) { log.debug("getScope: {}", path); WebSocketScope scope = scopes.get(path); // if we dont find a scope, go for default if (scope == null) { scope = scopes.get("default"); } log.debug("Returning: {}", scope); return scope; }
[ "public", "WebSocketScope", "getScope", "(", "String", "path", ")", "{", "log", ".", "debug", "(", "\"getScope: {}\"", ",", "path", ")", ";", "WebSocketScope", "scope", "=", "scopes", ".", "get", "(", "path", ")", ";", "// if we dont find a scope, go for default", "if", "(", "scope", "==", "null", ")", "{", "scope", "=", "scopes", ".", "get", "(", "\"default\"", ")", ";", "}", "log", ".", "debug", "(", "\"Returning: {}\"", ",", "scope", ")", ";", "return", "scope", ";", "}" ]
Get the corresponding scope. @param path scope path @return scope
[ "Get", "the", "corresponding", "scope", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L294-L303
3,542
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.getScope
private WebSocketScope getScope(WebSocketConnection conn) { if (log.isTraceEnabled()) { log.trace("Scopes: {}", scopes); } log.debug("getScope: {}", conn); WebSocketScope wsScope; String path = conn.getPath(); if (!scopes.containsKey(path)) { // check for default scope if (!scopes.containsKey("default")) { wsScope = new WebSocketScope(); wsScope.setPath(path); notifyListeners(WebSocketEvent.SCOPE_CREATED, wsScope); addWebSocketScope(wsScope); //log.debug("Use the IWebSocketScopeListener interface to be notified of new scopes"); } else { path = "default"; } } wsScope = scopes.get(path); log.debug("Returning: {}", wsScope); return wsScope; }
java
private WebSocketScope getScope(WebSocketConnection conn) { if (log.isTraceEnabled()) { log.trace("Scopes: {}", scopes); } log.debug("getScope: {}", conn); WebSocketScope wsScope; String path = conn.getPath(); if (!scopes.containsKey(path)) { // check for default scope if (!scopes.containsKey("default")) { wsScope = new WebSocketScope(); wsScope.setPath(path); notifyListeners(WebSocketEvent.SCOPE_CREATED, wsScope); addWebSocketScope(wsScope); //log.debug("Use the IWebSocketScopeListener interface to be notified of new scopes"); } else { path = "default"; } } wsScope = scopes.get(path); log.debug("Returning: {}", wsScope); return wsScope; }
[ "private", "WebSocketScope", "getScope", "(", "WebSocketConnection", "conn", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"Scopes: {}\"", ",", "scopes", ")", ";", "}", "log", ".", "debug", "(", "\"getScope: {}\"", ",", "conn", ")", ";", "WebSocketScope", "wsScope", ";", "String", "path", "=", "conn", ".", "getPath", "(", ")", ";", "if", "(", "!", "scopes", ".", "containsKey", "(", "path", ")", ")", "{", "// check for default scope", "if", "(", "!", "scopes", ".", "containsKey", "(", "\"default\"", ")", ")", "{", "wsScope", "=", "new", "WebSocketScope", "(", ")", ";", "wsScope", ".", "setPath", "(", "path", ")", ";", "notifyListeners", "(", "WebSocketEvent", ".", "SCOPE_CREATED", ",", "wsScope", ")", ";", "addWebSocketScope", "(", "wsScope", ")", ";", "//log.debug(\"Use the IWebSocketScopeListener interface to be notified of new scopes\");", "}", "else", "{", "path", "=", "\"default\"", ";", "}", "}", "wsScope", "=", "scopes", ".", "get", "(", "path", ")", ";", "log", ".", "debug", "(", "\"Returning: {}\"", ",", "wsScope", ")", ";", "return", "wsScope", ";", "}" ]
Get the corresponding scope, if none exists, make new one. @param conn @return wsScope
[ "Get", "the", "corresponding", "scope", "if", "none", "exists", "make", "new", "one", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L311-L333
3,543
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScopeManager.java
WebSocketScopeManager.setApplication
public void setApplication(IScope appScope) { log.debug("Application scope: {}", appScope); this.appScope = appScope; // add the name to the collection (no '/' prefix) activeRooms.add(appScope.getName()); }
java
public void setApplication(IScope appScope) { log.debug("Application scope: {}", appScope); this.appScope = appScope; // add the name to the collection (no '/' prefix) activeRooms.add(appScope.getName()); }
[ "public", "void", "setApplication", "(", "IScope", "appScope", ")", "{", "log", ".", "debug", "(", "\"Application scope: {}\"", ",", "appScope", ")", ";", "this", ".", "appScope", "=", "appScope", ";", "// add the name to the collection (no '/' prefix)", "activeRooms", ".", "add", "(", "appScope", ".", "getName", "(", ")", ")", ";", "}" ]
Set the application scope for this manager. @param appScope
[ "Set", "the", "application", "scope", "for", "this", "manager", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScopeManager.java#L349-L354
3,544
Red5/red5-websocket
src/main/java/org/red5/net/websocket/codec/WebSocketEncoder.java
WebSocketEncoder.encodeOutgoingData
public static IoBuffer encodeOutgoingData(Packet packet) { log.debug("encode outgoing: {}", packet); // get the payload data IoBuffer data = packet.getData(); // get the frame length based on the byte count int frameLen = data.limit(); // start with frame length + 2b (header info) IoBuffer buffer = IoBuffer.allocate(frameLen + 2, false); buffer.setAutoExpand(true); // set the proper flags / opcode for the data byte frameInfo = (byte) (1 << 7); switch (packet.getType()) { case TEXT: if (log.isTraceEnabled()) { log.trace("Encoding text frame \r\n{}", new String(packet.getData().array())); } frameInfo = (byte) (frameInfo | 1); break; case BINARY: log.trace("Encoding binary frame"); frameInfo = (byte) (frameInfo | 2); break; case CLOSE: frameInfo = (byte) (frameInfo | 8); break; case CONTINUATION: frameInfo = (byte) (frameInfo | 0); break; case PING: log.trace("ping out"); frameInfo = (byte) (frameInfo | 9); break; case PONG: log.trace("pong out"); frameInfo = (byte) (frameInfo | 0xa); break; default: break; } buffer.put(frameInfo); // set the frame length log.trace("Frame length {} ", frameLen); if (frameLen <= 125) { buffer.put((byte) ((byte) frameLen & (byte) 0x7F)); } else if (frameLen > 125 && frameLen <= 65535) { buffer.put((byte) ((byte) 126 & (byte) 0x7F)); buffer.putShort((short) frameLen); } else { buffer.put((byte) ((byte) 127 & (byte) 0x7F)); buffer.putLong((int) frameLen); } buffer.put(data); buffer.flip(); if (log.isTraceEnabled()) { log.trace("Encoded: {}", buffer); } return buffer; }
java
public static IoBuffer encodeOutgoingData(Packet packet) { log.debug("encode outgoing: {}", packet); // get the payload data IoBuffer data = packet.getData(); // get the frame length based on the byte count int frameLen = data.limit(); // start with frame length + 2b (header info) IoBuffer buffer = IoBuffer.allocate(frameLen + 2, false); buffer.setAutoExpand(true); // set the proper flags / opcode for the data byte frameInfo = (byte) (1 << 7); switch (packet.getType()) { case TEXT: if (log.isTraceEnabled()) { log.trace("Encoding text frame \r\n{}", new String(packet.getData().array())); } frameInfo = (byte) (frameInfo | 1); break; case BINARY: log.trace("Encoding binary frame"); frameInfo = (byte) (frameInfo | 2); break; case CLOSE: frameInfo = (byte) (frameInfo | 8); break; case CONTINUATION: frameInfo = (byte) (frameInfo | 0); break; case PING: log.trace("ping out"); frameInfo = (byte) (frameInfo | 9); break; case PONG: log.trace("pong out"); frameInfo = (byte) (frameInfo | 0xa); break; default: break; } buffer.put(frameInfo); // set the frame length log.trace("Frame length {} ", frameLen); if (frameLen <= 125) { buffer.put((byte) ((byte) frameLen & (byte) 0x7F)); } else if (frameLen > 125 && frameLen <= 65535) { buffer.put((byte) ((byte) 126 & (byte) 0x7F)); buffer.putShort((short) frameLen); } else { buffer.put((byte) ((byte) 127 & (byte) 0x7F)); buffer.putLong((int) frameLen); } buffer.put(data); buffer.flip(); if (log.isTraceEnabled()) { log.trace("Encoded: {}", buffer); } return buffer; }
[ "public", "static", "IoBuffer", "encodeOutgoingData", "(", "Packet", "packet", ")", "{", "log", ".", "debug", "(", "\"encode outgoing: {}\"", ",", "packet", ")", ";", "// get the payload data", "IoBuffer", "data", "=", "packet", ".", "getData", "(", ")", ";", "// get the frame length based on the byte count", "int", "frameLen", "=", "data", ".", "limit", "(", ")", ";", "// start with frame length + 2b (header info)", "IoBuffer", "buffer", "=", "IoBuffer", ".", "allocate", "(", "frameLen", "+", "2", ",", "false", ")", ";", "buffer", ".", "setAutoExpand", "(", "true", ")", ";", "// set the proper flags / opcode for the data", "byte", "frameInfo", "=", "(", "byte", ")", "(", "1", "<<", "7", ")", ";", "switch", "(", "packet", ".", "getType", "(", ")", ")", "{", "case", "TEXT", ":", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"Encoding text frame \\r\\n{}\"", ",", "new", "String", "(", "packet", ".", "getData", "(", ")", ".", "array", "(", ")", ")", ")", ";", "}", "frameInfo", "=", "(", "byte", ")", "(", "frameInfo", "|", "1", ")", ";", "break", ";", "case", "BINARY", ":", "log", ".", "trace", "(", "\"Encoding binary frame\"", ")", ";", "frameInfo", "=", "(", "byte", ")", "(", "frameInfo", "|", "2", ")", ";", "break", ";", "case", "CLOSE", ":", "frameInfo", "=", "(", "byte", ")", "(", "frameInfo", "|", "8", ")", ";", "break", ";", "case", "CONTINUATION", ":", "frameInfo", "=", "(", "byte", ")", "(", "frameInfo", "|", "0", ")", ";", "break", ";", "case", "PING", ":", "log", ".", "trace", "(", "\"ping out\"", ")", ";", "frameInfo", "=", "(", "byte", ")", "(", "frameInfo", "|", "9", ")", ";", "break", ";", "case", "PONG", ":", "log", ".", "trace", "(", "\"pong out\"", ")", ";", "frameInfo", "=", "(", "byte", ")", "(", "frameInfo", "|", "0xa", ")", ";", "break", ";", "default", ":", "break", ";", "}", "buffer", ".", "put", "(", "frameInfo", ")", ";", "// set the frame length", "log", ".", "trace", "(", "\"Frame length {} \"", ",", "frameLen", ")", ";", "if", "(", "frameLen", "<=", "125", ")", "{", "buffer", ".", "put", "(", "(", "byte", ")", "(", "(", "byte", ")", "frameLen", "&", "(", "byte", ")", "0x7F", ")", ")", ";", "}", "else", "if", "(", "frameLen", ">", "125", "&&", "frameLen", "<=", "65535", ")", "{", "buffer", ".", "put", "(", "(", "byte", ")", "(", "(", "byte", ")", "126", "&", "(", "byte", ")", "0x7F", ")", ")", ";", "buffer", ".", "putShort", "(", "(", "short", ")", "frameLen", ")", ";", "}", "else", "{", "buffer", ".", "put", "(", "(", "byte", ")", "(", "(", "byte", ")", "127", "&", "(", "byte", ")", "0x7F", ")", ")", ";", "buffer", ".", "putLong", "(", "(", "int", ")", "frameLen", ")", ";", "}", "buffer", ".", "put", "(", "data", ")", ";", "buffer", ".", "flip", "(", ")", ";", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"Encoded: {}\"", ",", "buffer", ")", ";", "}", "return", "buffer", ";", "}" ]
Encode the in buffer according to the Section 5.2. RFC 6455
[ "Encode", "the", "in", "buffer", "according", "to", "the", "Section", "5", ".", "2", ".", "RFC", "6455" ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/codec/WebSocketEncoder.java#L66-L123
3,545
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketPlugin.java
WebSocketPlugin.getManager
public WebSocketScopeManager getManager(String path) { log.debug("getManager: {}", path); // determine what the app scope name is String[] parts = path.split("\\/"); if (log.isTraceEnabled()) { log.trace("Path parts: {}", Arrays.toString(parts)); } if (parts.length > 1) { // skip default in a path if it exists in slot #1 String name = !"default".equals(parts[1]) ? parts[1] : ((parts.length >= 3) ? parts[2] : parts[1]); if (log.isDebugEnabled()) { log.debug("Managers: {}", managerMap.entrySet()); } for (Entry<IScope, WebSocketScopeManager> entry : managerMap.entrySet()) { IScope appScope = entry.getKey(); if (appScope.getName().equals(name)) { log.debug("Application scope name matches path: {}", name); return entry.getValue(); } else if (log.isTraceEnabled()) { log.trace("Application scope name: {} didnt match path: {}", appScope.getName(), name); } } } return null; }
java
public WebSocketScopeManager getManager(String path) { log.debug("getManager: {}", path); // determine what the app scope name is String[] parts = path.split("\\/"); if (log.isTraceEnabled()) { log.trace("Path parts: {}", Arrays.toString(parts)); } if (parts.length > 1) { // skip default in a path if it exists in slot #1 String name = !"default".equals(parts[1]) ? parts[1] : ((parts.length >= 3) ? parts[2] : parts[1]); if (log.isDebugEnabled()) { log.debug("Managers: {}", managerMap.entrySet()); } for (Entry<IScope, WebSocketScopeManager> entry : managerMap.entrySet()) { IScope appScope = entry.getKey(); if (appScope.getName().equals(name)) { log.debug("Application scope name matches path: {}", name); return entry.getValue(); } else if (log.isTraceEnabled()) { log.trace("Application scope name: {} didnt match path: {}", appScope.getName(), name); } } } return null; }
[ "public", "WebSocketScopeManager", "getManager", "(", "String", "path", ")", "{", "log", ".", "debug", "(", "\"getManager: {}\"", ",", "path", ")", ";", "// determine what the app scope name is", "String", "[", "]", "parts", "=", "path", ".", "split", "(", "\"\\\\/\"", ")", ";", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"Path parts: {}\"", ",", "Arrays", ".", "toString", "(", "parts", ")", ")", ";", "}", "if", "(", "parts", ".", "length", ">", "1", ")", "{", "// skip default in a path if it exists in slot #1", "String", "name", "=", "!", "\"default\"", ".", "equals", "(", "parts", "[", "1", "]", ")", "?", "parts", "[", "1", "]", ":", "(", "(", "parts", ".", "length", ">=", "3", ")", "?", "parts", "[", "2", "]", ":", "parts", "[", "1", "]", ")", ";", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Managers: {}\"", ",", "managerMap", ".", "entrySet", "(", ")", ")", ";", "}", "for", "(", "Entry", "<", "IScope", ",", "WebSocketScopeManager", ">", "entry", ":", "managerMap", ".", "entrySet", "(", ")", ")", "{", "IScope", "appScope", "=", "entry", ".", "getKey", "(", ")", ";", "if", "(", "appScope", ".", "getName", "(", ")", ".", "equals", "(", "name", ")", ")", "{", "log", ".", "debug", "(", "\"Application scope name matches path: {}\"", ",", "name", ")", ";", "return", "entry", ".", "getValue", "(", ")", ";", "}", "else", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"Application scope name: {} didnt match path: {}\"", ",", "appScope", ".", "getName", "(", ")", ",", "name", ")", ";", "}", "}", "}", "return", "null", ";", "}" ]
Returns a WebSocketScopeManager for a given path. @param path @return WebSocketScopeManager if registered for the given path and null otherwise
[ "Returns", "a", "WebSocketScopeManager", "for", "a", "given", "path", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketPlugin.java#L104-L128
3,546
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScope.java
WebSocketScope.register
public void register() { log.info("Application scope: {}", scope); // set the logger to the app scope //log = Red5LoggerFactory.getLogger(WebSocketScope.class, scope.getName()); WebSocketScopeManager manager = ((WebSocketPlugin) PluginRegistry.getPlugin("WebSocketPlugin")).getManager(scope); manager.setApplication(scope); log.info("WebSocket app added: {}", scope.getName()); manager.addWebSocketScope(this); log.info("WebSocket scope added"); }
java
public void register() { log.info("Application scope: {}", scope); // set the logger to the app scope //log = Red5LoggerFactory.getLogger(WebSocketScope.class, scope.getName()); WebSocketScopeManager manager = ((WebSocketPlugin) PluginRegistry.getPlugin("WebSocketPlugin")).getManager(scope); manager.setApplication(scope); log.info("WebSocket app added: {}", scope.getName()); manager.addWebSocketScope(this); log.info("WebSocket scope added"); }
[ "public", "void", "register", "(", ")", "{", "log", ".", "info", "(", "\"Application scope: {}\"", ",", "scope", ")", ";", "// set the logger to the app scope", "//log = Red5LoggerFactory.getLogger(WebSocketScope.class, scope.getName());", "WebSocketScopeManager", "manager", "=", "(", "(", "WebSocketPlugin", ")", "PluginRegistry", ".", "getPlugin", "(", "\"WebSocketPlugin\"", ")", ")", ".", "getManager", "(", "scope", ")", ";", "manager", ".", "setApplication", "(", "scope", ")", ";", "log", ".", "info", "(", "\"WebSocket app added: {}\"", ",", "scope", ".", "getName", "(", ")", ")", ";", "manager", ".", "addWebSocketScope", "(", "this", ")", ";", "log", ".", "info", "(", "\"WebSocket scope added\"", ")", ";", "}" ]
Registers with the WebSocketScopeManager.
[ "Registers", "with", "the", "WebSocketScopeManager", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScope.java#L74-L83
3,547
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScope.java
WebSocketScope.unregister
public void unregister() { // clean up the connections by first closing them for (WebSocketConnection conn : conns) { conn.close(); } conns.clear(); // clean up the listeners by first stopping them for (IWebSocketDataListener listener : listeners) { listener.stop(); } listeners.clear(); }
java
public void unregister() { // clean up the connections by first closing them for (WebSocketConnection conn : conns) { conn.close(); } conns.clear(); // clean up the listeners by first stopping them for (IWebSocketDataListener listener : listeners) { listener.stop(); } listeners.clear(); }
[ "public", "void", "unregister", "(", ")", "{", "// clean up the connections by first closing them", "for", "(", "WebSocketConnection", "conn", ":", "conns", ")", "{", "conn", ".", "close", "(", ")", ";", "}", "conns", ".", "clear", "(", ")", ";", "// clean up the listeners by first stopping them", "for", "(", "IWebSocketDataListener", "listener", ":", "listeners", ")", "{", "listener", ".", "stop", "(", ")", ";", "}", "listeners", ".", "clear", "(", ")", ";", "}" ]
Un-registers from the WebSocketScopeManager.
[ "Un", "-", "registers", "from", "the", "WebSocketScopeManager", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScope.java#L88-L99
3,548
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScope.java
WebSocketScope.addConnection
public void addConnection(WebSocketConnection conn) { conns.add(conn); for (IWebSocketDataListener listener : listeners) { listener.onWSConnect(conn); } }
java
public void addConnection(WebSocketConnection conn) { conns.add(conn); for (IWebSocketDataListener listener : listeners) { listener.onWSConnect(conn); } }
[ "public", "void", "addConnection", "(", "WebSocketConnection", "conn", ")", "{", "conns", ".", "add", "(", "conn", ")", ";", "for", "(", "IWebSocketDataListener", "listener", ":", "listeners", ")", "{", "listener", ".", "onWSConnect", "(", "conn", ")", ";", "}", "}" ]
Add new connection on scope. @param conn WebSocketConnection
[ "Add", "new", "connection", "on", "scope", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScope.java#L154-L159
3,549
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScope.java
WebSocketScope.setListeners
public void setListeners(Collection<IWebSocketDataListener> listeners) { log.trace("setListeners: {}", listeners); this.listeners.addAll(listeners); }
java
public void setListeners(Collection<IWebSocketDataListener> listeners) { log.trace("setListeners: {}", listeners); this.listeners.addAll(listeners); }
[ "public", "void", "setListeners", "(", "Collection", "<", "IWebSocketDataListener", ">", "listeners", ")", "{", "log", ".", "trace", "(", "\"setListeners: {}\"", ",", "listeners", ")", ";", "this", ".", "listeners", ".", "addAll", "(", "listeners", ")", ";", "}" ]
Add new listeners on scope. @param listeners list of IWebSocketDataListener
[ "Add", "new", "listeners", "on", "scope", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScope.java#L202-L205
3,550
Red5/red5-websocket
src/main/java/org/red5/net/websocket/WebSocketScope.java
WebSocketScope.onMessage
public void onMessage(WSMessage message) { log.trace("Listeners: {}", listeners.size()); for (IWebSocketDataListener listener : listeners) { try { listener.onWSMessage(message); } catch (Exception e) { log.warn("onMessage exception", e); } } }
java
public void onMessage(WSMessage message) { log.trace("Listeners: {}", listeners.size()); for (IWebSocketDataListener listener : listeners) { try { listener.onWSMessage(message); } catch (Exception e) { log.warn("onMessage exception", e); } } }
[ "public", "void", "onMessage", "(", "WSMessage", "message", ")", "{", "log", ".", "trace", "(", "\"Listeners: {}\"", ",", "listeners", ".", "size", "(", ")", ")", ";", "for", "(", "IWebSocketDataListener", "listener", ":", "listeners", ")", "{", "try", "{", "listener", ".", "onWSMessage", "(", "message", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "warn", "(", "\"onMessage exception\"", ",", "e", ")", ";", "}", "}", "}" ]
Message received from client and passed on to the listeners. @param message
[ "Message", "received", "from", "client", "and", "passed", "on", "to", "the", "listeners", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/WebSocketScope.java#L230-L239
3,551
Red5/red5-websocket
src/main/java/org/red5/net/websocket/util/IdGenerator.java
IdGenerator.generateId
public static final long generateId() { long id = 0; // add new seed material from current time random.addSeedMaterial(ThreadLocalRandom.current().nextLong()); // get a new id byte[] bytes = new byte[16]; // get random bytes random.nextBytes(bytes); for (int i = 0; i < bytes.length; i++) { id += ((long) bytes[i] & 0xffL) << (8 * i); } //System.out.println("Id: " + id); return id; }
java
public static final long generateId() { long id = 0; // add new seed material from current time random.addSeedMaterial(ThreadLocalRandom.current().nextLong()); // get a new id byte[] bytes = new byte[16]; // get random bytes random.nextBytes(bytes); for (int i = 0; i < bytes.length; i++) { id += ((long) bytes[i] & 0xffL) << (8 * i); } //System.out.println("Id: " + id); return id; }
[ "public", "static", "final", "long", "generateId", "(", ")", "{", "long", "id", "=", "0", ";", "// add new seed material from current time", "random", ".", "addSeedMaterial", "(", "ThreadLocalRandom", ".", "current", "(", ")", ".", "nextLong", "(", ")", ")", ";", "// get a new id", "byte", "[", "]", "bytes", "=", "new", "byte", "[", "16", "]", ";", "// get random bytes", "random", ".", "nextBytes", "(", "bytes", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bytes", ".", "length", ";", "i", "++", ")", "{", "id", "+=", "(", "(", "long", ")", "bytes", "[", "i", "]", "&", "0xff", "L", ")", "<<", "(", "8", "*", "i", ")", ";", "}", "//System.out.println(\"Id: \" + id);", "return", "id", ";", "}" ]
Returns a cryptographically generated id. @return id
[ "Returns", "a", "cryptographically", "generated", "id", "." ]
24b53f2f3875624fb01f0a2604f4117583aeab40
https://github.com/Red5/red5-websocket/blob/24b53f2f3875624fb01f0a2604f4117583aeab40/src/main/java/org/red5/net/websocket/util/IdGenerator.java#L40-L53
3,552
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.capitalize
static public String capitalize(String string0) { if (string0 == null) { return null; } int length = string0.length(); // if empty string, just return it if (length == 0) { return string0; } else if (length == 1) { return string0.toUpperCase(); } else { StringBuilder buf = new StringBuilder(length); buf.append(string0.substring(0, 1).toUpperCase()); buf.append(string0.substring(1)); return buf.toString(); } }
java
static public String capitalize(String string0) { if (string0 == null) { return null; } int length = string0.length(); // if empty string, just return it if (length == 0) { return string0; } else if (length == 1) { return string0.toUpperCase(); } else { StringBuilder buf = new StringBuilder(length); buf.append(string0.substring(0, 1).toUpperCase()); buf.append(string0.substring(1)); return buf.toString(); } }
[ "static", "public", "String", "capitalize", "(", "String", "string0", ")", "{", "if", "(", "string0", "==", "null", ")", "{", "return", "null", ";", "}", "int", "length", "=", "string0", ".", "length", "(", ")", ";", "// if empty string, just return it", "if", "(", "length", "==", "0", ")", "{", "return", "string0", ";", "}", "else", "if", "(", "length", "==", "1", ")", "{", "return", "string0", ".", "toUpperCase", "(", ")", ";", "}", "else", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", "length", ")", ";", "buf", ".", "append", "(", "string0", ".", "substring", "(", "0", ",", "1", ")", ".", "toUpperCase", "(", ")", ")", ";", "buf", ".", "append", "(", "string0", ".", "substring", "(", "1", ")", ")", ";", "return", "buf", ".", "toString", "(", ")", ";", "}", "}" ]
Safely capitalizes a string by converting the first character to upper case. Handles null, empty, and strings of length of 1 or greater. For example, this will convert "joe" to "Joe". If the string is null, this will return null. If the string is empty such as "", then it'll just return an empty string such as "". @param string0 The string to capitalize @return A new string with the first character converted to upper case
[ "Safely", "capitalizes", "a", "string", "by", "converting", "the", "first", "character", "to", "upper", "case", ".", "Handles", "null", "empty", "and", "strings", "of", "length", "of", "1", "or", "greater", ".", "For", "example", "this", "will", "convert", "joe", "to", "Joe", ".", "If", "the", "string", "is", "null", "this", "will", "return", "null", ".", "If", "the", "string", "is", "empty", "such", "as", "then", "it", "ll", "just", "return", "an", "empty", "string", "such", "as", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L212-L228
3,553
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.uncapitalize
static public String uncapitalize(String string0) { if (string0 == null) { return null; } int length = string0.length(); // if empty string, just return it if (length == 0) { return string0; } else if (length == 1) { return string0.toLowerCase(); } else { StringBuilder buf = new StringBuilder(length); buf.append(string0.substring(0, 1).toLowerCase()); buf.append(string0.substring(1)); return buf.toString(); } }
java
static public String uncapitalize(String string0) { if (string0 == null) { return null; } int length = string0.length(); // if empty string, just return it if (length == 0) { return string0; } else if (length == 1) { return string0.toLowerCase(); } else { StringBuilder buf = new StringBuilder(length); buf.append(string0.substring(0, 1).toLowerCase()); buf.append(string0.substring(1)); return buf.toString(); } }
[ "static", "public", "String", "uncapitalize", "(", "String", "string0", ")", "{", "if", "(", "string0", "==", "null", ")", "{", "return", "null", ";", "}", "int", "length", "=", "string0", ".", "length", "(", ")", ";", "// if empty string, just return it", "if", "(", "length", "==", "0", ")", "{", "return", "string0", ";", "}", "else", "if", "(", "length", "==", "1", ")", "{", "return", "string0", ".", "toLowerCase", "(", ")", ";", "}", "else", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", "length", ")", ";", "buf", ".", "append", "(", "string0", ".", "substring", "(", "0", ",", "1", ")", ".", "toLowerCase", "(", ")", ")", ";", "buf", ".", "append", "(", "string0", ".", "substring", "(", "1", ")", ")", ";", "return", "buf", ".", "toString", "(", ")", ";", "}", "}" ]
Safely uncapitalizes a string by converting the first character to lower case. Handles null, empty, and strings of length of 1 or greater. For example, this will convert "Joe" to "joe". If the string is null, this will return null. If the string is empty such as "", then it'll just return an empty string such as "". @param string0 The string to uncapitalize @return A new string with the first character converted to lower case
[ "Safely", "uncapitalizes", "a", "string", "by", "converting", "the", "first", "character", "to", "lower", "case", ".", "Handles", "null", "empty", "and", "strings", "of", "length", "of", "1", "or", "greater", ".", "For", "example", "this", "will", "convert", "Joe", "to", "joe", ".", "If", "the", "string", "is", "null", "this", "will", "return", "null", ".", "If", "the", "string", "is", "empty", "such", "as", "then", "it", "ll", "just", "return", "an", "empty", "string", "such", "as", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L239-L255
3,554
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.indexOf
static public int indexOf(String[] strings, String targetString) { if (strings == null) return -1; for (int i = 0; i < strings.length; i++) { if (strings[i] == null) { if (targetString == null) { return i; } } else { if (targetString != null) { if (strings[i].equals(targetString)) { return i; } } } } return -1; }
java
static public int indexOf(String[] strings, String targetString) { if (strings == null) return -1; for (int i = 0; i < strings.length; i++) { if (strings[i] == null) { if (targetString == null) { return i; } } else { if (targetString != null) { if (strings[i].equals(targetString)) { return i; } } } } return -1; }
[ "static", "public", "int", "indexOf", "(", "String", "[", "]", "strings", ",", "String", "targetString", ")", "{", "if", "(", "strings", "==", "null", ")", "return", "-", "1", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "strings", ".", "length", ";", "i", "++", ")", "{", "if", "(", "strings", "[", "i", "]", "==", "null", ")", "{", "if", "(", "targetString", "==", "null", ")", "{", "return", "i", ";", "}", "}", "else", "{", "if", "(", "targetString", "!=", "null", ")", "{", "if", "(", "strings", "[", "i", "]", ".", "equals", "(", "targetString", ")", ")", "{", "return", "i", ";", "}", "}", "}", "}", "return", "-", "1", ";", "}" ]
Finds the first occurrence of the targetString in the array of strings. Returns -1 if an occurrence wasn't found. This method will return true if a "null" is contained in the array and the targetString is also null. @param strings The array of strings to search. @param targetString The string to search for @return The index of the first occurrence, or -1 if not found. If strings array is null, will return -1;
[ "Finds", "the", "first", "occurrence", "of", "the", "targetString", "in", "the", "array", "of", "strings", ".", "Returns", "-", "1", "if", "an", "occurrence", "wasn", "t", "found", ".", "This", "method", "will", "return", "true", "if", "a", "null", "is", "contained", "in", "the", "array", "and", "the", "targetString", "is", "also", "null", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L280-L297
3,555
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.stripQuotes
static public String stripQuotes(String string0) { // if an empty string, return it if (string0.length() == 0) { return string0; } // if the first and last characters are quotes, just do 1 substring if (string0.length() > 1 && string0.charAt(0) == '"' && string0.charAt(string0.length() - 1) == '"') { return string0.substring(1, string0.length() - 1); } else if (string0.charAt(0) == '"') { string0 = string0.substring(1); } else if (string0.charAt(string0.length() - 1) == '"') { string0 = string0.substring(0, string0.length() - 1); } return string0; }
java
static public String stripQuotes(String string0) { // if an empty string, return it if (string0.length() == 0) { return string0; } // if the first and last characters are quotes, just do 1 substring if (string0.length() > 1 && string0.charAt(0) == '"' && string0.charAt(string0.length() - 1) == '"') { return string0.substring(1, string0.length() - 1); } else if (string0.charAt(0) == '"') { string0 = string0.substring(1); } else if (string0.charAt(string0.length() - 1) == '"') { string0 = string0.substring(0, string0.length() - 1); } return string0; }
[ "static", "public", "String", "stripQuotes", "(", "String", "string0", ")", "{", "// if an empty string, return it", "if", "(", "string0", ".", "length", "(", ")", "==", "0", ")", "{", "return", "string0", ";", "}", "// if the first and last characters are quotes, just do 1 substring", "if", "(", "string0", ".", "length", "(", ")", ">", "1", "&&", "string0", ".", "charAt", "(", "0", ")", "==", "'", "'", "&&", "string0", ".", "charAt", "(", "string0", ".", "length", "(", ")", "-", "1", ")", "==", "'", "'", ")", "{", "return", "string0", ".", "substring", "(", "1", ",", "string0", ".", "length", "(", ")", "-", "1", ")", ";", "}", "else", "if", "(", "string0", ".", "charAt", "(", "0", ")", "==", "'", "'", ")", "{", "string0", "=", "string0", ".", "substring", "(", "1", ")", ";", "}", "else", "if", "(", "string0", ".", "charAt", "(", "string0", ".", "length", "(", ")", "-", "1", ")", "==", "'", "'", ")", "{", "string0", "=", "string0", ".", "substring", "(", "0", ",", "string0", ".", "length", "(", ")", "-", "1", ")", ";", "}", "return", "string0", ";", "}" ]
If present, this method will strip off the leading and trailing " character in the string parameter. For example, "10958" will becomes just 10958.
[ "If", "present", "this", "method", "will", "strip", "off", "the", "leading", "and", "trailing", "character", "in", "the", "string", "parameter", ".", "For", "example", "10958", "will", "becomes", "just", "10958", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L305-L319
3,556
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.containsOnlyDigits
static public boolean containsOnlyDigits(String string0) { // are they all digits? for (int i = 0; i < string0.length(); i++) { if (!Character.isDigit(string0.charAt(i))) { return false; } } return true; }
java
static public boolean containsOnlyDigits(String string0) { // are they all digits? for (int i = 0; i < string0.length(); i++) { if (!Character.isDigit(string0.charAt(i))) { return false; } } return true; }
[ "static", "public", "boolean", "containsOnlyDigits", "(", "String", "string0", ")", "{", "// are they all digits?", "for", "(", "int", "i", "=", "0", ";", "i", "<", "string0", ".", "length", "(", ")", ";", "i", "++", ")", "{", "if", "(", "!", "Character", ".", "isDigit", "(", "string0", ".", "charAt", "(", "i", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if a string contains only digits. @return True if the string0 only contains digits, or false otherwise.
[ "Checks", "if", "a", "string", "contains", "only", "digits", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L326-L334
3,557
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.split
static public String[] split(String str, char delim) { if (str == null) { throw new NullPointerException("str can't be null"); } // Note the javadoc on StringTokenizer: // StringTokenizer is a legacy class that is retained for // compatibility reasons although its use is discouraged in // new code. // In other words, if StringTokenizer is ever removed from the JDK, // we need to have a look at String.split() (or java.util.regex) // if it is supported on a JSR169/Java ME platform by then. StringTokenizer st = new StringTokenizer(str, String.valueOf(delim)); int n = st.countTokens(); String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = st.nextToken(); } return s; }
java
static public String[] split(String str, char delim) { if (str == null) { throw new NullPointerException("str can't be null"); } // Note the javadoc on StringTokenizer: // StringTokenizer is a legacy class that is retained for // compatibility reasons although its use is discouraged in // new code. // In other words, if StringTokenizer is ever removed from the JDK, // we need to have a look at String.split() (or java.util.regex) // if it is supported on a JSR169/Java ME platform by then. StringTokenizer st = new StringTokenizer(str, String.valueOf(delim)); int n = st.countTokens(); String[] s = new String[n]; for (int i = 0; i < n; i++) { s[i] = st.nextToken(); } return s; }
[ "static", "public", "String", "[", "]", "split", "(", "String", "str", ",", "char", "delim", ")", "{", "if", "(", "str", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"str can't be null\"", ")", ";", "}", "// Note the javadoc on StringTokenizer:", "// StringTokenizer is a legacy class that is retained for", "// compatibility reasons although its use is discouraged in", "// new code.", "// In other words, if StringTokenizer is ever removed from the JDK,", "// we need to have a look at String.split() (or java.util.regex)", "// if it is supported on a JSR169/Java ME platform by then.", "StringTokenizer", "st", "=", "new", "StringTokenizer", "(", "str", ",", "String", ".", "valueOf", "(", "delim", ")", ")", ";", "int", "n", "=", "st", ".", "countTokens", "(", ")", ";", "String", "[", "]", "s", "=", "new", "String", "[", "n", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "s", "[", "i", "]", "=", "st", ".", "nextToken", "(", ")", ";", "}", "return", "s", ";", "}" ]
Splits a string around matches of the given delimiter character. Where applicable, this method can be used as a substitute for <code>String.split(String regex)</code>, which is not available on a JSR169/Java ME platform. @param str the string to be split @param delim the delimiter @throws NullPointerException if str is null
[ "Splits", "a", "string", "around", "matches", "of", "the", "given", "delimiter", "character", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L348-L367
3,558
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.formatForPrint
public final static String formatForPrint(String input) { if (input.length() > 60) { StringBuffer tmp = new StringBuffer(input.substring(0, 60)); tmp.append("&"); input = tmp.toString(); } return input; }
java
public final static String formatForPrint(String input) { if (input.length() > 60) { StringBuffer tmp = new StringBuffer(input.substring(0, 60)); tmp.append("&"); input = tmp.toString(); } return input; }
[ "public", "final", "static", "String", "formatForPrint", "(", "String", "input", ")", "{", "if", "(", "input", ".", "length", "(", ")", ">", "60", ")", "{", "StringBuffer", "tmp", "=", "new", "StringBuffer", "(", "input", ".", "substring", "(", "0", ",", "60", ")", ")", ";", "tmp", ".", "append", "(", "\"&\"", ")", ";", "input", "=", "tmp", ".", "toString", "(", ")", ";", "}", "return", "input", ";", "}" ]
Used to print out a string for error messages, chops is off at 60 chars for historical reasons.
[ "Used", "to", "print", "out", "a", "string", "for", "error", "messages", "chops", "is", "off", "at", "60", "chars", "for", "historical", "reasons", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L373-L380
3,559
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.toStringArray
public static String[] toStringArray(Object[] objArray) { int idx; int len = objArray.length; String[] strArray = new String[len]; for (idx = 0; idx < len; idx++) { strArray[idx] = objArray[idx].toString(); } return strArray; }
java
public static String[] toStringArray(Object[] objArray) { int idx; int len = objArray.length; String[] strArray = new String[len]; for (idx = 0; idx < len; idx++) { strArray[idx] = objArray[idx].toString(); } return strArray; }
[ "public", "static", "String", "[", "]", "toStringArray", "(", "Object", "[", "]", "objArray", ")", "{", "int", "idx", ";", "int", "len", "=", "objArray", ".", "length", ";", "String", "[", "]", "strArray", "=", "new", "String", "[", "len", "]", ";", "for", "(", "idx", "=", "0", ";", "idx", "<", "len", ";", "idx", "++", ")", "{", "strArray", "[", "idx", "]", "=", "objArray", "[", "idx", "]", ".", "toString", "(", ")", ";", "}", "return", "strArray", ";", "}" ]
A method that receive an array of Objects and return a String array representation of that array.
[ "A", "method", "that", "receive", "an", "array", "of", "Objects", "and", "return", "a", "String", "array", "representation", "of", "that", "array", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L386-L396
3,560
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.getAsciiBytes
public static byte[] getAsciiBytes(String input) { char[] c = input.toCharArray(); byte[] b = new byte[c.length]; for (int i = 0; i < c.length; i++) { b[i] = (byte) (c[i] & 0x007F); } return b; }
java
public static byte[] getAsciiBytes(String input) { char[] c = input.toCharArray(); byte[] b = new byte[c.length]; for (int i = 0; i < c.length; i++) { b[i] = (byte) (c[i] & 0x007F); } return b; }
[ "public", "static", "byte", "[", "]", "getAsciiBytes", "(", "String", "input", ")", "{", "char", "[", "]", "c", "=", "input", ".", "toCharArray", "(", ")", ";", "byte", "[", "]", "b", "=", "new", "byte", "[", "c", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "c", ".", "length", ";", "i", "++", ")", "{", "b", "[", "i", "]", "=", "(", "byte", ")", "(", "c", "[", "i", "]", "&", "0x007F", ")", ";", "}", "return", "b", ";", "}" ]
Get 7-bit ASCII character array from input String. The lower 7 bits of each character in the input string is assumed to be the ASCII character value. Hexadecimal - Character | 00 NUL| 01 SOH| 02 STX| 03 ETX| 04 EOT| 05 ENQ| 06 ACK| 07 BEL| | 08 BS | 09 HT | 0A NL | 0B VT | 0C NP | 0D CR | 0E SO | 0F SI | | 10 DLE| 11 DC1| 12 DC2| 13 DC3| 14 DC4| 15 NAK| 16 SYN| 17 ETB| | 18 CAN| 19 EM | 1A SUB| 1B ESC| 1C FS | 1D GS | 1E RS | 1F US | | 20 SP | 21 ! | 22 " | 23 # | 24 $ | 25 % | 26 & | 27 ' | | 28 ( | 29 ) | 2A * | 2B + | 2C , | 2D - | 2E . | 2F / | | 30 0 | 31 1 | 32 2 | 33 3 | 34 4 | 35 5 | 36 6 | 37 7 | | 38 8 | 39 9 | 3A : | 3B ; | 3C < | 3D = | 3E > | 3F ? | | 40 @ | 41 A | 42 B | 43 C | 44 D | 45 E | 46 F | 47 G | | 48 H | 49 I | 4A J | 4B K | 4C L | 4D M | 4E N | 4F O | | 50 P | 51 Q | 52 R | 53 S | 54 T | 55 U | 56 V | 57 W | | 58 X | 59 Y | 5A Z | 5B [ | 5C \ | 5D ] | 5E ^ | 5F _ | | 60 ` | 61 a | 62 b | 63 c | 64 d | 65 e | 66 f | 67 g | | 68 h | 69 i | 6A j | 6B k | 6C l | 6D m | 6E n | 6F o | | 70 p | 71 q | 72 r | 73 s | 74 t | 75 u | 76 v | 77 w | | 78 x | 79 y | 7A z | 7B { | 7C | | 7D } | 7E ~ | 7F DEL|
[ "Get", "7", "-", "bit", "ASCII", "character", "array", "from", "input", "String", ".", "The", "lower", "7", "bits", "of", "each", "character", "in", "the", "input", "string", "is", "assumed", "to", "be", "the", "ASCII", "character", "value", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L423-L431
3,561
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.trimTrailing
public static String trimTrailing(String str) { if (str == null) { return null; } int len = str.length(); for (; len > 0; len--) { if (!Character.isWhitespace(str.charAt(len - 1))) { break; } } return str.substring(0, len); }
java
public static String trimTrailing(String str) { if (str == null) { return null; } int len = str.length(); for (; len > 0; len--) { if (!Character.isWhitespace(str.charAt(len - 1))) { break; } } return str.substring(0, len); }
[ "public", "static", "String", "trimTrailing", "(", "String", "str", ")", "{", "if", "(", "str", "==", "null", ")", "{", "return", "null", ";", "}", "int", "len", "=", "str", ".", "length", "(", ")", ";", "for", "(", ";", "len", ">", "0", ";", "len", "--", ")", "{", "if", "(", "!", "Character", ".", "isWhitespace", "(", "str", ".", "charAt", "(", "len", "-", "1", ")", ")", ")", "{", "break", ";", "}", "}", "return", "str", ".", "substring", "(", "0", ",", "len", ")", ";", "}" ]
Trim off trailing blanks but not leading blanks @param str @return The input with trailing blanks stipped off
[ "Trim", "off", "trailing", "blanks", "but", "not", "leading", "blanks" ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L446-L457
3,562
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.truncate
public static String truncate(String value, int length) { if (value != null && value.length() > length) { value = value.substring(0, length); } return value; }
java
public static String truncate(String value, int length) { if (value != null && value.length() > length) { value = value.substring(0, length); } return value; }
[ "public", "static", "String", "truncate", "(", "String", "value", ",", "int", "length", ")", "{", "if", "(", "value", "!=", "null", "&&", "value", ".", "length", "(", ")", ">", "length", ")", "{", "value", "=", "value", ".", "substring", "(", "0", ",", "length", ")", ";", "}", "return", "value", ";", "}" ]
Truncate a String to the given length with no warnings or error raised if it is bigger. @param value String to be truncated @param length Maximum length of string @return Returns value if value is null or value.length() is less or equal to than length, otherwise a String representing value truncated to length.
[ "Truncate", "a", "String", "to", "the", "given", "length", "with", "no", "warnings", "or", "error", "raised", "if", "it", "is", "bigger", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L469-L474
3,563
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.hexDump
public static String hexDump(String prefix, byte[] data) { byte byte_value; StringBuffer str = new StringBuffer(data.length * 3); str.append(prefix); for (int i = 0; i < data.length; i += 16) { // dump the header: 00000000: String offset = Integer.toHexString(i); // "0" left pad offset field so it is always 8 char's long. str.append(" "); for (int offlen = offset.length(); offlen < 8; offlen++) { str.append("0"); } str.append(offset); str.append(":"); // dump hex version of 16 bytes per line. for (int j = 0; (j < 16) && ((i + j) < data.length); j++) { byte_value = data[i + j]; // add spaces between every 2 bytes. if ((j % 2) == 0) { str.append(" "); } // dump a single byte. byte high_nibble = (byte) ((byte_value & 0xf0) >>> 4); byte low_nibble = (byte) (byte_value & 0x0f); str.append(HEX_TABLE[high_nibble]); str.append(HEX_TABLE[low_nibble]); } // IF THIS IS THE LAST LINE OF HEX, THEN ADD THIS if (i + 16 > data.length) { // for debugging purposes, I want the last bytes always padded // over so that the ascii portion is correctly positioned int last_row_byte_count = data.length % 16; int num_bytes_short = 16 - last_row_byte_count; // number of spaces to add = (num bytes remaining * 2 spaces per byte) + (7 - (num bytes % 2)) int num_spaces = (num_bytes_short * 2) + (7 - (last_row_byte_count / 2)); for (int v = 0; v < num_spaces; v++) { str.append(" "); } } // dump ascii version of 16 bytes str.append(" "); for (int j = 0; (j < 16) && ((i + j) < data.length); j++) { char char_value = (char) data[i + j]; // RESOLVE (really want isAscii() or isPrintable()) //if (Character.isLetterOrDigit(char_value)) if (isPrintableChar(char_value)) { str.append(String.valueOf(char_value)); } else { str.append("."); } } // new line str.append("\n"); } // always trim off the last newline str.deleteCharAt(str.length() - 1); return (str.toString()); }
java
public static String hexDump(String prefix, byte[] data) { byte byte_value; StringBuffer str = new StringBuffer(data.length * 3); str.append(prefix); for (int i = 0; i < data.length; i += 16) { // dump the header: 00000000: String offset = Integer.toHexString(i); // "0" left pad offset field so it is always 8 char's long. str.append(" "); for (int offlen = offset.length(); offlen < 8; offlen++) { str.append("0"); } str.append(offset); str.append(":"); // dump hex version of 16 bytes per line. for (int j = 0; (j < 16) && ((i + j) < data.length); j++) { byte_value = data[i + j]; // add spaces between every 2 bytes. if ((j % 2) == 0) { str.append(" "); } // dump a single byte. byte high_nibble = (byte) ((byte_value & 0xf0) >>> 4); byte low_nibble = (byte) (byte_value & 0x0f); str.append(HEX_TABLE[high_nibble]); str.append(HEX_TABLE[low_nibble]); } // IF THIS IS THE LAST LINE OF HEX, THEN ADD THIS if (i + 16 > data.length) { // for debugging purposes, I want the last bytes always padded // over so that the ascii portion is correctly positioned int last_row_byte_count = data.length % 16; int num_bytes_short = 16 - last_row_byte_count; // number of spaces to add = (num bytes remaining * 2 spaces per byte) + (7 - (num bytes % 2)) int num_spaces = (num_bytes_short * 2) + (7 - (last_row_byte_count / 2)); for (int v = 0; v < num_spaces; v++) { str.append(" "); } } // dump ascii version of 16 bytes str.append(" "); for (int j = 0; (j < 16) && ((i + j) < data.length); j++) { char char_value = (char) data[i + j]; // RESOLVE (really want isAscii() or isPrintable()) //if (Character.isLetterOrDigit(char_value)) if (isPrintableChar(char_value)) { str.append(String.valueOf(char_value)); } else { str.append("."); } } // new line str.append("\n"); } // always trim off the last newline str.deleteCharAt(str.length() - 1); return (str.toString()); }
[ "public", "static", "String", "hexDump", "(", "String", "prefix", ",", "byte", "[", "]", "data", ")", "{", "byte", "byte_value", ";", "StringBuffer", "str", "=", "new", "StringBuffer", "(", "data", ".", "length", "*", "3", ")", ";", "str", ".", "append", "(", "prefix", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "i", "+=", "16", ")", "{", "// dump the header: 00000000:", "String", "offset", "=", "Integer", ".", "toHexString", "(", "i", ")", ";", "// \"0\" left pad offset field so it is always 8 char's long.", "str", ".", "append", "(", "\" \"", ")", ";", "for", "(", "int", "offlen", "=", "offset", ".", "length", "(", ")", ";", "offlen", "<", "8", ";", "offlen", "++", ")", "{", "str", ".", "append", "(", "\"0\"", ")", ";", "}", "str", ".", "append", "(", "offset", ")", ";", "str", ".", "append", "(", "\":\"", ")", ";", "// dump hex version of 16 bytes per line.", "for", "(", "int", "j", "=", "0", ";", "(", "j", "<", "16", ")", "&&", "(", "(", "i", "+", "j", ")", "<", "data", ".", "length", ")", ";", "j", "++", ")", "{", "byte_value", "=", "data", "[", "i", "+", "j", "]", ";", "// add spaces between every 2 bytes.", "if", "(", "(", "j", "%", "2", ")", "==", "0", ")", "{", "str", ".", "append", "(", "\" \"", ")", ";", "}", "// dump a single byte.", "byte", "high_nibble", "=", "(", "byte", ")", "(", "(", "byte_value", "&", "0xf0", ")", ">>>", "4", ")", ";", "byte", "low_nibble", "=", "(", "byte", ")", "(", "byte_value", "&", "0x0f", ")", ";", "str", ".", "append", "(", "HEX_TABLE", "[", "high_nibble", "]", ")", ";", "str", ".", "append", "(", "HEX_TABLE", "[", "low_nibble", "]", ")", ";", "}", "// IF THIS IS THE LAST LINE OF HEX, THEN ADD THIS", "if", "(", "i", "+", "16", ">", "data", ".", "length", ")", "{", "// for debugging purposes, I want the last bytes always padded", "// over so that the ascii portion is correctly positioned", "int", "last_row_byte_count", "=", "data", ".", "length", "%", "16", ";", "int", "num_bytes_short", "=", "16", "-", "last_row_byte_count", ";", "// number of spaces to add = (num bytes remaining * 2 spaces per byte) + (7 - (num bytes % 2))", "int", "num_spaces", "=", "(", "num_bytes_short", "*", "2", ")", "+", "(", "7", "-", "(", "last_row_byte_count", "/", "2", ")", ")", ";", "for", "(", "int", "v", "=", "0", ";", "v", "<", "num_spaces", ";", "v", "++", ")", "{", "str", ".", "append", "(", "\" \"", ")", ";", "}", "}", "// dump ascii version of 16 bytes", "str", ".", "append", "(", "\" \"", ")", ";", "for", "(", "int", "j", "=", "0", ";", "(", "j", "<", "16", ")", "&&", "(", "(", "i", "+", "j", ")", "<", "data", ".", "length", ")", ";", "j", "++", ")", "{", "char", "char_value", "=", "(", "char", ")", "data", "[", "i", "+", "j", "]", ";", "// RESOLVE (really want isAscii() or isPrintable())", "//if (Character.isLetterOrDigit(char_value))", "if", "(", "isPrintableChar", "(", "char_value", ")", ")", "{", "str", ".", "append", "(", "String", ".", "valueOf", "(", "char_value", ")", ")", ";", "}", "else", "{", "str", ".", "append", "(", "\".\"", ")", ";", "}", "}", "// new line", "str", ".", "append", "(", "\"\\n\"", ")", ";", "}", "// always trim off the last newline", "str", ".", "deleteCharAt", "(", "str", ".", "length", "(", ")", "-", "1", ")", ";", "return", "(", "str", ".", "toString", "(", ")", ")", ";", "}" ]
Convert a byte array to a human-readable String for debugging purposes.
[ "Convert", "a", "byte", "array", "to", "a", "human", "-", "readable", "String", "for", "debugging", "purposes", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L585-L657
3,564
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.quoteString
static String quoteString(String source, char quote) { // Normally, the quoted string is two characters longer than the source // string (because of start quote and end quote). StringBuffer quoted = new StringBuffer(source.length() + 2); quoted.append(quote); for (int i = 0; i < source.length(); i++) { char c = source.charAt(i); // if the character is a quote, escape it with an extra quote if (c == quote) quoted.append(quote); quoted.append(c); } quoted.append(quote); return quoted.toString(); }
java
static String quoteString(String source, char quote) { // Normally, the quoted string is two characters longer than the source // string (because of start quote and end quote). StringBuffer quoted = new StringBuffer(source.length() + 2); quoted.append(quote); for (int i = 0; i < source.length(); i++) { char c = source.charAt(i); // if the character is a quote, escape it with an extra quote if (c == quote) quoted.append(quote); quoted.append(c); } quoted.append(quote); return quoted.toString(); }
[ "static", "String", "quoteString", "(", "String", "source", ",", "char", "quote", ")", "{", "// Normally, the quoted string is two characters longer than the source", "// string (because of start quote and end quote).", "StringBuffer", "quoted", "=", "new", "StringBuffer", "(", "source", ".", "length", "(", ")", "+", "2", ")", ";", "quoted", ".", "append", "(", "quote", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "source", ".", "length", "(", ")", ";", "i", "++", ")", "{", "char", "c", "=", "source", ".", "charAt", "(", "i", ")", ";", "// if the character is a quote, escape it with an extra quote", "if", "(", "c", "==", "quote", ")", "quoted", ".", "append", "(", "quote", ")", ";", "quoted", ".", "append", "(", "c", ")", ";", "}", "quoted", ".", "append", "(", "quote", ")", ";", "return", "quoted", ".", "toString", "(", ")", ";", "}" ]
Quote a string so that it can be used as an identifier or a string literal in SQL statements. Identifiers are surrounded by double quotes and string literals are surrounded by single quotes. If the string contains quote characters, they are escaped. @param source the string to quote @param quote the character to quote the string with (' or &quot;) @return a string quoted with the specified quote character @see #quoteStringLiteral(String) @see IdUtil#normalToDelimited(String)
[ "Quote", "a", "string", "so", "that", "it", "can", "be", "used", "as", "an", "identifier", "or", "a", "string", "literal", "in", "SQL", "statements", ".", "Identifiers", "are", "surrounded", "by", "double", "quotes", "and", "string", "literals", "are", "surrounded", "by", "single", "quotes", ".", "If", "the", "string", "contains", "quote", "characters", "they", "are", "escaped", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L765-L778
3,565
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java
StringUtil.removeAllCharsExceptDigits
static public String removeAllCharsExceptDigits(String str0) { if (str0 == null) { return null; } if (str0.length() == 0) { return str0; } StringBuilder buf = new StringBuilder(str0.length()); int length = str0.length(); for (int i = 0; i < length; i++) { char c = str0.charAt(i); if (Character.isDigit(c)) { // append this character to our string buf.append(c); } } return buf.toString(); }
java
static public String removeAllCharsExceptDigits(String str0) { if (str0 == null) { return null; } if (str0.length() == 0) { return str0; } StringBuilder buf = new StringBuilder(str0.length()); int length = str0.length(); for (int i = 0; i < length; i++) { char c = str0.charAt(i); if (Character.isDigit(c)) { // append this character to our string buf.append(c); } } return buf.toString(); }
[ "static", "public", "String", "removeAllCharsExceptDigits", "(", "String", "str0", ")", "{", "if", "(", "str0", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "str0", ".", "length", "(", ")", "==", "0", ")", "{", "return", "str0", ";", "}", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", "str0", ".", "length", "(", ")", ")", ";", "int", "length", "=", "str0", ".", "length", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "char", "c", "=", "str0", ".", "charAt", "(", "i", ")", ";", "if", "(", "Character", ".", "isDigit", "(", "c", ")", ")", "{", "// append this character to our string", "buf", ".", "append", "(", "c", ")", ";", "}", "}", "return", "buf", ".", "toString", "(", ")", ";", "}" ]
Removes all other characters from a string except digits. A good way of cleaing up something like a phone number. @param str0 The string to clean up @return A new String that has all characters except digits removed
[ "Removes", "all", "other", "characters", "from", "a", "string", "except", "digits", ".", "A", "good", "way", "of", "cleaing", "up", "something", "like", "a", "phone", "number", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StringUtil.java#L967-L984
3,566
twitter/cloudhopper-commons
ch-commons-locale/src/main/java/com/cloudhopper/commons/locale/Country.java
Country.parse
protected static Country parse(String line) throws IOException { try { int pos = line.indexOf(' '); if (pos < 0) throw new IOException("Invalid format, could not parse 2 char code"); String code2 = line.substring(0, pos); int pos2 = line.indexOf(' ', pos+1); if (pos2 < 0) throw new IOException("Invalid format, could not parse 3 char code"); String code3 = line.substring(pos+1, pos2); int pos3 = line.indexOf(' ', pos2+1); if (pos3 < 0) throw new IOException("Invalid format, could not parse 3 char digit code"); String num3 = line.substring(pos2+1, pos3); // rest of line is the long name String longName = line.substring(pos3+1).trim(); // was there a name? if (longName == null || longName.equals("")) { throw new IOException("Country name was null or empty"); } // parse long name into its short name (strip anything after the last comma) String name = longName; int pos4 = longName.lastIndexOf(','); if (pos4 > 0) { // strip out the final part such as ", Republic of" from something like "Nigeria, Republic Of" name = longName.substring(0, pos4); } // create the new country return new Country(code2, name, longName); } catch (Exception e) { throw new IOException("Failed while parsing country for line: " + line, e); } }
java
protected static Country parse(String line) throws IOException { try { int pos = line.indexOf(' '); if (pos < 0) throw new IOException("Invalid format, could not parse 2 char code"); String code2 = line.substring(0, pos); int pos2 = line.indexOf(' ', pos+1); if (pos2 < 0) throw new IOException("Invalid format, could not parse 3 char code"); String code3 = line.substring(pos+1, pos2); int pos3 = line.indexOf(' ', pos2+1); if (pos3 < 0) throw new IOException("Invalid format, could not parse 3 char digit code"); String num3 = line.substring(pos2+1, pos3); // rest of line is the long name String longName = line.substring(pos3+1).trim(); // was there a name? if (longName == null || longName.equals("")) { throw new IOException("Country name was null or empty"); } // parse long name into its short name (strip anything after the last comma) String name = longName; int pos4 = longName.lastIndexOf(','); if (pos4 > 0) { // strip out the final part such as ", Republic of" from something like "Nigeria, Republic Of" name = longName.substring(0, pos4); } // create the new country return new Country(code2, name, longName); } catch (Exception e) { throw new IOException("Failed while parsing country for line: " + line, e); } }
[ "protected", "static", "Country", "parse", "(", "String", "line", ")", "throws", "IOException", "{", "try", "{", "int", "pos", "=", "line", ".", "indexOf", "(", "'", "'", ")", ";", "if", "(", "pos", "<", "0", ")", "throw", "new", "IOException", "(", "\"Invalid format, could not parse 2 char code\"", ")", ";", "String", "code2", "=", "line", ".", "substring", "(", "0", ",", "pos", ")", ";", "int", "pos2", "=", "line", ".", "indexOf", "(", "'", "'", ",", "pos", "+", "1", ")", ";", "if", "(", "pos2", "<", "0", ")", "throw", "new", "IOException", "(", "\"Invalid format, could not parse 3 char code\"", ")", ";", "String", "code3", "=", "line", ".", "substring", "(", "pos", "+", "1", ",", "pos2", ")", ";", "int", "pos3", "=", "line", ".", "indexOf", "(", "'", "'", ",", "pos2", "+", "1", ")", ";", "if", "(", "pos3", "<", "0", ")", "throw", "new", "IOException", "(", "\"Invalid format, could not parse 3 char digit code\"", ")", ";", "String", "num3", "=", "line", ".", "substring", "(", "pos2", "+", "1", ",", "pos3", ")", ";", "// rest of line is the long name", "String", "longName", "=", "line", ".", "substring", "(", "pos3", "+", "1", ")", ".", "trim", "(", ")", ";", "// was there a name?", "if", "(", "longName", "==", "null", "||", "longName", ".", "equals", "(", "\"\"", ")", ")", "{", "throw", "new", "IOException", "(", "\"Country name was null or empty\"", ")", ";", "}", "// parse long name into its short name (strip anything after the last comma)", "String", "name", "=", "longName", ";", "int", "pos4", "=", "longName", ".", "lastIndexOf", "(", "'", "'", ")", ";", "if", "(", "pos4", ">", "0", ")", "{", "// strip out the final part such as \", Republic of\" from something like \"Nigeria, Republic Of\"", "name", "=", "longName", ".", "substring", "(", "0", ",", "pos4", ")", ";", "}", "// create the new country", "return", "new", "Country", "(", "code2", ",", "name", ",", "longName", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "IOException", "(", "\"Failed while parsing country for line: \"", "+", "line", ",", "e", ")", ";", "}", "}" ]
AF AFG 004 Afghanistan
[ "AF", "AFG", "004", "Afghanistan" ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-locale/src/main/java/com/cloudhopper/commons/locale/Country.java#L139-L170
3,567
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteUtil.java
ByteUtil.encodeBcd
public static byte[] encodeBcd(String data, int num_bytes) { // allocate buffer byte buf[] = new byte[num_bytes]; // if length of addr is odd, then add an F onto the end of it if ((data.length() % 2) != 0) { data += "F"; } int index = 0; for (int i = 0; i < data.length(); i += 2) { StringBuilder x = new StringBuilder(data.substring(i, i + 2)); x.reverse(); buf[index] = ByteUtil.decodeHex(x.toString(), 2)[0]; index++; } return buf; }
java
public static byte[] encodeBcd(String data, int num_bytes) { // allocate buffer byte buf[] = new byte[num_bytes]; // if length of addr is odd, then add an F onto the end of it if ((data.length() % 2) != 0) { data += "F"; } int index = 0; for (int i = 0; i < data.length(); i += 2) { StringBuilder x = new StringBuilder(data.substring(i, i + 2)); x.reverse(); buf[index] = ByteUtil.decodeHex(x.toString(), 2)[0]; index++; } return buf; }
[ "public", "static", "byte", "[", "]", "encodeBcd", "(", "String", "data", ",", "int", "num_bytes", ")", "{", "// allocate buffer", "byte", "buf", "[", "]", "=", "new", "byte", "[", "num_bytes", "]", ";", "// if length of addr is odd, then add an F onto the end of it", "if", "(", "(", "data", ".", "length", "(", ")", "%", "2", ")", "!=", "0", ")", "{", "data", "+=", "\"F\"", ";", "}", "int", "index", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", "(", ")", ";", "i", "+=", "2", ")", "{", "StringBuilder", "x", "=", "new", "StringBuilder", "(", "data", ".", "substring", "(", "i", ",", "i", "+", "2", ")", ")", ";", "x", ".", "reverse", "(", ")", ";", "buf", "[", "index", "]", "=", "ByteUtil", ".", "decodeHex", "(", "x", ".", "toString", "(", ")", ",", "2", ")", "[", "0", "]", ";", "index", "++", ";", "}", "return", "buf", ";", "}" ]
BCD encodes a String into a byte array.
[ "BCD", "encodes", "a", "String", "into", "a", "byte", "array", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/ByteUtil.java#L33-L51
3,568
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/TimedStateBoolean.java
TimedStateBoolean.getAndSet
public boolean getAndSet(boolean newValue) { boolean oldValue = value.getAndSet(newValue); // did the state change? if (oldValue != newValue) valueTime = System.currentTimeMillis(); return oldValue; }
java
public boolean getAndSet(boolean newValue) { boolean oldValue = value.getAndSet(newValue); // did the state change? if (oldValue != newValue) valueTime = System.currentTimeMillis(); return oldValue; }
[ "public", "boolean", "getAndSet", "(", "boolean", "newValue", ")", "{", "boolean", "oldValue", "=", "value", ".", "getAndSet", "(", "newValue", ")", ";", "// did the state change?", "if", "(", "oldValue", "!=", "newValue", ")", "valueTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "return", "oldValue", ";", "}" ]
Sets to the given value and returns the previous value. If the previous value is different than the new value, the internal "valueTime" will be updated. @param newValue The new boolean value @return
[ "Sets", "to", "the", "given", "value", "and", "returns", "the", "previous", "value", ".", "If", "the", "previous", "value", "is", "different", "than", "the", "new", "value", "the", "internal", "valueTime", "will", "be", "updated", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/TimedStateBoolean.java#L100-L106
3,569
twitter/cloudhopper-commons
ch-commons-sql/src/main/java/com/cloudhopper/commons/sql/DataSourceManager.java
DataSourceManager.create
public static DataSource create(DataSourceConfiguration configuration) throws SQLMissingDependencyException, SQLConfigurationException { // verify all required properties are configured and set configuration.validate(); // clone the configuration so we can save the properties used to create the ds DataSourceConfiguration config = (DataSourceConfiguration)configuration.clone(); // verify database driver exists and try to register the database driver try { // create a new instance Driver driver = (Driver)Class.forName(config.getDriver()).newInstance(); // put out some properties to save 'em? } catch (Exception e) { throw new SQLMissingDependencyException("Database driver '" + config.getDriver() + "' failed to load. Perhaps missing jar file?", e); } // get the class responsible for creating the datasource String adapterClass = config.getProvider().getAdapter(); // create a new instance of the adapter DataSourceAdapter adapter = null; try { adapter = (DataSourceAdapter)Class.forName(adapterClass).newInstance(); } catch (Exception e) { //throw new SQLConfigurationException("Invalid DataSourceAdapter class specified. Should be impossible error?"); throw new SQLMissingDependencyException("DataSourceAdapter '" + adapterClass + "' failed to load. Perhaps missing jar file?", e); } // delegate creating the new datasource to the adapter ManagedDataSource mds = adapter.create(config); // if the user requested this datasource to be added to jmx if (config.getJmx()) { // hmm... if jmx is turned on, let's register the MBean MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { ObjectName name = new ObjectName(config.getJmxDomain() + ":type=ManagedDataSource,name=" + config.getName()); mbs.registerMBean(mds, name); } catch (Exception e) { // log the error, but don't throw an exception for this datasource logger.error("Error while attempting to register ManagedDataSourceMBean '" + config.getName() + "'", e); } } // return the datasource return mds.getDataSource(); }
java
public static DataSource create(DataSourceConfiguration configuration) throws SQLMissingDependencyException, SQLConfigurationException { // verify all required properties are configured and set configuration.validate(); // clone the configuration so we can save the properties used to create the ds DataSourceConfiguration config = (DataSourceConfiguration)configuration.clone(); // verify database driver exists and try to register the database driver try { // create a new instance Driver driver = (Driver)Class.forName(config.getDriver()).newInstance(); // put out some properties to save 'em? } catch (Exception e) { throw new SQLMissingDependencyException("Database driver '" + config.getDriver() + "' failed to load. Perhaps missing jar file?", e); } // get the class responsible for creating the datasource String adapterClass = config.getProvider().getAdapter(); // create a new instance of the adapter DataSourceAdapter adapter = null; try { adapter = (DataSourceAdapter)Class.forName(adapterClass).newInstance(); } catch (Exception e) { //throw new SQLConfigurationException("Invalid DataSourceAdapter class specified. Should be impossible error?"); throw new SQLMissingDependencyException("DataSourceAdapter '" + adapterClass + "' failed to load. Perhaps missing jar file?", e); } // delegate creating the new datasource to the adapter ManagedDataSource mds = adapter.create(config); // if the user requested this datasource to be added to jmx if (config.getJmx()) { // hmm... if jmx is turned on, let's register the MBean MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); try { ObjectName name = new ObjectName(config.getJmxDomain() + ":type=ManagedDataSource,name=" + config.getName()); mbs.registerMBean(mds, name); } catch (Exception e) { // log the error, but don't throw an exception for this datasource logger.error("Error while attempting to register ManagedDataSourceMBean '" + config.getName() + "'", e); } } // return the datasource return mds.getDataSource(); }
[ "public", "static", "DataSource", "create", "(", "DataSourceConfiguration", "configuration", ")", "throws", "SQLMissingDependencyException", ",", "SQLConfigurationException", "{", "// verify all required properties are configured and set", "configuration", ".", "validate", "(", ")", ";", "// clone the configuration so we can save the properties used to create the ds", "DataSourceConfiguration", "config", "=", "(", "DataSourceConfiguration", ")", "configuration", ".", "clone", "(", ")", ";", "// verify database driver exists and try to register the database driver", "try", "{", "// create a new instance", "Driver", "driver", "=", "(", "Driver", ")", "Class", ".", "forName", "(", "config", ".", "getDriver", "(", ")", ")", ".", "newInstance", "(", ")", ";", "// put out some properties to save 'em?", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "SQLMissingDependencyException", "(", "\"Database driver '\"", "+", "config", ".", "getDriver", "(", ")", "+", "\"' failed to load. Perhaps missing jar file?\"", ",", "e", ")", ";", "}", "// get the class responsible for creating the datasource", "String", "adapterClass", "=", "config", ".", "getProvider", "(", ")", ".", "getAdapter", "(", ")", ";", "// create a new instance of the adapter", "DataSourceAdapter", "adapter", "=", "null", ";", "try", "{", "adapter", "=", "(", "DataSourceAdapter", ")", "Class", ".", "forName", "(", "adapterClass", ")", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "//throw new SQLConfigurationException(\"Invalid DataSourceAdapter class specified. Should be impossible error?\");", "throw", "new", "SQLMissingDependencyException", "(", "\"DataSourceAdapter '\"", "+", "adapterClass", "+", "\"' failed to load. Perhaps missing jar file?\"", ",", "e", ")", ";", "}", "// delegate creating the new datasource to the adapter", "ManagedDataSource", "mds", "=", "adapter", ".", "create", "(", "config", ")", ";", "// if the user requested this datasource to be added to jmx", "if", "(", "config", ".", "getJmx", "(", ")", ")", "{", "// hmm... if jmx is turned on, let's register the MBean", "MBeanServer", "mbs", "=", "ManagementFactory", ".", "getPlatformMBeanServer", "(", ")", ";", "try", "{", "ObjectName", "name", "=", "new", "ObjectName", "(", "config", ".", "getJmxDomain", "(", ")", "+", "\":type=ManagedDataSource,name=\"", "+", "config", ".", "getName", "(", ")", ")", ";", "mbs", ".", "registerMBean", "(", "mds", ",", "name", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "// log the error, but don't throw an exception for this datasource", "logger", ".", "error", "(", "\"Error while attempting to register ManagedDataSourceMBean '\"", "+", "config", ".", "getName", "(", ")", "+", "\"'\"", ",", "e", ")", ";", "}", "}", "// return the datasource", "return", "mds", ".", "getDataSource", "(", ")", ";", "}" ]
Creates a new DataSource from the DataSourceConfiguration. @param configuration The configuration of the DataSource @return A new DataSource tied to the configuration @throws SQLMissingDependencyException Thrown if a dependency (external jar) is missing from the configuration. @throws SQLConfigurationException Thrown if there was an error while configuring the DataSource.
[ "Creates", "a", "new", "DataSource", "from", "the", "DataSourceConfiguration", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-sql/src/main/java/com/cloudhopper/commons/sql/DataSourceManager.java#L73-L119
3,570
twitter/cloudhopper-commons
ch-commons-xbean/src/main/java/com/cloudhopper/commons/xbean/TypeConverterUtil.java
TypeConverterUtil.convert
static public <E> E convert(String s, Class<E> type) throws ConversionException { // if enum, handle differently if (type.isEnum()) { Object obj = ClassUtil.findEnumConstant(type, s); if (obj == null) { throw new ConversionException("Invalid constant [" + s + "] used, supported values [" + toListString(type.getEnumConstants()) + "]"); } return (E)obj; // else, handle normally } else { TypeConverter converter = REGISTRY.get(type); if (converter == null) { throw new ConversionException("The type [" + type.getSimpleName() + "] is not supported"); } return (E)converter.convert(s); } }
java
static public <E> E convert(String s, Class<E> type) throws ConversionException { // if enum, handle differently if (type.isEnum()) { Object obj = ClassUtil.findEnumConstant(type, s); if (obj == null) { throw new ConversionException("Invalid constant [" + s + "] used, supported values [" + toListString(type.getEnumConstants()) + "]"); } return (E)obj; // else, handle normally } else { TypeConverter converter = REGISTRY.get(type); if (converter == null) { throw new ConversionException("The type [" + type.getSimpleName() + "] is not supported"); } return (E)converter.convert(s); } }
[ "static", "public", "<", "E", ">", "E", "convert", "(", "String", "s", ",", "Class", "<", "E", ">", "type", ")", "throws", "ConversionException", "{", "// if enum, handle differently", "if", "(", "type", ".", "isEnum", "(", ")", ")", "{", "Object", "obj", "=", "ClassUtil", ".", "findEnumConstant", "(", "type", ",", "s", ")", ";", "if", "(", "obj", "==", "null", ")", "{", "throw", "new", "ConversionException", "(", "\"Invalid constant [\"", "+", "s", "+", "\"] used, supported values [\"", "+", "toListString", "(", "type", ".", "getEnumConstants", "(", ")", ")", "+", "\"]\"", ")", ";", "}", "return", "(", "E", ")", "obj", ";", "// else, handle normally", "}", "else", "{", "TypeConverter", "converter", "=", "REGISTRY", ".", "get", "(", "type", ")", ";", "if", "(", "converter", "==", "null", ")", "{", "throw", "new", "ConversionException", "(", "\"The type [\"", "+", "type", ".", "getSimpleName", "(", ")", "+", "\"] is not supported\"", ")", ";", "}", "return", "(", "E", ")", "converter", ".", "convert", "(", "s", ")", ";", "}", "}" ]
Converts the string value into an Object of the Class type. Will either delegate conversion to a PropertyConverter or will handle creating enums directly. @param string0 The string value to convert @param type The Class type to convert it into @return A new Object converted from the String value
[ "Converts", "the", "string", "value", "into", "an", "Object", "of", "the", "Class", "type", ".", "Will", "either", "delegate", "conversion", "to", "a", "PropertyConverter", "or", "will", "handle", "creating", "enums", "directly", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-xbean/src/main/java/com/cloudhopper/commons/xbean/TypeConverterUtil.java#L95-L113
3,571
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/FileUtil.java
FileUtil.isValidFileExtension
public static boolean isValidFileExtension(String extension) { for (int i = 0; i < extension.length(); i++) { char c = extension.charAt(i); if (!(Character.isDigit(c) || Character.isLetter(c) || c == '_')) { return false; } } return true; }
java
public static boolean isValidFileExtension(String extension) { for (int i = 0; i < extension.length(); i++) { char c = extension.charAt(i); if (!(Character.isDigit(c) || Character.isLetter(c) || c == '_')) { return false; } } return true; }
[ "public", "static", "boolean", "isValidFileExtension", "(", "String", "extension", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "extension", ".", "length", "(", ")", ";", "i", "++", ")", "{", "char", "c", "=", "extension", ".", "charAt", "(", "i", ")", ";", "if", "(", "!", "(", "Character", ".", "isDigit", "(", "c", ")", "||", "Character", ".", "isLetter", "(", "c", ")", "||", "c", "==", "'", "'", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Checks if the extension is valid. This method only permits letters, digits, and an underscore character. @param extension The file extension to validate @return True if its valid, otherwise false
[ "Checks", "if", "the", "extension", "is", "valid", ".", "This", "method", "only", "permits", "letters", "digits", "and", "an", "underscore", "character", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/FileUtil.java#L140-L148
3,572
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/FileUtil.java
FileUtil.parseFileExtension
public static String parseFileExtension(String filename) { // if null, return null if (filename == null) { return null; } // find position of last period int pos = filename.lastIndexOf('.'); // did one exist or have any length? if (pos < 0 || (pos+1) >= filename.length()) { return null; } // parse extension return filename.substring(pos+1); }
java
public static String parseFileExtension(String filename) { // if null, return null if (filename == null) { return null; } // find position of last period int pos = filename.lastIndexOf('.'); // did one exist or have any length? if (pos < 0 || (pos+1) >= filename.length()) { return null; } // parse extension return filename.substring(pos+1); }
[ "public", "static", "String", "parseFileExtension", "(", "String", "filename", ")", "{", "// if null, return null", "if", "(", "filename", "==", "null", ")", "{", "return", "null", ";", "}", "// find position of last period", "int", "pos", "=", "filename", ".", "lastIndexOf", "(", "'", "'", ")", ";", "// did one exist or have any length?", "if", "(", "pos", "<", "0", "||", "(", "pos", "+", "1", ")", ">=", "filename", ".", "length", "(", ")", ")", "{", "return", "null", ";", "}", "// parse extension", "return", "filename", ".", "substring", "(", "pos", "+", "1", ")", ";", "}" ]
Parse the filename and return the file extension. For example, if the file is "app.2006-10-10.log", then this method will return "log". Will only return the last file extension. For example, if the filename ends with ".log.gz", then this method will return "gz" @param String to process containing the filename @return The file extension (without leading period) such as "gz" or "txt" or null if none exists.
[ "Parse", "the", "filename", "and", "return", "the", "file", "extension", ".", "For", "example", "if", "the", "file", "is", "app", ".", "2006", "-", "10", "-", "10", ".", "log", "then", "this", "method", "will", "return", "log", ".", "Will", "only", "return", "the", "last", "file", "extension", ".", "For", "example", "if", "the", "filename", "ends", "with", ".", "log", ".", "gz", "then", "this", "method", "will", "return", "gz" ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/FileUtil.java#L159-L172
3,573
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/FileUtil.java
FileUtil.copy
public static void copy(File sourceFile, File targetFile) throws FileAlreadyExistsException, IOException { copy(sourceFile, targetFile, false); }
java
public static void copy(File sourceFile, File targetFile) throws FileAlreadyExistsException, IOException { copy(sourceFile, targetFile, false); }
[ "public", "static", "void", "copy", "(", "File", "sourceFile", ",", "File", "targetFile", ")", "throws", "FileAlreadyExistsException", ",", "IOException", "{", "copy", "(", "sourceFile", ",", "targetFile", ",", "false", ")", ";", "}" ]
Copy the source file to the target file. @param sourceFile The source file to copy from @param targetFile The target file to copy to @throws FileAlreadyExistsException Thrown if the target file already exists. This exception is a subclass of IOException, so catching an IOException is enough if you don't care about this specific reason. @throws IOException Thrown if an error during the copy
[ "Copy", "the", "source", "file", "to", "the", "target", "file", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/FileUtil.java#L335-L337
3,574
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/FileUtil.java
FileUtil.copy
public static boolean copy(File sourceFile, File targetFile, boolean overwrite) throws FileAlreadyExistsException, IOException { boolean overwriteOccurred = false; // check if the targetFile already exists if (targetFile.exists()) { // if overwrite is not allowed, throw an exception if (!overwrite) { throw new FileAlreadyExistsException("Target file " + targetFile + " already exists"); } else { // set the flag that it occurred overwriteOccurred = true; } } // proceed with copy FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetFile); fis.getChannel().transferTo(0, sourceFile.length(), fos.getChannel()); fis.close(); fos.flush(); fos.close(); return overwriteOccurred; }
java
public static boolean copy(File sourceFile, File targetFile, boolean overwrite) throws FileAlreadyExistsException, IOException { boolean overwriteOccurred = false; // check if the targetFile already exists if (targetFile.exists()) { // if overwrite is not allowed, throw an exception if (!overwrite) { throw new FileAlreadyExistsException("Target file " + targetFile + " already exists"); } else { // set the flag that it occurred overwriteOccurred = true; } } // proceed with copy FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetFile); fis.getChannel().transferTo(0, sourceFile.length(), fos.getChannel()); fis.close(); fos.flush(); fos.close(); return overwriteOccurred; }
[ "public", "static", "boolean", "copy", "(", "File", "sourceFile", ",", "File", "targetFile", ",", "boolean", "overwrite", ")", "throws", "FileAlreadyExistsException", ",", "IOException", "{", "boolean", "overwriteOccurred", "=", "false", ";", "// check if the targetFile already exists", "if", "(", "targetFile", ".", "exists", "(", ")", ")", "{", "// if overwrite is not allowed, throw an exception", "if", "(", "!", "overwrite", ")", "{", "throw", "new", "FileAlreadyExistsException", "(", "\"Target file \"", "+", "targetFile", "+", "\" already exists\"", ")", ";", "}", "else", "{", "// set the flag that it occurred", "overwriteOccurred", "=", "true", ";", "}", "}", "// proceed with copy", "FileInputStream", "fis", "=", "new", "FileInputStream", "(", "sourceFile", ")", ";", "FileOutputStream", "fos", "=", "new", "FileOutputStream", "(", "targetFile", ")", ";", "fis", ".", "getChannel", "(", ")", ".", "transferTo", "(", "0", ",", "sourceFile", ".", "length", "(", ")", ",", "fos", ".", "getChannel", "(", ")", ")", ";", "fis", ".", "close", "(", ")", ";", "fos", ".", "flush", "(", ")", ";", "fos", ".", "close", "(", ")", ";", "return", "overwriteOccurred", ";", "}" ]
Copy the source file to the target file while optionally permitting an overwrite to occur in case the target file already exists. @param sourceFile The source file to copy from @param targetFile The target file to copy to @return True if an overwrite occurred, otherwise false. @throws FileAlreadyExistsException Thrown if the target file already exists and an overwrite is not permitted. This exception is a subclass of IOException, so catching an IOException is enough if you don't care about this specific reason. @throws IOException Thrown if an error during the copy
[ "Copy", "the", "source", "file", "to", "the", "target", "file", "while", "optionally", "permitting", "an", "overwrite", "to", "occur", "in", "case", "the", "target", "file", "already", "exists", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/FileUtil.java#L351-L374
3,575
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/filefilter/FileExtensionFilter.java
FileExtensionFilter.accept
public boolean accept(File file) { // extract this file's extension String fileExt = FileUtil.parseFileExtension(file.getName()); // a file extension might not have existed if (fileExt == null) { // if no file extension extracted, this definitely is not a match return false; } // does it match our list of acceptable file extensions? for (String extension : extensions) { if (caseSensitive) { if (fileExt.equals(extension)) { return true; } } else { if (fileExt.equalsIgnoreCase(extension)) { return true; } } } // if we got here, then no match was found return false; }
java
public boolean accept(File file) { // extract this file's extension String fileExt = FileUtil.parseFileExtension(file.getName()); // a file extension might not have existed if (fileExt == null) { // if no file extension extracted, this definitely is not a match return false; } // does it match our list of acceptable file extensions? for (String extension : extensions) { if (caseSensitive) { if (fileExt.equals(extension)) { return true; } } else { if (fileExt.equalsIgnoreCase(extension)) { return true; } } } // if we got here, then no match was found return false; }
[ "public", "boolean", "accept", "(", "File", "file", ")", "{", "// extract this file's extension", "String", "fileExt", "=", "FileUtil", ".", "parseFileExtension", "(", "file", ".", "getName", "(", ")", ")", ";", "// a file extension might not have existed", "if", "(", "fileExt", "==", "null", ")", "{", "// if no file extension extracted, this definitely is not a match", "return", "false", ";", "}", "// does it match our list of acceptable file extensions?", "for", "(", "String", "extension", ":", "extensions", ")", "{", "if", "(", "caseSensitive", ")", "{", "if", "(", "fileExt", ".", "equals", "(", "extension", ")", ")", "{", "return", "true", ";", "}", "}", "else", "{", "if", "(", "fileExt", ".", "equalsIgnoreCase", "(", "extension", ")", ")", "{", "return", "true", ";", "}", "}", "}", "// if we got here, then no match was found", "return", "false", ";", "}" ]
Accepts a File by its file extension. @param file The file to match @return True if the File matches this the array of acceptable file extensions.
[ "Accepts", "a", "File", "by", "its", "file", "extension", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/filefilter/FileExtensionFilter.java#L102-L127
3,576
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/MetaFieldUtil.java
MetaFieldUtil.toMetaFieldInfoString
public static String toMetaFieldInfoString(Object obj) { StringBuffer buf = new StringBuffer(100); MetaFieldInfo[] fields = toMetaFieldInfoArray(obj, null, true); for (int i = 0; i < fields.length; i++) { MetaFieldInfo field = fields[i]; buf.append(field.name); buf.append("="); // if the field's actual value is non-null and of type String if (field.actualValue != null && field.actualValue.getClass().equals(String.class)) { buf.append('"'); buf.append(field.value); buf.append('"'); } else { buf.append(field.value); } // if not last element, delimit with a comma if (i+1 < fields.length) buf.append(","); } return buf.toString(); }
java
public static String toMetaFieldInfoString(Object obj) { StringBuffer buf = new StringBuffer(100); MetaFieldInfo[] fields = toMetaFieldInfoArray(obj, null, true); for (int i = 0; i < fields.length; i++) { MetaFieldInfo field = fields[i]; buf.append(field.name); buf.append("="); // if the field's actual value is non-null and of type String if (field.actualValue != null && field.actualValue.getClass().equals(String.class)) { buf.append('"'); buf.append(field.value); buf.append('"'); } else { buf.append(field.value); } // if not last element, delimit with a comma if (i+1 < fields.length) buf.append(","); } return buf.toString(); }
[ "public", "static", "String", "toMetaFieldInfoString", "(", "Object", "obj", ")", "{", "StringBuffer", "buf", "=", "new", "StringBuffer", "(", "100", ")", ";", "MetaFieldInfo", "[", "]", "fields", "=", "toMetaFieldInfoArray", "(", "obj", ",", "null", ",", "true", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "fields", ".", "length", ";", "i", "++", ")", "{", "MetaFieldInfo", "field", "=", "fields", "[", "i", "]", ";", "buf", ".", "append", "(", "field", ".", "name", ")", ";", "buf", ".", "append", "(", "\"=\"", ")", ";", "// if the field's actual value is non-null and of type String", "if", "(", "field", ".", "actualValue", "!=", "null", "&&", "field", ".", "actualValue", ".", "getClass", "(", ")", ".", "equals", "(", "String", ".", "class", ")", ")", "{", "buf", ".", "append", "(", "'", "'", ")", ";", "buf", ".", "append", "(", "field", ".", "value", ")", ";", "buf", ".", "append", "(", "'", "'", ")", ";", "}", "else", "{", "buf", ".", "append", "(", "field", ".", "value", ")", ";", "}", "// if not last element, delimit with a comma", "if", "(", "i", "+", "1", "<", "fields", ".", "length", ")", "buf", ".", "append", "(", "\",\"", ")", ";", "}", "return", "buf", ".", "toString", "(", ")", ";", "}" ]
Creates a string for an object based on the MetaField annotations. @param obj The object to search @return A string representing the current values of any MetaFields
[ "Creates", "a", "string", "for", "an", "object", "based", "on", "the", "MetaField", "annotations", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/MetaFieldUtil.java#L47-L67
3,577
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/MetaFieldUtil.java
MetaFieldUtil.toMetaFieldInfoArray
public static MetaFieldInfo[] toMetaFieldInfoArray(Class type, Object obj, String stringForNullValues, boolean ignoreAnnotatedName, boolean recursive) { return internalToMetaFieldInfoArray(type, obj, null, null, stringForNullValues, ignoreAnnotatedName, recursive); }
java
public static MetaFieldInfo[] toMetaFieldInfoArray(Class type, Object obj, String stringForNullValues, boolean ignoreAnnotatedName, boolean recursive) { return internalToMetaFieldInfoArray(type, obj, null, null, stringForNullValues, ignoreAnnotatedName, recursive); }
[ "public", "static", "MetaFieldInfo", "[", "]", "toMetaFieldInfoArray", "(", "Class", "type", ",", "Object", "obj", ",", "String", "stringForNullValues", ",", "boolean", "ignoreAnnotatedName", ",", "boolean", "recursive", ")", "{", "return", "internalToMetaFieldInfoArray", "(", "type", ",", "obj", ",", "null", ",", "null", ",", "stringForNullValues", ",", "ignoreAnnotatedName", ",", "recursive", ")", ";", "}" ]
Returns a new MetaFieldInfo array of all Fields annotated with MetaField in the object type. The object must be an instance of the type, otherwise this method may throw a runtime exception. Optionally, this method can recursively search the object to provide a deep view of the entire class. @param type The class type of the object @param obj The runtime instance of the object to search. It must be an instance of the type. If its a subclass of the type, this method will only return MetaFields of the type passed in. @param stringForNullValues If a field is null, this is the string to swap in as the String value vs. "null" showing up. @param ignoreAnnotatedName Whether to ignore the name of the MetaField and always return the field name instead. If false, this method will use the annotated name if it exists, otherwise it'll use the field name. @param recursive If true, this method will recursively search any fields to see if they also contain MetaField annotations. If they do, this method will include those in its returned array. @return The MetaFieldInfo array
[ "Returns", "a", "new", "MetaFieldInfo", "array", "of", "all", "Fields", "annotated", "with", "MetaField", "in", "the", "object", "type", ".", "The", "object", "must", "be", "an", "instance", "of", "the", "type", "otherwise", "this", "method", "may", "throw", "a", "runtime", "exception", ".", "Optionally", "this", "method", "can", "recursively", "search", "the", "object", "to", "provide", "a", "deep", "view", "of", "the", "entire", "class", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/MetaFieldUtil.java#L138-L140
3,578
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/time/DateTimePeriod.java
DateTimePeriod.toMonths
public List<DateTimePeriod> toMonths() { ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>(); // default "current" month to start datetime DateTime currentStart = getStart(); // calculate "next" month DateTime nextStart = currentStart.plusMonths(1); // continue adding until we've reached the end while (nextStart.isBefore(getEnd()) || nextStart.isEqual(getEnd())) { // its okay to add the current list.add(new DateTimeMonth(currentStart, nextStart)); // increment both currentStart = nextStart; nextStart = currentStart.plusMonths(1); } return list; }
java
public List<DateTimePeriod> toMonths() { ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>(); // default "current" month to start datetime DateTime currentStart = getStart(); // calculate "next" month DateTime nextStart = currentStart.plusMonths(1); // continue adding until we've reached the end while (nextStart.isBefore(getEnd()) || nextStart.isEqual(getEnd())) { // its okay to add the current list.add(new DateTimeMonth(currentStart, nextStart)); // increment both currentStart = nextStart; nextStart = currentStart.plusMonths(1); } return list; }
[ "public", "List", "<", "DateTimePeriod", ">", "toMonths", "(", ")", "{", "ArrayList", "<", "DateTimePeriod", ">", "list", "=", "new", "ArrayList", "<", "DateTimePeriod", ">", "(", ")", ";", "// default \"current\" month to start datetime", "DateTime", "currentStart", "=", "getStart", "(", ")", ";", "// calculate \"next\" month", "DateTime", "nextStart", "=", "currentStart", ".", "plusMonths", "(", "1", ")", ";", "// continue adding until we've reached the end", "while", "(", "nextStart", ".", "isBefore", "(", "getEnd", "(", ")", ")", "||", "nextStart", ".", "isEqual", "(", "getEnd", "(", ")", ")", ")", "{", "// its okay to add the current", "list", ".", "add", "(", "new", "DateTimeMonth", "(", "currentStart", ",", "nextStart", ")", ")", ";", "// increment both", "currentStart", "=", "nextStart", ";", "nextStart", "=", "currentStart", ".", "plusMonths", "(", "1", ")", ";", "}", "return", "list", ";", "}" ]
Converts this period to a list of month periods. Partial months will not be included. For example, a period of "2009" will return a list of 12 months - one for each month in 2009. On the other hand, a period of "January 20, 2009" would return an empty list since partial months are not included. @return A list of month periods contained within this period
[ "Converts", "this", "period", "to", "a", "list", "of", "month", "periods", ".", "Partial", "months", "will", "not", "be", "included", ".", "For", "example", "a", "period", "of", "2009", "will", "return", "a", "list", "of", "12", "months", "-", "one", "for", "each", "month", "in", "2009", ".", "On", "the", "other", "hand", "a", "period", "of", "January", "20", "2009", "would", "return", "an", "empty", "list", "since", "partial", "months", "are", "not", "included", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/time/DateTimePeriod.java#L327-L344
3,579
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/time/DateTimePeriod.java
DateTimePeriod.toYears
public List<DateTimePeriod> toYears() { ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>(); // default "current" year to start datetime DateTime currentStart = getStart(); // calculate "next" year DateTime nextStart = currentStart.plusYears(1); // continue adding until we've reached the end while (nextStart.isBefore(getEnd()) || nextStart.isEqual(getEnd())) { // its okay to add the current list.add(new DateTimeYear(currentStart, nextStart)); // increment both currentStart = nextStart; nextStart = currentStart.plusYears(1); } return list; }
java
public List<DateTimePeriod> toYears() { ArrayList<DateTimePeriod> list = new ArrayList<DateTimePeriod>(); // default "current" year to start datetime DateTime currentStart = getStart(); // calculate "next" year DateTime nextStart = currentStart.plusYears(1); // continue adding until we've reached the end while (nextStart.isBefore(getEnd()) || nextStart.isEqual(getEnd())) { // its okay to add the current list.add(new DateTimeYear(currentStart, nextStart)); // increment both currentStart = nextStart; nextStart = currentStart.plusYears(1); } return list; }
[ "public", "List", "<", "DateTimePeriod", ">", "toYears", "(", ")", "{", "ArrayList", "<", "DateTimePeriod", ">", "list", "=", "new", "ArrayList", "<", "DateTimePeriod", ">", "(", ")", ";", "// default \"current\" year to start datetime", "DateTime", "currentStart", "=", "getStart", "(", ")", ";", "// calculate \"next\" year", "DateTime", "nextStart", "=", "currentStart", ".", "plusYears", "(", "1", ")", ";", "// continue adding until we've reached the end", "while", "(", "nextStart", ".", "isBefore", "(", "getEnd", "(", ")", ")", "||", "nextStart", ".", "isEqual", "(", "getEnd", "(", ")", ")", ")", "{", "// its okay to add the current", "list", ".", "add", "(", "new", "DateTimeYear", "(", "currentStart", ",", "nextStart", ")", ")", ";", "// increment both", "currentStart", "=", "nextStart", ";", "nextStart", "=", "currentStart", ".", "plusYears", "(", "1", ")", ";", "}", "return", "list", ";", "}" ]
Converts this period to a list of year periods. Partial years will not be included. For example, a period of "2009-2010" will return a list of 2 years - one for 2009 and one for 2010. On the other hand, a period of "January 2009" would return an empty list since partial years are not included. @return A list of year periods contained within this period
[ "Converts", "this", "period", "to", "a", "list", "of", "year", "periods", ".", "Partial", "years", "will", "not", "be", "included", ".", "For", "example", "a", "period", "of", "2009", "-", "2010", "will", "return", "a", "list", "of", "2", "years", "-", "one", "for", "2009", "and", "one", "for", "2010", ".", "On", "the", "other", "hand", "a", "period", "of", "January", "2009", "would", "return", "an", "empty", "list", "since", "partial", "years", "are", "not", "included", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/time/DateTimePeriod.java#L354-L371
3,580
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/time/DateTimePeriod.java
DateTimePeriod.create
static public DateTimePeriod create(DateTimeDuration duration, DateTime start) { if (duration == DateTimeDuration.YEAR) { return createYear(start); } else if (duration == DateTimeDuration.MONTH) { return createMonth(start); } else if (duration == DateTimeDuration.DAY) { return createDay(start); } else if (duration == DateTimeDuration.HOUR) { return createHour(start); } else if (duration == DateTimeDuration.FIVE_MINUTES) { return createFiveMinutes(start); } else { throw new UnsupportedOperationException("Duration " + duration + " not yet supported"); } }
java
static public DateTimePeriod create(DateTimeDuration duration, DateTime start) { if (duration == DateTimeDuration.YEAR) { return createYear(start); } else if (duration == DateTimeDuration.MONTH) { return createMonth(start); } else if (duration == DateTimeDuration.DAY) { return createDay(start); } else if (duration == DateTimeDuration.HOUR) { return createHour(start); } else if (duration == DateTimeDuration.FIVE_MINUTES) { return createFiveMinutes(start); } else { throw new UnsupportedOperationException("Duration " + duration + " not yet supported"); } }
[ "static", "public", "DateTimePeriod", "create", "(", "DateTimeDuration", "duration", ",", "DateTime", "start", ")", "{", "if", "(", "duration", "==", "DateTimeDuration", ".", "YEAR", ")", "{", "return", "createYear", "(", "start", ")", ";", "}", "else", "if", "(", "duration", "==", "DateTimeDuration", ".", "MONTH", ")", "{", "return", "createMonth", "(", "start", ")", ";", "}", "else", "if", "(", "duration", "==", "DateTimeDuration", ".", "DAY", ")", "{", "return", "createDay", "(", "start", ")", ";", "}", "else", "if", "(", "duration", "==", "DateTimeDuration", ".", "HOUR", ")", "{", "return", "createHour", "(", "start", ")", ";", "}", "else", "if", "(", "duration", "==", "DateTimeDuration", ".", "FIVE_MINUTES", ")", "{", "return", "createFiveMinutes", "(", "start", ")", ";", "}", "else", "{", "throw", "new", "UnsupportedOperationException", "(", "\"Duration \"", "+", "duration", "+", "\" not yet supported\"", ")", ";", "}", "}" ]
Creates a new period for the specified duration starting from the provided DateTime. @param duration The duration for this period such as Month, Hour, etc. @param start The DateTime to start this period from @return A new period
[ "Creates", "a", "new", "period", "for", "the", "specified", "duration", "starting", "from", "the", "provided", "DateTime", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/time/DateTimePeriod.java#L423-L437
3,581
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/time/DateTimePeriod.java
DateTimePeriod.createLastYearMonths
static public List<DateTimePeriod> createLastYearMonths(DateTimeZone zone) { ArrayList<DateTimePeriod> periods = new ArrayList<DateTimePeriod>(); // get today's date DateTime now = new DateTime(zone); // start with today's current month and 11 others (last 12 months) for (int i = 0; i < 12; i++) { // create a new period DateTimePeriod period = createMonth(now.getYear(), now.getMonthOfYear(), zone); periods.add(period); // subtract 1 month now = now.minusMonths(1); } return periods; }
java
static public List<DateTimePeriod> createLastYearMonths(DateTimeZone zone) { ArrayList<DateTimePeriod> periods = new ArrayList<DateTimePeriod>(); // get today's date DateTime now = new DateTime(zone); // start with today's current month and 11 others (last 12 months) for (int i = 0; i < 12; i++) { // create a new period DateTimePeriod period = createMonth(now.getYear(), now.getMonthOfYear(), zone); periods.add(period); // subtract 1 month now = now.minusMonths(1); } return periods; }
[ "static", "public", "List", "<", "DateTimePeriod", ">", "createLastYearMonths", "(", "DateTimeZone", "zone", ")", "{", "ArrayList", "<", "DateTimePeriod", ">", "periods", "=", "new", "ArrayList", "<", "DateTimePeriod", ">", "(", ")", ";", "// get today's date", "DateTime", "now", "=", "new", "DateTime", "(", "zone", ")", ";", "// start with today's current month and 11 others (last 12 months)", "for", "(", "int", "i", "=", "0", ";", "i", "<", "12", ";", "i", "++", ")", "{", "// create a new period", "DateTimePeriod", "period", "=", "createMonth", "(", "now", ".", "getYear", "(", ")", ",", "now", ".", "getMonthOfYear", "(", ")", ",", "zone", ")", ";", "periods", ".", "add", "(", "period", ")", ";", "// subtract 1 month", "now", "=", "now", ".", "minusMonths", "(", "1", ")", ";", "}", "return", "periods", ";", "}" ]
Create a list of DateTimePeriods that represent the last year of YearMonth periods. For example, if its currently January 2009, this would return periods representing "January 2009, December 2008, ... February 2008" @param zone @return
[ "Create", "a", "list", "of", "DateTimePeriods", "that", "represent", "the", "last", "year", "of", "YearMonth", "periods", ".", "For", "example", "if", "its", "currently", "January", "2009", "this", "would", "return", "periods", "representing", "January", "2009", "December", "2008", "...", "February", "2008" ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/time/DateTimePeriod.java#L503-L519
3,582
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/EnvironmentUtil.java
EnvironmentUtil.createCommonSystemProperties
public static Properties createCommonSystemProperties() throws EnvironmentException { // create a new system properties object Properties systemProperties = new Properties(); // host name, domain, fqdn String hostFQDN = getHostFQDN(); if (!StringUtil.isEmpty(hostFQDN)) { // save the fqdn systemProperties.put(HOST_FQDN, hostFQDN); // split up the fqdn to find the host name and domain String[] hostInfo = splitHostFQDN(hostFQDN); // save the host name and domain, defaulting to an empty string if null systemProperties.put(HOST_NAME, (hostInfo[0] != null ? hostInfo[0] : "")); systemProperties.put(HOST_DOMAIN, (hostInfo[1] != null ? hostInfo[1] : "")); // add a new host name //systemProperties.put(HOST_NAME, hostname); } else { systemProperties.put(HOST_FQDN, ""); systemProperties.put(HOST_NAME, ""); systemProperties.put(HOST_DOMAIN, ""); } return systemProperties; }
java
public static Properties createCommonSystemProperties() throws EnvironmentException { // create a new system properties object Properties systemProperties = new Properties(); // host name, domain, fqdn String hostFQDN = getHostFQDN(); if (!StringUtil.isEmpty(hostFQDN)) { // save the fqdn systemProperties.put(HOST_FQDN, hostFQDN); // split up the fqdn to find the host name and domain String[] hostInfo = splitHostFQDN(hostFQDN); // save the host name and domain, defaulting to an empty string if null systemProperties.put(HOST_NAME, (hostInfo[0] != null ? hostInfo[0] : "")); systemProperties.put(HOST_DOMAIN, (hostInfo[1] != null ? hostInfo[1] : "")); // add a new host name //systemProperties.put(HOST_NAME, hostname); } else { systemProperties.put(HOST_FQDN, ""); systemProperties.put(HOST_NAME, ""); systemProperties.put(HOST_DOMAIN, ""); } return systemProperties; }
[ "public", "static", "Properties", "createCommonSystemProperties", "(", ")", "throws", "EnvironmentException", "{", "// create a new system properties object", "Properties", "systemProperties", "=", "new", "Properties", "(", ")", ";", "// host name, domain, fqdn", "String", "hostFQDN", "=", "getHostFQDN", "(", ")", ";", "if", "(", "!", "StringUtil", ".", "isEmpty", "(", "hostFQDN", ")", ")", "{", "// save the fqdn", "systemProperties", ".", "put", "(", "HOST_FQDN", ",", "hostFQDN", ")", ";", "// split up the fqdn to find the host name and domain", "String", "[", "]", "hostInfo", "=", "splitHostFQDN", "(", "hostFQDN", ")", ";", "// save the host name and domain, defaulting to an empty string if null", "systemProperties", ".", "put", "(", "HOST_NAME", ",", "(", "hostInfo", "[", "0", "]", "!=", "null", "?", "hostInfo", "[", "0", "]", ":", "\"\"", ")", ")", ";", "systemProperties", ".", "put", "(", "HOST_DOMAIN", ",", "(", "hostInfo", "[", "1", "]", "!=", "null", "?", "hostInfo", "[", "1", "]", ":", "\"\"", ")", ")", ";", "// add a new host name", "//systemProperties.put(HOST_NAME, hostname);", "}", "else", "{", "systemProperties", ".", "put", "(", "HOST_FQDN", ",", "\"\"", ")", ";", "systemProperties", ".", "put", "(", "HOST_NAME", ",", "\"\"", ")", ";", "systemProperties", ".", "put", "(", "HOST_DOMAIN", ",", "\"\"", ")", ";", "}", "return", "systemProperties", ";", "}" ]
Creates a Properties object containing common system properties that are determined using various Java routines. For example, determining the hostname that the application is running on. HOST_NAME HOST_DOMAIN @return
[ "Creates", "a", "Properties", "object", "containing", "common", "system", "properties", "that", "are", "determined", "using", "various", "Java", "routines", ".", "For", "example", "determining", "the", "hostname", "that", "the", "application", "is", "running", "on", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/EnvironmentUtil.java#L48-L75
3,583
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/ThreadUtil.java
ThreadUtil.getAllThreads
static public Thread[] getAllThreads() { final ThreadGroup root = getRootThreadGroup(); final ThreadMXBean thbean = ManagementFactory.getThreadMXBean(); int nAlloc = thbean.getThreadCount(); int n = 0; Thread[] threads; do { nAlloc *= 2; threads = new Thread[nAlloc]; n = root.enumerate(threads, true); } while (n == nAlloc); return java.util.Arrays.copyOf(threads, n); }
java
static public Thread[] getAllThreads() { final ThreadGroup root = getRootThreadGroup(); final ThreadMXBean thbean = ManagementFactory.getThreadMXBean(); int nAlloc = thbean.getThreadCount(); int n = 0; Thread[] threads; do { nAlloc *= 2; threads = new Thread[nAlloc]; n = root.enumerate(threads, true); } while (n == nAlloc); return java.util.Arrays.copyOf(threads, n); }
[ "static", "public", "Thread", "[", "]", "getAllThreads", "(", ")", "{", "final", "ThreadGroup", "root", "=", "getRootThreadGroup", "(", ")", ";", "final", "ThreadMXBean", "thbean", "=", "ManagementFactory", ".", "getThreadMXBean", "(", ")", ";", "int", "nAlloc", "=", "thbean", ".", "getThreadCount", "(", ")", ";", "int", "n", "=", "0", ";", "Thread", "[", "]", "threads", ";", "do", "{", "nAlloc", "*=", "2", ";", "threads", "=", "new", "Thread", "[", "nAlloc", "]", ";", "n", "=", "root", ".", "enumerate", "(", "threads", ",", "true", ")", ";", "}", "while", "(", "n", "==", "nAlloc", ")", ";", "return", "java", ".", "util", ".", "Arrays", ".", "copyOf", "(", "threads", ",", "n", ")", ";", "}" ]
Gets all threads in the JVM. This is really a snapshot of all threads at the time this method is called. @return An array of all threads currently running in the JVM.
[ "Gets", "all", "threads", "in", "the", "JVM", ".", "This", "is", "really", "a", "snapshot", "of", "all", "threads", "at", "the", "time", "this", "method", "is", "called", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/ThreadUtil.java#L58-L70
3,584
twitter/cloudhopper-commons
ch-commons-sql/src/main/java/com/cloudhopper/commons/sql/DataSourceConfiguration.java
DataSourceConfiguration.validate
public void validate() throws SQLConfigurationException { if (this.url == null) { throw new SQLConfigurationException("url is a required property"); } if (this.username == null) { throw new SQLConfigurationException("username is a required property"); } /* password isn't required in many databases if (this.password == null) { throw new SQLConfigurationException("password is a required property"); } */ if (this.name == null) { throw new SQLConfigurationException("name is a required property"); } if (this.driver == null) { throw new SQLConfigurationException("driver is a required property"); } }
java
public void validate() throws SQLConfigurationException { if (this.url == null) { throw new SQLConfigurationException("url is a required property"); } if (this.username == null) { throw new SQLConfigurationException("username is a required property"); } /* password isn't required in many databases if (this.password == null) { throw new SQLConfigurationException("password is a required property"); } */ if (this.name == null) { throw new SQLConfigurationException("name is a required property"); } if (this.driver == null) { throw new SQLConfigurationException("driver is a required property"); } }
[ "public", "void", "validate", "(", ")", "throws", "SQLConfigurationException", "{", "if", "(", "this", ".", "url", "==", "null", ")", "{", "throw", "new", "SQLConfigurationException", "(", "\"url is a required property\"", ")", ";", "}", "if", "(", "this", ".", "username", "==", "null", ")", "{", "throw", "new", "SQLConfigurationException", "(", "\"username is a required property\"", ")", ";", "}", "/* password isn't required in many databases\n if (this.password == null) {\n throw new SQLConfigurationException(\"password is a required property\");\n }\n\t*/", "if", "(", "this", ".", "name", "==", "null", ")", "{", "throw", "new", "SQLConfigurationException", "(", "\"name is a required property\"", ")", ";", "}", "if", "(", "this", ".", "driver", "==", "null", ")", "{", "throw", "new", "SQLConfigurationException", "(", "\"driver is a required property\"", ")", ";", "}", "}" ]
Validates this configuration and checks that all required parameters are set. Throws an exception if a property is missing. @throws SQLConfigurationException Thrown if a required property is missing.
[ "Validates", "this", "configuration", "and", "checks", "that", "all", "required", "parameters", "are", "set", ".", "Throws", "an", "exception", "if", "a", "property", "is", "missing", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-sql/src/main/java/com/cloudhopper/commons/sql/DataSourceConfiguration.java#L97-L115
3,585
twitter/cloudhopper-commons
ch-commons-locale/src/main/java/com/cloudhopper/commons/locale/E164CountryCodeUtil.java
E164CountryCodeUtil.lookup
public static E164CountryCode lookup(String address) { // analyze just the first few chars -- max of 4 or length of address int len = (address.length() > maxPrefixLength ? maxPrefixLength : address.length()); // search backwards first, return the first result for (int i = len; i > 0; i--) { String prefix = address.substring(0, i); E164CountryCode entry = byPrefix.get(prefix); if (entry != null) { return entry; } } // nothing found return null; }
java
public static E164CountryCode lookup(String address) { // analyze just the first few chars -- max of 4 or length of address int len = (address.length() > maxPrefixLength ? maxPrefixLength : address.length()); // search backwards first, return the first result for (int i = len; i > 0; i--) { String prefix = address.substring(0, i); E164CountryCode entry = byPrefix.get(prefix); if (entry != null) { return entry; } } // nothing found return null; }
[ "public", "static", "E164CountryCode", "lookup", "(", "String", "address", ")", "{", "// analyze just the first few chars -- max of 4 or length of address", "int", "len", "=", "(", "address", ".", "length", "(", ")", ">", "maxPrefixLength", "?", "maxPrefixLength", ":", "address", ".", "length", "(", ")", ")", ";", "// search backwards first, return the first result", "for", "(", "int", "i", "=", "len", ";", "i", ">", "0", ";", "i", "--", ")", "{", "String", "prefix", "=", "address", ".", "substring", "(", "0", ",", "i", ")", ";", "E164CountryCode", "entry", "=", "byPrefix", ".", "get", "(", "prefix", ")", ";", "if", "(", "entry", "!=", "null", ")", "{", "return", "entry", ";", "}", "}", "// nothing found", "return", "null", ";", "}" ]
Looks up an E164CountryCode object by analyzing the address and returning the best match. For example, 12125551212 will return an entry for the US. @param address The address to lookup. @return
[ "Looks", "up", "an", "E164CountryCode", "object", "by", "analyzing", "the", "address", "and", "returning", "the", "best", "match", ".", "For", "example", "12125551212", "will", "return", "an", "entry", "for", "the", "US", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-locale/src/main/java/com/cloudhopper/commons/locale/E164CountryCodeUtil.java#L79-L92
3,586
twitter/cloudhopper-commons
ch-commons-io/src/main/java/com/cloudhopper/commons/io/FileMonitor.java
FileMonitor.addListener
public void addListener (FileChangedListener fileListener) { // Don't add if its already there for (Iterator<WeakReference<FileChangedListener>> i = listeners_.iterator(); i.hasNext(); ) { WeakReference<FileChangedListener> reference = i.next(); FileChangedListener listener = reference.get(); if (listener == fileListener) return; } // Use WeakReference to avoid memory leak if this becomes the // sole reference to the object. listeners_.add(new WeakReference<FileChangedListener>(fileListener)); }
java
public void addListener (FileChangedListener fileListener) { // Don't add if its already there for (Iterator<WeakReference<FileChangedListener>> i = listeners_.iterator(); i.hasNext(); ) { WeakReference<FileChangedListener> reference = i.next(); FileChangedListener listener = reference.get(); if (listener == fileListener) return; } // Use WeakReference to avoid memory leak if this becomes the // sole reference to the object. listeners_.add(new WeakReference<FileChangedListener>(fileListener)); }
[ "public", "void", "addListener", "(", "FileChangedListener", "fileListener", ")", "{", "// Don't add if its already there", "for", "(", "Iterator", "<", "WeakReference", "<", "FileChangedListener", ">", ">", "i", "=", "listeners_", ".", "iterator", "(", ")", ";", "i", ".", "hasNext", "(", ")", ";", ")", "{", "WeakReference", "<", "FileChangedListener", ">", "reference", "=", "i", ".", "next", "(", ")", ";", "FileChangedListener", "listener", "=", "reference", ".", "get", "(", ")", ";", "if", "(", "listener", "==", "fileListener", ")", "return", ";", "}", "// Use WeakReference to avoid memory leak if this becomes the", "// sole reference to the object.", "listeners_", ".", "add", "(", "new", "WeakReference", "<", "FileChangedListener", ">", "(", "fileListener", ")", ")", ";", "}" ]
Add listener to this file monitor. @param fileListener Listener to add.
[ "Add", "listener", "to", "this", "file", "monitor", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-io/src/main/java/com/cloudhopper/commons/io/FileMonitor.java#L127-L140
3,587
twitter/cloudhopper-commons
ch-commons-io/src/main/java/com/cloudhopper/commons/io/FileMonitor.java
FileMonitor.removeListener
public void removeListener (FileChangedListener fileListener) { for (Iterator<WeakReference<FileChangedListener>> i = listeners_.iterator(); i.hasNext(); ) { WeakReference<FileChangedListener> reference = i.next(); FileChangedListener listener = reference.get(); if (listener == fileListener) { i.remove(); break; } } }
java
public void removeListener (FileChangedListener fileListener) { for (Iterator<WeakReference<FileChangedListener>> i = listeners_.iterator(); i.hasNext(); ) { WeakReference<FileChangedListener> reference = i.next(); FileChangedListener listener = reference.get(); if (listener == fileListener) { i.remove(); break; } } }
[ "public", "void", "removeListener", "(", "FileChangedListener", "fileListener", ")", "{", "for", "(", "Iterator", "<", "WeakReference", "<", "FileChangedListener", ">", ">", "i", "=", "listeners_", ".", "iterator", "(", ")", ";", "i", ".", "hasNext", "(", ")", ";", ")", "{", "WeakReference", "<", "FileChangedListener", ">", "reference", "=", "i", ".", "next", "(", ")", ";", "FileChangedListener", "listener", "=", "reference", ".", "get", "(", ")", ";", "if", "(", "listener", "==", "fileListener", ")", "{", "i", ".", "remove", "(", ")", ";", "break", ";", "}", "}", "}" ]
Remove listener from this file monitor. @param fileListener Listener to remove.
[ "Remove", "listener", "from", "this", "file", "monitor", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-io/src/main/java/com/cloudhopper/commons/io/FileMonitor.java#L149-L159
3,588
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/DigitLookupMap.java
DigitLookupMap.dumpNode
private void dumpNode(Node node, int level, int idx, java.io.PrintStream out) { // if node null, then return if (node == null) { return; } // print out required spaces printSpaces(level, out); if (idx == -2) { out.print("ROOT -> "); } else { out.print(idx + " -> "); } // print out the values out.print("S: "); if (node.getSpecificValue() != null) { out.print(node.getSpecificValue().toString()); } else { out.print("(null)"); } out.print(", W: "); if (node.getPrefixValue() != null) { out.println(node.getPrefixValue().toString()); } else { out.println("(null)"); } // loop through each child node for (int index = 0; index < 10; index++) { // dump out this node... dumpNode(node.getNode(index), level + 1, index, out); } }
java
private void dumpNode(Node node, int level, int idx, java.io.PrintStream out) { // if node null, then return if (node == null) { return; } // print out required spaces printSpaces(level, out); if (idx == -2) { out.print("ROOT -> "); } else { out.print(idx + " -> "); } // print out the values out.print("S: "); if (node.getSpecificValue() != null) { out.print(node.getSpecificValue().toString()); } else { out.print("(null)"); } out.print(", W: "); if (node.getPrefixValue() != null) { out.println(node.getPrefixValue().toString()); } else { out.println("(null)"); } // loop through each child node for (int index = 0; index < 10; index++) { // dump out this node... dumpNode(node.getNode(index), level + 1, index, out); } }
[ "private", "void", "dumpNode", "(", "Node", "node", ",", "int", "level", ",", "int", "idx", ",", "java", ".", "io", ".", "PrintStream", "out", ")", "{", "// if node null, then return", "if", "(", "node", "==", "null", ")", "{", "return", ";", "}", "// print out required spaces", "printSpaces", "(", "level", ",", "out", ")", ";", "if", "(", "idx", "==", "-", "2", ")", "{", "out", ".", "print", "(", "\"ROOT -> \"", ")", ";", "}", "else", "{", "out", ".", "print", "(", "idx", "+", "\" -> \"", ")", ";", "}", "// print out the values", "out", ".", "print", "(", "\"S: \"", ")", ";", "if", "(", "node", ".", "getSpecificValue", "(", ")", "!=", "null", ")", "{", "out", ".", "print", "(", "node", ".", "getSpecificValue", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "out", ".", "print", "(", "\"(null)\"", ")", ";", "}", "out", ".", "print", "(", "\", W: \"", ")", ";", "if", "(", "node", ".", "getPrefixValue", "(", ")", "!=", "null", ")", "{", "out", ".", "println", "(", "node", ".", "getPrefixValue", "(", ")", ".", "toString", "(", ")", ")", ";", "}", "else", "{", "out", ".", "println", "(", "\"(null)\"", ")", ";", "}", "// loop through each child node", "for", "(", "int", "index", "=", "0", ";", "index", "<", "10", ";", "index", "++", ")", "{", "// dump out this node...", "dumpNode", "(", "node", ".", "getNode", "(", "index", ")", ",", "level", "+", "1", ",", "index", ",", "out", ")", ";", "}", "}" ]
Recursively dumps a node at a certain index.
[ "Recursively", "dumps", "a", "node", "at", "a", "certain", "index", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/DigitLookupMap.java#L299-L334
3,589
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/DigitLookupMap.java
DigitLookupMap.printSpaces
private void printSpaces(int count, java.io.PrintStream out) { for (int i = 0; i < count; i++) { out.print(" "); } }
java
private void printSpaces(int count, java.io.PrintStream out) { for (int i = 0; i < count; i++) { out.print(" "); } }
[ "private", "void", "printSpaces", "(", "int", "count", ",", "java", ".", "io", ".", "PrintStream", "out", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "count", ";", "i", "++", ")", "{", "out", ".", "print", "(", "\" \"", ")", ";", "}", "}" ]
Prints out certain number of spaces.
[ "Prints", "out", "certain", "number", "of", "spaces", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/DigitLookupMap.java#L339-L343
3,590
twitter/cloudhopper-commons
ch-commons-rfs/src/main/java/com/cloudhopper/commons/rfs/provider/SftpRemoteFileSystem.java
SftpRemoteFileSystem.findSshDirs
protected File[] findSshDirs() { ArrayList<File> dirs = new ArrayList<File>(); // user's home directory and .ssh subdir File sshHomeDir = new File(System.getProperty("user.home"), ".ssh"); if (sshHomeDir.exists() && sshHomeDir.isDirectory()) { dirs.add(sshHomeDir); } // FIXME: any other directories we should try to scan? return dirs.toArray(new File[0]); }
java
protected File[] findSshDirs() { ArrayList<File> dirs = new ArrayList<File>(); // user's home directory and .ssh subdir File sshHomeDir = new File(System.getProperty("user.home"), ".ssh"); if (sshHomeDir.exists() && sshHomeDir.isDirectory()) { dirs.add(sshHomeDir); } // FIXME: any other directories we should try to scan? return dirs.toArray(new File[0]); }
[ "protected", "File", "[", "]", "findSshDirs", "(", ")", "{", "ArrayList", "<", "File", ">", "dirs", "=", "new", "ArrayList", "<", "File", ">", "(", ")", ";", "// user's home directory and .ssh subdir", "File", "sshHomeDir", "=", "new", "File", "(", "System", ".", "getProperty", "(", "\"user.home\"", ")", ",", "\".ssh\"", ")", ";", "if", "(", "sshHomeDir", ".", "exists", "(", ")", "&&", "sshHomeDir", ".", "isDirectory", "(", ")", ")", "{", "dirs", ".", "add", "(", "sshHomeDir", ")", ";", "}", "// FIXME: any other directories we should try to scan?", "return", "dirs", ".", "toArray", "(", "new", "File", "[", "0", "]", ")", ";", "}" ]
Best attempt to find a default .ssh directory on this particular server. While more directories may be attempted, for now the user's home directory will be scanned for a .ssh directory. @return An array of .ssh directories to search or null if none were found.
[ "Best", "attempt", "to", "find", "a", "default", ".", "ssh", "directory", "on", "this", "particular", "server", ".", "While", "more", "directories", "may", "be", "attempted", "for", "now", "the", "user", "s", "home", "directory", "will", "be", "scanned", "for", "a", ".", "ssh", "directory", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-rfs/src/main/java/com/cloudhopper/commons/rfs/provider/SftpRemoteFileSystem.java#L67-L79
3,591
twitter/cloudhopper-commons
ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java
SslContextFactory.loadKeyStore
protected KeyStore loadKeyStore() throws Exception { return getKeyStore(keyStoreInputStream, sslConfig.getKeyStorePath(), sslConfig.getKeyStoreType(), sslConfig.getKeyStoreProvider(), sslConfig.getKeyStorePassword()); }
java
protected KeyStore loadKeyStore() throws Exception { return getKeyStore(keyStoreInputStream, sslConfig.getKeyStorePath(), sslConfig.getKeyStoreType(), sslConfig.getKeyStoreProvider(), sslConfig.getKeyStorePassword()); }
[ "protected", "KeyStore", "loadKeyStore", "(", ")", "throws", "Exception", "{", "return", "getKeyStore", "(", "keyStoreInputStream", ",", "sslConfig", ".", "getKeyStorePath", "(", ")", ",", "sslConfig", ".", "getKeyStoreType", "(", ")", ",", "sslConfig", ".", "getKeyStoreProvider", "(", ")", ",", "sslConfig", ".", "getKeyStorePassword", "(", ")", ")", ";", "}" ]
Override this method to provide alternate way to load a keystore. @return the key store instance @throws Exception
[ "Override", "this", "method", "to", "provide", "alternate", "way", "to", "load", "a", "keystore", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java#L183-L187
3,592
twitter/cloudhopper-commons
ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java
SslContextFactory.loadTrustStore
protected KeyStore loadTrustStore() throws Exception { return getKeyStore(trustStoreInputStream, sslConfig.getTrustStorePath(), sslConfig.getTrustStoreType(), sslConfig.getTrustStoreProvider(), sslConfig.getTrustStorePassword()); }
java
protected KeyStore loadTrustStore() throws Exception { return getKeyStore(trustStoreInputStream, sslConfig.getTrustStorePath(), sslConfig.getTrustStoreType(), sslConfig.getTrustStoreProvider(), sslConfig.getTrustStorePassword()); }
[ "protected", "KeyStore", "loadTrustStore", "(", ")", "throws", "Exception", "{", "return", "getKeyStore", "(", "trustStoreInputStream", ",", "sslConfig", ".", "getTrustStorePath", "(", ")", ",", "sslConfig", ".", "getTrustStoreType", "(", ")", ",", "sslConfig", ".", "getTrustStoreProvider", "(", ")", ",", "sslConfig", ".", "getTrustStorePassword", "(", ")", ")", ";", "}" ]
Override this method to provide alternate way to load a truststore. @return the key store instance @throws Exception
[ "Override", "this", "method", "to", "provide", "alternate", "way", "to", "load", "a", "truststore", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java#L195-L199
3,593
twitter/cloudhopper-commons
ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java
SslContextFactory.getKeyStore
protected KeyStore getKeyStore(InputStream storeStream, String storePath, String storeType, String storeProvider, String storePassword) throws Exception { KeyStore keystore = null; if (storeStream != null || storePath != null) { InputStream inStream = storeStream; try { if (inStream == null) { inStream = new FileInputStream(storePath); //assume it's a file } if (storeProvider != null) { keystore = KeyStore.getInstance(storeType, storeProvider); } else { keystore = KeyStore.getInstance(storeType); } keystore.load(inStream, storePassword == null ? null : storePassword.toCharArray()); } finally { if (inStream != null) { inStream.close(); } } } return keystore; }
java
protected KeyStore getKeyStore(InputStream storeStream, String storePath, String storeType, String storeProvider, String storePassword) throws Exception { KeyStore keystore = null; if (storeStream != null || storePath != null) { InputStream inStream = storeStream; try { if (inStream == null) { inStream = new FileInputStream(storePath); //assume it's a file } if (storeProvider != null) { keystore = KeyStore.getInstance(storeType, storeProvider); } else { keystore = KeyStore.getInstance(storeType); } keystore.load(inStream, storePassword == null ? null : storePassword.toCharArray()); } finally { if (inStream != null) { inStream.close(); } } } return keystore; }
[ "protected", "KeyStore", "getKeyStore", "(", "InputStream", "storeStream", ",", "String", "storePath", ",", "String", "storeType", ",", "String", "storeProvider", ",", "String", "storePassword", ")", "throws", "Exception", "{", "KeyStore", "keystore", "=", "null", ";", "if", "(", "storeStream", "!=", "null", "||", "storePath", "!=", "null", ")", "{", "InputStream", "inStream", "=", "storeStream", ";", "try", "{", "if", "(", "inStream", "==", "null", ")", "{", "inStream", "=", "new", "FileInputStream", "(", "storePath", ")", ";", "//assume it's a file", "}", "if", "(", "storeProvider", "!=", "null", ")", "{", "keystore", "=", "KeyStore", ".", "getInstance", "(", "storeType", ",", "storeProvider", ")", ";", "}", "else", "{", "keystore", "=", "KeyStore", ".", "getInstance", "(", "storeType", ")", ";", "}", "keystore", ".", "load", "(", "inStream", ",", "storePassword", "==", "null", "?", "null", ":", "storePassword", ".", "toCharArray", "(", ")", ")", ";", "}", "finally", "{", "if", "(", "inStream", "!=", "null", ")", "{", "inStream", ".", "close", "(", ")", ";", "}", "}", "}", "return", "keystore", ";", "}" ]
Loads keystore using an input stream or a file path in the same order of precedence. Required for integrations to be able to override the mechanism used to load a keystore in order to provide their own implementation. @param storeStream keystore input stream @param storePath path of keystore file @param storeType keystore type @param storeProvider keystore provider @param storePassword keystore password @return created keystore @throws Exception if the keystore cannot be obtained
[ "Loads", "keystore", "using", "an", "input", "stream", "or", "a", "file", "path", "in", "the", "same", "order", "of", "precedence", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java#L243-L264
3,594
twitter/cloudhopper-commons
ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java
SslContextFactory.checkKeyStore
public void checkKeyStore() { if (sslContext != null) return; //nothing to check if using preconfigured context if (keyStoreInputStream == null && sslConfig.getKeyStorePath() == null) { throw new IllegalStateException("SSL doesn't have a valid keystore"); } // if the keystore has been configured but there is no // truststore configured, use the keystore as the truststore if (trustStoreInputStream == null && sslConfig.getTrustStorePath() == null) { trustStoreInputStream = keyStoreInputStream; sslConfig.setTrustStorePath(sslConfig.getKeyStorePath()); sslConfig.setTrustStoreType(sslConfig.getKeyStoreType()); sslConfig.setTrustStoreProvider(sslConfig.getKeyStoreProvider()); sslConfig.setTrustStorePassword(sslConfig.getKeyStorePassword()); sslConfig.setTrustManagerFactoryAlgorithm(sslConfig.getKeyManagerFactoryAlgorithm()); } // It's the same stream we cannot read it twice, so read it once in memory if (keyStoreInputStream != null && keyStoreInputStream == trustStoreInputStream) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); streamCopy(keyStoreInputStream, baos, null, false); keyStoreInputStream.close(); keyStoreInputStream = new ByteArrayInputStream(baos.toByteArray()); trustStoreInputStream = new ByteArrayInputStream(baos.toByteArray()); } catch (Exception ex) { throw new IllegalStateException(ex); } } }
java
public void checkKeyStore() { if (sslContext != null) return; //nothing to check if using preconfigured context if (keyStoreInputStream == null && sslConfig.getKeyStorePath() == null) { throw new IllegalStateException("SSL doesn't have a valid keystore"); } // if the keystore has been configured but there is no // truststore configured, use the keystore as the truststore if (trustStoreInputStream == null && sslConfig.getTrustStorePath() == null) { trustStoreInputStream = keyStoreInputStream; sslConfig.setTrustStorePath(sslConfig.getKeyStorePath()); sslConfig.setTrustStoreType(sslConfig.getKeyStoreType()); sslConfig.setTrustStoreProvider(sslConfig.getKeyStoreProvider()); sslConfig.setTrustStorePassword(sslConfig.getKeyStorePassword()); sslConfig.setTrustManagerFactoryAlgorithm(sslConfig.getKeyManagerFactoryAlgorithm()); } // It's the same stream we cannot read it twice, so read it once in memory if (keyStoreInputStream != null && keyStoreInputStream == trustStoreInputStream) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); streamCopy(keyStoreInputStream, baos, null, false); keyStoreInputStream.close(); keyStoreInputStream = new ByteArrayInputStream(baos.toByteArray()); trustStoreInputStream = new ByteArrayInputStream(baos.toByteArray()); } catch (Exception ex) { throw new IllegalStateException(ex); } } }
[ "public", "void", "checkKeyStore", "(", ")", "{", "if", "(", "sslContext", "!=", "null", ")", "return", ";", "//nothing to check if using preconfigured context", "if", "(", "keyStoreInputStream", "==", "null", "&&", "sslConfig", ".", "getKeyStorePath", "(", ")", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"SSL doesn't have a valid keystore\"", ")", ";", "}", "// if the keystore has been configured but there is no", "// truststore configured, use the keystore as the truststore", "if", "(", "trustStoreInputStream", "==", "null", "&&", "sslConfig", ".", "getTrustStorePath", "(", ")", "==", "null", ")", "{", "trustStoreInputStream", "=", "keyStoreInputStream", ";", "sslConfig", ".", "setTrustStorePath", "(", "sslConfig", ".", "getKeyStorePath", "(", ")", ")", ";", "sslConfig", ".", "setTrustStoreType", "(", "sslConfig", ".", "getKeyStoreType", "(", ")", ")", ";", "sslConfig", ".", "setTrustStoreProvider", "(", "sslConfig", ".", "getKeyStoreProvider", "(", ")", ")", ";", "sslConfig", ".", "setTrustStorePassword", "(", "sslConfig", ".", "getKeyStorePassword", "(", ")", ")", ";", "sslConfig", ".", "setTrustManagerFactoryAlgorithm", "(", "sslConfig", ".", "getKeyManagerFactoryAlgorithm", "(", ")", ")", ";", "}", "// It's the same stream we cannot read it twice, so read it once in memory", "if", "(", "keyStoreInputStream", "!=", "null", "&&", "keyStoreInputStream", "==", "trustStoreInputStream", ")", "{", "try", "{", "ByteArrayOutputStream", "baos", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "streamCopy", "(", "keyStoreInputStream", ",", "baos", ",", "null", ",", "false", ")", ";", "keyStoreInputStream", ".", "close", "(", ")", ";", "keyStoreInputStream", "=", "new", "ByteArrayInputStream", "(", "baos", ".", "toByteArray", "(", ")", ")", ";", "trustStoreInputStream", "=", "new", "ByteArrayInputStream", "(", "baos", ".", "toByteArray", "(", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "ex", ")", ";", "}", "}", "}" ]
Check KeyStore Configuration. Ensures that if keystore has been configured but there's no truststore, that keystore is used as truststore. @throws IllegalStateException if SslContextFactory configuration can't be used.
[ "Check", "KeyStore", "Configuration", ".", "Ensures", "that", "if", "keystore", "has", "been", "configured", "but", "there", "s", "no", "truststore", "that", "keystore", "is", "used", "as", "truststore", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java#L341-L372
3,595
twitter/cloudhopper-commons
ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java
SslContextFactory.streamCopy
private static void streamCopy(InputStream is, OutputStream os, byte[] buf, boolean close) throws IOException { int len; if (buf == null) { buf = new byte[4096]; } while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); if (close) { is.close(); } }
java
private static void streamCopy(InputStream is, OutputStream os, byte[] buf, boolean close) throws IOException { int len; if (buf == null) { buf = new byte[4096]; } while ((len = is.read(buf)) > 0) { os.write(buf, 0, len); } os.flush(); if (close) { is.close(); } }
[ "private", "static", "void", "streamCopy", "(", "InputStream", "is", ",", "OutputStream", "os", ",", "byte", "[", "]", "buf", ",", "boolean", "close", ")", "throws", "IOException", "{", "int", "len", ";", "if", "(", "buf", "==", "null", ")", "{", "buf", "=", "new", "byte", "[", "4096", "]", ";", "}", "while", "(", "(", "len", "=", "is", ".", "read", "(", "buf", ")", ")", ">", "0", ")", "{", "os", ".", "write", "(", "buf", ",", "0", ",", "len", ")", ";", "}", "os", ".", "flush", "(", ")", ";", "if", "(", "close", ")", "{", "is", ".", "close", "(", ")", ";", "}", "}" ]
Copy the contents of is to os. @param is @param os @param buf Can be null @param close If true, is is closed after the copy. @throws IOException
[ "Copy", "the", "contents", "of", "is", "to", "os", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java#L382-L394
3,596
twitter/cloudhopper-commons
ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java
SslContextFactory.contains
private static boolean contains(Object[] arr, Object obj) { for (Object o : arr) { if (o.equals(obj)) return true; } return false; }
java
private static boolean contains(Object[] arr, Object obj) { for (Object o : arr) { if (o.equals(obj)) return true; } return false; }
[ "private", "static", "boolean", "contains", "(", "Object", "[", "]", "arr", ",", "Object", "obj", ")", "{", "for", "(", "Object", "o", ":", "arr", ")", "{", "if", "(", "o", ".", "equals", "(", "obj", ")", ")", "return", "true", ";", "}", "return", "false", ";", "}" ]
Does an object array include an object. @param arr The array @param obj The object
[ "Does", "an", "object", "array", "include", "an", "object", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-ssl/src/main/java/com/cloudhopper/commons/ssl/SslContextFactory.java#L401-L406
3,597
twitter/cloudhopper-commons
ch-commons-util/src/main/java/com/cloudhopper/commons/util/StackTraceUtil.java
StackTraceUtil.toStackTraceString
public static String toStackTraceString(String firstLine, StackTraceElement[] stack) { //add the class name and any message passed to constructor final StringBuilder result = new StringBuilder(firstLine); //result.append(aThrowable.toString()); final String NEW_LINE = System.getProperty("line.separator"); result.append(NEW_LINE); //add each element of the stack trace for (StackTraceElement element : stack ){ result.append(" at "); result.append( element ); result.append( NEW_LINE ); } return result.toString(); }
java
public static String toStackTraceString(String firstLine, StackTraceElement[] stack) { //add the class name and any message passed to constructor final StringBuilder result = new StringBuilder(firstLine); //result.append(aThrowable.toString()); final String NEW_LINE = System.getProperty("line.separator"); result.append(NEW_LINE); //add each element of the stack trace for (StackTraceElement element : stack ){ result.append(" at "); result.append( element ); result.append( NEW_LINE ); } return result.toString(); }
[ "public", "static", "String", "toStackTraceString", "(", "String", "firstLine", ",", "StackTraceElement", "[", "]", "stack", ")", "{", "//add the class name and any message passed to constructor", "final", "StringBuilder", "result", "=", "new", "StringBuilder", "(", "firstLine", ")", ";", "//result.append(aThrowable.toString());", "final", "String", "NEW_LINE", "=", "System", ".", "getProperty", "(", "\"line.separator\"", ")", ";", "result", ".", "append", "(", "NEW_LINE", ")", ";", "//add each element of the stack trace", "for", "(", "StackTraceElement", "element", ":", "stack", ")", "{", "result", ".", "append", "(", "\" at \"", ")", ";", "result", ".", "append", "(", "element", ")", ";", "result", ".", "append", "(", "NEW_LINE", ")", ";", "}", "return", "result", ".", "toString", "(", ")", ";", "}" ]
Defines a custom format for the stack trace as String.
[ "Defines", "a", "custom", "format", "for", "the", "stack", "trace", "as", "String", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-util/src/main/java/com/cloudhopper/commons/util/StackTraceUtil.java#L42-L57
3,598
twitter/cloudhopper-commons
ch-commons-charset/src/main/java/com/cloudhopper/commons/charset/ModifiedUTF8Charset.java
ModifiedUTF8Charset.encodeToByteArray
static public int encodeToByteArray(CharSequence charSeq, char[] charBuffer, int charOffset, int charLength, byte[] byteBuffer, int byteOffset) { int c = 0; int bytePos = byteOffset; // start at byte offset int charPos = charOffset; // start at char offset int charAbsLength = charPos + charLength; if (charBuffer == null) { if (charSeq == null) { throw new IllegalArgumentException("Both charSeq and charBuffer cannot be null"); } // use charSequence rather than charBuffer charOffset = 0; charAbsLength = charSeq.length(); } // optimized method is only ascii chars used for (; charPos < charAbsLength; charPos++) { // optimized method for getting char to encode if (charBuffer != null) { c = charBuffer[charPos]; } else { c = charSeq.charAt(charPos); } if (!((c >= 0x0000) && (c <= 0x007F))) break; byteBuffer[bytePos++] = (byte) c; } for (; charPos < charAbsLength; charPos++) { // optimized method for getting char to encode if (charBuffer != null) { c = charBuffer[charPos]; } else { c = charSeq.charAt(charPos); } if ((c >= 0x0000) && (c <= 0x007F)) { byteBuffer[bytePos++] = (byte) c; } else if (c > 0x07FF) { byteBuffer[bytePos++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); byteBuffer[bytePos++] = (byte) (0x80 | ((c >> 6) & 0x3F)); byteBuffer[bytePos++] = (byte) (0x80 | (c & 0x3F)); } else { byteBuffer[bytePos++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); byteBuffer[bytePos++] = (byte) (0x80 | (c & 0x3F)); } } return (bytePos-byteOffset); }
java
static public int encodeToByteArray(CharSequence charSeq, char[] charBuffer, int charOffset, int charLength, byte[] byteBuffer, int byteOffset) { int c = 0; int bytePos = byteOffset; // start at byte offset int charPos = charOffset; // start at char offset int charAbsLength = charPos + charLength; if (charBuffer == null) { if (charSeq == null) { throw new IllegalArgumentException("Both charSeq and charBuffer cannot be null"); } // use charSequence rather than charBuffer charOffset = 0; charAbsLength = charSeq.length(); } // optimized method is only ascii chars used for (; charPos < charAbsLength; charPos++) { // optimized method for getting char to encode if (charBuffer != null) { c = charBuffer[charPos]; } else { c = charSeq.charAt(charPos); } if (!((c >= 0x0000) && (c <= 0x007F))) break; byteBuffer[bytePos++] = (byte) c; } for (; charPos < charAbsLength; charPos++) { // optimized method for getting char to encode if (charBuffer != null) { c = charBuffer[charPos]; } else { c = charSeq.charAt(charPos); } if ((c >= 0x0000) && (c <= 0x007F)) { byteBuffer[bytePos++] = (byte) c; } else if (c > 0x07FF) { byteBuffer[bytePos++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); byteBuffer[bytePos++] = (byte) (0x80 | ((c >> 6) & 0x3F)); byteBuffer[bytePos++] = (byte) (0x80 | (c & 0x3F)); } else { byteBuffer[bytePos++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); byteBuffer[bytePos++] = (byte) (0x80 | (c & 0x3F)); } } return (bytePos-byteOffset); }
[ "static", "public", "int", "encodeToByteArray", "(", "CharSequence", "charSeq", ",", "char", "[", "]", "charBuffer", ",", "int", "charOffset", ",", "int", "charLength", ",", "byte", "[", "]", "byteBuffer", ",", "int", "byteOffset", ")", "{", "int", "c", "=", "0", ";", "int", "bytePos", "=", "byteOffset", ";", "// start at byte offset", "int", "charPos", "=", "charOffset", ";", "// start at char offset", "int", "charAbsLength", "=", "charPos", "+", "charLength", ";", "if", "(", "charBuffer", "==", "null", ")", "{", "if", "(", "charSeq", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Both charSeq and charBuffer cannot be null\"", ")", ";", "}", "// use charSequence rather than charBuffer", "charOffset", "=", "0", ";", "charAbsLength", "=", "charSeq", ".", "length", "(", ")", ";", "}", "// optimized method is only ascii chars used", "for", "(", ";", "charPos", "<", "charAbsLength", ";", "charPos", "++", ")", "{", "// optimized method for getting char to encode", "if", "(", "charBuffer", "!=", "null", ")", "{", "c", "=", "charBuffer", "[", "charPos", "]", ";", "}", "else", "{", "c", "=", "charSeq", ".", "charAt", "(", "charPos", ")", ";", "}", "if", "(", "!", "(", "(", "c", ">=", "0x0000", ")", "&&", "(", "c", "<=", "0x007F", ")", ")", ")", "break", ";", "byteBuffer", "[", "bytePos", "++", "]", "=", "(", "byte", ")", "c", ";", "}", "for", "(", ";", "charPos", "<", "charAbsLength", ";", "charPos", "++", ")", "{", "// optimized method for getting char to encode", "if", "(", "charBuffer", "!=", "null", ")", "{", "c", "=", "charBuffer", "[", "charPos", "]", ";", "}", "else", "{", "c", "=", "charSeq", ".", "charAt", "(", "charPos", ")", ";", "}", "if", "(", "(", "c", ">=", "0x0000", ")", "&&", "(", "c", "<=", "0x007F", ")", ")", "{", "byteBuffer", "[", "bytePos", "++", "]", "=", "(", "byte", ")", "c", ";", "}", "else", "if", "(", "c", ">", "0x07FF", ")", "{", "byteBuffer", "[", "bytePos", "++", "]", "=", "(", "byte", ")", "(", "0xE0", "|", "(", "(", "c", ">>", "12", ")", "&", "0x0F", ")", ")", ";", "byteBuffer", "[", "bytePos", "++", "]", "=", "(", "byte", ")", "(", "0x80", "|", "(", "(", "c", ">>", "6", ")", "&", "0x3F", ")", ")", ";", "byteBuffer", "[", "bytePos", "++", "]", "=", "(", "byte", ")", "(", "0x80", "|", "(", "c", "&", "0x3F", ")", ")", ";", "}", "else", "{", "byteBuffer", "[", "bytePos", "++", "]", "=", "(", "byte", ")", "(", "0xC0", "|", "(", "(", "c", ">>", "6", ")", "&", "0x1F", ")", ")", ";", "byteBuffer", "[", "bytePos", "++", "]", "=", "(", "byte", ")", "(", "0x80", "|", "(", "c", "&", "0x3F", ")", ")", ";", "}", "}", "return", "(", "bytePos", "-", "byteOffset", ")", ";", "}" ]
Encode the string to an array of UTF-8 bytes. The buffer must be pre-allocated and have enough space to hold the encoded string. @param charSeq The optional character sequence to use for encoding rather than the provided character buffer. It is always higher performance to supply a char array vs. use a CharSequence. Set to null if the character array is supplied. @param charBuffer The source char array to encode @param charOffset The offset in the source char array to start encode from @param charLength The length from the offset in the source char array to encode @param byteBuffer The destination byte array to encode to @param byteOffset The offset in the destination byte array to start encode to @return The number of bytes written to the destination byte array @see #calculateByteLength(java.lang.CharSequence)
[ "Encode", "the", "string", "to", "an", "array", "of", "UTF", "-", "8", "bytes", ".", "The", "buffer", "must", "be", "pre", "-", "allocated", "and", "have", "enough", "space", "to", "hold", "the", "encoded", "string", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-charset/src/main/java/com/cloudhopper/commons/charset/ModifiedUTF8Charset.java#L225-L273
3,599
twitter/cloudhopper-commons
ch-commons-rfs/src/main/java/com/cloudhopper/commons/rfs/RemoteFileSystemFactory.java
RemoteFileSystemFactory.create
public static RemoteFileSystem create(String url) throws MalformedURLException, FileSystemException { // parse url into a URL object URL r = URLParser.parse(url); // delegate responsibility to other method return create(r); }
java
public static RemoteFileSystem create(String url) throws MalformedURLException, FileSystemException { // parse url into a URL object URL r = URLParser.parse(url); // delegate responsibility to other method return create(r); }
[ "public", "static", "RemoteFileSystem", "create", "(", "String", "url", ")", "throws", "MalformedURLException", ",", "FileSystemException", "{", "// parse url into a URL object", "URL", "r", "=", "URLParser", ".", "parse", "(", "url", ")", ";", "// delegate responsibility to other method", "return", "create", "(", "r", ")", ";", "}" ]
Creates a new RemoteFileSystem by parsing the URL and creating the correct underlying provider to support the protocol.
[ "Creates", "a", "new", "RemoteFileSystem", "by", "parsing", "the", "URL", "and", "creating", "the", "correct", "underlying", "provider", "to", "support", "the", "protocol", "." ]
b5bc397dbec4537e8149e7ec0733c1d7ed477499
https://github.com/twitter/cloudhopper-commons/blob/b5bc397dbec4537e8149e7ec0733c1d7ed477499/ch-commons-rfs/src/main/java/com/cloudhopper/commons/rfs/RemoteFileSystemFactory.java#L46-L51