code
stringlengths
73
34.1k
label
stringclasses
1 value
public static<A, B, Z> Function2<A, B, Z> lift(Func2<A, B, Z> f) { return bridge.lift(f); }
java
public static<A, B, C, Z> Function3<A, B, C, Z> lift(Func3<A, B, C, Z> f) { return bridge.lift(f); }
java
public static<A, B, C, D, Z> Function4<A, B, C, D, Z> lift(Func4<A, B, C, D, Z> f) { return bridge.lift(f); }
java
public static<Z> Function0<Z> lift(Callable<Z> f) { return bridge.lift(f); }
java
public static CssSel sel(String selector, String value) { return j.sel(selector, value); }
java
public static<T> Vendor<T> vendor(Func0<T> f) { return j.vendor(f); }
java
public static<T> Vendor<T> vendor(Callable<T> f) { return j.vendor(f); }
java
public static<T> SessionVar<T> vendSessionVar(T defValue) { return (new VarsJBridge()).vendSessionVar(defValue, new Exception()); }
java
public static<T> SessionVar<T> vendSessionVar(Callable<T> defFunc) { return (new VarsJBridge()).vendSessionVar(defFunc, new Exception()); }
java
protected <T1> void dispatchCommand(final BiConsumer<P, T1> action, final T1 routable1) { routingFor(routable1) .routees() .forEach(routee -> routee.receiveCommand(action, routable1)); }
java
@Nullable public ResultT first() { final CoreRemoteMongoCursor<ResultT> cursor = iterator(); if (!cursor.hasNext()) { return null; } return cursor.next(); }
java
public <U> CoreRemoteMongoIterable<U> map(final Function<ResultT, U> mapper) { return new CoreRemoteMappingIterable<>(this, mapper); }
java
public <A extends Collection<? super ResultT>> A into(final A target) { forEach(new Block<ResultT>() { @Override public void apply(@Nonnull final ResultT t) { target.add(t); } }); return target; }
java
public AwsServiceClient withCodecRegistry(@Nonnull final CodecRegistry codecRegistry) { return new AwsServiceClientImpl(proxy.withCodecRegistry(codecRegistry), dispatcher); }
java
public void callFunction( final String name, final List<?> args, final @Nullable Long requestTimeout) { this.functionService.callFunction(name, args, requestTimeout); }
java
public <T> T callFunction( final String name, final List<?> args, final @Nullable Long requestTimeout, final Class<T> resultClass, final CodecRegistry codecRegistry ) { return this.functionService .withCodecRegistry(codecRegistry) .callFunction(name, args, requestTime...
java
public void start() { instanceLock.writeLock().lock(); try { for (final Map.Entry<MongoNamespace, NamespaceChangeStreamListener> streamerEntry : nsStreamers.entrySet()) { streamerEntry.getValue().start(); } } finally { instanceLock.writeLock().unlock(); } }
java
public void stop() { instanceLock.writeLock().lock(); try { for (final NamespaceChangeStreamListener streamer : nsStreamers.values()) { streamer.stop(); } } finally { instanceLock.writeLock().unlock(); } }
java
public void addNamespace(final MongoNamespace namespace) { this.instanceLock.writeLock().lock(); try { if (this.nsStreamers.containsKey(namespace)) { return; } final NamespaceChangeStreamListener streamer = new NamespaceChangeStreamListener( namespace, ...
java
@Override public void removeNamespace(final MongoNamespace namespace) { this.instanceLock.writeLock().lock(); try { if (!this.nsStreamers.containsKey(namespace)) { return; } final NamespaceChangeStreamListener streamer = this.nsStreamers.get(namespace); streamer.stop(); t...
java
public Map<BsonValue, ChangeEvent<BsonDocument>> getEventsForNamespace( final MongoNamespace namespace ) { this.instanceLock.readLock().lock(); final NamespaceChangeStreamListener streamer; try { streamer = nsStreamers.get(namespace); } finally { this.instanceLock.readLock().unlock()...
java
public @Nullable ChangeEvent<BsonDocument> getUnprocessedEventForDocumentId( final MongoNamespace namespace, final BsonValue documentId ) { this.instanceLock.readLock().lock(); final NamespaceChangeStreamListener streamer; try { streamer = nsStreamers.get(namespace); } finall...
java
void setPaused(final boolean isPaused) { docLock.writeLock().lock(); try { docsColl.updateOne( getDocFilter(namespace, documentId), new BsonDocument("$set", new BsonDocument( ConfigCodec.Fields.IS_PAUSED, new BsonBoolean(isPaused)))); ...
java
public void setSomePendingWritesAndSave( final long atTime, final ChangeEvent<BsonDocument> changeEvent ) { docLock.writeLock().lock(); try { // if we were frozen if (isPaused) { // unfreeze the document due to the local write setPaused(false); // and now the un...
java
private static ChangeEvent<BsonDocument> coalesceChangeEvents( final ChangeEvent<BsonDocument> lastUncommittedChangeEvent, final ChangeEvent<BsonDocument> newestChangeEvent ) { if (lastUncommittedChangeEvent == null) { return newestChangeEvent; } switch (lastUncommittedChangeEvent.getOpe...
java
static DocumentVersionInfo getRemoteVersionInfo(final BsonDocument remoteDocument) { final BsonDocument version = getDocumentVersionDoc(remoteDocument); return new DocumentVersionInfo( version, remoteDocument != null ? BsonUtils.getDocumentId(remoteDocument) : null ...
java
static BsonDocument getFreshVersionDocument() { final BsonDocument versionDoc = new BsonDocument(); versionDoc.append(Fields.SYNC_PROTOCOL_VERSION_FIELD, new BsonInt32(1)); versionDoc.append(Fields.INSTANCE_ID_FIELD, new BsonString(UUID.randomUUID().toString())); versionDoc.append(Fields.VERSION_COUNTE...
java
static BsonDocument getDocumentVersionDoc(final BsonDocument document) { if (document == null || !document.containsKey(DOCUMENT_VERSION_FIELD)) { return null; } return document.getDocument(DOCUMENT_VERSION_FIELD, null); }
java
static BsonDocument getVersionedFilter( @Nonnull final BsonValue documentId, @Nullable final BsonValue version ) { final BsonDocument filter = new BsonDocument("_id", documentId); if (version == null) { filter.put(DOCUMENT_VERSION_FIELD, new BsonDocument("$exists", BsonBoolean.FALSE)); }...
java
BsonDocument getNextVersion() { if (!this.hasVersion() || this.getVersionDoc() == null) { return getFreshVersionDocument(); } final BsonDocument nextVersion = BsonUtils.copyOfDocument(this.getVersionDoc()); nextVersion.put( Fields.VERSION_COUNTER_FIELD, new BsonInt64(this.g...
java
public RemoteMongoCollection<Document> getCollection(final String collectionName) { return new RemoteMongoCollectionImpl<>(proxy.getCollection(collectionName), dispatcher); }
java
static <T> StitchEvent<T> fromEvent(final Event event, final Decoder<T> decoder) { return new StitchEvent<>(event.getEventName(), event.getData(), decoder); }
java
protected final Event processEvent() throws IOException { while (true) { String line; try { line = readLine(); } catch (final EOFException ex) { if (doneOnce) { throw ex; } doneOnce = true; line = ""; } // If the line is empty (a blank...
java
private static String handleRichError(final Response response, final String body) { if (!response.getHeaders().containsKey(Headers.CONTENT_TYPE) || !response.getHeaders().get(Headers.CONTENT_TYPE).equals(ContentTypes.APPLICATION_JSON)) { return body; } final Document doc; try { doc ...
java
public static void initialize(final Context context) { if (!initialized.compareAndSet(false, true)) { return; } applicationContext = context.getApplicationContext(); final String packageName = applicationContext.getPackageName(); localAppName = packageName; final PackageManager manager ...
java
public static StitchAppClient getAppClient( @Nonnull final String clientAppId ) { ensureInitialized(); synchronized (Stitch.class) { if (!appClients.containsKey(clientAppId)) { throw new IllegalStateException( String.format("client for app '%s' has not yet been initialized", c...
java
public void start() { nsLock.writeLock().lock(); try { if (runnerThread != null) { return; } runnerThread = new Thread(new NamespaceChangeStreamRunner( new WeakReference<>(this), networkMonitor, logger)); runnerThread.start(); } finally { nsLock....
java
public void stop() { if (runnerThread == null) { return; } runnerThread.interrupt(); nsLock.writeLock().lock(); try { if (runnerThread == null) { return; } this.cancel(); this.close(); while (runnerThread.isAlive()) { runnerThread.interrupt(); ...
java
boolean openStream() throws InterruptedException, IOException { logger.info("stream START"); final boolean isOpen; final Set<BsonValue> idsToWatch = nsConfig.getSynchronizedDocumentIds(); if (!networkMonitor.isConnected()) { logger.info("stream END - Network disconnected"); return false; ...
java
@SuppressWarnings("unchecked") public Map<BsonValue, ChangeEvent<BsonDocument>> getEvents() { nsLock.readLock().lock(); final Map<BsonValue, ChangeEvent<BsonDocument>> events; try { events = new HashMap<>(this.events); } finally { nsLock.readLock().unlock(); } nsLock.writeLock().l...
java
public @Nullable ChangeEvent<BsonDocument> getUnprocessedEventForDocumentId( final BsonValue documentId ) { final ChangeEvent<BsonDocument> event; nsLock.readLock().lock(); try { event = this.events.get(documentId); } finally { nsLock.readLock().unlock(); } nsLock.writeLock(...
java
public static long hash(final BsonDocument doc) { if (doc == null) { return 0L; } final byte[] docBytes = toBytes(doc); long hashValue = FNV_64BIT_OFFSET_BASIS; for (int offset = 0; offset < docBytes.length; offset++) { hashValue ^= (0xFF & docBytes[offset]); hashValue *= FNV_64B...
java
public static boolean deleteDatabase(final StitchAppClientInfo appInfo, final String serviceName, final EmbeddedMongoClientFactory clientFactory, final String userId) { final String dataDir = appInfo...
java
public Task<Long> count() { return dispatcher.dispatchTask(new Callable<Long>() { @Override public Long call() { return proxy.count(); } }); }
java
public Task<RemoteInsertOneResult> insertOne(final DocumentT document) { return dispatcher.dispatchTask(new Callable<RemoteInsertOneResult>() { @Override public RemoteInsertOneResult call() { return proxy.insertOne(document); } }); }
java
public Task<Void> registerWithEmail(@NonNull final String email, @NonNull final String password) { return dispatcher.dispatchTask( new Callable<Void>() { @Override public Void call() { registerWithEmailInternal(email, password); return null; } })...
java
public Task<Void> confirmUser(@NonNull final String token, @NonNull final String tokenId) { return dispatcher.dispatchTask( new Callable<Void>() { @Override public Void call() { confirmUserInternal(token, tokenId); return null; } }); }
java
public Task<Void> resendConfirmationEmail(@NonNull final String email) { return dispatcher.dispatchTask( new Callable<Void>() { @Override public Void call() { resendConfirmationEmailInternal(email); return null; } }); }
java
public Task<Void> sendResetPasswordEmail(@NonNull final String email) { return dispatcher.dispatchTask( new Callable<Void>() { @Override public Void call() { sendResetPasswordEmailInternal(email); return null; } }); }
java
@Override public boolean commit() { final CoreRemoteMongoCollection<DocumentT> collection = getCollection(); final List<WriteModel<DocumentT>> writeModels = getBulkWriteModels(); // define success as any one operation succeeding for now boolean success = true; for (final WriteModel<DocumentT> wri...
java
@Override public Response doRequest(final StitchRequest stitchReq) { initAppMetadata(clientAppId); return super.doRequestUrl(stitchReq, getHostname()); }
java
@Override public EventStream doStreamRequest(final StitchRequest stitchReq) { initAppMetadata(clientAppId); return super.doStreamRequestUrl(stitchReq, getHostname()); }
java
public BsonDocument toUpdateDocument() { final List<BsonElement> unsets = new ArrayList<>(); for (final String removedField : this.removedFields) { unsets.add(new BsonElement(removedField, new BsonBoolean(true))); } final BsonDocument updateDocument = new BsonDocument(); if (this.updatedField...
java
public BsonDocument toBsonDocument() { final BsonDocument updateDescDoc = new BsonDocument(); updateDescDoc.put( Fields.UPDATED_FIELDS_FIELD, this.getUpdatedFields()); final BsonArray removedFields = new BsonArray(); for (final String field : this.getRemovedFields()) { removedFiel...
java
public static UpdateDescription fromBsonDocument(final BsonDocument document) { keyPresent(Fields.UPDATED_FIELDS_FIELD, document); keyPresent(Fields.REMOVED_FIELDS_FIELD, document); final BsonArray removedFieldsArr = document.getArray(Fields.REMOVED_FIELDS_FIELD); final Set<String> removedField...
java
public UpdateDescription merge(@Nullable final UpdateDescription otherDescription) { if (otherDescription != null) { for (final Map.Entry<String, BsonValue> entry : this.updatedFields.entrySet()) { if (otherDescription.removedFields.contains(entry.getKey())) { this.updatedFields.remove(entry...
java
@Override @SuppressWarnings("unchecked") public Stream<ChangeEvent<DocumentT>> watch(final BsonValue... ids) throws InterruptedException, IOException { return operations.watch( new HashSet<>(Arrays.asList(ids)), false, documentClass ).execute(service); }
java
public Task<Void> updateSyncFrequency(@NonNull final SyncFrequency syncFrequency) { return this.dispatcher.dispatchTask(new Callable<Void>() { @Override public Void call() throws Exception { SyncImpl.this.proxy.updateSyncFrequency(syncFrequency); return null; } }); }
java
public void emitEvent( final NamespaceSynchronizationConfig nsConfig, final ChangeEvent<BsonDocument> event) { listenersLock.lock(); try { if (nsConfig.getNamespaceListenerConfig() == null) { return; } final NamespaceListenerConfig namespaceListener = nsConfig.get...
java
static ChangeEvent<BsonDocument> changeEventForLocalInsert( final MongoNamespace namespace, final BsonDocument document, final boolean writePending ) { final BsonValue docId = BsonUtils.getDocumentId(document); return new ChangeEvent<>( new BsonDocument(), OperationType.INSER...
java
static ChangeEvent<BsonDocument> changeEventForLocalUpdate( final MongoNamespace namespace, final BsonValue documentId, final UpdateDescription update, final BsonDocument fullDocumentAfterUpdate, final boolean writePending ) { return new ChangeEvent<>( new BsonDocument(), ...
java
static ChangeEvent<BsonDocument> changeEventForLocalReplace( final MongoNamespace namespace, final BsonValue documentId, final BsonDocument document, final boolean writePending ) { return new ChangeEvent<>( new BsonDocument(), OperationType.REPLACE, document, ...
java
static ChangeEvent<BsonDocument> changeEventForLocalDelete( final MongoNamespace namespace, final BsonValue documentId, final boolean writePending ) { return new ChangeEvent<>( new BsonDocument(), OperationType.DELETE, null, namespace, new BsonDocument("_i...
java
public static <T> void notNull(final String name, final T value) { if (value == null) { throw new IllegalArgumentException(name + " can not be null"); } }
java
public static void keyPresent(final String key, final Map<String, ?> map) { if (!map.containsKey(key)) { throw new IllegalStateException( String.format("expected %s to be present", key)); } }
java
public static BsonDocument copyOfDocument(final BsonDocument document) { final BsonDocument newDocument = new BsonDocument(); for (final Map.Entry<String, BsonValue> kv : document.entrySet()) { newDocument.put(kv.getKey(), kv.getValue()); } return newDocument; }
java
public static <T> ConflictHandler<T> localWins() { return new ConflictHandler<T>() { @Override public T resolveConflict( final BsonValue documentId, final ChangeEvent<T> localEvent, final ChangeEvent<T> remoteEvent ) { return localEvent.getFullDocument(); ...
java
public static boolean isTodoItem(final Document todoItemDoc) { return todoItemDoc.containsKey(ID_KEY) && todoItemDoc.containsKey(TASK_KEY) && todoItemDoc.containsKey(CHECKED_KEY); }
java
void recover() { final List<NamespaceSynchronizationConfig> nsConfigs = new ArrayList<>(); for (final MongoNamespace ns : this.syncConfig.getSynchronizedNamespaces()) { nsConfigs.add(this.syncConfig.getNamespaceConfig(ns)); } for (final NamespaceSynchronizationConfig nsConfig : nsConfigs) { ...
java
private void recoverNamespace(final NamespaceSynchronizationConfig nsConfig) { final MongoCollection<BsonDocument> undoCollection = getUndoCollection(nsConfig.getNamespace()); final MongoCollection<BsonDocument> localCollection = getLocalCollection(nsConfig.getNamespace()); final List<BsonDo...
java
public void wipeInMemorySettings() { this.waitUntilInitialized(); syncLock.lock(); try { this.instanceChangeStreamListener.stop(); if (instancesColl.find().first() == null) { throw new IllegalStateException("expected to find instance configuration"); } this.syncConfig = new ...
java
public void start() { syncLock.lock(); try { if (!this.isConfigured) { return; } instanceChangeStreamListener.stop(); if (listenersEnabled) { instanceChangeStreamListener.start(); } if (syncThread == null) { syncThread = new Thread( new Da...
java
public void stop() { syncLock.lock(); try { if (syncThread == null) { return; } instanceChangeStreamListener.stop(); syncThread.interrupt(); try { syncThread.join(); } catch (final InterruptedException e) { return; } syncThread = null; ...
java
public void close() { this.waitUntilInitialized(); this.ongoingOperationsGroup.blockAndWait(); syncLock.lock(); try { if (this.networkMonitor != null) { this.networkMonitor.removeNetworkStateListener(this); } this.dispatcher.close(); stop(); this.localClient.close...
java
public boolean doSyncPass() { if (!this.isConfigured || !syncLock.tryLock()) { return false; } try { if (logicalT == Long.MAX_VALUE) { if (logger.isInfoEnabled()) { logger.info("reached max logical time; resetting back to 0"); } logicalT = 0; } logic...
java
@CheckReturnValue private LocalSyncWriteModelContainer resolveConflict( final NamespaceSynchronizationConfig nsConfig, final CoreDocumentSynchronizationConfig docConfig, final ChangeEvent<BsonDocument> remoteEvent ) { return resolveConflict(nsConfig, docConfig, docConfig.getLastUncommittedChan...
java
@SuppressWarnings("unchecked") private static Object resolveConflictWithResolver( final ConflictHandler conflictResolver, final BsonValue documentId, final ChangeEvent localEvent, final ChangeEvent remoteEvent ) { return conflictResolver.resolveConflict( documentId, local...
java
public void addWatcher(final MongoNamespace namespace, final Callback<ChangeEvent<BsonDocument>, Object> watcher) { instanceChangeStreamListener.addWatcher(namespace, watcher); }
java
public Set<CoreDocumentSynchronizationConfig> getSynchronizedDocuments( final MongoNamespace namespace ) { this.waitUntilInitialized(); try { ongoingOperationsGroup.enter(); return this.syncConfig.getSynchronizedDocuments(namespace); } finally { ongoingOperationsGroup.exit(); }...
java
public Set<BsonValue> getPausedDocumentIds(final MongoNamespace namespace) { this.waitUntilInitialized(); try { ongoingOperationsGroup.enter(); final Set<BsonValue> pausedDocumentIds = new HashSet<>(); for (final CoreDocumentSynchronizationConfig config : this.syncConfig.getSynchro...
java
boolean resumeSyncForDocument( final MongoNamespace namespace, final BsonValue documentId ) { if (namespace == null || documentId == null) { return false; } final NamespaceSynchronizationConfig namespaceSynchronizationConfig; final CoreDocumentSynchronizationConfig config; if (...
java
void insertOne(final MongoNamespace namespace, final BsonDocument document) { this.waitUntilInitialized(); try { ongoingOperationsGroup.enter(); // Remove forbidden fields from the document before inserting it into the local collection. final BsonDocument docForStorage = sanitizeDocument(docu...
java
DeleteResult deleteMany(final MongoNamespace namespace, final Bson filter) { this.waitUntilInitialized(); try { ongoingOperationsGroup.enter(); final List<ChangeEvent<BsonDocument>> eventsToEmit = new ArrayList<>(); final DeleteResult result; final NamespaceSyn...
java
MongoCollection<BsonDocument> getUndoCollection(final MongoNamespace namespace) { return localClient .getDatabase(String.format("sync_undo_%s", namespace.getDatabaseName())) .getCollection(namespace.getCollectionName(), BsonDocument.class) .withCodecRegistry(MongoClientSettings.getDefaultCod...
java
private <T> MongoCollection<T> getLocalCollection( final MongoNamespace namespace, final Class<T> resultClass, final CodecRegistry codecRegistry ) { return localClient .getDatabase(String.format("sync_user_%s", namespace.getDatabaseName())) .getCollection(namespace.getCollectionN...
java
MongoCollection<BsonDocument> getLocalCollection(final MongoNamespace namespace) { return getLocalCollection( namespace, BsonDocument.class, MongoClientSettings.getDefaultCodecRegistry()); }
java
private <T> CoreRemoteMongoCollection<T> getRemoteCollection( final MongoNamespace namespace, final Class<T> resultClass ) { return remoteClient .getDatabase(namespace.getDatabaseName()) .getCollection(namespace.getCollectionName(), resultClass); }
java
static BsonDocument sanitizeDocument(final BsonDocument document) { if (document == null) { return null; } if (document.containsKey(DOCUMENT_VERSION_FIELD)) { final BsonDocument clonedDoc = document.clone(); clonedDoc.remove(DOCUMENT_VERSION_FIELD); return clonedDoc; } retur...
java
private static BsonDocument withNewVersion( final BsonDocument document, final BsonDocument newVersion ) { final BsonDocument newDocument = BsonUtils.copyOfDocument(document); newDocument.put(DOCUMENT_VERSION_FIELD, newVersion); return newDocument; }
java
public static void clearallLocalDBs() { for (final Map.Entry<MongoClient, Boolean> entry : localInstances.entrySet()) { for (final String dbName : entry.getKey().listDatabaseNames()) { entry.getKey().getDatabase(dbName).drop(); } } }
java
public StitchObjectMapper withCodecRegistry(final CodecRegistry codecRegistry) { // We can't detect if their codecRegistry has any duplicate providers. There's also a chance // that putting ours first may prevent decoding of some of their classes if for example they // have their own way of decoding an Inte...
java
public StitchEvent<T> nextEvent() throws IOException { final Event nextEvent = eventStream.nextEvent(); if (nextEvent == null) { return null; } return StitchEvent.fromEvent(nextEvent, this.decoder); }
java
@Nullable public StitchUserT getUser() { authLock.readLock().lock(); try { return activeUser; } finally { authLock.readLock().unlock(); } }
java
private synchronized Response doAuthenticatedRequest( final StitchAuthRequest stitchReq, final AuthInfo authInfo ) { try { return requestClient.doRequest(prepareAuthRequest(stitchReq, authInfo)); } catch (final StitchServiceException ex) { return handleAuthFailure(ex, stitchReq); }...
java
private void tryRefreshAccessToken(final Long reqStartedAt) { authLock.writeLock().lock(); try { if (!isLoggedIn()) { throw new StitchClientException(StitchClientErrorCode.LOGGED_OUT_DURING_REQUEST); } try { final Jwt jwt = Jwt.fromEncoded(getAuthInfo().getAccessToken()); ...
java
private StitchUserT doLogin(final StitchCredential credential, final boolean asLinkRequest) { final Response response = doLoginRequest(credential, asLinkRequest); final StitchUserT previousUser = activeUser; final StitchUserT user = processLoginResponse(credential, response, asLinkRequest); if (asLink...
java
private static Interval parseStartExtended(CharSequence startStr, CharSequence endStr) { Instant start = Instant.parse(startStr); if (endStr.length() > 0) { char c = endStr.charAt(0); if (c == 'P' || c == 'p') { PeriodDuration amount = PeriodDuration.parse(endStr)...
java
private static Interval parseEndDateTime(Instant start, ZoneOffset offset, CharSequence endStr) { try { TemporalAccessor temporal = DateTimeFormatter.ISO_DATE_TIME.parseBest(endStr, OffsetDateTime::from, LocalDateTime::from); if (temporal instanceof OffsetDateTime) { Offs...
java
@Override public AccountingDate date(int prolepticYear, int month, int dayOfMonth) { return AccountingDate.of(this, prolepticYear, month, dayOfMonth); }
java
@Override public AccountingDate dateYearDay(Era era, int yearOfEra, int dayOfYear) { return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear); }
java