Collection should be sealed while calling this method
@param scope scope
@param stream stream
@param collectionNum collection to delete
@return future which when completed will have the collection deleted if it is empty or ignored otherwise.
326333
private CompletableFuture<Void> tryDeleteSealedCollection(String scope, String stream, Integer collectionNum) {
        // purge garbage znodes
        // attempt to delete entities node
        // delete collection
        return getLatestCollection(scope, stream)
                .thenCompose(latestcollectionNum ->
                        // 1. purge
                        storeHelper.getChildren(getEntitiesPath(scope, stream, collectionNum))
                                   .thenCompose(entitiesPos -> {
                                       String entitiesPath = getEntitiesPath(scope, stream, collectionNum);

                                       // delete entities greater than max pos
                                       return Futures.allOf(entitiesPos.stream().filter(pos -> getPositionFromPath(pos) > rollOverAfter)
                                                                    .map(pos -> storeHelper.deletePath(ZKPaths.makePath(entitiesPath, pos), false))
                                                                    .collect(Collectors.toList()));
                                   }))
                .thenCompose(x -> {
                    // 2. Try deleting entities root path. 
                    // if we are able to delete entities node then we can delete the whole thing
                    return Futures.exceptionallyExpecting(storeHelper.deletePath(getEntitiesPath(scope, stream, collectionNum), false)
                                                                     .thenCompose(v -> storeHelper.deleteTree(getCollectionPath(scope, stream, collectionNum))),
                            e -> Exceptions.unwrap(e) instanceof StoreException.DataNotEmptyException, null);
                });
    }
209008
@SuppressWarnings("unchecked")
    public <R> BaseSimpleReactStream<R> from(final Collection<R> collection) {
        return from(collection.stream());
    }
1134714
public static <T> Map<Boolean, List<T>> toMapPartition( Stream<T> stream, Predicate<T> predicate ) {
        return stream.collect(Collectors.partitioningBy(predicate));
    }
494570
public boolean removeAll(Collection<?> collection) {
        boolean result = false;
        synchronized (mLock) {
            Iterator<?> it;
            if (mOriginalValues != null) {
                it = mOriginalValues.iterator();

            } else {
                it = mObjects.iterator();
            }
            while (it.hasNext()) {
                if (collection.contains(it.next())) {
                    it.remove();
                    result = true;
                }
            }
        }
        if (mNotifyOnChange) notifyDataSetChanged();
        return result;
    }
690776
public String deleteScope(String scopeName) throws OAuthException {
        String responseMsg;
        Scope foundScope = DBManagerFactory.getInstance().findScope(scopeName).blockingGet();
        if (foundScope == null) {
            LOG.error("scope does not exist");
            throw new OAuthException(SCOPE_NOT_EXIST, HttpResponseStatus.BAD_REQUEST);
        } else {
            // first, check whether there is a client app registered with that scope
            List<ApplicationInfo> registeredApps = getClientAppsByScope(scopeName);
            if (registeredApps.size() > 0) {
                responseMsg = SCOPE_USED_BY_APP_MESSAGE;
            } else {
                boolean ok = DBManagerFactory.getInstance().deleteScope(scopeName).blockingGet();
                if (ok) {
                    responseMsg = SCOPE_DELETED_OK_MESSAGE;
                } else {
                    responseMsg = SCOPE_DELETED_NOK_MESSAGE;
                }
            }
        }
        return responseMsg;
    }
587351
public Observable<ServiceResponse<Void>> deleteByScopeWithServiceResponseAsync(String scope, String lockName) {
        if (scope == null) {
            throw new IllegalArgumentException("Parameter scope is required and cannot be null.");
        }
        if (lockName == null) {
            throw new IllegalArgumentException("Parameter lockName is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.deleteByScope(scope, lockName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = deleteByScopeDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }
849519
public CompletableFuture<Pair<List<String>, String>> listStreams(final String scope, final String token, final int limit) {
        Exceptions.checkNotNullOrEmpty(scope, "scope");
        return streamStore.listStream(scope, token, limit, executor);
    }
568847
public void dropAllDataMongoDBCollection(String collectionName) {
        DBCollection db = getMongoDBCollection(collectionName);
        DBCursor objectsList = db.find();
        try {
            while (objectsList.hasNext()) {
                db.remove(objectsList.next());
            }
        } finally {
            objectsList.close();
        }
    }
706996
@Override
  public <T> List<T> findAllAndRemove(String jxQuery, String collectionName) {
    CollectionMetaData cmd = cmdMap.get(collectionName);
    @SuppressWarnings("unchecked")
    Map<Object, T> collection = (Map<Object, T>) collectionsRef.get().get(collectionName);
    if((null == cmd) || (null == collection)) {
      throw new InvalidJsonDbApiUsageException("Collection by name '" + collectionName + "' not found. Create collection first.");
    }
    cmd.getCollectionLock().writeLock().lock();
    try {
      JXPathContext context = contextsRef.get().get(collectionName);
      @SuppressWarnings("unchecked")
      Iterator<T> resultItr = context.iterate(jxQuery);
      Set<Object> removeIds = new HashSet<Object>();
      while (resultItr.hasNext()) {
        T objectToRemove = resultItr.next();
        Object idToRemove = Util.getIdForEntity(objectToRemove, cmd.getIdAnnotatedFieldGetterMethod());
        removeIds.add(idToRemove);
      }

      if(removeIds.size() < 1) {
        return null;
      }

      JsonWriter jw;
      try {
        jw = new JsonWriter(dbConfig, cmd, collectionName, fileObjectsRef.get().get(collectionName));
      } catch (IOException ioe) {
        logger.error("Failed to obtain writer for " + collectionName, ioe);
        throw new JsonDBException("Failed to save " + collectionName, ioe);
      }
      boolean substractResult = jw.removeFromJsonFile(collection, removeIds);

      List<T> removedObjects = null;
      if(substractResult) {
        removedObjects = new ArrayList<T>();
        for (Object id : removeIds) {
          // Don't need to clone it, this object no more exists in the collection
          removedObjects.add(collection.remove(id));
        }
      }
      return removedObjects;

    } finally {
      cmd.getCollectionLock().writeLock().unlock();
    }
  }
167878
@Override
    public void deleteScope(final String scopeName, final SecurityContext securityContext,
            final AsyncResponse asyncResponse) {
        long traceId = LoggerHelpers.traceEnter(log, "deleteScope");

        try {
            restAuthHelper.authenticateAuthorize(getAuthorizationHeader(),
                    AuthResourceRepresentation.ofScopes(), READ_UPDATE);
        } catch (AuthException e) {
            log.warn("Delete scope for {} failed due to authentication failure.", scopeName);
            asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
            LoggerHelpers.traceLeave(log, "createStream", traceId);
            return;
        }

        controllerService.deleteScope(scopeName).thenApply(scopeStatus -> {
            if (scopeStatus.getStatus() == DeleteScopeStatus.Status.SUCCESS) {
                log.info("Successfully deleted scope: {}", scopeName);
                return Response.status(Status.NO_CONTENT).build();
            } else if (scopeStatus.getStatus() == DeleteScopeStatus.Status.SCOPE_NOT_FOUND) {
                log.warn("Scope: {} not found", scopeName);
                return Response.status(Status.NOT_FOUND).build();
            } else if (scopeStatus.getStatus() == DeleteScopeStatus.Status.SCOPE_NOT_EMPTY) {
                log.warn("Cannot delete scope: {} with non-empty streams", scopeName);
                return Response.status(Status.PRECONDITION_FAILED).build();
            } else {
                log.warn("deleteScope for {} failed", scopeName);
                return Response.status(Status.INTERNAL_SERVER_ERROR).build();
            }
        }).exceptionally(exception -> {
            log.warn("deleteScope for {} failed with exception: {}", scopeName, exception);
            return Response.status(Status.INTERNAL_SERVER_ERROR).build();
        }).thenApply(asyncResponse::resume)
        .thenAccept(x -> LoggerHelpers.traceLeave(log, "deleteScope", traceId));
    }
310516
public static boolean fclose(final OutputStream[] streams) {
      boolean success = true;

      for (OutputStream stream : streams) {
         boolean rv = fclose(stream);
         if (!rv) success = false;
      }

      return success;
   }
478455
public void setScope(java.util.Collection<String> scope) {
        if (scope == null) {
            this.scope = null;
            return;
        }

        this.scope = new java.util.ArrayList<String>(scope);
    }
388838
public final static <T> Stream<T> completableFutureToStream(final CompletableFuture<T> future) {
        return Stream.of(future.join());

    }
105786
public static <T> Map<T, Long> countBy(Collection<T> collection) {
        return countBy(collection.stream());
    }
879151
public static boolean allDone(Collection<Future> futures) {
        for (Future f : futures) {
            if (!f.isDone()) {
                return false;
            }
        }
        return true;
    }
1061297
public void deleteStream(String scope, String streamName, Duration latency) {
        DYNAMIC_LOGGER.incCounterValue(DELETE_STREAM, 1);
        deleteStreamLatency.reportSuccessValue(latency.toMillis());
    }
656373
@SuppressWarnings("unchecked")
	public static <T> Collection<T> removeAny(Collection<T> collection, T... elesRemoved) {
		collection.removeAll(newHashSet(elesRemoved));
		return collection;
	}