repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/codec/RTMP.java
RTMP.freePacket
private void freePacket(Packet packet) { if (packet != null && packet.getData() != null) { packet.clearData(); } }
java
private void freePacket(Packet packet) { if (packet != null && packet.getData() != null) { packet.clearData(); } }
[ "private", "void", "freePacket", "(", "Packet", "packet", ")", "{", "if", "(", "packet", "!=", "null", "&&", "packet", ".", "getData", "(", ")", "!=", "null", ")", "{", "packet", ".", "clearData", "(", ")", ";", "}", "}" ]
Releases a packet. @param packet Packet to release
[ "Releases", "a", "packet", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMP.java#L160-L164
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/codec/RTMP.java
RTMP.freeChannels
private void freeChannels() { for (ChannelInfo info : channels.values()) { freePacket(info.getReadPacket()); freePacket(info.getWritePacket()); } channels.clear(); }
java
private void freeChannels() { for (ChannelInfo info : channels.values()) { freePacket(info.getReadPacket()); freePacket(info.getWritePacket()); } channels.clear(); }
[ "private", "void", "freeChannels", "(", ")", "{", "for", "(", "ChannelInfo", "info", ":", "channels", ".", "values", "(", ")", ")", "{", "freePacket", "(", "info", ".", "getReadPacket", "(", ")", ")", ";", "freePacket", "(", "info", ".", "getWritePacket"...
Releases the channels.
[ "Releases", "the", "channels", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMP.java#L169-L175
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/codec/RTMP.java
RTMP.setLastReadPacket
public void setLastReadPacket(int channelId, Packet packet) { final ChannelInfo info = getChannelInfo(channelId); // grab last packet Packet prevPacket = info.getReadPacket(); // set new one info.setReadPacket(packet); // free the previous packet freePacket(prevPacket); }
java
public void setLastReadPacket(int channelId, Packet packet) { final ChannelInfo info = getChannelInfo(channelId); // grab last packet Packet prevPacket = info.getReadPacket(); // set new one info.setReadPacket(packet); // free the previous packet freePacket(prevPacket); }
[ "public", "void", "setLastReadPacket", "(", "int", "channelId", ",", "Packet", "packet", ")", "{", "final", "ChannelInfo", "info", "=", "getChannelInfo", "(", "channelId", ")", ";", "// grab last packet\r", "Packet", "prevPacket", "=", "info", ".", "getReadPacket"...
Setter for last read packet. @param channelId Channel id @param packet Packet
[ "Setter", "for", "last", "read", "packet", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/codec/RTMP.java#L244-L252
train
Red5/red5-server-common
src/main/java/org/red5/server/util/FileUtil.java
FileUtil.deleteDirectory
public static boolean deleteDirectory(String directory, boolean useOSNativeDelete) throws IOException { boolean result = false; if (!useOSNativeDelete) { File dir = new File(directory); // first all files have to be cleared out for (File file : dir.listFiles()) { if (file.delete()) { log.debug("{} was deleted", file.getName()); } else { log.debug("{} was not deleted", file.getName()); file.deleteOnExit(); } file = null; } // not you may remove the dir if (dir.delete()) { log.debug("Directory was deleted"); result = true; } else { log.debug("Directory was not deleted, it may be deleted on exit"); dir.deleteOnExit(); } dir = null; } else { Process p = null; Thread std = null; try { Runtime runTime = Runtime.getRuntime(); log.debug("Execute runtime"); //determine file system type if (File.separatorChar == '\\') { //we are windows p = runTime.exec("CMD /D /C \"RMDIR /Q /S " + directory.replace('/', '\\') + "\""); } else { //we are unix variant p = runTime.exec("rm -rf " + directory.replace('\\', File.separatorChar)); } // observe std out std = stdOut(p); // wait for the observer threads to finish while (std.isAlive()) { try { Thread.sleep(250); } catch (Exception e) { } } log.debug("Process threads wait exited"); result = true; } catch (Exception e) { log.error("Error running delete script", e); } finally { if (null != p) { log.debug("Destroying process"); p.destroy(); p = null; } std = null; } } return result; }
java
public static boolean deleteDirectory(String directory, boolean useOSNativeDelete) throws IOException { boolean result = false; if (!useOSNativeDelete) { File dir = new File(directory); // first all files have to be cleared out for (File file : dir.listFiles()) { if (file.delete()) { log.debug("{} was deleted", file.getName()); } else { log.debug("{} was not deleted", file.getName()); file.deleteOnExit(); } file = null; } // not you may remove the dir if (dir.delete()) { log.debug("Directory was deleted"); result = true; } else { log.debug("Directory was not deleted, it may be deleted on exit"); dir.deleteOnExit(); } dir = null; } else { Process p = null; Thread std = null; try { Runtime runTime = Runtime.getRuntime(); log.debug("Execute runtime"); //determine file system type if (File.separatorChar == '\\') { //we are windows p = runTime.exec("CMD /D /C \"RMDIR /Q /S " + directory.replace('/', '\\') + "\""); } else { //we are unix variant p = runTime.exec("rm -rf " + directory.replace('\\', File.separatorChar)); } // observe std out std = stdOut(p); // wait for the observer threads to finish while (std.isAlive()) { try { Thread.sleep(250); } catch (Exception e) { } } log.debug("Process threads wait exited"); result = true; } catch (Exception e) { log.error("Error running delete script", e); } finally { if (null != p) { log.debug("Destroying process"); p.destroy(); p = null; } std = null; } } return result; }
[ "public", "static", "boolean", "deleteDirectory", "(", "String", "directory", ",", "boolean", "useOSNativeDelete", ")", "throws", "IOException", "{", "boolean", "result", "=", "false", ";", "if", "(", "!", "useOSNativeDelete", ")", "{", "File", "dir", "=", "ne...
Deletes a directory and its contents. This will fail if there are any file locks or if the directory cannot be emptied. @param directory directory to delete @param useOSNativeDelete flag to signify use of operating system delete function @throws IOException if directory cannot be deleted @return true if directory was successfully deleted; false if directory did not exist
[ "Deletes", "a", "directory", "and", "its", "contents", ".", "This", "will", "fail", "if", "there", "are", "any", "file", "locks", "or", "if", "the", "directory", "cannot", "be", "emptied", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/util/FileUtil.java#L132-L192
train
Red5/red5-server-common
src/main/java/org/red5/server/util/FileUtil.java
FileUtil.stdOut
private final static Thread stdOut(final Process p) { final byte[] empty = new byte[128]; for (int b = 0; b < empty.length; b++) { empty[b] = (byte) 0; } Thread std = new Thread() { public void run() { StringBuilder sb = new StringBuilder(1024); byte[] buf = new byte[128]; BufferedInputStream bis = new BufferedInputStream(p.getInputStream()); log.debug("Process output:"); try { while (bis.read(buf) != -1) { sb.append(new String(buf).trim()); // clear buffer System.arraycopy(empty, 0, buf, 0, buf.length); } log.debug(sb.toString()); bis.close(); } catch (Exception e) { log.error("{}", e); } } }; std.setDaemon(true); std.start(); return std; }
java
private final static Thread stdOut(final Process p) { final byte[] empty = new byte[128]; for (int b = 0; b < empty.length; b++) { empty[b] = (byte) 0; } Thread std = new Thread() { public void run() { StringBuilder sb = new StringBuilder(1024); byte[] buf = new byte[128]; BufferedInputStream bis = new BufferedInputStream(p.getInputStream()); log.debug("Process output:"); try { while (bis.read(buf) != -1) { sb.append(new String(buf).trim()); // clear buffer System.arraycopy(empty, 0, buf, 0, buf.length); } log.debug(sb.toString()); bis.close(); } catch (Exception e) { log.error("{}", e); } } }; std.setDaemon(true); std.start(); return std; }
[ "private", "final", "static", "Thread", "stdOut", "(", "final", "Process", "p", ")", "{", "final", "byte", "[", "]", "empty", "=", "new", "byte", "[", "128", "]", ";", "for", "(", "int", "b", "=", "0", ";", "b", "<", "empty", ".", "length", ";", ...
Special method for capture of StdOut. @return stdOut thread
[ "Special", "method", "for", "capture", "of", "StdOut", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/util/FileUtil.java#L215-L242
train
Red5/red5-server-common
src/main/java/org/red5/server/util/FileUtil.java
FileUtil.unzip
public static void unzip(String compressedFileName, String destinationDir) { //strip everything except the applications name String dirName = null; // checks to see if there is a dash "-" in the filename of the war. String applicationName = compressedFileName.substring(compressedFileName.lastIndexOf("/")); int dashIndex = applicationName.indexOf('-'); if (dashIndex != -1) { //strip everything except the applications name dirName = compressedFileName.substring(0, dashIndex); } else { //grab every char up to the last '.' dirName = compressedFileName.substring(0, compressedFileName.lastIndexOf('.')); } log.debug("Directory: {}", dirName); //String tmpDir = System.getProperty("java.io.tmpdir"); File zipDir = new File(compressedFileName); File parent = zipDir.getParentFile(); log.debug("Parent: {}", (parent != null ? parent.getName() : null)); //File tmpDir = new File(System.getProperty("java.io.tmpdir"), dirName); File tmpDir = new File(destinationDir); // make the war directory log.debug("Making directory: {}", tmpDir.mkdirs()); ZipFile zf = null; try { zf = new ZipFile(compressedFileName); Enumeration<?> e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze = (ZipEntry) e.nextElement(); log.debug("Unzipping {}", ze.getName()); if (ze.isDirectory()) { log.debug("is a directory"); File dir = new File(tmpDir + "/" + ze.getName()); Boolean tmp = dir.mkdir(); log.debug("{}", tmp); continue; } // checks to see if a zipEntry contains a path // i.e. ze.getName() == "META-INF/MANIFEST.MF" // if this case is true, then we create the path first if (ze.getName().lastIndexOf("/") != -1) { String zipName = ze.getName(); String zipDirStructure = zipName.substring(0, zipName.lastIndexOf("/")); File completeDirectory = new File(tmpDir + "/" + zipDirStructure); if (!completeDirectory.exists()) { if (!completeDirectory.mkdirs()) { log.error("could not create complete directory structure"); } } } // creates the file FileOutputStream fout = new FileOutputStream(tmpDir + "/" + ze.getName()); InputStream in = zf.getInputStream(ze); copy(in, fout); in.close(); fout.close(); } e = null; } catch (IOException e) { log.error("Errored unzipping", e); //log.warn("Exception {}", e); } finally { if (zf != null) { try { zf.close(); } catch (IOException e) { } } } }
java
public static void unzip(String compressedFileName, String destinationDir) { //strip everything except the applications name String dirName = null; // checks to see if there is a dash "-" in the filename of the war. String applicationName = compressedFileName.substring(compressedFileName.lastIndexOf("/")); int dashIndex = applicationName.indexOf('-'); if (dashIndex != -1) { //strip everything except the applications name dirName = compressedFileName.substring(0, dashIndex); } else { //grab every char up to the last '.' dirName = compressedFileName.substring(0, compressedFileName.lastIndexOf('.')); } log.debug("Directory: {}", dirName); //String tmpDir = System.getProperty("java.io.tmpdir"); File zipDir = new File(compressedFileName); File parent = zipDir.getParentFile(); log.debug("Parent: {}", (parent != null ? parent.getName() : null)); //File tmpDir = new File(System.getProperty("java.io.tmpdir"), dirName); File tmpDir = new File(destinationDir); // make the war directory log.debug("Making directory: {}", tmpDir.mkdirs()); ZipFile zf = null; try { zf = new ZipFile(compressedFileName); Enumeration<?> e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze = (ZipEntry) e.nextElement(); log.debug("Unzipping {}", ze.getName()); if (ze.isDirectory()) { log.debug("is a directory"); File dir = new File(tmpDir + "/" + ze.getName()); Boolean tmp = dir.mkdir(); log.debug("{}", tmp); continue; } // checks to see if a zipEntry contains a path // i.e. ze.getName() == "META-INF/MANIFEST.MF" // if this case is true, then we create the path first if (ze.getName().lastIndexOf("/") != -1) { String zipName = ze.getName(); String zipDirStructure = zipName.substring(0, zipName.lastIndexOf("/")); File completeDirectory = new File(tmpDir + "/" + zipDirStructure); if (!completeDirectory.exists()) { if (!completeDirectory.mkdirs()) { log.error("could not create complete directory structure"); } } } // creates the file FileOutputStream fout = new FileOutputStream(tmpDir + "/" + ze.getName()); InputStream in = zf.getInputStream(ze); copy(in, fout); in.close(); fout.close(); } e = null; } catch (IOException e) { log.error("Errored unzipping", e); //log.warn("Exception {}", e); } finally { if (zf != null) { try { zf.close(); } catch (IOException e) { } } } }
[ "public", "static", "void", "unzip", "(", "String", "compressedFileName", ",", "String", "destinationDir", ")", "{", "//strip everything except the applications name\r", "String", "dirName", "=", "null", ";", "// checks to see if there is a dash \"-\" in the filename of the war. ...
Unzips a war file to an application located under the webapps directory @param compressedFileName The String name of the war file @param destinationDir The destination directory, ie: webapps
[ "Unzips", "a", "war", "file", "to", "an", "application", "located", "under", "the", "webapps", "directory" ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/util/FileUtil.java#L299-L369
train
Red5/red5-server-common
src/main/java/org/red5/server/util/FileUtil.java
FileUtil.formatPath
public static String formatPath(String absWebappsPath, String contextDirName) { StringBuilder path = new StringBuilder(absWebappsPath.length() + contextDirName.length()); path.append(absWebappsPath); if (log.isTraceEnabled()) { log.trace("Path start: {}", path.toString()); } int idx = -1; if (File.separatorChar != '/') { while ((idx = path.indexOf(File.separator)) != -1) { path.deleteCharAt(idx); path.insert(idx, '/'); } } if (log.isTraceEnabled()) { log.trace("Path step 1: {}", path.toString()); } //remove any './' if ((idx = path.indexOf("./")) != -1) { path.delete(idx, idx + 2); } if (log.isTraceEnabled()) { log.trace("Path step 2: {}", path.toString()); } //add / to base path if one doesnt exist if (path.charAt(path.length() - 1) != '/') { path.append('/'); } if (log.isTraceEnabled()) { log.trace("Path step 3: {}", path.toString()); } //remove the / from the beginning of the context dir if (contextDirName.charAt(0) == '/' && path.charAt(path.length() - 1) == '/') { path.append(contextDirName.substring(1)); } else { path.append(contextDirName); } if (log.isTraceEnabled()) { log.trace("Path step 4: {}", path.toString()); } return path.toString(); }
java
public static String formatPath(String absWebappsPath, String contextDirName) { StringBuilder path = new StringBuilder(absWebappsPath.length() + contextDirName.length()); path.append(absWebappsPath); if (log.isTraceEnabled()) { log.trace("Path start: {}", path.toString()); } int idx = -1; if (File.separatorChar != '/') { while ((idx = path.indexOf(File.separator)) != -1) { path.deleteCharAt(idx); path.insert(idx, '/'); } } if (log.isTraceEnabled()) { log.trace("Path step 1: {}", path.toString()); } //remove any './' if ((idx = path.indexOf("./")) != -1) { path.delete(idx, idx + 2); } if (log.isTraceEnabled()) { log.trace("Path step 2: {}", path.toString()); } //add / to base path if one doesnt exist if (path.charAt(path.length() - 1) != '/') { path.append('/'); } if (log.isTraceEnabled()) { log.trace("Path step 3: {}", path.toString()); } //remove the / from the beginning of the context dir if (contextDirName.charAt(0) == '/' && path.charAt(path.length() - 1) == '/') { path.append(contextDirName.substring(1)); } else { path.append(contextDirName); } if (log.isTraceEnabled()) { log.trace("Path step 4: {}", path.toString()); } return path.toString(); }
[ "public", "static", "String", "formatPath", "(", "String", "absWebappsPath", ",", "String", "contextDirName", ")", "{", "StringBuilder", "path", "=", "new", "StringBuilder", "(", "absWebappsPath", ".", "length", "(", ")", "+", "contextDirName", ".", "length", "(...
Quick-n-dirty directory formatting to support launching in windows, specifically from ant. @param absWebappsPath abs webapps path @param contextDirName conext directory name @return full path
[ "Quick", "-", "n", "-", "dirty", "directory", "formatting", "to", "support", "launching", "in", "windows", "specifically", "from", "ant", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/util/FileUtil.java#L395-L435
train
Red5/red5-server-common
src/main/java/org/red5/server/util/FileUtil.java
FileUtil.generateCustomName
public static String generateCustomName() { Random random = new Random(); StringBuilder sb = new StringBuilder(); sb.append(PropertyConverter.getCurrentTimeSeconds()); sb.append('_'); int i = random.nextInt(99999); if (i < 10) { sb.append("0000"); } else if (i < 100) { sb.append("000"); } else if (i < 1000) { sb.append("00"); } else if (i < 10000) { sb.append('0'); } sb.append(i); return sb.toString(); }
java
public static String generateCustomName() { Random random = new Random(); StringBuilder sb = new StringBuilder(); sb.append(PropertyConverter.getCurrentTimeSeconds()); sb.append('_'); int i = random.nextInt(99999); if (i < 10) { sb.append("0000"); } else if (i < 100) { sb.append("000"); } else if (i < 1000) { sb.append("00"); } else if (i < 10000) { sb.append('0'); } sb.append(i); return sb.toString(); }
[ "public", "static", "String", "generateCustomName", "(", ")", "{", "Random", "random", "=", "new", "Random", "(", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "sb", ".", "append", "(", "PropertyConverter", ".", "getCurrentTime...
Generates a custom name containing numbers and an underscore ex. 282818_00023. The name contains current seconds and a random number component. @return custom name
[ "Generates", "a", "custom", "name", "containing", "numbers", "and", "an", "underscore", "ex", ".", "282818_00023", ".", "The", "name", "contains", "current", "seconds", "and", "a", "random", "number", "component", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/util/FileUtil.java#L442-L459
train
Red5/red5-server-common
src/main/java/org/red5/server/util/FileUtil.java
FileUtil.readAsByteArray
public static byte[] readAsByteArray(File localSwfFile) { byte[] fileBytes = new byte[(int) localSwfFile.length()]; byte[] b = new byte[1]; FileInputStream fis = null; try { fis = new FileInputStream(localSwfFile); for (int i = 0; i < Integer.MAX_VALUE; i++) { if (fis.read(b) != -1) { fileBytes[i] = b[0]; } else { break; } } } catch (IOException e) { log.warn("Exception reading file bytes", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } } return fileBytes; }
java
public static byte[] readAsByteArray(File localSwfFile) { byte[] fileBytes = new byte[(int) localSwfFile.length()]; byte[] b = new byte[1]; FileInputStream fis = null; try { fis = new FileInputStream(localSwfFile); for (int i = 0; i < Integer.MAX_VALUE; i++) { if (fis.read(b) != -1) { fileBytes[i] = b[0]; } else { break; } } } catch (IOException e) { log.warn("Exception reading file bytes", e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } } return fileBytes; }
[ "public", "static", "byte", "[", "]", "readAsByteArray", "(", "File", "localSwfFile", ")", "{", "byte", "[", "]", "fileBytes", "=", "new", "byte", "[", "(", "int", ")", "localSwfFile", ".", "length", "(", ")", "]", ";", "byte", "[", "]", "b", "=", ...
Reads all the bytes of a given file into an array. If the file size exceeds Integer.MAX_VALUE, it will be truncated. @param localSwfFile swf file @return file bytes
[ "Reads", "all", "the", "bytes", "of", "a", "given", "file", "into", "an", "array", ".", "If", "the", "file", "size", "exceeds", "Integer", ".", "MAX_VALUE", "it", "will", "be", "truncated", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/util/FileUtil.java#L468-L492
train
Red5/red5-server-common
src/main/java/org/red5/server/so/SharedObjectScope.java
SharedObjectScope.getSecurityHandlers
private Set<ISharedObjectSecurity> getSecurityHandlers() { ISharedObjectSecurityService security = (ISharedObjectSecurityService) ScopeUtils.getScopeService(getParent(), ISharedObjectSecurityService.class); if (security == null) { return null; } return security.getSharedObjectSecurity(); }
java
private Set<ISharedObjectSecurity> getSecurityHandlers() { ISharedObjectSecurityService security = (ISharedObjectSecurityService) ScopeUtils.getScopeService(getParent(), ISharedObjectSecurityService.class); if (security == null) { return null; } return security.getSharedObjectSecurity(); }
[ "private", "Set", "<", "ISharedObjectSecurity", ">", "getSecurityHandlers", "(", ")", "{", "ISharedObjectSecurityService", "security", "=", "(", "ISharedObjectSecurityService", ")", "ScopeUtils", ".", "getScopeService", "(", "getParent", "(", ")", ",", "ISharedObjectSec...
Return security handlers for this shared object or <pre> null </pre> if none are found. @return set of security handlers
[ "Return", "security", "handlers", "for", "this", "shared", "object", "or" ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/so/SharedObjectScope.java#L487-L493
train
Red5/red5-server-common
src/main/java/org/red5/server/so/SharedObjectScope.java
SharedObjectScope.isConnectionAllowed
protected boolean isConnectionAllowed() { // Check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isConnectionAllowed(this)) { return false; } } // Check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; } for (ISharedObjectSecurity handler : handlers) { if (!handler.isConnectionAllowed(this)) { return false; } } return true; }
java
protected boolean isConnectionAllowed() { // Check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isConnectionAllowed(this)) { return false; } } // Check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; } for (ISharedObjectSecurity handler : handlers) { if (!handler.isConnectionAllowed(this)) { return false; } } return true; }
[ "protected", "boolean", "isConnectionAllowed", "(", ")", "{", "// Check internal handlers first\r", "for", "(", "ISharedObjectSecurity", "handler", ":", "securityHandlers", ")", "{", "if", "(", "!", "handler", ".", "isConnectionAllowed", "(", "this", ")", ")", "{", ...
Call handlers and check if connection to the existing SO is allowed. @return is connection allowed
[ "Call", "handlers", "and", "check", "if", "connection", "to", "the", "existing", "SO", "is", "allowed", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/so/SharedObjectScope.java#L500-L518
train
Red5/red5-server-common
src/main/java/org/red5/server/so/SharedObjectScope.java
SharedObjectScope.isWriteAllowed
protected boolean isWriteAllowed(String key, Object value) { // check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isWriteAllowed(this, key, value)) { return false; } } // check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; } for (ISharedObjectSecurity handler : handlers) { if (!handler.isWriteAllowed(this, key, value)) { return false; } } return true; }
java
protected boolean isWriteAllowed(String key, Object value) { // check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isWriteAllowed(this, key, value)) { return false; } } // check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; } for (ISharedObjectSecurity handler : handlers) { if (!handler.isWriteAllowed(this, key, value)) { return false; } } return true; }
[ "protected", "boolean", "isWriteAllowed", "(", "String", "key", ",", "Object", "value", ")", "{", "// check internal handlers first\r", "for", "(", "ISharedObjectSecurity", "handler", ":", "securityHandlers", ")", "{", "if", "(", "!", "handler", ".", "isWriteAllowed...
Call handlers and check if writing to the SO is allowed. @param key key @param value value @return is write allowed
[ "Call", "handlers", "and", "check", "if", "writing", "to", "the", "SO", "is", "allowed", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/so/SharedObjectScope.java#L529-L547
train
Red5/red5-server-common
src/main/java/org/red5/server/so/SharedObjectScope.java
SharedObjectScope.isDeleteAllowed
protected boolean isDeleteAllowed(String key) { // check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isDeleteAllowed(this, key)) { return false; } } // check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; } for (ISharedObjectSecurity handler : handlers) { if (!handler.isDeleteAllowed(this, key)) { return false; } } return true; }
java
protected boolean isDeleteAllowed(String key) { // check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isDeleteAllowed(this, key)) { return false; } } // check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; } for (ISharedObjectSecurity handler : handlers) { if (!handler.isDeleteAllowed(this, key)) { return false; } } return true; }
[ "protected", "boolean", "isDeleteAllowed", "(", "String", "key", ")", "{", "// check internal handlers first\r", "for", "(", "ISharedObjectSecurity", "handler", ":", "securityHandlers", ")", "{", "if", "(", "!", "handler", ".", "isDeleteAllowed", "(", "this", ",", ...
Call handlers and check if deleting a property from the SO is allowed. @param key key @return is delete allowed
[ "Call", "handlers", "and", "check", "if", "deleting", "a", "property", "from", "the", "SO", "is", "allowed", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/so/SharedObjectScope.java#L556-L574
train
Red5/red5-server-common
src/main/java/org/red5/server/so/SharedObjectScope.java
SharedObjectScope.isSendAllowed
protected boolean isSendAllowed(String message, List<?> arguments) { // check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isSendAllowed(this, message, arguments)) { return false; } } // check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; } for (ISharedObjectSecurity handler : handlers) { if (!handler.isSendAllowed(this, message, arguments)) { return false; } } return true; }
java
protected boolean isSendAllowed(String message, List<?> arguments) { // check internal handlers first for (ISharedObjectSecurity handler : securityHandlers) { if (!handler.isSendAllowed(this, message, arguments)) { return false; } } // check global SO handlers next final Set<ISharedObjectSecurity> handlers = getSecurityHandlers(); if (handlers == null) { return true; } for (ISharedObjectSecurity handler : handlers) { if (!handler.isSendAllowed(this, message, arguments)) { return false; } } return true; }
[ "protected", "boolean", "isSendAllowed", "(", "String", "message", ",", "List", "<", "?", ">", "arguments", ")", "{", "// check internal handlers first\r", "for", "(", "ISharedObjectSecurity", "handler", ":", "securityHandlers", ")", "{", "if", "(", "!", "handler"...
Call handlers and check if sending a message to the clients connected to the SO is allowed. @param message message @param arguments arguments @return is send allowed
[ "Call", "handlers", "and", "check", "if", "sending", "a", "message", "to", "the", "clients", "connected", "to", "the", "SO", "is", "allowed", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/so/SharedObjectScope.java#L585-L603
train
Red5/red5-server-common
src/main/java/org/red5/server/util/HttpConnectionUtil.java
HttpConnectionUtil.handleError
public static void handleError(HttpResponse response) throws ParseException, IOException { log.debug("{}", response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); if (entity != null) { log.debug("{}", EntityUtils.toString(entity)); } }
java
public static void handleError(HttpResponse response) throws ParseException, IOException { log.debug("{}", response.getStatusLine().toString()); HttpEntity entity = response.getEntity(); if (entity != null) { log.debug("{}", EntityUtils.toString(entity)); } }
[ "public", "static", "void", "handleError", "(", "HttpResponse", "response", ")", "throws", "ParseException", ",", "IOException", "{", "log", ".", "debug", "(", "\"{}\"", ",", "response", ".", "getStatusLine", "(", ")", ".", "toString", "(", ")", ")", ";", ...
Logs details about the request error. @param response http response @throws IOException on IO error @throws ParseException on parse error
[ "Logs", "details", "about", "the", "request", "error", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/util/HttpConnectionUtil.java#L131-L137
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPUtils.java
RTMPUtils.writeReverseInt
public static void writeReverseInt(IoBuffer out, int value) { out.put((byte) (0xFF & value)); out.put((byte) (0xFF & (value >> 8))); out.put((byte) (0xFF & (value >> 16))); out.put((byte) (0xFF & (value >> 24))); }
java
public static void writeReverseInt(IoBuffer out, int value) { out.put((byte) (0xFF & value)); out.put((byte) (0xFF & (value >> 8))); out.put((byte) (0xFF & (value >> 16))); out.put((byte) (0xFF & (value >> 24))); }
[ "public", "static", "void", "writeReverseInt", "(", "IoBuffer", "out", ",", "int", "value", ")", "{", "out", ".", "put", "(", "(", "byte", ")", "(", "0xFF", "&", "value", ")", ")", ";", "out", ".", "put", "(", "(", "byte", ")", "(", "0xFF", "&", ...
Writes reversed integer to buffer. @param out Buffer @param value Integer to write
[ "Writes", "reversed", "integer", "to", "buffer", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPUtils.java#L41-L46
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPUtils.java
RTMPUtils.readUnsignedMediumInt
public static int readUnsignedMediumInt(IoBuffer in) { final byte a = in.get(); final byte b = in.get(); final byte c = in.get(); int val = 0; val += (a & 0xff) << 16; val += (b & 0xff) << 8; val += (c & 0xff); return val; }
java
public static int readUnsignedMediumInt(IoBuffer in) { final byte a = in.get(); final byte b = in.get(); final byte c = in.get(); int val = 0; val += (a & 0xff) << 16; val += (b & 0xff) << 8; val += (c & 0xff); return val; }
[ "public", "static", "int", "readUnsignedMediumInt", "(", "IoBuffer", "in", ")", "{", "final", "byte", "a", "=", "in", ".", "get", "(", ")", ";", "final", "byte", "b", "=", "in", ".", "get", "(", ")", ";", "final", "byte", "c", "=", "in", ".", "ge...
Read unsigned 24 bit integer. @param in input @return unsigned int
[ "Read", "unsigned", "24", "bit", "integer", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPUtils.java#L67-L76
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPUtils.java
RTMPUtils.readMediumInt
public static int readMediumInt(IoBuffer in) { final byte a = in.get(); final byte b = in.get(); final byte c = in.get(); // Fix unsigned values int val = 0; val += (a & 0xff) << 16; val += (b & 0xff) << 8; val += (c & 0xff); return val; }
java
public static int readMediumInt(IoBuffer in) { final byte a = in.get(); final byte b = in.get(); final byte c = in.get(); // Fix unsigned values int val = 0; val += (a & 0xff) << 16; val += (b & 0xff) << 8; val += (c & 0xff); return val; }
[ "public", "static", "int", "readMediumInt", "(", "IoBuffer", "in", ")", "{", "final", "byte", "a", "=", "in", ".", "get", "(", ")", ";", "final", "byte", "b", "=", "in", ".", "get", "(", ")", ";", "final", "byte", "c", "=", "in", ".", "get", "(...
Read 24 bit integer. @param in input @return signed 3 byte int
[ "Read", "24", "bit", "integer", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPUtils.java#L85-L95
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPUtils.java
RTMPUtils.readReverseInt
public static int readReverseInt(IoBuffer in) { final byte a = in.get(); final byte b = in.get(); final byte c = in.get(); final byte d = in.get(); int val = 0; val += (d & 0xff) << 24; val += (c & 0xff) << 16; val += (b & 0xff) << 8; val += (a & 0xff); return val; }
java
public static int readReverseInt(IoBuffer in) { final byte a = in.get(); final byte b = in.get(); final byte c = in.get(); final byte d = in.get(); int val = 0; val += (d & 0xff) << 24; val += (c & 0xff) << 16; val += (b & 0xff) << 8; val += (a & 0xff); return val; }
[ "public", "static", "int", "readReverseInt", "(", "IoBuffer", "in", ")", "{", "final", "byte", "a", "=", "in", ".", "get", "(", ")", ";", "final", "byte", "b", "=", "in", ".", "get", "(", ")", ";", "final", "byte", "c", "=", "in", ".", "get", "...
Read integer in reversed order. @param in Input buffer @return Integer
[ "Read", "integer", "in", "reversed", "order", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPUtils.java#L104-L115
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPUtils.java
RTMPUtils.encodeHeaderByte
public static void encodeHeaderByte(IoBuffer out, byte headerSize, int channelId) { if (channelId <= 63) { out.put((byte) ((headerSize << 6) + channelId)); } else if (channelId <= 319) { out.put((byte) (headerSize << 6)); out.put((byte) (channelId - 64)); } else { out.put((byte) ((headerSize << 6) | 1)); channelId -= 64; out.put((byte) (channelId & 0xff)); out.put((byte) (channelId >> 8)); } }
java
public static void encodeHeaderByte(IoBuffer out, byte headerSize, int channelId) { if (channelId <= 63) { out.put((byte) ((headerSize << 6) + channelId)); } else if (channelId <= 319) { out.put((byte) (headerSize << 6)); out.put((byte) (channelId - 64)); } else { out.put((byte) ((headerSize << 6) | 1)); channelId -= 64; out.put((byte) (channelId & 0xff)); out.put((byte) (channelId >> 8)); } }
[ "public", "static", "void", "encodeHeaderByte", "(", "IoBuffer", "out", ",", "byte", "headerSize", ",", "int", "channelId", ")", "{", "if", "(", "channelId", "<=", "63", ")", "{", "out", ".", "put", "(", "(", "byte", ")", "(", "(", "headerSize", "<<", ...
Encodes header size marker and channel id into header marker. @param out output buffer @param headerSize Header size marker @param channelId Channel used
[ "Encodes", "header", "size", "marker", "and", "channel", "id", "into", "header", "marker", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPUtils.java#L124-L136
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPUtils.java
RTMPUtils.diffTimestamps
public static long diffTimestamps(final int a, final int b) { // first convert each to unsigned integers final long unsignedA = a & 0xFFFFFFFFL; final long unsignedB = b & 0xFFFFFFFFL; // then find the delta final long delta = unsignedA - unsignedB; return delta; }
java
public static long diffTimestamps(final int a, final int b) { // first convert each to unsigned integers final long unsignedA = a & 0xFFFFFFFFL; final long unsignedB = b & 0xFFFFFFFFL; // then find the delta final long delta = unsignedA - unsignedB; return delta; }
[ "public", "static", "long", "diffTimestamps", "(", "final", "int", "a", ",", "final", "int", "b", ")", "{", "// first convert each to unsigned integers\r", "final", "long", "unsignedA", "=", "a", "&", "0xFFFFFFFF", "L", ";", "final", "long", "unsignedB", "=", ...
Calculates the delta between two time stamps, adjusting for time stamp wrapping. @param a First time stamp @param b Second time stamp @return the distance between a and b, which will be negative if a is less than b.
[ "Calculates", "the", "delta", "between", "two", "time", "stamps", "adjusting", "for", "time", "stamp", "wrapping", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPUtils.java#L219-L226
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.startWaitForHandshake
public void startWaitForHandshake() { if (log.isDebugEnabled()) { log.debug("startWaitForHandshake - {}", sessionId); } // start the handshake checker after maxHandshakeTimeout milliseconds if (scheduler != null) { try { waitForHandshakeTask = scheduler.schedule(new WaitForHandshakeTask(), new Date(System.currentTimeMillis() + maxHandshakeTimeout)); } catch (TaskRejectedException e) { log.error("WaitForHandshake task was rejected for {}", sessionId, e); } } }
java
public void startWaitForHandshake() { if (log.isDebugEnabled()) { log.debug("startWaitForHandshake - {}", sessionId); } // start the handshake checker after maxHandshakeTimeout milliseconds if (scheduler != null) { try { waitForHandshakeTask = scheduler.schedule(new WaitForHandshakeTask(), new Date(System.currentTimeMillis() + maxHandshakeTimeout)); } catch (TaskRejectedException e) { log.error("WaitForHandshake task was rejected for {}", sessionId, e); } } }
[ "public", "void", "startWaitForHandshake", "(", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"startWaitForHandshake - {}\"", ",", "sessionId", ")", ";", "}", "// start the handshake checker after maxHandshakeTime...
Start waiting for a valid handshake.
[ "Start", "waiting", "for", "a", "valid", "handshake", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L500-L512
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.stopWaitForHandshake
private void stopWaitForHandshake() { if (waitForHandshakeTask != null) { boolean cancelled = waitForHandshakeTask.cancel(true); waitForHandshakeTask = null; if (cancelled && log.isDebugEnabled()) { log.debug("waitForHandshake was cancelled for {}", sessionId); } } }
java
private void stopWaitForHandshake() { if (waitForHandshakeTask != null) { boolean cancelled = waitForHandshakeTask.cancel(true); waitForHandshakeTask = null; if (cancelled && log.isDebugEnabled()) { log.debug("waitForHandshake was cancelled for {}", sessionId); } } }
[ "private", "void", "stopWaitForHandshake", "(", ")", "{", "if", "(", "waitForHandshakeTask", "!=", "null", ")", "{", "boolean", "cancelled", "=", "waitForHandshakeTask", ".", "cancel", "(", "true", ")", ";", "waitForHandshakeTask", "=", "null", ";", "if", "(",...
Cancels wait for handshake task.
[ "Cancels", "wait", "for", "handshake", "task", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L517-L525
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.startRoundTripMeasurement
private void startRoundTripMeasurement() { if (scheduler != null) { if (pingInterval > 0) { if (log.isDebugEnabled()) { log.debug("startRoundTripMeasurement - {}", sessionId); } try { // schedule with an initial delay of now + 2s to prevent ping messages during connect post processes keepAliveTask = scheduler.scheduleWithFixedDelay(new KeepAliveTask(), new Date(System.currentTimeMillis() + 2000L), pingInterval); if (log.isDebugEnabled()) { log.debug("Keep alive scheduled for {}", sessionId); } } catch (Exception e) { log.error("Error creating keep alive job for {}", sessionId, e); } } } else { log.error("startRoundTripMeasurement cannot be executed due to missing scheduler. This can happen if a connection drops before handshake is complete"); } }
java
private void startRoundTripMeasurement() { if (scheduler != null) { if (pingInterval > 0) { if (log.isDebugEnabled()) { log.debug("startRoundTripMeasurement - {}", sessionId); } try { // schedule with an initial delay of now + 2s to prevent ping messages during connect post processes keepAliveTask = scheduler.scheduleWithFixedDelay(new KeepAliveTask(), new Date(System.currentTimeMillis() + 2000L), pingInterval); if (log.isDebugEnabled()) { log.debug("Keep alive scheduled for {}", sessionId); } } catch (Exception e) { log.error("Error creating keep alive job for {}", sessionId, e); } } } else { log.error("startRoundTripMeasurement cannot be executed due to missing scheduler. This can happen if a connection drops before handshake is complete"); } }
[ "private", "void", "startRoundTripMeasurement", "(", ")", "{", "if", "(", "scheduler", "!=", "null", ")", "{", "if", "(", "pingInterval", ">", "0", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"st...
Starts measurement.
[ "Starts", "measurement", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L530-L549
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.stopRoundTripMeasurement
private void stopRoundTripMeasurement() { if (keepAliveTask != null) { boolean cancelled = keepAliveTask.cancel(true); keepAliveTask = null; if (cancelled && log.isDebugEnabled()) { log.debug("Keep alive was cancelled for {}", sessionId); } } }
java
private void stopRoundTripMeasurement() { if (keepAliveTask != null) { boolean cancelled = keepAliveTask.cancel(true); keepAliveTask = null; if (cancelled && log.isDebugEnabled()) { log.debug("Keep alive was cancelled for {}", sessionId); } } }
[ "private", "void", "stopRoundTripMeasurement", "(", ")", "{", "if", "(", "keepAliveTask", "!=", "null", ")", "{", "boolean", "cancelled", "=", "keepAliveTask", ".", "cancel", "(", "true", ")", ";", "keepAliveTask", "=", "null", ";", "if", "(", "cancelled", ...
Stops measurement.
[ "Stops", "measurement", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L554-L562
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.setup
public void setup(String host, String path, Map<String, Object> params) { this.host = host; this.path = path; this.params = params; if (Integer.valueOf(3).equals(params.get("objectEncoding"))) { if (log.isDebugEnabled()) { log.debug("Setting object encoding to AMF3"); } state.setEncoding(Encoding.AMF3); } }
java
public void setup(String host, String path, Map<String, Object> params) { this.host = host; this.path = path; this.params = params; if (Integer.valueOf(3).equals(params.get("objectEncoding"))) { if (log.isDebugEnabled()) { log.debug("Setting object encoding to AMF3"); } state.setEncoding(Encoding.AMF3); } }
[ "public", "void", "setup", "(", "String", "host", ",", "String", "path", ",", "Map", "<", "String", ",", "Object", ">", "params", ")", "{", "this", ".", "host", "=", "host", ";", "this", ".", "path", "=", "path", ";", "this", ".", "params", "=", ...
Initialize connection. @param host Connection host @param path Connection path @param params Params passed from client
[ "Initialize", "connection", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L574-L584
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.getChannel
public Channel getChannel(int channelId) { Channel channel = channels.putIfAbsent(channelId, new Channel(this, channelId)); if (channel == null) { channel = channels.get(channelId); } return channel; }
java
public Channel getChannel(int channelId) { Channel channel = channels.putIfAbsent(channelId, new Channel(this, channelId)); if (channel == null) { channel = channels.get(channelId); } return channel; }
[ "public", "Channel", "getChannel", "(", "int", "channelId", ")", "{", "Channel", "channel", "=", "channels", ".", "putIfAbsent", "(", "channelId", ",", "new", "Channel", "(", "this", ",", "channelId", ")", ")", ";", "if", "(", "channel", "==", "null", ")...
Return channel by id. @param channelId Channel id @return Channel by id
[ "Return", "channel", "by", "id", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L626-L632
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.closeChannel
public void closeChannel(int channelId) { if (log.isTraceEnabled()) { log.trace("closeChannel: {}", channelId); } Channel chan = channels.remove(channelId); if (log.isTraceEnabled()) { log.trace("channel: {} for id: {}", chan, channelId); if (chan == null) { log.trace("Channels: {}", channels); } } /* ReceivedMessageTaskQueue queue = tasksByChannels.remove(channelId); if (queue != null) { if (isConnected()) { // if connected, drain and process the tasks queued-up log.debug("Processing remaining tasks at close for channel: {}", channelId); processTasksQueue(queue); } queue.removeAllTasks(); } else if (log.isTraceEnabled()) { log.trace("No task queue for id: {}", channelId); } */ chan = null; }
java
public void closeChannel(int channelId) { if (log.isTraceEnabled()) { log.trace("closeChannel: {}", channelId); } Channel chan = channels.remove(channelId); if (log.isTraceEnabled()) { log.trace("channel: {} for id: {}", chan, channelId); if (chan == null) { log.trace("Channels: {}", channels); } } /* ReceivedMessageTaskQueue queue = tasksByChannels.remove(channelId); if (queue != null) { if (isConnected()) { // if connected, drain and process the tasks queued-up log.debug("Processing remaining tasks at close for channel: {}", channelId); processTasksQueue(queue); } queue.removeAllTasks(); } else if (log.isTraceEnabled()) { log.trace("No task queue for id: {}", channelId); } */ chan = null; }
[ "public", "void", "closeChannel", "(", "int", "channelId", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"closeChannel: {}\"", ",", "channelId", ")", ";", "}", "Channel", "chan", "=", "channels", ".", ...
Closes channel. @param channelId Channel id
[ "Closes", "channel", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L640-L665
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.isValidStreamId
public boolean isValidStreamId(Number streamId) { double d = streamId.doubleValue(); if (log.isTraceEnabled()) { log.trace("Checking validation for streamId {}; reservedStreams: {}; streams: {}, connection: {}", new Object[] { d, reservedStreams, streams, sessionId }); } if (d <= 0 || !reservedStreams.contains(d)) { log.warn("Stream id: {} was not reserved in connection {}", d, sessionId); // stream id has not been reserved before return false; } if (streams.get(d) != null) { // another stream already exists with this id log.warn("Another stream already exists with this id in streams {} in connection: {}", streams, sessionId); return false; } if (log.isTraceEnabled()) { log.trace("Stream id: {} is valid for connection: {}", d, sessionId); } return true; }
java
public boolean isValidStreamId(Number streamId) { double d = streamId.doubleValue(); if (log.isTraceEnabled()) { log.trace("Checking validation for streamId {}; reservedStreams: {}; streams: {}, connection: {}", new Object[] { d, reservedStreams, streams, sessionId }); } if (d <= 0 || !reservedStreams.contains(d)) { log.warn("Stream id: {} was not reserved in connection {}", d, sessionId); // stream id has not been reserved before return false; } if (streams.get(d) != null) { // another stream already exists with this id log.warn("Another stream already exists with this id in streams {} in connection: {}", streams, sessionId); return false; } if (log.isTraceEnabled()) { log.trace("Stream id: {} is valid for connection: {}", d, sessionId); } return true; }
[ "public", "boolean", "isValidStreamId", "(", "Number", "streamId", ")", "{", "double", "d", "=", "streamId", ".", "doubleValue", "(", ")", ";", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"Checking validation fo...
Returns whether or not a given stream id is valid. @param streamId stream id @return true if its valid, false if its invalid
[ "Returns", "whether", "or", "not", "a", "given", "stream", "id", "is", "valid", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L712-L731
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.isIdle
public boolean isIdle() { long lastPingTime = lastPingSentOn.get(); long lastPongTime = lastPongReceivedOn.get(); boolean idle = (lastPongTime > 0 && (lastPingTime - lastPongTime > maxInactivity)); if (log.isTraceEnabled()) { log.trace("Connection {} {} idle", getSessionId(), (idle ? "is" : "is not")); } return idle; }
java
public boolean isIdle() { long lastPingTime = lastPingSentOn.get(); long lastPongTime = lastPongReceivedOn.get(); boolean idle = (lastPongTime > 0 && (lastPingTime - lastPongTime > maxInactivity)); if (log.isTraceEnabled()) { log.trace("Connection {} {} idle", getSessionId(), (idle ? "is" : "is not")); } return idle; }
[ "public", "boolean", "isIdle", "(", ")", "{", "long", "lastPingTime", "=", "lastPingSentOn", ".", "get", "(", ")", ";", "long", "lastPongTime", "=", "lastPongReceivedOn", ".", "get", "(", ")", ";", "boolean", "idle", "=", "(", "lastPongTime", ">", "0", "...
Returns whether or not the connection has been idle for a maximum period. @return true if max idle period has been exceeded, false otherwise
[ "Returns", "whether", "or", "not", "the", "connection", "has", "been", "idle", "for", "a", "maximum", "period", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L738-L746
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.getStreamIdForChannelId
public Number getStreamIdForChannelId(int channelId) { if (channelId < 4) { return 0; } Number streamId = Math.floor(((channelId - 4) / 5.0d) + 1); if (log.isTraceEnabled()) { log.trace("Stream id: {} requested for channel id: {}", streamId, channelId); } return streamId; }
java
public Number getStreamIdForChannelId(int channelId) { if (channelId < 4) { return 0; } Number streamId = Math.floor(((channelId - 4) / 5.0d) + 1); if (log.isTraceEnabled()) { log.trace("Stream id: {} requested for channel id: {}", streamId, channelId); } return streamId; }
[ "public", "Number", "getStreamIdForChannelId", "(", "int", "channelId", ")", "{", "if", "(", "channelId", "<", "4", ")", "{", "return", "0", ";", "}", "Number", "streamId", "=", "Math", ".", "floor", "(", "(", "(", "channelId", "-", "4", ")", "/", "5...
Return stream id for given channel id. @param channelId Channel id @return ID of stream that channel belongs to
[ "Return", "stream", "id", "for", "given", "channel", "id", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L834-L843
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.getStreamByChannelId
public IClientStream getStreamByChannelId(int channelId) { // channels 2 and 3 are "special" and don't have an IClientStream associated if (channelId < 4) { return null; } Number streamId = getStreamIdForChannelId(channelId); if (log.isTraceEnabled()) { log.trace("Stream requested for channel id: {} stream id: {} streams: {}", channelId, streamId, streams); } return getStreamById(streamId); }
java
public IClientStream getStreamByChannelId(int channelId) { // channels 2 and 3 are "special" and don't have an IClientStream associated if (channelId < 4) { return null; } Number streamId = getStreamIdForChannelId(channelId); if (log.isTraceEnabled()) { log.trace("Stream requested for channel id: {} stream id: {} streams: {}", channelId, streamId, streams); } return getStreamById(streamId); }
[ "public", "IClientStream", "getStreamByChannelId", "(", "int", "channelId", ")", "{", "// channels 2 and 3 are \"special\" and don't have an IClientStream associated\r", "if", "(", "channelId", "<", "4", ")", "{", "return", "null", ";", "}", "Number", "streamId", "=", "...
Return stream by given channel id. @param channelId Channel id @return Stream that channel belongs to
[ "Return", "stream", "by", "given", "channel", "id", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L852-L862
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.getChannelIdForStreamId
public int getChannelIdForStreamId(Number streamId) { int channelId = (int) (streamId.doubleValue() * 5) - 1; if (log.isTraceEnabled()) { log.trace("Channel id: {} requested for stream id: {}", channelId, streamId); } return channelId; }
java
public int getChannelIdForStreamId(Number streamId) { int channelId = (int) (streamId.doubleValue() * 5) - 1; if (log.isTraceEnabled()) { log.trace("Channel id: {} requested for stream id: {}", channelId, streamId); } return channelId; }
[ "public", "int", "getChannelIdForStreamId", "(", "Number", "streamId", ")", "{", "int", "channelId", "=", "(", "int", ")", "(", "streamId", ".", "doubleValue", "(", ")", "*", "5", ")", "-", "1", ";", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ...
Return channel id for given stream id. @param streamId Stream id @return ID of channel that belongs to the stream
[ "Return", "channel", "id", "for", "given", "stream", "id", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L871-L877
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.createOutputStream
public OutputStream createOutputStream(Number streamId) { int channelId = getChannelIdForStreamId(streamId); if (log.isTraceEnabled()) { log.trace("Create output - stream id: {} channel id: {}", streamId, channelId); } final Channel data = getChannel(channelId++); final Channel video = getChannel(channelId++); final Channel audio = getChannel(channelId++); if (log.isTraceEnabled()) { log.trace("Output stream - data: {} video: {} audio: {}", data, video, audio); } return new OutputStream(video, audio, data); }
java
public OutputStream createOutputStream(Number streamId) { int channelId = getChannelIdForStreamId(streamId); if (log.isTraceEnabled()) { log.trace("Create output - stream id: {} channel id: {}", streamId, channelId); } final Channel data = getChannel(channelId++); final Channel video = getChannel(channelId++); final Channel audio = getChannel(channelId++); if (log.isTraceEnabled()) { log.trace("Output stream - data: {} video: {} audio: {}", data, video, audio); } return new OutputStream(video, audio, data); }
[ "public", "OutputStream", "createOutputStream", "(", "Number", "streamId", ")", "{", "int", "channelId", "=", "getChannelIdForStreamId", "(", "streamId", ")", ";", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"Crea...
Creates output stream object from stream id. Output stream consists of audio, video, and data channels. @see org.red5.server.stream.OutputStream @param streamId Stream id @return Output stream object
[ "Creates", "output", "stream", "object", "from", "stream", "id", ".", "Output", "stream", "consists", "of", "audio", "video", "and", "data", "channels", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L887-L899
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.customizeStream
private void customizeStream(Number streamId, AbstractClientStream stream) { Integer buffer = streamBuffers.get(streamId.doubleValue()); if (buffer != null) { stream.setClientBufferDuration(buffer); } stream.setName(createStreamName()); stream.setConnection(this); stream.setScope(this.getScope()); stream.setStreamId(streamId); }
java
private void customizeStream(Number streamId, AbstractClientStream stream) { Integer buffer = streamBuffers.get(streamId.doubleValue()); if (buffer != null) { stream.setClientBufferDuration(buffer); } stream.setName(createStreamName()); stream.setConnection(this); stream.setScope(this.getScope()); stream.setStreamId(streamId); }
[ "private", "void", "customizeStream", "(", "Number", "streamId", ",", "AbstractClientStream", "stream", ")", "{", "Integer", "buffer", "=", "streamBuffers", ".", "get", "(", "streamId", ".", "doubleValue", "(", ")", ")", ";", "if", "(", "buffer", "!=", "null...
Specify name, connection, scope and etc for stream @param streamId Stream id @param stream Stream
[ "Specify", "name", "connection", "scope", "and", "etc", "for", "stream" ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L909-L918
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.registerStream
private boolean registerStream(IClientStream stream) { if (streams.putIfAbsent(stream.getStreamId().doubleValue(), stream) == null) { usedStreams.incrementAndGet(); return true; } log.error("Unable to register stream {}, stream with id {} was already added", stream, stream.getStreamId()); return false; }
java
private boolean registerStream(IClientStream stream) { if (streams.putIfAbsent(stream.getStreamId().doubleValue(), stream) == null) { usedStreams.incrementAndGet(); return true; } log.error("Unable to register stream {}, stream with id {} was already added", stream, stream.getStreamId()); return false; }
[ "private", "boolean", "registerStream", "(", "IClientStream", "stream", ")", "{", "if", "(", "streams", ".", "putIfAbsent", "(", "stream", ".", "getStreamId", "(", ")", ".", "doubleValue", "(", ")", ",", "stream", ")", "==", "null", ")", "{", "usedStreams"...
Store a stream in the connection. @param stream
[ "Store", "a", "stream", "in", "the", "connection", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L925-L932
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.updateBytesRead
protected void updateBytesRead() { if (log.isTraceEnabled()) { log.trace("updateBytesRead"); } long bytesRead = getReadBytes(); if (bytesRead >= nextBytesRead) { BytesRead sbr = new BytesRead((int) (bytesRead % Integer.MAX_VALUE)); getChannel(2).write(sbr); nextBytesRead += bytesReadInterval; } }
java
protected void updateBytesRead() { if (log.isTraceEnabled()) { log.trace("updateBytesRead"); } long bytesRead = getReadBytes(); if (bytesRead >= nextBytesRead) { BytesRead sbr = new BytesRead((int) (bytesRead % Integer.MAX_VALUE)); getChannel(2).write(sbr); nextBytesRead += bytesReadInterval; } }
[ "protected", "void", "updateBytesRead", "(", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"updateBytesRead\"", ")", ";", "}", "long", "bytesRead", "=", "getReadBytes", "(", ")", ";", "if", "(", "byt...
Update number of bytes to read next value.
[ "Update", "number", "of", "bytes", "to", "read", "next", "value", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L1118-L1128
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.receivedBytesRead
public void receivedBytesRead(int bytes) { if (log.isDebugEnabled()) { log.debug("Client received {} bytes, written {} bytes, {} messages pending", new Object[] { bytes, getWrittenBytes(), getPendingMessages() }); } clientBytesRead.addAndGet(bytes); }
java
public void receivedBytesRead(int bytes) { if (log.isDebugEnabled()) { log.debug("Client received {} bytes, written {} bytes, {} messages pending", new Object[] { bytes, getWrittenBytes(), getPendingMessages() }); } clientBytesRead.addAndGet(bytes); }
[ "public", "void", "receivedBytesRead", "(", "int", "bytes", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "{", "log", ".", "debug", "(", "\"Client received {} bytes, written {} bytes, {} messages pending\"", ",", "new", "Object", "[", "]", "{...
Read number of received bytes. @param bytes Number of bytes
[ "Read", "number", "of", "received", "bytes", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L1136-L1141
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.writingMessage
protected void writingMessage(Packet message) { if (message.getMessage() instanceof VideoData) { Number streamId = message.getHeader().getStreamId(); final AtomicInteger value = new AtomicInteger(); AtomicInteger old = pendingVideos.putIfAbsent(streamId.doubleValue(), value); if (old == null) { old = value; } old.incrementAndGet(); } }
java
protected void writingMessage(Packet message) { if (message.getMessage() instanceof VideoData) { Number streamId = message.getHeader().getStreamId(); final AtomicInteger value = new AtomicInteger(); AtomicInteger old = pendingVideos.putIfAbsent(streamId.doubleValue(), value); if (old == null) { old = value; } old.incrementAndGet(); } }
[ "protected", "void", "writingMessage", "(", "Packet", "message", ")", "{", "if", "(", "message", ".", "getMessage", "(", ")", "instanceof", "VideoData", ")", "{", "Number", "streamId", "=", "message", ".", "getHeader", "(", ")", ".", "getStreamId", "(", ")...
Mark message as being written. @param message Message to mark
[ "Mark", "message", "as", "being", "written", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L1298-L1308
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.handleMessageReceived
public void handleMessageReceived(Packet packet) { if (log.isTraceEnabled()) { log.trace("handleMessageReceived - {}", sessionId); } // set the packet expiration time if maxHandlingTimeout is not disabled (set to 0) if (maxHandlingTimeout > 0) { packet.setExpirationTime(System.currentTimeMillis() + maxHandlingTimeout); } if (executor != null) { final byte dataType = packet.getHeader().getDataType(); // route these types outside the executor switch (dataType) { case Constants.TYPE_PING: case Constants.TYPE_ABORT: case Constants.TYPE_BYTES_READ: case Constants.TYPE_CHUNK_SIZE: case Constants.TYPE_CLIENT_BANDWIDTH: case Constants.TYPE_SERVER_BANDWIDTH: // pass message to the handler try { handler.messageReceived(this, packet); } catch (Exception e) { log.error("Error processing received message {}", sessionId, e); } break; default: final String messageType = getMessageType(packet); try { // increment the packet number final long packetNumber = packetSequence.incrementAndGet(); if (executorQueueSizeToDropAudioPackets > 0 && currentQueueSize.get() >= executorQueueSizeToDropAudioPackets) { if (packet.getHeader().getDataType() == Constants.TYPE_AUDIO_DATA) { // if there's a backlog of messages in the queue. Flash might have sent a burst of messages after a network congestion. Throw away packets that we are able to discard. log.info("Queue threshold reached. Discarding packet: session=[{}], msgType=[{}], packetNum=[{}]", sessionId, messageType, packetNumber); return; } } int streamId = packet.getHeader().getStreamId().intValue(); if (log.isTraceEnabled()) { log.trace("Handling message for streamId: {}, channelId: {} Channels: {}", streamId, packet.getHeader().getChannelId(), channels); } // create a task to setProcessing the message ReceivedMessageTask task = new ReceivedMessageTask(sessionId, packet, handler, this); task.setPacketNumber(packetNumber); // create a task queue ReceivedMessageTaskQueue newStreamTasks = new ReceivedMessageTaskQueue(streamId, this); // put the queue in the task by stream map ReceivedMessageTaskQueue currentStreamTasks = tasksByStreams.putIfAbsent(streamId, newStreamTasks); if (currentStreamTasks != null) { // add the task to the existing queue currentStreamTasks.addTask(task); } else { // add the task to the newly created and just added queue newStreamTasks.addTask(task); } } catch (Exception e) { log.error("Incoming message handling failed on session=[" + sessionId + "], messageType=[" + messageType + "]", e); if (log.isDebugEnabled()) { log.debug("Execution rejected on {} - {}", sessionId, RTMP.states[getStateCode()]); log.debug("Lock permits - decode: {} encode: {}", decoderLock.availablePermits(), encoderLock.availablePermits()); } } } } else { log.debug("Executor is null on {} state: {}", sessionId, RTMP.states[getStateCode()]); // pass message to the handler try { handler.messageReceived(this, packet); } catch (Exception e) { log.error("Error processing received message {} state: {}", sessionId, RTMP.states[getStateCode()], e); } } }
java
public void handleMessageReceived(Packet packet) { if (log.isTraceEnabled()) { log.trace("handleMessageReceived - {}", sessionId); } // set the packet expiration time if maxHandlingTimeout is not disabled (set to 0) if (maxHandlingTimeout > 0) { packet.setExpirationTime(System.currentTimeMillis() + maxHandlingTimeout); } if (executor != null) { final byte dataType = packet.getHeader().getDataType(); // route these types outside the executor switch (dataType) { case Constants.TYPE_PING: case Constants.TYPE_ABORT: case Constants.TYPE_BYTES_READ: case Constants.TYPE_CHUNK_SIZE: case Constants.TYPE_CLIENT_BANDWIDTH: case Constants.TYPE_SERVER_BANDWIDTH: // pass message to the handler try { handler.messageReceived(this, packet); } catch (Exception e) { log.error("Error processing received message {}", sessionId, e); } break; default: final String messageType = getMessageType(packet); try { // increment the packet number final long packetNumber = packetSequence.incrementAndGet(); if (executorQueueSizeToDropAudioPackets > 0 && currentQueueSize.get() >= executorQueueSizeToDropAudioPackets) { if (packet.getHeader().getDataType() == Constants.TYPE_AUDIO_DATA) { // if there's a backlog of messages in the queue. Flash might have sent a burst of messages after a network congestion. Throw away packets that we are able to discard. log.info("Queue threshold reached. Discarding packet: session=[{}], msgType=[{}], packetNum=[{}]", sessionId, messageType, packetNumber); return; } } int streamId = packet.getHeader().getStreamId().intValue(); if (log.isTraceEnabled()) { log.trace("Handling message for streamId: {}, channelId: {} Channels: {}", streamId, packet.getHeader().getChannelId(), channels); } // create a task to setProcessing the message ReceivedMessageTask task = new ReceivedMessageTask(sessionId, packet, handler, this); task.setPacketNumber(packetNumber); // create a task queue ReceivedMessageTaskQueue newStreamTasks = new ReceivedMessageTaskQueue(streamId, this); // put the queue in the task by stream map ReceivedMessageTaskQueue currentStreamTasks = tasksByStreams.putIfAbsent(streamId, newStreamTasks); if (currentStreamTasks != null) { // add the task to the existing queue currentStreamTasks.addTask(task); } else { // add the task to the newly created and just added queue newStreamTasks.addTask(task); } } catch (Exception e) { log.error("Incoming message handling failed on session=[" + sessionId + "], messageType=[" + messageType + "]", e); if (log.isDebugEnabled()) { log.debug("Execution rejected on {} - {}", sessionId, RTMP.states[getStateCode()]); log.debug("Lock permits - decode: {} encode: {}", decoderLock.availablePermits(), encoderLock.availablePermits()); } } } } else { log.debug("Executor is null on {} state: {}", sessionId, RTMP.states[getStateCode()]); // pass message to the handler try { handler.messageReceived(this, packet); } catch (Exception e) { log.error("Error processing received message {} state: {}", sessionId, RTMP.states[getStateCode()], e); } } }
[ "public", "void", "handleMessageReceived", "(", "Packet", "packet", ")", "{", "if", "(", "log", ".", "isTraceEnabled", "(", ")", ")", "{", "log", ".", "trace", "(", "\"handleMessageReceived - {}\"", ",", "sessionId", ")", ";", "}", "// set the packet expiration ...
Handle the incoming message. @param packet incoming message packet
[ "Handle", "the", "incoming", "message", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L1370-L1442
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.messageSent
public void messageSent(Packet message) { if (message.getMessage() instanceof VideoData) { Number streamId = message.getHeader().getStreamId(); AtomicInteger pending = pendingVideos.get(streamId.doubleValue()); if (log.isTraceEnabled()) { log.trace("Stream id: {} pending: {} total pending videos: {}", streamId, pending, pendingVideos.size()); } if (pending != null) { pending.decrementAndGet(); } } writtenMessages.incrementAndGet(); }
java
public void messageSent(Packet message) { if (message.getMessage() instanceof VideoData) { Number streamId = message.getHeader().getStreamId(); AtomicInteger pending = pendingVideos.get(streamId.doubleValue()); if (log.isTraceEnabled()) { log.trace("Stream id: {} pending: {} total pending videos: {}", streamId, pending, pendingVideos.size()); } if (pending != null) { pending.decrementAndGet(); } } writtenMessages.incrementAndGet(); }
[ "public", "void", "messageSent", "(", "Packet", "message", ")", "{", "if", "(", "message", ".", "getMessage", "(", ")", "instanceof", "VideoData", ")", "{", "Number", "streamId", "=", "message", ".", "getHeader", "(", ")", ".", "getStreamId", "(", ")", "...
Mark message as sent. @param message Message to mark
[ "Mark", "message", "as", "sent", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L1521-L1533
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.sendSharedObjectMessage
public void sendSharedObjectMessage(String name, int currentVersion, boolean persistent, Set<ISharedObjectEvent> events) { // create a new sync message for every client to avoid concurrent access through multiple threads SharedObjectMessage syncMessage = state.getEncoding() == Encoding.AMF3 ? new FlexSharedObjectMessage(null, name, currentVersion, persistent) : new SharedObjectMessage(null, name, currentVersion, persistent); syncMessage.addEvents(events); try { // get the channel for so updates Channel channel = getChannel(3); if (log.isTraceEnabled()) { log.trace("Send to channel: {}", channel); } channel.write(syncMessage); } catch (Exception e) { log.warn("Exception sending shared object", e); } }
java
public void sendSharedObjectMessage(String name, int currentVersion, boolean persistent, Set<ISharedObjectEvent> events) { // create a new sync message for every client to avoid concurrent access through multiple threads SharedObjectMessage syncMessage = state.getEncoding() == Encoding.AMF3 ? new FlexSharedObjectMessage(null, name, currentVersion, persistent) : new SharedObjectMessage(null, name, currentVersion, persistent); syncMessage.addEvents(events); try { // get the channel for so updates Channel channel = getChannel(3); if (log.isTraceEnabled()) { log.trace("Send to channel: {}", channel); } channel.write(syncMessage); } catch (Exception e) { log.warn("Exception sending shared object", e); } }
[ "public", "void", "sendSharedObjectMessage", "(", "String", "name", ",", "int", "currentVersion", ",", "boolean", "persistent", ",", "Set", "<", "ISharedObjectEvent", ">", "events", ")", "{", "// create a new sync message for every client to avoid concurrent access through mu...
Send a shared object message. @param name shared object name @param currentVersion the current version @param persistent toggle @param events shared object events
[ "Send", "a", "shared", "object", "message", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L1573-L1587
train
Red5/red5-server-common
src/main/java/org/red5/server/net/rtmp/RTMPConnection.java
RTMPConnection.pingReceived
public void pingReceived(Ping pong) { long now = System.currentTimeMillis(); long previousPingTime = lastPingSentOn.get(); int previousPingValue = (int) (previousPingTime & 0xffffffffL); int pongValue = pong.getValue2().intValue(); if (log.isDebugEnabled()) { log.debug("Pong received: session=[{}] at {} with value {}, previous received at {}", new Object[] { getSessionId(), now, pongValue, previousPingValue }); } if (pongValue == previousPingValue) { lastPingRoundTripTime.set((int) ((now - previousPingTime) & 0xffffffffL)); if (log.isDebugEnabled()) { log.debug("Ping response session=[{}], RTT=[{} ms]", new Object[] { getSessionId(), lastPingRoundTripTime.get() }); } } else { // don't log the congestion entry unless there are more than X messages waiting if (getPendingMessages() > 4) { int pingRtt = (int) ((now & 0xffffffffL)) - pongValue; log.info("Pong delayed: session=[{}], ping response took [{} ms] to arrive. Connection may be congested, or loopback", new Object[] { getSessionId(), pingRtt }); } } lastPongReceivedOn.set(now); }
java
public void pingReceived(Ping pong) { long now = System.currentTimeMillis(); long previousPingTime = lastPingSentOn.get(); int previousPingValue = (int) (previousPingTime & 0xffffffffL); int pongValue = pong.getValue2().intValue(); if (log.isDebugEnabled()) { log.debug("Pong received: session=[{}] at {} with value {}, previous received at {}", new Object[] { getSessionId(), now, pongValue, previousPingValue }); } if (pongValue == previousPingValue) { lastPingRoundTripTime.set((int) ((now - previousPingTime) & 0xffffffffL)); if (log.isDebugEnabled()) { log.debug("Ping response session=[{}], RTT=[{} ms]", new Object[] { getSessionId(), lastPingRoundTripTime.get() }); } } else { // don't log the congestion entry unless there are more than X messages waiting if (getPendingMessages() > 4) { int pingRtt = (int) ((now & 0xffffffffL)) - pongValue; log.info("Pong delayed: session=[{}], ping response took [{} ms] to arrive. Connection may be congested, or loopback", new Object[] { getSessionId(), pingRtt }); } } lastPongReceivedOn.set(now); }
[ "public", "void", "pingReceived", "(", "Ping", "pong", ")", "{", "long", "now", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "long", "previousPingTime", "=", "lastPingSentOn", ".", "get", "(", ")", ";", "int", "previousPingValue", "=", "(", "int...
Marks that ping back was received. @param pong Ping object
[ "Marks", "that", "ping", "back", "was", "received", "." ]
39ae73710c25bda86d70b13ef37ae707962217b9
https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/rtmp/RTMPConnection.java#L1612-L1633
train
metafacture/metafacture-core
metafacture-commons/src/main/java/org/metafacture/commons/tries/SetMatcher.java
SetMatcher.printAutomaton
public void printAutomaton(final PrintStream out) { out.println("digraph ahocorasick {"); printDebug(out, root); out.println("}"); }
java
public void printAutomaton(final PrintStream out) { out.println("digraph ahocorasick {"); printDebug(out, root); out.println("}"); }
[ "public", "void", "printAutomaton", "(", "final", "PrintStream", "out", ")", "{", "out", ".", "println", "(", "\"digraph ahocorasick {\"", ")", ";", "printDebug", "(", "out", ",", "root", ")", ";", "out", ".", "println", "(", "\"}\"", ")", ";", "}" ]
Prints dot description of the automaton to out for visualization in GraphViz. Used for debugging and education. @param out the stream t which the description is written
[ "Prints", "dot", "description", "of", "the", "automaton", "to", "out", "for", "visualization", "in", "GraphViz", ".", "Used", "for", "debugging", "and", "education", "." ]
cb43933ec8eb01a4ddce4019c14b2415cc441918
https://github.com/metafacture/metafacture-core/blob/cb43933ec8eb01a4ddce4019c14b2415cc441918/metafacture-commons/src/main/java/org/metafacture/commons/tries/SetMatcher.java#L135-L139
train
metafacture/metafacture-core
metafacture-json/src/main/java/org/metafacture/json/JsonEncoder.java
JsonEncoder.setJavaScriptEscapeChars
public void setJavaScriptEscapeChars(final int[] escapeCharacters) { final CharacterEscapes ce = new CharacterEscapes() { private static final long serialVersionUID = 1L; @Override public int[] getEscapeCodesForAscii() { if (escapeCharacters == null) { return CharacterEscapes.standardAsciiEscapesForJSON(); } return escapeCharacters; } @Override public SerializableString getEscapeSequence(final int ch) { final String jsEscaped = escapeChar((char) ch); return new SerializedString(jsEscaped); } }; jsonGenerator.setCharacterEscapes(ce); }
java
public void setJavaScriptEscapeChars(final int[] escapeCharacters) { final CharacterEscapes ce = new CharacterEscapes() { private static final long serialVersionUID = 1L; @Override public int[] getEscapeCodesForAscii() { if (escapeCharacters == null) { return CharacterEscapes.standardAsciiEscapesForJSON(); } return escapeCharacters; } @Override public SerializableString getEscapeSequence(final int ch) { final String jsEscaped = escapeChar((char) ch); return new SerializedString(jsEscaped); } }; jsonGenerator.setCharacterEscapes(ce); }
[ "public", "void", "setJavaScriptEscapeChars", "(", "final", "int", "[", "]", "escapeCharacters", ")", "{", "final", "CharacterEscapes", "ce", "=", "new", "CharacterEscapes", "(", ")", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";",...
By default JSON output does only have escaping where it is strictly necessary. This is recommended in the most cases. Nevertheless it can be sometimes useful to have some more escaping. @param escapeCharacters an array which defines which characters should be escaped and how it will be done. See {@link CharacterEscapes}. In most cases this should be null. Use like this: <pre>{@code int[] esc = CharacterEscapes.standardAsciiEscapesForJSON(); // and force escaping of a few others: esc['\''] = CharacterEscapes.ESCAPE_STANDARD; JsonEncoder.useEscapeJavaScript(esc); }</pre>
[ "By", "default", "JSON", "output", "does", "only", "have", "escaping", "where", "it", "is", "strictly", "necessary", ".", "This", "is", "recommended", "in", "the", "most", "cases", ".", "Nevertheless", "it", "can", "be", "sometimes", "useful", "to", "have", ...
cb43933ec8eb01a4ddce4019c14b2415cc441918
https://github.com/metafacture/metafacture-core/blob/cb43933ec8eb01a4ddce4019c14b2415cc441918/metafacture-json/src/main/java/org/metafacture/json/JsonEncoder.java#L92-L115
train
metafacture/metafacture-core
metafacture-flowcontrol/src/main/java/org/metafacture/flowcontrol/StreamBuffer.java
StreamBuffer.replay
public void replay() { int index = 0; for (MessageType type : typeBuffer) { switch (type) { case RECORD_START: getReceiver().startRecord(valueBuffer.get(index)); ++index; break; case RECORD_END: getReceiver().endRecord(); break; case ENTITY_START: getReceiver().startEntity(valueBuffer.get(index)); ++index; break; case ENTITY_END: getReceiver().endEntity(); break; default: getReceiver().literal(valueBuffer.get(index), valueBuffer.get(index+1)); index +=2; break; } } }
java
public void replay() { int index = 0; for (MessageType type : typeBuffer) { switch (type) { case RECORD_START: getReceiver().startRecord(valueBuffer.get(index)); ++index; break; case RECORD_END: getReceiver().endRecord(); break; case ENTITY_START: getReceiver().startEntity(valueBuffer.get(index)); ++index; break; case ENTITY_END: getReceiver().endEntity(); break; default: getReceiver().literal(valueBuffer.get(index), valueBuffer.get(index+1)); index +=2; break; } } }
[ "public", "void", "replay", "(", ")", "{", "int", "index", "=", "0", ";", "for", "(", "MessageType", "type", ":", "typeBuffer", ")", "{", "switch", "(", "type", ")", "{", "case", "RECORD_START", ":", "getReceiver", "(", ")", ".", "startRecord", "(", ...
Replays the buffered event.
[ "Replays", "the", "buffered", "event", "." ]
cb43933ec8eb01a4ddce4019c14b2415cc441918
https://github.com/metafacture/metafacture-core/blob/cb43933ec8eb01a4ddce4019c14b2415cc441918/metafacture-flowcontrol/src/main/java/org/metafacture/flowcontrol/StreamBuffer.java#L54-L80
train
metafacture/metafacture-core
metamorph/src/main/java/org/metafacture/metamorph/InlineMorph.java
InlineMorph.with
public InlineMorph with(String line) { if (scriptBuilder.length() == 0) { appendBoilerplate(line); } scriptBuilder .append(line) .append("\n"); return this; }
java
public InlineMorph with(String line) { if (scriptBuilder.length() == 0) { appendBoilerplate(line); } scriptBuilder .append(line) .append("\n"); return this; }
[ "public", "InlineMorph", "with", "(", "String", "line", ")", "{", "if", "(", "scriptBuilder", ".", "length", "(", ")", "==", "0", ")", "{", "appendBoilerplate", "(", "line", ")", ";", "}", "scriptBuilder", ".", "append", "(", "line", ")", ".", "append"...
Adds a line to the morph script. @param line the next line of the morph script @return a reference to {@code this} for continuation
[ "Adds", "a", "line", "to", "the", "morph", "script", "." ]
cb43933ec8eb01a4ddce4019c14b2415cc441918
https://github.com/metafacture/metafacture-core/blob/cb43933ec8eb01a4ddce4019c14b2415cc441918/metamorph/src/main/java/org/metafacture/metamorph/InlineMorph.java#L105-L113
train
metafacture/metafacture-core
metafacture-commons/src/main/java/org/metafacture/commons/StringUtil.java
StringUtil.repeatChars
public static String repeatChars(final char ch, final int count) { return CharBuffer.allocate(count).toString().replace('\0', ch); }
java
public static String repeatChars(final char ch, final int count) { return CharBuffer.allocate(count).toString().replace('\0', ch); }
[ "public", "static", "String", "repeatChars", "(", "final", "char", "ch", ",", "final", "int", "count", ")", "{", "return", "CharBuffer", ".", "allocate", "(", "count", ")", ".", "toString", "(", ")", ".", "replace", "(", "'", "'", ",", "ch", ")", ";"...
Creates a string which contains a sequence of repeated characters. @param ch to repeat @param count number of repetitions @return a string with {@code count} consisting only of {@code ch}
[ "Creates", "a", "string", "which", "contains", "a", "sequence", "of", "repeated", "characters", "." ]
cb43933ec8eb01a4ddce4019c14b2415cc441918
https://github.com/metafacture/metafacture-core/blob/cb43933ec8eb01a4ddce4019c14b2415cc441918/metafacture-commons/src/main/java/org/metafacture/commons/StringUtil.java#L155-L157
train
metafacture/metafacture-core
metafacture-mangling/src/main/java/org/metafacture/mangling/EntityPathTracker.java
EntityPathTracker.getCurrentPathWith
public String getCurrentPathWith(final String literalName) { if (entityStack.size() == 0) { return literalName; } return getCurrentPath() + entitySeparator + literalName; }
java
public String getCurrentPathWith(final String literalName) { if (entityStack.size() == 0) { return literalName; } return getCurrentPath() + entitySeparator + literalName; }
[ "public", "String", "getCurrentPathWith", "(", "final", "String", "literalName", ")", "{", "if", "(", "entityStack", ".", "size", "(", ")", "==", "0", ")", "{", "return", "literalName", ";", "}", "return", "getCurrentPath", "(", ")", "+", "entitySeparator", ...
Returns the current entity path with the given literal name appended. @param literalName the literal name to append to the current entity path. Must not be null. @return the current entity path with the literal name appended. The {@link #getEntitySeparator()} is used to separate both unless no entity was received yet in which case only the literal name is returned.
[ "Returns", "the", "current", "entity", "path", "with", "the", "given", "literal", "name", "appended", "." ]
cb43933ec8eb01a4ddce4019c14b2415cc441918
https://github.com/metafacture/metafacture-core/blob/cb43933ec8eb01a4ddce4019c14b2415cc441918/metafacture-mangling/src/main/java/org/metafacture/mangling/EntityPathTracker.java#L67-L72
train
metafacture/metafacture-core
metafacture-biblio/src/main/java/org/metafacture/biblio/iso2709/Iso646ByteBuffer.java
Iso646ByteBuffer.stringAt
String stringAt(final int fromIndex, final int length, final Charset charset) { return new String(byteArray, fromIndex, length, charset); }
java
String stringAt(final int fromIndex, final int length, final Charset charset) { return new String(byteArray, fromIndex, length, charset); }
[ "String", "stringAt", "(", "final", "int", "fromIndex", ",", "final", "int", "length", ",", "final", "Charset", "charset", ")", "{", "return", "new", "String", "(", "byteArray", ",", "fromIndex", ",", "length", ",", "charset", ")", ";", "}" ]
Returns a string containing the characters in the specified part of the record. @param fromIndex index of the first byte of the string. @param length number of bytes to include in the string. If zero an empty string is returned. @param charset used for decoding the byte sequence into characters. It is callers responsibility to make sure that the selected byte range contains a valid byte sequence when working with multi-byte encodings such as UTF-8. @return the string represented by the bytes in the given range
[ "Returns", "a", "string", "containing", "the", "characters", "in", "the", "specified", "part", "of", "the", "record", "." ]
cb43933ec8eb01a4ddce4019c14b2415cc441918
https://github.com/metafacture/metafacture-core/blob/cb43933ec8eb01a4ddce4019c14b2415cc441918/metafacture-biblio/src/main/java/org/metafacture/biblio/iso2709/Iso646ByteBuffer.java#L138-L141
train
metafacture/metafacture-core
metafacture-triples/src/main/java/org/metafacture/triples/MemoryWarningSystem.java
MemoryWarningSystem.findTenuredGenPool
private static MemoryPoolMXBean findTenuredGenPool() { // I don't know whether this approach is better, or whether // we should rather check for the pool name "Tenured Gen"? for (final MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) { return pool; } throw new AssertionError("Could not find tenured space"); }
java
private static MemoryPoolMXBean findTenuredGenPool() { // I don't know whether this approach is better, or whether // we should rather check for the pool name "Tenured Gen"? for (final MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) if (pool.getType() == MemoryType.HEAP && pool.isUsageThresholdSupported()) { return pool; } throw new AssertionError("Could not find tenured space"); }
[ "private", "static", "MemoryPoolMXBean", "findTenuredGenPool", "(", ")", "{", "// I don't know whether this approach is better, or whether", "// we should rather check for the pool name \"Tenured Gen\"?", "for", "(", "final", "MemoryPoolMXBean", "pool", ":", "ManagementFactory", ".",...
Tenured Space Pool can be determined by it being of type HEAP and by it being possible to set the usage threshold. @return MXBean for the Tenured Space Pool
[ "Tenured", "Space", "Pool", "can", "be", "determined", "by", "it", "being", "of", "type", "HEAP", "and", "by", "it", "being", "possible", "to", "set", "the", "usage", "threshold", "." ]
cb43933ec8eb01a4ddce4019c14b2415cc441918
https://github.com/metafacture/metafacture-core/blob/cb43933ec8eb01a4ddce4019c14b2415cc441918/metafacture-triples/src/main/java/org/metafacture/triples/MemoryWarningSystem.java#L97-L105
train
pili-engineering/pili-sdk-java
src/main/java/com/qiniu/pili/Hub.java
Hub.listLive
public ListRet listLive(String prefix, int limit, String marker) throws PiliException { return list(true, prefix, limit, marker); }
java
public ListRet listLive(String prefix, int limit, String marker) throws PiliException { return list(true, prefix, limit, marker); }
[ "public", "ListRet", "listLive", "(", "String", "prefix", ",", "int", "limit", ",", "String", "marker", ")", "throws", "PiliException", "{", "return", "list", "(", "true", ",", "prefix", ",", "limit", ",", "marker", ")", ";", "}" ]
list streams which is live @param prefix @param limit @param marker @return @throws PiliException
[ "list", "streams", "which", "is", "live" ]
7abadbd2baaa389d226a6f9351d82e2e5a60fe32
https://github.com/pili-engineering/pili-sdk-java/blob/7abadbd2baaa389d226a6f9351d82e2e5a60fe32/src/main/java/com/qiniu/pili/Hub.java#L117-L119
train
pili-engineering/pili-sdk-java
src/main/java/com/qiniu/pili/Hub.java
Hub.batchLiveStatus
public BatchLiveStatus[] batchLiveStatus(String[] streamTitles) throws PiliException { String path = baseUrl + "/livestreams"; String json = gson.toJson(new BatchLiveStatusOptions(streamTitles)); try { String resp = cli.callWithJson(path, json); BatchLiveStatusRet ret = gson.fromJson(resp, BatchLiveStatusRet.class); return ret.items; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
java
public BatchLiveStatus[] batchLiveStatus(String[] streamTitles) throws PiliException { String path = baseUrl + "/livestreams"; String json = gson.toJson(new BatchLiveStatusOptions(streamTitles)); try { String resp = cli.callWithJson(path, json); BatchLiveStatusRet ret = gson.fromJson(resp, BatchLiveStatusRet.class); return ret.items; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
[ "public", "BatchLiveStatus", "[", "]", "batchLiveStatus", "(", "String", "[", "]", "streamTitles", ")", "throws", "PiliException", "{", "String", "path", "=", "baseUrl", "+", "\"/livestreams\"", ";", "String", "json", "=", "gson", ".", "toJson", "(", "new", ...
batch get live status @param streamTitles @return @throws PiliException
[ "batch", "get", "live", "status" ]
7abadbd2baaa389d226a6f9351d82e2e5a60fe32
https://github.com/pili-engineering/pili-sdk-java/blob/7abadbd2baaa389d226a6f9351d82e2e5a60fe32/src/main/java/com/qiniu/pili/Hub.java#L128-L141
train
pili-engineering/pili-sdk-java
src/main/java/com/qiniu/pili/Stream.java
Stream.info
public Stream info() throws PiliException { try { String resp = cli.callWithGet(baseUrl); StreamInfo ret = gson.fromJson(resp, StreamInfo.class); ret.setMeta(info.getHub(), info.getKey()); this.info = ret; return this; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
java
public Stream info() throws PiliException { try { String resp = cli.callWithGet(baseUrl); StreamInfo ret = gson.fromJson(resp, StreamInfo.class); ret.setMeta(info.getHub(), info.getKey()); this.info = ret; return this; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
[ "public", "Stream", "info", "(", ")", "throws", "PiliException", "{", "try", "{", "String", "resp", "=", "cli", ".", "callWithGet", "(", "baseUrl", ")", ";", "StreamInfo", "ret", "=", "gson", ".", "fromJson", "(", "resp", ",", "StreamInfo", ".", "class",...
fetch stream info @return @throws PiliException
[ "fetch", "stream", "info" ]
7abadbd2baaa389d226a6f9351d82e2e5a60fe32
https://github.com/pili-engineering/pili-sdk-java/blob/7abadbd2baaa389d226a6f9351d82e2e5a60fe32/src/main/java/com/qiniu/pili/Stream.java#L79-L91
train
pili-engineering/pili-sdk-java
src/main/java/com/qiniu/pili/Stream.java
Stream.liveStatus
public LiveStatus liveStatus() throws PiliException { String path = baseUrl + "/live"; try { String resp = cli.callWithGet(path); LiveStatus status = gson.fromJson(resp, LiveStatus.class); return status; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
java
public LiveStatus liveStatus() throws PiliException { String path = baseUrl + "/live"; try { String resp = cli.callWithGet(path); LiveStatus status = gson.fromJson(resp, LiveStatus.class); return status; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
[ "public", "LiveStatus", "liveStatus", "(", ")", "throws", "PiliException", "{", "String", "path", "=", "baseUrl", "+", "\"/live\"", ";", "try", "{", "String", "resp", "=", "cli", ".", "callWithGet", "(", "path", ")", ";", "LiveStatus", "status", "=", "gson...
get the status of live stream @return @throws PiliException
[ "get", "the", "status", "of", "live", "stream" ]
7abadbd2baaa389d226a6f9351d82e2e5a60fe32
https://github.com/pili-engineering/pili-sdk-java/blob/7abadbd2baaa389d226a6f9351d82e2e5a60fe32/src/main/java/com/qiniu/pili/Stream.java#L127-L138
train
pili-engineering/pili-sdk-java
src/main/java/com/qiniu/pili/Stream.java
Stream.save
public String save(SaveOptions opts) throws PiliException { String path = baseUrl + "/saveas"; String json = gson.toJson(opts); try { String resp = cli.callWithJson(path, json); SaveRet ret = gson.fromJson(resp, SaveRet.class); return ret.fname; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
java
public String save(SaveOptions opts) throws PiliException { String path = baseUrl + "/saveas"; String json = gson.toJson(opts); try { String resp = cli.callWithJson(path, json); SaveRet ret = gson.fromJson(resp, SaveRet.class); return ret.fname; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
[ "public", "String", "save", "(", "SaveOptions", "opts", ")", "throws", "PiliException", "{", "String", "path", "=", "baseUrl", "+", "\"/saveas\"", ";", "String", "json", "=", "gson", ".", "toJson", "(", "opts", ")", ";", "try", "{", "String", "resp", "="...
save playback with more options @param opts @return @throws PiliException
[ "save", "playback", "with", "more", "options" ]
7abadbd2baaa389d226a6f9351d82e2e5a60fe32
https://github.com/pili-engineering/pili-sdk-java/blob/7abadbd2baaa389d226a6f9351d82e2e5a60fe32/src/main/java/com/qiniu/pili/Stream.java#L160-L173
train
pili-engineering/pili-sdk-java
src/main/java/com/qiniu/pili/Stream.java
Stream.snapshot
public String snapshot(SnapshotOptions opts) throws PiliException { String path = baseUrl + "/snapshot"; String json = gson.toJson(opts); try { String resp = cli.callWithJson(path, json); SnapshotRet ret = gson.fromJson(resp, SnapshotRet.class); return ret.fname; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
java
public String snapshot(SnapshotOptions opts) throws PiliException { String path = baseUrl + "/snapshot"; String json = gson.toJson(opts); try { String resp = cli.callWithJson(path, json); SnapshotRet ret = gson.fromJson(resp, SnapshotRet.class); return ret.fname; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
[ "public", "String", "snapshot", "(", "SnapshotOptions", "opts", ")", "throws", "PiliException", "{", "String", "path", "=", "baseUrl", "+", "\"/snapshot\"", ";", "String", "json", "=", "gson", ".", "toJson", "(", "opts", ")", ";", "try", "{", "String", "re...
snapshot the live stream @param opts @return @throws PiliException
[ "snapshot", "the", "live", "stream" ]
7abadbd2baaa389d226a6f9351d82e2e5a60fe32
https://github.com/pili-engineering/pili-sdk-java/blob/7abadbd2baaa389d226a6f9351d82e2e5a60fe32/src/main/java/com/qiniu/pili/Stream.java#L200-L212
train
pili-engineering/pili-sdk-java
src/main/java/com/qiniu/pili/Stream.java
Stream.updateConverts
public void updateConverts(String[] profiles) throws PiliException { String path = baseUrl + "/converts"; String json = gson.toJson(new ConvertsOptions(profiles)); try { cli.callWithJson(path, json); } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
java
public void updateConverts(String[] profiles) throws PiliException { String path = baseUrl + "/converts"; String json = gson.toJson(new ConvertsOptions(profiles)); try { cli.callWithJson(path, json); } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
[ "public", "void", "updateConverts", "(", "String", "[", "]", "profiles", ")", "throws", "PiliException", "{", "String", "path", "=", "baseUrl", "+", "\"/converts\"", ";", "String", "json", "=", "gson", ".", "toJson", "(", "new", "ConvertsOptions", "(", "prof...
update convert configs @param profiles @throws PiliException
[ "update", "convert", "configs" ]
7abadbd2baaa389d226a6f9351d82e2e5a60fe32
https://github.com/pili-engineering/pili-sdk-java/blob/7abadbd2baaa389d226a6f9351d82e2e5a60fe32/src/main/java/com/qiniu/pili/Stream.java#L220-L231
train
pili-engineering/pili-sdk-java
src/main/java/com/qiniu/pili/Stream.java
Stream.historyRecord
public Record[] historyRecord(long start, long end) throws PiliException { String path = appendQuery(baseUrl + "/historyrecord", start, end); try { String resp = cli.callWithGet(path); HistoryRet ret = gson.fromJson(resp, HistoryRet.class); return ret.items; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
java
public Record[] historyRecord(long start, long end) throws PiliException { String path = appendQuery(baseUrl + "/historyrecord", start, end); try { String resp = cli.callWithGet(path); HistoryRet ret = gson.fromJson(resp, HistoryRet.class); return ret.items; } catch (PiliException e) { throw e; } catch (Exception e) { throw new PiliException(e); } }
[ "public", "Record", "[", "]", "historyRecord", "(", "long", "start", ",", "long", "end", ")", "throws", "PiliException", "{", "String", "path", "=", "appendQuery", "(", "baseUrl", "+", "\"/historyrecord\"", ",", "start", ",", "end", ")", ";", "try", "{", ...
query the stream history @param start @param end @return @throws PiliException
[ "query", "the", "stream", "history" ]
7abadbd2baaa389d226a6f9351d82e2e5a60fe32
https://github.com/pili-engineering/pili-sdk-java/blob/7abadbd2baaa389d226a6f9351d82e2e5a60fe32/src/main/java/com/qiniu/pili/Stream.java#L241-L252
train
twilio/authy-java
src/main/java/com/authy/api/Instance.java
Instance.toXML
public String toXML() { Error error = getError(); if (error != null) { return error.toXML(); } StringWriter sw = new StringWriter(); String xml = ""; try { JAXBContext context = JAXBContext.newInstance(this.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(this, sw); xml = sw.toString(); } catch (Exception e) { e.printStackTrace(); } return xml; }
java
public String toXML() { Error error = getError(); if (error != null) { return error.toXML(); } StringWriter sw = new StringWriter(); String xml = ""; try { JAXBContext context = JAXBContext.newInstance(this.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(this, sw); xml = sw.toString(); } catch (Exception e) { e.printStackTrace(); } return xml; }
[ "public", "String", "toXML", "(", ")", "{", "Error", "error", "=", "getError", "(", ")", ";", "if", "(", "error", "!=", "null", ")", "{", "return", "error", ".", "toXML", "(", ")", ";", "}", "StringWriter", "sw", "=", "new", "StringWriter", "(", ")...
Map a Token instance to its XML representation. @return a String with the description of this object in XML.
[ "Map", "a", "Token", "instance", "to", "its", "XML", "representation", "." ]
55e3a5ff57a93b3eb36f5b59e8824e60af2b8b91
https://github.com/twilio/authy-java/blob/55e3a5ff57a93b3eb36f5b59e8824e60af2b8b91/src/main/java/com/authy/api/Instance.java#L73-L93
train
twilio/authy-java
src/main/java/com/authy/api/OneTouch.java
OneTouch.sendApprovalRequest
public OneTouchResponse sendApprovalRequest(ApprovalRequestParams approvalRequestParams) throws AuthyException {//Integer userId, String message, HashMap<String, Object> options, Integer secondsToExpire) throws OneTouchException { JSONObject params = new JSONObject(); params.put("message", approvalRequestParams.getMessage()); if (approvalRequestParams.getSecondsToExpire() != null) { params.put("seconds_to_expire", approvalRequestParams.getSecondsToExpire()); } if (approvalRequestParams.getDetails().size() > 0) { params.put("details", mapToJSONObject(approvalRequestParams.getDetails())); } if (approvalRequestParams.getHidden().size() > 0) { params.put("hidden_details", mapToJSONObject(approvalRequestParams.getHidden())); } if (!approvalRequestParams.getLogos().isEmpty()) { JSONArray jSONArray = new JSONArray(); for (Logo logo : approvalRequestParams.getLogos()) { logo.addToMap(jSONArray); } params.put("logos", jSONArray); } final Response response = this.post(APPROVAL_REQUEST_PRE + approvalRequestParams.getAuthyId() + APPROVAL_REQUEST_POS, new JSONBody(params)); OneTouchResponse oneTouchResponse = new OneTouchResponse(response.getStatus(), response.getBody()); if (!oneTouchResponse.isOk()) { oneTouchResponse.setError(errorFromJson(response.getBody())); } return oneTouchResponse; }
java
public OneTouchResponse sendApprovalRequest(ApprovalRequestParams approvalRequestParams) throws AuthyException {//Integer userId, String message, HashMap<String, Object> options, Integer secondsToExpire) throws OneTouchException { JSONObject params = new JSONObject(); params.put("message", approvalRequestParams.getMessage()); if (approvalRequestParams.getSecondsToExpire() != null) { params.put("seconds_to_expire", approvalRequestParams.getSecondsToExpire()); } if (approvalRequestParams.getDetails().size() > 0) { params.put("details", mapToJSONObject(approvalRequestParams.getDetails())); } if (approvalRequestParams.getHidden().size() > 0) { params.put("hidden_details", mapToJSONObject(approvalRequestParams.getHidden())); } if (!approvalRequestParams.getLogos().isEmpty()) { JSONArray jSONArray = new JSONArray(); for (Logo logo : approvalRequestParams.getLogos()) { logo.addToMap(jSONArray); } params.put("logos", jSONArray); } final Response response = this.post(APPROVAL_REQUEST_PRE + approvalRequestParams.getAuthyId() + APPROVAL_REQUEST_POS, new JSONBody(params)); OneTouchResponse oneTouchResponse = new OneTouchResponse(response.getStatus(), response.getBody()); if (!oneTouchResponse.isOk()) { oneTouchResponse.setError(errorFromJson(response.getBody())); } return oneTouchResponse; }
[ "public", "OneTouchResponse", "sendApprovalRequest", "(", "ApprovalRequestParams", "approvalRequestParams", ")", "throws", "AuthyException", "{", "//Integer userId, String message, HashMap<String, Object> options, Integer secondsToExpire) throws OneTouchException {", "JSONObject", "params", ...
Sends the OneTouch's approval request to the Authy servers and returns the OneTouchResponse that comes back. @param approvalRequestParams The bean wrapping the user's Authy approval request built using the ApprovalRequest.Builder @return The bean wrapping the response from Authy's service.
[ "Sends", "the", "OneTouch", "s", "approval", "request", "to", "the", "Authy", "servers", "and", "returns", "the", "OneTouchResponse", "that", "comes", "back", "." ]
55e3a5ff57a93b3eb36f5b59e8824e60af2b8b91
https://github.com/twilio/authy-java/blob/55e3a5ff57a93b3eb36f5b59e8824e60af2b8b91/src/main/java/com/authy/api/OneTouch.java#L40-L79
train
twilio/authy-java
src/main/java/com/authy/api/Users.java
Users.requestStatus
public UserStatus requestStatus(int userId) throws AuthyException { final Response response = this.get(String.format(USER_STATUS_PATH, userId), null); UserStatus userStatus = userStatusFromJson(response); return userStatus; }
java
public UserStatus requestStatus(int userId) throws AuthyException { final Response response = this.get(String.format(USER_STATUS_PATH, userId), null); UserStatus userStatus = userStatusFromJson(response); return userStatus; }
[ "public", "UserStatus", "requestStatus", "(", "int", "userId", ")", "throws", "AuthyException", "{", "final", "Response", "response", "=", "this", ".", "get", "(", "String", ".", "format", "(", "USER_STATUS_PATH", ",", "userId", ")", ",", "null", ")", ";", ...
Get user status. @return object containing user status
[ "Get", "user", "status", "." ]
55e3a5ff57a93b3eb36f5b59e8824e60af2b8b91
https://github.com/twilio/authy-java/blob/55e3a5ff57a93b3eb36f5b59e8824e60af2b8b91/src/main/java/com/authy/api/Users.java#L125-L129
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/terms/TransportTermsByQueryAction.java
TransportTermsByQueryAction.doExecute
@Override protected void doExecute(Task task, TermsByQueryRequest request, ActionListener<TermsByQueryResponse> listener) { request.nowInMillis(System.currentTimeMillis()); // set time to be used in scripts super.doExecute(task, request, listener); }
java
@Override protected void doExecute(Task task, TermsByQueryRequest request, ActionListener<TermsByQueryResponse> listener) { request.nowInMillis(System.currentTimeMillis()); // set time to be used in scripts super.doExecute(task, request, listener); }
[ "@", "Override", "protected", "void", "doExecute", "(", "Task", "task", ",", "TermsByQueryRequest", "request", ",", "ActionListener", "<", "TermsByQueryResponse", ">", "listener", ")", "{", "request", ".", "nowInMillis", "(", "System", ".", "currentTimeMillis", "(...
Executes the actions.
[ "Executes", "the", "actions", "." ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/terms/TransportTermsByQueryAction.java#L108-L112
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/terms/TransportTermsByQueryAction.java
TransportTermsByQueryAction.shards
@Override protected GroupShardsIterator shards(ClusterState clusterState, TermsByQueryRequest request, String[] concreteIndices) { Map<String, Set<String>> routingMap = indexNameExpressionResolver.resolveSearchRouting(clusterState, request.routing(), request.indices()); return clusterService.operationRouting().searchShards(clusterState, concreteIndices, routingMap, request.preference()); }
java
@Override protected GroupShardsIterator shards(ClusterState clusterState, TermsByQueryRequest request, String[] concreteIndices) { Map<String, Set<String>> routingMap = indexNameExpressionResolver.resolveSearchRouting(clusterState, request.routing(), request.indices()); return clusterService.operationRouting().searchShards(clusterState, concreteIndices, routingMap, request.preference()); }
[ "@", "Override", "protected", "GroupShardsIterator", "shards", "(", "ClusterState", "clusterState", ",", "TermsByQueryRequest", "request", ",", "String", "[", "]", "concreteIndices", ")", "{", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "routingMa...
The shards this request will execute against.
[ "The", "shards", "this", "request", "will", "execute", "against", "." ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/terms/TransportTermsByQueryAction.java#L134-L138
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/terms/TermsByQueryRequest.java
TermsByQueryRequest.validate
@Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); if (termsEncoding != null && termsEncoding.equals(TermsEncoding.BYTES)) { if (maxTermsPerShard == null) { validationException = ValidateActions.addValidationError("maxTermsPerShard not specified for terms encoding [bytes]", validationException); } } return validationException; }
java
@Override public ActionRequestValidationException validate() { ActionRequestValidationException validationException = super.validate(); if (termsEncoding != null && termsEncoding.equals(TermsEncoding.BYTES)) { if (maxTermsPerShard == null) { validationException = ValidateActions.addValidationError("maxTermsPerShard not specified for terms encoding [bytes]", validationException); } } return validationException; }
[ "@", "Override", "public", "ActionRequestValidationException", "validate", "(", ")", "{", "ActionRequestValidationException", "validationException", "=", "super", ".", "validate", "(", ")", ";", "if", "(", "termsEncoding", "!=", "null", "&&", "termsEncoding", ".", "...
Validates the request @return null if valid, exception otherwise
[ "Validates", "the", "request" ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/terms/TermsByQueryRequest.java#L93-L102
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/admin/version/GetIndicesVersionResponse.java
GetIndicesVersionResponse.getVersion
public long getVersion() { long version = 1; ArrayList<String> indices = new ArrayList<>(getIndices().keySet()); Collections.sort(indices); for (String index : indices) { version = 31 * version + getIndices().get(index); } return version; }
java
public long getVersion() { long version = 1; ArrayList<String> indices = new ArrayList<>(getIndices().keySet()); Collections.sort(indices); for (String index : indices) { version = 31 * version + getIndices().get(index); } return version; }
[ "public", "long", "getVersion", "(", ")", "{", "long", "version", "=", "1", ";", "ArrayList", "<", "String", ">", "indices", "=", "new", "ArrayList", "<>", "(", "getIndices", "(", ")", ".", "keySet", "(", ")", ")", ";", "Collections", ".", "sort", "(...
Returns the version for the set of indices.
[ "Returns", "the", "version", "for", "the", "set", "of", "indices", "." ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/admin/version/GetIndicesVersionResponse.java#L50-L60
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/admin/version/GetIndicesVersionResponse.java
GetIndicesVersionResponse.getIndices
public Map<String, Long> getIndices() { if (indicesVersions != null) { return indicesVersions; } Map<String, Long> indicesVersions = Maps.newHashMap(); Set<String> indices = Sets.newHashSet(); for (ShardIndexVersion shard : shards) { indices.add(shard.getShardRouting().getIndex()); } for (String index : indices) { List<ShardIndexVersion> shards = new ArrayList<>(); for (ShardIndexVersion shard : this.shards) { if (shard.getShardRouting().index().equals(index)) { shards.add(shard); } } indicesVersions.put(index, this.getIndexVersion(shards)); } this.indicesVersions = indicesVersions; return indicesVersions; }
java
public Map<String, Long> getIndices() { if (indicesVersions != null) { return indicesVersions; } Map<String, Long> indicesVersions = Maps.newHashMap(); Set<String> indices = Sets.newHashSet(); for (ShardIndexVersion shard : shards) { indices.add(shard.getShardRouting().getIndex()); } for (String index : indices) { List<ShardIndexVersion> shards = new ArrayList<>(); for (ShardIndexVersion shard : this.shards) { if (shard.getShardRouting().index().equals(index)) { shards.add(shard); } } indicesVersions.put(index, this.getIndexVersion(shards)); } this.indicesVersions = indicesVersions; return indicesVersions; }
[ "public", "Map", "<", "String", ",", "Long", ">", "getIndices", "(", ")", "{", "if", "(", "indicesVersions", "!=", "null", ")", "{", "return", "indicesVersions", ";", "}", "Map", "<", "String", ",", "Long", ">", "indicesVersions", "=", "Maps", ".", "ne...
Returns a map with the version of each index.
[ "Returns", "a", "map", "with", "the", "version", "of", "each", "index", "." ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/admin/version/GetIndicesVersionResponse.java#L65-L87
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/admin/version/GetIndicesVersionResponse.java
GetIndicesVersionResponse.getIndexVersion
private long getIndexVersion(List<ShardIndexVersion> shards) { long version = 1; // order shards per their id before computing the hash Collections.sort(shards, new Comparator<ShardIndexVersion>() { @Override public int compare(ShardIndexVersion o1, ShardIndexVersion o2) { return o1.getShardRouting().id() - o2.getShardRouting().id(); } }); // compute hash for (ShardIndexVersion shard : shards) { version = 31 * version + shard.getVersion(); } return version; }
java
private long getIndexVersion(List<ShardIndexVersion> shards) { long version = 1; // order shards per their id before computing the hash Collections.sort(shards, new Comparator<ShardIndexVersion>() { @Override public int compare(ShardIndexVersion o1, ShardIndexVersion o2) { return o1.getShardRouting().id() - o2.getShardRouting().id(); } }); // compute hash for (ShardIndexVersion shard : shards) { version = 31 * version + shard.getVersion(); } return version; }
[ "private", "long", "getIndexVersion", "(", "List", "<", "ShardIndexVersion", ">", "shards", ")", "{", "long", "version", "=", "1", ";", "// order shards per their id before computing the hash", "Collections", ".", "sort", "(", "shards", ",", "new", "Comparator", "<"...
Computes a unique hash based on the version of the shards.
[ "Computes", "a", "unique", "hash", "based", "on", "the", "version", "of", "the", "shards", "." ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/admin/version/GetIndicesVersionResponse.java#L92-L109
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/coordinate/pipeline/NodePipelineManager.java
NodePipelineManager.execute
public void execute(NodeTaskContext context) { NodeTaskReporter taskReporter = new NodeTaskReporter(this); taskQueue = new ArrayDeque<>(tasks); if (!taskQueue.isEmpty()) { NodeTask task = taskQueue.poll(); task.execute(context, taskReporter); } else { // if the queue is empty, reports that the pipeline execution was a success listener.onSuccess(); } }
java
public void execute(NodeTaskContext context) { NodeTaskReporter taskReporter = new NodeTaskReporter(this); taskQueue = new ArrayDeque<>(tasks); if (!taskQueue.isEmpty()) { NodeTask task = taskQueue.poll(); task.execute(context, taskReporter); } else { // if the queue is empty, reports that the pipeline execution was a success listener.onSuccess(); } }
[ "public", "void", "execute", "(", "NodeTaskContext", "context", ")", "{", "NodeTaskReporter", "taskReporter", "=", "new", "NodeTaskReporter", "(", "this", ")", ";", "taskQueue", "=", "new", "ArrayDeque", "<>", "(", "tasks", ")", ";", "if", "(", "!", "taskQue...
Starts the execution of the pipeline
[ "Starts", "the", "execution", "of", "the", "pipeline" ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/coordinate/pipeline/NodePipelineManager.java#L51-L61
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinCache.java
FilterJoinCache.put
public void put(final long cacheKey, final FilterJoinTerms terms) { logger.debug("{}: New cache entry {}", Thread.currentThread().getName(), cacheKey); this.cache.put(cacheKey, new CacheEntry(terms.getEncodedTerms(), terms.getSize(), terms.isPruned())); }
java
public void put(final long cacheKey, final FilterJoinTerms terms) { logger.debug("{}: New cache entry {}", Thread.currentThread().getName(), cacheKey); this.cache.put(cacheKey, new CacheEntry(terms.getEncodedTerms(), terms.getSize(), terms.isPruned())); }
[ "public", "void", "put", "(", "final", "long", "cacheKey", ",", "final", "FilterJoinTerms", "terms", ")", "{", "logger", ".", "debug", "(", "\"{}: New cache entry {}\"", ",", "Thread", ".", "currentThread", "(", ")", ".", "getName", "(", ")", ",", "cacheKey"...
Caches the provided list of encoded terms for the given filter join node.
[ "Caches", "the", "provided", "list", "of", "encoded", "terms", "for", "the", "given", "filter", "join", "node", "." ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinCache.java#L76-L79
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/terms/TermsByQueryAction.java
TermsByQueryAction.transportOptions
@Override public TransportRequestOptions transportOptions(Settings settings) { return TransportRequestOptions.builder() .withType(TransportRequestOptions.Type.REG) .build(); }
java
@Override public TransportRequestOptions transportOptions(Settings settings) { return TransportRequestOptions.builder() .withType(TransportRequestOptions.Type.REG) .build(); }
[ "@", "Override", "public", "TransportRequestOptions", "transportOptions", "(", "Settings", "settings", ")", "{", "return", "TransportRequestOptions", ".", "builder", "(", ")", ".", "withType", "(", "TransportRequestOptions", ".", "Type", ".", "REG", ")", ".", "bui...
Set transport options specific to a terms by query request. Enabling compression here does not really reduce data transfer, even increase it on the contrary. @param settings node settings @return the request options.
[ "Set", "transport", "options", "specific", "to", "a", "terms", "by", "query", "request", ".", "Enabling", "compression", "here", "does", "not", "really", "reduce", "data", "transfer", "even", "increase", "it", "on", "the", "contrary", "." ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/terms/TermsByQueryAction.java#L58-L63
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinVisitor.java
FilterJoinVisitor.await
private void await() { try { // Clean up all filter join leaf nodes that have been converted boolean nodeRemoved = this.removeConvertedNodes(root); // If some nodes were removed, it means that we converted in the previous iteration // at least one filter join into a field data terms query. We don't have to wait since // we might have new filter join leaf nodes. if (!nodeRemoved && root.hasChildren()) { logger.debug("Visitor thread block - blocking queue size: {}", blockingQueue.size()); this.blockingQueue.take(); // block until one async action is completed this.blockingQueue.offer(0); // add back the element to the queue, it will be removed after the node conversion logger.debug("Visitor thread unblock - blocking queue size: {}", blockingQueue.size()); } } catch (InterruptedException e) { logger.warn("Filter join visitor thread interrupted while waiting"); Thread.currentThread().interrupt(); } }
java
private void await() { try { // Clean up all filter join leaf nodes that have been converted boolean nodeRemoved = this.removeConvertedNodes(root); // If some nodes were removed, it means that we converted in the previous iteration // at least one filter join into a field data terms query. We don't have to wait since // we might have new filter join leaf nodes. if (!nodeRemoved && root.hasChildren()) { logger.debug("Visitor thread block - blocking queue size: {}", blockingQueue.size()); this.blockingQueue.take(); // block until one async action is completed this.blockingQueue.offer(0); // add back the element to the queue, it will be removed after the node conversion logger.debug("Visitor thread unblock - blocking queue size: {}", blockingQueue.size()); } } catch (InterruptedException e) { logger.warn("Filter join visitor thread interrupted while waiting"); Thread.currentThread().interrupt(); } }
[ "private", "void", "await", "(", ")", "{", "try", "{", "// Clean up all filter join leaf nodes that have been converted", "boolean", "nodeRemoved", "=", "this", ".", "removeConvertedNodes", "(", "root", ")", ";", "// If some nodes were removed, it means that we converted in the...
Await for the completion of an async action.
[ "Await", "for", "the", "completion", "of", "an", "async", "action", "." ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinVisitor.java#L119-L137
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinVisitor.java
FilterJoinVisitor.removeConvertedNodes
private boolean removeConvertedNodes(AbstractNode node) { boolean nodeRemoved = false; Iterator<AbstractNode> it = node.getChildren().iterator(); while (it.hasNext()) { FilterJoinNode child = (FilterJoinNode) it.next(); if (child.getState().equals(FilterJoinNode.State.CONVERTED)) { it.remove(); nodeRemoved |= true; } else { nodeRemoved |= this.removeConvertedNodes(child) ? true : false; } } return nodeRemoved; }
java
private boolean removeConvertedNodes(AbstractNode node) { boolean nodeRemoved = false; Iterator<AbstractNode> it = node.getChildren().iterator(); while (it.hasNext()) { FilterJoinNode child = (FilterJoinNode) it.next(); if (child.getState().equals(FilterJoinNode.State.CONVERTED)) { it.remove(); nodeRemoved |= true; } else { nodeRemoved |= this.removeConvertedNodes(child) ? true : false; } } return nodeRemoved; }
[ "private", "boolean", "removeConvertedNodes", "(", "AbstractNode", "node", ")", "{", "boolean", "nodeRemoved", "=", "false", ";", "Iterator", "<", "AbstractNode", ">", "it", "=", "node", ".", "getChildren", "(", ")", ".", "iterator", "(", ")", ";", "while", ...
Removes all the filter join leaf nodes that were converted. Returns true if at least one node has been removed.
[ "Removes", "all", "the", "filter", "join", "leaf", "nodes", "that", "were", "converted", ".", "Returns", "true", "if", "at", "least", "one", "node", "has", "been", "removed", "." ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinVisitor.java#L143-L157
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinVisitor.java
FilterJoinVisitor.executeAsyncOperation
protected void executeAsyncOperation(final FilterJoinNode node) { logger.debug("Executing async actions"); node.setState(FilterJoinNode.State.RUNNING); // set state before execution to avoid race conditions with listener NodePipelineManager pipeline = new NodePipelineManager(); pipeline.addListener(new NodePipelineListener() { @Override public void onSuccess() { node.setState(FilterJoinNode.State.COMPLETED); // set state before unblocking the queue to avoid race conditions FilterJoinVisitor.this.unblock(); } @Override public void onFailure(Throwable e) { node.setFailure(e); node.setState(FilterJoinNode.State.COMPLETED); // set state before unblocking the queue to avoid race conditions FilterJoinVisitor.this.unblock(); } }); // Adds the list of tasks to be executed pipeline.addTask(new IndicesVersionTask()); pipeline.addTask(new CacheLookupTask()); pipeline.addTask(new CardinalityEstimationTask()); pipeline.addTask(new TermsByQueryTask()); // Starts the execution of the pipeline pipeline.execute(new NodeTaskContext(client, node, this)); }
java
protected void executeAsyncOperation(final FilterJoinNode node) { logger.debug("Executing async actions"); node.setState(FilterJoinNode.State.RUNNING); // set state before execution to avoid race conditions with listener NodePipelineManager pipeline = new NodePipelineManager(); pipeline.addListener(new NodePipelineListener() { @Override public void onSuccess() { node.setState(FilterJoinNode.State.COMPLETED); // set state before unblocking the queue to avoid race conditions FilterJoinVisitor.this.unblock(); } @Override public void onFailure(Throwable e) { node.setFailure(e); node.setState(FilterJoinNode.State.COMPLETED); // set state before unblocking the queue to avoid race conditions FilterJoinVisitor.this.unblock(); } }); // Adds the list of tasks to be executed pipeline.addTask(new IndicesVersionTask()); pipeline.addTask(new CacheLookupTask()); pipeline.addTask(new CardinalityEstimationTask()); pipeline.addTask(new TermsByQueryTask()); // Starts the execution of the pipeline pipeline.execute(new NodeTaskContext(client, node, this)); }
[ "protected", "void", "executeAsyncOperation", "(", "final", "FilterJoinNode", "node", ")", "{", "logger", ".", "debug", "(", "\"Executing async actions\"", ")", ";", "node", ".", "setState", "(", "FilterJoinNode", ".", "State", ".", "RUNNING", ")", ";", "// set ...
Executes the pipeline of async actions to compute the terms for this node.
[ "Executes", "the", "pipeline", "of", "async", "actions", "to", "compute", "the", "terms", "for", "this", "node", "." ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinVisitor.java#L193-L223
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinVisitor.java
FilterJoinVisitor.checkForFailure
private void checkForFailure(FilterJoinNode node) { if (node.hasFailure()) { logger.error("Node processing failed: {}", node.getFailure()); throw new ElasticsearchException("Unexpected failure while processing a node", node.getFailure()); } }
java
private void checkForFailure(FilterJoinNode node) { if (node.hasFailure()) { logger.error("Node processing failed: {}", node.getFailure()); throw new ElasticsearchException("Unexpected failure while processing a node", node.getFailure()); } }
[ "private", "void", "checkForFailure", "(", "FilterJoinNode", "node", ")", "{", "if", "(", "node", ".", "hasFailure", "(", ")", ")", "{", "logger", ".", "error", "(", "\"Node processing failed: {}\"", ",", "node", ".", "getFailure", "(", ")", ")", ";", "thr...
Checks for an action failure
[ "Checks", "for", "an", "action", "failure" ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinVisitor.java#L258-L263
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinVisitor.java
FilterJoinVisitor.convertToTermsQuery
private void convertToTermsQuery(FilterJoinNode node) { Map<String, Object> parent = node.getParentSourceMap(); FilterJoinTerms terms = node.getTerms(); BytesRef bytes = terms.getEncodedTerms(); // Remove the filter join from the parent parent.remove(FilterJoinBuilder.NAME); // Create the nested object for the parameters of the field data terms query Map<String, Object> queryParams = new HashMap<>(); queryParams.put("value", bytes.bytes); // use the hash of the filter join source map as cache key - see #170 queryParams.put("_cache_key", node.getCacheId()); // Create the nested object for the field Map<String, Object> field = new HashMap<>(); field.put(node.getField(), queryParams); // Create the nested object for the field data terms query Map<String, Object> termsQuery = new HashMap<>(); // If bytes terms encoding is used, we switch to the terms enum based terms query if (node.getTermsEncoding().equals(TermsByQueryRequest.TermsEncoding.BYTES)) { termsQuery.put(TermsEnumTermsQueryParser.NAME, field); } else { termsQuery.put(FieldDataTermsQueryParser.NAME, field); } // Create the object for the constant score query Map<String, Object> constantScoreQueryParams = new HashMap<>(); constantScoreQueryParams.put("filter", termsQuery); // Add the constant score query to the parent parent.put(ConstantScoreQueryParser.NAME, constantScoreQueryParams); node.setState(FilterJoinNode.State.CONVERTED); this.blockingQueue.poll(); }
java
private void convertToTermsQuery(FilterJoinNode node) { Map<String, Object> parent = node.getParentSourceMap(); FilterJoinTerms terms = node.getTerms(); BytesRef bytes = terms.getEncodedTerms(); // Remove the filter join from the parent parent.remove(FilterJoinBuilder.NAME); // Create the nested object for the parameters of the field data terms query Map<String, Object> queryParams = new HashMap<>(); queryParams.put("value", bytes.bytes); // use the hash of the filter join source map as cache key - see #170 queryParams.put("_cache_key", node.getCacheId()); // Create the nested object for the field Map<String, Object> field = new HashMap<>(); field.put(node.getField(), queryParams); // Create the nested object for the field data terms query Map<String, Object> termsQuery = new HashMap<>(); // If bytes terms encoding is used, we switch to the terms enum based terms query if (node.getTermsEncoding().equals(TermsByQueryRequest.TermsEncoding.BYTES)) { termsQuery.put(TermsEnumTermsQueryParser.NAME, field); } else { termsQuery.put(FieldDataTermsQueryParser.NAME, field); } // Create the object for the constant score query Map<String, Object> constantScoreQueryParams = new HashMap<>(); constantScoreQueryParams.put("filter", termsQuery); // Add the constant score query to the parent parent.put(ConstantScoreQueryParser.NAME, constantScoreQueryParams); node.setState(FilterJoinNode.State.CONVERTED); this.blockingQueue.poll(); }
[ "private", "void", "convertToTermsQuery", "(", "FilterJoinNode", "node", ")", "{", "Map", "<", "String", ",", "Object", ">", "parent", "=", "node", ".", "getParentSourceMap", "(", ")", ";", "FilterJoinTerms", "terms", "=", "node", ".", "getTerms", "(", ")", ...
Converts a filter join into a terms query.
[ "Converts", "a", "filter", "join", "into", "a", "terms", "query", "." ]
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/action/coordinate/execution/FilterJoinVisitor.java#L268-L304
train
sirensolutions/siren-join
src/main/java/solutions/siren/join/index/query/FieldDataTermsQuery.java
FieldDataTermsQuery.getTermsSet
protected synchronized NumericTermsSet getTermsSet() { if (encodedTerms != null) { // late decoding of the encoded terms long start = System.nanoTime(); termsSet = (NumericTermsSet) TermsSet.readFrom(new BytesRef(encodedTerms)); logger.debug("{}: Deserialized {} terms - took {} ms", new Object[] { Thread.currentThread().getName(), termsSet.size(), (System.nanoTime() - start) / 1000000 }); encodedTerms = null; // release reference to the byte array to be able to reclaim memory } return termsSet; }
java
protected synchronized NumericTermsSet getTermsSet() { if (encodedTerms != null) { // late decoding of the encoded terms long start = System.nanoTime(); termsSet = (NumericTermsSet) TermsSet.readFrom(new BytesRef(encodedTerms)); logger.debug("{}: Deserialized {} terms - took {} ms", new Object[] { Thread.currentThread().getName(), termsSet.size(), (System.nanoTime() - start) / 1000000 }); encodedTerms = null; // release reference to the byte array to be able to reclaim memory } return termsSet; }
[ "protected", "synchronized", "NumericTermsSet", "getTermsSet", "(", ")", "{", "if", "(", "encodedTerms", "!=", "null", ")", "{", "// late decoding of the encoded terms", "long", "start", "=", "System", ".", "nanoTime", "(", ")", ";", "termsSet", "=", "(", "Numer...
Returns the set of terms. This method will perform a late-decoding of the encoded terms, and will release the byte array. This method needs to be synchronized as each segment thread will call it concurrently.
[ "Returns", "the", "set", "of", "terms", ".", "This", "method", "will", "perform", "a", "late", "-", "decoding", "of", "the", "encoded", "terms", "and", "will", "release", "the", "byte", "array", ".", "This", "method", "needs", "to", "be", "synchronized", ...
cba1111b209ce6f72ab7750d5488a573a6c77fe5
https://github.com/sirensolutions/siren-join/blob/cba1111b209ce6f72ab7750d5488a573a6c77fe5/src/main/java/solutions/siren/join/index/query/FieldDataTermsQuery.java#L137-L145
train
jruby/joni
src/org/joni/StackMachine.java
StackMachine.nullCheck
protected final int nullCheck(int id, int s) { int k = stk; while (true) { k--; StackEntry e = stack[k]; if (e.type == NULL_CHECK_START) { if (e.getNullCheckNum() == id) { return e.getNullCheckPStr() == s ? 1 : 0; } } } }
java
protected final int nullCheck(int id, int s) { int k = stk; while (true) { k--; StackEntry e = stack[k]; if (e.type == NULL_CHECK_START) { if (e.getNullCheckNum() == id) { return e.getNullCheckPStr() == s ? 1 : 0; } } } }
[ "protected", "final", "int", "nullCheck", "(", "int", "id", ",", "int", "s", ")", "{", "int", "k", "=", "stk", ";", "while", "(", "true", ")", "{", "k", "--", ";", "StackEntry", "e", "=", "stack", "[", "k", "]", ";", "if", "(", "e", ".", "typ...
int for consistency with other null check routines
[ "int", "for", "consistency", "with", "other", "null", "check", "routines" ]
182164fb64a9588ee5d866afa891a5edf597499b
https://github.com/jruby/joni/blob/182164fb64a9588ee5d866afa891a5edf597499b/src/org/joni/StackMachine.java#L442-L454
train
jruby/joni
src/org/joni/Lexer.java
Lexer.fetchNameForNoNamedGroup
private final int fetchNameForNoNamedGroup(int startCode, boolean ref) { int src = p; value = 0; int sign = 1; int endCode = nameEndCodePoint(startCode); int pnumHead = p; int nameEnd = stop; String err = null; if (!left()) { newValueException(EMPTY_GROUP_NAME); } else { fetch(); if (c == endCode) newValueException(EMPTY_GROUP_NAME); if (enc.isDigit(c)) { } else if (c == '-') { sign = -1; pnumHead = p; } else { err = INVALID_CHAR_IN_GROUP_NAME; } } while(left()) { nameEnd = p; fetch(); if (c == endCode || c == ')') break; if (!enc.isDigit(c)) err = INVALID_CHAR_IN_GROUP_NAME; } if (err == null && c != endCode) { err = INVALID_GROUP_NAME; nameEnd = stop; } if (err == null) { mark(); p = pnumHead; int backNum = scanUnsignedNumber(); restore(); if (backNum < 0) { newValueException(TOO_BIG_NUMBER); } else if (backNum == 0){ newValueException(INVALID_GROUP_NAME, src, nameEnd); } backNum *= sign; value = nameEnd; return backNum; } else { newValueException(err, src, nameEnd); return 0; // not reached } }
java
private final int fetchNameForNoNamedGroup(int startCode, boolean ref) { int src = p; value = 0; int sign = 1; int endCode = nameEndCodePoint(startCode); int pnumHead = p; int nameEnd = stop; String err = null; if (!left()) { newValueException(EMPTY_GROUP_NAME); } else { fetch(); if (c == endCode) newValueException(EMPTY_GROUP_NAME); if (enc.isDigit(c)) { } else if (c == '-') { sign = -1; pnumHead = p; } else { err = INVALID_CHAR_IN_GROUP_NAME; } } while(left()) { nameEnd = p; fetch(); if (c == endCode || c == ')') break; if (!enc.isDigit(c)) err = INVALID_CHAR_IN_GROUP_NAME; } if (err == null && c != endCode) { err = INVALID_GROUP_NAME; nameEnd = stop; } if (err == null) { mark(); p = pnumHead; int backNum = scanUnsignedNumber(); restore(); if (backNum < 0) { newValueException(TOO_BIG_NUMBER); } else if (backNum == 0){ newValueException(INVALID_GROUP_NAME, src, nameEnd); } backNum *= sign; value = nameEnd; return backNum; } else { newValueException(err, src, nameEnd); return 0; // not reached } }
[ "private", "final", "int", "fetchNameForNoNamedGroup", "(", "int", "startCode", ",", "boolean", "ref", ")", "{", "int", "src", "=", "p", ";", "value", "=", "0", ";", "int", "sign", "=", "1", ";", "int", "endCode", "=", "nameEndCodePoint", "(", "startCode...
make it return nameEnd!
[ "make", "it", "return", "nameEnd!" ]
182164fb64a9588ee5d866afa891a5edf597499b
https://github.com/jruby/joni/blob/182164fb64a9588ee5d866afa891a5edf597499b/src/org/joni/Lexer.java#L422-L478
train
ZuInnoTe/hadoopcryptoledger
hiveudf/src/main/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumUDFUtil.java
EthereumUDFUtil.getEthereumTransactionFromObject
public EthereumTransaction getEthereumTransactionFromObject(Object row) { EthereumTransaction result=null; if (row instanceof HiveEthereumTransaction) { // this is the case if you use the EthereumBlockSerde result=EthereumUDFUtil.convertToEthereumTransaction((HiveEthereumTransaction) row); } else { // this is the case if you have imported the EthereumTransaction in any other Hive supported format, such as ORC or Parquet StructField nonceSF=soi.getStructFieldRef("nonce"); StructField valueSF=soi.getStructFieldRef("valueRaw"); StructField receiveAddressSF=soi.getStructFieldRef("receiveAddress"); StructField gasPriceSF=soi.getStructFieldRef("gasPriceRaw"); StructField gasLimitSF=soi.getStructFieldRef("gasLimitRaw"); StructField dataSF=soi.getStructFieldRef("data"); StructField sigVSF=soi.getStructFieldRef("sig_v"); StructField sigRSF=soi.getStructFieldRef("sig_r"); StructField sigSSF=soi.getStructFieldRef("sig_s"); boolean baseNull = (nonceSF==null) || (valueSF==null)|| (receiveAddressSF==null); boolean gasDataNull = (gasPriceSF==null) || (gasLimitSF==null)|| (dataSF==null); boolean sigNull = (sigVSF==null) || (sigRSF==null)|| (sigSSF==null); if (baseNull || gasDataNull || sigNull) { LOG.error("Structure does not correspond to EthereumTransaction. You need the fields nonce, valueRaw, reciveAddress, gasPriceRaw, gasLimitRaw, data, sig_v, sig_r, sig_s"); return null; } byte[] nonce = (byte[]) soi.getStructFieldData(row,nonceSF); byte[] valueRaw = (byte[]) soi.getStructFieldData(row,valueSF); byte[] receiveAddress = (byte[]) soi.getStructFieldData(row,receiveAddressSF); byte[] gasPriceRaw =(byte[]) soi.getStructFieldData(row,gasPriceSF); byte[] gasLimitRaw = (byte[]) soi.getStructFieldData(row,gasLimitSF); byte[] data = (byte[]) soi.getStructFieldData(row,dataSF); byte[] sig_v = (byte[]) soi.getStructFieldData(row,sigVSF); byte[] sig_r = (byte[]) soi.getStructFieldData(row,sigRSF); byte[] sig_s = (byte[]) soi.getStructFieldData(row,sigSSF); result=new EthereumTransaction(); result.setNonce(nonce); result.setValueRaw(valueRaw); result.setReceiveAddress(receiveAddress); result.setGasPriceRaw(gasPriceRaw); result.setGasLimitRaw(gasLimitRaw); result.setData(data); result.setSig_v(sig_v); result.setSig_r(sig_r); result.setSig_s(sig_s); } return result; }
java
public EthereumTransaction getEthereumTransactionFromObject(Object row) { EthereumTransaction result=null; if (row instanceof HiveEthereumTransaction) { // this is the case if you use the EthereumBlockSerde result=EthereumUDFUtil.convertToEthereumTransaction((HiveEthereumTransaction) row); } else { // this is the case if you have imported the EthereumTransaction in any other Hive supported format, such as ORC or Parquet StructField nonceSF=soi.getStructFieldRef("nonce"); StructField valueSF=soi.getStructFieldRef("valueRaw"); StructField receiveAddressSF=soi.getStructFieldRef("receiveAddress"); StructField gasPriceSF=soi.getStructFieldRef("gasPriceRaw"); StructField gasLimitSF=soi.getStructFieldRef("gasLimitRaw"); StructField dataSF=soi.getStructFieldRef("data"); StructField sigVSF=soi.getStructFieldRef("sig_v"); StructField sigRSF=soi.getStructFieldRef("sig_r"); StructField sigSSF=soi.getStructFieldRef("sig_s"); boolean baseNull = (nonceSF==null) || (valueSF==null)|| (receiveAddressSF==null); boolean gasDataNull = (gasPriceSF==null) || (gasLimitSF==null)|| (dataSF==null); boolean sigNull = (sigVSF==null) || (sigRSF==null)|| (sigSSF==null); if (baseNull || gasDataNull || sigNull) { LOG.error("Structure does not correspond to EthereumTransaction. You need the fields nonce, valueRaw, reciveAddress, gasPriceRaw, gasLimitRaw, data, sig_v, sig_r, sig_s"); return null; } byte[] nonce = (byte[]) soi.getStructFieldData(row,nonceSF); byte[] valueRaw = (byte[]) soi.getStructFieldData(row,valueSF); byte[] receiveAddress = (byte[]) soi.getStructFieldData(row,receiveAddressSF); byte[] gasPriceRaw =(byte[]) soi.getStructFieldData(row,gasPriceSF); byte[] gasLimitRaw = (byte[]) soi.getStructFieldData(row,gasLimitSF); byte[] data = (byte[]) soi.getStructFieldData(row,dataSF); byte[] sig_v = (byte[]) soi.getStructFieldData(row,sigVSF); byte[] sig_r = (byte[]) soi.getStructFieldData(row,sigRSF); byte[] sig_s = (byte[]) soi.getStructFieldData(row,sigSSF); result=new EthereumTransaction(); result.setNonce(nonce); result.setValueRaw(valueRaw); result.setReceiveAddress(receiveAddress); result.setGasPriceRaw(gasPriceRaw); result.setGasLimitRaw(gasLimitRaw); result.setData(data); result.setSig_v(sig_v); result.setSig_r(sig_r); result.setSig_s(sig_s); } return result; }
[ "public", "EthereumTransaction", "getEthereumTransactionFromObject", "(", "Object", "row", ")", "{", "EthereumTransaction", "result", "=", "null", ";", "if", "(", "row", "instanceof", "HiveEthereumTransaction", ")", "{", "// this is the case if you use the EthereumBlockSerde"...
Create an object of type EthereumTransaction from any HiveTable @param row Object @return EthereumTransaction corresponding to object
[ "Create", "an", "object", "of", "type", "EthereumTransaction", "from", "any", "HiveTable" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/hiveudf/src/main/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumUDFUtil.java#L51-L93
train
ZuInnoTe/hadoopcryptoledger
hiveudf/src/main/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumUDFUtil.java
EthereumUDFUtil.convertToEthereumTransaction
public static EthereumTransaction convertToEthereumTransaction(HiveEthereumTransaction transaction) { EthereumTransaction result = new EthereumTransaction(); // note we set only the raw values, the other ones can be automatically dervied by the EthereumTransaction class if needed. This avoids conversion issues for large numbers result.setNonce(transaction.getNonce()); result.setValueRaw(transaction.getValueRaw()); result.setReceiveAddress(transaction.getReceiveAddress()); result.setGasPriceRaw(transaction.getGasPriceRaw()); result.setGasLimitRaw(transaction.getGasLimitRaw()); result.setData(transaction.getData()); result.setSig_v(transaction.getSig_v()); result.setSig_r(transaction.getSig_r()); result.setSig_s(transaction.getSig_s()); return result; }
java
public static EthereumTransaction convertToEthereumTransaction(HiveEthereumTransaction transaction) { EthereumTransaction result = new EthereumTransaction(); // note we set only the raw values, the other ones can be automatically dervied by the EthereumTransaction class if needed. This avoids conversion issues for large numbers result.setNonce(transaction.getNonce()); result.setValueRaw(transaction.getValueRaw()); result.setReceiveAddress(transaction.getReceiveAddress()); result.setGasPriceRaw(transaction.getGasPriceRaw()); result.setGasLimitRaw(transaction.getGasLimitRaw()); result.setData(transaction.getData()); result.setSig_v(transaction.getSig_v()); result.setSig_r(transaction.getSig_r()); result.setSig_s(transaction.getSig_s()); return result; }
[ "public", "static", "EthereumTransaction", "convertToEthereumTransaction", "(", "HiveEthereumTransaction", "transaction", ")", "{", "EthereumTransaction", "result", "=", "new", "EthereumTransaction", "(", ")", ";", "// note we set only the raw values, the other ones can be automati...
Convert HiveEthereumTransaction to Ethereum Transaction @param transaction in HiveEthereumTransaction format @return transaction in EthereumTransactionFormat
[ "Convert", "HiveEthereumTransaction", "to", "Ethereum", "Transaction" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/hiveudf/src/main/java/org/zuinnote/hadoop/ethereum/hive/udf/EthereumUDFUtil.java#L102-L115
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinUtil.java
BitcoinUtil.getSize
public static long getSize(byte[] byteSize) { if (byteSize.length!=4) { return 0; } ByteBuffer converterBuffer = ByteBuffer.wrap(byteSize); converterBuffer.order(ByteOrder.LITTLE_ENDIAN); return convertSignedIntToUnsigned(converterBuffer.getInt()); }
java
public static long getSize(byte[] byteSize) { if (byteSize.length!=4) { return 0; } ByteBuffer converterBuffer = ByteBuffer.wrap(byteSize); converterBuffer.order(ByteOrder.LITTLE_ENDIAN); return convertSignedIntToUnsigned(converterBuffer.getInt()); }
[ "public", "static", "long", "getSize", "(", "byte", "[", "]", "byteSize", ")", "{", "if", "(", "byteSize", ".", "length", "!=", "4", ")", "{", "return", "0", ";", "}", "ByteBuffer", "converterBuffer", "=", "ByteBuffer", ".", "wrap", "(", "byteSize", ")...
Reads a size from a reversed byte order, such as block size in the block header @param byteSize byte array with a length of exactly 4 @return size, returns 0 in case of invalid block size
[ "Reads", "a", "size", "from", "a", "reversed", "byte", "order", "such", "as", "block", "size", "in", "the", "block", "header" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinUtil.java#L258-L265
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinUtil.java
BitcoinUtil.reverseByteArray
public static byte[] reverseByteArray(byte[] inputByteArray) { byte[] result=new byte[inputByteArray.length]; for (int i=inputByteArray.length-1;i>=0;i--) { result[result.length-1-i]=inputByteArray[i]; } return result; }
java
public static byte[] reverseByteArray(byte[] inputByteArray) { byte[] result=new byte[inputByteArray.length]; for (int i=inputByteArray.length-1;i>=0;i--) { result[result.length-1-i]=inputByteArray[i]; } return result; }
[ "public", "static", "byte", "[", "]", "reverseByteArray", "(", "byte", "[", "]", "inputByteArray", ")", "{", "byte", "[", "]", "result", "=", "new", "byte", "[", "inputByteArray", ".", "length", "]", ";", "for", "(", "int", "i", "=", "inputByteArray", ...
Reverses the order of the byte array @param inputByteArray array to be reversed @return inputByteArray in reversed order
[ "Reverses", "the", "order", "of", "the", "byte", "array" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinUtil.java#L276-L282
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinUtil.java
BitcoinUtil.compareMagics
public static boolean compareMagics (byte[] magic1,byte[] magic2) { if (magic1.length!=magic2.length) { return false; } for (int i=0;i<magic1.length;i++) { if (magic1[i]!=magic2[i]) { return false; } } return true; }
java
public static boolean compareMagics (byte[] magic1,byte[] magic2) { if (magic1.length!=magic2.length) { return false; } for (int i=0;i<magic1.length;i++) { if (magic1[i]!=magic2[i]) { return false; } } return true; }
[ "public", "static", "boolean", "compareMagics", "(", "byte", "[", "]", "magic1", ",", "byte", "[", "]", "magic2", ")", "{", "if", "(", "magic1", ".", "length", "!=", "magic2", ".", "length", ")", "{", "return", "false", ";", "}", "for", "(", "int", ...
Compares two Bitcoin magics @param magic1 first magic @param magic2 second magics @return false, if do not match, true if match
[ "Compares", "two", "Bitcoin", "magics" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinUtil.java#L335-L346
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinUtil.java
BitcoinUtil.getTransactionHash
public static byte[] getTransactionHash(BitcoinTransaction transaction) throws IOException{ // convert transaction to byte array ByteArrayOutputStream transactionBAOS = new ByteArrayOutputStream(); byte[] version = reverseByteArray(convertIntToByteArray(transaction.getVersion())); transactionBAOS.write(version); byte[] inCounter = transaction.getInCounter(); transactionBAOS.write(inCounter); for (int i=0;i<transaction.getListOfInputs().size();i++) { transactionBAOS.write(transaction.getListOfInputs().get(i).getPrevTransactionHash()); transactionBAOS.write(reverseByteArray(convertIntToByteArray((int)(transaction.getListOfInputs().get(i).getPreviousTxOutIndex())))); transactionBAOS.write(transaction.getListOfInputs().get(i).getTxInScriptLength()); transactionBAOS.write(transaction.getListOfInputs().get(i).getTxInScript()); transactionBAOS.write(reverseByteArray(convertIntToByteArray((int)(transaction.getListOfInputs().get(i).getSeqNo())))); } byte[] outCounter = transaction.getOutCounter(); transactionBAOS.write(outCounter); for (int j=0;j<transaction.getListOfOutputs().size();j++) { transactionBAOS.write(convertBigIntegerToByteArray(transaction.getListOfOutputs().get(j).getValue(),8)); transactionBAOS.write(transaction.getListOfOutputs().get(j).getTxOutScriptLength()); transactionBAOS.write(transaction.getListOfOutputs().get(j).getTxOutScript()); } byte[] lockTime=reverseByteArray(convertIntToByteArray(transaction.getLockTime())); transactionBAOS.write(lockTime); byte[] transactionByteArray= transactionBAOS.toByteArray(); byte[] firstRoundHash; byte[] secondRoundHash; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); firstRoundHash = digest.digest(transactionByteArray); secondRoundHash = digest.digest(firstRoundHash); } catch (NoSuchAlgorithmException nsae) { LOG.error(nsae); return new byte[0]; } return secondRoundHash; }
java
public static byte[] getTransactionHash(BitcoinTransaction transaction) throws IOException{ // convert transaction to byte array ByteArrayOutputStream transactionBAOS = new ByteArrayOutputStream(); byte[] version = reverseByteArray(convertIntToByteArray(transaction.getVersion())); transactionBAOS.write(version); byte[] inCounter = transaction.getInCounter(); transactionBAOS.write(inCounter); for (int i=0;i<transaction.getListOfInputs().size();i++) { transactionBAOS.write(transaction.getListOfInputs().get(i).getPrevTransactionHash()); transactionBAOS.write(reverseByteArray(convertIntToByteArray((int)(transaction.getListOfInputs().get(i).getPreviousTxOutIndex())))); transactionBAOS.write(transaction.getListOfInputs().get(i).getTxInScriptLength()); transactionBAOS.write(transaction.getListOfInputs().get(i).getTxInScript()); transactionBAOS.write(reverseByteArray(convertIntToByteArray((int)(transaction.getListOfInputs().get(i).getSeqNo())))); } byte[] outCounter = transaction.getOutCounter(); transactionBAOS.write(outCounter); for (int j=0;j<transaction.getListOfOutputs().size();j++) { transactionBAOS.write(convertBigIntegerToByteArray(transaction.getListOfOutputs().get(j).getValue(),8)); transactionBAOS.write(transaction.getListOfOutputs().get(j).getTxOutScriptLength()); transactionBAOS.write(transaction.getListOfOutputs().get(j).getTxOutScript()); } byte[] lockTime=reverseByteArray(convertIntToByteArray(transaction.getLockTime())); transactionBAOS.write(lockTime); byte[] transactionByteArray= transactionBAOS.toByteArray(); byte[] firstRoundHash; byte[] secondRoundHash; try { MessageDigest digest = MessageDigest.getInstance("SHA-256"); firstRoundHash = digest.digest(transactionByteArray); secondRoundHash = digest.digest(firstRoundHash); } catch (NoSuchAlgorithmException nsae) { LOG.error(nsae); return new byte[0]; } return secondRoundHash; }
[ "public", "static", "byte", "[", "]", "getTransactionHash", "(", "BitcoinTransaction", "transaction", ")", "throws", "IOException", "{", "// convert transaction to byte array", "ByteArrayOutputStream", "transactionBAOS", "=", "new", "ByteArrayOutputStream", "(", ")", ";", ...
Calculates the double SHA256-Hash of a transaction in little endian format. This could be used for certain analysis scenario where one want to investigate the referenced transaction used as an input for a Transaction. Furthermore, it can be used as a unique identifier of the transaction It corresponds to the Bitcoin specification of txid (https://bitcoincore.org/en/segwit_wallet_dev/) @param transaction The BitcoinTransaction of which we want to calculate the hash @return byte array containing the hash of the transaction. Note: This one can be compared to a prevTransactionHash. However, if you want to search for it in popular blockchain explorers then you need to apply the function BitcoinUtil.reverseByteArray to it! @throws java.io.IOException in case of errors reading from the InputStream
[ "Calculates", "the", "double", "SHA256", "-", "Hash", "of", "a", "transaction", "in", "little", "endian", "format", ".", "This", "could", "be", "used", "for", "certain", "analysis", "scenario", "where", "one", "want", "to", "investigate", "the", "referenced", ...
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinUtil.java#L363-L399
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java
EthereumUtil.rlpDecodeNextItem
public static RLPObject rlpDecodeNextItem(ByteBuffer bb) { // detect object type RLPObject result=null; int objType = detectRLPObjectType(bb); switch (objType) { case EthereumUtil.RLP_OBJECTTYPE_ELEMENT: result=EthereumUtil.decodeRLPElement(bb); break; case EthereumUtil.RLP_OBJECTTYPE_LIST: result=EthereumUtil.decodeRLPList(bb); break; default: LOG.error("Unknown object type"); } return result; }
java
public static RLPObject rlpDecodeNextItem(ByteBuffer bb) { // detect object type RLPObject result=null; int objType = detectRLPObjectType(bb); switch (objType) { case EthereumUtil.RLP_OBJECTTYPE_ELEMENT: result=EthereumUtil.decodeRLPElement(bb); break; case EthereumUtil.RLP_OBJECTTYPE_LIST: result=EthereumUtil.decodeRLPList(bb); break; default: LOG.error("Unknown object type"); } return result; }
[ "public", "static", "RLPObject", "rlpDecodeNextItem", "(", "ByteBuffer", "bb", ")", "{", "// detect object type", "RLPObject", "result", "=", "null", ";", "int", "objType", "=", "detectRLPObjectType", "(", "bb", ")", ";", "switch", "(", "objType", ")", "{", "c...
Read RLP data from a Byte Buffer. @param bb ByteBuffer from which to read the RLP data @return RLPObject (e.g. RLPElement or RLPList) containing RLP data
[ "Read", "RLP", "data", "from", "a", "Byte", "Buffer", "." ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java#L76-L90
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java
EthereumUtil.detectRLPObjectType
public static int detectRLPObjectType(ByteBuffer bb) { bb.mark(); byte detector = bb.get(); int unsignedDetector=detector & 0xFF; int result = EthereumUtil.RLP_OBJECTTYPE_INVALID; if (unsignedDetector<=0x7f) { result=EthereumUtil.RLP_OBJECTTYPE_ELEMENT; } else if ((unsignedDetector>=0x80) && (unsignedDetector<=0xb7)) { result=EthereumUtil.RLP_OBJECTTYPE_ELEMENT; } else if ((unsignedDetector>=0xb8) && (unsignedDetector<=0xbf)) { result=EthereumUtil.RLP_OBJECTTYPE_ELEMENT; } else if ((unsignedDetector>=0xc0) && (unsignedDetector<=0xf7)) { result=EthereumUtil.RLP_OBJECTTYPE_LIST; } else if ((unsignedDetector>=0xf8) && (unsignedDetector<=0xff)) { result=EthereumUtil.RLP_OBJECTTYPE_LIST; } else { result=EthereumUtil.RLP_OBJECTTYPE_INVALID; LOG.error("Invalid RLP object type. Internal error or not RLP Data"); } bb.reset(); return result; }
java
public static int detectRLPObjectType(ByteBuffer bb) { bb.mark(); byte detector = bb.get(); int unsignedDetector=detector & 0xFF; int result = EthereumUtil.RLP_OBJECTTYPE_INVALID; if (unsignedDetector<=0x7f) { result=EthereumUtil.RLP_OBJECTTYPE_ELEMENT; } else if ((unsignedDetector>=0x80) && (unsignedDetector<=0xb7)) { result=EthereumUtil.RLP_OBJECTTYPE_ELEMENT; } else if ((unsignedDetector>=0xb8) && (unsignedDetector<=0xbf)) { result=EthereumUtil.RLP_OBJECTTYPE_ELEMENT; } else if ((unsignedDetector>=0xc0) && (unsignedDetector<=0xf7)) { result=EthereumUtil.RLP_OBJECTTYPE_LIST; } else if ((unsignedDetector>=0xf8) && (unsignedDetector<=0xff)) { result=EthereumUtil.RLP_OBJECTTYPE_LIST; } else { result=EthereumUtil.RLP_OBJECTTYPE_INVALID; LOG.error("Invalid RLP object type. Internal error or not RLP Data"); } bb.reset(); return result; }
[ "public", "static", "int", "detectRLPObjectType", "(", "ByteBuffer", "bb", ")", "{", "bb", ".", "mark", "(", ")", ";", "byte", "detector", "=", "bb", ".", "get", "(", ")", ";", "int", "unsignedDetector", "=", "detector", "&", "0xFF", ";", "int", "resul...
Detects the object type of an RLP encoded object. Note that it does not modify the read position in the ByteBuffer. @param bb ByteBuffer that contains RLP encoded object @return object type: EthereumUtil.RLP_OBJECTTYPE_ELEMENT or EthereumUtil.RLP_OBJECTTYPE_LIST or EthereumUtil.RLP_OBJECTTYPE_INVALID
[ "Detects", "the", "object", "type", "of", "an", "RLP", "encoded", "object", ".", "Note", "that", "it", "does", "not", "modify", "the", "read", "position", "in", "the", "ByteBuffer", "." ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java#L99-L126
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java
EthereumUtil.calculateChainId
public static Long calculateChainId(EthereumTransaction eTrans) { Long result=null; long rawResult=EthereumUtil.convertVarNumberToLong(new RLPElement(new byte[0],eTrans.getSig_v())); if (!((rawResult == EthereumUtil.LOWER_REAL_V) || (rawResult== (LOWER_REAL_V+1)))) { result = (rawResult-EthereumUtil.CHAIN_ID_INC)/2; } return result; }
java
public static Long calculateChainId(EthereumTransaction eTrans) { Long result=null; long rawResult=EthereumUtil.convertVarNumberToLong(new RLPElement(new byte[0],eTrans.getSig_v())); if (!((rawResult == EthereumUtil.LOWER_REAL_V) || (rawResult== (LOWER_REAL_V+1)))) { result = (rawResult-EthereumUtil.CHAIN_ID_INC)/2; } return result; }
[ "public", "static", "Long", "calculateChainId", "(", "EthereumTransaction", "eTrans", ")", "{", "Long", "result", "=", "null", ";", "long", "rawResult", "=", "EthereumUtil", ".", "convertVarNumberToLong", "(", "new", "RLPElement", "(", "new", "byte", "[", "0", ...
Calculates the chain Id @param eTrans Ethereum Transaction of which the chain id should be calculated @return chainId: 0, Ethereum testnet (aka Olympic); 1: Ethereum mainet (aka Frontier, Homestead, Metropolis) - also Classic (from fork) -also Expanse (alternative Ethereum implementation), 2 Morden (Ethereum testnet, now Ethereum classic testnet), 3 Ropsten public cross-client Ethereum testnet, 4: Rinkeby Geth Ethereum testnet, 42 Kovan, public Parity Ethereum testnet, 7762959 Musicoin, music blockchain
[ "Calculates", "the", "chain", "Id" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java#L364-L371
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java
EthereumUtil.convertToByte
public static Short convertToByte(RLPElement rpe) { Short result=0; if ((rpe.getRawData()!=null) || (rpe.getRawData().length==1)) { result=(short) ( rpe.getRawData()[0] & 0xFF); } return result; }
java
public static Short convertToByte(RLPElement rpe) { Short result=0; if ((rpe.getRawData()!=null) || (rpe.getRawData().length==1)) { result=(short) ( rpe.getRawData()[0] & 0xFF); } return result; }
[ "public", "static", "Short", "convertToByte", "(", "RLPElement", "rpe", ")", "{", "Short", "result", "=", "0", ";", "if", "(", "(", "rpe", ".", "getRawData", "(", ")", "!=", "null", ")", "||", "(", "rpe", ".", "getRawData", "(", ")", ".", "length", ...
Converts a byte in a RLPElement to byte @param rpe RLP element containing a raw byte @return short (=unsigned byte)
[ "Converts", "a", "byte", "in", "a", "RLPElement", "to", "byte" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java#L584-L590
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java
EthereumUtil.convertToShort
public static Integer convertToShort(RLPElement rpe) { Integer result=0; byte[] rawBytes=rpe.getRawData(); if ((rawBytes!=null)) { // fill leading zeros if (rawBytes.length<EthereumUtil.WORD_SIZE) { byte[] fullBytes=new byte[EthereumUtil.WORD_SIZE]; int dtDiff=EthereumUtil.WORD_SIZE-rawBytes.length; for (int i=0;i<rawBytes.length;i++) { fullBytes[dtDiff+i]=rawBytes[i]; result=(int) ByteBuffer.wrap(fullBytes).getShort() & 0xFFFF; } } else { result=(int) ByteBuffer.wrap(rawBytes).getShort() & 0xFFFF; } } return result; }
java
public static Integer convertToShort(RLPElement rpe) { Integer result=0; byte[] rawBytes=rpe.getRawData(); if ((rawBytes!=null)) { // fill leading zeros if (rawBytes.length<EthereumUtil.WORD_SIZE) { byte[] fullBytes=new byte[EthereumUtil.WORD_SIZE]; int dtDiff=EthereumUtil.WORD_SIZE-rawBytes.length; for (int i=0;i<rawBytes.length;i++) { fullBytes[dtDiff+i]=rawBytes[i]; result=(int) ByteBuffer.wrap(fullBytes).getShort() & 0xFFFF; } } else { result=(int) ByteBuffer.wrap(rawBytes).getShort() & 0xFFFF; } } return result; }
[ "public", "static", "Integer", "convertToShort", "(", "RLPElement", "rpe", ")", "{", "Integer", "result", "=", "0", ";", "byte", "[", "]", "rawBytes", "=", "rpe", ".", "getRawData", "(", ")", ";", "if", "(", "(", "rawBytes", "!=", "null", ")", ")", "...
Converts a short in a RLPElement to short @param rpe RLP element containing a raw short @return Integer (unsigned short) or null if not short
[ "Converts", "a", "short", "in", "a", "RLPElement", "to", "short" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java#L599-L617
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java
EthereumUtil.convertToInt
public static Long convertToInt(RLPElement rpe) { Long result=0L; byte[] rawBytes=rpe.getRawData(); if ((rawBytes!=null)) { // fill leading zeros if (rawBytes.length<EthereumUtil.INT_SIZE) { byte[] fullBytes=new byte[EthereumUtil.INT_SIZE]; int dtDiff=EthereumUtil.INT_SIZE-rawBytes.length; for (int i=0;i<rawBytes.length;i++) { fullBytes[dtDiff+i]=rawBytes[i]; result=(long) ByteBuffer.wrap(fullBytes).getInt()& 0x00000000ffffffffL; } } else { result=(long) ByteBuffer.wrap(rawBytes).getInt() & 0x00000000ffffffffL; } } return result; }
java
public static Long convertToInt(RLPElement rpe) { Long result=0L; byte[] rawBytes=rpe.getRawData(); if ((rawBytes!=null)) { // fill leading zeros if (rawBytes.length<EthereumUtil.INT_SIZE) { byte[] fullBytes=new byte[EthereumUtil.INT_SIZE]; int dtDiff=EthereumUtil.INT_SIZE-rawBytes.length; for (int i=0;i<rawBytes.length;i++) { fullBytes[dtDiff+i]=rawBytes[i]; result=(long) ByteBuffer.wrap(fullBytes).getInt()& 0x00000000ffffffffL; } } else { result=(long) ByteBuffer.wrap(rawBytes).getInt() & 0x00000000ffffffffL; } } return result; }
[ "public", "static", "Long", "convertToInt", "(", "RLPElement", "rpe", ")", "{", "Long", "result", "=", "0L", ";", "byte", "[", "]", "rawBytes", "=", "rpe", ".", "getRawData", "(", ")", ";", "if", "(", "(", "rawBytes", "!=", "null", ")", ")", "{", "...
Converts a int in a RLPElement to int @param rpe RLP element containing a raw int @return long (unsigned int) or null if not int
[ "Converts", "a", "int", "in", "a", "RLPElement", "to", "int" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java#L626-L643
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java
EthereumUtil.convertToLong
public static Long convertToLong(RLPElement rpe) { Long result=0L; byte[] rawBytes=rpe.getRawData(); if ((rawBytes!=null)) { // fill leading zeros if (rawBytes.length<EthereumUtil.LONG_SIZE) { byte[] fullBytes=new byte[EthereumUtil.LONG_SIZE]; int dtDiff=EthereumUtil.LONG_SIZE-rawBytes.length; for (int i=0;i<rawBytes.length;i++) { fullBytes[dtDiff+i]=rawBytes[i]; result=ByteBuffer.wrap(fullBytes).getLong(); } } else { result=ByteBuffer.wrap(rawBytes).getLong(); } } return result; }
java
public static Long convertToLong(RLPElement rpe) { Long result=0L; byte[] rawBytes=rpe.getRawData(); if ((rawBytes!=null)) { // fill leading zeros if (rawBytes.length<EthereumUtil.LONG_SIZE) { byte[] fullBytes=new byte[EthereumUtil.LONG_SIZE]; int dtDiff=EthereumUtil.LONG_SIZE-rawBytes.length; for (int i=0;i<rawBytes.length;i++) { fullBytes[dtDiff+i]=rawBytes[i]; result=ByteBuffer.wrap(fullBytes).getLong(); } } else { result=ByteBuffer.wrap(rawBytes).getLong(); } } return result; }
[ "public", "static", "Long", "convertToLong", "(", "RLPElement", "rpe", ")", "{", "Long", "result", "=", "0L", ";", "byte", "[", "]", "rawBytes", "=", "rpe", ".", "getRawData", "(", ")", ";", "if", "(", "(", "rawBytes", "!=", "null", ")", ")", "{", ...
Converts a long in a RLPElement to long @param rpe RLP element containing a raw long @return long or null if not long
[ "Converts", "a", "long", "in", "a", "RLPElement", "to", "long" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/ethereum/format/common/EthereumUtil.java#L652-L669
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinBlockReader.java
BitcoinBlockReader.parseAuxPOWBranch
public BitcoinAuxPOWBranch parseAuxPOWBranch(ByteBuffer rawByteBuffer) { byte[] noOfLinksVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfLinks=BitcoinUtil.getVarInt(noOfLinksVarInt); ArrayList<byte[]> links = new ArrayList((int)currentNoOfLinks); for (int i=0;i<currentNoOfLinks;i++) { byte[] currentLink = new byte[32]; rawByteBuffer.get(currentLink,0,32); links.add(currentLink); } byte[] branchSideBitmask=new byte[4]; rawByteBuffer.get(branchSideBitmask,0,4); return new BitcoinAuxPOWBranch(noOfLinksVarInt, links, branchSideBitmask); }
java
public BitcoinAuxPOWBranch parseAuxPOWBranch(ByteBuffer rawByteBuffer) { byte[] noOfLinksVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfLinks=BitcoinUtil.getVarInt(noOfLinksVarInt); ArrayList<byte[]> links = new ArrayList((int)currentNoOfLinks); for (int i=0;i<currentNoOfLinks;i++) { byte[] currentLink = new byte[32]; rawByteBuffer.get(currentLink,0,32); links.add(currentLink); } byte[] branchSideBitmask=new byte[4]; rawByteBuffer.get(branchSideBitmask,0,4); return new BitcoinAuxPOWBranch(noOfLinksVarInt, links, branchSideBitmask); }
[ "public", "BitcoinAuxPOWBranch", "parseAuxPOWBranch", "(", "ByteBuffer", "rawByteBuffer", ")", "{", "byte", "[", "]", "noOfLinksVarInt", "=", "BitcoinUtil", ".", "convertVarIntByteBufferToByteArray", "(", "rawByteBuffer", ")", ";", "long", "currentNoOfLinks", "=", "Bitc...
Parse an AUXPowBranch @param rawByteBuffer ByteBuffer from which the AuxPOWBranch should be parsed @return AuxPOWBranch
[ "Parse", "an", "AUXPowBranch" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinBlockReader.java#L260-L273
train
ZuInnoTe/hadoopcryptoledger
inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinBlockReader.java
BitcoinBlockReader.parseTransactions
public List<BitcoinTransaction> parseTransactions(ByteBuffer rawByteBuffer,long noOfTransactions) { ArrayList<BitcoinTransaction> resultTransactions = new ArrayList<>((int)noOfTransactions); // read all transactions from ByteBuffer for (int k=0;k<noOfTransactions;k++) { // read version int currentVersion=rawByteBuffer.getInt(); // read inCounter byte[] currentInCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfInputs=BitcoinUtil.getVarInt(currentInCounterVarInt); boolean segwit=false; byte marker=1; byte flag=0; // check segwit marker if (currentNoOfInputs==0) { // this seems to be segwit - lets be sure // check segwit flag rawByteBuffer.mark(); byte segwitFlag = rawByteBuffer.get(); if (segwitFlag!=0) { // load the real number of inputs segwit=true; marker=0; flag=segwitFlag; currentInCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); currentNoOfInputs=BitcoinUtil.getVarInt(currentInCounterVarInt); } else { LOG.warn("It seems a block with 0 transaction inputs was found"); rawByteBuffer.reset(); } } // read inputs List<BitcoinTransactionInput> currentTransactionInput = parseTransactionInputs(rawByteBuffer, currentNoOfInputs); // read outCounter byte[] currentOutCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfOutput=BitcoinUtil.getVarInt(currentOutCounterVarInt); // read outputs List<BitcoinTransactionOutput> currentTransactionOutput = parseTransactionOutputs(rawByteBuffer,currentNoOfOutput); List<BitcoinScriptWitnessItem> currentListOfTransactionSegwits; if (segwit) { // read segwit data // for each transaction input there is at least some segwit data item // read scriptWitness size currentListOfTransactionSegwits=new ArrayList<>(); for (int i=0;i<currentNoOfInputs;i++) { // get no of witness items for input byte[] currentWitnessCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfWitnesses=BitcoinUtil.getVarInt(currentWitnessCounterVarInt); List<BitcoinScriptWitness> currentTransactionSegwit = new ArrayList<>((int)currentNoOfWitnesses); for (int j=0;j<(int)currentNoOfWitnesses;j++) { // read size of segwit script byte[] currentTransactionSegwitScriptLength=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentTransactionSegwitScriptSize=BitcoinUtil.getVarInt(currentTransactionSegwitScriptLength); int currentTransactionSegwitScriptSizeInt= (int)currentTransactionSegwitScriptSize; // read segwit script byte[] currentTransactionInSegwitScript=new byte[currentTransactionSegwitScriptSizeInt]; rawByteBuffer.get(currentTransactionInSegwitScript,0,currentTransactionSegwitScriptSizeInt); // add segwit currentTransactionSegwit.add(new BitcoinScriptWitness(currentTransactionSegwitScriptLength,currentTransactionInSegwitScript)); } currentListOfTransactionSegwits.add(new BitcoinScriptWitnessItem(currentWitnessCounterVarInt,currentTransactionSegwit)); } } else { currentListOfTransactionSegwits=new ArrayList<>(); } // lock_time int currentTransactionLockTime = rawByteBuffer.getInt(); // add transaction resultTransactions.add(new BitcoinTransaction(marker,flag,currentVersion,currentInCounterVarInt,currentTransactionInput,currentOutCounterVarInt,currentTransactionOutput,currentListOfTransactionSegwits,currentTransactionLockTime)); } return resultTransactions; }
java
public List<BitcoinTransaction> parseTransactions(ByteBuffer rawByteBuffer,long noOfTransactions) { ArrayList<BitcoinTransaction> resultTransactions = new ArrayList<>((int)noOfTransactions); // read all transactions from ByteBuffer for (int k=0;k<noOfTransactions;k++) { // read version int currentVersion=rawByteBuffer.getInt(); // read inCounter byte[] currentInCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfInputs=BitcoinUtil.getVarInt(currentInCounterVarInt); boolean segwit=false; byte marker=1; byte flag=0; // check segwit marker if (currentNoOfInputs==0) { // this seems to be segwit - lets be sure // check segwit flag rawByteBuffer.mark(); byte segwitFlag = rawByteBuffer.get(); if (segwitFlag!=0) { // load the real number of inputs segwit=true; marker=0; flag=segwitFlag; currentInCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); currentNoOfInputs=BitcoinUtil.getVarInt(currentInCounterVarInt); } else { LOG.warn("It seems a block with 0 transaction inputs was found"); rawByteBuffer.reset(); } } // read inputs List<BitcoinTransactionInput> currentTransactionInput = parseTransactionInputs(rawByteBuffer, currentNoOfInputs); // read outCounter byte[] currentOutCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfOutput=BitcoinUtil.getVarInt(currentOutCounterVarInt); // read outputs List<BitcoinTransactionOutput> currentTransactionOutput = parseTransactionOutputs(rawByteBuffer,currentNoOfOutput); List<BitcoinScriptWitnessItem> currentListOfTransactionSegwits; if (segwit) { // read segwit data // for each transaction input there is at least some segwit data item // read scriptWitness size currentListOfTransactionSegwits=new ArrayList<>(); for (int i=0;i<currentNoOfInputs;i++) { // get no of witness items for input byte[] currentWitnessCounterVarInt=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentNoOfWitnesses=BitcoinUtil.getVarInt(currentWitnessCounterVarInt); List<BitcoinScriptWitness> currentTransactionSegwit = new ArrayList<>((int)currentNoOfWitnesses); for (int j=0;j<(int)currentNoOfWitnesses;j++) { // read size of segwit script byte[] currentTransactionSegwitScriptLength=BitcoinUtil.convertVarIntByteBufferToByteArray(rawByteBuffer); long currentTransactionSegwitScriptSize=BitcoinUtil.getVarInt(currentTransactionSegwitScriptLength); int currentTransactionSegwitScriptSizeInt= (int)currentTransactionSegwitScriptSize; // read segwit script byte[] currentTransactionInSegwitScript=new byte[currentTransactionSegwitScriptSizeInt]; rawByteBuffer.get(currentTransactionInSegwitScript,0,currentTransactionSegwitScriptSizeInt); // add segwit currentTransactionSegwit.add(new BitcoinScriptWitness(currentTransactionSegwitScriptLength,currentTransactionInSegwitScript)); } currentListOfTransactionSegwits.add(new BitcoinScriptWitnessItem(currentWitnessCounterVarInt,currentTransactionSegwit)); } } else { currentListOfTransactionSegwits=new ArrayList<>(); } // lock_time int currentTransactionLockTime = rawByteBuffer.getInt(); // add transaction resultTransactions.add(new BitcoinTransaction(marker,flag,currentVersion,currentInCounterVarInt,currentTransactionInput,currentOutCounterVarInt,currentTransactionOutput,currentListOfTransactionSegwits,currentTransactionLockTime)); } return resultTransactions; }
[ "public", "List", "<", "BitcoinTransaction", ">", "parseTransactions", "(", "ByteBuffer", "rawByteBuffer", ",", "long", "noOfTransactions", ")", "{", "ArrayList", "<", "BitcoinTransaction", ">", "resultTransactions", "=", "new", "ArrayList", "<>", "(", "(", "int", ...
Parses the Bitcoin transactions in a byte buffer. @param rawByteBuffer ByteBuffer from which the transactions have to be parsed @param noOfTransactions Number of expected transactions @return Array of transactions
[ "Parses", "the", "Bitcoin", "transactions", "in", "a", "byte", "buffer", "." ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/inputformat/src/main/java/org/zuinnote/hadoop/bitcoin/format/common/BitcoinBlockReader.java#L286-L361
train
ZuInnoTe/hadoopcryptoledger
examples/spark-bitcoinblock/src/main/java/org/zuinnote/spark/bitcoin/example/SparkBitcoinBlockCounter.java
SparkBitcoinBlockCounter.jobTotalNumOfTransactions
public static void jobTotalNumOfTransactions(JavaSparkContext sc, Configuration hadoopConf, String inputFile, String outputFile) { // read bitcoin data from HDFS JavaPairRDD<BytesWritable, BitcoinBlock> bitcoinBlocksRDD = sc.newAPIHadoopFile(inputFile, BitcoinBlockFileInputFormat.class, BytesWritable.class, BitcoinBlock.class,hadoopConf); // extract the no transactions / block (map) JavaPairRDD<String, Long> noOfTransactionPair = bitcoinBlocksRDD.mapToPair(new PairFunction<Tuple2<BytesWritable,BitcoinBlock>, String, Long>() { @Override public Tuple2<String, Long> call(Tuple2<BytesWritable,BitcoinBlock> tupleBlock) { return mapNoOfTransaction(tupleBlock._2()); } }); // combine the results from all blocks JavaPairRDD<String, Long> totalCount = noOfTransactionPair.reduceByKey(new Function2<Long, Long, Long>() { @Override public Long call(Long a, Long b) { return reduceSumUpTransactions(a,b); } }); // write results to HDFS totalCount.repartition(1).saveAsTextFile(outputFile); }
java
public static void jobTotalNumOfTransactions(JavaSparkContext sc, Configuration hadoopConf, String inputFile, String outputFile) { // read bitcoin data from HDFS JavaPairRDD<BytesWritable, BitcoinBlock> bitcoinBlocksRDD = sc.newAPIHadoopFile(inputFile, BitcoinBlockFileInputFormat.class, BytesWritable.class, BitcoinBlock.class,hadoopConf); // extract the no transactions / block (map) JavaPairRDD<String, Long> noOfTransactionPair = bitcoinBlocksRDD.mapToPair(new PairFunction<Tuple2<BytesWritable,BitcoinBlock>, String, Long>() { @Override public Tuple2<String, Long> call(Tuple2<BytesWritable,BitcoinBlock> tupleBlock) { return mapNoOfTransaction(tupleBlock._2()); } }); // combine the results from all blocks JavaPairRDD<String, Long> totalCount = noOfTransactionPair.reduceByKey(new Function2<Long, Long, Long>() { @Override public Long call(Long a, Long b) { return reduceSumUpTransactions(a,b); } }); // write results to HDFS totalCount.repartition(1).saveAsTextFile(outputFile); }
[ "public", "static", "void", "jobTotalNumOfTransactions", "(", "JavaSparkContext", "sc", ",", "Configuration", "hadoopConf", ",", "String", "inputFile", ",", "String", "outputFile", ")", "{", "// read bitcoin data from HDFS", "JavaPairRDD", "<", "BytesWritable", ",", "Bi...
a job for counting the total number of transactions @param sc context @param hadoopConf Configuration for input format @param inputFile Input file @param output outputFile file
[ "a", "job", "for", "counting", "the", "total", "number", "of", "transactions" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/examples/spark-bitcoinblock/src/main/java/org/zuinnote/spark/bitcoin/example/SparkBitcoinBlockCounter.java#L80-L99
train
ZuInnoTe/hadoopcryptoledger
examples/spark-bitcoinblock/src/main/java/org/zuinnote/spark/bitcoin/example/SparkBitcoinBlockCounter.java
SparkBitcoinBlockCounter.mapNoOfTransaction
public static Tuple2<String,Long> mapNoOfTransaction(BitcoinBlock block) { return new Tuple2<String, Long>("No of transactions: ",(long)(block.getTransactions().size())); }
java
public static Tuple2<String,Long> mapNoOfTransaction(BitcoinBlock block) { return new Tuple2<String, Long>("No of transactions: ",(long)(block.getTransactions().size())); }
[ "public", "static", "Tuple2", "<", "String", ",", "Long", ">", "mapNoOfTransaction", "(", "BitcoinBlock", "block", ")", "{", "return", "new", "Tuple2", "<", "String", ",", "Long", ">", "(", "\"No of transactions: \"", ",", "(", "long", ")", "(", "block", "...
Maps the number of transactions of a block to a tuple @param block Bitcoinblock @return Tuple containing the String "No of transactions. " and the number of transactions as long
[ "Maps", "the", "number", "of", "transactions", "of", "a", "block", "to", "a", "tuple" ]
5c9bfb61dd1a82374cd0de8413a7c66391ee4414
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/examples/spark-bitcoinblock/src/main/java/org/zuinnote/spark/bitcoin/example/SparkBitcoinBlockCounter.java#L109-L111
train
CloudSlang/cs-actions
cs-amazon/src/main/java/io/cloudslang/content/amazon/actions/lambda/InvokeLambdaAction.java
InvokeLambdaAction.execute
@Action(name = "Invoke AWS Lambda Function", outputs = { @Output(Outputs.RETURN_CODE), @Output(Outputs.RETURN_RESULT), @Output(Outputs.EXCEPTION) }, responses = { @Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.SUCCESS_RETURN_CODE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.FAILURE_RETURN_CODE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR) } ) public Map<String, String> execute( @Param(value = IDENTITY, required = true) String identity, @Param(value = CREDENTIAL, required = true, encrypted = true) String credential, @Param(value = REGION, required = true) String region, @Param(value = PROXY_HOST) String proxyHost, @Param(value = PROXY_PORT) String proxyPort, @Param(value = PROXY_USERNAME) String proxyUsername, @Param(value = PROXY_PASSWORD) String proxyPassword, @Param(value = FUNCTION_NAME, required = true) String function, @Param(value = FUNCTION_QUALIFIER) String qualifier, @Param(value = FUNCTION_PAYLOAD) String payload, @Param(value = CONNECT_TIMEOUT) String connectTimeoutMs, @Param(value = EXECUTION_TIMEOUT) String execTimeoutMs) { proxyPort = defaultIfEmpty(proxyPort, DefaultValues.PROXY_PORT); connectTimeoutMs = defaultIfEmpty(connectTimeoutMs, DefaultValues.CONNECT_TIMEOUT); execTimeoutMs = defaultIfBlank(execTimeoutMs, DefaultValues.EXEC_TIMEOUT); qualifier = defaultIfBlank(qualifier, DefaultValues.DEFAULT_FUNCTION_QUALIFIER); ClientConfiguration lambdaClientConf = AmazonWebServiceClientUtil.getClientConfiguration(proxyHost, proxyPort, proxyUsername, proxyPassword, connectTimeoutMs, execTimeoutMs); AWSLambdaAsyncClient client = (AWSLambdaAsyncClient) AWSLambdaAsyncClientBuilder.standard() .withClientConfiguration(lambdaClientConf) .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(identity, credential))) .withRegion(region) .build(); InvokeRequest invokeRequest = new InvokeRequest() .withFunctionName(function) .withQualifier(qualifier) .withPayload(payload) .withSdkClientExecutionTimeout(Integer.parseInt(execTimeoutMs)); try { InvokeResult invokeResult = client.invoke(invokeRequest); return OutputUtilities.getSuccessResultsMap(new String(invokeResult.getPayload().array())); } catch (Exception e) { return OutputUtilities.getFailureResultsMap(e); } }
java
@Action(name = "Invoke AWS Lambda Function", outputs = { @Output(Outputs.RETURN_CODE), @Output(Outputs.RETURN_RESULT), @Output(Outputs.EXCEPTION) }, responses = { @Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.SUCCESS_RETURN_CODE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.FAILURE_RETURN_CODE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR) } ) public Map<String, String> execute( @Param(value = IDENTITY, required = true) String identity, @Param(value = CREDENTIAL, required = true, encrypted = true) String credential, @Param(value = REGION, required = true) String region, @Param(value = PROXY_HOST) String proxyHost, @Param(value = PROXY_PORT) String proxyPort, @Param(value = PROXY_USERNAME) String proxyUsername, @Param(value = PROXY_PASSWORD) String proxyPassword, @Param(value = FUNCTION_NAME, required = true) String function, @Param(value = FUNCTION_QUALIFIER) String qualifier, @Param(value = FUNCTION_PAYLOAD) String payload, @Param(value = CONNECT_TIMEOUT) String connectTimeoutMs, @Param(value = EXECUTION_TIMEOUT) String execTimeoutMs) { proxyPort = defaultIfEmpty(proxyPort, DefaultValues.PROXY_PORT); connectTimeoutMs = defaultIfEmpty(connectTimeoutMs, DefaultValues.CONNECT_TIMEOUT); execTimeoutMs = defaultIfBlank(execTimeoutMs, DefaultValues.EXEC_TIMEOUT); qualifier = defaultIfBlank(qualifier, DefaultValues.DEFAULT_FUNCTION_QUALIFIER); ClientConfiguration lambdaClientConf = AmazonWebServiceClientUtil.getClientConfiguration(proxyHost, proxyPort, proxyUsername, proxyPassword, connectTimeoutMs, execTimeoutMs); AWSLambdaAsyncClient client = (AWSLambdaAsyncClient) AWSLambdaAsyncClientBuilder.standard() .withClientConfiguration(lambdaClientConf) .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(identity, credential))) .withRegion(region) .build(); InvokeRequest invokeRequest = new InvokeRequest() .withFunctionName(function) .withQualifier(qualifier) .withPayload(payload) .withSdkClientExecutionTimeout(Integer.parseInt(execTimeoutMs)); try { InvokeResult invokeResult = client.invoke(invokeRequest); return OutputUtilities.getSuccessResultsMap(new String(invokeResult.getPayload().array())); } catch (Exception e) { return OutputUtilities.getFailureResultsMap(e); } }
[ "@", "Action", "(", "name", "=", "\"Invoke AWS Lambda Function\"", ",", "outputs", "=", "{", "@", "Output", "(", "Outputs", ".", "RETURN_CODE", ")", ",", "@", "Output", "(", "Outputs", ".", "RETURN_RESULT", ")", ",", "@", "Output", "(", "Outputs", ".", "...
Invokes an AWS Lambda Function in sync mode using AWS Java SDK @param identity Access key associated with your Amazon AWS or IAM account. Example: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" @param credential Secret access key ID associated with your Amazon AWS or IAM account. @param proxyHost Optional - proxy server used to connect to Amazon API. If empty no proxy will be used. Default: "" @param proxyPort Optional - proxy server port. You must either specify values for both proxyHost and proxyPort inputs or leave them both empty. Default: "" @param proxyUsername Optional - proxy server user name. Default: "" @param proxyPassword Optional - proxy server password associated with the proxyUsername input value. Default: "" @param function Lambda function name to call Example: "helloWord" @param qualifier Optional - Lambda function version or alias Example: ":1" Default: "$LATEST" @param payload Optional - Lambda function payload in JSON format Example: "{"key1":"value1", "key1":"value2"}" Default: null @return A map with strings as keys and strings as values that contains: outcome of the action, returnCode of the operation, or failure message and the exception if there is one
[ "Invokes", "an", "AWS", "Lambda", "Function", "in", "sync", "mode", "using", "AWS", "Java", "SDK" ]
9a1be1e99ad88286a6c153d5f2275df6ae1a57a1
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/actions/lambda/InvokeLambdaAction.java#L71-L123
train
CloudSlang/cs-actions
cs-vmware/src/main/java/io/cloudslang/content/vmware/actions/guest/CustomizeLinuxGuest.java
CustomizeLinuxGuest.customizeLinuxGuest
@Action(name = "Customize Linux Guest", outputs = { @Output(Outputs.RETURN_CODE), @Output(Outputs.RETURN_RESULT), @Output(Outputs.EXCEPTION) }, responses = { @Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) }) public Map<String, String> customizeLinuxGuest(@Param(value = Inputs.HOST, required = true) String host, @Param(value = PORT) String port, @Param(value = PROTOCOL) String protocol, @Param(value = USERNAME, required = true) String username, @Param(value = PASSWORD, encrypted = true) String password, @Param(value = TRUST_EVERYONE) String trustEveryone, @Param(value = CLOSE_SESSION) String closeSession, @Param(value = VM_NAME, required = true) String virtualMachineName, @Param(value = COMPUTER_NAME, required = true) String computerName, @Param(value = DOMAIN) String domain, @Param(value = IP_ADDRESS) String ipAddress, @Param(value = SUBNET_MASK) String subnetMask, @Param(value = DEFAULT_GATEWAY) String defaultGateway, @Param(value = UTC_CLOCK) String hwClockUTC, @Param(value = TIME_ZONE) String timeZone, @Param(value = VMWARE_GLOBAL_SESSION_OBJECT) GlobalSessionObject<Map<String, Connection>> globalSessionObject) { try { final HttpInputs httpInputs = new HttpInputs.HttpInputsBuilder() .withHost(host) .withPort(port) .withProtocol(protocol) .withUsername(username) .withPassword(password) .withTrustEveryone(defaultIfEmpty(trustEveryone, FALSE)) .withCloseSession(defaultIfEmpty(closeSession, TRUE)) .withGlobalSessionObject(globalSessionObject) .build(); final VmInputs vmInputs = new VmInputs.VmInputsBuilder().withVirtualMachineName(virtualMachineName).build(); final GuestInputs guestInputs = new GuestInputs.GuestInputsBuilder() .withComputerName(computerName) .withDomain(domain) .withIpAddress(ipAddress) .withSubnetMask(subnetMask) .withDefaultGateway(defaultGateway) .withHwClockUTC(hwClockUTC) .withTimeZone(timeZone) .build(); return new GuestService().customizeVM(httpInputs, vmInputs, guestInputs, false); } catch (Exception ex) { return OutputUtilities.getFailureResultsMap(ex); } }
java
@Action(name = "Customize Linux Guest", outputs = { @Output(Outputs.RETURN_CODE), @Output(Outputs.RETURN_RESULT), @Output(Outputs.EXCEPTION) }, responses = { @Response(text = Outputs.SUCCESS, field = Outputs.RETURN_CODE, value = Outputs.RETURN_CODE_SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = Outputs.FAILURE, field = Outputs.RETURN_CODE, value = Outputs.RETURN_CODE_FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) }) public Map<String, String> customizeLinuxGuest(@Param(value = Inputs.HOST, required = true) String host, @Param(value = PORT) String port, @Param(value = PROTOCOL) String protocol, @Param(value = USERNAME, required = true) String username, @Param(value = PASSWORD, encrypted = true) String password, @Param(value = TRUST_EVERYONE) String trustEveryone, @Param(value = CLOSE_SESSION) String closeSession, @Param(value = VM_NAME, required = true) String virtualMachineName, @Param(value = COMPUTER_NAME, required = true) String computerName, @Param(value = DOMAIN) String domain, @Param(value = IP_ADDRESS) String ipAddress, @Param(value = SUBNET_MASK) String subnetMask, @Param(value = DEFAULT_GATEWAY) String defaultGateway, @Param(value = UTC_CLOCK) String hwClockUTC, @Param(value = TIME_ZONE) String timeZone, @Param(value = VMWARE_GLOBAL_SESSION_OBJECT) GlobalSessionObject<Map<String, Connection>> globalSessionObject) { try { final HttpInputs httpInputs = new HttpInputs.HttpInputsBuilder() .withHost(host) .withPort(port) .withProtocol(protocol) .withUsername(username) .withPassword(password) .withTrustEveryone(defaultIfEmpty(trustEveryone, FALSE)) .withCloseSession(defaultIfEmpty(closeSession, TRUE)) .withGlobalSessionObject(globalSessionObject) .build(); final VmInputs vmInputs = new VmInputs.VmInputsBuilder().withVirtualMachineName(virtualMachineName).build(); final GuestInputs guestInputs = new GuestInputs.GuestInputsBuilder() .withComputerName(computerName) .withDomain(domain) .withIpAddress(ipAddress) .withSubnetMask(subnetMask) .withDefaultGateway(defaultGateway) .withHwClockUTC(hwClockUTC) .withTimeZone(timeZone) .build(); return new GuestService().customizeVM(httpInputs, vmInputs, guestInputs, false); } catch (Exception ex) { return OutputUtilities.getFailureResultsMap(ex); } }
[ "@", "Action", "(", "name", "=", "\"Customize Linux Guest\"", ",", "outputs", "=", "{", "@", "Output", "(", "Outputs", ".", "RETURN_CODE", ")", ",", "@", "Output", "(", "Outputs", ".", "RETURN_RESULT", ")", ",", "@", "Output", "(", "Outputs", ".", "EXCEP...
Connects to specified data center and customize an existing linux OS based virtual machine identified by the inputs provided. @param host VMware host or IP - Example: "vc6.subdomain.example.com" @param port optional - the port to connect through - Examples: "443", "80" - Default: "443" @param protocol optional - the connection protocol - Valid: "http", "https" - Default: "https" @param username the VMware username use to connect @param password the password associated with "username" input @param trustEveryone optional - if "true" will allow connections from any host, if "false" the connection will be allowed only using a valid vCenter certificate - Default: "true" Check the: https://pubs.vmware.com/vsphere-50/index.jsp?topic=%2Fcom.vmware.wssdk.dsg.doc_50%2Fsdk_java_development.4.3.html to see how to import a certificate into Java Keystore and https://pubs.vmware.com/vsphere-50/index.jsp?topic=%2Fcom.vmware.wssdk.dsg.doc_50%2Fsdk_sg_server_certificate_Appendix.6.4.html to see how to obtain a valid vCenter certificate @param closeSession Whether to use the flow session context to cache the Connection to the host or not. If set to "false" it will close and remove any connection from the session context, otherwise the Connection will be kept alive and not removed. Valid values: "true", "false" Default value: "true" @param virtualMachineName name of Windows OS based virtual machine that will be customized @param computerName: the network host name of the (Windows) virtual machine @param domain: optional - the fully qualified domain name - Default: "" @param ipAddress: optional - the static ip address - Default: "" @param subnetMask: optional - the subnet mask for the virtual network adapter - Default: "" @param defaultGateway: optional - the default gateway for network adapter with a static IP address - Default: "" @param hwClockUTC: optional - the MAC address for network adapter with a static IP address - Default: "" @param timeZone: optional - the time zone for the new virtual machine according with https://technet.microsoft.com/en-us/library/ms145276%28v=sql.90%29.aspx - Default: "360" @return resultMap with String as key and value that contains returnCode of the operation, success message with task id of the execution or failure message and the exception if there is one
[ "Connects", "to", "specified", "data", "center", "and", "customize", "an", "existing", "linux", "OS", "based", "virtual", "machine", "identified", "by", "the", "inputs", "provided", "." ]
9a1be1e99ad88286a6c153d5f2275df6ae1a57a1
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-vmware/src/main/java/io/cloudslang/content/vmware/actions/guest/CustomizeLinuxGuest.java#L66-L126
train
CloudSlang/cs-actions
cs-json/src/main/java/io/cloudslang/content/json/actions/ArraySize.java
ArraySize.execute
@Action(name = "Array Size", outputs = { @Output(OutputNames.RETURN_RESULT), @Output(OutputNames.RETURN_CODE), @Output(OutputNames.EXCEPTION) }, responses = { @Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) }) public Map<String, String> execute(@Param(value = Constants.InputNames.ARRAY, required = true) String array) { Map<String, String> returnResult = new HashMap<>(); if (StringUtilities.isBlank(array)) { return populateResult(returnResult, new Exception(NOT_A_VALID_JSON_ARRAY_MESSAGE)); } JsonNode jsonNode; try { ObjectMapper mapper = new ObjectMapper(); jsonNode = mapper.readTree(array); } catch (IOException exception) { final String value = "Invalid jsonObject provided! " + exception.getMessage(); return populateResult(returnResult, value, exception); } final String result; if (jsonNode instanceof ArrayNode) { final ArrayNode asJsonArray = (ArrayNode) jsonNode; result = Integer.toString(asJsonArray.size()); } else { return populateResult(returnResult, new Exception(NOT_A_VALID_JSON_ARRAY_MESSAGE)); } return populateResult(returnResult, result, null); }
java
@Action(name = "Array Size", outputs = { @Output(OutputNames.RETURN_RESULT), @Output(OutputNames.RETURN_CODE), @Output(OutputNames.EXCEPTION) }, responses = { @Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) }) public Map<String, String> execute(@Param(value = Constants.InputNames.ARRAY, required = true) String array) { Map<String, String> returnResult = new HashMap<>(); if (StringUtilities.isBlank(array)) { return populateResult(returnResult, new Exception(NOT_A_VALID_JSON_ARRAY_MESSAGE)); } JsonNode jsonNode; try { ObjectMapper mapper = new ObjectMapper(); jsonNode = mapper.readTree(array); } catch (IOException exception) { final String value = "Invalid jsonObject provided! " + exception.getMessage(); return populateResult(returnResult, value, exception); } final String result; if (jsonNode instanceof ArrayNode) { final ArrayNode asJsonArray = (ArrayNode) jsonNode; result = Integer.toString(asJsonArray.size()); } else { return populateResult(returnResult, new Exception(NOT_A_VALID_JSON_ARRAY_MESSAGE)); } return populateResult(returnResult, result, null); }
[ "@", "Action", "(", "name", "=", "\"Array Size\"", ",", "outputs", "=", "{", "@", "Output", "(", "OutputNames", ".", "RETURN_RESULT", ")", ",", "@", "Output", "(", "OutputNames", ".", "RETURN_CODE", ")", ",", "@", "Output", "(", "OutputNames", ".", "EXCE...
This operation determines the number of elements in the given JSON array. If an element is itself another JSON array, it only counts as 1 element; in other words, it will not expand and count embedded arrays. Null values are also considered to be an element. @param array The string representation of a JSON array object. @return a map containing the output of the operation. Keys present in the map are: <p/> <br><br><b>returnResult</b> - This will contain size of the json array given in the input. <br><b>exception</b> - In case of success response, this result is empty. In case of failure response, this result contains the java stack trace of the runtime exception. <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure.
[ "This", "operation", "determines", "the", "number", "of", "elements", "in", "the", "given", "JSON", "array", ".", "If", "an", "element", "is", "itself", "another", "JSON", "array", "it", "only", "counts", "as", "1", "element", ";", "in", "other", "words", ...
9a1be1e99ad88286a6c153d5f2275df6ae1a57a1
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-json/src/main/java/io/cloudslang/content/json/actions/ArraySize.java#L63-L96
train
CloudSlang/cs-actions
cs-powershell/src/main/java/io/cloudslang/content/utils/XMLUtils.java
XMLUtils.parseXml
public static String parseXml(String xml, String expression) throws ParserConfigurationException, IOException, XPathExpressionException, SAXException { DocumentBuilder builder = ResourceLoader.getDocumentBuilder(); Document document; try { document = builder.parse(new InputSource(new StringReader(xml))); } catch (SAXException e) { throw new RuntimeException(RESPONSE_IS_NOT_WELL_FORMED + xml, e); } XPath xPath = XPathFactory.newInstance().newXPath(); return xPath.compile(expression).evaluate(document); }
java
public static String parseXml(String xml, String expression) throws ParserConfigurationException, IOException, XPathExpressionException, SAXException { DocumentBuilder builder = ResourceLoader.getDocumentBuilder(); Document document; try { document = builder.parse(new InputSource(new StringReader(xml))); } catch (SAXException e) { throw new RuntimeException(RESPONSE_IS_NOT_WELL_FORMED + xml, e); } XPath xPath = XPathFactory.newInstance().newXPath(); return xPath.compile(expression).evaluate(document); }
[ "public", "static", "String", "parseXml", "(", "String", "xml", ",", "String", "expression", ")", "throws", "ParserConfigurationException", ",", "IOException", ",", "XPathExpressionException", ",", "SAXException", "{", "DocumentBuilder", "builder", "=", "ResourceLoader"...
Parse the content of the given xml input and evaluates the given XPath expression. @param xml The xml source. @param expression The XPath expression. @return Evaluate the XPath expression and return the result as a String. @throws ParserConfigurationException @throws IOException @throws XPathExpressionException @throws SAXException
[ "Parse", "the", "content", "of", "the", "given", "xml", "input", "and", "evaluates", "the", "given", "XPath", "expression", "." ]
9a1be1e99ad88286a6c153d5f2275df6ae1a57a1
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-powershell/src/main/java/io/cloudslang/content/utils/XMLUtils.java#L53-L63
train