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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.startsWithCustomRoot | private boolean startsWithCustomRoot(String path) {
for (Enumeration<String> it = customRoots.elements(); it != null
&& it.hasMoreElements();) {
if (path.startsWith(it.nextElement())) {
return true;
}
}
return false;
} | java | private boolean startsWithCustomRoot(String path) {
for (Enumeration<String> it = customRoots.elements(); it != null
&& it.hasMoreElements();) {
if (path.startsWith(it.nextElement())) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"startsWithCustomRoot",
"(",
"String",
"path",
")",
"{",
"for",
"(",
"Enumeration",
"<",
"String",
">",
"it",
"=",
"customRoots",
".",
"elements",
"(",
")",
";",
"it",
"!=",
"null",
"&&",
"it",
".",
"hasMoreElements",
"(",
")",
";",... | Tests whether path starts with a custom file system root.
@param path
@return <em>true</em> if path starts with an element of customRoots,
<em>false</em> otherwise | [
"Tests",
"whether",
"path",
"starts",
"with",
"a",
"custom",
"file",
"system",
"root",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L532-L540 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.isDirectoryOrLinkedDirectory | public boolean isDirectoryOrLinkedDirectory(SftpFile file)
throws SftpStatusException, SshException {
return file.isDirectory()
|| (file.isLink() && stat(file.getAbsolutePath()).isDirectory());
} | java | public boolean isDirectoryOrLinkedDirectory(SftpFile file)
throws SftpStatusException, SshException {
return file.isDirectory()
|| (file.isLink() && stat(file.getAbsolutePath()).isDirectory());
} | [
"public",
"boolean",
"isDirectoryOrLinkedDirectory",
"(",
"SftpFile",
"file",
")",
"throws",
"SftpStatusException",
",",
"SshException",
"{",
"return",
"file",
".",
"isDirectory",
"(",
")",
"||",
"(",
"file",
".",
"isLink",
"(",
")",
"&&",
"stat",
"(",
"file",... | Determine whether the file object is pointing to a symbolic link that is
pointing to a directory.
@return boolean | [
"Determine",
"whether",
"the",
"file",
"object",
"is",
"pointing",
"to",
"a",
"symbolic",
"link",
"that",
"is",
"pointing",
"to",
"a",
"directory",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L658-L662 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.get | public SftpFileAttributes get(String remote, String local, boolean resume)
throws FileNotFoundException, SftpStatusException, SshException,
TransferCancelledException {
return get(remote, local, null, resume);
} | java | public SftpFileAttributes get(String remote, String local, boolean resume)
throws FileNotFoundException, SftpStatusException, SshException,
TransferCancelledException {
return get(remote, local, null, resume);
} | [
"public",
"SftpFileAttributes",
"get",
"(",
"String",
"remote",
",",
"String",
"local",
",",
"boolean",
"resume",
")",
"throws",
"FileNotFoundException",
",",
"SftpStatusException",
",",
"SshException",
",",
"TransferCancelledException",
"{",
"return",
"get",
"(",
"... | Download the remote file into the local file.
@param remote
@param local
@param resume
attempt to resume an interrupted download
@return the downloaded file's attributes
@throws FileNotFoundException
@throws SftpStatusException
@throws SshException
@throws TransferCancelledException | [
"Download",
"the",
"remote",
"file",
"into",
"the",
"local",
"file",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L1107-L1111 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.getInputStream | public InputStream getInputStream(String remotefile, long position)
throws SftpStatusException, SshException {
String remotePath = resolveRemotePath(remotefile);
sftp.getAttributes(remotePath);
return new SftpFileInputStream(sftp.openFile(remotePath,
SftpSubsystemChannel.OPEN_READ), position);
} | java | public InputStream getInputStream(String remotefile, long position)
throws SftpStatusException, SshException {
String remotePath = resolveRemotePath(remotefile);
sftp.getAttributes(remotePath);
return new SftpFileInputStream(sftp.openFile(remotePath,
SftpSubsystemChannel.OPEN_READ), position);
} | [
"public",
"InputStream",
"getInputStream",
"(",
"String",
"remotefile",
",",
"long",
"position",
")",
"throws",
"SftpStatusException",
",",
"SshException",
"{",
"String",
"remotePath",
"=",
"resolveRemotePath",
"(",
"remotefile",
")",
";",
"sftp",
".",
"getAttribute... | Create an InputStream for reading a remote file.
@param remotefile
@param position
@return InputStream
@throws SftpStatusException
@throws SshException | [
"Create",
"an",
"InputStream",
"for",
"reading",
"a",
"remote",
"file",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L1519-L1527 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.get | public SftpFileAttributes get(String remote, OutputStream local,
long position) throws SftpStatusException, SshException,
TransferCancelledException {
return get(remote, local, null, position);
} | java | public SftpFileAttributes get(String remote, OutputStream local,
long position) throws SftpStatusException, SshException,
TransferCancelledException {
return get(remote, local, null, position);
} | [
"public",
"SftpFileAttributes",
"get",
"(",
"String",
"remote",
",",
"OutputStream",
"local",
",",
"long",
"position",
")",
"throws",
"SftpStatusException",
",",
"SshException",
",",
"TransferCancelledException",
"{",
"return",
"get",
"(",
"remote",
",",
"local",
... | Download the remote file into an OutputStream.
@param remote
@param local
@param position
the position from which to start reading the remote file
@return the downloaded file's attributes
@throws SftpStatusException
@throws SshException
@throws TransferCancelledException | [
"Download",
"the",
"remote",
"file",
"into",
"an",
"OutputStream",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L1556-L1560 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.getOutputStream | public OutputStream getOutputStream(String remotefile)
throws SftpStatusException, SshException {
String remotePath = resolveRemotePath(remotefile);
return new SftpFileOutputStream(sftp.openFile(remotePath,
SftpSubsystemChannel.OPEN_CREATE
| SftpSubsystemChannel.OPEN_TRUNCATE
| SftpSubsystemChannel.OPEN_WRITE));
} | java | public OutputStream getOutputStream(String remotefile)
throws SftpStatusException, SshException {
String remotePath = resolveRemotePath(remotefile);
return new SftpFileOutputStream(sftp.openFile(remotePath,
SftpSubsystemChannel.OPEN_CREATE
| SftpSubsystemChannel.OPEN_TRUNCATE
| SftpSubsystemChannel.OPEN_WRITE));
} | [
"public",
"OutputStream",
"getOutputStream",
"(",
"String",
"remotefile",
")",
"throws",
"SftpStatusException",
",",
"SshException",
"{",
"String",
"remotePath",
"=",
"resolveRemotePath",
"(",
"remotefile",
")",
";",
"return",
"new",
"SftpFileOutputStream",
"(",
"sftp... | Create an OutputStream for writing to a remote file.
@param remotefile
@return OutputStream
@throws SftpStatusException
@throws SshException | [
"Create",
"an",
"OutputStream",
"for",
"writing",
"to",
"a",
"remote",
"file",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L1943-L1952 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.put | public void put(InputStream in, String remote, long position)
throws SftpStatusException, SshException,
TransferCancelledException {
put(in, remote, null, position);
} | java | public void put(InputStream in, String remote, long position)
throws SftpStatusException, SshException,
TransferCancelledException {
put(in, remote, null, position);
} | [
"public",
"void",
"put",
"(",
"InputStream",
"in",
",",
"String",
"remote",
",",
"long",
"position",
")",
"throws",
"SftpStatusException",
",",
"SshException",
",",
"TransferCancelledException",
"{",
"put",
"(",
"in",
",",
"remote",
",",
"null",
",",
"position... | Upload the contents of an InputStream to the remote computer.
@param in
@param remote
@param position
@throws SftpStatusException
@throws SshException
@throws TransferCancelledException | [
"Upload",
"the",
"contents",
"of",
"an",
"InputStream",
"to",
"the",
"remote",
"computer",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L1965-L1969 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.rm | public void rm(String path, boolean force, boolean recurse)
throws SftpStatusException, SshException {
String actual = resolveRemotePath(path);
SftpFileAttributes attrs = null;
attrs = sftp.getAttributes(actual);
SftpFile file;
if (attrs.isDirectory()) {
SftpFile[] list = ls(path);
if (!force && (list.length > 0)) {
throw new SftpStatusException(
SftpStatusException.SSH_FX_FAILURE,
"You cannot delete non-empty directory, use force=true to overide");
}
for (int i = 0; i < list.length; i++) {
file = list[i];
if (file.isDirectory() && !file.getFilename().equals(".")
&& !file.getFilename().equals("..")) {
if (recurse) {
rm(file.getAbsolutePath(), force, recurse);
} else {
throw new SftpStatusException(
SftpStatusException.SSH_FX_FAILURE,
"Directory has contents, cannot delete without recurse=true");
}
} else if (file.isFile()) {
sftp.removeFile(file.getAbsolutePath());
}
}
sftp.removeDirectory(actual);
} else {
sftp.removeFile(actual);
}
} | java | public void rm(String path, boolean force, boolean recurse)
throws SftpStatusException, SshException {
String actual = resolveRemotePath(path);
SftpFileAttributes attrs = null;
attrs = sftp.getAttributes(actual);
SftpFile file;
if (attrs.isDirectory()) {
SftpFile[] list = ls(path);
if (!force && (list.length > 0)) {
throw new SftpStatusException(
SftpStatusException.SSH_FX_FAILURE,
"You cannot delete non-empty directory, use force=true to overide");
}
for (int i = 0; i < list.length; i++) {
file = list[i];
if (file.isDirectory() && !file.getFilename().equals(".")
&& !file.getFilename().equals("..")) {
if (recurse) {
rm(file.getAbsolutePath(), force, recurse);
} else {
throw new SftpStatusException(
SftpStatusException.SSH_FX_FAILURE,
"Directory has contents, cannot delete without recurse=true");
}
} else if (file.isFile()) {
sftp.removeFile(file.getAbsolutePath());
}
}
sftp.removeDirectory(actual);
} else {
sftp.removeFile(actual);
}
} | [
"public",
"void",
"rm",
"(",
"String",
"path",
",",
"boolean",
"force",
",",
"boolean",
"recurse",
")",
"throws",
"SftpStatusException",
",",
"SshException",
"{",
"String",
"actual",
"=",
"resolveRemotePath",
"(",
"path",
")",
";",
"SftpFileAttributes",
"attrs",... | Remove a file or directory on the remote computer with options to force
deletion of existing files and recursion.
@param path
@param force
@param recurse
@throws SftpStatusException
@throws SshException | [
"Remove",
"a",
"file",
"or",
"directory",
"on",
"the",
"remote",
"computer",
"with",
"options",
"to",
"force",
"deletion",
"of",
"existing",
"files",
"and",
"recursion",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L2193-L2232 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.getAbsolutePath | public String getAbsolutePath(String path) throws SftpStatusException,
SshException {
String actual = resolveRemotePath(path);
return sftp.getAbsolutePath(actual);
} | java | public String getAbsolutePath(String path) throws SftpStatusException,
SshException {
String actual = resolveRemotePath(path);
return sftp.getAbsolutePath(actual);
} | [
"public",
"String",
"getAbsolutePath",
"(",
"String",
"path",
")",
"throws",
"SftpStatusException",
",",
"SshException",
"{",
"String",
"actual",
"=",
"resolveRemotePath",
"(",
"path",
")",
";",
"return",
"sftp",
".",
"getAbsolutePath",
"(",
"actual",
")",
";",
... | Get the absolute path for a file.
@param path
@return String
@throws SftpStatusException
@throws SshException | [
"Get",
"the",
"absolute",
"path",
"for",
"a",
"file",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L2303-L2307 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.putFiles | public void putFiles(String local, String remote,
FileTransferProgress progress, boolean resume)
throws FileNotFoundException, SftpStatusException, SshException,
TransferCancelledException {
putFileMatches(local, remote, progress, resume);
} | java | public void putFiles(String local, String remote,
FileTransferProgress progress, boolean resume)
throws FileNotFoundException, SftpStatusException, SshException,
TransferCancelledException {
putFileMatches(local, remote, progress, resume);
} | [
"public",
"void",
"putFiles",
"(",
"String",
"local",
",",
"String",
"remote",
",",
"FileTransferProgress",
"progress",
",",
"boolean",
"resume",
")",
"throws",
"FileNotFoundException",
",",
"SftpStatusException",
",",
"SshException",
",",
"TransferCancelledException",
... | make local copies of some of the variables, then call putfilematches,
which calls "put" on each file that matches the regexp local.
@param local
the regular expression path/name of the local files
@param remote
the path/name of the destination file
@param progress
@param resume
attempt to resume after an interrupted transfer
@throws SftpStatusException
@throws SshException
@throws TransferCancelledException
@throws FileNotFoundException | [
"make",
"local",
"copies",
"of",
"some",
"of",
"the",
"variables",
"then",
"call",
"putfilematches",
"which",
"calls",
"put",
"on",
"each",
"file",
"that",
"matches",
"the",
"regexp",
"local",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L3273-L3278 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/ssh2/AuthenticationProtocol.java | AuthenticationProtocol.authenticate | public int authenticate(AuthenticationClient auth, String servicename)
throws SshException {
try {
auth.authenticate(this, servicename);
readMessage();
transport
.disconnect(TransportProtocol.PROTOCOL_ERROR,
"Unexpected response received from Authentication Protocol");
throw new SshException(
"Unexpected response received from Authentication Protocol",
SshException.PROTOCOL_VIOLATION);
} catch (AuthenticationResult result) {
state = result.getResult();
if (state == SshAuthentication.COMPLETE)
transport.completedAuthentication();
return state;
}
} | java | public int authenticate(AuthenticationClient auth, String servicename)
throws SshException {
try {
auth.authenticate(this, servicename);
readMessage();
transport
.disconnect(TransportProtocol.PROTOCOL_ERROR,
"Unexpected response received from Authentication Protocol");
throw new SshException(
"Unexpected response received from Authentication Protocol",
SshException.PROTOCOL_VIOLATION);
} catch (AuthenticationResult result) {
state = result.getResult();
if (state == SshAuthentication.COMPLETE)
transport.completedAuthentication();
return state;
}
} | [
"public",
"int",
"authenticate",
"(",
"AuthenticationClient",
"auth",
",",
"String",
"servicename",
")",
"throws",
"SshException",
"{",
"try",
"{",
"auth",
".",
"authenticate",
"(",
"this",
",",
"servicename",
")",
";",
"readMessage",
"(",
")",
";",
"transport... | Authenticate using the mechanism provided.
@param auth
@param servicename
@return Any of the constants defined in <a
href="AuthenticationResult.html">AuthenticationResult</a>
@throws SshException | [
"Authenticate",
"using",
"the",
"mechanism",
"provided",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/ssh2/AuthenticationProtocol.java#L203-L220 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/ssh2/AuthenticationProtocol.java | AuthenticationProtocol.sendRequest | public void sendRequest(String username, String servicename,
String methodname, byte[] requestdata) throws SshException {
ByteArrayWriter msg = new ByteArrayWriter();
try {
msg.write(SSH_MSG_USERAUTH_REQUEST);
msg.writeString(username);
msg.writeString(servicename);
msg.writeString(methodname);
if (requestdata != null) {
msg.write(requestdata);
}
transport.sendMessage(msg.toByteArray(), true);
} catch (IOException ex) {
throw new SshException(ex, SshException.INTERNAL_ERROR);
} finally {
try {
msg.close();
} catch (IOException e) {
}
}
} | java | public void sendRequest(String username, String servicename,
String methodname, byte[] requestdata) throws SshException {
ByteArrayWriter msg = new ByteArrayWriter();
try {
msg.write(SSH_MSG_USERAUTH_REQUEST);
msg.writeString(username);
msg.writeString(servicename);
msg.writeString(methodname);
if (requestdata != null) {
msg.write(requestdata);
}
transport.sendMessage(msg.toByteArray(), true);
} catch (IOException ex) {
throw new SshException(ex, SshException.INTERNAL_ERROR);
} finally {
try {
msg.close();
} catch (IOException e) {
}
}
} | [
"public",
"void",
"sendRequest",
"(",
"String",
"username",
",",
"String",
"servicename",
",",
"String",
"methodname",
",",
"byte",
"[",
"]",
"requestdata",
")",
"throws",
"SshException",
"{",
"ByteArrayWriter",
"msg",
"=",
"new",
"ByteArrayWriter",
"(",
")",
... | Send an authentication request. This sends an SSH_MSG_USERAUTH_REQUEST
message.
@param username
@param servicename
@param methodname
@param requestdata
the request data as defined by the authentication
specification
@throws SshException | [
"Send",
"an",
"authentication",
"request",
".",
"This",
"sends",
"an",
"SSH_MSG_USERAUTH_REQUEST",
"message",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/ssh2/AuthenticationProtocol.java#L274-L297 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/util/UnsignedInteger32.java | UnsignedInteger32.add | public static UnsignedInteger32 add(UnsignedInteger32 x, UnsignedInteger32 y) {
return new UnsignedInteger32(x.longValue() + y.longValue());
} | java | public static UnsignedInteger32 add(UnsignedInteger32 x, UnsignedInteger32 y) {
return new UnsignedInteger32(x.longValue() + y.longValue());
} | [
"public",
"static",
"UnsignedInteger32",
"add",
"(",
"UnsignedInteger32",
"x",
",",
"UnsignedInteger32",
"y",
")",
"{",
"return",
"new",
"UnsignedInteger32",
"(",
"x",
".",
"longValue",
"(",
")",
"+",
"y",
".",
"longValue",
"(",
")",
")",
";",
"}"
] | Add two unsigned integers together.
@param x
@param y
@return UnsignedInteger32 | [
"Add",
"two",
"unsigned",
"integers",
"together",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/util/UnsignedInteger32.java#L129-L131 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/socks/Socks5Proxy.java | Socks5Proxy.setAuthenticationMethod | public boolean setAuthenticationMethod(int methodId, Authentication method) {
if (methodId < 0 || methodId > 255)
return false;
if (method == null) {
// Want to remove a particular method
return (authMethods.remove(new Integer(methodId)) != null);
} else {// Add the method, or rewrite old one
authMethods.put(new Integer(methodId), method);
}
return true;
} | java | public boolean setAuthenticationMethod(int methodId, Authentication method) {
if (methodId < 0 || methodId > 255)
return false;
if (method == null) {
// Want to remove a particular method
return (authMethods.remove(new Integer(methodId)) != null);
} else {// Add the method, or rewrite old one
authMethods.put(new Integer(methodId), method);
}
return true;
} | [
"public",
"boolean",
"setAuthenticationMethod",
"(",
"int",
"methodId",
",",
"Authentication",
"method",
")",
"{",
"if",
"(",
"methodId",
"<",
"0",
"||",
"methodId",
">",
"255",
")",
"return",
"false",
";",
"if",
"(",
"method",
"==",
"null",
")",
"{",
"/... | Adds another authentication method.
@param methodId
Authentication method id, see rfc1928
@param method
Implementation of Authentication
@see Authentication | [
"Adds",
"another",
"authentication",
"method",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/socks/Socks5Proxy.java#L149-L159 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/socks/Socks5Proxy.java | Socks5Proxy.getAuthenticationMethod | public Authentication getAuthenticationMethod(int methodId) {
Object method = authMethods.get(new Integer(methodId));
if (method == null)
return null;
return (Authentication) method;
} | java | public Authentication getAuthenticationMethod(int methodId) {
Object method = authMethods.get(new Integer(methodId));
if (method == null)
return null;
return (Authentication) method;
} | [
"public",
"Authentication",
"getAuthenticationMethod",
"(",
"int",
"methodId",
")",
"{",
"Object",
"method",
"=",
"authMethods",
".",
"get",
"(",
"new",
"Integer",
"(",
"methodId",
")",
")",
";",
"if",
"(",
"method",
"==",
"null",
")",
"return",
"null",
";... | Get authentication method, which corresponds to given method id
@param methodId
Authentication method id.
@return Implementation for given method or null, if one was not set. | [
"Get",
"authentication",
"method",
"which",
"corresponds",
"to",
"given",
"method",
"id"
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/socks/Socks5Proxy.java#L168-L173 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/ssh/components/jce/JCEComponentManager.java | JCEComponentManager.installCBCCiphers | public void installCBCCiphers(ComponentFactory ciphers) {
if (testJCECipher("3des-cbc", TripleDesCbc.class)) {
ciphers.add("3des-cbc", TripleDesCbc.class);
}
if (testJCECipher("blowfish-cbc", BlowfishCbc.class)) {
ciphers.add("blowfish-cbc", BlowfishCbc.class);
}
if (testJCECipher("aes128-cbc", AES128Cbc.class)) {
ciphers.add("aes128-cbc", AES128Cbc.class);
}
if (testJCECipher("aes192-cbc", AES192Cbc.class)) {
ciphers.add("aes192-cbc", AES192Cbc.class);
}
if (testJCECipher("aes256-cbc", AES256Cbc.class)) {
ciphers.add("aes256-cbc", AES256Cbc.class);
}
} | java | public void installCBCCiphers(ComponentFactory ciphers) {
if (testJCECipher("3des-cbc", TripleDesCbc.class)) {
ciphers.add("3des-cbc", TripleDesCbc.class);
}
if (testJCECipher("blowfish-cbc", BlowfishCbc.class)) {
ciphers.add("blowfish-cbc", BlowfishCbc.class);
}
if (testJCECipher("aes128-cbc", AES128Cbc.class)) {
ciphers.add("aes128-cbc", AES128Cbc.class);
}
if (testJCECipher("aes192-cbc", AES192Cbc.class)) {
ciphers.add("aes192-cbc", AES192Cbc.class);
}
if (testJCECipher("aes256-cbc", AES256Cbc.class)) {
ciphers.add("aes256-cbc", AES256Cbc.class);
}
} | [
"public",
"void",
"installCBCCiphers",
"(",
"ComponentFactory",
"ciphers",
")",
"{",
"if",
"(",
"testJCECipher",
"(",
"\"3des-cbc\"",
",",
"TripleDesCbc",
".",
"class",
")",
")",
"{",
"ciphers",
".",
"add",
"(",
"\"3des-cbc\"",
",",
"TripleDesCbc",
".",
"class... | Install deprecated Counter-Block-Mode ciphers.
@param ciphers | [
"Install",
"deprecated",
"Counter",
"-",
"Block",
"-",
"Mode",
"ciphers",
"."
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/ssh/components/jce/JCEComponentManager.java#L440-L460 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/ssh/components/jce/JCEComponentManager.java | JCEComponentManager.installArcFourCiphers | public void installArcFourCiphers(ComponentFactory ciphers) {
if (testJCECipher("arcfour", ArcFour.class)) {
ciphers.add("arcfour", ArcFour.class);
}
if (testJCECipher("arcfour128", ArcFour128.class)) {
ciphers.add("arcfour128", ArcFour128.class);
}
if (testJCECipher("arcfour256", ArcFour256.class)) {
ciphers.add("arcfour256", ArcFour256.class);
}
} | java | public void installArcFourCiphers(ComponentFactory ciphers) {
if (testJCECipher("arcfour", ArcFour.class)) {
ciphers.add("arcfour", ArcFour.class);
}
if (testJCECipher("arcfour128", ArcFour128.class)) {
ciphers.add("arcfour128", ArcFour128.class);
}
if (testJCECipher("arcfour256", ArcFour256.class)) {
ciphers.add("arcfour256", ArcFour256.class);
}
} | [
"public",
"void",
"installArcFourCiphers",
"(",
"ComponentFactory",
"ciphers",
")",
"{",
"if",
"(",
"testJCECipher",
"(",
"\"arcfour\"",
",",
"ArcFour",
".",
"class",
")",
")",
"{",
"ciphers",
".",
"add",
"(",
"\"arcfour\"",
",",
"ArcFour",
".",
"class",
")"... | Install deprecated ArcFour ciphers
@param ciphers | [
"Install",
"deprecated",
"ArcFour",
"ciphers"
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/ssh/components/jce/JCEComponentManager.java#L466-L479 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/events/Event.java | Event.addAttribute | public Event addAttribute(String key, Object value) {
eventAttributes.put(key, (value == null ? "null" : value));
return this;
} | java | public Event addAttribute(String key, Object value) {
eventAttributes.put(key, (value == null ? "null" : value));
return this;
} | [
"public",
"Event",
"addAttribute",
"(",
"String",
"key",
",",
"Object",
"value",
")",
"{",
"eventAttributes",
".",
"put",
"(",
"key",
",",
"(",
"value",
"==",
"null",
"?",
"\"null\"",
":",
"value",
")",
")",
";",
"return",
"this",
";",
"}"
] | Add an attribute to the event
@param key
key of attribute
@param String
value of attribute
@return this object, to allow event attribute chains | [
"Add",
"an",
"attribute",
"to",
"the",
"event"
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/events/Event.java#L111-L114 | train |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/socks/SocksSocket.java | SocksSocket.getInetAddress | public InetAddress getInetAddress(){
if(remoteIP == null){
try{
remoteIP = InetAddress.getByName(remoteHost);
}catch(UnknownHostException e){
return null;
}
}
return remoteIP;
} | java | public InetAddress getInetAddress(){
if(remoteIP == null){
try{
remoteIP = InetAddress.getByName(remoteHost);
}catch(UnknownHostException e){
return null;
}
}
return remoteIP;
} | [
"public",
"InetAddress",
"getInetAddress",
"(",
")",
"{",
"if",
"(",
"remoteIP",
"==",
"null",
")",
"{",
"try",
"{",
"remoteIP",
"=",
"InetAddress",
".",
"getByName",
"(",
"remoteHost",
")",
";",
"}",
"catch",
"(",
"UnknownHostException",
"e",
")",
"{",
... | Get remote host as InetAddress object, might return null if
addresses are resolved by proxy, and it is not possible to resolve
it locally
@return Ip address of the host this socket is connected to, or null
if address was returned by the proxy as DOMAINNAME and can't be
resolved locally. | [
"Get",
"remote",
"host",
"as",
"InetAddress",
"object",
"might",
"return",
"null",
"if",
"addresses",
"are",
"resolved",
"by",
"proxy",
"and",
"it",
"is",
"not",
"possible",
"to",
"resolve",
"it",
"locally"
] | ce11ceaf0aa0b129b54327a6891973e1e34689f7 | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/socks/SocksSocket.java#L230-L239 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/views/Indexer.java | Indexer.run | public void run(Iterable<Item> items, Context cx) {
Function prepareFunc = (Function) indexResults.getPrototype().get("prepare", indexResults);
prepareFunc.call(cx, scope, indexResults, NO_ARGS);
Object args[] = new Object[] { null, mapFunction };
for (Item item : items) {
args[0] = item;
indexFunction.call(cx, scope, indexResults, args);
}
Function doneFunc = (Function) indexResults.getPrototype().get("setDone", indexResults);
doneFunc.call(cx, scope, indexResults, NO_ARGS);
} | java | public void run(Iterable<Item> items, Context cx) {
Function prepareFunc = (Function) indexResults.getPrototype().get("prepare", indexResults);
prepareFunc.call(cx, scope, indexResults, NO_ARGS);
Object args[] = new Object[] { null, mapFunction };
for (Item item : items) {
args[0] = item;
indexFunction.call(cx, scope, indexResults, args);
}
Function doneFunc = (Function) indexResults.getPrototype().get("setDone", indexResults);
doneFunc.call(cx, scope, indexResults, NO_ARGS);
} | [
"public",
"void",
"run",
"(",
"Iterable",
"<",
"Item",
">",
"items",
",",
"Context",
"cx",
")",
"{",
"Function",
"prepareFunc",
"=",
"(",
"Function",
")",
"indexResults",
".",
"getPrototype",
"(",
")",
".",
"get",
"(",
"\"prepare\"",
",",
"indexResults",
... | Run the indexer on the given iterable of items. This will attempt to apply some
optimizations to ensure that only items which need re-indexing are actually passed
to the map function.
@param items The items to index
@param cx The current execution context | [
"Run",
"the",
"indexer",
"on",
"the",
"given",
"iterable",
"of",
"items",
".",
"This",
"will",
"attempt",
"to",
"apply",
"some",
"optimizations",
"to",
"ensure",
"that",
"only",
"items",
"which",
"need",
"re",
"-",
"indexing",
"are",
"actually",
"passed",
... | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/views/Indexer.java#L75-L87 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/views/Indexer.java | Indexer.create | public static Indexer create(String mapTxt) {
Context cx = Context.enter();
try {
return new Indexer(mapTxt, cx);
} finally {
Context.exit();
}
} | java | public static Indexer create(String mapTxt) {
Context cx = Context.enter();
try {
return new Indexer(mapTxt, cx);
} finally {
Context.exit();
}
} | [
"public",
"static",
"Indexer",
"create",
"(",
"String",
"mapTxt",
")",
"{",
"Context",
"cx",
"=",
"Context",
".",
"enter",
"(",
")",
";",
"try",
"{",
"return",
"new",
"Indexer",
"(",
"mapTxt",
",",
"cx",
")",
";",
"}",
"finally",
"{",
"Context",
".",... | Create a new indexer object
@param mapTxt The text of the map function
@return indexer | [
"Create",
"a",
"new",
"indexer",
"object"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/views/Indexer.java#L94-L101 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/http/Authenticator.java | Authenticator.isAuthorizedForBucket | public boolean isAuthorizedForBucket(AuthContext ctx, Bucket bucket) {
if (ctx.getUsername().equals(adminName)) {
return ctx.getPassword().equals(adminPass);
}
if (bucket.getName().equals(ctx.getUsername())) {
return bucket.getPassword().equals(ctx.getPassword());
}
return bucket.getPassword().isEmpty() && ctx.getPassword().isEmpty();
} | java | public boolean isAuthorizedForBucket(AuthContext ctx, Bucket bucket) {
if (ctx.getUsername().equals(adminName)) {
return ctx.getPassword().equals(adminPass);
}
if (bucket.getName().equals(ctx.getUsername())) {
return bucket.getPassword().equals(ctx.getPassword());
}
return bucket.getPassword().isEmpty() && ctx.getPassword().isEmpty();
} | [
"public",
"boolean",
"isAuthorizedForBucket",
"(",
"AuthContext",
"ctx",
",",
"Bucket",
"bucket",
")",
"{",
"if",
"(",
"ctx",
".",
"getUsername",
"(",
")",
".",
"equals",
"(",
"adminName",
")",
")",
"{",
"return",
"ctx",
".",
"getPassword",
"(",
")",
"."... | Determine if the given credentials allow access to the bucket
@param ctx The credentials
@param bucket The bucket to check against
@return true if the credentials match the bucket's credentials, or if the bucket is not password protected, or if
the credentials match the administrative credentials | [
"Determine",
"if",
"the",
"given",
"credentials",
"allow",
"access",
"to",
"the",
"bucket"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/http/Authenticator.java#L48-L58 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/http/Authenticator.java | Authenticator.isAdministrator | public boolean isAdministrator(AuthContext ctx) {
return ctx.getUsername() != null && ctx.getUsername().equals(adminName) &&
ctx.getPassword() != null && ctx.getPassword().equals(adminPass);
} | java | public boolean isAdministrator(AuthContext ctx) {
return ctx.getUsername() != null && ctx.getUsername().equals(adminName) &&
ctx.getPassword() != null && ctx.getPassword().equals(adminPass);
} | [
"public",
"boolean",
"isAdministrator",
"(",
"AuthContext",
"ctx",
")",
"{",
"return",
"ctx",
".",
"getUsername",
"(",
")",
"!=",
"null",
"&&",
"ctx",
".",
"getUsername",
"(",
")",
".",
"equals",
"(",
"adminName",
")",
"&&",
"ctx",
".",
"getPassword",
"(... | Check if the given credentials allow administrative access
@param ctx The credentials to check
@return true if the credentials match the administrative credentials | [
"Check",
"if",
"the",
"given",
"credentials",
"allow",
"administrative",
"access"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/http/Authenticator.java#L65-L68 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/protocol/BinaryConfigResponse.java | BinaryConfigResponse.create | public static BinaryResponse create(BinaryCommand command, MemcachedServer server, ErrorCode errOk, ErrorCode errNotSupp) {
if (!server.isCccpEnabled()) {
return new BinaryResponse(command, errNotSupp);
}
String config = server.getBucket().getJSON();
config = config.replaceAll(Pattern.quote(server.getHostname()),
Matcher.quoteReplacement("$HOST"));
byte[] jsBytes = config.getBytes();
ByteBuffer buf = create(command, errOk, Datatype.RAW.value(), 0, 0, jsBytes.length, 0);
buf.put(jsBytes);
buf.rewind();
return new BinaryResponse(buf);
} | java | public static BinaryResponse create(BinaryCommand command, MemcachedServer server, ErrorCode errOk, ErrorCode errNotSupp) {
if (!server.isCccpEnabled()) {
return new BinaryResponse(command, errNotSupp);
}
String config = server.getBucket().getJSON();
config = config.replaceAll(Pattern.quote(server.getHostname()),
Matcher.quoteReplacement("$HOST"));
byte[] jsBytes = config.getBytes();
ByteBuffer buf = create(command, errOk, Datatype.RAW.value(), 0, 0, jsBytes.length, 0);
buf.put(jsBytes);
buf.rewind();
return new BinaryResponse(buf);
} | [
"public",
"static",
"BinaryResponse",
"create",
"(",
"BinaryCommand",
"command",
",",
"MemcachedServer",
"server",
",",
"ErrorCode",
"errOk",
",",
"ErrorCode",
"errNotSupp",
")",
"{",
"if",
"(",
"!",
"server",
".",
"isCccpEnabled",
"(",
")",
")",
"{",
"return"... | Create a new response which contains a cluster configuration, if supported
@param command The command received
@param server The server on which the command was received
@param errOk Error code to be supplied if the configuration can be sent
@param errNotSupp Error code to be supplied if the configuration cannot
be sent
@return A response object | [
"Create",
"a",
"new",
"response",
"which",
"contains",
"a",
"cluster",
"configuration",
"if",
"supported"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/protocol/BinaryConfigResponse.java#L45-L59 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/DocumentLoader.java | DocumentLoader.loadDocuments | public void loadDocuments(String docsFile) throws IOException {
ZipFile zipFile = new ZipFile(docsFile);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
int numDocs = 0;
int numDesigns = 0;
while (entries.hasMoreElements()) {
ZipEntry ent = entries.nextElement();
String fName = ent.getName();
InputStream is = zipFile.getInputStream(ent);
String contents = ReaderUtils.fromStream(is);
Matcher mIsDoc = ptnDOCUMENT.matcher(fName);
if (mIsDoc.matches()) {
String docId = mIsDoc.group(1);
handleDocument(docId, contents);
numDocs++;
continue;
}
Matcher mIsDesign = ptnDESIGN.matcher(fName);
if (mIsDesign.matches()) {
String designName = mIsDesign.group(1);
handleDesign(designName, contents);
numDesigns++;
}
}
System.err.printf("Loaded %d documents. %d design documents%n", numDocs, numDesigns);
} | java | public void loadDocuments(String docsFile) throws IOException {
ZipFile zipFile = new ZipFile(docsFile);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
int numDocs = 0;
int numDesigns = 0;
while (entries.hasMoreElements()) {
ZipEntry ent = entries.nextElement();
String fName = ent.getName();
InputStream is = zipFile.getInputStream(ent);
String contents = ReaderUtils.fromStream(is);
Matcher mIsDoc = ptnDOCUMENT.matcher(fName);
if (mIsDoc.matches()) {
String docId = mIsDoc.group(1);
handleDocument(docId, contents);
numDocs++;
continue;
}
Matcher mIsDesign = ptnDESIGN.matcher(fName);
if (mIsDesign.matches()) {
String designName = mIsDesign.group(1);
handleDesign(designName, contents);
numDesigns++;
}
}
System.err.printf("Loaded %d documents. %d design documents%n", numDocs, numDesigns);
} | [
"public",
"void",
"loadDocuments",
"(",
"String",
"docsFile",
")",
"throws",
"IOException",
"{",
"ZipFile",
"zipFile",
"=",
"new",
"ZipFile",
"(",
"docsFile",
")",
";",
"Enumeration",
"<",
"?",
"extends",
"ZipEntry",
">",
"entries",
"=",
"zipFile",
".",
"ent... | Load documents into the bucket
@param docsFile The path to the ZIP file which contains the documents
@throws IOException if an I/O error occurs | [
"Load",
"documents",
"into",
"the",
"bucket"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/DocumentLoader.java#L88-L118 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/DocumentLoader.java | DocumentLoader.main | public static void main(String[] args) throws Exception {
String input = args[0];
File outputFile = new File(input.replace(".zip", "") + ".serialized.xz");
// Get the base name
FileOutputStream fos = new FileOutputStream(outputFile);
LZMA2Options options = new LZMA2Options(9);
XZOutputStream xzo = new XZOutputStream(fos, options);
ObjectOutputStream oos = new ObjectOutputStream(xzo);
BundleSerializer ml = new BundleSerializer();
ml.loadDocuments(input);
oos.writeObject(ml.toStore);
oos.flush();
oos.close();
} | java | public static void main(String[] args) throws Exception {
String input = args[0];
File outputFile = new File(input.replace(".zip", "") + ".serialized.xz");
// Get the base name
FileOutputStream fos = new FileOutputStream(outputFile);
LZMA2Options options = new LZMA2Options(9);
XZOutputStream xzo = new XZOutputStream(fos, options);
ObjectOutputStream oos = new ObjectOutputStream(xzo);
BundleSerializer ml = new BundleSerializer();
ml.loadDocuments(input);
oos.writeObject(ml.toStore);
oos.flush();
oos.close();
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"Exception",
"{",
"String",
"input",
"=",
"args",
"[",
"0",
"]",
";",
"File",
"outputFile",
"=",
"new",
"File",
"(",
"input",
".",
"replace",
"(",
"\".zip\"",
",",
"\... | Converts a zip file into a serialized compress resource.
@param args The ZIP file
@throws Exception if an error occurs | [
"Converts",
"a",
"zip",
"file",
"into",
"a",
"serialized",
"compress",
"resource",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/DocumentLoader.java#L186-L202 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/control/MockCommandDispatcher.java | MockCommandDispatcher.processInput | public String processInput(String input) {
JsonObject object;
try {
object = gs.fromJson(input, JsonObject.class);
} catch (Throwable t) {
return "{ \"status\" : \"fail\", \"error\" : \"Failed to parse input\" }";
}
String command = object.get("command").getAsString();
JsonObject payload;
if (!object.has("payload")) {
payload = new JsonObject();
} else {
payload = object.get("payload").getAsJsonObject();
}
CommandStatus status;
try {
status = dispatch(command, payload);
} catch (Throwable t) {
status = new CommandStatus();
status.fail(t).setPayload(payload);
}
return status.toString();
} | java | public String processInput(String input) {
JsonObject object;
try {
object = gs.fromJson(input, JsonObject.class);
} catch (Throwable t) {
return "{ \"status\" : \"fail\", \"error\" : \"Failed to parse input\" }";
}
String command = object.get("command").getAsString();
JsonObject payload;
if (!object.has("payload")) {
payload = new JsonObject();
} else {
payload = object.get("payload").getAsJsonObject();
}
CommandStatus status;
try {
status = dispatch(command, payload);
} catch (Throwable t) {
status = new CommandStatus();
status.fail(t).setPayload(payload);
}
return status.toString();
} | [
"public",
"String",
"processInput",
"(",
"String",
"input",
")",
"{",
"JsonObject",
"object",
";",
"try",
"{",
"object",
"=",
"gs",
".",
"fromJson",
"(",
"input",
",",
"JsonObject",
".",
"class",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",... | Process the input sent from the client utilizing the mock server
and return the response.
@param input the JSON encoded command from the user
@return a string to send to the client | [
"Process",
"the",
"input",
"sent",
"from",
"the",
"client",
"utilizing",
"the",
"mock",
"server",
"and",
"return",
"the",
"response",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/control/MockCommandDispatcher.java#L154-L181 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/MemcachedServer.java | MemcachedServer.main | public static void main(String[] args) {
try {
VBucketInfo vbi[] = new VBucketInfo[1024];
for (int ii = 0; ii < vbi.length; ++ii) {
vbi[ii] = new VBucketInfo();
}
MemcachedServer server = new MemcachedServer(null, null, 11211, vbi, false);
for (VBucketInfo aVbi : vbi) {
aVbi.setOwner(server);
}
server.run();
} catch (IOException e) {
Logger.getLogger(MemcachedServer.class.getName()).log(Level.SEVERE, "Fatal error! failed to create socket: ", e);
}
} | java | public static void main(String[] args) {
try {
VBucketInfo vbi[] = new VBucketInfo[1024];
for (int ii = 0; ii < vbi.length; ++ii) {
vbi[ii] = new VBucketInfo();
}
MemcachedServer server = new MemcachedServer(null, null, 11211, vbi, false);
for (VBucketInfo aVbi : vbi) {
aVbi.setOwner(server);
}
server.run();
} catch (IOException e) {
Logger.getLogger(MemcachedServer.class.getName()).log(Level.SEVERE, "Fatal error! failed to create socket: ", e);
}
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"try",
"{",
"VBucketInfo",
"vbi",
"[",
"]",
"=",
"new",
"VBucketInfo",
"[",
"1024",
"]",
";",
"for",
"(",
"int",
"ii",
"=",
"0",
";",
"ii",
"<",
"vbi",
".",
"length",
... | Program entry point that runs the memcached server as a standalone
server just like any other memcached server...
@param args Program arguments (not used) | [
"Program",
"entry",
"point",
"that",
"runs",
"the",
"memcached",
"server",
"as",
"a",
"standalone",
"server",
"just",
"like",
"any",
"other",
"memcached",
"server",
"..."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/MemcachedServer.java#L651-L665 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/views/DesignDocument.java | DesignDocument.create | public static DesignDocument create(String body, String name) throws DesignParseException {
DesignDocument doc = new DesignDocument(body);
doc.id = "_design/" + name;
doc.load();
return doc;
} | java | public static DesignDocument create(String body, String name) throws DesignParseException {
DesignDocument doc = new DesignDocument(body);
doc.id = "_design/" + name;
doc.load();
return doc;
} | [
"public",
"static",
"DesignDocument",
"create",
"(",
"String",
"body",
",",
"String",
"name",
")",
"throws",
"DesignParseException",
"{",
"DesignDocument",
"doc",
"=",
"new",
"DesignDocument",
"(",
"body",
")",
";",
"doc",
".",
"id",
"=",
"\"_design/\"",
"+",
... | Create a new design document
@param body The JSON encoded source of this design document
@param name The name of the design document. This should be the simple name, e.g. {@code beer}. If the
{@code body} contains a {@code _id} property, then that property will override
{@code name}
@return A new design document
@throws DesignParseException if a design parse error occurs | [
"Create",
"a",
"new",
"design",
"document"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/views/DesignDocument.java#L51-L56 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/util/Getopt.java | Getopt.parse | public List<Entry> parse(String[] argv) {
optind = -1;
List<Entry> ret = new ArrayList<Entry>();
int idx = 0;
while (idx < argv.length) {
if (argv[idx].equals("--")) {
// End of options!
++idx;
break;
}
if (argv[idx].charAt(0) != '-') {
// End of options
break;
}
if (argv[idx].startsWith("--")) {
idx = parseLongOption(argv, ret, idx);
} else if (argv[idx].startsWith("-")) {
idx = parseShortOption(argv, ret, idx);
} else {
break;
}
++idx;
}
if (idx != argv.length) {
optind = idx;
}
return ret;
} | java | public List<Entry> parse(String[] argv) {
optind = -1;
List<Entry> ret = new ArrayList<Entry>();
int idx = 0;
while (idx < argv.length) {
if (argv[idx].equals("--")) {
// End of options!
++idx;
break;
}
if (argv[idx].charAt(0) != '-') {
// End of options
break;
}
if (argv[idx].startsWith("--")) {
idx = parseLongOption(argv, ret, idx);
} else if (argv[idx].startsWith("-")) {
idx = parseShortOption(argv, ret, idx);
} else {
break;
}
++idx;
}
if (idx != argv.length) {
optind = idx;
}
return ret;
} | [
"public",
"List",
"<",
"Entry",
">",
"parse",
"(",
"String",
"[",
"]",
"argv",
")",
"{",
"optind",
"=",
"-",
"1",
";",
"List",
"<",
"Entry",
">",
"ret",
"=",
"new",
"ArrayList",
"<",
"Entry",
">",
"(",
")",
";",
"int",
"idx",
"=",
"0",
";",
"... | Parse the given hasArgument vector
@param argv The arguments to parse
@return The user-specified options | [
"Parse",
"the",
"given",
"hasArgument",
"vector"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/util/Getopt.java#L54-L88 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/Bucket.java | Bucket.create | public static Bucket create(CouchbaseMock mock, BucketConfiguration config) throws IOException {
switch (config.type) {
case MEMCACHED:
return new MemcachedBucket(mock, config);
case COUCHBASE:
return new CouchbaseBucket(mock, config);
default:
throw new FileNotFoundException("I don't know about this type...");
}
} | java | public static Bucket create(CouchbaseMock mock, BucketConfiguration config) throws IOException {
switch (config.type) {
case MEMCACHED:
return new MemcachedBucket(mock, config);
case COUCHBASE:
return new CouchbaseBucket(mock, config);
default:
throw new FileNotFoundException("I don't know about this type...");
}
} | [
"public",
"static",
"Bucket",
"create",
"(",
"CouchbaseMock",
"mock",
",",
"BucketConfiguration",
"config",
")",
"throws",
"IOException",
"{",
"switch",
"(",
"config",
".",
"type",
")",
"{",
"case",
"MEMCACHED",
":",
"return",
"new",
"MemcachedBucket",
"(",
"m... | Create a bucket.
@param mock The cluster this bucket is a member of
@param config The configuration for the bucket
@return The newly instantiated subclass
@throws IOException if an I/O error occurs | [
"Create",
"a",
"bucket",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/Bucket.java#L196-L205 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/Bucket.java | Bucket.getCommonConfig | protected Map<String,Object> getCommonConfig() {
Map<String,Object> mm = new HashMap<String, Object>();
mm.put("replicaNumber", numReplicas);
Map<String,Object> ramQuota = new HashMap<String, Object>();
ramQuota.put("rawRAM", 1024 * 1024 * 100);
ramQuota.put("ram", 1024 * 1024 * 100);
mm.put("quota", ramQuota);
return mm;
} | java | protected Map<String,Object> getCommonConfig() {
Map<String,Object> mm = new HashMap<String, Object>();
mm.put("replicaNumber", numReplicas);
Map<String,Object> ramQuota = new HashMap<String, Object>();
ramQuota.put("rawRAM", 1024 * 1024 * 100);
ramQuota.put("ram", 1024 * 1024 * 100);
mm.put("quota", ramQuota);
return mm;
} | [
"protected",
"Map",
"<",
"String",
",",
"Object",
">",
"getCommonConfig",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"mm",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"mm",
".",
"put",
"(",
"\"replicaNumber\... | Returns configuration information common to both Couchbase and Memcached buckets
@return The configuration object to be injected | [
"Returns",
"configuration",
"information",
"common",
"to",
"both",
"Couchbase",
"and",
"Memcached",
"buckets"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/Bucket.java#L258-L266 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/Bucket.java | Bucket.respawn | public void respawn(int index) {
configurationRwLock.writeLock().lock();
try {
if (index >= 0 && index < servers.length) {
servers[index].startup();
}
rebalance();
} finally {
Info.incrementConfigRevision();
configurationRwLock.writeLock().unlock();
}
} | java | public void respawn(int index) {
configurationRwLock.writeLock().lock();
try {
if (index >= 0 && index < servers.length) {
servers[index].startup();
}
rebalance();
} finally {
Info.incrementConfigRevision();
configurationRwLock.writeLock().unlock();
}
} | [
"public",
"void",
"respawn",
"(",
"int",
"index",
")",
"{",
"configurationRwLock",
".",
"writeLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"try",
"{",
"if",
"(",
"index",
">=",
"0",
"&&",
"index",
"<",
"servers",
".",
"length",
")",
"{",
"servers",
... | Re-Add a previously failed-over node
@param index The index to restore. This should be an index into the
{@link #servers} array. | [
"Re",
"-",
"Add",
"a",
"previously",
"failed",
"-",
"over",
"node"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/Bucket.java#L336-L347 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/Bucket.java | Bucket.rebalance | final void rebalance() {
// Let's start distribute the vbuckets across the servers
configurationRwLock.writeLock().lock();
try {
Info.incrementConfigRevision();
List<MemcachedServer> nodes = activeServers();
for (int ii = 0; ii < numVBuckets; ++ii) {
Collections.shuffle(nodes);
vbInfo[ii].setOwner(nodes.get(0));
if (nodes.size() < 2) {
continue;
}
List<MemcachedServer> replicas = nodes.subList(1, nodes.size());
if (replicas.size() > numReplicas) {
replicas = replicas.subList(0, numReplicas);
}
vbInfo[ii].setReplicas(replicas);
}
} finally {
Info.incrementConfigRevision();
configurationRwLock.writeLock().unlock();
}
} | java | final void rebalance() {
// Let's start distribute the vbuckets across the servers
configurationRwLock.writeLock().lock();
try {
Info.incrementConfigRevision();
List<MemcachedServer> nodes = activeServers();
for (int ii = 0; ii < numVBuckets; ++ii) {
Collections.shuffle(nodes);
vbInfo[ii].setOwner(nodes.get(0));
if (nodes.size() < 2) {
continue;
}
List<MemcachedServer> replicas = nodes.subList(1, nodes.size());
if (replicas.size() > numReplicas) {
replicas = replicas.subList(0, numReplicas);
}
vbInfo[ii].setReplicas(replicas);
}
} finally {
Info.incrementConfigRevision();
configurationRwLock.writeLock().unlock();
}
} | [
"final",
"void",
"rebalance",
"(",
")",
"{",
"// Let's start distribute the vbuckets across the servers",
"configurationRwLock",
".",
"writeLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"try",
"{",
"Info",
".",
"incrementConfigRevision",
"(",
")",
";",
"List",
"<",... | Issues a rebalance within the bucket. vBuckets which are mapped to failed-over
nodes are relocated with their first replica being promoted to active. | [
"Issues",
"a",
"rebalance",
"within",
"the",
"bucket",
".",
"vBuckets",
"which",
"are",
"mapped",
"to",
"failed",
"-",
"over",
"nodes",
"are",
"relocated",
"with",
"their",
"first",
"replica",
"being",
"promoted",
"to",
"active",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/Bucket.java#L391-L413 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/httpio/HandlerUtil.java | HandlerUtil.getJsonQuery | public static JsonObject getJsonQuery(URL url) throws MalformedURLException {
String query = url.getQuery();
JsonObject payload = new JsonObject();
JsonParser parser = new JsonParser();
if (query == null) {
return null;
}
for (String kv : query.split("&")) {
String[] parts = kv.split("=");
if (parts.length != 2) {
throw new MalformedURLException();
}
String optName = parts[0];
JsonElement optVal;
try {
optVal = parser.parse(URLDecoder.decode(parts[1], "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new MalformedURLException();
}
payload.add(optName, optVal);
}
return payload;
} | java | public static JsonObject getJsonQuery(URL url) throws MalformedURLException {
String query = url.getQuery();
JsonObject payload = new JsonObject();
JsonParser parser = new JsonParser();
if (query == null) {
return null;
}
for (String kv : query.split("&")) {
String[] parts = kv.split("=");
if (parts.length != 2) {
throw new MalformedURLException();
}
String optName = parts[0];
JsonElement optVal;
try {
optVal = parser.parse(URLDecoder.decode(parts[1], "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new MalformedURLException();
}
payload.add(optName, optVal);
}
return payload;
} | [
"public",
"static",
"JsonObject",
"getJsonQuery",
"(",
"URL",
"url",
")",
"throws",
"MalformedURLException",
"{",
"String",
"query",
"=",
"url",
".",
"getQuery",
"(",
")",
";",
"JsonObject",
"payload",
"=",
"new",
"JsonObject",
"(",
")",
";",
"JsonParser",
"... | Parses a url-encoded query string and
@param url The URL to decode
@return a map of keys and JSON Values
@throws MalformedURLException If one of the values is not JSON | [
"Parses",
"a",
"url",
"-",
"encoded",
"query",
"string",
"and"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/httpio/HandlerUtil.java#L89-L116 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/httpio/HandlerUtil.java | HandlerUtil.getQueryParams | public static Map<String,String> getQueryParams(String s) throws MalformedURLException {
Map<String,String> params = new HashMap<String, String>();
for (String kv : s.split("&")) {
String[] parts = kv.split("=");
if (parts.length != 2) {
throw new MalformedURLException();
}
try {
String k = URLDecoder.decode(parts[0], "UTF-8");
String v = URLDecoder.decode(parts[1], "UTF-8");
params.put(k, v);
} catch (UnsupportedEncodingException ex) {
throw new MalformedURLException(ex.getMessage());
}
}
return params;
} | java | public static Map<String,String> getQueryParams(String s) throws MalformedURLException {
Map<String,String> params = new HashMap<String, String>();
for (String kv : s.split("&")) {
String[] parts = kv.split("=");
if (parts.length != 2) {
throw new MalformedURLException();
}
try {
String k = URLDecoder.decode(parts[0], "UTF-8");
String v = URLDecoder.decode(parts[1], "UTF-8");
params.put(k, v);
} catch (UnsupportedEncodingException ex) {
throw new MalformedURLException(ex.getMessage());
}
}
return params;
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"String",
">",
"getQueryParams",
"(",
"String",
"s",
")",
"throws",
"MalformedURLException",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"params",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
... | Get traditional query parameters as a Java map
@param s The query string
@return A Java map with key-value pairs derived from the query string
@throws MalformedURLException If the query string is malformed. | [
"Get",
"traditional",
"query",
"parameters",
"as",
"a",
"Java",
"map"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/httpio/HandlerUtil.java#L124-L141 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/httpio/HandlerUtil.java | HandlerUtil.makeStringResponse | public static void makeStringResponse(HttpResponse response, String s) {
StringEntity entity = new StringEntity(s, ContentType.TEXT_PLAIN);
entity.setContentEncoding("utf-8");
response.setEntity(entity);
} | java | public static void makeStringResponse(HttpResponse response, String s) {
StringEntity entity = new StringEntity(s, ContentType.TEXT_PLAIN);
entity.setContentEncoding("utf-8");
response.setEntity(entity);
} | [
"public",
"static",
"void",
"makeStringResponse",
"(",
"HttpResponse",
"response",
",",
"String",
"s",
")",
"{",
"StringEntity",
"entity",
"=",
"new",
"StringEntity",
"(",
"s",
",",
"ContentType",
".",
"TEXT_PLAIN",
")",
";",
"entity",
".",
"setContentEncoding",... | Sets a string as the response
@param response The response object
@param s The response body | [
"Sets",
"a",
"string",
"as",
"the",
"response"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/httpio/HandlerUtil.java#L148-L152 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/httpio/HandlerUtil.java | HandlerUtil.makeResponse | public static void makeResponse(HttpResponse response, String msg, int status) {
response.setStatusCode(status);
makeStringResponse(response, msg);
} | java | public static void makeResponse(HttpResponse response, String msg, int status) {
response.setStatusCode(status);
makeStringResponse(response, msg);
} | [
"public",
"static",
"void",
"makeResponse",
"(",
"HttpResponse",
"response",
",",
"String",
"msg",
",",
"int",
"status",
")",
"{",
"response",
".",
"setStatusCode",
"(",
"status",
")",
";",
"makeStringResponse",
"(",
"response",
",",
"msg",
")",
";",
"}"
] | Sets the response body and status
@param response The response object
@param msg The response body
@param status The response status | [
"Sets",
"the",
"response",
"body",
"and",
"status"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/httpio/HandlerUtil.java#L160-L163 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/httpio/HandlerUtil.java | HandlerUtil.make400Response | public static void make400Response(HttpResponse response, String msg) {
makeResponse(response, msg, HttpStatus.SC_BAD_REQUEST);
} | java | public static void make400Response(HttpResponse response, String msg) {
makeResponse(response, msg, HttpStatus.SC_BAD_REQUEST);
} | [
"public",
"static",
"void",
"make400Response",
"(",
"HttpResponse",
"response",
",",
"String",
"msg",
")",
"{",
"makeResponse",
"(",
"response",
",",
"msg",
",",
"HttpStatus",
".",
"SC_BAD_REQUEST",
")",
";",
"}"
] | Sets a 404 not found response with a message
@param response The response object
@param msg The message | [
"Sets",
"a",
"404",
"not",
"found",
"response",
"with",
"a",
"message"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/httpio/HandlerUtil.java#L170-L172 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/httpio/HandlerUtil.java | HandlerUtil.bailResponse | public static void bailResponse(HttpContext cx, HttpResponse response) throws IOException, HttpException {
HttpServerConnection conn = getConnection(cx);
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
conn.flush();
} | java | public static void bailResponse(HttpContext cx, HttpResponse response) throws IOException, HttpException {
HttpServerConnection conn = getConnection(cx);
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
conn.flush();
} | [
"public",
"static",
"void",
"bailResponse",
"(",
"HttpContext",
"cx",
",",
"HttpResponse",
"response",
")",
"throws",
"IOException",
",",
"HttpException",
"{",
"HttpServerConnection",
"conn",
"=",
"getConnection",
"(",
"cx",
")",
";",
"conn",
".",
"sendResponseHea... | Send and flush the response object over the current connection and close the connection
@param cx The context
@param response The response object
@throws IOException if an I/O error occurs
@throws HttpException if a http error occurs | [
"Send",
"and",
"flush",
"the",
"response",
"object",
"over",
"the",
"current",
"connection",
"and",
"close",
"the",
"connection"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/httpio/HandlerUtil.java#L191-L196 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/httpio/HandlerUtil.java | HandlerUtil.getAuth | public static AuthContext getAuth(HttpContext cx, HttpRequest req) throws IOException {
AuthContext auth = (AuthContext) cx.getAttribute(HttpServer.CX_AUTH);
if (auth == null) {
Header authHdr = req.getLastHeader(HttpHeaders.AUTHORIZATION);
if (authHdr == null) {
auth = new AuthContext();
} else {
auth = new AuthContext(authHdr.getValue());
}
}
return auth;
} | java | public static AuthContext getAuth(HttpContext cx, HttpRequest req) throws IOException {
AuthContext auth = (AuthContext) cx.getAttribute(HttpServer.CX_AUTH);
if (auth == null) {
Header authHdr = req.getLastHeader(HttpHeaders.AUTHORIZATION);
if (authHdr == null) {
auth = new AuthContext();
} else {
auth = new AuthContext(authHdr.getValue());
}
}
return auth;
} | [
"public",
"static",
"AuthContext",
"getAuth",
"(",
"HttpContext",
"cx",
",",
"HttpRequest",
"req",
")",
"throws",
"IOException",
"{",
"AuthContext",
"auth",
"=",
"(",
"AuthContext",
")",
"cx",
".",
"getAttribute",
"(",
"HttpServer",
".",
"CX_AUTH",
")",
";",
... | Get any authorization credentials supplied over the connection. If no credentials were provided in the request,
an empty AuthContex is returned
@param cx The HTTP Context (from httpcomonents)
@param req The request
@return The authentication info
@throws IOException if an I/O error occurs | [
"Get",
"any",
"authorization",
"credentials",
"supplied",
"over",
"the",
"connection",
".",
"If",
"no",
"credentials",
"were",
"provided",
"in",
"the",
"request",
"an",
"empty",
"AuthContex",
"is",
"returned"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/httpio/HandlerUtil.java#L206-L217 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/views/Reducer.java | Reducer.create | public static Reducer create(String txt) {
Context cx = Context.enter();
try {
return new Reducer(txt, cx);
} finally {
Context.exit();
}
} | java | public static Reducer create(String txt) {
Context cx = Context.enter();
try {
return new Reducer(txt, cx);
} finally {
Context.exit();
}
} | [
"public",
"static",
"Reducer",
"create",
"(",
"String",
"txt",
")",
"{",
"Context",
"cx",
"=",
"Context",
".",
"enter",
"(",
")",
";",
"try",
"{",
"return",
"new",
"Reducer",
"(",
"txt",
",",
"cx",
")",
";",
"}",
"finally",
"{",
"Context",
".",
"ex... | Create a new Reducer object
@param txt The raw reduce JavaScript source
@return The compiled reduce function | [
"Create",
"a",
"new",
"Reducer",
"object"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/views/Reducer.java#L61-L68 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/httpio/HttpServer.java | HttpServer.stopServer | public void stopServer() {
shouldRun = false;
try {
listener.close();
} catch (IOException ex) {
// Don't care
}
while (true) {
synchronized (allWorkers) {
if (allWorkers.isEmpty()) {
break;
}
for (Worker w : allWorkers) {
w.stopSocket();
w.interrupt();
}
}
}
try {
listener.close();
} catch (IOException ex) {
ex.printStackTrace();
}
} | java | public void stopServer() {
shouldRun = false;
try {
listener.close();
} catch (IOException ex) {
// Don't care
}
while (true) {
synchronized (allWorkers) {
if (allWorkers.isEmpty()) {
break;
}
for (Worker w : allWorkers) {
w.stopSocket();
w.interrupt();
}
}
}
try {
listener.close();
} catch (IOException ex) {
ex.printStackTrace();
}
} | [
"public",
"void",
"stopServer",
"(",
")",
"{",
"shouldRun",
"=",
"false",
";",
"try",
"{",
"listener",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"// Don't care",
"}",
"while",
"(",
"true",
")",
"{",
"synchronized",
... | Shut down the HTTP server and all its workers, and close the listener socket. | [
"Shut",
"down",
"the",
"HTTP",
"server",
"and",
"all",
"its",
"workers",
"and",
"close",
"the",
"listener",
"socket",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/httpio/HttpServer.java#L264-L288 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/client/RestAPIUtil.java | RestAPIUtil.defineDesignDocument | public static void defineDesignDocument(CouchbaseMock mock, String designName, String contents, String bucketName) throws IOException {
URL url = getDesignURL(mock, designName, bucketName);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
setAuthHeaders(mock, bucketName, conn);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
osw.write(contents);
osw.flush();
osw.close();
try {
conn.getInputStream().close();
} catch (IOException ex) {
InputStream es = conn.getErrorStream();
if (es != null) {
System.err.printf("Problem creating view: %s%n", ReaderUtils.fromStream(es));
} else {
System.err.printf("Error stream is null!\n");
}
throw ex;
}
} | java | public static void defineDesignDocument(CouchbaseMock mock, String designName, String contents, String bucketName) throws IOException {
URL url = getDesignURL(mock, designName, bucketName);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
setAuthHeaders(mock, bucketName, conn);
conn.setRequestMethod("PUT");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
osw.write(contents);
osw.flush();
osw.close();
try {
conn.getInputStream().close();
} catch (IOException ex) {
InputStream es = conn.getErrorStream();
if (es != null) {
System.err.printf("Problem creating view: %s%n", ReaderUtils.fromStream(es));
} else {
System.err.printf("Error stream is null!\n");
}
throw ex;
}
} | [
"public",
"static",
"void",
"defineDesignDocument",
"(",
"CouchbaseMock",
"mock",
",",
"String",
"designName",
",",
"String",
"contents",
",",
"String",
"bucketName",
")",
"throws",
"IOException",
"{",
"URL",
"url",
"=",
"getDesignURL",
"(",
"mock",
",",
"design... | Utility method to define a view | [
"Utility",
"method",
"to",
"define",
"a",
"view"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/client/RestAPIUtil.java#L53-L79 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/http/ControlHandler.java | ControlHandler.sendHelpText | private static void sendHelpText(HttpResponse response, int code) throws IOException {
HandlerUtil.makeStringResponse(response, MockHelpCommandHandler.getIndentedHelp());
response.setStatusCode(code);
} | java | private static void sendHelpText(HttpResponse response, int code) throws IOException {
HandlerUtil.makeStringResponse(response, MockHelpCommandHandler.getIndentedHelp());
response.setStatusCode(code);
} | [
"private",
"static",
"void",
"sendHelpText",
"(",
"HttpResponse",
"response",
",",
"int",
"code",
")",
"throws",
"IOException",
"{",
"HandlerUtil",
".",
"makeStringResponse",
"(",
"response",
",",
"MockHelpCommandHandler",
".",
"getIndentedHelp",
"(",
")",
")",
";... | Sends a help text with the provided code
@param response The response
@param code The HTTP status code to be used in the response | [
"Sends",
"a",
"help",
"text",
"with",
"the",
"provided",
"code"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/http/ControlHandler.java#L59-L62 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/MutationInfoWriter.java | MutationInfoWriter.write | public void write(ByteBuffer bb, VBucketCoordinates coords) {
if (!enabled) {
return;
}
bb.putLong(24, coords.getUuid());
bb.putLong(32, coords.getSeqno());
} | java | public void write(ByteBuffer bb, VBucketCoordinates coords) {
if (!enabled) {
return;
}
bb.putLong(24, coords.getUuid());
bb.putLong(32, coords.getSeqno());
} | [
"public",
"void",
"write",
"(",
"ByteBuffer",
"bb",
",",
"VBucketCoordinates",
"coords",
")",
"{",
"if",
"(",
"!",
"enabled",
")",
"{",
"return",
";",
"}",
"bb",
".",
"putLong",
"(",
"24",
",",
"coords",
".",
"getUuid",
"(",
")",
")",
";",
"bb",
".... | Write the appropriate mutation information into the output buffers.
This method will do nothing if extra mutation information is not enabled.
@param bb The output buffer
@param coords The coordinates to write | [
"Write",
"the",
"appropriate",
"mutation",
"information",
"into",
"the",
"output",
"buffers",
".",
"This",
"method",
"will",
"do",
"nothing",
"if",
"extra",
"mutation",
"information",
"is",
"not",
"enabled",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/MutationInfoWriter.java#L50-L57 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/CouchbaseMock.java | CouchbaseMock.startHarakiriMonitor | public void startHarakiriMonitor(InetSocketAddress address, boolean terminate) throws IOException {
if (terminate) {
harakiriMonitor.setTemrinateAction(new Callable() {
@Override
public Object call() throws Exception {
System.exit(1);
return null;
}
});
}
harakiriMonitor.connect(address.getHostName(), address.getPort());
harakiriMonitor.start();
} | java | public void startHarakiriMonitor(InetSocketAddress address, boolean terminate) throws IOException {
if (terminate) {
harakiriMonitor.setTemrinateAction(new Callable() {
@Override
public Object call() throws Exception {
System.exit(1);
return null;
}
});
}
harakiriMonitor.connect(address.getHostName(), address.getPort());
harakiriMonitor.start();
} | [
"public",
"void",
"startHarakiriMonitor",
"(",
"InetSocketAddress",
"address",
",",
"boolean",
"terminate",
")",
"throws",
"IOException",
"{",
"if",
"(",
"terminate",
")",
"{",
"harakiriMonitor",
".",
"setTemrinateAction",
"(",
"new",
"Callable",
"(",
")",
"{",
... | Tell the harakiri monitor to connect to the given address.
@param address The address the monitor should connect to
@param terminate Whether the application should exit when a disconnect is detected on the socket
@throws IOException If the monitor could not listen on the given port, or if the monitor is already listening | [
"Tell",
"the",
"harakiri",
"monitor",
"to",
"connect",
"to",
"the",
"given",
"address",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/CouchbaseMock.java#L90-L103 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/CouchbaseMock.java | CouchbaseMock.createDefaultConfig | private static BucketConfiguration createDefaultConfig(String hostname, int numNodes, int bucketStartPort, int numVBuckets, int numReplicas) {
BucketConfiguration defaultConfig = new BucketConfiguration();
defaultConfig.type = BucketType.COUCHBASE;
defaultConfig.hostname = hostname;
defaultConfig.numNodes = numNodes;
if (numReplicas > -1) {
defaultConfig.numReplicas = numReplicas;
}
defaultConfig.bucketStartPort = bucketStartPort;
defaultConfig.numVBuckets = numVBuckets;
return defaultConfig;
} | java | private static BucketConfiguration createDefaultConfig(String hostname, int numNodes, int bucketStartPort, int numVBuckets, int numReplicas) {
BucketConfiguration defaultConfig = new BucketConfiguration();
defaultConfig.type = BucketType.COUCHBASE;
defaultConfig.hostname = hostname;
defaultConfig.numNodes = numNodes;
if (numReplicas > -1) {
defaultConfig.numReplicas = numReplicas;
}
defaultConfig.bucketStartPort = bucketStartPort;
defaultConfig.numVBuckets = numVBuckets;
return defaultConfig;
} | [
"private",
"static",
"BucketConfiguration",
"createDefaultConfig",
"(",
"String",
"hostname",
",",
"int",
"numNodes",
",",
"int",
"bucketStartPort",
",",
"int",
"numVBuckets",
",",
"int",
"numReplicas",
")",
"{",
"BucketConfiguration",
"defaultConfig",
"=",
"new",
"... | Initializes the default configuration from the command line parameters. This is present in order to allow the
super constructor to be the first statement | [
"Initializes",
"the",
"default",
"configuration",
"from",
"the",
"command",
"line",
"parameters",
".",
"This",
"is",
"present",
"in",
"order",
"to",
"allow",
"the",
"super",
"constructor",
"to",
"be",
"the",
"first",
"statement"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/CouchbaseMock.java#L215-L227 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/CouchbaseMock.java | CouchbaseMock.getCarrierPort | public int getCarrierPort(String bucketName) {
Bucket bucket = buckets.get(bucketName);
if (null == bucket) {
// Buckets are created when the mock is started. Calling getCarrierPort()
// before the mock has been started makes no sense.
throw new RuntimeException("Bucket does not exist. Has the mock been started?");
}
return bucket.getCarrierPort();
} | java | public int getCarrierPort(String bucketName) {
Bucket bucket = buckets.get(bucketName);
if (null == bucket) {
// Buckets are created when the mock is started. Calling getCarrierPort()
// before the mock has been started makes no sense.
throw new RuntimeException("Bucket does not exist. Has the mock been started?");
}
return bucket.getCarrierPort();
} | [
"public",
"int",
"getCarrierPort",
"(",
"String",
"bucketName",
")",
"{",
"Bucket",
"bucket",
"=",
"buckets",
".",
"get",
"(",
"bucketName",
")",
";",
"if",
"(",
"null",
"==",
"bucket",
")",
"{",
"// Buckets are created when the mock is started. Calling getCarrierPo... | Get the carrier port for a bucket.
@param bucketName The bucket name to fetch the carrier port for.
@return The carrier port. | [
"Get",
"the",
"carrier",
"port",
"for",
"a",
"bucket",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/CouchbaseMock.java#L293-L301 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/CouchbaseMock.java | CouchbaseMock.createBucket | public void createBucket(BucketConfiguration config) throws BucketAlreadyExistsException, IOException {
if (!config.validate()) {
throw new IllegalArgumentException("Invalid bucket configuration");
}
synchronized (buckets) {
if (buckets.containsKey(config.name)) {
throw new BucketAlreadyExistsException(config.name);
}
Bucket bucket = Bucket.create(this, config);
BucketAdminServer adminServer = new BucketAdminServer(bucket, httpServer, this);
adminServer.register();
bucket.setAdminServer(adminServer);
HttpAuthVerifier verifier = new HttpAuthVerifier(bucket, authenticator);
if (config.type == BucketType.COUCHBASE) {
CAPIServer capi = new CAPIServer(bucket, verifier);
capi.register(httpServer);
bucket.setCAPIServer(capi);
}
buckets.put(config.name, bucket);
bucket.start();
}
} | java | public void createBucket(BucketConfiguration config) throws BucketAlreadyExistsException, IOException {
if (!config.validate()) {
throw new IllegalArgumentException("Invalid bucket configuration");
}
synchronized (buckets) {
if (buckets.containsKey(config.name)) {
throw new BucketAlreadyExistsException(config.name);
}
Bucket bucket = Bucket.create(this, config);
BucketAdminServer adminServer = new BucketAdminServer(bucket, httpServer, this);
adminServer.register();
bucket.setAdminServer(adminServer);
HttpAuthVerifier verifier = new HttpAuthVerifier(bucket, authenticator);
if (config.type == BucketType.COUCHBASE) {
CAPIServer capi = new CAPIServer(bucket, verifier);
capi.register(httpServer);
bucket.setCAPIServer(capi);
}
buckets.put(config.name, bucket);
bucket.start();
}
} | [
"public",
"void",
"createBucket",
"(",
"BucketConfiguration",
"config",
")",
"throws",
"BucketAlreadyExistsException",
",",
"IOException",
"{",
"if",
"(",
"!",
"config",
".",
"validate",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Inval... | Create a new bucket, and start it.
@param config The bucket configuration to use
@throws BucketAlreadyExistsException If the bucket already exists
@throws IOException If an I/O error occurs | [
"Create",
"a",
"new",
"bucket",
"and",
"start",
"it",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/CouchbaseMock.java#L326-L352 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/CouchbaseMock.java | CouchbaseMock.removeBucket | public void removeBucket(String name) throws FileNotFoundException {
Bucket bucket;
synchronized (buckets) {
if (!buckets.containsKey(name)) {
throw new FileNotFoundException("No such bucket: "+ name);
}
bucket = buckets.remove(name);
}
CAPIServer capi = bucket.getCAPIServer();
if (capi != null) {
capi.shutdown();
}
BucketAdminServer adminServer = bucket.getAdminServer();
if (adminServer != null) {
adminServer.shutdown();
}
bucket.stop();
} | java | public void removeBucket(String name) throws FileNotFoundException {
Bucket bucket;
synchronized (buckets) {
if (!buckets.containsKey(name)) {
throw new FileNotFoundException("No such bucket: "+ name);
}
bucket = buckets.remove(name);
}
CAPIServer capi = bucket.getCAPIServer();
if (capi != null) {
capi.shutdown();
}
BucketAdminServer adminServer = bucket.getAdminServer();
if (adminServer != null) {
adminServer.shutdown();
}
bucket.stop();
} | [
"public",
"void",
"removeBucket",
"(",
"String",
"name",
")",
"throws",
"FileNotFoundException",
"{",
"Bucket",
"bucket",
";",
"synchronized",
"(",
"buckets",
")",
"{",
"if",
"(",
"!",
"buckets",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"throw",
"ne... | Destroy a bucket
@param name The name of the bucket to remove
@throws FileNotFoundException If the bucket does not exist | [
"Destroy",
"a",
"bucket"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/CouchbaseMock.java#L359-L376 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/CouchbaseMock.java | CouchbaseMock.start | private void start(String docsFile, String monitorAddress, boolean useBeerSample) throws IOException {
try {
if (port == 0) {
ServerSocketChannel ch = ServerSocketChannel.open();
ch.socket().bind(new InetSocketAddress(0));
port = ch.socket().getLocalPort();
if (monitorAddress == null && debug) {
System.out.println("port=" + port);
}
httpServer.bind(ch);
} else {
httpServer.bind(new InetSocketAddress(port));
}
} catch (IOException ex) {
Logger.getLogger(CouchbaseMock.class.getName()).log(Level.SEVERE, null, ex);
System.exit(-1);
}
for (BucketConfiguration config : initialConfigs.values()) {
try {
createBucket(config);
} catch (BucketAlreadyExistsException ex) {
throw new IOException(ex);
}
}
httpServer.start();
// See if we need to load documents:
if (docsFile != null) {
DocumentLoader loader = new DocumentLoader(this, "default");
loader.loadDocuments(docsFile);
} else if (useBeerSample) {
RestAPIUtil.loadBeerSample(this);
}
if (monitorAddress != null) {
startHarakiriMonitor(monitorAddress, true);
} else if (debug) {
StringBuilder wireshark = new StringBuilder("couchbase && (");
System.out.println("\nConnection strings:");
for (Bucket bucket : getBuckets().values()) {
System.out.println("couchbase://127.0.0.1:" + port + "=http/" + bucket.getName());
StringBuilder connstr = new StringBuilder("couchbase://");
for (MemcachedServer server : bucket.getServers()) {
connstr.append(server.getHostname())
.append(":")
.append(server.getPort())
.append("=mcd,");
wireshark.append("tcp.port == ").append(server.getPort()).append(" || ");
}
connstr.replace(connstr.length() - 1, connstr.length(), "");
connstr.append("/").append(bucket.getName());
System.out.println(connstr);
}
wireshark.replace(wireshark.length() - 4, wireshark.length(), "");
wireshark.append(")");
System.out.println("\nWireshark filters:");
System.out.println("http && tcp.port == " + port);
System.out.println(wireshark);
}
startupLatch.countDown();
} | java | private void start(String docsFile, String monitorAddress, boolean useBeerSample) throws IOException {
try {
if (port == 0) {
ServerSocketChannel ch = ServerSocketChannel.open();
ch.socket().bind(new InetSocketAddress(0));
port = ch.socket().getLocalPort();
if (monitorAddress == null && debug) {
System.out.println("port=" + port);
}
httpServer.bind(ch);
} else {
httpServer.bind(new InetSocketAddress(port));
}
} catch (IOException ex) {
Logger.getLogger(CouchbaseMock.class.getName()).log(Level.SEVERE, null, ex);
System.exit(-1);
}
for (BucketConfiguration config : initialConfigs.values()) {
try {
createBucket(config);
} catch (BucketAlreadyExistsException ex) {
throw new IOException(ex);
}
}
httpServer.start();
// See if we need to load documents:
if (docsFile != null) {
DocumentLoader loader = new DocumentLoader(this, "default");
loader.loadDocuments(docsFile);
} else if (useBeerSample) {
RestAPIUtil.loadBeerSample(this);
}
if (monitorAddress != null) {
startHarakiriMonitor(monitorAddress, true);
} else if (debug) {
StringBuilder wireshark = new StringBuilder("couchbase && (");
System.out.println("\nConnection strings:");
for (Bucket bucket : getBuckets().values()) {
System.out.println("couchbase://127.0.0.1:" + port + "=http/" + bucket.getName());
StringBuilder connstr = new StringBuilder("couchbase://");
for (MemcachedServer server : bucket.getServers()) {
connstr.append(server.getHostname())
.append(":")
.append(server.getPort())
.append("=mcd,");
wireshark.append("tcp.port == ").append(server.getPort()).append(" || ");
}
connstr.replace(connstr.length() - 1, connstr.length(), "");
connstr.append("/").append(bucket.getName());
System.out.println(connstr);
}
wireshark.replace(wireshark.length() - 4, wireshark.length(), "");
wireshark.append(")");
System.out.println("\nWireshark filters:");
System.out.println("http && tcp.port == " + port);
System.out.println(wireshark);
}
startupLatch.countDown();
} | [
"private",
"void",
"start",
"(",
"String",
"docsFile",
",",
"String",
"monitorAddress",
",",
"boolean",
"useBeerSample",
")",
"throws",
"IOException",
"{",
"try",
"{",
"if",
"(",
"port",
"==",
"0",
")",
"{",
"ServerSocketChannel",
"ch",
"=",
"ServerSocketChann... | Used for the command line, this ensures that the CountDownLatch object is only set to 0
when all the command line parameters have been initialized; so that when the monitor
finally sends the port over the socket, all the items will have already been initialized.
@param docsFile Document file to load
@param monitorAddress Monitor address
@param useBeerSample Whether to load the beer-sample bucket
@throws IOException if an I/O error occurs | [
"Used",
"for",
"the",
"command",
"line",
"this",
"ensures",
"that",
"the",
"CountDownLatch",
"object",
"is",
"only",
"set",
"to",
"0",
"when",
"all",
"the",
"command",
"line",
"parameters",
"have",
"been",
"initialized",
";",
"so",
"that",
"when",
"the",
"... | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/CouchbaseMock.java#L387-L449 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/client/Retryer.java | Retryer.run | public void run() throws Exception {
// Send the initial command:
client.sendRequest(cmd);
long endTime = System.currentTimeMillis() + spec.getMaxDuration();
// Wait until the 'after' time
Thread.sleep(spec.getAfter());
int numAttempts = 0;
long now = System.currentTimeMillis();
while (now < endTime) {
client.sendRequest(cmd);
now = System.currentTimeMillis();
numAttempts ++;
// See how to retry:
long sleepTime = 0;
if (spec.isConstant()) {
sleepTime = spec.getInterval();
} else if (spec.isLinear()) {
sleepTime = spec.getInterval() * numAttempts;
} else if (spec.isExponential()) {
sleepTime = (long) Math.pow(spec.getInterval(), numAttempts);
}
if (spec.getCeil() > 0) {
sleepTime = Math.min(spec.getCeil(), sleepTime);
}
if (now + sleepTime > endTime) {
break;
} else {
accuSleep(sleepTime);
now = System.currentTimeMillis();
}
}
} | java | public void run() throws Exception {
// Send the initial command:
client.sendRequest(cmd);
long endTime = System.currentTimeMillis() + spec.getMaxDuration();
// Wait until the 'after' time
Thread.sleep(spec.getAfter());
int numAttempts = 0;
long now = System.currentTimeMillis();
while (now < endTime) {
client.sendRequest(cmd);
now = System.currentTimeMillis();
numAttempts ++;
// See how to retry:
long sleepTime = 0;
if (spec.isConstant()) {
sleepTime = spec.getInterval();
} else if (spec.isLinear()) {
sleepTime = spec.getInterval() * numAttempts;
} else if (spec.isExponential()) {
sleepTime = (long) Math.pow(spec.getInterval(), numAttempts);
}
if (spec.getCeil() > 0) {
sleepTime = Math.min(spec.getCeil(), sleepTime);
}
if (now + sleepTime > endTime) {
break;
} else {
accuSleep(sleepTime);
now = System.currentTimeMillis();
}
}
} | [
"public",
"void",
"run",
"(",
")",
"throws",
"Exception",
"{",
"// Send the initial command:",
"client",
".",
"sendRequest",
"(",
"cmd",
")",
";",
"long",
"endTime",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"+",
"spec",
".",
"getMaxDuration",
"(",
... | Runs until the retry duration is reached
@throws Exception if an error occurs | [
"Runs",
"until",
"the",
"retry",
"duration",
"is",
"reached"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/client/Retryer.java#L47-L86 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/MemcachedConnection.java | MemcachedConnection.step | public void step() throws IOException {
if (closed) {
throw new ClosedChannelException();
}
if (input.position() == header.length) {
if (command == null) {
command = CommandFactory.create(input);
}
if (command.complete()) {
command.process();
protocolHandler.execute(command, this);
command = null;
input.rewind();
}
}
} | java | public void step() throws IOException {
if (closed) {
throw new ClosedChannelException();
}
if (input.position() == header.length) {
if (command == null) {
command = CommandFactory.create(input);
}
if (command.complete()) {
command.process();
protocolHandler.execute(command, this);
command = null;
input.rewind();
}
}
} | [
"public",
"void",
"step",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"closed",
")",
"{",
"throw",
"new",
"ClosedChannelException",
"(",
")",
";",
"}",
"if",
"(",
"input",
".",
"position",
"(",
")",
"==",
"header",
".",
"length",
")",
"{",
"if... | Attempt to process a single command from the input buffer. Note this does
not actually read from the socket.
@throws IOException if the client has been closed | [
"Attempt",
"to",
"process",
"a",
"single",
"command",
"from",
"the",
"input",
"buffer",
".",
"Note",
"this",
"does",
"not",
"actually",
"read",
"from",
"the",
"socket",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/MemcachedConnection.java#L61-L77 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/MemcachedConnection.java | MemcachedConnection.hasOutput | boolean hasOutput() {
if (pending == null) {
return false;
}
if (pending.isEmpty()) {
return false;
}
if (!pending.get(0).hasRemaining()) {
return false;
}
return true;
} | java | boolean hasOutput() {
if (pending == null) {
return false;
}
if (pending.isEmpty()) {
return false;
}
if (!pending.get(0).hasRemaining()) {
return false;
}
return true;
} | [
"boolean",
"hasOutput",
"(",
")",
"{",
"if",
"(",
"pending",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"pending",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"pending",
".",
"get",
"(",
... | Determines whether this connection has pending responses to be sent
@return true there are pending responses | [
"Determines",
"whether",
"this",
"connection",
"has",
"pending",
"responses",
"to",
"be",
"sent"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/MemcachedConnection.java#L97-L110 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/MemcachedConnection.java | MemcachedConnection.returnOutputContext | public void returnOutputContext(OutputContext ctx) {
List<ByteBuffer> remaining = ctx.releaseRemaining();
if (pending == null) {
pending = remaining;
} else {
List<ByteBuffer> tmp = pending;
pending = remaining;
pending.addAll(tmp);
}
} | java | public void returnOutputContext(OutputContext ctx) {
List<ByteBuffer> remaining = ctx.releaseRemaining();
if (pending == null) {
pending = remaining;
} else {
List<ByteBuffer> tmp = pending;
pending = remaining;
pending.addAll(tmp);
}
} | [
"public",
"void",
"returnOutputContext",
"(",
"OutputContext",
"ctx",
")",
"{",
"List",
"<",
"ByteBuffer",
">",
"remaining",
"=",
"ctx",
".",
"releaseRemaining",
"(",
")",
";",
"if",
"(",
"pending",
"==",
"null",
")",
"{",
"pending",
"=",
"remaining",
";",... | Re-transfer ownership of a given output buffer to the connection
@param ctx An OutputContext previously returned by {@link #borrowOutputContext()} | [
"Re",
"-",
"transfer",
"ownership",
"of",
"a",
"given",
"output",
"buffer",
"to",
"the",
"connection"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/MemcachedConnection.java#L148-L157 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/MemcachedConnection.java | MemcachedConnection.setSupportedFeatures | void setSupportedFeatures(boolean[] input) {
if (input.length != supportedFeatures.length) {
throw new IllegalArgumentException("Bad features length!");
}
// Scan through all other features and disable them unless they are supported
for (int i = 0; i < input.length; i++) {
BinaryHelloCommand.Feature feature = BinaryHelloCommand.Feature.valueOf(i);
if (feature == null) {
supportedFeatures[i] = false;
continue;
}
switch (feature) {
case MUTATION_SEQNO:
case XERROR:
case XATTR:
case SELECT_BUCKET:
case TRACING:
supportedFeatures[i] = input[i];
break;
case SNAPPY:
supportedFeatures[i] = input[i] && server.getCompression() != CompressionMode.DISABLED;
break;
default:
supportedFeatures[i] = false;
break;
}
}
// Post-processing
if (supportedFeatures[BinaryHelloCommand.Feature.MUTATION_SEQNO.getValue()]) {
miw.setEnabled(true);
} else {
miw.setEnabled(false);
}
} | java | void setSupportedFeatures(boolean[] input) {
if (input.length != supportedFeatures.length) {
throw new IllegalArgumentException("Bad features length!");
}
// Scan through all other features and disable them unless they are supported
for (int i = 0; i < input.length; i++) {
BinaryHelloCommand.Feature feature = BinaryHelloCommand.Feature.valueOf(i);
if (feature == null) {
supportedFeatures[i] = false;
continue;
}
switch (feature) {
case MUTATION_SEQNO:
case XERROR:
case XATTR:
case SELECT_BUCKET:
case TRACING:
supportedFeatures[i] = input[i];
break;
case SNAPPY:
supportedFeatures[i] = input[i] && server.getCompression() != CompressionMode.DISABLED;
break;
default:
supportedFeatures[i] = false;
break;
}
}
// Post-processing
if (supportedFeatures[BinaryHelloCommand.Feature.MUTATION_SEQNO.getValue()]) {
miw.setEnabled(true);
} else {
miw.setEnabled(false);
}
} | [
"void",
"setSupportedFeatures",
"(",
"boolean",
"[",
"]",
"input",
")",
"{",
"if",
"(",
"input",
".",
"length",
"!=",
"supportedFeatures",
".",
"length",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Bad features length!\"",
")",
";",
"}",
"// ... | Sets the supported features from a HELLO command.
Note that the actual enabled features will be the ones supported by the mock
and also supported by the client. Currently the only supported feature is
MUTATION_SEQNO.
@param input The features requested by the client. | [
"Sets",
"the",
"supported",
"features",
"from",
"a",
"HELLO",
"command",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/MemcachedConnection.java#L215-L253 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/OutputContext.java | OutputContext.getIov | public ByteBuffer[] getIov() {
if (buffers.size() == 1) {
singleArray[0] = buffers.get(0);
return singleArray;
}
return buffers.toArray(new ByteBuffer[buffers.size()]);
} | java | public ByteBuffer[] getIov() {
if (buffers.size() == 1) {
singleArray[0] = buffers.get(0);
return singleArray;
}
return buffers.toArray(new ByteBuffer[buffers.size()]);
} | [
"public",
"ByteBuffer",
"[",
"]",
"getIov",
"(",
")",
"{",
"if",
"(",
"buffers",
".",
"size",
"(",
")",
"==",
"1",
")",
"{",
"singleArray",
"[",
"0",
"]",
"=",
"buffers",
".",
"get",
"(",
"0",
")",
";",
"return",
"singleArray",
";",
"}",
"return"... | Get an array of buffers representing all the active chunks
@return An array of buffers | [
"Get",
"an",
"array",
"of",
"buffers",
"representing",
"all",
"the",
"active",
"chunks"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/OutputContext.java#L37-L43 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/OutputContext.java | OutputContext.getSlice | public OutputContext getSlice(int limit) {
List<ByteBuffer> newBufs = new LinkedList<ByteBuffer>();
ByteBuffer buf = ByteBuffer.allocate(limit);
Iterator<ByteBuffer> iter = buffers.iterator();
while (iter.hasNext() && buf.position() < buf.limit()) {
ByteBuffer cur = iter.next();
int diff = buf.limit() - buf.position();
if (diff > cur.limit()) {
buf.put(cur);
iter.remove();
} else {
ByteBuffer slice = cur.duplicate();
slice.limit(diff);
buf.put(slice);
}
}
return new OutputContext(newBufs);
} | java | public OutputContext getSlice(int limit) {
List<ByteBuffer> newBufs = new LinkedList<ByteBuffer>();
ByteBuffer buf = ByteBuffer.allocate(limit);
Iterator<ByteBuffer> iter = buffers.iterator();
while (iter.hasNext() && buf.position() < buf.limit()) {
ByteBuffer cur = iter.next();
int diff = buf.limit() - buf.position();
if (diff > cur.limit()) {
buf.put(cur);
iter.remove();
} else {
ByteBuffer slice = cur.duplicate();
slice.limit(diff);
buf.put(slice);
}
}
return new OutputContext(newBufs);
} | [
"public",
"OutputContext",
"getSlice",
"(",
"int",
"limit",
")",
"{",
"List",
"<",
"ByteBuffer",
">",
"newBufs",
"=",
"new",
"LinkedList",
"<",
"ByteBuffer",
">",
"(",
")",
";",
"ByteBuffer",
"buf",
"=",
"ByteBuffer",
".",
"allocate",
"(",
"limit",
")",
... | Get an OutputBuffer containing a subset of the current one
@param limit How many bytes should be available
@return a new OutputContext | [
"Get",
"an",
"OutputBuffer",
"containing",
"a",
"subset",
"of",
"the",
"current",
"one"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/OutputContext.java#L60-L78 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/OutputContext.java | OutputContext.updateBytesSent | public void updateBytesSent(long num) {
Iterator<ByteBuffer> iter = buffers.iterator();
while (iter.hasNext()) {
ByteBuffer cur = iter.next();
if (cur.hasRemaining()) {
break;
}
iter.remove();
}
} | java | public void updateBytesSent(long num) {
Iterator<ByteBuffer> iter = buffers.iterator();
while (iter.hasNext()) {
ByteBuffer cur = iter.next();
if (cur.hasRemaining()) {
break;
}
iter.remove();
}
} | [
"public",
"void",
"updateBytesSent",
"(",
"long",
"num",
")",
"{",
"Iterator",
"<",
"ByteBuffer",
">",
"iter",
"=",
"buffers",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"ByteBuffer",
"cur",
"=",
"iter",
... | Indicate that some data has been flushed to the network
@param num ignored for now. This is because each individual {@link java.nio.ByteBuffer} keeps track
of how many of its bytes were sent | [
"Indicate",
"that",
"some",
"data",
"has",
"been",
"flushed",
"to",
"the",
"network"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/OutputContext.java#L85-L95 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/OutputContext.java | OutputContext.releaseRemaining | public List<ByteBuffer> releaseRemaining() {
List<ByteBuffer> ret = buffers;
buffers = null;
return ret;
} | java | public List<ByteBuffer> releaseRemaining() {
List<ByteBuffer> ret = buffers;
buffers = null;
return ret;
} | [
"public",
"List",
"<",
"ByteBuffer",
">",
"releaseRemaining",
"(",
")",
"{",
"List",
"<",
"ByteBuffer",
">",
"ret",
"=",
"buffers",
";",
"buffers",
"=",
"null",
";",
"return",
"ret",
";",
"}"
] | Truncate the output. This will empty the list of chunks
@return The list of remaining chunks. | [
"Truncate",
"the",
"output",
".",
"This",
"will",
"empty",
"the",
"list",
"of",
"chunks"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/OutputContext.java#L110-L114 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/VBucketStore.java | VBucketStore.incrCoords | private MutationStatus incrCoords(KeySpec ks) {
final StorageVBucketCoordinates curCoord;
synchronized (vbCoords) {
curCoord = vbCoords[ks.vbId];
}
long seq = curCoord.incrSeqno();
long uuid = curCoord.getUuid();
VBucketCoordinates coord = new BasicVBucketCoordinates(uuid, seq);
return new MutationStatus(coord);
} | java | private MutationStatus incrCoords(KeySpec ks) {
final StorageVBucketCoordinates curCoord;
synchronized (vbCoords) {
curCoord = vbCoords[ks.vbId];
}
long seq = curCoord.incrSeqno();
long uuid = curCoord.getUuid();
VBucketCoordinates coord = new BasicVBucketCoordinates(uuid, seq);
return new MutationStatus(coord);
} | [
"private",
"MutationStatus",
"incrCoords",
"(",
"KeySpec",
"ks",
")",
"{",
"final",
"StorageVBucketCoordinates",
"curCoord",
";",
"synchronized",
"(",
"vbCoords",
")",
"{",
"curCoord",
"=",
"vbCoords",
"[",
"ks",
".",
"vbId",
"]",
";",
"}",
"long",
"seq",
"=... | Increments the current coordinates for a new mutation.
@param ks The key spec containing the vBucket ID whose coordinates should be increases
@return A status object. | [
"Increments",
"the",
"current",
"coordinates",
"for",
"a",
"new",
"mutation",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/VBucketStore.java#L93-L103 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/VBucketStore.java | VBucketStore.forceStorageMutation | void forceStorageMutation(Item itm, VBucketCoordinates coords) {
forceMutation(itm.getKeySpec().vbId, itm, coords, false);
} | java | void forceStorageMutation(Item itm, VBucketCoordinates coords) {
forceMutation(itm.getKeySpec().vbId, itm, coords, false);
} | [
"void",
"forceStorageMutation",
"(",
"Item",
"itm",
",",
"VBucketCoordinates",
"coords",
")",
"{",
"forceMutation",
"(",
"itm",
".",
"getKeySpec",
"(",
")",
".",
"vbId",
",",
"itm",
",",
"coords",
",",
"false",
")",
";",
"}"
] | Force a storage of an item to the cache.
This assumes the current object belongs to a replica, as it will blindly
assume information passed here is authoritative.
@param itm The item to mutate (should be a copy of the original)
@param coords Coordinate info | [
"Force",
"a",
"storage",
"of",
"an",
"item",
"to",
"the",
"cache",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/VBucketStore.java#L312-L314 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/VBucketStore.java | VBucketStore.forceDeleteMutation | void forceDeleteMutation(Item itm, VBucketCoordinates coords) {
forceMutation(itm.getKeySpec().vbId, itm, coords, true);
} | java | void forceDeleteMutation(Item itm, VBucketCoordinates coords) {
forceMutation(itm.getKeySpec().vbId, itm, coords, true);
} | [
"void",
"forceDeleteMutation",
"(",
"Item",
"itm",
",",
"VBucketCoordinates",
"coords",
")",
"{",
"forceMutation",
"(",
"itm",
".",
"getKeySpec",
"(",
")",
".",
"vbId",
",",
"itm",
",",
"coords",
",",
"true",
")",
";",
"}"
] | Forces the deletion of an item from the case.
@see #forceStorageMutation(Item, VBucketCoordinates)
@param itm
@param coords | [
"Forces",
"the",
"deletion",
"of",
"an",
"item",
"from",
"the",
"case",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/VBucketStore.java#L323-L325 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/memcached/VBucketStore.java | VBucketStore.convertExpiryTime | public static int convertExpiryTime(int original) {
if (original == 0) {
return original;
} else if (original > THIRTY_DAYS) {
return original + (int)Info.getClockOffset();
}
return (int)((new Date().getTime() / 1000) + original + Info.getClockOffset());
} | java | public static int convertExpiryTime(int original) {
if (original == 0) {
return original;
} else if (original > THIRTY_DAYS) {
return original + (int)Info.getClockOffset();
}
return (int)((new Date().getTime() / 1000) + original + Info.getClockOffset());
} | [
"public",
"static",
"int",
"convertExpiryTime",
"(",
"int",
"original",
")",
"{",
"if",
"(",
"original",
"==",
"0",
")",
"{",
"return",
"original",
";",
"}",
"else",
"if",
"(",
"original",
">",
"THIRTY_DAYS",
")",
"{",
"return",
"original",
"+",
"(",
"... | Converts an expiration value to an absolute Unix timestamp.
@param original The original value passed in from the client. This can
be a relative or absolute (unix) timestamp
@return The converted value | [
"Converts",
"an",
"expiration",
"value",
"to",
"an",
"absolute",
"Unix",
"timestamp",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/memcached/VBucketStore.java#L337-L345 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/JsonUtils.java | JsonUtils.decode | public static <T> T decode(String json, Class<T> cls) {
return GSON.fromJson(json, cls);
} | java | public static <T> T decode(String json, Class<T> cls) {
return GSON.fromJson(json, cls);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"decode",
"(",
"String",
"json",
",",
"Class",
"<",
"T",
">",
"cls",
")",
"{",
"return",
"GSON",
".",
"fromJson",
"(",
"json",
",",
"cls",
")",
";",
"}"
] | Attempt to decode a JSON string as a Java object
@param json The JSON string to decode
@param cls The class to decode as
@param <T> Class parameter
@return An instance of {@code cls}, or an exception | [
"Attempt",
"to",
"decode",
"a",
"JSON",
"string",
"as",
"a",
"Java",
"object"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/JsonUtils.java#L46-L48 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/JsonUtils.java | JsonUtils.decodeAsMap | @SuppressWarnings("unchecked")
public static Map<String,Object> decodeAsMap(String json) {
return decode(json, HashMap.class);
} | java | @SuppressWarnings("unchecked")
public static Map<String,Object> decodeAsMap(String json) {
return decode(json, HashMap.class);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"decodeAsMap",
"(",
"String",
"json",
")",
"{",
"return",
"decode",
"(",
"json",
",",
"HashMap",
".",
"class",
")",
";",
"}"
] | Decode a JSON string as Java map. The string must represent a JSON Object
@param json The JSON to decode
@return a map representing the JSON Object | [
"Decode",
"a",
"JSON",
"string",
"as",
"Java",
"map",
".",
"The",
"string",
"must",
"represent",
"a",
"JSON",
"Object"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/JsonUtils.java#L64-L67 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/views/QueryResult.java | QueryResult.rowAt | public Map<String,Object> rowAt(int ix) {
return (Map<String,Object>) rows.get(ix);
} | java | public Map<String,Object> rowAt(int ix) {
return (Map<String,Object>) rows.get(ix);
} | [
"public",
"Map",
"<",
"String",
",",
"Object",
">",
"rowAt",
"(",
"int",
"ix",
")",
"{",
"return",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
")",
"rows",
".",
"get",
"(",
"ix",
")",
";",
"}"
] | Get the raw JSON row at a given index
@param ix The index of the row to fetch
@return The row | [
"Get",
"the",
"raw",
"JSON",
"row",
"at",
"a",
"given",
"index"
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/views/QueryResult.java#L55-L57 | train |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/views/View.java | View.executeRaw | public String executeRaw(Iterable<Item> items, Configuration config) throws QueryExecutionException {
if (config == null) {
config = new Configuration();
}
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
NativeObject configObject = config.toNativeObject();
Scriptable redFunc = null;
if (reducer != null) {
redFunc = reducer.getFunction();
}
try {
// long indexStart = System.currentTimeMillis();
indexer.run(items, cx);
// long indexEnd = System.currentTimeMillis();
// System.err.printf("Indexing took %d ms%n", indexEnd-indexStart);
Scriptable indexResults = indexer.getLastResults();
Scriptable resultObject;
try {
// long filterStart = System.currentTimeMillis();
resultObject = jsRun.execute(configObject, indexResults, redFunc, cx);
// long filterEnd = System.currentTimeMillis();
// System.err.printf("Filtering took %d ms%n", filterEnd-filterStart);
} catch (JavaScriptException ex) {
Object thrownObject = ex.getValue();
String jsonException;
try {
jsonException = (String) NativeJSON.stringify(cx, scope, thrownObject, null, null);
throw new QueryExecutionException(jsonException);
} catch (EcmaError ex2) {
throw new QueryExecutionException(ex2.getErrorMessage());
}
} catch (EcmaError parseErr) {
throw new QueryExecutionException(parseErr.getErrorMessage());
}
NativeArray rows = (NativeArray) resultObject.get("rows", resultObject);
resultObject.delete("rows");
StringBuilder sb = new StringBuilder();
sb.append("{");
for (Object id : ((NativeObject)resultObject).getAllIds()) {
if (! (id instanceof String)) {
throw new RuntimeException("ARGH: " + id);
}
sb.append('"').append(id).append("\":");
sb.append((String)NativeJSON.stringify(cx, scope, resultObject.get((String)id, resultObject), null, null));
sb.append(",");
}
sb.append("\"rows\":[\n");
for (int i = 0; i < rows.size(); i++) {
Object o = rows.get(i, rows);
sb.append((String)NativeJSON.stringify(cx, scope, o, null, null));
if (i < rows.size()-1) {
sb.append(",");
}
sb.append("\n");
}
sb.append("]\n");
sb.append("}\n");
return sb.toString();
} finally {
Context.exit();
}
} | java | public String executeRaw(Iterable<Item> items, Configuration config) throws QueryExecutionException {
if (config == null) {
config = new Configuration();
}
Context cx = Context.enter();
Scriptable scope = cx.initStandardObjects();
NativeObject configObject = config.toNativeObject();
Scriptable redFunc = null;
if (reducer != null) {
redFunc = reducer.getFunction();
}
try {
// long indexStart = System.currentTimeMillis();
indexer.run(items, cx);
// long indexEnd = System.currentTimeMillis();
// System.err.printf("Indexing took %d ms%n", indexEnd-indexStart);
Scriptable indexResults = indexer.getLastResults();
Scriptable resultObject;
try {
// long filterStart = System.currentTimeMillis();
resultObject = jsRun.execute(configObject, indexResults, redFunc, cx);
// long filterEnd = System.currentTimeMillis();
// System.err.printf("Filtering took %d ms%n", filterEnd-filterStart);
} catch (JavaScriptException ex) {
Object thrownObject = ex.getValue();
String jsonException;
try {
jsonException = (String) NativeJSON.stringify(cx, scope, thrownObject, null, null);
throw new QueryExecutionException(jsonException);
} catch (EcmaError ex2) {
throw new QueryExecutionException(ex2.getErrorMessage());
}
} catch (EcmaError parseErr) {
throw new QueryExecutionException(parseErr.getErrorMessage());
}
NativeArray rows = (NativeArray) resultObject.get("rows", resultObject);
resultObject.delete("rows");
StringBuilder sb = new StringBuilder();
sb.append("{");
for (Object id : ((NativeObject)resultObject).getAllIds()) {
if (! (id instanceof String)) {
throw new RuntimeException("ARGH: " + id);
}
sb.append('"').append(id).append("\":");
sb.append((String)NativeJSON.stringify(cx, scope, resultObject.get((String)id, resultObject), null, null));
sb.append(",");
}
sb.append("\"rows\":[\n");
for (int i = 0; i < rows.size(); i++) {
Object o = rows.get(i, rows);
sb.append((String)NativeJSON.stringify(cx, scope, o, null, null));
if (i < rows.size()-1) {
sb.append(",");
}
sb.append("\n");
}
sb.append("]\n");
sb.append("}\n");
return sb.toString();
} finally {
Context.exit();
}
} | [
"public",
"String",
"executeRaw",
"(",
"Iterable",
"<",
"Item",
">",
"items",
",",
"Configuration",
"config",
")",
"throws",
"QueryExecutionException",
"{",
"if",
"(",
"config",
"==",
"null",
")",
"{",
"config",
"=",
"new",
"Configuration",
"(",
")",
";",
... | Executes the view query with the given parameters.
@param items The items to be indexed
@param config The configuration to use for filters
@return A string suitable for returning to a Couchbase client
@throws QueryExecutionException If a query execution error occurs | [
"Executes",
"the",
"view",
"query",
"with",
"the",
"given",
"parameters",
"."
] | 2085bbebade1d5b6356480e7bf335139d08383da | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/views/View.java#L122-L193 | train |
Stratio/stratio-cassandra | tools/stress/src/org/apache/cassandra/stress/settings/StressSettings.java | StressSettings.getThriftClient | public synchronized ThriftClient getThriftClient()
{
if (mode.api != ConnectionAPI.THRIFT_SMART)
return getSimpleThriftClient();
if (tclient == null)
tclient = getSmartThriftClient();
return tclient;
} | java | public synchronized ThriftClient getThriftClient()
{
if (mode.api != ConnectionAPI.THRIFT_SMART)
return getSimpleThriftClient();
if (tclient == null)
tclient = getSmartThriftClient();
return tclient;
} | [
"public",
"synchronized",
"ThriftClient",
"getThriftClient",
"(",
")",
"{",
"if",
"(",
"mode",
".",
"api",
"!=",
"ConnectionAPI",
".",
"THRIFT_SMART",
")",
"return",
"getSimpleThriftClient",
"(",
")",
";",
"if",
"(",
"tclient",
"==",
"null",
")",
"tclient",
... | Thrift client connection
@return cassandra client connection | [
"Thrift",
"client",
"connection"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/tools/stress/src/org/apache/cassandra/stress/settings/StressSettings.java#L82-L91 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/locator/PropertyFileSnitch.java | PropertyFileSnitch.getEndpointInfo | public String[] getEndpointInfo(InetAddress endpoint)
{
String[] rawEndpointInfo = getRawEndpointInfo(endpoint);
if (rawEndpointInfo == null)
throw new RuntimeException("Unknown host " + endpoint + " with no default configured");
return rawEndpointInfo;
} | java | public String[] getEndpointInfo(InetAddress endpoint)
{
String[] rawEndpointInfo = getRawEndpointInfo(endpoint);
if (rawEndpointInfo == null)
throw new RuntimeException("Unknown host " + endpoint + " with no default configured");
return rawEndpointInfo;
} | [
"public",
"String",
"[",
"]",
"getEndpointInfo",
"(",
"InetAddress",
"endpoint",
")",
"{",
"String",
"[",
"]",
"rawEndpointInfo",
"=",
"getRawEndpointInfo",
"(",
"endpoint",
")",
";",
"if",
"(",
"rawEndpointInfo",
"==",
"null",
")",
"throw",
"new",
"RuntimeExc... | Get the raw information about an end point
@param endpoint endpoint to process
@return a array of string with the first index being the data center and the second being the rack | [
"Get",
"the",
"raw",
"information",
"about",
"an",
"end",
"point"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/locator/PropertyFileSnitch.java#L88-L94 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/locator/PropertyFileSnitch.java | PropertyFileSnitch.getDatacenter | public String getDatacenter(InetAddress endpoint)
{
String[] info = getEndpointInfo(endpoint);
assert info != null : "No location defined for endpoint " + endpoint;
return info[0];
} | java | public String getDatacenter(InetAddress endpoint)
{
String[] info = getEndpointInfo(endpoint);
assert info != null : "No location defined for endpoint " + endpoint;
return info[0];
} | [
"public",
"String",
"getDatacenter",
"(",
"InetAddress",
"endpoint",
")",
"{",
"String",
"[",
"]",
"info",
"=",
"getEndpointInfo",
"(",
"endpoint",
")",
";",
"assert",
"info",
"!=",
"null",
":",
"\"No location defined for endpoint \"",
"+",
"endpoint",
";",
"ret... | Return the data center for which an endpoint resides in
@param endpoint the endpoint to process
@return string of data center | [
"Return",
"the",
"data",
"center",
"for",
"which",
"an",
"endpoint",
"resides",
"in"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/locator/PropertyFileSnitch.java#L113-L118 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/locator/PropertyFileSnitch.java | PropertyFileSnitch.getRack | public String getRack(InetAddress endpoint)
{
String[] info = getEndpointInfo(endpoint);
assert info != null : "No location defined for endpoint " + endpoint;
return info[1];
} | java | public String getRack(InetAddress endpoint)
{
String[] info = getEndpointInfo(endpoint);
assert info != null : "No location defined for endpoint " + endpoint;
return info[1];
} | [
"public",
"String",
"getRack",
"(",
"InetAddress",
"endpoint",
")",
"{",
"String",
"[",
"]",
"info",
"=",
"getEndpointInfo",
"(",
"endpoint",
")",
";",
"assert",
"info",
"!=",
"null",
":",
"\"No location defined for endpoint \"",
"+",
"endpoint",
";",
"return",
... | Return the rack for which an endpoint resides in
@param endpoint the endpoint to process
@return string of rack | [
"Return",
"the",
"rack",
"for",
"which",
"an",
"endpoint",
"resides",
"in"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/locator/PropertyFileSnitch.java#L126-L131 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.setPartitionFilter | public void setPartitionFilter(Expression partitionFilter) throws IOException
{
UDFContext context = UDFContext.getUDFContext();
Properties property = context.getUDFProperties(AbstractCassandraStorage.class);
property.setProperty(PARTITION_FILTER_SIGNATURE, indexExpressionsToString(filterToIndexExpressions(partitionFilter)));
} | java | public void setPartitionFilter(Expression partitionFilter) throws IOException
{
UDFContext context = UDFContext.getUDFContext();
Properties property = context.getUDFProperties(AbstractCassandraStorage.class);
property.setProperty(PARTITION_FILTER_SIGNATURE, indexExpressionsToString(filterToIndexExpressions(partitionFilter)));
} | [
"public",
"void",
"setPartitionFilter",
"(",
"Expression",
"partitionFilter",
")",
"throws",
"IOException",
"{",
"UDFContext",
"context",
"=",
"UDFContext",
".",
"getUDFContext",
"(",
")",
";",
"Properties",
"property",
"=",
"context",
".",
"getUDFProperties",
"(",
... | set partition filter | [
"set",
"partition",
"filter"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L485-L490 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.putNext | public void putNext(Tuple t) throws IOException
{
/*
We support two cases for output:
First, the original output:
(key, (name, value), (name,value), {(name,value)}) (tuples or bag is optional)
For supers, we only accept the original output.
*/
if (t.size() < 1)
{
// simply nothing here, we can't even delete without a key
logger.warn("Empty output skipped, filter empty tuples to suppress this warning");
return;
}
ByteBuffer key = objToBB(t.get(0));
if (t.getType(1) == DataType.TUPLE)
writeColumnsFromTuple(key, t, 1);
else if (t.getType(1) == DataType.BAG)
{
if (t.size() > 2)
throw new IOException("No arguments allowed after bag");
writeColumnsFromBag(key, (DataBag) t.get(1));
}
else
throw new IOException("Second argument in output must be a tuple or bag");
} | java | public void putNext(Tuple t) throws IOException
{
/*
We support two cases for output:
First, the original output:
(key, (name, value), (name,value), {(name,value)}) (tuples or bag is optional)
For supers, we only accept the original output.
*/
if (t.size() < 1)
{
// simply nothing here, we can't even delete without a key
logger.warn("Empty output skipped, filter empty tuples to suppress this warning");
return;
}
ByteBuffer key = objToBB(t.get(0));
if (t.getType(1) == DataType.TUPLE)
writeColumnsFromTuple(key, t, 1);
else if (t.getType(1) == DataType.BAG)
{
if (t.size() > 2)
throw new IOException("No arguments allowed after bag");
writeColumnsFromBag(key, (DataBag) t.get(1));
}
else
throw new IOException("Second argument in output must be a tuple or bag");
} | [
"public",
"void",
"putNext",
"(",
"Tuple",
"t",
")",
"throws",
"IOException",
"{",
"/*\n We support two cases for output:\n First, the original output:\n (key, (name, value), (name,value), {(name,value)}) (tuples or bag is optional)\n For supers, we only accept th... | write next row | [
"write",
"next",
"row"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L499-L525 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.writeColumnsFromTuple | private void writeColumnsFromTuple(ByteBuffer key, Tuple t, int offset) throws IOException
{
ArrayList<Mutation> mutationList = new ArrayList<Mutation>();
for (int i = offset; i < t.size(); i++)
{
if (t.getType(i) == DataType.BAG)
writeColumnsFromBag(key, (DataBag) t.get(i));
else if (t.getType(i) == DataType.TUPLE)
{
Tuple inner = (Tuple) t.get(i);
if (inner.size() > 0) // may be empty, for an indexed column that wasn't present
mutationList.add(mutationFromTuple(inner));
}
else if (!usePartitionFilter)
{
throw new IOException("Output type was not a bag or a tuple");
}
}
if (mutationList.size() > 0)
writeMutations(key, mutationList);
} | java | private void writeColumnsFromTuple(ByteBuffer key, Tuple t, int offset) throws IOException
{
ArrayList<Mutation> mutationList = new ArrayList<Mutation>();
for (int i = offset; i < t.size(); i++)
{
if (t.getType(i) == DataType.BAG)
writeColumnsFromBag(key, (DataBag) t.get(i));
else if (t.getType(i) == DataType.TUPLE)
{
Tuple inner = (Tuple) t.get(i);
if (inner.size() > 0) // may be empty, for an indexed column that wasn't present
mutationList.add(mutationFromTuple(inner));
}
else if (!usePartitionFilter)
{
throw new IOException("Output type was not a bag or a tuple");
}
}
if (mutationList.size() > 0)
writeMutations(key, mutationList);
} | [
"private",
"void",
"writeColumnsFromTuple",
"(",
"ByteBuffer",
"key",
",",
"Tuple",
"t",
",",
"int",
"offset",
")",
"throws",
"IOException",
"{",
"ArrayList",
"<",
"Mutation",
">",
"mutationList",
"=",
"new",
"ArrayList",
"<",
"Mutation",
">",
"(",
")",
";",... | write tuple data to cassandra | [
"write",
"tuple",
"data",
"to",
"cassandra"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L528-L548 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.mutationFromTuple | private Mutation mutationFromTuple(Tuple t) throws IOException
{
Mutation mutation = new Mutation();
if (t.get(1) == null)
{
if (allow_deletes)
{
mutation.deletion = new Deletion();
mutation.deletion.predicate = new org.apache.cassandra.thrift.SlicePredicate();
mutation.deletion.predicate.column_names = Arrays.asList(objToBB(t.get(0)));
mutation.deletion.setTimestamp(FBUtilities.timestampMicros());
}
else
throw new IOException("null found but deletes are disabled, set " + PIG_ALLOW_DELETES +
"=true in environment or allow_deletes=true in URL to enable");
}
else
{
org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column();
column.setName(objToBB(t.get(0)));
column.setValue(objToBB(t.get(1)));
column.setTimestamp(FBUtilities.timestampMicros());
mutation.column_or_supercolumn = new ColumnOrSuperColumn();
mutation.column_or_supercolumn.column = column;
}
return mutation;
} | java | private Mutation mutationFromTuple(Tuple t) throws IOException
{
Mutation mutation = new Mutation();
if (t.get(1) == null)
{
if (allow_deletes)
{
mutation.deletion = new Deletion();
mutation.deletion.predicate = new org.apache.cassandra.thrift.SlicePredicate();
mutation.deletion.predicate.column_names = Arrays.asList(objToBB(t.get(0)));
mutation.deletion.setTimestamp(FBUtilities.timestampMicros());
}
else
throw new IOException("null found but deletes are disabled, set " + PIG_ALLOW_DELETES +
"=true in environment or allow_deletes=true in URL to enable");
}
else
{
org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column();
column.setName(objToBB(t.get(0)));
column.setValue(objToBB(t.get(1)));
column.setTimestamp(FBUtilities.timestampMicros());
mutation.column_or_supercolumn = new ColumnOrSuperColumn();
mutation.column_or_supercolumn.column = column;
}
return mutation;
} | [
"private",
"Mutation",
"mutationFromTuple",
"(",
"Tuple",
"t",
")",
"throws",
"IOException",
"{",
"Mutation",
"mutation",
"=",
"new",
"Mutation",
"(",
")",
";",
"if",
"(",
"t",
".",
"get",
"(",
"1",
")",
"==",
"null",
")",
"{",
"if",
"(",
"allow_delete... | compose Cassandra mutation from tuple | [
"compose",
"Cassandra",
"mutation",
"from",
"tuple"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L551-L577 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.writeColumnsFromBag | private void writeColumnsFromBag(ByteBuffer key, DataBag bag) throws IOException
{
List<Mutation> mutationList = new ArrayList<Mutation>();
for (Tuple pair : bag)
{
Mutation mutation = new Mutation();
if (DataType.findType(pair.get(1)) == DataType.BAG) // supercolumn
{
SuperColumn sc = new SuperColumn();
sc.setName(objToBB(pair.get(0)));
List<org.apache.cassandra.thrift.Column> columns = new ArrayList<org.apache.cassandra.thrift.Column>();
for (Tuple subcol : (DataBag) pair.get(1))
{
org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column();
column.setName(objToBB(subcol.get(0)));
column.setValue(objToBB(subcol.get(1)));
column.setTimestamp(FBUtilities.timestampMicros());
columns.add(column);
}
if (columns.isEmpty())
{
if (allow_deletes)
{
mutation.deletion = new Deletion();
mutation.deletion.super_column = objToBB(pair.get(0));
mutation.deletion.setTimestamp(FBUtilities.timestampMicros());
}
else
throw new IOException("SuperColumn deletion attempted with empty bag, but deletes are disabled, set " +
PIG_ALLOW_DELETES + "=true in environment or allow_deletes=true in URL to enable");
}
else
{
sc.columns = columns;
mutation.column_or_supercolumn = new ColumnOrSuperColumn();
mutation.column_or_supercolumn.super_column = sc;
}
}
else
mutation = mutationFromTuple(pair);
mutationList.add(mutation);
// for wide rows, we need to limit the amount of mutations we write at once
if (mutationList.size() >= 10) // arbitrary, CFOF will re-batch this up, and BOF won't care
{
writeMutations(key, mutationList);
mutationList.clear();
}
}
// write the last batch
if (mutationList.size() > 0)
writeMutations(key, mutationList);
} | java | private void writeColumnsFromBag(ByteBuffer key, DataBag bag) throws IOException
{
List<Mutation> mutationList = new ArrayList<Mutation>();
for (Tuple pair : bag)
{
Mutation mutation = new Mutation();
if (DataType.findType(pair.get(1)) == DataType.BAG) // supercolumn
{
SuperColumn sc = new SuperColumn();
sc.setName(objToBB(pair.get(0)));
List<org.apache.cassandra.thrift.Column> columns = new ArrayList<org.apache.cassandra.thrift.Column>();
for (Tuple subcol : (DataBag) pair.get(1))
{
org.apache.cassandra.thrift.Column column = new org.apache.cassandra.thrift.Column();
column.setName(objToBB(subcol.get(0)));
column.setValue(objToBB(subcol.get(1)));
column.setTimestamp(FBUtilities.timestampMicros());
columns.add(column);
}
if (columns.isEmpty())
{
if (allow_deletes)
{
mutation.deletion = new Deletion();
mutation.deletion.super_column = objToBB(pair.get(0));
mutation.deletion.setTimestamp(FBUtilities.timestampMicros());
}
else
throw new IOException("SuperColumn deletion attempted with empty bag, but deletes are disabled, set " +
PIG_ALLOW_DELETES + "=true in environment or allow_deletes=true in URL to enable");
}
else
{
sc.columns = columns;
mutation.column_or_supercolumn = new ColumnOrSuperColumn();
mutation.column_or_supercolumn.super_column = sc;
}
}
else
mutation = mutationFromTuple(pair);
mutationList.add(mutation);
// for wide rows, we need to limit the amount of mutations we write at once
if (mutationList.size() >= 10) // arbitrary, CFOF will re-batch this up, and BOF won't care
{
writeMutations(key, mutationList);
mutationList.clear();
}
}
// write the last batch
if (mutationList.size() > 0)
writeMutations(key, mutationList);
} | [
"private",
"void",
"writeColumnsFromBag",
"(",
"ByteBuffer",
"key",
",",
"DataBag",
"bag",
")",
"throws",
"IOException",
"{",
"List",
"<",
"Mutation",
">",
"mutationList",
"=",
"new",
"ArrayList",
"<",
"Mutation",
">",
"(",
")",
";",
"for",
"(",
"Tuple",
"... | write bag data to Cassandra | [
"write",
"bag",
"data",
"to",
"Cassandra"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L580-L631 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.writeMutations | private void writeMutations(ByteBuffer key, List<Mutation> mutations) throws IOException
{
try
{
writer.write(key, mutations);
}
catch (InterruptedException e)
{
throw new IOException(e);
}
} | java | private void writeMutations(ByteBuffer key, List<Mutation> mutations) throws IOException
{
try
{
writer.write(key, mutations);
}
catch (InterruptedException e)
{
throw new IOException(e);
}
} | [
"private",
"void",
"writeMutations",
"(",
"ByteBuffer",
"key",
",",
"List",
"<",
"Mutation",
">",
"mutations",
")",
"throws",
"IOException",
"{",
"try",
"{",
"writer",
".",
"write",
"(",
"key",
",",
"mutations",
")",
";",
"}",
"catch",
"(",
"InterruptedExc... | write mutation to Cassandra | [
"write",
"mutation",
"to",
"Cassandra"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L634-L644 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.filterToIndexExpressions | private List<IndexExpression> filterToIndexExpressions(Expression expression) throws IOException
{
List<IndexExpression> indexExpressions = new ArrayList<IndexExpression>();
Expression.BinaryExpression be = (Expression.BinaryExpression)expression;
ByteBuffer name = ByteBuffer.wrap(be.getLhs().toString().getBytes());
ByteBuffer value = ByteBuffer.wrap(be.getRhs().toString().getBytes());
switch (expression.getOpType())
{
case OP_EQ:
indexExpressions.add(new IndexExpression(name, IndexOperator.EQ, value));
break;
case OP_GE:
indexExpressions.add(new IndexExpression(name, IndexOperator.GTE, value));
break;
case OP_GT:
indexExpressions.add(new IndexExpression(name, IndexOperator.GT, value));
break;
case OP_LE:
indexExpressions.add(new IndexExpression(name, IndexOperator.LTE, value));
break;
case OP_LT:
indexExpressions.add(new IndexExpression(name, IndexOperator.LT, value));
break;
case OP_AND:
indexExpressions.addAll(filterToIndexExpressions(be.getLhs()));
indexExpressions.addAll(filterToIndexExpressions(be.getRhs()));
break;
default:
throw new IOException("Unsupported expression type: " + expression.getOpType().name());
}
return indexExpressions;
} | java | private List<IndexExpression> filterToIndexExpressions(Expression expression) throws IOException
{
List<IndexExpression> indexExpressions = new ArrayList<IndexExpression>();
Expression.BinaryExpression be = (Expression.BinaryExpression)expression;
ByteBuffer name = ByteBuffer.wrap(be.getLhs().toString().getBytes());
ByteBuffer value = ByteBuffer.wrap(be.getRhs().toString().getBytes());
switch (expression.getOpType())
{
case OP_EQ:
indexExpressions.add(new IndexExpression(name, IndexOperator.EQ, value));
break;
case OP_GE:
indexExpressions.add(new IndexExpression(name, IndexOperator.GTE, value));
break;
case OP_GT:
indexExpressions.add(new IndexExpression(name, IndexOperator.GT, value));
break;
case OP_LE:
indexExpressions.add(new IndexExpression(name, IndexOperator.LTE, value));
break;
case OP_LT:
indexExpressions.add(new IndexExpression(name, IndexOperator.LT, value));
break;
case OP_AND:
indexExpressions.addAll(filterToIndexExpressions(be.getLhs()));
indexExpressions.addAll(filterToIndexExpressions(be.getRhs()));
break;
default:
throw new IOException("Unsupported expression type: " + expression.getOpType().name());
}
return indexExpressions;
} | [
"private",
"List",
"<",
"IndexExpression",
">",
"filterToIndexExpressions",
"(",
"Expression",
"expression",
")",
"throws",
"IOException",
"{",
"List",
"<",
"IndexExpression",
">",
"indexExpressions",
"=",
"new",
"ArrayList",
"<",
"IndexExpression",
">",
"(",
")",
... | get a list of Cassandra IndexExpression from Pig expression | [
"get",
"a",
"list",
"of",
"Cassandra",
"IndexExpression",
"from",
"Pig",
"expression"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L647-L678 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.indexExpressionsToString | private static String indexExpressionsToString(List<IndexExpression> indexExpressions) throws IOException
{
assert indexExpressions != null;
// oh, you thought cfdefToString was awful?
IndexClause indexClause = new IndexClause();
indexClause.setExpressions(indexExpressions);
indexClause.setStart_key("".getBytes());
TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
try
{
return Hex.bytesToHex(serializer.serialize(indexClause));
}
catch (TException e)
{
throw new IOException(e);
}
} | java | private static String indexExpressionsToString(List<IndexExpression> indexExpressions) throws IOException
{
assert indexExpressions != null;
// oh, you thought cfdefToString was awful?
IndexClause indexClause = new IndexClause();
indexClause.setExpressions(indexExpressions);
indexClause.setStart_key("".getBytes());
TSerializer serializer = new TSerializer(new TBinaryProtocol.Factory());
try
{
return Hex.bytesToHex(serializer.serialize(indexClause));
}
catch (TException e)
{
throw new IOException(e);
}
} | [
"private",
"static",
"String",
"indexExpressionsToString",
"(",
"List",
"<",
"IndexExpression",
">",
"indexExpressions",
")",
"throws",
"IOException",
"{",
"assert",
"indexExpressions",
"!=",
"null",
";",
"// oh, you thought cfdefToString was awful?",
"IndexClause",
"indexC... | convert a list of index expression to string | [
"convert",
"a",
"list",
"of",
"index",
"expression",
"to",
"string"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L681-L697 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.indexExpressionsFromString | private static List<IndexExpression> indexExpressionsFromString(String ie) throws IOException
{
assert ie != null;
TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());
IndexClause indexClause = new IndexClause();
try
{
deserializer.deserialize(indexClause, Hex.hexToBytes(ie));
}
catch (TException e)
{
throw new IOException(e);
}
return indexClause.getExpressions();
} | java | private static List<IndexExpression> indexExpressionsFromString(String ie) throws IOException
{
assert ie != null;
TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());
IndexClause indexClause = new IndexClause();
try
{
deserializer.deserialize(indexClause, Hex.hexToBytes(ie));
}
catch (TException e)
{
throw new IOException(e);
}
return indexClause.getExpressions();
} | [
"private",
"static",
"List",
"<",
"IndexExpression",
">",
"indexExpressionsFromString",
"(",
"String",
"ie",
")",
"throws",
"IOException",
"{",
"assert",
"ie",
"!=",
"null",
";",
"TDeserializer",
"deserializer",
"=",
"new",
"TDeserializer",
"(",
"new",
"TBinaryPro... | convert string to a list of index expression | [
"convert",
"string",
"to",
"a",
"list",
"of",
"index",
"expression"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L700-L714 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.getIndexExpressions | private List<IndexExpression> getIndexExpressions() throws IOException
{
UDFContext context = UDFContext.getUDFContext();
Properties property = context.getUDFProperties(AbstractCassandraStorage.class);
if (property.getProperty(PARTITION_FILTER_SIGNATURE) != null)
return indexExpressionsFromString(property.getProperty(PARTITION_FILTER_SIGNATURE));
else
return null;
} | java | private List<IndexExpression> getIndexExpressions() throws IOException
{
UDFContext context = UDFContext.getUDFContext();
Properties property = context.getUDFProperties(AbstractCassandraStorage.class);
if (property.getProperty(PARTITION_FILTER_SIGNATURE) != null)
return indexExpressionsFromString(property.getProperty(PARTITION_FILTER_SIGNATURE));
else
return null;
} | [
"private",
"List",
"<",
"IndexExpression",
">",
"getIndexExpressions",
"(",
")",
"throws",
"IOException",
"{",
"UDFContext",
"context",
"=",
"UDFContext",
".",
"getUDFContext",
"(",
")",
";",
"Properties",
"property",
"=",
"context",
".",
"getUDFProperties",
"(",
... | get a list of index expression | [
"get",
"a",
"list",
"of",
"index",
"expression"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L717-L725 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.getColumnMetadata | protected List<ColumnDef> getColumnMetadata(Cassandra.Client client)
throws TException, CharacterCodingException, InvalidRequestException, ConfigurationException
{
return getColumnMeta(client, true, true);
} | java | protected List<ColumnDef> getColumnMetadata(Cassandra.Client client)
throws TException, CharacterCodingException, InvalidRequestException, ConfigurationException
{
return getColumnMeta(client, true, true);
} | [
"protected",
"List",
"<",
"ColumnDef",
">",
"getColumnMetadata",
"(",
"Cassandra",
".",
"Client",
"client",
")",
"throws",
"TException",
",",
"CharacterCodingException",
",",
"InvalidRequestException",
",",
"ConfigurationException",
"{",
"return",
"getColumnMeta",
"(",
... | get a list of column for the column family | [
"get",
"a",
"list",
"of",
"column",
"for",
"the",
"column",
"family"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L728-L732 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.keyToTuple | private Tuple keyToTuple(ByteBuffer key, CfDef cfDef, AbstractType comparator) throws IOException
{
Tuple tuple = TupleFactory.getInstance().newTuple(1);
addKeyToTuple(tuple, key, cfDef, comparator);
return tuple;
} | java | private Tuple keyToTuple(ByteBuffer key, CfDef cfDef, AbstractType comparator) throws IOException
{
Tuple tuple = TupleFactory.getInstance().newTuple(1);
addKeyToTuple(tuple, key, cfDef, comparator);
return tuple;
} | [
"private",
"Tuple",
"keyToTuple",
"(",
"ByteBuffer",
"key",
",",
"CfDef",
"cfDef",
",",
"AbstractType",
"comparator",
")",
"throws",
"IOException",
"{",
"Tuple",
"tuple",
"=",
"TupleFactory",
".",
"getInstance",
"(",
")",
".",
"newTuple",
"(",
"1",
")",
";",... | convert key to a tuple | [
"convert",
"key",
"to",
"a",
"tuple"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L735-L740 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java | CassandraStorage.addKeyToTuple | private void addKeyToTuple(Tuple tuple, ByteBuffer key, CfDef cfDef, AbstractType comparator) throws IOException
{
if( comparator instanceof AbstractCompositeType )
{
setTupleValue(tuple, 0, composeComposite((AbstractCompositeType)comparator,key));
}
else
{
setTupleValue(tuple, 0, cassandraToObj(getDefaultMarshallers(cfDef).get(MarshallerType.KEY_VALIDATOR), key));
}
} | java | private void addKeyToTuple(Tuple tuple, ByteBuffer key, CfDef cfDef, AbstractType comparator) throws IOException
{
if( comparator instanceof AbstractCompositeType )
{
setTupleValue(tuple, 0, composeComposite((AbstractCompositeType)comparator,key));
}
else
{
setTupleValue(tuple, 0, cassandraToObj(getDefaultMarshallers(cfDef).get(MarshallerType.KEY_VALIDATOR), key));
}
} | [
"private",
"void",
"addKeyToTuple",
"(",
"Tuple",
"tuple",
",",
"ByteBuffer",
"key",
",",
"CfDef",
"cfDef",
",",
"AbstractType",
"comparator",
")",
"throws",
"IOException",
"{",
"if",
"(",
"comparator",
"instanceof",
"AbstractCompositeType",
")",
"{",
"setTupleVal... | add key to a tuple | [
"add",
"key",
"to",
"a",
"tuple"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/pig/CassandraStorage.java#L743-L754 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/db/DeletionInfo.java | DeletionInfo.rangeIterator | public Iterator<RangeTombstone> rangeIterator()
{
return ranges == null ? Iterators.<RangeTombstone>emptyIterator() : ranges.iterator();
} | java | public Iterator<RangeTombstone> rangeIterator()
{
return ranges == null ? Iterators.<RangeTombstone>emptyIterator() : ranges.iterator();
} | [
"public",
"Iterator",
"<",
"RangeTombstone",
">",
"rangeIterator",
"(",
")",
"{",
"return",
"ranges",
"==",
"null",
"?",
"Iterators",
".",
"<",
"RangeTombstone",
">",
"emptyIterator",
"(",
")",
":",
"ranges",
".",
"iterator",
"(",
")",
";",
"}"
] | Use sparingly, not the most efficient thing | [
"Use",
"sparingly",
"not",
"the",
"most",
"efficient",
"thing"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/DeletionInfo.java#L291-L294 | train |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/query/builder/BooleanConditionBuilder.java | BooleanConditionBuilder.must | public BooleanConditionBuilder must(ConditionBuilder... conditionBuilders) {
if (must == null) {
must = new ArrayList<>(conditionBuilders.length);
}
for (ConditionBuilder conditionBuilder : conditionBuilders) {
must.add(conditionBuilder.build());
}
return this;
} | java | public BooleanConditionBuilder must(ConditionBuilder... conditionBuilders) {
if (must == null) {
must = new ArrayList<>(conditionBuilders.length);
}
for (ConditionBuilder conditionBuilder : conditionBuilders) {
must.add(conditionBuilder.build());
}
return this;
} | [
"public",
"BooleanConditionBuilder",
"must",
"(",
"ConditionBuilder",
"...",
"conditionBuilders",
")",
"{",
"if",
"(",
"must",
"==",
"null",
")",
"{",
"must",
"=",
"new",
"ArrayList",
"<>",
"(",
"conditionBuilders",
".",
"length",
")",
";",
"}",
"for",
"(",
... | Returns this builder with the specified mandatory conditions.
@param conditionBuilders The mandatory conditions to be added.
@return this builder with the specified mandatory conditions. | [
"Returns",
"this",
"builder",
"with",
"the",
"specified",
"mandatory",
"conditions",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/query/builder/BooleanConditionBuilder.java#L52-L60 | train |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/query/builder/BooleanConditionBuilder.java | BooleanConditionBuilder.should | public BooleanConditionBuilder should(ConditionBuilder... conditionBuilders) {
if (should == null) {
should = new ArrayList<>(conditionBuilders.length);
}
for (ConditionBuilder conditionBuilder : conditionBuilders) {
should.add(conditionBuilder.build());
}
return this;
} | java | public BooleanConditionBuilder should(ConditionBuilder... conditionBuilders) {
if (should == null) {
should = new ArrayList<>(conditionBuilders.length);
}
for (ConditionBuilder conditionBuilder : conditionBuilders) {
should.add(conditionBuilder.build());
}
return this;
} | [
"public",
"BooleanConditionBuilder",
"should",
"(",
"ConditionBuilder",
"...",
"conditionBuilders",
")",
"{",
"if",
"(",
"should",
"==",
"null",
")",
"{",
"should",
"=",
"new",
"ArrayList",
"<>",
"(",
"conditionBuilders",
".",
"length",
")",
";",
"}",
"for",
... | Returns this builder with the specified optional conditions.
@param conditionBuilders The optional conditions to be added.
@return this builder with the specified optional conditions. | [
"Returns",
"this",
"builder",
"with",
"the",
"specified",
"optional",
"conditions",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/query/builder/BooleanConditionBuilder.java#L68-L76 | train |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/query/builder/BooleanConditionBuilder.java | BooleanConditionBuilder.not | public BooleanConditionBuilder not(ConditionBuilder... conditionBuilders) {
if (not == null) {
not = new ArrayList<>(conditionBuilders.length);
}
for (ConditionBuilder conditionBuilder : conditionBuilders) {
not.add(conditionBuilder.build());
}
return this;
} | java | public BooleanConditionBuilder not(ConditionBuilder... conditionBuilders) {
if (not == null) {
not = new ArrayList<>(conditionBuilders.length);
}
for (ConditionBuilder conditionBuilder : conditionBuilders) {
not.add(conditionBuilder.build());
}
return this;
} | [
"public",
"BooleanConditionBuilder",
"not",
"(",
"ConditionBuilder",
"...",
"conditionBuilders",
")",
"{",
"if",
"(",
"not",
"==",
"null",
")",
"{",
"not",
"=",
"new",
"ArrayList",
"<>",
"(",
"conditionBuilders",
".",
"length",
")",
";",
"}",
"for",
"(",
"... | Returns this builder with the specified mandatory not conditions.
@param conditionBuilders The mandatory not conditions to be added.
@return this builder with the specified mandatory not conditions. | [
"Returns",
"this",
"builder",
"with",
"the",
"specified",
"mandatory",
"not",
"conditions",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/query/builder/BooleanConditionBuilder.java#L84-L92 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/config/Schema.java | Schema.load | public Schema load(KSMetaData keyspaceDef)
{
for (CFMetaData cfm : keyspaceDef.cfMetaData().values())
load(cfm);
setKeyspaceDefinition(keyspaceDef);
return this;
} | java | public Schema load(KSMetaData keyspaceDef)
{
for (CFMetaData cfm : keyspaceDef.cfMetaData().values())
load(cfm);
setKeyspaceDefinition(keyspaceDef);
return this;
} | [
"public",
"Schema",
"load",
"(",
"KSMetaData",
"keyspaceDef",
")",
"{",
"for",
"(",
"CFMetaData",
"cfm",
":",
"keyspaceDef",
".",
"cfMetaData",
"(",
")",
".",
"values",
"(",
")",
")",
"load",
"(",
"cfm",
")",
";",
"setKeyspaceDefinition",
"(",
"keyspaceDef... | Load specific keyspace into Schema
@param keyspaceDef The keyspace to load up
@return self to support chaining calls | [
"Load",
"specific",
"keyspace",
"into",
"Schema"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/Schema.java#L110-L118 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/config/Schema.java | Schema.storeKeyspaceInstance | public void storeKeyspaceInstance(Keyspace keyspace)
{
if (keyspaceInstances.containsKey(keyspace.getName()))
throw new IllegalArgumentException(String.format("Keyspace %s was already initialized.", keyspace.getName()));
keyspaceInstances.put(keyspace.getName(), keyspace);
} | java | public void storeKeyspaceInstance(Keyspace keyspace)
{
if (keyspaceInstances.containsKey(keyspace.getName()))
throw new IllegalArgumentException(String.format("Keyspace %s was already initialized.", keyspace.getName()));
keyspaceInstances.put(keyspace.getName(), keyspace);
} | [
"public",
"void",
"storeKeyspaceInstance",
"(",
"Keyspace",
"keyspace",
")",
"{",
"if",
"(",
"keyspaceInstances",
".",
"containsKey",
"(",
"keyspace",
".",
"getName",
"(",
")",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"String",
".",
"format",
... | Store given Keyspace instance to the schema
@param keyspace The Keyspace instance to store
@throws IllegalArgumentException if Keyspace is already stored | [
"Store",
"given",
"Keyspace",
"instance",
"to",
"the",
"schema"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/Schema.java#L150-L156 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/config/Schema.java | Schema.getCFMetaData | public CFMetaData getCFMetaData(String keyspaceName, String cfName)
{
assert keyspaceName != null;
KSMetaData ksm = keyspaces.get(keyspaceName);
return (ksm == null) ? null : ksm.cfMetaData().get(cfName);
} | java | public CFMetaData getCFMetaData(String keyspaceName, String cfName)
{
assert keyspaceName != null;
KSMetaData ksm = keyspaces.get(keyspaceName);
return (ksm == null) ? null : ksm.cfMetaData().get(cfName);
} | [
"public",
"CFMetaData",
"getCFMetaData",
"(",
"String",
"keyspaceName",
",",
"String",
"cfName",
")",
"{",
"assert",
"keyspaceName",
"!=",
"null",
";",
"KSMetaData",
"ksm",
"=",
"keyspaces",
".",
"get",
"(",
"keyspaceName",
")",
";",
"return",
"(",
"ksm",
"=... | Given a keyspace name & column family name, get the column family
meta data. If the keyspace name or column family name is not valid
this function returns null.
@param keyspaceName The keyspace name
@param cfName The ColumnFamily name
@return ColumnFamily Metadata object or null if it wasn't found | [
"Given",
"a",
"keyspace",
"name",
"&",
"column",
"family",
"name",
"get",
"the",
"column",
"family",
"meta",
"data",
".",
"If",
"the",
"keyspace",
"name",
"or",
"column",
"family",
"name",
"is",
"not",
"valid",
"this",
"function",
"returns",
"null",
"."
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/Schema.java#L190-L195 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/config/Schema.java | Schema.getCFMetaData | public CFMetaData getCFMetaData(UUID cfId)
{
Pair<String,String> cf = getCF(cfId);
return (cf == null) ? null : getCFMetaData(cf.left, cf.right);
} | java | public CFMetaData getCFMetaData(UUID cfId)
{
Pair<String,String> cf = getCF(cfId);
return (cf == null) ? null : getCFMetaData(cf.left, cf.right);
} | [
"public",
"CFMetaData",
"getCFMetaData",
"(",
"UUID",
"cfId",
")",
"{",
"Pair",
"<",
"String",
",",
"String",
">",
"cf",
"=",
"getCF",
"(",
"cfId",
")",
";",
"return",
"(",
"cf",
"==",
"null",
")",
"?",
"null",
":",
"getCFMetaData",
"(",
"cf",
".",
... | Get ColumnFamily metadata by its identifier
@param cfId The ColumnFamily identifier
@return metadata about ColumnFamily | [
"Get",
"ColumnFamily",
"metadata",
"by",
"its",
"identifier"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/Schema.java#L204-L208 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/config/Schema.java | Schema.getKeyspaceMetaData | public Map<String, CFMetaData> getKeyspaceMetaData(String keyspaceName)
{
assert keyspaceName != null;
KSMetaData ksm = keyspaces.get(keyspaceName);
assert ksm != null;
return ksm.cfMetaData();
} | java | public Map<String, CFMetaData> getKeyspaceMetaData(String keyspaceName)
{
assert keyspaceName != null;
KSMetaData ksm = keyspaces.get(keyspaceName);
assert ksm != null;
return ksm.cfMetaData();
} | [
"public",
"Map",
"<",
"String",
",",
"CFMetaData",
">",
"getKeyspaceMetaData",
"(",
"String",
"keyspaceName",
")",
"{",
"assert",
"keyspaceName",
"!=",
"null",
";",
"KSMetaData",
"ksm",
"=",
"keyspaces",
".",
"get",
"(",
"keyspaceName",
")",
";",
"assert",
"... | Get metadata about keyspace inner ColumnFamilies
@param keyspaceName The name of the keyspace
@return metadata about ColumnFamilies the belong to the given keyspace | [
"Get",
"metadata",
"about",
"keyspace",
"inner",
"ColumnFamilies"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/Schema.java#L258-L264 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/config/Schema.java | Schema.purge | public void purge(CFMetaData cfm)
{
cfIdMap.remove(Pair.create(cfm.ksName, cfm.cfName));
cfm.markPurged();
} | java | public void purge(CFMetaData cfm)
{
cfIdMap.remove(Pair.create(cfm.ksName, cfm.cfName));
cfm.markPurged();
} | [
"public",
"void",
"purge",
"(",
"CFMetaData",
"cfm",
")",
"{",
"cfIdMap",
".",
"remove",
"(",
"Pair",
".",
"create",
"(",
"cfm",
".",
"ksName",
",",
"cfm",
".",
"cfName",
")",
")",
";",
"cfm",
".",
"markPurged",
"(",
")",
";",
"}"
] | Used for ColumnFamily data eviction out from the schema
@param cfm The ColumnFamily Definition to evict | [
"Used",
"for",
"ColumnFamily",
"data",
"eviction",
"out",
"from",
"the",
"schema"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/Schema.java#L348-L352 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/config/Schema.java | Schema.updateVersion | public void updateVersion()
{
try
{
MessageDigest versionDigest = MessageDigest.getInstance("MD5");
for (Row row : SystemKeyspace.serializedSchema())
{
if (invalidSchemaRow(row) || ignoredSchemaRow(row))
continue;
// we want to digest only live columns
ColumnFamilyStore.removeDeletedColumnsOnly(row.cf, Integer.MAX_VALUE, SecondaryIndexManager.nullUpdater);
row.cf.purgeTombstones(Integer.MAX_VALUE);
row.cf.updateDigest(versionDigest);
}
version = UUID.nameUUIDFromBytes(versionDigest.digest());
SystemKeyspace.updateSchemaVersion(version);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | java | public void updateVersion()
{
try
{
MessageDigest versionDigest = MessageDigest.getInstance("MD5");
for (Row row : SystemKeyspace.serializedSchema())
{
if (invalidSchemaRow(row) || ignoredSchemaRow(row))
continue;
// we want to digest only live columns
ColumnFamilyStore.removeDeletedColumnsOnly(row.cf, Integer.MAX_VALUE, SecondaryIndexManager.nullUpdater);
row.cf.purgeTombstones(Integer.MAX_VALUE);
row.cf.updateDigest(versionDigest);
}
version = UUID.nameUUIDFromBytes(versionDigest.digest());
SystemKeyspace.updateSchemaVersion(version);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | [
"public",
"void",
"updateVersion",
"(",
")",
"{",
"try",
"{",
"MessageDigest",
"versionDigest",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"\"MD5\"",
")",
";",
"for",
"(",
"Row",
"row",
":",
"SystemKeyspace",
".",
"serializedSchema",
"(",
")",
")",
"{",
... | Read schema from system keyspace and calculate MD5 digest of every row, resulting digest
will be converted into UUID which would act as content-based version of the schema. | [
"Read",
"schema",
"from",
"system",
"keyspace",
"and",
"calculate",
"MD5",
"digest",
"of",
"every",
"row",
"resulting",
"digest",
"will",
"be",
"converted",
"into",
"UUID",
"which",
"would",
"act",
"as",
"content",
"-",
"based",
"version",
"of",
"the",
"sche... | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/config/Schema.java#L368-L392 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/utils/concurrent/WaitQueue.java | WaitQueue.signal | public boolean signal()
{
if (!hasWaiters())
return false;
while (true)
{
RegisteredSignal s = queue.poll();
if (s == null || s.signal() != null)
return s != null;
}
} | java | public boolean signal()
{
if (!hasWaiters())
return false;
while (true)
{
RegisteredSignal s = queue.poll();
if (s == null || s.signal() != null)
return s != null;
}
} | [
"public",
"boolean",
"signal",
"(",
")",
"{",
"if",
"(",
"!",
"hasWaiters",
"(",
")",
")",
"return",
"false",
";",
"while",
"(",
"true",
")",
"{",
"RegisteredSignal",
"s",
"=",
"queue",
".",
"poll",
"(",
")",
";",
"if",
"(",
"s",
"==",
"null",
"|... | Signal one waiting thread | [
"Signal",
"one",
"waiting",
"thread"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/concurrent/WaitQueue.java#L114-L124 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/utils/concurrent/WaitQueue.java | WaitQueue.signalAll | public void signalAll()
{
if (!hasWaiters())
return;
// to avoid a race where the condition is not met and the woken thread managed to wait on the queue before
// we finish signalling it all, we pick a random thread we have woken-up and hold onto it, so that if we encounter
// it again we know we're looping. We reselect a random thread periodically, progressively less often.
// the "correct" solution to this problem is to use a queue that permits snapshot iteration, but this solution is sufficient
int i = 0, s = 5;
Thread randomThread = null;
Iterator<RegisteredSignal> iter = queue.iterator();
while (iter.hasNext())
{
RegisteredSignal signal = iter.next();
Thread signalled = signal.signal();
if (signalled != null)
{
if (signalled == randomThread)
break;
if (++i == s)
{
randomThread = signalled;
s <<= 1;
}
}
iter.remove();
}
} | java | public void signalAll()
{
if (!hasWaiters())
return;
// to avoid a race where the condition is not met and the woken thread managed to wait on the queue before
// we finish signalling it all, we pick a random thread we have woken-up and hold onto it, so that if we encounter
// it again we know we're looping. We reselect a random thread periodically, progressively less often.
// the "correct" solution to this problem is to use a queue that permits snapshot iteration, but this solution is sufficient
int i = 0, s = 5;
Thread randomThread = null;
Iterator<RegisteredSignal> iter = queue.iterator();
while (iter.hasNext())
{
RegisteredSignal signal = iter.next();
Thread signalled = signal.signal();
if (signalled != null)
{
if (signalled == randomThread)
break;
if (++i == s)
{
randomThread = signalled;
s <<= 1;
}
}
iter.remove();
}
} | [
"public",
"void",
"signalAll",
"(",
")",
"{",
"if",
"(",
"!",
"hasWaiters",
"(",
")",
")",
"return",
";",
"// to avoid a race where the condition is not met and the woken thread managed to wait on the queue before",
"// we finish signalling it all, we pick a random thread we have wok... | Signal all waiting threads | [
"Signal",
"all",
"waiting",
"threads"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/concurrent/WaitQueue.java#L129-L160 | train |
Stratio/stratio-cassandra | src/java/org/apache/cassandra/utils/concurrent/WaitQueue.java | WaitQueue.getWaiting | public int getWaiting()
{
if (!hasWaiters())
return 0;
Iterator<RegisteredSignal> iter = queue.iterator();
int count = 0;
while (iter.hasNext())
{
Signal next = iter.next();
if (!next.isCancelled())
count++;
}
return count;
} | java | public int getWaiting()
{
if (!hasWaiters())
return 0;
Iterator<RegisteredSignal> iter = queue.iterator();
int count = 0;
while (iter.hasNext())
{
Signal next = iter.next();
if (!next.isCancelled())
count++;
}
return count;
} | [
"public",
"int",
"getWaiting",
"(",
")",
"{",
"if",
"(",
"!",
"hasWaiters",
"(",
")",
")",
"return",
"0",
";",
"Iterator",
"<",
"RegisteredSignal",
">",
"iter",
"=",
"queue",
".",
"iterator",
"(",
")",
";",
"int",
"count",
"=",
"0",
";",
"while",
"... | Return how many threads are waiting
@return | [
"Return",
"how",
"many",
"threads",
"are",
"waiting"
] | f6416b43ad5309083349ad56266450fa8c6a2106 | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/utils/concurrent/WaitQueue.java#L183-L196 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.