_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q166000 | BasicBSONObject.getDate | validation | public Date getDate(final String field, final Date def) {
Object foo = get(field);
return (foo != null) ? (Date) foo : def;
} | java | {
"resource": ""
} |
q166001 | BasicBSONObject.canonicalize | validation | @SuppressWarnings("unchecked")
private static Object canonicalize(final Object from) {
if (from instanceof BSONObject && !(from instanceof BasicBSONList)) {
return canonicalizeBSONObject((BSONObject) from);
} else if (from instanceof List) {
return canonicalizeList((List<Object>) from);
} else if (from instanceof Map) {
return canonicalizeMap((Map<String, Object>) from);
} else {
return from;
}
} | java | {
"resource": ""
} |
q166002 | MongoClient.getCredential | validation | @Nullable
public MongoCredential getCredential() {
if (getCredentialsList().size() > 1) {
throw new IllegalStateException("Instance constructed with more than one MongoCredential");
} else if (getCredentialsList().isEmpty()) {
return null;
} else {
return getCredentialsList().get(0);
}
} | java | {
"resource": ""
} |
q166003 | MongoClient.startSession | validation | public ClientSession startSession(final ClientSessionOptions options) {
ClientSession clientSession = createClientSession(notNull("options", options));
if (clientSession == null) {
throw new MongoClientException("Sessions are not supported by the MongoDB cluster to which this client is connected");
}
return clientSession;
} | java | {
"resource": ""
} |
q166004 | WriteConcern.getWTimeout | validation | @Nullable
public Integer getWTimeout(final TimeUnit timeUnit) {
notNull("timeUnit", timeUnit);
return wTimeoutMS == null ? null : (int) timeUnit.convert(wTimeoutMS, TimeUnit.MILLISECONDS);
} | java | {
"resource": ""
} |
q166005 | WriteConcern.asDocument | validation | public BsonDocument asDocument() {
BsonDocument document = new BsonDocument();
addW(document);
addWTimeout(document);
addFSync(document);
addJ(document);
return document;
} | java | {
"resource": ""
} |
q166006 | WriteConcern.isAcknowledged | validation | public boolean isAcknowledged() {
if (w instanceof Integer) {
return (Integer) w > 0 || (journal != null && journal) || (fsync != null && fsync);
}
return true;
} | java | {
"resource": ""
} |
q166007 | WriteConcern.withW | validation | public WriteConcern withW(final int w) {
return new WriteConcern(Integer.valueOf(w), wTimeoutMS, fsync, journal);
} | java | {
"resource": ""
} |
q166008 | WriteConcern.withW | validation | public WriteConcern withW(final String w) {
notNull("w", w);
return new WriteConcern(w, wTimeoutMS, fsync, journal);
} | java | {
"resource": ""
} |
q166009 | WriteConcern.withWTimeout | validation | public WriteConcern withWTimeout(final long wTimeout, final TimeUnit timeUnit) {
notNull("timeUnit", timeUnit);
long newWTimeOutMS = TimeUnit.MILLISECONDS.convert(wTimeout, timeUnit);
isTrueArgument("wTimeout >= 0", wTimeout >= 0);
isTrueArgument("wTimeout <= " + Integer.MAX_VALUE + " ms", newWTimeOutMS <= Integer.MAX_VALUE);
return new WriteConcern(w, (int) newWTimeOutMS, fsync, journal);
} | java | {
"resource": ""
} |
q166010 | WriteConcern.majorityWriteConcern | validation | @Deprecated
public static Majority majorityWriteConcern(final int wtimeout, final boolean fsync, final boolean j) {
return new Majority(wtimeout, fsync, j);
} | java | {
"resource": ""
} |
q166011 | BulkWriteOperation.insert | validation | public void insert(final DBObject document) {
isTrue("already executed", !closed);
if (document.get(ID_FIELD_NAME) == null) {
document.put(ID_FIELD_NAME, new ObjectId());
}
addRequest(new InsertRequest(document, collection.getObjectCodec()));
} | java | {
"resource": ""
} |
q166012 | BulkWriteOperation.find | validation | public BulkWriteRequestBuilder find(final DBObject query) {
isTrue("already executed", !closed);
return new BulkWriteRequestBuilder(this, query, collection.getDefaultDBObjectCodec(), collection.getObjectCodec());
} | java | {
"resource": ""
} |
q166013 | BulkWriteOperation.execute | validation | public BulkWriteResult execute() {
isTrue("already executed", !closed);
closed = true;
return collection.executeBulkWriteOperation(ordered, bypassDocumentValidation, requests);
} | java | {
"resource": ""
} |
q166014 | BasicDBObject.copy | validation | public Object copy() {
// copy field values into new object
BasicDBObject newCopy = new BasicDBObject(this.toMap());
// need to clone the sub obj
for (final String field : keySet()) {
Object val = get(field);
if (val instanceof BasicDBObject) {
newCopy.put(field, ((BasicDBObject) val).copy());
} else if (val instanceof BasicDBList) {
newCopy.put(field, ((BasicDBList) val).copy());
}
}
return newCopy;
} | java | {
"resource": ""
} |
q166015 | Indexes.geoHaystack | validation | public static Bson geoHaystack(final String fieldName, final Bson additional) {
notNull("fieldName", fieldName);
return compoundIndex(new BsonDocument(fieldName, new BsonString("geoHaystack")), additional);
} | java | {
"resource": ""
} |
q166016 | CreateIndexesOperation.getIndexNames | validation | public List<String> getIndexNames() {
List<String> indexNames = new ArrayList<String>(requests.size());
for (IndexRequest request : requests) {
if (request.getName() != null) {
indexNames.add(request.getName());
} else {
indexNames.add(IndexHelper.generateIndexName(request.getKeys()));
}
}
return indexNames;
} | java | {
"resource": ""
} |
q166017 | BsonDocument.get | validation | public BsonValue get(final Object key, final BsonValue defaultValue) {
BsonValue value = get(key);
return value != null ? value : defaultValue;
} | java | {
"resource": ""
} |
q166018 | BsonDocument.getDocument | validation | public BsonDocument getDocument(final Object key, final BsonDocument defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asDocument();
} | java | {
"resource": ""
} |
q166019 | BsonDocument.getArray | validation | public BsonArray getArray(final Object key, final BsonArray defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asArray();
} | java | {
"resource": ""
} |
q166020 | BsonDocument.getNumber | validation | public BsonNumber getNumber(final Object key, final BsonNumber defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asNumber();
} | java | {
"resource": ""
} |
q166021 | BsonDocument.getInt32 | validation | public BsonInt32 getInt32(final Object key, final BsonInt32 defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asInt32();
} | java | {
"resource": ""
} |
q166022 | BsonDocument.getInt64 | validation | public BsonInt64 getInt64(final Object key, final BsonInt64 defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asInt64();
} | java | {
"resource": ""
} |
q166023 | BsonDocument.getDecimal128 | validation | public BsonDecimal128 getDecimal128(final Object key, final BsonDecimal128 defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asDecimal128();
} | java | {
"resource": ""
} |
q166024 | BsonDocument.getDouble | validation | public BsonDouble getDouble(final Object key, final BsonDouble defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asDouble();
} | java | {
"resource": ""
} |
q166025 | BsonDocument.getBoolean | validation | public BsonBoolean getBoolean(final Object key, final BsonBoolean defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asBoolean();
} | java | {
"resource": ""
} |
q166026 | BsonDocument.getString | validation | public BsonString getString(final Object key, final BsonString defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asString();
} | java | {
"resource": ""
} |
q166027 | BsonDocument.getDateTime | validation | public BsonDateTime getDateTime(final Object key, final BsonDateTime defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asDateTime();
} | java | {
"resource": ""
} |
q166028 | BsonDocument.getTimestamp | validation | public BsonTimestamp getTimestamp(final Object key, final BsonTimestamp defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asTimestamp();
} | java | {
"resource": ""
} |
q166029 | BsonDocument.getObjectId | validation | public BsonObjectId getObjectId(final Object key, final BsonObjectId defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asObjectId();
} | java | {
"resource": ""
} |
q166030 | BsonDocument.getBinary | validation | public BsonBinary getBinary(final Object key, final BsonBinary defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asBinary();
} | java | {
"resource": ""
} |
q166031 | BsonDocument.getRegularExpression | validation | public BsonRegularExpression getRegularExpression(final Object key, final BsonRegularExpression defaultValue) {
if (!containsKey(key)) {
return defaultValue;
}
return get(key).asRegularExpression();
} | java | {
"resource": ""
} |
q166032 | AsynchronousTlsChannelGroup.writeHandlingTasks | validation | private void writeHandlingTasks(final RegisteredSocket socket, final WriteOperation op) throws IOException {
while (true) {
try {
socket.tlsChannel.write(op.bufferSet.array, op.bufferSet.offset, op.bufferSet.length);
return;
} catch (NeedsTaskException e) {
warnAboutNeedTask();
e.getTask().run();
}
}
} | java | {
"resource": ""
} |
q166033 | BsonDocumentWrapper.asBsonDocument | validation | @SuppressWarnings({"rawtypes", "unchecked"})
public static BsonDocument asBsonDocument(final Object document, final CodecRegistry codecRegistry) {
if (document == null) {
return null;
}
if (document instanceof BsonDocument) {
return (BsonDocument) document;
} else {
return new BsonDocumentWrapper(document, codecRegistry.get(document.getClass()));
}
} | java | {
"resource": ""
} |
q166034 | Assertions.notNull | validation | public static <T> T notNull(final String name, final T value, final SingleResultCallback<?> callback) {
if (value == null) {
IllegalArgumentException exception = new IllegalArgumentException(name + " can not be null");
callback.onResult(null, exception);
throw exception;
}
return value;
} | java | {
"resource": ""
} |
q166035 | Assertions.isTrue | validation | public static void isTrue(final String name, final boolean condition, final SingleResultCallback<?> callback) {
if (!condition) {
IllegalStateException exception = new IllegalStateException("state should be: " + name);
callback.onResult(null, exception);
throw exception;
}
} | java | {
"resource": ""
} |
q166036 | ClassModelBuilder.getProperty | validation | public PropertyModelBuilder<?> getProperty(final String propertyName) {
notNull("propertyName", propertyName);
for (PropertyModelBuilder<?> propertyModelBuilder : propertyModelBuilders) {
if (propertyModelBuilder.getName().equals(propertyName)) {
return propertyModelBuilder;
}
}
return null;
} | java | {
"resource": ""
} |
q166037 | ClassModelBuilder.build | validation | public ClassModel<T> build() {
List<PropertyModel<?>> propertyModels = new ArrayList<PropertyModel<?>>();
PropertyModel<?> idPropertyModel = null;
stateNotNull("type", type);
for (Convention convention : conventions) {
convention.apply(this);
}
stateNotNull("instanceCreatorFactory", instanceCreatorFactory);
if (discriminatorEnabled) {
stateNotNull("discriminatorKey", discriminatorKey);
stateNotNull("discriminator", discriminator);
}
for (PropertyModelBuilder<?> propertyModelBuilder : propertyModelBuilders) {
boolean isIdProperty = propertyModelBuilder.getName().equals(idPropertyName);
if (isIdProperty) {
propertyModelBuilder.readName(ID_PROPERTY_NAME).writeName(ID_PROPERTY_NAME);
}
PropertyModel<?> model = propertyModelBuilder.build();
propertyModels.add(model);
if (isIdProperty) {
idPropertyModel = model;
}
}
validatePropertyModels(type.getSimpleName(), propertyModels);
return new ClassModel<T>(type, propertyNameToTypeParameterMap, instanceCreatorFactory, discriminatorEnabled, discriminatorKey,
discriminator, IdPropertyModelHolder.create(type, idPropertyModel, idGenerator), unmodifiableList(propertyModels));
} | java | {
"resource": ""
} |
q166038 | ReplaceOneModel.getOptions | validation | @Deprecated
public UpdateOptions getOptions() {
return new UpdateOptions()
.bypassDocumentValidation(options.getBypassDocumentValidation())
.collation(options.getCollation())
.upsert(options.isUpsert());
} | java | {
"resource": ""
} |
q166039 | ReflectionDBObject.getWrapperIfReflectionObject | validation | @Nullable
public static JavaWrapper getWrapperIfReflectionObject(final Class c) {
if (ReflectionDBObject.class.isAssignableFrom(c)) {
return getWrapper(c);
}
return null;
} | java | {
"resource": ""
} |
q166040 | ReflectionDBObject.getWrapper | validation | public static JavaWrapper getWrapper(final Class c) {
JavaWrapper w = _wrappers.get(c);
if (w == null) {
w = new JavaWrapper(c);
_wrappers.put(c, w);
}
return w;
} | java | {
"resource": ""
} |
q166041 | BsonBinary.asUuid | validation | public UUID asUuid() {
if (!BsonBinarySubType.isUuid(type)) {
throw new BsonInvalidOperationException("type must be a UUID subtype.");
}
if (type != BsonBinarySubType.UUID_STANDARD.getValue()) {
throw new BsonInvalidOperationException("uuidRepresentation must be set to return the correct UUID.");
}
return UuidHelper.decodeBinaryToUuid(this.data.clone(), this.type, UuidRepresentation.STANDARD);
} | java | {
"resource": ""
} |
q166042 | BsonBinary.asUuid | validation | public UUID asUuid(final UuidRepresentation uuidRepresentation) {
Assertions.notNull("uuidRepresentation", uuidRepresentation);
final byte uuidType = uuidRepresentation == UuidRepresentation.STANDARD
? BsonBinarySubType.UUID_STANDARD.getValue()
: BsonBinarySubType.UUID_LEGACY.getValue();
if (type != uuidType) {
throw new BsonInvalidOperationException("uuidRepresentation does not match current uuidRepresentation.");
}
return UuidHelper.decodeBinaryToUuid(data.clone(), type, uuidRepresentation);
} | java | {
"resource": ""
} |
q166043 | JSONParser.parse | validation | protected Object parse(final String name) {
Object value = null;
char current = get();
switch (current) {
// null
case 'n':
read('n');
read('u');
read('l');
read('l');
value = null;
break;
// NaN
case 'N':
read('N');
read('a');
read('N');
value = Double.NaN;
break;
// true
case 't':
read('t');
read('r');
read('u');
read('e');
value = true;
break;
// false
case 'f':
read('f');
read('a');
read('l');
read('s');
read('e');
value = false;
break;
// string
case '\'':
case '\"':
value = parseString(true);
break;
// number
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '+':
case '-':
value = parseNumber();
break;
// array
case '[':
value = parseArray(name);
break;
// object
case '{':
value = parseObject(name);
break;
default:
throw new JSONParseException(s, pos);
}
return value;
} | java | {
"resource": ""
} |
q166044 | JSONParser.readHex | validation | public void readHex() {
if (pos < s.length()
&& ((s.charAt(pos) >= '0' && s.charAt(pos) <= '9')
|| (s.charAt(pos) >= 'A' && s.charAt(pos) <= 'F')
|| (s.charAt(pos) >= 'a' && s.charAt(pos) <= 'f'))) {
pos++;
} else {
throw new JSONParseException(s, pos);
}
} | java | {
"resource": ""
} |
q166045 | JSONParser.skipWS | validation | public void skipWS() {
while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) {
pos++;
}
} | java | {
"resource": ""
} |
q166046 | JSONParser.parseString | validation | public String parseString(final boolean needQuote) {
char quot = 0;
if (check('\'')) {
quot = '\'';
} else if (check('\"')) {
quot = '\"';
} else if (needQuote) {
throw new JSONParseException(s, pos);
}
char current;
if (quot > 0) {
read(quot);
}
StringBuilder buf = new StringBuilder();
int start = pos;
while (pos < s.length()) {
current = s.charAt(pos);
if (quot > 0) {
if (current == quot) {
break;
}
} else {
if (current == ':' || current == ' ') {
break;
}
}
if (current == '\\') {
pos++;
char x = get();
char special = 0;
//CHECKSTYLE:OFF
switch (x) {
case 'u': // decode unicode
buf.append(s.substring(start, pos - 1));
pos++;
int tempPos = pos;
readHex();
readHex();
readHex();
readHex();
int codePoint = Integer.parseInt(s.substring(tempPos, tempPos + 4), 16);
buf.append((char) codePoint);
start = pos;
continue;
case 'n':
special = '\n';
break;
case 'r':
special = '\r';
break;
case 't':
special = '\t';
break;
case 'b':
special = '\b';
break;
case '"':
special = '\"';
break;
case '\\':
special = '\\';
break;
default:
break;
}
//CHECKSTYLE:ON
buf.append(s.substring(start, pos - 1));
if (special != 0) {
pos++;
buf.append(special);
}
start = pos;
continue;
}
pos++;
}
buf.append(s.substring(start, pos));
if (quot > 0) {
read(quot);
}
return buf.toString();
} | java | {
"resource": ""
} |
q166047 | JSONParser.parseNumber | validation | public Number parseNumber() {
get();
int start = this.pos;
boolean isDouble = false;
if (check('-') || check('+')) {
pos++;
}
outer:
while (pos < s.length()) {
switch (s.charAt(pos)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
pos++;
break;
case '.':
isDouble = true;
parseFraction();
break;
case 'e':
case 'E':
isDouble = true;
parseExponent();
break;
default:
break outer;
}
}
try {
if (isDouble) {
return Double.valueOf(s.substring(start, pos));
}
Long val = Long.valueOf(s.substring(start, pos));
if (val <= Integer.MAX_VALUE && val >= Integer.MIN_VALUE) {
return val.intValue();
}
return val;
} catch (NumberFormatException e) {
throw new JSONParseException(s, start, e);
}
} | java | {
"resource": ""
} |
q166048 | JSONParser.parseExponent | validation | public void parseExponent() {
// get past E
pos++;
if (check('-') || check('+')) {
pos++;
}
outer:
while (pos < s.length()) {
switch (s.charAt(pos)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
pos++;
break;
default:
break outer;
}
}
} | java | {
"resource": ""
} |
q166049 | JSONParser.parseArray | validation | protected Object parseArray(final String name) {
if (name != null) {
_callback.arrayStart(name);
} else {
_callback.arrayStart();
}
read('[');
int i = 0;
char current = get();
while (current != ']') {
String elemName = String.valueOf(i++);
Object elem = parse(elemName);
doCallback(elemName, elem);
if ((current = get()) == ',') {
read(',');
} else if (current == ']') {
break;
} else {
throw new JSONParseException(s, pos);
}
}
read(']');
return _callback.arrayDone();
} | java | {
"resource": ""
} |
q166050 | BulkUpdateRequestBuilder.updateOne | validation | public void updateOne(final DBObject update) {
bulkWriteOperation.addRequest(new UpdateRequest(query, update, false, upsert, queryCodec, collation, arrayFilters));
} | java | {
"resource": ""
} |
q166051 | ConnectionDescription.withConnectionId | validation | public ConnectionDescription withConnectionId(final ConnectionId connectionId) {
notNull("connectionId", connectionId);
return new ConnectionDescription(connectionId, serverVersion, maxWireVersion, serverType, maxBatchCount, maxDocumentSize,
maxMessageSize, compressors);
} | java | {
"resource": ""
} |
q166052 | WriteConcernResult.acknowledged | validation | public static WriteConcernResult acknowledged(final int count, final boolean isUpdateOfExisting, @Nullable final BsonValue upsertedId) {
return new WriteConcernResult() {
@Override
public boolean wasAcknowledged() {
return true;
}
@Override
public int getCount() {
return count;
}
@Override
public boolean isUpdateOfExisting() {
return isUpdateOfExisting;
}
@Override
@Nullable
public BsonValue getUpsertedId() {
return upsertedId;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WriteConcernResult that = (WriteConcernResult) o;
if (!that.wasAcknowledged()) {
return false;
}
if (count != that.getCount()) {
return false;
}
if (isUpdateOfExisting != that.isUpdateOfExisting()) {
return false;
}
if (upsertedId != null ? !upsertedId.equals(that.getUpsertedId()) : that.getUpsertedId() != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = count;
result = 31 * result + (isUpdateOfExisting ? 1 : 0);
result = 31 * result + (upsertedId != null ? upsertedId.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "AcknowledgedWriteResult{"
+ "count=" + count
+ ", isUpdateOfExisting=" + isUpdateOfExisting
+ ", upsertedId=" + upsertedId
+ '}';
}
};
} | java | {
"resource": ""
} |
q166053 | WriteConcernResult.unacknowledged | validation | public static WriteConcernResult unacknowledged() {
return new WriteConcernResult() {
@Override
public boolean wasAcknowledged() {
return false;
}
@Override
public int getCount() {
throw getUnacknowledgedWriteException();
}
@Override
public boolean isUpdateOfExisting() {
throw getUnacknowledgedWriteException();
}
@Override
public BsonValue getUpsertedId() {
throw getUnacknowledgedWriteException();
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WriteConcernResult that = (WriteConcernResult) o;
return !that.wasAcknowledged();
}
@Override
public int hashCode() {
return 1;
}
@Override
public String toString() {
return "UnacknowledgedWriteResult{}";
}
private UnsupportedOperationException getUnacknowledgedWriteException() {
return new UnsupportedOperationException("Cannot get information about an unacknowledged write");
}
};
} | java | {
"resource": ""
} |
q166054 | Document.getEmbeddedValue | validation | @SuppressWarnings("unchecked")
private <T> T getEmbeddedValue(final List<?> keys, final Class<T> clazz, final T defaultValue) {
Object value = this;
Iterator<?> keyIterator = keys.iterator();
while (keyIterator.hasNext()) {
Object key = keyIterator.next();
value = ((Document) value).get(key);
if (!(value instanceof Document)) {
if (value == null) {
return defaultValue;
} else if (keyIterator.hasNext()) {
throw new ClassCastException(format("At key %s, the value is not a Document (%s)",
key, value.getClass().getName()));
}
}
}
return clazz != null ? clazz.cast(value) : (T) value;
} | java | {
"resource": ""
} |
q166055 | Document.constructValuesList | validation | @SuppressWarnings("unchecked")
private <T> List<T> constructValuesList(final Object key, final Class<T> clazz, final List<T> defaultValue) {
List<?> value = get(key, List.class);
if (value == null) {
return defaultValue;
}
for (Object item : value) {
if (!clazz.isAssignableFrom(item.getClass())) {
throw new ClassCastException(format("List element cannot be cast to %s", clazz.getName()));
}
}
return (List<T>) value;
} | java | {
"resource": ""
} |
q166056 | TransactionOptions.merge | validation | public static TransactionOptions merge(final TransactionOptions options, final TransactionOptions defaultOptions) {
notNull("options", options);
notNull("defaultOptions", defaultOptions);
return TransactionOptions.builder()
.writeConcern(options.getWriteConcern() == null
? defaultOptions.getWriteConcern() : options.getWriteConcern())
.readConcern(options.getReadConcern() == null
? defaultOptions.getReadConcern() : options.getReadConcern())
.readPreference(options.getReadPreference() == null
? defaultOptions.getReadPreference() : options.getReadPreference())
.build();
} | java | {
"resource": ""
} |
q166057 | ConcurrentPool.release | validation | @Override
public void release(final T t, final boolean prune) {
if (t == null) {
throw new IllegalArgumentException("Can not return a null item to the pool");
}
if (closed) {
close(t);
return;
}
if (prune) {
close(t);
} else {
available.addLast(t);
}
releasePermit();
} | java | {
"resource": ""
} |
q166058 | ConcurrentPool.get | validation | @Override
public T get(final long timeout, final TimeUnit timeUnit) {
if (closed) {
throw new IllegalStateException("The pool is closed");
}
if (!acquirePermit(timeout, timeUnit)) {
throw new MongoTimeoutException(String.format("Timeout waiting for a pooled item after %d %s", timeout, timeUnit));
}
T t = available.pollLast();
if (t == null) {
t = createNewAndReleasePermitIfFailure(false);
}
return t;
} | java | {
"resource": ""
} |
q166059 | ConcurrentPool.close | validation | @Override
public void close() {
closed = true;
Iterator<T> iter = available.iterator();
while (iter.hasNext()) {
T t = iter.next();
close(t);
iter.remove();
}
} | java | {
"resource": ""
} |
q166060 | LazyBSONObject.pipe | validation | public int pipe(final OutputStream os) throws IOException {
WritableByteChannel channel = Channels.newChannel(os);
return channel.write(getBufferForInternalBytes());
} | java | {
"resource": ""
} |
q166061 | AbstractBsonReader.throwInvalidContextType | validation | protected void throwInvalidContextType(final String methodName, final BsonContextType actualContextType,
final BsonContextType... validContextTypes) {
String validContextTypesString = StringUtils.join(" or ", asList(validContextTypes));
String message = format("%s can only be called when ContextType is %s, not when ContextType is %s.",
methodName, validContextTypesString, actualContextType);
throw new BsonInvalidOperationException(message);
} | java | {
"resource": ""
} |
q166062 | AbstractBsonReader.throwInvalidState | validation | protected void throwInvalidState(final String methodName, final State... validStates) {
String validStatesString = StringUtils.join(" or ", asList(validStates));
String message = format("%s can only be called when State is %s, not when State is %s.",
methodName, validStatesString, state);
throw new BsonInvalidOperationException(message);
} | java | {
"resource": ""
} |
q166063 | AbstractBsonReader.verifyBSONType | validation | protected void verifyBSONType(final String methodName, final BsonType requiredBsonType) {
if (state == State.INITIAL || state == State.SCOPE_DOCUMENT || state == State.TYPE) {
readBsonType();
}
if (state == State.NAME) {
// ignore name
skipName();
}
if (state != State.VALUE) {
throwInvalidState(methodName, State.VALUE);
}
if (currentBsonType != requiredBsonType) {
throw new BsonInvalidOperationException(format("%s can only be called when CurrentBSONType is %s, "
+ "not when CurrentBSONType is %s.",
methodName, requiredBsonType, currentBsonType));
}
} | java | {
"resource": ""
} |
q166064 | AbstractBsonReader.verifyName | validation | protected void verifyName(final String expectedName) {
readBsonType();
String actualName = readName();
if (!actualName.equals(expectedName)) {
throw new BsonSerializationException(format("Expected element name to be '%s', not '%s'.",
expectedName, actualName));
}
} | java | {
"resource": ""
} |
q166065 | AbstractBsonReader.checkPreconditions | validation | protected void checkPreconditions(final String methodName, final BsonType type) {
if (isClosed()) {
throw new IllegalStateException("BsonWriter is closed");
}
verifyBSONType(methodName, type);
} | java | {
"resource": ""
} |
q166066 | Decimal128.parse | validation | public static Decimal128 parse(final String value) {
String lowerCasedValue = value.toLowerCase();
if (NaN_STRINGS.contains(lowerCasedValue)) {
return NaN;
}
if (NEGATIVE_NaN_STRINGS.contains(lowerCasedValue)) {
return NEGATIVE_NaN;
}
if (POSITIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {
return POSITIVE_INFINITY;
}
if (NEGATIVE_INFINITY_STRINGS.contains(lowerCasedValue)) {
return NEGATIVE_INFINITY;
}
return new Decimal128(new BigDecimal(value), value.charAt(0) == '-');
} | java | {
"resource": ""
} |
q166067 | Decimal128.bigDecimalValue | validation | public BigDecimal bigDecimalValue() {
if (isNaN()) {
throw new ArithmeticException("NaN can not be converted to a BigDecimal");
}
if (isInfinite()) {
throw new ArithmeticException("Infinity can not be converted to a BigDecimal");
}
BigDecimal bigDecimal = bigDecimalValueNoNegativeZeroCheck();
// If the BigDecimal is 0, but the Decimal128 is negative, that means we have -0.
if (isNegative() && bigDecimal.signum() == 0) {
throw new ArithmeticException("Negative zero can not be converted to a BigDecimal");
}
return bigDecimal;
} | java | {
"resource": ""
} |
q166068 | Decimal128.getBytes | validation | private byte[] getBytes() {
byte[] bytes = new byte[15];
long mask = 0x00000000000000ff;
for (int i = 14; i >= 7; i--) {
bytes[i] = (byte) ((low & mask) >>> ((14 - i) << 3));
mask = mask << 8;
}
mask = 0x00000000000000ff;
for (int i = 6; i >= 1; i--) {
bytes[i] = (byte) ((high & mask) >>> ((6 - i) << 3));
mask = mask << 8;
}
mask = 0x0001000000000000L;
bytes[0] = (byte) ((high & mask) >>> 48);
return bytes;
} | java | {
"resource": ""
} |
q166069 | AggregateExplainOperation.hint | validation | public AggregateExplainOperation hint(final BsonValue hint) {
isTrueArgument("BsonString or BsonDocument", hint == null || hint.isDocument() || hint.isString());
this.hint = hint;
return this;
} | java | {
"resource": ""
} |
q166070 | Collation.asDocument | validation | public BsonDocument asDocument() {
BsonDocument collation = new BsonDocument();
if (locale != null) {
collation.put("locale", new BsonString(locale));
}
if (caseLevel != null) {
collation.put("caseLevel", new BsonBoolean(caseLevel));
}
if (caseFirst != null) {
collation.put("caseFirst", new BsonString(caseFirst.getValue()));
}
if (strength != null) {
collation.put("strength", new BsonInt32(strength.getIntRepresentation()));
}
if (numericOrdering != null) {
collation.put("numericOrdering", new BsonBoolean(numericOrdering));
}
if (alternate != null) {
collation.put("alternate", new BsonString(alternate.getValue()));
}
if (maxVariable != null) {
collation.put("maxVariable", new BsonString(maxVariable.getValue()));
}
if (normalization != null) {
collation.put("normalization", new BsonBoolean(normalization));
}
if (backwards != null) {
collation.put("backwards", new BsonBoolean(backwards));
}
return collation;
} | java | {
"resource": ""
} |
q166071 | GridFSDBFile.writeTo | validation | public long writeTo(final File file) throws IOException {
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
return writeTo(out);
} finally {
if (out != null) {
out.close();
}
}
} | java | {
"resource": ""
} |
q166072 | GridFSDBFile.writeTo | validation | public long writeTo(final OutputStream out) throws IOException {
int nc = numChunks();
for (int i = 0; i < nc; i++) {
out.write(getChunk(i));
}
return length;
} | java | {
"resource": ""
} |
q166073 | GridFSDBFile.remove | validation | void remove() {
fs.getFilesCollection().remove(new BasicDBObject("_id", id));
fs.getChunksCollection().remove(new BasicDBObject("files_id", id));
} | java | {
"resource": ""
} |
q166074 | PushOptions.sort | validation | public PushOptions sort(@Nullable final Integer sort) {
if (sortDocument != null) {
throw new IllegalStateException("sort can not be set if sortDocument already is");
}
this.sort = sort;
return this;
} | java | {
"resource": ""
} |
q166075 | PushOptions.sortDocument | validation | public PushOptions sortDocument(@Nullable final Bson sortDocument) {
if (sort != null) {
throw new IllegalStateException("sortDocument can not be set if sort already is");
}
this.sortDocument = sortDocument;
return this;
} | java | {
"resource": ""
} |
q166076 | ChangeStreamDocument.getNamespace | validation | @BsonIgnore @Nullable
public MongoNamespace getNamespace() {
if (namespaceDocument == null) {
return null;
}
if (!namespaceDocument.containsKey("db") || !namespaceDocument.containsKey("coll")) {
return null;
}
return new MongoNamespace(namespaceDocument.getString("db").getValue(), namespaceDocument.getString("coll").getValue());
} | java | {
"resource": ""
} |
q166077 | ChangeStreamDocument.getDatabaseName | validation | @BsonIgnore @Nullable
public String getDatabaseName() {
if (namespaceDocument == null) {
return null;
}
if (!namespaceDocument.containsKey("db")) {
return null;
}
return namespaceDocument.getString("db").getValue();
} | java | {
"resource": ""
} |
q166078 | ChangeStreamDocument.createCodec | validation | public static <TFullDocument> Codec<ChangeStreamDocument<TFullDocument>> createCodec(final Class<TFullDocument> fullDocumentClass,
final CodecRegistry codecRegistry) {
return new ChangeStreamDocumentCodec<TFullDocument>(fullDocumentClass, codecRegistry);
} | java | {
"resource": ""
} |
q166079 | ClientSessionOptions.builder | validation | public static Builder builder(final ClientSessionOptions options) {
notNull("options", options);
Builder builder = new Builder();
builder.causallyConsistent = options.isCausallyConsistent();
builder.defaultTransactionOptions = options.getDefaultTransactionOptions();
return builder;
} | java | {
"resource": ""
} |
q166080 | MongoOptions.reset | validation | public void reset() {
connectionsPerHost = 10;
threadsAllowedToBlockForConnectionMultiplier = 5;
maxWaitTime = 1000 * 60 * 2;
connectTimeout = 1000 * 10;
socketFactory = SocketFactory.getDefault();
socketTimeout = 0;
socketKeepAlive = false;
readPreference = null;
writeConcern = null;
safe = false;
w = 0;
wtimeout = 0;
fsync = false;
j = false;
dbDecoderFactory = DefaultDBDecoder.FACTORY;
dbEncoderFactory = DefaultDBEncoder.FACTORY;
description = null;
cursorFinalizerEnabled = true;
alwaysUseMBeans = false;
requiredReplicaSetName = null;
} | java | {
"resource": ""
} |
q166081 | MongoOptions.copy | validation | public MongoOptions copy() {
MongoOptions m = new MongoOptions();
m.connectionsPerHost = connectionsPerHost;
m.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier;
m.maxWaitTime = maxWaitTime;
m.connectTimeout = connectTimeout;
m.socketFactory = socketFactory;
m.socketTimeout = socketTimeout;
m.socketKeepAlive = socketKeepAlive;
m.readPreference = readPreference;
m.writeConcern = writeConcern;
m.safe = safe;
m.w = w;
m.wtimeout = wtimeout;
m.fsync = fsync;
m.j = j;
m.dbDecoderFactory = dbDecoderFactory;
m.dbEncoderFactory = dbEncoderFactory;
m.description = description;
m.cursorFinalizerEnabled = cursorFinalizerEnabled;
m.alwaysUseMBeans = alwaysUseMBeans;
m.requiredReplicaSetName = requiredReplicaSetName;
return m;
} | java | {
"resource": ""
} |
q166082 | MongoOptions.getWriteConcern | validation | @SuppressWarnings("deprecation")
public WriteConcern getWriteConcern() {
WriteConcern retVal;
if (writeConcern != null) {
retVal = writeConcern;
} else if (w != 0 || wtimeout != 0 || fsync | j) {
retVal = WriteConcern.ACKNOWLEDGED;
if (w != 0) {
retVal = retVal.withW(w);
}
if (wtimeout != 0) {
retVal = retVal.withWTimeout(wtimeout, TimeUnit.MILLISECONDS);
}
if (fsync) {
retVal = retVal.withFsync(fsync);
}
if (j) {
retVal = retVal.withJ(j);
}
} else if (safe) {
retVal = WriteConcern.ACKNOWLEDGED;
} else {
retVal = WriteConcern.UNACKNOWLEDGED;
}
return retVal;
} | java | {
"resource": ""
} |
q166083 | UserAgent.getUserAgent | validation | public static String getUserAgent(String serviceName, boolean allowTelemetry) {
String macAddress = "Not Collected";
if (allowTelemetry) {
macAddress = GetHashMac.getHashMac();
}
return String.format(serviceName + " MacAddressHash:%s", macAddress);
} | java | {
"resource": ""
} |
q166084 | VcapResult.populateProperties | validation | @SuppressFBWarnings("UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR")
private void populateProperties(ConfigurableEnvironment environment, VcapPojo[] pojos) {
final Map<String, Object> map = new HashMap<>();
populateDefaultStorageProperties(map,
findPojoForServiceType(VcapServiceType.AZURE_STORAGE, pojos));
populateDefaultServiceBusProperties(map,
findPojoForServiceType(VcapServiceType.AZURE_SERVICEBUS, pojos));
populateDefaultDocumentDBProperties(map,
findPojoForServiceType(VcapServiceType.AZURE_DOCUMENTDB, pojos));
addOrReplace(environment.getPropertySources(), map);
} | java | {
"resource": ""
} |
q166085 | AzureADGraphClient.isMatchingUserGroupKey | validation | private boolean isMatchingUserGroupKey(final JsonNode node) {
return node.get(aadAuthenticationProperties.getUserGroup().getKey()).asText()
.equals(aadAuthenticationProperties.getUserGroup().getValue());
} | java | {
"resource": ""
} |
q166086 | AzureADGraphClient.convertGroupsToGrantedAuthorities | validation | public Set<GrantedAuthority> convertGroupsToGrantedAuthorities(final List<UserGroup> groups) {
// Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities
final Set<GrantedAuthority> mappedAuthorities = groups.stream().filter(this::isValidUserGroupToGrantAuthority)
.map(userGroup -> new SimpleGrantedAuthority(DEFAULT_ROLE_PREFIX + userGroup.getDisplayName()))
.collect(Collectors.toCollection(LinkedHashSet::new));
if (mappedAuthorities.isEmpty()) {
mappedAuthorities.add(DEFAULT_AUTHORITY);
}
return mappedAuthorities;
} | java | {
"resource": ""
} |
q166087 | ServiceEndpointsProperties.getServiceEndpoints | validation | public ServiceEndpoints getServiceEndpoints(String environment) {
Assert.notEmpty(endpoints, "No service endpoints found");
if (!endpoints.containsKey(environment)) {
throw new IllegalArgumentException(environment + " is not found in the configuration," +
" only following environments are supported: " + endpoints.keySet());
}
return endpoints.get(environment);
} | java | {
"resource": ""
} |
q166088 | AADAuthenticationFilterAutoConfiguration.azureADJwtTokenFilter | validation | @Bean
@Scope(BeanDefinition.SCOPE_SINGLETON)
@ConditionalOnMissingBean(AADAuthenticationFilter.class)
public AADAuthenticationFilter azureADJwtTokenFilter() {
LOG.info("AzureADJwtTokenFilter Constructor.");
return new AADAuthenticationFilter(aadAuthProps, serviceEndpointsProps, getJWTResourceRetriever());
} | java | {
"resource": ""
} |
q166089 | TodolistController.getAllTodoItems | validation | @RequestMapping(value = "/api/todolist", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<List<TodoItem>> getAllTodoItems() {
return new ResponseEntity<>(todoList, HttpStatus.OK);
} | java | {
"resource": ""
} |
q166090 | LiveReload.register | validation | public LiveReload register(final Path path, final String... includes) {
if (Files.exists(path)) {
paths.add(new Object[]{path, Arrays.asList(includes)});
}
return this;
} | java | {
"resource": ""
} |
q166091 | AssetCompiler.build | validation | public Map<String, List<File>> build(final String dist, final File dir) throws Exception {
log.debug("{} aggregators: {}", dist, aggregators);
aggregators(aggregators, conf);
return buildInternal(dist, dir);
} | java | {
"resource": ""
} |
q166092 | AssetCompiler.summary | validation | public String summary(Map<String, List<File>> result, Path outDir, String dist, long duration,
String... extraInfo) {
StringBuilder buffer = new StringBuilder();
buffer.append("Summary:\n");
long seconds = Duration.ofMillis(duration).getSeconds();
String took = seconds > 0 ? seconds + "s" : duration + "ms";
buffer.append("Pipeline: ").append(pipeline(dist)).append("\n");
buffer.append("Time: ").append(took).append("\n");
buffer.append("Output: ").append(outDir).append("\n");
Stream.of(extraInfo).forEach(line -> buffer.append(line).append("\n"));
int w1 = result.keySet().stream()
.map(it -> it.length() + 2)
.max(Integer::compareTo)
.orElse(0);
int mw1 = Math.max(w1, "Fileset".length() + 2);
int w2 = result.values().stream()
.flatMap(List::stream)
.map(file -> outDir.relativize(file.toPath()).toString())
.map(String::length)
.max(Integer::compareTo)
.orElse(0);
buffer.append(format(w1, w2, "Fileset", "Output", "Size"));
result.forEach((fileset, files) -> {
if (files.size() > 0) {
// Head
buffer.append(format(mw1, w2, " " + fileset, "", ""));
// Tail
files.forEach(file -> buffer.append(format(mw1, w2, "", outDir.relativize(file.toPath()),
AssetCompiler.humanReadableByteCount(file.length()))));
}
});
return buffer.toString();
} | java | {
"resource": ""
} |
q166093 | Watcher.register | validation | private void register(final Path dir) throws IOException {
WatchKey key = dir.register(watcher, new Kind[]{ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY }, HIGH);
keys.put(key, dir);
} | java | {
"resource": ""
} |
q166094 | RamlType.newProperty | validation | public RamlType newProperty(String name, String type, boolean required, String... values) {
if (properties == null) {
properties = new LinkedHashMap<>();
}
if (values.length > 0) {
properties.put(required ? name : name + "?", ImmutableMap.of("enum", values));
} else {
properties.put(required ? name : name + "?", type);
}
return this;
} | java | {
"resource": ""
} |
q166095 | RamlType.valueOf | validation | public static RamlType valueOf(String name) {
switch (name.toLowerCase()) {
case "boolean":
return BOOLEAN;
case "byte":
case "short":
case "int":
case "integer":
case "long":
return INTEGER;
case "float":
case "double":
return NUMBER;
case "char":
case "character":
case "string":
return STRING;
case "file":
case "upload":
case "path":
case "binary":
return FILE;
case "date":
case "datetime":
case "localdatetime":
return DATE_TIME;
}
return new RamlType("object", name);
} | java | {
"resource": ""
} |
q166096 | FileEventOptions.kind | validation | public FileEventOptions kind(final WatchEvent.Kind<Path> kind) {
requireNonNull(kind, "WatchEvent.Kind required.");
kinds.add(kind);
return this;
} | java | {
"resource": ""
} |
q166097 | Hbs.doWith | validation | public Hbs doWith(final Consumer<Handlebars> callback) {
requireNonNull(callback, "Configurer is required.");
return doWith((hbs, conf) -> callback.accept(hbs));
} | java | {
"resource": ""
} |
q166098 | Micrometer.doWith | validation | public Micrometer doWith(@Nonnull final Consumer<CompositeMeterRegistry> configurer) {
return doWith((registry, conf) -> configurer.accept(registry));
} | java | {
"resource": ""
} |
q166099 | Thl.doWith | validation | public Thl doWith(final Consumer<TemplateEngine> callback) {
requireNonNull(callback, "Callback required.");
return doWith((e, c) -> callback.accept(e));
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.