_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q165700 | DynamicPropertyFactory.getFloatProperty | validation | public DynamicFloatProperty getFloatProperty(String propName, float defaultValue, final Runnable propertyChangeCallback) {
checkAndWarn(propName);
DynamicFloatProperty property = new DynamicFloatProperty(propName, defaultValue);
addCallback(propertyChangeCallback, property);
return property;
} | java | {
"resource": ""
} |
q165701 | DynamicPropertyFactory.getDoubleProperty | validation | public DynamicDoubleProperty getDoubleProperty(String propName, double defaultValue, final Runnable propertyChangeCallback) {
checkAndWarn(propName);
DynamicDoubleProperty property = new DynamicDoubleProperty(propName, defaultValue);
addCallback(propertyChangeCallback, property);
return property;
} | java | {
"resource": ""
} |
q165702 | DynamoDbDeploymentContextTableCache.loadPropertiesFromTable | validation | @Override
protected Map<String, PropertyWithDeploymentContext> loadPropertiesFromTable(String table) {
Map<String, PropertyWithDeploymentContext> propertyMap = new HashMap<String, PropertyWithDeploymentContext>();
Map<String, AttributeValue> lastKeysEvaluated = null;
do {
ScanRequest scanRequest = new ScanRequest()
.withTableName(table)
.withExclusiveStartKey(lastKeysEvaluated);
ScanResult result = dbScanWithThroughputBackOff(scanRequest);
for (Map<String, AttributeValue> item : result.getItems()) {
String keyVal = item.get(keyAttributeName.get()).getS();
//Need to deal with the fact that these attributes might not exist
DeploymentContext.ContextKey contextKey = item.containsKey(contextKeyAttributeName.get()) ? DeploymentContext.ContextKey.valueOf(item.get(contextKeyAttributeName.get()).getS()) : null;
String contextVal = item.containsKey(contextValueAttributeName.get()) ? item.get(contextValueAttributeName.get()).getS() : null;
String key = keyVal + ";" + contextKey + ";" + contextVal;
propertyMap.put(key,
new PropertyWithDeploymentContext(
contextKey,
contextVal,
keyVal,
item.get(valueAttributeName.get()).getS()
));
}
lastKeysEvaluated = result.getLastEvaluatedKey();
} while (lastKeysEvaluated != null);
return propertyMap;
} | java | {
"resource": ""
} |
q165703 | DynamicProperty.getInstance | validation | public static DynamicProperty getInstance(String propName) {
// This is to ensure that a configuration source is registered with
// DynamicProperty
if (dynamicPropertySupportImpl == null) {
DynamicPropertyFactory.getInstance();
}
DynamicProperty prop = ALL_PROPS.get(propName);
if (prop == null) {
prop = new DynamicProperty(propName);
DynamicProperty oldProp = ALL_PROPS.putIfAbsent(propName, prop);
if (oldProp != null) {
prop = oldProp;
}
}
return prop;
} | java | {
"resource": ""
} |
q165704 | DynamicProperty.updateAllProperties | validation | private static boolean updateAllProperties() {
boolean changed = false;
for (DynamicProperty prop : ALL_PROPS.values()) {
if (prop.updateValue()) {
prop.notifyCallbacks();
changed = true;
}
}
return changed;
} | java | {
"resource": ""
} |
q165705 | PropertyWrapper.addCallback | validation | @Override
public void addCallback(Runnable callback) {
if (callback != null) {
prop.addCallback(callback);
callbacks.add(callback);
}
} | java | {
"resource": ""
} |
q165706 | PropertyWrapper.removeAllCallbacks | validation | @Override
public void removeAllCallbacks() {
final Set<Runnable> callbacksToRemove = new HashSet<Runnable>(callbacks);
for (Runnable callback : callbacksToRemove) {
prop.removeCallback(callback);
}
callbacks.removeAll(callbacksToRemove);
} | java | {
"resource": ""
} |
q165707 | HttpVerbUriRegexPropertyValue.getVerbUriRegex | validation | public static HttpVerbUriRegexPropertyValue getVerbUriRegex(String propValue) {
HttpVerbUriRegexPropertyValue returnValue = null;
if (propValue != null) {
propValue = propValue.trim();
int methodSeparatorIndex = propValue.indexOf(METHOD_SEPARATOR);
String uriRegex = propValue; // to begin with
Verb verb = Verb.ANY_VERB;
if (methodSeparatorIndex != -1) {
// user may have supplied a verb
verb = getVerb(propValue.substring(0, methodSeparatorIndex));
if (verb != Verb.ANY_VERB) {
// update uriRegex
uriRegex = propValue.substring(methodSeparatorIndex + 1);
}
}
returnValue = new HttpVerbUriRegexPropertyValue(verb, uriRegex);
}
return returnValue;
} | java | {
"resource": ""
} |
q165708 | ConfigurationUtils.loadPropertiesFromInputStream | validation | public static Properties loadPropertiesFromInputStream(InputStream fin) throws IOException {
Properties props = new Properties();
InputStreamReader reader = new InputStreamReader(fin, "UTF-8");
try {
props.load(reader);
return props;
} finally {
if (reader != null) {
reader.close();
}
if (fin != null) {
fin.close();
}
}
} | java | {
"resource": ""
} |
q165709 | OverridingPropertiesConfiguration.addProperty | validation | @Override
public void addProperty(String name, Object value) {
if (containsKey(name)) {
// clear without triggering an event
clearPropertyDirect(name);
}
super.addProperty(name, value);
} | java | {
"resource": ""
} |
q165710 | DynamicPropertyUpdater.updateProperties | validation | public void updateProperties(final WatchedUpdateResult result, final Configuration config,
final boolean ignoreDeletesFromSource) {
if (result == null || !result.hasChanges()) {
return;
}
logger.debug("incremental result? [{}]", result.isIncremental());
logger.debug("ignored deletes from source? [{}]", ignoreDeletesFromSource);
if (!result.isIncremental()) {
Map<String, Object> props = result.getComplete();
if (props == null) {
return;
}
for (Entry<String, Object> entry : props.entrySet()) {
addOrChangeProperty(entry.getKey(), entry.getValue(), config);
}
Set<String> existingKeys = new HashSet<String>();
for (Iterator<String> i = config.getKeys(); i.hasNext();) {
existingKeys.add(i.next());
}
if (!ignoreDeletesFromSource) {
for (String key : existingKeys) {
if (!props.containsKey(key)) {
deleteProperty(key, config);
}
}
}
} else {
Map<String, Object> props = result.getAdded();
if (props != null) {
for (Entry<String, Object> entry : props.entrySet()) {
addOrChangeProperty(entry.getKey(), entry.getValue(), config);
}
}
props = result.getChanged();
if (props != null) {
for (Entry<String, Object> entry : props.entrySet()) {
addOrChangeProperty(entry.getKey(), entry.getValue(), config);
}
}
if (!ignoreDeletesFromSource) {
props = result.getDeleted();
if (props != null) {
for (String name : props.keySet()) {
deleteProperty(name, config);
}
}
}
}
} | java | {
"resource": ""
} |
q165711 | DynamicPropertyUpdater.addOrChangeProperty | validation | void addOrChangeProperty(final String name, final Object newValue, final Configuration config) {
// We do not want to abort the operation due to failed validation on one property
try {
if (!config.containsKey(name)) {
logger.debug("adding property key [{}], value [{}]", name, newValue);
config.addProperty(name, newValue);
} else {
Object oldValue = config.getProperty(name);
if (newValue != null) {
Object newValueArray;
if (oldValue instanceof CopyOnWriteArrayList && AbstractConfiguration.getDefaultListDelimiter() != '\0'){
newValueArray =
new CopyOnWriteArrayList();
Iterable<String> stringiterator = Splitter.on(AbstractConfiguration.getDefaultListDelimiter()).omitEmptyStrings().trimResults().split((String)newValue);
for(String s :stringiterator){
((CopyOnWriteArrayList) newValueArray).add(s);
}
} else {
newValueArray = newValue;
}
if (!newValueArray.equals(oldValue)) {
logger.debug("updating property key [{}], value [{}]", name, newValue);
config.setProperty(name, newValue);
}
} else if (oldValue != null) {
logger.debug("nulling out property key [{}]", name);
config.setProperty(name, null);
}
}
} catch (ValidationException e) {
logger.warn("Validation failed for property " + name, e);
}
} | java | {
"resource": ""
} |
q165712 | DynamicPropertyUpdater.deleteProperty | validation | void deleteProperty(final String key, final Configuration config) {
if (config.containsKey(key)) {
logger.debug("deleting property key [" + key + "]");
config.clearProperty(key);
}
} | java | {
"resource": ""
} |
q165713 | ConcurrentMapConfiguration.clear | validation | @Override
public void clear()
{
fireEvent(EVENT_CLEAR, null, null, true);
map.clear();
fireEvent(EVENT_CLEAR, null, null, false);
} | java | {
"resource": ""
} |
q165714 | ConcurrentMapConfiguration.getProperties | validation | public Properties getProperties() {
Properties p = new Properties();
for (Iterator i = getKeys(); i.hasNext();) {
String name = (String) i.next();
String value = getString(name);
p.put(name, value);
}
return p;
} | java | {
"resource": ""
} |
q165715 | AbstractPollingScheduler.initialLoad | validation | protected synchronized void initialLoad(final PolledConfigurationSource source, final Configuration config) {
PollResult result = null;
try {
result = source.poll(true, null);
checkPoint = result.getCheckPoint();
fireEvent(EventType.POLL_SUCCESS, result, null);
} catch (Throwable e) {
throw new RuntimeException("Unable to load Properties source from " + source, e);
}
try {
populateProperties(result, config);
} catch (Throwable e) {
throw new RuntimeException("Unable to load Properties", e);
}
} | java | {
"resource": ""
} |
q165716 | ConcurrentCompositeConfiguration.addConfigurationAtIndex | validation | public void addConfigurationAtIndex(AbstractConfiguration config, String name, int index)
throws IndexOutOfBoundsException {
if (!configList.contains(config)) {
checkIndex(index);
configList.add(index, config);
if (name != null) {
namedConfigurations.put(name, config);
}
config.addConfigurationListener(eventPropagater);
fireEvent(EVENT_CONFIGURATION_SOURCE_CHANGED, null, null, false);
} else {
logger.warn(config + " is not added as it already exits");
}
} | java | {
"resource": ""
} |
q165717 | ConcurrentCompositeConfiguration.removeConfiguration | validation | public boolean removeConfiguration(Configuration config)
{
// Make sure that you can't remove the inMemoryConfiguration from
// the CompositeConfiguration object
if (!config.equals(containerConfiguration))
{
String configName = getNameForConfiguration(config);
if (configName != null) {
namedConfigurations.remove(configName);
}
return configList.remove(config);
} else {
throw new IllegalArgumentException("Can't remove container configuration");
}
} | java | {
"resource": ""
} |
q165718 | ConcurrentCompositeConfiguration.removeConfiguration | validation | public Configuration removeConfiguration(String name)
{
Configuration conf = getConfiguration(name);
if (conf != null && !conf.equals(containerConfiguration))
{
configList.remove(conf);
namedConfigurations.remove(name);
} else if (conf != null && conf.equals(containerConfiguration)) {
throw new IllegalArgumentException("Can't remove container configuration");
}
return conf;
} | java | {
"resource": ""
} |
q165719 | ConcurrentCompositeConfiguration.getKeys | validation | public Iterator<String> getKeys() throws ConcurrentModificationException
{
Set<String> keys = new LinkedHashSet<String>();
for (Iterator<String> it = overrideProperties.getKeys(); it.hasNext();) {
keys.add(it.next());
}
for (Configuration config : configList)
{
for (Iterator<String> it = config.getKeys(); it.hasNext();)
{
try {
keys.add(it.next());
} catch (ConcurrentModificationException e) {
logger.error("unexpected exception when iterating the keys for configuration " + config
+ " with name " + getNameForConfiguration(config));
throw e;
}
}
}
return keys.iterator();
} | java | {
"resource": ""
} |
q165720 | ConcurrentCompositeConfiguration.getKeys | validation | @Override
public Iterator<String> getKeys(String prefix)
{
Set<String> keys = new LinkedHashSet<String>();
for (Iterator<String> it = overrideProperties.getKeys(prefix); it.hasNext();) {
keys.add(it.next());
}
for (Configuration config : configList)
{
for (Iterator<String> it = config.getKeys(prefix); it.hasNext();)
{
keys.add(it.next());
}
}
return keys.iterator();
} | java | {
"resource": ""
} |
q165721 | ConcurrentCompositeConfiguration.containsKey | validation | @Override
public boolean containsKey(String key)
{
if (overrideProperties.containsKey(key)) {
return true;
}
for (Configuration config : configList)
{
if (config.containsKey(key))
{
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q165722 | ConcurrentCompositeConfiguration.getList | validation | @Override
public List getList(String key, List defaultValue)
{
List<Object> list = new ArrayList<Object>();
// add all elements from the first configuration containing the requested key
Iterator<AbstractConfiguration> it = configList.iterator();
if (overrideProperties.containsKey(key)) {
appendListProperty(list, overrideProperties, key);
}
while (it.hasNext() && list.isEmpty())
{
Configuration config = it.next();
if ((config != containerConfiguration || containerConfigurationChanged)
&& config.containsKey(key))
{
appendListProperty(list, config, key);
}
}
// add all elements from the in memory configuration
if (list.isEmpty()) {
appendListProperty(list, containerConfiguration, key);
}
if (list.isEmpty())
{
return defaultValue;
}
ListIterator<Object> lit = list.listIterator();
while (lit.hasNext())
{
lit.set(interpolate(lit.next()));
}
return list;
} | java | {
"resource": ""
} |
q165723 | ConcurrentCompositeConfiguration.getStringArray | validation | @Override
public String[] getStringArray(String key)
{
List<Object> list = getList(key);
// transform property values into strings
String[] tokens = new String[list.size()];
for (int i = 0; i < tokens.length; i++)
{
tokens[i] = String.valueOf(list.get(i));
}
return tokens;
} | java | {
"resource": ""
} |
q165724 | ConfigurationManager.loadCascadedPropertiesFromResources | validation | public static void loadCascadedPropertiesFromResources(String configName) throws IOException {
Properties props = loadCascadedProperties(configName);
if (instance instanceof AggregatedConfiguration) {
ConcurrentMapConfiguration config = new ConcurrentMapConfiguration();
config.loadProperties(props);
((AggregatedConfiguration) instance).addConfiguration(config, configName);
} else {
ConfigurationUtils.loadProperties(props, instance);
}
} | java | {
"resource": ""
} |
q165725 | ConfigurationManager.loadPropertiesFromConfiguration | validation | public static void loadPropertiesFromConfiguration(AbstractConfiguration config) {
if (instance == null) {
instance = getConfigInstance();
}
if (instance instanceof AggregatedConfiguration) {
((AggregatedConfiguration) instance).addConfiguration(config);
} else {
Properties props = ConfigurationUtils.getProperties(config);
ConfigurationUtils.loadProperties(props, instance);
}
} | java | {
"resource": ""
} |
q165726 | ConfigurationManager.loadProperties | validation | public static void loadProperties(Properties properties) {
if (instance == null) {
instance = getConfigInstance();
}
ConfigurationUtils.loadProperties(properties, instance);
} | java | {
"resource": ""
} |
q165727 | URLConfigurationSource.poll | validation | @Override
public PollResult poll(boolean initial, Object checkPoint)
throws IOException {
if (configUrls == null || configUrls.length == 0) {
return PollResult.createFull(null);
}
Map<String, Object> map = new HashMap<String, Object>();
for (URL url: configUrls) {
InputStream fin = url.openStream();
Properties props = ConfigurationUtils.loadPropertiesFromInputStream(fin);
for (Entry<Object, Object> entry: props.entrySet()) {
map.put((String) entry.getKey(), entry.getValue());
}
}
return PollResult.createFull(map);
} | java | {
"resource": ""
} |
q165728 | Location.getAngle | validation | public double getAngle(Location location) {
// Euclidean distance (Pythagorean theorem) - not correct when the surface is a sphere
double latitudeDifference = location.latitude - latitude;
double longitudeDifference = location.longitude - longitude;
return Math.atan2(latitudeDifference, longitudeDifference);
} | java | {
"resource": ""
} |
q165729 | ConcurrentMemoization.computeIfAbsent | validation | @Override
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {
// This might look like a Double Checked Idiom (which is broken), but it is not
// because value is not a global variable
V value = get(key);
if (value != null) {
return value;
}
return super.computeIfAbsent(key, mappingFunction);
} | java | {
"resource": ""
} |
q165730 | CloudBalancingGenerator.main | validation | public static void main(String[] args) {
CloudBalancingGenerator generator = new CloudBalancingGenerator();
generator.writeCloudBalance(2, 6);
generator.writeCloudBalance(3, 9);
generator.writeCloudBalance(4, 12);
// generator.writeCloudBalance(5, 15);
// generator.writeCloudBalance(6, 18);
// generator.writeCloudBalance(7, 21);
// generator.writeCloudBalance(8, 24);
// generator.writeCloudBalance(9, 27);
// generator.writeCloudBalance(10, 30);
// generator.writeCloudBalance(11, 33);
// generator.writeCloudBalance(12, 36);
// generator.writeCloudBalance(13, 39);
// generator.writeCloudBalance(14, 42);
// generator.writeCloudBalance(15, 45);
// generator.writeCloudBalance(16, 48);
// generator.writeCloudBalance(17, 51);
// generator.writeCloudBalance(18, 54);
// generator.writeCloudBalance(19, 57);
// generator.writeCloudBalance(20, 60);
generator.writeCloudBalance(100, 300);
generator.writeCloudBalance(200, 600);
generator.writeCloudBalance(400, 1200);
generator.writeCloudBalance(800, 2400);
generator.writeCloudBalance(1600, 4800);
} | java | {
"resource": ""
} |
q165731 | ReflectionHelper.getGetterPropertyName | validation | public static String getGetterPropertyName(Member member) {
if (member instanceof Field) {
return member.getName();
} else if (member instanceof Method) {
String methodName = member.getName();
for (String prefix : PROPERTY_ACCESSOR_PREFIXES) {
if (methodName.startsWith(prefix)) {
return decapitalizePropertyName(methodName.substring(prefix.length()));
}
}
}
return null;
} | java | {
"resource": ""
} |
q165732 | ReflectionHelper.isGetterMethod | validation | public static boolean isGetterMethod(Method method) {
if (method.getParameterTypes().length != 0) {
return false;
}
String methodName = method.getName();
if (methodName.startsWith(PROPERTY_ACCESSOR_PREFIX_GET) && method.getReturnType() != void.class) {
return true;
} else if (methodName.startsWith(PROPERTY_ACCESSOR_PREFIX_IS) && method.getReturnType() == boolean.class) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q165733 | HardMediumSoftBigDecimalScoreHolder.addHardConstraintMatch | validation | public void addHardConstraintMatch(RuleContext kcontext, BigDecimal hardWeight) {
hardScore = hardScore.add(hardWeight);
registerConstraintMatch(kcontext,
() -> hardScore = hardScore.subtract(hardWeight),
() -> HardMediumSoftBigDecimalScore.of(hardWeight, BigDecimal.ZERO, BigDecimal.ZERO));
} | java | {
"resource": ""
} |
q165734 | HardMediumSoftBigDecimalScoreHolder.addMediumConstraintMatch | validation | public void addMediumConstraintMatch(RuleContext kcontext, BigDecimal mediumWeight) {
mediumScore = mediumScore.add(mediumWeight);
registerConstraintMatch(kcontext,
() -> mediumScore = mediumScore.subtract(mediumWeight),
() -> HardMediumSoftBigDecimalScore.of(BigDecimal.ZERO, mediumWeight, BigDecimal.ZERO));
} | java | {
"resource": ""
} |
q165735 | HardMediumSoftBigDecimalScoreHolder.addSoftConstraintMatch | validation | public void addSoftConstraintMatch(RuleContext kcontext, BigDecimal softWeight) {
softScore = softScore.add(softWeight);
registerConstraintMatch(kcontext,
() -> softScore = softScore.subtract(softWeight),
() -> HardMediumSoftBigDecimalScore.of(BigDecimal.ZERO, BigDecimal.ZERO, softWeight));
} | java | {
"resource": ""
} |
q165736 | ReflectionsWorkaroundClasspathHelper.cleanPath | validation | public static String cleanPath(final URL url) {
String path = url.getPath();
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) { /**/ }
if (path.startsWith("jar:")) {
path = path.substring("jar:".length());
}
if (path.startsWith("file:")) {
path = path.substring("file:".length());
}
if (path.endsWith("!/")) {
path = path.substring(0, path.lastIndexOf("!/")) + "/";
}
return path;
} | java | {
"resource": ""
} |
q165737 | InvestmentSolution.calculateStandardDeviationSquaredFemtos | validation | public long calculateStandardDeviationSquaredFemtos() {
long totalFemtos = 0L;
for (AssetClassAllocation a : assetClassAllocationList) {
for (AssetClassAllocation b : assetClassAllocationList) {
if (a == b) {
totalFemtos += a.getQuantifiedStandardDeviationRiskMicros() * b.getQuantifiedStandardDeviationRiskMicros()
* 1000L;
} else {
// Matches twice: once for (A, B) and once for (B, A)
long correlationMillis = a.getAssetClass().getCorrelationMillisMap().get(b.getAssetClass());
totalFemtos += a.getQuantifiedStandardDeviationRiskMicros() * b.getQuantifiedStandardDeviationRiskMicros()
* correlationMillis;
}
}
}
return totalFemtos;
} | java | {
"resource": ""
} |
q165738 | SolutionDescriptor.checkIfProblemFactsExist | validation | public void checkIfProblemFactsExist() {
if (problemFactCollectionMemberAccessorMap.isEmpty() && problemFactMemberAccessorMap.isEmpty()) {
throw new IllegalStateException("The solutionClass (" + solutionClass
+ ") must have at least 1 member with a "
+ ProblemFactCollectionProperty.class.getSimpleName() + " annotation or a "
+ ProblemFactProperty.class.getSimpleName() + " annotation"
+ " when used with Drools score calculation.");
}
} | java | {
"resource": ""
} |
q165739 | SolutionDescriptor.getProblemScale | validation | public long getProblemScale(Solution_ solution) {
long problemScale = 0L;
for (Iterator<Object> it = extractAllEntitiesIterator(solution); it.hasNext(); ) {
Object entity = it.next();
EntityDescriptor<Solution_> entityDescriptor = findEntityDescriptorOrFail(entity.getClass());
problemScale += entityDescriptor.getProblemScale(solution, entity);
}
return problemScale;
} | java | {
"resource": ""
} |
q165740 | ParSeqRestClient.generateTaskName | validation | static String generateTaskName(final Request<?> request) {
return request.getBaseUriTemplate() + " "
+ OperationNameGenerator.generate(request.getMethod(), request.getMethodName());
} | java | {
"resource": ""
} |
q165741 | ParSeqRestClient.hasRequestContextTimeout | validation | private boolean hasRequestContextTimeout(RequestContext requestContext) {
Object requestTimeout = requestContext.getLocalAttr(R2Constants.REQUEST_TIMEOUT);
return (requestTimeout instanceof Number) && (((Number)requestTimeout).intValue() > 0);
} | java | {
"resource": ""
} |
q165742 | ParSeqRestClient.needApplyTaskTimeout | validation | private boolean needApplyTaskTimeout(RequestContext requestContext, ConfigValue<Long> timeout) {
// return false if no timeout configured or per-request timeout already specified in request context
return timeout.getValue() != null && timeout.getValue() > 0 && !hasRequestContextTimeout(requestContext);
} | java | {
"resource": ""
} |
q165743 | ParSeqRestClient.createTaskWithTimeout | validation | private <T> Task<Response<T>> createTaskWithTimeout(final String name, final Request<T> request,
final RequestContext requestContext, RequestConfig config) {
ConfigValue<Long> timeout = config.getTimeoutMs();
Task<Response<T>> requestTask;
if (RequestGroup.isBatchable(request, config)) {
requestTask = createBatchableTask(name, request, requestContext, config);
} else {
requestTask = Task.async(name, () -> sendRequest(request, requestContext));
}
if (!needApplyTaskTimeout(requestContext, timeout)) {
return requestTask;
} else {
return withTimeout(requestTask, timeout);
}
} | java | {
"resource": ""
} |
q165744 | GraphvizEngine.build | validation | public Task<HttpResponse> build(final String hash, final InputStream body)
throws IOException {
if (hash == null) {
// Missing hash
String content = "Missing hash.";
LOG.info(content);
return Task.value(new HttpResponse(HttpServletResponse.SC_BAD_REQUEST, content));
} else {
// Have cache
if (_hashManager.contains(hash)) {
LOG.info("hash found in cache: " + hash);
return Task.value(new HttpResponse(HttpServletResponse.SC_OK, ""));
} else {
if (body == null) {
// Missing body
String content = "Missing body.";
LOG.info(content);
return Task.value(new HttpResponse(HttpServletResponse.SC_BAD_REQUEST, content));
} else if (_dotLocation == null) {
// Missing dot
String content = "Missing dot.";
LOG.info(content);
return Task.value(new HttpResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, content));
} else {
// Build task
final Task<Exec.Result> buildTask = getBuildTask(hash, body);
return buildTask.transform("result", result -> {
Integer status = null;
String content = null;
if (result.isFailed()) {
// Task fail
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
content = result.getError().toString();
} else {
// Task success
switch (result.get().getStatus()) {
// Success
case 0:
_hashManager.add(hash);
status = HttpServletResponse.SC_OK;
content = "";
break;
// Timeout
case 137:
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
content = "graphviz process was killed because it did not finish within " + _timeoutMs + "ms";
break;
// Unknown
default:
status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
content = writeGenericFailureInfo(result.get());
break;
}
}
// Clean up cache
_inFlightBuildTasks.remove(hash, buildTask);
return Success.of(new HttpResponse(status, content));
});
}
}
}
} | java | {
"resource": ""
} |
q165745 | GraphvizEngine.getBuildTask | validation | private Task<Exec.Result> getBuildTask(final String hash, final InputStream body) {
Task<Exec.Result> existing = _inFlightBuildTasks.get(hash);
if (existing != null) {
LOG.info("using in flight shareable: " + hash);
return existing.shareable();
} else {
Task<Exec.Result> newBuildTask = createNewBuildTask(hash, body);
existing = _inFlightBuildTasks.putIfAbsent(hash, newBuildTask);
if (existing != null) {
LOG.info("using in flight shareable: " + hash);
return existing.shareable();
} else {
return newBuildTask;
}
}
} | java | {
"resource": ""
} |
q165746 | GraphvizEngine.createNewBuildTask | validation | private Task<Exec.Result> createNewBuildTask(final String hash, final InputStream body) {
LOG.info("building: " + hash);
final Task<Void> createDotFile = Task.action("createDotFile",
() -> Files.copy(body, pathToCacheFile(hash, "dot"), StandardCopyOption.REPLACE_EXISTING));
// Task that runs a graphviz command.
// We give process TIMEOUT_MS time to finish, after that
// it will be forcefully killed.
final Task<Exec.Result> graphviz = _exec
.command("graphviz", _timeoutMs, TimeUnit.MILLISECONDS, _dotLocation, "-T" + Constants.OUTPUT_TYPE,
"-Grankdir=LR", "-Gnewrank=true", "-Gbgcolor=transparent", pathToCacheFile(hash, "dot").toString(), "-o",
pathToCacheFile(hash, Constants.OUTPUT_TYPE).toString());
// Since Exec utility allows only certain number of processes
// to run in parallel and rest is enqueued, we also specify
// timeout on a task level equal to 2 * graphviz timeout.
final Task<Exec.Result> graphvizWithTimeout = graphviz.withTimeout(_timeoutMs * 2, TimeUnit.MILLISECONDS);
return createDotFile.andThen(graphvizWithTimeout);
} | java | {
"resource": ""
} |
q165747 | GraphvizEngine.writeGenericFailureInfo | validation | private String writeGenericFailureInfo(final Exec.Result result)
throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("graphviz process returned: ").append(result.getStatus()).append("\n").append("stdout:\n");
Files.lines(result.getStdout()).forEach(sb::append);
sb.append("stderr:\n");
Files.lines(result.getStderr()).forEach(sb::append);
return sb.toString();
} | java | {
"resource": ""
} |
q165748 | Trace.single | validation | public static Trace single(ShallowTrace shallowTrace) {
return single(shallowTrace, TraceBuilder.UNKNOWN_PLAN_CLASS, TraceBuilder.UNKNOWN_PLAN_ID);
} | java | {
"resource": ""
} |
q165749 | BatchingStrategy.batchable | validation | public Task<T> batchable(final String desc, final K key) {
Task<T> batchableTask = Task.async(desc, ctx -> {
final BatchPromise<T> result = new BatchPromise<>();
final Long planId = ctx.getPlanId();
final GroupBatchBuilder builder = _batches.computeIfAbsent(planId, k -> new GroupBatchBuilder());
final G group = classify(key);
Batch<K, T> fullBatch = builder.add(group, key, ctx.getShallowTraceBuilder(), result);
if (fullBatch != null) {
try {
ctx.run(taskForBatch(group, fullBatch, true));
} catch (Throwable t) {
//we don't care if some of promises have already been completed
//all we care is that all remaining promises have been failed
fullBatch.failAll(t);
}
}
return result;
});
batchableTask.getShallowTraceBuilder().setTaskType("batched");
return batchableTask;
} | java | {
"resource": ""
} |
q165750 | BatchingStrategy.getBatchName | validation | public String getBatchName(G group, Batch<K, T> batch) {
return "batch(keys: " + batch.keySize() + ", size: " + batch.batchSize() + ")";
} | java | {
"resource": ""
} |
q165751 | BatchAggregationTimeMetric.harvest | validation | public synchronized <T> T harvest(Function<Histogram, T> consumer) {
initializeRecorder();
_recycle = _recorder.getIntervalHistogram(_recycle);
return consumer.apply(_recycle);
} | java | {
"resource": ""
} |
q165752 | RequestConfigProviderImpl.createDefaultConfig | validation | private static ParSeqRestliClientConfig createDefaultConfig() {
ParSeqRestliClientConfigBuilder builder = new ParSeqRestliClientConfigBuilder();
builder.addTimeoutMs("*.*/*.*", DEFAULT_TIMEOUT);
builder.addBatchingEnabled("*.*/*.*", DEFAULT_BATCHING_ENABLED);
builder.addMaxBatchSize("*.*/*.*", DEFAULT_MAX_BATCH_SIZE);
return builder.build();
} | java | {
"resource": ""
} |
q165753 | FusionTask.compose | validation | private <R> Consumer3<FusionTraceContext, Promise<S>, Settable<T>> compose(
final Consumer3<FusionTraceContext, Promise<S>, Settable<R>> predecessor,
final Consumer3<FusionTraceContext, Promise<R>, Settable<T>> propagator) {
return (traceContext, src, dst) -> {
/*
* At this point we know that transformation chain's length > 1.
* This code is executed during task execution, not when task is constructed.
*/
traceContext.createSurrogate();
predecessor.accept(traceContext, src, new Settable<R>() {
@Override
public void done(R value) throws PromiseResolvedException {
try {
/* Track start time of the transformation. End time is tracked by closure created by completing() */
getEffectiveShallowTraceBuilder(traceContext).setStartNanos(System.nanoTime());
propagator.accept(traceContext, Promises.value(value), dst);
} catch (Exception e) {
/* This can only happen if there is an internal problem. Propagators should not throw any exceptions. */
LOGGER.error("ParSeq ingternal error. An exception was thrown by propagator", e);
}
}
@Override
public void fail(Throwable error) throws PromiseResolvedException {
try {
/* Track start time of the transformation. End time is tracked by closure created by completing() */
getEffectiveShallowTraceBuilder(traceContext).setStartNanos(System.nanoTime());
propagator.accept(traceContext, Promises.error(error), dst);
} catch (Exception e) {
/* This can only happen if there is an internal problem. Propagators should not throw any exceptions. */
LOGGER.error("ParSeq ingternal error. An exception was thrown by propagator.", e);
}
}
});
};
} | java | {
"resource": ""
} |
q165754 | FusionTask.create | validation | public static <S, T> FusionTask<?, T> create(final String name, final Task<S> task, final PromisePropagator<S, T> propagator) {
return new FusionTask<S, T>(name, task, propagator);
} | java | {
"resource": ""
} |
q165755 | EngineBuilder.setEngineProperty | validation | public EngineBuilder setEngineProperty(String key, Object value) {
_properties.put(key, value);
return this;
} | java | {
"resource": ""
} |
q165756 | Promises.value | validation | @SuppressWarnings("unchecked")
public static <T> Promise<T> value(final T value) {
if (value == null) {
if (VOID == null) {
return new ResolvedValue<T>(value);
} else {
return (Promise<T>) VOID;
}
}
return new ResolvedValue<T>(value);
} | java | {
"resource": ""
} |
q165757 | Promises.propagateResult | validation | public static <T> void propagateResult(final Promise<T> source, final Settable<T> dest) {
source.addListener(new TransformingPromiseListener<T, T>(dest, PromiseTransformer.identity()));
} | java | {
"resource": ""
} |
q165758 | Examples.createResilientSummary | validation | Task<String> createResilientSummary(int id) {
return fetchPerson(id).map(this::shortSummary).recover(e -> "Member " + id);
} | java | {
"resource": ""
} |
q165759 | Examples.createResponsiveSummary | validation | Task<String> createResponsiveSummary(int id) {
return fetchPerson(id).withTimeout(100, TimeUnit.MILLISECONDS).map(this::shortSummary).recover(e -> "Member " + id);
} | java | {
"resource": ""
} |
q165760 | Examples.createConnectionsSummaries | validation | Task<List<String>> createConnectionsSummaries(int id) {
return fetchPerson(id).flatMap("createConnectionsSummaries", person -> createConnectionsSummaries(person.getConnections()));
} | java | {
"resource": ""
} |
q165761 | Tasks.withSideEffect | validation | @Deprecated
public static <T> Task<T> withSideEffect(final Task<T> parent, final Task<?> sideEffect) {
return parent.withSideEffect(t -> sideEffect);
} | java | {
"resource": ""
} |
q165762 | Tasks.timeoutWithError | validation | @Deprecated
public static <T> Task<T> timeoutWithError(final long time, final TimeUnit unit, final Task<T> task) {
return task.withTimeout(time, unit);
} | java | {
"resource": ""
} |
q165763 | ZKUtil.findNodeWithNextLowestSN | validation | public static String findNodeWithNextLowestSN(List<String> children, String node) {
List<String> sortedChildren = children.stream()
.sorted((String o1, String o2) ->
Long.compare(getSequenceNumber(o1), getSequenceNumber(o2)))
.collect(Collectors.toList());
int index = sortedChildren.indexOf(node);
if (index > 0) {
return sortedChildren.get(index-1);
} else if (index == 0) {
return node;
} else {
return null;
}
} | java | {
"resource": ""
} |
q165764 | BaseTask.appendTaskStackTrace | validation | private void appendTaskStackTrace(final Throwable error) {
StackTraceElement[] taskStackTrace = _taskStackTraceHolder != null ? _taskStackTraceHolder.getStackTrace() : null;
// At a minimum, any stack trace should have at least 3 stack frames (caller + BaseTask + getStackTrace).
// So if there are less than 3 stack frames available then there's something fishy and it's better to ignore them.
if (!ParSeqGlobalConfiguration.isCrossThreadStackTracesEnabled() || error == null ||
taskStackTrace == null || taskStackTrace.length <= 2) {
return;
}
StackTraceElement[] errorStackTrace = error.getStackTrace();
if (errorStackTrace.length <= 2) {
return;
}
// Skip stack frames up to the BaseTask (useless java.util.concurrent stuff)
int skipErrorFrames = 1;
while (skipErrorFrames < errorStackTrace.length) {
int index = errorStackTrace.length - 1 - skipErrorFrames;
if (!errorStackTrace[index].getClassName().equals(CANONICAL_NAME) &&
errorStackTrace[index + 1].getClassName().equals(CANONICAL_NAME)) {
break;
}
skipErrorFrames++;
}
// Safeguard against accidentally removing entire stack trace
if (skipErrorFrames == errorStackTrace.length) {
skipErrorFrames = 0;
}
// Skip stack frames up to the BaseTask (useless Thread.getStackTrace stuff)
int skipTaskFrames = 1;
while (skipTaskFrames < taskStackTrace.length) {
if (!taskStackTrace[skipTaskFrames].getClassName().equals(CANONICAL_NAME) &&
taskStackTrace[skipTaskFrames - 1].getClassName().equals(CANONICAL_NAME)) {
break;
}
skipTaskFrames++;
}
// Safeguard against accidentally removing entire stack trace
if (skipTaskFrames == taskStackTrace.length) {
skipTaskFrames = 0;
}
int combinedLength = errorStackTrace.length - skipErrorFrames + taskStackTrace.length - skipTaskFrames;
if (combinedLength <= 0) {
return;
}
StackTraceElement[] concatenatedStackTrace = new StackTraceElement[combinedLength + 1];
System.arraycopy(errorStackTrace, 0, concatenatedStackTrace,
0, errorStackTrace.length - skipErrorFrames);
concatenatedStackTrace[errorStackTrace.length - skipErrorFrames] =
new StackTraceElement("********** Task \"" + getName() + "\" (above) was instantiated as following (below): **********", "",null, 0);
System.arraycopy(taskStackTrace, skipTaskFrames, concatenatedStackTrace,
errorStackTrace.length - skipErrorFrames + 1, taskStackTrace.length - skipTaskFrames);
error.setStackTrace(concatenatedStackTrace);
} | java | {
"resource": ""
} |
q165765 | ExecutionMonitor.monitor | validation | private void monitor() {
_lastMonitoringStep = _clock.nanoTime();
_nextAllowedLogging = _lastMonitoringStep;
while(!_stopped) {
try {
_clock.sleepNano(_checkIntervalNano);
} catch (InterruptedException e) {
break;
}
monitorStep();
}
} | java | {
"resource": ""
} |
q165766 | ExecutionMonitor.checkForStall | validation | private void checkForStall(long currentTime) {
long delta = currentTime - _lastMonitoringStep;
if (delta < _shortestObservedDelta) {
_shortestObservedDelta = delta;
}
long stall = Math.max(0, delta - _shortestObservedDelta);
if (stall > _minStallNano) {
_stalls.put(_lastMonitoringStep, stall);
if (_stalls.size() > _stallsHistorySize) {
_stalls.pollFirstEntry();
}
}
} | java | {
"resource": ""
} |
q165767 | RetriableTask.withRetryPolicy | validation | public static <U> Task<U> withRetryPolicy(String name, RetryPolicy policy, Function1<Integer, Task<U>> taskFunction) {
RetriableTask<U> retriableTask = new RetriableTask<>(name, policy, taskFunction);
Task<U> retryTaskWrapper = Task.async(name + " retriableTask", retriableTask::run);
retryTaskWrapper.getShallowTraceBuilder().setTaskType(TaskType.WITH_RETRY.getName());
return retryTaskWrapper;
} | java | {
"resource": ""
} |
q165768 | RetriableTask.wrap | validation | private Task<T> wrap(int attempt) {
Task<T> retryTask = Task.async(_policy.getName() + ", attempt " + attempt, context -> {
final SettablePromise<T> result = Promises.settable();
Task<T> task = _taskFunction.apply(attempt);
final Task<T> recovery = Task.async(_name + " recovery", recoveryContext -> {
final SettablePromise<T> recoveryResult = Promises.settable();
if (task.isFailed()) {
// Failed task will cause retry to be scheduled.
ErrorClassification errorClassification = _policy.getErrorClassifier().apply(task.getError());
retry(attempt + 1, task.getError(), errorClassification, recoveryContext, recoveryResult);
} else {
recoveryResult.done(task.get());
}
return recoveryResult;
});
// Recovery task should run immediately after the original task to process its error.
recovery.setPriority(Priority.MAX_PRIORITY);
recovery.getShallowTraceBuilder().setSystemHidden(true);
Promises.propagateResult(recovery, result);
context.after(task).run(recovery);
context.run(task);
return result;
});
retryTask.getShallowTraceBuilder().setTaskType(TaskType.RETRY.getName());
return retryTask;
} | java | {
"resource": ""
} |
q165769 | RetriableTask.retry | validation | private void retry(int attempt, Throwable error, ErrorClassification errorClassification, Context recoveryContext, SettablePromise<T> recoveryResult) {
long backoffTime = _policy.getBackoffPolicy().nextBackoff(attempt, error);
if (errorClassification == ErrorClassification.UNRECOVERABLE) {
// For fatal errors there are no retries.
LOGGER.debug(String.format("Attempt %s of %s interrupted: %s", attempt, _name, error.getMessage()));
recoveryResult.fail(error);
} else if (_policy.getTerminationPolicy().shouldTerminate(attempt, System.currentTimeMillis() - _startedAt + backoffTime)) {
// Retry policy commands that no more retries should be done.
LOGGER.debug(String.format("Too many exceptions after attempt %s of %s, aborting: %s", attempt, _name, error.getMessage()));
recoveryResult.fail(error);
} else {
// Schedule a new retry task after a computed backoff timeout.
LOGGER.debug(String.format("Attempt %s of %s failed and will be retried after %s millis: %s", attempt, _name, backoffTime, error.getMessage()));
Task<T> retryTask = wrap(attempt);
Promises.propagateResult(retryTask, recoveryResult);
recoveryContext.createTimer(backoffTime, TimeUnit.MILLISECONDS, retryTask);
}
} | java | {
"resource": ""
} |
q165770 | RetriableTask.run | validation | private Promise<? extends T> run(Context context) {
_startedAt = System.currentTimeMillis();
Task<T> task = wrap(0);
context.run(task);
return task;
} | java | {
"resource": ""
} |
q165771 | ConfigValueCoercers.failCoercion | validation | private static Exception failCoercion(final Object object, final Class<?> targetType)
{
return new Exception("Could not convert object to " + targetType.getSimpleName() + ". Object is instance of: "
+ object.getClass().getName() + ", value: " + object.toString());
} | java | {
"resource": ""
} |
q165772 | ParSeqRestliClientBuilder.setRestClient | validation | @Deprecated
public ParSeqRestliClientBuilder setRestClient(RestClient client) {
ArgumentUtil.requireNotNull(client, "client");
_client = client;
return this;
} | java | {
"resource": ""
} |
q165773 | ZKLock.acquire | validation | private Task<String> acquire(long deadline) {
final String uuid = UUID.randomUUID().toString();
return
/* Step 1: create znode with a pathname of "_locknode_/guid-lock-"
* and the sequence and ephemeral flags set. */
safeCreateLockNode(uuid, deadline, false)
.onFailure(e -> _zkClient.deleteNodeHasUUID(_lockPath, uuid))
.flatMap(lockNode -> tryAcquire(lockNode, deadline)
.withTimeout(deadline - System.currentTimeMillis(), TimeUnit.MILLISECONDS)
.onFailure(e -> _zkClient.deleteNode(lockNode)));
} | java | {
"resource": ""
} |
q165774 | ZKLock.release | validation | private Task<Void> release() {
return PlanLocal.get(getPlanLocalKey(), LockInternal.class).flatMap(lockInternal -> {
// should never be null.
if (lockInternal == null) {
LOG.error("LockInternal is null when releasing lock: ", _lockPath);
} else {
lockInternal._lockCount--;
if (lockInternal._lockCount == 0) {
return PlanLocal.remove(getPlanLocalKey())
.flatMap(unused ->
_zkClient.delete(lockInternal._lockNode, -1)
.recover(e -> {
_zkClient.deleteNode(lockInternal._lockNode);
return null;
})
);
}
}
return Task.value(null);
});
} | java | {
"resource": ""
} |
q165775 | Engine.tryAcquirePermit | validation | private boolean tryAcquirePermit(String planClass) {
return _concurrentPlans.tryAcquire() &&
(_planBasedRateLimiter == null || _planBasedRateLimiter.tryAcquire(planClass));
} | java | {
"resource": ""
} |
q165776 | HttpClient.getNingClient | validation | public static synchronized AsyncHttpClient getNingClient() {
if (_client.get() == null) {
initialize(new AsyncHttpClientConfig.Builder().build());
}
return _client.get();
} | java | {
"resource": ""
} |
q165777 | HttpClient.initialize | validation | @SuppressWarnings("resource")
public static synchronized void initialize(AsyncHttpClientConfig cfg) {
if (!_client.compareAndSet(null, new AsyncHttpClient(cfg))) {
throw new RuntimeException("async http client concurrently initialized");
}
} | java | {
"resource": ""
} |
q165778 | CharacterReader.consumeToAny | validation | public String consumeToAny(final char... chars) {
bufferUp();
final int start = bufPos;
final int remaining = bufLength;
final char[] val = charBuf;
OUTER:
while (bufPos < remaining) {
for (char c : chars) {
if (val[bufPos] == c)
break OUTER;
}
bufPos++;
}
return bufPos > start ? cacheString(charBuf, stringCache, start, bufPos - start) : "";
} | java | {
"resource": ""
} |
q165779 | Validate.noNullElements | validation | public static void noNullElements(Object[] objects, String msg) {
for (Object obj : objects)
if (obj == null)
throw new IllegalArgumentException(msg);
} | java | {
"resource": ""
} |
q165780 | Validate.notEmpty | validation | public static void notEmpty(String string, String msg) {
if (string == null || string.length() == 0)
throw new IllegalArgumentException(msg);
} | java | {
"resource": ""
} |
q165781 | TransformParser.parseTransform | validation | static Matrix parseTransform(String s) {
//Log.d(TAG, s);
Matrix matrix = new Matrix();
while (true) {
parseTransformItem(s, matrix);
int rparen = s.indexOf(")");
if (rparen > 0 && s.length() > rparen + 1) {
s = s.substring(rparen + 1).replaceFirst("[\\s,]*", "");
} else {
break;
}
}
return matrix;
} | java | {
"resource": ""
} |
q165782 | GridFS.getFileList | validation | public DBCursor getFileList(final DBObject query, final DBObject sort) {
return filesCollection.find(query).sort(sort);
} | java | {
"resource": ""
} |
q165783 | GridFS.find | validation | public List<GridFSDBFile> find(final String filename, final DBObject sort) {
return find(new BasicDBObject("filename", filename), sort);
} | java | {
"resource": ""
} |
q165784 | GridFS.find | validation | public List<GridFSDBFile> find(final DBObject query, final DBObject sort) {
List<GridFSDBFile> files = new ArrayList<GridFSDBFile>();
DBCursor cursor = filesCollection.find(query);
if (sort != null) {
cursor.sort(sort);
}
try {
while (cursor.hasNext()) {
files.add(injectGridFSInstance(cursor.next()));
}
} finally {
cursor.close();
}
return Collections.unmodifiableList(files);
} | java | {
"resource": ""
} |
q165785 | GridFS.remove | validation | public void remove(final ObjectId id) {
if (id == null) {
throw new IllegalArgumentException("file id can not be null");
}
filesCollection.remove(new BasicDBObject("_id", id));
chunksCollection.remove(new BasicDBObject("files_id", id));
} | java | {
"resource": ""
} |
q165786 | GridFS.remove | validation | public void remove(final DBObject query) {
if (query == null) {
throw new IllegalArgumentException("query can not be null");
}
for (final GridFSDBFile f : find(query)) {
f.remove();
}
} | java | {
"resource": ""
} |
q165787 | BasicBSONList.put | validation | @Override
public Object put(final String key, final Object v) {
return put(_getInt(key), v);
} | java | {
"resource": ""
} |
q165788 | BasicBSONList.get | validation | public Object get(final String key) {
int i = _getInt(key);
if (i < 0) {
return null;
}
if (i >= size()) {
return null;
}
return get(i);
} | java | {
"resource": ""
} |
q165789 | TypeData.builder | validation | public static <T> Builder<T> builder(final Class<T> type) {
return new Builder<T>(notNull("type", type));
} | java | {
"resource": ""
} |
q165790 | ListIndexesOperation.getMaxTime | validation | public long getMaxTime(final TimeUnit timeUnit) {
notNull("timeUnit", timeUnit);
return timeUnit.convert(maxTimeMS, TimeUnit.MILLISECONDS);
} | java | {
"resource": ""
} |
q165791 | MongoCompressor.withProperty | validation | public <T> MongoCompressor withProperty(final String key, final T value) {
return new MongoCompressor(this, key, value);
} | java | {
"resource": ""
} |
q165792 | ReplicaSetStatus.getName | validation | @SuppressWarnings("deprecation")
@Nullable
public String getName() {
List<ServerDescription> any = getClusterDescription().getAnyPrimaryOrSecondary();
return any.isEmpty() ? null : any.get(0).getSetName();
} | java | {
"resource": ""
} |
q165793 | ReplicaSetStatus.getMaster | validation | @SuppressWarnings("deprecation")
@Nullable
public ServerAddress getMaster() {
List<ServerDescription> primaries = getClusterDescription().getPrimaries();
return primaries.isEmpty() ? null : primaries.get(0).getAddress();
} | java | {
"resource": ""
} |
q165794 | ReplicaSetStatus.isMaster | validation | public boolean isMaster(final ServerAddress serverAddress) {
ServerAddress masterServerAddress = getMaster();
return masterServerAddress != null && masterServerAddress.equals(serverAddress);
} | java | {
"resource": ""
} |
q165795 | ReplicaSetStatus.getMaxBsonObjectSize | validation | @SuppressWarnings("deprecation")
public int getMaxBsonObjectSize() {
List<ServerDescription> primaries = getClusterDescription().getPrimaries();
return primaries.isEmpty() ? ServerDescription.getDefaultMaxDocumentSize() : primaries.get(0).getMaxDocumentSize();
} | java | {
"resource": ""
} |
q165796 | QueryBuilder.put | validation | public QueryBuilder put(final String key) {
_currentKey = key;
if (_query.get(key) == null) {
_query.put(_currentKey, new NullObject());
}
return this;
} | java | {
"resource": ""
} |
q165797 | ClientSessionImpl.applyMajorityWriteConcernToTransactionOptions | validation | private void applyMajorityWriteConcernToTransactionOptions() {
if (transactionOptions != null) {
WriteConcern writeConcern = transactionOptions.getWriteConcern();
if (writeConcern != null) {
transactionOptions = TransactionOptions.merge(TransactionOptions.builder()
.writeConcern(writeConcern.withW("majority")).build(), transactionOptions);
} else {
transactionOptions = TransactionOptions.merge(TransactionOptions.builder()
.writeConcern(WriteConcern.MAJORITY).build(), transactionOptions);
}
} else {
transactionOptions = TransactionOptions.builder().writeConcern(WriteConcern.MAJORITY).build();
}
} | java | {
"resource": ""
} |
q165798 | CommandResult.ok | validation | public boolean ok() {
Object okValue = get("ok");
if (okValue instanceof Boolean) {
return (Boolean) okValue;
} else if (okValue instanceof Number) {
return ((Number) okValue).intValue() == 1;
} else {
return false;
}
} | java | {
"resource": ""
} |
q165799 | CommandResult.getErrorMessage | validation | @Nullable
public String getErrorMessage() {
Object foo = get("errmsg");
if (foo == null) {
return null;
}
return foo.toString();
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.