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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bazaarvoice/emodb | common/client/src/main/java/com/bazaarvoice/emodb/client/uri/EmoUriComponent.java | EmoUriComponent.encode | public static String encode(String s, Type t) {
return _encode(s, t, false, false);
} | java | public static String encode(String s, Type t) {
return _encode(s, t, false, false);
} | [
"public",
"static",
"String",
"encode",
"(",
"String",
"s",
",",
"Type",
"t",
")",
"{",
"return",
"_encode",
"(",
"s",
",",
"t",
",",
"false",
",",
"false",
")",
";",
"}"
] | Encodes the characters of string that are either non-ASCII characters
or are ASCII characters that must be percent-encoded using the
UTF-8 encoding.
@param s the string to be encoded.
@param t the URI component type identifying the ASCII characters that
must be percent-encoded.
@return the encoded string. | [
"Encodes",
"the",
"characters",
"of",
"string",
"that",
"are",
"either",
"non",
"-",
"ASCII",
"characters",
"or",
"are",
"ASCII",
"characters",
"that",
"must",
"be",
"percent",
"-",
"encoded",
"using",
"the",
"UTF",
"-",
"8",
"encoding",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/client/src/main/java/com/bazaarvoice/emodb/client/uri/EmoUriComponent.java#L197-L199 | train |
bazaarvoice/emodb | common/client/src/main/java/com/bazaarvoice/emodb/client/uri/EmoUriComponent.java | EmoUriComponent.decodePath | public static List<PathSegment> decodePath(URI u, boolean decode) {
String rawPath = u.getRawPath();
if (rawPath != null && rawPath.length() > 0 && rawPath.charAt(0) == '/') {
rawPath = rawPath.substring(1);
}
return decodePath(rawPath, decode);
} | java | public static List<PathSegment> decodePath(URI u, boolean decode) {
String rawPath = u.getRawPath();
if (rawPath != null && rawPath.length() > 0 && rawPath.charAt(0) == '/') {
rawPath = rawPath.substring(1);
}
return decodePath(rawPath, decode);
} | [
"public",
"static",
"List",
"<",
"PathSegment",
">",
"decodePath",
"(",
"URI",
"u",
",",
"boolean",
"decode",
")",
"{",
"String",
"rawPath",
"=",
"u",
".",
"getRawPath",
"(",
")",
";",
"if",
"(",
"rawPath",
"!=",
"null",
"&&",
"rawPath",
".",
"length",... | Decode the path component of a URI as path segments.
@param u the URI. If the path component is an absolute path component
then the leading '/' is ignored and is not considered a delimiator
of a path segment.
@param decode true if the path segments of the path component
should be in decoded form.
@return the list of path segments. | [
"Decode",
"the",
"path",
"component",
"of",
"a",
"URI",
"as",
"path",
"segments",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/client/src/main/java/com/bazaarvoice/emodb/client/uri/EmoUriComponent.java#L590-L596 | train |
bazaarvoice/emodb | common/client/src/main/java/com/bazaarvoice/emodb/client/uri/EmoUriComponent.java | EmoUriComponent.decodePathSegment | public static void decodePathSegment(List<PathSegment> segments, String segment, boolean decode) {
int colon = segment.indexOf(';');
if (colon != -1) {
segments.add(new PathSegmentImpl(
(colon == 0) ? "" : segment.substring(0, colon),
decode,
decodeMatrix(segment, decode)));
} else {
segments.add(new PathSegmentImpl(
segment,
decode));
}
} | java | public static void decodePathSegment(List<PathSegment> segments, String segment, boolean decode) {
int colon = segment.indexOf(';');
if (colon != -1) {
segments.add(new PathSegmentImpl(
(colon == 0) ? "" : segment.substring(0, colon),
decode,
decodeMatrix(segment, decode)));
} else {
segments.add(new PathSegmentImpl(
segment,
decode));
}
} | [
"public",
"static",
"void",
"decodePathSegment",
"(",
"List",
"<",
"PathSegment",
">",
"segments",
",",
"String",
"segment",
",",
"boolean",
"decode",
")",
"{",
"int",
"colon",
"=",
"segment",
".",
"indexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"colon",
... | Decode the path segment and add it to the list of path segments.
@param segments mutable list of path segments.
@param segment path segment to be decoded.
@param decode {@code true} if the path segment should be in a decoded form. | [
"Decode",
"the",
"path",
"segment",
"and",
"add",
"it",
"to",
"the",
"list",
"of",
"path",
"segments",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/client/src/main/java/com/bazaarvoice/emodb/client/uri/EmoUriComponent.java#L648-L660 | train |
bazaarvoice/emodb | common/client/src/main/java/com/bazaarvoice/emodb/client/uri/EmoUriComponent.java | EmoUriComponent.decodeMatrix | public static MultivaluedMap<String, String> decodeMatrix(String pathSegment, boolean decode) {
// EMODB-MODIFICATION Replaced with EmoMultivaluedMap implementation
MultivaluedMap<String, String> matrixMap = EmoMultivaluedMap.create();
// Skip over path segment
int s = pathSegment.indexOf(';') + 1;
if (s == 0 || s == pathSegment.length()) {
return matrixMap;
}
do {
int e = pathSegment.indexOf(';', s);
if (e == -1) {
decodeMatrixParam(matrixMap, pathSegment.substring(s), decode);
} else if (e > s) {
decodeMatrixParam(matrixMap, pathSegment.substring(s, e), decode);
}
s = e + 1;
} while (s > 0 && s < pathSegment.length());
return matrixMap;
} | java | public static MultivaluedMap<String, String> decodeMatrix(String pathSegment, boolean decode) {
// EMODB-MODIFICATION Replaced with EmoMultivaluedMap implementation
MultivaluedMap<String, String> matrixMap = EmoMultivaluedMap.create();
// Skip over path segment
int s = pathSegment.indexOf(';') + 1;
if (s == 0 || s == pathSegment.length()) {
return matrixMap;
}
do {
int e = pathSegment.indexOf(';', s);
if (e == -1) {
decodeMatrixParam(matrixMap, pathSegment.substring(s), decode);
} else if (e > s) {
decodeMatrixParam(matrixMap, pathSegment.substring(s, e), decode);
}
s = e + 1;
} while (s > 0 && s < pathSegment.length());
return matrixMap;
} | [
"public",
"static",
"MultivaluedMap",
"<",
"String",
",",
"String",
">",
"decodeMatrix",
"(",
"String",
"pathSegment",
",",
"boolean",
"decode",
")",
"{",
"// EMODB-MODIFICATION Replaced with EmoMultivaluedMap implementation",
"MultivaluedMap",
"<",
"String",
",",
"String... | Decode the matrix component of a URI path segment.
@param pathSegment the path segment component in encoded form.
@param decode true if the matrix parameters of the path segment component
should be in decoded form.
@return the multivalued map of matrix parameters. | [
"Decode",
"the",
"matrix",
"component",
"of",
"a",
"URI",
"path",
"segment",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/client/src/main/java/com/bazaarvoice/emodb/client/uri/EmoUriComponent.java#L670-L692 | train |
bazaarvoice/emodb | common/client/src/main/java/com/bazaarvoice/emodb/client/uri/EmoUriComponent.java | EmoUriComponent.decodeOctets | private static int decodeOctets(int i, ByteBuffer bb, StringBuilder sb) {
// If there is only one octet and is an ASCII character
if (bb.limit() == 1 && (bb.get(0) & 0xFF) < 0x80) {
// Octet can be appended directly
sb.append((char) bb.get(0));
return i + 2;
} else {
//
CharBuffer cb = UTF_8_CHARSET.decode(bb);
sb.append(cb.toString());
return i + bb.limit() * 3 - 1;
}
} | java | private static int decodeOctets(int i, ByteBuffer bb, StringBuilder sb) {
// If there is only one octet and is an ASCII character
if (bb.limit() == 1 && (bb.get(0) & 0xFF) < 0x80) {
// Octet can be appended directly
sb.append((char) bb.get(0));
return i + 2;
} else {
//
CharBuffer cb = UTF_8_CHARSET.decode(bb);
sb.append(cb.toString());
return i + bb.limit() * 3 - 1;
}
} | [
"private",
"static",
"int",
"decodeOctets",
"(",
"int",
"i",
",",
"ByteBuffer",
"bb",
",",
"StringBuilder",
"sb",
")",
"{",
"// If there is only one octet and is an ASCII character",
"if",
"(",
"bb",
".",
"limit",
"(",
")",
"==",
"1",
"&&",
"(",
"bb",
".",
"... | Decodes octets to characters using the UTF-8 decoding and appends
the characters to a StringBuffer.
@return the index to the next unchecked character in the string to decode | [
"Decodes",
"octets",
"to",
"characters",
"using",
"the",
"UTF",
"-",
"8",
"decoding",
"and",
"appends",
"the",
"characters",
"to",
"a",
"StringBuffer",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/client/src/main/java/com/bazaarvoice/emodb/client/uri/EmoUriComponent.java#L822-L834 | train |
bazaarvoice/emodb | auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/shiro/PrincipalWithRoles.java | PrincipalWithRoles.toUserIdentity | public UserIdentity toUserIdentity() {
if (_userIdentity == null) {
String[] roles = _roles.toArray(new String[_roles.size()]);
_userIdentity = new DefaultUserIdentity(
new javax.security.auth.Subject(true, ImmutableSet.of(this), ImmutableSet.of(), ImmutableSet.of()),
new BasicUserPrincipal(getId()), roles);
}
return _userIdentity;
} | java | public UserIdentity toUserIdentity() {
if (_userIdentity == null) {
String[] roles = _roles.toArray(new String[_roles.size()]);
_userIdentity = new DefaultUserIdentity(
new javax.security.auth.Subject(true, ImmutableSet.of(this), ImmutableSet.of(), ImmutableSet.of()),
new BasicUserPrincipal(getId()), roles);
}
return _userIdentity;
} | [
"public",
"UserIdentity",
"toUserIdentity",
"(",
")",
"{",
"if",
"(",
"_userIdentity",
"==",
"null",
")",
"{",
"String",
"[",
"]",
"roles",
"=",
"_roles",
".",
"toArray",
"(",
"new",
"String",
"[",
"_roles",
".",
"size",
"(",
")",
"]",
")",
";",
"_us... | Returns this instance as a Jetty UserIdentity. The returned instance is immutable and cached. | [
"Returns",
"this",
"instance",
"as",
"a",
"Jetty",
"UserIdentity",
".",
"The",
"returned",
"instance",
"is",
"immutable",
"and",
"cached",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/shiro/PrincipalWithRoles.java#L47-L56 | train |
bazaarvoice/emodb | common/stash/src/main/java/com/bazaarvoice/emodb/common/stash/RestartingS3InputStream.java | RestartingS3InputStream.reopenS3InputStream | private void reopenS3InputStream()
throws IOException {
// First attempt to close the existing input stream
try {
closeS3InputStream();
} catch (IOException ignore) {
// Ignore this exception; we're re-opening because there was in issue with the existing stream
// in the first place.
}
InputStream remainingIn = null;
int attempt = 0;
while (remainingIn == null) {
try {
S3Object s3Object = _s3.getObject(
new GetObjectRequest(_bucket, _key)
.withRange(_pos, _length - 1)); // Range is inclusive, hence length-1
remainingIn = s3Object.getObjectContent();
} catch (AmazonClientException e) {
// Allow up to 3 retries
attempt += 1;
if (!e.isRetryable() || attempt == 4) {
throw e;
}
// Back-off on each retry
try {
Thread.sleep(200 * attempt);
} catch (InterruptedException interrupt) {
throw Throwables.propagate(interrupt);
}
}
}
_in = remainingIn;
} | java | private void reopenS3InputStream()
throws IOException {
// First attempt to close the existing input stream
try {
closeS3InputStream();
} catch (IOException ignore) {
// Ignore this exception; we're re-opening because there was in issue with the existing stream
// in the first place.
}
InputStream remainingIn = null;
int attempt = 0;
while (remainingIn == null) {
try {
S3Object s3Object = _s3.getObject(
new GetObjectRequest(_bucket, _key)
.withRange(_pos, _length - 1)); // Range is inclusive, hence length-1
remainingIn = s3Object.getObjectContent();
} catch (AmazonClientException e) {
// Allow up to 3 retries
attempt += 1;
if (!e.isRetryable() || attempt == 4) {
throw e;
}
// Back-off on each retry
try {
Thread.sleep(200 * attempt);
} catch (InterruptedException interrupt) {
throw Throwables.propagate(interrupt);
}
}
}
_in = remainingIn;
} | [
"private",
"void",
"reopenS3InputStream",
"(",
")",
"throws",
"IOException",
"{",
"// First attempt to close the existing input stream",
"try",
"{",
"closeS3InputStream",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"ignore",
")",
"{",
"// Ignore this exception; we're... | Re-opens the input stream, starting at the first unread byte. | [
"Re",
"-",
"opens",
"the",
"input",
"stream",
"starting",
"at",
"the",
"first",
"unread",
"byte",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/stash/src/main/java/com/bazaarvoice/emodb/common/stash/RestartingS3InputStream.java#L137-L172 | train |
bazaarvoice/emodb | table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/TableJson.java | TableJson.newDropTable | Delta newDropTable() {
Delta storageDelta = Deltas.mapBuilder()
.put(StorageState.DROPPED.getMarkerAttribute().key(), now())
.build();
MapDeltaBuilder storageMapDelta = Deltas.mapBuilder();
if (_master != null) {
for (Storage storage : _master.getPrimaryAndMirrors()) {
storageMapDelta.update(storage.getUuidString(), storageDelta);
}
}
for (Storage facade : _facades) {
for (Storage storage : facade.getPrimaryAndMirrors()) {
storageMapDelta.update(storage.getUuidString(), storageDelta);
}
}
// Delete most of the information about the table, but leave enough that we can run a job later that
// purges all the data out of Cassandra.
return Deltas.mapBuilder()
.remove(UUID_ATTR.key())
.remove(ATTRIBUTES.key())
.update(STORAGE.key(), storageMapDelta.build())
.removeRest()
.build();
} | java | Delta newDropTable() {
Delta storageDelta = Deltas.mapBuilder()
.put(StorageState.DROPPED.getMarkerAttribute().key(), now())
.build();
MapDeltaBuilder storageMapDelta = Deltas.mapBuilder();
if (_master != null) {
for (Storage storage : _master.getPrimaryAndMirrors()) {
storageMapDelta.update(storage.getUuidString(), storageDelta);
}
}
for (Storage facade : _facades) {
for (Storage storage : facade.getPrimaryAndMirrors()) {
storageMapDelta.update(storage.getUuidString(), storageDelta);
}
}
// Delete most of the information about the table, but leave enough that we can run a job later that
// purges all the data out of Cassandra.
return Deltas.mapBuilder()
.remove(UUID_ATTR.key())
.remove(ATTRIBUTES.key())
.update(STORAGE.key(), storageMapDelta.build())
.removeRest()
.build();
} | [
"Delta",
"newDropTable",
"(",
")",
"{",
"Delta",
"storageDelta",
"=",
"Deltas",
".",
"mapBuilder",
"(",
")",
".",
"put",
"(",
"StorageState",
".",
"DROPPED",
".",
"getMarkerAttribute",
"(",
")",
".",
"key",
"(",
")",
",",
"now",
"(",
")",
")",
".",
"... | Mark an entire table as dropped. A maintenance job will come along later and actually purge the data. | [
"Mark",
"an",
"entire",
"table",
"as",
"dropped",
".",
"A",
"maintenance",
"job",
"will",
"come",
"along",
"later",
"and",
"actually",
"purge",
"the",
"data",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/TableJson.java#L175-L200 | train |
bazaarvoice/emodb | table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/TableJson.java | TableJson.newDropFacade | Delta newDropFacade(Storage facade) {
Delta storageDelta = Deltas.mapBuilder()
.put(StorageState.DROPPED.getMarkerAttribute().key(), now())
.build();
MapDeltaBuilder storageMapDelta = Deltas.mapBuilder();
for (Storage storage : facade.getPrimaryAndMirrors()) {
storageMapDelta.update(storage.getUuidString(), storageDelta);
}
return Deltas.mapBuilder()
.update(STORAGE.key(), storageMapDelta.build())
.build();
} | java | Delta newDropFacade(Storage facade) {
Delta storageDelta = Deltas.mapBuilder()
.put(StorageState.DROPPED.getMarkerAttribute().key(), now())
.build();
MapDeltaBuilder storageMapDelta = Deltas.mapBuilder();
for (Storage storage : facade.getPrimaryAndMirrors()) {
storageMapDelta.update(storage.getUuidString(), storageDelta);
}
return Deltas.mapBuilder()
.update(STORAGE.key(), storageMapDelta.build())
.build();
} | [
"Delta",
"newDropFacade",
"(",
"Storage",
"facade",
")",
"{",
"Delta",
"storageDelta",
"=",
"Deltas",
".",
"mapBuilder",
"(",
")",
".",
"put",
"(",
"StorageState",
".",
"DROPPED",
".",
"getMarkerAttribute",
"(",
")",
".",
"key",
"(",
")",
",",
"now",
"("... | Mark a facade as dropped. A maintenance job will come along later and actually purge the data. | [
"Mark",
"a",
"facade",
"as",
"dropped",
".",
"A",
"maintenance",
"job",
"will",
"come",
"along",
"later",
"and",
"actually",
"purge",
"the",
"data",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/TableJson.java#L203-L216 | train |
bazaarvoice/emodb | table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/TableJson.java | TableJson.newMoveStart | Delta newMoveStart(Storage src, String destUuid, String destPlacement, int destShardsLog2) {
return Deltas.mapBuilder()
.update(STORAGE.key(), Deltas.mapBuilder()
.update(src.getUuidString(), Deltas.mapBuilder()
.put(Storage.MOVE_TO.key(), destUuid)
.build())
.put(destUuid, storageAttributesBuilder(destPlacement, destShardsLog2, src.isFacade())
.put(StorageState.MIRROR_CREATED.getMarkerAttribute().key(), now())
.put(Storage.GROUP_ID.key(), src.getGroupId())
.build())
.build())
.build();
} | java | Delta newMoveStart(Storage src, String destUuid, String destPlacement, int destShardsLog2) {
return Deltas.mapBuilder()
.update(STORAGE.key(), Deltas.mapBuilder()
.update(src.getUuidString(), Deltas.mapBuilder()
.put(Storage.MOVE_TO.key(), destUuid)
.build())
.put(destUuid, storageAttributesBuilder(destPlacement, destShardsLog2, src.isFacade())
.put(StorageState.MIRROR_CREATED.getMarkerAttribute().key(), now())
.put(Storage.GROUP_ID.key(), src.getGroupId())
.build())
.build())
.build();
} | [
"Delta",
"newMoveStart",
"(",
"Storage",
"src",
",",
"String",
"destUuid",
",",
"String",
"destPlacement",
",",
"int",
"destShardsLog2",
")",
"{",
"return",
"Deltas",
".",
"mapBuilder",
"(",
")",
".",
"update",
"(",
"STORAGE",
".",
"key",
"(",
")",
",",
... | First step in a move, creates the destination storage and sets up mirroring. | [
"First",
"step",
"in",
"a",
"move",
"creates",
"the",
"destination",
"storage",
"and",
"sets",
"up",
"mirroring",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/TableJson.java#L236-L248 | train |
bazaarvoice/emodb | table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/TableJson.java | TableJson.newMoveRestart | Delta newMoveRestart(Storage src, Storage dest) {
// If the destination used to be the initial primary for the group, it's consistent and ready to promote
// but lacking the MIRROR_CONSISTENT marker attribute which is the prereq for promotion. Add one.
Delta consistentMarker = dest.isConsistent() ?
Deltas.conditional(Conditions.isUndefined(), Deltas.literal(now())) :
Deltas.noop();
return Deltas.mapBuilder()
.update(STORAGE.key(), Deltas.mapBuilder()
.update(src.getUuidString(), Deltas.mapBuilder()
.put(Storage.MOVE_TO.key(), dest.getUuidString())
.build())
.update(dest.getUuidString(), Deltas.mapBuilder()
// Clean slate: clear 'moveTo' plus all markers for promotion states and later.
.update(StorageState.MIRROR_CONSISTENT.getMarkerAttribute().key(), consistentMarker)
.remove(Storage.MOVE_TO.key())
.remove(Storage.PROMOTION_ID.key())
.remove(StorageState.PRIMARY.getMarkerAttribute().key())
.remove(StorageState.MIRROR_EXPIRING.getMarkerAttribute().key())
.remove(StorageState.MIRROR_EXPIRED.getMarkerAttribute().key())
.build())
.build())
.build();
} | java | Delta newMoveRestart(Storage src, Storage dest) {
// If the destination used to be the initial primary for the group, it's consistent and ready to promote
// but lacking the MIRROR_CONSISTENT marker attribute which is the prereq for promotion. Add one.
Delta consistentMarker = dest.isConsistent() ?
Deltas.conditional(Conditions.isUndefined(), Deltas.literal(now())) :
Deltas.noop();
return Deltas.mapBuilder()
.update(STORAGE.key(), Deltas.mapBuilder()
.update(src.getUuidString(), Deltas.mapBuilder()
.put(Storage.MOVE_TO.key(), dest.getUuidString())
.build())
.update(dest.getUuidString(), Deltas.mapBuilder()
// Clean slate: clear 'moveTo' plus all markers for promotion states and later.
.update(StorageState.MIRROR_CONSISTENT.getMarkerAttribute().key(), consistentMarker)
.remove(Storage.MOVE_TO.key())
.remove(Storage.PROMOTION_ID.key())
.remove(StorageState.PRIMARY.getMarkerAttribute().key())
.remove(StorageState.MIRROR_EXPIRING.getMarkerAttribute().key())
.remove(StorageState.MIRROR_EXPIRED.getMarkerAttribute().key())
.build())
.build())
.build();
} | [
"Delta",
"newMoveRestart",
"(",
"Storage",
"src",
",",
"Storage",
"dest",
")",
"{",
"// If the destination used to be the initial primary for the group, it's consistent and ready to promote",
"// but lacking the MIRROR_CONSISTENT marker attribute which is the prereq for promotion. Add one.",
... | Start a move to an existing mirror that may or may not have once been primary. | [
"Start",
"a",
"move",
"to",
"an",
"existing",
"mirror",
"that",
"may",
"or",
"may",
"not",
"have",
"once",
"been",
"primary",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/TableJson.java#L268-L290 | train |
bazaarvoice/emodb | sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStash.java | DataStoreStash.listStashTables | public Iterable<StashTable> listStashTables()
throws StashNotAvailableException {
final StashReader stashReader = _stashReader.getLockedView();
return new Iterable<StashTable>() {
@Override
public Iterator<StashTable> iterator() {
return stashReader.listTables();
}
};
} | java | public Iterable<StashTable> listStashTables()
throws StashNotAvailableException {
final StashReader stashReader = _stashReader.getLockedView();
return new Iterable<StashTable>() {
@Override
public Iterator<StashTable> iterator() {
return stashReader.listTables();
}
};
} | [
"public",
"Iterable",
"<",
"StashTable",
">",
"listStashTables",
"(",
")",
"throws",
"StashNotAvailableException",
"{",
"final",
"StashReader",
"stashReader",
"=",
"_stashReader",
".",
"getLockedView",
"(",
")",
";",
"return",
"new",
"Iterable",
"<",
"StashTable",
... | Lists all tables present in Stash. Note that tables that were present in EmoDB but empty during the
Stash operation are not listed. | [
"Lists",
"all",
"tables",
"present",
"in",
"Stash",
".",
"Note",
"that",
"tables",
"that",
"were",
"present",
"in",
"EmoDB",
"but",
"empty",
"during",
"the",
"Stash",
"operation",
"are",
"not",
"listed",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStash.java#L145-L155 | train |
bazaarvoice/emodb | sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStash.java | DataStoreStash.scan | public StashRowIterable scan(final String table)
throws StashNotAvailableException, TableNotStashedException {
try {
final StashReader stashReader = _stashReader.getLockedView();
return new StashRowIterable() {
@Override
protected StashRowIterator createStashRowIterator() {
return stashReader.scan(table);
}
};
} catch (TableNotStashedException e) {
throw propagateTableNotStashed(e);
}
} | java | public StashRowIterable scan(final String table)
throws StashNotAvailableException, TableNotStashedException {
try {
final StashReader stashReader = _stashReader.getLockedView();
return new StashRowIterable() {
@Override
protected StashRowIterator createStashRowIterator() {
return stashReader.scan(table);
}
};
} catch (TableNotStashedException e) {
throw propagateTableNotStashed(e);
}
} | [
"public",
"StashRowIterable",
"scan",
"(",
"final",
"String",
"table",
")",
"throws",
"StashNotAvailableException",
",",
"TableNotStashedException",
"{",
"try",
"{",
"final",
"StashReader",
"stashReader",
"=",
"_stashReader",
".",
"getLockedView",
"(",
")",
";",
"re... | Scans all rows from Stash for the given table. | [
"Scans",
"all",
"rows",
"from",
"Stash",
"for",
"the",
"given",
"table",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStash.java#L204-L218 | train |
bazaarvoice/emodb | sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStash.java | DataStoreStash.getSplits | public Collection<String> getSplits(String table)
throws StashNotAvailableException, TableNotStashedException {
try {
return FluentIterable.from(_stashReader.getSplits(table))
.transform(Functions.toStringFunction())
.toList();
} catch (TableNotStashedException e) {
throw propagateTableNotStashed(e);
}
} | java | public Collection<String> getSplits(String table)
throws StashNotAvailableException, TableNotStashedException {
try {
return FluentIterable.from(_stashReader.getSplits(table))
.transform(Functions.toStringFunction())
.toList();
} catch (TableNotStashedException e) {
throw propagateTableNotStashed(e);
}
} | [
"public",
"Collection",
"<",
"String",
">",
"getSplits",
"(",
"String",
"table",
")",
"throws",
"StashNotAvailableException",
",",
"TableNotStashedException",
"{",
"try",
"{",
"return",
"FluentIterable",
".",
"from",
"(",
"_stashReader",
".",
"getSplits",
"(",
"ta... | Gets the splits from Stash for the given table. | [
"Gets",
"the",
"splits",
"from",
"Stash",
"for",
"the",
"given",
"table",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStash.java#L223-L232 | train |
bazaarvoice/emodb | sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStash.java | DataStoreStash.propagateTableNotStashed | private RuntimeException propagateTableNotStashed(TableNotStashedException e)
throws TableNotStashedException, UnknownTableException {
if (_dataStore.getTableExists(e.getTable())) {
throw e;
}
throw new UnknownTableException(e.getTable());
} | java | private RuntimeException propagateTableNotStashed(TableNotStashedException e)
throws TableNotStashedException, UnknownTableException {
if (_dataStore.getTableExists(e.getTable())) {
throw e;
}
throw new UnknownTableException(e.getTable());
} | [
"private",
"RuntimeException",
"propagateTableNotStashed",
"(",
"TableNotStashedException",
"e",
")",
"throws",
"TableNotStashedException",
",",
"UnknownTableException",
"{",
"if",
"(",
"_dataStore",
".",
"getTableExists",
"(",
"e",
".",
"getTable",
"(",
")",
")",
")"... | If a table exists but is empty then it will not be stashed. This method will surface this exception
only if the table exists. Otherwise it converts it to an UnknownTableException. | [
"If",
"a",
"table",
"exists",
"but",
"is",
"empty",
"then",
"it",
"will",
"not",
"be",
"stashed",
".",
"This",
"method",
"will",
"surface",
"this",
"exception",
"only",
"if",
"the",
"table",
"exists",
".",
"Otherwise",
"it",
"converts",
"it",
"to",
"an",... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStash.java#L259-L265 | train |
bazaarvoice/emodb | common/api/src/main/java/com/bazaarvoice/emodb/common/api/Names.java | Names.isLegalRoleName | public static boolean isLegalRoleName(String role) {
return role != null &&
role.length() > 0 && role.length() <= 255 &&
ROLE_NAME_ALLOWED.matchesAllOf(role);
} | java | public static boolean isLegalRoleName(String role) {
return role != null &&
role.length() > 0 && role.length() <= 255 &&
ROLE_NAME_ALLOWED.matchesAllOf(role);
} | [
"public",
"static",
"boolean",
"isLegalRoleName",
"(",
"String",
"role",
")",
"{",
"return",
"role",
"!=",
"null",
"&&",
"role",
".",
"length",
"(",
")",
">",
"0",
"&&",
"role",
".",
"length",
"(",
")",
"<=",
"255",
"&&",
"ROLE_NAME_ALLOWED",
".",
"mat... | Role names mostly follow the same conventions as table names except, since they are only used internally, are
slightly more permissive, such as allowing capital letters. | [
"Role",
"names",
"mostly",
"follow",
"the",
"same",
"conventions",
"as",
"table",
"names",
"except",
"since",
"they",
"are",
"only",
"used",
"internally",
"are",
"slightly",
"more",
"permissive",
"such",
"as",
"allowing",
"capital",
"letters",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/api/src/main/java/com/bazaarvoice/emodb/common/api/Names.java#L44-L48 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java | EmoTableAllTablesReportDAO.verifyOrCreateReport | @Override
public void verifyOrCreateReport(String reportId) {
checkNotNull(reportId, "reportId");
String tableName = getTableName(reportId);
if (_dataStore.getTableExists(tableName)) {
return; // Nothing to do.
}
try {
// TODO: when run in the EU this should be routed to the US data center.
_dataStore.createTable(tableName,
new TableOptionsBuilder().setPlacement(_systemTablePlacement).build(),
ImmutableMap.<String, String>of(),
new AuditBuilder().setComment("create table").build()
);
} catch (TableExistsException e) {
// This is expected if we're continuing an existing report.
}
} | java | @Override
public void verifyOrCreateReport(String reportId) {
checkNotNull(reportId, "reportId");
String tableName = getTableName(reportId);
if (_dataStore.getTableExists(tableName)) {
return; // Nothing to do.
}
try {
// TODO: when run in the EU this should be routed to the US data center.
_dataStore.createTable(tableName,
new TableOptionsBuilder().setPlacement(_systemTablePlacement).build(),
ImmutableMap.<String, String>of(),
new AuditBuilder().setComment("create table").build()
);
} catch (TableExistsException e) {
// This is expected if we're continuing an existing report.
}
} | [
"@",
"Override",
"public",
"void",
"verifyOrCreateReport",
"(",
"String",
"reportId",
")",
"{",
"checkNotNull",
"(",
"reportId",
",",
"\"reportId\"",
")",
";",
"String",
"tableName",
"=",
"getTableName",
"(",
"reportId",
")",
";",
"if",
"(",
"_dataStore",
".",... | Verifies that the given report table exists or, if not, creates it. | [
"Verifies",
"that",
"the",
"given",
"report",
"table",
"exists",
"or",
"if",
"not",
"creates",
"it",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java#L64-L83 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java | EmoTableAllTablesReportDAO.updateReport | @Override
public void updateReport(AllTablesReportDelta delta) {
checkNotNull(delta, "delta");
updateMetadata(delta);
if (delta.getTable().isPresent()) {
updateTableData(delta, delta.getTable().get());
}
} | java | @Override
public void updateReport(AllTablesReportDelta delta) {
checkNotNull(delta, "delta");
updateMetadata(delta);
if (delta.getTable().isPresent()) {
updateTableData(delta, delta.getTable().get());
}
} | [
"@",
"Override",
"public",
"void",
"updateReport",
"(",
"AllTablesReportDelta",
"delta",
")",
"{",
"checkNotNull",
"(",
"delta",
",",
"\"delta\"",
")",
";",
"updateMetadata",
"(",
"delta",
")",
";",
"if",
"(",
"delta",
".",
"getTable",
"(",
")",
".",
"isPr... | Updates the metadata associated with the report. | [
"Updates",
"the",
"metadata",
"associated",
"with",
"the",
"report",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java#L88-L97 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java | EmoTableAllTablesReportDAO.getReportMetadata | @Override
public TableReportMetadata getReportMetadata(String reportId) {
checkNotNull(reportId, "reportId");
final String reportTable = getTableName(reportId);
Map<String, Object> metadata;
try {
metadata = _dataStore.get(reportTable, REPORT_METADATA_KEY);
} catch (UnknownTableException e) {
// The table is only unknown if the report doesn't exist
throw new ReportNotFoundException(reportId);
}
if (Intrinsic.isDeleted(metadata)) {
throw new ReportNotFoundException(reportId);
}
Date startTime = JsonHelper.parseTimestamp((String) metadata.get("startTime"));
Date completeTime = null;
if (metadata.containsKey("completeTime")) {
completeTime = JsonHelper.parseTimestamp((String) metadata.get("completeTime"));
}
Boolean success = (Boolean) metadata.get("success");
List<String> placements;
Object placementMap = metadata.get("placements");
if (placementMap != null) {
placements = ImmutableList.copyOf(
JsonHelper.convert(placementMap, new TypeReference<Map<String, Object>>() {}).keySet());
} else {
placements = ImmutableList.of();
}
return new TableReportMetadata(reportId, startTime, completeTime, success, placements);
} | java | @Override
public TableReportMetadata getReportMetadata(String reportId) {
checkNotNull(reportId, "reportId");
final String reportTable = getTableName(reportId);
Map<String, Object> metadata;
try {
metadata = _dataStore.get(reportTable, REPORT_METADATA_KEY);
} catch (UnknownTableException e) {
// The table is only unknown if the report doesn't exist
throw new ReportNotFoundException(reportId);
}
if (Intrinsic.isDeleted(metadata)) {
throw new ReportNotFoundException(reportId);
}
Date startTime = JsonHelper.parseTimestamp((String) metadata.get("startTime"));
Date completeTime = null;
if (metadata.containsKey("completeTime")) {
completeTime = JsonHelper.parseTimestamp((String) metadata.get("completeTime"));
}
Boolean success = (Boolean) metadata.get("success");
List<String> placements;
Object placementMap = metadata.get("placements");
if (placementMap != null) {
placements = ImmutableList.copyOf(
JsonHelper.convert(placementMap, new TypeReference<Map<String, Object>>() {}).keySet());
} else {
placements = ImmutableList.of();
}
return new TableReportMetadata(reportId, startTime, completeTime, success, placements);
} | [
"@",
"Override",
"public",
"TableReportMetadata",
"getReportMetadata",
"(",
"String",
"reportId",
")",
"{",
"checkNotNull",
"(",
"reportId",
",",
"\"reportId\"",
")",
";",
"final",
"String",
"reportTable",
"=",
"getTableName",
"(",
"reportId",
")",
";",
"Map",
"... | Returns the table data for a given report. The caller can optionally return a partial report with ony
the requested tables. | [
"Returns",
"the",
"table",
"data",
"for",
"a",
"given",
"report",
".",
"The",
"caller",
"can",
"optionally",
"return",
"a",
"partial",
"report",
"with",
"ony",
"the",
"requested",
"tables",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java#L164-L199 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java | EmoTableAllTablesReportDAO.getReportEntries | @Override
public Iterable<TableReportEntry> getReportEntries(String reportId, final AllTablesReportQuery query) {
checkNotNull(reportId, "reportId");
final String reportTable = getTableName(reportId);
// Set up several filters based on the query attributes
final Predicate<String> placementFilter = query.getPlacements().isEmpty()
? Predicates.<String>alwaysTrue()
: Predicates.in(query.getPlacements());
final Predicate<Boolean> droppedFilter = query.isIncludeDropped()
? Predicates.<Boolean>alwaysTrue()
: Predicates.equalTo(false);
final Predicate<Boolean> facadeFilter = query.isIncludeFacades()
? Predicates.<Boolean>alwaysTrue()
: Predicates.equalTo(false);
return new Iterable<TableReportEntry>() {
@Override
public Iterator<TableReportEntry> iterator() {
return Iterators.limit(
Iterators.filter(
Iterators.transform(
queryDataStoreForTableReportResults(reportTable, query),
new Function<Map<String, Object>, TableReportEntry>() {
@Nullable
@Override
public TableReportEntry apply(Map<String, Object> map) {
if (Intrinsic.getId(map).startsWith("~")) {
// Skip this row, it's the metadata
return null;
}
return convertToTableReportEntry(
map, placementFilter, droppedFilter, facadeFilter);
}
}),
Predicates.notNull()
),
query.getLimit()
);
}
};
} | java | @Override
public Iterable<TableReportEntry> getReportEntries(String reportId, final AllTablesReportQuery query) {
checkNotNull(reportId, "reportId");
final String reportTable = getTableName(reportId);
// Set up several filters based on the query attributes
final Predicate<String> placementFilter = query.getPlacements().isEmpty()
? Predicates.<String>alwaysTrue()
: Predicates.in(query.getPlacements());
final Predicate<Boolean> droppedFilter = query.isIncludeDropped()
? Predicates.<Boolean>alwaysTrue()
: Predicates.equalTo(false);
final Predicate<Boolean> facadeFilter = query.isIncludeFacades()
? Predicates.<Boolean>alwaysTrue()
: Predicates.equalTo(false);
return new Iterable<TableReportEntry>() {
@Override
public Iterator<TableReportEntry> iterator() {
return Iterators.limit(
Iterators.filter(
Iterators.transform(
queryDataStoreForTableReportResults(reportTable, query),
new Function<Map<String, Object>, TableReportEntry>() {
@Nullable
@Override
public TableReportEntry apply(Map<String, Object> map) {
if (Intrinsic.getId(map).startsWith("~")) {
// Skip this row, it's the metadata
return null;
}
return convertToTableReportEntry(
map, placementFilter, droppedFilter, facadeFilter);
}
}),
Predicates.notNull()
),
query.getLimit()
);
}
};
} | [
"@",
"Override",
"public",
"Iterable",
"<",
"TableReportEntry",
">",
"getReportEntries",
"(",
"String",
"reportId",
",",
"final",
"AllTablesReportQuery",
"query",
")",
"{",
"checkNotNull",
"(",
"reportId",
",",
"\"reportId\"",
")",
";",
"final",
"String",
"reportT... | Returns the matching table report entries for a report ID and query parameters. | [
"Returns",
"the",
"matching",
"table",
"report",
"entries",
"for",
"a",
"report",
"ID",
"and",
"query",
"parameters",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java#L204-L249 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java | EmoTableAllTablesReportDAO.queryDataStoreForTableReportResults | private Iterator<Map<String, Object>> queryDataStoreForTableReportResults(final String reportTable, final AllTablesReportQuery query) {
if (!query.getTableNames().isEmpty()) {
// Querying for a specific set of tables.
return Iterators.concat(
Iterators.transform(
query.getTableNames().iterator(),
new Function<String, Map<String, Object>>() {
@Override
public Map<String, Object> apply(String tableName) {
return _dataStore.get(reportTable, tableName, ReadConsistency.STRONG);
}
}
));
}
// Querying over the full set of tables
return new AbstractIterator<Map<String, Object>>() {
private String _from = query.getFromTable();
private Iterator<Map<String, Object>> _batch = Iterators.emptyIterator();
private long _limit = 0;
@Override
protected Map<String, Object> computeNext() {
if (!_batch.hasNext()) {
if (_limit == 0) {
// First iteration get the requested number of results
_limit = query.getLimit();
} else {
// Subsequent requests iterate over all remaining results; dataStore will batch the results
_limit = Long.MAX_VALUE;
}
_batch = _dataStore.scan(reportTable, _from, _limit, false, ReadConsistency.STRONG);
if (!_batch.hasNext()) {
return endOfData();
}
}
Map<String, Object> result = _batch.next();
_from = Intrinsic.getId(result);
return result;
}
};
} | java | private Iterator<Map<String, Object>> queryDataStoreForTableReportResults(final String reportTable, final AllTablesReportQuery query) {
if (!query.getTableNames().isEmpty()) {
// Querying for a specific set of tables.
return Iterators.concat(
Iterators.transform(
query.getTableNames().iterator(),
new Function<String, Map<String, Object>>() {
@Override
public Map<String, Object> apply(String tableName) {
return _dataStore.get(reportTable, tableName, ReadConsistency.STRONG);
}
}
));
}
// Querying over the full set of tables
return new AbstractIterator<Map<String, Object>>() {
private String _from = query.getFromTable();
private Iterator<Map<String, Object>> _batch = Iterators.emptyIterator();
private long _limit = 0;
@Override
protected Map<String, Object> computeNext() {
if (!_batch.hasNext()) {
if (_limit == 0) {
// First iteration get the requested number of results
_limit = query.getLimit();
} else {
// Subsequent requests iterate over all remaining results; dataStore will batch the results
_limit = Long.MAX_VALUE;
}
_batch = _dataStore.scan(reportTable, _from, _limit, false, ReadConsistency.STRONG);
if (!_batch.hasNext()) {
return endOfData();
}
}
Map<String, Object> result = _batch.next();
_from = Intrinsic.getId(result);
return result;
}
};
} | [
"private",
"Iterator",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"queryDataStoreForTableReportResults",
"(",
"final",
"String",
"reportTable",
",",
"final",
"AllTablesReportQuery",
"query",
")",
"{",
"if",
"(",
"!",
"query",
".",
"getTableNames",
"(",
... | Returns an iterator of report results based on the query configuration. The results are guaranteed to be a
superset of results matching the original query; further filtering may be required to exactly match the
query. | [
"Returns",
"an",
"iterator",
"of",
"report",
"results",
"based",
"on",
"the",
"query",
"configuration",
".",
"The",
"results",
"are",
"guaranteed",
"to",
"be",
"a",
"superset",
"of",
"results",
"matching",
"the",
"original",
"query",
";",
"further",
"filtering... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java#L256-L300 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java | EmoTableAllTablesReportDAO.convertToTableReportEntry | @Nullable
private TableReportEntry convertToTableReportEntry(Map<String, Object> map, Predicate<String> placementFilter,
Predicate<Boolean> droppedFilter, Predicate<Boolean> facadeFilter) {
if (Intrinsic.isDeleted(map)) {
return null;
}
final String tableName = Intrinsic.getId(map);
List<TableReportEntryTable> tables = Lists.newArrayListWithExpectedSize(map.size());
for (Map.Entry<String, Object> entry : toMap(map.get("tables")).entrySet()) {
TableReportEntryTable entryTable =
convertToTableReportEntryTable(entry.getKey(), toMap(entry.getValue()),
placementFilter, droppedFilter, facadeFilter);
if (entryTable != null) {
tables.add(entryTable);
}
}
// If all tables were filtered then return null
if (tables.isEmpty()) {
return null;
}
return new TableReportEntry(tableName, tables);
} | java | @Nullable
private TableReportEntry convertToTableReportEntry(Map<String, Object> map, Predicate<String> placementFilter,
Predicate<Boolean> droppedFilter, Predicate<Boolean> facadeFilter) {
if (Intrinsic.isDeleted(map)) {
return null;
}
final String tableName = Intrinsic.getId(map);
List<TableReportEntryTable> tables = Lists.newArrayListWithExpectedSize(map.size());
for (Map.Entry<String, Object> entry : toMap(map.get("tables")).entrySet()) {
TableReportEntryTable entryTable =
convertToTableReportEntryTable(entry.getKey(), toMap(entry.getValue()),
placementFilter, droppedFilter, facadeFilter);
if (entryTable != null) {
tables.add(entryTable);
}
}
// If all tables were filtered then return null
if (tables.isEmpty()) {
return null;
}
return new TableReportEntry(tableName, tables);
} | [
"@",
"Nullable",
"private",
"TableReportEntry",
"convertToTableReportEntry",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
",",
"Predicate",
"<",
"String",
">",
"placementFilter",
",",
"Predicate",
"<",
"Boolean",
">",
"droppedFilter",
",",
"Predicate",
... | Accepts a row from the table report and returns it converted into a TableReportEntry. If the row is deleted
or if it doesn't match all of the configured filters then null is returned. | [
"Accepts",
"a",
"row",
"from",
"the",
"table",
"report",
"and",
"returns",
"it",
"converted",
"into",
"a",
"TableReportEntry",
".",
"If",
"the",
"row",
"is",
"deleted",
"or",
"if",
"it",
"doesn",
"t",
"match",
"all",
"of",
"the",
"configured",
"filters",
... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java#L306-L332 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java | EmoTableAllTablesReportDAO.convertToTableReportEntryTable | @Nullable
private TableReportEntryTable convertToTableReportEntryTable(
String tableId, Map<String, Object> map, Predicate<String> placementFilter,
Predicate<Boolean> droppedFilter, Predicate<Boolean> facadeFilter) {
// Check the filters for placement, dropped, and facade
String placement = (String) map.get("placement");
if (!placementFilter.apply(placement)) {
return null;
}
Boolean dropped = Objects.firstNonNull((Boolean) map.get("dropped"), false);
if (!droppedFilter.apply(dropped)) {
return null;
}
Boolean facade = Objects.firstNonNull((Boolean) map.get("facade"), false);
if (!facadeFilter.apply(facade)) {
return null;
}
List<Integer> shards = Lists.newArrayList();
// Aggregate the column, size and update statistics across all shards.
TableStatistics.Aggregator aggregator = TableStatistics.newAggregator();
Object shardJson = map.get("shards");
if (shardJson != null) {
Map<String, TableStatistics> shardMap = JsonHelper.convert(
shardJson, new TypeReference<Map<String, TableStatistics>>() {
});
for (Map.Entry<String, TableStatistics> entry : shardMap.entrySet()) {
Integer shardId = Integer.parseInt(entry.getKey());
shards.add(shardId);
aggregator.add(entry.getValue());
}
}
TableStatistics tableStatistics = aggregator.aggregate();
Collections.sort(shards);
return new TableReportEntryTable(tableId, placement, shards, dropped, facade, tableStatistics.getRecordCount(),
tableStatistics.getColumnStatistics().toStatistics(),
tableStatistics.getSizeStatistics().toStatistics(),
tableStatistics.getUpdateTimeStatistics().toStatistics());
} | java | @Nullable
private TableReportEntryTable convertToTableReportEntryTable(
String tableId, Map<String, Object> map, Predicate<String> placementFilter,
Predicate<Boolean> droppedFilter, Predicate<Boolean> facadeFilter) {
// Check the filters for placement, dropped, and facade
String placement = (String) map.get("placement");
if (!placementFilter.apply(placement)) {
return null;
}
Boolean dropped = Objects.firstNonNull((Boolean) map.get("dropped"), false);
if (!droppedFilter.apply(dropped)) {
return null;
}
Boolean facade = Objects.firstNonNull((Boolean) map.get("facade"), false);
if (!facadeFilter.apply(facade)) {
return null;
}
List<Integer> shards = Lists.newArrayList();
// Aggregate the column, size and update statistics across all shards.
TableStatistics.Aggregator aggregator = TableStatistics.newAggregator();
Object shardJson = map.get("shards");
if (shardJson != null) {
Map<String, TableStatistics> shardMap = JsonHelper.convert(
shardJson, new TypeReference<Map<String, TableStatistics>>() {
});
for (Map.Entry<String, TableStatistics> entry : shardMap.entrySet()) {
Integer shardId = Integer.parseInt(entry.getKey());
shards.add(shardId);
aggregator.add(entry.getValue());
}
}
TableStatistics tableStatistics = aggregator.aggregate();
Collections.sort(shards);
return new TableReportEntryTable(tableId, placement, shards, dropped, facade, tableStatistics.getRecordCount(),
tableStatistics.getColumnStatistics().toStatistics(),
tableStatistics.getSizeStatistics().toStatistics(),
tableStatistics.getUpdateTimeStatistics().toStatistics());
} | [
"@",
"Nullable",
"private",
"TableReportEntryTable",
"convertToTableReportEntryTable",
"(",
"String",
"tableId",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
",",
"Predicate",
"<",
"String",
">",
"placementFilter",
",",
"Predicate",
"<",
"Boolean",
">",
... | Accepts the table portion of a table report entry and converts it to a TableReportEntryTable. If the
entry doesn't match all of the configured filters then null is returned. | [
"Accepts",
"the",
"table",
"portion",
"of",
"a",
"table",
"report",
"entry",
"and",
"converts",
"it",
"to",
"a",
"TableReportEntryTable",
".",
"If",
"the",
"entry",
"doesn",
"t",
"match",
"all",
"of",
"the",
"configured",
"filters",
"then",
"null",
"is",
"... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/report/db/EmoTableAllTablesReportDAO.java#L338-L387 | train |
bazaarvoice/emodb | databus-api/src/main/java/com/bazaarvoice/emodb/databus/api/Event.java | Event.getJsonSerializingContent | @JsonView(EventViews.ContentOnly.class)
@JsonProperty("content")
private Map<String, Object> getJsonSerializingContent() {
//noinspection unchecked
return (Map<String, Object>) _content;
} | java | @JsonView(EventViews.ContentOnly.class)
@JsonProperty("content")
private Map<String, Object> getJsonSerializingContent() {
//noinspection unchecked
return (Map<String, Object>) _content;
} | [
"@",
"JsonView",
"(",
"EventViews",
".",
"ContentOnly",
".",
"class",
")",
"@",
"JsonProperty",
"(",
"\"content\"",
")",
"private",
"Map",
"<",
"String",
",",
"Object",
">",
"getJsonSerializingContent",
"(",
")",
"{",
"//noinspection unchecked",
"return",
"(",
... | For purposes of JSON serialization wrapping the content in an unmodifiable view may cause the serializer
to choose a less-optimal implementation. Since JSON serialization cannot modify the underlying content
it is safe to return the original content object to the serializer. | [
"For",
"purposes",
"of",
"JSON",
"serialization",
"wrapping",
"the",
"content",
"in",
"an",
"unmodifiable",
"view",
"may",
"cause",
"the",
"serializer",
"to",
"choose",
"a",
"less",
"-",
"optimal",
"implementation",
".",
"Since",
"JSON",
"serialization",
"cannot... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus-api/src/main/java/com/bazaarvoice/emodb/databus/api/Event.java#L45-L50 | train |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/db/DeltaIterator.java | DeltaIterator.reverseCompute | private BlockedDelta reverseCompute() {
int contentSize = getValue(_next).remaining();
UUID correctChangeId = getChangeId(_next);
int numBlocks = 1;
if (_list == null) {
_list = Lists.newArrayListWithCapacity(3);
}
_list.add(_next);
_oldDelta = _next;
while (_iterator.hasNext() && getChangeId(_next = _iterator.next()).equals(correctChangeId)) {
numBlocks++;
_list.add(_next);
contentSize += getValue(_next).remaining();
_next = null;
}
Collections.reverse(_list);
// delta is fragmented if the first block is not zero. In this case, we skip it.
if (getBlock(_list.get(0)) != 0) {
// We must also clear the list of the fragmented delta blocks to avoid them being stitched in with
// the next delta, which will cause a buffer overflow
_list.clear();
return null;
}
int expectedBlocks = getNumBlocks(_list.get(0));
while (expectedBlocks != _list.size()) {
contentSize -= getValue(_list.remove(_list.size() - 1)).remaining();
}
return new BlockedDelta(numBlocks, stitchContent(contentSize));
} | java | private BlockedDelta reverseCompute() {
int contentSize = getValue(_next).remaining();
UUID correctChangeId = getChangeId(_next);
int numBlocks = 1;
if (_list == null) {
_list = Lists.newArrayListWithCapacity(3);
}
_list.add(_next);
_oldDelta = _next;
while (_iterator.hasNext() && getChangeId(_next = _iterator.next()).equals(correctChangeId)) {
numBlocks++;
_list.add(_next);
contentSize += getValue(_next).remaining();
_next = null;
}
Collections.reverse(_list);
// delta is fragmented if the first block is not zero. In this case, we skip it.
if (getBlock(_list.get(0)) != 0) {
// We must also clear the list of the fragmented delta blocks to avoid them being stitched in with
// the next delta, which will cause a buffer overflow
_list.clear();
return null;
}
int expectedBlocks = getNumBlocks(_list.get(0));
while (expectedBlocks != _list.size()) {
contentSize -= getValue(_list.remove(_list.size() - 1)).remaining();
}
return new BlockedDelta(numBlocks, stitchContent(contentSize));
} | [
"private",
"BlockedDelta",
"reverseCompute",
"(",
")",
"{",
"int",
"contentSize",
"=",
"getValue",
"(",
"_next",
")",
".",
"remaining",
"(",
")",
";",
"UUID",
"correctChangeId",
"=",
"getChangeId",
"(",
"_next",
")",
";",
"int",
"numBlocks",
"=",
"1",
";",... | stitch delta together in reverse | [
"stitch",
"delta",
"together",
"in",
"reverse"
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/DeltaIterator.java#L38-L77 | train |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/db/DeltaIterator.java | DeltaIterator.compute | private BlockedDelta compute(int numBlocks) {
int contentSize = getValue(_next).remaining();
_oldDelta = _next;
UUID changeId = getChangeId(_next);
if (_list == null) {
_list = Lists.newArrayListWithCapacity(numBlocks);
}
_list.add(_next);
for (int i = 1; i < numBlocks; i++) {
if (_iterator.hasNext()) {
_next = _iterator.next();
if (getChangeId(_next).equals(changeId)) {
_list.add(_next);
contentSize += getValue(_next).remaining();
} else {
// fragmented delta encountered, we must skip over it
// We must also clear the list of the fragmented delta blocks to avoid them being stitched in with
// the next delta, which will cause a buffer overflow
_list.clear();
return null;
}
} else {
// fragmented delta and no other deltas to skip to
throw new DeltaStitchingException(_rowKey, getChangeId(_next).toString(), numBlocks, i - 1);
}
}
numBlocks += skipForward();
return new BlockedDelta(numBlocks, stitchContent(contentSize));
} | java | private BlockedDelta compute(int numBlocks) {
int contentSize = getValue(_next).remaining();
_oldDelta = _next;
UUID changeId = getChangeId(_next);
if (_list == null) {
_list = Lists.newArrayListWithCapacity(numBlocks);
}
_list.add(_next);
for (int i = 1; i < numBlocks; i++) {
if (_iterator.hasNext()) {
_next = _iterator.next();
if (getChangeId(_next).equals(changeId)) {
_list.add(_next);
contentSize += getValue(_next).remaining();
} else {
// fragmented delta encountered, we must skip over it
// We must also clear the list of the fragmented delta blocks to avoid them being stitched in with
// the next delta, which will cause a buffer overflow
_list.clear();
return null;
}
} else {
// fragmented delta and no other deltas to skip to
throw new DeltaStitchingException(_rowKey, getChangeId(_next).toString(), numBlocks, i - 1);
}
}
numBlocks += skipForward();
return new BlockedDelta(numBlocks, stitchContent(contentSize));
} | [
"private",
"BlockedDelta",
"compute",
"(",
"int",
"numBlocks",
")",
"{",
"int",
"contentSize",
"=",
"getValue",
"(",
"_next",
")",
".",
"remaining",
"(",
")",
";",
"_oldDelta",
"=",
"_next",
";",
"UUID",
"changeId",
"=",
"getChangeId",
"(",
"_next",
")",
... | stitch delta together and return it as one bytebuffer | [
"stitch",
"delta",
"together",
"and",
"return",
"it",
"as",
"one",
"bytebuffer"
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/DeltaIterator.java#L80-L115 | train |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/db/DeltaIterator.java | DeltaIterator.skipForward | private int skipForward() {
int numSkips = 0;
_next = null;
while (_iterator.hasNext() && getBlock(_next = _iterator.next()) != 0) {
numSkips++;
_next = null;
}
return numSkips;
} | java | private int skipForward() {
int numSkips = 0;
_next = null;
while (_iterator.hasNext() && getBlock(_next = _iterator.next()) != 0) {
numSkips++;
_next = null;
}
return numSkips;
} | [
"private",
"int",
"skipForward",
"(",
")",
"{",
"int",
"numSkips",
"=",
"0",
";",
"_next",
"=",
"null",
";",
"while",
"(",
"_iterator",
".",
"hasNext",
"(",
")",
"&&",
"getBlock",
"(",
"_next",
"=",
"_iterator",
".",
"next",
"(",
")",
")",
"!=",
"0... | This handles the edge case in which a client has explicity specified a changeId when writing and overwrote an exisiting delta. | [
"This",
"handles",
"the",
"edge",
"case",
"in",
"which",
"a",
"client",
"has",
"explicity",
"specified",
"a",
"changeId",
"when",
"writing",
"and",
"overwrote",
"an",
"exisiting",
"delta",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/DeltaIterator.java#L177-L185 | train |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/db/DeltaIterator.java | DeltaIterator.getNumBlocks | private int getNumBlocks(R delta) {
ByteBuffer content = getValue(delta);
int numBlocks = 0;
// build numBlocks by adding together each hex digit
for (int i = 0; i < _prefixLength; i++) {
byte b = content.get(i);
numBlocks = numBlocks << 4 | (b <= '9' ? b - '0' : b - 'A' + 10);
}
return numBlocks;
} | java | private int getNumBlocks(R delta) {
ByteBuffer content = getValue(delta);
int numBlocks = 0;
// build numBlocks by adding together each hex digit
for (int i = 0; i < _prefixLength; i++) {
byte b = content.get(i);
numBlocks = numBlocks << 4 | (b <= '9' ? b - '0' : b - 'A' + 10);
}
return numBlocks;
} | [
"private",
"int",
"getNumBlocks",
"(",
"R",
"delta",
")",
"{",
"ByteBuffer",
"content",
"=",
"getValue",
"(",
"delta",
")",
";",
"int",
"numBlocks",
"=",
"0",
";",
"// build numBlocks by adding together each hex digit",
"for",
"(",
"int",
"i",
"=",
"0",
";",
... | converts utf-8 encoded hex to int by building it digit by digit. | [
"converts",
"utf",
"-",
"8",
"encoded",
"hex",
"to",
"int",
"by",
"building",
"it",
"digit",
"by",
"digit",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/DeltaIterator.java#L188-L199 | train |
bazaarvoice/emodb | databus/src/main/java/com/bazaarvoice/emodb/databus/repl/DefaultReplicationManager.java | DefaultReplicationManager.newRemoteReplicationSource | private ReplicationSource newRemoteReplicationSource(DataCenter dataCenter) {
MultiThreadedServiceFactory<ReplicationSource> clientFactory = new ReplicationClientFactory(_jerseyClient)
.usingApiKey(_replicationApiKey);
ServiceEndPoint endPoint = new ServiceEndPointBuilder()
.withServiceName(clientFactory.getServiceName())
.withId(dataCenter.getName())
.withPayload(new PayloadBuilder()
.withUrl(dataCenter.getServiceUri().resolve(ReplicationClient.SERVICE_PATH))
.withAdminUrl(dataCenter.getAdminUri())
.toString())
.build();
return ServicePoolBuilder.create(ReplicationSource.class)
.withHostDiscovery(new FixedHostDiscovery(endPoint))
.withServiceFactory(clientFactory)
.withCachingPolicy(ServiceCachingPolicyBuilder.getMultiThreadedClientPolicy())
.withHealthCheckExecutor(_healthCheckExecutor)
.withMetricRegistry(_metrics)
.buildProxy(new ExponentialBackoffRetry(30, 1, 10, TimeUnit.SECONDS));
} | java | private ReplicationSource newRemoteReplicationSource(DataCenter dataCenter) {
MultiThreadedServiceFactory<ReplicationSource> clientFactory = new ReplicationClientFactory(_jerseyClient)
.usingApiKey(_replicationApiKey);
ServiceEndPoint endPoint = new ServiceEndPointBuilder()
.withServiceName(clientFactory.getServiceName())
.withId(dataCenter.getName())
.withPayload(new PayloadBuilder()
.withUrl(dataCenter.getServiceUri().resolve(ReplicationClient.SERVICE_PATH))
.withAdminUrl(dataCenter.getAdminUri())
.toString())
.build();
return ServicePoolBuilder.create(ReplicationSource.class)
.withHostDiscovery(new FixedHostDiscovery(endPoint))
.withServiceFactory(clientFactory)
.withCachingPolicy(ServiceCachingPolicyBuilder.getMultiThreadedClientPolicy())
.withHealthCheckExecutor(_healthCheckExecutor)
.withMetricRegistry(_metrics)
.buildProxy(new ExponentialBackoffRetry(30, 1, 10, TimeUnit.SECONDS));
} | [
"private",
"ReplicationSource",
"newRemoteReplicationSource",
"(",
"DataCenter",
"dataCenter",
")",
"{",
"MultiThreadedServiceFactory",
"<",
"ReplicationSource",
">",
"clientFactory",
"=",
"new",
"ReplicationClientFactory",
"(",
"_jerseyClient",
")",
".",
"usingApiKey",
"("... | Creates a ReplicationSource proxy to the remote data center. | [
"Creates",
"a",
"ReplicationSource",
"proxy",
"to",
"the",
"remote",
"data",
"center",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus/src/main/java/com/bazaarvoice/emodb/databus/repl/DefaultReplicationManager.java#L184-L204 | train |
bazaarvoice/emodb | common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/CqlCluster.java | CqlCluster.registerMetrics | private void registerMetrics() {
if (_metricName == null) {
// No metric name was provided; skip registration
return;
}
Metrics metrics = _cluster.getMetrics();
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "connected-to-hosts"),
metrics.getConnectedToHosts());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "open-connections"),
metrics.getOpenConnections());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "trashed-connections"),
metrics.getTrashedConnections());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "executor-queue-depth"),
metrics.getExecutorQueueDepth());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "blocking-executor-queue-depth"),
metrics.getBlockingExecutorQueueDepth());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "reconnection-scheduler-task-count"),
metrics.getReconnectionSchedulerQueueSize());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "task-scheduler-task-count"),
metrics.getTaskSchedulerQueueSize());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "connection-errors"),
metrics.getErrorMetrics().getConnectionErrors());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "read-timeouts"),
metrics.getErrorMetrics().getReadTimeouts());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "write-timeouts"),
metrics.getErrorMetrics().getWriteTimeouts());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "client-timeouts"),
metrics.getErrorMetrics().getClientTimeouts());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "ignores"),
metrics.getErrorMetrics().getIgnores());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "unavailables"),
metrics.getErrorMetrics().getUnavailables());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "speculative-executions"),
metrics.getErrorMetrics().getSpeculativeExecutions());
} | java | private void registerMetrics() {
if (_metricName == null) {
// No metric name was provided; skip registration
return;
}
Metrics metrics = _cluster.getMetrics();
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "connected-to-hosts"),
metrics.getConnectedToHosts());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "open-connections"),
metrics.getOpenConnections());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "trashed-connections"),
metrics.getTrashedConnections());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "executor-queue-depth"),
metrics.getExecutorQueueDepth());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "blocking-executor-queue-depth"),
metrics.getBlockingExecutorQueueDepth());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "reconnection-scheduler-task-count"),
metrics.getReconnectionSchedulerQueueSize());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "task-scheduler-task-count"),
metrics.getTaskSchedulerQueueSize());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "connection-errors"),
metrics.getErrorMetrics().getConnectionErrors());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "read-timeouts"),
metrics.getErrorMetrics().getReadTimeouts());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "write-timeouts"),
metrics.getErrorMetrics().getWriteTimeouts());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "client-timeouts"),
metrics.getErrorMetrics().getClientTimeouts());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "ignores"),
metrics.getErrorMetrics().getIgnores());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "unavailables"),
metrics.getErrorMetrics().getUnavailables());
_metricRegistry.register(
MetricRegistry.name("bv.emodb.cql", _metricName, "ConnectionPool", "speculative-executions"),
metrics.getErrorMetrics().getSpeculativeExecutions());
} | [
"private",
"void",
"registerMetrics",
"(",
")",
"{",
"if",
"(",
"_metricName",
"==",
"null",
")",
"{",
"// No metric name was provided; skip registration",
"return",
";",
"}",
"Metrics",
"metrics",
"=",
"_cluster",
".",
"getMetrics",
"(",
")",
";",
"_metricRegistr... | Registers metrics for this cluster. Ideally this would be done before the cluster is started so conflicting
metric names could be detected earlier, but since the CQL driver doesn't publish metrics until after it is
initialized the metrics cannot be registered until then. | [
"Registers",
"metrics",
"for",
"this",
"cluster",
".",
"Ideally",
"this",
"would",
"be",
"done",
"before",
"the",
"cluster",
"is",
"started",
"so",
"conflicting",
"metric",
"names",
"could",
"be",
"detected",
"earlier",
"but",
"since",
"the",
"CQL",
"driver",
... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/CqlCluster.java#L49-L112 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java | FileSystemUtil.getRootFileStatus | public static FileStatus getRootFileStatus(Path rootPath) {
return new FileStatus(0, true, 1, 1024, -1, -1, DIRECTORY_PERMISSION, null, null, rootPath);
} | java | public static FileStatus getRootFileStatus(Path rootPath) {
return new FileStatus(0, true, 1, 1024, -1, -1, DIRECTORY_PERMISSION, null, null, rootPath);
} | [
"public",
"static",
"FileStatus",
"getRootFileStatus",
"(",
"Path",
"rootPath",
")",
"{",
"return",
"new",
"FileStatus",
"(",
"0",
",",
"true",
",",
"1",
",",
"1024",
",",
"-",
"1",
",",
"-",
"1",
",",
"DIRECTORY_PERMISSION",
",",
"null",
",",
"null",
... | Returns a FileStatus for the given root path. | [
"Returns",
"a",
"FileStatus",
"for",
"the",
"given",
"root",
"path",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java#L40-L42 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java | FileSystemUtil.getTableFileStatus | public static FileStatus getTableFileStatus(Path rootPath, String table) {
return new FileStatus(0, true, 1, 1024, -1, -1, DIRECTORY_PERMISSION, null, null,
getTablePath(rootPath, table));
} | java | public static FileStatus getTableFileStatus(Path rootPath, String table) {
return new FileStatus(0, true, 1, 1024, -1, -1, DIRECTORY_PERMISSION, null, null,
getTablePath(rootPath, table));
} | [
"public",
"static",
"FileStatus",
"getTableFileStatus",
"(",
"Path",
"rootPath",
",",
"String",
"table",
")",
"{",
"return",
"new",
"FileStatus",
"(",
"0",
",",
"true",
",",
"1",
",",
"1024",
",",
"-",
"1",
",",
"-",
"1",
",",
"DIRECTORY_PERMISSION",
","... | Returns a FileStatus for a table. | [
"Returns",
"a",
"FileStatus",
"for",
"a",
"table",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java#L47-L50 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java | FileSystemUtil.getSplitFileStatus | public static FileStatus getSplitFileStatus(Path rootPath, String table, String split, long size, int blockSize) {
return new FileStatus(size, false, 1, blockSize, -1, -1, FILE_PERMISSION, null, null,
getSplitPath(rootPath, table, split));
} | java | public static FileStatus getSplitFileStatus(Path rootPath, String table, String split, long size, int blockSize) {
return new FileStatus(size, false, 1, blockSize, -1, -1, FILE_PERMISSION, null, null,
getSplitPath(rootPath, table, split));
} | [
"public",
"static",
"FileStatus",
"getSplitFileStatus",
"(",
"Path",
"rootPath",
",",
"String",
"table",
",",
"String",
"split",
",",
"long",
"size",
",",
"int",
"blockSize",
")",
"{",
"return",
"new",
"FileStatus",
"(",
"size",
",",
"false",
",",
"1",
","... | Returns a FileStatus for a split. | [
"Returns",
"a",
"FileStatus",
"for",
"a",
"split",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java#L55-L58 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java | FileSystemUtil.getTableName | @Nullable
public static String getTableName(Path rootPath, Path path) {
path = qualified(rootPath, path);
if (rootPath.equals(path)) {
// Path is root, no table
return null;
}
Path tablePath;
Path parent = path.getParent();
if (Objects.equals(parent, rootPath)) {
// The path itself represents a table (e.g.; emodb://ci.us/mytable)
tablePath = path;
} else if (parent != null && Objects.equals(parent.getParent(), rootPath)) {
// The path is a split (e.g.; emodb://ci.us/mytable/split-id)
tablePath = parent;
} else {
throw new IllegalArgumentException(
format("Path does not represent a table, split, or root (path=%s, root=%s)", path, rootPath));
}
return decode(tablePath.getName());
} | java | @Nullable
public static String getTableName(Path rootPath, Path path) {
path = qualified(rootPath, path);
if (rootPath.equals(path)) {
// Path is root, no table
return null;
}
Path tablePath;
Path parent = path.getParent();
if (Objects.equals(parent, rootPath)) {
// The path itself represents a table (e.g.; emodb://ci.us/mytable)
tablePath = path;
} else if (parent != null && Objects.equals(parent.getParent(), rootPath)) {
// The path is a split (e.g.; emodb://ci.us/mytable/split-id)
tablePath = parent;
} else {
throw new IllegalArgumentException(
format("Path does not represent a table, split, or root (path=%s, root=%s)", path, rootPath));
}
return decode(tablePath.getName());
} | [
"@",
"Nullable",
"public",
"static",
"String",
"getTableName",
"(",
"Path",
"rootPath",
",",
"Path",
"path",
")",
"{",
"path",
"=",
"qualified",
"(",
"rootPath",
",",
"path",
")",
";",
"if",
"(",
"rootPath",
".",
"equals",
"(",
"path",
")",
")",
"{",
... | Gets the table name from a path, or null if the path is the root path. | [
"Gets",
"the",
"table",
"name",
"from",
"a",
"path",
"or",
"null",
"if",
"the",
"path",
"is",
"the",
"root",
"path",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java#L63-L84 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java | FileSystemUtil.qualified | private static Path qualified(Path rootPath, Path path) {
URI rootUri = rootPath.toUri();
return path.makeQualified(rootUri, new Path(rootUri.getPath()));
} | java | private static Path qualified(Path rootPath, Path path) {
URI rootUri = rootPath.toUri();
return path.makeQualified(rootUri, new Path(rootUri.getPath()));
} | [
"private",
"static",
"Path",
"qualified",
"(",
"Path",
"rootPath",
",",
"Path",
"path",
")",
"{",
"URI",
"rootUri",
"=",
"rootPath",
".",
"toUri",
"(",
")",
";",
"return",
"path",
".",
"makeQualified",
"(",
"rootUri",
",",
"new",
"Path",
"(",
"rootUri",
... | Qualifies a path so it includes the schema and authority from the root path. | [
"Qualifies",
"a",
"path",
"so",
"it",
"includes",
"the",
"schema",
"and",
"authority",
"from",
"the",
"root",
"path",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java#L110-L113 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java | FileSystemUtil.getTablePath | public static Path getTablePath(Path rootPath, String table) {
return new Path(rootPath, encode(table));
} | java | public static Path getTablePath(Path rootPath, String table) {
return new Path(rootPath, encode(table));
} | [
"public",
"static",
"Path",
"getTablePath",
"(",
"Path",
"rootPath",
",",
"String",
"table",
")",
"{",
"return",
"new",
"Path",
"(",
"rootPath",
",",
"encode",
"(",
"table",
")",
")",
";",
"}"
] | Gets the path for a table from the given root. | [
"Gets",
"the",
"path",
"for",
"a",
"table",
"from",
"the",
"given",
"root",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java#L118-L120 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java | FileSystemUtil.getSplitPath | public static Path getSplitPath(Path rootPath, String table, String split) {
return new Path(getTablePath(rootPath, table), encode(split));
} | java | public static Path getSplitPath(Path rootPath, String table, String split) {
return new Path(getTablePath(rootPath, table), encode(split));
} | [
"public",
"static",
"Path",
"getSplitPath",
"(",
"Path",
"rootPath",
",",
"String",
"table",
",",
"String",
"split",
")",
"{",
"return",
"new",
"Path",
"(",
"getTablePath",
"(",
"rootPath",
",",
"table",
")",
",",
"encode",
"(",
"split",
")",
")",
";",
... | Gets the path for a split from the given root. | [
"Gets",
"the",
"path",
"for",
"a",
"split",
"from",
"the",
"given",
"root",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java#L125-L127 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java | FileSystemUtil.encode | private static String encode(String pathElement) {
try {
return URLEncoder.encode(pathElement, Charsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw Throwables.propagate(e); // Should never happen
}
} | java | private static String encode(String pathElement) {
try {
return URLEncoder.encode(pathElement, Charsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw Throwables.propagate(e); // Should never happen
}
} | [
"private",
"static",
"String",
"encode",
"(",
"String",
"pathElement",
")",
"{",
"try",
"{",
"return",
"URLEncoder",
".",
"encode",
"(",
"pathElement",
",",
"Charsets",
".",
"UTF_8",
".",
"name",
"(",
")",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingE... | URL encodes a path element | [
"URL",
"encodes",
"a",
"path",
"element"
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java#L166-L172 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java | FileSystemUtil.decode | private static String decode(String pathElement) {
try {
return URLDecoder.decode(pathElement, Charsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw Throwables.propagate(e); // Should never happen
}
} | java | private static String decode(String pathElement) {
try {
return URLDecoder.decode(pathElement, Charsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw Throwables.propagate(e); // Should never happen
}
} | [
"private",
"static",
"String",
"decode",
"(",
"String",
"pathElement",
")",
"{",
"try",
"{",
"return",
"URLDecoder",
".",
"decode",
"(",
"pathElement",
",",
"Charsets",
".",
"UTF_8",
".",
"name",
"(",
")",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingE... | URL decodes a path element | [
"URL",
"decodes",
"a",
"path",
"element"
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/FileSystemUtil.java#L177-L183 | train |
bazaarvoice/emodb | table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/PlacementCache.java | PlacementCache.getLocalPlacements | public Collection<String> getLocalPlacements() {
List<String> placements = Lists.newArrayList();
for (String placementName : _placementFactory.getValidPlacements()) {
Placement placement;
try {
placement = get(placementName);
} catch (UnknownPlacementException e) {
continue; // Placement must live in another data center.
}
placements.add(placement.getName());
}
return placements;
} | java | public Collection<String> getLocalPlacements() {
List<String> placements = Lists.newArrayList();
for (String placementName : _placementFactory.getValidPlacements()) {
Placement placement;
try {
placement = get(placementName);
} catch (UnknownPlacementException e) {
continue; // Placement must live in another data center.
}
placements.add(placement.getName());
}
return placements;
} | [
"public",
"Collection",
"<",
"String",
">",
"getLocalPlacements",
"(",
")",
"{",
"List",
"<",
"String",
">",
"placements",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"for",
"(",
"String",
"placementName",
":",
"_placementFactory",
".",
"getValidPlacemen... | Returns all placements accessible in the local data center, including internal placements. | [
"Returns",
"all",
"placements",
"accessible",
"in",
"the",
"local",
"data",
"center",
"including",
"internal",
"placements",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/PlacementCache.java#L44-L56 | train |
bazaarvoice/emodb | job/src/main/java/com/bazaarvoice/emodb/job/service/DefaultJobService.java | DefaultJobService.recordFinalStatus | private <Q, R> void recordFinalStatus(JobIdentifier<Q, R> jobId, JobStatus<Q, R> jobStatus) {
try {
_jobStatusDAO.updateJobStatus(jobId, jobStatus);
} catch (Exception e) {
_log.error("Failed to record final status for job: [id={}, status={}]", jobId, jobStatus.getStatus(), e);
}
} | java | private <Q, R> void recordFinalStatus(JobIdentifier<Q, R> jobId, JobStatus<Q, R> jobStatus) {
try {
_jobStatusDAO.updateJobStatus(jobId, jobStatus);
} catch (Exception e) {
_log.error("Failed to record final status for job: [id={}, status={}]", jobId, jobStatus.getStatus(), e);
}
} | [
"private",
"<",
"Q",
",",
"R",
">",
"void",
"recordFinalStatus",
"(",
"JobIdentifier",
"<",
"Q",
",",
"R",
">",
"jobId",
",",
"JobStatus",
"<",
"Q",
",",
"R",
">",
"jobStatus",
")",
"{",
"try",
"{",
"_jobStatusDAO",
".",
"updateJobStatus",
"(",
"jobId"... | Attempts to record the final status for a job. Logs any errors, but always returns without throwing an
exception.
@param jobId The job ID
@param jobStatus The job's status
@param <Q> The job's request type
@param <R> The job's result type. | [
"Attempts",
"to",
"record",
"the",
"final",
"status",
"for",
"a",
"job",
".",
"Logs",
"any",
"errors",
"but",
"always",
"returns",
"without",
"throwing",
"an",
"exception",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/job/src/main/java/com/bazaarvoice/emodb/job/service/DefaultJobService.java#L337-L343 | train |
bazaarvoice/emodb | job/src/main/java/com/bazaarvoice/emodb/job/service/DefaultJobService.java | DefaultJobService.acknowledgeQueueMessage | private void acknowledgeQueueMessage(String messageId) {
try {
_queueService.acknowledge(_queueName, ImmutableList.of(messageId));
} catch (Exception e) {
_log.error("Failed to acknowledge message: [messageId={}]", messageId, e);
}
} | java | private void acknowledgeQueueMessage(String messageId) {
try {
_queueService.acknowledge(_queueName, ImmutableList.of(messageId));
} catch (Exception e) {
_log.error("Failed to acknowledge message: [messageId={}]", messageId, e);
}
} | [
"private",
"void",
"acknowledgeQueueMessage",
"(",
"String",
"messageId",
")",
"{",
"try",
"{",
"_queueService",
".",
"acknowledge",
"(",
"_queueName",
",",
"ImmutableList",
".",
"of",
"(",
"messageId",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")"... | Attempts to acknowledge a message on the queue. Logs any errors, but always returns without throwing an
exception.
@param messageId The message ID | [
"Attempts",
"to",
"acknowledge",
"a",
"message",
"on",
"the",
"queue",
".",
"Logs",
"any",
"errors",
"but",
"always",
"returns",
"without",
"throwing",
"an",
"exception",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/job/src/main/java/com/bazaarvoice/emodb/job/service/DefaultJobService.java#L350-L356 | train |
bazaarvoice/emodb | mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/schema/RefreshSchema.java | RefreshSchema.encode | private String encode(String str) {
if (str == null) {
return null;
}
try {
return URLEncoder.encode(str, Charsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
// Should never happen
throw Throwables.propagate(e);
}
} | java | private String encode(String str) {
if (str == null) {
return null;
}
try {
return URLEncoder.encode(str, Charsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
// Should never happen
throw Throwables.propagate(e);
}
} | [
"private",
"String",
"encode",
"(",
"String",
"str",
")",
"{",
"if",
"(",
"str",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"return",
"URLEncoder",
".",
"encode",
"(",
"str",
",",
"Charsets",
".",
"UTF_8",
".",
"name",
"(",
")"... | URL encodes the given string. | [
"URL",
"encodes",
"the",
"given",
"string",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/schema/RefreshSchema.java#L263-L273 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/scanner/scanstatus/DataStoreScanStatusDAO.java | DataStoreScanStatusDAO.getTable | private String getTable() {
if (!_tableChecked) {
if (!_dataStore.getTableExists(_tableName)) {
_dataStore.createTable(
_tableName,
new TableOptionsBuilder().setPlacement(_tablePlacement).build(),
ImmutableMap.<String, Object>of(),
new AuditBuilder().setLocalHost().setComment("Create scan status table").build());
_tableChecked = true;
}
}
return _tableName;
} | java | private String getTable() {
if (!_tableChecked) {
if (!_dataStore.getTableExists(_tableName)) {
_dataStore.createTable(
_tableName,
new TableOptionsBuilder().setPlacement(_tablePlacement).build(),
ImmutableMap.<String, Object>of(),
new AuditBuilder().setLocalHost().setComment("Create scan status table").build());
_tableChecked = true;
}
}
return _tableName;
} | [
"private",
"String",
"getTable",
"(",
")",
"{",
"if",
"(",
"!",
"_tableChecked",
")",
"{",
"if",
"(",
"!",
"_dataStore",
".",
"getTableExists",
"(",
"_tableName",
")",
")",
"{",
"_dataStore",
".",
"createTable",
"(",
"_tableName",
",",
"new",
"TableOptions... | Returns the scan status table name. On the first call it also verifies that the table exists, then skips this
check on future calls. | [
"Returns",
"the",
"scan",
"status",
"table",
"name",
".",
"On",
"the",
"first",
"call",
"it",
"also",
"verifies",
"that",
"the",
"table",
"exists",
"then",
"skips",
"this",
"check",
"on",
"future",
"calls",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/scanstatus/DataStoreScanStatusDAO.java#L53-L67 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/scanner/scanstatus/DataStoreScanStatusDAO.java | DataStoreScanStatusDAO.extrapolateStartTimeFromScanRanges | private Date extrapolateStartTimeFromScanRanges(List<ScanRangeStatus> pendingScanRanges,
List<ScanRangeStatus> activeScanRanges,
List<ScanRangeStatus> completeScanRanges) {
Date startTime = null;
for (ScanRangeStatus status : Iterables.concat(pendingScanRanges, activeScanRanges, completeScanRanges)) {
Date queuedTime = status.getScanQueuedTime();
if (queuedTime != null && (startTime == null || queuedTime.before(startTime))) {
startTime = queuedTime;
}
}
if (startTime == null) {
// Either the scan contained no scan ranges or no scans were ever queued, neither of which is likely to
// ever happen. But, so we don't return null choose a reasonably old date.
startTime = new Date(0);
}
return startTime;
} | java | private Date extrapolateStartTimeFromScanRanges(List<ScanRangeStatus> pendingScanRanges,
List<ScanRangeStatus> activeScanRanges,
List<ScanRangeStatus> completeScanRanges) {
Date startTime = null;
for (ScanRangeStatus status : Iterables.concat(pendingScanRanges, activeScanRanges, completeScanRanges)) {
Date queuedTime = status.getScanQueuedTime();
if (queuedTime != null && (startTime == null || queuedTime.before(startTime))) {
startTime = queuedTime;
}
}
if (startTime == null) {
// Either the scan contained no scan ranges or no scans were ever queued, neither of which is likely to
// ever happen. But, so we don't return null choose a reasonably old date.
startTime = new Date(0);
}
return startTime;
} | [
"private",
"Date",
"extrapolateStartTimeFromScanRanges",
"(",
"List",
"<",
"ScanRangeStatus",
">",
"pendingScanRanges",
",",
"List",
"<",
"ScanRangeStatus",
">",
"activeScanRanges",
",",
"List",
"<",
"ScanRangeStatus",
">",
"completeScanRanges",
")",
"{",
"Date",
"sta... | For grandfathered in ScanStatuses that did not include a startTime attribute extrapolate it as the earliest
time a scan range was queued. | [
"For",
"grandfathered",
"in",
"ScanStatuses",
"that",
"did",
"not",
"include",
"a",
"startTime",
"attribute",
"extrapolate",
"it",
"as",
"the",
"earliest",
"time",
"a",
"scan",
"range",
"was",
"queued",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/scanstatus/DataStoreScanStatusDAO.java#L209-L228 | train |
bazaarvoice/emodb | event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/AstyanaxEventId.java | AstyanaxEventId.computeChecksum | private static int computeChecksum(byte[] buf, int offset, int length, String channel) {
Hasher hasher = Hashing.murmur3_32().newHasher();
hasher.putBytes(buf, offset, length);
hasher.putUnencodedChars(channel);
return hasher.hash().asInt() & 0xffff;
} | java | private static int computeChecksum(byte[] buf, int offset, int length, String channel) {
Hasher hasher = Hashing.murmur3_32().newHasher();
hasher.putBytes(buf, offset, length);
hasher.putUnencodedChars(channel);
return hasher.hash().asInt() & 0xffff;
} | [
"private",
"static",
"int",
"computeChecksum",
"(",
"byte",
"[",
"]",
"buf",
",",
"int",
"offset",
",",
"int",
"length",
",",
"String",
"channel",
")",
"{",
"Hasher",
"hasher",
"=",
"Hashing",
".",
"murmur3_32",
"(",
")",
".",
"newHasher",
"(",
")",
";... | Computes a 16-bit checksum of the contents of the specific ByteBuffer and channel name. | [
"Computes",
"a",
"16",
"-",
"bit",
"checksum",
"of",
"the",
"contents",
"of",
"the",
"specific",
"ByteBuffer",
"and",
"channel",
"name",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/AstyanaxEventId.java#L75-L80 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/auth/OwnerDatabusAuthorizer.java | OwnerDatabusAuthorizer.ownerCanReadTable | private boolean ownerCanReadTable(String ownerId, String table) {
return _internalAuthorizer.hasPermissionById(ownerId, getReadPermission(table));
} | java | private boolean ownerCanReadTable(String ownerId, String table) {
return _internalAuthorizer.hasPermissionById(ownerId, getReadPermission(table));
} | [
"private",
"boolean",
"ownerCanReadTable",
"(",
"String",
"ownerId",
",",
"String",
"table",
")",
"{",
"return",
"_internalAuthorizer",
".",
"hasPermissionById",
"(",
"ownerId",
",",
"getReadPermission",
"(",
"table",
")",
")",
";",
"}"
] | Determines if an owner has read permission on a table. This always calls back to the authorizer and will not
return a cached value. | [
"Determines",
"if",
"an",
"owner",
"has",
"read",
"permission",
"on",
"a",
"table",
".",
"This",
"always",
"calls",
"back",
"to",
"the",
"authorizer",
"and",
"will",
"not",
"return",
"a",
"cached",
"value",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/auth/OwnerDatabusAuthorizer.java#L187-L189 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/auth/OwnerDatabusAuthorizer.java | OwnerDatabusAuthorizer.getReadPermission | private Permission getReadPermission(String table) {
return _readPermissionCache != null ?
_readPermissionCache.getUnchecked(table) :
createReadPermission(table);
} | java | private Permission getReadPermission(String table) {
return _readPermissionCache != null ?
_readPermissionCache.getUnchecked(table) :
createReadPermission(table);
} | [
"private",
"Permission",
"getReadPermission",
"(",
"String",
"table",
")",
"{",
"return",
"_readPermissionCache",
"!=",
"null",
"?",
"_readPermissionCache",
".",
"getUnchecked",
"(",
"table",
")",
":",
"createReadPermission",
"(",
"table",
")",
";",
"}"
] | Gets the Permission instance for read permission on a table. If caching is enabled the result is either returned
from or added to the cache. | [
"Gets",
"the",
"Permission",
"instance",
"for",
"read",
"permission",
"on",
"a",
"table",
".",
"If",
"caching",
"is",
"enabled",
"the",
"result",
"is",
"either",
"returned",
"from",
"or",
"added",
"to",
"the",
"cache",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/auth/OwnerDatabusAuthorizer.java#L195-L199 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/auth/OwnerDatabusAuthorizer.java | OwnerDatabusAuthorizer.createReadPermission | private Permission createReadPermission(String table) {
return _permissionResolver.resolvePermission(Permissions.readSorTable(new NamedResource(table)));
} | java | private Permission createReadPermission(String table) {
return _permissionResolver.resolvePermission(Permissions.readSorTable(new NamedResource(table)));
} | [
"private",
"Permission",
"createReadPermission",
"(",
"String",
"table",
")",
"{",
"return",
"_permissionResolver",
".",
"resolvePermission",
"(",
"Permissions",
".",
"readSorTable",
"(",
"new",
"NamedResource",
"(",
"table",
")",
")",
")",
";",
"}"
] | Creates a Permission instance for read permission on a table. This always resolves a new instance and will
not return a cached value. | [
"Creates",
"a",
"Permission",
"instance",
"for",
"read",
"permission",
"on",
"a",
"table",
".",
"This",
"always",
"resolves",
"a",
"new",
"instance",
"and",
"will",
"not",
"return",
"a",
"cached",
"value",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/auth/OwnerDatabusAuthorizer.java#L205-L207 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/EmoFileSystem.java | EmoFileSystem.splitNameWithoutGzipExtension | private String splitNameWithoutGzipExtension(String split)
throws IOException {
if (split == null) {
throw new IOException("Path is not a split");
}
if (split.endsWith(".gz")) {
return split.substring(0, split.length() - 3);
}
return split;
} | java | private String splitNameWithoutGzipExtension(String split)
throws IOException {
if (split == null) {
throw new IOException("Path is not a split");
}
if (split.endsWith(".gz")) {
return split.substring(0, split.length() - 3);
}
return split;
} | [
"private",
"String",
"splitNameWithoutGzipExtension",
"(",
"String",
"split",
")",
"throws",
"IOException",
"{",
"if",
"(",
"split",
"==",
"null",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"Path is not a split\"",
")",
";",
"}",
"if",
"(",
"split",
".",
... | Since we appended a gzip extension to the split file name we need to take it off to get the actual split. | [
"Since",
"we",
"appended",
"a",
"gzip",
"extension",
"to",
"the",
"split",
"file",
"name",
"we",
"need",
"to",
"take",
"it",
"off",
"to",
"get",
"the",
"actual",
"split",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/EmoFileSystem.java#L265-L274 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/EmoFileSystem.java | EmoFileSystem.open | @Override
public FSDataInputStream open(Path path, int bufferSize)
throws IOException {
String table = getTableName(_rootPath, path);
String split = getSplitName(_rootPath, path);
split = splitNameWithoutGzipExtension(split);
return new FSDataInputStream(new EmoSplitInputStream(table, split));
} | java | @Override
public FSDataInputStream open(Path path, int bufferSize)
throws IOException {
String table = getTableName(_rootPath, path);
String split = getSplitName(_rootPath, path);
split = splitNameWithoutGzipExtension(split);
return new FSDataInputStream(new EmoSplitInputStream(table, split));
} | [
"@",
"Override",
"public",
"FSDataInputStream",
"open",
"(",
"Path",
"path",
",",
"int",
"bufferSize",
")",
"throws",
"IOException",
"{",
"String",
"table",
"=",
"getTableName",
"(",
"_rootPath",
",",
"path",
")",
";",
"String",
"split",
"=",
"getSplitName",
... | Opens a split for reading. Note that the preferred and more efficient way to do this is by using an
EmoInputFormat. However, if using a MapReduce framework which does not support custom input formats,
such as Presto, the splits can be opened directly using this method. | [
"Opens",
"a",
"split",
"for",
"reading",
".",
"Note",
"that",
"the",
"preferred",
"and",
"more",
"efficient",
"way",
"to",
"do",
"this",
"is",
"by",
"using",
"an",
"EmoInputFormat",
".",
"However",
"if",
"using",
"a",
"MapReduce",
"framework",
"which",
"do... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/EmoFileSystem.java#L281-L288 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/EmoFileSystem.java | EmoFileSystem.create | @Override
public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress)
throws IOException {
throw new IOException("Create not supported for EmoFileSystem: " + f);
} | java | @Override
public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress)
throws IOException {
throw new IOException("Create not supported for EmoFileSystem: " + f);
} | [
"@",
"Override",
"public",
"FSDataOutputStream",
"create",
"(",
"Path",
"f",
",",
"FsPermission",
"permission",
",",
"boolean",
"overwrite",
",",
"int",
"bufferSize",
",",
"short",
"replication",
",",
"long",
"blockSize",
",",
"Progressable",
"progress",
")",
"t... | All remaining FileSystem operations are not supported and will throw exceptions. | [
"All",
"remaining",
"FileSystem",
"operations",
"are",
"not",
"supported",
"and",
"will",
"throw",
"exceptions",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/EmoFileSystem.java#L483-L487 | train |
bazaarvoice/emodb | common/dropwizard-client/src/main/java/com/bazaarvoice/emodb/common/jersey/dropwizard/JerseyEmoResource.java | JerseyEmoResource.asEmoClientException | private EmoClientException asEmoClientException(UniformInterfaceException e)
throws EmoClientException {
throw new EmoClientException(e.getMessage(), e, toEmoResponse(e.getResponse()));
} | java | private EmoClientException asEmoClientException(UniformInterfaceException e)
throws EmoClientException {
throw new EmoClientException(e.getMessage(), e, toEmoResponse(e.getResponse()));
} | [
"private",
"EmoClientException",
"asEmoClientException",
"(",
"UniformInterfaceException",
"e",
")",
"throws",
"EmoClientException",
"{",
"throw",
"new",
"EmoClientException",
"(",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
",",
"toEmoResponse",
"(",
"e",
".",
"g... | Returns an EmoClientException with a thin wrapper around the Jersey exception response. | [
"Returns",
"an",
"EmoClientException",
"with",
"a",
"thin",
"wrapper",
"around",
"the",
"Jersey",
"exception",
"response",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/dropwizard-client/src/main/java/com/bazaarvoice/emodb/common/jersey/dropwizard/JerseyEmoResource.java#L138-L141 | train |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/core/AbstractBatchReader.java | AbstractBatchReader.loadNextBatch | private boolean loadNextBatch() {
if (!hasNextBatch()) {
// No batches remaining to load
_batch = Iterators.emptyIterator();
return true;
}
Exception batchFetchException = null;
_timer.start();
try {
_batch = nextBatch(_currentBatchSize);
} catch (Exception e) {
batchFetchException = e;
} finally {
_timer.stop();
}
long batchFetchTime = _timer.elapsed(TimeUnit.MILLISECONDS);
_timer.reset();
if (batchFetchException != null) {
boolean isTimeout = isTimeoutException(batchFetchException);
boolean isDataSize = !isTimeout && isDataSizeException(batchFetchException);
// Check if the exception was not due to a timeout or size limit, or if the batch size is already at the minimum
if (!(isTimeout || isDataSize) || _currentBatchSize == _minBatchSize) {
throw Throwables.propagate(batchFetchException);
}
// Reduce the current batch size by half, but not below the minimum size
_currentBatchSize = Math.max(_currentBatchSize / 2, _minBatchSize);
if (isTimeout) {
// Record how long it took to timeout; we'll use this to approximate and try to avoid future timeouts
_lastTimeoutTime = batchFetchTime;
}
return false;
}
// We didn't time out. Evaluate whether to increase the current batch size.
int nextBatchSize = Math.min(_currentBatchSize + _batchIncrementSize, _maxBatchSize);
if (nextBatchSize != _currentBatchSize) {
if (_lastTimeoutTime != 0) {
// We've seen a timeout; use this as a guide to predict whether the next batch will timeout.
float msPerRow = (float) batchFetchTime / _currentBatchSize;
int estimatedMaxBatchSizeUntilTimeout = (int) (_lastTimeoutTime / msPerRow);
// Check for negative value in case of integer size overrun
if (estimatedMaxBatchSizeUntilTimeout > 0 && estimatedMaxBatchSizeUntilTimeout < nextBatchSize) {
nextBatchSize = estimatedMaxBatchSizeUntilTimeout;
}
}
_currentBatchSize = nextBatchSize;
}
// It's possible the underlying resource read the requested number of rows but, after filtering is applied,
// all rows are excluded. This can happen, for example, if Cassandra returns the requested number of rows
// but they are all range ghosts. In this case return false to prompt the next batch to load immediately.
return _batch.hasNext();
} | java | private boolean loadNextBatch() {
if (!hasNextBatch()) {
// No batches remaining to load
_batch = Iterators.emptyIterator();
return true;
}
Exception batchFetchException = null;
_timer.start();
try {
_batch = nextBatch(_currentBatchSize);
} catch (Exception e) {
batchFetchException = e;
} finally {
_timer.stop();
}
long batchFetchTime = _timer.elapsed(TimeUnit.MILLISECONDS);
_timer.reset();
if (batchFetchException != null) {
boolean isTimeout = isTimeoutException(batchFetchException);
boolean isDataSize = !isTimeout && isDataSizeException(batchFetchException);
// Check if the exception was not due to a timeout or size limit, or if the batch size is already at the minimum
if (!(isTimeout || isDataSize) || _currentBatchSize == _minBatchSize) {
throw Throwables.propagate(batchFetchException);
}
// Reduce the current batch size by half, but not below the minimum size
_currentBatchSize = Math.max(_currentBatchSize / 2, _minBatchSize);
if (isTimeout) {
// Record how long it took to timeout; we'll use this to approximate and try to avoid future timeouts
_lastTimeoutTime = batchFetchTime;
}
return false;
}
// We didn't time out. Evaluate whether to increase the current batch size.
int nextBatchSize = Math.min(_currentBatchSize + _batchIncrementSize, _maxBatchSize);
if (nextBatchSize != _currentBatchSize) {
if (_lastTimeoutTime != 0) {
// We've seen a timeout; use this as a guide to predict whether the next batch will timeout.
float msPerRow = (float) batchFetchTime / _currentBatchSize;
int estimatedMaxBatchSizeUntilTimeout = (int) (_lastTimeoutTime / msPerRow);
// Check for negative value in case of integer size overrun
if (estimatedMaxBatchSizeUntilTimeout > 0 && estimatedMaxBatchSizeUntilTimeout < nextBatchSize) {
nextBatchSize = estimatedMaxBatchSizeUntilTimeout;
}
}
_currentBatchSize = nextBatchSize;
}
// It's possible the underlying resource read the requested number of rows but, after filtering is applied,
// all rows are excluded. This can happen, for example, if Cassandra returns the requested number of rows
// but they are all range ghosts. In this case return false to prompt the next batch to load immediately.
return _batch.hasNext();
} | [
"private",
"boolean",
"loadNextBatch",
"(",
")",
"{",
"if",
"(",
"!",
"hasNextBatch",
"(",
")",
")",
"{",
"// No batches remaining to load",
"_batch",
"=",
"Iterators",
".",
"emptyIterator",
"(",
")",
";",
"return",
"true",
";",
"}",
"Exception",
"batchFetchEx... | Loads the next batch from the underlying resource.
@return True if a non-empty batch was read or all data has already been read, false if the batch was
empty or the batch read timed out. | [
"Loads",
"the",
"next",
"batch",
"from",
"the",
"underlying",
"resource",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/core/AbstractBatchReader.java#L91-L153 | train |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/audit/s3/AthenaAuditWriter.java | AthenaAuditWriter.prepareClosedLogFilesForTransfer | private void prepareClosedLogFilesForTransfer() {
for (final File logFile : _stagingDir.listFiles((dir, name) -> name.startsWith(_logFilePrefix) && name.endsWith(CLOSED_FILE_SUFFIX))) {
boolean moved;
String fileName = logFile.getName().substring(0, logFile.getName().length() - CLOSED_FILE_SUFFIX.length()) + COMPRESSED_FILE_SUFFIX;
try (FileInputStream fileIn = new FileInputStream(logFile);
FileOutputStream fileOut = new FileOutputStream(new File(logFile.getParentFile(), fileName));
GzipCompressorOutputStream gzipOut = new GzipCompressorOutputStream(fileOut)) {
ByteStreams.copy(fileIn, gzipOut);
moved = true;
} catch (IOException e) {
_log.warn("Failed to compress audit log file: {}", logFile, e);
moved = false;
}
if (moved) {
if (!logFile.delete()) {
_log.warn("Failed to delete audit log file: {}", logFile);
}
}
}
} | java | private void prepareClosedLogFilesForTransfer() {
for (final File logFile : _stagingDir.listFiles((dir, name) -> name.startsWith(_logFilePrefix) && name.endsWith(CLOSED_FILE_SUFFIX))) {
boolean moved;
String fileName = logFile.getName().substring(0, logFile.getName().length() - CLOSED_FILE_SUFFIX.length()) + COMPRESSED_FILE_SUFFIX;
try (FileInputStream fileIn = new FileInputStream(logFile);
FileOutputStream fileOut = new FileOutputStream(new File(logFile.getParentFile(), fileName));
GzipCompressorOutputStream gzipOut = new GzipCompressorOutputStream(fileOut)) {
ByteStreams.copy(fileIn, gzipOut);
moved = true;
} catch (IOException e) {
_log.warn("Failed to compress audit log file: {}", logFile, e);
moved = false;
}
if (moved) {
if (!logFile.delete()) {
_log.warn("Failed to delete audit log file: {}", logFile);
}
}
}
} | [
"private",
"void",
"prepareClosedLogFilesForTransfer",
"(",
")",
"{",
"for",
"(",
"final",
"File",
"logFile",
":",
"_stagingDir",
".",
"listFiles",
"(",
"(",
"dir",
",",
"name",
")",
"->",
"name",
".",
"startsWith",
"(",
"_logFilePrefix",
")",
"&&",
"name",
... | This method takes all closed log files and GZIPs and renames them in preparation for transfer. If the operation
fails the original file is unmodified so the next call should attempt to prepare the file again. This means
the same file may be transferred more than once, but this guarantees that so long as the host remains active the
file will eventually be transferred. | [
"This",
"method",
"takes",
"all",
"closed",
"log",
"files",
"and",
"GZIPs",
"and",
"renames",
"them",
"in",
"preparation",
"for",
"transfer",
".",
"If",
"the",
"operation",
"fails",
"the",
"original",
"file",
"is",
"unmodified",
"so",
"the",
"next",
"call",
... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/audit/s3/AthenaAuditWriter.java#L280-L301 | train |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/audit/s3/AthenaAuditWriter.java | AthenaAuditWriter.processQueuedAudits | private void processQueuedAudits(boolean interruptable) {
QueuedAudit audit;
try {
while (!(_auditService.isShutdown() && interruptable) && ((audit = _auditQueue.poll()) != null)) {
boolean written = false;
while (!written) {
AuditOutput auditOutput = getAuditOutputForTime(audit.time);
written = auditOutput.writeAudit(audit);
}
}
} catch (Exception e) {
_log.error("Processing of queued audits failed", e);
}
} | java | private void processQueuedAudits(boolean interruptable) {
QueuedAudit audit;
try {
while (!(_auditService.isShutdown() && interruptable) && ((audit = _auditQueue.poll()) != null)) {
boolean written = false;
while (!written) {
AuditOutput auditOutput = getAuditOutputForTime(audit.time);
written = auditOutput.writeAudit(audit);
}
}
} catch (Exception e) {
_log.error("Processing of queued audits failed", e);
}
} | [
"private",
"void",
"processQueuedAudits",
"(",
"boolean",
"interruptable",
")",
"{",
"QueuedAudit",
"audit",
";",
"try",
"{",
"while",
"(",
"!",
"(",
"_auditService",
".",
"isShutdown",
"(",
")",
"&&",
"interruptable",
")",
"&&",
"(",
"(",
"audit",
"=",
"_... | This method is run at regular intervals to remove audits from the audit queue and write them to a local file. | [
"This",
"method",
"is",
"run",
"at",
"regular",
"intervals",
"to",
"remove",
"audits",
"from",
"the",
"audit",
"queue",
"and",
"write",
"them",
"to",
"a",
"local",
"file",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/audit/s3/AthenaAuditWriter.java#L341-L354 | train |
bazaarvoice/emodb | auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java | ApiKeyRealm.prepareCacheManager | private CacheManager prepareCacheManager(CacheManager cacheManager) {
if (cacheManager == null || !(cacheManager instanceof InvalidatableCacheManager)) {
return cacheManager;
}
return new ValidatingCacheManager(cacheManager) {
@Nullable
@Override
protected CacheValidator<?, ?> getCacheValidatorForCache(String name) {
String cacheName = getAuthenticationCacheName();
if (cacheName != null && name.equals(cacheName)) {
return new ValidatingCacheManager.CacheValidator<Object, AuthenticationInfo>(Object.class, AuthenticationInfo.class) {
@Override
public boolean isCurrentValue(Object key, AuthenticationInfo value) {
String id;
if (AnonymousToken.isAnonymousPrincipal(key)) {
if (_anonymousId == null) {
return false;
}
id = _anonymousId;
} else {
// For all non-anonymous users "key" is an API key
id = (String) key;
}
AuthenticationInfo authenticationInfo = getUncachedAuthenticationInfoForKey(id);
return Objects.equal(authenticationInfo, value);
}
};
}
cacheName = getAuthorizationCacheName();
if (cacheName != null && name.equals(cacheName)) {
return new ValidatingCacheManager.CacheValidator<Object, AuthorizationInfo>(Object.class, AuthorizationInfo.class) {
@Override
public boolean isCurrentValue(Object key, AuthorizationInfo value) {
// Key is always a principal collection
PrincipalCollection principalCollection = (PrincipalCollection) key;
AuthorizationInfo authorizationInfo = getUncachedAuthorizationInfoFromPrincipals(principalCollection);
// Only the roles are used for authorization
return authorizationInfo != null && authorizationInfo.getRoles().equals(value.getRoles());
}
};
}
cacheName = getIdAuthorizationCacheName();
if (cacheName != null && name.equals(cacheName)) {
return new ValidatingCacheManager.CacheValidator<String, AuthorizationInfo>(String.class, AuthorizationInfo.class) {
@Override
public boolean isCurrentValue(String key, AuthorizationInfo value) {
// Key is the identity's ID
AuthorizationInfo authorizationInfo = getUncachedAuthorizationInfoById(key);
// Only the roles are used for authorization
return authorizationInfo != null && authorizationInfo.getRoles().equals(value.getRoles());
}
};
}
cacheName = getRolesCacheName();
if (cacheName != null && name.equals(cacheName)) {
return new ValidatingCacheManager.CacheValidator<String, RolePermissionSet>(String.class, RolePermissionSet.class) {
@Override
public boolean isCurrentValue(String key, RolePermissionSet value) {
// The key is the role name
Set<Permission> currentPermissions = _permissionReader.getPermissions(PermissionIDs.forRole(key));
return value.permissions().equals(currentPermissions);
}
};
}
return null;
}
};
} | java | private CacheManager prepareCacheManager(CacheManager cacheManager) {
if (cacheManager == null || !(cacheManager instanceof InvalidatableCacheManager)) {
return cacheManager;
}
return new ValidatingCacheManager(cacheManager) {
@Nullable
@Override
protected CacheValidator<?, ?> getCacheValidatorForCache(String name) {
String cacheName = getAuthenticationCacheName();
if (cacheName != null && name.equals(cacheName)) {
return new ValidatingCacheManager.CacheValidator<Object, AuthenticationInfo>(Object.class, AuthenticationInfo.class) {
@Override
public boolean isCurrentValue(Object key, AuthenticationInfo value) {
String id;
if (AnonymousToken.isAnonymousPrincipal(key)) {
if (_anonymousId == null) {
return false;
}
id = _anonymousId;
} else {
// For all non-anonymous users "key" is an API key
id = (String) key;
}
AuthenticationInfo authenticationInfo = getUncachedAuthenticationInfoForKey(id);
return Objects.equal(authenticationInfo, value);
}
};
}
cacheName = getAuthorizationCacheName();
if (cacheName != null && name.equals(cacheName)) {
return new ValidatingCacheManager.CacheValidator<Object, AuthorizationInfo>(Object.class, AuthorizationInfo.class) {
@Override
public boolean isCurrentValue(Object key, AuthorizationInfo value) {
// Key is always a principal collection
PrincipalCollection principalCollection = (PrincipalCollection) key;
AuthorizationInfo authorizationInfo = getUncachedAuthorizationInfoFromPrincipals(principalCollection);
// Only the roles are used for authorization
return authorizationInfo != null && authorizationInfo.getRoles().equals(value.getRoles());
}
};
}
cacheName = getIdAuthorizationCacheName();
if (cacheName != null && name.equals(cacheName)) {
return new ValidatingCacheManager.CacheValidator<String, AuthorizationInfo>(String.class, AuthorizationInfo.class) {
@Override
public boolean isCurrentValue(String key, AuthorizationInfo value) {
// Key is the identity's ID
AuthorizationInfo authorizationInfo = getUncachedAuthorizationInfoById(key);
// Only the roles are used for authorization
return authorizationInfo != null && authorizationInfo.getRoles().equals(value.getRoles());
}
};
}
cacheName = getRolesCacheName();
if (cacheName != null && name.equals(cacheName)) {
return new ValidatingCacheManager.CacheValidator<String, RolePermissionSet>(String.class, RolePermissionSet.class) {
@Override
public boolean isCurrentValue(String key, RolePermissionSet value) {
// The key is the role name
Set<Permission> currentPermissions = _permissionReader.getPermissions(PermissionIDs.forRole(key));
return value.permissions().equals(currentPermissions);
}
};
}
return null;
}
};
} | [
"private",
"CacheManager",
"prepareCacheManager",
"(",
"CacheManager",
"cacheManager",
")",
"{",
"if",
"(",
"cacheManager",
"==",
"null",
"||",
"!",
"(",
"cacheManager",
"instanceof",
"InvalidatableCacheManager",
")",
")",
"{",
"return",
"cacheManager",
";",
"}",
... | If necessary, wraps the raw cache manager with a validating facade. | [
"If",
"necessary",
"wraps",
"the",
"raw",
"cache",
"manager",
"with",
"a",
"validating",
"facade",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L94-L167 | train |
bazaarvoice/emodb | auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java | ApiKeyRealm.supports | @Override
public boolean supports(AuthenticationToken token) {
return super.supports(token) || (_anonymousId != null && AnonymousToken.isAnonymous(token));
} | java | @Override
public boolean supports(AuthenticationToken token) {
return super.supports(token) || (_anonymousId != null && AnonymousToken.isAnonymous(token));
} | [
"@",
"Override",
"public",
"boolean",
"supports",
"(",
"AuthenticationToken",
"token",
")",
"{",
"return",
"super",
".",
"supports",
"(",
"token",
")",
"||",
"(",
"_anonymousId",
"!=",
"null",
"&&",
"AnonymousToken",
".",
"isAnonymous",
"(",
"token",
")",
")... | Override the parent method to also accept anonymous tokens | [
"Override",
"the",
"parent",
"method",
"to",
"also",
"accept",
"anonymous",
"tokens"
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L181-L184 | train |
bazaarvoice/emodb | auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java | ApiKeyRealm.doGetAuthenticationInfo | @SuppressWarnings("unchecked")
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
String id;
if (AnonymousToken.isAnonymous(token)) {
// Only continue if an anonymous identity has been set
if (_anonymousId != null) {
id = _anonymousId;
} else {
return null;
}
} else {
id = ((ApiKeyAuthenticationToken) token).getPrincipal();
}
return getUncachedAuthenticationInfoForKey(id);
} | java | @SuppressWarnings("unchecked")
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
throws AuthenticationException {
String id;
if (AnonymousToken.isAnonymous(token)) {
// Only continue if an anonymous identity has been set
if (_anonymousId != null) {
id = _anonymousId;
} else {
return null;
}
} else {
id = ((ApiKeyAuthenticationToken) token).getPrincipal();
}
return getUncachedAuthenticationInfoForKey(id);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"@",
"Override",
"protected",
"AuthenticationInfo",
"doGetAuthenticationInfo",
"(",
"AuthenticationToken",
"token",
")",
"throws",
"AuthenticationException",
"{",
"String",
"id",
";",
"if",
"(",
"AnonymousToken",
".",
... | Gets the AuthenticationInfo that matches a token. This method is only called if the info is not already
cached by the realm, so this method does not need to perform any further caching. | [
"Gets",
"the",
"AuthenticationInfo",
"that",
"matches",
"a",
"token",
".",
"This",
"method",
"is",
"only",
"called",
"if",
"the",
"info",
"is",
"not",
"already",
"cached",
"by",
"the",
"realm",
"so",
"this",
"method",
"does",
"not",
"need",
"to",
"perform"... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L190-L208 | train |
bazaarvoice/emodb | auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java | ApiKeyRealm.createAuthenticationInfo | private ApiKeyAuthenticationInfo createAuthenticationInfo(String authenticationId, ApiKey apiKey) {
return new ApiKeyAuthenticationInfo(authenticationId, apiKey, getName());
} | java | private ApiKeyAuthenticationInfo createAuthenticationInfo(String authenticationId, ApiKey apiKey) {
return new ApiKeyAuthenticationInfo(authenticationId, apiKey, getName());
} | [
"private",
"ApiKeyAuthenticationInfo",
"createAuthenticationInfo",
"(",
"String",
"authenticationId",
",",
"ApiKey",
"apiKey",
")",
"{",
"return",
"new",
"ApiKeyAuthenticationInfo",
"(",
"authenticationId",
",",
"apiKey",
",",
"getName",
"(",
")",
")",
";",
"}"
] | Simple method to build and AuthenticationInfo instance from an API key. | [
"Simple",
"method",
"to",
"build",
"and",
"AuthenticationInfo",
"instance",
"from",
"an",
"API",
"key",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L225-L227 | train |
bazaarvoice/emodb | auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java | ApiKeyRealm.doGetAuthorizationInfo | @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
AuthorizationInfo authorizationInfo = getUncachedAuthorizationInfoFromPrincipals(principals);
Cache<String, AuthorizationInfo> idAuthorizationCache = getAvailableIdAuthorizationCache();
if (idAuthorizationCache != null) {
// Proactively cache any ID authorization info not already in cache
for (PrincipalWithRoles principal : getPrincipalsFromPrincipalCollection(principals)) {
if (idAuthorizationCache.get(principal.getId()) == null) {
cacheAuthorizationInfoById(principal.getId(), authorizationInfo);
}
}
}
return authorizationInfo;
} | java | @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
AuthorizationInfo authorizationInfo = getUncachedAuthorizationInfoFromPrincipals(principals);
Cache<String, AuthorizationInfo> idAuthorizationCache = getAvailableIdAuthorizationCache();
if (idAuthorizationCache != null) {
// Proactively cache any ID authorization info not already in cache
for (PrincipalWithRoles principal : getPrincipalsFromPrincipalCollection(principals)) {
if (idAuthorizationCache.get(principal.getId()) == null) {
cacheAuthorizationInfoById(principal.getId(), authorizationInfo);
}
}
}
return authorizationInfo;
} | [
"@",
"Override",
"protected",
"AuthorizationInfo",
"doGetAuthorizationInfo",
"(",
"PrincipalCollection",
"principals",
")",
"{",
"AuthorizationInfo",
"authorizationInfo",
"=",
"getUncachedAuthorizationInfoFromPrincipals",
"(",
"principals",
")",
";",
"Cache",
"<",
"String",
... | Gets the AuthorizationInfo that matches a token. This method is only called if the info is not already
cached by the realm, so this method does not need to perform any further caching. | [
"Gets",
"the",
"AuthorizationInfo",
"that",
"matches",
"a",
"token",
".",
"This",
"method",
"is",
"only",
"called",
"if",
"the",
"info",
"is",
"not",
"already",
"cached",
"by",
"the",
"realm",
"so",
"this",
"method",
"does",
"not",
"need",
"to",
"perform",... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L233-L249 | train |
bazaarvoice/emodb | auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java | ApiKeyRealm.getRolePermissions | protected Collection<Permission> getRolePermissions(String role) {
if (role == null) {
return null;
}
Cache<String, RolePermissionSet> cache = getAvailableRolesCache();
if (cache == null) {
return _permissionReader.getPermissions(PermissionIDs.forRole(role));
}
RolePermissionSet rolePermissionSet = cache.get(role);
if (rolePermissionSet == null) {
Set<Permission> permissions = _permissionReader.getPermissions(PermissionIDs.forRole(role));
rolePermissionSet = new SimpleRolePermissionSet(permissions);
cache.put(role, rolePermissionSet);
}
return rolePermissionSet.permissions();
} | java | protected Collection<Permission> getRolePermissions(String role) {
if (role == null) {
return null;
}
Cache<String, RolePermissionSet> cache = getAvailableRolesCache();
if (cache == null) {
return _permissionReader.getPermissions(PermissionIDs.forRole(role));
}
RolePermissionSet rolePermissionSet = cache.get(role);
if (rolePermissionSet == null) {
Set<Permission> permissions = _permissionReader.getPermissions(PermissionIDs.forRole(role));
rolePermissionSet = new SimpleRolePermissionSet(permissions);
cache.put(role, rolePermissionSet);
}
return rolePermissionSet.permissions();
} | [
"protected",
"Collection",
"<",
"Permission",
">",
"getRolePermissions",
"(",
"String",
"role",
")",
"{",
"if",
"(",
"role",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"Cache",
"<",
"String",
",",
"RolePermissionSet",
">",
"cache",
"=",
"getAvaila... | Gets the permissions for a role. If possible the permissions are cached for efficiency. | [
"Gets",
"the",
"permissions",
"for",
"a",
"role",
".",
"If",
"possible",
"the",
"permissions",
"are",
"cached",
"for",
"efficiency",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L331-L350 | train |
bazaarvoice/emodb | auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java | ApiKeyRealm.getAuthorizationInfoById | @Nullable
private AuthorizationInfo getAuthorizationInfoById(String id) {
AuthorizationInfo authorizationInfo;
// Search the cache first
Cache<String, AuthorizationInfo> idAuthorizationCache = getAvailableIdAuthorizationCache();
if (idAuthorizationCache != null) {
authorizationInfo = idAuthorizationCache.get(id);
if (authorizationInfo != null) {
// Check whether it is the stand-in "null" cached value
if (authorizationInfo != _nullAuthorizationInfo) {
_log.debug("Authorization info found cached for id {}", id);
return authorizationInfo;
} else {
_log.debug("Authorization info previously cached as not found for id {}", id);
return null;
}
}
}
authorizationInfo = getUncachedAuthorizationInfoById(id);
cacheAuthorizationInfoById(id, authorizationInfo);
return authorizationInfo;
} | java | @Nullable
private AuthorizationInfo getAuthorizationInfoById(String id) {
AuthorizationInfo authorizationInfo;
// Search the cache first
Cache<String, AuthorizationInfo> idAuthorizationCache = getAvailableIdAuthorizationCache();
if (idAuthorizationCache != null) {
authorizationInfo = idAuthorizationCache.get(id);
if (authorizationInfo != null) {
// Check whether it is the stand-in "null" cached value
if (authorizationInfo != _nullAuthorizationInfo) {
_log.debug("Authorization info found cached for id {}", id);
return authorizationInfo;
} else {
_log.debug("Authorization info previously cached as not found for id {}", id);
return null;
}
}
}
authorizationInfo = getUncachedAuthorizationInfoById(id);
cacheAuthorizationInfoById(id, authorizationInfo);
return authorizationInfo;
} | [
"@",
"Nullable",
"private",
"AuthorizationInfo",
"getAuthorizationInfoById",
"(",
"String",
"id",
")",
"{",
"AuthorizationInfo",
"authorizationInfo",
";",
"// Search the cache first",
"Cache",
"<",
"String",
",",
"AuthorizationInfo",
">",
"idAuthorizationCache",
"=",
"get... | Gets the authorization info for a user by their ID. If possible the value is cached for efficient lookup. | [
"Gets",
"the",
"authorization",
"info",
"for",
"a",
"user",
"by",
"their",
"ID",
".",
"If",
"possible",
"the",
"value",
"is",
"cached",
"for",
"efficient",
"lookup",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L375-L400 | train |
bazaarvoice/emodb | auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java | ApiKeyRealm.cacheAuthorizationInfoById | private void cacheAuthorizationInfoById(String id, AuthorizationInfo authorizationInfo) {
Cache<String, AuthorizationInfo> idAuthorizationCache = getAvailableIdAuthorizationCache();
if (idAuthorizationCache != null) {
idAuthorizationCache.put(id, authorizationInfo);
}
} | java | private void cacheAuthorizationInfoById(String id, AuthorizationInfo authorizationInfo) {
Cache<String, AuthorizationInfo> idAuthorizationCache = getAvailableIdAuthorizationCache();
if (idAuthorizationCache != null) {
idAuthorizationCache.put(id, authorizationInfo);
}
} | [
"private",
"void",
"cacheAuthorizationInfoById",
"(",
"String",
"id",
",",
"AuthorizationInfo",
"authorizationInfo",
")",
"{",
"Cache",
"<",
"String",
",",
"AuthorizationInfo",
">",
"idAuthorizationCache",
"=",
"getAvailableIdAuthorizationCache",
"(",
")",
";",
"if",
... | If possible, this method caches the authorization info for an API key by its ID. This may be called
either by an explicit call to get the authorization info by ID or as a side effect of loading the
authorization info by API key and proactive caching by ID. | [
"If",
"possible",
"this",
"method",
"caches",
"the",
"authorization",
"info",
"for",
"an",
"API",
"key",
"by",
"its",
"ID",
".",
"This",
"may",
"be",
"called",
"either",
"by",
"an",
"explicit",
"call",
"to",
"get",
"the",
"authorization",
"info",
"by",
"... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/apikey/ApiKeyRealm.java#L407-L413 | train |
bazaarvoice/emodb | sor-api/src/main/java/com/bazaarvoice/emodb/sor/delta/deser/JsonTokener.java | JsonTokener.nextClean | public char nextClean(char c) {
char n = nextClean();
if (n != c) {
throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'");
}
return n;
} | java | public char nextClean(char c) {
char n = nextClean();
if (n != c) {
throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'");
}
return n;
} | [
"public",
"char",
"nextClean",
"(",
"char",
"c",
")",
"{",
"char",
"n",
"=",
"nextClean",
"(",
")",
";",
"if",
"(",
"n",
"!=",
"c",
")",
"{",
"throw",
"syntaxError",
"(",
"\"Expected '\"",
"+",
"c",
"+",
"\"' and instead saw '\"",
"+",
"n",
"+",
"\"'... | Consume the next character, skipping whitespace, and check that it matches a
specified character.
@param c The character to match.
@return The character. | [
"Consume",
"the",
"next",
"character",
"skipping",
"whitespace",
"and",
"check",
"that",
"it",
"matches",
"a",
"specified",
"character",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-api/src/main/java/com/bazaarvoice/emodb/sor/delta/deser/JsonTokener.java#L143-L149 | train |
bazaarvoice/emodb | sor-api/src/main/java/com/bazaarvoice/emodb/sor/delta/deser/JsonTokener.java | JsonTokener.nextString | public String nextString() {
nextClean('"');
StringBuilder sb = new StringBuilder();
for (;;) {
char c = next();
switch (c) {
case 0:
case '\n':
case '\r':
throw syntaxError("Unterminated string");
case '\\':
c = next();
switch (c) {
case 'b':
sb.append('\b');
break;
case 't':
sb.append('\t');
break;
case 'n':
sb.append('\n');
break;
case 'f':
sb.append('\f');
break;
case 'r':
sb.append('\r');
break;
case 'u':
sb.append((char)Integer.parseInt(next(4), 16));
break;
default:
sb.append(c);
}
break;
case '"':
return sb.toString();
default:
if (c < ' ') {
throw syntaxError("Unescaped control character (ascii " + ((int) c) + ") in string");
}
sb.append(c);
break;
}
}
} | java | public String nextString() {
nextClean('"');
StringBuilder sb = new StringBuilder();
for (;;) {
char c = next();
switch (c) {
case 0:
case '\n':
case '\r':
throw syntaxError("Unterminated string");
case '\\':
c = next();
switch (c) {
case 'b':
sb.append('\b');
break;
case 't':
sb.append('\t');
break;
case 'n':
sb.append('\n');
break;
case 'f':
sb.append('\f');
break;
case 'r':
sb.append('\r');
break;
case 'u':
sb.append((char)Integer.parseInt(next(4), 16));
break;
default:
sb.append(c);
}
break;
case '"':
return sb.toString();
default:
if (c < ' ') {
throw syntaxError("Unescaped control character (ascii " + ((int) c) + ") in string");
}
sb.append(c);
break;
}
}
} | [
"public",
"String",
"nextString",
"(",
")",
"{",
"nextClean",
"(",
"'",
"'",
")",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
";",
";",
")",
"{",
"char",
"c",
"=",
"next",
"(",
")",
";",
"switch",
"(",
"c",... | Return the characters up to the next close quote character.
Backslash processing is done. The formal JSON format does not
allow strings in single quotes, but an implementation is allowed to
accept them.
@return A String. | [
"Return",
"the",
"characters",
"up",
"to",
"the",
"next",
"close",
"quote",
"character",
".",
"Backslash",
"processing",
"is",
"done",
".",
"The",
"formal",
"JSON",
"format",
"does",
"not",
"allow",
"strings",
"in",
"single",
"quotes",
"but",
"an",
"implemen... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-api/src/main/java/com/bazaarvoice/emodb/sor/delta/deser/JsonTokener.java#L170-L215 | train |
bazaarvoice/emodb | sor-api/src/main/java/com/bazaarvoice/emodb/sor/delta/deser/JsonTokener.java | JsonTokener.nextValue | public Object nextValue() {
char c = lookAhead();
switch (c) {
case '"':
return nextString();
case '{':
return nextObject();
case '[':
return nextArray();
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
String s = nextToken();
return tokenToValue(s);
} | java | public Object nextValue() {
char c = lookAhead();
switch (c) {
case '"':
return nextString();
case '{':
return nextObject();
case '[':
return nextArray();
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
String s = nextToken();
return tokenToValue(s);
} | [
"public",
"Object",
"nextValue",
"(",
")",
"{",
"char",
"c",
"=",
"lookAhead",
"(",
")",
";",
"switch",
"(",
"c",
")",
"{",
"case",
"'",
"'",
":",
"return",
"nextString",
"(",
")",
";",
"case",
"'",
"'",
":",
"return",
"nextObject",
"(",
")",
";"... | Get the next value. The value can be a Boolean, Double, Integer,
List, Map, Long, or String, or null.
@return An object. | [
"Get",
"the",
"next",
"value",
".",
"The",
"value",
"can",
"be",
"a",
"Boolean",
"Double",
"Integer",
"List",
"Map",
"Long",
"or",
"String",
"or",
"null",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-api/src/main/java/com/bazaarvoice/emodb/sor/delta/deser/JsonTokener.java#L224-L244 | train |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/core/RowVersionUtils.java | RowVersionUtils.getVersionRetroactively | public static long getVersionRetroactively(PendingCompaction pendingCompaction) {
Compaction compaction = pendingCompaction.getCompaction();
// Calculate the version and create a dummy compaction record for the resolver
return compaction.getCount() - (long)pendingCompaction.getDeltasToArchive().size();
} | java | public static long getVersionRetroactively(PendingCompaction pendingCompaction) {
Compaction compaction = pendingCompaction.getCompaction();
// Calculate the version and create a dummy compaction record for the resolver
return compaction.getCount() - (long)pendingCompaction.getDeltasToArchive().size();
} | [
"public",
"static",
"long",
"getVersionRetroactively",
"(",
"PendingCompaction",
"pendingCompaction",
")",
"{",
"Compaction",
"compaction",
"=",
"pendingCompaction",
".",
"getCompaction",
"(",
")",
";",
"// Calculate the version and create a dummy compaction record for the resolv... | Find the version of the first delta of a pending compaction retroactively | [
"Find",
"the",
"version",
"of",
"the",
"first",
"delta",
"of",
"a",
"pending",
"compaction",
"retroactively"
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/core/RowVersionUtils.java#L10-L14 | train |
bazaarvoice/emodb | sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStreaming.java | DataStoreStreaming.listTables | public static Iterable<Table> listTables(DataStore dataStore) {
return listTables(dataStore, null, Long.MAX_VALUE);
} | java | public static Iterable<Table> listTables(DataStore dataStore) {
return listTables(dataStore, null, Long.MAX_VALUE);
} | [
"public",
"static",
"Iterable",
"<",
"Table",
">",
"listTables",
"(",
"DataStore",
"dataStore",
")",
"{",
"return",
"listTables",
"(",
"dataStore",
",",
"null",
",",
"Long",
".",
"MAX_VALUE",
")",
";",
"}"
] | Retrieves metadata about all DataStore tables. | [
"Retrieves",
"metadata",
"about",
"all",
"DataStore",
"tables",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStreaming.java#L33-L35 | train |
bazaarvoice/emodb | sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStreaming.java | DataStoreStreaming.scan | public static Iterable<Map<String, Object>> scan(DataStore dataStore,
String table,
boolean includeDeletes,
ReadConsistency consistency) {
return scan(dataStore, table, null, Long.MAX_VALUE, includeDeletes, consistency);
} | java | public static Iterable<Map<String, Object>> scan(DataStore dataStore,
String table,
boolean includeDeletes,
ReadConsistency consistency) {
return scan(dataStore, table, null, Long.MAX_VALUE, includeDeletes, consistency);
} | [
"public",
"static",
"Iterable",
"<",
"Map",
"<",
"String",
",",
"Object",
">",
">",
"scan",
"(",
"DataStore",
"dataStore",
",",
"String",
"table",
",",
"boolean",
"includeDeletes",
",",
"ReadConsistency",
"consistency",
")",
"{",
"return",
"scan",
"(",
"data... | Retrieves all records from the specified table. | [
"Retrieves",
"all",
"records",
"from",
"the",
"specified",
"table",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStreaming.java#L40-L45 | train |
bazaarvoice/emodb | sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStreaming.java | DataStoreStreaming.updateAll | public static void updateAll(DataStore dataStore, Iterable<Update> updates) {
updateAll(dataStore, updates.iterator(), ImmutableSet.<String>of());
} | java | public static void updateAll(DataStore dataStore, Iterable<Update> updates) {
updateAll(dataStore, updates.iterator(), ImmutableSet.<String>of());
} | [
"public",
"static",
"void",
"updateAll",
"(",
"DataStore",
"dataStore",
",",
"Iterable",
"<",
"Update",
">",
"updates",
")",
"{",
"updateAll",
"(",
"dataStore",
",",
"updates",
".",
"iterator",
"(",
")",
",",
"ImmutableSet",
".",
"<",
"String",
">",
"of",
... | Creates, updates or deletes zero or more pieces of content in the data store. | [
"Creates",
"updates",
"or",
"deletes",
"zero",
"or",
"more",
"pieces",
"of",
"content",
"in",
"the",
"data",
"store",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStreaming.java#L135-L137 | train |
bazaarvoice/emodb | sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStreaming.java | DataStoreStreaming.updateAll | public static void updateAll(DataStore dataStore, Iterable<Update> updates, Set<String> tags) {
updateAll(dataStore, updates.iterator(), tags);
} | java | public static void updateAll(DataStore dataStore, Iterable<Update> updates, Set<String> tags) {
updateAll(dataStore, updates.iterator(), tags);
} | [
"public",
"static",
"void",
"updateAll",
"(",
"DataStore",
"dataStore",
",",
"Iterable",
"<",
"Update",
">",
"updates",
",",
"Set",
"<",
"String",
">",
"tags",
")",
"{",
"updateAll",
"(",
"dataStore",
",",
"updates",
".",
"iterator",
"(",
")",
",",
"tags... | Creates, updates or deletes zero or more pieces of content in the data store.
You can attach a set of databus event tags for these updates | [
"Creates",
"updates",
"or",
"deletes",
"zero",
"or",
"more",
"pieces",
"of",
"content",
"in",
"the",
"data",
"store",
".",
"You",
"can",
"attach",
"a",
"set",
"of",
"databus",
"event",
"tags",
"for",
"these",
"updates"
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-client-common/src/main/java/com/bazaarvoice/emodb/sor/client/DataStoreStreaming.java#L143-L145 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java | RoleResource1.getAllRoles | @GET
public Iterator<EmoRole> getAllRoles(final @Authenticated Subject subject) {
return _uac.getAllRoles(subject);
} | java | @GET
public Iterator<EmoRole> getAllRoles(final @Authenticated Subject subject) {
return _uac.getAllRoles(subject);
} | [
"@",
"GET",
"public",
"Iterator",
"<",
"EmoRole",
">",
"getAllRoles",
"(",
"final",
"@",
"Authenticated",
"Subject",
"subject",
")",
"{",
"return",
"_uac",
".",
"getAllRoles",
"(",
"subject",
")",
";",
"}"
] | Returns all roles for which the caller has read access. Since the number of roles is typically low
this call does not support "from" or "limit" parameters similar to the system or record. | [
"Returns",
"all",
"roles",
"for",
"which",
"the",
"caller",
"has",
"read",
"access",
".",
"Since",
"the",
"number",
"of",
"roles",
"is",
"typically",
"low",
"this",
"call",
"does",
"not",
"support",
"from",
"or",
"limit",
"parameters",
"similar",
"to",
"th... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java#L52-L55 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java | RoleResource1.getAllRolesInGroup | @GET
@Path("{group}")
public Iterator<EmoRole> getAllRolesInGroup(@PathParam("group") String group,
final @Authenticated Subject subject) {
return _uac.getAllRolesInGroup(subject, group);
} | java | @GET
@Path("{group}")
public Iterator<EmoRole> getAllRolesInGroup(@PathParam("group") String group,
final @Authenticated Subject subject) {
return _uac.getAllRolesInGroup(subject, group);
} | [
"@",
"GET",
"@",
"Path",
"(",
"\"{group}\"",
")",
"public",
"Iterator",
"<",
"EmoRole",
">",
"getAllRolesInGroup",
"(",
"@",
"PathParam",
"(",
"\"group\"",
")",
"String",
"group",
",",
"final",
"@",
"Authenticated",
"Subject",
"subject",
")",
"{",
"return",
... | Returns all roles in the specified group for which the caller has read access. Since the number of roles is
typically low this call does not support "from" or "limit" parameters similar to the system or record. | [
"Returns",
"all",
"roles",
"in",
"the",
"specified",
"group",
"for",
"which",
"the",
"caller",
"has",
"read",
"access",
".",
"Since",
"the",
"number",
"of",
"roles",
"is",
"typically",
"low",
"this",
"call",
"does",
"not",
"support",
"from",
"or",
"limit",... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java#L61-L66 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java | RoleResource1.getRole | @GET
@Path("{group}/{id}")
public EmoRole getRole(@PathParam("group") String group, @PathParam("id") String id,
final @Authenticated Subject subject) {
return _uac.getRole(subject, new EmoRoleKey(group, id));
} | java | @GET
@Path("{group}/{id}")
public EmoRole getRole(@PathParam("group") String group, @PathParam("id") String id,
final @Authenticated Subject subject) {
return _uac.getRole(subject, new EmoRoleKey(group, id));
} | [
"@",
"GET",
"@",
"Path",
"(",
"\"{group}/{id}\"",
")",
"public",
"EmoRole",
"getRole",
"(",
"@",
"PathParam",
"(",
"\"group\"",
")",
"String",
"group",
",",
"@",
"PathParam",
"(",
"\"id\"",
")",
"String",
"id",
",",
"final",
"@",
"Authenticated",
"Subject"... | RESTful endpoint for viewing a role. | [
"RESTful",
"endpoint",
"for",
"viewing",
"a",
"role",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java#L71-L76 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java | RoleResource1.createRole | @POST
@Path("{group}/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response createRole(@PathParam("group") String group, @PathParam("id") String id, EmoRole role,
final @Authenticated Subject subject) {
checkArgument(role.getId().equals(new EmoRoleKey(group, id)),
"Body contains conflicting role identifier");
return createRoleFromUpdateRequest(group, id,
new CreateEmoRoleRequest()
.setName(role.getName())
.setDescription(role.getDescription())
.setPermissions(role.getPermissions()),
subject);
} | java | @POST
@Path("{group}/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public Response createRole(@PathParam("group") String group, @PathParam("id") String id, EmoRole role,
final @Authenticated Subject subject) {
checkArgument(role.getId().equals(new EmoRoleKey(group, id)),
"Body contains conflicting role identifier");
return createRoleFromUpdateRequest(group, id,
new CreateEmoRoleRequest()
.setName(role.getName())
.setDescription(role.getDescription())
.setPermissions(role.getPermissions()),
subject);
} | [
"@",
"POST",
"@",
"Path",
"(",
"\"{group}/{id}\"",
")",
"@",
"Consumes",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"public",
"Response",
"createRole",
"(",
"@",
"PathParam",
"(",
"\"group\"",
")",
"String",
"group",
",",
"@",
"PathParam",
"(",
"\"id\""... | RESTful endpoint for creating a role. | [
"RESTful",
"endpoint",
"for",
"creating",
"a",
"role",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java#L81-L94 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java | RoleResource1.updateRole | @PUT
@Path("{group}/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public SuccessResponse updateRole(@PathParam("group") String group, @PathParam("id") String id,
EmoRole role, final @Authenticated Subject subject) {
checkArgument(role.getId().equals(new EmoRoleKey(group, id)),
"Body contains conflicting role identifier");
return updateRoleFromUpdateRequest(group, id,
new UpdateEmoRoleRequest()
.setName(role.getName())
.setDescription(role.getDescription())
.setGrantedPermissions(role.getPermissions())
.setRevokeOtherPermissions(true),
subject);
} | java | @PUT
@Path("{group}/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public SuccessResponse updateRole(@PathParam("group") String group, @PathParam("id") String id,
EmoRole role, final @Authenticated Subject subject) {
checkArgument(role.getId().equals(new EmoRoleKey(group, id)),
"Body contains conflicting role identifier");
return updateRoleFromUpdateRequest(group, id,
new UpdateEmoRoleRequest()
.setName(role.getName())
.setDescription(role.getDescription())
.setGrantedPermissions(role.getPermissions())
.setRevokeOtherPermissions(true),
subject);
} | [
"@",
"PUT",
"@",
"Path",
"(",
"\"{group}/{id}\"",
")",
"@",
"Consumes",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"public",
"SuccessResponse",
"updateRole",
"(",
"@",
"PathParam",
"(",
"\"group\"",
")",
"String",
"group",
",",
"@",
"PathParam",
"(",
"\... | RESTful endpoint for updating a role. Note that all attributes of the role will be updated to match the
provided object. | [
"RESTful",
"endpoint",
"for",
"updating",
"a",
"role",
".",
"Note",
"that",
"all",
"attributes",
"of",
"the",
"role",
"will",
"be",
"updated",
"to",
"match",
"the",
"provided",
"object",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java#L116-L131 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java | RoleResource1.deleteRole | @DELETE
@Path("{group}/{id}")
public SuccessResponse deleteRole(@PathParam("group") String group, @PathParam("id") String id,
final @Authenticated Subject subject) {
_uac.deleteRole(subject, new EmoRoleKey(group, id));
return SuccessResponse.instance();
} | java | @DELETE
@Path("{group}/{id}")
public SuccessResponse deleteRole(@PathParam("group") String group, @PathParam("id") String id,
final @Authenticated Subject subject) {
_uac.deleteRole(subject, new EmoRoleKey(group, id));
return SuccessResponse.instance();
} | [
"@",
"DELETE",
"@",
"Path",
"(",
"\"{group}/{id}\"",
")",
"public",
"SuccessResponse",
"deleteRole",
"(",
"@",
"PathParam",
"(",
"\"group\"",
")",
"String",
"group",
",",
"@",
"PathParam",
"(",
"\"id\"",
")",
"String",
"id",
",",
"final",
"@",
"Authenticated... | RESTful endpoint for deleting a role. | [
"RESTful",
"endpoint",
"for",
"deleting",
"a",
"role",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java#L149-L155 | train |
bazaarvoice/emodb | event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/AstyanaxEventReaderDAO.java | AstyanaxEventReaderDAO.readManifestForChannel | private Iterator<Column<ByteBuffer>> readManifestForChannel(final String channel, final boolean weak) {
final ByteBuffer oldestSlab = weak ? _oldestSlab.getIfPresent(channel) : null;
final ConsistencyLevel consistency;
RangeBuilder range = new RangeBuilder().setLimit(50);
if (oldestSlab != null) {
range.setStart(oldestSlab);
consistency = ConsistencyLevel.CL_LOCAL_ONE;
} else {
consistency = ConsistencyLevel.CL_LOCAL_QUORUM;
}
final Iterator<Column<ByteBuffer>> manifestColumns = executePaginated(
_keyspace.prepareQuery(ColumnFamilies.MANIFEST, consistency)
.getKey(channel)
.withColumnRange(range.build())
.autoPaginate(true));
if (oldestSlab != null) {
// Query was executed weakly using the cached oldest slab, so don't update the cache with an unreliable oldest value
return manifestColumns;
} else {
PeekingIterator<Column<ByteBuffer>> peekingManifestColumns = Iterators.peekingIterator(manifestColumns);
if (peekingManifestColumns.hasNext()) {
// Cache the first slab returned from querying the full manifest column family since it is the oldest.
cacheOldestSlabForChannel(channel, TimeUUIDSerializer.get().fromByteBuffer(peekingManifestColumns.peek().getName()));
return peekingManifestColumns;
} else {
// Channel was completely empty. Cache a TimeUUID for the current time. This will cause future calls
// to read at most 1 minute of tombstones until the cache expires 10 seconds later.
cacheOldestSlabForChannel(channel, TimeUUIDs.newUUID());
return Iterators.emptyIterator();
}
}
} | java | private Iterator<Column<ByteBuffer>> readManifestForChannel(final String channel, final boolean weak) {
final ByteBuffer oldestSlab = weak ? _oldestSlab.getIfPresent(channel) : null;
final ConsistencyLevel consistency;
RangeBuilder range = new RangeBuilder().setLimit(50);
if (oldestSlab != null) {
range.setStart(oldestSlab);
consistency = ConsistencyLevel.CL_LOCAL_ONE;
} else {
consistency = ConsistencyLevel.CL_LOCAL_QUORUM;
}
final Iterator<Column<ByteBuffer>> manifestColumns = executePaginated(
_keyspace.prepareQuery(ColumnFamilies.MANIFEST, consistency)
.getKey(channel)
.withColumnRange(range.build())
.autoPaginate(true));
if (oldestSlab != null) {
// Query was executed weakly using the cached oldest slab, so don't update the cache with an unreliable oldest value
return manifestColumns;
} else {
PeekingIterator<Column<ByteBuffer>> peekingManifestColumns = Iterators.peekingIterator(manifestColumns);
if (peekingManifestColumns.hasNext()) {
// Cache the first slab returned from querying the full manifest column family since it is the oldest.
cacheOldestSlabForChannel(channel, TimeUUIDSerializer.get().fromByteBuffer(peekingManifestColumns.peek().getName()));
return peekingManifestColumns;
} else {
// Channel was completely empty. Cache a TimeUUID for the current time. This will cause future calls
// to read at most 1 minute of tombstones until the cache expires 10 seconds later.
cacheOldestSlabForChannel(channel, TimeUUIDs.newUUID());
return Iterators.emptyIterator();
}
}
} | [
"private",
"Iterator",
"<",
"Column",
"<",
"ByteBuffer",
">",
">",
"readManifestForChannel",
"(",
"final",
"String",
"channel",
",",
"final",
"boolean",
"weak",
")",
"{",
"final",
"ByteBuffer",
"oldestSlab",
"=",
"weak",
"?",
"_oldestSlab",
".",
"getIfPresent",
... | Reads the ordered manifest for a channel. The read can either be weak or strong. A weak read will use CL1
and may use the cached oldest slab from a previous strong call to improve performance. A strong read will use
CL local_quorum and will always read the entire manifest row. This makes a weak read significantly faster than a
strong read but also means the call is not guaranteed to return the entire manifest. Because of this at least
every 10 seconds a weak read for a channel is automatically promoted to a strong read.
The vast majority of calls to this method are performed during a "peek" or "poll" operation. Since these are
typically called repeatedly a weak call provides improved performance while guaranteeing that at least every
10 seconds the manifest is strongly read so no slabs are missed over time. Calls which must guarantee
the full manifest should explicitly request strong consistency. | [
"Reads",
"the",
"ordered",
"manifest",
"for",
"a",
"channel",
".",
"The",
"read",
"can",
"either",
"be",
"weak",
"or",
"strong",
".",
"A",
"weak",
"read",
"will",
"use",
"CL1",
"and",
"may",
"use",
"the",
"cached",
"oldest",
"slab",
"from",
"a",
"previ... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/AstyanaxEventReaderDAO.java#L339-L373 | train |
bazaarvoice/emodb | event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/AstyanaxEventReaderDAO.java | AstyanaxEventReaderDAO.readSlab | private boolean readSlab(String channel, ByteBuffer slabId, SlabCursor cursor, boolean open, EventSink sink) {
int start = cursor.get();
if (start == SlabCursor.END) {
return true;
}
boolean recent = isRecent(slabId);
// Event add and delete write with local quorum, so read with local quorum to get a consistent view of things.
// Using a lower consistency level could result in (a) duplicate events because we miss deletes and (b)
// incorrectly closing or deleting slabs when slabs look empty if we miss adds.
ColumnList<Integer> eventColumns = execute(
_keyspace.prepareQuery(ColumnFamilies.SLAB, ConsistencyLevel.CL_LOCAL_QUORUM)
.getKey(slabId)
.withColumnRange(start, Constants.OPEN_SLAB_MARKER, false, Integer.MAX_VALUE));
boolean searching = true;
boolean empty = (start == 0); // If we skipped events in the query we must assume the slab isn't empty.
boolean more = false;
int next = start;
for (Column<Integer> eventColumn : eventColumns) {
int eventIdx = eventColumn.getName();
// Open slabs have a dummy entry at maxint that indicates that this slab is still open.
if (eventIdx == Constants.OPEN_SLAB_MARKER) {
break;
}
// Found at least one data item.
empty = false;
if (!searching) {
more = true; // There are more events to be found next time we poll this slab.
break;
}
// Pass the data on to the EventSink. It will tell us whether or not to keep searching.
EventId eventId = AstyanaxEventId.create(channel, slabId, eventIdx);
ByteBuffer eventData = eventColumn.getByteBufferValue();
searching = sink.accept(eventId, eventData);
next = eventIdx;
}
// Next time we query this slab start the search with last event received by the sink, repeating it.
cursor.set(next);
// Stale open slab? Rare, should only happen when a writer crashes without cleaning up and closing its open
// slabs. Normally writers re-write the OPEN_SLAB_MARKER column on every write as a sort of heartbeat. Readers
// detect "stale" slabs when the open slab markers expire, and they close those slabs on behalf of the crashed writers.
boolean hasOpenSlabMarker = !eventColumns.isEmpty() &&
eventColumns.getColumnByIndex(eventColumns.size() - 1).getName() == Constants.OPEN_SLAB_MARKER;
boolean stale = open && !recent && !hasOpenSlabMarker;
if (stale) {
_staleSlabMeter.mark();
}
// If the slab is currently closed or should be closed then it will never receive more data so check to see if
// we can (a) delete it (it's empty) or at least (b) close it.
if (empty && (!open || stale)) {
deleteEmptySlabAsync(channel, slabId);
open = false;
} else if (stale) {
closeStaleSlabAsync(channel, slabId);
open = false;
}
// If we ran through all the data in a closed slab, skip this slab next time. This is especially common with
// badly-behaving Databus listeners that poll repeatedly but don't ack.
if (!more && !open) {
cursor.set(SlabCursor.END);
}
return searching;
} | java | private boolean readSlab(String channel, ByteBuffer slabId, SlabCursor cursor, boolean open, EventSink sink) {
int start = cursor.get();
if (start == SlabCursor.END) {
return true;
}
boolean recent = isRecent(slabId);
// Event add and delete write with local quorum, so read with local quorum to get a consistent view of things.
// Using a lower consistency level could result in (a) duplicate events because we miss deletes and (b)
// incorrectly closing or deleting slabs when slabs look empty if we miss adds.
ColumnList<Integer> eventColumns = execute(
_keyspace.prepareQuery(ColumnFamilies.SLAB, ConsistencyLevel.CL_LOCAL_QUORUM)
.getKey(slabId)
.withColumnRange(start, Constants.OPEN_SLAB_MARKER, false, Integer.MAX_VALUE));
boolean searching = true;
boolean empty = (start == 0); // If we skipped events in the query we must assume the slab isn't empty.
boolean more = false;
int next = start;
for (Column<Integer> eventColumn : eventColumns) {
int eventIdx = eventColumn.getName();
// Open slabs have a dummy entry at maxint that indicates that this slab is still open.
if (eventIdx == Constants.OPEN_SLAB_MARKER) {
break;
}
// Found at least one data item.
empty = false;
if (!searching) {
more = true; // There are more events to be found next time we poll this slab.
break;
}
// Pass the data on to the EventSink. It will tell us whether or not to keep searching.
EventId eventId = AstyanaxEventId.create(channel, slabId, eventIdx);
ByteBuffer eventData = eventColumn.getByteBufferValue();
searching = sink.accept(eventId, eventData);
next = eventIdx;
}
// Next time we query this slab start the search with last event received by the sink, repeating it.
cursor.set(next);
// Stale open slab? Rare, should only happen when a writer crashes without cleaning up and closing its open
// slabs. Normally writers re-write the OPEN_SLAB_MARKER column on every write as a sort of heartbeat. Readers
// detect "stale" slabs when the open slab markers expire, and they close those slabs on behalf of the crashed writers.
boolean hasOpenSlabMarker = !eventColumns.isEmpty() &&
eventColumns.getColumnByIndex(eventColumns.size() - 1).getName() == Constants.OPEN_SLAB_MARKER;
boolean stale = open && !recent && !hasOpenSlabMarker;
if (stale) {
_staleSlabMeter.mark();
}
// If the slab is currently closed or should be closed then it will never receive more data so check to see if
// we can (a) delete it (it's empty) or at least (b) close it.
if (empty && (!open || stale)) {
deleteEmptySlabAsync(channel, slabId);
open = false;
} else if (stale) {
closeStaleSlabAsync(channel, slabId);
open = false;
}
// If we ran through all the data in a closed slab, skip this slab next time. This is especially common with
// badly-behaving Databus listeners that poll repeatedly but don't ack.
if (!more && !open) {
cursor.set(SlabCursor.END);
}
return searching;
} | [
"private",
"boolean",
"readSlab",
"(",
"String",
"channel",
",",
"ByteBuffer",
"slabId",
",",
"SlabCursor",
"cursor",
",",
"boolean",
"open",
",",
"EventSink",
"sink",
")",
"{",
"int",
"start",
"=",
"cursor",
".",
"get",
"(",
")",
";",
"if",
"(",
"start"... | Returns true to keep searching for more events, false to stop searching for events. | [
"Returns",
"true",
"to",
"keep",
"searching",
"for",
"more",
"events",
"false",
"to",
"stop",
"searching",
"for",
"events",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/AstyanaxEventReaderDAO.java#L389-L462 | train |
bazaarvoice/emodb | sor/src/main/java/com/bazaarvoice/emodb/sor/db/ScanRangeSplits.java | ScanRangeSplits.combineGroups | public ScanRangeSplits combineGroups() {
return new ScanRangeSplits(ImmutableList.of(new SplitGroup(
FluentIterable.from(_splitGroups)
.transformAndConcat(new Function<SplitGroup, Iterable<TokenRange>>() {
@Override
public Iterable<TokenRange> apply(SplitGroup splitGroup) {
return splitGroup.getTokenRanges();
}
})
.toList())));
} | java | public ScanRangeSplits combineGroups() {
return new ScanRangeSplits(ImmutableList.of(new SplitGroup(
FluentIterable.from(_splitGroups)
.transformAndConcat(new Function<SplitGroup, Iterable<TokenRange>>() {
@Override
public Iterable<TokenRange> apply(SplitGroup splitGroup) {
return splitGroup.getTokenRanges();
}
})
.toList())));
} | [
"public",
"ScanRangeSplits",
"combineGroups",
"(",
")",
"{",
"return",
"new",
"ScanRangeSplits",
"(",
"ImmutableList",
".",
"of",
"(",
"new",
"SplitGroup",
"(",
"FluentIterable",
".",
"from",
"(",
"_splitGroups",
")",
".",
"transformAndConcat",
"(",
"new",
"Func... | Returns a new ScanRangeSplits where all of the token ranges from all groups are combined into a single group.
This is useful when the caller is going to perform an operation on all token ranges and is not concerned about
creating hot spots. | [
"Returns",
"a",
"new",
"ScanRangeSplits",
"where",
"all",
"of",
"the",
"token",
"ranges",
"from",
"all",
"groups",
"are",
"combined",
"into",
"a",
"single",
"group",
".",
"This",
"is",
"useful",
"when",
"the",
"caller",
"is",
"going",
"to",
"perform",
"an"... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/ScanRangeSplits.java#L45-L55 | train |
bazaarvoice/emodb | common/uuid/src/main/java/com/bazaarvoice/emodb/common/uuid/UUIDs.java | UUIDs.asByteArray | public static byte[] asByteArray(UUID uuid) {
long msb = uuid.getMostSignificantBits();
long lsb = uuid.getLeastSignificantBits();
byte[] buf = new byte[16];
for (int i = 0; i < 8; i++) {
buf[i] = (byte) (msb >>> 8 * (7 - i));
buf[i + 8] = (byte) (lsb >>> 8 * (7 - i));
}
return buf;
} | java | public static byte[] asByteArray(UUID uuid) {
long msb = uuid.getMostSignificantBits();
long lsb = uuid.getLeastSignificantBits();
byte[] buf = new byte[16];
for (int i = 0; i < 8; i++) {
buf[i] = (byte) (msb >>> 8 * (7 - i));
buf[i + 8] = (byte) (lsb >>> 8 * (7 - i));
}
return buf;
} | [
"public",
"static",
"byte",
"[",
"]",
"asByteArray",
"(",
"UUID",
"uuid",
")",
"{",
"long",
"msb",
"=",
"uuid",
".",
"getMostSignificantBits",
"(",
")",
";",
"long",
"lsb",
"=",
"uuid",
".",
"getLeastSignificantBits",
"(",
")",
";",
"byte",
"[",
"]",
"... | Returns the byte-array equivalent of the specified UUID in big-endian order. | [
"Returns",
"the",
"byte",
"-",
"array",
"equivalent",
"of",
"the",
"specified",
"UUID",
"in",
"big",
"-",
"endian",
"order",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/uuid/src/main/java/com/bazaarvoice/emodb/common/uuid/UUIDs.java#L13-L22 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/scanner/writer/TemporaryFileScanWriter.java | TemporaryFileScanWriter.closeShardFiles | private void closeShardFiles(ShardFiles shardFiles) {
shardFiles.deleteAllShardFiles();
_lock.lock();
try {
_openShardFiles.remove(shardFiles.getKey());
_shardFilesClosedOrExceptionCaught.signalAll();
} finally {
_lock.unlock();
}
} | java | private void closeShardFiles(ShardFiles shardFiles) {
shardFiles.deleteAllShardFiles();
_lock.lock();
try {
_openShardFiles.remove(shardFiles.getKey());
_shardFilesClosedOrExceptionCaught.signalAll();
} finally {
_lock.unlock();
}
} | [
"private",
"void",
"closeShardFiles",
"(",
"ShardFiles",
"shardFiles",
")",
"{",
"shardFiles",
".",
"deleteAllShardFiles",
"(",
")",
";",
"_lock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"_openShardFiles",
".",
"remove",
"(",
"shardFiles",
".",
"getKey",
"("... | Cleans up any files associated with the ShardFiles instance and removes it from then open set of ShardFiles. | [
"Cleans",
"up",
"any",
"files",
"associated",
"with",
"the",
"ShardFiles",
"instance",
"and",
"removes",
"it",
"from",
"then",
"open",
"set",
"of",
"ShardFiles",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/writer/TemporaryFileScanWriter.java#L183-L192 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/scanner/writer/TemporaryFileScanWriter.java | TemporaryFileScanWriter.transferComplete | private void transferComplete(ShardFiles shardFiles) {
_log.debug("Transfer complete: id={}, file={}", _taskId, shardFiles.getFirstFile());
closeShardFiles(shardFiles);
_openTransfers.dec();
} | java | private void transferComplete(ShardFiles shardFiles) {
_log.debug("Transfer complete: id={}, file={}", _taskId, shardFiles.getFirstFile());
closeShardFiles(shardFiles);
_openTransfers.dec();
} | [
"private",
"void",
"transferComplete",
"(",
"ShardFiles",
"shardFiles",
")",
"{",
"_log",
".",
"debug",
"(",
"\"Transfer complete: id={}, file={}\"",
",",
"_taskId",
",",
"shardFiles",
".",
"getFirstFile",
"(",
")",
")",
";",
"closeShardFiles",
"(",
"shardFiles",
... | Called when a shard file has been transferred, successfully or otherwise. This also closes the ShardFiles. | [
"Called",
"when",
"a",
"shard",
"file",
"has",
"been",
"transferred",
"successfully",
"or",
"otherwise",
".",
"This",
"also",
"closes",
"the",
"ShardFiles",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/writer/TemporaryFileScanWriter.java#L195-L199 | train |
bazaarvoice/emodb | sor-api/src/main/java/com/bazaarvoice/emodb/sor/api/Coordinate.java | Coordinate.asJson | public Map<String, Object> asJson() {
return ImmutableMap.<String, Object>of(
Intrinsic.TABLE, _table,
Intrinsic.ID, _id);
} | java | public Map<String, Object> asJson() {
return ImmutableMap.<String, Object>of(
Intrinsic.TABLE, _table,
Intrinsic.ID, _id);
} | [
"public",
"Map",
"<",
"String",
",",
"Object",
">",
"asJson",
"(",
")",
"{",
"return",
"ImmutableMap",
".",
"<",
"String",
",",
"Object",
">",
"of",
"(",
"Intrinsic",
".",
"TABLE",
",",
"_table",
",",
"Intrinsic",
".",
"ID",
",",
"_id",
")",
";",
"... | Returns a Json map with two entries, one for "~table" and one for "~id", similar to all System of Record objects. | [
"Returns",
"a",
"Json",
"map",
"with",
"two",
"entries",
"one",
"for",
"~table",
"and",
"one",
"for",
"~id",
"similar",
"to",
"all",
"System",
"of",
"Record",
"objects",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-api/src/main/java/com/bazaarvoice/emodb/sor/api/Coordinate.java#L58-L62 | train |
bazaarvoice/emodb | databus/src/main/java/com/bazaarvoice/emodb/databus/core/EventKeyFormat.java | EventKeyFormat.encode | static String encode(List<String> eventIds) {
checkArgument(!eventIds.isEmpty(), "Empty event ID list.");
if (eventIds.size() == 1) {
return checkValid(eventIds.get(0));
}
// Concatenate the event IDs using a simple scheme that efficiently encodes events that are the same length and
// share a common prefix.
StringBuilder buf = new StringBuilder();
String prevId = null;
for (String eventId : eventIds) {
checkValid(eventId);
int commonPrefixLength;
if (prevId == null) {
// First event ID
buf.append(eventId);
} else if (prevId.length() == eventId.length() &&
(commonPrefixLength = getCommonPrefixLength(prevId, eventId)) > 0) {
// Event ID is same length and shares a common prefix with the previous. Just add the part that's different.
buf.append(DELIM_SHARED_PREFIX).append(eventId.substring(commonPrefixLength));
} else {
buf.append(DELIM_REGULAR).append(eventId);
}
prevId = eventId;
}
return buf.toString();
} | java | static String encode(List<String> eventIds) {
checkArgument(!eventIds.isEmpty(), "Empty event ID list.");
if (eventIds.size() == 1) {
return checkValid(eventIds.get(0));
}
// Concatenate the event IDs using a simple scheme that efficiently encodes events that are the same length and
// share a common prefix.
StringBuilder buf = new StringBuilder();
String prevId = null;
for (String eventId : eventIds) {
checkValid(eventId);
int commonPrefixLength;
if (prevId == null) {
// First event ID
buf.append(eventId);
} else if (prevId.length() == eventId.length() &&
(commonPrefixLength = getCommonPrefixLength(prevId, eventId)) > 0) {
// Event ID is same length and shares a common prefix with the previous. Just add the part that's different.
buf.append(DELIM_SHARED_PREFIX).append(eventId.substring(commonPrefixLength));
} else {
buf.append(DELIM_REGULAR).append(eventId);
}
prevId = eventId;
}
return buf.toString();
} | [
"static",
"String",
"encode",
"(",
"List",
"<",
"String",
">",
"eventIds",
")",
"{",
"checkArgument",
"(",
"!",
"eventIds",
".",
"isEmpty",
"(",
")",
",",
"\"Empty event ID list.\"",
")",
";",
"if",
"(",
"eventIds",
".",
"size",
"(",
")",
"==",
"1",
")... | Combine multiple EventStore event IDs into a single Databus event key. To get the most compact encoded string,
sort the event ID list before encoding it. | [
"Combine",
"multiple",
"EventStore",
"event",
"IDs",
"into",
"a",
"single",
"Databus",
"event",
"key",
".",
"To",
"get",
"the",
"most",
"compact",
"encoded",
"string",
"sort",
"the",
"event",
"ID",
"list",
"before",
"encoding",
"it",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus/src/main/java/com/bazaarvoice/emodb/databus/core/EventKeyFormat.java#L37-L62 | train |
bazaarvoice/emodb | databus/src/main/java/com/bazaarvoice/emodb/databus/core/EventKeyFormat.java | EventKeyFormat.decodeAll | static List<String> decodeAll(Collection<String> eventKeys) {
List<String> eventIds = Lists.newArrayList();
for (String eventKey : eventKeys) {
decodeTo(eventKey, eventIds);
}
return eventIds;
} | java | static List<String> decodeAll(Collection<String> eventKeys) {
List<String> eventIds = Lists.newArrayList();
for (String eventKey : eventKeys) {
decodeTo(eventKey, eventIds);
}
return eventIds;
} | [
"static",
"List",
"<",
"String",
">",
"decodeAll",
"(",
"Collection",
"<",
"String",
">",
"eventKeys",
")",
"{",
"List",
"<",
"String",
">",
"eventIds",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"for",
"(",
"String",
"eventKey",
":",
"eventKeys",... | Split Databus event keys into EventStore event IDs. | [
"Split",
"Databus",
"event",
"keys",
"into",
"EventStore",
"event",
"IDs",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus/src/main/java/com/bazaarvoice/emodb/databus/core/EventKeyFormat.java#L65-L71 | train |
bazaarvoice/emodb | databus/src/main/java/com/bazaarvoice/emodb/databus/core/EventKeyFormat.java | EventKeyFormat.decodeTo | static void decodeTo(String eventKey, Collection<String> eventIds) {
int startIdx = 0;
String prevId = null;
for (int i = 0; i < eventKey.length(); i++) {
char ch = eventKey.charAt(i);
if (ch == DELIM_REGULAR || ch == DELIM_SHARED_PREFIX) {
String eventId = checkValid(combine(prevId, eventKey.substring(startIdx, i)));
eventIds.add(eventId);
prevId = (ch == DELIM_REGULAR) ? null : eventId;
startIdx = i + 1;
}
}
// Add the final event ID
eventIds.add(checkValid(combine(prevId, eventKey.substring(startIdx, eventKey.length()))));
} | java | static void decodeTo(String eventKey, Collection<String> eventIds) {
int startIdx = 0;
String prevId = null;
for (int i = 0; i < eventKey.length(); i++) {
char ch = eventKey.charAt(i);
if (ch == DELIM_REGULAR || ch == DELIM_SHARED_PREFIX) {
String eventId = checkValid(combine(prevId, eventKey.substring(startIdx, i)));
eventIds.add(eventId);
prevId = (ch == DELIM_REGULAR) ? null : eventId;
startIdx = i + 1;
}
}
// Add the final event ID
eventIds.add(checkValid(combine(prevId, eventKey.substring(startIdx, eventKey.length()))));
} | [
"static",
"void",
"decodeTo",
"(",
"String",
"eventKey",
",",
"Collection",
"<",
"String",
">",
"eventIds",
")",
"{",
"int",
"startIdx",
"=",
"0",
";",
"String",
"prevId",
"=",
"null",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"eventKey",... | Split a Databus event key into EventStore event IDs. | [
"Split",
"a",
"Databus",
"event",
"key",
"into",
"EventStore",
"event",
"IDs",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus/src/main/java/com/bazaarvoice/emodb/databus/core/EventKeyFormat.java#L74-L88 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/BaseRecordReader.java | BaseRecordReader.setNextKeyValue | public boolean setNextKeyValue(Text key, Row value)
throws IOException {
if (!_rows.hasNext()) {
Closeables.close(this, true);
return false;
}
try {
Map<String, Object> content = _rows.next();
key.set(Coordinate.fromJson(content).toString());
value.set(content);
_rowsRead += 1;
} catch (Exception e) {
for (Throwable cause : Throwables.getCausalChain(e)) {
Throwables.propagateIfInstanceOf(cause, IOException.class);
}
throw new IOException("Failed to read next row", e);
}
return true;
} | java | public boolean setNextKeyValue(Text key, Row value)
throws IOException {
if (!_rows.hasNext()) {
Closeables.close(this, true);
return false;
}
try {
Map<String, Object> content = _rows.next();
key.set(Coordinate.fromJson(content).toString());
value.set(content);
_rowsRead += 1;
} catch (Exception e) {
for (Throwable cause : Throwables.getCausalChain(e)) {
Throwables.propagateIfInstanceOf(cause, IOException.class);
}
throw new IOException("Failed to read next row", e);
}
return true;
} | [
"public",
"boolean",
"setNextKeyValue",
"(",
"Text",
"key",
",",
"Row",
"value",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"_rows",
".",
"hasNext",
"(",
")",
")",
"{",
"Closeables",
".",
"close",
"(",
"this",
",",
"true",
")",
";",
"return",
... | Read the next row from the split, storing the coordinate in "key" and the content in "value". If there are no
more rows then false is returned and "key" and "value" are not modified.
@return true if a row was read, false if there were no more rows | [
"Read",
"the",
"next",
"row",
"from",
"the",
"split",
"storing",
"the",
"coordinate",
"in",
"key",
"and",
"the",
"content",
"in",
"value",
".",
"If",
"there",
"are",
"no",
"more",
"rows",
"then",
"false",
"is",
"returned",
"and",
"key",
"and",
"value",
... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/BaseRecordReader.java#L52-L71 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/BaseRecordReader.java | BaseRecordReader.getProgress | public float getProgress()
throws IOException {
if (!_rows.hasNext()) {
return 1;
} else if (_rowsRead < _approximateSize) {
return (float) _rowsRead / _approximateSize;
} else {
// We've already read the expected number of rows.
return ((float) (_approximateSize - 1) + 0.5f) / _approximateSize;
}
} | java | public float getProgress()
throws IOException {
if (!_rows.hasNext()) {
return 1;
} else if (_rowsRead < _approximateSize) {
return (float) _rowsRead / _approximateSize;
} else {
// We've already read the expected number of rows.
return ((float) (_approximateSize - 1) + 0.5f) / _approximateSize;
}
} | [
"public",
"float",
"getProgress",
"(",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"_rows",
".",
"hasNext",
"(",
")",
")",
"{",
"return",
"1",
";",
"}",
"else",
"if",
"(",
"_rowsRead",
"<",
"_approximateSize",
")",
"{",
"return",
"(",
"float",
... | Returns a rough approximate of the progress on a scale from 0 to 1 | [
"Returns",
"a",
"rough",
"approximate",
"of",
"the",
"progress",
"on",
"a",
"scale",
"from",
"0",
"to",
"1"
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/BaseRecordReader.java#L76-L86 | train |
bazaarvoice/emodb | auth/auth-store/src/main/java/com/bazaarvoice/emodb/auth/role/DeferringRoleManager.java | DeferringRoleManager.getPermissionsForRole | @Override
public Set<String> getPermissionsForRole(RoleIdentifier id) {
checkNotNull(id, "id");
return _delegate.getPermissionsForRole(id);
} | java | @Override
public Set<String> getPermissionsForRole(RoleIdentifier id) {
checkNotNull(id, "id");
return _delegate.getPermissionsForRole(id);
} | [
"@",
"Override",
"public",
"Set",
"<",
"String",
">",
"getPermissionsForRole",
"(",
"RoleIdentifier",
"id",
")",
"{",
"checkNotNull",
"(",
"id",
",",
"\"id\"",
")",
";",
"return",
"_delegate",
".",
"getPermissionsForRole",
"(",
"id",
")",
";",
"}"
] | Although this implementation overrides specific roles the permissions associated with them are
still managed by the permission manager, so always defer to the delegate to read permissions. | [
"Although",
"this",
"implementation",
"overrides",
"specific",
"roles",
"the",
"permissions",
"associated",
"with",
"them",
"are",
"still",
"managed",
"by",
"the",
"permission",
"manager",
"so",
"always",
"defer",
"to",
"the",
"delegate",
"to",
"read",
"permission... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-store/src/main/java/com/bazaarvoice/emodb/auth/role/DeferringRoleManager.java#L61-L65 | train |
bazaarvoice/emodb | databus/src/main/java/com/bazaarvoice/emodb/databus/core/UpdateRefSerializer.java | UpdateRefSerializer.trim | private static ByteBuffer trim(ByteBuffer buf) {
if (buf.capacity() <= 4 * buf.remaining()) {
return buf;
} else {
ByteBuffer clone = ByteBuffer.allocate(buf.remaining());
buf.get(clone.array());
return clone;
}
} | java | private static ByteBuffer trim(ByteBuffer buf) {
if (buf.capacity() <= 4 * buf.remaining()) {
return buf;
} else {
ByteBuffer clone = ByteBuffer.allocate(buf.remaining());
buf.get(clone.array());
return clone;
}
} | [
"private",
"static",
"ByteBuffer",
"trim",
"(",
"ByteBuffer",
"buf",
")",
"{",
"if",
"(",
"buf",
".",
"capacity",
"(",
")",
"<=",
"4",
"*",
"buf",
".",
"remaining",
"(",
")",
")",
"{",
"return",
"buf",
";",
"}",
"else",
"{",
"ByteBuffer",
"clone",
... | Serialized Astyanax Composite objects use a lot of memory. Trim it down. | [
"Serialized",
"Astyanax",
"Composite",
"objects",
"use",
"a",
"lot",
"of",
"memory",
".",
"Trim",
"it",
"down",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus/src/main/java/com/bazaarvoice/emodb/databus/core/UpdateRefSerializer.java#L63-L71 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/uac/LocalSubjectUserAccessControl.java | LocalSubjectUserAccessControl.verifyPermission | private void verifyPermission(Subject subject, String permission)
throws UnauthorizedException {
if (!subject.hasPermission(permission)) {
throw new UnauthorizedException();
}
} | java | private void verifyPermission(Subject subject, String permission)
throws UnauthorizedException {
if (!subject.hasPermission(permission)) {
throw new UnauthorizedException();
}
} | [
"private",
"void",
"verifyPermission",
"(",
"Subject",
"subject",
",",
"String",
"permission",
")",
"throws",
"UnauthorizedException",
"{",
"if",
"(",
"!",
"subject",
".",
"hasPermission",
"(",
"permission",
")",
")",
"{",
"throw",
"new",
"UnauthorizedException",
... | Verifies whether the user has a specific permission. If not it throws a standard UnauthorizedException.
@throws UnauthorizedException User did not have the permission | [
"Verifies",
"whether",
"the",
"user",
"has",
"a",
"specific",
"permission",
".",
"If",
"not",
"it",
"throws",
"a",
"standard",
"UnauthorizedException",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/uac/LocalSubjectUserAccessControl.java#L583-L588 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/uac/LocalSubjectUserAccessControl.java | LocalSubjectUserAccessControl.verifyPermissionToGrantRoles | private void verifyPermissionToGrantRoles(Subject subject, Iterable<RoleIdentifier> roleIds) {
Set<RoleIdentifier> unauthorizedIds = Sets.newTreeSet();
boolean anyAuthorized = false;
for (RoleIdentifier roleId : roleIds) {
// Verify the caller has permission to grant this role
if (subject.hasPermission(Permissions.grantRole(roleId))) {
anyAuthorized = true;
} else {
unauthorizedIds.add(roleId);
}
}
if (!unauthorizedIds.isEmpty()) {
// If the caller was not authorized to assign any of the provided roles raise a generic exception, otherwise
// the exception provides insight as to which roles were unauthorized. This provides some helpful feedback
// where appropriate without exposing potentially exploitable information about whether the subject's API key
// is valid.
if (!anyAuthorized) {
throw new UnauthorizedException();
} else {
throw new UnauthorizedException("Not authorized for roles: " + Joiner.on(", ").join(unauthorizedIds));
}
}
} | java | private void verifyPermissionToGrantRoles(Subject subject, Iterable<RoleIdentifier> roleIds) {
Set<RoleIdentifier> unauthorizedIds = Sets.newTreeSet();
boolean anyAuthorized = false;
for (RoleIdentifier roleId : roleIds) {
// Verify the caller has permission to grant this role
if (subject.hasPermission(Permissions.grantRole(roleId))) {
anyAuthorized = true;
} else {
unauthorizedIds.add(roleId);
}
}
if (!unauthorizedIds.isEmpty()) {
// If the caller was not authorized to assign any of the provided roles raise a generic exception, otherwise
// the exception provides insight as to which roles were unauthorized. This provides some helpful feedback
// where appropriate without exposing potentially exploitable information about whether the subject's API key
// is valid.
if (!anyAuthorized) {
throw new UnauthorizedException();
} else {
throw new UnauthorizedException("Not authorized for roles: " + Joiner.on(", ").join(unauthorizedIds));
}
}
} | [
"private",
"void",
"verifyPermissionToGrantRoles",
"(",
"Subject",
"subject",
",",
"Iterable",
"<",
"RoleIdentifier",
">",
"roleIds",
")",
"{",
"Set",
"<",
"RoleIdentifier",
">",
"unauthorizedIds",
"=",
"Sets",
".",
"newTreeSet",
"(",
")",
";",
"boolean",
"anyAu... | Verifies whether the user has permission to grant all of the provided roles. If not it throws an UnauthorizedException.
@throws UnauthorizedException User did not have the permission to grant at least one role. | [
"Verifies",
"whether",
"the",
"user",
"has",
"permission",
"to",
"grant",
"all",
"of",
"the",
"provided",
"roles",
".",
"If",
"not",
"it",
"throws",
"an",
"UnauthorizedException",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/uac/LocalSubjectUserAccessControl.java#L594-L618 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/uac/LocalSubjectUserAccessControl.java | LocalSubjectUserAccessControl.convertUncheckedException | private RuntimeException convertUncheckedException(Exception e) {
if (Throwables.getRootCause(e) instanceof TimeoutException) {
_lockTimeoutMeter.mark();
throw new ServiceUnavailableException("Failed to acquire update lock, try again later", new Random().nextInt(5) + 1);
}
throw Throwables.propagate(e);
} | java | private RuntimeException convertUncheckedException(Exception e) {
if (Throwables.getRootCause(e) instanceof TimeoutException) {
_lockTimeoutMeter.mark();
throw new ServiceUnavailableException("Failed to acquire update lock, try again later", new Random().nextInt(5) + 1);
}
throw Throwables.propagate(e);
} | [
"private",
"RuntimeException",
"convertUncheckedException",
"(",
"Exception",
"e",
")",
"{",
"if",
"(",
"Throwables",
".",
"getRootCause",
"(",
"e",
")",
"instanceof",
"TimeoutException",
")",
"{",
"_lockTimeoutMeter",
".",
"mark",
"(",
")",
";",
"throw",
"new",... | Converts unchecked exceptions to appropriate API exceptions. Specifically, if the subsystem fails to acquire
the synchronization lock for a non-read operation it will throw a TimeoutException. This method converts
that to a ServiceUnavailableException. All other exceptions are rethrown as-is.
This method never returns, it always results in an exception being thrown. The return value is present to
support more natural exception handling by the caller. | [
"Converts",
"unchecked",
"exceptions",
"to",
"appropriate",
"API",
"exceptions",
".",
"Specifically",
"if",
"the",
"subsystem",
"fails",
"to",
"acquire",
"the",
"synchronization",
"lock",
"for",
"a",
"non",
"-",
"read",
"operation",
"it",
"will",
"throw",
"a",
... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/uac/LocalSubjectUserAccessControl.java#L628-L634 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/Row.java | Row.ensureTextSet | private void ensureTextSet() {
if (_text.limit() == 0) {
checkState(_map != null, "Neither JSON text nor map has been set");
_text.clear();
// First try reading the JSON directly into be buffer.
try {
JsonHelper.writeJson(new ByteBufferOutputStream(_text), _map);
// Set the limit and move the position back to zero.
_text.flip();
} catch (Exception e) {
if (Iterables.tryFind(Throwables.getCausalChain(e), Predicates.instanceOf(BufferOverflowException.class)).isPresent()) {
// Buffer was insufficient. Allocate a new array and read the bytes into it.
byte[] utf8 = JsonHelper.asUtf8Bytes(_map);
_text = ByteBuffer.wrap(utf8);
} else {
throw Throwables.propagate(e);
}
}
}
} | java | private void ensureTextSet() {
if (_text.limit() == 0) {
checkState(_map != null, "Neither JSON text nor map has been set");
_text.clear();
// First try reading the JSON directly into be buffer.
try {
JsonHelper.writeJson(new ByteBufferOutputStream(_text), _map);
// Set the limit and move the position back to zero.
_text.flip();
} catch (Exception e) {
if (Iterables.tryFind(Throwables.getCausalChain(e), Predicates.instanceOf(BufferOverflowException.class)).isPresent()) {
// Buffer was insufficient. Allocate a new array and read the bytes into it.
byte[] utf8 = JsonHelper.asUtf8Bytes(_map);
_text = ByteBuffer.wrap(utf8);
} else {
throw Throwables.propagate(e);
}
}
}
} | [
"private",
"void",
"ensureTextSet",
"(",
")",
"{",
"if",
"(",
"_text",
".",
"limit",
"(",
")",
"==",
"0",
")",
"{",
"checkState",
"(",
"_map",
"!=",
"null",
",",
"\"Neither JSON text nor map has been set\"",
")",
";",
"_text",
".",
"clear",
"(",
")",
";"... | Ensures that either the UTF-8 text has been set directly or by indirectly converting the Map contents to JSON. | [
"Ensures",
"that",
"either",
"the",
"UTF",
"-",
"8",
"text",
"has",
"been",
"set",
"directly",
"or",
"by",
"indirectly",
"converting",
"the",
"Map",
"contents",
"to",
"JSON",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/Row.java#L104-L123 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/Row.java | Row.readFields | @Override
public void readFields(DataInput in)
throws IOException {
// Read the length as a variable int
int length = WritableUtils.readVInt(in);
// If necessary increase the buffer capacity
if (length > _text.capacity()) {
_text = ByteBuffer.allocate(length);
}
// For efficiency read directly into the buffer's array
in.readFully(_text.array(), 0, length);
// Since we bypassed putting into the buffer set the position and limit directly
_text.position(0);
_text.limit(length);
// Set the map to null since the contents may have changed.
_map = null;
} | java | @Override
public void readFields(DataInput in)
throws IOException {
// Read the length as a variable int
int length = WritableUtils.readVInt(in);
// If necessary increase the buffer capacity
if (length > _text.capacity()) {
_text = ByteBuffer.allocate(length);
}
// For efficiency read directly into the buffer's array
in.readFully(_text.array(), 0, length);
// Since we bypassed putting into the buffer set the position and limit directly
_text.position(0);
_text.limit(length);
// Set the map to null since the contents may have changed.
_map = null;
} | [
"@",
"Override",
"public",
"void",
"readFields",
"(",
"DataInput",
"in",
")",
"throws",
"IOException",
"{",
"// Read the length as a variable int",
"int",
"length",
"=",
"WritableUtils",
".",
"readVInt",
"(",
"in",
")",
";",
"// If necessary increase the buffer capacity... | Sets this instance's content from the input. | [
"Sets",
"this",
"instance",
"s",
"content",
"from",
"the",
"input",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/Row.java#L202-L218 | train |
bazaarvoice/emodb | mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/Row.java | Row.write | @Override
public void write(DataOutput out)
throws IOException {
ensureTextSet();
// Write a variable int with the length
WritableUtils.writeVInt(out, _text.limit());
// Write the bytes. For efficiency directly access the buffer's array.
out.write(_text.array(), 0, _text.limit());
} | java | @Override
public void write(DataOutput out)
throws IOException {
ensureTextSet();
// Write a variable int with the length
WritableUtils.writeVInt(out, _text.limit());
// Write the bytes. For efficiency directly access the buffer's array.
out.write(_text.array(), 0, _text.limit());
} | [
"@",
"Override",
"public",
"void",
"write",
"(",
"DataOutput",
"out",
")",
"throws",
"IOException",
"{",
"ensureTextSet",
"(",
")",
";",
"// Write a variable int with the length",
"WritableUtils",
".",
"writeVInt",
"(",
"out",
",",
"_text",
".",
"limit",
"(",
")... | Writes this instance's content to the output. Note that the format for Row is identical to Text, so even though
the classes are unrelated a Text object can read the bytes written by a Row as a JSON string. | [
"Writes",
"this",
"instance",
"s",
"content",
"to",
"the",
"output",
".",
"Note",
"that",
"the",
"format",
"for",
"Row",
"is",
"identical",
"to",
"Text",
"so",
"even",
"though",
"the",
"classes",
"are",
"unrelated",
"a",
"Text",
"object",
"can",
"read",
... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/Row.java#L224-L232 | train |
bazaarvoice/emodb | common/stash/src/main/java/com/bazaarvoice/emodb/common/stash/StandardStashReader.java | StandardStashReader.getLockedView | public StashReader getLockedView() {
return new FixedStashReader(URI.create(String.format("s3://%s/%s", _bucket, getRootPath())), _s3);
} | java | public StashReader getLockedView() {
return new FixedStashReader(URI.create(String.format("s3://%s/%s", _bucket, getRootPath())), _s3);
} | [
"public",
"StashReader",
"getLockedView",
"(",
")",
"{",
"return",
"new",
"FixedStashReader",
"(",
"URI",
".",
"create",
"(",
"String",
".",
"format",
"(",
"\"s3://%s/%s\"",
",",
"_bucket",
",",
"getRootPath",
"(",
")",
")",
")",
",",
"_s3",
")",
";",
"}... | Returns a new StashReader that is locked to the same stash time the instance is currently using. Future calls to
lock or unlock the stash time on this instance will not affect the returned instance. | [
"Returns",
"a",
"new",
"StashReader",
"that",
"is",
"locked",
"to",
"the",
"same",
"stash",
"time",
"the",
"instance",
"is",
"currently",
"using",
".",
"Future",
"calls",
"to",
"lock",
"or",
"unlock",
"the",
"stash",
"time",
"on",
"this",
"instance",
"will... | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/stash/src/main/java/com/bazaarvoice/emodb/common/stash/StandardStashReader.java#L194-L196 | train |
bazaarvoice/emodb | web/src/main/java/com/bazaarvoice/emodb/web/scanner/ScanUploader.java | ScanUploader.createPlan | private ScanPlan createPlan(String scanId, ScanOptions options) {
ScanPlan plan = new ScanPlan(scanId, options);
for (String placement : options.getPlacements()) {
String cluster = _dataTools.getPlacementCluster(placement);
ScanRangeSplits scanRangeSplits = _dataTools.getScanRangeSplits(placement, options.getRangeScanSplitSize(), Optional.<ScanRange>absent());
if (!options.isScanByAZ()) {
// Optionally we can reduce load across the ring by limiting scans AZ at a time. However, the caller
// has requested to scan all token ranges as quickly as possible, so collapse all token ranges into a
// single group.
scanRangeSplits = scanRangeSplits.combineGroups();
}
for (ScanRangeSplits.SplitGroup splitGroup : scanRangeSplits.getSplitGroups()) {
// Start a new batch, indicating the subsequent token ranges can be scanned in parallel
plan.startNewBatchForCluster(cluster);
// Add the scan ranges associated with each token range in the split group to the batch
for (ScanRangeSplits.TokenRange tokenRange : splitGroup.getTokenRanges()) {
plan.addTokenRangeToCurrentBatchForCluster(cluster, placement, tokenRange.getScanRanges());
}
}
}
return plan;
} | java | private ScanPlan createPlan(String scanId, ScanOptions options) {
ScanPlan plan = new ScanPlan(scanId, options);
for (String placement : options.getPlacements()) {
String cluster = _dataTools.getPlacementCluster(placement);
ScanRangeSplits scanRangeSplits = _dataTools.getScanRangeSplits(placement, options.getRangeScanSplitSize(), Optional.<ScanRange>absent());
if (!options.isScanByAZ()) {
// Optionally we can reduce load across the ring by limiting scans AZ at a time. However, the caller
// has requested to scan all token ranges as quickly as possible, so collapse all token ranges into a
// single group.
scanRangeSplits = scanRangeSplits.combineGroups();
}
for (ScanRangeSplits.SplitGroup splitGroup : scanRangeSplits.getSplitGroups()) {
// Start a new batch, indicating the subsequent token ranges can be scanned in parallel
plan.startNewBatchForCluster(cluster);
// Add the scan ranges associated with each token range in the split group to the batch
for (ScanRangeSplits.TokenRange tokenRange : splitGroup.getTokenRanges()) {
plan.addTokenRangeToCurrentBatchForCluster(cluster, placement, tokenRange.getScanRanges());
}
}
}
return plan;
} | [
"private",
"ScanPlan",
"createPlan",
"(",
"String",
"scanId",
",",
"ScanOptions",
"options",
")",
"{",
"ScanPlan",
"plan",
"=",
"new",
"ScanPlan",
"(",
"scanId",
",",
"options",
")",
";",
"for",
"(",
"String",
"placement",
":",
"options",
".",
"getPlacements... | Returns a ScanPlan based on the Cassandra rings and token ranges. | [
"Returns",
"a",
"ScanPlan",
"based",
"on",
"the",
"Cassandra",
"rings",
"and",
"token",
"ranges",
"."
] | 97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/ScanUploader.java#L134-L159 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.