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
web/src/main/java/com/bazaarvoice/emodb/web/scanner/ScanUploader.java
ScanUploader.resubmitWorkflowTasks
public ScanStatus resubmitWorkflowTasks(String scanId) { ScanStatus status = _scanStatusDAO.getScanStatus(scanId); if (status == null) { return null; } if (status.getCompleteTime() == null) { // Resubmit any active tasks for (ScanRangeStatus active : status.getActiveScanRanges()) { _scanWorkflow.addScanRangeTask(scanId, active.getTaskId(), active.getPlacement(), active.getScanRange()); } // Send notification to evaluate whether any new range tasks can be started _scanWorkflow.scanStatusUpdated(scanId); } return status; }
java
public ScanStatus resubmitWorkflowTasks(String scanId) { ScanStatus status = _scanStatusDAO.getScanStatus(scanId); if (status == null) { return null; } if (status.getCompleteTime() == null) { // Resubmit any active tasks for (ScanRangeStatus active : status.getActiveScanRanges()) { _scanWorkflow.addScanRangeTask(scanId, active.getTaskId(), active.getPlacement(), active.getScanRange()); } // Send notification to evaluate whether any new range tasks can be started _scanWorkflow.scanStatusUpdated(scanId); } return status; }
[ "public", "ScanStatus", "resubmitWorkflowTasks", "(", "String", "scanId", ")", "{", "ScanStatus", "status", "=", "_scanStatusDAO", ".", "getScanStatus", "(", "scanId", ")", ";", "if", "(", "status", "==", "null", ")", "{", "return", "null", ";", "}", "if", ...
Sometimes due to unexpected errors while submitting scan ranges to the underlying queues a scan can get stuck. This method takes all available tasks for a scan and resubmits them. This method is safe because the underlying system is resilient to task resubmissions and concurrent work on the same task.
[ "Sometimes", "due", "to", "unexpected", "errors", "while", "submitting", "scan", "ranges", "to", "the", "underlying", "queues", "a", "scan", "can", "get", "stuck", ".", "This", "method", "takes", "all", "available", "tasks", "for", "a", "scan", "and", "resub...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/ScanUploader.java#L253-L270
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/scanner/scheduling/ScheduledDailyScanUpload.java
ScheduledDailyScanUpload.getNextExecutionTimeAfter
public Instant getNextExecutionTimeAfter(Instant now) { OffsetTime timeOfDay = OffsetTime.from(TIME_OF_DAY_FORMAT.parse(getTimeOfDay())); // The time of the next run is based on the time past midnight UTC relative to the current time Instant nextExecTime = now.atOffset(ZoneOffset.UTC).with(timeOfDay).toInstant(); // If the first execution would have been for earlier today move to the next execution. while (nextExecTime.isBefore(now)) { nextExecTime = nextExecTime.plus(Duration.ofDays(1)); } return nextExecTime; }
java
public Instant getNextExecutionTimeAfter(Instant now) { OffsetTime timeOfDay = OffsetTime.from(TIME_OF_DAY_FORMAT.parse(getTimeOfDay())); // The time of the next run is based on the time past midnight UTC relative to the current time Instant nextExecTime = now.atOffset(ZoneOffset.UTC).with(timeOfDay).toInstant(); // If the first execution would have been for earlier today move to the next execution. while (nextExecTime.isBefore(now)) { nextExecTime = nextExecTime.plus(Duration.ofDays(1)); } return nextExecTime; }
[ "public", "Instant", "getNextExecutionTimeAfter", "(", "Instant", "now", ")", "{", "OffsetTime", "timeOfDay", "=", "OffsetTime", ".", "from", "(", "TIME_OF_DAY_FORMAT", ".", "parse", "(", "getTimeOfDay", "(", ")", ")", ")", ";", "// The time of the next run is based...
Gets the first execution time for the given scan and upload which is at or after "now".
[ "Gets", "the", "first", "execution", "time", "for", "the", "given", "scan", "and", "upload", "which", "is", "at", "or", "after", "now", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/scheduling/ScheduledDailyScanUpload.java#L93-L105
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/scanner/writer/ScanWriterGenerator.java
ScanWriterGenerator.createScanWriter
public ScanWriter createScanWriter(final int taskId, Set<ScanDestination> destinations) { checkArgument(!destinations.isEmpty(), "destinations.isEmpty()"); if (destinations.size() == 1) { return createScanWriter(taskId, Iterables.getOnlyElement(destinations)); } return new MultiScanWriter(ImmutableList.copyOf( Iterables.transform(destinations, new Function<ScanDestination, ScanWriter>() { @Override public ScanWriter apply(ScanDestination destination) { return createScanWriter(taskId, destination); } }) )); }
java
public ScanWriter createScanWriter(final int taskId, Set<ScanDestination> destinations) { checkArgument(!destinations.isEmpty(), "destinations.isEmpty()"); if (destinations.size() == 1) { return createScanWriter(taskId, Iterables.getOnlyElement(destinations)); } return new MultiScanWriter(ImmutableList.copyOf( Iterables.transform(destinations, new Function<ScanDestination, ScanWriter>() { @Override public ScanWriter apply(ScanDestination destination) { return createScanWriter(taskId, destination); } }) )); }
[ "public", "ScanWriter", "createScanWriter", "(", "final", "int", "taskId", ",", "Set", "<", "ScanDestination", ">", "destinations", ")", "{", "checkArgument", "(", "!", "destinations", ".", "isEmpty", "(", ")", ",", "\"destinations.isEmpty()\"", ")", ";", "if", ...
Creates a scan writer from the given desintations.
[ "Creates", "a", "scan", "writer", "from", "the", "given", "desintations", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/writer/ScanWriterGenerator.java#L30-L44
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/scanner/writer/ScanWriterGenerator.java
ScanWriterGenerator.createScanWriter
public ScanWriter createScanWriter(int taskId, ScanDestination destination) { if (destination.isDiscarding()) { return _scanWriterFactory.createDiscardingScanWriter(taskId, Optional.<Integer>absent()); } URI uri = destination.getUri(); String scheme = uri.getScheme(); if ("file".equals(scheme)) { return _scanWriterFactory.createFileScanWriter(taskId, uri, Optional.<Integer>absent()); } if ("s3".equals(scheme)) { return _scanWriterFactory.createS3ScanWriter(taskId, uri, Optional.<Integer>absent()); } throw new IllegalArgumentException("Unsupported destination: " + destination); }
java
public ScanWriter createScanWriter(int taskId, ScanDestination destination) { if (destination.isDiscarding()) { return _scanWriterFactory.createDiscardingScanWriter(taskId, Optional.<Integer>absent()); } URI uri = destination.getUri(); String scheme = uri.getScheme(); if ("file".equals(scheme)) { return _scanWriterFactory.createFileScanWriter(taskId, uri, Optional.<Integer>absent()); } if ("s3".equals(scheme)) { return _scanWriterFactory.createS3ScanWriter(taskId, uri, Optional.<Integer>absent()); } throw new IllegalArgumentException("Unsupported destination: " + destination); }
[ "public", "ScanWriter", "createScanWriter", "(", "int", "taskId", ",", "ScanDestination", "destination", ")", "{", "if", "(", "destination", ".", "isDiscarding", "(", ")", ")", "{", "return", "_scanWriterFactory", ".", "createDiscardingScanWriter", "(", "taskId", ...
Creates a scan writer for the given destination.
[ "Creates", "a", "scan", "writer", "for", "the", "given", "destination", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/writer/ScanWriterGenerator.java#L49-L66
train
bazaarvoice/emodb
common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/CassandraKeyspace.java
CassandraKeyspace.prepareColumnMutation
public <K, C> ColumnMutation prepareColumnMutation(ColumnFamily<K, C> cf, K rowKey, C column, ConsistencyLevel consistency) { return _astyanaxKeyspace.prepareColumnMutation(cf, rowKey, column).setConsistencyLevel(clamp(consistency)); }
java
public <K, C> ColumnMutation prepareColumnMutation(ColumnFamily<K, C> cf, K rowKey, C column, ConsistencyLevel consistency) { return _astyanaxKeyspace.prepareColumnMutation(cf, rowKey, column).setConsistencyLevel(clamp(consistency)); }
[ "public", "<", "K", ",", "C", ">", "ColumnMutation", "prepareColumnMutation", "(", "ColumnFamily", "<", "K", ",", "C", ">", "cf", ",", "K", "rowKey", ",", "C", "column", ",", "ConsistencyLevel", "consistency", ")", "{", "return", "_astyanaxKeyspace", ".", ...
Mutation for a single column.
[ "Mutation", "for", "a", "single", "column", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/CassandraKeyspace.java#L110-L112
train
bazaarvoice/emodb
common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/CassandraKeyspace.java
CassandraKeyspace.getMismatchedPartitioner
private String getMismatchedPartitioner(Class<? extends IPartitioner> expectedPartitioner) { String partitioner = null; try { partitioner = _astyanaxKeyspace.describePartitioner(); boolean matches = CassandraPartitioner.fromClass(partitioner).matches(expectedPartitioner.getName()); if (matches) { return null; } else { return partitioner; } } catch (ConnectionException e) { throw Throwables.propagate(e); } catch (IllegalArgumentException e) { // Only thrown if the partitioner doesn't match any compatible partitioner, so by definition it is mismatched. return partitioner; } }
java
private String getMismatchedPartitioner(Class<? extends IPartitioner> expectedPartitioner) { String partitioner = null; try { partitioner = _astyanaxKeyspace.describePartitioner(); boolean matches = CassandraPartitioner.fromClass(partitioner).matches(expectedPartitioner.getName()); if (matches) { return null; } else { return partitioner; } } catch (ConnectionException e) { throw Throwables.propagate(e); } catch (IllegalArgumentException e) { // Only thrown if the partitioner doesn't match any compatible partitioner, so by definition it is mismatched. return partitioner; } }
[ "private", "String", "getMismatchedPartitioner", "(", "Class", "<", "?", "extends", "IPartitioner", ">", "expectedPartitioner", ")", "{", "String", "partitioner", "=", "null", ";", "try", "{", "partitioner", "=", "_astyanaxKeyspace", ".", "describePartitioner", "(",...
Returns the actual partitioner in use by Cassandra if it does not match the expected partitioner, null if it matches.
[ "Returns", "the", "actual", "partitioner", "in", "use", "by", "Cassandra", "if", "it", "does", "not", "match", "the", "expected", "partitioner", "null", "if", "it", "matches", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/CassandraKeyspace.java#L164-L181
train
bazaarvoice/emodb
event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/ChannelAllocationState.java
ChannelAllocationState.attachAndAllocate
public synchronized SlabAllocation attachAndAllocate(SlabRef slab, PeekingIterator<Integer> eventSizes) { attach(slab); return allocate(eventSizes); }
java
public synchronized SlabAllocation attachAndAllocate(SlabRef slab, PeekingIterator<Integer> eventSizes) { attach(slab); return allocate(eventSizes); }
[ "public", "synchronized", "SlabAllocation", "attachAndAllocate", "(", "SlabRef", "slab", ",", "PeekingIterator", "<", "Integer", ">", "eventSizes", ")", "{", "attach", "(", "slab", ")", ";", "return", "allocate", "(", "eventSizes", ")", ";", "}" ]
Attaches a slab and allocates from it in a single atomic operation.
[ "Attaches", "a", "slab", "and", "allocates", "from", "it", "in", "a", "single", "atomic", "operation", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/ChannelAllocationState.java#L32-L35
train
bazaarvoice/emodb
event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/ChannelAllocationState.java
ChannelAllocationState.attach
public synchronized void attach(SlabRef slab) { // Assume ownership of the caller's ref. No need to call slab.addRef(). checkState(!isAttached()); _slab = slab; _slabConsumed = 0; _slabBytesConsumed = 0; _slabExpiresAt = System.currentTimeMillis() + Constants.SLAB_ROTATE_TTL.toMillis(); }
java
public synchronized void attach(SlabRef slab) { // Assume ownership of the caller's ref. No need to call slab.addRef(). checkState(!isAttached()); _slab = slab; _slabConsumed = 0; _slabBytesConsumed = 0; _slabExpiresAt = System.currentTimeMillis() + Constants.SLAB_ROTATE_TTL.toMillis(); }
[ "public", "synchronized", "void", "attach", "(", "SlabRef", "slab", ")", "{", "// Assume ownership of the caller's ref. No need to call slab.addRef().", "checkState", "(", "!", "isAttached", "(", ")", ")", ";", "_slab", "=", "slab", ";", "_slabConsumed", "=", "0", ...
Attaches a new slab to the channel with the specified capacity.
[ "Attaches", "a", "new", "slab", "to", "the", "channel", "with", "the", "specified", "capacity", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/ChannelAllocationState.java#L38-L46
train
bazaarvoice/emodb
event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/ChannelAllocationState.java
ChannelAllocationState.detach
public synchronized SlabRef detach() { if (!isAttached()) { return null; } // Pass ownership of the slab ref to the caller. No need to call slab.release(). SlabRef slab = _slab; _slab = null; _slabExpiresAt = 0; return slab; }
java
public synchronized SlabRef detach() { if (!isAttached()) { return null; } // Pass ownership of the slab ref to the caller. No need to call slab.release(). SlabRef slab = _slab; _slab = null; _slabExpiresAt = 0; return slab; }
[ "public", "synchronized", "SlabRef", "detach", "(", ")", "{", "if", "(", "!", "isAttached", "(", ")", ")", "{", "return", "null", ";", "}", "// Pass ownership of the slab ref to the caller. No need to call slab.release().", "SlabRef", "slab", "=", "_slab", ";", "_s...
Detaches a slab from the channel and returns it to the caller to dispose of.
[ "Detaches", "a", "slab", "from", "the", "channel", "and", "returns", "it", "to", "the", "caller", "to", "dispose", "of", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/event/db/astyanax/ChannelAllocationState.java#L49-L59
train
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java
AstyanaxTableDAO.getNextMaintenanceOp
@Nullable private MaintenanceOp getNextMaintenanceOp(final TableJson json, boolean includeTask) { if (json.isDeleted() || json.getStorages().isEmpty()) { return null; } // Loop through the table uuids and pick the MaintenanceOp that should execute first, with the minimum "when". MaintenanceOp op = NULLS_LAST.min(Iterables.transform(json.getStorages(), new Function<Storage, MaintenanceOp>() { @Override public MaintenanceOp apply(Storage storage) { return getNextMaintenanceOp(json, storage); } })); // Don't expose the MaintenanceOp Runnable to most callers. It may only be run from the right data center // and with the right locks in place so it's best to not leak it to where it may be called accidentally. if (op != null && !includeTask) { op.clearTask(); } return op; }
java
@Nullable private MaintenanceOp getNextMaintenanceOp(final TableJson json, boolean includeTask) { if (json.isDeleted() || json.getStorages().isEmpty()) { return null; } // Loop through the table uuids and pick the MaintenanceOp that should execute first, with the minimum "when". MaintenanceOp op = NULLS_LAST.min(Iterables.transform(json.getStorages(), new Function<Storage, MaintenanceOp>() { @Override public MaintenanceOp apply(Storage storage) { return getNextMaintenanceOp(json, storage); } })); // Don't expose the MaintenanceOp Runnable to most callers. It may only be run from the right data center // and with the right locks in place so it's best to not leak it to where it may be called accidentally. if (op != null && !includeTask) { op.clearTask(); } return op; }
[ "@", "Nullable", "private", "MaintenanceOp", "getNextMaintenanceOp", "(", "final", "TableJson", "json", ",", "boolean", "includeTask", ")", "{", "if", "(", "json", ".", "isDeleted", "(", ")", "||", "json", ".", "getStorages", "(", ")", ".", "isEmpty", "(", ...
Returns the next maintenance operation that should be performed on the specified table.
[ "Returns", "the", "next", "maintenance", "operation", "that", "should", "be", "performed", "on", "the", "specified", "table", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java#L325-L344
train
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java
AstyanaxTableDAO.checkFacadeAllowed
@Override public boolean checkFacadeAllowed(String table, FacadeOptions options) throws FacadeExistsException { return checkFacadeAllowed(readTableJson(table, true), options.getPlacement(), null); }
java
@Override public boolean checkFacadeAllowed(String table, FacadeOptions options) throws FacadeExistsException { return checkFacadeAllowed(readTableJson(table, true), options.getPlacement(), null); }
[ "@", "Override", "public", "boolean", "checkFacadeAllowed", "(", "String", "table", ",", "FacadeOptions", "options", ")", "throws", "FacadeExistsException", "{", "return", "checkFacadeAllowed", "(", "readTableJson", "(", "table", ",", "true", ")", ",", "options", ...
Returns true if facade may be created for the specified table and placement. Throws an exception if a facade is not allowed because of a conflict with the master or another facade. Returns false if there is already a facade at the specified placement, so facade creation would be idempotent.
[ "Returns", "true", "if", "facade", "may", "be", "created", "for", "the", "specified", "table", "and", "placement", ".", "Throws", "an", "exception", "if", "a", "facade", "is", "not", "allowed", "because", "of", "a", "conflict", "with", "the", "master", "or...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java#L644-L648
train
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java
AstyanaxTableDAO.purgeData
private void purgeData(TableJson json, Storage storage, int iteration, Runnable progress) { _log.info("Purging data for table '{}' and table uuid '{}' (facade={}, iteration={}).", json.getTable(), storage.getUuidString(), storage.isFacade(), iteration); // Cap the # of writes-per-second to avoid saturating the cluster. Runnable rateLimitedProgress = rateLimited(_placementCache.get(storage.getPlacement()), progress); // Delete all the data for this table. audit(json.getTable(), "doPurgeData" + iteration, new AuditBuilder() .set("_uuid", storage.getUuidString()) .set("_placement", storage.getPlacement()) .build()); _dataPurgeDAO.purge(newAstyanaxStorage(storage, json.getTable()), rateLimitedProgress); }
java
private void purgeData(TableJson json, Storage storage, int iteration, Runnable progress) { _log.info("Purging data for table '{}' and table uuid '{}' (facade={}, iteration={}).", json.getTable(), storage.getUuidString(), storage.isFacade(), iteration); // Cap the # of writes-per-second to avoid saturating the cluster. Runnable rateLimitedProgress = rateLimited(_placementCache.get(storage.getPlacement()), progress); // Delete all the data for this table. audit(json.getTable(), "doPurgeData" + iteration, new AuditBuilder() .set("_uuid", storage.getUuidString()) .set("_placement", storage.getPlacement()) .build()); _dataPurgeDAO.purge(newAstyanaxStorage(storage, json.getTable()), rateLimitedProgress); }
[ "private", "void", "purgeData", "(", "TableJson", "json", ",", "Storage", "storage", ",", "int", "iteration", ",", "Runnable", "progress", ")", "{", "_log", ".", "info", "(", "\"Purging data for table '{}' and table uuid '{}' (facade={}, iteration={}).\"", ",", "json", ...
Purge a dropped table or facade. Executed twice, once for fast cleanup and again much later for stragglers.
[ "Purge", "a", "dropped", "table", "or", "facade", ".", "Executed", "twice", "once", "for", "fast", "cleanup", "and", "again", "much", "later", "for", "stragglers", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java#L746-L759
train
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java
AstyanaxTableDAO.deleteFinal
private void deleteFinal(TableJson json, Storage storage) { // Remove the uuid and storage--we no longer need it. Leave the uuid in _systemTableUuid so it isn't reused. Delta delta = json.newDeleteStorage(storage); Audit audit = new AuditBuilder() .set("_op", "doDeleteFinal") .set("_uuid", storage.getUuidString()) .build(); updateTableMetadata(json.getTable(), delta, audit, InvalidationScope.LOCAL); }
java
private void deleteFinal(TableJson json, Storage storage) { // Remove the uuid and storage--we no longer need it. Leave the uuid in _systemTableUuid so it isn't reused. Delta delta = json.newDeleteStorage(storage); Audit audit = new AuditBuilder() .set("_op", "doDeleteFinal") .set("_uuid", storage.getUuidString()) .build(); updateTableMetadata(json.getTable(), delta, audit, InvalidationScope.LOCAL); }
[ "private", "void", "deleteFinal", "(", "TableJson", "json", ",", "Storage", "storage", ")", "{", "// Remove the uuid and storage--we no longer need it. Leave the uuid in _systemTableUuid so it isn't reused.", "Delta", "delta", "=", "json", ".", "newDeleteStorage", "(", "storag...
Last step in dropping a table or facade.
[ "Last", "step", "in", "dropping", "a", "table", "or", "facade", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java#L764-L773
train
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java
AstyanaxTableDAO.moveCancel
private void moveCancel(TableJson json, Storage src, Storage dest) { Delta delta = json.newMoveCancel(src); Audit audit = new AuditBuilder() .set("_op", "doMoveCancel") .set("_srcUuid", src.getUuidString()) .set("_srcPlacement", src.getPlacement()) .set("_destUuid", dest.getUuidString()) .set("_destPlacement", dest.getPlacement()) .build(); updateTableMetadata(json.getTable(), delta, audit, InvalidationScope.GLOBAL); }
java
private void moveCancel(TableJson json, Storage src, Storage dest) { Delta delta = json.newMoveCancel(src); Audit audit = new AuditBuilder() .set("_op", "doMoveCancel") .set("_srcUuid", src.getUuidString()) .set("_srcPlacement", src.getPlacement()) .set("_destUuid", dest.getUuidString()) .set("_destPlacement", dest.getPlacement()) .build(); updateTableMetadata(json.getTable(), delta, audit, InvalidationScope.GLOBAL); }
[ "private", "void", "moveCancel", "(", "TableJson", "json", ",", "Storage", "src", ",", "Storage", "dest", ")", "{", "Delta", "delta", "=", "json", ".", "newMoveCancel", "(", "src", ")", ";", "Audit", "audit", "=", "new", "AuditBuilder", "(", ")", ".", ...
Cancel a move before mirror promotion has taken place.
[ "Cancel", "a", "move", "before", "mirror", "promotion", "has", "taken", "place", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java#L941-L951
train
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java
AstyanaxTableDAO.newUnpublishedDatabusEventUpdate
Delta newUnpublishedDatabusEventUpdate(String tableName, String updateType, String datetime) { return Deltas.mapBuilder() .update("tables", Deltas.setBuilder().add(ImmutableMap.of("table", tableName, "date", datetime, "event", updateType)).build()) .build(); }
java
Delta newUnpublishedDatabusEventUpdate(String tableName, String updateType, String datetime) { return Deltas.mapBuilder() .update("tables", Deltas.setBuilder().add(ImmutableMap.of("table", tableName, "date", datetime, "event", updateType)).build()) .build(); }
[ "Delta", "newUnpublishedDatabusEventUpdate", "(", "String", "tableName", ",", "String", "updateType", ",", "String", "datetime", ")", "{", "return", "Deltas", ".", "mapBuilder", "(", ")", ".", "update", "(", "\"tables\"", ",", "Deltas", ".", "setBuilder", "(", ...
Delta for storing the unpublished databus events.
[ "Delta", "for", "storing", "the", "unpublished", "databus", "events", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTableDAO.java#L1533-L1537
train
bazaarvoice/emodb
sor-api/src/main/java/com/bazaarvoice/emodb/sor/condition/impl/AndConditionImpl.java
AndConditionImpl.conditionsEqual
private boolean conditionsEqual(Collection<Condition> conditions) { if (conditions.size() != _conditions.size()) { return false; } List<Condition> unvalidatedConditions = new ArrayList<>(conditions); for (Condition condition : _conditions) { if (!unvalidatedConditions.remove(condition)) { return false; } } return true; }
java
private boolean conditionsEqual(Collection<Condition> conditions) { if (conditions.size() != _conditions.size()) { return false; } List<Condition> unvalidatedConditions = new ArrayList<>(conditions); for (Condition condition : _conditions) { if (!unvalidatedConditions.remove(condition)) { return false; } } return true; }
[ "private", "boolean", "conditionsEqual", "(", "Collection", "<", "Condition", ">", "conditions", ")", "{", "if", "(", "conditions", ".", "size", "(", ")", "!=", "_conditions", ".", "size", "(", ")", ")", "{", "return", "false", ";", "}", "List", "<", "...
The order of the conditions is irrelevant, just check the set is the same.
[ "The", "order", "of", "the", "conditions", "is", "irrelevant", "just", "check", "the", "set", "is", "the", "same", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor-api/src/main/java/com/bazaarvoice/emodb/sor/condition/impl/AndConditionImpl.java#L74-L85
train
bazaarvoice/emodb
mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/HadoopDataStoreManager.java
HadoopDataStoreManager.getDataStore
public CloseableDataStore getDataStore(URI location, String apiKey, MetricRegistry metricRegistry) throws IOException { String id = LocationUtil.getDataStoreIdentifier(location, apiKey); CloseableDataStore dataStore = null; while (dataStore == null) { // Get the cached DataStore if it exists DataStoreMonitor dataStoreMonitor = _dataStoreByLocation.get(id); if (dataStoreMonitor == null || (dataStore = dataStoreMonitor.getDataStore()) == null) { // Either the value wasn't cached or the cached value was closed before the reference count could // be incremented. Create a new DataStore and cache it. CloseableDataStore unmonitoredDataStore; switch (LocationUtil.getLocationType(location)) { case EMO_HOST_DISCOVERY: unmonitoredDataStore = createDataStoreWithHostDiscovery(location, apiKey, metricRegistry); break; case EMO_URL: unmonitoredDataStore = createDataStoreWithUrl(location, apiKey, metricRegistry); break; default: throw new IllegalArgumentException("Location does not use a data store: " + location); } dataStoreMonitor = new DataStoreMonitor(id, unmonitoredDataStore); if (_dataStoreByLocation.putIfAbsent(id, dataStoreMonitor) != null) { // Race condition; close the created DataStore and try again dataStoreMonitor.closeNow(); } else { // New data store was cached; return the value dataStore = dataStoreMonitor.getDataStore(); } } } return dataStore; }
java
public CloseableDataStore getDataStore(URI location, String apiKey, MetricRegistry metricRegistry) throws IOException { String id = LocationUtil.getDataStoreIdentifier(location, apiKey); CloseableDataStore dataStore = null; while (dataStore == null) { // Get the cached DataStore if it exists DataStoreMonitor dataStoreMonitor = _dataStoreByLocation.get(id); if (dataStoreMonitor == null || (dataStore = dataStoreMonitor.getDataStore()) == null) { // Either the value wasn't cached or the cached value was closed before the reference count could // be incremented. Create a new DataStore and cache it. CloseableDataStore unmonitoredDataStore; switch (LocationUtil.getLocationType(location)) { case EMO_HOST_DISCOVERY: unmonitoredDataStore = createDataStoreWithHostDiscovery(location, apiKey, metricRegistry); break; case EMO_URL: unmonitoredDataStore = createDataStoreWithUrl(location, apiKey, metricRegistry); break; default: throw new IllegalArgumentException("Location does not use a data store: " + location); } dataStoreMonitor = new DataStoreMonitor(id, unmonitoredDataStore); if (_dataStoreByLocation.putIfAbsent(id, dataStoreMonitor) != null) { // Race condition; close the created DataStore and try again dataStoreMonitor.closeNow(); } else { // New data store was cached; return the value dataStore = dataStoreMonitor.getDataStore(); } } } return dataStore; }
[ "public", "CloseableDataStore", "getDataStore", "(", "URI", "location", ",", "String", "apiKey", ",", "MetricRegistry", "metricRegistry", ")", "throws", "IOException", "{", "String", "id", "=", "LocationUtil", ".", "getDataStoreIdentifier", "(", "location", ",", "ap...
Returns a DataStore for a given location. If a cached instance already exists its reference count is incremented and returned, otherwise a new instance is created and cached.
[ "Returns", "a", "DataStore", "for", "a", "given", "location", ".", "If", "a", "cached", "instance", "already", "exists", "its", "reference", "count", "is", "incremented", "and", "returned", "otherwise", "a", "new", "instance", "is", "created", "and", "cached",...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/HadoopDataStoreManager.java#L61-L96
train
bazaarvoice/emodb
mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/HadoopDataStoreManager.java
HadoopDataStoreManager.createDataStoreServiceFactory
private MultiThreadedServiceFactory<AuthDataStore> createDataStoreServiceFactory(String cluster, MetricRegistry metricRegistry) { HttpClientConfiguration clientConfig = new HttpClientConfiguration(); clientConfig.setKeepAlive(Duration.seconds(1)); clientConfig.setConnectionTimeout(Duration.seconds(10)); clientConfig.setTimeout(Duration.minutes(5)); return DataStoreClientFactory.forClusterAndHttpConfiguration(cluster, clientConfig, metricRegistry); }
java
private MultiThreadedServiceFactory<AuthDataStore> createDataStoreServiceFactory(String cluster, MetricRegistry metricRegistry) { HttpClientConfiguration clientConfig = new HttpClientConfiguration(); clientConfig.setKeepAlive(Duration.seconds(1)); clientConfig.setConnectionTimeout(Duration.seconds(10)); clientConfig.setTimeout(Duration.minutes(5)); return DataStoreClientFactory.forClusterAndHttpConfiguration(cluster, clientConfig, metricRegistry); }
[ "private", "MultiThreadedServiceFactory", "<", "AuthDataStore", ">", "createDataStoreServiceFactory", "(", "String", "cluster", ",", "MetricRegistry", "metricRegistry", ")", "{", "HttpClientConfiguration", "clientConfig", "=", "new", "HttpClientConfiguration", "(", ")", ";"...
Creates a ServiceFactory for a cluster with reasonable configurations.
[ "Creates", "a", "ServiceFactory", "for", "a", "cluster", "with", "reasonable", "configurations", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/HadoopDataStoreManager.java#L164-L171
train
bazaarvoice/emodb
sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/CqlBlockedDataReaderDAO.java
CqlBlockedDataReaderDAO.columnScan
private ResultSet columnScan(DeltaPlacement placement, TableDDL tableDDL, ByteBuffer rowKey, Range<RangeTimeUUID> columnRange, boolean ascending, ConsistencyLevel consistency) { Select.Where where = (tableDDL == placement.getBlockedDeltaTableDDL() ? selectDeltaFrom(placement.getBlockedDeltaTableDDL()) : selectFrom(tableDDL)) .where(eq(tableDDL.getRowKeyColumnName(), rowKey)); if (columnRange.hasLowerBound()) { if (columnRange.lowerBoundType() == BoundType.CLOSED) { where = where.and(gte(tableDDL.getChangeIdColumnName(), columnRange.lowerEndpoint().getUuid())); } else { where = where.and(gt(tableDDL.getChangeIdColumnName(), columnRange.lowerEndpoint().getUuid())); } } if (columnRange.hasUpperBound()) { if (columnRange.upperBoundType() == BoundType.CLOSED) { where = where.and(lte(tableDDL.getChangeIdColumnName(), columnRange.upperEndpoint().getUuid())); } else { where = where.and(lt(tableDDL.getChangeIdColumnName(), columnRange.upperEndpoint().getUuid())); } } Statement statement = where .orderBy(ascending ? asc(tableDDL.getChangeIdColumnName()) : desc(tableDDL.getChangeIdColumnName())) .setConsistencyLevel(consistency); return AdaptiveResultSet.executeAdaptiveQuery(placement.getKeyspace().getCqlSession(), statement, _driverConfig.getSingleRowFetchSize()); }
java
private ResultSet columnScan(DeltaPlacement placement, TableDDL tableDDL, ByteBuffer rowKey, Range<RangeTimeUUID> columnRange, boolean ascending, ConsistencyLevel consistency) { Select.Where where = (tableDDL == placement.getBlockedDeltaTableDDL() ? selectDeltaFrom(placement.getBlockedDeltaTableDDL()) : selectFrom(tableDDL)) .where(eq(tableDDL.getRowKeyColumnName(), rowKey)); if (columnRange.hasLowerBound()) { if (columnRange.lowerBoundType() == BoundType.CLOSED) { where = where.and(gte(tableDDL.getChangeIdColumnName(), columnRange.lowerEndpoint().getUuid())); } else { where = where.and(gt(tableDDL.getChangeIdColumnName(), columnRange.lowerEndpoint().getUuid())); } } if (columnRange.hasUpperBound()) { if (columnRange.upperBoundType() == BoundType.CLOSED) { where = where.and(lte(tableDDL.getChangeIdColumnName(), columnRange.upperEndpoint().getUuid())); } else { where = where.and(lt(tableDDL.getChangeIdColumnName(), columnRange.upperEndpoint().getUuid())); } } Statement statement = where .orderBy(ascending ? asc(tableDDL.getChangeIdColumnName()) : desc(tableDDL.getChangeIdColumnName())) .setConsistencyLevel(consistency); return AdaptiveResultSet.executeAdaptiveQuery(placement.getKeyspace().getCqlSession(), statement, _driverConfig.getSingleRowFetchSize()); }
[ "private", "ResultSet", "columnScan", "(", "DeltaPlacement", "placement", ",", "TableDDL", "tableDDL", ",", "ByteBuffer", "rowKey", ",", "Range", "<", "RangeTimeUUID", ">", "columnRange", ",", "boolean", "ascending", ",", "ConsistencyLevel", "consistency", ")", "{",...
Reads columns from the delta or delta history table. The range of columns, order, and limit can be parameterized.
[ "Reads", "columns", "from", "the", "delta", "or", "delta", "history", "table", ".", "The", "range", "of", "columns", "order", "and", "limit", "can", "be", "parameterized", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/CqlBlockedDataReaderDAO.java#L740-L767
train
bazaarvoice/emodb
mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/udf/AbstractEmoFieldUDF.java
AbstractEmoFieldUDF.moveParserToField
private boolean moveParserToField(JsonParser parser, String path) throws IOException { List<String> segments = getFieldPath(path); for (String segment : segments) { if (parser.getCurrentToken() != JsonToken.START_OBJECT) { // Always expect the path to be fields in a JSON map return false; } boolean found = false; JsonToken currentToken = parser.nextToken(); while (!found && currentToken != JsonToken.END_OBJECT) { if (currentToken != JsonToken.FIELD_NAME) { // This should always be a field. Something is amiss. throw new IOException("Field not found at expected location"); } String fieldName = parser.getText(); if (fieldName.equals(segment)) { // Move to the next token, which is the field value found = true; currentToken = parser.nextToken(); } else { parser.nextValue(); currentToken = skipValue(parser); } } if (!found) { // Field was not found return false; } } // The current location in the parser is the value. return true; }
java
private boolean moveParserToField(JsonParser parser, String path) throws IOException { List<String> segments = getFieldPath(path); for (String segment : segments) { if (parser.getCurrentToken() != JsonToken.START_OBJECT) { // Always expect the path to be fields in a JSON map return false; } boolean found = false; JsonToken currentToken = parser.nextToken(); while (!found && currentToken != JsonToken.END_OBJECT) { if (currentToken != JsonToken.FIELD_NAME) { // This should always be a field. Something is amiss. throw new IOException("Field not found at expected location"); } String fieldName = parser.getText(); if (fieldName.equals(segment)) { // Move to the next token, which is the field value found = true; currentToken = parser.nextToken(); } else { parser.nextValue(); currentToken = skipValue(parser); } } if (!found) { // Field was not found return false; } } // The current location in the parser is the value. return true; }
[ "private", "boolean", "moveParserToField", "(", "JsonParser", "parser", ",", "String", "path", ")", "throws", "IOException", "{", "List", "<", "String", ">", "segments", "=", "getFieldPath", "(", "path", ")", ";", "for", "(", "String", "segment", ":", "segme...
Don't materialize the entire parser content, do a targeted search for the value that matches the path.
[ "Don", "t", "materialize", "the", "entire", "parser", "content", "do", "a", "targeted", "search", "for", "the", "value", "that", "matches", "the", "path", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/udf/AbstractEmoFieldUDF.java#L71-L108
train
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/RowKeyUtils.java
RowKeyUtils.getRowKeyRaw
static ByteBuffer getRowKeyRaw(int shardId, long tableUuid, byte[] contentKeyBytes) { checkArgument(shardId >= 0 && shardId < 256); // Assemble a single array which is "1 byte shard id + 8 byte table uuid + n-byte content key". ByteBuffer rowKey = ByteBuffer.allocate(9 + contentKeyBytes.length); rowKey.put((byte) shardId); rowKey.putLong(tableUuid); rowKey.put(contentKeyBytes); rowKey.flip(); return rowKey; }
java
static ByteBuffer getRowKeyRaw(int shardId, long tableUuid, byte[] contentKeyBytes) { checkArgument(shardId >= 0 && shardId < 256); // Assemble a single array which is "1 byte shard id + 8 byte table uuid + n-byte content key". ByteBuffer rowKey = ByteBuffer.allocate(9 + contentKeyBytes.length); rowKey.put((byte) shardId); rowKey.putLong(tableUuid); rowKey.put(contentKeyBytes); rowKey.flip(); return rowKey; }
[ "static", "ByteBuffer", "getRowKeyRaw", "(", "int", "shardId", ",", "long", "tableUuid", ",", "byte", "[", "]", "contentKeyBytes", ")", "{", "checkArgument", "(", "shardId", ">=", "0", "&&", "shardId", "<", "256", ")", ";", "// Assemble a single array which is \...
Constructs a row key when the row's shard ID is already known, which is rare. Generally this is used for range queries to construct the lower or upper bound for a query, so it doesn't necessarily need to produce a valid row key.
[ "Constructs", "a", "row", "key", "when", "the", "row", "s", "shard", "ID", "is", "already", "known", "which", "is", "rare", ".", "Generally", "this", "is", "used", "for", "range", "queries", "to", "construct", "the", "lower", "or", "upper", "bound", "for...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/RowKeyUtils.java#L82-L93
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/migrator/DistributedMigratorRangeMonitor.java
DistributedMigratorRangeMonitor.claimMigrationRangeTasks
private List<ClaimedTask> claimMigrationRangeTasks(int max) { try { Date claimTime = new Date(); List<ScanRangeTask> migrationRangeTasks = _workflow.claimScanRangeTasks(max, QUEUE_CLAIM_TTL); if (migrationRangeTasks.isEmpty()) { return ImmutableList.of(); } List<ClaimedTask> newlyClaimedTasks = Lists.newArrayListWithCapacity(migrationRangeTasks.size()); for (ScanRangeTask task : migrationRangeTasks) { final ClaimedTask claimedTask = new ClaimedTask(task, claimTime); // Record that the task is claimed locally boolean alreadyClaimed = _claimedTasks.putIfAbsent(task.getId(), claimedTask) != null; if (alreadyClaimed) { _log.warn("Workflow returned migration range task that is already claimed: {}", task); // Do not acknowledge the task, let it expire naturally. Eventually it should come up again // after the previous claim has been released. } else { _log.info("Claimed migration range task: {}", task); newlyClaimedTasks.add(claimedTask); // Schedule a follow-up to ensure the scanning service assigns it a thread // in a reasonable amount of time. _backgroundService.schedule( new Runnable() { @Override public void run() { validateClaimedTaskHasStarted(claimedTask); } }, CLAIM_START_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); } } return newlyClaimedTasks; } catch (Exception e) { _log.error("Failed to start next available migration range", e); return ImmutableList.of(); } }
java
private List<ClaimedTask> claimMigrationRangeTasks(int max) { try { Date claimTime = new Date(); List<ScanRangeTask> migrationRangeTasks = _workflow.claimScanRangeTasks(max, QUEUE_CLAIM_TTL); if (migrationRangeTasks.isEmpty()) { return ImmutableList.of(); } List<ClaimedTask> newlyClaimedTasks = Lists.newArrayListWithCapacity(migrationRangeTasks.size()); for (ScanRangeTask task : migrationRangeTasks) { final ClaimedTask claimedTask = new ClaimedTask(task, claimTime); // Record that the task is claimed locally boolean alreadyClaimed = _claimedTasks.putIfAbsent(task.getId(), claimedTask) != null; if (alreadyClaimed) { _log.warn("Workflow returned migration range task that is already claimed: {}", task); // Do not acknowledge the task, let it expire naturally. Eventually it should come up again // after the previous claim has been released. } else { _log.info("Claimed migration range task: {}", task); newlyClaimedTasks.add(claimedTask); // Schedule a follow-up to ensure the scanning service assigns it a thread // in a reasonable amount of time. _backgroundService.schedule( new Runnable() { @Override public void run() { validateClaimedTaskHasStarted(claimedTask); } }, CLAIM_START_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS); } } return newlyClaimedTasks; } catch (Exception e) { _log.error("Failed to start next available migration range", e); return ImmutableList.of(); } }
[ "private", "List", "<", "ClaimedTask", ">", "claimMigrationRangeTasks", "(", "int", "max", ")", "{", "try", "{", "Date", "claimTime", "=", "new", "Date", "(", ")", ";", "List", "<", "ScanRangeTask", ">", "migrationRangeTasks", "=", "_workflow", ".", "claimSc...
Claims migration range tasks that have been queued by the leader and are ready to scan.
[ "Claims", "migration", "range", "tasks", "that", "have", "been", "queued", "by", "the", "leader", "and", "are", "ready", "to", "scan", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/migrator/DistributedMigratorRangeMonitor.java#L141-L182
train
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/Storage.java
Storage.initializeGroup
static Storage initializeGroup(Collection<Storage> group) { List<Storage> sorted = Ordering.natural().immutableSortedCopy(group); Storage primary = sorted.get(0); // After sorting, the first storage in each group is the primary. if (!primary.isConsistent()) { // Dropping the primary drops the entire group (primary+mirrors), so 'primary' must be a mirror that // should have been dropped but was missed due to error conditions related to eventual consistency. return null; } for (Storage storage : sorted) { storage._group = sorted; } return primary; }
java
static Storage initializeGroup(Collection<Storage> group) { List<Storage> sorted = Ordering.natural().immutableSortedCopy(group); Storage primary = sorted.get(0); // After sorting, the first storage in each group is the primary. if (!primary.isConsistent()) { // Dropping the primary drops the entire group (primary+mirrors), so 'primary' must be a mirror that // should have been dropped but was missed due to error conditions related to eventual consistency. return null; } for (Storage storage : sorted) { storage._group = sorted; } return primary; }
[ "static", "Storage", "initializeGroup", "(", "Collection", "<", "Storage", ">", "group", ")", "{", "List", "<", "Storage", ">", "sorted", "=", "Ordering", ".", "natural", "(", ")", ".", "immutableSortedCopy", "(", "group", ")", ";", "Storage", "primary", "...
Post-construction initialization links all non-dropped members of group together. Returns the primary member of the group, other members are mirrors.
[ "Post", "-", "construction", "initialization", "links", "all", "non", "-", "dropped", "members", "of", "group", "together", ".", "Returns", "the", "primary", "member", "of", "the", "group", "other", "members", "are", "mirrors", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/Storage.java#L108-L120
train
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/Storage.java
Storage.getMoveTo
Storage getMoveTo() { String destUuid = get(MOVE_TO); return destUuid != null ? find(getMirrors(), destUuid) : null; }
java
Storage getMoveTo() { String destUuid = get(MOVE_TO); return destUuid != null ? find(getMirrors(), destUuid) : null; }
[ "Storage", "getMoveTo", "(", ")", "{", "String", "destUuid", "=", "get", "(", "MOVE_TO", ")", ";", "return", "destUuid", "!=", "null", "?", "find", "(", "getMirrors", "(", ")", ",", "destUuid", ")", ":", "null", ";", "}" ]
Move-related properties
[ "Move", "-", "related", "properties" ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/Storage.java#L206-L209
train
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/Storage.java
Storage.compareTo
@Override public int compareTo(Storage o) { return ComparisonChain.start() .compareTrueFirst(isConsistent(), o.isConsistent()) // Primaries *must* be consistent. .compareTrueFirst(_masterPrimary, o._masterPrimary) // Master primary sorts first .compare(o.getPromotionId(), getPromotionId(), TimeUUIDs.ordering().nullsLast()) // Facade primary sorts first .compare(_uuid, o._uuid) // Break ties in a way that's compatible with equals() .result(); }
java
@Override public int compareTo(Storage o) { return ComparisonChain.start() .compareTrueFirst(isConsistent(), o.isConsistent()) // Primaries *must* be consistent. .compareTrueFirst(_masterPrimary, o._masterPrimary) // Master primary sorts first .compare(o.getPromotionId(), getPromotionId(), TimeUUIDs.ordering().nullsLast()) // Facade primary sorts first .compare(_uuid, o._uuid) // Break ties in a way that's compatible with equals() .result(); }
[ "@", "Override", "public", "int", "compareTo", "(", "Storage", "o", ")", "{", "return", "ComparisonChain", ".", "start", "(", ")", ".", "compareTrueFirst", "(", "isConsistent", "(", ")", ",", "o", ".", "isConsistent", "(", ")", ")", "// Primaries *must* be c...
Storage objects sort such that primaries sort first, mirrors after.
[ "Storage", "objects", "sort", "such", "that", "primaries", "sort", "first", "mirrors", "after", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/Storage.java#L241-L249
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/DistributedScanRangeMonitor.java
DistributedScanRangeMonitor.renewClaimedTasks
private void renewClaimedTasks() { try { List<ClaimedTask> claimedTasks = ImmutableList.copyOf(_claimedTasks.values()); List<ScanRangeTask> tasks = Lists.newArrayList(); for (ClaimedTask claimedTask : claimedTasks) { if (claimedTask.isComplete()) { // Task is likely being removed in another thread. However, go ahead and remove it now // to allow other tasks to start sooner. _log.info("Complete claimed task found during renew: id={}", claimedTask.getTaskId()); _claimedTasks.remove(claimedTask.getTaskId()); } else if (claimedTask.isStarted()) { // Task has started and is not complete. Renew it. tasks.add(claimedTask.getTask()); } } if (!tasks.isEmpty()) { _scanWorkflow.renewScanRangeTasks(tasks, QUEUE_RENEW_TTL); for (ScanRangeTask task : tasks) { _log.info("Renewed scan range task: {}", task); } } } catch (Exception e) { _log.error("Failed to renew scan ranges", e); } }
java
private void renewClaimedTasks() { try { List<ClaimedTask> claimedTasks = ImmutableList.copyOf(_claimedTasks.values()); List<ScanRangeTask> tasks = Lists.newArrayList(); for (ClaimedTask claimedTask : claimedTasks) { if (claimedTask.isComplete()) { // Task is likely being removed in another thread. However, go ahead and remove it now // to allow other tasks to start sooner. _log.info("Complete claimed task found during renew: id={}", claimedTask.getTaskId()); _claimedTasks.remove(claimedTask.getTaskId()); } else if (claimedTask.isStarted()) { // Task has started and is not complete. Renew it. tasks.add(claimedTask.getTask()); } } if (!tasks.isEmpty()) { _scanWorkflow.renewScanRangeTasks(tasks, QUEUE_RENEW_TTL); for (ScanRangeTask task : tasks) { _log.info("Renewed scan range task: {}", task); } } } catch (Exception e) { _log.error("Failed to renew scan ranges", e); } }
[ "private", "void", "renewClaimedTasks", "(", ")", "{", "try", "{", "List", "<", "ClaimedTask", ">", "claimedTasks", "=", "ImmutableList", ".", "copyOf", "(", "_claimedTasks", ".", "values", "(", ")", ")", ";", "List", "<", "ScanRangeTask", ">", "tasks", "=...
Renews all claimed scan range tasks that have not been released. Unless this is called periodically the scan workflow will make this task available to be claimed again.
[ "Renews", "all", "claimed", "scan", "range", "tasks", "that", "have", "not", "been", "released", ".", "Unless", "this", "is", "called", "periodically", "the", "scan", "workflow", "will", "make", "this", "task", "available", "to", "be", "claimed", "again", "....
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/DistributedScanRangeMonitor.java#L225-L251
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/DistributedScanRangeMonitor.java
DistributedScanRangeMonitor.unclaimTask
private void unclaimTask(ClaimedTask claimedTask, boolean releaseTask) { _claimedTasks.remove(claimedTask.getTaskId()); claimedTask.setComplete(true); if (releaseTask) { try { _scanWorkflow.releaseScanRangeTask(claimedTask.getTask()); _log.info("Released scan range task: {}", claimedTask.getTask()); } catch (Exception e) { _log.error("Failed to release scan range", e); } } }
java
private void unclaimTask(ClaimedTask claimedTask, boolean releaseTask) { _claimedTasks.remove(claimedTask.getTaskId()); claimedTask.setComplete(true); if (releaseTask) { try { _scanWorkflow.releaseScanRangeTask(claimedTask.getTask()); _log.info("Released scan range task: {}", claimedTask.getTask()); } catch (Exception e) { _log.error("Failed to release scan range", e); } } }
[ "private", "void", "unclaimTask", "(", "ClaimedTask", "claimedTask", ",", "boolean", "releaseTask", ")", "{", "_claimedTasks", ".", "remove", "(", "claimedTask", ".", "getTaskId", "(", ")", ")", ";", "claimedTask", ".", "setComplete", "(", "true", ")", ";", ...
Unclaims a previously claimed task. Effectively this stops the renewing the task and, if releaseTask is true, removes the task permanently from the workflow queue.
[ "Unclaims", "a", "previously", "claimed", "task", ".", "Effectively", "this", "stops", "the", "renewing", "the", "task", "and", "if", "releaseTask", "is", "true", "removes", "the", "task", "permanently", "from", "the", "workflow", "queue", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/DistributedScanRangeMonitor.java#L257-L269
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/DistributedScanRangeMonitor.java
DistributedScanRangeMonitor.asyncRangeScan
private boolean asyncRangeScan(ScanRangeTask task) { final String scanId = task.getScanId(); final int taskId = task.getId(); final String placement = task.getPlacement(); final ScanRange range = task.getRange(); RangeScanUploaderResult result; try { // Verify that this range hasn't already been completed (protect against queue re-posts) ScanStatus status = _scanStatusDAO.getScanStatus(scanId); if (status.isCanceled()) { _log.info("Ignoring scan range from canceled task: [task={}]", task); return true; } ScanRangeStatus completedStatus = Iterables.getOnlyElement( Iterables.filter(status.getCompleteScanRanges(), new Predicate<ScanRangeStatus>() { @Override public boolean apply(ScanRangeStatus rangeStatus) { return rangeStatus.getTaskId() == taskId; } }), null); if (completedStatus != null) { _log.info("Ignoring duplicate post of completed scan range task: [task={}, completeTime={}]", task, completedStatus.getScanCompleteTime()); return true; } _log.info("Started scan range task: {}", task); _scanStatusDAO.setScanRangeTaskActive(scanId, taskId, new Date()); // Perform the range scan result = _rangeScanUploader.scanAndUpload(scanId, taskId, status.getOptions(), placement, range, status.getCompactionControlTime()); _log.info("Completed scan range task: {}", task); } catch (Throwable t) { _log.error("Scan range task failed: {}", task, t); result = RangeScanUploaderResult.failure(); } try { switch (result.getStatus()) { case SUCCESS: _scanStatusDAO.setScanRangeTaskComplete(scanId, taskId, new Date()); break; case FAILURE: _scanStatusDAO.setScanRangeTaskInactive(scanId, taskId); break; case REPSPLIT: // The portion of the range up to the resplit is what was completed. //noinspection ConstantConditions ScanRange completedRange = ScanRange.create(range.getFrom(), result.getResplitRange().getFrom()); _scanStatusDAO.setScanRangeTaskPartiallyComplete(scanId, taskId, completedRange, result.getResplitRange(), new Date()); break; } } catch (Throwable t) { _log.error("Failed to mark scan range result: [id={}, placement={}, range={}, result={}]", scanId, placement, range, result, t); // Since the scan result wasn't marked the leader will not have an accurate view of the state. return false; } return true; }
java
private boolean asyncRangeScan(ScanRangeTask task) { final String scanId = task.getScanId(); final int taskId = task.getId(); final String placement = task.getPlacement(); final ScanRange range = task.getRange(); RangeScanUploaderResult result; try { // Verify that this range hasn't already been completed (protect against queue re-posts) ScanStatus status = _scanStatusDAO.getScanStatus(scanId); if (status.isCanceled()) { _log.info("Ignoring scan range from canceled task: [task={}]", task); return true; } ScanRangeStatus completedStatus = Iterables.getOnlyElement( Iterables.filter(status.getCompleteScanRanges(), new Predicate<ScanRangeStatus>() { @Override public boolean apply(ScanRangeStatus rangeStatus) { return rangeStatus.getTaskId() == taskId; } }), null); if (completedStatus != null) { _log.info("Ignoring duplicate post of completed scan range task: [task={}, completeTime={}]", task, completedStatus.getScanCompleteTime()); return true; } _log.info("Started scan range task: {}", task); _scanStatusDAO.setScanRangeTaskActive(scanId, taskId, new Date()); // Perform the range scan result = _rangeScanUploader.scanAndUpload(scanId, taskId, status.getOptions(), placement, range, status.getCompactionControlTime()); _log.info("Completed scan range task: {}", task); } catch (Throwable t) { _log.error("Scan range task failed: {}", task, t); result = RangeScanUploaderResult.failure(); } try { switch (result.getStatus()) { case SUCCESS: _scanStatusDAO.setScanRangeTaskComplete(scanId, taskId, new Date()); break; case FAILURE: _scanStatusDAO.setScanRangeTaskInactive(scanId, taskId); break; case REPSPLIT: // The portion of the range up to the resplit is what was completed. //noinspection ConstantConditions ScanRange completedRange = ScanRange.create(range.getFrom(), result.getResplitRange().getFrom()); _scanStatusDAO.setScanRangeTaskPartiallyComplete(scanId, taskId, completedRange, result.getResplitRange(), new Date()); break; } } catch (Throwable t) { _log.error("Failed to mark scan range result: [id={}, placement={}, range={}, result={}]", scanId, placement, range, result, t); // Since the scan result wasn't marked the leader will not have an accurate view of the state. return false; } return true; }
[ "private", "boolean", "asyncRangeScan", "(", "ScanRangeTask", "task", ")", "{", "final", "String", "scanId", "=", "task", ".", "getScanId", "(", ")", ";", "final", "int", "taskId", "=", "task", ".", "getId", "(", ")", ";", "final", "String", "placement", ...
Performs a range scan and updates the global scan status with the scan result. @return true if the system state is consistent and the task can be released, false otherwise
[ "Performs", "a", "range", "scan", "and", "updates", "the", "global", "scan", "status", "with", "the", "scan", "result", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/DistributedScanRangeMonitor.java#L300-L367
train
bazaarvoice/emodb
auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/identity/AuthIdentityModification.java
AuthIdentityModification.getUpdatedRolesFrom
protected Set<String> getUpdatedRolesFrom(Set<String> roles) { Set<String> updatedRoles = Sets.newHashSet(roles); updatedRoles.addAll(_rolesAdded); updatedRoles.removeAll(_rolesRemoved); return updatedRoles; }
java
protected Set<String> getUpdatedRolesFrom(Set<String> roles) { Set<String> updatedRoles = Sets.newHashSet(roles); updatedRoles.addAll(_rolesAdded); updatedRoles.removeAll(_rolesRemoved); return updatedRoles; }
[ "protected", "Set", "<", "String", ">", "getUpdatedRolesFrom", "(", "Set", "<", "String", ">", "roles", ")", "{", "Set", "<", "String", ">", "updatedRoles", "=", "Sets", ".", "newHashSet", "(", "roles", ")", ";", "updatedRoles", ".", "addAll", "(", "_rol...
Helper method for subclasses which, given a set of roles, returns a new set of roles with all added and removed roles from this modification applied.
[ "Helper", "method", "for", "subclasses", "which", "given", "a", "set", "of", "roles", "returns", "a", "new", "set", "of", "roles", "with", "all", "added", "and", "removed", "roles", "from", "this", "modification", "applied", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/identity/AuthIdentityModification.java#L81-L86
train
bazaarvoice/emodb
common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/nio/BufferUtils.java
BufferUtils.getString
public static String getString(ByteBuffer buf, Charset encoding) { return getString(buf, 0, buf.remaining(), encoding); }
java
public static String getString(ByteBuffer buf, Charset encoding) { return getString(buf, 0, buf.remaining(), encoding); }
[ "public", "static", "String", "getString", "(", "ByteBuffer", "buf", ",", "Charset", "encoding", ")", "{", "return", "getString", "(", "buf", ",", "0", ",", "buf", ".", "remaining", "(", ")", ",", "encoding", ")", ";", "}" ]
Converts all remaining bytes in the buffer a String using the specified encoding. Does not move the buffer position.
[ "Converts", "all", "remaining", "bytes", "in", "the", "buffer", "a", "String", "using", "the", "specified", "encoding", ".", "Does", "not", "move", "the", "buffer", "position", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/nio/BufferUtils.java#L14-L16
train
bazaarvoice/emodb
common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/nio/BufferUtils.java
BufferUtils.getString
public static String getString(ByteBuffer buf, int offset, int length, Charset encoding) { buf = buf.duplicate(); buf.position(buf.position() + offset); if (buf.hasArray()) { return new String(buf.array(), buf.arrayOffset() + buf.position(), length, encoding); } else { byte[] bytes = new byte[length]; buf.get(bytes); return new String(bytes, encoding); } }
java
public static String getString(ByteBuffer buf, int offset, int length, Charset encoding) { buf = buf.duplicate(); buf.position(buf.position() + offset); if (buf.hasArray()) { return new String(buf.array(), buf.arrayOffset() + buf.position(), length, encoding); } else { byte[] bytes = new byte[length]; buf.get(bytes); return new String(bytes, encoding); } }
[ "public", "static", "String", "getString", "(", "ByteBuffer", "buf", ",", "int", "offset", ",", "int", "length", ",", "Charset", "encoding", ")", "{", "buf", "=", "buf", ".", "duplicate", "(", ")", ";", "buf", ".", "position", "(", "buf", ".", "positio...
Converts the specified number of bytes in the buffer and converts them to a String using the specified encoding. Does not move the buffer position.
[ "Converts", "the", "specified", "number", "of", "bytes", "in", "the", "buffer", "and", "converts", "them", "to", "a", "String", "using", "the", "specified", "encoding", ".", "Does", "not", "move", "the", "buffer", "position", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/nio/BufferUtils.java#L22-L32
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/throttling/AdHocThrottleManager.java
AdHocThrottleManager.addThrottle
public void addThrottle(AdHocThrottleEndpoint endpoint, AdHocThrottle throttle) { checkNotNull(throttle, "throttle"); String key = endpoint.toString(); try { // If the throttle is unlimited make sure it is not set, since the absence of a value indicates unlimited if (throttle.isUnlimited()) { _throttleMap.remove(key); } _throttleMap.set(key, throttle); } catch (Exception e) { throw Throwables.propagate(e); } }
java
public void addThrottle(AdHocThrottleEndpoint endpoint, AdHocThrottle throttle) { checkNotNull(throttle, "throttle"); String key = endpoint.toString(); try { // If the throttle is unlimited make sure it is not set, since the absence of a value indicates unlimited if (throttle.isUnlimited()) { _throttleMap.remove(key); } _throttleMap.set(key, throttle); } catch (Exception e) { throw Throwables.propagate(e); } }
[ "public", "void", "addThrottle", "(", "AdHocThrottleEndpoint", "endpoint", ",", "AdHocThrottle", "throttle", ")", "{", "checkNotNull", "(", "throttle", ",", "\"throttle\"", ")", ";", "String", "key", "=", "endpoint", ".", "toString", "(", ")", ";", "try", "{",...
Adds a throttle for an HTTP method and path.
[ "Adds", "a", "throttle", "for", "an", "HTTP", "method", "and", "path", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/throttling/AdHocThrottleManager.java#L34-L47
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/throttling/AdHocThrottleManager.java
AdHocThrottleManager.removeThrottle
public void removeThrottle(AdHocThrottleEndpoint endpoint) { try { _throttleMap.remove(endpoint.toString()); } catch (Exception e) { _log.warn("Failed to remove throttle for {} {}", endpoint.getMethod(), endpoint.getPath(), e); } }
java
public void removeThrottle(AdHocThrottleEndpoint endpoint) { try { _throttleMap.remove(endpoint.toString()); } catch (Exception e) { _log.warn("Failed to remove throttle for {} {}", endpoint.getMethod(), endpoint.getPath(), e); } }
[ "public", "void", "removeThrottle", "(", "AdHocThrottleEndpoint", "endpoint", ")", "{", "try", "{", "_throttleMap", ".", "remove", "(", "endpoint", ".", "toString", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "_log", ".", "warn", "...
Removes the throttle for an HTTP method and path. This effectively allows umlimited concurrency.
[ "Removes", "the", "throttle", "for", "an", "HTTP", "method", "and", "path", ".", "This", "effectively", "allows", "umlimited", "concurrency", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/throttling/AdHocThrottleManager.java#L52-L58
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/throttling/AdHocThrottleManager.java
AdHocThrottleManager.getThrottle
public AdHocThrottle getThrottle(AdHocThrottleEndpoint endpoint) { String key = endpoint.toString(); AdHocThrottle throttle = _throttleMap.get(key); if (throttle == null) { // No throttle set, allow unlimited throttle = AdHocThrottle.unlimitedInstance(); } else if (throttle.getExpiration().isBefore(Instant.now())) { // Throttle is expired; remove it and allow unlimited. There is a slight chance for a race condition // here but since throttles are rarely put in place this is extremely unlikely. To help avoid this // wait 24 hours before removing. if (throttle.getExpiration().isBefore(Instant.now().minus(Duration.ofDays(1)))) { try { _throttleMap.remove(key); } catch (Exception e) { _log.warn("Failed to remove expired throttle for {} {}", endpoint.getMethod(), endpoint.getPath(), e); } } throttle = AdHocThrottle.unlimitedInstance(); } return throttle; }
java
public AdHocThrottle getThrottle(AdHocThrottleEndpoint endpoint) { String key = endpoint.toString(); AdHocThrottle throttle = _throttleMap.get(key); if (throttle == null) { // No throttle set, allow unlimited throttle = AdHocThrottle.unlimitedInstance(); } else if (throttle.getExpiration().isBefore(Instant.now())) { // Throttle is expired; remove it and allow unlimited. There is a slight chance for a race condition // here but since throttles are rarely put in place this is extremely unlikely. To help avoid this // wait 24 hours before removing. if (throttle.getExpiration().isBefore(Instant.now().minus(Duration.ofDays(1)))) { try { _throttleMap.remove(key); } catch (Exception e) { _log.warn("Failed to remove expired throttle for {} {}", endpoint.getMethod(), endpoint.getPath(), e); } } throttle = AdHocThrottle.unlimitedInstance(); } return throttle; }
[ "public", "AdHocThrottle", "getThrottle", "(", "AdHocThrottleEndpoint", "endpoint", ")", "{", "String", "key", "=", "endpoint", ".", "toString", "(", ")", ";", "AdHocThrottle", "throttle", "=", "_throttleMap", ".", "get", "(", "key", ")", ";", "if", "(", "th...
Returns the throttle in effect for the given HTTP method and path. This method is always guaranteed to return a non-null throttle that is not expired. If no throttle has been configured or if the configured throttle has expired then it will return an unlimited throttle with an effectively infinite expiration date.
[ "Returns", "the", "throttle", "in", "effect", "for", "the", "given", "HTTP", "method", "and", "path", ".", "This", "method", "is", "always", "guaranteed", "to", "return", "a", "non", "-", "null", "throttle", "that", "is", "not", "expired", ".", "If", "no...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/throttling/AdHocThrottleManager.java#L65-L85
train
bazaarvoice/emodb
mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java
LocationUtil.getLocationType
public static LocationType getLocationType(URI location) { String scheme = location.getScheme(); if (EMODB_SCHEME.equals(scheme)) { // If the host matches the locator pattern then assume host discovery, otherwise it's a // direct URL to an EmoDB server if (LOCATOR_PATTERN.matcher(location.getHost()).matches()) { return LocationType.EMO_HOST_DISCOVERY; } else { return LocationType.EMO_URL; } } else if (STASH_SCHEME.equals(scheme)) { return LocationType.STASH; } throw new IllegalArgumentException("Invalid location: " + location); }
java
public static LocationType getLocationType(URI location) { String scheme = location.getScheme(); if (EMODB_SCHEME.equals(scheme)) { // If the host matches the locator pattern then assume host discovery, otherwise it's a // direct URL to an EmoDB server if (LOCATOR_PATTERN.matcher(location.getHost()).matches()) { return LocationType.EMO_HOST_DISCOVERY; } else { return LocationType.EMO_URL; } } else if (STASH_SCHEME.equals(scheme)) { return LocationType.STASH; } throw new IllegalArgumentException("Invalid location: " + location); }
[ "public", "static", "LocationType", "getLocationType", "(", "URI", "location", ")", "{", "String", "scheme", "=", "location", ".", "getScheme", "(", ")", ";", "if", "(", "EMODB_SCHEME", ".", "equals", "(", "scheme", ")", ")", "{", "// If the host matches the l...
Returns the location type from a location URI.
[ "Returns", "the", "location", "type", "from", "a", "location", "URI", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java#L103-L118
train
bazaarvoice/emodb
mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java
LocationUtil.getDataStoreIdentifier
public static String getDataStoreIdentifier(URI location, String apiKey) { checkArgument(getLocationType(location) != LocationType.STASH, "Stash locations do not have a data source ID"); UriBuilder uriBuilder = UriBuilder.fromUri(location) .userInfo(apiKey) .replacePath(null) .replaceQuery(null); if (getLocationType(location) == LocationType.EMO_HOST_DISCOVERY) { Optional<String> zkConnectionStringOverride = getZkConnectionStringOverride(location); if (zkConnectionStringOverride.isPresent()) { uriBuilder.queryParam(ZK_CONNECTION_STRING_PARAM, zkConnectionStringOverride.get()); } Optional<List<String>> hosts = getHostOverride(location); if (hosts.isPresent()) { for (String host : hosts.get()) { uriBuilder.queryParam(HOST_PARAM, host); } } } return uriBuilder.build().toString(); }
java
public static String getDataStoreIdentifier(URI location, String apiKey) { checkArgument(getLocationType(location) != LocationType.STASH, "Stash locations do not have a data source ID"); UriBuilder uriBuilder = UriBuilder.fromUri(location) .userInfo(apiKey) .replacePath(null) .replaceQuery(null); if (getLocationType(location) == LocationType.EMO_HOST_DISCOVERY) { Optional<String> zkConnectionStringOverride = getZkConnectionStringOverride(location); if (zkConnectionStringOverride.isPresent()) { uriBuilder.queryParam(ZK_CONNECTION_STRING_PARAM, zkConnectionStringOverride.get()); } Optional<List<String>> hosts = getHostOverride(location); if (hosts.isPresent()) { for (String host : hosts.get()) { uriBuilder.queryParam(HOST_PARAM, host); } } } return uriBuilder.build().toString(); }
[ "public", "static", "String", "getDataStoreIdentifier", "(", "URI", "location", ",", "String", "apiKey", ")", "{", "checkArgument", "(", "getLocationType", "(", "location", ")", "!=", "LocationType", ".", "STASH", ",", "\"Stash locations do not have a data source ID\"",...
Converts a location URI to a data source identifier.
[ "Converts", "a", "location", "URI", "to", "a", "data", "source", "identifier", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java#L127-L148
train
bazaarvoice/emodb
mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java
LocationUtil.getCuratorForLocation
public static Optional<CuratorFramework> getCuratorForLocation(URI location) { final String defaultConnectionString; final String namespace; if (getLocationType(location) != LocationType.EMO_HOST_DISCOVERY) { // Only host discovery may require ZooKeeper return Optional.absent(); } if (getHostOverride(location).isPresent()) { // Fixed host discovery doesn't require ZooKeeper return Optional.absent(); } Matcher matcher = getLocatorMatcher(location); checkArgument(matcher.matches(), "Invalid location: %s", location); if (matcher.group("universe") != null) { // Normal host discovery String universe = matcher.group("universe"); Region region = getRegion(Objects.firstNonNull(matcher.group("region"), DEFAULT_REGION)); namespace = format("%s/%s", universe, region); defaultConnectionString = DEFAULT_ZK_CONNECTION_STRING; } else { // Local host discovery; typically for developer testing namespace = null; defaultConnectionString = DEFAULT_LOCAL_ZK_CONNECTION_STRING; } String connectionString = getZkConnectionStringOverride(location).or(defaultConnectionString); CuratorFramework curator = CuratorFrameworkFactory.builder() .ensembleProvider(new ResolvingEnsembleProvider(connectionString)) .retryPolicy(new BoundedExponentialBackoffRetry(100, 1000, 10)) .threadFactory(new ThreadFactoryBuilder().setNameFormat("emo-zookeeper-%d").build()) .namespace(namespace) .build(); curator.start(); return Optional.of(curator); }
java
public static Optional<CuratorFramework> getCuratorForLocation(URI location) { final String defaultConnectionString; final String namespace; if (getLocationType(location) != LocationType.EMO_HOST_DISCOVERY) { // Only host discovery may require ZooKeeper return Optional.absent(); } if (getHostOverride(location).isPresent()) { // Fixed host discovery doesn't require ZooKeeper return Optional.absent(); } Matcher matcher = getLocatorMatcher(location); checkArgument(matcher.matches(), "Invalid location: %s", location); if (matcher.group("universe") != null) { // Normal host discovery String universe = matcher.group("universe"); Region region = getRegion(Objects.firstNonNull(matcher.group("region"), DEFAULT_REGION)); namespace = format("%s/%s", universe, region); defaultConnectionString = DEFAULT_ZK_CONNECTION_STRING; } else { // Local host discovery; typically for developer testing namespace = null; defaultConnectionString = DEFAULT_LOCAL_ZK_CONNECTION_STRING; } String connectionString = getZkConnectionStringOverride(location).or(defaultConnectionString); CuratorFramework curator = CuratorFrameworkFactory.builder() .ensembleProvider(new ResolvingEnsembleProvider(connectionString)) .retryPolicy(new BoundedExponentialBackoffRetry(100, 1000, 10)) .threadFactory(new ThreadFactoryBuilder().setNameFormat("emo-zookeeper-%d").build()) .namespace(namespace) .build(); curator.start(); return Optional.of(curator); }
[ "public", "static", "Optional", "<", "CuratorFramework", ">", "getCuratorForLocation", "(", "URI", "location", ")", "{", "final", "String", "defaultConnectionString", ";", "final", "String", "namespace", ";", "if", "(", "getLocationType", "(", "location", ")", "!=...
Returns a configured, started Curator for a given location, or absent if the location does not use host discovery.
[ "Returns", "a", "configured", "started", "Curator", "for", "a", "given", "location", "or", "absent", "if", "the", "location", "does", "not", "use", "host", "discovery", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java#L198-L239
train
bazaarvoice/emodb
mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java
LocationUtil.getClusterForLocation
public static String getClusterForLocation(URI location) { Matcher matcher = getLocatorMatcher(location); checkArgument(matcher.matches(), "Invalid location: %s", location); final String clusterPrefix; if (matcher.group("universe") != null) { clusterPrefix = matcher.group("universe"); } else { clusterPrefix = "local"; } String group = Objects.firstNonNull(matcher.group("group"), DEFAULT_GROUP); return format("%s_%s", clusterPrefix, group); }
java
public static String getClusterForLocation(URI location) { Matcher matcher = getLocatorMatcher(location); checkArgument(matcher.matches(), "Invalid location: %s", location); final String clusterPrefix; if (matcher.group("universe") != null) { clusterPrefix = matcher.group("universe"); } else { clusterPrefix = "local"; } String group = Objects.firstNonNull(matcher.group("group"), DEFAULT_GROUP); return format("%s_%s", clusterPrefix, group); }
[ "public", "static", "String", "getClusterForLocation", "(", "URI", "location", ")", "{", "Matcher", "matcher", "=", "getLocatorMatcher", "(", "location", ")", ";", "checkArgument", "(", "matcher", ".", "matches", "(", ")", ",", "\"Invalid location: %s\"", ",", "...
Returns the EmoDB cluster name associated with the given location.
[ "Returns", "the", "EmoDB", "cluster", "name", "associated", "with", "the", "given", "location", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java#L244-L258
train
bazaarvoice/emodb
mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java
LocationUtil.toLocation
public static URI toLocation(String source, String table) { // Verify the source is a valid EmoDB URI URI sourceUri = URI.create(source); return toLocation(sourceUri, table); }
java
public static URI toLocation(String source, String table) { // Verify the source is a valid EmoDB URI URI sourceUri = URI.create(source); return toLocation(sourceUri, table); }
[ "public", "static", "URI", "toLocation", "(", "String", "source", ",", "String", "table", ")", "{", "// Verify the source is a valid EmoDB URI", "URI", "sourceUri", "=", "URI", ".", "create", "(", "source", ")", ";", "return", "toLocation", "(", "sourceUri", ","...
Returns a location URI from a source and table name.
[ "Returns", "a", "location", "URI", "from", "a", "source", "and", "table", "name", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java#L300-L304
train
bazaarvoice/emodb
mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java
LocationUtil.toLocation
public static URI toLocation(URI sourceUri, String table) { getLocationType(sourceUri); // Raises an exception if the location type is invalid. return UriBuilder.fromUri(sourceUri).path(table).build(); }
java
public static URI toLocation(URI sourceUri, String table) { getLocationType(sourceUri); // Raises an exception if the location type is invalid. return UriBuilder.fromUri(sourceUri).path(table).build(); }
[ "public", "static", "URI", "toLocation", "(", "URI", "sourceUri", ",", "String", "table", ")", "{", "getLocationType", "(", "sourceUri", ")", ";", "// Raises an exception if the location type is invalid.", "return", "UriBuilder", ".", "fromUri", "(", "sourceUri", ")",...
Returns a Location URI from a source URI and table name.
[ "Returns", "a", "Location", "URI", "from", "a", "source", "URI", "and", "table", "name", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/LocationUtil.java#L309-L312
train
bazaarvoice/emodb
databus-client-common/src/main/java/com/bazaarvoice/emodb/databus/client/DatabusClient.java
DatabusClient.replayAsync
@Override public String replayAsync(String apiKey, String subscription) { return replayAsyncSince(apiKey, subscription, null); }
java
@Override public String replayAsync(String apiKey, String subscription) { return replayAsyncSince(apiKey, subscription, null); }
[ "@", "Override", "public", "String", "replayAsync", "(", "String", "apiKey", ",", "String", "subscription", ")", "{", "return", "replayAsyncSince", "(", "apiKey", ",", "subscription", ",", "null", ")", ";", "}" ]
Any server can initiate a replay request, no need for @PartitionKey
[ "Any", "server", "can", "initiate", "a", "replay", "request", "no", "need", "for" ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus-client-common/src/main/java/com/bazaarvoice/emodb/databus/client/DatabusClient.java#L289-L292
train
bazaarvoice/emodb
databus-client-common/src/main/java/com/bazaarvoice/emodb/databus/client/DatabusClient.java
DatabusClient.moveAsync
@Override public String moveAsync(String apiKey, String from, String to) { checkNotNull(from, "from"); checkNotNull(to, "to"); try { URI uri = _databus.clone() .segment("_move") .queryParam("from", from) .queryParam("to", to) .build(); Map<String, Object> response = _client.resource(uri) .header(ApiKeyRequest.AUTHENTICATION_HEADER, apiKey) .post(new TypeReference<Map<String, Object>>(){}, null); return response.get("id").toString(); } catch (EmoClientException e) { throw convertException(e); } }
java
@Override public String moveAsync(String apiKey, String from, String to) { checkNotNull(from, "from"); checkNotNull(to, "to"); try { URI uri = _databus.clone() .segment("_move") .queryParam("from", from) .queryParam("to", to) .build(); Map<String, Object> response = _client.resource(uri) .header(ApiKeyRequest.AUTHENTICATION_HEADER, apiKey) .post(new TypeReference<Map<String, Object>>(){}, null); return response.get("id").toString(); } catch (EmoClientException e) { throw convertException(e); } }
[ "@", "Override", "public", "String", "moveAsync", "(", "String", "apiKey", ",", "String", "from", ",", "String", "to", ")", "{", "checkNotNull", "(", "from", ",", "\"from\"", ")", ";", "checkNotNull", "(", "to", ",", "\"to\"", ")", ";", "try", "{", "UR...
Any server can initiate a move request, no need for @PartitionKey
[ "Any", "server", "can", "initiate", "a", "move", "request", "no", "need", "for" ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus-client-common/src/main/java/com/bazaarvoice/emodb/databus/client/DatabusClient.java#L332-L349
train
bazaarvoice/emodb
databus-client-common/src/main/java/com/bazaarvoice/emodb/databus/client/DatabusClient.java
DatabusClient.getMoveStatus
@Override public MoveSubscriptionStatus getMoveStatus(String apiKey, String reference) { checkNotNull(reference, "reference"); try { URI uri = _databus.clone() .segment("_move") .segment(reference) .build(); return _client.resource(uri) .header(ApiKeyRequest.AUTHENTICATION_HEADER, apiKey) .get(MoveSubscriptionStatus.class); } catch (EmoClientException e) { throw convertException(e); } }
java
@Override public MoveSubscriptionStatus getMoveStatus(String apiKey, String reference) { checkNotNull(reference, "reference"); try { URI uri = _databus.clone() .segment("_move") .segment(reference) .build(); return _client.resource(uri) .header(ApiKeyRequest.AUTHENTICATION_HEADER, apiKey) .get(MoveSubscriptionStatus.class); } catch (EmoClientException e) { throw convertException(e); } }
[ "@", "Override", "public", "MoveSubscriptionStatus", "getMoveStatus", "(", "String", "apiKey", ",", "String", "reference", ")", "{", "checkNotNull", "(", "reference", ",", "\"reference\"", ")", ";", "try", "{", "URI", "uri", "=", "_databus", ".", "clone", "(",...
Any server can get the move status, no need for @PartitionKey
[ "Any", "server", "can", "get", "the", "move", "status", "no", "need", "for" ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus-client-common/src/main/java/com/bazaarvoice/emodb/databus/client/DatabusClient.java#L352-L366
train
bazaarvoice/emodb
common/json/src/main/java/com/bazaarvoice/emodb/common/json/deferred/LazyJsonMap.java
LazyJsonMap.deserialized
private Map<String, Object> deserialized() { // Written as a loop to prevent the need for locking DeserializationState deserState; while (!(deserState = _deserState.get()).isDeserialized()) { Map<String, Object> deserialized = JsonHelper.fromJson(deserState.json, new TypeReference<Map<String, Object>>() {}); deserialized.putAll(deserState.overrides); DeserializationState newDeserState = new DeserializationState(deserialized); _deserState.compareAndSet(deserState, newDeserState); } return deserState.deserialized; }
java
private Map<String, Object> deserialized() { // Written as a loop to prevent the need for locking DeserializationState deserState; while (!(deserState = _deserState.get()).isDeserialized()) { Map<String, Object> deserialized = JsonHelper.fromJson(deserState.json, new TypeReference<Map<String, Object>>() {}); deserialized.putAll(deserState.overrides); DeserializationState newDeserState = new DeserializationState(deserialized); _deserState.compareAndSet(deserState, newDeserState); } return deserState.deserialized; }
[ "private", "Map", "<", "String", ",", "Object", ">", "deserialized", "(", ")", "{", "// Written as a loop to prevent the need for locking", "DeserializationState", "deserState", ";", "while", "(", "!", "(", "deserState", "=", "_deserState", ".", "get", "(", ")", "...
Returns the JSON as a Map. If necessary the JSON is converted to a Map as a result of this call.
[ "Returns", "the", "JSON", "as", "a", "Map", ".", "If", "necessary", "the", "JSON", "is", "converted", "to", "a", "Map", "as", "a", "result", "of", "this", "call", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/json/src/main/java/com/bazaarvoice/emodb/common/json/deferred/LazyJsonMap.java#L122-L132
train
bazaarvoice/emodb
common/json/src/main/java/com/bazaarvoice/emodb/common/json/deferred/LazyJsonMap.java
LazyJsonMap.put
@Override public Object put(String key, Object value) { DeserializationState deserializationState = _deserState.get(); if (deserializationState.isDeserialized()) { return deserializationState.deserialized.put(key, value); } return deserializationState.overrides.put(key, value); }
java
@Override public Object put(String key, Object value) { DeserializationState deserializationState = _deserState.get(); if (deserializationState.isDeserialized()) { return deserializationState.deserialized.put(key, value); } return deserializationState.overrides.put(key, value); }
[ "@", "Override", "public", "Object", "put", "(", "String", "key", ",", "Object", "value", ")", "{", "DeserializationState", "deserializationState", "=", "_deserState", ".", "get", "(", ")", ";", "if", "(", "deserializationState", ".", "isDeserialized", "(", ")...
For efficiency this method breaks the contract that the old value is returned. Otherwise common operations such as adding intrinsics and template attributes would require deserializing the object.
[ "For", "efficiency", "this", "method", "breaks", "the", "contract", "that", "the", "old", "value", "is", "returned", ".", "Otherwise", "common", "operations", "such", "as", "adding", "intrinsics", "and", "template", "attributes", "would", "require", "deserializing...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/json/src/main/java/com/bazaarvoice/emodb/common/json/deferred/LazyJsonMap.java#L183-L190
train
bazaarvoice/emodb
common/json/src/main/java/com/bazaarvoice/emodb/common/json/deferred/LazyJsonMap.java
LazyJsonMap.writeTo
void writeTo(JsonGenerator generator) throws IOException { DeserializationState deserState = _deserState.get(); if (deserState.isDeserialized()) { // Object has already been deserialized, use standard writer generator.writeObject(deserState.deserialized); return; } if (deserState.overrides.isEmpty()) { // With no overrides the most efficient action is to copy the original JSON verbatim. try { generator.writeRaw(deserState.json); return; } catch (UnsupportedOperationException e) { // Not all parsers are guaranteed to support this. If this is one then use the default // generator implementation which follows. } } ObjectCodec codec = generator.getCodec(); if (codec == null) { // No codec, defer to generator generator.writeObject(deserialized()); return; } JsonParser parser = codec.getFactory().createParser(deserState.json); checkState(parser.nextToken() == JsonToken.START_OBJECT, "JSON did not contain an object"); generator.writeStartObject(); // Typically the JSON string has been pre-sorted. Insert the overrides in order. If it turns out the // JSON wasn't sorted then we'll just dump the remaining overrides at the end; it's valid JSON // one way or the other. //noinspection unchecked Iterator<Map.Entry<String, Object>> sortedOverrides = ((Map<String, Object>) OrderedJson.ordered(deserState.overrides)).entrySet().iterator(); Map.Entry<String, Object> nextOverride = sortedOverrides.hasNext() ? sortedOverrides.next() : null; JsonToken token; while ((token = parser.nextToken()) != JsonToken.END_OBJECT) { assert token == JsonToken.FIELD_NAME; String field = parser.getText(); if (deserState.overrides.containsKey(field)) { // There's an override for this entry; skip it token = parser.nextToken(); if (token.isStructStart()) { parser.skipChildren(); } } else { // Write all overrides which sort prior to this field while (nextOverride != null && OrderedJson.KEY_COMPARATOR.compare(nextOverride.getKey(), field) < 0) { generator.writeFieldName(nextOverride.getKey()); generator.writeObject(nextOverride.getValue()); nextOverride = sortedOverrides.hasNext() ? sortedOverrides.next() : null; } // Copy this field name and value to the generator generator.copyCurrentStructure(parser); } // Both of the above operations leave the current token immediately prior to the next // field or the end object token. } // Write any remaining overrides while (nextOverride != null) { generator.writeFieldName(nextOverride.getKey()); generator.writeObject(nextOverride.getValue()); nextOverride = sortedOverrides.hasNext() ? sortedOverrides.next() : null; } generator.writeEndObject(); }
java
void writeTo(JsonGenerator generator) throws IOException { DeserializationState deserState = _deserState.get(); if (deserState.isDeserialized()) { // Object has already been deserialized, use standard writer generator.writeObject(deserState.deserialized); return; } if (deserState.overrides.isEmpty()) { // With no overrides the most efficient action is to copy the original JSON verbatim. try { generator.writeRaw(deserState.json); return; } catch (UnsupportedOperationException e) { // Not all parsers are guaranteed to support this. If this is one then use the default // generator implementation which follows. } } ObjectCodec codec = generator.getCodec(); if (codec == null) { // No codec, defer to generator generator.writeObject(deserialized()); return; } JsonParser parser = codec.getFactory().createParser(deserState.json); checkState(parser.nextToken() == JsonToken.START_OBJECT, "JSON did not contain an object"); generator.writeStartObject(); // Typically the JSON string has been pre-sorted. Insert the overrides in order. If it turns out the // JSON wasn't sorted then we'll just dump the remaining overrides at the end; it's valid JSON // one way or the other. //noinspection unchecked Iterator<Map.Entry<String, Object>> sortedOverrides = ((Map<String, Object>) OrderedJson.ordered(deserState.overrides)).entrySet().iterator(); Map.Entry<String, Object> nextOverride = sortedOverrides.hasNext() ? sortedOverrides.next() : null; JsonToken token; while ((token = parser.nextToken()) != JsonToken.END_OBJECT) { assert token == JsonToken.FIELD_NAME; String field = parser.getText(); if (deserState.overrides.containsKey(field)) { // There's an override for this entry; skip it token = parser.nextToken(); if (token.isStructStart()) { parser.skipChildren(); } } else { // Write all overrides which sort prior to this field while (nextOverride != null && OrderedJson.KEY_COMPARATOR.compare(nextOverride.getKey(), field) < 0) { generator.writeFieldName(nextOverride.getKey()); generator.writeObject(nextOverride.getValue()); nextOverride = sortedOverrides.hasNext() ? sortedOverrides.next() : null; } // Copy this field name and value to the generator generator.copyCurrentStructure(parser); } // Both of the above operations leave the current token immediately prior to the next // field or the end object token. } // Write any remaining overrides while (nextOverride != null) { generator.writeFieldName(nextOverride.getKey()); generator.writeObject(nextOverride.getValue()); nextOverride = sortedOverrides.hasNext() ? sortedOverrides.next() : null; } generator.writeEndObject(); }
[ "void", "writeTo", "(", "JsonGenerator", "generator", ")", "throws", "IOException", "{", "DeserializationState", "deserState", "=", "_deserState", ".", "get", "(", ")", ";", "if", "(", "deserState", ".", "isDeserialized", "(", ")", ")", "{", "// Object has alrea...
Writes this record to the provided generator in the most efficient manner possible in the current state.
[ "Writes", "this", "record", "to", "the", "provided", "generator", "in", "the", "most", "efficient", "manner", "possible", "in", "the", "current", "state", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/json/src/main/java/com/bazaarvoice/emodb/common/json/deferred/LazyJsonMap.java#L243-L318
train
bazaarvoice/emodb
event/src/main/java/com/bazaarvoice/emodb/event/dedup/DefaultDedupEventStore.java
DefaultDedupEventStore.getQueueReadOnly
private SortedQueue getQueueReadOnly(String queueName, Duration waitDuration) { DedupQueue service = getQueueReadWrite(queueName, waitDuration); if (service != null) { try { return service.getQueue(); } catch (ReadOnlyQueueException e) { // Fall through } } return _sortedQueueFactory.create(queueName, true, _queueDAO); }
java
private SortedQueue getQueueReadOnly(String queueName, Duration waitDuration) { DedupQueue service = getQueueReadWrite(queueName, waitDuration); if (service != null) { try { return service.getQueue(); } catch (ReadOnlyQueueException e) { // Fall through } } return _sortedQueueFactory.create(queueName, true, _queueDAO); }
[ "private", "SortedQueue", "getQueueReadOnly", "(", "String", "queueName", ",", "Duration", "waitDuration", ")", "{", "DedupQueue", "service", "=", "getQueueReadWrite", "(", "queueName", ",", "waitDuration", ")", ";", "if", "(", "service", "!=", "null", ")", "{",...
Returns the persistent sorted queue managed by this JVM, or a stub that supports only read-only operations if not managed by this JVM.
[ "Returns", "the", "persistent", "sorted", "queue", "managed", "by", "this", "JVM", "or", "a", "stub", "that", "supports", "only", "read", "-", "only", "operations", "if", "not", "managed", "by", "this", "JVM", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/event/dedup/DefaultDedupEventStore.java#L171-L181
train
bazaarvoice/emodb
uac-api/src/main/java/com/bazaarvoice/emodb/uac/api/UserAccessControlRequest.java
UserAccessControlRequest.setCustomRequestParameter
public void setCustomRequestParameter(String param, String... values) { _customRequestParameters.putAll(param, Arrays.asList(values)); }
java
public void setCustomRequestParameter(String param, String... values) { _customRequestParameters.putAll(param, Arrays.asList(values)); }
[ "public", "void", "setCustomRequestParameter", "(", "String", "param", ",", "String", "...", "values", ")", "{", "_customRequestParameters", ".", "putAll", "(", "param", ",", "Arrays", ".", "asList", "(", "values", ")", ")", ";", "}" ]
Sets custom request parameters. Custom parameters may include new features not yet officially supported or additional parameters to existing calls not intended for widespread use. As such this method is not typically used by most clients. Furthermore, adding additional parameters may cause the request to fail.
[ "Sets", "custom", "request", "parameters", ".", "Custom", "parameters", "may", "include", "new", "features", "not", "yet", "officially", "supported", "or", "additional", "parameters", "to", "existing", "calls", "not", "intended", "for", "widespread", "use", ".", ...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/uac-api/src/main/java/com/bazaarvoice/emodb/uac/api/UserAccessControlRequest.java#L21-L23
train
bazaarvoice/emodb
event/src/main/java/com/bazaarvoice/emodb/sortedq/core/SplitQueue.java
SplitQueue.remove
void remove(T obj) { _queue.remove(obj); if (_prioritize == obj) { _prioritize = null; } }
java
void remove(T obj) { _queue.remove(obj); if (_prioritize == obj) { _prioritize = null; } }
[ "void", "remove", "(", "T", "obj", ")", "{", "_queue", ".", "remove", "(", "obj", ")", ";", "if", "(", "_prioritize", "==", "obj", ")", "{", "_prioritize", "=", "null", ";", "}", "}" ]
Removes an object from the queue.
[ "Removes", "an", "object", "from", "the", "queue", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/sortedq/core/SplitQueue.java#L30-L35
train
bazaarvoice/emodb
event/src/main/java/com/bazaarvoice/emodb/sortedq/core/SplitQueue.java
SplitQueue.cycle
T cycle() { if (_prioritize != null) { return _prioritize; } if (!_queue.isEmpty()) { T first = _queue.keySet().iterator().next(); _queue.get(first); // Access the object so it gets bumped to the back of the queue. return first; } return null; }
java
T cycle() { if (_prioritize != null) { return _prioritize; } if (!_queue.isEmpty()) { T first = _queue.keySet().iterator().next(); _queue.get(first); // Access the object so it gets bumped to the back of the queue. return first; } return null; }
[ "T", "cycle", "(", ")", "{", "if", "(", "_prioritize", "!=", "null", ")", "{", "return", "_prioritize", ";", "}", "if", "(", "!", "_queue", ".", "isEmpty", "(", ")", ")", "{", "T", "first", "=", "_queue", ".", "keySet", "(", ")", ".", "iterator",...
Returns the head of the queue, then cycles it to the back of the queue.
[ "Returns", "the", "head", "of", "the", "queue", "then", "cycles", "it", "to", "the", "back", "of", "the", "queue", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/sortedq/core/SplitQueue.java#L47-L57
train
bazaarvoice/emodb
auth/auth-store/src/main/java/com/bazaarvoice/emodb/auth/permissions/TablePermissionManagerDAO.java
TablePermissionManagerDAO.createDelta
private Delta createDelta(PermissionUpdateRequest request) { MapDeltaBuilder builder = Deltas.mapBuilder(); for (String permissionString : request.getPermitted()) { builder.put("perm_" + validated(permissionString), 1); } for (String permissionString : request.getRevoked()) { builder.remove("perm_" + validated(permissionString)); } if (request.isRevokeRest()) { builder.removeRest(); } return builder.build(); }
java
private Delta createDelta(PermissionUpdateRequest request) { MapDeltaBuilder builder = Deltas.mapBuilder(); for (String permissionString : request.getPermitted()) { builder.put("perm_" + validated(permissionString), 1); } for (String permissionString : request.getRevoked()) { builder.remove("perm_" + validated(permissionString)); } if (request.isRevokeRest()) { builder.removeRest(); } return builder.build(); }
[ "private", "Delta", "createDelta", "(", "PermissionUpdateRequest", "request", ")", "{", "MapDeltaBuilder", "builder", "=", "Deltas", ".", "mapBuilder", "(", ")", ";", "for", "(", "String", "permissionString", ":", "request", ".", "getPermitted", "(", ")", ")", ...
Returns a delta constructed from this request, or null if the request contained no changes.
[ "Returns", "a", "delta", "constructed", "from", "this", "request", "or", "null", "if", "the", "request", "contained", "no", "changes", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-store/src/main/java/com/bazaarvoice/emodb/auth/permissions/TablePermissionManagerDAO.java#L93-L106
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/ScanPlan.java
ScanPlan.addTokenRangeToCurrentBatchForCluster
public void addTokenRangeToCurrentBatchForCluster(String cluster, String placement, Collection<ScanRange> ranges) { PlanBatch batch = _clusterTails.get(cluster); if (batch == null) { batch = new PlanBatch(); _clusterHeads.put(cluster, batch); _clusterTails.put(cluster, batch); } batch.addPlanItem(new PlanItem(placement, ranges)); }
java
public void addTokenRangeToCurrentBatchForCluster(String cluster, String placement, Collection<ScanRange> ranges) { PlanBatch batch = _clusterTails.get(cluster); if (batch == null) { batch = new PlanBatch(); _clusterHeads.put(cluster, batch); _clusterTails.put(cluster, batch); } batch.addPlanItem(new PlanItem(placement, ranges)); }
[ "public", "void", "addTokenRangeToCurrentBatchForCluster", "(", "String", "cluster", ",", "String", "placement", ",", "Collection", "<", "ScanRange", ">", "ranges", ")", "{", "PlanBatch", "batch", "=", "_clusterTails", ".", "get", "(", "cluster", ")", ";", "if",...
Adds a collection of scan ranges to the plan for a specific placement. The range collection should all belong to a single token range in the ring. @param cluster An identifier for the underlying resources used to scan the placement (typically an identifier for the Cassandra ring) @param placement The name of the placement @param ranges All non-overlapping sub-ranges from a single token range in the ring
[ "Adds", "a", "collection", "of", "scan", "ranges", "to", "the", "plan", "for", "a", "specific", "placement", ".", "The", "range", "collection", "should", "all", "belong", "to", "a", "single", "token", "range", "in", "the", "ring", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/ScanPlan.java#L81-L89
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/ScanPlan.java
ScanPlan.toScanStatus
public ScanStatus toScanStatus() { List<ScanRangeStatus> pendingRangeStatuses = Lists.newArrayList(); // Unique identifier for each scan task int taskId = 0; // Unique identifier for each batch int batchId = 0; // Unique identifier which identifies all tasks which affect the same resources in the ring int concurrencyId = 0; for (PlanBatch batch : _clusterHeads.values()) { // Within a single Cassandra ring each batch runs serially. This is enforced by blocking on the prior batch // from the same cluster. Integer lastBatchId = null; while (batch != null) { List<PlanItem> items = batch.getItems(); if (!items.isEmpty()) { Optional<Integer> blockingBatch = Optional.fromNullable(lastBatchId); for (PlanItem item : items) { String placement = item.getPlacement(); // If the token range is subdivided into more than one scan range then mark all sub-ranges with // the same unique concurrency ID. Optional<Integer> concurrency = item.getScanRanges().size() > 1 ? Optional.of(concurrencyId++) : Optional.<Integer>absent(); for (ScanRange scanRange : item.getScanRanges()) { pendingRangeStatuses.add(new ScanRangeStatus( taskId++, placement, scanRange, batchId, blockingBatch, concurrency)); } } lastBatchId = batchId; batchId++; } batch = batch.getNextBatch(); } } return new ScanStatus(_scanId, _options, false, false, new Date(), pendingRangeStatuses, ImmutableList.<ScanRangeStatus>of(), ImmutableList.<ScanRangeStatus>of()); }
java
public ScanStatus toScanStatus() { List<ScanRangeStatus> pendingRangeStatuses = Lists.newArrayList(); // Unique identifier for each scan task int taskId = 0; // Unique identifier for each batch int batchId = 0; // Unique identifier which identifies all tasks which affect the same resources in the ring int concurrencyId = 0; for (PlanBatch batch : _clusterHeads.values()) { // Within a single Cassandra ring each batch runs serially. This is enforced by blocking on the prior batch // from the same cluster. Integer lastBatchId = null; while (batch != null) { List<PlanItem> items = batch.getItems(); if (!items.isEmpty()) { Optional<Integer> blockingBatch = Optional.fromNullable(lastBatchId); for (PlanItem item : items) { String placement = item.getPlacement(); // If the token range is subdivided into more than one scan range then mark all sub-ranges with // the same unique concurrency ID. Optional<Integer> concurrency = item.getScanRanges().size() > 1 ? Optional.of(concurrencyId++) : Optional.<Integer>absent(); for (ScanRange scanRange : item.getScanRanges()) { pendingRangeStatuses.add(new ScanRangeStatus( taskId++, placement, scanRange, batchId, blockingBatch, concurrency)); } } lastBatchId = batchId; batchId++; } batch = batch.getNextBatch(); } } return new ScanStatus(_scanId, _options, false, false, new Date(), pendingRangeStatuses, ImmutableList.<ScanRangeStatus>of(), ImmutableList.<ScanRangeStatus>of()); }
[ "public", "ScanStatus", "toScanStatus", "(", ")", "{", "List", "<", "ScanRangeStatus", ">", "pendingRangeStatuses", "=", "Lists", ".", "newArrayList", "(", ")", ";", "// Unique identifier for each scan task", "int", "taskId", "=", "0", ";", "// Unique identifier for e...
Creates a ScanStatus based on the current state of the plan. All scan ranges are added as pending tasks.
[ "Creates", "a", "ScanStatus", "based", "on", "the", "current", "state", "of", "the", "plan", ".", "All", "scan", "ranges", "are", "added", "as", "pending", "tasks", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/control/ScanPlan.java#L94-L133
train
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/scanner/ScanDestination.java
ScanDestination.getDestinationWithSubpath
public ScanDestination getDestinationWithSubpath(String path) { if (isDiscarding()) { return discard(); } if (path == null) { return new ScanDestination(_uri); } return new ScanDestination(UriBuilder.fromUri(_uri).path(path).build()); }
java
public ScanDestination getDestinationWithSubpath(String path) { if (isDiscarding()) { return discard(); } if (path == null) { return new ScanDestination(_uri); } return new ScanDestination(UriBuilder.fromUri(_uri).path(path).build()); }
[ "public", "ScanDestination", "getDestinationWithSubpath", "(", "String", "path", ")", "{", "if", "(", "isDiscarding", "(", ")", ")", "{", "return", "discard", "(", ")", ";", "}", "if", "(", "path", "==", "null", ")", "{", "return", "new", "ScanDestination"...
Creates a new scan destination at the given path rooted at the current scan destination.
[ "Creates", "a", "new", "scan", "destination", "at", "the", "given", "path", "rooted", "at", "the", "current", "scan", "destination", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/scanner/ScanDestination.java#L60-L68
train
bazaarvoice/emodb
common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/CassandraConfiguration.java
CassandraConfiguration.performHostDiscovery
synchronized public void performHostDiscovery(MetricRegistry metricRegistry) { // Host discovery is not idempotent; only take action if it hasn't been performed. if (_hostDiscoveryPerformed) { return; } Iterable<String> hosts = null; // Statically configured list of seeds. if (_seeds != null) { hosts = Splitter.on(',').trimResults().split(_seeds); } // Perform ZooKeeper discovery to find the seeds. if (_zooKeeperServiceName != null) { checkState(hosts == null, "Too many host discovery mechanisms configured."); checkState(_curator != null, "ZooKeeper host discovery is configured but withZooKeeperHostDiscovery() was not called."); try (HostDiscovery hostDiscovery = new ZooKeeperHostDiscovery(_curator, _zooKeeperServiceName, metricRegistry)) { List<String> hostList = Lists.newArrayList(); for (ServiceEndPoint endPoint : hostDiscovery.getHosts()) { // The host:port is in the end point ID hostList.add(endPoint.getId()); // The partitioner class name is in the json-encoded end point payload if (_partitioner == null && endPoint.getPayload() != null) { JsonNode payload = JsonHelper.fromJson(endPoint.getPayload(), JsonNode.class); String partitioner = payload.path("partitioner").textValue(); if (partitioner != null) { _partitioner = CassandraPartitioner.fromClass(partitioner); } } } hosts = hostList; } catch (IOException ex) { // suppress any IOExceptions that might result from closing our ZooKeeperHostDiscovery } } checkState(hosts != null, "No Cassandra host discovery mechanisms are configured."); //noinspection ConstantConditions checkState(!Iterables.isEmpty(hosts), "Unable to discover any Cassandra seed instances."); checkState(_partitioner != null, "Cassandra partitioner not configured or discoverable."); _seeds = Joiner.on(',').join(hosts); _hostDiscoveryPerformed = true; }
java
synchronized public void performHostDiscovery(MetricRegistry metricRegistry) { // Host discovery is not idempotent; only take action if it hasn't been performed. if (_hostDiscoveryPerformed) { return; } Iterable<String> hosts = null; // Statically configured list of seeds. if (_seeds != null) { hosts = Splitter.on(',').trimResults().split(_seeds); } // Perform ZooKeeper discovery to find the seeds. if (_zooKeeperServiceName != null) { checkState(hosts == null, "Too many host discovery mechanisms configured."); checkState(_curator != null, "ZooKeeper host discovery is configured but withZooKeeperHostDiscovery() was not called."); try (HostDiscovery hostDiscovery = new ZooKeeperHostDiscovery(_curator, _zooKeeperServiceName, metricRegistry)) { List<String> hostList = Lists.newArrayList(); for (ServiceEndPoint endPoint : hostDiscovery.getHosts()) { // The host:port is in the end point ID hostList.add(endPoint.getId()); // The partitioner class name is in the json-encoded end point payload if (_partitioner == null && endPoint.getPayload() != null) { JsonNode payload = JsonHelper.fromJson(endPoint.getPayload(), JsonNode.class); String partitioner = payload.path("partitioner").textValue(); if (partitioner != null) { _partitioner = CassandraPartitioner.fromClass(partitioner); } } } hosts = hostList; } catch (IOException ex) { // suppress any IOExceptions that might result from closing our ZooKeeperHostDiscovery } } checkState(hosts != null, "No Cassandra host discovery mechanisms are configured."); //noinspection ConstantConditions checkState(!Iterables.isEmpty(hosts), "Unable to discover any Cassandra seed instances."); checkState(_partitioner != null, "Cassandra partitioner not configured or discoverable."); _seeds = Joiner.on(',').join(hosts); _hostDiscoveryPerformed = true; }
[ "synchronized", "public", "void", "performHostDiscovery", "(", "MetricRegistry", "metricRegistry", ")", "{", "// Host discovery is not idempotent; only take action if it hasn't been performed.", "if", "(", "_hostDiscoveryPerformed", ")", "{", "return", ";", "}", "Iterable", "<"...
Discover Cassandra seeds and partitioner, if not statically configured.
[ "Discover", "Cassandra", "seeds", "and", "partitioner", "if", "not", "statically", "configured", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/CassandraConfiguration.java#L413-L459
train
bazaarvoice/emodb
auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/jersey/AuthenticationResourceFilter.java
AuthenticationResourceFilter.setJettyAuthentication
private void setJettyAuthentication(Subject subject) { // In unit test environments there may not be a current connection. If any nulls are encountered // then, by definition, there is no container to update. HttpConnection connection = HttpConnection.getCurrentConnection(); if (connection == null) { return; } Request jettyRequest = connection.getHttpChannel().getRequest(); if (jettyRequest == null) { return; } // This cast down is safe; subject is always created with this type of principal PrincipalWithRoles principal = (PrincipalWithRoles) subject.getPrincipal(); UserIdentity identity = principal.toUserIdentity(); jettyRequest.setAuthentication(new UserAuthentication(SecurityContext.BASIC_AUTH, identity)); }
java
private void setJettyAuthentication(Subject subject) { // In unit test environments there may not be a current connection. If any nulls are encountered // then, by definition, there is no container to update. HttpConnection connection = HttpConnection.getCurrentConnection(); if (connection == null) { return; } Request jettyRequest = connection.getHttpChannel().getRequest(); if (jettyRequest == null) { return; } // This cast down is safe; subject is always created with this type of principal PrincipalWithRoles principal = (PrincipalWithRoles) subject.getPrincipal(); UserIdentity identity = principal.toUserIdentity(); jettyRequest.setAuthentication(new UserAuthentication(SecurityContext.BASIC_AUTH, identity)); }
[ "private", "void", "setJettyAuthentication", "(", "Subject", "subject", ")", "{", "// In unit test environments there may not be a current connection. If any nulls are encountered", "// then, by definition, there is no container to update.", "HttpConnection", "connection", "=", "HttpConne...
Certain aspects of the container, such as logging, need the authentication information to behave properly. This method updates the request with the necessary objects to recognize the authenticated user.
[ "Certain", "aspects", "of", "the", "container", "such", "as", "logging", "need", "the", "authentication", "information", "to", "behave", "properly", ".", "This", "method", "updates", "the", "request", "with", "the", "necessary", "objects", "to", "recognize", "th...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/jersey/AuthenticationResourceFilter.java#L79-L96
train
bazaarvoice/emodb
auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/util/CredentialEncrypter.java
CredentialEncrypter.isPotentiallyEncryptedBytes
public static boolean isPotentiallyEncryptedBytes(byte[] bytes) { checkNotNull(bytes, "bytes"); // The number of bytes is a non-zero multiple of the block size. try { return bytes.length != 0 && bytes.length % Cipher.getInstance(CIPHER).getBlockSize() == 0; } catch (Throwable t) { // This shouldn't happen since AES is supported by all JVMs. throw Throwables.propagate(t); } }
java
public static boolean isPotentiallyEncryptedBytes(byte[] bytes) { checkNotNull(bytes, "bytes"); // The number of bytes is a non-zero multiple of the block size. try { return bytes.length != 0 && bytes.length % Cipher.getInstance(CIPHER).getBlockSize() == 0; } catch (Throwable t) { // This shouldn't happen since AES is supported by all JVMs. throw Throwables.propagate(t); } }
[ "public", "static", "boolean", "isPotentiallyEncryptedBytes", "(", "byte", "[", "]", "bytes", ")", "{", "checkNotNull", "(", "bytes", ",", "\"bytes\"", ")", ";", "// The number of bytes is a non-zero multiple of the block size.", "try", "{", "return", "bytes", ".", "l...
Returns true if the provided bytes _could_ be encrypted credentials, even if they can't be decrypted by a specific instance.
[ "Returns", "true", "if", "the", "provided", "bytes", "_could_", "be", "encrypted", "credentials", "even", "if", "they", "can", "t", "be", "decrypted", "by", "a", "specific", "instance", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/util/CredentialEncrypter.java#L148-L158
train
bazaarvoice/emodb
auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/util/CredentialEncrypter.java
CredentialEncrypter.isPotentiallyEncryptedString
public static boolean isPotentiallyEncryptedString(String string) { checkNotNull(string, "string"); // String is base64 encoded byte[] encryptedBytes; try { encryptedBytes = BaseEncoding.base64().omitPadding().decode(string); } catch (IllegalArgumentException e) { return false; } return isPotentiallyEncryptedBytes(encryptedBytes); }
java
public static boolean isPotentiallyEncryptedString(String string) { checkNotNull(string, "string"); // String is base64 encoded byte[] encryptedBytes; try { encryptedBytes = BaseEncoding.base64().omitPadding().decode(string); } catch (IllegalArgumentException e) { return false; } return isPotentiallyEncryptedBytes(encryptedBytes); }
[ "public", "static", "boolean", "isPotentiallyEncryptedString", "(", "String", "string", ")", "{", "checkNotNull", "(", "string", ",", "\"string\"", ")", ";", "// String is base64 encoded", "byte", "[", "]", "encryptedBytes", ";", "try", "{", "encryptedBytes", "=", ...
Returns true if the provided String _could_ be encrypted credentials, even if it can't be decrypted by a specific instance.
[ "Returns", "true", "if", "the", "provided", "String", "_could_", "be", "encrypted", "credentials", "even", "if", "it", "can", "t", "be", "decrypted", "by", "a", "specific", "instance", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/util/CredentialEncrypter.java#L164-L176
train
bazaarvoice/emodb
common/zookeeper/src/main/java/com/bazaarvoice/emodb/common/zookeeper/leader/PartitionedLeaderService.java
PartitionedLeaderService.getPartitionLeaderServices
public List<LeaderService> getPartitionLeaderServices() { return _partitionLeaders.stream() .map(PartitionLeader::getLeaderService) .collect(Collectors.toList()); }
java
public List<LeaderService> getPartitionLeaderServices() { return _partitionLeaders.stream() .map(PartitionLeader::getLeaderService) .collect(Collectors.toList()); }
[ "public", "List", "<", "LeaderService", ">", "getPartitionLeaderServices", "(", ")", "{", "return", "_partitionLeaders", ".", "stream", "(", ")", ".", "map", "(", "PartitionLeader", "::", "getLeaderService", ")", ".", "collect", "(", "Collectors", ".", "toList",...
Returns the underlying leader services for each partition. The services are guaranteed to be returned ordered by partition number.
[ "Returns", "the", "underlying", "leader", "services", "for", "each", "partition", ".", "The", "services", "are", "guaranteed", "to", "be", "returned", "ordered", "by", "partition", "number", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/zookeeper/src/main/java/com/bazaarvoice/emodb/common/zookeeper/leader/PartitionedLeaderService.java#L137-L141
train
bazaarvoice/emodb
sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/AstyanaxDataReaderDAO.java
AstyanaxDataReaderDAO.decodeRows
private Iterator<Record> decodeRows(Iterator<Row<ByteBuffer, UUID>> iter, final AstyanaxTable table, final int largeRowThreshold, final ReadConsistency consistency) { // Avoiding pinning multiple decoded rows into memory at once. return Iterators.transform(iter, new Function<Row<ByteBuffer, UUID>, Record>() { @Override public Record apply(Row<ByteBuffer, UUID> row) { // Convert the results into a Record object, lazily fetching the rest of the columns as necessary. String key = AstyanaxStorage.getContentKey(row.getRawKey()); return newRecord(new Key(table, key), row.getRawKey(), row.getColumns(), largeRowThreshold, consistency, null); } }); }
java
private Iterator<Record> decodeRows(Iterator<Row<ByteBuffer, UUID>> iter, final AstyanaxTable table, final int largeRowThreshold, final ReadConsistency consistency) { // Avoiding pinning multiple decoded rows into memory at once. return Iterators.transform(iter, new Function<Row<ByteBuffer, UUID>, Record>() { @Override public Record apply(Row<ByteBuffer, UUID> row) { // Convert the results into a Record object, lazily fetching the rest of the columns as necessary. String key = AstyanaxStorage.getContentKey(row.getRawKey()); return newRecord(new Key(table, key), row.getRawKey(), row.getColumns(), largeRowThreshold, consistency, null); } }); }
[ "private", "Iterator", "<", "Record", ">", "decodeRows", "(", "Iterator", "<", "Row", "<", "ByteBuffer", ",", "UUID", ">", ">", "iter", ",", "final", "AstyanaxTable", "table", ",", "final", "int", "largeRowThreshold", ",", "final", "ReadConsistency", "consiste...
Decodes rows returned by scanning a table.
[ "Decodes", "rows", "returned", "by", "scanning", "a", "table", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/astyanax/AstyanaxDataReaderDAO.java#L1024-L1035
train
bazaarvoice/emodb
auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/jersey/AuthResourceFilterFactory.java
AuthResourceFilterFactory.createSubstitutionMap
private Map<String,Function<HttpRequestContext, String>> createSubstitutionMap(String[] permissions, AbstractMethod am) { Map<String, Function<HttpRequestContext, String>> map = Maps.newLinkedHashMap(); for (String permission : permissions) { Matcher matcher = SUBSTITUTION_MATCHER.matcher(permission); while (matcher.find()) { String match = matcher.group(); if (map.containsKey(match)) { continue; } String param = matcher.group("param"); Function<HttpRequestContext, String> substitution; if (param.startsWith("?")) { substitution = createQuerySubstitution(param.substring(1)); } else { substitution = createPathSubstitution(param, am); } map.put(match, substitution); } } return map; }
java
private Map<String,Function<HttpRequestContext, String>> createSubstitutionMap(String[] permissions, AbstractMethod am) { Map<String, Function<HttpRequestContext, String>> map = Maps.newLinkedHashMap(); for (String permission : permissions) { Matcher matcher = SUBSTITUTION_MATCHER.matcher(permission); while (matcher.find()) { String match = matcher.group(); if (map.containsKey(match)) { continue; } String param = matcher.group("param"); Function<HttpRequestContext, String> substitution; if (param.startsWith("?")) { substitution = createQuerySubstitution(param.substring(1)); } else { substitution = createPathSubstitution(param, am); } map.put(match, substitution); } } return map; }
[ "private", "Map", "<", "String", ",", "Function", "<", "HttpRequestContext", ",", "String", ">", ">", "createSubstitutionMap", "(", "String", "[", "]", "permissions", ",", "AbstractMethod", "am", ")", "{", "Map", "<", "String", ",", "Function", "<", "HttpReq...
Returns a mapping from permissions found in the annotations to functions which can perform any necessary substitutions based on actual values in the request.
[ "Returns", "a", "mapping", "from", "permissions", "found", "in", "the", "annotations", "to", "functions", "which", "can", "perform", "any", "necessary", "substitutions", "based", "on", "actual", "values", "in", "the", "request", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/auth/auth-core/src/main/java/com/bazaarvoice/emodb/auth/jersey/AuthResourceFilterFactory.java#L98-L123
train
bazaarvoice/emodb
event/src/main/java/com/bazaarvoice/emodb/event/core/DefaultClaimStore.java
DefaultClaimStore.removeEmptyClaimSets
private synchronized void removeEmptyClaimSets() { Iterables.removeIf(_map.values(), new Predicate<Handle>() { @Override public boolean apply(Handle handle) { handle.getClaimSet().pump(); return handle.getRefCount().get() == 0 && handle.getClaimSet().size() == 0; } }); }
java
private synchronized void removeEmptyClaimSets() { Iterables.removeIf(_map.values(), new Predicate<Handle>() { @Override public boolean apply(Handle handle) { handle.getClaimSet().pump(); return handle.getRefCount().get() == 0 && handle.getClaimSet().size() == 0; } }); }
[ "private", "synchronized", "void", "removeEmptyClaimSets", "(", ")", "{", "Iterables", ".", "removeIf", "(", "_map", ".", "values", "(", ")", ",", "new", "Predicate", "<", "Handle", ">", "(", ")", "{", "@", "Override", "public", "boolean", "apply", "(", ...
Cleans up old claim sets for subscriptions that have become inactive. Ensures the map of claim sets doesn't grow forever.
[ "Cleans", "up", "old", "claim", "sets", "for", "subscriptions", "that", "have", "become", "inactive", ".", "Ensures", "the", "map", "of", "claim", "sets", "doesn", "t", "grow", "forever", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/event/core/DefaultClaimStore.java#L111-L119
train
bazaarvoice/emodb
mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java
EmoSerDe.getObjectInspectorForType
private ObjectInspector getObjectInspectorForType(TypeInfo type) throws SerDeException { switch (type.getCategory()) { case PRIMITIVE: PrimitiveTypeInfo primitiveType = (PrimitiveTypeInfo) type; if (isSupportedPrimitive(primitiveType)) { return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(primitiveType.getPrimitiveCategory()); } break; case STRUCT: StructTypeInfo structType = (StructTypeInfo) type; List<ObjectInspector> structInspectors = Lists.newArrayListWithCapacity(structType.getAllStructFieldTypeInfos().size()); for (TypeInfo fieldType : structType.getAllStructFieldTypeInfos()) { structInspectors.add(getObjectInspectorForType(fieldType)); } return ObjectInspectorFactory.getStandardStructObjectInspector(structType.getAllStructFieldNames(), structInspectors); case MAP: MapTypeInfo mapType = (MapTypeInfo) type; return ObjectInspectorFactory.getStandardMapObjectInspector( getObjectInspectorForType(mapType.getMapKeyTypeInfo()), getObjectInspectorForType(mapType.getMapValueTypeInfo())); case LIST: ListTypeInfo listType = (ListTypeInfo) type; return ObjectInspectorFactory.getStandardListObjectInspector(getObjectInspectorForType(listType.getListElementTypeInfo())); case UNION: UnionTypeInfo unionType = (UnionTypeInfo) type; List<ObjectInspector> unionInspectors = Lists.newArrayListWithCapacity(unionType.getAllUnionObjectTypeInfos().size()); for (TypeInfo fieldType : unionType.getAllUnionObjectTypeInfos()) { unionInspectors.add(getObjectInspectorForType(fieldType)); } return ObjectInspectorFactory.getStandardUnionObjectInspector(unionInspectors); } // Should be unreachable throw new SerDeException("Unsupported type: " + type); }
java
private ObjectInspector getObjectInspectorForType(TypeInfo type) throws SerDeException { switch (type.getCategory()) { case PRIMITIVE: PrimitiveTypeInfo primitiveType = (PrimitiveTypeInfo) type; if (isSupportedPrimitive(primitiveType)) { return PrimitiveObjectInspectorFactory.getPrimitiveJavaObjectInspector(primitiveType.getPrimitiveCategory()); } break; case STRUCT: StructTypeInfo structType = (StructTypeInfo) type; List<ObjectInspector> structInspectors = Lists.newArrayListWithCapacity(structType.getAllStructFieldTypeInfos().size()); for (TypeInfo fieldType : structType.getAllStructFieldTypeInfos()) { structInspectors.add(getObjectInspectorForType(fieldType)); } return ObjectInspectorFactory.getStandardStructObjectInspector(structType.getAllStructFieldNames(), structInspectors); case MAP: MapTypeInfo mapType = (MapTypeInfo) type; return ObjectInspectorFactory.getStandardMapObjectInspector( getObjectInspectorForType(mapType.getMapKeyTypeInfo()), getObjectInspectorForType(mapType.getMapValueTypeInfo())); case LIST: ListTypeInfo listType = (ListTypeInfo) type; return ObjectInspectorFactory.getStandardListObjectInspector(getObjectInspectorForType(listType.getListElementTypeInfo())); case UNION: UnionTypeInfo unionType = (UnionTypeInfo) type; List<ObjectInspector> unionInspectors = Lists.newArrayListWithCapacity(unionType.getAllUnionObjectTypeInfos().size()); for (TypeInfo fieldType : unionType.getAllUnionObjectTypeInfos()) { unionInspectors.add(getObjectInspectorForType(fieldType)); } return ObjectInspectorFactory.getStandardUnionObjectInspector(unionInspectors); } // Should be unreachable throw new SerDeException("Unsupported type: " + type); }
[ "private", "ObjectInspector", "getObjectInspectorForType", "(", "TypeInfo", "type", ")", "throws", "SerDeException", "{", "switch", "(", "type", ".", "getCategory", "(", ")", ")", "{", "case", "PRIMITIVE", ":", "PrimitiveTypeInfo", "primitiveType", "=", "(", "Prim...
Returns the associated ObjectInspector for a type. This most delegates the to Hive java implementations but filters out primitives not supported by EmoDB.
[ "Returns", "the", "associated", "ObjectInspector", "for", "a", "type", ".", "This", "most", "delegates", "the", "to", "Hive", "java", "implementations", "but", "filters", "out", "primitives", "not", "supported", "by", "EmoDB", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java#L105-L139
train
bazaarvoice/emodb
mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java
EmoSerDe.getRawValue
private Object getRawValue(String columnName, Map<String, Object> content) throws ColumnNotFoundException { String field = columnName; Object value = content; while (field != null) { // If at any point in the path a null is encountered stop if (value == null) { throw new ColumnNotFoundException(); } // With the exception of leaf values the intermediate values must always be Maps. if (!(value instanceof Map)) { throw new ColumnNotFoundException(); } //noinspection unchecked Map<String, Object> map = (Map<String, Object>) value; String nextField = null; int separator = field.indexOf('/'); if (separator != -1) { nextField = field.substring(separator + 1); field = field.substring(0, separator); } // Typically Hive column names are all lower case. Because of this we can't just look up the key directly; // we need to look it up in a case-insensitive fashion. For efficiency first try it as-is. boolean found = false; if (map.containsKey(field)) { value = map.get(field); found = true; } else { // Look for the key case-insensitively for (Iterator<String> iter = map.keySet().iterator(); !found && iter.hasNext(); ) { String key = iter.next(); if (key.equalsIgnoreCase(field)) { value = map.get(key); found = true; } } } if (!found) { throw new ColumnNotFoundException(); } field = nextField; } return value; }
java
private Object getRawValue(String columnName, Map<String, Object> content) throws ColumnNotFoundException { String field = columnName; Object value = content; while (field != null) { // If at any point in the path a null is encountered stop if (value == null) { throw new ColumnNotFoundException(); } // With the exception of leaf values the intermediate values must always be Maps. if (!(value instanceof Map)) { throw new ColumnNotFoundException(); } //noinspection unchecked Map<String, Object> map = (Map<String, Object>) value; String nextField = null; int separator = field.indexOf('/'); if (separator != -1) { nextField = field.substring(separator + 1); field = field.substring(0, separator); } // Typically Hive column names are all lower case. Because of this we can't just look up the key directly; // we need to look it up in a case-insensitive fashion. For efficiency first try it as-is. boolean found = false; if (map.containsKey(field)) { value = map.get(field); found = true; } else { // Look for the key case-insensitively for (Iterator<String> iter = map.keySet().iterator(); !found && iter.hasNext(); ) { String key = iter.next(); if (key.equalsIgnoreCase(field)) { value = map.get(key); found = true; } } } if (!found) { throw new ColumnNotFoundException(); } field = nextField; } return value; }
[ "private", "Object", "getRawValue", "(", "String", "columnName", ",", "Map", "<", "String", ",", "Object", ">", "content", ")", "throws", "ColumnNotFoundException", "{", "String", "field", "=", "columnName", ";", "Object", "value", "=", "content", ";", "while"...
Returns the raw value for a given Map. If the value was found is and is null then null is returned. If no value is present then ColumnNotFoundException is thrown. @throws ColumnNotFoundException The column was not found in the map
[ "Returns", "the", "raw", "value", "for", "a", "given", "Map", ".", "If", "the", "value", "was", "found", "is", "and", "is", "null", "then", "null", "is", "returned", ".", "If", "no", "value", "is", "present", "then", "ColumnNotFoundException", "is", "thr...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java#L222-L273
train
bazaarvoice/emodb
mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java
EmoSerDe.deserialize
private Object deserialize(TypeInfo type, Object rawValue) throws SerDeException { Object value = null; if (rawValue != null) { switch (type.getCategory()) { case PRIMITIVE: value = deserializePrimitive((PrimitiveTypeInfo) type, rawValue); break; case STRUCT: value = deserializeStruct((StructTypeInfo) type, rawValue); break; case MAP: value = deserializeMap((MapTypeInfo) type, rawValue); break; case LIST: value = deserializeList((ListTypeInfo) type, rawValue); break; case UNION: value = deserializeUnion((UnionTypeInfo) type, rawValue); break; } } return value; }
java
private Object deserialize(TypeInfo type, Object rawValue) throws SerDeException { Object value = null; if (rawValue != null) { switch (type.getCategory()) { case PRIMITIVE: value = deserializePrimitive((PrimitiveTypeInfo) type, rawValue); break; case STRUCT: value = deserializeStruct((StructTypeInfo) type, rawValue); break; case MAP: value = deserializeMap((MapTypeInfo) type, rawValue); break; case LIST: value = deserializeList((ListTypeInfo) type, rawValue); break; case UNION: value = deserializeUnion((UnionTypeInfo) type, rawValue); break; } } return value; }
[ "private", "Object", "deserialize", "(", "TypeInfo", "type", ",", "Object", "rawValue", ")", "throws", "SerDeException", "{", "Object", "value", "=", "null", ";", "if", "(", "rawValue", "!=", "null", ")", "{", "switch", "(", "type", ".", "getCategory", "("...
Deserializes a raw value to the provided type.
[ "Deserializes", "a", "raw", "value", "to", "the", "provided", "type", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java#L290-L315
train
bazaarvoice/emodb
mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java
EmoSerDe.isSupportedPrimitive
private boolean isSupportedPrimitive(PrimitiveTypeInfo type) { switch (type.getPrimitiveCategory()) { case VOID: case STRING: case BOOLEAN: case BYTE: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: case DATE: case TIMESTAMP: return true; default: return false; } }
java
private boolean isSupportedPrimitive(PrimitiveTypeInfo type) { switch (type.getPrimitiveCategory()) { case VOID: case STRING: case BOOLEAN: case BYTE: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: case DATE: case TIMESTAMP: return true; default: return false; } }
[ "private", "boolean", "isSupportedPrimitive", "(", "PrimitiveTypeInfo", "type", ")", "{", "switch", "(", "type", ".", "getPrimitiveCategory", "(", ")", ")", "{", "case", "VOID", ":", "case", "STRING", ":", "case", "BOOLEAN", ":", "case", "BYTE", ":", "case",...
Determines if the given primitive is supported by this deserializer. At this time the only exclusions are BINARY, DECIMAL, VARCHAR, CHAR, and UNKNOWN.
[ "Determines", "if", "the", "given", "primitive", "is", "supported", "by", "this", "deserializer", ".", "At", "this", "time", "the", "only", "exclusions", "are", "BINARY", "DECIMAL", "VARCHAR", "CHAR", "and", "UNKNOWN", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java#L321-L338
train
bazaarvoice/emodb
mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java
EmoSerDe.deserializePrimitive
private Object deserializePrimitive(PrimitiveTypeInfo type, Object value) throws SerDeException { switch (type.getPrimitiveCategory()) { case VOID: return null; case STRING: return deserializeString(value); case BOOLEAN: return deserializeBoolean(value); case BYTE: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: return deserializeNumber(value, type); case DATE: case TIMESTAMP: return deserializeDate(value, type); default: throw new SerDeException("Unsupported type: " + type.getPrimitiveCategory()); } }
java
private Object deserializePrimitive(PrimitiveTypeInfo type, Object value) throws SerDeException { switch (type.getPrimitiveCategory()) { case VOID: return null; case STRING: return deserializeString(value); case BOOLEAN: return deserializeBoolean(value); case BYTE: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: return deserializeNumber(value, type); case DATE: case TIMESTAMP: return deserializeDate(value, type); default: throw new SerDeException("Unsupported type: " + type.getPrimitiveCategory()); } }
[ "private", "Object", "deserializePrimitive", "(", "PrimitiveTypeInfo", "type", ",", "Object", "value", ")", "throws", "SerDeException", "{", "switch", "(", "type", ".", "getPrimitiveCategory", "(", ")", ")", "{", "case", "VOID", ":", "return", "null", ";", "ca...
Deserializes a primitive to its corresponding Java type, doing a best-effort conversion when necessary.
[ "Deserializes", "a", "primitive", "to", "its", "corresponding", "Java", "type", "doing", "a", "best", "-", "effort", "conversion", "when", "necessary", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java#L343-L365
train
bazaarvoice/emodb
common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/cqldriver/AdaptiveResultSet.java
AdaptiveResultSet.executeAdaptiveQueryAsync
public static ListenableFuture<ResultSet> executeAdaptiveQueryAsync(Session session, Statement statement, int fetchSize) { return executeAdaptiveQueryAsync(session, statement, fetchSize, MAX_ADAPTATIONS); }
java
public static ListenableFuture<ResultSet> executeAdaptiveQueryAsync(Session session, Statement statement, int fetchSize) { return executeAdaptiveQueryAsync(session, statement, fetchSize, MAX_ADAPTATIONS); }
[ "public", "static", "ListenableFuture", "<", "ResultSet", ">", "executeAdaptiveQueryAsync", "(", "Session", "session", ",", "Statement", "statement", ",", "int", "fetchSize", ")", "{", "return", "executeAdaptiveQueryAsync", "(", "session", ",", "statement", ",", "fe...
Executes a query asychronously, dynamically adjusting the fetch size down if necessary.
[ "Executes", "a", "query", "asychronously", "dynamically", "adjusting", "the", "fetch", "size", "down", "if", "necessary", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/cqldriver/AdaptiveResultSet.java#L51-L53
train
bazaarvoice/emodb
common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/cqldriver/AdaptiveResultSet.java
AdaptiveResultSet.executeAdaptiveQuery
public static ResultSet executeAdaptiveQuery(Session session, Statement statement, int fetchSize) { int remainingAdaptations = MAX_ADAPTATIONS; while (true) { try { statement.setFetchSize(fetchSize); ResultSet resultSet = session.execute(statement); return new AdaptiveResultSet(session, resultSet, remainingAdaptations); } catch (Throwable t) { if (isAdaptiveException(t) && --remainingAdaptations != 0 && fetchSize > MIN_FETCH_SIZE) { // Try again with half the fetch size fetchSize = Math.max(fetchSize / 2, MIN_FETCH_SIZE); _log.debug("Repeating previous query with fetch size {} due to {}", fetchSize, t.getMessage()); } else { throw Throwables.propagate(t); } } } }
java
public static ResultSet executeAdaptiveQuery(Session session, Statement statement, int fetchSize) { int remainingAdaptations = MAX_ADAPTATIONS; while (true) { try { statement.setFetchSize(fetchSize); ResultSet resultSet = session.execute(statement); return new AdaptiveResultSet(session, resultSet, remainingAdaptations); } catch (Throwable t) { if (isAdaptiveException(t) && --remainingAdaptations != 0 && fetchSize > MIN_FETCH_SIZE) { // Try again with half the fetch size fetchSize = Math.max(fetchSize / 2, MIN_FETCH_SIZE); _log.debug("Repeating previous query with fetch size {} due to {}", fetchSize, t.getMessage()); } else { throw Throwables.propagate(t); } } } }
[ "public", "static", "ResultSet", "executeAdaptiveQuery", "(", "Session", "session", ",", "Statement", "statement", ",", "int", "fetchSize", ")", "{", "int", "remainingAdaptations", "=", "MAX_ADAPTATIONS", ";", "while", "(", "true", ")", "{", "try", "{", "stateme...
Executes a query sychronously, dynamically adjusting the fetch size down if necessary.
[ "Executes", "a", "query", "sychronously", "dynamically", "adjusting", "the", "fetch", "size", "down", "if", "necessary", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/cqldriver/AdaptiveResultSet.java#L84-L101
train
bazaarvoice/emodb
common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/cqldriver/AdaptiveResultSet.java
AdaptiveResultSet.isAdaptiveException
private static boolean isAdaptiveException(Throwable t) { if (t instanceof FrameTooLongException) { return true; } if (t instanceof NoHostAvailableException) { // If the issue on every host is adaptive then the exception is adaptive Collection<Throwable> hostExceptions = ((NoHostAvailableException) t).getErrors().values(); return !hostExceptions.isEmpty() && hostExceptions.stream().allMatch(AdaptiveResultSet::isAdaptiveException); } return false; }
java
private static boolean isAdaptiveException(Throwable t) { if (t instanceof FrameTooLongException) { return true; } if (t instanceof NoHostAvailableException) { // If the issue on every host is adaptive then the exception is adaptive Collection<Throwable> hostExceptions = ((NoHostAvailableException) t).getErrors().values(); return !hostExceptions.isEmpty() && hostExceptions.stream().allMatch(AdaptiveResultSet::isAdaptiveException); } return false; }
[ "private", "static", "boolean", "isAdaptiveException", "(", "Throwable", "t", ")", "{", "if", "(", "t", "instanceof", "FrameTooLongException", ")", "{", "return", "true", ";", "}", "if", "(", "t", "instanceof", "NoHostAvailableException", ")", "{", "// If the is...
Returns true if the exception is one which indicates that the frame size may be too large, false otherwise.
[ "Returns", "true", "if", "the", "exception", "is", "one", "which", "indicates", "that", "the", "frame", "size", "may", "be", "too", "large", "false", "otherwise", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/cqldriver/AdaptiveResultSet.java#L106-L118
train
bazaarvoice/emodb
common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/cqldriver/AdaptiveResultSet.java
AdaptiveResultSet.reduceFetchSize
private boolean reduceFetchSize(Throwable reason) { if (!isAdaptiveException(reason) || --_remainingAdaptations == 0) { return false; } ExecutionInfo executionInfo = _delegate.getExecutionInfo(); Statement statement = executionInfo.getStatement(); PagingState pagingState = executionInfo.getPagingState(); int fetchSize = statement.getFetchSize(); while (fetchSize > MIN_FETCH_SIZE) { fetchSize = Math.max(fetchSize / 2, MIN_FETCH_SIZE); _log.debug("Retrying query at next page with fetch size {} due to {}", fetchSize, reason.getMessage()); statement.setFetchSize(fetchSize); statement.setPagingState(pagingState); try { _delegate = _session.execute(statement); return true; } catch (Throwable t) { // Exit the adaptation loop if the exception isn't one where adapting further may help if (!isAdaptiveException(t) || --_remainingAdaptations == 0) { return false; } } } return false; }
java
private boolean reduceFetchSize(Throwable reason) { if (!isAdaptiveException(reason) || --_remainingAdaptations == 0) { return false; } ExecutionInfo executionInfo = _delegate.getExecutionInfo(); Statement statement = executionInfo.getStatement(); PagingState pagingState = executionInfo.getPagingState(); int fetchSize = statement.getFetchSize(); while (fetchSize > MIN_FETCH_SIZE) { fetchSize = Math.max(fetchSize / 2, MIN_FETCH_SIZE); _log.debug("Retrying query at next page with fetch size {} due to {}", fetchSize, reason.getMessage()); statement.setFetchSize(fetchSize); statement.setPagingState(pagingState); try { _delegate = _session.execute(statement); return true; } catch (Throwable t) { // Exit the adaptation loop if the exception isn't one where adapting further may help if (!isAdaptiveException(t) || --_remainingAdaptations == 0) { return false; } } } return false; }
[ "private", "boolean", "reduceFetchSize", "(", "Throwable", "reason", ")", "{", "if", "(", "!", "isAdaptiveException", "(", "reason", ")", "||", "--", "_remainingAdaptations", "==", "0", ")", "{", "return", "false", ";", "}", "ExecutionInfo", "executionInfo", "...
Reduces the fetch size and retries the query. Returns true if the query succeeded, false if the root cause of the exception does not indicate a frame size issue, if the frame size cannot be adjusted down any further, or if the retried query fails for an unrelated reason.
[ "Reduces", "the", "fetch", "size", "and", "retries", "the", "query", ".", "Returns", "true", "if", "the", "query", "succeeded", "false", "if", "the", "root", "cause", "of", "the", "exception", "does", "not", "indicate", "a", "frame", "size", "issue", "if",...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/cqldriver/AdaptiveResultSet.java#L184-L211
train
bazaarvoice/emodb
sor/src/main/java/com/bazaarvoice/emodb/sor/db/DAOUtils.java
DAOUtils.skipPrefix
public ByteBuffer skipPrefix(ByteBuffer value) { value.position(value.position() + _prefixLength); return value; }
java
public ByteBuffer skipPrefix(ByteBuffer value) { value.position(value.position() + _prefixLength); return value; }
[ "public", "ByteBuffer", "skipPrefix", "(", "ByteBuffer", "value", ")", "{", "value", ".", "position", "(", "value", ".", "position", "(", ")", "+", "_prefixLength", ")", ";", "return", "value", ";", "}" ]
removes the hex prefix that indicates the number of blocks in the delta
[ "removes", "the", "hex", "prefix", "that", "indicates", "the", "number", "of", "blocks", "in", "the", "delta" ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/db/DAOUtils.java#L86-L89
train
bazaarvoice/emodb
databus/src/main/java/com/bazaarvoice/emodb/databus/repl/ReplicationClientFactory.java
ReplicationClientFactory.usingApiKey
public ReplicationClientFactory usingApiKey(String apiKey) { if (Objects.equal(_apiKey, apiKey)) { return this; } return new ReplicationClientFactory(_jerseyClient, apiKey); }
java
public ReplicationClientFactory usingApiKey(String apiKey) { if (Objects.equal(_apiKey, apiKey)) { return this; } return new ReplicationClientFactory(_jerseyClient, apiKey); }
[ "public", "ReplicationClientFactory", "usingApiKey", "(", "String", "apiKey", ")", "{", "if", "(", "Objects", ".", "equal", "(", "_apiKey", ",", "apiKey", ")", ")", "{", "return", "this", ";", "}", "return", "new", "ReplicationClientFactory", "(", "_jerseyClie...
Creates a view of this instance using the given API Key and sharing the same underlying resources. Note that this method may return a new instance so the caller must use the returned value.
[ "Creates", "a", "view", "of", "this", "instance", "using", "the", "given", "API", "Key", "and", "sharing", "the", "same", "underlying", "resources", ".", "Note", "that", "this", "method", "may", "return", "a", "new", "instance", "so", "the", "caller", "mus...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/databus/src/main/java/com/bazaarvoice/emodb/databus/repl/ReplicationClientFactory.java#L38-L43
train
bazaarvoice/emodb
sor/src/main/java/com/bazaarvoice/emodb/sor/core/DefaultDataStore.java
DefaultDataStore.resolveAnnotated
private AnnotatedContent resolveAnnotated(Record record, final ReadConsistency consistency) { final Resolved resolved = resolve(record, consistency); final Table table = record.getKey().getTable(); return new AnnotatedContent() { @Override public Map<String, Object> getContent() { return toContent(resolved, consistency); } @Override public boolean isChangeDeltaPending(UUID changeId) { long fullConsistencyTimestamp = _dataWriterDao.getFullConsistencyTimestamp(table); return resolved.isChangeDeltaPending(changeId, fullConsistencyTimestamp); } @Override public boolean isChangeDeltaRedundant(UUID changeId) { return resolved.isChangeDeltaRedundant(changeId); } }; }
java
private AnnotatedContent resolveAnnotated(Record record, final ReadConsistency consistency) { final Resolved resolved = resolve(record, consistency); final Table table = record.getKey().getTable(); return new AnnotatedContent() { @Override public Map<String, Object> getContent() { return toContent(resolved, consistency); } @Override public boolean isChangeDeltaPending(UUID changeId) { long fullConsistencyTimestamp = _dataWriterDao.getFullConsistencyTimestamp(table); return resolved.isChangeDeltaPending(changeId, fullConsistencyTimestamp); } @Override public boolean isChangeDeltaRedundant(UUID changeId) { return resolved.isChangeDeltaRedundant(changeId); } }; }
[ "private", "AnnotatedContent", "resolveAnnotated", "(", "Record", "record", ",", "final", "ReadConsistency", "consistency", ")", "{", "final", "Resolved", "resolved", "=", "resolve", "(", "record", ",", "consistency", ")", ";", "final", "Table", "table", "=", "r...
Resolve a set of changes, returning an interface that includes info about specific change IDs.
[ "Resolve", "a", "set", "of", "changes", "returning", "an", "interface", "that", "includes", "info", "about", "specific", "change", "IDs", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/core/DefaultDataStore.java#L435-L456
train
bazaarvoice/emodb
sor/src/main/java/com/bazaarvoice/emodb/sor/core/DefaultDataStore.java
DefaultDataStore.createFacade
@Override public void createFacade(String table, FacadeOptions facadeOptions, Audit audit) { checkLegalTableName(table); checkNotNull(facadeOptions, "facadeDefinition"); checkNotNull(audit, "audit"); _tableDao.createFacade(table, facadeOptions, audit); }
java
@Override public void createFacade(String table, FacadeOptions facadeOptions, Audit audit) { checkLegalTableName(table); checkNotNull(facadeOptions, "facadeDefinition"); checkNotNull(audit, "audit"); _tableDao.createFacade(table, facadeOptions, audit); }
[ "@", "Override", "public", "void", "createFacade", "(", "String", "table", ",", "FacadeOptions", "facadeOptions", ",", "Audit", "audit", ")", "{", "checkLegalTableName", "(", "table", ")", ";", "checkNotNull", "(", "facadeOptions", ",", "\"facadeDefinition\"", ")"...
Facade related methods
[ "Facade", "related", "methods" ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/sor/src/main/java/com/bazaarvoice/emodb/sor/core/DefaultDataStore.java#L775-L781
train
bazaarvoice/emodb
event/src/main/java/com/bazaarvoice/emodb/event/owner/OstrichOwnerGroup.java
OstrichOwnerGroup.startIfOwner
@Nullable @Override public T startIfOwner(String name, Duration waitDuration) { long timeoutAt = System.currentTimeMillis() + waitDuration.toMillis(); LeaderService leaderService = _leaderMap.getUnchecked(name).orNull(); if (leaderService == null || !awaitRunning(leaderService, timeoutAt)) { return null; } Service service; for (;;) { Optional<Service> opt = leaderService.getCurrentDelegateService(); if (opt.isPresent()) { service = opt.get(); break; } if (System.currentTimeMillis() >= timeoutAt) { return null; } try { Thread.sleep(10); } catch (InterruptedException e) { throw Throwables.propagate(e); } } if (!awaitRunning(service, timeoutAt)) { return null; } //noinspection unchecked return (T) service; }
java
@Nullable @Override public T startIfOwner(String name, Duration waitDuration) { long timeoutAt = System.currentTimeMillis() + waitDuration.toMillis(); LeaderService leaderService = _leaderMap.getUnchecked(name).orNull(); if (leaderService == null || !awaitRunning(leaderService, timeoutAt)) { return null; } Service service; for (;;) { Optional<Service> opt = leaderService.getCurrentDelegateService(); if (opt.isPresent()) { service = opt.get(); break; } if (System.currentTimeMillis() >= timeoutAt) { return null; } try { Thread.sleep(10); } catch (InterruptedException e) { throw Throwables.propagate(e); } } if (!awaitRunning(service, timeoutAt)) { return null; } //noinspection unchecked return (T) service; }
[ "@", "Nullable", "@", "Override", "public", "T", "startIfOwner", "(", "String", "name", ",", "Duration", "waitDuration", ")", "{", "long", "timeoutAt", "=", "System", ".", "currentTimeMillis", "(", ")", "+", "waitDuration", ".", "toMillis", "(", ")", ";", ...
Returns the specified managed service if this server is responsible for the specified object and has won a ZooKeeper-managed leader election. @param name object name. Whether this server owns the object is computed by Ostrich using consistent hashing. @param waitDuration the amount of time to wait for this server to win the leader election and for the service to startup, if the object is managed by this server.
[ "Returns", "the", "specified", "managed", "service", "if", "this", "server", "is", "responsible", "for", "the", "specified", "object", "and", "has", "won", "a", "ZooKeeper", "-", "managed", "leader", "election", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/event/owner/OstrichOwnerGroup.java#L115-L144
train
bazaarvoice/emodb
event/src/main/java/com/bazaarvoice/emodb/event/owner/OstrichOwnerGroup.java
OstrichOwnerGroup.awaitRunning
private boolean awaitRunning(Service service, long timeoutAt) { if (service.isRunning()) { return true; } long waitMillis = timeoutAt - System.currentTimeMillis(); if (waitMillis <= 0) { return false; } try { service.start().get(waitMillis, TimeUnit.MILLISECONDS); } catch (Exception e) { // Fall through } return service.isRunning(); }
java
private boolean awaitRunning(Service service, long timeoutAt) { if (service.isRunning()) { return true; } long waitMillis = timeoutAt - System.currentTimeMillis(); if (waitMillis <= 0) { return false; } try { service.start().get(waitMillis, TimeUnit.MILLISECONDS); } catch (Exception e) { // Fall through } return service.isRunning(); }
[ "private", "boolean", "awaitRunning", "(", "Service", "service", ",", "long", "timeoutAt", ")", "{", "if", "(", "service", ".", "isRunning", "(", ")", ")", "{", "return", "true", ";", "}", "long", "waitMillis", "=", "timeoutAt", "-", "System", ".", "curr...
Returns true if the Guava service entered the RUNNING state within the specified time period.
[ "Returns", "true", "if", "the", "Guava", "service", "entered", "the", "RUNNING", "state", "within", "the", "specified", "time", "period", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/event/src/main/java/com/bazaarvoice/emodb/event/owner/OstrichOwnerGroup.java#L241-L255
train
bazaarvoice/emodb
common/uuid/src/main/java/com/bazaarvoice/emodb/common/uuid/TimeUUIDs.java
TimeUUIDs.compare
public static int compare(UUID uuid1, UUID uuid2) { int timeResult = Longs.compare(uuid1.timestamp(), uuid2.timestamp()); if (timeResult != 0) { return timeResult; } // if the time component is identical, break ties using the clockSeqAndNode // component (the 64 least significant bits). the top 16 bits of the lsb are // the "clockSeq" number which, theoretically, is an incrementing counter. in // practice, however, (and in com.eaio.uuid) clockSeq is a random number and // shouldn't be interpreted as meaning anything. just use it for breaking ties. return uuid1.compareTo(uuid2); }
java
public static int compare(UUID uuid1, UUID uuid2) { int timeResult = Longs.compare(uuid1.timestamp(), uuid2.timestamp()); if (timeResult != 0) { return timeResult; } // if the time component is identical, break ties using the clockSeqAndNode // component (the 64 least significant bits). the top 16 bits of the lsb are // the "clockSeq" number which, theoretically, is an incrementing counter. in // practice, however, (and in com.eaio.uuid) clockSeq is a random number and // shouldn't be interpreted as meaning anything. just use it for breaking ties. return uuid1.compareTo(uuid2); }
[ "public", "static", "int", "compare", "(", "UUID", "uuid1", ",", "UUID", "uuid2", ")", "{", "int", "timeResult", "=", "Longs", ".", "compare", "(", "uuid1", ".", "timestamp", "(", ")", ",", "uuid2", ".", "timestamp", "(", ")", ")", ";", "if", "(", ...
Compare two time UUIDs deterministically, first by their embedded timestamp, next by their node-specific sequence number, finally breaking ties using their embedded node identifier.\ @throws UnsupportedOperationException if either uuid is not a timestamp UUID
[ "Compare", "two", "time", "UUIDs", "deterministically", "first", "by", "their", "embedded", "timestamp", "next", "by", "their", "node", "-", "specific", "sequence", "number", "finally", "breaking", "ties", "using", "their", "embedded", "node", "identifier", ".", ...
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/uuid/src/main/java/com/bazaarvoice/emodb/common/uuid/TimeUUIDs.java#L158-L169
train
bazaarvoice/emodb
common/uuid/src/main/java/com/bazaarvoice/emodb/common/uuid/TimeUUIDs.java
TimeUUIDs.compareTimestamps
public static int compareTimestamps(UUID uuid1, UUID uuid2) { return Longs.compare(uuid1.timestamp(), uuid2.timestamp()); }
java
public static int compareTimestamps(UUID uuid1, UUID uuid2) { return Longs.compare(uuid1.timestamp(), uuid2.timestamp()); }
[ "public", "static", "int", "compareTimestamps", "(", "UUID", "uuid1", ",", "UUID", "uuid2", ")", "{", "return", "Longs", ".", "compare", "(", "uuid1", ".", "timestamp", "(", ")", ",", "uuid2", ".", "timestamp", "(", ")", ")", ";", "}" ]
Compare the embedded timestamps of the given UUIDs. This is used when it is OK to return an equality based on timestamps alone @throws UnsupportedOperationException if either uuid is not a timestamp UUID
[ "Compare", "the", "embedded", "timestamps", "of", "the", "given", "UUIDs", ".", "This", "is", "used", "when", "it", "is", "OK", "to", "return", "an", "equality", "based", "on", "timestamps", "alone" ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/uuid/src/main/java/com/bazaarvoice/emodb/common/uuid/TimeUUIDs.java#L176-L178
train
bazaarvoice/emodb
mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/BaseInputFormat.java
BaseInputFormat.getSplits
public static Iterable<SplitPath> getSplits(final Configuration config, Path[] paths) { final int splitSize = getSplitSize(config); return FluentIterable.from(Arrays.asList(paths)) .transformAndConcat(new Function<Path, Iterable<? extends SplitPath>>() { @Override public Iterable<? extends SplitPath> apply(Path path) { try { EmoInputSplittable emoFs = (EmoInputSplittable) path.getFileSystem(config); return emoFs.getInputSplits(config, path, splitSize); } catch (IOException e) { throw Throwables.propagate(e); } } }); }
java
public static Iterable<SplitPath> getSplits(final Configuration config, Path[] paths) { final int splitSize = getSplitSize(config); return FluentIterable.from(Arrays.asList(paths)) .transformAndConcat(new Function<Path, Iterable<? extends SplitPath>>() { @Override public Iterable<? extends SplitPath> apply(Path path) { try { EmoInputSplittable emoFs = (EmoInputSplittable) path.getFileSystem(config); return emoFs.getInputSplits(config, path, splitSize); } catch (IOException e) { throw Throwables.propagate(e); } } }); }
[ "public", "static", "Iterable", "<", "SplitPath", ">", "getSplits", "(", "final", "Configuration", "config", ",", "Path", "[", "]", "paths", ")", "{", "final", "int", "splitSize", "=", "getSplitSize", "(", "config", ")", ";", "return", "FluentIterable", ".",...
Gets the splits for a given list of EmoDB paths.
[ "Gets", "the", "splits", "for", "a", "given", "list", "of", "EmoDB", "paths", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/BaseInputFormat.java#L40-L55
train
bazaarvoice/emodb
mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/BaseInputFormat.java
BaseInputFormat.createRecordReader
public static BaseRecordReader createRecordReader(Configuration config, Path path) throws IOException { EmoInputSplittable emoFs = (EmoInputSplittable) path.getFileSystem(config); return emoFs.getBaseRecordReader(config, path, getSplitSize(config)); }
java
public static BaseRecordReader createRecordReader(Configuration config, Path path) throws IOException { EmoInputSplittable emoFs = (EmoInputSplittable) path.getFileSystem(config); return emoFs.getBaseRecordReader(config, path, getSplitSize(config)); }
[ "public", "static", "BaseRecordReader", "createRecordReader", "(", "Configuration", "config", ",", "Path", "path", ")", "throws", "IOException", "{", "EmoInputSplittable", "emoFs", "=", "(", "EmoInputSplittable", ")", "path", ".", "getFileSystem", "(", "config", ")"...
Gets a record reader for a given split.
[ "Gets", "a", "record", "reader", "for", "a", "given", "split", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hadoop/src/main/java/com/bazaarvoice/emodb/hadoop/io/BaseInputFormat.java#L60-L64
train
bazaarvoice/emodb
table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTable.java
AstyanaxTable.hasUUID
boolean hasUUID(long uuid) { if (_readStorage.hasUUID(uuid)) { return true; } for (AstyanaxStorage storage : _writeStorage) { if (storage.hasUUID(uuid)) { return true; } } return false; }
java
boolean hasUUID(long uuid) { if (_readStorage.hasUUID(uuid)) { return true; } for (AstyanaxStorage storage : _writeStorage) { if (storage.hasUUID(uuid)) { return true; } } return false; }
[ "boolean", "hasUUID", "(", "long", "uuid", ")", "{", "if", "(", "_readStorage", ".", "hasUUID", "(", "uuid", ")", ")", "{", "return", "true", ";", "}", "for", "(", "AstyanaxStorage", "storage", ":", "_writeStorage", ")", "{", "if", "(", "storage", ".",...
Test if a given UUID matches this table.
[ "Test", "if", "a", "given", "UUID", "matches", "this", "table", "." ]
97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/table/src/main/java/com/bazaarvoice/emodb/table/db/astyanax/AstyanaxTable.java#L93-L103
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/TypeUtils.java
TypeUtils.parse
static Type parse(String str) { try { return doParse(str); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } }
java
static Type parse(String str) { try { return doParse(str); } catch (RuntimeException ex) { throw ex; } catch (Exception ex) { throw new RuntimeException(ex); } }
[ "static", "Type", "parse", "(", "String", "str", ")", "{", "try", "{", "return", "doParse", "(", "str", ")", ";", "}", "catch", "(", "RuntimeException", "ex", ")", "{", "throw", "ex", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "n...
Parses the TypeToken string format. @param str the string @return the token
[ "Parses", "the", "TypeToken", "string", "format", "." ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/TypeUtils.java#L71-L79
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/TypeUtils.java
TypeUtils.doParse
private static Type doParse(String str) throws Exception { Class<?> token = PRIMITIVES.get(str); if (token != null) { return token; } int first = str.indexOf('<'); if (first < 0) { return StringConvert.loadType(str); } int last = str.lastIndexOf('>'); String baseStr = str.substring(0, first); Class<?> base = StringConvert.loadType(baseStr); String argsStr = str.substring(first + 1, last); List<String> splitArgs = split(argsStr); List<Type> types = new ArrayList<Type>(); for (String splitArg : splitArgs) { Type argType; if (splitArg.startsWith(EXTENDS)) { String remainder = splitArg.substring(EXTENDS.length()); argType = wildExtendsType(doParse(remainder)); } else if (splitArg.startsWith(SUPER)) { String remainder = splitArg.substring(SUPER.length()); argType = wildSuperType(doParse(remainder)); } else if (splitArg.equals("?")) { argType = wildExtendsType(Object.class); } else if (splitArg.endsWith("[]")) { String componentStr = splitArg.substring(0, splitArg.length() - 2); Class<?> componentCls = StringConvert.loadType(componentStr); argType = Array.newInstance(componentCls, 0).getClass(); } else if (splitArg.startsWith("[L") && splitArg.endsWith(";")) { String componentStr = splitArg.substring(2, splitArg.length() - 1); Class<?> componentCls = StringConvert.loadType(componentStr); argType = Array.newInstance(componentCls, 0).getClass(); } else { argType = doParse(splitArg); } types.add(argType); } return newParameterizedType(base, types.toArray(new Type[types.size()])); }
java
private static Type doParse(String str) throws Exception { Class<?> token = PRIMITIVES.get(str); if (token != null) { return token; } int first = str.indexOf('<'); if (first < 0) { return StringConvert.loadType(str); } int last = str.lastIndexOf('>'); String baseStr = str.substring(0, first); Class<?> base = StringConvert.loadType(baseStr); String argsStr = str.substring(first + 1, last); List<String> splitArgs = split(argsStr); List<Type> types = new ArrayList<Type>(); for (String splitArg : splitArgs) { Type argType; if (splitArg.startsWith(EXTENDS)) { String remainder = splitArg.substring(EXTENDS.length()); argType = wildExtendsType(doParse(remainder)); } else if (splitArg.startsWith(SUPER)) { String remainder = splitArg.substring(SUPER.length()); argType = wildSuperType(doParse(remainder)); } else if (splitArg.equals("?")) { argType = wildExtendsType(Object.class); } else if (splitArg.endsWith("[]")) { String componentStr = splitArg.substring(0, splitArg.length() - 2); Class<?> componentCls = StringConvert.loadType(componentStr); argType = Array.newInstance(componentCls, 0).getClass(); } else if (splitArg.startsWith("[L") && splitArg.endsWith(";")) { String componentStr = splitArg.substring(2, splitArg.length() - 1); Class<?> componentCls = StringConvert.loadType(componentStr); argType = Array.newInstance(componentCls, 0).getClass(); } else { argType = doParse(splitArg); } types.add(argType); } return newParameterizedType(base, types.toArray(new Type[types.size()])); }
[ "private", "static", "Type", "doParse", "(", "String", "str", ")", "throws", "Exception", "{", "Class", "<", "?", ">", "token", "=", "PRIMITIVES", ".", "get", "(", "str", ")", ";", "if", "(", "token", "!=", "null", ")", "{", "return", "token", ";", ...
parse an element
[ "parse", "an", "element" ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/TypeUtils.java#L82-L121
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/TypeUtils.java
TypeUtils.split
private static List<String> split(String str) { List<String> result = new ArrayList<String>(); int genericCount = 0; int startPos = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ',' && genericCount == 0) { result.add(str.substring(startPos, i).trim()); startPos = i + 1; } else if (str.charAt(i) == '<') { genericCount++; } else if (str.charAt(i) == '>') { genericCount--; } } result.add(str.substring(startPos).trim()); return result; }
java
private static List<String> split(String str) { List<String> result = new ArrayList<String>(); int genericCount = 0; int startPos = 0; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == ',' && genericCount == 0) { result.add(str.substring(startPos, i).trim()); startPos = i + 1; } else if (str.charAt(i) == '<') { genericCount++; } else if (str.charAt(i) == '>') { genericCount--; } } result.add(str.substring(startPos).trim()); return result; }
[ "private", "static", "List", "<", "String", ">", "split", "(", "String", "str", ")", "{", "List", "<", "String", ">", "result", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "int", "genericCount", "=", "0", ";", "int", "startPos", "=", ...
split by comma, handling nested generified types
[ "split", "by", "comma", "handling", "nested", "generified", "types" ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/TypeUtils.java#L124-L140
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/StringConvert.java
StringConvert.tryRegisterGuava
private void tryRegisterGuava() { try { // Guava is not a direct dependency, which is significant in the Java 9 module system // to access Guava this module must add a read edge to the module graph // but since this code is written for Java 6, we have to do this by reflection // yuck Class<?> moduleClass = Class.class.getMethod("getModule").getReturnType(); Object convertModule = Class.class.getMethod("getModule").invoke(StringConvert.class); Object layer = convertModule.getClass().getMethod("getLayer").invoke(convertModule); if (layer != null) { Object optGuava = layer.getClass().getMethod("findModule", String.class).invoke(layer, "com.google.common"); boolean found = (Boolean) optGuava.getClass().getMethod("isPresent").invoke(optGuava); if (found) { Object guavaModule = optGuava.getClass().getMethod("get").invoke(optGuava); moduleClass.getMethod("addReads", moduleClass).invoke(convertModule, guavaModule); } } } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterGuava1: " + ex); } } try { // can now check for Guava // if we have created a read edge, or if we are on the classpath, this will succeed loadType("com.google.common.reflect.TypeToken"); @SuppressWarnings("unchecked") Class<?> cls = (Class<TypedStringConverter<?>>) loadType("org.joda.convert.TypeTokenStringConverter"); TypedStringConverter<?> conv = (TypedStringConverter<?>) cls.getDeclaredConstructor().newInstance(); registered.put(conv.getEffectiveType(), conv); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterGuava2: " + ex); } } }
java
private void tryRegisterGuava() { try { // Guava is not a direct dependency, which is significant in the Java 9 module system // to access Guava this module must add a read edge to the module graph // but since this code is written for Java 6, we have to do this by reflection // yuck Class<?> moduleClass = Class.class.getMethod("getModule").getReturnType(); Object convertModule = Class.class.getMethod("getModule").invoke(StringConvert.class); Object layer = convertModule.getClass().getMethod("getLayer").invoke(convertModule); if (layer != null) { Object optGuava = layer.getClass().getMethod("findModule", String.class).invoke(layer, "com.google.common"); boolean found = (Boolean) optGuava.getClass().getMethod("isPresent").invoke(optGuava); if (found) { Object guavaModule = optGuava.getClass().getMethod("get").invoke(optGuava); moduleClass.getMethod("addReads", moduleClass).invoke(convertModule, guavaModule); } } } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterGuava1: " + ex); } } try { // can now check for Guava // if we have created a read edge, or if we are on the classpath, this will succeed loadType("com.google.common.reflect.TypeToken"); @SuppressWarnings("unchecked") Class<?> cls = (Class<TypedStringConverter<?>>) loadType("org.joda.convert.TypeTokenStringConverter"); TypedStringConverter<?> conv = (TypedStringConverter<?>) cls.getDeclaredConstructor().newInstance(); registered.put(conv.getEffectiveType(), conv); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterGuava2: " + ex); } } }
[ "private", "void", "tryRegisterGuava", "(", ")", "{", "try", "{", "// Guava is not a direct dependency, which is significant in the Java 9 module system\r", "// to access Guava this module must add a read edge to the module graph\r", "// but since this code is written for Java 6, we have to do t...
Tries to register the Guava converters class.
[ "Tries", "to", "register", "the", "Guava", "converters", "class", "." ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/StringConvert.java#L196-L233
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/StringConvert.java
StringConvert.tryRegisterJava8Optionals
private void tryRegisterJava8Optionals() { try { loadType("java.util.OptionalInt"); @SuppressWarnings("unchecked") Class<?> cls1 = (Class<TypedStringConverter<?>>) loadType("org.joda.convert.OptionalIntStringConverter"); TypedStringConverter<?> conv1 = (TypedStringConverter<?>) cls1.getDeclaredConstructor().newInstance(); registered.put(conv1.getEffectiveType(), conv1); @SuppressWarnings("unchecked") Class<?> cls2 = (Class<TypedStringConverter<?>>) loadType("org.joda.convert.OptionalLongStringConverter"); TypedStringConverter<?> conv2 = (TypedStringConverter<?>) cls2.getDeclaredConstructor().newInstance(); registered.put(conv2.getEffectiveType(), conv2); @SuppressWarnings("unchecked") Class<?> cls3 = (Class<TypedStringConverter<?>>) loadType("org.joda.convert.OptionalDoubleStringConverter"); TypedStringConverter<?> conv3 = (TypedStringConverter<?>) cls3.getDeclaredConstructor().newInstance(); registered.put(conv3.getEffectiveType(), conv3); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterOptionals: " + ex); } } }
java
private void tryRegisterJava8Optionals() { try { loadType("java.util.OptionalInt"); @SuppressWarnings("unchecked") Class<?> cls1 = (Class<TypedStringConverter<?>>) loadType("org.joda.convert.OptionalIntStringConverter"); TypedStringConverter<?> conv1 = (TypedStringConverter<?>) cls1.getDeclaredConstructor().newInstance(); registered.put(conv1.getEffectiveType(), conv1); @SuppressWarnings("unchecked") Class<?> cls2 = (Class<TypedStringConverter<?>>) loadType("org.joda.convert.OptionalLongStringConverter"); TypedStringConverter<?> conv2 = (TypedStringConverter<?>) cls2.getDeclaredConstructor().newInstance(); registered.put(conv2.getEffectiveType(), conv2); @SuppressWarnings("unchecked") Class<?> cls3 = (Class<TypedStringConverter<?>>) loadType("org.joda.convert.OptionalDoubleStringConverter"); TypedStringConverter<?> conv3 = (TypedStringConverter<?>) cls3.getDeclaredConstructor().newInstance(); registered.put(conv3.getEffectiveType(), conv3); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterOptionals: " + ex); } } }
[ "private", "void", "tryRegisterJava8Optionals", "(", ")", "{", "try", "{", "loadType", "(", "\"java.util.OptionalInt\"", ")", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "Class", "<", "?", ">", "cls1", "=", "(", "Class", "<", "TypedStringConverter",...
Tries to register the Java 8 optional classes.
[ "Tries", "to", "register", "the", "Java", "8", "optional", "classes", "." ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/StringConvert.java#L238-L261
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/StringConvert.java
StringConvert.tryRegisterTimeZone
private void tryRegisterTimeZone() { try { registered.put(SimpleTimeZone.class, JDKStringConverter.TIME_ZONE); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterTimeZone1: " + ex); } } try { TimeZone zone = TimeZone.getDefault(); registered.put(zone.getClass(), JDKStringConverter.TIME_ZONE); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterTimeZone2: " + ex); } } try { TimeZone zone = TimeZone.getTimeZone("Europe/London"); registered.put(zone.getClass(), JDKStringConverter.TIME_ZONE); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterTimeZone3: " + ex); } } }
java
private void tryRegisterTimeZone() { try { registered.put(SimpleTimeZone.class, JDKStringConverter.TIME_ZONE); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterTimeZone1: " + ex); } } try { TimeZone zone = TimeZone.getDefault(); registered.put(zone.getClass(), JDKStringConverter.TIME_ZONE); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterTimeZone2: " + ex); } } try { TimeZone zone = TimeZone.getTimeZone("Europe/London"); registered.put(zone.getClass(), JDKStringConverter.TIME_ZONE); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterTimeZone3: " + ex); } } }
[ "private", "void", "tryRegisterTimeZone", "(", ")", "{", "try", "{", "registered", ".", "put", "(", "SimpleTimeZone", ".", "class", ",", "JDKStringConverter", ".", "TIME_ZONE", ")", ";", "}", "catch", "(", "Throwable", "ex", ")", "{", "if", "(", "LOG", "...
Tries to register the subclasses of TimeZone. Try various things, doesn't matter if the map entry gets overwritten.
[ "Tries", "to", "register", "the", "subclasses", "of", "TimeZone", ".", "Try", "various", "things", "doesn", "t", "matter", "if", "the", "map", "entry", "gets", "overwritten", "." ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/StringConvert.java#L267-L294
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/StringConvert.java
StringConvert.tryRegisterJava8
private void tryRegisterJava8() { try { tryRegister("java.time.Instant", "parse"); tryRegister("java.time.Duration", "parse"); tryRegister("java.time.LocalDate", "parse"); tryRegister("java.time.LocalTime", "parse"); tryRegister("java.time.LocalDateTime", "parse"); tryRegister("java.time.OffsetTime", "parse"); tryRegister("java.time.OffsetDateTime", "parse"); tryRegister("java.time.ZonedDateTime", "parse"); tryRegister("java.time.Year", "parse"); tryRegister("java.time.YearMonth", "parse"); tryRegister("java.time.MonthDay", "parse"); tryRegister("java.time.Period", "parse"); tryRegister("java.time.ZoneOffset", "of"); tryRegister("java.time.ZoneId", "of"); tryRegister("java.time.ZoneRegion", "of"); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterJava8: " + ex); } } }
java
private void tryRegisterJava8() { try { tryRegister("java.time.Instant", "parse"); tryRegister("java.time.Duration", "parse"); tryRegister("java.time.LocalDate", "parse"); tryRegister("java.time.LocalTime", "parse"); tryRegister("java.time.LocalDateTime", "parse"); tryRegister("java.time.OffsetTime", "parse"); tryRegister("java.time.OffsetDateTime", "parse"); tryRegister("java.time.ZonedDateTime", "parse"); tryRegister("java.time.Year", "parse"); tryRegister("java.time.YearMonth", "parse"); tryRegister("java.time.MonthDay", "parse"); tryRegister("java.time.Period", "parse"); tryRegister("java.time.ZoneOffset", "of"); tryRegister("java.time.ZoneId", "of"); tryRegister("java.time.ZoneRegion", "of"); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterJava8: " + ex); } } }
[ "private", "void", "tryRegisterJava8", "(", ")", "{", "try", "{", "tryRegister", "(", "\"java.time.Instant\"", ",", "\"parse\"", ")", ";", "tryRegister", "(", "\"java.time.Duration\"", ",", "\"parse\"", ")", ";", "tryRegister", "(", "\"java.time.LocalDate\"", ",", ...
Tries to register Java 8 classes.
[ "Tries", "to", "register", "Java", "8", "classes", "." ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/StringConvert.java#L299-L322
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/StringConvert.java
StringConvert.tryRegisterThreeTenBackport
private void tryRegisterThreeTenBackport() { try { tryRegister("org.threeten.bp.Instant", "parse"); tryRegister("org.threeten.bp.Duration", "parse"); tryRegister("org.threeten.bp.LocalDate", "parse"); tryRegister("org.threeten.bp.LocalTime", "parse"); tryRegister("org.threeten.bp.LocalDateTime", "parse"); tryRegister("org.threeten.bp.OffsetTime", "parse"); tryRegister("org.threeten.bp.OffsetDateTime", "parse"); tryRegister("org.threeten.bp.ZonedDateTime", "parse"); tryRegister("org.threeten.bp.Year", "parse"); tryRegister("org.threeten.bp.YearMonth", "parse"); tryRegister("org.threeten.bp.MonthDay", "parse"); tryRegister("org.threeten.bp.Period", "parse"); tryRegister("org.threeten.bp.ZoneOffset", "of"); tryRegister("org.threeten.bp.ZoneId", "of"); tryRegister("org.threeten.bp.ZoneRegion", "of"); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterThreeTenBackport: " + ex); } } }
java
private void tryRegisterThreeTenBackport() { try { tryRegister("org.threeten.bp.Instant", "parse"); tryRegister("org.threeten.bp.Duration", "parse"); tryRegister("org.threeten.bp.LocalDate", "parse"); tryRegister("org.threeten.bp.LocalTime", "parse"); tryRegister("org.threeten.bp.LocalDateTime", "parse"); tryRegister("org.threeten.bp.OffsetTime", "parse"); tryRegister("org.threeten.bp.OffsetDateTime", "parse"); tryRegister("org.threeten.bp.ZonedDateTime", "parse"); tryRegister("org.threeten.bp.Year", "parse"); tryRegister("org.threeten.bp.YearMonth", "parse"); tryRegister("org.threeten.bp.MonthDay", "parse"); tryRegister("org.threeten.bp.Period", "parse"); tryRegister("org.threeten.bp.ZoneOffset", "of"); tryRegister("org.threeten.bp.ZoneId", "of"); tryRegister("org.threeten.bp.ZoneRegion", "of"); } catch (Throwable ex) { if (LOG) { System.err.println("tryRegisterThreeTenBackport: " + ex); } } }
[ "private", "void", "tryRegisterThreeTenBackport", "(", ")", "{", "try", "{", "tryRegister", "(", "\"org.threeten.bp.Instant\"", ",", "\"parse\"", ")", ";", "tryRegister", "(", "\"org.threeten.bp.Duration\"", ",", "\"parse\"", ")", ";", "tryRegister", "(", "\"org.three...
Tries to register ThreeTen backport classes.
[ "Tries", "to", "register", "ThreeTen", "backport", "classes", "." ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/StringConvert.java#L327-L350
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/StringConvert.java
StringConvert.loadType
static Class<?> loadType(String fullName) throws ClassNotFoundException { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); return loader != null ? loader.loadClass(fullName) : Class.forName(fullName); } catch (ClassNotFoundException ex) { return loadPrimitiveType(fullName, ex); } }
java
static Class<?> loadType(String fullName) throws ClassNotFoundException { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); return loader != null ? loader.loadClass(fullName) : Class.forName(fullName); } catch (ClassNotFoundException ex) { return loadPrimitiveType(fullName, ex); } }
[ "static", "Class", "<", "?", ">", "loadType", "(", "String", "fullName", ")", "throws", "ClassNotFoundException", "{", "try", "{", "ClassLoader", "loader", "=", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "return", ...
loads a type avoiding nulls, context class loader if available
[ "loads", "a", "type", "avoiding", "nulls", "context", "class", "loader", "if", "available" ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/StringConvert.java#L854-L861
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/StringConvert.java
StringConvert.loadPrimitiveType
private static Class<?> loadPrimitiveType(String fullName, ClassNotFoundException ex) throws ClassNotFoundException { if (fullName.equals("int")) { return int.class; } else if (fullName.equals("long")) { return long.class; } else if (fullName.equals("double")) { return double.class; } else if (fullName.equals("boolean")) { return boolean.class; } else if (fullName.equals("short")) { return short.class; } else if (fullName.equals("byte")) { return byte.class; } else if (fullName.equals("char")) { return char.class; } else if (fullName.equals("float")) { return float.class; } else if (fullName.equals("void")) { return void.class; } throw ex; }
java
private static Class<?> loadPrimitiveType(String fullName, ClassNotFoundException ex) throws ClassNotFoundException { if (fullName.equals("int")) { return int.class; } else if (fullName.equals("long")) { return long.class; } else if (fullName.equals("double")) { return double.class; } else if (fullName.equals("boolean")) { return boolean.class; } else if (fullName.equals("short")) { return short.class; } else if (fullName.equals("byte")) { return byte.class; } else if (fullName.equals("char")) { return char.class; } else if (fullName.equals("float")) { return float.class; } else if (fullName.equals("void")) { return void.class; } throw ex; }
[ "private", "static", "Class", "<", "?", ">", "loadPrimitiveType", "(", "String", "fullName", ",", "ClassNotFoundException", "ex", ")", "throws", "ClassNotFoundException", "{", "if", "(", "fullName", ".", "equals", "(", "\"int\"", ")", ")", "{", "return", "int"...
handle primitive types
[ "handle", "primitive", "types" ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/StringConvert.java#L864-L885
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/AnnotationStringConverterFactory.java
AnnotationStringConverterFactory.findAnnotatedConverter
private <T> StringConverter<T> findAnnotatedConverter(final Class<T> cls) { Method toString = findToStringMethod(cls); // checks superclasses if (toString == null) { return null; } MethodConstructorStringConverter<T> con = findFromStringConstructor(cls, toString); MethodsStringConverter<T> mth = findFromStringMethod(cls, toString, con == null); // optionally checks superclasses if (con == null && mth == null) { throw new IllegalStateException("Class annotated with @ToString but not with @FromString: " + cls.getName()); } if (con != null && mth != null) { throw new IllegalStateException("Both method and constructor are annotated with @FromString: " + cls.getName()); } return (con != null ? con : mth); }
java
private <T> StringConverter<T> findAnnotatedConverter(final Class<T> cls) { Method toString = findToStringMethod(cls); // checks superclasses if (toString == null) { return null; } MethodConstructorStringConverter<T> con = findFromStringConstructor(cls, toString); MethodsStringConverter<T> mth = findFromStringMethod(cls, toString, con == null); // optionally checks superclasses if (con == null && mth == null) { throw new IllegalStateException("Class annotated with @ToString but not with @FromString: " + cls.getName()); } if (con != null && mth != null) { throw new IllegalStateException("Both method and constructor are annotated with @FromString: " + cls.getName()); } return (con != null ? con : mth); }
[ "private", "<", "T", ">", "StringConverter", "<", "T", ">", "findAnnotatedConverter", "(", "final", "Class", "<", "T", ">", "cls", ")", "{", "Method", "toString", "=", "findToStringMethod", "(", "cls", ")", ";", "// checks superclasses", "if", "(", "toString...
Finds a converter searching annotated. @param <T> the type of the converter @param cls the class to find a method for, not null @return the converter, not null @throws RuntimeException if none found
[ "Finds", "a", "converter", "searching", "annotated", "." ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/AnnotationStringConverterFactory.java#L62-L76
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/AnnotationStringConverterFactory.java
AnnotationStringConverterFactory.eliminateEnumSubclass
private Class<?> eliminateEnumSubclass(Class<?> cls) { Class<?> sup = cls.getSuperclass(); if (sup != null && sup.getSuperclass() == Enum.class) { return sup; } return cls; }
java
private Class<?> eliminateEnumSubclass(Class<?> cls) { Class<?> sup = cls.getSuperclass(); if (sup != null && sup.getSuperclass() == Enum.class) { return sup; } return cls; }
[ "private", "Class", "<", "?", ">", "eliminateEnumSubclass", "(", "Class", "<", "?", ">", "cls", ")", "{", "Class", "<", "?", ">", "sup", "=", "cls", ".", "getSuperclass", "(", ")", ";", "if", "(", "sup", "!=", "null", "&&", "sup", ".", "getSupercla...
eliminates enum subclass as they are pesky
[ "eliminates", "enum", "subclass", "as", "they", "are", "pesky" ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/AnnotationStringConverterFactory.java#L239-L245
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/RenameHandler.java
RenameHandler.createInstance
private static RenameHandler createInstance() { // log errors to System.err, as problems in static initializers can be troublesome to diagnose RenameHandler instance = create(false); try { // calling loadFromClasspath() is the best option even though it mutates INSTANCE // only serious errors will be caught here, most errors will log from parseRenameFile() instance.loadFromClasspath(); } catch (IllegalStateException ex) { System.err.println("ERROR: " + ex.getMessage()); ex.printStackTrace(); } catch (Throwable ex) { System.err.println("ERROR: Failed to load Renamed.ini files: " + ex.getMessage()); ex.printStackTrace(); } return instance; }
java
private static RenameHandler createInstance() { // log errors to System.err, as problems in static initializers can be troublesome to diagnose RenameHandler instance = create(false); try { // calling loadFromClasspath() is the best option even though it mutates INSTANCE // only serious errors will be caught here, most errors will log from parseRenameFile() instance.loadFromClasspath(); } catch (IllegalStateException ex) { System.err.println("ERROR: " + ex.getMessage()); ex.printStackTrace(); } catch (Throwable ex) { System.err.println("ERROR: Failed to load Renamed.ini files: " + ex.getMessage()); ex.printStackTrace(); } return instance; }
[ "private", "static", "RenameHandler", "createInstance", "(", ")", "{", "// log errors to System.err, as problems in static initializers can be troublesome to diagnose", "RenameHandler", "instance", "=", "create", "(", "false", ")", ";", "try", "{", "// calling loadFromClasspath()...
this is a method to aid IDE debugging of class initialization
[ "this", "is", "a", "method", "to", "aid", "IDE", "debugging", "of", "class", "initialization" ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/RenameHandler.java#L80-L96
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/RenameHandler.java
RenameHandler.lookupType
public Class<?> lookupType(String name) throws ClassNotFoundException { if (name == null) { throw new IllegalArgumentException("name must not be null"); } Class<?> type = typeRenames.get(name); if (type == null) { type = StringConvert.loadType(name); } return type; }
java
public Class<?> lookupType(String name) throws ClassNotFoundException { if (name == null) { throw new IllegalArgumentException("name must not be null"); } Class<?> type = typeRenames.get(name); if (type == null) { type = StringConvert.loadType(name); } return type; }
[ "public", "Class", "<", "?", ">", "lookupType", "(", "String", "name", ")", "throws", "ClassNotFoundException", "{", "if", "(", "name", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"name must not be null\"", ")", ";", "}", "Class"...
Lookup a type from a name, handling renames. @param name the name of the type to lookup, not null @return the type, not null @throws ClassNotFoundException if the name is not a valid type
[ "Lookup", "a", "type", "from", "a", "name", "handling", "renames", "." ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/RenameHandler.java#L191-L200
train
JodaOrg/joda-convert
src/main/java/org/joda/convert/RenameHandler.java
RenameHandler.lookupEnum
public <T extends Enum<T>> T lookupEnum(Class<T> type, String name) { if (type == null) { throw new IllegalArgumentException("type must not be null"); } if (name == null) { throw new IllegalArgumentException("name must not be null"); } Map<String, Enum<?>> map = getEnumRenames(type); Enum<?> value = map.get(name); if (value != null) { return type.cast(value); } return Enum.valueOf(type, name); }
java
public <T extends Enum<T>> T lookupEnum(Class<T> type, String name) { if (type == null) { throw new IllegalArgumentException("type must not be null"); } if (name == null) { throw new IllegalArgumentException("name must not be null"); } Map<String, Enum<?>> map = getEnumRenames(type); Enum<?> value = map.get(name); if (value != null) { return type.cast(value); } return Enum.valueOf(type, name); }
[ "public", "<", "T", "extends", "Enum", "<", "T", ">", ">", "T", "lookupEnum", "(", "Class", "<", "T", ">", "type", ",", "String", "name", ")", "{", "if", "(", "type", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"type mu...
Lookup an enum from a name, handling renames. @param <T> the type of the desired enum @param type the enum type, not null @param name the name of the enum to lookup, not null @return the enum value, not null @throws IllegalArgumentException if the name is not a valid enum constant
[ "Lookup", "an", "enum", "from", "a", "name", "handling", "renames", "." ]
266bd825f4550590d5dafdf4225c548559e0633b
https://github.com/JodaOrg/joda-convert/blob/266bd825f4550590d5dafdf4225c548559e0633b/src/main/java/org/joda/convert/RenameHandler.java#L267-L280
train
bazaarvoice/jersey-hmac-auth
client/src/main/java/com/bazaarvoice/auth/hmac/client/RequestEncoder.java
RequestEncoder.getSerializedEntity
private byte[] getSerializedEntity(ClientRequest request) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { // By using the RequestWriter parent class, we match the behavior of entity writing from // for example, com.sun.jersey.client.urlconnection.URLConnectionClientHandler. writeRequestEntity(request, new RequestEntityWriterListener() { public void onRequestEntitySize(long size) throws IOException { } public OutputStream onGetOutputStream() throws IOException { return outputStream; } }); } catch (IOException e) { throw new ClientHandlerException("Unable to serialize request entity", e); } return outputStream.toByteArray(); }
java
private byte[] getSerializedEntity(ClientRequest request) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { // By using the RequestWriter parent class, we match the behavior of entity writing from // for example, com.sun.jersey.client.urlconnection.URLConnectionClientHandler. writeRequestEntity(request, new RequestEntityWriterListener() { public void onRequestEntitySize(long size) throws IOException { } public OutputStream onGetOutputStream() throws IOException { return outputStream; } }); } catch (IOException e) { throw new ClientHandlerException("Unable to serialize request entity", e); } return outputStream.toByteArray(); }
[ "private", "byte", "[", "]", "getSerializedEntity", "(", "ClientRequest", "request", ")", "{", "final", "ByteArrayOutputStream", "outputStream", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "try", "{", "// By using the RequestWriter parent class, we match the behavio...
Get the serialized representation of the request entity. This is used when generating the client signature, because this is the representation that the server will receive and use when it generates the server-side signature to compare to the client-side signature. @see com.sun.jersey.client.urlconnection.URLConnectionClientHandler
[ "Get", "the", "serialized", "representation", "of", "the", "request", "entity", ".", "This", "is", "used", "when", "generating", "the", "client", "signature", "because", "this", "is", "the", "representation", "that", "the", "server", "will", "receive", "and", ...
17e2a40a4b7b783de4d77ad97f8a623af6baf688
https://github.com/bazaarvoice/jersey-hmac-auth/blob/17e2a40a4b7b783de4d77ad97f8a623af6baf688/client/src/main/java/com/bazaarvoice/auth/hmac/client/RequestEncoder.java#L98-L118
train
bazaarvoice/jersey-hmac-auth
common/src/main/java/com/bazaarvoice/auth/hmac/server/AbstractCachingAuthenticator.java
AbstractCachingAuthenticator.cachePrincipal
protected void cachePrincipal(String apiKey, Principal principal) { cache.put(apiKey, Optional.fromNullable(principal)); }
java
protected void cachePrincipal(String apiKey, Principal principal) { cache.put(apiKey, Optional.fromNullable(principal)); }
[ "protected", "void", "cachePrincipal", "(", "String", "apiKey", ",", "Principal", "principal", ")", "{", "cache", ".", "put", "(", "apiKey", ",", "Optional", ".", "fromNullable", "(", "principal", ")", ")", ";", "}" ]
Put this principal directly into cache. This can avoid lookup on user request and "prepay" the lookup cost. @param apiKey the api key @param principal the principal
[ "Put", "this", "principal", "directly", "into", "cache", ".", "This", "can", "avoid", "lookup", "on", "user", "request", "and", "prepay", "the", "lookup", "cost", "." ]
17e2a40a4b7b783de4d77ad97f8a623af6baf688
https://github.com/bazaarvoice/jersey-hmac-auth/blob/17e2a40a4b7b783de4d77ad97f8a623af6baf688/common/src/main/java/com/bazaarvoice/auth/hmac/server/AbstractCachingAuthenticator.java#L67-L69
train
bazaarvoice/jersey-hmac-auth
common/src/main/java/com/bazaarvoice/auth/hmac/server/AbstractAuthenticator.java
AbstractAuthenticator.validateTimestamp
private boolean validateTimestamp(String timestamp) { DateTime requestTime = TimeUtils.parse(timestamp); long difference = Math.abs(new Duration(requestTime, nowInUTC()).getMillis()); return difference <= allowedTimestampRange; }
java
private boolean validateTimestamp(String timestamp) { DateTime requestTime = TimeUtils.parse(timestamp); long difference = Math.abs(new Duration(requestTime, nowInUTC()).getMillis()); return difference <= allowedTimestampRange; }
[ "private", "boolean", "validateTimestamp", "(", "String", "timestamp", ")", "{", "DateTime", "requestTime", "=", "TimeUtils", ".", "parse", "(", "timestamp", ")", ";", "long", "difference", "=", "Math", ".", "abs", "(", "new", "Duration", "(", "requestTime", ...
To protect against replay attacks, make sure the timestamp on the request is valid by ensuring that the difference between the request time and the current time on the server does not fall outside the acceptable time range. Note that the request time may have been generated on a different machine and so it may be ahead or behind the current server time. @param timestamp the timestamp specified on the request (in standard ISO8601 format) @return true if the timestamp is valid
[ "To", "protect", "against", "replay", "attacks", "make", "sure", "the", "timestamp", "on", "the", "request", "is", "valid", "by", "ensuring", "that", "the", "difference", "between", "the", "request", "time", "and", "the", "current", "time", "on", "the", "ser...
17e2a40a4b7b783de4d77ad97f8a623af6baf688
https://github.com/bazaarvoice/jersey-hmac-auth/blob/17e2a40a4b7b783de4d77ad97f8a623af6baf688/common/src/main/java/com/bazaarvoice/auth/hmac/server/AbstractAuthenticator.java#L101-L105
train