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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java | KeyUtils.getPrefixedKeyString | public static String getPrefixedKeyString(Query query, Result result, List<String> typeNames) {
StringBuilder sb = new StringBuilder();
addTypeName(query, result, typeNames, sb);
addKeyString(query, result, sb);
return sb.toString();
} | java | public static String getPrefixedKeyString(Query query, Result result, List<String> typeNames) {
StringBuilder sb = new StringBuilder();
addTypeName(query, result, typeNames, sb);
addKeyString(query, result, sb);
return sb.toString();
} | [
"public",
"static",
"String",
"getPrefixedKeyString",
"(",
"Query",
"query",
",",
"Result",
"result",
",",
"List",
"<",
"String",
">",
"typeNames",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"addTypeName",
"(",
"query",
",",
"result",
",",
"typeNames",
",",
"sb",
")",
";",
"addKeyString",
"(",
"query",
",",
"result",
",",
"sb",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] | Gets the key string, without rootPrefix or Alias
@param query the query
@param result the result
@param typeNames the type names
@return the key string | [
"Gets",
"the",
"key",
"string",
"without",
"rootPrefix",
"or",
"Alias"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java#L89-L94 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java | KeyUtils.addMBeanIdentifier | private static void addMBeanIdentifier(Query query, Result result, StringBuilder sb) {
if (result.getKeyAlias() != null) {
sb.append(result.getKeyAlias());
} else if (query.isUseObjDomainAsKey()) {
sb.append(StringUtils.cleanupStr(result.getObjDomain(), query.isAllowDottedKeys()));
} else {
sb.append(StringUtils.cleanupStr(result.getClassName()));
}
} | java | private static void addMBeanIdentifier(Query query, Result result, StringBuilder sb) {
if (result.getKeyAlias() != null) {
sb.append(result.getKeyAlias());
} else if (query.isUseObjDomainAsKey()) {
sb.append(StringUtils.cleanupStr(result.getObjDomain(), query.isAllowDottedKeys()));
} else {
sb.append(StringUtils.cleanupStr(result.getClassName()));
}
} | [
"private",
"static",
"void",
"addMBeanIdentifier",
"(",
"Query",
"query",
",",
"Result",
"result",
",",
"StringBuilder",
"sb",
")",
"{",
"if",
"(",
"result",
".",
"getKeyAlias",
"(",
")",
"!=",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"result",
".",
"getKeyAlias",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"query",
".",
"isUseObjDomainAsKey",
"(",
")",
")",
"{",
"sb",
".",
"append",
"(",
"StringUtils",
".",
"cleanupStr",
"(",
"result",
".",
"getObjDomain",
"(",
")",
",",
"query",
".",
"isAllowDottedKeys",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"sb",
".",
"append",
"(",
"StringUtils",
".",
"cleanupStr",
"(",
"result",
".",
"getClassName",
"(",
")",
")",
")",
";",
"}",
"}"
] | Adds a key to the StringBuilder
It uses in order of preference:
1. resultAlias if that was specified as part of the query
2. The domain portion of the ObjectName in the query if useObjDomainAsKey is set to true
3. else, the Class Name of the MBean. I.e. ClassName will be used by default if the
user doesn't specify anything special
@param query
@param result
@param sb | [
"Adds",
"a",
"key",
"to",
"the",
"StringBuilder"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/KeyUtils.java#L127-L135 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-ganglia/src/main/java/com/googlecode/jmxtrans/model/output/GangliaWriter.java | GangliaWriter.validateSetup | @Override
public void validateSetup(Server server, Query query) throws ValidationException {
// Determine the spoofed hostname
spoofedHostName = getSpoofedHostName(server.getHost(), server.getAlias());
log.debug("Validated Ganglia metric [" +
HOST + ": " + host + ", " +
PORT + ": " + port + ", " +
ADDRESSING_MODE + ": " + addressingMode + ", " +
TTL + ": " + ttl + ", " +
V31 + ": " + v31 + ", " +
UNITS + ": '" + units + "', " +
SLOPE + ": " + slope + ", " +
TMAX + ": " + tmax + ", " +
DMAX + ": " + dmax + ", " +
SPOOF_NAME + ": " + spoofedHostName + ", " +
GROUP_NAME + ": '" + groupName + "']");
} | java | @Override
public void validateSetup(Server server, Query query) throws ValidationException {
// Determine the spoofed hostname
spoofedHostName = getSpoofedHostName(server.getHost(), server.getAlias());
log.debug("Validated Ganglia metric [" +
HOST + ": " + host + ", " +
PORT + ": " + port + ", " +
ADDRESSING_MODE + ": " + addressingMode + ", " +
TTL + ": " + ttl + ", " +
V31 + ": " + v31 + ", " +
UNITS + ": '" + units + "', " +
SLOPE + ": " + slope + ", " +
TMAX + ": " + tmax + ", " +
DMAX + ": " + dmax + ", " +
SPOOF_NAME + ": " + spoofedHostName + ", " +
GROUP_NAME + ": '" + groupName + "']");
} | [
"@",
"Override",
"public",
"void",
"validateSetup",
"(",
"Server",
"server",
",",
"Query",
"query",
")",
"throws",
"ValidationException",
"{",
"// Determine the spoofed hostname",
"spoofedHostName",
"=",
"getSpoofedHostName",
"(",
"server",
".",
"getHost",
"(",
")",
",",
"server",
".",
"getAlias",
"(",
")",
")",
";",
"log",
".",
"debug",
"(",
"\"Validated Ganglia metric [\"",
"+",
"HOST",
"+",
"\": \"",
"+",
"host",
"+",
"\", \"",
"+",
"PORT",
"+",
"\": \"",
"+",
"port",
"+",
"\", \"",
"+",
"ADDRESSING_MODE",
"+",
"\": \"",
"+",
"addressingMode",
"+",
"\", \"",
"+",
"TTL",
"+",
"\": \"",
"+",
"ttl",
"+",
"\", \"",
"+",
"V31",
"+",
"\": \"",
"+",
"v31",
"+",
"\", \"",
"+",
"UNITS",
"+",
"\": '\"",
"+",
"units",
"+",
"\"', \"",
"+",
"SLOPE",
"+",
"\": \"",
"+",
"slope",
"+",
"\", \"",
"+",
"TMAX",
"+",
"\": \"",
"+",
"tmax",
"+",
"\", \"",
"+",
"DMAX",
"+",
"\": \"",
"+",
"dmax",
"+",
"\", \"",
"+",
"SPOOF_NAME",
"+",
"\": \"",
"+",
"spoofedHostName",
"+",
"\", \"",
"+",
"GROUP_NAME",
"+",
"\": '\"",
"+",
"groupName",
"+",
"\"']\"",
")",
";",
"}"
] | Parse and validate settings. | [
"Parse",
"and",
"validate",
"settings",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-ganglia/src/main/java/com/googlecode/jmxtrans/model/output/GangliaWriter.java#L152-L169 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-ganglia/src/main/java/com/googlecode/jmxtrans/model/output/GangliaWriter.java | GangliaWriter.internalWrite | @Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
for (final Result result : results) {
final String name = KeyUtils.getKeyString(query, result, getTypeNames());
Object transformedValue = valueTransformer.apply(result.getValue());
GMetricType dataType = getType(result.getValue());
log.debug("Sending Ganglia metric {}={} [type={}]", name, transformedValue, dataType);
try (GMetric metric = new GMetric(host, port, addressingMode, ttl, v31, null, spoofedHostName)) {
metric.announce(name, transformedValue.toString(), dataType, units, slope, tmax, dmax, groupName);
}
}
} | java | @Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
for (final Result result : results) {
final String name = KeyUtils.getKeyString(query, result, getTypeNames());
Object transformedValue = valueTransformer.apply(result.getValue());
GMetricType dataType = getType(result.getValue());
log.debug("Sending Ganglia metric {}={} [type={}]", name, transformedValue, dataType);
try (GMetric metric = new GMetric(host, port, addressingMode, ttl, v31, null, spoofedHostName)) {
metric.announce(name, transformedValue.toString(), dataType, units, slope, tmax, dmax, groupName);
}
}
} | [
"@",
"Override",
"public",
"void",
"internalWrite",
"(",
"Server",
"server",
",",
"Query",
"query",
",",
"ImmutableList",
"<",
"Result",
">",
"results",
")",
"throws",
"Exception",
"{",
"for",
"(",
"final",
"Result",
"result",
":",
"results",
")",
"{",
"final",
"String",
"name",
"=",
"KeyUtils",
".",
"getKeyString",
"(",
"query",
",",
"result",
",",
"getTypeNames",
"(",
")",
")",
";",
"Object",
"transformedValue",
"=",
"valueTransformer",
".",
"apply",
"(",
"result",
".",
"getValue",
"(",
")",
")",
";",
"GMetricType",
"dataType",
"=",
"getType",
"(",
"result",
".",
"getValue",
"(",
")",
")",
";",
"log",
".",
"debug",
"(",
"\"Sending Ganglia metric {}={} [type={}]\"",
",",
"name",
",",
"transformedValue",
",",
"dataType",
")",
";",
"try",
"(",
"GMetric",
"metric",
"=",
"new",
"GMetric",
"(",
"host",
",",
"port",
",",
"addressingMode",
",",
"ttl",
",",
"v31",
",",
"null",
",",
"spoofedHostName",
")",
")",
"{",
"metric",
".",
"announce",
"(",
"name",
",",
"transformedValue",
".",
"toString",
"(",
")",
",",
"dataType",
",",
"units",
",",
"slope",
",",
"tmax",
",",
"dmax",
",",
"groupName",
")",
";",
"}",
"}",
"}"
] | Send query result values to Ganglia. | [
"Send",
"query",
"result",
"values",
"to",
"Ganglia",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-ganglia/src/main/java/com/googlecode/jmxtrans/model/output/GangliaWriter.java#L192-L205 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-ganglia/src/main/java/com/googlecode/jmxtrans/model/output/GangliaWriter.java | GangliaWriter.getType | private static GMetricType getType(final Object obj) {
// FIXME This is far from covering all cases.
// FIXME Wasteful use of high capacity types (eg Short => INT32)
// Direct mapping when possible
if (obj instanceof Long || obj instanceof Integer || obj instanceof Byte || obj instanceof Short)
return GMetricType.INT32;
if (obj instanceof Float)
return GMetricType.FLOAT;
if (obj instanceof Double)
return GMetricType.DOUBLE;
// Convert to double or int if possible
try {
Double.parseDouble(obj.toString());
return GMetricType.DOUBLE;
} catch (NumberFormatException e) {
// Not a double
}
try {
Integer.parseInt(obj.toString());
return GMetricType.UINT32;
} catch (NumberFormatException e) {
// Not an int
}
return GMetricType.STRING;
} | java | private static GMetricType getType(final Object obj) {
// FIXME This is far from covering all cases.
// FIXME Wasteful use of high capacity types (eg Short => INT32)
// Direct mapping when possible
if (obj instanceof Long || obj instanceof Integer || obj instanceof Byte || obj instanceof Short)
return GMetricType.INT32;
if (obj instanceof Float)
return GMetricType.FLOAT;
if (obj instanceof Double)
return GMetricType.DOUBLE;
// Convert to double or int if possible
try {
Double.parseDouble(obj.toString());
return GMetricType.DOUBLE;
} catch (NumberFormatException e) {
// Not a double
}
try {
Integer.parseInt(obj.toString());
return GMetricType.UINT32;
} catch (NumberFormatException e) {
// Not an int
}
return GMetricType.STRING;
} | [
"private",
"static",
"GMetricType",
"getType",
"(",
"final",
"Object",
"obj",
")",
"{",
"// FIXME This is far from covering all cases.",
"// FIXME Wasteful use of high capacity types (eg Short => INT32)",
"// Direct mapping when possible",
"if",
"(",
"obj",
"instanceof",
"Long",
"||",
"obj",
"instanceof",
"Integer",
"||",
"obj",
"instanceof",
"Byte",
"||",
"obj",
"instanceof",
"Short",
")",
"return",
"GMetricType",
".",
"INT32",
";",
"if",
"(",
"obj",
"instanceof",
"Float",
")",
"return",
"GMetricType",
".",
"FLOAT",
";",
"if",
"(",
"obj",
"instanceof",
"Double",
")",
"return",
"GMetricType",
".",
"DOUBLE",
";",
"// Convert to double or int if possible",
"try",
"{",
"Double",
".",
"parseDouble",
"(",
"obj",
".",
"toString",
"(",
")",
")",
";",
"return",
"GMetricType",
".",
"DOUBLE",
";",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"// Not a double",
"}",
"try",
"{",
"Integer",
".",
"parseInt",
"(",
"obj",
".",
"toString",
"(",
")",
")",
";",
"return",
"GMetricType",
".",
"UINT32",
";",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"// Not an int",
"}",
"return",
"GMetricType",
".",
"STRING",
";",
"}"
] | Guess the Ganglia gmetric type to use for a given object.
@param obj the object to inspect
@return an appropriate {@link GMetricType}, {@link GMetricType#STRING} by default | [
"Guess",
"the",
"Ganglia",
"gmetric",
"type",
"to",
"use",
"for",
"a",
"given",
"object",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-ganglia/src/main/java/com/googlecode/jmxtrans/model/output/GangliaWriter.java#L254-L282 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/output/Settings.java | Settings.getBooleanSetting | public static Boolean getBooleanSetting(Map<String, Object> settings, String key, Boolean defaultVal) {
final Object value = settings.get(key);
if (value == null) {
return defaultVal;
}
if (value instanceof Boolean) {
return (Boolean) value;
}
if (value instanceof String) {
return Boolean.valueOf((String) value);
}
return defaultVal;
} | java | public static Boolean getBooleanSetting(Map<String, Object> settings, String key, Boolean defaultVal) {
final Object value = settings.get(key);
if (value == null) {
return defaultVal;
}
if (value instanceof Boolean) {
return (Boolean) value;
}
if (value instanceof String) {
return Boolean.valueOf((String) value);
}
return defaultVal;
} | [
"public",
"static",
"Boolean",
"getBooleanSetting",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"settings",
",",
"String",
"key",
",",
"Boolean",
"defaultVal",
")",
"{",
"final",
"Object",
"value",
"=",
"settings",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"defaultVal",
";",
"}",
"if",
"(",
"value",
"instanceof",
"Boolean",
")",
"{",
"return",
"(",
"Boolean",
")",
"value",
";",
"}",
"if",
"(",
"value",
"instanceof",
"String",
")",
"{",
"return",
"Boolean",
".",
"valueOf",
"(",
"(",
"String",
")",
"value",
")",
";",
"}",
"return",
"defaultVal",
";",
"}"
] | Gets a Boolean value for the key, returning the default value given if
not specified or not a valid boolean value.
@param settings
@param key the key to get the boolean setting for
@param defaultVal the default value to return if the setting was not specified
or was not coercible to a Boolean value
@return the Boolean value for the setting | [
"Gets",
"a",
"Boolean",
"value",
"for",
"the",
"key",
"returning",
"the",
"default",
"value",
"given",
"if",
"not",
"specified",
"or",
"not",
"a",
"valid",
"boolean",
"value",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/output/Settings.java#L62-L75 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/output/Settings.java | Settings.getIntegerSetting | public static Integer getIntegerSetting(Map<String, Object> settings, String key, Integer defaultVal) {
final Object value = settings.get(key);
if (value == null) {
return defaultVal;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value instanceof String) {
try {
return Integer.parseInt((String) value);
} catch (NumberFormatException e) {
return defaultVal;
}
}
return defaultVal;
} | java | public static Integer getIntegerSetting(Map<String, Object> settings, String key, Integer defaultVal) {
final Object value = settings.get(key);
if (value == null) {
return defaultVal;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value instanceof String) {
try {
return Integer.parseInt((String) value);
} catch (NumberFormatException e) {
return defaultVal;
}
}
return defaultVal;
} | [
"public",
"static",
"Integer",
"getIntegerSetting",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"settings",
",",
"String",
"key",
",",
"Integer",
"defaultVal",
")",
"{",
"final",
"Object",
"value",
"=",
"settings",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"defaultVal",
";",
"}",
"if",
"(",
"value",
"instanceof",
"Number",
")",
"{",
"return",
"(",
"(",
"Number",
")",
"value",
")",
".",
"intValue",
"(",
")",
";",
"}",
"if",
"(",
"value",
"instanceof",
"String",
")",
"{",
"try",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"(",
"String",
")",
"value",
")",
";",
"}",
"catch",
"(",
"NumberFormatException",
"e",
")",
"{",
"return",
"defaultVal",
";",
"}",
"}",
"return",
"defaultVal",
";",
"}"
] | Gets an Integer value for the key, returning the default value given if
not specified or not a valid numeric value.
@param settings
@param key the key to get the Integer setting for
@param defaultVal the default value to return if the setting was not specified
or was not coercible to an Integer value
@return the Integer value for the setting | [
"Gets",
"an",
"Integer",
"value",
"for",
"the",
"key",
"returning",
"the",
"default",
"value",
"given",
"if",
"not",
"specified",
"or",
"not",
"a",
"valid",
"numeric",
"value",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/output/Settings.java#L88-L105 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/output/Settings.java | Settings.getStringSetting | public static String getStringSetting(Map<String, Object> settings, String key, String defaultVal) {
final Object value = settings.get(key);
return value != null ? value.toString() : defaultVal;
} | java | public static String getStringSetting(Map<String, Object> settings, String key, String defaultVal) {
final Object value = settings.get(key);
return value != null ? value.toString() : defaultVal;
} | [
"public",
"static",
"String",
"getStringSetting",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"settings",
",",
"String",
"key",
",",
"String",
"defaultVal",
")",
"{",
"final",
"Object",
"value",
"=",
"settings",
".",
"get",
"(",
"key",
")",
";",
"return",
"value",
"!=",
"null",
"?",
"value",
".",
"toString",
"(",
")",
":",
"defaultVal",
";",
"}"
] | Gets a String value for the setting, returning the default value if not
specified.
@param settings
@param key the key to get the String setting for
@param defaultVal the default value to return if the setting was not specified
@return the String value for the setting | [
"Gets",
"a",
"String",
"value",
"for",
"the",
"setting",
"returning",
"the",
"default",
"value",
"if",
"not",
"specified",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/output/Settings.java#L117-L120 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/output/Settings.java | Settings.getIntSetting | protected static int getIntSetting(Map<String, Object> settings, String key, int defaultVal) throws IllegalArgumentException {
if (settings.containsKey(key)) {
final Object objectValue = settings.get(key);
if (objectValue == null) {
throw new IllegalArgumentException("Setting '" + key + " null");
}
final String value = objectValue.toString();
try {
return Integer.parseInt(value);
} catch (Exception e) {
throw new IllegalArgumentException("Setting '" + key + "=" + value + "' is not an integer", e);
}
} else {
return defaultVal;
}
} | java | protected static int getIntSetting(Map<String, Object> settings, String key, int defaultVal) throws IllegalArgumentException {
if (settings.containsKey(key)) {
final Object objectValue = settings.get(key);
if (objectValue == null) {
throw new IllegalArgumentException("Setting '" + key + " null");
}
final String value = objectValue.toString();
try {
return Integer.parseInt(value);
} catch (Exception e) {
throw new IllegalArgumentException("Setting '" + key + "=" + value + "' is not an integer", e);
}
} else {
return defaultVal;
}
} | [
"protected",
"static",
"int",
"getIntSetting",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"settings",
",",
"String",
"key",
",",
"int",
"defaultVal",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"settings",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"final",
"Object",
"objectValue",
"=",
"settings",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"objectValue",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Setting '\"",
"+",
"key",
"+",
"\" null\"",
")",
";",
"}",
"final",
"String",
"value",
"=",
"objectValue",
".",
"toString",
"(",
")",
";",
"try",
"{",
"return",
"Integer",
".",
"parseInt",
"(",
"value",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Setting '\"",
"+",
"key",
"+",
"\"=\"",
"+",
"value",
"+",
"\"' is not an integer\"",
",",
"e",
")",
";",
"}",
"}",
"else",
"{",
"return",
"defaultVal",
";",
"}",
"}"
] | Gets an int value for the setting, returning the default value if not
specified.
@param settings
@param key the key to get the int value for
@param defaultVal default value if the setting was not specified
@return the int value for the setting
@throws IllegalArgumentException if setting does not contain an int | [
"Gets",
"an",
"int",
"value",
"for",
"the",
"setting",
"returning",
"the",
"default",
"value",
"if",
"not",
"specified",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/output/Settings.java#L133-L148 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-velocity/src/main/java/com/googlecode/jmxtrans/model/output/VelocityWriter.java | VelocityWriter.getVelocityEngine | protected VelocityEngine getVelocityEngine(List<String> paths) {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
ve.setProperty("cp.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
ve.setProperty("cp.resource.loader.cache", "true");
ve.setProperty("cp.resource.loader.path", StringUtils.join(paths, ","));
ve.setProperty("cp.resource.loader.modificationCheckInterval ", "10");
ve.setProperty("input.encoding", "UTF-8");
ve.setProperty("output.encoding", "UTF-8");
ve.setProperty("runtime.log", "");
return ve;
} | java | protected VelocityEngine getVelocityEngine(List<String> paths) {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
ve.setProperty("cp.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
ve.setProperty("cp.resource.loader.cache", "true");
ve.setProperty("cp.resource.loader.path", StringUtils.join(paths, ","));
ve.setProperty("cp.resource.loader.modificationCheckInterval ", "10");
ve.setProperty("input.encoding", "UTF-8");
ve.setProperty("output.encoding", "UTF-8");
ve.setProperty("runtime.log", "");
return ve;
} | [
"protected",
"VelocityEngine",
"getVelocityEngine",
"(",
"List",
"<",
"String",
">",
"paths",
")",
"{",
"VelocityEngine",
"ve",
"=",
"new",
"VelocityEngine",
"(",
")",
";",
"ve",
".",
"setProperty",
"(",
"RuntimeConstants",
".",
"RESOURCE_LOADER",
",",
"\"file\"",
")",
";",
"ve",
".",
"setProperty",
"(",
"\"cp.resource.loader.class\"",
",",
"\"org.apache.velocity.runtime.resource.loader.FileResourceLoader\"",
")",
";",
"ve",
".",
"setProperty",
"(",
"\"cp.resource.loader.cache\"",
",",
"\"true\"",
")",
";",
"ve",
".",
"setProperty",
"(",
"\"cp.resource.loader.path\"",
",",
"StringUtils",
".",
"join",
"(",
"paths",
",",
"\",\"",
")",
")",
";",
"ve",
".",
"setProperty",
"(",
"\"cp.resource.loader.modificationCheckInterval \"",
",",
"\"10\"",
")",
";",
"ve",
".",
"setProperty",
"(",
"\"input.encoding\"",
",",
"\"UTF-8\"",
")",
";",
"ve",
".",
"setProperty",
"(",
"\"output.encoding\"",
",",
"\"UTF-8\"",
")",
";",
"ve",
".",
"setProperty",
"(",
"\"runtime.log\"",
",",
"\"\"",
")",
";",
"return",
"ve",
";",
"}"
] | Sets velocity up to load resources from a list of paths. | [
"Sets",
"velocity",
"up",
"to",
"load",
"resources",
"from",
"a",
"list",
"of",
"paths",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-velocity/src/main/java/com/googlecode/jmxtrans/model/output/VelocityWriter.java#L89-L100 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/util/ProcessConfigUtils.java | ProcessConfigUtils.parseProcess | public JmxProcess parseProcess(File file) throws IOException {
String fileName = file.getName();
ObjectMapper mapper = fileName.endsWith(".yml") || fileName.endsWith(".yaml") ? yamlMapper : jsonMapper;
JsonNode jsonNode = mapper.readTree(file);
JmxProcess jmx = mapper.treeToValue(jsonNode, JmxProcess.class);
jmx.setName(fileName);
return jmx;
} | java | public JmxProcess parseProcess(File file) throws IOException {
String fileName = file.getName();
ObjectMapper mapper = fileName.endsWith(".yml") || fileName.endsWith(".yaml") ? yamlMapper : jsonMapper;
JsonNode jsonNode = mapper.readTree(file);
JmxProcess jmx = mapper.treeToValue(jsonNode, JmxProcess.class);
jmx.setName(fileName);
return jmx;
} | [
"public",
"JmxProcess",
"parseProcess",
"(",
"File",
"file",
")",
"throws",
"IOException",
"{",
"String",
"fileName",
"=",
"file",
".",
"getName",
"(",
")",
";",
"ObjectMapper",
"mapper",
"=",
"fileName",
".",
"endsWith",
"(",
"\".yml\"",
")",
"||",
"fileName",
".",
"endsWith",
"(",
"\".yaml\"",
")",
"?",
"yamlMapper",
":",
"jsonMapper",
";",
"JsonNode",
"jsonNode",
"=",
"mapper",
".",
"readTree",
"(",
"file",
")",
";",
"JmxProcess",
"jmx",
"=",
"mapper",
".",
"treeToValue",
"(",
"jsonNode",
",",
"JmxProcess",
".",
"class",
")",
";",
"jmx",
".",
"setName",
"(",
"fileName",
")",
";",
"return",
"jmx",
";",
"}"
] | Uses jackson to load json configuration from a File into a full object
tree representation of that json. | [
"Uses",
"jackson",
"to",
"load",
"json",
"configuration",
"from",
"a",
"File",
"into",
"a",
"full",
"object",
"tree",
"representation",
"of",
"that",
"json",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/util/ProcessConfigUtils.java#L59-L66 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java | OpenTSDBMessageFormatter.addTags | void addTags(StringBuilder resultString, Server server) {
if (hostnameTag) {
addTag(resultString, "host", server.getLabel());
}
// Add the constant tag names and values.
for (Map.Entry<String, String> tagEntry : tags.entrySet()) {
addTag(resultString, tagEntry.getKey(), tagEntry.getValue());
}
} | java | void addTags(StringBuilder resultString, Server server) {
if (hostnameTag) {
addTag(resultString, "host", server.getLabel());
}
// Add the constant tag names and values.
for (Map.Entry<String, String> tagEntry : tags.entrySet()) {
addTag(resultString, tagEntry.getKey(), tagEntry.getValue());
}
} | [
"void",
"addTags",
"(",
"StringBuilder",
"resultString",
",",
"Server",
"server",
")",
"{",
"if",
"(",
"hostnameTag",
")",
"{",
"addTag",
"(",
"resultString",
",",
"\"host\"",
",",
"server",
".",
"getLabel",
"(",
")",
")",
";",
"}",
"// Add the constant tag names and values.",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"tagEntry",
":",
"tags",
".",
"entrySet",
"(",
")",
")",
"{",
"addTag",
"(",
"resultString",
",",
"tagEntry",
".",
"getKey",
"(",
")",
",",
"tagEntry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}"
] | Add tags to the given result string, including a "host" tag with the name of the server and all of the tags
defined in the "settings" entry in the configuration file within the "tag" element.
@param resultString - the string containing the metric name, timestamp, value, and possibly other content. | [
"Add",
"tags",
"to",
"the",
"given",
"result",
"string",
"including",
"a",
"host",
"tag",
"with",
"the",
"name",
"of",
"the",
"server",
"and",
"all",
"of",
"the",
"tags",
"defined",
"in",
"the",
"settings",
"entry",
"in",
"the",
"configuration",
"file",
"within",
"the",
"tag",
"element",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java#L102-L111 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java | OpenTSDBMessageFormatter.addTag | void addTag(StringBuilder resultString, String tagName, String tagValue) {
resultString.append(" ");
resultString.append(sanitizeString(tagName));
resultString.append("=");
resultString.append(sanitizeString(tagValue));
} | java | void addTag(StringBuilder resultString, String tagName, String tagValue) {
resultString.append(" ");
resultString.append(sanitizeString(tagName));
resultString.append("=");
resultString.append(sanitizeString(tagValue));
} | [
"void",
"addTag",
"(",
"StringBuilder",
"resultString",
",",
"String",
"tagName",
",",
"String",
"tagValue",
")",
"{",
"resultString",
".",
"append",
"(",
"\" \"",
")",
";",
"resultString",
".",
"append",
"(",
"sanitizeString",
"(",
"tagName",
")",
")",
";",
"resultString",
".",
"append",
"(",
"\"=\"",
")",
";",
"resultString",
".",
"append",
"(",
"sanitizeString",
"(",
"tagValue",
")",
")",
";",
"}"
] | Add one tag, with the provided name and value, to the given result string.
@param resultString - the string containing the metric name, timestamp, value, and possibly other content.
@return String - the new result string with the tag appended. | [
"Add",
"one",
"tag",
"with",
"the",
"provided",
"name",
"and",
"value",
"to",
"the",
"given",
"result",
"string",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java#L119-L124 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java | OpenTSDBMessageFormatter.formatResultString | private void formatResultString(StringBuilder resultString, String metricName, long epoch, Object value) {
resultString.append(sanitizeString(metricName));
resultString.append(" ");
resultString.append(Long.toString(epoch));
resultString.append(" ");
resultString.append(sanitizeString(value.toString()));
} | java | private void formatResultString(StringBuilder resultString, String metricName, long epoch, Object value) {
resultString.append(sanitizeString(metricName));
resultString.append(" ");
resultString.append(Long.toString(epoch));
resultString.append(" ");
resultString.append(sanitizeString(value.toString()));
} | [
"private",
"void",
"formatResultString",
"(",
"StringBuilder",
"resultString",
",",
"String",
"metricName",
",",
"long",
"epoch",
",",
"Object",
"value",
")",
"{",
"resultString",
".",
"append",
"(",
"sanitizeString",
"(",
"metricName",
")",
")",
";",
"resultString",
".",
"append",
"(",
"\" \"",
")",
";",
"resultString",
".",
"append",
"(",
"Long",
".",
"toString",
"(",
"epoch",
")",
")",
";",
"resultString",
".",
"append",
"(",
"\" \"",
")",
";",
"resultString",
".",
"append",
"(",
"sanitizeString",
"(",
"value",
".",
"toString",
"(",
")",
")",
")",
";",
"}"
] | Format the result string given the class name and attribute name of the source value, the timestamp, and the
value.
@param epoch - the timestamp of the metric.
@param value - value of the attribute to use as the metric value.
@return String - the formatted result string. | [
"Format",
"the",
"result",
"string",
"given",
"the",
"class",
"name",
"and",
"attribute",
"name",
"of",
"the",
"source",
"value",
"the",
"timestamp",
"and",
"the",
"value",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java#L134-L140 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java | OpenTSDBMessageFormatter.processOneMetric | protected void processOneMetric(List<String> resultStrings, Server server, Result result, Object value, String addTagName,
String addTagValue) {
String metricName = this.metricNameStrategy.formatName(result);
//
// Skip any non-numeric values since OpenTSDB only supports numeric metrics.
//
if (isNumeric(value)) {
StringBuilder resultString = new StringBuilder();
formatResultString(resultString, metricName, result.getEpoch() / 1000L, value);
addTags(resultString, server);
if (addTagName != null) {
addTag(resultString, addTagName, addTagValue);
}
if (!typeNames.isEmpty()) {
this.addTypeNamesTags(resultString, result);
}
resultStrings.add(resultString.toString());
} else {
log.debug("Skipping non-numeric value for metric {}; value={}", metricName, value);
}
} | java | protected void processOneMetric(List<String> resultStrings, Server server, Result result, Object value, String addTagName,
String addTagValue) {
String metricName = this.metricNameStrategy.formatName(result);
//
// Skip any non-numeric values since OpenTSDB only supports numeric metrics.
//
if (isNumeric(value)) {
StringBuilder resultString = new StringBuilder();
formatResultString(resultString, metricName, result.getEpoch() / 1000L, value);
addTags(resultString, server);
if (addTagName != null) {
addTag(resultString, addTagName, addTagValue);
}
if (!typeNames.isEmpty()) {
this.addTypeNamesTags(resultString, result);
}
resultStrings.add(resultString.toString());
} else {
log.debug("Skipping non-numeric value for metric {}; value={}", metricName, value);
}
} | [
"protected",
"void",
"processOneMetric",
"(",
"List",
"<",
"String",
">",
"resultStrings",
",",
"Server",
"server",
",",
"Result",
"result",
",",
"Object",
"value",
",",
"String",
"addTagName",
",",
"String",
"addTagValue",
")",
"{",
"String",
"metricName",
"=",
"this",
".",
"metricNameStrategy",
".",
"formatName",
"(",
"result",
")",
";",
"//",
"// Skip any non-numeric values since OpenTSDB only supports numeric metrics.",
"//",
"if",
"(",
"isNumeric",
"(",
"value",
")",
")",
"{",
"StringBuilder",
"resultString",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"formatResultString",
"(",
"resultString",
",",
"metricName",
",",
"result",
".",
"getEpoch",
"(",
")",
"/",
"1000L",
",",
"value",
")",
";",
"addTags",
"(",
"resultString",
",",
"server",
")",
";",
"if",
"(",
"addTagName",
"!=",
"null",
")",
"{",
"addTag",
"(",
"resultString",
",",
"addTagName",
",",
"addTagValue",
")",
";",
"}",
"if",
"(",
"!",
"typeNames",
".",
"isEmpty",
"(",
")",
")",
"{",
"this",
".",
"addTypeNamesTags",
"(",
"resultString",
",",
"result",
")",
";",
"}",
"resultStrings",
".",
"add",
"(",
"resultString",
".",
"toString",
"(",
")",
")",
";",
"}",
"else",
"{",
"log",
".",
"debug",
"(",
"\"Skipping non-numeric value for metric {}; value={}\"",
",",
"metricName",
",",
"value",
")",
";",
"}",
"}"
] | Process a single metric from the given JMX query result with the specified value. | [
"Process",
"a",
"single",
"metric",
"from",
"the",
"given",
"JMX",
"query",
"result",
"with",
"the",
"specified",
"value",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/support/opentsdb/OpenTSDBMessageFormatter.java#L180-L205 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/StackdriverWriter.java | StackdriverWriter.getGatewayMessage | private String getGatewayMessage(final List<Result> results) throws IOException {
int valueCount = 0;
Writer writer = new StringWriter();
JsonGenerator g = jsonFactory.createGenerator(writer);
g.writeStartObject();
g.writeNumberField("timestamp", System.currentTimeMillis() / 1000);
g.writeNumberField("proto_version", STACKDRIVER_PROTOCOL_VERSION);
g.writeArrayFieldStart("data");
List<String> typeNames = this.getTypeNames();
for (Result metric : results) {
if (isNumeric(metric.getValue())) {
// we have a numeric value, write a value into the message
StringBuilder nameBuilder = new StringBuilder();
// put the prefix if set
if (this.prefix != null) {
nameBuilder.append(prefix);
nameBuilder.append(".");
}
// put the class name or its alias if available
if (!metric.getKeyAlias().isEmpty()) {
nameBuilder.append(metric.getKeyAlias());
} else {
nameBuilder.append(metric.getClassName());
}
// Wildcard "typeNames" substitution
String typeName = com.googlecode.jmxtrans.model.naming.StringUtils.cleanupStr(
TypeNameValuesStringBuilder.getDefaultBuilder().build(typeNames, metric.getTypeName()));
if (typeName != null && typeName.length() > 0) {
nameBuilder.append(".");
nameBuilder.append(typeName);
}
// add the attribute name
nameBuilder.append(".");
nameBuilder.append(KeyUtils.getValueKey(metric));
// check for Float/Double NaN since these will cause the message validation to fail
if (metric.getValue() instanceof Float && ((Float) metric.getValue()).isNaN()) {
logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping");
continue;
}
if (metric.getValue() instanceof Double && ((Double) metric.getValue()).isNaN()) {
logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping");
continue;
}
valueCount++;
g.writeStartObject();
g.writeStringField("name", nameBuilder.toString());
g.writeNumberField("value", Double.valueOf(metric.getValue().toString()));
// if the metric is attached to an instance, include that in the message
if (instanceId != null && !instanceId.isEmpty()) {
g.writeStringField("instance", instanceId);
}
g.writeNumberField("collected_at", metric.getEpoch() / 1000);
g.writeEndObject();
}
}
g.writeEndArray();
g.writeEndObject();
g.flush();
g.close();
// return the message if there are any values to report
if (valueCount > 0) {
return writer.toString();
} else {
return null;
}
} | java | private String getGatewayMessage(final List<Result> results) throws IOException {
int valueCount = 0;
Writer writer = new StringWriter();
JsonGenerator g = jsonFactory.createGenerator(writer);
g.writeStartObject();
g.writeNumberField("timestamp", System.currentTimeMillis() / 1000);
g.writeNumberField("proto_version", STACKDRIVER_PROTOCOL_VERSION);
g.writeArrayFieldStart("data");
List<String> typeNames = this.getTypeNames();
for (Result metric : results) {
if (isNumeric(metric.getValue())) {
// we have a numeric value, write a value into the message
StringBuilder nameBuilder = new StringBuilder();
// put the prefix if set
if (this.prefix != null) {
nameBuilder.append(prefix);
nameBuilder.append(".");
}
// put the class name or its alias if available
if (!metric.getKeyAlias().isEmpty()) {
nameBuilder.append(metric.getKeyAlias());
} else {
nameBuilder.append(metric.getClassName());
}
// Wildcard "typeNames" substitution
String typeName = com.googlecode.jmxtrans.model.naming.StringUtils.cleanupStr(
TypeNameValuesStringBuilder.getDefaultBuilder().build(typeNames, metric.getTypeName()));
if (typeName != null && typeName.length() > 0) {
nameBuilder.append(".");
nameBuilder.append(typeName);
}
// add the attribute name
nameBuilder.append(".");
nameBuilder.append(KeyUtils.getValueKey(metric));
// check for Float/Double NaN since these will cause the message validation to fail
if (metric.getValue() instanceof Float && ((Float) metric.getValue()).isNaN()) {
logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping");
continue;
}
if (metric.getValue() instanceof Double && ((Double) metric.getValue()).isNaN()) {
logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping");
continue;
}
valueCount++;
g.writeStartObject();
g.writeStringField("name", nameBuilder.toString());
g.writeNumberField("value", Double.valueOf(metric.getValue().toString()));
// if the metric is attached to an instance, include that in the message
if (instanceId != null && !instanceId.isEmpty()) {
g.writeStringField("instance", instanceId);
}
g.writeNumberField("collected_at", metric.getEpoch() / 1000);
g.writeEndObject();
}
}
g.writeEndArray();
g.writeEndObject();
g.flush();
g.close();
// return the message if there are any values to report
if (valueCount > 0) {
return writer.toString();
} else {
return null;
}
} | [
"private",
"String",
"getGatewayMessage",
"(",
"final",
"List",
"<",
"Result",
">",
"results",
")",
"throws",
"IOException",
"{",
"int",
"valueCount",
"=",
"0",
";",
"Writer",
"writer",
"=",
"new",
"StringWriter",
"(",
")",
";",
"JsonGenerator",
"g",
"=",
"jsonFactory",
".",
"createGenerator",
"(",
"writer",
")",
";",
"g",
".",
"writeStartObject",
"(",
")",
";",
"g",
".",
"writeNumberField",
"(",
"\"timestamp\"",
",",
"System",
".",
"currentTimeMillis",
"(",
")",
"/",
"1000",
")",
";",
"g",
".",
"writeNumberField",
"(",
"\"proto_version\"",
",",
"STACKDRIVER_PROTOCOL_VERSION",
")",
";",
"g",
".",
"writeArrayFieldStart",
"(",
"\"data\"",
")",
";",
"List",
"<",
"String",
">",
"typeNames",
"=",
"this",
".",
"getTypeNames",
"(",
")",
";",
"for",
"(",
"Result",
"metric",
":",
"results",
")",
"{",
"if",
"(",
"isNumeric",
"(",
"metric",
".",
"getValue",
"(",
")",
")",
")",
"{",
"// we have a numeric value, write a value into the message",
"StringBuilder",
"nameBuilder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"// put the prefix if set",
"if",
"(",
"this",
".",
"prefix",
"!=",
"null",
")",
"{",
"nameBuilder",
".",
"append",
"(",
"prefix",
")",
";",
"nameBuilder",
".",
"append",
"(",
"\".\"",
")",
";",
"}",
"// put the class name or its alias if available",
"if",
"(",
"!",
"metric",
".",
"getKeyAlias",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"nameBuilder",
".",
"append",
"(",
"metric",
".",
"getKeyAlias",
"(",
")",
")",
";",
"}",
"else",
"{",
"nameBuilder",
".",
"append",
"(",
"metric",
".",
"getClassName",
"(",
")",
")",
";",
"}",
"// Wildcard \"typeNames\" substitution",
"String",
"typeName",
"=",
"com",
".",
"googlecode",
".",
"jmxtrans",
".",
"model",
".",
"naming",
".",
"StringUtils",
".",
"cleanupStr",
"(",
"TypeNameValuesStringBuilder",
".",
"getDefaultBuilder",
"(",
")",
".",
"build",
"(",
"typeNames",
",",
"metric",
".",
"getTypeName",
"(",
")",
")",
")",
";",
"if",
"(",
"typeName",
"!=",
"null",
"&&",
"typeName",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"nameBuilder",
".",
"append",
"(",
"\".\"",
")",
";",
"nameBuilder",
".",
"append",
"(",
"typeName",
")",
";",
"}",
"// add the attribute name",
"nameBuilder",
".",
"append",
"(",
"\".\"",
")",
";",
"nameBuilder",
".",
"append",
"(",
"KeyUtils",
".",
"getValueKey",
"(",
"metric",
")",
")",
";",
"// check for Float/Double NaN since these will cause the message validation to fail",
"if",
"(",
"metric",
".",
"getValue",
"(",
")",
"instanceof",
"Float",
"&&",
"(",
"(",
"Float",
")",
"metric",
".",
"getValue",
"(",
")",
")",
".",
"isNaN",
"(",
")",
")",
"{",
"logger",
".",
"info",
"(",
"\"Metric value for \"",
"+",
"nameBuilder",
".",
"toString",
"(",
")",
"+",
"\" is NaN, skipping\"",
")",
";",
"continue",
";",
"}",
"if",
"(",
"metric",
".",
"getValue",
"(",
")",
"instanceof",
"Double",
"&&",
"(",
"(",
"Double",
")",
"metric",
".",
"getValue",
"(",
")",
")",
".",
"isNaN",
"(",
")",
")",
"{",
"logger",
".",
"info",
"(",
"\"Metric value for \"",
"+",
"nameBuilder",
".",
"toString",
"(",
")",
"+",
"\" is NaN, skipping\"",
")",
";",
"continue",
";",
"}",
"valueCount",
"++",
";",
"g",
".",
"writeStartObject",
"(",
")",
";",
"g",
".",
"writeStringField",
"(",
"\"name\"",
",",
"nameBuilder",
".",
"toString",
"(",
")",
")",
";",
"g",
".",
"writeNumberField",
"(",
"\"value\"",
",",
"Double",
".",
"valueOf",
"(",
"metric",
".",
"getValue",
"(",
")",
".",
"toString",
"(",
")",
")",
")",
";",
"// if the metric is attached to an instance, include that in the message",
"if",
"(",
"instanceId",
"!=",
"null",
"&&",
"!",
"instanceId",
".",
"isEmpty",
"(",
")",
")",
"{",
"g",
".",
"writeStringField",
"(",
"\"instance\"",
",",
"instanceId",
")",
";",
"}",
"g",
".",
"writeNumberField",
"(",
"\"collected_at\"",
",",
"metric",
".",
"getEpoch",
"(",
")",
"/",
"1000",
")",
";",
"g",
".",
"writeEndObject",
"(",
")",
";",
"}",
"}",
"g",
".",
"writeEndArray",
"(",
")",
";",
"g",
".",
"writeEndObject",
"(",
")",
";",
"g",
".",
"flush",
"(",
")",
";",
"g",
".",
"close",
"(",
")",
";",
"// return the message if there are any values to report",
"if",
"(",
"valueCount",
">",
"0",
")",
"{",
"return",
"writer",
".",
"toString",
"(",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}"
] | Take query results, make a JSON String
@param results List of Result objects
@return a String containing a JSON message, or null if there are no values to report
@throws IOException if there is some problem generating the JSON, should be uncommon | [
"Take",
"query",
"results",
"make",
"a",
"JSON",
"String"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/StackdriverWriter.java#L279-L360 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/StackdriverWriter.java | StackdriverWriter.doSend | private void doSend(final String gatewayMessage) {
HttpURLConnection urlConnection = null;
try {
if (proxy == null) {
urlConnection = (HttpURLConnection) gatewayUrl.openConnection();
} else {
urlConnection = (HttpURLConnection) gatewayUrl.openConnection(proxy);
}
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setReadTimeout(timeoutInMillis);
urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey);
// Stackdriver's own implementation does not specify char encoding
// to use. Let's take the simplest approach and at lest ensure that
// if we have problems they can be reproduced in consistant ways.
// See https://github.com/Stackdriver/stackdriver-custommetrics-java/blob/master/src/main/java/com/stackdriver/api/custommetrics/CustomMetricsPoster.java#L262
// for details.
urlConnection.getOutputStream().write(gatewayMessage.getBytes(ISO_8859_1));
int responseCode = urlConnection.getResponseCode();
if (responseCode != 200 && responseCode != 201) {
logger.warn("Failed to send results to Stackdriver server: responseCode=" + responseCode + " message=" + urlConnection.getResponseMessage());
}
} catch (Exception e) {
logger.warn("Failure to send result to Stackdriver server", e);
} finally {
if (urlConnection != null) {
try {
InputStream in = urlConnection.getInputStream();
in.close();
InputStream err = urlConnection.getErrorStream();
if (err != null) {
err.close();
}
urlConnection.disconnect();
} catch (IOException e) {
logger.warn("Error flushing http connection for one result, continuing");
logger.debug("Stack trace for the http connection, usually a network timeout", e);
}
}
}
} | java | private void doSend(final String gatewayMessage) {
HttpURLConnection urlConnection = null;
try {
if (proxy == null) {
urlConnection = (HttpURLConnection) gatewayUrl.openConnection();
} else {
urlConnection = (HttpURLConnection) gatewayUrl.openConnection(proxy);
}
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setReadTimeout(timeoutInMillis);
urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey);
// Stackdriver's own implementation does not specify char encoding
// to use. Let's take the simplest approach and at lest ensure that
// if we have problems they can be reproduced in consistant ways.
// See https://github.com/Stackdriver/stackdriver-custommetrics-java/blob/master/src/main/java/com/stackdriver/api/custommetrics/CustomMetricsPoster.java#L262
// for details.
urlConnection.getOutputStream().write(gatewayMessage.getBytes(ISO_8859_1));
int responseCode = urlConnection.getResponseCode();
if (responseCode != 200 && responseCode != 201) {
logger.warn("Failed to send results to Stackdriver server: responseCode=" + responseCode + " message=" + urlConnection.getResponseMessage());
}
} catch (Exception e) {
logger.warn("Failure to send result to Stackdriver server", e);
} finally {
if (urlConnection != null) {
try {
InputStream in = urlConnection.getInputStream();
in.close();
InputStream err = urlConnection.getErrorStream();
if (err != null) {
err.close();
}
urlConnection.disconnect();
} catch (IOException e) {
logger.warn("Error flushing http connection for one result, continuing");
logger.debug("Stack trace for the http connection, usually a network timeout", e);
}
}
}
} | [
"private",
"void",
"doSend",
"(",
"final",
"String",
"gatewayMessage",
")",
"{",
"HttpURLConnection",
"urlConnection",
"=",
"null",
";",
"try",
"{",
"if",
"(",
"proxy",
"==",
"null",
")",
"{",
"urlConnection",
"=",
"(",
"HttpURLConnection",
")",
"gatewayUrl",
".",
"openConnection",
"(",
")",
";",
"}",
"else",
"{",
"urlConnection",
"=",
"(",
"HttpURLConnection",
")",
"gatewayUrl",
".",
"openConnection",
"(",
"proxy",
")",
";",
"}",
"urlConnection",
".",
"setRequestMethod",
"(",
"\"POST\"",
")",
";",
"urlConnection",
".",
"setDoInput",
"(",
"true",
")",
";",
"urlConnection",
".",
"setDoOutput",
"(",
"true",
")",
";",
"urlConnection",
".",
"setReadTimeout",
"(",
"timeoutInMillis",
")",
";",
"urlConnection",
".",
"setRequestProperty",
"(",
"\"content-type\"",
",",
"\"application/json; charset=utf-8\"",
")",
";",
"urlConnection",
".",
"setRequestProperty",
"(",
"\"x-stackdriver-apikey\"",
",",
"apiKey",
")",
";",
"// Stackdriver's own implementation does not specify char encoding",
"// to use. Let's take the simplest approach and at lest ensure that",
"// if we have problems they can be reproduced in consistant ways.",
"// See https://github.com/Stackdriver/stackdriver-custommetrics-java/blob/master/src/main/java/com/stackdriver/api/custommetrics/CustomMetricsPoster.java#L262",
"// for details.",
"urlConnection",
".",
"getOutputStream",
"(",
")",
".",
"write",
"(",
"gatewayMessage",
".",
"getBytes",
"(",
"ISO_8859_1",
")",
")",
";",
"int",
"responseCode",
"=",
"urlConnection",
".",
"getResponseCode",
"(",
")",
";",
"if",
"(",
"responseCode",
"!=",
"200",
"&&",
"responseCode",
"!=",
"201",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Failed to send results to Stackdriver server: responseCode=\"",
"+",
"responseCode",
"+",
"\" message=\"",
"+",
"urlConnection",
".",
"getResponseMessage",
"(",
")",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Failure to send result to Stackdriver server\"",
",",
"e",
")",
";",
"}",
"finally",
"{",
"if",
"(",
"urlConnection",
"!=",
"null",
")",
"{",
"try",
"{",
"InputStream",
"in",
"=",
"urlConnection",
".",
"getInputStream",
"(",
")",
";",
"in",
".",
"close",
"(",
")",
";",
"InputStream",
"err",
"=",
"urlConnection",
".",
"getErrorStream",
"(",
")",
";",
"if",
"(",
"err",
"!=",
"null",
")",
"{",
"err",
".",
"close",
"(",
")",
";",
"}",
"urlConnection",
".",
"disconnect",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"logger",
".",
"warn",
"(",
"\"Error flushing http connection for one result, continuing\"",
")",
";",
"logger",
".",
"debug",
"(",
"\"Stack trace for the http connection, usually a network timeout\"",
",",
"e",
")",
";",
"}",
"}",
"}",
"}"
] | Post the formatted results to the gateway URL over HTTP
@param gatewayMessage String in the Stackdriver custom metrics JSON format containing the data points | [
"Post",
"the",
"formatted",
"results",
"to",
"the",
"gateway",
"URL",
"over",
"HTTP"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-core/src/main/java/com/googlecode/jmxtrans/model/output/StackdriverWriter.java#L367-L413 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java | JmxTransformer.doMain | private void doMain() throws Exception {
// Start the process
this.start();
while (true) {
// look for some terminator
// attempt to read off queue
// process message
// TODO : Make something here, maybe watch for files?
try {
Thread.sleep(5);
} catch (Exception e) {
log.info("shutting down", e);
break;
}
}
this.unregisterMBeans();
} | java | private void doMain() throws Exception {
// Start the process
this.start();
while (true) {
// look for some terminator
// attempt to read off queue
// process message
// TODO : Make something here, maybe watch for files?
try {
Thread.sleep(5);
} catch (Exception e) {
log.info("shutting down", e);
break;
}
}
this.unregisterMBeans();
} | [
"private",
"void",
"doMain",
"(",
")",
"throws",
"Exception",
"{",
"// Start the process",
"this",
".",
"start",
"(",
")",
";",
"while",
"(",
"true",
")",
"{",
"// look for some terminator",
"// attempt to read off queue",
"// process message",
"// TODO : Make something here, maybe watch for files?",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"5",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"log",
".",
"info",
"(",
"\"shutting down\"",
",",
"e",
")",
";",
"break",
";",
"}",
"}",
"this",
".",
"unregisterMBeans",
"(",
")",
";",
"}"
] | The real main method. | [
"The",
"real",
"main",
"method",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java#L156-L174 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java | JmxTransformer.stopWriterAndClearMasterServerList | private void stopWriterAndClearMasterServerList() {
for (Server server : this.masterServersList) {
for (OutputWriter writer : server.getOutputWriters()) {
try {
writer.close();
} catch (LifecycleException ex) {
log.error("Eror stopping writer: {}", writer);
}
}
for (Query query : server.getQueries()) {
for (OutputWriter writer : query.getOutputWriterInstances()) {
try {
writer.close();
log.debug("Stopped writer: {} for query: {}", writer, query);
} catch (LifecycleException ex) {
log.error("Error stopping writer: {} for query: {}", writer, query, ex);
}
}
}
}
this.masterServersList = ImmutableList.of();
} | java | private void stopWriterAndClearMasterServerList() {
for (Server server : this.masterServersList) {
for (OutputWriter writer : server.getOutputWriters()) {
try {
writer.close();
} catch (LifecycleException ex) {
log.error("Eror stopping writer: {}", writer);
}
}
for (Query query : server.getQueries()) {
for (OutputWriter writer : query.getOutputWriterInstances()) {
try {
writer.close();
log.debug("Stopped writer: {} for query: {}", writer, query);
} catch (LifecycleException ex) {
log.error("Error stopping writer: {} for query: {}", writer, query, ex);
}
}
}
}
this.masterServersList = ImmutableList.of();
} | [
"private",
"void",
"stopWriterAndClearMasterServerList",
"(",
")",
"{",
"for",
"(",
"Server",
"server",
":",
"this",
".",
"masterServersList",
")",
"{",
"for",
"(",
"OutputWriter",
"writer",
":",
"server",
".",
"getOutputWriters",
"(",
")",
")",
"{",
"try",
"{",
"writer",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"LifecycleException",
"ex",
")",
"{",
"log",
".",
"error",
"(",
"\"Eror stopping writer: {}\"",
",",
"writer",
")",
";",
"}",
"}",
"for",
"(",
"Query",
"query",
":",
"server",
".",
"getQueries",
"(",
")",
")",
"{",
"for",
"(",
"OutputWriter",
"writer",
":",
"query",
".",
"getOutputWriterInstances",
"(",
")",
")",
"{",
"try",
"{",
"writer",
".",
"close",
"(",
")",
";",
"log",
".",
"debug",
"(",
"\"Stopped writer: {} for query: {}\"",
",",
"writer",
",",
"query",
")",
";",
"}",
"catch",
"(",
"LifecycleException",
"ex",
")",
"{",
"log",
".",
"error",
"(",
"\"Error stopping writer: {} for query: {}\"",
",",
"writer",
",",
"query",
",",
"ex",
")",
";",
"}",
"}",
"}",
"}",
"this",
".",
"masterServersList",
"=",
"ImmutableList",
".",
"of",
"(",
")",
";",
"}"
] | Shut down the output writers and clear the master server list
Used both during shutdown and when re-reading config files | [
"Shut",
"down",
"the",
"output",
"writers",
"and",
"clear",
"the",
"master",
"server",
"list",
"Used",
"both",
"during",
"shutdown",
"and",
"when",
"re",
"-",
"reading",
"config",
"files"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java#L252-L273 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java | JmxTransformer.startupWatchdir | private void startupWatchdir() throws Exception {
File dirToWatch;
if (this.configuration.getProcessConfigDirOrFile().isFile()) {
dirToWatch = new File(FilenameUtils.getFullPath(this.configuration.getProcessConfigDirOrFile().getAbsolutePath()));
} else {
dirToWatch = this.configuration.getProcessConfigDirOrFile();
}
// start the watcher
this.watcher = new WatchDir(dirToWatch, this);
this.watcher.start();
} | java | private void startupWatchdir() throws Exception {
File dirToWatch;
if (this.configuration.getProcessConfigDirOrFile().isFile()) {
dirToWatch = new File(FilenameUtils.getFullPath(this.configuration.getProcessConfigDirOrFile().getAbsolutePath()));
} else {
dirToWatch = this.configuration.getProcessConfigDirOrFile();
}
// start the watcher
this.watcher = new WatchDir(dirToWatch, this);
this.watcher.start();
} | [
"private",
"void",
"startupWatchdir",
"(",
")",
"throws",
"Exception",
"{",
"File",
"dirToWatch",
";",
"if",
"(",
"this",
".",
"configuration",
".",
"getProcessConfigDirOrFile",
"(",
")",
".",
"isFile",
"(",
")",
")",
"{",
"dirToWatch",
"=",
"new",
"File",
"(",
"FilenameUtils",
".",
"getFullPath",
"(",
"this",
".",
"configuration",
".",
"getProcessConfigDirOrFile",
"(",
")",
".",
"getAbsolutePath",
"(",
")",
")",
")",
";",
"}",
"else",
"{",
"dirToWatch",
"=",
"this",
".",
"configuration",
".",
"getProcessConfigDirOrFile",
"(",
")",
";",
"}",
"// start the watcher",
"this",
".",
"watcher",
"=",
"new",
"WatchDir",
"(",
"dirToWatch",
",",
"this",
")",
";",
"this",
".",
"watcher",
".",
"start",
"(",
")",
";",
"}"
] | Startup the watchdir service. | [
"Startup",
"the",
"watchdir",
"service",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java#L278-L289 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java | JmxTransformer.executeStandalone | public void executeStandalone(JmxProcess process) throws Exception {
this.masterServersList = process.getServers();
this.serverScheduler.start();
this.processServersIntoJobs();
// Sleep for 10 seconds to wait for jobs to complete.
// There should be a better way, but it seems that way isn't working
// right now.
Thread.sleep(MILLISECONDS.convert(10, SECONDS));
} | java | public void executeStandalone(JmxProcess process) throws Exception {
this.masterServersList = process.getServers();
this.serverScheduler.start();
this.processServersIntoJobs();
// Sleep for 10 seconds to wait for jobs to complete.
// There should be a better way, but it seems that way isn't working
// right now.
Thread.sleep(MILLISECONDS.convert(10, SECONDS));
} | [
"public",
"void",
"executeStandalone",
"(",
"JmxProcess",
"process",
")",
"throws",
"Exception",
"{",
"this",
".",
"masterServersList",
"=",
"process",
".",
"getServers",
"(",
")",
";",
"this",
".",
"serverScheduler",
".",
"start",
"(",
")",
";",
"this",
".",
"processServersIntoJobs",
"(",
")",
";",
"// Sleep for 10 seconds to wait for jobs to complete.",
"// There should be a better way, but it seems that way isn't working",
"// right now.",
"Thread",
".",
"sleep",
"(",
"MILLISECONDS",
".",
"convert",
"(",
"10",
",",
"SECONDS",
")",
")",
";",
"}"
] | Handy method which runs the JmxProcess | [
"Handy",
"method",
"which",
"runs",
"the",
"JmxProcess"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java#L294-L305 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java | JmxTransformer.processFilesIntoServers | private void processFilesIntoServers() throws LifecycleException {
// Shutdown the outputwriters and clear the current server list - this gives us a clean
// start when re-reading the json config files
try {
this.stopWriterAndClearMasterServerList();
} catch (Exception e) {
log.error("Error while clearing master server list: " + e.getMessage(), e);
throw new LifecycleException(e);
}
this.masterServersList = configurationParser.parseServers(getProcessConfigFiles(), configuration.isContinueOnJsonError());
} | java | private void processFilesIntoServers() throws LifecycleException {
// Shutdown the outputwriters and clear the current server list - this gives us a clean
// start when re-reading the json config files
try {
this.stopWriterAndClearMasterServerList();
} catch (Exception e) {
log.error("Error while clearing master server list: " + e.getMessage(), e);
throw new LifecycleException(e);
}
this.masterServersList = configurationParser.parseServers(getProcessConfigFiles(), configuration.isContinueOnJsonError());
} | [
"private",
"void",
"processFilesIntoServers",
"(",
")",
"throws",
"LifecycleException",
"{",
"// Shutdown the outputwriters and clear the current server list - this gives us a clean",
"// start when re-reading the json config files",
"try",
"{",
"this",
".",
"stopWriterAndClearMasterServerList",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"log",
".",
"error",
"(",
"\"Error while clearing master server list: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"throw",
"new",
"LifecycleException",
"(",
"e",
")",
";",
"}",
"this",
".",
"masterServersList",
"=",
"configurationParser",
".",
"parseServers",
"(",
"getProcessConfigFiles",
"(",
")",
",",
"configuration",
".",
"isContinueOnJsonError",
"(",
")",
")",
";",
"}"
] | Processes all the json files and manages the dedup process | [
"Processes",
"all",
"the",
"json",
"files",
"and",
"manages",
"the",
"dedup",
"process"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java#L344-L355 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java | JmxTransformer.isProcessConfigFile | private boolean isProcessConfigFile(File file) {
if (this.configuration.getProcessConfigDirOrFile().isFile()) {
return file.equals(this.configuration.getProcessConfigDirOrFile());
}
// If the file doesn't exist anymore, treat it as a regular file (to handle file deletion events)
if(file.exists() && !file.isFile()) {
return false;
}
final String fileName = file.getName();
return !fileName.startsWith(".") && (fileName.endsWith(".json") || fileName.endsWith(".yml") || fileName.endsWith(".yaml"));
} | java | private boolean isProcessConfigFile(File file) {
if (this.configuration.getProcessConfigDirOrFile().isFile()) {
return file.equals(this.configuration.getProcessConfigDirOrFile());
}
// If the file doesn't exist anymore, treat it as a regular file (to handle file deletion events)
if(file.exists() && !file.isFile()) {
return false;
}
final String fileName = file.getName();
return !fileName.startsWith(".") && (fileName.endsWith(".json") || fileName.endsWith(".yml") || fileName.endsWith(".yaml"));
} | [
"private",
"boolean",
"isProcessConfigFile",
"(",
"File",
"file",
")",
"{",
"if",
"(",
"this",
".",
"configuration",
".",
"getProcessConfigDirOrFile",
"(",
")",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"file",
".",
"equals",
"(",
"this",
".",
"configuration",
".",
"getProcessConfigDirOrFile",
"(",
")",
")",
";",
"}",
"// If the file doesn't exist anymore, treat it as a regular file (to handle file deletion events)",
"if",
"(",
"file",
".",
"exists",
"(",
")",
"&&",
"!",
"file",
".",
"isFile",
"(",
")",
")",
"{",
"return",
"false",
";",
"}",
"final",
"String",
"fileName",
"=",
"file",
".",
"getName",
"(",
")",
";",
"return",
"!",
"fileName",
".",
"startsWith",
"(",
"\".\"",
")",
"&&",
"(",
"fileName",
".",
"endsWith",
"(",
"\".json\"",
")",
"||",
"fileName",
".",
"endsWith",
"(",
"\".yml\"",
")",
"||",
"fileName",
".",
"endsWith",
"(",
"\".yaml\"",
")",
")",
";",
"}"
] | Are we a file and a JSON or YAML file? | [
"Are",
"we",
"a",
"file",
"and",
"a",
"JSON",
"or",
"YAML",
"file?"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java#L460-L472 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/Server.java | Server.getServerConnection | @Override
@JsonIgnore
public JMXConnector getServerConnection() throws IOException {
JMXServiceURL url = getJmxServiceURL();
return JMXConnectorFactory.connect(url, this.getEnvironment());
} | java | @Override
@JsonIgnore
public JMXConnector getServerConnection() throws IOException {
JMXServiceURL url = getJmxServiceURL();
return JMXConnectorFactory.connect(url, this.getEnvironment());
} | [
"@",
"Override",
"@",
"JsonIgnore",
"public",
"JMXConnector",
"getServerConnection",
"(",
")",
"throws",
"IOException",
"{",
"JMXServiceURL",
"url",
"=",
"getJmxServiceURL",
"(",
")",
";",
"return",
"JMXConnectorFactory",
".",
"connect",
"(",
"url",
",",
"this",
".",
"getEnvironment",
"(",
")",
")",
";",
"}"
] | Helper method for connecting to a Server. You need to close the resulting
connection. | [
"Helper",
"method",
"for",
"connecting",
"to",
"a",
"Server",
".",
"You",
"need",
"to",
"close",
"the",
"resulting",
"connection",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/Server.java#L343-L348 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-logback/src/main/java/com/googlecode/jmxtrans/model/output/KeyOutWriter.java | KeyOutWriter.validateSetup | @Override
public void validateSetup(Server server, Query query) throws ValidationException {
// Check if we've already created a logger for this file. If so, use it.
Logger logger;
if (loggers.containsKey(outputFile)) {
logger = getLogger(outputFile);
}else{
// need to create a logger
try {
logger = buildLogger(outputFile);
loggers.put(outputFile, logger);
} catch (IOException e) {
throw new ValidationException("Failed to setup logback", query, e);
}
}
logwriter = new LogWriter(logger,delimiter);
} | java | @Override
public void validateSetup(Server server, Query query) throws ValidationException {
// Check if we've already created a logger for this file. If so, use it.
Logger logger;
if (loggers.containsKey(outputFile)) {
logger = getLogger(outputFile);
}else{
// need to create a logger
try {
logger = buildLogger(outputFile);
loggers.put(outputFile, logger);
} catch (IOException e) {
throw new ValidationException("Failed to setup logback", query, e);
}
}
logwriter = new LogWriter(logger,delimiter);
} | [
"@",
"Override",
"public",
"void",
"validateSetup",
"(",
"Server",
"server",
",",
"Query",
"query",
")",
"throws",
"ValidationException",
"{",
"// Check if we've already created a logger for this file. If so, use it.",
"Logger",
"logger",
";",
"if",
"(",
"loggers",
".",
"containsKey",
"(",
"outputFile",
")",
")",
"{",
"logger",
"=",
"getLogger",
"(",
"outputFile",
")",
";",
"}",
"else",
"{",
"// need to create a logger",
"try",
"{",
"logger",
"=",
"buildLogger",
"(",
"outputFile",
")",
";",
"loggers",
".",
"put",
"(",
"outputFile",
",",
"logger",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"ValidationException",
"(",
"\"Failed to setup logback\"",
",",
"query",
",",
"e",
")",
";",
"}",
"}",
"logwriter",
"=",
"new",
"LogWriter",
"(",
"logger",
",",
"delimiter",
")",
";",
"}"
] | Creates the logging | [
"Creates",
"the",
"logging"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-logback/src/main/java/com/googlecode/jmxtrans/model/output/KeyOutWriter.java#L129-L145 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-logback/src/main/java/com/googlecode/jmxtrans/model/output/KeyOutWriter.java | KeyOutWriter.internalWrite | @Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
graphiteWriter.write(logwriter, server, query, results);
} | java | @Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
graphiteWriter.write(logwriter, server, query, results);
} | [
"@",
"Override",
"public",
"void",
"internalWrite",
"(",
"Server",
"server",
",",
"Query",
"query",
",",
"ImmutableList",
"<",
"Result",
">",
"results",
")",
"throws",
"Exception",
"{",
"graphiteWriter",
".",
"write",
"(",
"logwriter",
",",
"server",
",",
"query",
",",
"results",
")",
";",
"}"
] | The meat of the output. Reuses the GraphiteWriter2 class but writes in a logfile
instead of a network socket. | [
"The",
"meat",
"of",
"the",
"output",
".",
"Reuses",
"the",
"GraphiteWriter2",
"class",
"but",
"writes",
"in",
"a",
"logfile",
"instead",
"of",
"a",
"network",
"socket",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-logback/src/main/java/com/googlecode/jmxtrans/model/output/KeyOutWriter.java#L193-L196 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-cloudwatch/src/main/java/com/googlecode/jmxtrans/model/output/CloudWatchWriter.java | CloudWatchWriter.createCloudWatchClient | private AmazonCloudWatchClient createCloudWatchClient() {
AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient(new InstanceProfileCredentialsProvider());
cloudWatchClient.setRegion(checkNotNull(Regions.getCurrentRegion(), "Problems getting AWS metadata"));
return cloudWatchClient;
} | java | private AmazonCloudWatchClient createCloudWatchClient() {
AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient(new InstanceProfileCredentialsProvider());
cloudWatchClient.setRegion(checkNotNull(Regions.getCurrentRegion(), "Problems getting AWS metadata"));
return cloudWatchClient;
} | [
"private",
"AmazonCloudWatchClient",
"createCloudWatchClient",
"(",
")",
"{",
"AmazonCloudWatchClient",
"cloudWatchClient",
"=",
"new",
"AmazonCloudWatchClient",
"(",
"new",
"InstanceProfileCredentialsProvider",
"(",
")",
")",
";",
"cloudWatchClient",
".",
"setRegion",
"(",
"checkNotNull",
"(",
"Regions",
".",
"getCurrentRegion",
"(",
")",
",",
"\"Problems getting AWS metadata\"",
")",
")",
";",
"return",
"cloudWatchClient",
";",
"}"
] | Configuring the CloudWatch client.
Credentials are loaded from the Amazon EC2 Instance Metadata Service | [
"Configuring",
"the",
"CloudWatch",
"client",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-cloudwatch/src/main/java/com/googlecode/jmxtrans/model/output/CloudWatchWriter.java#L96-L100 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/JexlNamingStrategy.java | JexlNamingStrategy.formatName | @Override
public String formatName(Result result) {
String formatted;
JexlContext context = new MapContext();
this.populateContext(context, result);
try {
formatted = (String) this.parsedExpr.evaluate(context);
} catch (JexlException jexlExc) {
LOG.error("error applying JEXL expression to query results", jexlExc);
formatted = null;
}
return formatted;
} | java | @Override
public String formatName(Result result) {
String formatted;
JexlContext context = new MapContext();
this.populateContext(context, result);
try {
formatted = (String) this.parsedExpr.evaluate(context);
} catch (JexlException jexlExc) {
LOG.error("error applying JEXL expression to query results", jexlExc);
formatted = null;
}
return formatted;
} | [
"@",
"Override",
"public",
"String",
"formatName",
"(",
"Result",
"result",
")",
"{",
"String",
"formatted",
";",
"JexlContext",
"context",
"=",
"new",
"MapContext",
"(",
")",
";",
"this",
".",
"populateContext",
"(",
"context",
",",
"result",
")",
";",
"try",
"{",
"formatted",
"=",
"(",
"String",
")",
"this",
".",
"parsedExpr",
".",
"evaluate",
"(",
"context",
")",
";",
"}",
"catch",
"(",
"JexlException",
"jexlExc",
")",
"{",
"LOG",
".",
"error",
"(",
"\"error applying JEXL expression to query results\"",
",",
"jexlExc",
")",
";",
"formatted",
"=",
"null",
";",
"}",
"return",
"formatted",
";",
"}"
] | Format the name for the given result.
@param result - the result of a JMX query.
@return String - the formatted string resulting from the expression, or null if the formatting fails. | [
"Format",
"the",
"name",
"for",
"the",
"given",
"result",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/JexlNamingStrategy.java#L100-L114 | train |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/JexlNamingStrategy.java | JexlNamingStrategy.populateContext | protected void populateContext(JexlContext context, Result result) {
context.set(VAR_CLASSNAME, result.getClassName());
context.set(VAR_ATTRIBUTE_NAME, result.getAttributeName());
context.set(VAR_CLASSNAME_ALIAS, result.getKeyAlias());
Map<String, String> typeNameMap = TypeNameValue.extractMap(result.getTypeName());
context.set(VAR_TYPENAME, typeNameMap);
String effectiveClassname = result.getKeyAlias();
if (effectiveClassname == null) {
effectiveClassname = result.getClassName();
}
context.set(VAR_EFFECTIVE_CLASSNAME, effectiveClassname);
context.set(VAR_RESULT, result);
} | java | protected void populateContext(JexlContext context, Result result) {
context.set(VAR_CLASSNAME, result.getClassName());
context.set(VAR_ATTRIBUTE_NAME, result.getAttributeName());
context.set(VAR_CLASSNAME_ALIAS, result.getKeyAlias());
Map<String, String> typeNameMap = TypeNameValue.extractMap(result.getTypeName());
context.set(VAR_TYPENAME, typeNameMap);
String effectiveClassname = result.getKeyAlias();
if (effectiveClassname == null) {
effectiveClassname = result.getClassName();
}
context.set(VAR_EFFECTIVE_CLASSNAME, effectiveClassname);
context.set(VAR_RESULT, result);
} | [
"protected",
"void",
"populateContext",
"(",
"JexlContext",
"context",
",",
"Result",
"result",
")",
"{",
"context",
".",
"set",
"(",
"VAR_CLASSNAME",
",",
"result",
".",
"getClassName",
"(",
")",
")",
";",
"context",
".",
"set",
"(",
"VAR_ATTRIBUTE_NAME",
",",
"result",
".",
"getAttributeName",
"(",
")",
")",
";",
"context",
".",
"set",
"(",
"VAR_CLASSNAME_ALIAS",
",",
"result",
".",
"getKeyAlias",
"(",
")",
")",
";",
"Map",
"<",
"String",
",",
"String",
">",
"typeNameMap",
"=",
"TypeNameValue",
".",
"extractMap",
"(",
"result",
".",
"getTypeName",
"(",
")",
")",
";",
"context",
".",
"set",
"(",
"VAR_TYPENAME",
",",
"typeNameMap",
")",
";",
"String",
"effectiveClassname",
"=",
"result",
".",
"getKeyAlias",
"(",
")",
";",
"if",
"(",
"effectiveClassname",
"==",
"null",
")",
"{",
"effectiveClassname",
"=",
"result",
".",
"getClassName",
"(",
")",
";",
"}",
"context",
".",
"set",
"(",
"VAR_EFFECTIVE_CLASSNAME",
",",
"effectiveClassname",
")",
";",
"context",
".",
"set",
"(",
"VAR_RESULT",
",",
"result",
")",
";",
"}"
] | Populate the context with values from the result.
@param context - the expression context used when evaluating JEXL expressions.
@param result - the result of a JMX query. | [
"Populate",
"the",
"context",
"with",
"values",
"from",
"the",
"result",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/naming/JexlNamingStrategy.java#L126-L141 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java | RRDToolWriter.getDataSourceName | public String getDataSourceName(String typeName, String attributeName, List<String> valuePath) {
String result;
String entry = StringUtils.join(valuePath, '.');
if (typeName != null) {
result = typeName + attributeName + entry;
} else {
result = attributeName + entry;
}
if (attributeName.length() > 15) {
String[] split = StringUtils.splitByCharacterTypeCamelCase(attributeName);
String join = StringUtils.join(split, '.');
attributeName = WordUtils.initials(join, INITIALS);
}
result = attributeName + DigestUtils.md5Hex(result);
result = StringUtils.left(result, 19);
return result;
} | java | public String getDataSourceName(String typeName, String attributeName, List<String> valuePath) {
String result;
String entry = StringUtils.join(valuePath, '.');
if (typeName != null) {
result = typeName + attributeName + entry;
} else {
result = attributeName + entry;
}
if (attributeName.length() > 15) {
String[] split = StringUtils.splitByCharacterTypeCamelCase(attributeName);
String join = StringUtils.join(split, '.');
attributeName = WordUtils.initials(join, INITIALS);
}
result = attributeName + DigestUtils.md5Hex(result);
result = StringUtils.left(result, 19);
return result;
} | [
"public",
"String",
"getDataSourceName",
"(",
"String",
"typeName",
",",
"String",
"attributeName",
",",
"List",
"<",
"String",
">",
"valuePath",
")",
"{",
"String",
"result",
";",
"String",
"entry",
"=",
"StringUtils",
".",
"join",
"(",
"valuePath",
",",
"'",
"'",
")",
";",
"if",
"(",
"typeName",
"!=",
"null",
")",
"{",
"result",
"=",
"typeName",
"+",
"attributeName",
"+",
"entry",
";",
"}",
"else",
"{",
"result",
"=",
"attributeName",
"+",
"entry",
";",
"}",
"if",
"(",
"attributeName",
".",
"length",
"(",
")",
">",
"15",
")",
"{",
"String",
"[",
"]",
"split",
"=",
"StringUtils",
".",
"splitByCharacterTypeCamelCase",
"(",
"attributeName",
")",
";",
"String",
"join",
"=",
"StringUtils",
".",
"join",
"(",
"split",
",",
"'",
"'",
")",
";",
"attributeName",
"=",
"WordUtils",
".",
"initials",
"(",
"join",
",",
"INITIALS",
")",
";",
"}",
"result",
"=",
"attributeName",
"+",
"DigestUtils",
".",
"md5Hex",
"(",
"result",
")",
";",
"result",
"=",
"StringUtils",
".",
"left",
"(",
"result",
",",
"19",
")",
";",
"return",
"result",
";",
"}"
] | rrd datasources must be less than 21 characters in length, so work to
make it shorter. Not ideal at all, but works fairly well it seems. | [
"rrd",
"datasources",
"must",
"be",
"less",
"than",
"21",
"characters",
"in",
"length",
"so",
"work",
"to",
"make",
"it",
"shorter",
".",
"Not",
"ideal",
"at",
"all",
"but",
"works",
"fairly",
"well",
"it",
"seems",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java#L108-L127 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java | RRDToolWriter.rrdToolUpdate | protected void rrdToolUpdate(String template, String data) throws Exception {
List<String> commands = new ArrayList<>();
commands.add(binaryPath + "/rrdtool");
commands.add("update");
commands.add(outputFile.getCanonicalPath());
commands.add("-t");
commands.add(template);
commands.add("N:" + data);
ProcessBuilder pb = new ProcessBuilder(commands);
Process process = pb.start();
checkErrorStream(process);
} | java | protected void rrdToolUpdate(String template, String data) throws Exception {
List<String> commands = new ArrayList<>();
commands.add(binaryPath + "/rrdtool");
commands.add("update");
commands.add(outputFile.getCanonicalPath());
commands.add("-t");
commands.add(template);
commands.add("N:" + data);
ProcessBuilder pb = new ProcessBuilder(commands);
Process process = pb.start();
checkErrorStream(process);
} | [
"protected",
"void",
"rrdToolUpdate",
"(",
"String",
"template",
",",
"String",
"data",
")",
"throws",
"Exception",
"{",
"List",
"<",
"String",
">",
"commands",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"commands",
".",
"add",
"(",
"binaryPath",
"+",
"\"/rrdtool\"",
")",
";",
"commands",
".",
"add",
"(",
"\"update\"",
")",
";",
"commands",
".",
"add",
"(",
"outputFile",
".",
"getCanonicalPath",
"(",
")",
")",
";",
"commands",
".",
"add",
"(",
"\"-t\"",
")",
";",
"commands",
".",
"add",
"(",
"template",
")",
";",
"commands",
".",
"add",
"(",
"\"N:\"",
"+",
"data",
")",
";",
"ProcessBuilder",
"pb",
"=",
"new",
"ProcessBuilder",
"(",
"commands",
")",
";",
"Process",
"process",
"=",
"pb",
".",
"start",
"(",
")",
";",
"checkErrorStream",
"(",
"process",
")",
";",
"}"
] | Executes the rrdtool update command. | [
"Executes",
"the",
"rrdtool",
"update",
"command",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java#L187-L199 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java | RRDToolWriter.rrdToolCreateDatabase | protected void rrdToolCreateDatabase(RrdDef def) throws Exception {
List<String> commands = new ArrayList<>();
commands.add(this.binaryPath + "/rrdtool");
commands.add("create");
commands.add(this.outputFile.getCanonicalPath());
commands.add("-s");
commands.add(String.valueOf(def.getStep()));
for (DsDef dsdef : def.getDsDefs()) {
commands.add(getDsDefStr(dsdef));
}
for (ArcDef adef : def.getArcDefs()) {
commands.add(getRraStr(adef));
}
ProcessBuilder pb = new ProcessBuilder(commands);
Process process = pb.start();
try {
checkErrorStream(process);
} finally {
IOUtils.closeQuietly(process.getInputStream());
IOUtils.closeQuietly(process.getOutputStream());
IOUtils.closeQuietly(process.getErrorStream());
}
} | java | protected void rrdToolCreateDatabase(RrdDef def) throws Exception {
List<String> commands = new ArrayList<>();
commands.add(this.binaryPath + "/rrdtool");
commands.add("create");
commands.add(this.outputFile.getCanonicalPath());
commands.add("-s");
commands.add(String.valueOf(def.getStep()));
for (DsDef dsdef : def.getDsDefs()) {
commands.add(getDsDefStr(dsdef));
}
for (ArcDef adef : def.getArcDefs()) {
commands.add(getRraStr(adef));
}
ProcessBuilder pb = new ProcessBuilder(commands);
Process process = pb.start();
try {
checkErrorStream(process);
} finally {
IOUtils.closeQuietly(process.getInputStream());
IOUtils.closeQuietly(process.getOutputStream());
IOUtils.closeQuietly(process.getErrorStream());
}
} | [
"protected",
"void",
"rrdToolCreateDatabase",
"(",
"RrdDef",
"def",
")",
"throws",
"Exception",
"{",
"List",
"<",
"String",
">",
"commands",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"commands",
".",
"add",
"(",
"this",
".",
"binaryPath",
"+",
"\"/rrdtool\"",
")",
";",
"commands",
".",
"add",
"(",
"\"create\"",
")",
";",
"commands",
".",
"add",
"(",
"this",
".",
"outputFile",
".",
"getCanonicalPath",
"(",
")",
")",
";",
"commands",
".",
"add",
"(",
"\"-s\"",
")",
";",
"commands",
".",
"add",
"(",
"String",
".",
"valueOf",
"(",
"def",
".",
"getStep",
"(",
")",
")",
")",
";",
"for",
"(",
"DsDef",
"dsdef",
":",
"def",
".",
"getDsDefs",
"(",
")",
")",
"{",
"commands",
".",
"add",
"(",
"getDsDefStr",
"(",
"dsdef",
")",
")",
";",
"}",
"for",
"(",
"ArcDef",
"adef",
":",
"def",
".",
"getArcDefs",
"(",
")",
")",
"{",
"commands",
".",
"add",
"(",
"getRraStr",
"(",
"adef",
")",
")",
";",
"}",
"ProcessBuilder",
"pb",
"=",
"new",
"ProcessBuilder",
"(",
"commands",
")",
";",
"Process",
"process",
"=",
"pb",
".",
"start",
"(",
")",
";",
"try",
"{",
"checkErrorStream",
"(",
"process",
")",
";",
"}",
"finally",
"{",
"IOUtils",
".",
"closeQuietly",
"(",
"process",
".",
"getInputStream",
"(",
")",
")",
";",
"IOUtils",
".",
"closeQuietly",
"(",
"process",
".",
"getOutputStream",
"(",
")",
")",
";",
"IOUtils",
".",
"closeQuietly",
"(",
"process",
".",
"getErrorStream",
"(",
")",
")",
";",
"}",
"}"
] | Calls out to the rrdtool binary with the 'create' command. | [
"Calls",
"out",
"to",
"the",
"rrdtool",
"binary",
"with",
"the",
"create",
"command",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java#L219-L244 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java | RRDToolWriter.checkErrorStream | private void checkErrorStream(Process process) throws Exception {
// rrdtool should use platform encoding (unless you did something
// very strange with your installation of rrdtool). So let's be
// explicit and use the presumed correct encoding to read errors.
try (
InputStream is = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is, Charset.defaultCharset());
BufferedReader br = new BufferedReader(isr)
) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
if (sb.length() > 0) {
throw new RuntimeException(sb.toString());
}
}
} | java | private void checkErrorStream(Process process) throws Exception {
// rrdtool should use platform encoding (unless you did something
// very strange with your installation of rrdtool). So let's be
// explicit and use the presumed correct encoding to read errors.
try (
InputStream is = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(is, Charset.defaultCharset());
BufferedReader br = new BufferedReader(isr)
) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
if (sb.length() > 0) {
throw new RuntimeException(sb.toString());
}
}
} | [
"private",
"void",
"checkErrorStream",
"(",
"Process",
"process",
")",
"throws",
"Exception",
"{",
"// rrdtool should use platform encoding (unless you did something",
"// very strange with your installation of rrdtool). So let's be",
"// explicit and use the presumed correct encoding to read errors.",
"try",
"(",
"InputStream",
"is",
"=",
"process",
".",
"getErrorStream",
"(",
")",
";",
"InputStreamReader",
"isr",
"=",
"new",
"InputStreamReader",
"(",
"is",
",",
"Charset",
".",
"defaultCharset",
"(",
")",
")",
";",
"BufferedReader",
"br",
"=",
"new",
"BufferedReader",
"(",
"isr",
")",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"String",
"line",
";",
"while",
"(",
"(",
"line",
"=",
"br",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"line",
")",
";",
"}",
"if",
"(",
"sb",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Check to see if there was an error processing an rrdtool command | [
"Check",
"to",
"see",
"if",
"there",
"was",
"an",
"error",
"processing",
"an",
"rrdtool",
"command"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java#L249-L267 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java | RRDToolWriter.getRraStr | private String getRraStr(ArcDef def) {
return "RRA:" + def.getConsolFun() + ":" + def.getXff() + ":" + def.getSteps() + ":" + def.getRows();
} | java | private String getRraStr(ArcDef def) {
return "RRA:" + def.getConsolFun() + ":" + def.getXff() + ":" + def.getSteps() + ":" + def.getRows();
} | [
"private",
"String",
"getRraStr",
"(",
"ArcDef",
"def",
")",
"{",
"return",
"\"RRA:\"",
"+",
"def",
".",
"getConsolFun",
"(",
")",
"+",
"\":\"",
"+",
"def",
".",
"getXff",
"(",
")",
"+",
"\":\"",
"+",
"def",
".",
"getSteps",
"(",
")",
"+",
"\":\"",
"+",
"def",
".",
"getRows",
"(",
")",
";",
"}"
] | Generate a RRA line for rrdtool | [
"Generate",
"a",
"RRA",
"line",
"for",
"rrdtool"
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java#L272-L274 | train |
jmxtrans/jmxtrans | jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java | RRDToolWriter.getDsNames | private List<String> getDsNames(DsDef[] defs) {
List<String> names = new ArrayList<>();
for (DsDef def : defs) {
names.add(def.getDsName());
}
return names;
} | java | private List<String> getDsNames(DsDef[] defs) {
List<String> names = new ArrayList<>();
for (DsDef def : defs) {
names.add(def.getDsName());
}
return names;
} | [
"private",
"List",
"<",
"String",
">",
"getDsNames",
"(",
"DsDef",
"[",
"]",
"defs",
")",
"{",
"List",
"<",
"String",
">",
"names",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"DsDef",
"def",
":",
"defs",
")",
"{",
"names",
".",
"add",
"(",
"def",
".",
"getDsName",
"(",
")",
")",
";",
"}",
"return",
"names",
";",
"}"
] | Get a list of DsNames used to create the datasource. | [
"Get",
"a",
"list",
"of",
"DsNames",
"used",
"to",
"create",
"the",
"datasource",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-jrobin/src/main/java/com/googlecode/jmxtrans/model/output/RRDToolWriter.java#L291-L297 | train |
jmxtrans/jmxtrans | jmxtrans-utils/src/main/java/com/googlecode/jmxtrans/classloader/ClassLoaderEnricher.java | ClassLoaderEnricher.add | public void add(URL url) {
URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysClass = URLClassLoader.class;
try {
Method method = sysClass.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(sysLoader, new Object[]{ url });
} catch (InvocationTargetException e) {
throw new JarLoadingException(e);
} catch (NoSuchMethodException e) {
throw new JarLoadingException(e);
} catch (IllegalAccessException e) {
throw new JarLoadingException(e);
}
} | java | public void add(URL url) {
URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysClass = URLClassLoader.class;
try {
Method method = sysClass.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(sysLoader, new Object[]{ url });
} catch (InvocationTargetException e) {
throw new JarLoadingException(e);
} catch (NoSuchMethodException e) {
throw new JarLoadingException(e);
} catch (IllegalAccessException e) {
throw new JarLoadingException(e);
}
} | [
"public",
"void",
"add",
"(",
"URL",
"url",
")",
"{",
"URLClassLoader",
"sysLoader",
"=",
"(",
"URLClassLoader",
")",
"ClassLoader",
".",
"getSystemClassLoader",
"(",
")",
";",
"Class",
"sysClass",
"=",
"URLClassLoader",
".",
"class",
";",
"try",
"{",
"Method",
"method",
"=",
"sysClass",
".",
"getDeclaredMethod",
"(",
"\"addURL\"",
",",
"URL",
".",
"class",
")",
";",
"method",
".",
"setAccessible",
"(",
"true",
")",
";",
"method",
".",
"invoke",
"(",
"sysLoader",
",",
"new",
"Object",
"[",
"]",
"{",
"url",
"}",
")",
";",
"}",
"catch",
"(",
"InvocationTargetException",
"e",
")",
"{",
"throw",
"new",
"JarLoadingException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"NoSuchMethodException",
"e",
")",
"{",
"throw",
"new",
"JarLoadingException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"JarLoadingException",
"(",
"e",
")",
";",
"}",
"}"
] | Add the given URL to the system class loader.
Note that this method uses reflection to change the visibility of the URLClassLoader.addURL() method. This will
fail if a security manager forbids it.
@param url | [
"Add",
"the",
"given",
"URL",
"to",
"the",
"system",
"class",
"loader",
"."
] | 496f342de3bcf2c2226626374b7a16edf8f4ba2a | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-utils/src/main/java/com/googlecode/jmxtrans/classloader/ClassLoaderEnricher.java#L50-L65 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/Parameterized.java | Parameterized.describeClassTree | private static void describeClassTree(Class<?> inputClass, Set<Class<?>> setOfClasses) {
// can't map null class
if(inputClass == null) {
return;
}
// don't further analyze a class that has been analyzed already
if(Object.class.equals(inputClass) || setOfClasses.contains(inputClass)) {
return;
}
// add to analysis set
setOfClasses.add(inputClass);
// perform super class analysis
describeClassTree(inputClass.getSuperclass(), setOfClasses);
// perform analysis on interfaces
for(Class<?> hasInterface : inputClass.getInterfaces()) {
describeClassTree(hasInterface, setOfClasses);
}
} | java | private static void describeClassTree(Class<?> inputClass, Set<Class<?>> setOfClasses) {
// can't map null class
if(inputClass == null) {
return;
}
// don't further analyze a class that has been analyzed already
if(Object.class.equals(inputClass) || setOfClasses.contains(inputClass)) {
return;
}
// add to analysis set
setOfClasses.add(inputClass);
// perform super class analysis
describeClassTree(inputClass.getSuperclass(), setOfClasses);
// perform analysis on interfaces
for(Class<?> hasInterface : inputClass.getInterfaces()) {
describeClassTree(hasInterface, setOfClasses);
}
} | [
"private",
"static",
"void",
"describeClassTree",
"(",
"Class",
"<",
"?",
">",
"inputClass",
",",
"Set",
"<",
"Class",
"<",
"?",
">",
">",
"setOfClasses",
")",
"{",
"// can't map null class",
"if",
"(",
"inputClass",
"==",
"null",
")",
"{",
"return",
";",
"}",
"// don't further analyze a class that has been analyzed already",
"if",
"(",
"Object",
".",
"class",
".",
"equals",
"(",
"inputClass",
")",
"||",
"setOfClasses",
".",
"contains",
"(",
"inputClass",
")",
")",
"{",
"return",
";",
"}",
"// add to analysis set",
"setOfClasses",
".",
"add",
"(",
"inputClass",
")",
";",
"// perform super class analysis",
"describeClassTree",
"(",
"inputClass",
".",
"getSuperclass",
"(",
")",
",",
"setOfClasses",
")",
";",
"// perform analysis on interfaces",
"for",
"(",
"Class",
"<",
"?",
">",
"hasInterface",
":",
"inputClass",
".",
"getInterfaces",
"(",
")",
")",
"{",
"describeClassTree",
"(",
"hasInterface",
",",
"setOfClasses",
")",
";",
"}",
"}"
] | Recursive handler for describing the set of classes while
using the setOfClasses parameter as a collector
@param inputClass the class to analyze
@param setOfClasses the set collector to collect the results | [
"Recursive",
"handler",
"for",
"describing",
"the",
"set",
"of",
"classes",
"while",
"using",
"the",
"setOfClasses",
"parameter",
"as",
"a",
"collector"
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/Parameterized.java#L48-L69 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/Parameterized.java | Parameterized.describeClassTree | private static Set<Class<?>> describeClassTree(Class<?> inputClass) {
if(inputClass == null) {
return Collections.emptySet();
}
// create result collector
Set<Class<?>> classes = Sets.newLinkedHashSet();
// describe tree
describeClassTree(inputClass, classes);
return classes;
} | java | private static Set<Class<?>> describeClassTree(Class<?> inputClass) {
if(inputClass == null) {
return Collections.emptySet();
}
// create result collector
Set<Class<?>> classes = Sets.newLinkedHashSet();
// describe tree
describeClassTree(inputClass, classes);
return classes;
} | [
"private",
"static",
"Set",
"<",
"Class",
"<",
"?",
">",
">",
"describeClassTree",
"(",
"Class",
"<",
"?",
">",
"inputClass",
")",
"{",
"if",
"(",
"inputClass",
"==",
"null",
")",
"{",
"return",
"Collections",
".",
"emptySet",
"(",
")",
";",
"}",
"// create result collector",
"Set",
"<",
"Class",
"<",
"?",
">",
">",
"classes",
"=",
"Sets",
".",
"newLinkedHashSet",
"(",
")",
";",
"// describe tree",
"describeClassTree",
"(",
"inputClass",
",",
"classes",
")",
";",
"return",
"classes",
";",
"}"
] | Given an object return the set of classes that it extends
or implements.
@param inputClass object to describe
@return set of classes that are implemented or extended by that object | [
"Given",
"an",
"object",
"return",
"the",
"set",
"of",
"classes",
"that",
"it",
"extends",
"or",
"implements",
"."
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/Parameterized.java#L78-L90 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/DefaultUsageFormatter.java | DefaultUsageFormatter.usage | public void usage(StringBuilder out, String indent) {
if (commander.getDescriptions() == null) {
commander.createDescriptions();
}
boolean hasCommands = !commander.getCommands().isEmpty();
boolean hasOptions = !commander.getDescriptions().isEmpty();
// Indentation constants
final int descriptionIndent = 6;
final int indentCount = indent.length() + descriptionIndent;
// Append first line (aka main line) of the usage
appendMainLine(out, hasOptions, hasCommands, indentCount, indent);
// Align the descriptions at the "longestName" column
int longestName = 0;
List<ParameterDescription> sortedParameters = Lists.newArrayList();
for (ParameterDescription pd : commander.getFields().values()) {
if (!pd.getParameter().hidden()) {
sortedParameters.add(pd);
// + to have an extra space between the name and the description
int length = pd.getNames().length() + 2;
if (length > longestName) {
longestName = length;
}
}
}
// Sort the options
sortedParameters.sort(commander.getParameterDescriptionComparator());
// Append all the parameter names and descriptions
appendAllParametersDetails(out, indentCount, indent, sortedParameters);
// Append commands if they were specified
if (hasCommands) {
appendCommands(out, indentCount, descriptionIndent, indent);
}
} | java | public void usage(StringBuilder out, String indent) {
if (commander.getDescriptions() == null) {
commander.createDescriptions();
}
boolean hasCommands = !commander.getCommands().isEmpty();
boolean hasOptions = !commander.getDescriptions().isEmpty();
// Indentation constants
final int descriptionIndent = 6;
final int indentCount = indent.length() + descriptionIndent;
// Append first line (aka main line) of the usage
appendMainLine(out, hasOptions, hasCommands, indentCount, indent);
// Align the descriptions at the "longestName" column
int longestName = 0;
List<ParameterDescription> sortedParameters = Lists.newArrayList();
for (ParameterDescription pd : commander.getFields().values()) {
if (!pd.getParameter().hidden()) {
sortedParameters.add(pd);
// + to have an extra space between the name and the description
int length = pd.getNames().length() + 2;
if (length > longestName) {
longestName = length;
}
}
}
// Sort the options
sortedParameters.sort(commander.getParameterDescriptionComparator());
// Append all the parameter names and descriptions
appendAllParametersDetails(out, indentCount, indent, sortedParameters);
// Append commands if they were specified
if (hasCommands) {
appendCommands(out, indentCount, descriptionIndent, indent);
}
} | [
"public",
"void",
"usage",
"(",
"StringBuilder",
"out",
",",
"String",
"indent",
")",
"{",
"if",
"(",
"commander",
".",
"getDescriptions",
"(",
")",
"==",
"null",
")",
"{",
"commander",
".",
"createDescriptions",
"(",
")",
";",
"}",
"boolean",
"hasCommands",
"=",
"!",
"commander",
".",
"getCommands",
"(",
")",
".",
"isEmpty",
"(",
")",
";",
"boolean",
"hasOptions",
"=",
"!",
"commander",
".",
"getDescriptions",
"(",
")",
".",
"isEmpty",
"(",
")",
";",
"// Indentation constants",
"final",
"int",
"descriptionIndent",
"=",
"6",
";",
"final",
"int",
"indentCount",
"=",
"indent",
".",
"length",
"(",
")",
"+",
"descriptionIndent",
";",
"// Append first line (aka main line) of the usage",
"appendMainLine",
"(",
"out",
",",
"hasOptions",
",",
"hasCommands",
",",
"indentCount",
",",
"indent",
")",
";",
"// Align the descriptions at the \"longestName\" column",
"int",
"longestName",
"=",
"0",
";",
"List",
"<",
"ParameterDescription",
">",
"sortedParameters",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"for",
"(",
"ParameterDescription",
"pd",
":",
"commander",
".",
"getFields",
"(",
")",
".",
"values",
"(",
")",
")",
"{",
"if",
"(",
"!",
"pd",
".",
"getParameter",
"(",
")",
".",
"hidden",
"(",
")",
")",
"{",
"sortedParameters",
".",
"add",
"(",
"pd",
")",
";",
"// + to have an extra space between the name and the description",
"int",
"length",
"=",
"pd",
".",
"getNames",
"(",
")",
".",
"length",
"(",
")",
"+",
"2",
";",
"if",
"(",
"length",
">",
"longestName",
")",
"{",
"longestName",
"=",
"length",
";",
"}",
"}",
"}",
"// Sort the options",
"sortedParameters",
".",
"sort",
"(",
"commander",
".",
"getParameterDescriptionComparator",
"(",
")",
")",
";",
"// Append all the parameter names and descriptions",
"appendAllParametersDetails",
"(",
"out",
",",
"indentCount",
",",
"indent",
",",
"sortedParameters",
")",
";",
"// Append commands if they were specified",
"if",
"(",
"hasCommands",
")",
"{",
"appendCommands",
"(",
"out",
",",
"indentCount",
",",
"descriptionIndent",
",",
"indent",
")",
";",
"}",
"}"
] | Stores the usage in the argument string builder, with the argument indentation. This works by appending
each portion of the help in the following order. Their outputs can be modified by overriding them in a
subclass of this class.
<ul>
<li>Main line - {@link #appendMainLine(StringBuilder, boolean, boolean, int, String)}</li>
<li>Parameters - {@link #appendAllParametersDetails(StringBuilder, int, String, List)}</li>
<li>Commands - {@link #appendCommands(StringBuilder, int, int, String)}</li>
</ul> | [
"Stores",
"the",
"usage",
"in",
"the",
"argument",
"string",
"builder",
"with",
"the",
"argument",
"indentation",
".",
"This",
"works",
"by",
"appending",
"each",
"portion",
"of",
"the",
"help",
"in",
"the",
"following",
"order",
".",
"Their",
"outputs",
"can",
"be",
"modified",
"by",
"overriding",
"them",
"in",
"a",
"subclass",
"of",
"this",
"class",
"."
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/DefaultUsageFormatter.java#L86-L126 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/ParameterDescription.java | ParameterDescription.findResourceBundle | @SuppressWarnings("deprecation")
private ResourceBundle findResourceBundle(Object o) {
ResourceBundle result = null;
Parameters p = o.getClass().getAnnotation(Parameters.class);
if (p != null && ! isEmpty(p.resourceBundle())) {
result = ResourceBundle.getBundle(p.resourceBundle(), Locale.getDefault());
} else {
com.beust.jcommander.ResourceBundle a = o.getClass().getAnnotation(
com.beust.jcommander.ResourceBundle.class);
if (a != null && ! isEmpty(a.value())) {
result = ResourceBundle.getBundle(a.value(), Locale.getDefault());
}
}
return result;
} | java | @SuppressWarnings("deprecation")
private ResourceBundle findResourceBundle(Object o) {
ResourceBundle result = null;
Parameters p = o.getClass().getAnnotation(Parameters.class);
if (p != null && ! isEmpty(p.resourceBundle())) {
result = ResourceBundle.getBundle(p.resourceBundle(), Locale.getDefault());
} else {
com.beust.jcommander.ResourceBundle a = o.getClass().getAnnotation(
com.beust.jcommander.ResourceBundle.class);
if (a != null && ! isEmpty(a.value())) {
result = ResourceBundle.getBundle(a.value(), Locale.getDefault());
}
}
return result;
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"private",
"ResourceBundle",
"findResourceBundle",
"(",
"Object",
"o",
")",
"{",
"ResourceBundle",
"result",
"=",
"null",
";",
"Parameters",
"p",
"=",
"o",
".",
"getClass",
"(",
")",
".",
"getAnnotation",
"(",
"Parameters",
".",
"class",
")",
";",
"if",
"(",
"p",
"!=",
"null",
"&&",
"!",
"isEmpty",
"(",
"p",
".",
"resourceBundle",
"(",
")",
")",
")",
"{",
"result",
"=",
"ResourceBundle",
".",
"getBundle",
"(",
"p",
".",
"resourceBundle",
"(",
")",
",",
"Locale",
".",
"getDefault",
"(",
")",
")",
";",
"}",
"else",
"{",
"com",
".",
"beust",
".",
"jcommander",
".",
"ResourceBundle",
"a",
"=",
"o",
".",
"getClass",
"(",
")",
".",
"getAnnotation",
"(",
"com",
".",
"beust",
".",
"jcommander",
".",
"ResourceBundle",
".",
"class",
")",
";",
"if",
"(",
"a",
"!=",
"null",
"&&",
"!",
"isEmpty",
"(",
"a",
".",
"value",
"(",
")",
")",
")",
"{",
"result",
"=",
"ResourceBundle",
".",
"getBundle",
"(",
"a",
".",
"value",
"(",
")",
",",
"Locale",
".",
"getDefault",
"(",
")",
")",
";",
"}",
"}",
"return",
"result",
";",
"}"
] | Find the resource bundle in the annotations.
@return | [
"Find",
"the",
"resource",
"bundle",
"in",
"the",
"annotations",
"."
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/ParameterDescription.java#L72-L88 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/JCommander.java | JCommander.addObject | public final void addObject(Object object) {
if (object instanceof Iterable) {
// Iterable
for (Object o : (Iterable<?>) object) {
objects.add(o);
}
} else if (object.getClass().isArray()) {
// Array
for (Object o : (Object[]) object) {
objects.add(o);
}
} else {
// Single object
objects.add(object);
}
} | java | public final void addObject(Object object) {
if (object instanceof Iterable) {
// Iterable
for (Object o : (Iterable<?>) object) {
objects.add(o);
}
} else if (object.getClass().isArray()) {
// Array
for (Object o : (Object[]) object) {
objects.add(o);
}
} else {
// Single object
objects.add(object);
}
} | [
"public",
"final",
"void",
"addObject",
"(",
"Object",
"object",
")",
"{",
"if",
"(",
"object",
"instanceof",
"Iterable",
")",
"{",
"// Iterable",
"for",
"(",
"Object",
"o",
":",
"(",
"Iterable",
"<",
"?",
">",
")",
"object",
")",
"{",
"objects",
".",
"add",
"(",
"o",
")",
";",
"}",
"}",
"else",
"if",
"(",
"object",
".",
"getClass",
"(",
")",
".",
"isArray",
"(",
")",
")",
"{",
"// Array",
"for",
"(",
"Object",
"o",
":",
"(",
"Object",
"[",
"]",
")",
"object",
")",
"{",
"objects",
".",
"add",
"(",
"o",
")",
";",
"}",
"}",
"else",
"{",
"// Single object",
"objects",
".",
"add",
"(",
"object",
")",
";",
"}",
"}"
] | declared final since this is invoked from constructors | [
"declared",
"final",
"since",
"this",
"is",
"invoked",
"from",
"constructors"
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/JCommander.java#L304-L319 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/JCommander.java | JCommander.parse | public void parse(String... args) {
try {
parse(true /* validate */, args);
} catch(ParameterException ex) {
ex.setJCommander(this);
throw ex;
}
} | java | public void parse(String... args) {
try {
parse(true /* validate */, args);
} catch(ParameterException ex) {
ex.setJCommander(this);
throw ex;
}
} | [
"public",
"void",
"parse",
"(",
"String",
"...",
"args",
")",
"{",
"try",
"{",
"parse",
"(",
"true",
"/* validate */",
",",
"args",
")",
";",
"}",
"catch",
"(",
"ParameterException",
"ex",
")",
"{",
"ex",
".",
"setJCommander",
"(",
"this",
")",
";",
"throw",
"ex",
";",
"}",
"}"
] | Parse and validate the command line parameters. | [
"Parse",
"and",
"validate",
"the",
"command",
"line",
"parameters",
"."
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/JCommander.java#L333-L340 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/JCommander.java | JCommander.validateOptions | private void validateOptions() {
// No validation if we found a help parameter
if (helpWasSpecified) {
return;
}
if (!requiredFields.isEmpty()) {
List<String> missingFields = new ArrayList<>();
for (ParameterDescription pd : requiredFields.values()) {
missingFields.add("[" + Strings.join(" | ", pd.getParameter().names()) + "]");
}
String message = Strings.join(", ", missingFields);
throw new ParameterException("The following "
+ pluralize(requiredFields.size(), "option is required: ", "options are required: ")
+ message);
}
if (mainParameter != null && mainParameter.description != null) {
ParameterDescription mainParameterDescription = mainParameter.description;
// Make sure we have a main parameter if it was required
if (mainParameterDescription.getParameter().required() &&
!mainParameterDescription.isAssigned()) {
throw new ParameterException("Main parameters are required (\""
+ mainParameterDescription.getDescription() + "\")");
}
// If the main parameter has an arity, make sure the correct number of parameters was passed
int arity = mainParameterDescription.getParameter().arity();
if (arity != Parameter.DEFAULT_ARITY) {
Object value = mainParameterDescription.getParameterized().get(mainParameter.object);
if (List.class.isAssignableFrom(value.getClass())) {
int size = ((List<?>) value).size();
if (size != arity) {
throw new ParameterException("There should be exactly " + arity + " main parameters but "
+ size + " were found");
}
}
}
}
} | java | private void validateOptions() {
// No validation if we found a help parameter
if (helpWasSpecified) {
return;
}
if (!requiredFields.isEmpty()) {
List<String> missingFields = new ArrayList<>();
for (ParameterDescription pd : requiredFields.values()) {
missingFields.add("[" + Strings.join(" | ", pd.getParameter().names()) + "]");
}
String message = Strings.join(", ", missingFields);
throw new ParameterException("The following "
+ pluralize(requiredFields.size(), "option is required: ", "options are required: ")
+ message);
}
if (mainParameter != null && mainParameter.description != null) {
ParameterDescription mainParameterDescription = mainParameter.description;
// Make sure we have a main parameter if it was required
if (mainParameterDescription.getParameter().required() &&
!mainParameterDescription.isAssigned()) {
throw new ParameterException("Main parameters are required (\""
+ mainParameterDescription.getDescription() + "\")");
}
// If the main parameter has an arity, make sure the correct number of parameters was passed
int arity = mainParameterDescription.getParameter().arity();
if (arity != Parameter.DEFAULT_ARITY) {
Object value = mainParameterDescription.getParameterized().get(mainParameter.object);
if (List.class.isAssignableFrom(value.getClass())) {
int size = ((List<?>) value).size();
if (size != arity) {
throw new ParameterException("There should be exactly " + arity + " main parameters but "
+ size + " were found");
}
}
}
}
} | [
"private",
"void",
"validateOptions",
"(",
")",
"{",
"// No validation if we found a help parameter",
"if",
"(",
"helpWasSpecified",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"requiredFields",
".",
"isEmpty",
"(",
")",
")",
"{",
"List",
"<",
"String",
">",
"missingFields",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"ParameterDescription",
"pd",
":",
"requiredFields",
".",
"values",
"(",
")",
")",
"{",
"missingFields",
".",
"add",
"(",
"\"[\"",
"+",
"Strings",
".",
"join",
"(",
"\" | \"",
",",
"pd",
".",
"getParameter",
"(",
")",
".",
"names",
"(",
")",
")",
"+",
"\"]\"",
")",
";",
"}",
"String",
"message",
"=",
"Strings",
".",
"join",
"(",
"\", \"",
",",
"missingFields",
")",
";",
"throw",
"new",
"ParameterException",
"(",
"\"The following \"",
"+",
"pluralize",
"(",
"requiredFields",
".",
"size",
"(",
")",
",",
"\"option is required: \"",
",",
"\"options are required: \"",
")",
"+",
"message",
")",
";",
"}",
"if",
"(",
"mainParameter",
"!=",
"null",
"&&",
"mainParameter",
".",
"description",
"!=",
"null",
")",
"{",
"ParameterDescription",
"mainParameterDescription",
"=",
"mainParameter",
".",
"description",
";",
"// Make sure we have a main parameter if it was required",
"if",
"(",
"mainParameterDescription",
".",
"getParameter",
"(",
")",
".",
"required",
"(",
")",
"&&",
"!",
"mainParameterDescription",
".",
"isAssigned",
"(",
")",
")",
"{",
"throw",
"new",
"ParameterException",
"(",
"\"Main parameters are required (\\\"\"",
"+",
"mainParameterDescription",
".",
"getDescription",
"(",
")",
"+",
"\"\\\")\"",
")",
";",
"}",
"// If the main parameter has an arity, make sure the correct number of parameters was passed",
"int",
"arity",
"=",
"mainParameterDescription",
".",
"getParameter",
"(",
")",
".",
"arity",
"(",
")",
";",
"if",
"(",
"arity",
"!=",
"Parameter",
".",
"DEFAULT_ARITY",
")",
"{",
"Object",
"value",
"=",
"mainParameterDescription",
".",
"getParameterized",
"(",
")",
".",
"get",
"(",
"mainParameter",
".",
"object",
")",
";",
"if",
"(",
"List",
".",
"class",
".",
"isAssignableFrom",
"(",
"value",
".",
"getClass",
"(",
")",
")",
")",
"{",
"int",
"size",
"=",
"(",
"(",
"List",
"<",
"?",
">",
")",
"value",
")",
".",
"size",
"(",
")",
";",
"if",
"(",
"size",
"!=",
"arity",
")",
"{",
"throw",
"new",
"ParameterException",
"(",
"\"There should be exactly \"",
"+",
"arity",
"+",
"\" main parameters but \"",
"+",
"size",
"+",
"\" were found\"",
")",
";",
"}",
"}",
"}",
"}",
"}"
] | Make sure that all the required parameters have received a value. | [
"Make",
"sure",
"that",
"all",
"the",
"required",
"parameters",
"have",
"received",
"a",
"value",
"."
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/JCommander.java#L375-L415 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/JCommander.java | JCommander.readFile | private List<String> readFile(String fileName) {
List<String> result = Lists.newArrayList();
try (BufferedReader bufRead = Files.newBufferedReader(Paths.get(fileName), options.atFileCharset)) {
String line;
// Read through file one line at time. Print line # and line
while ((line = bufRead.readLine()) != null) {
// Allow empty lines and # comments in these at files
if (line.length() > 0 && !line.trim().startsWith("#")) {
result.add(line);
}
}
} catch (IOException e) {
throw new ParameterException("Could not read file " + fileName + ": " + e);
}
return result;
} | java | private List<String> readFile(String fileName) {
List<String> result = Lists.newArrayList();
try (BufferedReader bufRead = Files.newBufferedReader(Paths.get(fileName), options.atFileCharset)) {
String line;
// Read through file one line at time. Print line # and line
while ((line = bufRead.readLine()) != null) {
// Allow empty lines and # comments in these at files
if (line.length() > 0 && !line.trim().startsWith("#")) {
result.add(line);
}
}
} catch (IOException e) {
throw new ParameterException("Could not read file " + fileName + ": " + e);
}
return result;
} | [
"private",
"List",
"<",
"String",
">",
"readFile",
"(",
"String",
"fileName",
")",
"{",
"List",
"<",
"String",
">",
"result",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"try",
"(",
"BufferedReader",
"bufRead",
"=",
"Files",
".",
"newBufferedReader",
"(",
"Paths",
".",
"get",
"(",
"fileName",
")",
",",
"options",
".",
"atFileCharset",
")",
")",
"{",
"String",
"line",
";",
"// Read through file one line at time. Print line # and line",
"while",
"(",
"(",
"line",
"=",
"bufRead",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"// Allow empty lines and # comments in these at files",
"if",
"(",
"line",
".",
"length",
"(",
")",
">",
"0",
"&&",
"!",
"line",
".",
"trim",
"(",
")",
".",
"startsWith",
"(",
"\"#\"",
")",
")",
"{",
"result",
".",
"add",
"(",
"line",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"ParameterException",
"(",
"\"Could not read file \"",
"+",
"fileName",
"+",
"\": \"",
"+",
"e",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Reads the file specified by filename and returns the file content as a string.
End of lines are replaced by a space.
@param fileName the command line filename
@return the file content as a string. | [
"Reads",
"the",
"file",
"specified",
"by",
"filename",
"and",
"returns",
"the",
"file",
"content",
"as",
"a",
"string",
".",
"End",
"of",
"lines",
"are",
"replaced",
"by",
"a",
"space",
"."
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/JCommander.java#L557-L574 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/JCommander.java | JCommander.trim | private static String trim(String string) {
String result = string.trim();
if (result.startsWith("\"") && result.endsWith("\"") && result.length() > 1) {
result = result.substring(1, result.length() - 1);
}
return result;
} | java | private static String trim(String string) {
String result = string.trim();
if (result.startsWith("\"") && result.endsWith("\"") && result.length() > 1) {
result = result.substring(1, result.length() - 1);
}
return result;
} | [
"private",
"static",
"String",
"trim",
"(",
"String",
"string",
")",
"{",
"String",
"result",
"=",
"string",
".",
"trim",
"(",
")",
";",
"if",
"(",
"result",
".",
"startsWith",
"(",
"\"\\\"\"",
")",
"&&",
"result",
".",
"endsWith",
"(",
"\"\\\"\"",
")",
"&&",
"result",
".",
"length",
"(",
")",
">",
"1",
")",
"{",
"result",
"=",
"result",
".",
"substring",
"(",
"1",
",",
"result",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Remove spaces at both ends and handle double quotes. | [
"Remove",
"spaces",
"at",
"both",
"ends",
"and",
"handle",
"double",
"quotes",
"."
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/JCommander.java#L579-L585 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/JCommander.java | JCommander.readPassword | private char[] readPassword(String description, boolean echoInput) {
getConsole().print(description + ": ");
return getConsole().readPassword(echoInput);
} | java | private char[] readPassword(String description, boolean echoInput) {
getConsole().print(description + ": ");
return getConsole().readPassword(echoInput);
} | [
"private",
"char",
"[",
"]",
"readPassword",
"(",
"String",
"description",
",",
"boolean",
"echoInput",
")",
"{",
"getConsole",
"(",
")",
".",
"print",
"(",
"description",
"+",
"\": \"",
")",
";",
"return",
"getConsole",
"(",
")",
".",
"readPassword",
"(",
"echoInput",
")",
";",
"}"
] | Invoke Console.readPassword through reflection to avoid depending
on Java 6. | [
"Invoke",
"Console",
".",
"readPassword",
"through",
"reflection",
"to",
"avoid",
"depending",
"on",
"Java",
"6",
"."
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/JCommander.java#L935-L938 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/JCommander.java | JCommander.setProgramName | public void setProgramName(String name, String... aliases) {
programName = new ProgramName(name, Arrays.asList(aliases));
} | java | public void setProgramName(String name, String... aliases) {
programName = new ProgramName(name, Arrays.asList(aliases));
} | [
"public",
"void",
"setProgramName",
"(",
"String",
"name",
",",
"String",
"...",
"aliases",
")",
"{",
"programName",
"=",
"new",
"ProgramName",
"(",
"name",
",",
"Arrays",
".",
"asList",
"(",
"aliases",
")",
")",
";",
"}"
] | Set the program name
@param name program name
@param aliases aliases to the program name | [
"Set",
"the",
"program",
"name"
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/JCommander.java#L1014-L1016 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/JCommander.java | JCommander.addConverterFactory | public void addConverterFactory(final IStringConverterFactory converterFactory) {
addConverterInstanceFactory(new IStringConverterInstanceFactory() {
@SuppressWarnings("unchecked")
@Override
public IStringConverter<?> getConverterInstance(Parameter parameter, Class<?> forType, String optionName) {
final Class<? extends IStringConverter<?>> converterClass = converterFactory.getConverter(forType);
try {
if(optionName == null) {
optionName = parameter.names().length > 0 ? parameter.names()[0] : "[Main class]";
}
return converterClass != null ? instantiateConverter(optionName, converterClass) : null;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new ParameterException(e);
}
}
});
} | java | public void addConverterFactory(final IStringConverterFactory converterFactory) {
addConverterInstanceFactory(new IStringConverterInstanceFactory() {
@SuppressWarnings("unchecked")
@Override
public IStringConverter<?> getConverterInstance(Parameter parameter, Class<?> forType, String optionName) {
final Class<? extends IStringConverter<?>> converterClass = converterFactory.getConverter(forType);
try {
if(optionName == null) {
optionName = parameter.names().length > 0 ? parameter.names()[0] : "[Main class]";
}
return converterClass != null ? instantiateConverter(optionName, converterClass) : null;
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new ParameterException(e);
}
}
});
} | [
"public",
"void",
"addConverterFactory",
"(",
"final",
"IStringConverterFactory",
"converterFactory",
")",
"{",
"addConverterInstanceFactory",
"(",
"new",
"IStringConverterInstanceFactory",
"(",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"@",
"Override",
"public",
"IStringConverter",
"<",
"?",
">",
"getConverterInstance",
"(",
"Parameter",
"parameter",
",",
"Class",
"<",
"?",
">",
"forType",
",",
"String",
"optionName",
")",
"{",
"final",
"Class",
"<",
"?",
"extends",
"IStringConverter",
"<",
"?",
">",
">",
"converterClass",
"=",
"converterFactory",
".",
"getConverter",
"(",
"forType",
")",
";",
"try",
"{",
"if",
"(",
"optionName",
"==",
"null",
")",
"{",
"optionName",
"=",
"parameter",
".",
"names",
"(",
")",
".",
"length",
">",
"0",
"?",
"parameter",
".",
"names",
"(",
")",
"[",
"0",
"]",
":",
"\"[Main class]\"",
";",
"}",
"return",
"converterClass",
"!=",
"null",
"?",
"instantiateConverter",
"(",
"optionName",
",",
"converterClass",
")",
":",
"null",
";",
"}",
"catch",
"(",
"InstantiationException",
"|",
"IllegalAccessException",
"|",
"InvocationTargetException",
"e",
")",
"{",
"throw",
"new",
"ParameterException",
"(",
"e",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
] | Adds a factory to lookup string converters. The added factory is used prior to previously added factories.
@param converterFactory the factory determining string converters | [
"Adds",
"a",
"factory",
"to",
"lookup",
"string",
"converters",
".",
"The",
"added",
"factory",
"is",
"used",
"prior",
"to",
"previously",
"added",
"factories",
"."
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/JCommander.java#L1254-L1270 | train |
cbeust/jcommander | src/main/java/com/beust/jcommander/JCommander.java | JCommander.addCommand | public void addCommand(String name, Object object, String... aliases) {
JCommander jc = new JCommander(options);
jc.addObject(object);
jc.createDescriptions();
jc.setProgramName(name, aliases);
ProgramName progName = jc.programName;
commands.put(progName, jc);
/*
* Register aliases
*/
//register command name as an alias of itself for reverse lookup
//Note: Name clash check is intentionally omitted to resemble the
// original behaviour of clashing commands.
// Aliases are, however, are strictly checked for name clashes.
aliasMap.put(new StringKey(name), progName);
for (String a : aliases) {
IKey alias = new StringKey(a);
//omit pointless aliases to avoid name clash exception
if (!alias.equals(name)) {
ProgramName mappedName = aliasMap.get(alias);
if (mappedName != null && !mappedName.equals(progName)) {
throw new ParameterException("Cannot set alias " + alias
+ " for " + name
+ " command because it has already been defined for "
+ mappedName.name + " command");
}
aliasMap.put(alias, progName);
}
}
} | java | public void addCommand(String name, Object object, String... aliases) {
JCommander jc = new JCommander(options);
jc.addObject(object);
jc.createDescriptions();
jc.setProgramName(name, aliases);
ProgramName progName = jc.programName;
commands.put(progName, jc);
/*
* Register aliases
*/
//register command name as an alias of itself for reverse lookup
//Note: Name clash check is intentionally omitted to resemble the
// original behaviour of clashing commands.
// Aliases are, however, are strictly checked for name clashes.
aliasMap.put(new StringKey(name), progName);
for (String a : aliases) {
IKey alias = new StringKey(a);
//omit pointless aliases to avoid name clash exception
if (!alias.equals(name)) {
ProgramName mappedName = aliasMap.get(alias);
if (mappedName != null && !mappedName.equals(progName)) {
throw new ParameterException("Cannot set alias " + alias
+ " for " + name
+ " command because it has already been defined for "
+ mappedName.name + " command");
}
aliasMap.put(alias, progName);
}
}
} | [
"public",
"void",
"addCommand",
"(",
"String",
"name",
",",
"Object",
"object",
",",
"String",
"...",
"aliases",
")",
"{",
"JCommander",
"jc",
"=",
"new",
"JCommander",
"(",
"options",
")",
";",
"jc",
".",
"addObject",
"(",
"object",
")",
";",
"jc",
".",
"createDescriptions",
"(",
")",
";",
"jc",
".",
"setProgramName",
"(",
"name",
",",
"aliases",
")",
";",
"ProgramName",
"progName",
"=",
"jc",
".",
"programName",
";",
"commands",
".",
"put",
"(",
"progName",
",",
"jc",
")",
";",
"/*\n * Register aliases\n */",
"//register command name as an alias of itself for reverse lookup",
"//Note: Name clash check is intentionally omitted to resemble the",
"// original behaviour of clashing commands.",
"// Aliases are, however, are strictly checked for name clashes.",
"aliasMap",
".",
"put",
"(",
"new",
"StringKey",
"(",
"name",
")",
",",
"progName",
")",
";",
"for",
"(",
"String",
"a",
":",
"aliases",
")",
"{",
"IKey",
"alias",
"=",
"new",
"StringKey",
"(",
"a",
")",
";",
"//omit pointless aliases to avoid name clash exception",
"if",
"(",
"!",
"alias",
".",
"equals",
"(",
"name",
")",
")",
"{",
"ProgramName",
"mappedName",
"=",
"aliasMap",
".",
"get",
"(",
"alias",
")",
";",
"if",
"(",
"mappedName",
"!=",
"null",
"&&",
"!",
"mappedName",
".",
"equals",
"(",
"progName",
")",
")",
"{",
"throw",
"new",
"ParameterException",
"(",
"\"Cannot set alias \"",
"+",
"alias",
"+",
"\" for \"",
"+",
"name",
"+",
"\" command because it has already been defined for \"",
"+",
"mappedName",
".",
"name",
"+",
"\" command\"",
")",
";",
"}",
"aliasMap",
".",
"put",
"(",
"alias",
",",
"progName",
")",
";",
"}",
"}",
"}"
] | Add a command object and its aliases. | [
"Add",
"a",
"command",
"object",
"and",
"its",
"aliases",
"."
] | 85cb6f7217e15f62225185ffd97491f34b7b49bb | https://github.com/cbeust/jcommander/blob/85cb6f7217e15f62225185ffd97491f34b7b49bb/src/main/java/com/beust/jcommander/JCommander.java#L1391-L1421 | train |
timehop/sticky-headers-recyclerview | library/src/main/java/com/timehop/stickyheadersrecyclerview/HeaderPositionCalculator.java | HeaderPositionCalculator.itemIsObscuredByHeader | private boolean itemIsObscuredByHeader(RecyclerView parent, View item, View header, int orientation) {
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) item.getLayoutParams();
mDimensionCalculator.initMargins(mTempRect1, header);
int adapterPosition = parent.getChildAdapterPosition(item);
if (adapterPosition == RecyclerView.NO_POSITION || mHeaderProvider.getHeader(parent, adapterPosition) != header) {
// Resolves https://github.com/timehop/sticky-headers-recyclerview/issues/36
// Handles an edge case where a trailing header is smaller than the current sticky header.
return false;
}
if (orientation == LinearLayoutManager.VERTICAL) {
int itemTop = item.getTop() - layoutParams.topMargin;
int headerBottom = getListTop(parent) + header.getBottom() + mTempRect1.bottom + mTempRect1.top;
if (itemTop >= headerBottom) {
return false;
}
} else {
int itemLeft = item.getLeft() - layoutParams.leftMargin;
int headerRight = getListLeft(parent) + header.getRight() + mTempRect1.right + mTempRect1.left;
if (itemLeft >= headerRight) {
return false;
}
}
return true;
} | java | private boolean itemIsObscuredByHeader(RecyclerView parent, View item, View header, int orientation) {
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) item.getLayoutParams();
mDimensionCalculator.initMargins(mTempRect1, header);
int adapterPosition = parent.getChildAdapterPosition(item);
if (adapterPosition == RecyclerView.NO_POSITION || mHeaderProvider.getHeader(parent, adapterPosition) != header) {
// Resolves https://github.com/timehop/sticky-headers-recyclerview/issues/36
// Handles an edge case where a trailing header is smaller than the current sticky header.
return false;
}
if (orientation == LinearLayoutManager.VERTICAL) {
int itemTop = item.getTop() - layoutParams.topMargin;
int headerBottom = getListTop(parent) + header.getBottom() + mTempRect1.bottom + mTempRect1.top;
if (itemTop >= headerBottom) {
return false;
}
} else {
int itemLeft = item.getLeft() - layoutParams.leftMargin;
int headerRight = getListLeft(parent) + header.getRight() + mTempRect1.right + mTempRect1.left;
if (itemLeft >= headerRight) {
return false;
}
}
return true;
} | [
"private",
"boolean",
"itemIsObscuredByHeader",
"(",
"RecyclerView",
"parent",
",",
"View",
"item",
",",
"View",
"header",
",",
"int",
"orientation",
")",
"{",
"RecyclerView",
".",
"LayoutParams",
"layoutParams",
"=",
"(",
"RecyclerView",
".",
"LayoutParams",
")",
"item",
".",
"getLayoutParams",
"(",
")",
";",
"mDimensionCalculator",
".",
"initMargins",
"(",
"mTempRect1",
",",
"header",
")",
";",
"int",
"adapterPosition",
"=",
"parent",
".",
"getChildAdapterPosition",
"(",
"item",
")",
";",
"if",
"(",
"adapterPosition",
"==",
"RecyclerView",
".",
"NO_POSITION",
"||",
"mHeaderProvider",
".",
"getHeader",
"(",
"parent",
",",
"adapterPosition",
")",
"!=",
"header",
")",
"{",
"// Resolves https://github.com/timehop/sticky-headers-recyclerview/issues/36",
"// Handles an edge case where a trailing header is smaller than the current sticky header.",
"return",
"false",
";",
"}",
"if",
"(",
"orientation",
"==",
"LinearLayoutManager",
".",
"VERTICAL",
")",
"{",
"int",
"itemTop",
"=",
"item",
".",
"getTop",
"(",
")",
"-",
"layoutParams",
".",
"topMargin",
";",
"int",
"headerBottom",
"=",
"getListTop",
"(",
"parent",
")",
"+",
"header",
".",
"getBottom",
"(",
")",
"+",
"mTempRect1",
".",
"bottom",
"+",
"mTempRect1",
".",
"top",
";",
"if",
"(",
"itemTop",
">=",
"headerBottom",
")",
"{",
"return",
"false",
";",
"}",
"}",
"else",
"{",
"int",
"itemLeft",
"=",
"item",
".",
"getLeft",
"(",
")",
"-",
"layoutParams",
".",
"leftMargin",
";",
"int",
"headerRight",
"=",
"getListLeft",
"(",
"parent",
")",
"+",
"header",
".",
"getRight",
"(",
")",
"+",
"mTempRect1",
".",
"right",
"+",
"mTempRect1",
".",
"left",
";",
"if",
"(",
"itemLeft",
">=",
"headerRight",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}"
] | Determines if an item is obscured by a header
@param parent
@param item to determine if obscured by header
@param header that might be obscuring the item
@param orientation of the {@link RecyclerView}
@return true if the item view is obscured by the header view | [
"Determines",
"if",
"an",
"item",
"is",
"obscured",
"by",
"a",
"header"
] | f5a9e9b8f5d96734e20439b0a41381865fa52fb7 | https://github.com/timehop/sticky-headers-recyclerview/blob/f5a9e9b8f5d96734e20439b0a41381865fa52fb7/library/src/main/java/com/timehop/stickyheadersrecyclerview/HeaderPositionCalculator.java#L218-L244 | train |
timehop/sticky-headers-recyclerview | library/src/main/java/com/timehop/stickyheadersrecyclerview/rendering/HeaderRenderer.java | HeaderRenderer.drawHeader | public void drawHeader(RecyclerView recyclerView, Canvas canvas, View header, Rect offset) {
canvas.save();
if (recyclerView.getLayoutManager().getClipToPadding()) {
// Clip drawing of headers to the padding of the RecyclerView. Avoids drawing in the padding
initClipRectForHeader(mTempRect, recyclerView, header);
canvas.clipRect(mTempRect);
}
canvas.translate(offset.left, offset.top);
header.draw(canvas);
canvas.restore();
} | java | public void drawHeader(RecyclerView recyclerView, Canvas canvas, View header, Rect offset) {
canvas.save();
if (recyclerView.getLayoutManager().getClipToPadding()) {
// Clip drawing of headers to the padding of the RecyclerView. Avoids drawing in the padding
initClipRectForHeader(mTempRect, recyclerView, header);
canvas.clipRect(mTempRect);
}
canvas.translate(offset.left, offset.top);
header.draw(canvas);
canvas.restore();
} | [
"public",
"void",
"drawHeader",
"(",
"RecyclerView",
"recyclerView",
",",
"Canvas",
"canvas",
",",
"View",
"header",
",",
"Rect",
"offset",
")",
"{",
"canvas",
".",
"save",
"(",
")",
";",
"if",
"(",
"recyclerView",
".",
"getLayoutManager",
"(",
")",
".",
"getClipToPadding",
"(",
")",
")",
"{",
"// Clip drawing of headers to the padding of the RecyclerView. Avoids drawing in the padding",
"initClipRectForHeader",
"(",
"mTempRect",
",",
"recyclerView",
",",
"header",
")",
";",
"canvas",
".",
"clipRect",
"(",
"mTempRect",
")",
";",
"}",
"canvas",
".",
"translate",
"(",
"offset",
".",
"left",
",",
"offset",
".",
"top",
")",
";",
"header",
".",
"draw",
"(",
"canvas",
")",
";",
"canvas",
".",
"restore",
"(",
")",
";",
"}"
] | Draws a header to a canvas, offsetting by some x and y amount
@param recyclerView the parent recycler view for drawing the header into
@param canvas the canvas on which to draw the header
@param header the view to draw as the header
@param offset a Rect used to define the x/y offset of the header. Specify x/y offset by setting
the {@link Rect#left} and {@link Rect#top} properties, respectively. | [
"Draws",
"a",
"header",
"to",
"a",
"canvas",
"offsetting",
"by",
"some",
"x",
"and",
"y",
"amount"
] | f5a9e9b8f5d96734e20439b0a41381865fa52fb7 | https://github.com/timehop/sticky-headers-recyclerview/blob/f5a9e9b8f5d96734e20439b0a41381865fa52fb7/library/src/main/java/com/timehop/stickyheadersrecyclerview/rendering/HeaderRenderer.java#L45-L58 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/IanaLinkRelations.java | IanaLinkRelations.isIanaRel | public static boolean isIanaRel(String relation) {
Assert.notNull(relation, "Link relation must not be null!");
return LINK_RELATIONS.stream() //
.anyMatch(it -> it.value().equalsIgnoreCase(relation));
} | java | public static boolean isIanaRel(String relation) {
Assert.notNull(relation, "Link relation must not be null!");
return LINK_RELATIONS.stream() //
.anyMatch(it -> it.value().equalsIgnoreCase(relation));
} | [
"public",
"static",
"boolean",
"isIanaRel",
"(",
"String",
"relation",
")",
"{",
"Assert",
".",
"notNull",
"(",
"relation",
",",
"\"Link relation must not be null!\"",
")",
";",
"return",
"LINK_RELATIONS",
".",
"stream",
"(",
")",
"//",
".",
"anyMatch",
"(",
"it",
"->",
"it",
".",
"value",
"(",
")",
".",
"equalsIgnoreCase",
"(",
"relation",
")",
")",
";",
"}"
] | Is this relation an IANA standard? Per RFC 8288, parsing of link relations is case insensitive.
@param relation must not be {@literal null}.
@return boolean | [
"Is",
"this",
"relation",
"an",
"IANA",
"standard?",
"Per",
"RFC",
"8288",
"parsing",
"of",
"link",
"relations",
"is",
"case",
"insensitive",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/IanaLinkRelations.java#L771-L777 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/server/core/MethodParameters.java | MethodParameters.getParametersOfType | public List<MethodParameter> getParametersOfType(Class<?> type) {
Assert.notNull(type, "Type must not be null!");
return getParameters().stream() //
.filter(it -> it.getParameterType().equals(type)) //
.collect(Collectors.toList());
} | java | public List<MethodParameter> getParametersOfType(Class<?> type) {
Assert.notNull(type, "Type must not be null!");
return getParameters().stream() //
.filter(it -> it.getParameterType().equals(type)) //
.collect(Collectors.toList());
} | [
"public",
"List",
"<",
"MethodParameter",
">",
"getParametersOfType",
"(",
"Class",
"<",
"?",
">",
"type",
")",
"{",
"Assert",
".",
"notNull",
"(",
"type",
",",
"\"Type must not be null!\"",
")",
";",
"return",
"getParameters",
"(",
")",
".",
"stream",
"(",
")",
"//",
".",
"filter",
"(",
"it",
"->",
"it",
".",
"getParameterType",
"(",
")",
".",
"equals",
"(",
"type",
")",
")",
"//",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
";",
"}"
] | Returns all parameters of the given type.
@param type must not be {@literal null}.
@return
@since 0.9 | [
"Returns",
"all",
"parameters",
"of",
"the",
"given",
"type",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/core/MethodParameters.java#L117-L124 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/UriTemplate.java | UriTemplate.isTemplate | public static boolean isTemplate(String candidate) {
return StringUtils.hasText(candidate) //
? VARIABLE_REGEX.matcher(candidate).find()
: false;
} | java | public static boolean isTemplate(String candidate) {
return StringUtils.hasText(candidate) //
? VARIABLE_REGEX.matcher(candidate).find()
: false;
} | [
"public",
"static",
"boolean",
"isTemplate",
"(",
"String",
"candidate",
")",
"{",
"return",
"StringUtils",
".",
"hasText",
"(",
"candidate",
")",
"//",
"?",
"VARIABLE_REGEX",
".",
"matcher",
"(",
"candidate",
")",
".",
"find",
"(",
")",
":",
"false",
";",
"}"
] | Returns whether the given candidate is a URI template.
@param candidate
@return | [
"Returns",
"whether",
"the",
"given",
"candidate",
"is",
"a",
"URI",
"template",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/UriTemplate.java#L192-L197 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/UriTemplate.java | UriTemplate.getVariableNames | public List<String> getVariableNames() {
return variables.asList().stream() //
.map(TemplateVariable::getName) //
.collect(Collectors.toList());
} | java | public List<String> getVariableNames() {
return variables.asList().stream() //
.map(TemplateVariable::getName) //
.collect(Collectors.toList());
} | [
"public",
"List",
"<",
"String",
">",
"getVariableNames",
"(",
")",
"{",
"return",
"variables",
".",
"asList",
"(",
")",
".",
"stream",
"(",
")",
"//",
".",
"map",
"(",
"TemplateVariable",
"::",
"getName",
")",
"//",
".",
"collect",
"(",
"Collectors",
".",
"toList",
"(",
")",
")",
";",
"}"
] | Returns the names of the variables discovered.
@return | [
"Returns",
"the",
"names",
"of",
"the",
"variables",
"discovered",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/UriTemplate.java#L213-L218 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/server/core/AnnotationMappingDiscoverer.java | AnnotationMappingDiscoverer.join | private static String join(String typeMapping, String mapping) {
return MULTIPLE_SLASHES.matcher(typeMapping.concat("/").concat(mapping)).replaceAll("/");
} | java | private static String join(String typeMapping, String mapping) {
return MULTIPLE_SLASHES.matcher(typeMapping.concat("/").concat(mapping)).replaceAll("/");
} | [
"private",
"static",
"String",
"join",
"(",
"String",
"typeMapping",
",",
"String",
"mapping",
")",
"{",
"return",
"MULTIPLE_SLASHES",
".",
"matcher",
"(",
"typeMapping",
".",
"concat",
"(",
"\"/\"",
")",
".",
"concat",
"(",
"mapping",
")",
")",
".",
"replaceAll",
"(",
"\"/\"",
")",
";",
"}"
] | Joins the given mappings making sure exactly one slash.
@param typeMapping must not be {@literal null} or empty.
@param mapping must not be {@literal null} or empty.
@return | [
"Joins",
"the",
"given",
"mappings",
"making",
"sure",
"exactly",
"one",
"slash",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/core/AnnotationMappingDiscoverer.java#L179-L181 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/server/core/EncodingUtils.java | EncodingUtils.encodePath | public static String encodePath(Object source) {
Assert.notNull(source, "Path value must not be null!");
try {
return UriUtils.encodePath(source.toString(), ENCODING);
} catch (Throwable e) {
throw new IllegalStateException(e);
}
} | java | public static String encodePath(Object source) {
Assert.notNull(source, "Path value must not be null!");
try {
return UriUtils.encodePath(source.toString(), ENCODING);
} catch (Throwable e) {
throw new IllegalStateException(e);
}
} | [
"public",
"static",
"String",
"encodePath",
"(",
"Object",
"source",
")",
"{",
"Assert",
".",
"notNull",
"(",
"source",
",",
"\"Path value must not be null!\"",
")",
";",
"try",
"{",
"return",
"UriUtils",
".",
"encodePath",
"(",
"source",
".",
"toString",
"(",
")",
",",
"ENCODING",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"e",
")",
";",
"}",
"}"
] | Encodes the given path value.
@param source must not be {@literal null}.
@return | [
"Encodes",
"the",
"given",
"path",
"value",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/core/EncodingUtils.java#L42-L51 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/server/core/EncodingUtils.java | EncodingUtils.encodeParameter | public static String encodeParameter(Object source) {
Assert.notNull(source, "Request parameter value must not be null!");
try {
return UriUtils.encodeQueryParam(source.toString(), ENCODING);
} catch (Throwable e) {
throw new IllegalStateException(e);
}
} | java | public static String encodeParameter(Object source) {
Assert.notNull(source, "Request parameter value must not be null!");
try {
return UriUtils.encodeQueryParam(source.toString(), ENCODING);
} catch (Throwable e) {
throw new IllegalStateException(e);
}
} | [
"public",
"static",
"String",
"encodeParameter",
"(",
"Object",
"source",
")",
"{",
"Assert",
".",
"notNull",
"(",
"source",
",",
"\"Request parameter value must not be null!\"",
")",
";",
"try",
"{",
"return",
"UriUtils",
".",
"encodeQueryParam",
"(",
"source",
".",
"toString",
"(",
")",
",",
"ENCODING",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"e",
")",
";",
"}",
"}"
] | Encodes the given request parameter value.
@param source must not be {@literal null}.
@return | [
"Encodes",
"the",
"given",
"request",
"parameter",
"value",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/core/EncodingUtils.java#L59-L68 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/server/mvc/RepresentationModelAssemblerSupport.java | RepresentationModelAssemblerSupport.createModelWithId | protected D createModelWithId(Object id, T entity) {
return createModelWithId(id, entity, new Object[0]);
} | java | protected D createModelWithId(Object id, T entity) {
return createModelWithId(id, entity, new Object[0]);
} | [
"protected",
"D",
"createModelWithId",
"(",
"Object",
"id",
",",
"T",
"entity",
")",
"{",
"return",
"createModelWithId",
"(",
"id",
",",
"entity",
",",
"new",
"Object",
"[",
"0",
"]",
")",
";",
"}"
] | Creates a new resource with a self link to the given id.
@param entity must not be {@literal null}.
@param id must not be {@literal null}.
@return | [
"Creates",
"a",
"new",
"resource",
"with",
"a",
"self",
"link",
"to",
"the",
"given",
"id",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/mvc/RepresentationModelAssemblerSupport.java#L78-L80 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsSerializers.java | HalFormsSerializers.validate | private static void validate(RepresentationModel<?> resource, HalFormsAffordanceModel model) {
String affordanceUri = model.getURI();
String selfLinkUri = resource.getRequiredLink(IanaLinkRelations.SELF.value()).expand().getHref();
if (!affordanceUri.equals(selfLinkUri)) {
throw new IllegalStateException("Affordance's URI " + affordanceUri + " doesn't match self link " + selfLinkUri
+ " as expected in HAL-FORMS");
}
} | java | private static void validate(RepresentationModel<?> resource, HalFormsAffordanceModel model) {
String affordanceUri = model.getURI();
String selfLinkUri = resource.getRequiredLink(IanaLinkRelations.SELF.value()).expand().getHref();
if (!affordanceUri.equals(selfLinkUri)) {
throw new IllegalStateException("Affordance's URI " + affordanceUri + " doesn't match self link " + selfLinkUri
+ " as expected in HAL-FORMS");
}
} | [
"private",
"static",
"void",
"validate",
"(",
"RepresentationModel",
"<",
"?",
">",
"resource",
",",
"HalFormsAffordanceModel",
"model",
")",
"{",
"String",
"affordanceUri",
"=",
"model",
".",
"getURI",
"(",
")",
";",
"String",
"selfLinkUri",
"=",
"resource",
".",
"getRequiredLink",
"(",
"IanaLinkRelations",
".",
"SELF",
".",
"value",
"(",
")",
")",
".",
"expand",
"(",
")",
".",
"getHref",
"(",
")",
";",
"if",
"(",
"!",
"affordanceUri",
".",
"equals",
"(",
"selfLinkUri",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Affordance's URI \"",
"+",
"affordanceUri",
"+",
"\" doesn't match self link \"",
"+",
"selfLinkUri",
"+",
"\" as expected in HAL-FORMS\"",
")",
";",
"}",
"}"
] | Verify that the resource's self link and the affordance's URI have the same relative path.
@param resource
@param model | [
"Verify",
"that",
"the",
"resource",
"s",
"self",
"link",
"and",
"the",
"affordance",
"s",
"URI",
"have",
"the",
"same",
"relative",
"path",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsSerializers.java#L289-L298 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/client/Hop.java | Hop.withParameter | public Hop withParameter(String name, Object value) {
Assert.hasText(name, "Name must not be null or empty!");
HashMap<String, Object> parameters = new HashMap<>(this.parameters);
parameters.put(name, value);
return new Hop(this.rel, parameters, this.headers);
} | java | public Hop withParameter(String name, Object value) {
Assert.hasText(name, "Name must not be null or empty!");
HashMap<String, Object> parameters = new HashMap<>(this.parameters);
parameters.put(name, value);
return new Hop(this.rel, parameters, this.headers);
} | [
"public",
"Hop",
"withParameter",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"Assert",
".",
"hasText",
"(",
"name",
",",
"\"Name must not be null or empty!\"",
")",
";",
"HashMap",
"<",
"String",
",",
"Object",
">",
"parameters",
"=",
"new",
"HashMap",
"<>",
"(",
"this",
".",
"parameters",
")",
";",
"parameters",
".",
"put",
"(",
"name",
",",
"value",
")",
";",
"return",
"new",
"Hop",
"(",
"this",
".",
"rel",
",",
"parameters",
",",
"this",
".",
"headers",
")",
";",
"}"
] | Add one parameter to the map of parameters.
@param name must not be {@literal null} or empty.
@param value can be {@literal null}.
@return | [
"Add",
"one",
"parameter",
"to",
"the",
"map",
"of",
"parameters",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/client/Hop.java#L79-L87 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/client/Hop.java | Hop.header | public Hop header(String headerName, String headerValue) {
Assert.hasText(headerName, "headerName must not be null or empty!");
if (this.headers == HttpHeaders.EMPTY) {
HttpHeaders newHeaders = new HttpHeaders();
newHeaders.add(headerName, headerValue);
return new Hop(this.rel, this.parameters, newHeaders);
}
this.headers.add(headerName, headerValue);
return this;
} | java | public Hop header(String headerName, String headerValue) {
Assert.hasText(headerName, "headerName must not be null or empty!");
if (this.headers == HttpHeaders.EMPTY) {
HttpHeaders newHeaders = new HttpHeaders();
newHeaders.add(headerName, headerValue);
return new Hop(this.rel, this.parameters, newHeaders);
}
this.headers.add(headerName, headerValue);
return this;
} | [
"public",
"Hop",
"header",
"(",
"String",
"headerName",
",",
"String",
"headerValue",
")",
"{",
"Assert",
".",
"hasText",
"(",
"headerName",
",",
"\"headerName must not be null or empty!\"",
")",
";",
"if",
"(",
"this",
".",
"headers",
"==",
"HttpHeaders",
".",
"EMPTY",
")",
"{",
"HttpHeaders",
"newHeaders",
"=",
"new",
"HttpHeaders",
"(",
")",
";",
"newHeaders",
".",
"add",
"(",
"headerName",
",",
"headerValue",
")",
";",
"return",
"new",
"Hop",
"(",
"this",
".",
"rel",
",",
"this",
".",
"parameters",
",",
"newHeaders",
")",
";",
"}",
"this",
".",
"headers",
".",
"add",
"(",
"headerName",
",",
"headerValue",
")",
";",
"return",
"this",
";",
"}"
] | Add one header to the HttpHeaders collection.
@param headerName must not be {@literal null} or empty.
@param headerValue can be {@literal null}.
@return | [
"Add",
"one",
"header",
"to",
"the",
"HttpHeaders",
"collection",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/client/Hop.java#L96-L110 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/mediatype/uber/UberData.java | UberData.doExtractLinksAndContent | private static List<UberData> doExtractLinksAndContent(Object item) {
if (item instanceof EntityModel) {
return extractLinksAndContent((EntityModel<?>) item);
}
if (item instanceof RepresentationModel) {
return extractLinksAndContent((RepresentationModel<?>) item);
}
return extractLinksAndContent(new EntityModel<>(item));
} | java | private static List<UberData> doExtractLinksAndContent(Object item) {
if (item instanceof EntityModel) {
return extractLinksAndContent((EntityModel<?>) item);
}
if (item instanceof RepresentationModel) {
return extractLinksAndContent((RepresentationModel<?>) item);
}
return extractLinksAndContent(new EntityModel<>(item));
} | [
"private",
"static",
"List",
"<",
"UberData",
">",
"doExtractLinksAndContent",
"(",
"Object",
"item",
")",
"{",
"if",
"(",
"item",
"instanceof",
"EntityModel",
")",
"{",
"return",
"extractLinksAndContent",
"(",
"(",
"EntityModel",
"<",
"?",
">",
")",
"item",
")",
";",
"}",
"if",
"(",
"item",
"instanceof",
"RepresentationModel",
")",
"{",
"return",
"extractLinksAndContent",
"(",
"(",
"RepresentationModel",
"<",
"?",
">",
")",
"item",
")",
";",
"}",
"return",
"extractLinksAndContent",
"(",
"new",
"EntityModel",
"<>",
"(",
"item",
")",
")",
";",
"}"
] | Extract links and content from an object of any type. | [
"Extract",
"links",
"and",
"content",
"from",
"an",
"object",
"of",
"any",
"type",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/mediatype/uber/UberData.java#L279-L290 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsDocument.java | HalFormsDocument.getTemplate | @JsonIgnore
public HalFormsTemplate getTemplate(String key) {
Assert.notNull(key, "Template key must not be null!");
return this.templates.get(key);
} | java | @JsonIgnore
public HalFormsTemplate getTemplate(String key) {
Assert.notNull(key, "Template key must not be null!");
return this.templates.get(key);
} | [
"@",
"JsonIgnore",
"public",
"HalFormsTemplate",
"getTemplate",
"(",
"String",
"key",
")",
"{",
"Assert",
".",
"notNull",
"(",
"key",
",",
"\"Template key must not be null!\"",
")",
";",
"return",
"this",
".",
"templates",
".",
"get",
"(",
"key",
")",
";",
"}"
] | Returns the template with the given name.
@param key must not be {@literal null}.
@return | [
"Returns",
"the",
"template",
"with",
"the",
"given",
"name",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsDocument.java#L144-L150 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsDocument.java | HalFormsDocument.andEmbedded | public HalFormsDocument<T> andEmbedded(HalLinkRelation key, Object value) {
Assert.notNull(key, "Embedded key must not be null!");
Assert.notNull(value, "Embedded value must not be null!");
Map<HalLinkRelation, Object> embedded = new HashMap<>(this.embedded);
embedded.put(key, value);
return new HalFormsDocument<>(resource, resources, embedded, pageMetadata, links, templates);
} | java | public HalFormsDocument<T> andEmbedded(HalLinkRelation key, Object value) {
Assert.notNull(key, "Embedded key must not be null!");
Assert.notNull(value, "Embedded value must not be null!");
Map<HalLinkRelation, Object> embedded = new HashMap<>(this.embedded);
embedded.put(key, value);
return new HalFormsDocument<>(resource, resources, embedded, pageMetadata, links, templates);
} | [
"public",
"HalFormsDocument",
"<",
"T",
">",
"andEmbedded",
"(",
"HalLinkRelation",
"key",
",",
"Object",
"value",
")",
"{",
"Assert",
".",
"notNull",
"(",
"key",
",",
"\"Embedded key must not be null!\"",
")",
";",
"Assert",
".",
"notNull",
"(",
"value",
",",
"\"Embedded value must not be null!\"",
")",
";",
"Map",
"<",
"HalLinkRelation",
",",
"Object",
">",
"embedded",
"=",
"new",
"HashMap",
"<>",
"(",
"this",
".",
"embedded",
")",
";",
"embedded",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"new",
"HalFormsDocument",
"<>",
"(",
"resource",
",",
"resources",
",",
"embedded",
",",
"pageMetadata",
",",
"links",
",",
"templates",
")",
";",
"}"
] | Adds the given value as embedded one.
@param key must not be {@literal null} or empty.
@param value must not be {@literal null}.
@return | [
"Adds",
"the",
"given",
"value",
"as",
"embedded",
"one",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/mediatype/hal/forms/HalFormsDocument.java#L198-L207 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonItem.java | CollectionJsonItem.toRawData | @Nullable
public Object toRawData(JavaType javaType) {
if (this.data.isEmpty()) {
return null;
}
if (PRIMITIVE_TYPES.contains(javaType.getRawClass())) {
return this.data.get(0).getValue();
}
return PropertyUtils.createObjectFromProperties(javaType.getRawClass(), //
this.data.stream().collect(Collectors.toMap(CollectionJsonData::getName, CollectionJsonData::getValue)));
} | java | @Nullable
public Object toRawData(JavaType javaType) {
if (this.data.isEmpty()) {
return null;
}
if (PRIMITIVE_TYPES.contains(javaType.getRawClass())) {
return this.data.get(0).getValue();
}
return PropertyUtils.createObjectFromProperties(javaType.getRawClass(), //
this.data.stream().collect(Collectors.toMap(CollectionJsonData::getName, CollectionJsonData::getValue)));
} | [
"@",
"Nullable",
"public",
"Object",
"toRawData",
"(",
"JavaType",
"javaType",
")",
"{",
"if",
"(",
"this",
".",
"data",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"PRIMITIVE_TYPES",
".",
"contains",
"(",
"javaType",
".",
"getRawClass",
"(",
")",
")",
")",
"{",
"return",
"this",
".",
"data",
".",
"get",
"(",
"0",
")",
".",
"getValue",
"(",
")",
";",
"}",
"return",
"PropertyUtils",
".",
"createObjectFromProperties",
"(",
"javaType",
".",
"getRawClass",
"(",
")",
",",
"//",
"this",
".",
"data",
".",
"stream",
"(",
")",
".",
"collect",
"(",
"Collectors",
".",
"toMap",
"(",
"CollectionJsonData",
"::",
"getName",
",",
"CollectionJsonData",
"::",
"getValue",
")",
")",
")",
";",
"}"
] | Generate an object used the deserialized properties and the provided type from the deserializer.
@param javaType - type of the object to create
@return | [
"Generate",
"an",
"object",
"used",
"the",
"deserialized",
"properties",
"and",
"the",
"provided",
"type",
"from",
"the",
"deserializer",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/mediatype/collectionjson/CollectionJsonItem.java#L105-L118 | train |
spring-projects/spring-hateoas | src/main/java/org/springframework/hateoas/RepresentationModel.java | RepresentationModel.add | @SuppressWarnings("unchecked")
public T add(Link link) {
Assert.notNull(link, "Link must not be null!");
this.links.add(link);
return (T) this;
} | java | @SuppressWarnings("unchecked")
public T add(Link link) {
Assert.notNull(link, "Link must not be null!");
this.links.add(link);
return (T) this;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"T",
"add",
"(",
"Link",
"link",
")",
"{",
"Assert",
".",
"notNull",
"(",
"link",
",",
"\"Link must not be null!\"",
")",
";",
"this",
".",
"links",
".",
"add",
"(",
"link",
")",
";",
"return",
"(",
"T",
")",
"this",
";",
"}"
] | Adds the given link to the resource.
@param link | [
"Adds",
"the",
"given",
"link",
"to",
"the",
"resource",
"."
] | 70ebff9309f086cd8d6a97daf67e0dc215c87d9c | https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/RepresentationModel.java#L65-L73 | train |
datastax/java-driver | examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonColumn.java | JacksonJsonColumn.insertJsonColumn | private static void insertJsonColumn(CqlSession session) {
User alice = new User("alice", 30);
User bob = new User("bob", 35);
// Build and execute a simple statement
Statement stmt =
insertInto("examples", "json_jackson_column")
.value("id", literal(1))
// the User object will be converted into a String and persisted into the VARCHAR column
// "json"
.value("json", literal(alice, session.getContext().getCodecRegistry()))
.build();
session.execute(stmt);
// The JSON object can be a bound value if the statement is prepared
// (subsequent calls to the prepare() method will return cached statement)
PreparedStatement pst =
session.prepare(
insertInto("examples", "json_jackson_column")
.value("id", bindMarker("id"))
.value("json", bindMarker("json"))
.build());
session.execute(pst.bind().setInt("id", 2).set("json", bob, User.class));
} | java | private static void insertJsonColumn(CqlSession session) {
User alice = new User("alice", 30);
User bob = new User("bob", 35);
// Build and execute a simple statement
Statement stmt =
insertInto("examples", "json_jackson_column")
.value("id", literal(1))
// the User object will be converted into a String and persisted into the VARCHAR column
// "json"
.value("json", literal(alice, session.getContext().getCodecRegistry()))
.build();
session.execute(stmt);
// The JSON object can be a bound value if the statement is prepared
// (subsequent calls to the prepare() method will return cached statement)
PreparedStatement pst =
session.prepare(
insertInto("examples", "json_jackson_column")
.value("id", bindMarker("id"))
.value("json", bindMarker("json"))
.build());
session.execute(pst.bind().setInt("id", 2).set("json", bob, User.class));
} | [
"private",
"static",
"void",
"insertJsonColumn",
"(",
"CqlSession",
"session",
")",
"{",
"User",
"alice",
"=",
"new",
"User",
"(",
"\"alice\"",
",",
"30",
")",
";",
"User",
"bob",
"=",
"new",
"User",
"(",
"\"bob\"",
",",
"35",
")",
";",
"// Build and execute a simple statement",
"Statement",
"stmt",
"=",
"insertInto",
"(",
"\"examples\"",
",",
"\"json_jackson_column\"",
")",
".",
"value",
"(",
"\"id\"",
",",
"literal",
"(",
"1",
")",
")",
"// the User object will be converted into a String and persisted into the VARCHAR column",
"// \"json\"",
".",
"value",
"(",
"\"json\"",
",",
"literal",
"(",
"alice",
",",
"session",
".",
"getContext",
"(",
")",
".",
"getCodecRegistry",
"(",
")",
")",
")",
".",
"build",
"(",
")",
";",
"session",
".",
"execute",
"(",
"stmt",
")",
";",
"// The JSON object can be a bound value if the statement is prepared",
"// (subsequent calls to the prepare() method will return cached statement)",
"PreparedStatement",
"pst",
"=",
"session",
".",
"prepare",
"(",
"insertInto",
"(",
"\"examples\"",
",",
"\"json_jackson_column\"",
")",
".",
"value",
"(",
"\"id\"",
",",
"bindMarker",
"(",
"\"id\"",
")",
")",
".",
"value",
"(",
"\"json\"",
",",
"bindMarker",
"(",
"\"json\"",
")",
")",
".",
"build",
"(",
")",
")",
";",
"session",
".",
"execute",
"(",
"pst",
".",
"bind",
"(",
")",
".",
"setInt",
"(",
"\"id\"",
",",
"2",
")",
".",
"set",
"(",
"\"json\"",
",",
"bob",
",",
"User",
".",
"class",
")",
")",
";",
"}"
] | Mapping a User instance to a table column | [
"Mapping",
"a",
"User",
"instance",
"to",
"a",
"table",
"column"
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonColumn.java#L93-L118 | train |
datastax/java-driver | examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonColumn.java | JacksonJsonColumn.selectJsonColumn | private static void selectJsonColumn(CqlSession session) {
Statement stmt =
selectFrom("examples", "json_jackson_column")
.all()
.whereColumn("id")
.in(literal(1), literal(2))
.build();
ResultSet rows = session.execute(stmt);
for (Row row : rows) {
int id = row.getInt("id");
// retrieve the JSON payload and convert it to a User instance
User user = row.get("json", User.class);
// it is also possible to retrieve the raw JSON payload
String json = row.getString("json");
System.out.printf(
"Retrieved row:%n id %d%n user %s%n user (raw) %s%n%n",
id, user, json);
}
} | java | private static void selectJsonColumn(CqlSession session) {
Statement stmt =
selectFrom("examples", "json_jackson_column")
.all()
.whereColumn("id")
.in(literal(1), literal(2))
.build();
ResultSet rows = session.execute(stmt);
for (Row row : rows) {
int id = row.getInt("id");
// retrieve the JSON payload and convert it to a User instance
User user = row.get("json", User.class);
// it is also possible to retrieve the raw JSON payload
String json = row.getString("json");
System.out.printf(
"Retrieved row:%n id %d%n user %s%n user (raw) %s%n%n",
id, user, json);
}
} | [
"private",
"static",
"void",
"selectJsonColumn",
"(",
"CqlSession",
"session",
")",
"{",
"Statement",
"stmt",
"=",
"selectFrom",
"(",
"\"examples\"",
",",
"\"json_jackson_column\"",
")",
".",
"all",
"(",
")",
".",
"whereColumn",
"(",
"\"id\"",
")",
".",
"in",
"(",
"literal",
"(",
"1",
")",
",",
"literal",
"(",
"2",
")",
")",
".",
"build",
"(",
")",
";",
"ResultSet",
"rows",
"=",
"session",
".",
"execute",
"(",
"stmt",
")",
";",
"for",
"(",
"Row",
"row",
":",
"rows",
")",
"{",
"int",
"id",
"=",
"row",
".",
"getInt",
"(",
"\"id\"",
")",
";",
"// retrieve the JSON payload and convert it to a User instance",
"User",
"user",
"=",
"row",
".",
"get",
"(",
"\"json\"",
",",
"User",
".",
"class",
")",
";",
"// it is also possible to retrieve the raw JSON payload",
"String",
"json",
"=",
"row",
".",
"getString",
"(",
"\"json\"",
")",
";",
"System",
".",
"out",
".",
"printf",
"(",
"\"Retrieved row:%n id %d%n user %s%n user (raw) %s%n%n\"",
",",
"id",
",",
"user",
",",
"json",
")",
";",
"}",
"}"
] | Retrieving User instances from a table column | [
"Retrieving",
"User",
"instances",
"from",
"a",
"table",
"column"
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/json/jackson/JacksonJsonColumn.java#L121-L142 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/util/ProtocolUtils.java | ProtocolUtils.opcodeString | public static String opcodeString(int opcode) {
switch (opcode) {
case ProtocolConstants.Opcode.ERROR:
return "ERROR";
case ProtocolConstants.Opcode.STARTUP:
return "STARTUP";
case ProtocolConstants.Opcode.READY:
return "READY";
case ProtocolConstants.Opcode.AUTHENTICATE:
return "AUTHENTICATE";
case ProtocolConstants.Opcode.OPTIONS:
return "OPTIONS";
case ProtocolConstants.Opcode.SUPPORTED:
return "SUPPORTED";
case ProtocolConstants.Opcode.QUERY:
return "QUERY";
case ProtocolConstants.Opcode.RESULT:
return "RESULT";
case ProtocolConstants.Opcode.PREPARE:
return "PREPARE";
case ProtocolConstants.Opcode.EXECUTE:
return "EXECUTE";
case ProtocolConstants.Opcode.REGISTER:
return "REGISTER";
case ProtocolConstants.Opcode.EVENT:
return "EVENT";
case ProtocolConstants.Opcode.BATCH:
return "BATCH";
case ProtocolConstants.Opcode.AUTH_CHALLENGE:
return "AUTH_CHALLENGE";
case ProtocolConstants.Opcode.AUTH_RESPONSE:
return "AUTH_RESPONSE";
case ProtocolConstants.Opcode.AUTH_SUCCESS:
return "AUTH_SUCCESS";
default:
return "0x" + Integer.toHexString(opcode);
}
} | java | public static String opcodeString(int opcode) {
switch (opcode) {
case ProtocolConstants.Opcode.ERROR:
return "ERROR";
case ProtocolConstants.Opcode.STARTUP:
return "STARTUP";
case ProtocolConstants.Opcode.READY:
return "READY";
case ProtocolConstants.Opcode.AUTHENTICATE:
return "AUTHENTICATE";
case ProtocolConstants.Opcode.OPTIONS:
return "OPTIONS";
case ProtocolConstants.Opcode.SUPPORTED:
return "SUPPORTED";
case ProtocolConstants.Opcode.QUERY:
return "QUERY";
case ProtocolConstants.Opcode.RESULT:
return "RESULT";
case ProtocolConstants.Opcode.PREPARE:
return "PREPARE";
case ProtocolConstants.Opcode.EXECUTE:
return "EXECUTE";
case ProtocolConstants.Opcode.REGISTER:
return "REGISTER";
case ProtocolConstants.Opcode.EVENT:
return "EVENT";
case ProtocolConstants.Opcode.BATCH:
return "BATCH";
case ProtocolConstants.Opcode.AUTH_CHALLENGE:
return "AUTH_CHALLENGE";
case ProtocolConstants.Opcode.AUTH_RESPONSE:
return "AUTH_RESPONSE";
case ProtocolConstants.Opcode.AUTH_SUCCESS:
return "AUTH_SUCCESS";
default:
return "0x" + Integer.toHexString(opcode);
}
} | [
"public",
"static",
"String",
"opcodeString",
"(",
"int",
"opcode",
")",
"{",
"switch",
"(",
"opcode",
")",
"{",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"ERROR",
":",
"return",
"\"ERROR\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"STARTUP",
":",
"return",
"\"STARTUP\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"READY",
":",
"return",
"\"READY\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"AUTHENTICATE",
":",
"return",
"\"AUTHENTICATE\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"OPTIONS",
":",
"return",
"\"OPTIONS\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"SUPPORTED",
":",
"return",
"\"SUPPORTED\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"QUERY",
":",
"return",
"\"QUERY\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"RESULT",
":",
"return",
"\"RESULT\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"PREPARE",
":",
"return",
"\"PREPARE\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"EXECUTE",
":",
"return",
"\"EXECUTE\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"REGISTER",
":",
"return",
"\"REGISTER\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"EVENT",
":",
"return",
"\"EVENT\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"BATCH",
":",
"return",
"\"BATCH\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"AUTH_CHALLENGE",
":",
"return",
"\"AUTH_CHALLENGE\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"AUTH_RESPONSE",
":",
"return",
"\"AUTH_RESPONSE\"",
";",
"case",
"ProtocolConstants",
".",
"Opcode",
".",
"AUTH_SUCCESS",
":",
"return",
"\"AUTH_SUCCESS\"",
";",
"default",
":",
"return",
"\"0x\"",
"+",
"Integer",
".",
"toHexString",
"(",
"opcode",
")",
";",
"}",
"}"
] | Formats a message opcode for logs and error messages.
<p>Note that the reason why we don't use enums is because the driver can be extended with
custom opcodes. | [
"Formats",
"a",
"message",
"opcode",
"for",
"logs",
"and",
"error",
"messages",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/ProtocolUtils.java#L27-L64 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/util/ProtocolUtils.java | ProtocolUtils.errorCodeString | public static String errorCodeString(int errorCode) {
switch (errorCode) {
case ProtocolConstants.ErrorCode.SERVER_ERROR:
return "SERVER_ERROR";
case ProtocolConstants.ErrorCode.PROTOCOL_ERROR:
return "PROTOCOL_ERROR";
case ProtocolConstants.ErrorCode.AUTH_ERROR:
return "AUTH_ERROR";
case ProtocolConstants.ErrorCode.UNAVAILABLE:
return "UNAVAILABLE";
case ProtocolConstants.ErrorCode.OVERLOADED:
return "OVERLOADED";
case ProtocolConstants.ErrorCode.IS_BOOTSTRAPPING:
return "IS_BOOTSTRAPPING";
case ProtocolConstants.ErrorCode.TRUNCATE_ERROR:
return "TRUNCATE_ERROR";
case ProtocolConstants.ErrorCode.WRITE_TIMEOUT:
return "WRITE_TIMEOUT";
case ProtocolConstants.ErrorCode.READ_TIMEOUT:
return "READ_TIMEOUT";
case ProtocolConstants.ErrorCode.READ_FAILURE:
return "READ_FAILURE";
case ProtocolConstants.ErrorCode.FUNCTION_FAILURE:
return "FUNCTION_FAILURE";
case ProtocolConstants.ErrorCode.WRITE_FAILURE:
return "WRITE_FAILURE";
case ProtocolConstants.ErrorCode.SYNTAX_ERROR:
return "SYNTAX_ERROR";
case ProtocolConstants.ErrorCode.UNAUTHORIZED:
return "UNAUTHORIZED";
case ProtocolConstants.ErrorCode.INVALID:
return "INVALID";
case ProtocolConstants.ErrorCode.CONFIG_ERROR:
return "CONFIG_ERROR";
case ProtocolConstants.ErrorCode.ALREADY_EXISTS:
return "ALREADY_EXISTS";
case ProtocolConstants.ErrorCode.UNPREPARED:
return "UNPREPARED";
default:
return "0x" + Integer.toHexString(errorCode);
}
} | java | public static String errorCodeString(int errorCode) {
switch (errorCode) {
case ProtocolConstants.ErrorCode.SERVER_ERROR:
return "SERVER_ERROR";
case ProtocolConstants.ErrorCode.PROTOCOL_ERROR:
return "PROTOCOL_ERROR";
case ProtocolConstants.ErrorCode.AUTH_ERROR:
return "AUTH_ERROR";
case ProtocolConstants.ErrorCode.UNAVAILABLE:
return "UNAVAILABLE";
case ProtocolConstants.ErrorCode.OVERLOADED:
return "OVERLOADED";
case ProtocolConstants.ErrorCode.IS_BOOTSTRAPPING:
return "IS_BOOTSTRAPPING";
case ProtocolConstants.ErrorCode.TRUNCATE_ERROR:
return "TRUNCATE_ERROR";
case ProtocolConstants.ErrorCode.WRITE_TIMEOUT:
return "WRITE_TIMEOUT";
case ProtocolConstants.ErrorCode.READ_TIMEOUT:
return "READ_TIMEOUT";
case ProtocolConstants.ErrorCode.READ_FAILURE:
return "READ_FAILURE";
case ProtocolConstants.ErrorCode.FUNCTION_FAILURE:
return "FUNCTION_FAILURE";
case ProtocolConstants.ErrorCode.WRITE_FAILURE:
return "WRITE_FAILURE";
case ProtocolConstants.ErrorCode.SYNTAX_ERROR:
return "SYNTAX_ERROR";
case ProtocolConstants.ErrorCode.UNAUTHORIZED:
return "UNAUTHORIZED";
case ProtocolConstants.ErrorCode.INVALID:
return "INVALID";
case ProtocolConstants.ErrorCode.CONFIG_ERROR:
return "CONFIG_ERROR";
case ProtocolConstants.ErrorCode.ALREADY_EXISTS:
return "ALREADY_EXISTS";
case ProtocolConstants.ErrorCode.UNPREPARED:
return "UNPREPARED";
default:
return "0x" + Integer.toHexString(errorCode);
}
} | [
"public",
"static",
"String",
"errorCodeString",
"(",
"int",
"errorCode",
")",
"{",
"switch",
"(",
"errorCode",
")",
"{",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"SERVER_ERROR",
":",
"return",
"\"SERVER_ERROR\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"PROTOCOL_ERROR",
":",
"return",
"\"PROTOCOL_ERROR\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"AUTH_ERROR",
":",
"return",
"\"AUTH_ERROR\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"UNAVAILABLE",
":",
"return",
"\"UNAVAILABLE\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"OVERLOADED",
":",
"return",
"\"OVERLOADED\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"IS_BOOTSTRAPPING",
":",
"return",
"\"IS_BOOTSTRAPPING\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"TRUNCATE_ERROR",
":",
"return",
"\"TRUNCATE_ERROR\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"WRITE_TIMEOUT",
":",
"return",
"\"WRITE_TIMEOUT\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"READ_TIMEOUT",
":",
"return",
"\"READ_TIMEOUT\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"READ_FAILURE",
":",
"return",
"\"READ_FAILURE\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"FUNCTION_FAILURE",
":",
"return",
"\"FUNCTION_FAILURE\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"WRITE_FAILURE",
":",
"return",
"\"WRITE_FAILURE\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"SYNTAX_ERROR",
":",
"return",
"\"SYNTAX_ERROR\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"UNAUTHORIZED",
":",
"return",
"\"UNAUTHORIZED\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"INVALID",
":",
"return",
"\"INVALID\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"CONFIG_ERROR",
":",
"return",
"\"CONFIG_ERROR\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"ALREADY_EXISTS",
":",
"return",
"\"ALREADY_EXISTS\"",
";",
"case",
"ProtocolConstants",
".",
"ErrorCode",
".",
"UNPREPARED",
":",
"return",
"\"UNPREPARED\"",
";",
"default",
":",
"return",
"\"0x\"",
"+",
"Integer",
".",
"toHexString",
"(",
"errorCode",
")",
";",
"}",
"}"
] | Formats an error code for logs and error messages.
<p>Note that the reason why we don't use enums is because the driver can be extended with
custom codes. | [
"Formats",
"an",
"error",
"code",
"for",
"logs",
"and",
"error",
"messages",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/ProtocolUtils.java#L72-L113 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Reconnection.java | Reconnection.reconnectNow | public void reconnectNow(boolean forceIfStopped) {
assert executor.inEventLoop();
if (state == State.ATTEMPT_IN_PROGRESS || state == State.STOP_AFTER_CURRENT) {
LOG.debug(
"[{}] reconnectNow and current attempt was still running, letting it complete",
logPrefix);
if (state == State.STOP_AFTER_CURRENT) {
// Make sure that we will schedule other attempts if this one fails.
state = State.ATTEMPT_IN_PROGRESS;
}
} else if (state == State.STOPPED && !forceIfStopped) {
LOG.debug("[{}] reconnectNow(false) while stopped, nothing to do", logPrefix);
} else {
assert state == State.SCHEDULED || (state == State.STOPPED && forceIfStopped);
LOG.debug("[{}] Forcing next attempt now", logPrefix);
if (nextAttempt != null) {
nextAttempt.cancel(true);
}
try {
onNextAttemptStarted(reconnectionTask.call());
} catch (Exception e) {
Loggers.warnWithException(
LOG, "[{}] Uncaught error while starting reconnection attempt", logPrefix, e);
scheduleNextAttempt();
}
}
} | java | public void reconnectNow(boolean forceIfStopped) {
assert executor.inEventLoop();
if (state == State.ATTEMPT_IN_PROGRESS || state == State.STOP_AFTER_CURRENT) {
LOG.debug(
"[{}] reconnectNow and current attempt was still running, letting it complete",
logPrefix);
if (state == State.STOP_AFTER_CURRENT) {
// Make sure that we will schedule other attempts if this one fails.
state = State.ATTEMPT_IN_PROGRESS;
}
} else if (state == State.STOPPED && !forceIfStopped) {
LOG.debug("[{}] reconnectNow(false) while stopped, nothing to do", logPrefix);
} else {
assert state == State.SCHEDULED || (state == State.STOPPED && forceIfStopped);
LOG.debug("[{}] Forcing next attempt now", logPrefix);
if (nextAttempt != null) {
nextAttempt.cancel(true);
}
try {
onNextAttemptStarted(reconnectionTask.call());
} catch (Exception e) {
Loggers.warnWithException(
LOG, "[{}] Uncaught error while starting reconnection attempt", logPrefix, e);
scheduleNextAttempt();
}
}
} | [
"public",
"void",
"reconnectNow",
"(",
"boolean",
"forceIfStopped",
")",
"{",
"assert",
"executor",
".",
"inEventLoop",
"(",
")",
";",
"if",
"(",
"state",
"==",
"State",
".",
"ATTEMPT_IN_PROGRESS",
"||",
"state",
"==",
"State",
".",
"STOP_AFTER_CURRENT",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"[{}] reconnectNow and current attempt was still running, letting it complete\"",
",",
"logPrefix",
")",
";",
"if",
"(",
"state",
"==",
"State",
".",
"STOP_AFTER_CURRENT",
")",
"{",
"// Make sure that we will schedule other attempts if this one fails.",
"state",
"=",
"State",
".",
"ATTEMPT_IN_PROGRESS",
";",
"}",
"}",
"else",
"if",
"(",
"state",
"==",
"State",
".",
"STOPPED",
"&&",
"!",
"forceIfStopped",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"[{}] reconnectNow(false) while stopped, nothing to do\"",
",",
"logPrefix",
")",
";",
"}",
"else",
"{",
"assert",
"state",
"==",
"State",
".",
"SCHEDULED",
"||",
"(",
"state",
"==",
"State",
".",
"STOPPED",
"&&",
"forceIfStopped",
")",
";",
"LOG",
".",
"debug",
"(",
"\"[{}] Forcing next attempt now\"",
",",
"logPrefix",
")",
";",
"if",
"(",
"nextAttempt",
"!=",
"null",
")",
"{",
"nextAttempt",
".",
"cancel",
"(",
"true",
")",
";",
"}",
"try",
"{",
"onNextAttemptStarted",
"(",
"reconnectionTask",
".",
"call",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Loggers",
".",
"warnWithException",
"(",
"LOG",
",",
"\"[{}] Uncaught error while starting reconnection attempt\"",
",",
"logPrefix",
",",
"e",
")",
";",
"scheduleNextAttempt",
"(",
")",
";",
"}",
"}",
"}"
] | Forces a reconnection now, without waiting for the next scheduled attempt.
@param forceIfStopped if true and the reconnection is not running, it will get started (meaning
subsequent reconnections will be scheduled if this attempt fails). If false and the
reconnection is not running, no attempt is scheduled. | [
"Forces",
"a",
"reconnection",
"now",
"without",
"waiting",
"for",
"the",
"next",
"scheduled",
"attempt",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Reconnection.java#L130-L156 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Reconnection.java | Reconnection.onNextAttemptStarted | private void onNextAttemptStarted(CompletionStage<Boolean> futureOutcome) {
assert executor.inEventLoop();
state = State.ATTEMPT_IN_PROGRESS;
futureOutcome
.whenCompleteAsync(this::onNextAttemptCompleted, executor)
.exceptionally(UncaughtExceptions::log);
} | java | private void onNextAttemptStarted(CompletionStage<Boolean> futureOutcome) {
assert executor.inEventLoop();
state = State.ATTEMPT_IN_PROGRESS;
futureOutcome
.whenCompleteAsync(this::onNextAttemptCompleted, executor)
.exceptionally(UncaughtExceptions::log);
} | [
"private",
"void",
"onNextAttemptStarted",
"(",
"CompletionStage",
"<",
"Boolean",
">",
"futureOutcome",
")",
"{",
"assert",
"executor",
".",
"inEventLoop",
"(",
")",
";",
"state",
"=",
"State",
".",
"ATTEMPT_IN_PROGRESS",
";",
"futureOutcome",
".",
"whenCompleteAsync",
"(",
"this",
"::",
"onNextAttemptCompleted",
",",
"executor",
")",
".",
"exceptionally",
"(",
"UncaughtExceptions",
"::",
"log",
")",
";",
"}"
] | the CompletableFuture to find out if that succeeded or not. | [
"the",
"CompletableFuture",
"to",
"find",
"out",
"if",
"that",
"succeeded",
"or",
"not",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/Reconnection.java#L210-L216 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CompletableFutures.java | CompletableFutures.getCompleted | public static <T> T getCompleted(CompletionStage<T> stage) {
CompletableFuture<T> future = stage.toCompletableFuture();
Preconditions.checkArgument(future.isDone() && !future.isCompletedExceptionally());
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
// Neither can happen given the precondition
throw new AssertionError("Unexpected error", e);
}
} | java | public static <T> T getCompleted(CompletionStage<T> stage) {
CompletableFuture<T> future = stage.toCompletableFuture();
Preconditions.checkArgument(future.isDone() && !future.isCompletedExceptionally());
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
// Neither can happen given the precondition
throw new AssertionError("Unexpected error", e);
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"getCompleted",
"(",
"CompletionStage",
"<",
"T",
">",
"stage",
")",
"{",
"CompletableFuture",
"<",
"T",
">",
"future",
"=",
"stage",
".",
"toCompletableFuture",
"(",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"future",
".",
"isDone",
"(",
")",
"&&",
"!",
"future",
".",
"isCompletedExceptionally",
"(",
")",
")",
";",
"try",
"{",
"return",
"future",
".",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"|",
"ExecutionException",
"e",
")",
"{",
"// Neither can happen given the precondition",
"throw",
"new",
"AssertionError",
"(",
"\"Unexpected error\"",
",",
"e",
")",
";",
"}",
"}"
] | Get the result now, when we know for sure that the future is complete. | [
"Get",
"the",
"result",
"now",
"when",
"we",
"know",
"for",
"sure",
"that",
"the",
"future",
"is",
"complete",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CompletableFutures.java#L77-L86 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CompletableFutures.java | CompletableFutures.getFailed | public static Throwable getFailed(CompletionStage<?> stage) {
CompletableFuture<?> future = stage.toCompletableFuture();
Preconditions.checkArgument(future.isCompletedExceptionally());
try {
future.get();
throw new AssertionError("future should be failed");
} catch (InterruptedException e) {
throw new AssertionError("Unexpected error", e);
} catch (ExecutionException e) {
return e.getCause();
}
} | java | public static Throwable getFailed(CompletionStage<?> stage) {
CompletableFuture<?> future = stage.toCompletableFuture();
Preconditions.checkArgument(future.isCompletedExceptionally());
try {
future.get();
throw new AssertionError("future should be failed");
} catch (InterruptedException e) {
throw new AssertionError("Unexpected error", e);
} catch (ExecutionException e) {
return e.getCause();
}
} | [
"public",
"static",
"Throwable",
"getFailed",
"(",
"CompletionStage",
"<",
"?",
">",
"stage",
")",
"{",
"CompletableFuture",
"<",
"?",
">",
"future",
"=",
"stage",
".",
"toCompletableFuture",
"(",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"future",
".",
"isCompletedExceptionally",
"(",
")",
")",
";",
"try",
"{",
"future",
".",
"get",
"(",
")",
";",
"throw",
"new",
"AssertionError",
"(",
"\"future should be failed\"",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"throw",
"new",
"AssertionError",
"(",
"\"Unexpected error\"",
",",
"e",
")",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"return",
"e",
".",
"getCause",
"(",
")",
";",
"}",
"}"
] | Get the error now, when we know for sure that the future is failed. | [
"Get",
"the",
"error",
"now",
"when",
"we",
"know",
"for",
"sure",
"that",
"the",
"future",
"is",
"failed",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/concurrent/CompletableFutures.java#L89-L100 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareHandler.java | CqlPrepareHandler.prepareOnOtherNode | private CompletionStage<Void> prepareOnOtherNode(Node node) {
LOG.trace("[{}] Repreparing on {}", logPrefix, node);
DriverChannel channel = session.getChannel(node, logPrefix);
if (channel == null) {
LOG.trace("[{}] Could not get a channel to reprepare on {}, skipping", logPrefix, node);
return CompletableFuture.completedFuture(null);
} else {
ThrottledAdminRequestHandler handler =
new ThrottledAdminRequestHandler(
channel,
message,
request.getCustomPayload(),
timeout,
throttler,
session.getMetricUpdater(),
logPrefix,
message.toString());
return handler
.start()
.handle(
(result, error) -> {
if (error == null) {
LOG.trace("[{}] Successfully reprepared on {}", logPrefix, node);
} else {
Loggers.warnWithException(
LOG, "[{}] Error while repreparing on {}", node, logPrefix, error);
}
return null;
});
}
} | java | private CompletionStage<Void> prepareOnOtherNode(Node node) {
LOG.trace("[{}] Repreparing on {}", logPrefix, node);
DriverChannel channel = session.getChannel(node, logPrefix);
if (channel == null) {
LOG.trace("[{}] Could not get a channel to reprepare on {}, skipping", logPrefix, node);
return CompletableFuture.completedFuture(null);
} else {
ThrottledAdminRequestHandler handler =
new ThrottledAdminRequestHandler(
channel,
message,
request.getCustomPayload(),
timeout,
throttler,
session.getMetricUpdater(),
logPrefix,
message.toString());
return handler
.start()
.handle(
(result, error) -> {
if (error == null) {
LOG.trace("[{}] Successfully reprepared on {}", logPrefix, node);
} else {
Loggers.warnWithException(
LOG, "[{}] Error while repreparing on {}", node, logPrefix, error);
}
return null;
});
}
} | [
"private",
"CompletionStage",
"<",
"Void",
">",
"prepareOnOtherNode",
"(",
"Node",
"node",
")",
"{",
"LOG",
".",
"trace",
"(",
"\"[{}] Repreparing on {}\"",
",",
"logPrefix",
",",
"node",
")",
";",
"DriverChannel",
"channel",
"=",
"session",
".",
"getChannel",
"(",
"node",
",",
"logPrefix",
")",
";",
"if",
"(",
"channel",
"==",
"null",
")",
"{",
"LOG",
".",
"trace",
"(",
"\"[{}] Could not get a channel to reprepare on {}, skipping\"",
",",
"logPrefix",
",",
"node",
")",
";",
"return",
"CompletableFuture",
".",
"completedFuture",
"(",
"null",
")",
";",
"}",
"else",
"{",
"ThrottledAdminRequestHandler",
"handler",
"=",
"new",
"ThrottledAdminRequestHandler",
"(",
"channel",
",",
"message",
",",
"request",
".",
"getCustomPayload",
"(",
")",
",",
"timeout",
",",
"throttler",
",",
"session",
".",
"getMetricUpdater",
"(",
")",
",",
"logPrefix",
",",
"message",
".",
"toString",
"(",
")",
")",
";",
"return",
"handler",
".",
"start",
"(",
")",
".",
"handle",
"(",
"(",
"result",
",",
"error",
")",
"->",
"{",
"if",
"(",
"error",
"==",
"null",
")",
"{",
"LOG",
".",
"trace",
"(",
"\"[{}] Successfully reprepared on {}\"",
",",
"logPrefix",
",",
"node",
")",
";",
"}",
"else",
"{",
"Loggers",
".",
"warnWithException",
"(",
"LOG",
",",
"\"[{}] Error while repreparing on {}\"",
",",
"node",
",",
"logPrefix",
",",
"error",
")",
";",
"}",
"return",
"null",
";",
"}",
")",
";",
"}",
"}"
] | blocking, the preparation will be retried later on that node. Simply warn and move on. | [
"blocking",
"the",
"preparation",
"will",
"be",
"retried",
"later",
"on",
"that",
"node",
".",
"Simply",
"warn",
"and",
"move",
"on",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/cql/CqlPrepareHandler.java#L275-L305 | train |
datastax/java-driver | examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonColumn.java | Jsr353JsonColumn.insertJsonColumn | private static void insertJsonColumn(CqlSession session) {
JsonObject alice = Json.createObjectBuilder().add("name", "alice").add("age", 30).build();
JsonObject bob = Json.createObjectBuilder().add("name", "bob").add("age", 35).build();
// Build and execute a simple statement
Statement stmt =
insertInto("examples", "json_jsr353_column")
.value("id", literal(1))
// the JSON object will be converted into a String and persisted into the VARCHAR column
// "json"
.value("json", literal(alice, session.getContext().getCodecRegistry()))
.build();
session.execute(stmt);
// The JSON object can be a bound value if the statement is prepared
// (subsequent calls to the prepare() method will return cached statement)
PreparedStatement pst =
session.prepare(
insertInto("examples", "json_jsr353_column")
.value("id", bindMarker("id"))
.value("json", bindMarker("json"))
.build());
session.execute(
pst.bind()
.setInt("id", 2)
// note that the codec requires that the type passed to the set() method
// be always JsonStructure, and not a subclass of it, such as JsonObject
.set("json", bob, JsonStructure.class));
} | java | private static void insertJsonColumn(CqlSession session) {
JsonObject alice = Json.createObjectBuilder().add("name", "alice").add("age", 30).build();
JsonObject bob = Json.createObjectBuilder().add("name", "bob").add("age", 35).build();
// Build and execute a simple statement
Statement stmt =
insertInto("examples", "json_jsr353_column")
.value("id", literal(1))
// the JSON object will be converted into a String and persisted into the VARCHAR column
// "json"
.value("json", literal(alice, session.getContext().getCodecRegistry()))
.build();
session.execute(stmt);
// The JSON object can be a bound value if the statement is prepared
// (subsequent calls to the prepare() method will return cached statement)
PreparedStatement pst =
session.prepare(
insertInto("examples", "json_jsr353_column")
.value("id", bindMarker("id"))
.value("json", bindMarker("json"))
.build());
session.execute(
pst.bind()
.setInt("id", 2)
// note that the codec requires that the type passed to the set() method
// be always JsonStructure, and not a subclass of it, such as JsonObject
.set("json", bob, JsonStructure.class));
} | [
"private",
"static",
"void",
"insertJsonColumn",
"(",
"CqlSession",
"session",
")",
"{",
"JsonObject",
"alice",
"=",
"Json",
".",
"createObjectBuilder",
"(",
")",
".",
"add",
"(",
"\"name\"",
",",
"\"alice\"",
")",
".",
"add",
"(",
"\"age\"",
",",
"30",
")",
".",
"build",
"(",
")",
";",
"JsonObject",
"bob",
"=",
"Json",
".",
"createObjectBuilder",
"(",
")",
".",
"add",
"(",
"\"name\"",
",",
"\"bob\"",
")",
".",
"add",
"(",
"\"age\"",
",",
"35",
")",
".",
"build",
"(",
")",
";",
"// Build and execute a simple statement",
"Statement",
"stmt",
"=",
"insertInto",
"(",
"\"examples\"",
",",
"\"json_jsr353_column\"",
")",
".",
"value",
"(",
"\"id\"",
",",
"literal",
"(",
"1",
")",
")",
"// the JSON object will be converted into a String and persisted into the VARCHAR column",
"// \"json\"",
".",
"value",
"(",
"\"json\"",
",",
"literal",
"(",
"alice",
",",
"session",
".",
"getContext",
"(",
")",
".",
"getCodecRegistry",
"(",
")",
")",
")",
".",
"build",
"(",
")",
";",
"session",
".",
"execute",
"(",
"stmt",
")",
";",
"// The JSON object can be a bound value if the statement is prepared",
"// (subsequent calls to the prepare() method will return cached statement)",
"PreparedStatement",
"pst",
"=",
"session",
".",
"prepare",
"(",
"insertInto",
"(",
"\"examples\"",
",",
"\"json_jsr353_column\"",
")",
".",
"value",
"(",
"\"id\"",
",",
"bindMarker",
"(",
"\"id\"",
")",
")",
".",
"value",
"(",
"\"json\"",
",",
"bindMarker",
"(",
"\"json\"",
")",
")",
".",
"build",
"(",
")",
")",
";",
"session",
".",
"execute",
"(",
"pst",
".",
"bind",
"(",
")",
".",
"setInt",
"(",
"\"id\"",
",",
"2",
")",
"// note that the codec requires that the type passed to the set() method",
"// be always JsonStructure, and not a subclass of it, such as JsonObject",
".",
"set",
"(",
"\"json\"",
",",
"bob",
",",
"JsonStructure",
".",
"class",
")",
")",
";",
"}"
] | Mapping a JSON object to a table column | [
"Mapping",
"a",
"JSON",
"object",
"to",
"a",
"table",
"column"
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/json/jsr/Jsr353JsonColumn.java#L102-L132 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/util/Loggers.java | Loggers.warnWithException | public static void warnWithException(Logger logger, String format, Object... arguments) {
if (logger.isDebugEnabled()) {
logger.warn(format, arguments);
} else {
Object last = arguments[arguments.length - 1];
if (last instanceof Throwable) {
Throwable t = (Throwable) last;
arguments[arguments.length - 1] = t.getClass().getSimpleName() + ": " + t.getMessage();
logger.warn(format + " ({})", arguments);
} else {
// Should only be called with an exception as last argument, but handle gracefully anyway
logger.warn(format, arguments);
}
}
} | java | public static void warnWithException(Logger logger, String format, Object... arguments) {
if (logger.isDebugEnabled()) {
logger.warn(format, arguments);
} else {
Object last = arguments[arguments.length - 1];
if (last instanceof Throwable) {
Throwable t = (Throwable) last;
arguments[arguments.length - 1] = t.getClass().getSimpleName() + ": " + t.getMessage();
logger.warn(format + " ({})", arguments);
} else {
// Should only be called with an exception as last argument, but handle gracefully anyway
logger.warn(format, arguments);
}
}
} | [
"public",
"static",
"void",
"warnWithException",
"(",
"Logger",
"logger",
",",
"String",
"format",
",",
"Object",
"...",
"arguments",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"warn",
"(",
"format",
",",
"arguments",
")",
";",
"}",
"else",
"{",
"Object",
"last",
"=",
"arguments",
"[",
"arguments",
".",
"length",
"-",
"1",
"]",
";",
"if",
"(",
"last",
"instanceof",
"Throwable",
")",
"{",
"Throwable",
"t",
"=",
"(",
"Throwable",
")",
"last",
";",
"arguments",
"[",
"arguments",
".",
"length",
"-",
"1",
"]",
"=",
"t",
".",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
"+",
"\": \"",
"+",
"t",
".",
"getMessage",
"(",
")",
";",
"logger",
".",
"warn",
"(",
"format",
"+",
"\" ({})\"",
",",
"arguments",
")",
";",
"}",
"else",
"{",
"// Should only be called with an exception as last argument, but handle gracefully anyway",
"logger",
".",
"warn",
"(",
"format",
",",
"arguments",
")",
";",
"}",
"}",
"}"
] | Emits a warning log that includes an exception. If the current level is debug, the full stack
trace is included, otherwise only the exception's message. | [
"Emits",
"a",
"warning",
"log",
"that",
"includes",
"an",
"exception",
".",
"If",
"the",
"current",
"level",
"is",
"debug",
"the",
"full",
"stack",
"trace",
"is",
"included",
"otherwise",
"only",
"the",
"exception",
"s",
"message",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/Loggers.java#L26-L40 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultTopologyMonitor.java | DefaultTopologyMonitor.savePort | private void savePort(DriverChannel channel) {
if (port < 0) {
SocketAddress address = channel.getEndPoint().resolve();
if (address instanceof InetSocketAddress) {
port = ((InetSocketAddress) address).getPort();
}
}
} | java | private void savePort(DriverChannel channel) {
if (port < 0) {
SocketAddress address = channel.getEndPoint().resolve();
if (address instanceof InetSocketAddress) {
port = ((InetSocketAddress) address).getPort();
}
}
} | [
"private",
"void",
"savePort",
"(",
"DriverChannel",
"channel",
")",
"{",
"if",
"(",
"port",
"<",
"0",
")",
"{",
"SocketAddress",
"address",
"=",
"channel",
".",
"getEndPoint",
"(",
")",
".",
"resolve",
"(",
")",
";",
"if",
"(",
"address",
"instanceof",
"InetSocketAddress",
")",
"{",
"port",
"=",
"(",
"(",
"InetSocketAddress",
")",
"address",
")",
".",
"getPort",
"(",
")",
";",
"}",
"}",
"}"
] | We save it the first time we get a control connection channel. | [
"We",
"save",
"it",
"the",
"first",
"time",
"we",
"get",
"a",
"control",
"connection",
"channel",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/metadata/DefaultTopologyMonitor.java#L345-L352 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminResult.java | AdminResult.iterator | @NonNull
@Override
public Iterator<AdminRow> iterator() {
return new AbstractIterator<AdminRow>() {
@Override
protected AdminRow computeNext() {
List<ByteBuffer> rowData = data.poll();
return (rowData == null)
? endOfData()
: new AdminRow(columnSpecs, rowData, protocolVersion);
}
};
} | java | @NonNull
@Override
public Iterator<AdminRow> iterator() {
return new AbstractIterator<AdminRow>() {
@Override
protected AdminRow computeNext() {
List<ByteBuffer> rowData = data.poll();
return (rowData == null)
? endOfData()
: new AdminRow(columnSpecs, rowData, protocolVersion);
}
};
} | [
"@",
"NonNull",
"@",
"Override",
"public",
"Iterator",
"<",
"AdminRow",
">",
"iterator",
"(",
")",
"{",
"return",
"new",
"AbstractIterator",
"<",
"AdminRow",
">",
"(",
")",
"{",
"@",
"Override",
"protected",
"AdminRow",
"computeNext",
"(",
")",
"{",
"List",
"<",
"ByteBuffer",
">",
"rowData",
"=",
"data",
".",
"poll",
"(",
")",
";",
"return",
"(",
"rowData",
"==",
"null",
")",
"?",
"endOfData",
"(",
")",
":",
"new",
"AdminRow",
"(",
"columnSpecs",
",",
"rowData",
",",
"protocolVersion",
")",
";",
"}",
"}",
";",
"}"
] | This consumes the result's data and can be called only once. | [
"This",
"consumes",
"the",
"result",
"s",
"data",
"and",
"can",
"be",
"called",
"only",
"once",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/adminrequest/AdminResult.java#L57-L69 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistry.java | CachingCodecRegistry.createCodec | protected TypeCodec<?> createCodec(GenericType<?> javaType, boolean isJavaCovariant) {
TypeToken<?> token = javaType.__getToken();
if (List.class.isAssignableFrom(token.getRawType())
&& token.getType() instanceof ParameterizedType) {
Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments();
GenericType<?> elementType = GenericType.of(typeArguments[0]);
TypeCodec<?> elementCodec = codecFor(elementType, isJavaCovariant);
return TypeCodecs.listOf(elementCodec);
} else if (Set.class.isAssignableFrom(token.getRawType())
&& token.getType() instanceof ParameterizedType) {
Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments();
GenericType<?> elementType = GenericType.of(typeArguments[0]);
TypeCodec<?> elementCodec = codecFor(elementType, isJavaCovariant);
return TypeCodecs.setOf(elementCodec);
} else if (Map.class.isAssignableFrom(token.getRawType())
&& token.getType() instanceof ParameterizedType) {
Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments();
GenericType<?> keyType = GenericType.of(typeArguments[0]);
GenericType<?> valueType = GenericType.of(typeArguments[1]);
TypeCodec<?> keyCodec = codecFor(keyType, isJavaCovariant);
TypeCodec<?> valueCodec = codecFor(valueType, isJavaCovariant);
return TypeCodecs.mapOf(keyCodec, valueCodec);
}
throw new CodecNotFoundException(null, javaType);
} | java | protected TypeCodec<?> createCodec(GenericType<?> javaType, boolean isJavaCovariant) {
TypeToken<?> token = javaType.__getToken();
if (List.class.isAssignableFrom(token.getRawType())
&& token.getType() instanceof ParameterizedType) {
Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments();
GenericType<?> elementType = GenericType.of(typeArguments[0]);
TypeCodec<?> elementCodec = codecFor(elementType, isJavaCovariant);
return TypeCodecs.listOf(elementCodec);
} else if (Set.class.isAssignableFrom(token.getRawType())
&& token.getType() instanceof ParameterizedType) {
Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments();
GenericType<?> elementType = GenericType.of(typeArguments[0]);
TypeCodec<?> elementCodec = codecFor(elementType, isJavaCovariant);
return TypeCodecs.setOf(elementCodec);
} else if (Map.class.isAssignableFrom(token.getRawType())
&& token.getType() instanceof ParameterizedType) {
Type[] typeArguments = ((ParameterizedType) token.getType()).getActualTypeArguments();
GenericType<?> keyType = GenericType.of(typeArguments[0]);
GenericType<?> valueType = GenericType.of(typeArguments[1]);
TypeCodec<?> keyCodec = codecFor(keyType, isJavaCovariant);
TypeCodec<?> valueCodec = codecFor(valueType, isJavaCovariant);
return TypeCodecs.mapOf(keyCodec, valueCodec);
}
throw new CodecNotFoundException(null, javaType);
} | [
"protected",
"TypeCodec",
"<",
"?",
">",
"createCodec",
"(",
"GenericType",
"<",
"?",
">",
"javaType",
",",
"boolean",
"isJavaCovariant",
")",
"{",
"TypeToken",
"<",
"?",
">",
"token",
"=",
"javaType",
".",
"__getToken",
"(",
")",
";",
"if",
"(",
"List",
".",
"class",
".",
"isAssignableFrom",
"(",
"token",
".",
"getRawType",
"(",
")",
")",
"&&",
"token",
".",
"getType",
"(",
")",
"instanceof",
"ParameterizedType",
")",
"{",
"Type",
"[",
"]",
"typeArguments",
"=",
"(",
"(",
"ParameterizedType",
")",
"token",
".",
"getType",
"(",
")",
")",
".",
"getActualTypeArguments",
"(",
")",
";",
"GenericType",
"<",
"?",
">",
"elementType",
"=",
"GenericType",
".",
"of",
"(",
"typeArguments",
"[",
"0",
"]",
")",
";",
"TypeCodec",
"<",
"?",
">",
"elementCodec",
"=",
"codecFor",
"(",
"elementType",
",",
"isJavaCovariant",
")",
";",
"return",
"TypeCodecs",
".",
"listOf",
"(",
"elementCodec",
")",
";",
"}",
"else",
"if",
"(",
"Set",
".",
"class",
".",
"isAssignableFrom",
"(",
"token",
".",
"getRawType",
"(",
")",
")",
"&&",
"token",
".",
"getType",
"(",
")",
"instanceof",
"ParameterizedType",
")",
"{",
"Type",
"[",
"]",
"typeArguments",
"=",
"(",
"(",
"ParameterizedType",
")",
"token",
".",
"getType",
"(",
")",
")",
".",
"getActualTypeArguments",
"(",
")",
";",
"GenericType",
"<",
"?",
">",
"elementType",
"=",
"GenericType",
".",
"of",
"(",
"typeArguments",
"[",
"0",
"]",
")",
";",
"TypeCodec",
"<",
"?",
">",
"elementCodec",
"=",
"codecFor",
"(",
"elementType",
",",
"isJavaCovariant",
")",
";",
"return",
"TypeCodecs",
".",
"setOf",
"(",
"elementCodec",
")",
";",
"}",
"else",
"if",
"(",
"Map",
".",
"class",
".",
"isAssignableFrom",
"(",
"token",
".",
"getRawType",
"(",
")",
")",
"&&",
"token",
".",
"getType",
"(",
")",
"instanceof",
"ParameterizedType",
")",
"{",
"Type",
"[",
"]",
"typeArguments",
"=",
"(",
"(",
"ParameterizedType",
")",
"token",
".",
"getType",
"(",
")",
")",
".",
"getActualTypeArguments",
"(",
")",
";",
"GenericType",
"<",
"?",
">",
"keyType",
"=",
"GenericType",
".",
"of",
"(",
"typeArguments",
"[",
"0",
"]",
")",
";",
"GenericType",
"<",
"?",
">",
"valueType",
"=",
"GenericType",
".",
"of",
"(",
"typeArguments",
"[",
"1",
"]",
")",
";",
"TypeCodec",
"<",
"?",
">",
"keyCodec",
"=",
"codecFor",
"(",
"keyType",
",",
"isJavaCovariant",
")",
";",
"TypeCodec",
"<",
"?",
">",
"valueCodec",
"=",
"codecFor",
"(",
"valueType",
",",
"isJavaCovariant",
")",
";",
"return",
"TypeCodecs",
".",
"mapOf",
"(",
"keyCodec",
",",
"valueCodec",
")",
";",
"}",
"throw",
"new",
"CodecNotFoundException",
"(",
"null",
",",
"javaType",
")",
";",
"}"
] | Variant where the CQL type is unknown. Can be covariant if we come from a lookup by Java value. | [
"Variant",
"where",
"the",
"CQL",
"type",
"is",
"unknown",
".",
"Can",
"be",
"covariant",
"if",
"we",
"come",
"from",
"a",
"lookup",
"by",
"Java",
"value",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistry.java#L348-L372 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistry.java | CachingCodecRegistry.createCodec | protected TypeCodec<?> createCodec(DataType cqlType) {
if (cqlType instanceof ListType) {
DataType elementType = ((ListType) cqlType).getElementType();
TypeCodec<Object> elementCodec = codecFor(elementType);
return TypeCodecs.listOf(elementCodec);
} else if (cqlType instanceof SetType) {
DataType elementType = ((SetType) cqlType).getElementType();
TypeCodec<Object> elementCodec = codecFor(elementType);
return TypeCodecs.setOf(elementCodec);
} else if (cqlType instanceof MapType) {
DataType keyType = ((MapType) cqlType).getKeyType();
DataType valueType = ((MapType) cqlType).getValueType();
TypeCodec<Object> keyCodec = codecFor(keyType);
TypeCodec<Object> valueCodec = codecFor(valueType);
return TypeCodecs.mapOf(keyCodec, valueCodec);
} else if (cqlType instanceof TupleType) {
return TypeCodecs.tupleOf((TupleType) cqlType);
} else if (cqlType instanceof UserDefinedType) {
return TypeCodecs.udtOf((UserDefinedType) cqlType);
} else if (cqlType instanceof CustomType) {
return TypeCodecs.custom(cqlType);
}
throw new CodecNotFoundException(cqlType, null);
} | java | protected TypeCodec<?> createCodec(DataType cqlType) {
if (cqlType instanceof ListType) {
DataType elementType = ((ListType) cqlType).getElementType();
TypeCodec<Object> elementCodec = codecFor(elementType);
return TypeCodecs.listOf(elementCodec);
} else if (cqlType instanceof SetType) {
DataType elementType = ((SetType) cqlType).getElementType();
TypeCodec<Object> elementCodec = codecFor(elementType);
return TypeCodecs.setOf(elementCodec);
} else if (cqlType instanceof MapType) {
DataType keyType = ((MapType) cqlType).getKeyType();
DataType valueType = ((MapType) cqlType).getValueType();
TypeCodec<Object> keyCodec = codecFor(keyType);
TypeCodec<Object> valueCodec = codecFor(valueType);
return TypeCodecs.mapOf(keyCodec, valueCodec);
} else if (cqlType instanceof TupleType) {
return TypeCodecs.tupleOf((TupleType) cqlType);
} else if (cqlType instanceof UserDefinedType) {
return TypeCodecs.udtOf((UserDefinedType) cqlType);
} else if (cqlType instanceof CustomType) {
return TypeCodecs.custom(cqlType);
}
throw new CodecNotFoundException(cqlType, null);
} | [
"protected",
"TypeCodec",
"<",
"?",
">",
"createCodec",
"(",
"DataType",
"cqlType",
")",
"{",
"if",
"(",
"cqlType",
"instanceof",
"ListType",
")",
"{",
"DataType",
"elementType",
"=",
"(",
"(",
"ListType",
")",
"cqlType",
")",
".",
"getElementType",
"(",
")",
";",
"TypeCodec",
"<",
"Object",
">",
"elementCodec",
"=",
"codecFor",
"(",
"elementType",
")",
";",
"return",
"TypeCodecs",
".",
"listOf",
"(",
"elementCodec",
")",
";",
"}",
"else",
"if",
"(",
"cqlType",
"instanceof",
"SetType",
")",
"{",
"DataType",
"elementType",
"=",
"(",
"(",
"SetType",
")",
"cqlType",
")",
".",
"getElementType",
"(",
")",
";",
"TypeCodec",
"<",
"Object",
">",
"elementCodec",
"=",
"codecFor",
"(",
"elementType",
")",
";",
"return",
"TypeCodecs",
".",
"setOf",
"(",
"elementCodec",
")",
";",
"}",
"else",
"if",
"(",
"cqlType",
"instanceof",
"MapType",
")",
"{",
"DataType",
"keyType",
"=",
"(",
"(",
"MapType",
")",
"cqlType",
")",
".",
"getKeyType",
"(",
")",
";",
"DataType",
"valueType",
"=",
"(",
"(",
"MapType",
")",
"cqlType",
")",
".",
"getValueType",
"(",
")",
";",
"TypeCodec",
"<",
"Object",
">",
"keyCodec",
"=",
"codecFor",
"(",
"keyType",
")",
";",
"TypeCodec",
"<",
"Object",
">",
"valueCodec",
"=",
"codecFor",
"(",
"valueType",
")",
";",
"return",
"TypeCodecs",
".",
"mapOf",
"(",
"keyCodec",
",",
"valueCodec",
")",
";",
"}",
"else",
"if",
"(",
"cqlType",
"instanceof",
"TupleType",
")",
"{",
"return",
"TypeCodecs",
".",
"tupleOf",
"(",
"(",
"TupleType",
")",
"cqlType",
")",
";",
"}",
"else",
"if",
"(",
"cqlType",
"instanceof",
"UserDefinedType",
")",
"{",
"return",
"TypeCodecs",
".",
"udtOf",
"(",
"(",
"UserDefinedType",
")",
"cqlType",
")",
";",
"}",
"else",
"if",
"(",
"cqlType",
"instanceof",
"CustomType",
")",
"{",
"return",
"TypeCodecs",
".",
"custom",
"(",
"cqlType",
")",
";",
"}",
"throw",
"new",
"CodecNotFoundException",
"(",
"cqlType",
",",
"null",
")",
";",
"}"
] | Variant where the Java type is unknown. | [
"Variant",
"where",
"the",
"Java",
"type",
"is",
"unknown",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistry.java#L376-L399 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistry.java | CachingCodecRegistry.uncheckedCast | private static <DeclaredT, RuntimeT> TypeCodec<DeclaredT> uncheckedCast(
TypeCodec<RuntimeT> codec) {
@SuppressWarnings("unchecked")
TypeCodec<DeclaredT> result = (TypeCodec<DeclaredT>) codec;
return result;
} | java | private static <DeclaredT, RuntimeT> TypeCodec<DeclaredT> uncheckedCast(
TypeCodec<RuntimeT> codec) {
@SuppressWarnings("unchecked")
TypeCodec<DeclaredT> result = (TypeCodec<DeclaredT>) codec;
return result;
} | [
"private",
"static",
"<",
"DeclaredT",
",",
"RuntimeT",
">",
"TypeCodec",
"<",
"DeclaredT",
">",
"uncheckedCast",
"(",
"TypeCodec",
"<",
"RuntimeT",
">",
"codec",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"TypeCodec",
"<",
"DeclaredT",
">",
"result",
"=",
"(",
"TypeCodec",
"<",
"DeclaredT",
">",
")",
"codec",
";",
"return",
"result",
";",
"}"
] | We call this after validating the types, so we know the cast will never fail. | [
"We",
"call",
"this",
"after",
"validating",
"the",
"types",
"so",
"we",
"know",
"the",
"cast",
"will",
"never",
"fail",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/registry/CachingCodecRegistry.java#L410-L415 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/time/MonotonicTimestampGenerator.java | MonotonicTimestampGenerator.computeNext | protected long computeNext(long last) {
long currentTick = clock.currentTimeMicros();
if (last >= currentTick) {
maybeLog(currentTick, last);
return last + 1;
}
return currentTick;
} | java | protected long computeNext(long last) {
long currentTick = clock.currentTimeMicros();
if (last >= currentTick) {
maybeLog(currentTick, last);
return last + 1;
}
return currentTick;
} | [
"protected",
"long",
"computeNext",
"(",
"long",
"last",
")",
"{",
"long",
"currentTick",
"=",
"clock",
".",
"currentTimeMicros",
"(",
")",
";",
"if",
"(",
"last",
">=",
"currentTick",
")",
"{",
"maybeLog",
"(",
"currentTick",
",",
"last",
")",
";",
"return",
"last",
"+",
"1",
";",
"}",
"return",
"currentTick",
";",
"}"
] | Compute the next timestamp, given the current clock tick and the last timestamp returned.
<p>If timestamps have to drift ahead of the current clock tick to guarantee monotonicity, a
warning will be logged according to the rules defined in the configuration. | [
"Compute",
"the",
"next",
"timestamp",
"given",
"the",
"current",
"clock",
"tick",
"and",
"the",
"last",
"timestamp",
"returned",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/time/MonotonicTimestampGenerator.java#L73-L80 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ParseUtils.java | ParseUtils.skipSpaces | public static int skipSpaces(String toParse, int idx) {
while (isBlank(toParse.charAt(idx)) && idx < toParse.length()) ++idx;
return idx;
} | java | public static int skipSpaces(String toParse, int idx) {
while (isBlank(toParse.charAt(idx)) && idx < toParse.length()) ++idx;
return idx;
} | [
"public",
"static",
"int",
"skipSpaces",
"(",
"String",
"toParse",
",",
"int",
"idx",
")",
"{",
"while",
"(",
"isBlank",
"(",
"toParse",
".",
"charAt",
"(",
"idx",
")",
")",
"&&",
"idx",
"<",
"toParse",
".",
"length",
"(",
")",
")",
"++",
"idx",
";",
"return",
"idx",
";",
"}"
] | Returns the index of the first character in toParse from idx that is not a "space".
@param toParse the string to skip space on.
@param idx the index to start skipping space from.
@return the index of the first character in toParse from idx that is not a "space. | [
"Returns",
"the",
"index",
"of",
"the",
"first",
"character",
"in",
"toParse",
"from",
"idx",
"that",
"is",
"not",
"a",
"space",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ParseUtils.java#L27-L30 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ParseUtils.java | ParseUtils.skipCQLValue | public static int skipCQLValue(String toParse, int idx) {
if (idx >= toParse.length()) throw new IllegalArgumentException();
if (isBlank(toParse.charAt(idx))) throw new IllegalArgumentException();
int cbrackets = 0;
int sbrackets = 0;
int parens = 0;
boolean inString = false;
do {
char c = toParse.charAt(idx);
if (inString) {
if (c == '\'') {
if (idx + 1 < toParse.length() && toParse.charAt(idx + 1) == '\'') {
++idx; // this is an escaped quote, skip it
} else {
inString = false;
if (cbrackets == 0 && sbrackets == 0 && parens == 0) return idx + 1;
}
}
// Skip any other character
} else if (c == '\'') {
inString = true;
} else if (c == '{') {
++cbrackets;
} else if (c == '[') {
++sbrackets;
} else if (c == '(') {
++parens;
} else if (c == '}') {
if (cbrackets == 0) return idx;
--cbrackets;
if (cbrackets == 0 && sbrackets == 0 && parens == 0) return idx + 1;
} else if (c == ']') {
if (sbrackets == 0) return idx;
--sbrackets;
if (cbrackets == 0 && sbrackets == 0 && parens == 0) return idx + 1;
} else if (c == ')') {
if (parens == 0) return idx;
--parens;
if (cbrackets == 0 && sbrackets == 0 && parens == 0) return idx + 1;
} else if (isBlank(c) || !isCqlIdentifierChar(c)) {
if (cbrackets == 0 && sbrackets == 0 && parens == 0) return idx;
}
} while (++idx < toParse.length());
if (inString || cbrackets != 0 || sbrackets != 0 || parens != 0)
throw new IllegalArgumentException();
return idx;
} | java | public static int skipCQLValue(String toParse, int idx) {
if (idx >= toParse.length()) throw new IllegalArgumentException();
if (isBlank(toParse.charAt(idx))) throw new IllegalArgumentException();
int cbrackets = 0;
int sbrackets = 0;
int parens = 0;
boolean inString = false;
do {
char c = toParse.charAt(idx);
if (inString) {
if (c == '\'') {
if (idx + 1 < toParse.length() && toParse.charAt(idx + 1) == '\'') {
++idx; // this is an escaped quote, skip it
} else {
inString = false;
if (cbrackets == 0 && sbrackets == 0 && parens == 0) return idx + 1;
}
}
// Skip any other character
} else if (c == '\'') {
inString = true;
} else if (c == '{') {
++cbrackets;
} else if (c == '[') {
++sbrackets;
} else if (c == '(') {
++parens;
} else if (c == '}') {
if (cbrackets == 0) return idx;
--cbrackets;
if (cbrackets == 0 && sbrackets == 0 && parens == 0) return idx + 1;
} else if (c == ']') {
if (sbrackets == 0) return idx;
--sbrackets;
if (cbrackets == 0 && sbrackets == 0 && parens == 0) return idx + 1;
} else if (c == ')') {
if (parens == 0) return idx;
--parens;
if (cbrackets == 0 && sbrackets == 0 && parens == 0) return idx + 1;
} else if (isBlank(c) || !isCqlIdentifierChar(c)) {
if (cbrackets == 0 && sbrackets == 0 && parens == 0) return idx;
}
} while (++idx < toParse.length());
if (inString || cbrackets != 0 || sbrackets != 0 || parens != 0)
throw new IllegalArgumentException();
return idx;
} | [
"public",
"static",
"int",
"skipCQLValue",
"(",
"String",
"toParse",
",",
"int",
"idx",
")",
"{",
"if",
"(",
"idx",
">=",
"toParse",
".",
"length",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"if",
"(",
"isBlank",
"(",
"toParse",
".",
"charAt",
"(",
"idx",
")",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"int",
"cbrackets",
"=",
"0",
";",
"int",
"sbrackets",
"=",
"0",
";",
"int",
"parens",
"=",
"0",
";",
"boolean",
"inString",
"=",
"false",
";",
"do",
"{",
"char",
"c",
"=",
"toParse",
".",
"charAt",
"(",
"idx",
")",
";",
"if",
"(",
"inString",
")",
"{",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"if",
"(",
"idx",
"+",
"1",
"<",
"toParse",
".",
"length",
"(",
")",
"&&",
"toParse",
".",
"charAt",
"(",
"idx",
"+",
"1",
")",
"==",
"'",
"'",
")",
"{",
"++",
"idx",
";",
"// this is an escaped quote, skip it",
"}",
"else",
"{",
"inString",
"=",
"false",
";",
"if",
"(",
"cbrackets",
"==",
"0",
"&&",
"sbrackets",
"==",
"0",
"&&",
"parens",
"==",
"0",
")",
"return",
"idx",
"+",
"1",
";",
"}",
"}",
"// Skip any other character",
"}",
"else",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"inString",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"++",
"cbrackets",
";",
"}",
"else",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"++",
"sbrackets",
";",
"}",
"else",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"++",
"parens",
";",
"}",
"else",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"if",
"(",
"cbrackets",
"==",
"0",
")",
"return",
"idx",
";",
"--",
"cbrackets",
";",
"if",
"(",
"cbrackets",
"==",
"0",
"&&",
"sbrackets",
"==",
"0",
"&&",
"parens",
"==",
"0",
")",
"return",
"idx",
"+",
"1",
";",
"}",
"else",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"if",
"(",
"sbrackets",
"==",
"0",
")",
"return",
"idx",
";",
"--",
"sbrackets",
";",
"if",
"(",
"cbrackets",
"==",
"0",
"&&",
"sbrackets",
"==",
"0",
"&&",
"parens",
"==",
"0",
")",
"return",
"idx",
"+",
"1",
";",
"}",
"else",
"if",
"(",
"c",
"==",
"'",
"'",
")",
"{",
"if",
"(",
"parens",
"==",
"0",
")",
"return",
"idx",
";",
"--",
"parens",
";",
"if",
"(",
"cbrackets",
"==",
"0",
"&&",
"sbrackets",
"==",
"0",
"&&",
"parens",
"==",
"0",
")",
"return",
"idx",
"+",
"1",
";",
"}",
"else",
"if",
"(",
"isBlank",
"(",
"c",
")",
"||",
"!",
"isCqlIdentifierChar",
"(",
"c",
")",
")",
"{",
"if",
"(",
"cbrackets",
"==",
"0",
"&&",
"sbrackets",
"==",
"0",
"&&",
"parens",
"==",
"0",
")",
"return",
"idx",
";",
"}",
"}",
"while",
"(",
"++",
"idx",
"<",
"toParse",
".",
"length",
"(",
")",
")",
";",
"if",
"(",
"inString",
"||",
"cbrackets",
"!=",
"0",
"||",
"sbrackets",
"!=",
"0",
"||",
"parens",
"!=",
"0",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"return",
"idx",
";",
"}"
] | Assuming that idx points to the beginning of a CQL value in toParse, returns the index of the
first character after this value.
@param toParse the string to skip a value form.
@param idx the index to start parsing a value from.
@return the index ending the CQL value starting at {@code idx}.
@throws IllegalArgumentException if idx doesn't point to the start of a valid CQL value. | [
"Assuming",
"that",
"idx",
"points",
"to",
"the",
"beginning",
"of",
"a",
"CQL",
"value",
"in",
"toParse",
"returns",
"the",
"index",
"of",
"the",
"first",
"character",
"after",
"this",
"value",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ParseUtils.java#L41-L94 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ParseUtils.java | ParseUtils.skipCQLId | public static int skipCQLId(String toParse, int idx) {
if (idx >= toParse.length()) throw new IllegalArgumentException();
char c = toParse.charAt(idx);
if (isCqlIdentifierChar(c)) {
while (idx < toParse.length() && isCqlIdentifierChar(toParse.charAt(idx))) idx++;
return idx;
}
if (c != '"') throw new IllegalArgumentException();
while (++idx < toParse.length()) {
c = toParse.charAt(idx);
if (c != '"') continue;
if (idx + 1 < toParse.length() && toParse.charAt(idx + 1) == '\"')
++idx; // this is an escaped double quote, skip it
else return idx + 1;
}
throw new IllegalArgumentException();
} | java | public static int skipCQLId(String toParse, int idx) {
if (idx >= toParse.length()) throw new IllegalArgumentException();
char c = toParse.charAt(idx);
if (isCqlIdentifierChar(c)) {
while (idx < toParse.length() && isCqlIdentifierChar(toParse.charAt(idx))) idx++;
return idx;
}
if (c != '"') throw new IllegalArgumentException();
while (++idx < toParse.length()) {
c = toParse.charAt(idx);
if (c != '"') continue;
if (idx + 1 < toParse.length() && toParse.charAt(idx + 1) == '\"')
++idx; // this is an escaped double quote, skip it
else return idx + 1;
}
throw new IllegalArgumentException();
} | [
"public",
"static",
"int",
"skipCQLId",
"(",
"String",
"toParse",
",",
"int",
"idx",
")",
"{",
"if",
"(",
"idx",
">=",
"toParse",
".",
"length",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"char",
"c",
"=",
"toParse",
".",
"charAt",
"(",
"idx",
")",
";",
"if",
"(",
"isCqlIdentifierChar",
"(",
"c",
")",
")",
"{",
"while",
"(",
"idx",
"<",
"toParse",
".",
"length",
"(",
")",
"&&",
"isCqlIdentifierChar",
"(",
"toParse",
".",
"charAt",
"(",
"idx",
")",
")",
")",
"idx",
"++",
";",
"return",
"idx",
";",
"}",
"if",
"(",
"c",
"!=",
"'",
"'",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"while",
"(",
"++",
"idx",
"<",
"toParse",
".",
"length",
"(",
")",
")",
"{",
"c",
"=",
"toParse",
".",
"charAt",
"(",
"idx",
")",
";",
"if",
"(",
"c",
"!=",
"'",
"'",
")",
"continue",
";",
"if",
"(",
"idx",
"+",
"1",
"<",
"toParse",
".",
"length",
"(",
")",
"&&",
"toParse",
".",
"charAt",
"(",
"idx",
"+",
"1",
")",
"==",
"'",
"'",
")",
"++",
"idx",
";",
"// this is an escaped double quote, skip it",
"else",
"return",
"idx",
"+",
"1",
";",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}"
] | Assuming that idx points to the beginning of a CQL identifier in toParse, returns the index of
the first character after this identifier.
@param toParse the string to skip an identifier from.
@param idx the index to start parsing an identifier from.
@return the index ending the CQL identifier starting at {@code idx}.
@throws IllegalArgumentException if idx doesn't point to the start of a valid CQL identifier. | [
"Assuming",
"that",
"idx",
"points",
"to",
"the",
"beginning",
"of",
"a",
"CQL",
"identifier",
"in",
"toParse",
"returns",
"the",
"index",
"of",
"the",
"first",
"character",
"after",
"this",
"identifier",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/type/codec/ParseUtils.java#L105-L125 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/context/EventBus.java | EventBus.register | public <EventT> Object register(Class<EventT> eventClass, Consumer<EventT> listener) {
LOG.debug("[{}] Registering {} for {}", logPrefix, listener, eventClass);
listeners.put(eventClass, listener);
// The reason for the key mechanism is that this will often be used with method references,
// and you get a different object every time you reference a method, so register(Foo::bar)
// followed by unregister(Foo::bar) wouldn't work as expected.
return listener;
} | java | public <EventT> Object register(Class<EventT> eventClass, Consumer<EventT> listener) {
LOG.debug("[{}] Registering {} for {}", logPrefix, listener, eventClass);
listeners.put(eventClass, listener);
// The reason for the key mechanism is that this will often be used with method references,
// and you get a different object every time you reference a method, so register(Foo::bar)
// followed by unregister(Foo::bar) wouldn't work as expected.
return listener;
} | [
"public",
"<",
"EventT",
">",
"Object",
"register",
"(",
"Class",
"<",
"EventT",
">",
"eventClass",
",",
"Consumer",
"<",
"EventT",
">",
"listener",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"[{}] Registering {} for {}\"",
",",
"logPrefix",
",",
"listener",
",",
"eventClass",
")",
";",
"listeners",
".",
"put",
"(",
"eventClass",
",",
"listener",
")",
";",
"// The reason for the key mechanism is that this will often be used with method references,",
"// and you get a different object every time you reference a method, so register(Foo::bar)",
"// followed by unregister(Foo::bar) wouldn't work as expected.",
"return",
"listener",
";",
"}"
] | Registers a listener for an event type.
<p>If the listener has a shorter lifecycle than the {@code Cluster} instance, it is recommended
to save the key returned by this method, and use it later to unregister and therefore avoid a
leak.
@return a key that is needed to unregister later. | [
"Registers",
"a",
"listener",
"for",
"an",
"event",
"type",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/context/EventBus.java#L58-L65 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/context/EventBus.java | EventBus.unregister | public <EventT> boolean unregister(Object key, Class<EventT> eventClass) {
LOG.debug("[{}] Unregistering {} for {}", logPrefix, key, eventClass);
return listeners.remove(eventClass, key);
} | java | public <EventT> boolean unregister(Object key, Class<EventT> eventClass) {
LOG.debug("[{}] Unregistering {} for {}", logPrefix, key, eventClass);
return listeners.remove(eventClass, key);
} | [
"public",
"<",
"EventT",
">",
"boolean",
"unregister",
"(",
"Object",
"key",
",",
"Class",
"<",
"EventT",
">",
"eventClass",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"[{}] Unregistering {} for {}\"",
",",
"logPrefix",
",",
"key",
",",
"eventClass",
")",
";",
"return",
"listeners",
".",
"remove",
"(",
"eventClass",
",",
"key",
")",
";",
"}"
] | Unregisters a listener.
@param key the key that was returned by {@link #register(Class, Consumer)} | [
"Unregisters",
"a",
"listener",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/context/EventBus.java#L72-L75 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/context/EventBus.java | EventBus.fire | public void fire(Object event) {
LOG.debug("[{}] Firing an instance of {}: {}", logPrefix, event.getClass(), event);
// if the exact match thing gets too cumbersome, we can reconsider, but I'd like to avoid
// scanning all the keys with instanceof checks.
Class<?> eventClass = event.getClass();
for (Consumer<?> l : listeners.get(eventClass)) {
@SuppressWarnings("unchecked")
Consumer<Object> listener = (Consumer<Object>) l;
LOG.debug("[{}] Notifying {} of {}", logPrefix, listener, event);
listener.accept(event);
}
} | java | public void fire(Object event) {
LOG.debug("[{}] Firing an instance of {}: {}", logPrefix, event.getClass(), event);
// if the exact match thing gets too cumbersome, we can reconsider, but I'd like to avoid
// scanning all the keys with instanceof checks.
Class<?> eventClass = event.getClass();
for (Consumer<?> l : listeners.get(eventClass)) {
@SuppressWarnings("unchecked")
Consumer<Object> listener = (Consumer<Object>) l;
LOG.debug("[{}] Notifying {} of {}", logPrefix, listener, event);
listener.accept(event);
}
} | [
"public",
"void",
"fire",
"(",
"Object",
"event",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"[{}] Firing an instance of {}: {}\"",
",",
"logPrefix",
",",
"event",
".",
"getClass",
"(",
")",
",",
"event",
")",
";",
"// if the exact match thing gets too cumbersome, we can reconsider, but I'd like to avoid",
"// scanning all the keys with instanceof checks.",
"Class",
"<",
"?",
">",
"eventClass",
"=",
"event",
".",
"getClass",
"(",
")",
";",
"for",
"(",
"Consumer",
"<",
"?",
">",
"l",
":",
"listeners",
".",
"get",
"(",
"eventClass",
")",
")",
"{",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"Consumer",
"<",
"Object",
">",
"listener",
"=",
"(",
"Consumer",
"<",
"Object",
">",
")",
"l",
";",
"LOG",
".",
"debug",
"(",
"\"[{}] Notifying {} of {}\"",
",",
"logPrefix",
",",
"listener",
",",
"event",
")",
";",
"listener",
".",
"accept",
"(",
"event",
")",
";",
"}",
"}"
] | Sends an event that will notify any registered listener for that class.
<p>Listeners are looked up by an <b>exact match</b> on the class of the object, as returned by
{@code event.getClass()}. Listeners of a supertype won't be notified.
<p>The listeners are invoked on the calling thread. It's their responsibility to schedule event
processing asynchronously if needed. | [
"Sends",
"an",
"event",
"that",
"will",
"notify",
"any",
"registered",
"listener",
"for",
"that",
"class",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/context/EventBus.java#L86-L97 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/util/Strings.java | Strings.needsDoubleQuotes | public static boolean needsDoubleQuotes(String s) {
// this method should only be called for C*-provided identifiers,
// so we expect it to be non-null and non-empty.
assert s != null && !s.isEmpty();
char c = s.charAt(0);
if (!(c >= 97 && c <= 122)) // a-z
return true;
for (int i = 1; i < s.length(); i++) {
c = s.charAt(i);
if (!((c >= 48 && c <= 57) // 0-9
|| (c == 95) // _
|| (c >= 97 && c <= 122) // a-z
)) {
return true;
}
}
return isReservedCqlKeyword(s);
} | java | public static boolean needsDoubleQuotes(String s) {
// this method should only be called for C*-provided identifiers,
// so we expect it to be non-null and non-empty.
assert s != null && !s.isEmpty();
char c = s.charAt(0);
if (!(c >= 97 && c <= 122)) // a-z
return true;
for (int i = 1; i < s.length(); i++) {
c = s.charAt(i);
if (!((c >= 48 && c <= 57) // 0-9
|| (c == 95) // _
|| (c >= 97 && c <= 122) // a-z
)) {
return true;
}
}
return isReservedCqlKeyword(s);
} | [
"public",
"static",
"boolean",
"needsDoubleQuotes",
"(",
"String",
"s",
")",
"{",
"// this method should only be called for C*-provided identifiers,",
"// so we expect it to be non-null and non-empty.",
"assert",
"s",
"!=",
"null",
"&&",
"!",
"s",
".",
"isEmpty",
"(",
")",
";",
"char",
"c",
"=",
"s",
".",
"charAt",
"(",
"0",
")",
";",
"if",
"(",
"!",
"(",
"c",
">=",
"97",
"&&",
"c",
"<=",
"122",
")",
")",
"// a-z",
"return",
"true",
";",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"s",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"c",
"=",
"s",
".",
"charAt",
"(",
"i",
")",
";",
"if",
"(",
"!",
"(",
"(",
"c",
">=",
"48",
"&&",
"c",
"<=",
"57",
")",
"// 0-9",
"||",
"(",
"c",
"==",
"95",
")",
"// _",
"||",
"(",
"c",
">=",
"97",
"&&",
"c",
"<=",
"122",
")",
"// a-z",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"isReservedCqlKeyword",
"(",
"s",
")",
";",
"}"
] | Whether a string needs double quotes to be a valid CQL identifier. | [
"Whether",
"a",
"string",
"needs",
"double",
"quotes",
"to",
"be",
"a",
"valid",
"CQL",
"identifier",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/Strings.java#L91-L108 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/util/Strings.java | Strings.isLongLiteral | public static boolean isLongLiteral(String str) {
if (str == null || str.isEmpty()) return false;
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((c < '0' && (i != 0 || c != '-')) || c > '9') return false;
}
return true;
} | java | public static boolean isLongLiteral(String str) {
if (str == null || str.isEmpty()) return false;
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((c < '0' && (i != 0 || c != '-')) || c > '9') return false;
}
return true;
} | [
"public",
"static",
"boolean",
"isLongLiteral",
"(",
"String",
"str",
")",
"{",
"if",
"(",
"str",
"==",
"null",
"||",
"str",
".",
"isEmpty",
"(",
")",
")",
"return",
"false",
";",
"char",
"[",
"]",
"chars",
"=",
"str",
".",
"toCharArray",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"chars",
".",
"length",
";",
"i",
"++",
")",
"{",
"char",
"c",
"=",
"chars",
"[",
"i",
"]",
";",
"if",
"(",
"(",
"c",
"<",
"'",
"'",
"&&",
"(",
"i",
"!=",
"0",
"||",
"c",
"!=",
"'",
"'",
")",
")",
"||",
"c",
">",
"'",
"'",
")",
"return",
"false",
";",
"}",
"return",
"true",
";",
"}"
] | Check whether the given string corresponds to a valid CQL long literal. Long literals are
composed solely by digits, but can have an optional leading minus sign.
@param str The string to inspect.
@return {@code true} if the given string corresponds to a valid CQL integer literal, {@code
false} otherwise. | [
"Check",
"whether",
"the",
"given",
"string",
"corresponds",
"to",
"a",
"valid",
"CQL",
"long",
"literal",
".",
"Long",
"literals",
"are",
"composed",
"solely",
"by",
"digits",
"but",
"can",
"have",
"an",
"optional",
"leading",
"minus",
"sign",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/util/Strings.java#L245-L253 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/api/core/CqlIdentifier.java | CqlIdentifier.asCql | @NonNull
public String asCql(boolean pretty) {
if (pretty) {
return Strings.needsDoubleQuotes(internal) ? Strings.doubleQuote(internal) : internal;
} else {
return Strings.doubleQuote(internal);
}
} | java | @NonNull
public String asCql(boolean pretty) {
if (pretty) {
return Strings.needsDoubleQuotes(internal) ? Strings.doubleQuote(internal) : internal;
} else {
return Strings.doubleQuote(internal);
}
} | [
"@",
"NonNull",
"public",
"String",
"asCql",
"(",
"boolean",
"pretty",
")",
"{",
"if",
"(",
"pretty",
")",
"{",
"return",
"Strings",
".",
"needsDoubleQuotes",
"(",
"internal",
")",
"?",
"Strings",
".",
"doubleQuote",
"(",
"internal",
")",
":",
"internal",
";",
"}",
"else",
"{",
"return",
"Strings",
".",
"doubleQuote",
"(",
"internal",
")",
";",
"}",
"}"
] | Returns the identifier in a format appropriate for concatenation in a CQL query.
@param pretty if {@code true}, use the shortest possible representation: if the identifier is
case-insensitive, an unquoted, lower-case string, otherwise the double-quoted form. If
{@code false}, always use the double-quoted form (this is slightly more efficient since we
don't need to inspect the string). | [
"Returns",
"the",
"identifier",
"in",
"a",
"format",
"appropriate",
"for",
"concatenation",
"in",
"a",
"CQL",
"query",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/api/core/CqlIdentifier.java#L117-L124 | train |
datastax/java-driver | core/src/main/java/com/datastax/oss/driver/internal/core/context/StartupOptionsBuilder.java | StartupOptionsBuilder.build | public Map<String, String> build() {
NullAllowingImmutableMap.Builder<String, String> builder = NullAllowingImmutableMap.builder(3);
// add compression (if configured) and driver name and version
String compressionAlgorithm = context.getCompressor().algorithm();
if (compressionAlgorithm != null && !compressionAlgorithm.trim().isEmpty()) {
builder.put(Startup.COMPRESSION_KEY, compressionAlgorithm.trim());
}
return builder
.put(DRIVER_NAME_KEY, getDriverName())
.put(DRIVER_VERSION_KEY, getDriverVersion())
.build();
} | java | public Map<String, String> build() {
NullAllowingImmutableMap.Builder<String, String> builder = NullAllowingImmutableMap.builder(3);
// add compression (if configured) and driver name and version
String compressionAlgorithm = context.getCompressor().algorithm();
if (compressionAlgorithm != null && !compressionAlgorithm.trim().isEmpty()) {
builder.put(Startup.COMPRESSION_KEY, compressionAlgorithm.trim());
}
return builder
.put(DRIVER_NAME_KEY, getDriverName())
.put(DRIVER_VERSION_KEY, getDriverVersion())
.build();
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"build",
"(",
")",
"{",
"NullAllowingImmutableMap",
".",
"Builder",
"<",
"String",
",",
"String",
">",
"builder",
"=",
"NullAllowingImmutableMap",
".",
"builder",
"(",
"3",
")",
";",
"// add compression (if configured) and driver name and version",
"String",
"compressionAlgorithm",
"=",
"context",
".",
"getCompressor",
"(",
")",
".",
"algorithm",
"(",
")",
";",
"if",
"(",
"compressionAlgorithm",
"!=",
"null",
"&&",
"!",
"compressionAlgorithm",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"builder",
".",
"put",
"(",
"Startup",
".",
"COMPRESSION_KEY",
",",
"compressionAlgorithm",
".",
"trim",
"(",
")",
")",
";",
"}",
"return",
"builder",
".",
"put",
"(",
"DRIVER_NAME_KEY",
",",
"getDriverName",
"(",
")",
")",
".",
"put",
"(",
"DRIVER_VERSION_KEY",
",",
"getDriverVersion",
"(",
")",
")",
".",
"build",
"(",
")",
";",
"}"
] | Builds a map of options to send in a Startup message.
<p>The default set of options are built here and include {@link
com.datastax.oss.protocol.internal.request.Startup#COMPRESSION_KEY} (if the context passed in
has a compressor/algorithm set), and the driver's {@link #DRIVER_NAME_KEY} and {@link
#DRIVER_VERSION_KEY}. The {@link com.datastax.oss.protocol.internal.request.Startup}
constructor will add {@link
com.datastax.oss.protocol.internal.request.Startup#CQL_VERSION_KEY}.
@return Map of Startup Options. | [
"Builds",
"a",
"map",
"of",
"options",
"to",
"send",
"in",
"a",
"Startup",
"message",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/core/src/main/java/com/datastax/oss/driver/internal/core/context/StartupOptionsBuilder.java#L48-L59 | train |
datastax/java-driver | examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java | DowngradingRetry.connect | private void connect() {
session = CqlSession.builder().build();
System.out.printf("Connected to session: %s%n", session.getName());
} | java | private void connect() {
session = CqlSession.builder().build();
System.out.printf("Connected to session: %s%n", session.getName());
} | [
"private",
"void",
"connect",
"(",
")",
"{",
"session",
"=",
"CqlSession",
".",
"builder",
"(",
")",
".",
"build",
"(",
")",
";",
"System",
".",
"out",
".",
"printf",
"(",
"\"Connected to session: %s%n\"",
",",
"session",
".",
"getName",
"(",
")",
")",
";",
"}"
] | Initiates a connection to the session specified by the application.conf. | [
"Initiates",
"a",
"connection",
"to",
"the",
"session",
"specified",
"by",
"the",
"application",
".",
"conf",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java#L109-L113 | train |
datastax/java-driver | examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java | DowngradingRetry.write | private void write(ConsistencyLevel cl, int retryCount) {
System.out.printf("Writing at %s (retry count: %d)%n", cl, retryCount);
BatchStatement batch =
BatchStatement.newInstance(UNLOGGED)
.add(
SimpleStatement.newInstance(
"INSERT INTO downgrading.sensor_data "
+ "(sensor_id, date, timestamp, value) "
+ "VALUES ("
+ "756716f7-2e54-4715-9f00-91dcbea6cf50,"
+ "'2018-02-26',"
+ "'2018-02-26T13:53:46.345+01:00',"
+ "2.34)"))
.add(
SimpleStatement.newInstance(
"INSERT INTO downgrading.sensor_data "
+ "(sensor_id, date, timestamp, value) "
+ "VALUES ("
+ "756716f7-2e54-4715-9f00-91dcbea6cf50,"
+ "'2018-02-26',"
+ "'2018-02-26T13:54:27.488+01:00',"
+ "2.47)"))
.add(
SimpleStatement.newInstance(
"INSERT INTO downgrading.sensor_data "
+ "(sensor_id, date, timestamp, value) "
+ "VALUES ("
+ "756716f7-2e54-4715-9f00-91dcbea6cf50,"
+ "'2018-02-26',"
+ "'2018-02-26T13:56:33.739+01:00',"
+ "2.52)"))
.setConsistencyLevel(cl);
try {
session.execute(batch);
System.out.println("Write succeeded at " + cl);
} catch (DriverException e) {
if (retryCount == maxRetries) {
throw e;
}
e = unwrapAllNodesFailedException(e);
System.out.println("Write failed: " + e);
// General intent:
// 1) If we know the write has been fully persisted on at least one replica,
// ignore the exception since the write will be eventually propagated to other replicas.
// 2) If the write couldn't be persisted at all, abort as it is unlikely that a retry would
// succeed.
// 3) If the write was only partially persisted, retry at the highest consistency
// level that is likely to succeed.
if (e instanceof UnavailableException) {
// With an UnavailableException, we know that the write wasn't even attempted.
// Downgrade to the number of replicas reported alive and retry.
int aliveReplicas = ((UnavailableException) e).getAlive();
ConsistencyLevel downgraded = downgrade(cl, aliveReplicas, e);
write(downgraded, retryCount + 1);
} else if (e instanceof WriteTimeoutException) {
DefaultWriteType writeType = (DefaultWriteType) ((WriteTimeoutException) e).getWriteType();
int acknowledgements = ((WriteTimeoutException) e).getReceived();
switch (writeType) {
case SIMPLE:
case BATCH:
// For simple and batch writes, as long as one replica acknowledged the write,
// ignore the exception; if none responded however, abort as it is unlikely that
// a retry would ever succeed.
if (acknowledgements == 0) {
throw e;
}
break;
case UNLOGGED_BATCH:
// For unlogged batches, the write might have been persisted only partially,
// so we can't simply ignore the exception: instead, we need to retry with
// consistency level equal to the number of acknowledged writes.
ConsistencyLevel downgraded = downgrade(cl, acknowledgements, e);
write(downgraded, retryCount + 1);
break;
case BATCH_LOG:
// Rare edge case: the peers that were chosen by the coordinator
// to receive the distributed batch log failed to respond.
// Simply retry with same consistency level.
write(cl, retryCount + 1);
break;
default:
// Other write types are uncommon and should not be retried.
throw e;
}
} else {
// Unexpected error: just retry with same consistency level
// and hope to talk to a healthier coordinator.
write(cl, retryCount + 1);
}
}
} | java | private void write(ConsistencyLevel cl, int retryCount) {
System.out.printf("Writing at %s (retry count: %d)%n", cl, retryCount);
BatchStatement batch =
BatchStatement.newInstance(UNLOGGED)
.add(
SimpleStatement.newInstance(
"INSERT INTO downgrading.sensor_data "
+ "(sensor_id, date, timestamp, value) "
+ "VALUES ("
+ "756716f7-2e54-4715-9f00-91dcbea6cf50,"
+ "'2018-02-26',"
+ "'2018-02-26T13:53:46.345+01:00',"
+ "2.34)"))
.add(
SimpleStatement.newInstance(
"INSERT INTO downgrading.sensor_data "
+ "(sensor_id, date, timestamp, value) "
+ "VALUES ("
+ "756716f7-2e54-4715-9f00-91dcbea6cf50,"
+ "'2018-02-26',"
+ "'2018-02-26T13:54:27.488+01:00',"
+ "2.47)"))
.add(
SimpleStatement.newInstance(
"INSERT INTO downgrading.sensor_data "
+ "(sensor_id, date, timestamp, value) "
+ "VALUES ("
+ "756716f7-2e54-4715-9f00-91dcbea6cf50,"
+ "'2018-02-26',"
+ "'2018-02-26T13:56:33.739+01:00',"
+ "2.52)"))
.setConsistencyLevel(cl);
try {
session.execute(batch);
System.out.println("Write succeeded at " + cl);
} catch (DriverException e) {
if (retryCount == maxRetries) {
throw e;
}
e = unwrapAllNodesFailedException(e);
System.out.println("Write failed: " + e);
// General intent:
// 1) If we know the write has been fully persisted on at least one replica,
// ignore the exception since the write will be eventually propagated to other replicas.
// 2) If the write couldn't be persisted at all, abort as it is unlikely that a retry would
// succeed.
// 3) If the write was only partially persisted, retry at the highest consistency
// level that is likely to succeed.
if (e instanceof UnavailableException) {
// With an UnavailableException, we know that the write wasn't even attempted.
// Downgrade to the number of replicas reported alive and retry.
int aliveReplicas = ((UnavailableException) e).getAlive();
ConsistencyLevel downgraded = downgrade(cl, aliveReplicas, e);
write(downgraded, retryCount + 1);
} else if (e instanceof WriteTimeoutException) {
DefaultWriteType writeType = (DefaultWriteType) ((WriteTimeoutException) e).getWriteType();
int acknowledgements = ((WriteTimeoutException) e).getReceived();
switch (writeType) {
case SIMPLE:
case BATCH:
// For simple and batch writes, as long as one replica acknowledged the write,
// ignore the exception; if none responded however, abort as it is unlikely that
// a retry would ever succeed.
if (acknowledgements == 0) {
throw e;
}
break;
case UNLOGGED_BATCH:
// For unlogged batches, the write might have been persisted only partially,
// so we can't simply ignore the exception: instead, we need to retry with
// consistency level equal to the number of acknowledged writes.
ConsistencyLevel downgraded = downgrade(cl, acknowledgements, e);
write(downgraded, retryCount + 1);
break;
case BATCH_LOG:
// Rare edge case: the peers that were chosen by the coordinator
// to receive the distributed batch log failed to respond.
// Simply retry with same consistency level.
write(cl, retryCount + 1);
break;
default:
// Other write types are uncommon and should not be retried.
throw e;
}
} else {
// Unexpected error: just retry with same consistency level
// and hope to talk to a healthier coordinator.
write(cl, retryCount + 1);
}
}
} | [
"private",
"void",
"write",
"(",
"ConsistencyLevel",
"cl",
",",
"int",
"retryCount",
")",
"{",
"System",
".",
"out",
".",
"printf",
"(",
"\"Writing at %s (retry count: %d)%n\"",
",",
"cl",
",",
"retryCount",
")",
";",
"BatchStatement",
"batch",
"=",
"BatchStatement",
".",
"newInstance",
"(",
"UNLOGGED",
")",
".",
"add",
"(",
"SimpleStatement",
".",
"newInstance",
"(",
"\"INSERT INTO downgrading.sensor_data \"",
"+",
"\"(sensor_id, date, timestamp, value) \"",
"+",
"\"VALUES (\"",
"+",
"\"756716f7-2e54-4715-9f00-91dcbea6cf50,\"",
"+",
"\"'2018-02-26',\"",
"+",
"\"'2018-02-26T13:53:46.345+01:00',\"",
"+",
"\"2.34)\"",
")",
")",
".",
"add",
"(",
"SimpleStatement",
".",
"newInstance",
"(",
"\"INSERT INTO downgrading.sensor_data \"",
"+",
"\"(sensor_id, date, timestamp, value) \"",
"+",
"\"VALUES (\"",
"+",
"\"756716f7-2e54-4715-9f00-91dcbea6cf50,\"",
"+",
"\"'2018-02-26',\"",
"+",
"\"'2018-02-26T13:54:27.488+01:00',\"",
"+",
"\"2.47)\"",
")",
")",
".",
"add",
"(",
"SimpleStatement",
".",
"newInstance",
"(",
"\"INSERT INTO downgrading.sensor_data \"",
"+",
"\"(sensor_id, date, timestamp, value) \"",
"+",
"\"VALUES (\"",
"+",
"\"756716f7-2e54-4715-9f00-91dcbea6cf50,\"",
"+",
"\"'2018-02-26',\"",
"+",
"\"'2018-02-26T13:56:33.739+01:00',\"",
"+",
"\"2.52)\"",
")",
")",
".",
"setConsistencyLevel",
"(",
"cl",
")",
";",
"try",
"{",
"session",
".",
"execute",
"(",
"batch",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"Write succeeded at \"",
"+",
"cl",
")",
";",
"}",
"catch",
"(",
"DriverException",
"e",
")",
"{",
"if",
"(",
"retryCount",
"==",
"maxRetries",
")",
"{",
"throw",
"e",
";",
"}",
"e",
"=",
"unwrapAllNodesFailedException",
"(",
"e",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"Write failed: \"",
"+",
"e",
")",
";",
"// General intent:",
"// 1) If we know the write has been fully persisted on at least one replica,",
"// ignore the exception since the write will be eventually propagated to other replicas.",
"// 2) If the write couldn't be persisted at all, abort as it is unlikely that a retry would",
"// succeed.",
"// 3) If the write was only partially persisted, retry at the highest consistency",
"// level that is likely to succeed.",
"if",
"(",
"e",
"instanceof",
"UnavailableException",
")",
"{",
"// With an UnavailableException, we know that the write wasn't even attempted.",
"// Downgrade to the number of replicas reported alive and retry.",
"int",
"aliveReplicas",
"=",
"(",
"(",
"UnavailableException",
")",
"e",
")",
".",
"getAlive",
"(",
")",
";",
"ConsistencyLevel",
"downgraded",
"=",
"downgrade",
"(",
"cl",
",",
"aliveReplicas",
",",
"e",
")",
";",
"write",
"(",
"downgraded",
",",
"retryCount",
"+",
"1",
")",
";",
"}",
"else",
"if",
"(",
"e",
"instanceof",
"WriteTimeoutException",
")",
"{",
"DefaultWriteType",
"writeType",
"=",
"(",
"DefaultWriteType",
")",
"(",
"(",
"WriteTimeoutException",
")",
"e",
")",
".",
"getWriteType",
"(",
")",
";",
"int",
"acknowledgements",
"=",
"(",
"(",
"WriteTimeoutException",
")",
"e",
")",
".",
"getReceived",
"(",
")",
";",
"switch",
"(",
"writeType",
")",
"{",
"case",
"SIMPLE",
":",
"case",
"BATCH",
":",
"// For simple and batch writes, as long as one replica acknowledged the write,",
"// ignore the exception; if none responded however, abort as it is unlikely that",
"// a retry would ever succeed.",
"if",
"(",
"acknowledgements",
"==",
"0",
")",
"{",
"throw",
"e",
";",
"}",
"break",
";",
"case",
"UNLOGGED_BATCH",
":",
"// For unlogged batches, the write might have been persisted only partially,",
"// so we can't simply ignore the exception: instead, we need to retry with",
"// consistency level equal to the number of acknowledged writes.",
"ConsistencyLevel",
"downgraded",
"=",
"downgrade",
"(",
"cl",
",",
"acknowledgements",
",",
"e",
")",
";",
"write",
"(",
"downgraded",
",",
"retryCount",
"+",
"1",
")",
";",
"break",
";",
"case",
"BATCH_LOG",
":",
"// Rare edge case: the peers that were chosen by the coordinator",
"// to receive the distributed batch log failed to respond.",
"// Simply retry with same consistency level.",
"write",
"(",
"cl",
",",
"retryCount",
"+",
"1",
")",
";",
"break",
";",
"default",
":",
"// Other write types are uncommon and should not be retried.",
"throw",
"e",
";",
"}",
"}",
"else",
"{",
"// Unexpected error: just retry with same consistency level",
"// and hope to talk to a healthier coordinator.",
"write",
"(",
"cl",
",",
"retryCount",
"+",
"1",
")",
";",
"}",
"}",
"}"
] | Inserts data, retrying if necessary with a downgraded CL.
@param cl the consistency level to apply.
@param retryCount the current retry count.
@throws DriverException if the current consistency level cannot be downgraded. | [
"Inserts",
"data",
"retrying",
"if",
"necessary",
"with",
"a",
"downgraded",
"CL",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java#L140-L250 | train |
datastax/java-driver | examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java | DowngradingRetry.read | private ResultSet read(ConsistencyLevel cl, int retryCount) {
System.out.printf("Reading at %s (retry count: %d)%n", cl, retryCount);
Statement stmt =
SimpleStatement.newInstance(
"SELECT sensor_id, date, timestamp, value "
+ "FROM downgrading.sensor_data "
+ "WHERE "
+ "sensor_id = 756716f7-2e54-4715-9f00-91dcbea6cf50 AND "
+ "date = '2018-02-26' AND "
+ "timestamp > '2018-02-26+01:00'")
.setConsistencyLevel(cl);
try {
ResultSet rows = session.execute(stmt);
System.out.println("Read succeeded at " + cl);
return rows;
} catch (DriverException e) {
if (retryCount == maxRetries) {
throw e;
}
e = unwrapAllNodesFailedException(e);
System.out.println("Read failed: " + e);
// General intent: downgrade and retry at the highest consistency level
// that is likely to succeed.
if (e instanceof UnavailableException) {
// Downgrade to the number of replicas reported alive and retry.
int aliveReplicas = ((UnavailableException) e).getAlive();
ConsistencyLevel downgraded = downgrade(cl, aliveReplicas, e);
return read(downgraded, retryCount + 1);
} else if (e instanceof ReadTimeoutException) {
ReadTimeoutException readTimeout = (ReadTimeoutException) e;
int received = readTimeout.getReceived();
int required = readTimeout.getBlockFor();
// If fewer replicas responded than required by the consistency level
// (but at least one replica did respond), retry with a consistency level
// equal to the number of received acknowledgements.
if (received < required) {
ConsistencyLevel downgraded = downgrade(cl, received, e);
return read(downgraded, retryCount + 1);
}
// If we received enough replies to meet the consistency level,
// but the actual data was not present among the received responses,
// then retry with the initial consistency level, we might be luckier next time
// and get the data back.
if (!readTimeout.wasDataPresent()) {
return read(cl, retryCount + 1);
}
// Otherwise, abort since the read timeout is unlikely to be solved by a retry.
throw e;
} else {
// Unexpected error: just retry with same consistency level
// and hope to talk to a healthier coordinator.
return read(cl, retryCount + 1);
}
}
} | java | private ResultSet read(ConsistencyLevel cl, int retryCount) {
System.out.printf("Reading at %s (retry count: %d)%n", cl, retryCount);
Statement stmt =
SimpleStatement.newInstance(
"SELECT sensor_id, date, timestamp, value "
+ "FROM downgrading.sensor_data "
+ "WHERE "
+ "sensor_id = 756716f7-2e54-4715-9f00-91dcbea6cf50 AND "
+ "date = '2018-02-26' AND "
+ "timestamp > '2018-02-26+01:00'")
.setConsistencyLevel(cl);
try {
ResultSet rows = session.execute(stmt);
System.out.println("Read succeeded at " + cl);
return rows;
} catch (DriverException e) {
if (retryCount == maxRetries) {
throw e;
}
e = unwrapAllNodesFailedException(e);
System.out.println("Read failed: " + e);
// General intent: downgrade and retry at the highest consistency level
// that is likely to succeed.
if (e instanceof UnavailableException) {
// Downgrade to the number of replicas reported alive and retry.
int aliveReplicas = ((UnavailableException) e).getAlive();
ConsistencyLevel downgraded = downgrade(cl, aliveReplicas, e);
return read(downgraded, retryCount + 1);
} else if (e instanceof ReadTimeoutException) {
ReadTimeoutException readTimeout = (ReadTimeoutException) e;
int received = readTimeout.getReceived();
int required = readTimeout.getBlockFor();
// If fewer replicas responded than required by the consistency level
// (but at least one replica did respond), retry with a consistency level
// equal to the number of received acknowledgements.
if (received < required) {
ConsistencyLevel downgraded = downgrade(cl, received, e);
return read(downgraded, retryCount + 1);
}
// If we received enough replies to meet the consistency level,
// but the actual data was not present among the received responses,
// then retry with the initial consistency level, we might be luckier next time
// and get the data back.
if (!readTimeout.wasDataPresent()) {
return read(cl, retryCount + 1);
}
// Otherwise, abort since the read timeout is unlikely to be solved by a retry.
throw e;
} else {
// Unexpected error: just retry with same consistency level
// and hope to talk to a healthier coordinator.
return read(cl, retryCount + 1);
}
}
} | [
"private",
"ResultSet",
"read",
"(",
"ConsistencyLevel",
"cl",
",",
"int",
"retryCount",
")",
"{",
"System",
".",
"out",
".",
"printf",
"(",
"\"Reading at %s (retry count: %d)%n\"",
",",
"cl",
",",
"retryCount",
")",
";",
"Statement",
"stmt",
"=",
"SimpleStatement",
".",
"newInstance",
"(",
"\"SELECT sensor_id, date, timestamp, value \"",
"+",
"\"FROM downgrading.sensor_data \"",
"+",
"\"WHERE \"",
"+",
"\"sensor_id = 756716f7-2e54-4715-9f00-91dcbea6cf50 AND \"",
"+",
"\"date = '2018-02-26' AND \"",
"+",
"\"timestamp > '2018-02-26+01:00'\"",
")",
".",
"setConsistencyLevel",
"(",
"cl",
")",
";",
"try",
"{",
"ResultSet",
"rows",
"=",
"session",
".",
"execute",
"(",
"stmt",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"Read succeeded at \"",
"+",
"cl",
")",
";",
"return",
"rows",
";",
"}",
"catch",
"(",
"DriverException",
"e",
")",
"{",
"if",
"(",
"retryCount",
"==",
"maxRetries",
")",
"{",
"throw",
"e",
";",
"}",
"e",
"=",
"unwrapAllNodesFailedException",
"(",
"e",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"Read failed: \"",
"+",
"e",
")",
";",
"// General intent: downgrade and retry at the highest consistency level",
"// that is likely to succeed.",
"if",
"(",
"e",
"instanceof",
"UnavailableException",
")",
"{",
"// Downgrade to the number of replicas reported alive and retry.",
"int",
"aliveReplicas",
"=",
"(",
"(",
"UnavailableException",
")",
"e",
")",
".",
"getAlive",
"(",
")",
";",
"ConsistencyLevel",
"downgraded",
"=",
"downgrade",
"(",
"cl",
",",
"aliveReplicas",
",",
"e",
")",
";",
"return",
"read",
"(",
"downgraded",
",",
"retryCount",
"+",
"1",
")",
";",
"}",
"else",
"if",
"(",
"e",
"instanceof",
"ReadTimeoutException",
")",
"{",
"ReadTimeoutException",
"readTimeout",
"=",
"(",
"ReadTimeoutException",
")",
"e",
";",
"int",
"received",
"=",
"readTimeout",
".",
"getReceived",
"(",
")",
";",
"int",
"required",
"=",
"readTimeout",
".",
"getBlockFor",
"(",
")",
";",
"// If fewer replicas responded than required by the consistency level",
"// (but at least one replica did respond), retry with a consistency level",
"// equal to the number of received acknowledgements.",
"if",
"(",
"received",
"<",
"required",
")",
"{",
"ConsistencyLevel",
"downgraded",
"=",
"downgrade",
"(",
"cl",
",",
"received",
",",
"e",
")",
";",
"return",
"read",
"(",
"downgraded",
",",
"retryCount",
"+",
"1",
")",
";",
"}",
"// If we received enough replies to meet the consistency level,",
"// but the actual data was not present among the received responses,",
"// then retry with the initial consistency level, we might be luckier next time",
"// and get the data back.",
"if",
"(",
"!",
"readTimeout",
".",
"wasDataPresent",
"(",
")",
")",
"{",
"return",
"read",
"(",
"cl",
",",
"retryCount",
"+",
"1",
")",
";",
"}",
"// Otherwise, abort since the read timeout is unlikely to be solved by a retry.",
"throw",
"e",
";",
"}",
"else",
"{",
"// Unexpected error: just retry with same consistency level",
"// and hope to talk to a healthier coordinator.",
"return",
"read",
"(",
"cl",
",",
"retryCount",
"+",
"1",
")",
";",
"}",
"}",
"}"
] | Queries data, retrying if necessary with a downgraded CL.
@param cl the consistency level to apply.
@param retryCount the current retry count.
@throws DriverException if the current consistency level cannot be downgraded. | [
"Queries",
"data",
"retrying",
"if",
"necessary",
"with",
"a",
"downgraded",
"CL",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java#L259-L334 | train |
datastax/java-driver | examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java | DowngradingRetry.display | private void display(ResultSet rows) {
final int width1 = 38;
final int width2 = 12;
final int width3 = 30;
final int width4 = 21;
String format = "%-" + width1 + "s%-" + width2 + "s%-" + width3 + "s%-" + width4 + "s%n";
// headings
System.out.printf(format, "sensor_id", "date", "timestamp", "value");
// separators
drawLine(width1, width2, width3, width4);
// data
for (Row row : rows) {
System.out.printf(
format,
row.getUuid("sensor_id"),
row.getLocalDate("date"),
row.getInstant("timestamp"),
row.getDouble("value"));
}
} | java | private void display(ResultSet rows) {
final int width1 = 38;
final int width2 = 12;
final int width3 = 30;
final int width4 = 21;
String format = "%-" + width1 + "s%-" + width2 + "s%-" + width3 + "s%-" + width4 + "s%n";
// headings
System.out.printf(format, "sensor_id", "date", "timestamp", "value");
// separators
drawLine(width1, width2, width3, width4);
// data
for (Row row : rows) {
System.out.printf(
format,
row.getUuid("sensor_id"),
row.getLocalDate("date"),
row.getInstant("timestamp"),
row.getDouble("value"));
}
} | [
"private",
"void",
"display",
"(",
"ResultSet",
"rows",
")",
"{",
"final",
"int",
"width1",
"=",
"38",
";",
"final",
"int",
"width2",
"=",
"12",
";",
"final",
"int",
"width3",
"=",
"30",
";",
"final",
"int",
"width4",
"=",
"21",
";",
"String",
"format",
"=",
"\"%-\"",
"+",
"width1",
"+",
"\"s%-\"",
"+",
"width2",
"+",
"\"s%-\"",
"+",
"width3",
"+",
"\"s%-\"",
"+",
"width4",
"+",
"\"s%n\"",
";",
"// headings",
"System",
".",
"out",
".",
"printf",
"(",
"format",
",",
"\"sensor_id\"",
",",
"\"date\"",
",",
"\"timestamp\"",
",",
"\"value\"",
")",
";",
"// separators",
"drawLine",
"(",
"width1",
",",
"width2",
",",
"width3",
",",
"width4",
")",
";",
"// data",
"for",
"(",
"Row",
"row",
":",
"rows",
")",
"{",
"System",
".",
"out",
".",
"printf",
"(",
"format",
",",
"row",
".",
"getUuid",
"(",
"\"sensor_id\"",
")",
",",
"row",
".",
"getLocalDate",
"(",
"\"date\"",
")",
",",
"row",
".",
"getInstant",
"(",
"\"timestamp\"",
")",
",",
"row",
".",
"getDouble",
"(",
"\"value\"",
")",
")",
";",
"}",
"}"
] | Displays the results on the console.
@param rows the results to display. | [
"Displays",
"the",
"results",
"on",
"the",
"console",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java#L341-L366 | train |
datastax/java-driver | examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java | DowngradingRetry.downgrade | private static ConsistencyLevel downgrade(
ConsistencyLevel current, int acknowledgements, DriverException original) {
if (acknowledgements >= 3) {
return DefaultConsistencyLevel.THREE;
}
if (acknowledgements == 2) {
return DefaultConsistencyLevel.TWO;
}
if (acknowledgements == 1) {
return DefaultConsistencyLevel.ONE;
}
// Edge case: EACH_QUORUM does not report a global number of alive replicas
// so even if we get 0 alive replicas, there might be
// a node up in some other datacenter, so retry at ONE.
if (current == DefaultConsistencyLevel.EACH_QUORUM) {
return DefaultConsistencyLevel.ONE;
}
throw original;
} | java | private static ConsistencyLevel downgrade(
ConsistencyLevel current, int acknowledgements, DriverException original) {
if (acknowledgements >= 3) {
return DefaultConsistencyLevel.THREE;
}
if (acknowledgements == 2) {
return DefaultConsistencyLevel.TWO;
}
if (acknowledgements == 1) {
return DefaultConsistencyLevel.ONE;
}
// Edge case: EACH_QUORUM does not report a global number of alive replicas
// so even if we get 0 alive replicas, there might be
// a node up in some other datacenter, so retry at ONE.
if (current == DefaultConsistencyLevel.EACH_QUORUM) {
return DefaultConsistencyLevel.ONE;
}
throw original;
} | [
"private",
"static",
"ConsistencyLevel",
"downgrade",
"(",
"ConsistencyLevel",
"current",
",",
"int",
"acknowledgements",
",",
"DriverException",
"original",
")",
"{",
"if",
"(",
"acknowledgements",
">=",
"3",
")",
"{",
"return",
"DefaultConsistencyLevel",
".",
"THREE",
";",
"}",
"if",
"(",
"acknowledgements",
"==",
"2",
")",
"{",
"return",
"DefaultConsistencyLevel",
".",
"TWO",
";",
"}",
"if",
"(",
"acknowledgements",
"==",
"1",
")",
"{",
"return",
"DefaultConsistencyLevel",
".",
"ONE",
";",
"}",
"// Edge case: EACH_QUORUM does not report a global number of alive replicas",
"// so even if we get 0 alive replicas, there might be",
"// a node up in some other datacenter, so retry at ONE.",
"if",
"(",
"current",
"==",
"DefaultConsistencyLevel",
".",
"EACH_QUORUM",
")",
"{",
"return",
"DefaultConsistencyLevel",
".",
"ONE",
";",
"}",
"throw",
"original",
";",
"}"
] | Downgrades the current consistency level to the highest level that is likely to succeed, given
the number of acknowledgements received. Rethrows the original exception if the current
consistency level cannot be downgraded any further.
@param current the current CL.
@param acknowledgements the acknowledgements received.
@param original the original exception.
@return the downgraded CL.
@throws DriverException if the current consistency level cannot be downgraded. | [
"Downgrades",
"the",
"current",
"consistency",
"level",
"to",
"the",
"highest",
"level",
"that",
"is",
"likely",
"to",
"succeed",
"given",
"the",
"number",
"of",
"acknowledgements",
"received",
".",
"Rethrows",
"the",
"original",
"exception",
"if",
"the",
"current",
"consistency",
"level",
"cannot",
"be",
"downgraded",
"any",
"further",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java#L386-L404 | train |
datastax/java-driver | examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java | DowngradingRetry.drawLine | private static void drawLine(int... widths) {
for (int width : widths) {
for (int i = 1; i < width; i++) {
System.out.print('-');
}
System.out.print('+');
}
System.out.println();
} | java | private static void drawLine(int... widths) {
for (int width : widths) {
for (int i = 1; i < width; i++) {
System.out.print('-');
}
System.out.print('+');
}
System.out.println();
} | [
"private",
"static",
"void",
"drawLine",
"(",
"int",
"...",
"widths",
")",
"{",
"for",
"(",
"int",
"width",
":",
"widths",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"width",
";",
"i",
"++",
")",
"{",
"System",
".",
"out",
".",
"print",
"(",
"'",
"'",
")",
";",
"}",
"System",
".",
"out",
".",
"print",
"(",
"'",
"'",
")",
";",
"}",
"System",
".",
"out",
".",
"println",
"(",
")",
";",
"}"
] | Draws a line to isolate headings from rows.
@param widths the column widths. | [
"Draws",
"a",
"line",
"to",
"isolate",
"headings",
"from",
"rows",
"."
] | 612a63f2525618e2020e86c9ad75ab37adba6132 | https://github.com/datastax/java-driver/blob/612a63f2525618e2020e86c9ad75ab37adba6132/examples/src/main/java/com/datastax/oss/driver/examples/retry/DowngradingRetry.java#L438-L446 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.