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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java | LogUtils.createFullReportLog | public static void createFullReportLog(String sessionLogDir)
throws Exception {
File xml_logs_report_file = new File(sessionLogDir + File.separator
+ "report_logs.xml");
if (xml_logs_report_file.exists()) {
xml_logs_report_file.delete();
xml_logs_report_file.createNewFile();
}
xml_logs_report_file = new File(sessionLogDir + File.separator
+ "report_logs.xml");
OutputStream report_logs = new FileOutputStream(xml_logs_report_file);
List<File> files = null;
Document result = null;
files = getFileListing(new File(sessionLogDir));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
// Create the document
Document doc = builder.newDocument();
// Fill the document
Element execution = doc.createElement("execution");
execution.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xi",
"http://www.w3.org/2001/XInclude");
doc.appendChild(execution);
for (File file : files) {
// all files are Sorted with CompareTO
Element include = doc.createElementNS(
"http://www.w3.org/2001/XInclude", "xi:include");
include.setAttribute("href", file.getAbsolutePath());
execution.appendChild(include);
}
// Serialize the document into System.out
TransformerFactory xformFactory = TransformerFactory.newInstance();
//Fortify Mod: disable external entity injection
xformFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer idTransform = xformFactory.newTransformer();
Source input = new DOMSource(doc);
Result output = new StreamResult(report_logs);
idTransform.transform(input, output);
// Fortify Mod: Close report_logs and release its resources
report_logs.close();
result = doc; // actually we do not needs results
} | java | public static void createFullReportLog(String sessionLogDir)
throws Exception {
File xml_logs_report_file = new File(sessionLogDir + File.separator
+ "report_logs.xml");
if (xml_logs_report_file.exists()) {
xml_logs_report_file.delete();
xml_logs_report_file.createNewFile();
}
xml_logs_report_file = new File(sessionLogDir + File.separator
+ "report_logs.xml");
OutputStream report_logs = new FileOutputStream(xml_logs_report_file);
List<File> files = null;
Document result = null;
files = getFileListing(new File(sessionLogDir));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
factory.setExpandEntityReferences(false);
DocumentBuilder builder = factory.newDocumentBuilder();
// Create the document
Document doc = builder.newDocument();
// Fill the document
Element execution = doc.createElement("execution");
execution.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xi",
"http://www.w3.org/2001/XInclude");
doc.appendChild(execution);
for (File file : files) {
// all files are Sorted with CompareTO
Element include = doc.createElementNS(
"http://www.w3.org/2001/XInclude", "xi:include");
include.setAttribute("href", file.getAbsolutePath());
execution.appendChild(include);
}
// Serialize the document into System.out
TransformerFactory xformFactory = TransformerFactory.newInstance();
//Fortify Mod: disable external entity injection
xformFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
Transformer idTransform = xformFactory.newTransformer();
Source input = new DOMSource(doc);
Result output = new StreamResult(report_logs);
idTransform.transform(input, output);
// Fortify Mod: Close report_logs and release its resources
report_logs.close();
result = doc; // actually we do not needs results
} | [
"public",
"static",
"void",
"createFullReportLog",
"(",
"String",
"sessionLogDir",
")",
"throws",
"Exception",
"{",
"File",
"xml_logs_report_file",
"=",
"new",
"File",
"(",
"sessionLogDir",
"+",
"File",
".",
"separator",
"+",
"\"report_logs.xml\"",
")",
";",
"if",... | Generate a file in logDir refererring all logfiles. Create a file called
"report_logs.xml" in the log folder that includes all logs listed inside
the directory.
@param sessionLogDir
considered log directory
@throws Exception
@author F.Vitale vitale@imaa.cnr.it | [
"Generate",
"a",
"file",
"in",
"logDir",
"refererring",
"all",
"logfiles",
".",
"Create",
"a",
"file",
"called",
"report_logs",
".",
"xml",
"in",
"the",
"log",
"folder",
"that",
"includes",
"all",
"logs",
"listed",
"inside",
"the",
"directory",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java#L441-L488 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java | LogUtils.getFileListing | private static List<File> getFileListing(File logDir) throws Exception {
List<File> result = getFileListingLogs(logDir);
return result;
} | java | private static List<File> getFileListing(File logDir) throws Exception {
List<File> result = getFileListingLogs(logDir);
return result;
} | [
"private",
"static",
"List",
"<",
"File",
">",
"getFileListing",
"(",
"File",
"logDir",
")",
"throws",
"Exception",
"{",
"List",
"<",
"File",
">",
"result",
"=",
"getFileListingLogs",
"(",
"logDir",
")",
";",
"return",
"result",
";",
"}"
] | Recursively walk a directory tree and return a List of all log files
found.
@param logDir
die to walk
@return
@throws Exception | [
"Recursively",
"walk",
"a",
"directory",
"tree",
"and",
"return",
"a",
"List",
"of",
"all",
"log",
"files",
"found",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java#L500-L503 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java | LogUtils.getFileListingLogs | static private List<File> getFileListingLogs(File aStartingDir)
throws Exception {
List<File> result = new ArrayList<File>();
File[] logfiles = aStartingDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile();
}
});
List<File> logFilesList = Arrays.asList(logfiles);
File[] allDirs = aStartingDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (File file : logFilesList) {
if (file.getName().equals("log.xml")) {
result.add(file);
}
}
List<File> allDirsList = Arrays.asList(allDirs);
Collections.sort(allDirsList, new Comparator<File>() {
public int compare(File o1, File o2) {
if (o1.lastModified() > o2.lastModified()) {
return +1;
} else if (o1.lastModified() < o2.lastModified()) {
return -1;
} else {
return 0;
}
}
});
for (File file : allDirsList) {
if (!file.isFile()) {
List<File> deeperList = getFileListingLogs(file);
result.addAll(deeperList);
}
}
return result;
} | java | static private List<File> getFileListingLogs(File aStartingDir)
throws Exception {
List<File> result = new ArrayList<File>();
File[] logfiles = aStartingDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isFile();
}
});
List<File> logFilesList = Arrays.asList(logfiles);
File[] allDirs = aStartingDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (File file : logFilesList) {
if (file.getName().equals("log.xml")) {
result.add(file);
}
}
List<File> allDirsList = Arrays.asList(allDirs);
Collections.sort(allDirsList, new Comparator<File>() {
public int compare(File o1, File o2) {
if (o1.lastModified() > o2.lastModified()) {
return +1;
} else if (o1.lastModified() < o2.lastModified()) {
return -1;
} else {
return 0;
}
}
});
for (File file : allDirsList) {
if (!file.isFile()) {
List<File> deeperList = getFileListingLogs(file);
result.addAll(deeperList);
}
}
return result;
} | [
"static",
"private",
"List",
"<",
"File",
">",
"getFileListingLogs",
"(",
"File",
"aStartingDir",
")",
"throws",
"Exception",
"{",
"List",
"<",
"File",
">",
"result",
"=",
"new",
"ArrayList",
"<",
"File",
">",
"(",
")",
";",
"File",
"[",
"]",
"logfiles",... | Get all log files and directories and make recursive call.
@param aStartingDir
@return
@throws Exception | [
"Get",
"all",
"log",
"files",
"and",
"directories",
"and",
"make",
"recursive",
"call",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/LogUtils.java#L512-L555 | train |
opengeospatial/teamengine | teamengine-web/src/main/java/com/occamlab/te/web/CoverageMonitor.java | CoverageMonitor.writeCoverageResults | public void writeCoverageResults() {
File coverageFile = new File(this.testSessionDir,
ICS_MAP.get(this.requestId));
if (coverageFile.exists()) {
return;
}
OutputStream fos = null;
try {
fos = new FileOutputStream(coverageFile, false);
writeDocument(fos, this.coverageDoc);
} catch (FileNotFoundException e) {
} finally {
try {
// Fortify Mod: If fos is null, then nothing was written
if( fos != null) {
fos.close();
LOGR.config("Wrote coverage results to "
+ coverageFile.getCanonicalPath());
}
else {
// If nothing was written, then there should be an exception message.
// If an additional message is desired, then add it here.
}
} catch (IOException ioe) {
LOGR.warning(ioe.getMessage());
}
}
} | java | public void writeCoverageResults() {
File coverageFile = new File(this.testSessionDir,
ICS_MAP.get(this.requestId));
if (coverageFile.exists()) {
return;
}
OutputStream fos = null;
try {
fos = new FileOutputStream(coverageFile, false);
writeDocument(fos, this.coverageDoc);
} catch (FileNotFoundException e) {
} finally {
try {
// Fortify Mod: If fos is null, then nothing was written
if( fos != null) {
fos.close();
LOGR.config("Wrote coverage results to "
+ coverageFile.getCanonicalPath());
}
else {
// If nothing was written, then there should be an exception message.
// If an additional message is desired, then add it here.
}
} catch (IOException ioe) {
LOGR.warning(ioe.getMessage());
}
}
} | [
"public",
"void",
"writeCoverageResults",
"(",
")",
"{",
"File",
"coverageFile",
"=",
"new",
"File",
"(",
"this",
".",
"testSessionDir",
",",
"ICS_MAP",
".",
"get",
"(",
"this",
".",
"requestId",
")",
")",
";",
"if",
"(",
"coverageFile",
".",
"exists",
"... | Writes the residual ICS document to a file in the test session directory. | [
"Writes",
"the",
"residual",
"ICS",
"document",
"to",
"a",
"file",
"in",
"the",
"test",
"session",
"directory",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/CoverageMonitor.java#L198-L226 | train |
opengeospatial/teamengine | teamengine-web/src/main/java/com/occamlab/te/web/CoverageMonitor.java | CoverageMonitor.writeDocument | void writeDocument(OutputStream outStream, Document doc) {
DOMImplementationRegistry domRegistry = null;
try {
domRegistry = DOMImplementationRegistry.newInstance();
// Fortify Mod: Broaden try block to capture all potential exceptions
// } catch (Exception e) {
// LOGR.warning(e.getMessage());
// }
DOMImplementationLS impl = (DOMImplementationLS) domRegistry
.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("xml-declaration", false);
writer.getDomConfig().setParameter("format-pretty-print", true);
LSOutput output = impl.createLSOutput();
output.setEncoding("UTF-8");
output.setByteStream(outStream);
writer.write(doc, output);
} catch (Exception e) {
LOGR.warning(e.getMessage());
}
} | java | void writeDocument(OutputStream outStream, Document doc) {
DOMImplementationRegistry domRegistry = null;
try {
domRegistry = DOMImplementationRegistry.newInstance();
// Fortify Mod: Broaden try block to capture all potential exceptions
// } catch (Exception e) {
// LOGR.warning(e.getMessage());
// }
DOMImplementationLS impl = (DOMImplementationLS) domRegistry
.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("xml-declaration", false);
writer.getDomConfig().setParameter("format-pretty-print", true);
LSOutput output = impl.createLSOutput();
output.setEncoding("UTF-8");
output.setByteStream(outStream);
writer.write(doc, output);
} catch (Exception e) {
LOGR.warning(e.getMessage());
}
} | [
"void",
"writeDocument",
"(",
"OutputStream",
"outStream",
",",
"Document",
"doc",
")",
"{",
"DOMImplementationRegistry",
"domRegistry",
"=",
"null",
";",
"try",
"{",
"domRegistry",
"=",
"DOMImplementationRegistry",
".",
"newInstance",
"(",
")",
";",
"// Fortify Mod... | Writes a DOM Document to the given OutputStream using the "UTF-8"
encoding. The XML declaration is omitted.
@param outStream
The destination OutputStream object.
@param doc
A Document node. | [
"Writes",
"a",
"DOM",
"Document",
"to",
"the",
"given",
"OutputStream",
"using",
"the",
"UTF",
"-",
"8",
"encoding",
".",
"The",
"XML",
"declaration",
"is",
"omitted",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/CoverageMonitor.java#L237-L257 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/XMLParserUtils.java | XMLParserUtils.createXIncludeAwareSAXParser | public static SAXParser createXIncludeAwareSAXParser(boolean doBaseURIFixup) {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
SAXParser parser = null;
try {
factory.setFeature(Constants.XERCES_FEATURE_PREFIX
+ Constants.XINCLUDE_FIXUP_BASE_URIS_FEATURE,
doBaseURIFixup);
parser = factory.newSAXParser();
} catch (Exception x) {
throw new RuntimeException(x);
}
return parser;
} | java | public static SAXParser createXIncludeAwareSAXParser(boolean doBaseURIFixup) {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setXIncludeAware(true);
SAXParser parser = null;
try {
factory.setFeature(Constants.XERCES_FEATURE_PREFIX
+ Constants.XINCLUDE_FIXUP_BASE_URIS_FEATURE,
doBaseURIFixup);
parser = factory.newSAXParser();
} catch (Exception x) {
throw new RuntimeException(x);
}
return parser;
} | [
"public",
"static",
"SAXParser",
"createXIncludeAwareSAXParser",
"(",
"boolean",
"doBaseURIFixup",
")",
"{",
"SAXParserFactory",
"factory",
"=",
"SAXParserFactory",
".",
"newInstance",
"(",
")",
";",
"factory",
".",
"setNamespaceAware",
"(",
"true",
")",
";",
"facto... | Creates a SAXParser that is configured to resolve XInclude references but
not perform schema validation.
@param doBaseURIFixup
A boolean value that specifies whether or not to add xml:base
attributes when resolving xi:include elements; adding these
attributes may render an instance document schema-invalid.
@return An XInclude-aware SAXParser instance.
@see <a href="http://www.w3.org/TR/xinclude/">XML Inclusions (XInclude)
Version 1.0, Second Edition</a> | [
"Creates",
"a",
"SAXParser",
"that",
"is",
"configured",
"to",
"resolve",
"XInclude",
"references",
"but",
"not",
"perform",
"schema",
"validation",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/XMLParserUtils.java#L27-L41 | train |
opengeospatial/teamengine | teamengine-web/src/main/java/com/occamlab/te/web/listeners/CleartextPasswordContextListener.java | CleartextPasswordContextListener.contextInitialized | @Override
public void contextInitialized(ServletContextEvent evt) {
File usersDir = new File(SetupOptions.getBaseConfigDirectory(), "users");
if (!usersDir.isDirectory()) {
return;
}
DocumentBuilder domBuilder = null;
try {
domBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
LOGR.warning(e.getMessage());
return;
}
DOMImplementationLS lsFactory = buildDOM3LoadAndSaveFactory();
LSSerializer serializer = lsFactory.createLSSerializer();
serializer.getDomConfig().setParameter(Constants.DOM_XMLDECL, Boolean.FALSE);
serializer.getDomConfig().setParameter(Constants.DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
LSOutput output = lsFactory.createLSOutput();
output.setEncoding("UTF-8");
for (File userDir : usersDir.listFiles()) {
File userFile = new File(userDir, "user.xml");
if (!userFile.isFile()) {
continue;
}
try {
Document doc = domBuilder.parse(userFile);
Node pwNode = doc.getElementsByTagName("password").item(0);
if (null == pwNode) {
continue;
}
String password = pwNode.getTextContent();
if (password.split(":").length == 5) {
break;
}
pwNode.setTextContent(PasswordStorage.createHash(password));
// overwrite contents of file
// Fortify Mod: Make sure that the output stream is closed
// output.setByteStream(new FileOutputStream(userFile, false));
FileOutputStream os = new FileOutputStream(userFile, false);
output.setByteStream(os);
serializer.write(doc, output);
os.close();
} catch (Exception e) {
LOGR.info(e.getMessage());
continue;
}
}
} | java | @Override
public void contextInitialized(ServletContextEvent evt) {
File usersDir = new File(SetupOptions.getBaseConfigDirectory(), "users");
if (!usersDir.isDirectory()) {
return;
}
DocumentBuilder domBuilder = null;
try {
domBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
LOGR.warning(e.getMessage());
return;
}
DOMImplementationLS lsFactory = buildDOM3LoadAndSaveFactory();
LSSerializer serializer = lsFactory.createLSSerializer();
serializer.getDomConfig().setParameter(Constants.DOM_XMLDECL, Boolean.FALSE);
serializer.getDomConfig().setParameter(Constants.DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
LSOutput output = lsFactory.createLSOutput();
output.setEncoding("UTF-8");
for (File userDir : usersDir.listFiles()) {
File userFile = new File(userDir, "user.xml");
if (!userFile.isFile()) {
continue;
}
try {
Document doc = domBuilder.parse(userFile);
Node pwNode = doc.getElementsByTagName("password").item(0);
if (null == pwNode) {
continue;
}
String password = pwNode.getTextContent();
if (password.split(":").length == 5) {
break;
}
pwNode.setTextContent(PasswordStorage.createHash(password));
// overwrite contents of file
// Fortify Mod: Make sure that the output stream is closed
// output.setByteStream(new FileOutputStream(userFile, false));
FileOutputStream os = new FileOutputStream(userFile, false);
output.setByteStream(os);
serializer.write(doc, output);
os.close();
} catch (Exception e) {
LOGR.info(e.getMessage());
continue;
}
}
} | [
"@",
"Override",
"public",
"void",
"contextInitialized",
"(",
"ServletContextEvent",
"evt",
")",
"{",
"File",
"usersDir",
"=",
"new",
"File",
"(",
"SetupOptions",
".",
"getBaseConfigDirectory",
"(",
")",
",",
"\"users\"",
")",
";",
"if",
"(",
"!",
"usersDir",
... | Checks that passwords in the user files are not in clear text. If a hash
value is found for some user, it is assumed that all user passwords have
previously been hashed and no further checks are done. | [
"Checks",
"that",
"passwords",
"in",
"the",
"user",
"files",
"are",
"not",
"in",
"clear",
"text",
".",
"If",
"a",
"hash",
"value",
"is",
"found",
"for",
"some",
"user",
"it",
"is",
"assumed",
"that",
"all",
"user",
"passwords",
"have",
"previously",
"bee... | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/listeners/CleartextPasswordContextListener.java#L57-L104 | train |
opengeospatial/teamengine | teamengine-web/src/main/java/com/occamlab/te/web/listeners/CleartextPasswordContextListener.java | CleartextPasswordContextListener.buildDOM3LoadAndSaveFactory | DOMImplementationLS buildDOM3LoadAndSaveFactory() {
DOMImplementationLS factory = null;
try {
DOMImplementationRegistry domRegistry = DOMImplementationRegistry.newInstance();
factory = (DOMImplementationLS) domRegistry.getDOMImplementation("LS 3.0");
} catch (Exception e) {
LOGR.log(Level.WARNING, "Failed to create DOMImplementationLS", e);
}
return factory;
} | java | DOMImplementationLS buildDOM3LoadAndSaveFactory() {
DOMImplementationLS factory = null;
try {
DOMImplementationRegistry domRegistry = DOMImplementationRegistry.newInstance();
factory = (DOMImplementationLS) domRegistry.getDOMImplementation("LS 3.0");
} catch (Exception e) {
LOGR.log(Level.WARNING, "Failed to create DOMImplementationLS", e);
}
return factory;
} | [
"DOMImplementationLS",
"buildDOM3LoadAndSaveFactory",
"(",
")",
"{",
"DOMImplementationLS",
"factory",
"=",
"null",
";",
"try",
"{",
"DOMImplementationRegistry",
"domRegistry",
"=",
"DOMImplementationRegistry",
".",
"newInstance",
"(",
")",
";",
"factory",
"=",
"(",
"... | Builds a DOMImplementationLS factory that supports the
"DOM Level 3 Load and Save" specification. It provides various factory
methods for creating the objects required for loading and saving DOM
nodes.
@return A factory object, or <code>null</code> if one cannot be created
(in which case a warning will be logged).
@see <a href="https://www.w3.org/TR/DOM-Level-3-LS/">Document Object
Model (DOM) Level 3 Load and Save Specification, Version 1.0</a> | [
"Builds",
"a",
"DOMImplementationLS",
"factory",
"that",
"supports",
"the",
"DOM",
"Level",
"3",
"Load",
"and",
"Save",
"specification",
".",
"It",
"provides",
"various",
"factory",
"methods",
"for",
"creating",
"the",
"objects",
"required",
"for",
"loading",
"a... | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-web/src/main/java/com/occamlab/te/web/listeners/CleartextPasswordContextListener.java#L118-L127 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/Utils.java | Utils.randomString | public static String randomString(int len, Random random) {
if (len < 1) {
return "";
}
int start = ' ';
int end = 'z' + 1;
StringBuffer buffer = new StringBuffer();
int gap = end - start;
while (len-- != 0) {
char ch;
ch = (char) (random.nextInt(gap) + start);
if (Character.isLetterOrDigit(ch)) {
buffer.append(ch);
} else {
len++;
}
}
return buffer.toString();
} | java | public static String randomString(int len, Random random) {
if (len < 1) {
return "";
}
int start = ' ';
int end = 'z' + 1;
StringBuffer buffer = new StringBuffer();
int gap = end - start;
while (len-- != 0) {
char ch;
ch = (char) (random.nextInt(gap) + start);
if (Character.isLetterOrDigit(ch)) {
buffer.append(ch);
} else {
len++;
}
}
return buffer.toString();
} | [
"public",
"static",
"String",
"randomString",
"(",
"int",
"len",
",",
"Random",
"random",
")",
"{",
"if",
"(",
"len",
"<",
"1",
")",
"{",
"return",
"\"\"",
";",
"}",
"int",
"start",
"=",
"'",
"'",
";",
"int",
"end",
"=",
"'",
"'",
"+",
"1",
";"... | Returns a random string of a certain length | [
"Returns",
"a",
"random",
"string",
"of",
"a",
"certain",
"length"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/Utils.java#L47-L68 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/util/Utils.java | Utils.generateMD5 | public static String generateMD5(String text) {
byte[] md5hash = null;
try {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
md5hash = new byte[8];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
} catch (Exception e) {
jlogger.log(Level.SEVERE,
"Error generating MD5: " + e.getMessage(), e);
System.out.println("Error generating MD5: " + e.getMessage());
return "";
}
return convertToHex(md5hash);
} | java | public static String generateMD5(String text) {
byte[] md5hash = null;
try {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
md5hash = new byte[8];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
} catch (Exception e) {
jlogger.log(Level.SEVERE,
"Error generating MD5: " + e.getMessage(), e);
System.out.println("Error generating MD5: " + e.getMessage());
return "";
}
return convertToHex(md5hash);
} | [
"public",
"static",
"String",
"generateMD5",
"(",
"String",
"text",
")",
"{",
"byte",
"[",
"]",
"md5hash",
"=",
"null",
";",
"try",
"{",
"MessageDigest",
"md",
";",
"md",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"\"MD5\"",
")",
";",
"md5hash",
"=",... | Uses MD5 to create a hash value for the given String | [
"Uses",
"MD5",
"to",
"create",
"a",
"hash",
"value",
"for",
"the",
"given",
"String"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/util/Utils.java#L74-L90 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/TECore.java | TECore.build_soap_request | static public URLConnection build_soap_request(Node xml) throws Exception {
String sUrl = null;
String method = "POST";
String charset = ((Element) xml).getAttribute("charset").equals("") ? ((Element) xml)
.getAttribute("charset") : "UTF-8";
String version = ((Element) xml).getAttribute("version");
String action = "";
String contentType = "";
Element body = null;
// Read in the test information (from CTL)
NodeList nl = xml.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
if (n.getLocalName().equals("url")) {
sUrl = n.getTextContent();
} else if (n.getLocalName().equals("action")) {
action = n.getTextContent();
} // else if (n.getLocalName().equals("header")) {
// header = (org.w3c.dom.Element) n;
/*
* }
*/else if (n.getLocalName().equals("body")) {
body = (org.w3c.dom.Element) n;
}
}
}
// Get the list of the header blocks needed to build the SOAP Header
// section
List<Element> headerBloks = DomUtils.getElementsByTagNameNS(xml,
CTL_NS, HEADER_BLOCKS);
// Open the URLConnection
URLConnection uc = new URL(sUrl).openConnection();
if (uc instanceof HttpURLConnection) {
((HttpURLConnection) uc).setRequestMethod(method);
}
uc.setDoOutput(true);
byte[] bytes = null;
// SOAP POST
bytes = SoapUtils.getSoapMessageAsByte(version, headerBloks, body,
charset);
// System.out.println("SOAP MESSAGE " + new String(bytes));
uc.setRequestProperty("User-Agent", "Team Engine 1.2");
uc.setRequestProperty("Cache-Control", "no-cache");
uc.setRequestProperty("Pragma", "no-cache");
uc.setRequestProperty("charset", charset);
uc.setRequestProperty("Content-Length", Integer.toString(bytes.length));
if (version.equals(SOAP_V_1_1)) {
// Handle HTTP binding for SOAP 1.1
// uc.setRequestProperty("Accept", "application/soap+xml");
uc.setRequestProperty("Accept", "text/xml");
uc.setRequestProperty("SOAPAction", action);
contentType = "text/xml";
if (!charset.equals("")) {
contentType = contentType + "; charset=" + charset;
}
uc.setRequestProperty("Content-Type", contentType);
} else {
// Handle HTTP binding for SOAP 1.2
uc.setRequestProperty("Accept", "application/soap+xml");
contentType = "application/soap+xml";
if (!charset.equals("")) {
contentType = contentType + "; charset=" + charset;
}
if (!action.equals("")) {
contentType = contentType + "; action=" + action;
}
uc.setRequestProperty("Content-Type", contentType);
}
OutputStream os = uc.getOutputStream();
os.write(bytes);
return uc;
} | java | static public URLConnection build_soap_request(Node xml) throws Exception {
String sUrl = null;
String method = "POST";
String charset = ((Element) xml).getAttribute("charset").equals("") ? ((Element) xml)
.getAttribute("charset") : "UTF-8";
String version = ((Element) xml).getAttribute("version");
String action = "";
String contentType = "";
Element body = null;
// Read in the test information (from CTL)
NodeList nl = xml.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node n = nl.item(i);
if (n.getNodeType() == Node.ELEMENT_NODE) {
if (n.getLocalName().equals("url")) {
sUrl = n.getTextContent();
} else if (n.getLocalName().equals("action")) {
action = n.getTextContent();
} // else if (n.getLocalName().equals("header")) {
// header = (org.w3c.dom.Element) n;
/*
* }
*/else if (n.getLocalName().equals("body")) {
body = (org.w3c.dom.Element) n;
}
}
}
// Get the list of the header blocks needed to build the SOAP Header
// section
List<Element> headerBloks = DomUtils.getElementsByTagNameNS(xml,
CTL_NS, HEADER_BLOCKS);
// Open the URLConnection
URLConnection uc = new URL(sUrl).openConnection();
if (uc instanceof HttpURLConnection) {
((HttpURLConnection) uc).setRequestMethod(method);
}
uc.setDoOutput(true);
byte[] bytes = null;
// SOAP POST
bytes = SoapUtils.getSoapMessageAsByte(version, headerBloks, body,
charset);
// System.out.println("SOAP MESSAGE " + new String(bytes));
uc.setRequestProperty("User-Agent", "Team Engine 1.2");
uc.setRequestProperty("Cache-Control", "no-cache");
uc.setRequestProperty("Pragma", "no-cache");
uc.setRequestProperty("charset", charset);
uc.setRequestProperty("Content-Length", Integer.toString(bytes.length));
if (version.equals(SOAP_V_1_1)) {
// Handle HTTP binding for SOAP 1.1
// uc.setRequestProperty("Accept", "application/soap+xml");
uc.setRequestProperty("Accept", "text/xml");
uc.setRequestProperty("SOAPAction", action);
contentType = "text/xml";
if (!charset.equals("")) {
contentType = contentType + "; charset=" + charset;
}
uc.setRequestProperty("Content-Type", contentType);
} else {
// Handle HTTP binding for SOAP 1.2
uc.setRequestProperty("Accept", "application/soap+xml");
contentType = "application/soap+xml";
if (!charset.equals("")) {
contentType = contentType + "; charset=" + charset;
}
if (!action.equals("")) {
contentType = contentType + "; action=" + action;
}
uc.setRequestProperty("Content-Type", contentType);
}
OutputStream os = uc.getOutputStream();
os.write(bytes);
return uc;
} | [
"static",
"public",
"URLConnection",
"build_soap_request",
"(",
"Node",
"xml",
")",
"throws",
"Exception",
"{",
"String",
"sUrl",
"=",
"null",
";",
"String",
"method",
"=",
"\"POST\"",
";",
"String",
"charset",
"=",
"(",
"(",
"Element",
")",
"xml",
")",
".... | Create SOAP request, sends it and return an URL Connection ready to be
parsed.
@param xml
the soap-request node (from CTL)
@return The URL Connection
@throws Exception
the exception
<soap-request version="1.1|1.2" charset="UTF-8">
<url>http://blah</url> <action>Some-URI</action> <headers>
<header MutUnderstand="true" rely="true" role="http://etc">
<t:Transaction xmlns:t="some-URI" >5</t:Transaction>
</header> </headers> <body> <m:GetLastTradePrice
xmlns:m="Some-URI"> <symbol>DEF</symbol>
</m:GetLastTradePrice> </body> <parsers:SOAPParser
return="content"> <parsers:XMLValidatingParser>
<parsers:schemas> <parsers:schema
type="url">http://blah/schema.xsd</parsers:schema>
</parsers:schemas> </parsers:XMLValidatingParser>
</parsers:SOAPParser> </soap-request> | [
"Create",
"SOAP",
"request",
"sends",
"it",
"and",
"return",
"an",
"URL",
"Connection",
"ready",
"to",
"be",
"parsed",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/TECore.java#L1538-L1617 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/TECore.java | TECore.parse | public Element parse(URLConnection uc, Node instruction) throws Throwable {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document response_doc = db.newDocument();
return parse(uc, instruction, response_doc);
} | java | public Element parse(URLConnection uc, Node instruction) throws Throwable {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document response_doc = db.newDocument();
return parse(uc, instruction, response_doc);
} | [
"public",
"Element",
"parse",
"(",
"URLConnection",
"uc",
",",
"Node",
"instruction",
")",
"throws",
"Throwable",
"{",
"DocumentBuilderFactory",
"dbf",
"=",
"DocumentBuilderFactory",
".",
"newInstance",
"(",
")",
";",
"dbf",
".",
"setNamespaceAware",
"(",
"true",
... | Parses the content retrieved from some URI and builds a DOM Document
containing information extracted from the response message. Subsidiary
parsers are invoked in accord with the supplied parser instructions.
@param uc
A URLConnection object.
@param instruction
A Document or Element node containing parser instructions.
@return An Element containing selected info from a URLConnection as
specified by instruction Element and children. | [
"Parses",
"the",
"content",
"retrieved",
"from",
"some",
"URI",
"and",
"builds",
"a",
"DOM",
"Document",
"containing",
"information",
"extracted",
"from",
"the",
"response",
"message",
".",
"Subsidiary",
"parsers",
"are",
"invoked",
"in",
"accord",
"with",
"the"... | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/TECore.java#L2070-L2078 | train |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/TECore.java | TECore.findXMLResource | public Document findXMLResource(String name) {
URL url = this.getClass().getResource(name);
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
docFactory.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
docFactory.setExpandEntityReferences(false);
Document doc = null;
try {
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.parse(url.toURI().toString());
} catch (Exception e) {
LOGR.log(Level.WARNING, "Failed to parse classpath resource "
+ name, e);
}
return doc;
} | java | public Document findXMLResource(String name) {
URL url = this.getClass().getResource(name);
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
docFactory.setNamespaceAware(true);
// Fortify Mod: Disable entity expansion to foil External Entity Injections
docFactory.setExpandEntityReferences(false);
Document doc = null;
try {
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
doc = docBuilder.parse(url.toURI().toString());
} catch (Exception e) {
LOGR.log(Level.WARNING, "Failed to parse classpath resource "
+ name, e);
}
return doc;
} | [
"public",
"Document",
"findXMLResource",
"(",
"String",
"name",
")",
"{",
"URL",
"url",
"=",
"this",
".",
"getClass",
"(",
")",
".",
"getResource",
"(",
"name",
")",
";",
"DocumentBuilderFactory",
"docFactory",
"=",
"DocumentBuilderFactory",
".",
"newInstance",
... | Builds a DOM Document representing a classpath resource.
@param name
The name of an XML resource.
@return A Document node, or {@code null} if the resource cannot be parsed
for any reason. | [
"Builds",
"a",
"DOM",
"Document",
"representing",
"a",
"classpath",
"resource",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/TECore.java#L2550-L2566 | train |
opengeospatial/teamengine | teamengine-spi/src/main/java/com/occamlab/te/spi/util/HtmlReport.java | HtmlReport.earlHtmlReport | public static File earlHtmlReport( String outputDir )
throws FileNotFoundException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
String resourceDir = cl.getResource( "com/occamlab/te/earl/lib" ).getPath();
String earlXsl = cl.getResource( "com/occamlab/te/earl_html_report.xsl" ).toString();
File htmlOutput = new File( outputDir, "result" );
htmlOutput.mkdir();
LOGR.fine( "HTML output is written to directory " + htmlOutput );
File earlResult = new File( outputDir, "earl-results.rdf" );
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer( new StreamSource( earlXsl ) );
transformer.setParameter( "outputDir", htmlOutput );
File indexHtml = new File( htmlOutput, "index.html" );
indexHtml.createNewFile();
FileOutputStream outputStream = new FileOutputStream( indexHtml );
transformer.transform( new StreamSource( earlResult ), new StreamResult( outputStream ) );
// Foritfy Mod: Close the outputStream releasing its resources
outputStream.close();
FileUtils.copyDirectory( new File( resourceDir ), htmlOutput );
} catch ( Exception e ) {
LOGR.log( Level.SEVERE, "Transformation of EARL to HTML failed.", e );
throw new RuntimeException( e );
}
if ( !htmlOutput.exists() ) {
throw new FileNotFoundException( "HTML results not found at " + htmlOutput.getAbsolutePath() );
}
return htmlOutput;
} | java | public static File earlHtmlReport( String outputDir )
throws FileNotFoundException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
String resourceDir = cl.getResource( "com/occamlab/te/earl/lib" ).getPath();
String earlXsl = cl.getResource( "com/occamlab/te/earl_html_report.xsl" ).toString();
File htmlOutput = new File( outputDir, "result" );
htmlOutput.mkdir();
LOGR.fine( "HTML output is written to directory " + htmlOutput );
File earlResult = new File( outputDir, "earl-results.rdf" );
try {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer( new StreamSource( earlXsl ) );
transformer.setParameter( "outputDir", htmlOutput );
File indexHtml = new File( htmlOutput, "index.html" );
indexHtml.createNewFile();
FileOutputStream outputStream = new FileOutputStream( indexHtml );
transformer.transform( new StreamSource( earlResult ), new StreamResult( outputStream ) );
// Foritfy Mod: Close the outputStream releasing its resources
outputStream.close();
FileUtils.copyDirectory( new File( resourceDir ), htmlOutput );
} catch ( Exception e ) {
LOGR.log( Level.SEVERE, "Transformation of EARL to HTML failed.", e );
throw new RuntimeException( e );
}
if ( !htmlOutput.exists() ) {
throw new FileNotFoundException( "HTML results not found at " + htmlOutput.getAbsolutePath() );
}
return htmlOutput;
} | [
"public",
"static",
"File",
"earlHtmlReport",
"(",
"String",
"outputDir",
")",
"throws",
"FileNotFoundException",
"{",
"ClassLoader",
"cl",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassLoader",
"(",
")",
";",
"String",
"resourceDir",
"=",
... | Convert EARL result into HTML report.
@param outputDir
Location of the test result.
@return
Return the output file.
@throws FileNotFoundException
Throws exception if file is not available. | [
"Convert",
"EARL",
"result",
"into",
"HTML",
"report",
"."
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-spi/src/main/java/com/occamlab/te/spi/util/HtmlReport.java#L77-L108 | train |
opengeospatial/teamengine | teamengine-spi/src/main/java/com/occamlab/te/spi/util/HtmlReport.java | HtmlReport.addDir | private static void addDir(File dirObj, ZipOutputStream out)
throws IOException {
File[] dirList = dirObj.listFiles();
byte[] tmpBuf = new byte[1024];
for (int i = 0; i < dirList.length; i++) {
if (dirList[i].isDirectory()) {
addDir(dirList[i], out);
continue;
}
FileInputStream in = new FileInputStream(
dirList[i].getAbsolutePath());
System.out.println(" Adding: " + dirList[i].getAbsolutePath());
out.putNextEntry(new ZipEntry(dirList[i].getAbsolutePath()));
// Transfer from the file to the ZIP file
int len;
while ((len = in.read(tmpBuf)) > 0) {
out.write(tmpBuf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
} | java | private static void addDir(File dirObj, ZipOutputStream out)
throws IOException {
File[] dirList = dirObj.listFiles();
byte[] tmpBuf = new byte[1024];
for (int i = 0; i < dirList.length; i++) {
if (dirList[i].isDirectory()) {
addDir(dirList[i], out);
continue;
}
FileInputStream in = new FileInputStream(
dirList[i].getAbsolutePath());
System.out.println(" Adding: " + dirList[i].getAbsolutePath());
out.putNextEntry(new ZipEntry(dirList[i].getAbsolutePath()));
// Transfer from the file to the ZIP file
int len;
while ((len = in.read(tmpBuf)) > 0) {
out.write(tmpBuf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
} | [
"private",
"static",
"void",
"addDir",
"(",
"File",
"dirObj",
",",
"ZipOutputStream",
"out",
")",
"throws",
"IOException",
"{",
"File",
"[",
"]",
"dirList",
"=",
"dirObj",
".",
"listFiles",
"(",
")",
";",
"byte",
"[",
"]",
"tmpBuf",
"=",
"new",
"byte",
... | Add directory to zip file
@param dirObj
@param out
@throws IOException | [
"Add",
"directory",
"to",
"zip",
"file"
] | b6b890214b6784bbe19460bf753bdf28a9514bee | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-spi/src/main/java/com/occamlab/te/spi/util/HtmlReport.java#L149-L176 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/config/refresher/CarrierRefresher.java | CarrierRefresher.buildRefreshFallbackSequence | private Observable<ProposedBucketConfigContext> buildRefreshFallbackSequence(List<NodeInfo> nodeInfos, String bucketName) {
Observable<ProposedBucketConfigContext> failbackSequence = null;
for (final NodeInfo nodeInfo : nodeInfos) {
if (!isValidCarrierNode(environment.sslEnabled(), nodeInfo)) {
continue;
}
if (failbackSequence == null) {
failbackSequence = refreshAgainstNode(bucketName, nodeInfo.hostname());
} else {
failbackSequence = failbackSequence.onErrorResumeNext(
refreshAgainstNode(bucketName, nodeInfo.hostname())
);
}
}
if (failbackSequence == null) {
LOGGER.debug("Could not build refresh sequence, node list is empty - ignoring attempt.");
return Observable.empty();
}
return failbackSequence;
} | java | private Observable<ProposedBucketConfigContext> buildRefreshFallbackSequence(List<NodeInfo> nodeInfos, String bucketName) {
Observable<ProposedBucketConfigContext> failbackSequence = null;
for (final NodeInfo nodeInfo : nodeInfos) {
if (!isValidCarrierNode(environment.sslEnabled(), nodeInfo)) {
continue;
}
if (failbackSequence == null) {
failbackSequence = refreshAgainstNode(bucketName, nodeInfo.hostname());
} else {
failbackSequence = failbackSequence.onErrorResumeNext(
refreshAgainstNode(bucketName, nodeInfo.hostname())
);
}
}
if (failbackSequence == null) {
LOGGER.debug("Could not build refresh sequence, node list is empty - ignoring attempt.");
return Observable.empty();
}
return failbackSequence;
} | [
"private",
"Observable",
"<",
"ProposedBucketConfigContext",
">",
"buildRefreshFallbackSequence",
"(",
"List",
"<",
"NodeInfo",
">",
"nodeInfos",
",",
"String",
"bucketName",
")",
"{",
"Observable",
"<",
"ProposedBucketConfigContext",
">",
"failbackSequence",
"=",
"null... | Helper method which builds the refresh fallback sequence based on the node list.
@param nodeInfos the list of node infos.
@param bucketName the name of the bucket.
@return an observable containing flatMapped failback sequences. | [
"Helper",
"method",
"which",
"builds",
"the",
"refresh",
"fallback",
"sequence",
"based",
"on",
"the",
"node",
"list",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/refresher/CarrierRefresher.java#L267-L287 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/config/refresher/CarrierRefresher.java | CarrierRefresher.shiftNodeList | <T> void shiftNodeList(List<T> nodeList) {
int shiftBy = (int) (nodeOffset++ % nodeList.size());
for(int i = 0; i < shiftBy; i++) {
T element = nodeList.remove(0);
nodeList.add(element);
}
} | java | <T> void shiftNodeList(List<T> nodeList) {
int shiftBy = (int) (nodeOffset++ % nodeList.size());
for(int i = 0; i < shiftBy; i++) {
T element = nodeList.remove(0);
nodeList.add(element);
}
} | [
"<",
"T",
">",
"void",
"shiftNodeList",
"(",
"List",
"<",
"T",
">",
"nodeList",
")",
"{",
"int",
"shiftBy",
"=",
"(",
"int",
")",
"(",
"nodeOffset",
"++",
"%",
"nodeList",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
... | Helper method to transparently rearrange the node list based on the current global offset.
@param nodeList the list to shift. | [
"Helper",
"method",
"to",
"transparently",
"rearrange",
"the",
"node",
"list",
"based",
"on",
"the",
"current",
"global",
"offset",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/refresher/CarrierRefresher.java#L294-L300 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/config/refresher/CarrierRefresher.java | CarrierRefresher.isValidCarrierNode | private static boolean isValidCarrierNode(final boolean sslEnabled, final NodeInfo nodeInfo) {
if (sslEnabled && nodeInfo.sslServices().containsKey(ServiceType.BINARY)) {
return true;
} else if (nodeInfo.services().containsKey(ServiceType.BINARY)) {
return true;
}
return false;
} | java | private static boolean isValidCarrierNode(final boolean sslEnabled, final NodeInfo nodeInfo) {
if (sslEnabled && nodeInfo.sslServices().containsKey(ServiceType.BINARY)) {
return true;
} else if (nodeInfo.services().containsKey(ServiceType.BINARY)) {
return true;
}
return false;
} | [
"private",
"static",
"boolean",
"isValidCarrierNode",
"(",
"final",
"boolean",
"sslEnabled",
",",
"final",
"NodeInfo",
"nodeInfo",
")",
"{",
"if",
"(",
"sslEnabled",
"&&",
"nodeInfo",
".",
"sslServices",
"(",
")",
".",
"containsKey",
"(",
"ServiceType",
".",
"... | Helper method to detect if the given node can actually perform carrier refresh.
@param sslEnabled true if ssl enabled, false otherwise.
@param nodeInfo the node info for the given node.
@return true if it is a valid carrier node, false otherwise. | [
"Helper",
"method",
"to",
"detect",
"if",
"the",
"given",
"node",
"can",
"actually",
"perform",
"carrier",
"refresh",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/refresher/CarrierRefresher.java#L309-L316 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/config/refresher/CarrierRefresher.java | CarrierRefresher.allowedToPoll | private boolean allowedToPoll(final String bucket) {
Long bucketLastPollTimestamp = lastPollTimestamps.get(bucket);
return bucketLastPollTimestamp == null || ((System.nanoTime() - bucketLastPollTimestamp) >= pollFloorNs);
} | java | private boolean allowedToPoll(final String bucket) {
Long bucketLastPollTimestamp = lastPollTimestamps.get(bucket);
return bucketLastPollTimestamp == null || ((System.nanoTime() - bucketLastPollTimestamp) >= pollFloorNs);
} | [
"private",
"boolean",
"allowedToPoll",
"(",
"final",
"String",
"bucket",
")",
"{",
"Long",
"bucketLastPollTimestamp",
"=",
"lastPollTimestamps",
".",
"get",
"(",
"bucket",
")",
";",
"return",
"bucketLastPollTimestamp",
"==",
"null",
"||",
"(",
"(",
"System",
"."... | Returns true if polling is allowed, false if we are below the configured floor poll interval. | [
"Returns",
"true",
"if",
"polling",
"is",
"allowed",
"false",
"if",
"we",
"are",
"below",
"the",
"configured",
"floor",
"poll",
"interval",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/refresher/CarrierRefresher.java#L321-L324 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/utils/yasjl/JsonNumberByteBufProcessor.java | JsonNumberByteBufProcessor.process | public boolean process(byte value) throws Exception {
if (value == (byte) 'e' || value == (byte) 'E') {
return true;
}
if (value >= (byte) '0' && value <= (byte) '9') {
return true;
}
return value == JSON_MINUS || value == JSON_PLUS || value == (byte) '.';
} | java | public boolean process(byte value) throws Exception {
if (value == (byte) 'e' || value == (byte) 'E') {
return true;
}
if (value >= (byte) '0' && value <= (byte) '9') {
return true;
}
return value == JSON_MINUS || value == JSON_PLUS || value == (byte) '.';
} | [
"public",
"boolean",
"process",
"(",
"byte",
"value",
")",
"throws",
"Exception",
"{",
"if",
"(",
"value",
"==",
"(",
"byte",
")",
"'",
"'",
"||",
"value",
"==",
"(",
"byte",
")",
"'",
"'",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"value"... | not verifying if valid | [
"not",
"verifying",
"if",
"valid"
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/utils/yasjl/JsonNumberByteBufProcessor.java#L34-L42 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/ResponseHandler.java | ResponseHandler.bucketHasFastForwardMap | private static boolean bucketHasFastForwardMap(String bucketName, ClusterConfig clusterConfig) {
if (bucketName == null) {
return false;
}
BucketConfig bucketConfig = clusterConfig.bucketConfig(bucketName);
return bucketConfig != null && bucketConfig.hasFastForwardMap();
} | java | private static boolean bucketHasFastForwardMap(String bucketName, ClusterConfig clusterConfig) {
if (bucketName == null) {
return false;
}
BucketConfig bucketConfig = clusterConfig.bucketConfig(bucketName);
return bucketConfig != null && bucketConfig.hasFastForwardMap();
} | [
"private",
"static",
"boolean",
"bucketHasFastForwardMap",
"(",
"String",
"bucketName",
",",
"ClusterConfig",
"clusterConfig",
")",
"{",
"if",
"(",
"bucketName",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"BucketConfig",
"bucketConfig",
"=",
"clusterConf... | Helper method to check if the current given bucket contains a fast forward map.
@param bucketName the name of the bucket.
@param clusterConfig the current cluster configuration.
@return true if it has a ffwd-map, false otherwise. | [
"Helper",
"method",
"to",
"check",
"if",
"the",
"current",
"given",
"bucket",
"contains",
"a",
"fast",
"forward",
"map",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/ResponseHandler.java#L230-L236 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/ResponseStatusConverter.java | ResponseStatusConverter.fromBinary | public static ResponseStatus fromBinary(final short code) {
KeyValueStatus status = KeyValueStatus.valueOf(code);
switch (status) {
case SUCCESS:
return ResponseStatus.SUCCESS;
case ERR_EXISTS:
return ResponseStatus.EXISTS;
case ERR_NOT_FOUND:
return ResponseStatus.NOT_EXISTS;
case ERR_NOT_MY_VBUCKET:
return ResponseStatus.RETRY;
case ERR_NOT_STORED:
return ResponseStatus.NOT_STORED;
case ERR_TOO_BIG:
return ResponseStatus.TOO_BIG;
case ERR_TEMP_FAIL:
return ResponseStatus.TEMPORARY_FAILURE;
case ERR_BUSY:
return ResponseStatus.SERVER_BUSY;
case ERR_NO_MEM:
return ResponseStatus.OUT_OF_MEMORY;
case ERR_UNKNOWN_COMMAND:
return ResponseStatus.COMMAND_UNAVAILABLE;
case ERR_NOT_SUPPORTED:
return ResponseStatus.COMMAND_UNAVAILABLE;
case ERR_ACCESS:
return ResponseStatus.ACCESS_ERROR;
case ERR_INTERNAL:
return ResponseStatus.INTERNAL_ERROR;
case ERR_INVALID:
return ResponseStatus.INVALID_ARGUMENTS;
case ERR_DELTA_BADVAL:
return ResponseStatus.INVALID_ARGUMENTS;
case ERR_RANGE:
return ResponseStatus.RANGE_ERROR;
case ERR_ROLLBACK:
return ResponseStatus.ROLLBACK;
//== the following codes are for subdocument API ==
case ERR_SUBDOC_PATH_NOT_FOUND:
return ResponseStatus.SUBDOC_PATH_NOT_FOUND;
case ERR_SUBDOC_PATH_MISMATCH:
return ResponseStatus.SUBDOC_PATH_MISMATCH;
case ERR_SUBDOC_PATH_INVALID:
return ResponseStatus.SUBDOC_PATH_INVALID;
case ERR_SUBDOC_PATH_TOO_BIG:
return ResponseStatus.SUBDOC_PATH_TOO_BIG;
case ERR_SUBDOC_DOC_TOO_DEEP:
return ResponseStatus.SUBDOC_DOC_TOO_DEEP;
case ERR_SUBDOC_VALUE_CANTINSERT:
return ResponseStatus.SUBDOC_VALUE_CANTINSERT;
case ERR_SUBDOC_DOC_NOT_JSON:
return ResponseStatus.SUBDOC_DOC_NOT_JSON;
case ERR_SUBDOC_NUM_RANGE:
return ResponseStatus.SUBDOC_NUM_RANGE;
case ERR_SUBDOC_DELTA_RANGE:
return ResponseStatus.SUBDOC_DELTA_RANGE;
case ERR_SUBDOC_PATH_EXISTS:
return ResponseStatus.SUBDOC_PATH_EXISTS;
case ERR_SUBDOC_VALUE_TOO_DEEP:
return ResponseStatus.SUBDOC_VALUE_TOO_DEEP;
case ERR_SUBDOC_INVALID_COMBO:
return ResponseStatus.SUBDOC_INVALID_COMBO;
case ERR_SUBDOC_MULTI_PATH_FAILURE:
return ResponseStatus.SUBDOC_MULTI_PATH_FAILURE;
case ERR_SUBDOC_XATTR_INVALID_FLAG_COMBO:
return ResponseStatus.INTERNAL_ERROR;
case ERR_SUBDOC_XATTR_UNKNOWN_MACRO:
return ResponseStatus.SUBDOC_XATTR_UNKNOWN_MACRO;
case ERR_SUBDOC_XATTR_INVALID_KEY_COMBO:
return ResponseStatus.SUBDOC_XATTR_INVALID_KEY_COMBO;
//== end of subdocument API codes ==
}
return ResponseStatus.FAILURE;
} | java | public static ResponseStatus fromBinary(final short code) {
KeyValueStatus status = KeyValueStatus.valueOf(code);
switch (status) {
case SUCCESS:
return ResponseStatus.SUCCESS;
case ERR_EXISTS:
return ResponseStatus.EXISTS;
case ERR_NOT_FOUND:
return ResponseStatus.NOT_EXISTS;
case ERR_NOT_MY_VBUCKET:
return ResponseStatus.RETRY;
case ERR_NOT_STORED:
return ResponseStatus.NOT_STORED;
case ERR_TOO_BIG:
return ResponseStatus.TOO_BIG;
case ERR_TEMP_FAIL:
return ResponseStatus.TEMPORARY_FAILURE;
case ERR_BUSY:
return ResponseStatus.SERVER_BUSY;
case ERR_NO_MEM:
return ResponseStatus.OUT_OF_MEMORY;
case ERR_UNKNOWN_COMMAND:
return ResponseStatus.COMMAND_UNAVAILABLE;
case ERR_NOT_SUPPORTED:
return ResponseStatus.COMMAND_UNAVAILABLE;
case ERR_ACCESS:
return ResponseStatus.ACCESS_ERROR;
case ERR_INTERNAL:
return ResponseStatus.INTERNAL_ERROR;
case ERR_INVALID:
return ResponseStatus.INVALID_ARGUMENTS;
case ERR_DELTA_BADVAL:
return ResponseStatus.INVALID_ARGUMENTS;
case ERR_RANGE:
return ResponseStatus.RANGE_ERROR;
case ERR_ROLLBACK:
return ResponseStatus.ROLLBACK;
//== the following codes are for subdocument API ==
case ERR_SUBDOC_PATH_NOT_FOUND:
return ResponseStatus.SUBDOC_PATH_NOT_FOUND;
case ERR_SUBDOC_PATH_MISMATCH:
return ResponseStatus.SUBDOC_PATH_MISMATCH;
case ERR_SUBDOC_PATH_INVALID:
return ResponseStatus.SUBDOC_PATH_INVALID;
case ERR_SUBDOC_PATH_TOO_BIG:
return ResponseStatus.SUBDOC_PATH_TOO_BIG;
case ERR_SUBDOC_DOC_TOO_DEEP:
return ResponseStatus.SUBDOC_DOC_TOO_DEEP;
case ERR_SUBDOC_VALUE_CANTINSERT:
return ResponseStatus.SUBDOC_VALUE_CANTINSERT;
case ERR_SUBDOC_DOC_NOT_JSON:
return ResponseStatus.SUBDOC_DOC_NOT_JSON;
case ERR_SUBDOC_NUM_RANGE:
return ResponseStatus.SUBDOC_NUM_RANGE;
case ERR_SUBDOC_DELTA_RANGE:
return ResponseStatus.SUBDOC_DELTA_RANGE;
case ERR_SUBDOC_PATH_EXISTS:
return ResponseStatus.SUBDOC_PATH_EXISTS;
case ERR_SUBDOC_VALUE_TOO_DEEP:
return ResponseStatus.SUBDOC_VALUE_TOO_DEEP;
case ERR_SUBDOC_INVALID_COMBO:
return ResponseStatus.SUBDOC_INVALID_COMBO;
case ERR_SUBDOC_MULTI_PATH_FAILURE:
return ResponseStatus.SUBDOC_MULTI_PATH_FAILURE;
case ERR_SUBDOC_XATTR_INVALID_FLAG_COMBO:
return ResponseStatus.INTERNAL_ERROR;
case ERR_SUBDOC_XATTR_UNKNOWN_MACRO:
return ResponseStatus.SUBDOC_XATTR_UNKNOWN_MACRO;
case ERR_SUBDOC_XATTR_INVALID_KEY_COMBO:
return ResponseStatus.SUBDOC_XATTR_INVALID_KEY_COMBO;
//== end of subdocument API codes ==
}
return ResponseStatus.FAILURE;
} | [
"public",
"static",
"ResponseStatus",
"fromBinary",
"(",
"final",
"short",
"code",
")",
"{",
"KeyValueStatus",
"status",
"=",
"KeyValueStatus",
".",
"valueOf",
"(",
"code",
")",
";",
"switch",
"(",
"status",
")",
"{",
"case",
"SUCCESS",
":",
"return",
"Respo... | Convert the binary protocol status in a typesafe enum that can be acted upon later.
@param code the status to convert.
@return the converted response status. | [
"Convert",
"the",
"binary",
"protocol",
"status",
"in",
"a",
"typesafe",
"enum",
"that",
"can",
"be",
"acted",
"upon",
"later",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/ResponseStatusConverter.java#L64-L137 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/ResponseStatusConverter.java | ResponseStatusConverter.readErrorCodeFromErrorMap | public static ErrorMap.ErrorCode readErrorCodeFromErrorMap(final short code) {
if (BINARY_ERROR_MAP == null) {
LOGGER.trace("Binary error map unavailable");
return null;
}
ErrorMap.ErrorCode result = BINARY_ERROR_MAP.errors().get(code);
return result;
} | java | public static ErrorMap.ErrorCode readErrorCodeFromErrorMap(final short code) {
if (BINARY_ERROR_MAP == null) {
LOGGER.trace("Binary error map unavailable");
return null;
}
ErrorMap.ErrorCode result = BINARY_ERROR_MAP.errors().get(code);
return result;
} | [
"public",
"static",
"ErrorMap",
".",
"ErrorCode",
"readErrorCodeFromErrorMap",
"(",
"final",
"short",
"code",
")",
"{",
"if",
"(",
"BINARY_ERROR_MAP",
"==",
"null",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"Binary error map unavailable\"",
")",
";",
"return",
"n... | Get the error code from Key Value error map
@param code the status to convert. | [
"Get",
"the",
"error",
"code",
"from",
"Key",
"Value",
"error",
"map"
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/ResponseStatusConverter.java#L144-L151 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/ResponseStatusConverter.java | ResponseStatusConverter.fromHttp | public static ResponseStatus fromHttp(final int code) {
ResponseStatus status;
switch (code) {
case HTTP_OK:
case HTTP_CREATED:
case HTTP_ACCEPTED:
status = ResponseStatus.SUCCESS;
break;
case HTTP_NOT_FOUND:
status = ResponseStatus.NOT_EXISTS;
break;
case HTTP_BAD_REQUEST:
status = ResponseStatus.INVALID_ARGUMENTS;
break;
case HTTP_INTERNAL_ERROR:
status = ResponseStatus.INTERNAL_ERROR;
break;
case HTTP_UNAUTHORIZED:
status = ResponseStatus.ACCESS_ERROR;
break;
case HTTP_TOO_MANY_REQUESTS:
status = ResponseStatus.FAILURE;
break;
default:
LOGGER.warn("Unknown ResponseStatus with Protocol HTTP: {}", code);
status = ResponseStatus.FAILURE;
}
return status;
} | java | public static ResponseStatus fromHttp(final int code) {
ResponseStatus status;
switch (code) {
case HTTP_OK:
case HTTP_CREATED:
case HTTP_ACCEPTED:
status = ResponseStatus.SUCCESS;
break;
case HTTP_NOT_FOUND:
status = ResponseStatus.NOT_EXISTS;
break;
case HTTP_BAD_REQUEST:
status = ResponseStatus.INVALID_ARGUMENTS;
break;
case HTTP_INTERNAL_ERROR:
status = ResponseStatus.INTERNAL_ERROR;
break;
case HTTP_UNAUTHORIZED:
status = ResponseStatus.ACCESS_ERROR;
break;
case HTTP_TOO_MANY_REQUESTS:
status = ResponseStatus.FAILURE;
break;
default:
LOGGER.warn("Unknown ResponseStatus with Protocol HTTP: {}", code);
status = ResponseStatus.FAILURE;
}
return status;
} | [
"public",
"static",
"ResponseStatus",
"fromHttp",
"(",
"final",
"int",
"code",
")",
"{",
"ResponseStatus",
"status",
";",
"switch",
"(",
"code",
")",
"{",
"case",
"HTTP_OK",
":",
"case",
"HTTP_CREATED",
":",
"case",
"HTTP_ACCEPTED",
":",
"status",
"=",
"Resp... | Convert the http protocol status in a typesafe enum that can be acted upon later.
@param code the status to convert.
@return the converted response status. | [
"Convert",
"the",
"http",
"protocol",
"status",
"in",
"a",
"typesafe",
"enum",
"that",
"can",
"be",
"acted",
"upon",
"later",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/ResponseStatusConverter.java#L159-L187 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/ResponseStatusConverter.java | ResponseStatusConverter.updateBinaryErrorMap | public static void updateBinaryErrorMap(final ErrorMap map) {
if (map == null) {
return;
}
if (BINARY_ERROR_MAP == null || map.compareTo(BINARY_ERROR_MAP) > 0) {
BINARY_ERROR_MAP = map;
}
} | java | public static void updateBinaryErrorMap(final ErrorMap map) {
if (map == null) {
return;
}
if (BINARY_ERROR_MAP == null || map.compareTo(BINARY_ERROR_MAP) > 0) {
BINARY_ERROR_MAP = map;
}
} | [
"public",
"static",
"void",
"updateBinaryErrorMap",
"(",
"final",
"ErrorMap",
"map",
")",
"{",
"if",
"(",
"map",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"BINARY_ERROR_MAP",
"==",
"null",
"||",
"map",
".",
"compareTo",
"(",
"BINARY_ERROR_MAP"... | Updates the current error map in use for all uses of the response status converter.
If the provided one is older than the one stored, this update operation will be ignored.
@param map the map in use, it always uses the latest one. | [
"Updates",
"the",
"current",
"error",
"map",
"in",
"use",
"for",
"all",
"uses",
"of",
"the",
"response",
"status",
"converter",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/ResponseStatusConverter.java#L204-L212 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/lang/Tuple.java | Tuple.create | public static <T1, T2> Tuple2<T1, T2> create(final T1 v1, final T2 v2) {
return new Tuple2<T1, T2>(v1, v2);
} | java | public static <T1, T2> Tuple2<T1, T2> create(final T1 v1, final T2 v2) {
return new Tuple2<T1, T2>(v1, v2);
} | [
"public",
"static",
"<",
"T1",
",",
"T2",
">",
"Tuple2",
"<",
"T1",
",",
"T2",
">",
"create",
"(",
"final",
"T1",
"v1",
",",
"final",
"T2",
"v2",
")",
"{",
"return",
"new",
"Tuple2",
"<",
"T1",
",",
"T2",
">",
"(",
"v1",
",",
"v2",
")",
";",
... | Creates a tuple with two values.
@param v1 the first value.
@param v2 the second value.
@return a tuple containing the values. | [
"Creates",
"a",
"tuple",
"with",
"two",
"values",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/lang/Tuple.java#L44-L46 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/lang/Tuple.java | Tuple.create | public static <T1, T2, T3> Tuple3<T1, T2, T3> create(final T1 v1, final T2 v2, final T3 v3) {
return new Tuple3<T1, T2, T3>(v1, v2, v3);
} | java | public static <T1, T2, T3> Tuple3<T1, T2, T3> create(final T1 v1, final T2 v2, final T3 v3) {
return new Tuple3<T1, T2, T3>(v1, v2, v3);
} | [
"public",
"static",
"<",
"T1",
",",
"T2",
",",
"T3",
">",
"Tuple3",
"<",
"T1",
",",
"T2",
",",
"T3",
">",
"create",
"(",
"final",
"T1",
"v1",
",",
"final",
"T2",
"v2",
",",
"final",
"T3",
"v3",
")",
"{",
"return",
"new",
"Tuple3",
"<",
"T1",
... | Creates a tuple with three values.
@param v1 the first value.
@param v2 the second value.
@param v3 the third value.
@return a tuple containing the values. | [
"Creates",
"a",
"tuple",
"with",
"three",
"values",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/lang/Tuple.java#L56-L58 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/lang/Tuple.java | Tuple.create | public static <T1, T2, T3, T4> Tuple4<T1, T2, T3, T4> create(final T1 v1, final T2 v2, final T3 v3, final T4 v4) {
return new Tuple4<T1, T2, T3, T4>(v1, v2, v3, v4);
} | java | public static <T1, T2, T3, T4> Tuple4<T1, T2, T3, T4> create(final T1 v1, final T2 v2, final T3 v3, final T4 v4) {
return new Tuple4<T1, T2, T3, T4>(v1, v2, v3, v4);
} | [
"public",
"static",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
">",
"Tuple4",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
">",
"create",
"(",
"final",
"T1",
"v1",
",",
"final",
"T2",
"v2",
",",
"final",
"T3",
"v3",
",",
"final",
"T4",
"v4",
... | Creates a tuple with four values.
@param v1 the first value.
@param v2 the second value.
@param v3 the third value.
@param v4 the fourth value.
@return a tuple containing the values. | [
"Creates",
"a",
"tuple",
"with",
"four",
"values",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/lang/Tuple.java#L69-L71 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/lang/Tuple.java | Tuple.create | public static <T1, T2, T3, T4, T5> Tuple5<T1, T2, T3, T4, T5> create(final T1 v1, final T2 v2, final T3 v3,
final T4 v4, final T5 v5) {
return new Tuple5<T1, T2, T3, T4, T5>(v1, v2, v3, v4, v5);
} | java | public static <T1, T2, T3, T4, T5> Tuple5<T1, T2, T3, T4, T5> create(final T1 v1, final T2 v2, final T3 v3,
final T4 v4, final T5 v5) {
return new Tuple5<T1, T2, T3, T4, T5>(v1, v2, v3, v4, v5);
} | [
"public",
"static",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
">",
"Tuple5",
"<",
"T1",
",",
"T2",
",",
"T3",
",",
"T4",
",",
"T5",
">",
"create",
"(",
"final",
"T1",
"v1",
",",
"final",
"T2",
"v2",
",",
"final",
"T3",
"v3",
",... | Creates a tuple with five values.
@param v1 the first value.
@param v2 the second value.
@param v3 the third value.
@param v4 the fourth value.
@param v5 the fifth value.
@return a tuple containing the values. | [
"Creates",
"a",
"tuple",
"with",
"five",
"values",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/lang/Tuple.java#L83-L86 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/message/internal/DiagnosticsReport.java | DiagnosticsReport.exportToJson | public String exportToJson(boolean pretty) {
Map<String, Object> result = new HashMap<String, Object>();
Map<String, List<Map<String, Object>>> services = new HashMap<String, List<Map<String, Object>>>();
for (EndpointHealth h : endpoints) {
String type = serviceTypeFromEnum(h.type());
if (!services.containsKey(type)) {
services.put(type, new ArrayList<Map<String, Object>>());
}
List<Map<String, Object>> eps = services.get(type);
eps.add(h.toMap());
}
result.put("version", version);
result.put("services", services);
result.put("sdk", sdk);
result.put("id", id);
try {
if (pretty) {
return DefaultObjectMapper.prettyWriter().writeValueAsString(result);
} else {
return DefaultObjectMapper.writeValueAsString(result);
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not encode as JSON string.", e);
}
} | java | public String exportToJson(boolean pretty) {
Map<String, Object> result = new HashMap<String, Object>();
Map<String, List<Map<String, Object>>> services = new HashMap<String, List<Map<String, Object>>>();
for (EndpointHealth h : endpoints) {
String type = serviceTypeFromEnum(h.type());
if (!services.containsKey(type)) {
services.put(type, new ArrayList<Map<String, Object>>());
}
List<Map<String, Object>> eps = services.get(type);
eps.add(h.toMap());
}
result.put("version", version);
result.put("services", services);
result.put("sdk", sdk);
result.put("id", id);
try {
if (pretty) {
return DefaultObjectMapper.prettyWriter().writeValueAsString(result);
} else {
return DefaultObjectMapper.writeValueAsString(result);
}
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not encode as JSON string.", e);
}
} | [
"public",
"String",
"exportToJson",
"(",
"boolean",
"pretty",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"result",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"Map",
"<",
"String",
",",
"List",
"<",
"Map",
"<",
... | Exports this report into the standard JSON format which is consistent
across different language SDKs.
@return the encoded JSON string. | [
"Exports",
"this",
"report",
"into",
"the",
"standard",
"JSON",
"format",
"which",
"is",
"consistent",
"across",
"different",
"language",
"SDKs",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/message/internal/DiagnosticsReport.java#L103-L130 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/config/DefaultConfigurationProvider.java | DefaultConfigurationProvider.upsertBucketConfig | private void upsertBucketConfig(final BucketConfig newConfig) {
ClusterConfig cluster = currentConfig;
BucketConfig oldConfig = cluster.bucketConfig(newConfig.name());
if (newConfig.rev() > 0 && oldConfig != null && newConfig.rev() <= oldConfig.rev()) {
LOGGER.trace("Not applying new configuration, older or same rev ID.");
return;
}
// If the current password of the config is empty and an old config exists
// make sure to transfer the password over to the new config. Otherwise it
// is possible that authentication errors because of a null password arise.
// See JVMCBC-185
if (newConfig.password() == null && oldConfig != null) {
newConfig.password(oldConfig.password());
}
//copy the username as well
if (oldConfig != null) {
newConfig.username(oldConfig.username());
}
// this is the first config, decide on external networking
if (oldConfig == null) {
externalNetwork = determineNetworkResolution(newConfig, environment.networkResolution(), seedHosts);
LOGGER.info("Selected network configuration: {}", externalNetwork != null ? externalNetwork : "default");
}
if (externalNetwork != null) {
newConfig.useAlternateNetwork(externalNetwork);
}
cluster.setBucketConfig(newConfig.name(), newConfig);
LOGGER.debug("Applying new configuration {}", newConfig);
currentConfig = cluster;
boolean tainted = newConfig.tainted();
for (Refresher refresher : refreshers.values()) {
if (tainted) {
refresher.markTainted(newConfig);
} else {
refresher.markUntainted(newConfig);
}
}
configObservable.onNext(currentConfig);
} | java | private void upsertBucketConfig(final BucketConfig newConfig) {
ClusterConfig cluster = currentConfig;
BucketConfig oldConfig = cluster.bucketConfig(newConfig.name());
if (newConfig.rev() > 0 && oldConfig != null && newConfig.rev() <= oldConfig.rev()) {
LOGGER.trace("Not applying new configuration, older or same rev ID.");
return;
}
// If the current password of the config is empty and an old config exists
// make sure to transfer the password over to the new config. Otherwise it
// is possible that authentication errors because of a null password arise.
// See JVMCBC-185
if (newConfig.password() == null && oldConfig != null) {
newConfig.password(oldConfig.password());
}
//copy the username as well
if (oldConfig != null) {
newConfig.username(oldConfig.username());
}
// this is the first config, decide on external networking
if (oldConfig == null) {
externalNetwork = determineNetworkResolution(newConfig, environment.networkResolution(), seedHosts);
LOGGER.info("Selected network configuration: {}", externalNetwork != null ? externalNetwork : "default");
}
if (externalNetwork != null) {
newConfig.useAlternateNetwork(externalNetwork);
}
cluster.setBucketConfig(newConfig.name(), newConfig);
LOGGER.debug("Applying new configuration {}", newConfig);
currentConfig = cluster;
boolean tainted = newConfig.tainted();
for (Refresher refresher : refreshers.values()) {
if (tainted) {
refresher.markTainted(newConfig);
} else {
refresher.markUntainted(newConfig);
}
}
configObservable.onNext(currentConfig);
} | [
"private",
"void",
"upsertBucketConfig",
"(",
"final",
"BucketConfig",
"newConfig",
")",
"{",
"ClusterConfig",
"cluster",
"=",
"currentConfig",
";",
"BucketConfig",
"oldConfig",
"=",
"cluster",
".",
"bucketConfig",
"(",
"newConfig",
".",
"name",
"(",
")",
")",
"... | Helper method which takes the given bucket config and applies it to the cluster config.
This method also sends out an update to the subject afterwards, so that observers are notified.
@param newConfig the configuration of the bucket. | [
"Helper",
"method",
"which",
"takes",
"the",
"given",
"bucket",
"config",
"and",
"applies",
"it",
"to",
"the",
"cluster",
"config",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/DefaultConfigurationProvider.java#L492-L539 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/config/DefaultConfigurationProvider.java | DefaultConfigurationProvider.determineNetworkResolution | public static String determineNetworkResolution(final BucketConfig config, final NetworkResolution nr,
final Set<NetworkAddress> seedHosts) {
if (nr.equals(NetworkResolution.DEFAULT)) {
return null;
} else if (nr.equals(NetworkResolution.AUTO)) {
for (NodeInfo info : config.nodes()) {
if (seedHosts.contains(info.hostname())) {
return null;
}
Map<String, AlternateAddress> aa = info.alternateAddresses();
if (aa != null && !aa.isEmpty()) {
for (Map.Entry<String, AlternateAddress> entry : aa.entrySet()) {
AlternateAddress alternateAddress = entry.getValue();
if (alternateAddress != null && seedHosts.contains(alternateAddress.hostname())) {
return entry.getKey();
}
}
}
}
return null;
} else {
return nr.name();
}
} | java | public static String determineNetworkResolution(final BucketConfig config, final NetworkResolution nr,
final Set<NetworkAddress> seedHosts) {
if (nr.equals(NetworkResolution.DEFAULT)) {
return null;
} else if (nr.equals(NetworkResolution.AUTO)) {
for (NodeInfo info : config.nodes()) {
if (seedHosts.contains(info.hostname())) {
return null;
}
Map<String, AlternateAddress> aa = info.alternateAddresses();
if (aa != null && !aa.isEmpty()) {
for (Map.Entry<String, AlternateAddress> entry : aa.entrySet()) {
AlternateAddress alternateAddress = entry.getValue();
if (alternateAddress != null && seedHosts.contains(alternateAddress.hostname())) {
return entry.getKey();
}
}
}
}
return null;
} else {
return nr.name();
}
} | [
"public",
"static",
"String",
"determineNetworkResolution",
"(",
"final",
"BucketConfig",
"config",
",",
"final",
"NetworkResolution",
"nr",
",",
"final",
"Set",
"<",
"NetworkAddress",
">",
"seedHosts",
")",
"{",
"if",
"(",
"nr",
".",
"equals",
"(",
"NetworkReso... | Helper method to figure out which network resolution should be used.
if DEFAULT is selected, then null is returned which is equal to the "internal" or default
config mode. If AUTO is used then we perform the select heuristic based off of the seed
hosts given. All other resolution settings (i.e. EXTERNAL) are returned directly and are
considered to be part of the alternate address configs.
@param config the config to check against
@param nr the network resolution setting from the environment
@param seedHosts the seed hosts from bootstrap for autoconfig.
@return the found setting if external is used, null if internal/default is used. | [
"Helper",
"method",
"to",
"figure",
"out",
"which",
"network",
"resolution",
"should",
"be",
"used",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/DefaultConfigurationProvider.java#L554-L578 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/utils/HealthPinger.java | HealthPinger.mapToServiceHealth | private static Observable<PingServiceHealth> mapToServiceHealth(final String scope,
final ServiceType type, final Observable<? extends CouchbaseResponse> input,
final AtomicReference<CouchbaseRequest> request, final long timeout, final TimeUnit timeUnit) {
return input
.map(new Func1<CouchbaseResponse, PingServiceHealth>() {
@Override
public PingServiceHealth call(CouchbaseResponse response) {
DiagnosticRequest request = (DiagnosticRequest) response.request();
String id = "0x" + Integer.toHexString(request.localSocket().hashCode());
return new PingServiceHealth(
type,
PingServiceHealth.PingState.OK,
id,
TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - response.request().creationTime()),
request.localSocket(),
request.remoteSocket(),
scope
);
}
})
.onErrorReturn(new Func1<Throwable, PingServiceHealth>() {
@Override
public PingServiceHealth call(Throwable throwable) {
SocketAddress local = ((DiagnosticRequest) request.get()).localSocket();
SocketAddress remote = ((DiagnosticRequest) request.get()).remoteSocket();
String id = local == null ? "0x0000" : "0x" + Integer.toHexString(local.hashCode());
if (throwable instanceof TimeoutException) {
return new PingServiceHealth(
type,
PingServiceHealth.PingState.TIMEOUT,
id,
timeUnit.toMicros(timeout),
local,
remote,
scope
);
} else {
LOGGER.warn("Error while running PingService for {}", type, throwable);
return new PingServiceHealth(
type,
PingServiceHealth.PingState.ERROR,
id,
TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - request.get().creationTime()),
local,
remote,
scope
);
}
}
});
} | java | private static Observable<PingServiceHealth> mapToServiceHealth(final String scope,
final ServiceType type, final Observable<? extends CouchbaseResponse> input,
final AtomicReference<CouchbaseRequest> request, final long timeout, final TimeUnit timeUnit) {
return input
.map(new Func1<CouchbaseResponse, PingServiceHealth>() {
@Override
public PingServiceHealth call(CouchbaseResponse response) {
DiagnosticRequest request = (DiagnosticRequest) response.request();
String id = "0x" + Integer.toHexString(request.localSocket().hashCode());
return new PingServiceHealth(
type,
PingServiceHealth.PingState.OK,
id,
TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - response.request().creationTime()),
request.localSocket(),
request.remoteSocket(),
scope
);
}
})
.onErrorReturn(new Func1<Throwable, PingServiceHealth>() {
@Override
public PingServiceHealth call(Throwable throwable) {
SocketAddress local = ((DiagnosticRequest) request.get()).localSocket();
SocketAddress remote = ((DiagnosticRequest) request.get()).remoteSocket();
String id = local == null ? "0x0000" : "0x" + Integer.toHexString(local.hashCode());
if (throwable instanceof TimeoutException) {
return new PingServiceHealth(
type,
PingServiceHealth.PingState.TIMEOUT,
id,
timeUnit.toMicros(timeout),
local,
remote,
scope
);
} else {
LOGGER.warn("Error while running PingService for {}", type, throwable);
return new PingServiceHealth(
type,
PingServiceHealth.PingState.ERROR,
id,
TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - request.get().creationTime()),
local,
remote,
scope
);
}
}
});
} | [
"private",
"static",
"Observable",
"<",
"PingServiceHealth",
">",
"mapToServiceHealth",
"(",
"final",
"String",
"scope",
",",
"final",
"ServiceType",
"type",
",",
"final",
"Observable",
"<",
"?",
"extends",
"CouchbaseResponse",
">",
"input",
",",
"final",
"AtomicR... | Helper method to perform the proper health conversion.
@param input the response input
@return the converted output. | [
"Helper",
"method",
"to",
"perform",
"the",
"proper",
"health",
"conversion",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/utils/HealthPinger.java#L190-L240 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueFeatureHandler.java | KeyValueFeatureHandler.helloRequest | private FullBinaryMemcacheRequest helloRequest(int connId) throws Exception {
byte[] key = generateAgentJson(
ctx.environment().userAgent(),
ctx.coreId(),
connId
);
short keyLength = (short) key.length;
ByteBuf wanted = Unpooled.buffer(features.size() * 2);
for (ServerFeatures feature : features) {
wanted.writeShort(feature.value());
}
LOGGER.debug("Requesting supported features: {}", features);
FullBinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest(key, Unpooled.EMPTY_BUFFER, wanted);
request.setOpcode(HELLO_CMD);
request.setKeyLength(keyLength);
request.setTotalBodyLength(keyLength + wanted.readableBytes());
return request;
} | java | private FullBinaryMemcacheRequest helloRequest(int connId) throws Exception {
byte[] key = generateAgentJson(
ctx.environment().userAgent(),
ctx.coreId(),
connId
);
short keyLength = (short) key.length;
ByteBuf wanted = Unpooled.buffer(features.size() * 2);
for (ServerFeatures feature : features) {
wanted.writeShort(feature.value());
}
LOGGER.debug("Requesting supported features: {}", features);
FullBinaryMemcacheRequest request = new DefaultFullBinaryMemcacheRequest(key, Unpooled.EMPTY_BUFFER, wanted);
request.setOpcode(HELLO_CMD);
request.setKeyLength(keyLength);
request.setTotalBodyLength(keyLength + wanted.readableBytes());
return request;
} | [
"private",
"FullBinaryMemcacheRequest",
"helloRequest",
"(",
"int",
"connId",
")",
"throws",
"Exception",
"{",
"byte",
"[",
"]",
"key",
"=",
"generateAgentJson",
"(",
"ctx",
".",
"environment",
"(",
")",
".",
"userAgent",
"(",
")",
",",
"ctx",
".",
"coreId",... | Creates the HELLO request to ask for certain supported features.
@param connId the connection id
@return the request to send over the wire | [
"Creates",
"the",
"HELLO",
"request",
"to",
"ask",
"for",
"certain",
"supported",
"features",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueFeatureHandler.java#L130-L149 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueFeatureHandler.java | KeyValueFeatureHandler.generateAgentJson | static byte[] generateAgentJson(String agent, long coreId, long channelId) throws Exception {
String id = paddedHex(coreId) + "/" + paddedHex(channelId);
if (agent.length() > 200) {
agent = agent.substring(0, 200);
}
HashMap<String, String> result = new HashMap<String, String>();
result.put("a", agent);
result.put("i", id);
return DefaultObjectMapper.writeValueAsBytes(result);
} | java | static byte[] generateAgentJson(String agent, long coreId, long channelId) throws Exception {
String id = paddedHex(coreId) + "/" + paddedHex(channelId);
if (agent.length() > 200) {
agent = agent.substring(0, 200);
}
HashMap<String, String> result = new HashMap<String, String>();
result.put("a", agent);
result.put("i", id);
return DefaultObjectMapper.writeValueAsBytes(result);
} | [
"static",
"byte",
"[",
"]",
"generateAgentJson",
"(",
"String",
"agent",
",",
"long",
"coreId",
",",
"long",
"channelId",
")",
"throws",
"Exception",
"{",
"String",
"id",
"=",
"paddedHex",
"(",
"coreId",
")",
"+",
"\"/\"",
"+",
"paddedHex",
"(",
"channelId... | Helper method to generate the user agent JSON. | [
"Helper",
"method",
"to",
"generate",
"the",
"user",
"agent",
"JSON",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueFeatureHandler.java#L154-L164 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java | KeyValueAuthHandler.channelActive | @Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
ctx.writeAndFlush(new DefaultBinaryMemcacheRequest().setOpcode(SASL_LIST_MECHS_OPCODE));
} | java | @Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
ctx.writeAndFlush(new DefaultBinaryMemcacheRequest().setOpcode(SASL_LIST_MECHS_OPCODE));
} | [
"@",
"Override",
"public",
"void",
"channelActive",
"(",
"final",
"ChannelHandlerContext",
"ctx",
")",
"throws",
"Exception",
"{",
"this",
".",
"ctx",
"=",
"ctx",
";",
"ctx",
".",
"writeAndFlush",
"(",
"new",
"DefaultBinaryMemcacheRequest",
"(",
")",
".",
"set... | Once the channel is marked as active, the SASL negotiation is started.
@param ctx the handler context.
@throws Exception if something goes wrong during negotiation. | [
"Once",
"the",
"channel",
"is",
"marked",
"as",
"active",
"the",
"SASL",
"negotiation",
"is",
"started",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java#L140-L144 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java | KeyValueAuthHandler.channelRead0 | @Override
protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
if (msg.getOpcode() == SASL_LIST_MECHS_OPCODE) {
handleListMechsResponse(ctx, msg);
} else if (msg.getOpcode() == SASL_AUTH_OPCODE) {
handleAuthResponse(ctx, msg);
} else if (msg.getOpcode() == SASL_STEP_OPCODE) {
checkIsAuthed(msg);
}
} | java | @Override
protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
if (msg.getOpcode() == SASL_LIST_MECHS_OPCODE) {
handleListMechsResponse(ctx, msg);
} else if (msg.getOpcode() == SASL_AUTH_OPCODE) {
handleAuthResponse(ctx, msg);
} else if (msg.getOpcode() == SASL_STEP_OPCODE) {
checkIsAuthed(msg);
}
} | [
"@",
"Override",
"protected",
"void",
"channelRead0",
"(",
"ChannelHandlerContext",
"ctx",
",",
"FullBinaryMemcacheResponse",
"msg",
")",
"throws",
"Exception",
"{",
"if",
"(",
"msg",
".",
"getOpcode",
"(",
")",
"==",
"SASL_LIST_MECHS_OPCODE",
")",
"{",
"handleLis... | Dispatches incoming SASL responses to the appropriate handler methods.
@param ctx the handler context.
@param msg the incoming message to investigate.
@throws Exception if something goes wrong during negotiation. | [
"Dispatches",
"incoming",
"SASL",
"responses",
"to",
"the",
"appropriate",
"handler",
"methods",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java#L173-L182 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java | KeyValueAuthHandler.handleListMechsResponse | private void handleListMechsResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
String remote = ctx.channel().remoteAddress().toString();
String[] supportedMechanisms = msg.content().toString(CharsetUtil.UTF_8).split(" ");
if (supportedMechanisms.length == 0) {
throw new AuthenticationException("Received empty SASL mechanisms list from server: " + remote);
}
if (forceSaslPlain) {
LOGGER.trace("Got SASL Mechs {} but forcing PLAIN due to config setting.", Arrays.asList(supportedMechanisms));
supportedMechanisms = new String[] { "PLAIN" };
}
saslClient = Sasl.createSaslClient(supportedMechanisms, null, "couchbase", remote, null, this);
selectedMechanism = saslClient.getMechanismName();
int mechanismLength = selectedMechanism.length();
byte[] bytePayload = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(new byte[]{}) : null;
ByteBuf payload = bytePayload != null ? ctx.alloc().buffer().writeBytes(bytePayload) : Unpooled.EMPTY_BUFFER;
FullBinaryMemcacheRequest initialRequest = new DefaultFullBinaryMemcacheRequest(
selectedMechanism.getBytes(CharsetUtil.UTF_8),
Unpooled.EMPTY_BUFFER,
payload
);
initialRequest
.setOpcode(SASL_AUTH_OPCODE)
.setKeyLength((short) mechanismLength)
.setTotalBodyLength(mechanismLength + payload.readableBytes());
ChannelFuture future = ctx.writeAndFlush(initialRequest);
future.addListener(new GenericFutureListener<Future<Void>>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (!future.isSuccess()) {
LOGGER.warn("Error during SASL Auth negotiation phase.", future);
}
}
});
} | java | private void handleListMechsResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
String remote = ctx.channel().remoteAddress().toString();
String[] supportedMechanisms = msg.content().toString(CharsetUtil.UTF_8).split(" ");
if (supportedMechanisms.length == 0) {
throw new AuthenticationException("Received empty SASL mechanisms list from server: " + remote);
}
if (forceSaslPlain) {
LOGGER.trace("Got SASL Mechs {} but forcing PLAIN due to config setting.", Arrays.asList(supportedMechanisms));
supportedMechanisms = new String[] { "PLAIN" };
}
saslClient = Sasl.createSaslClient(supportedMechanisms, null, "couchbase", remote, null, this);
selectedMechanism = saslClient.getMechanismName();
int mechanismLength = selectedMechanism.length();
byte[] bytePayload = saslClient.hasInitialResponse() ? saslClient.evaluateChallenge(new byte[]{}) : null;
ByteBuf payload = bytePayload != null ? ctx.alloc().buffer().writeBytes(bytePayload) : Unpooled.EMPTY_BUFFER;
FullBinaryMemcacheRequest initialRequest = new DefaultFullBinaryMemcacheRequest(
selectedMechanism.getBytes(CharsetUtil.UTF_8),
Unpooled.EMPTY_BUFFER,
payload
);
initialRequest
.setOpcode(SASL_AUTH_OPCODE)
.setKeyLength((short) mechanismLength)
.setTotalBodyLength(mechanismLength + payload.readableBytes());
ChannelFuture future = ctx.writeAndFlush(initialRequest);
future.addListener(new GenericFutureListener<Future<Void>>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (!future.isSuccess()) {
LOGGER.warn("Error during SASL Auth negotiation phase.", future);
}
}
});
} | [
"private",
"void",
"handleListMechsResponse",
"(",
"ChannelHandlerContext",
"ctx",
",",
"FullBinaryMemcacheResponse",
"msg",
")",
"throws",
"Exception",
"{",
"String",
"remote",
"=",
"ctx",
".",
"channel",
"(",
")",
".",
"remoteAddress",
"(",
")",
".",
"toString",... | Handles an incoming SASL list mechanisms response and dispatches the next SASL AUTH step.
@param ctx the handler context.
@param msg the incoming message to investigate.
@throws Exception if something goes wrong during negotiation. | [
"Handles",
"an",
"incoming",
"SASL",
"list",
"mechanisms",
"response",
"and",
"dispatches",
"the",
"next",
"SASL",
"AUTH",
"step",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java#L191-L227 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java | KeyValueAuthHandler.handleAuthResponse | private void handleAuthResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
if (saslClient.isComplete()) {
checkIsAuthed(msg);
return;
}
byte[] response = new byte[msg.content().readableBytes()];
msg.content().readBytes(response);
byte[] evaluatedBytes = saslClient.evaluateChallenge(response);
if (evaluatedBytes != null) {
ByteBuf content;
// This is needed against older server versions where the protocol does not
// align on cram and plain, the else block is used for all the newer cram-sha*
// mechanisms.
//
// Note that most likely this is only executed in the CRAM-MD5 case only, but
// just to play it safe keep it for both mechanisms.
if (selectedMechanism.equals("CRAM-MD5") || selectedMechanism.equals("PLAIN")) {
String[] evaluated = new String(evaluatedBytes).split(" ");
content = Unpooled.copiedBuffer(username + "\0" + evaluated[1], CharsetUtil.UTF_8);
} else {
content = Unpooled.wrappedBuffer(evaluatedBytes);
}
FullBinaryMemcacheRequest stepRequest = new DefaultFullBinaryMemcacheRequest(
selectedMechanism.getBytes(CharsetUtil.UTF_8),
Unpooled.EMPTY_BUFFER,
content
);
stepRequest
.setOpcode(SASL_STEP_OPCODE)
.setKeyLength((short) selectedMechanism.length())
.setTotalBodyLength(content.readableBytes() + selectedMechanism.length());
ChannelFuture future = ctx.writeAndFlush(stepRequest);
future.addListener(new GenericFutureListener<Future<Void>>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (!future.isSuccess()) {
LOGGER.warn("Error during SASL Auth negotiation phase.", future);
}
}
});
} else {
throw new AuthenticationException("SASL Challenge evaluation returned null.");
}
} | java | private void handleAuthResponse(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
if (saslClient.isComplete()) {
checkIsAuthed(msg);
return;
}
byte[] response = new byte[msg.content().readableBytes()];
msg.content().readBytes(response);
byte[] evaluatedBytes = saslClient.evaluateChallenge(response);
if (evaluatedBytes != null) {
ByteBuf content;
// This is needed against older server versions where the protocol does not
// align on cram and plain, the else block is used for all the newer cram-sha*
// mechanisms.
//
// Note that most likely this is only executed in the CRAM-MD5 case only, but
// just to play it safe keep it for both mechanisms.
if (selectedMechanism.equals("CRAM-MD5") || selectedMechanism.equals("PLAIN")) {
String[] evaluated = new String(evaluatedBytes).split(" ");
content = Unpooled.copiedBuffer(username + "\0" + evaluated[1], CharsetUtil.UTF_8);
} else {
content = Unpooled.wrappedBuffer(evaluatedBytes);
}
FullBinaryMemcacheRequest stepRequest = new DefaultFullBinaryMemcacheRequest(
selectedMechanism.getBytes(CharsetUtil.UTF_8),
Unpooled.EMPTY_BUFFER,
content
);
stepRequest
.setOpcode(SASL_STEP_OPCODE)
.setKeyLength((short) selectedMechanism.length())
.setTotalBodyLength(content.readableBytes() + selectedMechanism.length());
ChannelFuture future = ctx.writeAndFlush(stepRequest);
future.addListener(new GenericFutureListener<Future<Void>>() {
@Override
public void operationComplete(Future<Void> future) throws Exception {
if (!future.isSuccess()) {
LOGGER.warn("Error during SASL Auth negotiation phase.", future);
}
}
});
} else {
throw new AuthenticationException("SASL Challenge evaluation returned null.");
}
} | [
"private",
"void",
"handleAuthResponse",
"(",
"ChannelHandlerContext",
"ctx",
",",
"FullBinaryMemcacheResponse",
"msg",
")",
"throws",
"Exception",
"{",
"if",
"(",
"saslClient",
".",
"isComplete",
"(",
")",
")",
"{",
"checkIsAuthed",
"(",
"msg",
")",
";",
"retur... | Handles an incoming SASL AUTH response and - if needed - dispatches the SASL STEPs.
@param ctx the handler context.
@param msg the incoming message to investigate.
@throws Exception if something goes wrong during negotiation. | [
"Handles",
"an",
"incoming",
"SASL",
"AUTH",
"response",
"and",
"-",
"if",
"needed",
"-",
"dispatches",
"the",
"SASL",
"STEPs",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java#L236-L284 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java | KeyValueAuthHandler.checkIsAuthed | private void checkIsAuthed(final FullBinaryMemcacheResponse msg) {
switch (msg.getStatus()) {
case SASL_AUTH_SUCCESS:
originalPromise.setSuccess();
ctx.pipeline().remove(this);
ctx.fireChannelActive();
break;
case SASL_AUTH_FAILURE:
originalPromise.setFailure(new AuthenticationException("Authentication Failure"));
break;
default:
originalPromise.setFailure(new AuthenticationException("Unhandled SASL auth status: "
+ msg.getStatus()));
}
} | java | private void checkIsAuthed(final FullBinaryMemcacheResponse msg) {
switch (msg.getStatus()) {
case SASL_AUTH_SUCCESS:
originalPromise.setSuccess();
ctx.pipeline().remove(this);
ctx.fireChannelActive();
break;
case SASL_AUTH_FAILURE:
originalPromise.setFailure(new AuthenticationException("Authentication Failure"));
break;
default:
originalPromise.setFailure(new AuthenticationException("Unhandled SASL auth status: "
+ msg.getStatus()));
}
} | [
"private",
"void",
"checkIsAuthed",
"(",
"final",
"FullBinaryMemcacheResponse",
"msg",
")",
"{",
"switch",
"(",
"msg",
".",
"getStatus",
"(",
")",
")",
"{",
"case",
"SASL_AUTH_SUCCESS",
":",
"originalPromise",
".",
"setSuccess",
"(",
")",
";",
"ctx",
".",
"p... | Once authentication is completed, check the response and react appropriately to the upper layers.
@param msg the incoming message to investigate. | [
"Once",
"authentication",
"is",
"completed",
"check",
"the",
"response",
"and",
"react",
"appropriately",
"to",
"the",
"upper",
"layers",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueAuthHandler.java#L291-L305 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/time/ExponentialDelay.java | ExponentialDelay.calculatePowerOfTwo | protected long calculatePowerOfTwo(long attempt) {
long step;
if (attempt >= 64) { //safeguard against overflow in the bitshift operation
step = Long.MAX_VALUE;
} else {
step = (1L << (attempt - 1));
}
//round will cap at Long.MAX_VALUE
return Math.round(step * growBy);
} | java | protected long calculatePowerOfTwo(long attempt) {
long step;
if (attempt >= 64) { //safeguard against overflow in the bitshift operation
step = Long.MAX_VALUE;
} else {
step = (1L << (attempt - 1));
}
//round will cap at Long.MAX_VALUE
return Math.round(step * growBy);
} | [
"protected",
"long",
"calculatePowerOfTwo",
"(",
"long",
"attempt",
")",
"{",
"long",
"step",
";",
"if",
"(",
"attempt",
">=",
"64",
")",
"{",
"//safeguard against overflow in the bitshift operation",
"step",
"=",
"Long",
".",
"MAX_VALUE",
";",
"}",
"else",
"{",... | fastpath with bitwise operator | [
"fastpath",
"with",
"bitwise",
"operator"
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/time/ExponentialDelay.java#L88-L97 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/retry/RetryHelper.java | RetryHelper.retryOrCancel | public static void retryOrCancel(final CoreEnvironment environment, final CouchbaseRequest request,
final EventSink<ResponseEvent> responseBuffer) {
if (!request.isActive()) {
return;
}
if (environment.retryStrategy().shouldRetry(request, environment)) {
retry(request, responseBuffer);
} else {
request.observable().onError(new RequestCancelledException("Could not dispatch request, cancelling "
+ "instead of retrying."));
}
} | java | public static void retryOrCancel(final CoreEnvironment environment, final CouchbaseRequest request,
final EventSink<ResponseEvent> responseBuffer) {
if (!request.isActive()) {
return;
}
if (environment.retryStrategy().shouldRetry(request, environment)) {
retry(request, responseBuffer);
} else {
request.observable().onError(new RequestCancelledException("Could not dispatch request, cancelling "
+ "instead of retrying."));
}
} | [
"public",
"static",
"void",
"retryOrCancel",
"(",
"final",
"CoreEnvironment",
"environment",
",",
"final",
"CouchbaseRequest",
"request",
",",
"final",
"EventSink",
"<",
"ResponseEvent",
">",
"responseBuffer",
")",
"{",
"if",
"(",
"!",
"request",
".",
"isActive",
... | Either retry or cancel a request, based on the strategy used.
@param environment the core environment for context.
@param request the request to either retry or cancel.
@param responseBuffer the response buffer where to maybe retry on. | [
"Either",
"retry",
"or",
"cancel",
"a",
"request",
"based",
"on",
"the",
"strategy",
"used",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/retry/RetryHelper.java#L42-L54 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/retry/RetryHelper.java | RetryHelper.retry | public static void retry(final CouchbaseRequest request, final EventSink<ResponseEvent> responseBuffer) {
if(!responseBuffer.tryPublishEvent(ResponseHandler.RESPONSE_TRANSLATOR, request, request.observable())) {
request.observable().onError(CouchbaseCore.BACKPRESSURE_EXCEPTION);
}
} | java | public static void retry(final CouchbaseRequest request, final EventSink<ResponseEvent> responseBuffer) {
if(!responseBuffer.tryPublishEvent(ResponseHandler.RESPONSE_TRANSLATOR, request, request.observable())) {
request.observable().onError(CouchbaseCore.BACKPRESSURE_EXCEPTION);
}
} | [
"public",
"static",
"void",
"retry",
"(",
"final",
"CouchbaseRequest",
"request",
",",
"final",
"EventSink",
"<",
"ResponseEvent",
">",
"responseBuffer",
")",
"{",
"if",
"(",
"!",
"responseBuffer",
".",
"tryPublishEvent",
"(",
"ResponseHandler",
".",
"RESPONSE_TRA... | Always retry the request and send it into the response buffer.
@param request the request to retry
@param responseBuffer the response buffer to send it into. | [
"Always",
"retry",
"the",
"request",
"and",
"send",
"it",
"into",
"the",
"response",
"buffer",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/retry/RetryHelper.java#L62-L66 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/analytics/parser/YasjlAnalyticsResponseParser.java | YasjlAnalyticsResponseParser.parse | public GenericAnalyticsResponse parse() throws Exception {
try {
parser.parse();
//discard only if EOF is not thrown
responseContent.discardReadBytes();
LOGGER.trace("Received last chunk and completed parsing for requestId {}", requestID);
} catch (EOFException ex) {
//ignore as we expect chunked responses
LOGGER.trace("Still expecting more data for requestId {}", requestID);
}
//return back response only once
if (!this.sentResponse && this.response != null) {
this.sentResponse = true;
return this.response;
}
return null;
} | java | public GenericAnalyticsResponse parse() throws Exception {
try {
parser.parse();
//discard only if EOF is not thrown
responseContent.discardReadBytes();
LOGGER.trace("Received last chunk and completed parsing for requestId {}", requestID);
} catch (EOFException ex) {
//ignore as we expect chunked responses
LOGGER.trace("Still expecting more data for requestId {}", requestID);
}
//return back response only once
if (!this.sentResponse && this.response != null) {
this.sentResponse = true;
return this.response;
}
return null;
} | [
"public",
"GenericAnalyticsResponse",
"parse",
"(",
")",
"throws",
"Exception",
"{",
"try",
"{",
"parser",
".",
"parse",
"(",
")",
";",
"//discard only if EOF is not thrown",
"responseContent",
".",
"discardReadBytes",
"(",
")",
";",
"LOGGER",
".",
"trace",
"(",
... | Instruct the parser to run a new parsing cycle on the current response content.
@return the {@link GenericQueryResponse} if ready, null otherwise.
@throws Exception if the internal parsing can't complete. | [
"Instruct",
"the",
"parser",
"to",
"run",
"a",
"new",
"parsing",
"cycle",
"on",
"the",
"current",
"response",
"content",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/analytics/parser/YasjlAnalyticsResponseParser.java#L350-L368 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/analytics/parser/YasjlAnalyticsResponseParser.java | YasjlAnalyticsResponseParser.finishParsingAndReset | public void finishParsingAndReset() {
if (queryRowObservable != null) {
queryRowObservable.onCompleted();
}
if (queryInfoObservable != null) {
queryInfoObservable.onCompleted();
}
if (queryErrorObservable != null) {
queryErrorObservable.onCompleted();
}
if (queryStatusObservable != null) {
queryStatusObservable.onCompleted();
}
if (querySignatureObservable != null) {
querySignatureObservable.onCompleted();
}
if (queryProfileInfoObservable != null) {
queryProfileInfoObservable.onCompleted();
}
queryInfoObservable = null;
queryRowObservable = null;
queryErrorObservable = null;
queryStatusObservable = null;
querySignatureObservable = null;
queryProfileInfoObservable = null;
this.initialized = false;
} | java | public void finishParsingAndReset() {
if (queryRowObservable != null) {
queryRowObservable.onCompleted();
}
if (queryInfoObservable != null) {
queryInfoObservable.onCompleted();
}
if (queryErrorObservable != null) {
queryErrorObservable.onCompleted();
}
if (queryStatusObservable != null) {
queryStatusObservable.onCompleted();
}
if (querySignatureObservable != null) {
querySignatureObservable.onCompleted();
}
if (queryProfileInfoObservable != null) {
queryProfileInfoObservable.onCompleted();
}
queryInfoObservable = null;
queryRowObservable = null;
queryErrorObservable = null;
queryStatusObservable = null;
querySignatureObservable = null;
queryProfileInfoObservable = null;
this.initialized = false;
} | [
"public",
"void",
"finishParsingAndReset",
"(",
")",
"{",
"if",
"(",
"queryRowObservable",
"!=",
"null",
")",
"{",
"queryRowObservable",
".",
"onCompleted",
"(",
")",
";",
"}",
"if",
"(",
"queryInfoObservable",
"!=",
"null",
")",
"{",
"queryInfoObservable",
".... | Instruct the parser to finish the parsing and reset its internal state, turning it
back to uninitialized as well. | [
"Instruct",
"the",
"parser",
"to",
"finish",
"the",
"parsing",
"and",
"reset",
"its",
"internal",
"state",
"turning",
"it",
"back",
"to",
"uninitialized",
"as",
"well",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/analytics/parser/YasjlAnalyticsResponseParser.java#L374-L400 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/config/ConfigHandler.java | ConfigHandler.maybePushConfigChunk | private void maybePushConfigChunk() {
String currentChunk = responseContent.toString(CHARSET);
int separatorIndex = currentChunk.indexOf("\n\n\n\n");
if (separatorIndex > 0) {
String content = currentChunk.substring(0, separatorIndex);
streamingConfigObservable.onNext(content.trim());
responseContent.clear();
responseContent.writeBytes(currentChunk.substring(separatorIndex + 4).getBytes(CHARSET));
}
} | java | private void maybePushConfigChunk() {
String currentChunk = responseContent.toString(CHARSET);
int separatorIndex = currentChunk.indexOf("\n\n\n\n");
if (separatorIndex > 0) {
String content = currentChunk.substring(0, separatorIndex);
streamingConfigObservable.onNext(content.trim());
responseContent.clear();
responseContent.writeBytes(currentChunk.substring(separatorIndex + 4).getBytes(CHARSET));
}
} | [
"private",
"void",
"maybePushConfigChunk",
"(",
")",
"{",
"String",
"currentChunk",
"=",
"responseContent",
".",
"toString",
"(",
"CHARSET",
")",
";",
"int",
"separatorIndex",
"=",
"currentChunk",
".",
"indexOf",
"(",
"\"\\n\\n\\n\\n\"",
")",
";",
"if",
"(",
"... | Push a config chunk into the streaming observable. | [
"Push",
"a",
"config",
"chunk",
"into",
"the",
"streaming",
"observable",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/config/ConfigHandler.java#L300-L310 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.writeMetrics | private void writeMetrics(final CouchbaseResponse response) {
if (currentRequest != null && currentOpTime >= 0 && env() != null
&& env().networkLatencyMetricsCollector().isEnabled()) {
try {
Class<? extends CouchbaseRequest> requestClass = currentRequest.getClass();
String simpleName = classNameCache.get(requestClass);
if (simpleName == null) {
simpleName = requestClass.getSimpleName();
classNameCache.put(requestClass, simpleName);
}
NetworkLatencyMetricsIdentifier identifier = new NetworkLatencyMetricsIdentifier(
remoteHostname,
serviceType().toString(),
simpleName,
response.status().toString()
);
env().networkLatencyMetricsCollector().record(identifier, currentOpTime);
} catch (Throwable e) {
LOGGER.warn("Could not collect latency metric for request {} ({})",
user(currentRequest.toString()),
currentOpTime,
e
);
}
}
} | java | private void writeMetrics(final CouchbaseResponse response) {
if (currentRequest != null && currentOpTime >= 0 && env() != null
&& env().networkLatencyMetricsCollector().isEnabled()) {
try {
Class<? extends CouchbaseRequest> requestClass = currentRequest.getClass();
String simpleName = classNameCache.get(requestClass);
if (simpleName == null) {
simpleName = requestClass.getSimpleName();
classNameCache.put(requestClass, simpleName);
}
NetworkLatencyMetricsIdentifier identifier = new NetworkLatencyMetricsIdentifier(
remoteHostname,
serviceType().toString(),
simpleName,
response.status().toString()
);
env().networkLatencyMetricsCollector().record(identifier, currentOpTime);
} catch (Throwable e) {
LOGGER.warn("Could not collect latency metric for request {} ({})",
user(currentRequest.toString()),
currentOpTime,
e
);
}
}
} | [
"private",
"void",
"writeMetrics",
"(",
"final",
"CouchbaseResponse",
"response",
")",
"{",
"if",
"(",
"currentRequest",
"!=",
"null",
"&&",
"currentOpTime",
">=",
"0",
"&&",
"env",
"(",
")",
"!=",
"null",
"&&",
"env",
"(",
")",
".",
"networkLatencyMetricsCo... | Helper method which creates the metrics for the current response and publishes them if enabled.
@param response the response which is needed as context. | [
"Helper",
"method",
"which",
"creates",
"the",
"metrics",
"for",
"the",
"current",
"response",
"and",
"publishes",
"them",
"if",
"enabled",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L383-L410 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.resetStatesAfterDecode | private void resetStatesAfterDecode(final ChannelHandlerContext ctx) {
if (traceEnabled) {
LOGGER.trace("{}Finished decoding of {}", logIdent(ctx, endpoint), currentRequest);
}
currentRequest = null;
currentDecodingState = DecodingState.INITIAL;
} | java | private void resetStatesAfterDecode(final ChannelHandlerContext ctx) {
if (traceEnabled) {
LOGGER.trace("{}Finished decoding of {}", logIdent(ctx, endpoint), currentRequest);
}
currentRequest = null;
currentDecodingState = DecodingState.INITIAL;
} | [
"private",
"void",
"resetStatesAfterDecode",
"(",
"final",
"ChannelHandlerContext",
"ctx",
")",
"{",
"if",
"(",
"traceEnabled",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"\"{}Finished decoding of {}\"",
",",
"logIdent",
"(",
"ctx",
",",
"endpoint",
")",
",",
"curre... | Helper method which performs the final tasks in the decoding process.
@param ctx the channel handler context for logging purposes. | [
"Helper",
"method",
"which",
"performs",
"the",
"final",
"tasks",
"in",
"the",
"decoding",
"process",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L417-L423 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.initialDecodeTasks | private void initialDecodeTasks(final ChannelHandlerContext ctx) {
currentRequest = sentRequestQueue.poll();
currentDecodingState = DecodingState.STARTED;
if (currentRequest != null) {
Long st = sentRequestTimings.poll();
if (st != null) {
currentOpTime = System.nanoTime() - st;
} else {
currentOpTime = -1;
}
}
if (env().operationTracingEnabled()) {
Span dispatchSpan = dispatchSpans.poll();
if (dispatchSpan != null) {
currentDispatchSpan = dispatchSpan;
}
}
if (traceEnabled) {
LOGGER.trace("{}Started decoding of {}", logIdent(ctx, endpoint), currentRequest);
}
} | java | private void initialDecodeTasks(final ChannelHandlerContext ctx) {
currentRequest = sentRequestQueue.poll();
currentDecodingState = DecodingState.STARTED;
if (currentRequest != null) {
Long st = sentRequestTimings.poll();
if (st != null) {
currentOpTime = System.nanoTime() - st;
} else {
currentOpTime = -1;
}
}
if (env().operationTracingEnabled()) {
Span dispatchSpan = dispatchSpans.poll();
if (dispatchSpan != null) {
currentDispatchSpan = dispatchSpan;
}
}
if (traceEnabled) {
LOGGER.trace("{}Started decoding of {}", logIdent(ctx, endpoint), currentRequest);
}
} | [
"private",
"void",
"initialDecodeTasks",
"(",
"final",
"ChannelHandlerContext",
"ctx",
")",
"{",
"currentRequest",
"=",
"sentRequestQueue",
".",
"poll",
"(",
")",
";",
"currentDecodingState",
"=",
"DecodingState",
".",
"STARTED",
";",
"if",
"(",
"currentRequest",
... | Helper method which performs the initial decoding process.
@param ctx the channel handler context for logging purposes. | [
"Helper",
"method",
"which",
"performs",
"the",
"initial",
"decoding",
"process",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L434-L457 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.publishResponse | protected void publishResponse(final CouchbaseResponse response,
final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
if (response.status() != ResponseStatus.RETRY && observable != null) {
if (moveResponseOut) {
Scheduler scheduler = env().scheduler();
if (scheduler instanceof CoreScheduler) {
scheduleDirect((CoreScheduler) scheduler, response, observable);
} else {
scheduleWorker(scheduler, response, observable);
}
} else {
completeResponse(response, observable);
}
} else {
responseBuffer.publishEvent(ResponseHandler.RESPONSE_TRANSLATOR, response, observable);
}
} | java | protected void publishResponse(final CouchbaseResponse response,
final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
if (response.status() != ResponseStatus.RETRY && observable != null) {
if (moveResponseOut) {
Scheduler scheduler = env().scheduler();
if (scheduler instanceof CoreScheduler) {
scheduleDirect((CoreScheduler) scheduler, response, observable);
} else {
scheduleWorker(scheduler, response, observable);
}
} else {
completeResponse(response, observable);
}
} else {
responseBuffer.publishEvent(ResponseHandler.RESPONSE_TRANSLATOR, response, observable);
}
} | [
"protected",
"void",
"publishResponse",
"(",
"final",
"CouchbaseResponse",
"response",
",",
"final",
"Subject",
"<",
"CouchbaseResponse",
",",
"CouchbaseResponse",
">",
"observable",
")",
"{",
"if",
"(",
"response",
".",
"status",
"(",
")",
"!=",
"ResponseStatus",... | Publishes a response with the attached observable.
@param response the response to publish.
@param observable pushing into the event sink. | [
"Publishes",
"a",
"response",
"with",
"the",
"attached",
"observable",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L465-L481 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.completeResponse | private void completeResponse(final CouchbaseResponse response,
final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
// Noone is listening anymore, handle tracing and/or orphan reporting
// depending on if enabled or not.
CouchbaseRequest request = response.request();
if (request != null && !request.isActive()) {
if (env().operationTracingEnabled() && request.span() != null) {
Scope scope = env().tracer().scopeManager()
.activate(request.span(), true);
scope.span().setBaggageItem("couchbase.orphan", "true");
scope.close();
}
if (env().orphanResponseReportingEnabled()) {
env().orphanResponseReporter().report(response);
}
}
try {
observable.onNext(response);
observable.onCompleted();
} catch (Exception ex) {
LOGGER.warn("Caught exception while onNext on observable", ex);
observable.onError(ex);
}
} | java | private void completeResponse(final CouchbaseResponse response,
final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
// Noone is listening anymore, handle tracing and/or orphan reporting
// depending on if enabled or not.
CouchbaseRequest request = response.request();
if (request != null && !request.isActive()) {
if (env().operationTracingEnabled() && request.span() != null) {
Scope scope = env().tracer().scopeManager()
.activate(request.span(), true);
scope.span().setBaggageItem("couchbase.orphan", "true");
scope.close();
}
if (env().orphanResponseReportingEnabled()) {
env().orphanResponseReporter().report(response);
}
}
try {
observable.onNext(response);
observable.onCompleted();
} catch (Exception ex) {
LOGGER.warn("Caught exception while onNext on observable", ex);
observable.onError(ex);
}
} | [
"private",
"void",
"completeResponse",
"(",
"final",
"CouchbaseResponse",
"response",
",",
"final",
"Subject",
"<",
"CouchbaseResponse",
",",
"CouchbaseResponse",
">",
"observable",
")",
"{",
"// Noone is listening anymore, handle tracing and/or orphan reporting",
"// depending... | Fulfill and complete the response observable.
When called directly, this method completes on the event loop, but it can also be used in a callback (see
{@link #scheduleDirect(CoreScheduler, CouchbaseResponse, Subject)} for example. | [
"Fulfill",
"and",
"complete",
"the",
"response",
"observable",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L489-L513 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.scheduleDirect | private void scheduleDirect(CoreScheduler scheduler, final CouchbaseResponse response,
final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
scheduler.scheduleDirect(new Action0() {
@Override
public void call() {
completeResponse(response, observable);
}
});
} | java | private void scheduleDirect(CoreScheduler scheduler, final CouchbaseResponse response,
final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
scheduler.scheduleDirect(new Action0() {
@Override
public void call() {
completeResponse(response, observable);
}
});
} | [
"private",
"void",
"scheduleDirect",
"(",
"CoreScheduler",
"scheduler",
",",
"final",
"CouchbaseResponse",
"response",
",",
"final",
"Subject",
"<",
"CouchbaseResponse",
",",
"CouchbaseResponse",
">",
"observable",
")",
"{",
"scheduler",
".",
"scheduleDirect",
"(",
... | Optimized version of dispatching onto the core scheduler through direct scheduling.
This method has less GC overhead compared to {@link #scheduleWorker(Scheduler, CouchbaseResponse, Subject)}
since no worker needs to be generated explicitly (but is not part of the public Scheduler interface). | [
"Optimized",
"version",
"of",
"dispatching",
"onto",
"the",
"core",
"scheduler",
"through",
"direct",
"scheduling",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L521-L529 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.scheduleWorker | private void scheduleWorker(Scheduler scheduler, final CouchbaseResponse response,
final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
final Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(new Action0() {
@Override
public void call() {
completeResponse(response, observable);
worker.unsubscribe();
}
});
} | java | private void scheduleWorker(Scheduler scheduler, final CouchbaseResponse response,
final Subject<CouchbaseResponse, CouchbaseResponse> observable) {
final Scheduler.Worker worker = scheduler.createWorker();
worker.schedule(new Action0() {
@Override
public void call() {
completeResponse(response, observable);
worker.unsubscribe();
}
});
} | [
"private",
"void",
"scheduleWorker",
"(",
"Scheduler",
"scheduler",
",",
"final",
"CouchbaseResponse",
"response",
",",
"final",
"Subject",
"<",
"CouchbaseResponse",
",",
"CouchbaseResponse",
">",
"observable",
")",
"{",
"final",
"Scheduler",
".",
"Worker",
"worker"... | Dispatches the response on a generic scheduler through creating a worker. | [
"Dispatches",
"the",
"response",
"on",
"a",
"generic",
"scheduler",
"through",
"creating",
"a",
"worker",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L534-L544 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.channelActiveSideEffects | private void channelActiveSideEffects(final ChannelHandlerContext ctx) {
long interval = env().keepAliveInterval();
if (env().continuousKeepAliveEnabled()) {
continuousKeepAliveFuture = ctx.executor().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (shouldSendKeepAlive()) {
createAndWriteKeepAlive(ctx);
}
}
}, interval, interval, TimeUnit.MILLISECONDS);
}
} | java | private void channelActiveSideEffects(final ChannelHandlerContext ctx) {
long interval = env().keepAliveInterval();
if (env().continuousKeepAliveEnabled()) {
continuousKeepAliveFuture = ctx.executor().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if (shouldSendKeepAlive()) {
createAndWriteKeepAlive(ctx);
}
}
}, interval, interval, TimeUnit.MILLISECONDS);
}
} | [
"private",
"void",
"channelActiveSideEffects",
"(",
"final",
"ChannelHandlerContext",
"ctx",
")",
"{",
"long",
"interval",
"=",
"env",
"(",
")",
".",
"keepAliveInterval",
"(",
")",
";",
"if",
"(",
"env",
"(",
")",
".",
"continuousKeepAliveEnabled",
"(",
")",
... | Helper method to perform certain side effects when the channel is connected. | [
"Helper",
"method",
"to",
"perform",
"certain",
"side",
"effects",
"when",
"the",
"channel",
"is",
"connected",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L621-L633 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.handleOutstandingOperations | private void handleOutstandingOperations(final ChannelHandlerContext ctx) {
if (sentRequestQueue.isEmpty()) {
LOGGER.trace(logIdent(ctx, endpoint) + "Not cancelling operations - sent queue is empty.");
return;
}
LOGGER.debug(logIdent(ctx, endpoint) + "Cancelling " + sentRequestQueue.size() + " outstanding requests.");
while (!sentRequestQueue.isEmpty()) {
REQUEST req = sentRequestQueue.poll();
try {
sideEffectRequestToCancel(req);
failSafe(env().scheduler(), moveResponseOut, req.observable(),
new RequestCancelledException("Request cancelled in-flight."));
} catch (Exception ex) {
LOGGER.info(
"Exception thrown while cancelling outstanding operation: {}",
user(req.toString()),
ex
);
}
}
sentRequestTimings.clear();
} | java | private void handleOutstandingOperations(final ChannelHandlerContext ctx) {
if (sentRequestQueue.isEmpty()) {
LOGGER.trace(logIdent(ctx, endpoint) + "Not cancelling operations - sent queue is empty.");
return;
}
LOGGER.debug(logIdent(ctx, endpoint) + "Cancelling " + sentRequestQueue.size() + " outstanding requests.");
while (!sentRequestQueue.isEmpty()) {
REQUEST req = sentRequestQueue.poll();
try {
sideEffectRequestToCancel(req);
failSafe(env().scheduler(), moveResponseOut, req.observable(),
new RequestCancelledException("Request cancelled in-flight."));
} catch (Exception ex) {
LOGGER.info(
"Exception thrown while cancelling outstanding operation: {}",
user(req.toString()),
ex
);
}
}
sentRequestTimings.clear();
} | [
"private",
"void",
"handleOutstandingOperations",
"(",
"final",
"ChannelHandlerContext",
"ctx",
")",
"{",
"if",
"(",
"sentRequestQueue",
".",
"isEmpty",
"(",
")",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"logIdent",
"(",
"ctx",
",",
"endpoint",
")",
"+",
"\"No... | Cancells any outstanding operations which are currently on the wire.
@param ctx the handler context. | [
"Cancells",
"any",
"outstanding",
"operations",
"which",
"are",
"currently",
"on",
"the",
"wire",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L675-L698 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.createAndWriteKeepAlive | private void createAndWriteKeepAlive(final ChannelHandlerContext ctx) {
final CouchbaseRequest keepAlive = createKeepAliveRequest();
if (keepAlive != null) {
Subscriber<CouchbaseResponse> subscriber = new KeepAliveResponseAction(ctx);
keepAlive.subscriber(subscriber);
keepAlive
.observable()
.timeout(env().keepAliveTimeout(), TimeUnit.MILLISECONDS)
.subscribe(subscriber);
onKeepAliveFired(ctx, keepAlive);
Channel channel = ctx.channel();
if (channel.isActive() && channel.isWritable()) {
ctx.pipeline().writeAndFlush(keepAlive);
}
}
} | java | private void createAndWriteKeepAlive(final ChannelHandlerContext ctx) {
final CouchbaseRequest keepAlive = createKeepAliveRequest();
if (keepAlive != null) {
Subscriber<CouchbaseResponse> subscriber = new KeepAliveResponseAction(ctx);
keepAlive.subscriber(subscriber);
keepAlive
.observable()
.timeout(env().keepAliveTimeout(), TimeUnit.MILLISECONDS)
.subscribe(subscriber);
onKeepAliveFired(ctx, keepAlive);
Channel channel = ctx.channel();
if (channel.isActive() && channel.isWritable()) {
ctx.pipeline().writeAndFlush(keepAlive);
}
}
} | [
"private",
"void",
"createAndWriteKeepAlive",
"(",
"final",
"ChannelHandlerContext",
"ctx",
")",
"{",
"final",
"CouchbaseRequest",
"keepAlive",
"=",
"createKeepAliveRequest",
"(",
")",
";",
"if",
"(",
"keepAlive",
"!=",
"null",
")",
"{",
"Subscriber",
"<",
"Couchb... | Helper method to create, write and flush the keepalive message. | [
"Helper",
"method",
"to",
"create",
"write",
"and",
"flush",
"the",
"keepalive",
"message",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L728-L745 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.onKeepAliveFired | protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) {
if (env().continuousKeepAliveEnabled() && LOGGER.isTraceEnabled()) {
LOGGER.trace(logIdent(ctx, endpoint) + "Continuous KeepAlive fired");
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug(logIdent(ctx, endpoint) + "KeepAlive fired");
}
} | java | protected void onKeepAliveFired(ChannelHandlerContext ctx, CouchbaseRequest keepAliveRequest) {
if (env().continuousKeepAliveEnabled() && LOGGER.isTraceEnabled()) {
LOGGER.trace(logIdent(ctx, endpoint) + "Continuous KeepAlive fired");
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug(logIdent(ctx, endpoint) + "KeepAlive fired");
}
} | [
"protected",
"void",
"onKeepAliveFired",
"(",
"ChannelHandlerContext",
"ctx",
",",
"CouchbaseRequest",
"keepAliveRequest",
")",
"{",
"if",
"(",
"env",
"(",
")",
".",
"continuousKeepAliveEnabled",
"(",
")",
"&&",
"LOGGER",
".",
"isTraceEnabled",
"(",
")",
")",
"{... | Override to customize the behavior when a keep alive has been triggered and a keep alive request sent.
The default behavior is to log the event at debug level.
@param ctx the channel context.
@param keepAliveRequest the keep alive request that was sent when keep alive was triggered | [
"Override",
"to",
"customize",
"the",
"behavior",
"when",
"a",
"keep",
"alive",
"has",
"been",
"triggered",
"and",
"a",
"keep",
"alive",
"request",
"sent",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L788-L794 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.onKeepAliveResponse | protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) {
if (traceEnabled) {
LOGGER.trace(logIdent(ctx, endpoint) + "keepAlive was answered, status "
+ keepAliveResponse.status());
}
} | java | protected void onKeepAliveResponse(ChannelHandlerContext ctx, CouchbaseResponse keepAliveResponse) {
if (traceEnabled) {
LOGGER.trace(logIdent(ctx, endpoint) + "keepAlive was answered, status "
+ keepAliveResponse.status());
}
} | [
"protected",
"void",
"onKeepAliveResponse",
"(",
"ChannelHandlerContext",
"ctx",
",",
"CouchbaseResponse",
"keepAliveResponse",
")",
"{",
"if",
"(",
"traceEnabled",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"logIdent",
"(",
"ctx",
",",
"endpoint",
")",
"+",
"\"keep... | Override to customize the behavior when a keep alive has been responded to.
The default behavior is to log the event and the response status at trace level.
@param ctx the channel context.
@param keepAliveResponse the keep alive request that was sent when keep alive was triggered | [
"Override",
"to",
"customize",
"the",
"behavior",
"when",
"a",
"keep",
"alive",
"has",
"been",
"responded",
"to",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L804-L809 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.completeRequestSpan | protected void completeRequestSpan(final CouchbaseRequest request) {
if (request != null && request.span() != null) {
if (env().operationTracingEnabled()) {
env().tracer().scopeManager()
.activate(request.span(), true)
.close();
}
}
} | java | protected void completeRequestSpan(final CouchbaseRequest request) {
if (request != null && request.span() != null) {
if (env().operationTracingEnabled()) {
env().tracer().scopeManager()
.activate(request.span(), true)
.close();
}
}
} | [
"protected",
"void",
"completeRequestSpan",
"(",
"final",
"CouchbaseRequest",
"request",
")",
"{",
"if",
"(",
"request",
"!=",
"null",
"&&",
"request",
".",
"span",
"(",
")",
"!=",
"null",
")",
"{",
"if",
"(",
"env",
"(",
")",
".",
"operationTracingEnabled... | Helper method to complete the request span, called from child instances.
@param request the corresponding request. | [
"Helper",
"method",
"to",
"complete",
"the",
"request",
"span",
"called",
"from",
"child",
"instances",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L928-L936 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java | AbstractGenericHandler.remoteHttpHost | protected String remoteHttpHost(ChannelHandlerContext ctx) {
if (remoteHttpHost == null) {
SocketAddress addr = ctx.channel().remoteAddress();
if (addr instanceof InetSocketAddress) {
InetSocketAddress inetAddr = (InetSocketAddress) addr;
remoteHttpHost = inetAddr.getAddress().getHostAddress() + ":" + inetAddr.getPort();
} else {
remoteHttpHost = addr.toString();
}
}
return remoteHttpHost;
} | java | protected String remoteHttpHost(ChannelHandlerContext ctx) {
if (remoteHttpHost == null) {
SocketAddress addr = ctx.channel().remoteAddress();
if (addr instanceof InetSocketAddress) {
InetSocketAddress inetAddr = (InetSocketAddress) addr;
remoteHttpHost = inetAddr.getAddress().getHostAddress() + ":" + inetAddr.getPort();
} else {
remoteHttpHost = addr.toString();
}
}
return remoteHttpHost;
} | [
"protected",
"String",
"remoteHttpHost",
"(",
"ChannelHandlerContext",
"ctx",
")",
"{",
"if",
"(",
"remoteHttpHost",
"==",
"null",
")",
"{",
"SocketAddress",
"addr",
"=",
"ctx",
".",
"channel",
"(",
")",
".",
"remoteAddress",
"(",
")",
";",
"if",
"(",
"add... | Helper method to return the remote http host, cached.
@param ctx the handler context.
@return the remote http host. | [
"Helper",
"method",
"to",
"return",
"the",
"remote",
"http",
"host",
"cached",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractGenericHandler.java#L944-L955 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/env/CoreScheduler.java | CoreScheduler.scheduleDirect | public Subscription scheduleDirect(Action0 action) {
PoolWorker pw = pool.get().getEventLoop();
return pw.scheduleActual(action, -1, TimeUnit.NANOSECONDS);
} | java | public Subscription scheduleDirect(Action0 action) {
PoolWorker pw = pool.get().getEventLoop();
return pw.scheduleActual(action, -1, TimeUnit.NANOSECONDS);
} | [
"public",
"Subscription",
"scheduleDirect",
"(",
"Action0",
"action",
")",
"{",
"PoolWorker",
"pw",
"=",
"pool",
".",
"get",
"(",
")",
".",
"getEventLoop",
"(",
")",
";",
"return",
"pw",
".",
"scheduleActual",
"(",
"action",
",",
"-",
"1",
",",
"TimeUnit... | Schedules the action directly on one of the event loop workers
without the additional infrastructure and checking.
@param action the action to schedule
@return the subscription | [
"Schedules",
"the",
"action",
"directly",
"on",
"one",
"of",
"the",
"event",
"loop",
"workers",
"without",
"the",
"additional",
"infrastructure",
"and",
"checking",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/env/CoreScheduler.java#L143-L146 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/RequestHandler.java | RequestHandler.addService | public Observable<Service> addService(final AddServiceRequest request) {
LOGGER.debug("Got instructed to add Service {}, to Node {}", request.type(), request.hostname());
return nodeBy(request.hostname()).addService(request);
} | java | public Observable<Service> addService(final AddServiceRequest request) {
LOGGER.debug("Got instructed to add Service {}, to Node {}", request.type(), request.hostname());
return nodeBy(request.hostname()).addService(request);
} | [
"public",
"Observable",
"<",
"Service",
">",
"addService",
"(",
"final",
"AddServiceRequest",
"request",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Got instructed to add Service {}, to Node {}\"",
",",
"request",
".",
"type",
"(",
")",
",",
"request",
".",
"hostnam... | Add the service to the node.
@param request the request which contains infos about the service and node to add.
@return an observable which contains the newly created service. | [
"Add",
"the",
"service",
"to",
"the",
"node",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/RequestHandler.java#L356-L359 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/RequestHandler.java | RequestHandler.removeService | public Observable<Service> removeService(final RemoveServiceRequest request) {
LOGGER.debug("Got instructed to remove Service {}, from Node {}", request.type(), request.hostname());
return nodeBy(request.hostname()).removeService(request);
} | java | public Observable<Service> removeService(final RemoveServiceRequest request) {
LOGGER.debug("Got instructed to remove Service {}, from Node {}", request.type(), request.hostname());
return nodeBy(request.hostname()).removeService(request);
} | [
"public",
"Observable",
"<",
"Service",
">",
"removeService",
"(",
"final",
"RemoveServiceRequest",
"request",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Got instructed to remove Service {}, from Node {}\"",
",",
"request",
".",
"type",
"(",
")",
",",
"request",
".",... | Remove a service from a node.
@param request the request which contains infos about the service and node to remove.
@return an observable which contains the removed service. | [
"Remove",
"a",
"service",
"from",
"a",
"node",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/RequestHandler.java#L367-L370 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/RequestHandler.java | RequestHandler.nodeBy | public Node nodeBy(final NetworkAddress hostname) {
if (hostname == null) {
return null;
}
for (Node node : nodes) {
if (node.hostname().equals(hostname)) {
return node;
}
}
return null;
} | java | public Node nodeBy(final NetworkAddress hostname) {
if (hostname == null) {
return null;
}
for (Node node : nodes) {
if (node.hostname().equals(hostname)) {
return node;
}
}
return null;
} | [
"public",
"Node",
"nodeBy",
"(",
"final",
"NetworkAddress",
"hostname",
")",
"{",
"if",
"(",
"hostname",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"for",
"(",
"Node",
"node",
":",
"nodes",
")",
"{",
"if",
"(",
"node",
".",
"hostname",
"(",
... | Returns the node by its hostname.
@param hostname the hostname of the node.
@return the node or null if no hostname for that ip address. | [
"Returns",
"the",
"node",
"by",
"its",
"hostname",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/RequestHandler.java#L378-L389 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/RequestHandler.java | RequestHandler.locator | protected Locator locator(final CouchbaseRequest request) {
if (request instanceof BinaryRequest) {
return binaryLocator;
} else if (request instanceof ViewRequest) {
return viewLocator;
} else if (request instanceof QueryRequest) {
return queryLocator;
} else if (request instanceof ConfigRequest) {
return configLocator;
} else if (request instanceof SearchRequest) {
return searchLocator;
} else if (request instanceof AnalyticsRequest) {
return analyticsLocator;
} else {
throw new IllegalArgumentException("Unknown Request Type: " + request);
}
} | java | protected Locator locator(final CouchbaseRequest request) {
if (request instanceof BinaryRequest) {
return binaryLocator;
} else if (request instanceof ViewRequest) {
return viewLocator;
} else if (request instanceof QueryRequest) {
return queryLocator;
} else if (request instanceof ConfigRequest) {
return configLocator;
} else if (request instanceof SearchRequest) {
return searchLocator;
} else if (request instanceof AnalyticsRequest) {
return analyticsLocator;
} else {
throw new IllegalArgumentException("Unknown Request Type: " + request);
}
} | [
"protected",
"Locator",
"locator",
"(",
"final",
"CouchbaseRequest",
"request",
")",
"{",
"if",
"(",
"request",
"instanceof",
"BinaryRequest",
")",
"{",
"return",
"binaryLocator",
";",
"}",
"else",
"if",
"(",
"request",
"instanceof",
"ViewRequest",
")",
"{",
"... | Helper method to detect the correct locator for the given request type.
@return the locator for the given request type. | [
"Helper",
"method",
"to",
"detect",
"the",
"correct",
"locator",
"for",
"the",
"given",
"request",
"type",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/RequestHandler.java#L396-L412 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/RequestHandler.java | RequestHandler.diagnostics | public Observable<DiagnosticsResponse> diagnostics(final String id) {
List<Observable<EndpointHealth>> diags = new ArrayList<Observable<EndpointHealth>>(nodes.size());
for (Node node : nodes) {
diags.add(node.diagnostics());
}
final RingBufferDiagnostics ringBufferDiagnostics = RingBufferMonitor.instance().diagnostics();
return Observable.merge(diags).toList().map(new Func1<List<EndpointHealth>, DiagnosticsResponse>() {
@Override
public DiagnosticsResponse call(List<EndpointHealth> checks) {
return new DiagnosticsResponse(new DiagnosticsReport(checks, environment.userAgent(), id, ringBufferDiagnostics));
}
});
} | java | public Observable<DiagnosticsResponse> diagnostics(final String id) {
List<Observable<EndpointHealth>> diags = new ArrayList<Observable<EndpointHealth>>(nodes.size());
for (Node node : nodes) {
diags.add(node.diagnostics());
}
final RingBufferDiagnostics ringBufferDiagnostics = RingBufferMonitor.instance().diagnostics();
return Observable.merge(diags).toList().map(new Func1<List<EndpointHealth>, DiagnosticsResponse>() {
@Override
public DiagnosticsResponse call(List<EndpointHealth> checks) {
return new DiagnosticsResponse(new DiagnosticsReport(checks, environment.userAgent(), id, ringBufferDiagnostics));
}
});
} | [
"public",
"Observable",
"<",
"DiagnosticsResponse",
">",
"diagnostics",
"(",
"final",
"String",
"id",
")",
"{",
"List",
"<",
"Observable",
"<",
"EndpointHealth",
">>",
"diags",
"=",
"new",
"ArrayList",
"<",
"Observable",
"<",
"EndpointHealth",
">",
">",
"(",
... | Performs the logistics of collecting and assembling the individual health check information
on a per-service basis.
@return an observable with the response once ready. | [
"Performs",
"the",
"logistics",
"of",
"collecting",
"and",
"assembling",
"the",
"individual",
"health",
"check",
"information",
"on",
"a",
"per",
"-",
"service",
"basis",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/RequestHandler.java#L420-L432 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/RequestHandler.java | RequestHandler.reconfigure | public Observable<ClusterConfig> reconfigure(final ClusterConfig config) {
LOGGER.debug("Starting reconfiguration.");
if (config.bucketConfigs().values().isEmpty()) {
LOGGER.debug("No open bucket found in config, disconnecting all nodes.");
//JVMCBC-231: a race condition can happen where the nodes set is seen as
// not empty, while the subsequent Observable.from is not, failing in calling last()
List<Node> snapshotNodes;
synchronized (nodes) {
snapshotNodes = new ArrayList<Node>(nodes);
}
if (snapshotNodes.isEmpty()) {
return Observable.just(config);
}
return Observable.from(snapshotNodes).doOnNext(new Action1<Node>() {
@Override
public void call(Node node) {
removeNode(node);
node.disconnect().subscribe(new Subscriber<LifecycleState>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {
LOGGER.warn("Got error during node disconnect.", e);
}
@Override
public void onNext(LifecycleState lifecycleState) {}
});
}
}).last().map(new Func1<Node, ClusterConfig>() {
@Override
public ClusterConfig call(Node node) {
return config;
}
});
}
return Observable
.just(config)
.flatMap(new Func1<ClusterConfig, Observable<BucketConfig>>() {
@Override
public Observable<BucketConfig> call(final ClusterConfig clusterConfig) {
return Observable.from(clusterConfig.bucketConfigs().values());
}
}).flatMap(new Func1<BucketConfig, Observable<Boolean>>() {
@Override
public Observable<Boolean> call(BucketConfig bucketConfig) {
return reconfigureBucket(bucketConfig);
}
})
.last()
.doOnNext(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
Set<NetworkAddress> configNodes = config.allNodeAddresses();
for (Node node : nodes) {
if (!configNodes.contains(node.hostname())) {
LOGGER.debug("Removing and disconnecting node {}.", node.hostname());
removeNode(node);
node.disconnect().subscribe(new Subscriber<LifecycleState>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {
LOGGER.warn("Got error during node disconnect.", e);
}
@Override
public void onNext(LifecycleState lifecycleState) {}
});
}
}
}
})
.map(new Func1<Boolean, ClusterConfig>() {
@Override
public ClusterConfig call(Boolean aBoolean) {
return config;
}
});
} | java | public Observable<ClusterConfig> reconfigure(final ClusterConfig config) {
LOGGER.debug("Starting reconfiguration.");
if (config.bucketConfigs().values().isEmpty()) {
LOGGER.debug("No open bucket found in config, disconnecting all nodes.");
//JVMCBC-231: a race condition can happen where the nodes set is seen as
// not empty, while the subsequent Observable.from is not, failing in calling last()
List<Node> snapshotNodes;
synchronized (nodes) {
snapshotNodes = new ArrayList<Node>(nodes);
}
if (snapshotNodes.isEmpty()) {
return Observable.just(config);
}
return Observable.from(snapshotNodes).doOnNext(new Action1<Node>() {
@Override
public void call(Node node) {
removeNode(node);
node.disconnect().subscribe(new Subscriber<LifecycleState>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {
LOGGER.warn("Got error during node disconnect.", e);
}
@Override
public void onNext(LifecycleState lifecycleState) {}
});
}
}).last().map(new Func1<Node, ClusterConfig>() {
@Override
public ClusterConfig call(Node node) {
return config;
}
});
}
return Observable
.just(config)
.flatMap(new Func1<ClusterConfig, Observable<BucketConfig>>() {
@Override
public Observable<BucketConfig> call(final ClusterConfig clusterConfig) {
return Observable.from(clusterConfig.bucketConfigs().values());
}
}).flatMap(new Func1<BucketConfig, Observable<Boolean>>() {
@Override
public Observable<Boolean> call(BucketConfig bucketConfig) {
return reconfigureBucket(bucketConfig);
}
})
.last()
.doOnNext(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
Set<NetworkAddress> configNodes = config.allNodeAddresses();
for (Node node : nodes) {
if (!configNodes.contains(node.hostname())) {
LOGGER.debug("Removing and disconnecting node {}.", node.hostname());
removeNode(node);
node.disconnect().subscribe(new Subscriber<LifecycleState>() {
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {
LOGGER.warn("Got error during node disconnect.", e);
}
@Override
public void onNext(LifecycleState lifecycleState) {}
});
}
}
}
})
.map(new Func1<Boolean, ClusterConfig>() {
@Override
public ClusterConfig call(Boolean aBoolean) {
return config;
}
});
} | [
"public",
"Observable",
"<",
"ClusterConfig",
">",
"reconfigure",
"(",
"final",
"ClusterConfig",
"config",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Starting reconfiguration.\"",
")",
";",
"if",
"(",
"config",
".",
"bucketConfigs",
"(",
")",
".",
"values",
"("... | Helper method which grabs the current configuration and checks if the node setup is out of sync.
This method is always called when a new configuration arrives and it will try to sync the actual node
and service setup with the one proposed by the configuration. | [
"Helper",
"method",
"which",
"grabs",
"the",
"current",
"configuration",
"and",
"checks",
"if",
"the",
"node",
"setup",
"is",
"out",
"of",
"sync",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/RequestHandler.java#L440-L525 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/RequestHandler.java | RequestHandler.reconfigureBucket | private Observable<Boolean> reconfigureBucket(final BucketConfig config) {
LOGGER.debug("Starting reconfiguration for bucket {}", config.name());
List<Observable<Boolean>> observables = new ArrayList<Observable<Boolean>>();
for (final NodeInfo nodeInfo : config.nodes()) {
final String alternate = nodeInfo.useAlternateNetwork();
final NetworkAddress altHost = alternate != null ? nodeInfo.alternateAddresses().get(alternate).hostname(): null;
Observable<Boolean> obs = addNode(nodeInfo.hostname(), altHost)
.flatMap(new Func1<LifecycleState, Observable<Map<ServiceType, Integer>>>() {
@Override
public Observable<Map<ServiceType, Integer>> call(final LifecycleState lifecycleState) {
Map<ServiceType, Integer> services;
if (alternate != null) {
AlternateAddress aa = nodeInfo.alternateAddresses().get(alternate);
services = environment.sslEnabled() ? aa.sslServices() : aa.services();
} else {
services = environment.sslEnabled() ? nodeInfo.sslServices() : nodeInfo.services();
}
return Observable.just(services);
}
}).flatMap(new Func1<Map<ServiceType, Integer>, Observable<AddServiceRequest>>() {
@Override
public Observable<AddServiceRequest> call(final Map<ServiceType, Integer> services) {
List<AddServiceRequest> requests = new ArrayList<AddServiceRequest>(services.size());
for (Map.Entry<ServiceType, Integer> service : services.entrySet()) {
requests.add(new AddServiceRequest(service.getKey(), config.name(), config.username(),
config.password(), service.getValue(), nodeInfo.hostname()));
}
return Observable.from(requests);
}
}).flatMap(new Func1<AddServiceRequest, Observable<Service>>() {
@Override
public Observable<Service> call(AddServiceRequest request) {
return addService(request);
}
}).last().map(new Func1<Service, Boolean>() {
@Override
public Boolean call(Service service) {
return true;
}
});
observables.add(obs);
}
return Observable.merge(observables).last();
} | java | private Observable<Boolean> reconfigureBucket(final BucketConfig config) {
LOGGER.debug("Starting reconfiguration for bucket {}", config.name());
List<Observable<Boolean>> observables = new ArrayList<Observable<Boolean>>();
for (final NodeInfo nodeInfo : config.nodes()) {
final String alternate = nodeInfo.useAlternateNetwork();
final NetworkAddress altHost = alternate != null ? nodeInfo.alternateAddresses().get(alternate).hostname(): null;
Observable<Boolean> obs = addNode(nodeInfo.hostname(), altHost)
.flatMap(new Func1<LifecycleState, Observable<Map<ServiceType, Integer>>>() {
@Override
public Observable<Map<ServiceType, Integer>> call(final LifecycleState lifecycleState) {
Map<ServiceType, Integer> services;
if (alternate != null) {
AlternateAddress aa = nodeInfo.alternateAddresses().get(alternate);
services = environment.sslEnabled() ? aa.sslServices() : aa.services();
} else {
services = environment.sslEnabled() ? nodeInfo.sslServices() : nodeInfo.services();
}
return Observable.just(services);
}
}).flatMap(new Func1<Map<ServiceType, Integer>, Observable<AddServiceRequest>>() {
@Override
public Observable<AddServiceRequest> call(final Map<ServiceType, Integer> services) {
List<AddServiceRequest> requests = new ArrayList<AddServiceRequest>(services.size());
for (Map.Entry<ServiceType, Integer> service : services.entrySet()) {
requests.add(new AddServiceRequest(service.getKey(), config.name(), config.username(),
config.password(), service.getValue(), nodeInfo.hostname()));
}
return Observable.from(requests);
}
}).flatMap(new Func1<AddServiceRequest, Observable<Service>>() {
@Override
public Observable<Service> call(AddServiceRequest request) {
return addService(request);
}
}).last().map(new Func1<Service, Boolean>() {
@Override
public Boolean call(Service service) {
return true;
}
});
observables.add(obs);
}
return Observable.merge(observables).last();
} | [
"private",
"Observable",
"<",
"Boolean",
">",
"reconfigureBucket",
"(",
"final",
"BucketConfig",
"config",
")",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Starting reconfiguration for bucket {}\"",
",",
"config",
".",
"name",
"(",
")",
")",
";",
"List",
"<",
"Observab... | For every bucket that is open, apply the reconfiguration.
@param config the config for this bucket. | [
"For",
"every",
"bucket",
"that",
"is",
"open",
"apply",
"the",
"reconfiguration",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/RequestHandler.java#L532-L576 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/service/strategies/PartitionSelectionStrategy.java | PartitionSelectionStrategy.selectByPartition | private static Endpoint selectByPartition(final List<Endpoint> endpoints, final short partition) {
if (partition >= 0) {
int numEndpoints = endpoints.size();
Endpoint endpoint = numEndpoints == 1 ? endpoints.get(0) : endpoints.get(partition % numEndpoints);
if (endpoint != null && endpoint.isState(LifecycleState.CONNECTED) && endpoint.isFree()) {
return endpoint;
}
return null;
} else {
return selectFirstConnected(endpoints);
}
} | java | private static Endpoint selectByPartition(final List<Endpoint> endpoints, final short partition) {
if (partition >= 0) {
int numEndpoints = endpoints.size();
Endpoint endpoint = numEndpoints == 1 ? endpoints.get(0) : endpoints.get(partition % numEndpoints);
if (endpoint != null && endpoint.isState(LifecycleState.CONNECTED) && endpoint.isFree()) {
return endpoint;
}
return null;
} else {
return selectFirstConnected(endpoints);
}
} | [
"private",
"static",
"Endpoint",
"selectByPartition",
"(",
"final",
"List",
"<",
"Endpoint",
">",
"endpoints",
",",
"final",
"short",
"partition",
")",
"{",
"if",
"(",
"partition",
">=",
"0",
")",
"{",
"int",
"numEndpoints",
"=",
"endpoints",
".",
"size",
... | Helper method to select the proper target endpoint by partition.
@param endpoints the list of currently available endpoints.
@param partition the partition of the incoming request.
@return the selected endpoint, or null if no acceptable one found. | [
"Helper",
"method",
"to",
"select",
"the",
"proper",
"target",
"endpoint",
"by",
"partition",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/service/strategies/PartitionSelectionStrategy.java#L68-L79 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/service/strategies/PartitionSelectionStrategy.java | PartitionSelectionStrategy.selectFirstConnected | private static Endpoint selectFirstConnected(final List<Endpoint> endpoints) {
for (Endpoint endpoint : endpoints) {
if (endpoint.isState(LifecycleState.CONNECTED) && endpoint.isFree()) {
return endpoint;
}
}
return null;
} | java | private static Endpoint selectFirstConnected(final List<Endpoint> endpoints) {
for (Endpoint endpoint : endpoints) {
if (endpoint.isState(LifecycleState.CONNECTED) && endpoint.isFree()) {
return endpoint;
}
}
return null;
} | [
"private",
"static",
"Endpoint",
"selectFirstConnected",
"(",
"final",
"List",
"<",
"Endpoint",
">",
"endpoints",
")",
"{",
"for",
"(",
"Endpoint",
"endpoint",
":",
"endpoints",
")",
"{",
"if",
"(",
"endpoint",
".",
"isState",
"(",
"LifecycleState",
".",
"CO... | Helper method to select the first connected endpoint if no particular pinning is needed.
@param endpoints the list of endpoints.
@return the first connected or null if none found. | [
"Helper",
"method",
"to",
"select",
"the",
"first",
"connected",
"endpoint",
"if",
"no",
"particular",
"pinning",
"is",
"needed",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/service/strategies/PartitionSelectionStrategy.java#L87-L94 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/tracing/RingBufferDiagnostics.java | RingBufferDiagnostics.totalCount | @InterfaceAudience.Public
@InterfaceStability.Experimental
public int totalCount() {
int total = countNonService;
for (Map.Entry<ServiceType, Integer> entry : counts.entrySet()) {
total += entry.getValue();
}
return total;
} | java | @InterfaceAudience.Public
@InterfaceStability.Experimental
public int totalCount() {
int total = countNonService;
for (Map.Entry<ServiceType, Integer> entry : counts.entrySet()) {
total += entry.getValue();
}
return total;
} | [
"@",
"InterfaceAudience",
".",
"Public",
"@",
"InterfaceStability",
".",
"Experimental",
"public",
"int",
"totalCount",
"(",
")",
"{",
"int",
"total",
"=",
"countNonService",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"ServiceType",
",",
"Integer",
">",
"ent... | Returns the count of all requests in the ringbuffer | [
"Returns",
"the",
"count",
"of",
"all",
"requests",
"in",
"the",
"ringbuffer"
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/tracing/RingBufferDiagnostics.java#L59-L67 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java | ViewHandler.encodeKeysGet | private String encodeKeysGet(String keys) {
try {
return URLEncoder.encode(keys, "UTF-8");
} catch(Exception ex) {
throw new RuntimeException("Could not prepare view argument: " + ex);
}
} | java | private String encodeKeysGet(String keys) {
try {
return URLEncoder.encode(keys, "UTF-8");
} catch(Exception ex) {
throw new RuntimeException("Could not prepare view argument: " + ex);
}
} | [
"private",
"String",
"encodeKeysGet",
"(",
"String",
"keys",
")",
"{",
"try",
"{",
"return",
"URLEncoder",
".",
"encode",
"(",
"keys",
",",
"\"UTF-8\"",
")",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\... | Encodes the "keys" JSON array into an URL-encoded form suitable for a GET on query service. | [
"Encodes",
"the",
"keys",
"JSON",
"array",
"into",
"an",
"URL",
"-",
"encoded",
"form",
"suitable",
"for",
"a",
"GET",
"on",
"query",
"service",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java#L236-L242 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java | ViewHandler.parseQueryResponse | private void parseQueryResponse(boolean last) {
if (viewParsingState == QUERY_STATE_INITIAL) {
parseViewInitial();
}
if (viewParsingState == QUERY_STATE_INFO) {
parseViewInfo();
}
if (viewParsingState == QUERY_STATE_ROWS) {
parseViewRows(last);
}
if (viewParsingState == QUERY_STATE_ERROR) {
parseViewError(last);
}
if (viewParsingState == QUERY_STATE_DONE) {
cleanupViewStates();
}
} | java | private void parseQueryResponse(boolean last) {
if (viewParsingState == QUERY_STATE_INITIAL) {
parseViewInitial();
}
if (viewParsingState == QUERY_STATE_INFO) {
parseViewInfo();
}
if (viewParsingState == QUERY_STATE_ROWS) {
parseViewRows(last);
}
if (viewParsingState == QUERY_STATE_ERROR) {
parseViewError(last);
}
if (viewParsingState == QUERY_STATE_DONE) {
cleanupViewStates();
}
} | [
"private",
"void",
"parseQueryResponse",
"(",
"boolean",
"last",
")",
"{",
"if",
"(",
"viewParsingState",
"==",
"QUERY_STATE_INITIAL",
")",
"{",
"parseViewInitial",
"(",
")",
";",
"}",
"if",
"(",
"viewParsingState",
"==",
"QUERY_STATE_INFO",
")",
"{",
"parseView... | Main dispatch method for a query parse cycle.
@param last if the given content chunk is the last one. | [
"Main",
"dispatch",
"method",
"for",
"a",
"query",
"parse",
"cycle",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java#L360-L380 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java | ViewHandler.parseViewInitial | private void parseViewInitial() {
switch (responseHeader.getStatus().code()) {
case 200:
viewParsingState = QUERY_STATE_INFO;
break;
default:
viewInfoObservable.onCompleted();
viewRowObservable.onCompleted();
viewParsingState = QUERY_STATE_ERROR;
}
} | java | private void parseViewInitial() {
switch (responseHeader.getStatus().code()) {
case 200:
viewParsingState = QUERY_STATE_INFO;
break;
default:
viewInfoObservable.onCompleted();
viewRowObservable.onCompleted();
viewParsingState = QUERY_STATE_ERROR;
}
} | [
"private",
"void",
"parseViewInitial",
"(",
")",
"{",
"switch",
"(",
"responseHeader",
".",
"getStatus",
"(",
")",
".",
"code",
"(",
")",
")",
"{",
"case",
"200",
":",
"viewParsingState",
"=",
"QUERY_STATE_INFO",
";",
"break",
";",
"default",
":",
"viewInf... | Parse the initial view query state. | [
"Parse",
"the",
"initial",
"view",
"query",
"state",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java#L397-L407 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java | ViewHandler.parseViewError | private void parseViewError(boolean last) {
if (!last) {
return;
}
if (responseHeader.getStatus().code() == 200) {
int openBracketPos = responseContent.bytesBefore((byte) '[') + responseContent.readerIndex();
int closeBracketLength = findSectionClosingPosition(responseContent, '[', ']') - openBracketPos + 1;
ByteBuf slice = responseContent.slice(openBracketPos, closeBracketLength);
viewErrorObservable.onNext("{\"errors\":" + slice.toString(CharsetUtil.UTF_8) + "}");
} else {
viewErrorObservable.onNext("{\"errors\":[" + responseContent.toString(CharsetUtil.UTF_8) + "]}");
}
viewErrorObservable.onCompleted();
viewParsingState = QUERY_STATE_DONE;
responseContent.discardReadBytes();
} | java | private void parseViewError(boolean last) {
if (!last) {
return;
}
if (responseHeader.getStatus().code() == 200) {
int openBracketPos = responseContent.bytesBefore((byte) '[') + responseContent.readerIndex();
int closeBracketLength = findSectionClosingPosition(responseContent, '[', ']') - openBracketPos + 1;
ByteBuf slice = responseContent.slice(openBracketPos, closeBracketLength);
viewErrorObservable.onNext("{\"errors\":" + slice.toString(CharsetUtil.UTF_8) + "}");
} else {
viewErrorObservable.onNext("{\"errors\":[" + responseContent.toString(CharsetUtil.UTF_8) + "]}");
}
viewErrorObservable.onCompleted();
viewParsingState = QUERY_STATE_DONE;
responseContent.discardReadBytes();
} | [
"private",
"void",
"parseViewError",
"(",
"boolean",
"last",
")",
"{",
"if",
"(",
"!",
"last",
")",
"{",
"return",
";",
"}",
"if",
"(",
"responseHeader",
".",
"getStatus",
"(",
")",
".",
"code",
"(",
")",
"==",
"200",
")",
"{",
"int",
"openBracketPos... | The query response is an error, parse it and attache it to the observable.
@param last if the given content chunk is the last one. | [
"The",
"query",
"response",
"is",
"an",
"error",
"parse",
"it",
"and",
"attache",
"it",
"to",
"the",
"observable",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java#L414-L431 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java | ViewHandler.parseViewInfo | private void parseViewInfo() {
int rowsStart = -1;
for (int i = responseContent.readerIndex(); i < responseContent.writerIndex() - 2; i++) {
byte curr = responseContent.getByte(i);
byte f1 = responseContent.getByte(i + 1);
byte f2 = responseContent.getByte(i + 2);
if (curr == '"' && f1 == 'r' && f2 == 'o') {
rowsStart = i;
break;
}
}
if (rowsStart == -1) {
return;
}
ByteBuf info = responseContent.readBytes(rowsStart - responseContent.readerIndex());
int closingPointer = info.forEachByteDesc(new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value != ',';
}
});
if (closingPointer > 0) {
info.setByte(closingPointer, '}');
viewInfoObservable.onNext(info);
} else {
//JVMCBC-360 don't forget to release the now unused info ByteBuf
info.release();
viewInfoObservable.onNext(Unpooled.EMPTY_BUFFER);
}
viewInfoObservable.onCompleted();
viewParsingState = QUERY_STATE_ROWS;
} | java | private void parseViewInfo() {
int rowsStart = -1;
for (int i = responseContent.readerIndex(); i < responseContent.writerIndex() - 2; i++) {
byte curr = responseContent.getByte(i);
byte f1 = responseContent.getByte(i + 1);
byte f2 = responseContent.getByte(i + 2);
if (curr == '"' && f1 == 'r' && f2 == 'o') {
rowsStart = i;
break;
}
}
if (rowsStart == -1) {
return;
}
ByteBuf info = responseContent.readBytes(rowsStart - responseContent.readerIndex());
int closingPointer = info.forEachByteDesc(new ByteBufProcessor() {
@Override
public boolean process(byte value) throws Exception {
return value != ',';
}
});
if (closingPointer > 0) {
info.setByte(closingPointer, '}');
viewInfoObservable.onNext(info);
} else {
//JVMCBC-360 don't forget to release the now unused info ByteBuf
info.release();
viewInfoObservable.onNext(Unpooled.EMPTY_BUFFER);
}
viewInfoObservable.onCompleted();
viewParsingState = QUERY_STATE_ROWS;
} | [
"private",
"void",
"parseViewInfo",
"(",
")",
"{",
"int",
"rowsStart",
"=",
"-",
"1",
";",
"for",
"(",
"int",
"i",
"=",
"responseContent",
".",
"readerIndex",
"(",
")",
";",
"i",
"<",
"responseContent",
".",
"writerIndex",
"(",
")",
"-",
"2",
";",
"i... | Parse out the info portion from the header part of the query response.
This includes the total rows, but also debug info if attached. | [
"Parse",
"out",
"the",
"info",
"portion",
"from",
"the",
"header",
"part",
"of",
"the",
"query",
"response",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java#L438-L473 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java | ViewHandler.parseViewRows | private void parseViewRows(boolean last) {
while (true) {
int openBracketPos = responseContent.bytesBefore((byte) '{');
int errorBlockPosition = findErrorBlockPosition(openBracketPos);
if (errorBlockPosition > 0 && errorBlockPosition < openBracketPos) {
responseContent.readerIndex(errorBlockPosition + responseContent.readerIndex());
viewRowObservable.onCompleted();
viewParsingState = QUERY_STATE_ERROR;
return;
}
int closeBracketPos = findSectionClosingPosition(responseContent, '{', '}');
if (closeBracketPos == -1) {
break;
}
int from = responseContent.readerIndex() + openBracketPos;
int to = closeBracketPos - openBracketPos - responseContent.readerIndex() + 1;
viewRowObservable.onNext(responseContent.slice(from, to).copy());
responseContent.readerIndex(closeBracketPos);
responseContent.discardReadBytes();
}
if (last) {
viewRowObservable.onCompleted();
viewErrorObservable.onCompleted();
viewParsingState = QUERY_STATE_DONE;
}
} | java | private void parseViewRows(boolean last) {
while (true) {
int openBracketPos = responseContent.bytesBefore((byte) '{');
int errorBlockPosition = findErrorBlockPosition(openBracketPos);
if (errorBlockPosition > 0 && errorBlockPosition < openBracketPos) {
responseContent.readerIndex(errorBlockPosition + responseContent.readerIndex());
viewRowObservable.onCompleted();
viewParsingState = QUERY_STATE_ERROR;
return;
}
int closeBracketPos = findSectionClosingPosition(responseContent, '{', '}');
if (closeBracketPos == -1) {
break;
}
int from = responseContent.readerIndex() + openBracketPos;
int to = closeBracketPos - openBracketPos - responseContent.readerIndex() + 1;
viewRowObservable.onNext(responseContent.slice(from, to).copy());
responseContent.readerIndex(closeBracketPos);
responseContent.discardReadBytes();
}
if (last) {
viewRowObservable.onCompleted();
viewErrorObservable.onCompleted();
viewParsingState = QUERY_STATE_DONE;
}
} | [
"private",
"void",
"parseViewRows",
"(",
"boolean",
"last",
")",
"{",
"while",
"(",
"true",
")",
"{",
"int",
"openBracketPos",
"=",
"responseContent",
".",
"bytesBefore",
"(",
"(",
"byte",
")",
"'",
"'",
")",
";",
"int",
"errorBlockPosition",
"=",
"findErr... | Streaming parse the actual rows from the response and pass to the underlying observable.
@param last if the given content chunk is the last one. | [
"Streaming",
"parse",
"the",
"actual",
"rows",
"from",
"the",
"response",
"and",
"pass",
"to",
"the",
"underlying",
"observable",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/view/ViewHandler.java#L480-L510 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/config/DefaultMemcachedBucketConfig.java | DefaultMemcachedBucketConfig.calculateKetamaHash | private static long calculateKetamaHash(final byte[] key) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(key);
byte[] digest = md5.digest();
long rv = ((long) (digest[3] & 0xFF) << 24)
| ((long) (digest[2] & 0xFF) << 16)
| ((long) (digest[1] & 0xFF) << 8)
| (digest[0] & 0xFF);
return rv & 0xffffffffL;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Could not encode ketama hash.", e);
}
} | java | private static long calculateKetamaHash(final byte[] key) {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(key);
byte[] digest = md5.digest();
long rv = ((long) (digest[3] & 0xFF) << 24)
| ((long) (digest[2] & 0xFF) << 16)
| ((long) (digest[1] & 0xFF) << 8)
| (digest[0] & 0xFF);
return rv & 0xffffffffL;
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Could not encode ketama hash.", e);
}
} | [
"private",
"static",
"long",
"calculateKetamaHash",
"(",
"final",
"byte",
"[",
"]",
"key",
")",
"{",
"try",
"{",
"MessageDigest",
"md5",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"\"MD5\"",
")",
";",
"md5",
".",
"update",
"(",
"key",
")",
";",
"byte... | Calculates the ketama hash for the given key.
@param key the key to calculate.
@return the calculated hash. | [
"Calculates",
"the",
"ketama",
"hash",
"for",
"the",
"given",
"key",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/DefaultMemcachedBucketConfig.java#L144-L157 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/query/QueryHandler.java | QueryHandler.parseQueryResponse | private void parseQueryResponse(boolean lastChunk) {
if (sectionDone || queryParsingState == QUERY_STATE_INITIAL) {
queryParsingState = transitionToNextToken(lastChunk);
}
if (queryParsingState == QUERY_STATE_SIGNATURE) {
parseQuerySignature(lastChunk);
}
if (queryParsingState == QUERY_STATE_ROWS_DECIDE) {
decideBetweenRawAndObjects(lastChunk);
}
if (queryParsingState == QUERY_STATE_ROWS) {
parseQueryRows(lastChunk);
} else if (queryParsingState == QUERY_STATE_ROWS_RAW) {
parseQueryRowsRaw(lastChunk);
}
if (queryParsingState == QUERY_STATE_ERROR) {
parseQueryError(lastChunk);
}
if (queryParsingState == QUERY_STATE_WARNING) {
parseQueryError(lastChunk); //warning are treated the same as errors -> sent to errorObservable
}
if (queryParsingState == QUERY_STATE_STATUS) {
parseQueryStatus(lastChunk);
}
if (queryParsingState == QUERY_STATE_INFO) {
parseQueryInfo(lastChunk);
} else if (queryParsingState == QUERY_STATE_NO_INFO) {
finishInfo();
}
if (queryParsingState == QUERY_STATE_DONE) {
//final state, but there could still be a small chunk with closing brackets
//only finalize and reset if this is the last chunk
sectionDone = lastChunk;
//if false this will allow next iteration to skip non-relevant automatic
//transition to next token (which is desirable since there is no more token).
//complete queryProfile as we are parsing it only in handler v2
queryProfileInfoObservable.onCompleted();
if (sectionDone) {
cleanupQueryStates();
}
}
} | java | private void parseQueryResponse(boolean lastChunk) {
if (sectionDone || queryParsingState == QUERY_STATE_INITIAL) {
queryParsingState = transitionToNextToken(lastChunk);
}
if (queryParsingState == QUERY_STATE_SIGNATURE) {
parseQuerySignature(lastChunk);
}
if (queryParsingState == QUERY_STATE_ROWS_DECIDE) {
decideBetweenRawAndObjects(lastChunk);
}
if (queryParsingState == QUERY_STATE_ROWS) {
parseQueryRows(lastChunk);
} else if (queryParsingState == QUERY_STATE_ROWS_RAW) {
parseQueryRowsRaw(lastChunk);
}
if (queryParsingState == QUERY_STATE_ERROR) {
parseQueryError(lastChunk);
}
if (queryParsingState == QUERY_STATE_WARNING) {
parseQueryError(lastChunk); //warning are treated the same as errors -> sent to errorObservable
}
if (queryParsingState == QUERY_STATE_STATUS) {
parseQueryStatus(lastChunk);
}
if (queryParsingState == QUERY_STATE_INFO) {
parseQueryInfo(lastChunk);
} else if (queryParsingState == QUERY_STATE_NO_INFO) {
finishInfo();
}
if (queryParsingState == QUERY_STATE_DONE) {
//final state, but there could still be a small chunk with closing brackets
//only finalize and reset if this is the last chunk
sectionDone = lastChunk;
//if false this will allow next iteration to skip non-relevant automatic
//transition to next token (which is desirable since there is no more token).
//complete queryProfile as we are parsing it only in handler v2
queryProfileInfoObservable.onCompleted();
if (sectionDone) {
cleanupQueryStates();
}
}
} | [
"private",
"void",
"parseQueryResponse",
"(",
"boolean",
"lastChunk",
")",
"{",
"if",
"(",
"sectionDone",
"||",
"queryParsingState",
"==",
"QUERY_STATE_INITIAL",
")",
"{",
"queryParsingState",
"=",
"transitionToNextToken",
"(",
"lastChunk",
")",
";",
"}",
"if",
"(... | Generic dispatch method to parse the query response chunks.
Depending on the state the parser is currently in, several different sub-methods are called
which do the actual handling.
@param lastChunk if the current emitted content body is the last one. | [
"Generic",
"dispatch",
"method",
"to",
"parse",
"the",
"query",
"response",
"chunks",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/query/QueryHandler.java#L427-L476 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/query/QueryHandler.java | QueryHandler.parseQuerySignature | private void parseQuerySignature(boolean lastChunk) {
ByteBufProcessor processor = null;
//signature can be any valid JSON item, which get tricky to detect
//let's try to find out what's the boundary character
int openPos = responseContent.forEachByte(new WhitespaceSkipper()) - responseContent.readerIndex();
if (openPos < 0) {
//only whitespace left in the buffer, need more data
return;
}
char openChar = (char) responseContent.getByte(responseContent.readerIndex() + openPos);
if (openChar == '{') {
processor = new ClosingPositionBufProcessor('{', '}', true);
} else if (openChar == '[') {
processor = new ClosingPositionBufProcessor('[', ']', true);
} else if (openChar == '"') {
processor = new StringClosingPositionBufProcessor();
} //else this should be a scalar, skip processor
int closePos;
if (processor != null) {
closePos = responseContent.forEachByte(processor) - responseContent.readerIndex();
} else {
closePos = findNextChar(responseContent, ',') - 1;
}
if (closePos > 0) {
responseContent.skipBytes(openPos);
int length = closePos - openPos + 1;
ByteBuf signature = responseContent.readSlice(length);
querySignatureObservable.onNext(signature.copy());
} else {
//wait for more data
return;
}
//note: the signature section could be absent, so we'll make sure to complete the observable
// when receiving status since this is in every well-formed response.
sectionDone();
queryParsingState = transitionToNextToken(lastChunk);
} | java | private void parseQuerySignature(boolean lastChunk) {
ByteBufProcessor processor = null;
//signature can be any valid JSON item, which get tricky to detect
//let's try to find out what's the boundary character
int openPos = responseContent.forEachByte(new WhitespaceSkipper()) - responseContent.readerIndex();
if (openPos < 0) {
//only whitespace left in the buffer, need more data
return;
}
char openChar = (char) responseContent.getByte(responseContent.readerIndex() + openPos);
if (openChar == '{') {
processor = new ClosingPositionBufProcessor('{', '}', true);
} else if (openChar == '[') {
processor = new ClosingPositionBufProcessor('[', ']', true);
} else if (openChar == '"') {
processor = new StringClosingPositionBufProcessor();
} //else this should be a scalar, skip processor
int closePos;
if (processor != null) {
closePos = responseContent.forEachByte(processor) - responseContent.readerIndex();
} else {
closePos = findNextChar(responseContent, ',') - 1;
}
if (closePos > 0) {
responseContent.skipBytes(openPos);
int length = closePos - openPos + 1;
ByteBuf signature = responseContent.readSlice(length);
querySignatureObservable.onNext(signature.copy());
} else {
//wait for more data
return;
}
//note: the signature section could be absent, so we'll make sure to complete the observable
// when receiving status since this is in every well-formed response.
sectionDone();
queryParsingState = transitionToNextToken(lastChunk);
} | [
"private",
"void",
"parseQuerySignature",
"(",
"boolean",
"lastChunk",
")",
"{",
"ByteBufProcessor",
"processor",
"=",
"null",
";",
"//signature can be any valid JSON item, which get tricky to detect",
"//let's try to find out what's the boundary character",
"int",
"openPos",
"=",
... | Parse the signature section in the N1QL response. | [
"Parse",
"the",
"signature",
"section",
"in",
"the",
"N1QL",
"response",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/query/QueryHandler.java#L574-L611 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/query/QueryHandler.java | QueryHandler.parseQueryRowsRaw | private void parseQueryRowsRaw(boolean lastChunk) {
while (responseContent.isReadable()) {
int splitPos = findSplitPosition(responseContent, ',');
int arrayEndPos = findSplitPosition(responseContent, ']');
boolean doSectionDone = false;
if (splitPos == -1 && arrayEndPos == -1) {
//need more data
break;
} else if (arrayEndPos > 0 && (arrayEndPos < splitPos || splitPos == -1)) {
splitPos = arrayEndPos;
doSectionDone = true;
}
int length = splitPos - responseContent.readerIndex();
ByteBuf resultSlice = responseContent.readSlice(length);
queryRowObservable.onNext(resultSlice.copy());
responseContent.skipBytes(1);
responseContent.discardReadBytes();
if (doSectionDone) {
sectionDone();
queryParsingState = transitionToNextToken(lastChunk);
break;
}
}
} | java | private void parseQueryRowsRaw(boolean lastChunk) {
while (responseContent.isReadable()) {
int splitPos = findSplitPosition(responseContent, ',');
int arrayEndPos = findSplitPosition(responseContent, ']');
boolean doSectionDone = false;
if (splitPos == -1 && arrayEndPos == -1) {
//need more data
break;
} else if (arrayEndPos > 0 && (arrayEndPos < splitPos || splitPos == -1)) {
splitPos = arrayEndPos;
doSectionDone = true;
}
int length = splitPos - responseContent.readerIndex();
ByteBuf resultSlice = responseContent.readSlice(length);
queryRowObservable.onNext(resultSlice.copy());
responseContent.skipBytes(1);
responseContent.discardReadBytes();
if (doSectionDone) {
sectionDone();
queryParsingState = transitionToNextToken(lastChunk);
break;
}
}
} | [
"private",
"void",
"parseQueryRowsRaw",
"(",
"boolean",
"lastChunk",
")",
"{",
"while",
"(",
"responseContent",
".",
"isReadable",
"(",
")",
")",
"{",
"int",
"splitPos",
"=",
"findSplitPosition",
"(",
"responseContent",
",",
"'",
"'",
")",
";",
"int",
"array... | Parses the query raw results from the content stream as long as there is data to be found. | [
"Parses",
"the",
"query",
"raw",
"results",
"from",
"the",
"content",
"stream",
"as",
"long",
"as",
"there",
"is",
"data",
"to",
"be",
"found",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/query/QueryHandler.java#L654-L681 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/query/QueryHandler.java | QueryHandler.parseQueryError | private void parseQueryError(boolean lastChunk) {
while (true) {
int openBracketPos = findNextChar(responseContent, '{');
if (isEmptySection(openBracketPos) || (lastChunk && openBracketPos < 0)) {
sectionDone();
queryParsingState = transitionToNextToken(lastChunk); //warnings or status
break;
}
int closeBracketPos = findSectionClosingPosition(responseContent, '{', '}');
if (closeBracketPos == -1) {
break;
}
int length = closeBracketPos - openBracketPos - responseContent.readerIndex() + 1;
responseContent.skipBytes(openBracketPos);
ByteBuf resultSlice = responseContent.readSlice(length);
queryErrorObservable.onNext(resultSlice.copy());
}
} | java | private void parseQueryError(boolean lastChunk) {
while (true) {
int openBracketPos = findNextChar(responseContent, '{');
if (isEmptySection(openBracketPos) || (lastChunk && openBracketPos < 0)) {
sectionDone();
queryParsingState = transitionToNextToken(lastChunk); //warnings or status
break;
}
int closeBracketPos = findSectionClosingPosition(responseContent, '{', '}');
if (closeBracketPos == -1) {
break;
}
int length = closeBracketPos - openBracketPos - responseContent.readerIndex() + 1;
responseContent.skipBytes(openBracketPos);
ByteBuf resultSlice = responseContent.readSlice(length);
queryErrorObservable.onNext(resultSlice.copy());
}
} | [
"private",
"void",
"parseQueryError",
"(",
"boolean",
"lastChunk",
")",
"{",
"while",
"(",
"true",
")",
"{",
"int",
"openBracketPos",
"=",
"findNextChar",
"(",
"responseContent",
",",
"'",
"'",
")",
";",
"if",
"(",
"isEmptySection",
"(",
"openBracketPos",
")... | Parses the errors and warnings from the content stream as long as there are some to be found. | [
"Parses",
"the",
"errors",
"and",
"warnings",
"from",
"the",
"content",
"stream",
"as",
"long",
"as",
"there",
"are",
"some",
"to",
"be",
"found",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/query/QueryHandler.java#L686-L705 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/metrics/AbstractLatencyMetricsCollector.java | AbstractLatencyMetricsCollector.remove | protected void remove(I identifier) {
LatencyStats removed = latencyMetrics.remove(identifier);
if (removed != null) {
try {
removed.stop();
} catch (Exception ex) {
LOGGER.warn("Caught exception while removing LatencyStats, moving on.", ex);
}
}
} | java | protected void remove(I identifier) {
LatencyStats removed = latencyMetrics.remove(identifier);
if (removed != null) {
try {
removed.stop();
} catch (Exception ex) {
LOGGER.warn("Caught exception while removing LatencyStats, moving on.", ex);
}
}
} | [
"protected",
"void",
"remove",
"(",
"I",
"identifier",
")",
"{",
"LatencyStats",
"removed",
"=",
"latencyMetrics",
".",
"remove",
"(",
"identifier",
")",
";",
"if",
"(",
"removed",
"!=",
"null",
")",
"{",
"try",
"{",
"removed",
".",
"stop",
"(",
")",
"... | Helper method to remove an item out of the stored metrics. | [
"Helper",
"method",
"to",
"remove",
"an",
"item",
"out",
"of",
"the",
"stored",
"metrics",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/metrics/AbstractLatencyMetricsCollector.java#L124-L133 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/security/sasl/ShaSaslClient.java | ShaSaslClient.hmac | private byte[] hmac(byte[] key, byte[] data) {
try {
final Mac mac = Mac.getInstance(hmacAlgorithm);
mac.init(new SecretKeySpec(key, mac.getAlgorithm()));
return mac.doFinal(data);
} catch (InvalidKeyException e) {
if (key.length == 0) {
throw new UnsupportedOperationException("This JVM does not support empty HMAC keys (empty passwords). "
+ "Please set a bucket password or upgrade your JVM.");
} else {
throw new RuntimeException("Failed to generate HMAC hash for password", e);
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
} | java | private byte[] hmac(byte[] key, byte[] data) {
try {
final Mac mac = Mac.getInstance(hmacAlgorithm);
mac.init(new SecretKeySpec(key, mac.getAlgorithm()));
return mac.doFinal(data);
} catch (InvalidKeyException e) {
if (key.length == 0) {
throw new UnsupportedOperationException("This JVM does not support empty HMAC keys (empty passwords). "
+ "Please set a bucket password or upgrade your JVM.");
} else {
throw new RuntimeException("Failed to generate HMAC hash for password", e);
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
} | [
"private",
"byte",
"[",
"]",
"hmac",
"(",
"byte",
"[",
"]",
"key",
",",
"byte",
"[",
"]",
"data",
")",
"{",
"try",
"{",
"final",
"Mac",
"mac",
"=",
"Mac",
".",
"getInstance",
"(",
"hmacAlgorithm",
")",
";",
"mac",
".",
"init",
"(",
"new",
"Secret... | Generate the HMAC with the given SHA algorithm | [
"Generate",
"the",
"HMAC",
"with",
"the",
"given",
"SHA",
"algorithm"
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/security/sasl/ShaSaslClient.java#L228-L243 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/security/sasl/ShaSaslClient.java | ShaSaslClient.xor | private static void xor(byte[] result, byte[] other) {
for (int i = 0; i < result.length; ++i) {
result[i] = (byte) (result[i] ^ other[i]);
}
} | java | private static void xor(byte[] result, byte[] other) {
for (int i = 0; i < result.length; ++i) {
result[i] = (byte) (result[i] ^ other[i]);
}
} | [
"private",
"static",
"void",
"xor",
"(",
"byte",
"[",
"]",
"result",
",",
"byte",
"[",
"]",
"other",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"result",
".",
"length",
";",
"++",
"i",
")",
"{",
"result",
"[",
"i",
"]",
"=",
... | XOR the two arrays and store the result in the first one.
@param result Where to store the result
@param other The other array to xor with | [
"XOR",
"the",
"two",
"arrays",
"and",
"store",
"the",
"result",
"in",
"the",
"first",
"one",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/security/sasl/ShaSaslClient.java#L299-L303 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/config/DefaultCouchbaseBucketConfig.java | DefaultCouchbaseBucketConfig.buildNodesWithPrimaryPartitions | private static Set<NetworkAddress> buildNodesWithPrimaryPartitions(final List<NodeInfo> nodeInfos,
final List<Partition> partitions) {
Set<NetworkAddress> nodes = new HashSet<NetworkAddress>(nodeInfos.size());
for (Partition partition : partitions) {
int index = partition.master();
if (index >= 0) {
nodes.add(nodeInfos.get(index).hostname());
}
}
return nodes;
} | java | private static Set<NetworkAddress> buildNodesWithPrimaryPartitions(final List<NodeInfo> nodeInfos,
final List<Partition> partitions) {
Set<NetworkAddress> nodes = new HashSet<NetworkAddress>(nodeInfos.size());
for (Partition partition : partitions) {
int index = partition.master();
if (index >= 0) {
nodes.add(nodeInfos.get(index).hostname());
}
}
return nodes;
} | [
"private",
"static",
"Set",
"<",
"NetworkAddress",
">",
"buildNodesWithPrimaryPartitions",
"(",
"final",
"List",
"<",
"NodeInfo",
">",
"nodeInfos",
",",
"final",
"List",
"<",
"Partition",
">",
"partitions",
")",
"{",
"Set",
"<",
"NetworkAddress",
">",
"nodes",
... | Pre-computes a set of nodes that have primary partitions active.
@param nodeInfos the list of nodes.
@param partitions the partitions.
@return a set containing the addresses of nodes with primary partitions. | [
"Pre",
"-",
"computes",
"a",
"set",
"of",
"nodes",
"that",
"have",
"primary",
"partitions",
"active",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/DefaultCouchbaseBucketConfig.java#L93-L103 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/tracing/DefaultOrphanResponseReporter.java | DefaultOrphanResponseReporter.logOrphans | void logOrphans(final List<Map<String, Object>> toLog) {
try {
String result = pretty
? prettyWriter().writeValueAsString(toLog)
: writer().writeValueAsString(toLog);
LOGGER.warn("Orphan responses observed: {}", result);
} catch (Exception ex) {
LOGGER.warn("Could not write orphan log.", ex);
}
} | java | void logOrphans(final List<Map<String, Object>> toLog) {
try {
String result = pretty
? prettyWriter().writeValueAsString(toLog)
: writer().writeValueAsString(toLog);
LOGGER.warn("Orphan responses observed: {}", result);
} catch (Exception ex) {
LOGGER.warn("Could not write orphan log.", ex);
}
} | [
"void",
"logOrphans",
"(",
"final",
"List",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"toLog",
")",
"{",
"try",
"{",
"String",
"result",
"=",
"pretty",
"?",
"prettyWriter",
"(",
")",
".",
"writeValueAsString",
"(",
"toLog",
")",
":",
"writer"... | This method is intended to be overridden in test implementations
to assert against the output. | [
"This",
"method",
"is",
"intended",
"to",
"be",
"overridden",
"in",
"test",
"implementations",
"to",
"assert",
"against",
"the",
"output",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/tracing/DefaultOrphanResponseReporter.java#L406-L415 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/env/Diagnostics.java | Diagnostics.collect | public static Map<String, Object> collect() {
Map<String, Object> infos = new TreeMap<String, Object>();
systemInfo(infos);
memInfo(infos);
threadInfo(infos);
gcInfo(infos);
runtimeInfo(infos);
return infos;
} | java | public static Map<String, Object> collect() {
Map<String, Object> infos = new TreeMap<String, Object>();
systemInfo(infos);
memInfo(infos);
threadInfo(infos);
gcInfo(infos);
runtimeInfo(infos);
return infos;
} | [
"public",
"static",
"Map",
"<",
"String",
",",
"Object",
">",
"collect",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"infos",
"=",
"new",
"TreeMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"systemInfo",
"(",
"infos",
")",
";"... | Collects all available infos in one map.
@return the map populated with the information. | [
"Collects",
"all",
"available",
"infos",
"in",
"one",
"map",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/env/Diagnostics.java#L136-L146 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/env/Diagnostics.java | Diagnostics.collectAndFormat | public static String collectAndFormat() {
Map<String, Object> infos = collect();
StringBuilder sb = new StringBuilder();
sb.append("Diagnostics {\n");
int count = 0;
for (Map.Entry<String, Object> info : infos.entrySet()) {
if (count++ > 0) {
sb.append(",\n");
}
sb.append(" ").append(info.getKey()).append("=").append(info.getValue());
}
sb.append("\n}");
return sb.toString();
} | java | public static String collectAndFormat() {
Map<String, Object> infos = collect();
StringBuilder sb = new StringBuilder();
sb.append("Diagnostics {\n");
int count = 0;
for (Map.Entry<String, Object> info : infos.entrySet()) {
if (count++ > 0) {
sb.append(",\n");
}
sb.append(" ").append(info.getKey()).append("=").append(info.getValue());
}
sb.append("\n}");
return sb.toString();
} | [
"public",
"static",
"String",
"collectAndFormat",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"infos",
"=",
"collect",
"(",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"append",
"(",
"\"Diagnostics... | Collects all available infos and formats it in a better readable way.
@return a formatted string of available information. | [
"Collects",
"all",
"available",
"infos",
"and",
"formats",
"it",
"in",
"a",
"better",
"readable",
"way",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/env/Diagnostics.java#L153-L168 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueSelectBucketHandler.java | KeyValueSelectBucketHandler.channelActive | @Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
if (selectBucketEnabled) {
byte[] key = bucket.getBytes();
short keyLength = (short) bucket.length();
BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(key);
request.setOpcode(SELECT_BUCKET_OPCODE);
request.setKeyLength(keyLength);
request.setTotalBodyLength(keyLength);
this.ctx.writeAndFlush(request);
} else {
//remove the handler if the feature is not enabled
originalPromise.setSuccess();
this.ctx.pipeline().remove(this);
this.ctx.fireChannelActive();
}
} | java | @Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
this.ctx = ctx;
if (selectBucketEnabled) {
byte[] key = bucket.getBytes();
short keyLength = (short) bucket.length();
BinaryMemcacheRequest request = new DefaultBinaryMemcacheRequest(key);
request.setOpcode(SELECT_BUCKET_OPCODE);
request.setKeyLength(keyLength);
request.setTotalBodyLength(keyLength);
this.ctx.writeAndFlush(request);
} else {
//remove the handler if the feature is not enabled
originalPromise.setSuccess();
this.ctx.pipeline().remove(this);
this.ctx.fireChannelActive();
}
} | [
"@",
"Override",
"public",
"void",
"channelActive",
"(",
"final",
"ChannelHandlerContext",
"ctx",
")",
"throws",
"Exception",
"{",
"this",
".",
"ctx",
"=",
"ctx",
";",
"if",
"(",
"selectBucketEnabled",
")",
"{",
"byte",
"[",
"]",
"key",
"=",
"bucket",
".",... | Once the channel is marked as active, select bucket command is sent if the HELLO request has SELECT_BUCKET feature
enabled.
@param ctx the handler context.
@throws Exception if something goes wrong during communicating to the server. | [
"Once",
"the",
"channel",
"is",
"marked",
"as",
"active",
"select",
"bucket",
"command",
"is",
"sent",
"if",
"the",
"HELLO",
"request",
"has",
"SELECT_BUCKET",
"feature",
"enabled",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueSelectBucketHandler.java#L116-L133 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueSelectBucketHandler.java | KeyValueSelectBucketHandler.channelRead0 | @Override
protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
switch (msg.getStatus()) {
case SUCCESS:
originalPromise.setSuccess();
ctx.pipeline().remove(this);
ctx.fireChannelActive();
break;
case ACCESS_ERROR:
originalPromise.setFailure(new AuthenticationException("Authentication failure on Select Bucket command"));
break;
case NOTFOUND_ERROR:
originalPromise.setFailure(new AuthenticationException("Bucket not found on Select Bucket command"));
break;
default:
originalPromise.setFailure(new AuthenticationException("Unhandled select bucket status: "
+ msg.getStatus()));
}
} | java | @Override
protected void channelRead0(ChannelHandlerContext ctx, FullBinaryMemcacheResponse msg) throws Exception {
switch (msg.getStatus()) {
case SUCCESS:
originalPromise.setSuccess();
ctx.pipeline().remove(this);
ctx.fireChannelActive();
break;
case ACCESS_ERROR:
originalPromise.setFailure(new AuthenticationException("Authentication failure on Select Bucket command"));
break;
case NOTFOUND_ERROR:
originalPromise.setFailure(new AuthenticationException("Bucket not found on Select Bucket command"));
break;
default:
originalPromise.setFailure(new AuthenticationException("Unhandled select bucket status: "
+ msg.getStatus()));
}
} | [
"@",
"Override",
"protected",
"void",
"channelRead0",
"(",
"ChannelHandlerContext",
"ctx",
",",
"FullBinaryMemcacheResponse",
"msg",
")",
"throws",
"Exception",
"{",
"switch",
"(",
"msg",
".",
"getStatus",
"(",
")",
")",
"{",
"case",
"SUCCESS",
":",
"originalPro... | Handles incoming Select bucket responses.
@param ctx the handler context.
@param msg the incoming message to investigate.
@throws Exception if something goes wrong during communicating to the server. | [
"Handles",
"incoming",
"Select",
"bucket",
"responses",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/kv/KeyValueSelectBucketHandler.java#L142-L160 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/deps/io/netty/handler/codec/memcache/binary/BinaryMemcacheObjectAggregator.java | BinaryMemcacheObjectAggregator.toFullMessage | private static FullMemcacheMessage toFullMessage(final MemcacheMessage msg) {
if (msg instanceof FullMemcacheMessage) {
return ((FullMemcacheMessage) msg).retain();
}
FullMemcacheMessage fullMsg;
if (msg instanceof BinaryMemcacheRequest) {
fullMsg = toFullRequest((BinaryMemcacheRequest) msg, Unpooled.EMPTY_BUFFER);
} else if (msg instanceof BinaryMemcacheResponse) {
fullMsg = toFullResponse((BinaryMemcacheResponse) msg, Unpooled.EMPTY_BUFFER);
} else {
throw new IllegalStateException();
}
return fullMsg;
} | java | private static FullMemcacheMessage toFullMessage(final MemcacheMessage msg) {
if (msg instanceof FullMemcacheMessage) {
return ((FullMemcacheMessage) msg).retain();
}
FullMemcacheMessage fullMsg;
if (msg instanceof BinaryMemcacheRequest) {
fullMsg = toFullRequest((BinaryMemcacheRequest) msg, Unpooled.EMPTY_BUFFER);
} else if (msg instanceof BinaryMemcacheResponse) {
fullMsg = toFullResponse((BinaryMemcacheResponse) msg, Unpooled.EMPTY_BUFFER);
} else {
throw new IllegalStateException();
}
return fullMsg;
} | [
"private",
"static",
"FullMemcacheMessage",
"toFullMessage",
"(",
"final",
"MemcacheMessage",
"msg",
")",
"{",
"if",
"(",
"msg",
"instanceof",
"FullMemcacheMessage",
")",
"{",
"return",
"(",
"(",
"FullMemcacheMessage",
")",
"msg",
")",
".",
"retain",
"(",
")",
... | Convert a invalid message into a full message.
This method makes sure that upstream handlers always get a full message returned, even
when invalid chunks are failing.
@param msg the message to transform.
@return a full message containing parts of the original message. | [
"Convert",
"a",
"invalid",
"message",
"into",
"a",
"full",
"message",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/deps/io/netty/handler/codec/memcache/binary/BinaryMemcacheObjectAggregator.java#L124-L139 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/config/refresher/HttpRefresher.java | HttpRefresher.repeatConfigUntilUnsubscribed | private void repeatConfigUntilUnsubscribed(final String name, Observable<BucketStreamingResponse> response) {
response.flatMap(new Func1<BucketStreamingResponse, Observable<ProposedBucketConfigContext>>() {
@Override
public Observable<ProposedBucketConfigContext> call(final BucketStreamingResponse response) {
LOGGER.debug("Config stream started for {} on {}.", name, response.host());
return response
.configs()
.map(new Func1<String, ProposedBucketConfigContext>() {
@Override
public ProposedBucketConfigContext call(String s) {
String raw = s.replace("$HOST", response.host());
return new ProposedBucketConfigContext(name, raw, NetworkAddress.create(response.host()));
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
LOGGER.debug("Config stream ended for {} on {}.", name, response.host());
}
});
}
})
.repeatWhen(new Func1<Observable<? extends Void>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Void> observable) {
return observable.flatMap(new Func1<Void, Observable<?>>() {
@Override
public Observable<?> call(Void aVoid) {
if (HttpRefresher.this.registrations().containsKey(name)) {
LOGGER.debug("Resubscribing config stream for bucket {}, still registered.", name);
return Observable.just(true);
} else {
LOGGER.debug("Not resubscribing config stream for bucket {}, not registered.", name);
return Observable.empty();
}
}
});
}
}).subscribe(new Subscriber<ProposedBucketConfigContext>() {
@Override
public void onCompleted() {
// ignored on purpose
}
@Override
public void onError(Throwable e) {
LOGGER.error("Error while subscribing to Http refresh stream!", e);
}
@Override
public void onNext(ProposedBucketConfigContext ctx) {
pushConfig(ctx);
}
});
} | java | private void repeatConfigUntilUnsubscribed(final String name, Observable<BucketStreamingResponse> response) {
response.flatMap(new Func1<BucketStreamingResponse, Observable<ProposedBucketConfigContext>>() {
@Override
public Observable<ProposedBucketConfigContext> call(final BucketStreamingResponse response) {
LOGGER.debug("Config stream started for {} on {}.", name, response.host());
return response
.configs()
.map(new Func1<String, ProposedBucketConfigContext>() {
@Override
public ProposedBucketConfigContext call(String s) {
String raw = s.replace("$HOST", response.host());
return new ProposedBucketConfigContext(name, raw, NetworkAddress.create(response.host()));
}
})
.doOnCompleted(new Action0() {
@Override
public void call() {
LOGGER.debug("Config stream ended for {} on {}.", name, response.host());
}
});
}
})
.repeatWhen(new Func1<Observable<? extends Void>, Observable<?>>() {
@Override
public Observable<?> call(Observable<? extends Void> observable) {
return observable.flatMap(new Func1<Void, Observable<?>>() {
@Override
public Observable<?> call(Void aVoid) {
if (HttpRefresher.this.registrations().containsKey(name)) {
LOGGER.debug("Resubscribing config stream for bucket {}, still registered.", name);
return Observable.just(true);
} else {
LOGGER.debug("Not resubscribing config stream for bucket {}, not registered.", name);
return Observable.empty();
}
}
});
}
}).subscribe(new Subscriber<ProposedBucketConfigContext>() {
@Override
public void onCompleted() {
// ignored on purpose
}
@Override
public void onError(Throwable e) {
LOGGER.error("Error while subscribing to Http refresh stream!", e);
}
@Override
public void onNext(ProposedBucketConfigContext ctx) {
pushConfig(ctx);
}
});
} | [
"private",
"void",
"repeatConfigUntilUnsubscribed",
"(",
"final",
"String",
"name",
",",
"Observable",
"<",
"BucketStreamingResponse",
">",
"response",
")",
"{",
"response",
".",
"flatMap",
"(",
"new",
"Func1",
"<",
"BucketStreamingResponse",
",",
"Observable",
"<",... | Helper method to push configs until unsubscribed, even when a stream closes.
@param name the name of the bucket.
@param response the response source observable to resubscribe if needed. | [
"Helper",
"method",
"to",
"push",
"configs",
"until",
"unsubscribed",
"even",
"when",
"a",
"stream",
"closes",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/refresher/HttpRefresher.java#L151-L206 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/config/refresher/HttpRefresher.java | HttpRefresher.isValidConfigNode | private static boolean isValidConfigNode(final boolean sslEnabled, final NodeInfo nodeInfo) {
if (sslEnabled && nodeInfo.sslServices().containsKey(ServiceType.CONFIG)) {
return true;
} else if (nodeInfo.services().containsKey(ServiceType.CONFIG)) {
return true;
}
return false;
} | java | private static boolean isValidConfigNode(final boolean sslEnabled, final NodeInfo nodeInfo) {
if (sslEnabled && nodeInfo.sslServices().containsKey(ServiceType.CONFIG)) {
return true;
} else if (nodeInfo.services().containsKey(ServiceType.CONFIG)) {
return true;
}
return false;
} | [
"private",
"static",
"boolean",
"isValidConfigNode",
"(",
"final",
"boolean",
"sslEnabled",
",",
"final",
"NodeInfo",
"nodeInfo",
")",
"{",
"if",
"(",
"sslEnabled",
"&&",
"nodeInfo",
".",
"sslServices",
"(",
")",
".",
"containsKey",
"(",
"ServiceType",
".",
"C... | Helper method to detect if the given node can actually perform http config refresh.
@param sslEnabled true if ssl enabled, false otherwise.
@param nodeInfo the node info for the given node.
@return true if it is a valid config node, false otherwise. | [
"Helper",
"method",
"to",
"detect",
"if",
"the",
"given",
"node",
"can",
"actually",
"perform",
"http",
"config",
"refresh",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/config/refresher/HttpRefresher.java#L367-L374 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java | ByteBufJsonParser.parse | public void parse() throws EOFException {
if (!startedStreaming && levelStack.isEmpty()) {
readNextChar(null);
switch (currentChar) {
case (byte) 0xEF:
pushLevel(Mode.BOM);
break;
case O_CURLY:
pushLevel(Mode.JSON_OBJECT);
break;
case O_SQUARE:
pushLevel(Mode.JSON_ARRAY);
break;
default:
throw new IllegalStateException("Only UTF-8 is supported");
}
startedStreaming = true;
}
while (true) {
if (levelStack.isEmpty()) {
return; //nothing more to do
}
JsonLevel currentLevel = levelStack.peek();
switch (currentLevel.peekMode()) {
case BOM:
readBOM();
break;
case JSON_OBJECT:
readObject(currentLevel);
break;
case JSON_ARRAY:
readArray(currentLevel);
break;
case JSON_OBJECT_VALUE:
case JSON_ARRAY_VALUE:
case JSON_STRING_HASH_KEY:
case JSON_STRING_VALUE:
case JSON_BOOLEAN_TRUE_VALUE:
case JSON_BOOLEAN_FALSE_VALUE:
case JSON_NUMBER_VALUE:
case JSON_NULL_VALUE:
readValue(currentLevel);
break;
}
}
} | java | public void parse() throws EOFException {
if (!startedStreaming && levelStack.isEmpty()) {
readNextChar(null);
switch (currentChar) {
case (byte) 0xEF:
pushLevel(Mode.BOM);
break;
case O_CURLY:
pushLevel(Mode.JSON_OBJECT);
break;
case O_SQUARE:
pushLevel(Mode.JSON_ARRAY);
break;
default:
throw new IllegalStateException("Only UTF-8 is supported");
}
startedStreaming = true;
}
while (true) {
if (levelStack.isEmpty()) {
return; //nothing more to do
}
JsonLevel currentLevel = levelStack.peek();
switch (currentLevel.peekMode()) {
case BOM:
readBOM();
break;
case JSON_OBJECT:
readObject(currentLevel);
break;
case JSON_ARRAY:
readArray(currentLevel);
break;
case JSON_OBJECT_VALUE:
case JSON_ARRAY_VALUE:
case JSON_STRING_HASH_KEY:
case JSON_STRING_VALUE:
case JSON_BOOLEAN_TRUE_VALUE:
case JSON_BOOLEAN_FALSE_VALUE:
case JSON_NUMBER_VALUE:
case JSON_NULL_VALUE:
readValue(currentLevel);
break;
}
}
} | [
"public",
"void",
"parse",
"(",
")",
"throws",
"EOFException",
"{",
"if",
"(",
"!",
"startedStreaming",
"&&",
"levelStack",
".",
"isEmpty",
"(",
")",
")",
"{",
"readNextChar",
"(",
"null",
")",
";",
"switch",
"(",
"currentChar",
")",
"{",
"case",
"(",
... | Instructs the parser to start parsing the current buffer.
@throws EOFException if parsing fails. | [
"Instructs",
"the",
"parser",
"to",
"start",
"parsing",
"the",
"current",
"buffer",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java#L107-L156 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java | ByteBufJsonParser.popAndResetToOldLevel | private void popAndResetToOldLevel() {
this.levelStack.pop();
if (!this.levelStack.isEmpty()) {
JsonLevel newTop = levelStack.peek();
if (newTop != null) {
newTop.removeLastTokenFromJsonPointer();
}
}
} | java | private void popAndResetToOldLevel() {
this.levelStack.pop();
if (!this.levelStack.isEmpty()) {
JsonLevel newTop = levelStack.peek();
if (newTop != null) {
newTop.removeLastTokenFromJsonPointer();
}
}
} | [
"private",
"void",
"popAndResetToOldLevel",
"(",
")",
"{",
"this",
".",
"levelStack",
".",
"pop",
"(",
")",
";",
"if",
"(",
"!",
"this",
".",
"levelStack",
".",
"isEmpty",
"(",
")",
")",
"{",
"JsonLevel",
"newTop",
"=",
"levelStack",
".",
"peek",
"(",
... | Helper method to clean up after being done with the last stack
so it removes the tokens that pointed to that object. | [
"Helper",
"method",
"to",
"clean",
"up",
"after",
"being",
"done",
"with",
"the",
"last",
"stack",
"so",
"it",
"removes",
"the",
"tokens",
"that",
"pointed",
"to",
"that",
"object",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java#L193-L201 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java | ByteBufJsonParser.readArray | private void readArray(final JsonLevel level) throws EOFException {
while (true) {
readNextChar(level);
if (this.currentChar == JSON_ST) {
level.pushMode(Mode.JSON_STRING_VALUE);
readValue(level);
} else if (this.currentChar == O_CURLY) {
if (this.tree.isIntermediaryPath(level.jsonPointer())) {
this.pushLevel(Mode.JSON_OBJECT);
return;
}
level.pushMode(Mode.JSON_OBJECT_VALUE);
readValue(level);
} else if (this.currentChar == O_SQUARE) {
if (this.tree.isIntermediaryPath(level.jsonPointer())) {
this.pushLevel(Mode.JSON_ARRAY);
return;
} else {
level.pushMode(Mode.JSON_ARRAY_VALUE);
readValue(level);
}
} else if (this.currentChar == JSON_T) {
level.pushMode(Mode.JSON_BOOLEAN_TRUE_VALUE);
readValue(level);
} else if (this.currentChar == JSON_F) {
level.pushMode(Mode.JSON_BOOLEAN_FALSE_VALUE);
readValue(level);
} else if (this.currentChar == JSON_N) {
level.pushMode(Mode.JSON_NULL_VALUE);
readValue(level);
} else if (isNumber(this.currentChar)) {
level.pushMode(JSON_NUMBER_VALUE);
readValue(level);
} else if (this.currentChar == JSON_COMMA) {
level.updateIndex();
level.setArrayIndexOnJsonPointer();
} else if (this.currentChar == C_SQUARE) {
popAndResetToOldLevel();
return;
}
}
} | java | private void readArray(final JsonLevel level) throws EOFException {
while (true) {
readNextChar(level);
if (this.currentChar == JSON_ST) {
level.pushMode(Mode.JSON_STRING_VALUE);
readValue(level);
} else if (this.currentChar == O_CURLY) {
if (this.tree.isIntermediaryPath(level.jsonPointer())) {
this.pushLevel(Mode.JSON_OBJECT);
return;
}
level.pushMode(Mode.JSON_OBJECT_VALUE);
readValue(level);
} else if (this.currentChar == O_SQUARE) {
if (this.tree.isIntermediaryPath(level.jsonPointer())) {
this.pushLevel(Mode.JSON_ARRAY);
return;
} else {
level.pushMode(Mode.JSON_ARRAY_VALUE);
readValue(level);
}
} else if (this.currentChar == JSON_T) {
level.pushMode(Mode.JSON_BOOLEAN_TRUE_VALUE);
readValue(level);
} else if (this.currentChar == JSON_F) {
level.pushMode(Mode.JSON_BOOLEAN_FALSE_VALUE);
readValue(level);
} else if (this.currentChar == JSON_N) {
level.pushMode(Mode.JSON_NULL_VALUE);
readValue(level);
} else if (isNumber(this.currentChar)) {
level.pushMode(JSON_NUMBER_VALUE);
readValue(level);
} else if (this.currentChar == JSON_COMMA) {
level.updateIndex();
level.setArrayIndexOnJsonPointer();
} else if (this.currentChar == C_SQUARE) {
popAndResetToOldLevel();
return;
}
}
} | [
"private",
"void",
"readArray",
"(",
"final",
"JsonLevel",
"level",
")",
"throws",
"EOFException",
"{",
"while",
"(",
"true",
")",
"{",
"readNextChar",
"(",
"level",
")",
";",
"if",
"(",
"this",
".",
"currentChar",
"==",
"JSON_ST",
")",
"{",
"level",
"."... | Handle the logic for reading down a JSON Array.
@param level the current level.
@throws EOFException if more data is needed. | [
"Handle",
"the",
"logic",
"for",
"reading",
"down",
"a",
"JSON",
"Array",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java#L283-L324 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java | ByteBufJsonParser.readValue | private void readValue(final JsonLevel level) throws EOFException {
int readerIndex = content.readerIndex();
ByteBufProcessor processor = null;
Mode mode = level.peekMode();
switch (mode) {
case JSON_ARRAY_VALUE:
arProcessor.reset();
processor = arProcessor;
break;
case JSON_OBJECT_VALUE:
obProcessor.reset();
processor = obProcessor;
break;
case JSON_STRING_VALUE:
case JSON_STRING_HASH_KEY:
processor = stProcessor;
break;
case JSON_NULL_VALUE:
nullProcessor.reset();
processor = nullProcessor;
break;
case JSON_BOOLEAN_TRUE_VALUE:
processor = trueProcessor;
break;
case JSON_BOOLEAN_FALSE_VALUE:
processor = falseProcessor;
break;
case JSON_NUMBER_VALUE:
processor = numProcessor;
break;
}
int length;
boolean shouldSaveValue = tree.isTerminalPath(level.jsonPointer()) || mode == Mode.JSON_STRING_HASH_KEY;
int lastValidIndex = content.forEachByte(processor);
if (lastValidIndex == -1) {
if (mode == Mode.JSON_NUMBER_VALUE && content.readableBytes() > 2) {
length = 1;
level.setCurrentValue(this.content.copy(readerIndex - 1, length), length);
//no need to skip here
this.content.discardReadBytes();
level.emitJsonPointerValue();
} else {
throw NEED_MORE_DATA;
}
} else {
if (mode == Mode.JSON_OBJECT_VALUE ||
mode == Mode.JSON_ARRAY_VALUE ||
mode == Mode.JSON_STRING_VALUE ||
mode == Mode.JSON_STRING_HASH_KEY ||
mode == Mode.JSON_NULL_VALUE ||
mode == Mode.JSON_BOOLEAN_TRUE_VALUE ||
mode == Mode.JSON_BOOLEAN_FALSE_VALUE) {
length = lastValidIndex - readerIndex + 1;
if (shouldSaveValue) {
level.setCurrentValue(this.content.copy(readerIndex - 1, length + 1), length);
level.emitJsonPointerValue();
}
this.content.skipBytes(length);
this.content.discardReadBytes();
} else {
//special handling for number as they don't need structural tokens intact
//and the processor returns only on an unacceptable value rather than a finite state automaton
length = lastValidIndex - readerIndex;
if (length > 0) {
if (shouldSaveValue) {
level.setCurrentValue(this.content.copy(readerIndex - 1, length + 1), length);
level.emitJsonPointerValue();
}
this.content.skipBytes(length);
this.content.discardReadBytes();
} else {
length = 1;
if (shouldSaveValue) {
level.setCurrentValue(this.content.copy(readerIndex - 1, length), length);
this.content.discardReadBytes();
level.emitJsonPointerValue();
}
}
}
}
if (mode != Mode.JSON_STRING_HASH_KEY) {
level.removeLastTokenFromJsonPointer();
}
level.popMode();
} | java | private void readValue(final JsonLevel level) throws EOFException {
int readerIndex = content.readerIndex();
ByteBufProcessor processor = null;
Mode mode = level.peekMode();
switch (mode) {
case JSON_ARRAY_VALUE:
arProcessor.reset();
processor = arProcessor;
break;
case JSON_OBJECT_VALUE:
obProcessor.reset();
processor = obProcessor;
break;
case JSON_STRING_VALUE:
case JSON_STRING_HASH_KEY:
processor = stProcessor;
break;
case JSON_NULL_VALUE:
nullProcessor.reset();
processor = nullProcessor;
break;
case JSON_BOOLEAN_TRUE_VALUE:
processor = trueProcessor;
break;
case JSON_BOOLEAN_FALSE_VALUE:
processor = falseProcessor;
break;
case JSON_NUMBER_VALUE:
processor = numProcessor;
break;
}
int length;
boolean shouldSaveValue = tree.isTerminalPath(level.jsonPointer()) || mode == Mode.JSON_STRING_HASH_KEY;
int lastValidIndex = content.forEachByte(processor);
if (lastValidIndex == -1) {
if (mode == Mode.JSON_NUMBER_VALUE && content.readableBytes() > 2) {
length = 1;
level.setCurrentValue(this.content.copy(readerIndex - 1, length), length);
//no need to skip here
this.content.discardReadBytes();
level.emitJsonPointerValue();
} else {
throw NEED_MORE_DATA;
}
} else {
if (mode == Mode.JSON_OBJECT_VALUE ||
mode == Mode.JSON_ARRAY_VALUE ||
mode == Mode.JSON_STRING_VALUE ||
mode == Mode.JSON_STRING_HASH_KEY ||
mode == Mode.JSON_NULL_VALUE ||
mode == Mode.JSON_BOOLEAN_TRUE_VALUE ||
mode == Mode.JSON_BOOLEAN_FALSE_VALUE) {
length = lastValidIndex - readerIndex + 1;
if (shouldSaveValue) {
level.setCurrentValue(this.content.copy(readerIndex - 1, length + 1), length);
level.emitJsonPointerValue();
}
this.content.skipBytes(length);
this.content.discardReadBytes();
} else {
//special handling for number as they don't need structural tokens intact
//and the processor returns only on an unacceptable value rather than a finite state automaton
length = lastValidIndex - readerIndex;
if (length > 0) {
if (shouldSaveValue) {
level.setCurrentValue(this.content.copy(readerIndex - 1, length + 1), length);
level.emitJsonPointerValue();
}
this.content.skipBytes(length);
this.content.discardReadBytes();
} else {
length = 1;
if (shouldSaveValue) {
level.setCurrentValue(this.content.copy(readerIndex - 1, length), length);
this.content.discardReadBytes();
level.emitJsonPointerValue();
}
}
}
}
if (mode != Mode.JSON_STRING_HASH_KEY) {
level.removeLastTokenFromJsonPointer();
}
level.popMode();
} | [
"private",
"void",
"readValue",
"(",
"final",
"JsonLevel",
"level",
")",
"throws",
"EOFException",
"{",
"int",
"readerIndex",
"=",
"content",
".",
"readerIndex",
"(",
")",
";",
"ByteBufProcessor",
"processor",
"=",
"null",
";",
"Mode",
"mode",
"=",
"level",
... | Handle the logic for reading down a JSON Value.
@param level the current level.
@throws EOFException if more data is needed. | [
"Handle",
"the",
"logic",
"for",
"reading",
"down",
"a",
"JSON",
"Value",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java#L332-L418 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java | ByteBufJsonParser.readBOM | private void readBOM() throws EOFException {
int readerIndex = content.readerIndex();
int lastBOMIndex = content.forEachByte(bomProcessor);
if (lastBOMIndex == -1) {
throw NEED_MORE_DATA;
}
if (lastBOMIndex > readerIndex) {
this.content.skipBytes(lastBOMIndex - readerIndex + 1);
this.content.discardReadBytes();
}
this.levelStack.pop();
} | java | private void readBOM() throws EOFException {
int readerIndex = content.readerIndex();
int lastBOMIndex = content.forEachByte(bomProcessor);
if (lastBOMIndex == -1) {
throw NEED_MORE_DATA;
}
if (lastBOMIndex > readerIndex) {
this.content.skipBytes(lastBOMIndex - readerIndex + 1);
this.content.discardReadBytes();
}
this.levelStack.pop();
} | [
"private",
"void",
"readBOM",
"(",
")",
"throws",
"EOFException",
"{",
"int",
"readerIndex",
"=",
"content",
".",
"readerIndex",
"(",
")",
";",
"int",
"lastBOMIndex",
"=",
"content",
".",
"forEachByte",
"(",
"bomProcessor",
")",
";",
"if",
"(",
"lastBOMIndex... | Reads the UTF-8 Byte Order Mark.
@throws EOFException if more input is needed. | [
"Reads",
"the",
"UTF",
"-",
"8",
"Byte",
"Order",
"Mark",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java#L425-L438 | train |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/event/metrics/LatencyMetric.java | LatencyMetric.export | public Map<String, Object> export() {
Map<String, Object> result = new HashMap<String, Object>();
result.put("min", min());
result.put("max", max());
result.put("count", count());
result.put("percentiles", percentiles());
result.put("timeUnit", timeUnit().toString());
return result;
} | java | public Map<String, Object> export() {
Map<String, Object> result = new HashMap<String, Object>();
result.put("min", min());
result.put("max", max());
result.put("count", count());
result.put("percentiles", percentiles());
result.put("timeUnit", timeUnit().toString());
return result;
} | [
"public",
"Map",
"<",
"String",
",",
"Object",
">",
"export",
"(",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"result",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"result",
".",
"put",
"(",
"\"min\"",
",",
"... | Exports this object to a plain map structure which can be easily converted into other
target formats.
@return the exported structure. | [
"Exports",
"this",
"object",
"to",
"a",
"plain",
"map",
"structure",
"which",
"can",
"be",
"easily",
"converted",
"into",
"other",
"target",
"formats",
"."
] | 97f0427112c2168fee1d6499904f5fa0e24c6797 | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/event/metrics/LatencyMetric.java#L97-L105 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.