Example usage for com.google.common.collect ImmutableList stream

List of usage examples for com.google.common.collect ImmutableList stream

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList stream.

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:dagger.internal.codegen.ComponentImplementation.java

/**
 * Returns the {@link ModifiableBindingMethod}s for this subcomponent implementation and its
 * superclasses.//from   ww w  .  j  av a 2  s .  c o m
 */
ImmutableList<ModifiableBindingMethod> getModifiableBindingMethods() {
    ImmutableList.Builder<ModifiableBindingMethod> modifiableBindingMethodsBuilder = ImmutableList.builder();
    if (superclassImplementation.isPresent()) {
        ImmutableList<ModifiableBindingMethod> superclassModifiableBindingMethods = superclassImplementation
                .get().getModifiableBindingMethods();
        superclassModifiableBindingMethods.stream()
                .filter(method -> !modifiableBindingMethods.finalized(method))
                .forEach(modifiableBindingMethodsBuilder::add);
    }
    modifiableBindingMethodsBuilder.addAll(modifiableBindingMethods.getNonFinalizedMethods());
    return modifiableBindingMethodsBuilder.build();
}

From source file:ru.org.linux.topic.TopicController.java

private ModelAndView jumpMessage(HttpServletRequest request, int msgid, int cid, boolean skipDeleted)
        throws Exception {
    Template tmpl = Template.getTemplate(request);
    Topic topic = messageDao.getById(msgid);

    CommentList comments = commentService.getCommentList(topic, false);
    CommentNode node = comments.getNode(cid);

    if (node == null && skipDeleted) {
        ImmutableList<Comment> list = comments.getList();

        if (list.isEmpty()) {
            return new ModelAndView(new RedirectView(topic.getLink()));
        }//from w w  w . ja v a 2  s.  c o  m

        Comment c = list.stream().filter(v -> v.getId() > cid).findFirst().orElse(list.get(list.size() - 1));

        node = comments.getNode(c.getId());
    }

    boolean deleted = false;

    if (node == null && tmpl.isModeratorSession()) {
        comments = commentService.getCommentList(topic, true);
        node = comments.getNode(cid);
        deleted = true;
    }

    if (node == null) {
        throw new MessageNotFoundException(topic, cid,
                " #" + cid + "     ??");
    }

    int pagenum = deleted ? 0 : comments.getCommentPage(node.getComment(), tmpl.getProf());

    TopicLinkBuilder redirectUrl = TopicLinkBuilder.pageLink(topic, pagenum)
            .lastmod(tmpl.getProf().getMessages()).comment(node.getComment().getId());

    if (deleted) {
        redirectUrl = redirectUrl.showDeleted();
    }

    if (tmpl.isSessionAuthorized() && !deleted) {
        Set<Integer> ignoreList = ignoreListDao.get(tmpl.getCurrentUser());

        Set<Integer> hideSet = commentService.makeHideSet(comments,
                getDefaultFilter(tmpl.getProf(), ignoreList.isEmpty()), ignoreList);

        if (hideSet.contains(node.getComment().getId())) {
            redirectUrl = redirectUrl.filter(CommentFilter.FILTER_NONE);
        }
    }

    return new ModelAndView(new RedirectView(redirectUrl.build()));
}

From source file:com.facebook.buck.parser.ParserWithConfigurableAttributes.java

@Override
public ImmutableList<ImmutableSet<BuildTarget>> resolveTargetSpecs(ParsingContext parsingContext,
        Iterable<? extends TargetNodeSpec> specs, TargetConfiguration targetConfiguration)
        throws BuildFileParseException, InterruptedException {

    try (PerBuildStateWithConfigurableAttributes state = (PerBuildStateWithConfigurableAttributes) perBuildStateFactory
            .create(parsingContext, permState, targetPlatforms.get())) {
        TargetNodeFilterForSpecResolver<TargetNode<?>> targetNodeFilter = (spec, nodes) -> spec.filter(nodes);

        TargetNodeProviderForSpecResolver<TargetNode<?>> targetNodeProvider = DefaultParser
                .createTargetNodeProviderForSpecResolver(state);

        ImmutableList<ImmutableSet<BuildTarget>> buildTargets = targetSpecResolver.resolveTargetSpecs(
                parsingContext.getCell(), specs, targetConfiguration,
                (buildTarget, targetNode, targetType) -> DefaultParser.applyDefaultFlavors(buildTarget,
                        targetNode, targetType, parsingContext.getApplyDefaultFlavorsMode()),
                targetNodeProvider, targetNodeFilter);

        if (!state.getParsingContext().excludeUnsupportedTargets()) {
            return buildTargets;
        }/*from  w  ww  .  j  av  a2 s . co m*/
        return buildTargets.stream()
                .map(targets -> filterIncompatibleTargetNodes(state, targets.stream().map(state::getTargetNode))
                        .map(TargetNode::getBuildTarget).collect(ImmutableSet.toImmutableSet()))
                .collect(ImmutableList.toImmutableList());
    }
}

From source file:dagger.internal.codegen.ComponentModelBuilder.java

private void addConstructor() {
    List<List<CodeBlock>> partitions = Lists.partition(generatedComponentModel.getInitializations(),
            INITIALIZATIONS_PER_INITIALIZE_METHOD);

    ImmutableList<ParameterSpec> constructorParameters = constructorParameters();
    MethodSpec.Builder constructor = constructorBuilder()
            .addModifiers(generatedComponentModel.isAbstract() ? PROTECTED : PRIVATE)
            .addParameters(constructorParameters);

    if (generatedComponentModel.supermodel().isPresent()) {
        constructor.addStatement(CodeBlock.of("super($L)", constructorParameters.stream()
                .map(param -> CodeBlock.of("$N", param)).collect(toParametersCodeBlock())));
    }/*  w  ww  .j  ava 2  s  .  c  o m*/

    ImmutableList<ParameterSpec> initializeParameters = initializeParameters();
    CodeBlock initializeParametersCodeBlock = constructorParameters.stream()
            .map(param -> CodeBlock.of("$N", param)).collect(toParametersCodeBlock());

    UniqueNameSet methodNames = new UniqueNameSet();
    for (List<CodeBlock> partition : partitions) {
        String methodName = methodNames.getUniqueName("initialize");
        MethodSpec.Builder initializeMethod = methodBuilder(methodName).addModifiers(PRIVATE)
                /* TODO(gak): Strictly speaking, we only need the suppression here if we are also
                 * initializing a raw field in this method, but the structure of this code makes it
                 * awkward to pass that bit through.  This will be cleaned up when we no longer
                 * separate fields and initilization as we do now. */
                .addAnnotation(AnnotationSpecs.suppressWarnings(UNCHECKED))
                .addCode(CodeBlocks.concat(partition));
        initializeMethod.addParameters(initializeParameters);
        constructor.addStatement("$L($L)", methodName, initializeParametersCodeBlock);
        generatedComponentModel.addMethod(INITIALIZE_METHOD, initializeMethod.build());
    }
    generatedComponentModel.addMethod(CONSTRUCTOR, constructor.build());
}

From source file:com.digitalpetri.opcua.sdk.client.ClientSessionManager.java

private void transferSubscriptions(Transferring transferringState, OpcUaSession session) {
    UaTcpStackClient stackClient = client.getStackClient();
    OpcUaSubscriptionManager subscriptionManager = client.getSubscriptionManager();
    ImmutableList<UaSubscription> subscriptions = subscriptionManager.getSubscriptions();

    UInteger[] subscriptionIdsArray = subscriptions.stream().map(UaSubscription::getSubscriptionId)
            .toArray(UInteger[]::new);

    TransferSubscriptionsRequest request = new TransferSubscriptionsRequest(
            client.newRequestHeader(session.getAuthenticationToken()), subscriptionIdsArray, true);

    logger.debug("Sending TransferSubscriptionsRequest...");

    stackClient.<TransferSubscriptionsResponse>sendRequest(request).whenCompleteAsync((tsr, ex) -> {
        CompletableFuture<OpcUaSession> sessionFuture = transferringState.sessionFuture;

        if (tsr != null) {
            TransferResult[] results = tsr.getResults();

            for (int i = 0; i < results.length; i++) {
                TransferResult result = results[i];

                if (!result.getStatusCode().isGood()) {
                    UaSubscription subscription = subscriptions.get(i);

                    subscriptionManager.transferFailed(subscription.getSubscriptionId(),
                            result.getStatusCode());
                }//from  ww w . j  a  v a2 s  . c o m
            }

            if (logger.isDebugEnabled()) {
                Stream<UInteger> subscriptionIds = subscriptions.stream()
                        .map(UaSubscription::getSubscriptionId);
                Stream<StatusCode> statusCodes = Arrays.stream(results).map(TransferResult::getStatusCode);

                String[] ss = StreamUtils
                        .zip(subscriptionIds, statusCodes,
                                (i, s) -> String.format("id=%s/%s", i,
                                        StatusCodes.lookup(s.getValue()).map(sa -> sa[0]).orElse(s.toString())))
                        .toArray(String[]::new);

                logger.debug("TransferSubscriptions results: {}", Arrays.toString(ss));
            }

            state.compareAndSet(transferringState, new Active(session, sessionFuture));
            sessionFuture.complete(session);
        } else {
            StatusCode statusCode = UaException.extract(ex).map(UaException::getStatusCode)
                    .orElse(StatusCode.BAD);

            // Bad_ServiceUnsupported is the correct response when transfers aren't supported but
            // server implementations tend to interpret the spec in their own unique way...
            if (statusCode.getValue() == StatusCodes.Bad_NotImplemented
                    || statusCode.getValue() == StatusCodes.Bad_NotSupported
                    || statusCode.getValue() == StatusCodes.Bad_OutOfService
                    || statusCode.getValue() == StatusCodes.Bad_ServiceUnsupported) {

                logger.debug("TransferSubscriptions not supported: {}", statusCode);

                // transferFailed() will remove the subscription, but that is okay
                // because the list from getSubscriptions() above is a copy.
                for (UaSubscription subscription : subscriptions) {
                    subscriptionManager.transferFailed(subscription.getSubscriptionId(), statusCode);
                }

                state.compareAndSet(transferringState, new Active(session, sessionFuture));
                sessionFuture.complete(session);
            } else {
                logger.debug("TransferSubscriptions failed: {}", statusCode);

                Closing closing = new Closing();

                if (state.compareAndSet(transferringState, closing)) {
                    closeSession(closing, completedFuture(session));

                    closing.closeFuture.whenComplete((v, ex2) -> sessionFuture.completeExceptionally(ex));
                }
            }
        }
    });
}

From source file:com.google.errorprone.dataflow.nullnesspropagation.inference.NullnessQualifierInference.java

@Override
public Void visitMethodInvocation(MethodInvocationTree node, Void unused) {
    JCMethodInvocation sourceNode = (JCMethodInvocation) node;
    MethodSymbol callee = (MethodSymbol) TreeInfo.symbol(sourceNode.getMethodSelect());

    ImmutableList<TypeAndSymbol> formalParameters = callee.isVarArgs()
            ? expandVarargsToArity(callee.getParameters(), sourceNode.args.size())
            : callee.getParameters().stream().map(var -> TypeAndSymbol.create(var.type, var))
                    .collect(ImmutableList.toImmutableList());

    // Generate constraints for each argument write.
    Streams.forEachPair(formalParameters.stream(), sourceNode.getArguments().stream(), (formal, actual) -> {
        // formal parameter type (no l-val b/c that would wrongly constrain the method return)
        // TODO(b/116977632): constraints for actual parameter type (i.e. after type variable
        // substitution) without ignoring annotations directly on the parameter or vararg
        generateConstraintsForWrite(formal.type(), formal.symbol(), actual, /*lVal=*/ null);
    });/* w w w .  ja  va  2s.  c o  m*/

    // Generate constraints for method return
    generateConstraintsFromAnnotations(sourceNode.type, callee, callee.getReturnType(), sourceNode,
            new ArrayDeque<>());

    // If return type is parameterized by a generic type on receiver, collate references to that
    // generic between the receiver and the result/argument types.
    if (!callee.isStatic() && node.getMethodSelect() instanceof JCFieldAccess) {
        JCFieldAccess fieldAccess = ((JCFieldAccess) node.getMethodSelect());
        for (TypeVariableSymbol tvs : fieldAccess.selected.type.tsym.getTypeParameters()) {
            Type rcvrtype = fieldAccess.selected.type.tsym.type;
            ImmutableSet<InferenceVariable> rcvrReferences = findUnannotatedTypeVarRefs(tvs, rcvrtype,
                    /*decl=*/ null, fieldAccess.selected);
            Type restype = fieldAccess.sym.type.asMethodType().restype;
            // TODO(b/116977632): Propagate constraints for instantiated receiver types as well?
            findUnannotatedTypeVarRefs(tvs, restype, fieldAccess.sym, node).forEach(
                    resRef -> rcvrReferences.forEach(rcvrRef -> qualifierConstraints.putEdge(resRef, rcvrRef)));
            Streams.forEachPair(formalParameters.stream(), node.getArguments().stream(),
                    (formal, actual) -> findUnannotatedTypeVarRefs(tvs, formal.type(), formal.symbol(), actual)
                            .forEach(argRef -> rcvrReferences
                                    .forEach(rcvrRef -> qualifierConstraints.putEdge(argRef, rcvrRef))));
        }
    }

    // Get all references to each typeVar in the return type and formal parameters and relate them
    // in the constraint graph; covariant in the return type, contravariant in the argument types.
    // Annotated type var references override the type var's inferred qualifier, so ignore them.
    //
    // Additionally generate equality constraints between inferred types that are instantiations of
    // type parameters.  For instance, if a method type parameter <T> was instantiated List<String>
    // for a given call site m(x), and T appears in the return type as Optional<T>, then the
    // expression's inferred type will be Optional<List<String>> and we generate constraints to
    // equate T[0] = m(x)[0, 0].  If m's parameter's type is T then the argument type's inferred
    // type is List<String> and we also generate constraints to equate T[0] = x[0], which will
    // allow the inference to conclude later that x[0] = m(x)[0, 0], meaning the nullness qualifier
    // for x's <String> is the same as the one for m(x)'s <String>.
    for (TypeVariableSymbol typeVar : callee.getTypeParameters()) {
        TypeVariableInferenceVar typeVarIV = TypeVariableInferenceVar.create(typeVar, node);
        visitUnannotatedTypeVarRefsAndEquateInferredComponents(typeVarIV, callee.getReturnType(), callee, node,
                iv -> qualifierConstraints.putEdge(typeVarIV, iv));
        Streams.forEachPair(formalParameters.stream(), node.getArguments().stream(),
                (formal, actual) -> visitUnannotatedTypeVarRefsAndEquateInferredComponents(typeVarIV,
                        formal.type(), formal.symbol(), actual,
                        iv -> qualifierConstraints.putEdge(iv, typeVarIV)));
    }
    return super.visitMethodInvocation(node, unused);
}

From source file:com.facebook.buck.features.ocaml.PrebuiltOcamlLibraryDescription.java

@Override
public OcamlLibrary createBuildRule(BuildRuleCreationContextWithTargetGraph context, BuildTarget buildTarget,
        BuildRuleParams params, PrebuiltOcamlLibraryDescriptionArg args) {

    boolean bytecodeOnly = args.getBytecodeOnly();

    String libDir = args.getLibDir();

    String nativeLib = args.getNativeLib();
    String bytecodeLib = args.getBytecodeLib();
    ImmutableList<String> cLibs = args.getCLibs();
    ImmutableList<String> nativeCLibs = args.getNativeCLibs();
    ImmutableList<String> bytecodeCLibs = args.getBytecodeCLibs();

    Path libPath = buildTarget.getBasePath().resolve(libDir);
    Path includeDir = libPath.resolve(args.getIncludeDir());

    ProjectFilesystem projectFilesystem = context.getProjectFilesystem();
    Optional<SourcePath> staticNativeLibraryPath = bytecodeOnly ? Optional.empty()
            : Optional.of(PathSourcePath.of(projectFilesystem, libPath.resolve(nativeLib)));
    SourcePath staticBytecodeLibraryPath = PathSourcePath.of(projectFilesystem, libPath.resolve(bytecodeLib));
    ImmutableList<SourcePath> staticCLibraryPaths = cLibs.stream()
            .map(input -> PathSourcePath.of(projectFilesystem, libPath.resolve(input)))
            .collect(ImmutableList.toImmutableList());

    ImmutableList<SourcePath> staticNativeCLibraryPaths = nativeCLibs.stream()
            .map(input -> PathSourcePath.of(projectFilesystem, libPath.resolve(input)))
            .collect(ImmutableList.toImmutableList());

    ImmutableList<SourcePath> staticBytecodeCLibraryPaths = bytecodeCLibs.stream()
            .map(input -> PathSourcePath.of(projectFilesystem, libPath.resolve(input)))
            .collect(ImmutableList.toImmutableList());

    SourcePath bytecodeLibraryPath = PathSourcePath.of(projectFilesystem, libPath.resolve(bytecodeLib));

    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(context.getActionGraphBuilder());

    CxxDeps allDeps = CxxDeps.builder().addDeps(args.getDeps()).addPlatformDeps(args.getPlatformDeps()).build();

    return new PrebuiltOcamlLibrary(buildTarget, projectFilesystem, params, ruleFinder, staticNativeLibraryPath,
            staticBytecodeLibraryPath, staticCLibraryPaths, staticNativeCLibraryPaths,
            staticBytecodeCLibraryPaths, bytecodeLibraryPath, libPath, includeDir, allDeps);
}

From source file:com.spectralogic.dsbrowser.gui.services.tasks.GetBucketTask.java

@Override
protected ObservableList<TreeItem<Ds3TreeTableValue>> call() {
    try {//from   w w  w .  ja  v  a2 s  .  c  o m
        final GetBucketRequest request = BucketUtil.createRequest(ds3Value, bucket, ds3TreeTableItem,
                resourceBundle, PAGE_LENGTH);
        //if marker is set blank for a item that means offset is 0 else set the marker
        final GetBucketResponse bucketResponse = session.getClient().getBucket(request);
        //marker for the next request
        final String marker = bucketResponse.getListBucketResult().getNextMarker();
        //get list of objects with condition key should not be null and key name and prefix should not be same
        final ImmutableList<Ds3Object> ds3ObjectListFiles = bucketResponse.getListBucketResult().getObjects()
                .stream().filter(c -> c.getKey() != null)
                .filter(c -> !c.getKey().equals(ds3Value.getFullName()))
                .map(i -> new Ds3Object(i.getKey(), i.getSize())).collect(GuavaCollectors.immutableList());

        //use to store list of files
        final ImmutableList<Ds3TreeTableValue> filteredFiles;
        if (!Guard.isNullOrEmpty(ds3ObjectListFiles)) {
            filteredFiles = BucketUtil.getFilterFilesList(ds3ObjectListFiles, bucketResponse, bucket, session,
                    dateTimeUtils);
        } else {
            filteredFiles = ImmutableList.of();
        }

        //directoryValues is used to store directories
        final ImmutableList<Ds3TreeTableValue> directoryValues = BucketUtil.getDirectoryValues(bucketResponse,
                bucket);

        //after getting both lists we need to merge in partialResult and need to sort
        Platform.runLater(() -> {
            //if selected item is not load more then clear partial result list so that items will not appear twice
            if (ds3Value.getType() != Ds3TreeTableValue.Type.Loader) {
                partialResults.get().clear();
            }

            if (Guard.isNotNullAndNotEmpty(directoryValues)) {
                final ImmutableList<Ds3TreeTableItem> directoryItems = directoryValues.stream()
                        .map(item -> new Ds3TreeTableItem(bucket, session, item, workers, ds3Common,
                                dateTimeUtils, loggingService))
                        .collect(GuavaCollectors.immutableList());
                partialResults.get().addAll(directoryItems);
            }
            if (Guard.isNotNullAndNotEmpty(filteredFiles)) {
                final ImmutableList<Ds3TreeTableItem> fileItems = filteredFiles.stream()
                        .map(item -> new Ds3TreeTableItem(bucket, session, item, workers, ds3Common,
                                dateTimeUtils, loggingService))
                        .filter(distinctByKey(p -> p.getValue().getFullName()))
                        .collect(GuavaCollectors.immutableList());
                partialResults.get().addAll(fileItems);
            }
            partialResults.get().sort(new PartialResultComparator());
            ds3Common.getExpandedNodesInfo().put(
                    session.getSessionName() + StringConstants.SESSION_SEPARATOR + session.getEndpoint(),
                    ds3TreeTableItem);

            //if selected item was button then just remove that click more button and add new one
            if (ds3Value.getType() == Ds3TreeTableValue.Type.Loader) {
                //clear the selection
                if (null != ds3TreeTable && null != ds3TreeTable.getSelectionModel()
                        && null != ds3TreeTableItem.getParent()) {
                    ds3TreeTable.getSelectionModel().clearSelection();
                    ds3TreeTable.getSelectionModel().select(ds3TreeTableItem.getParent());
                    ds3Common.getExpandedNodesInfo().put(session.getSessionName()
                            + StringConstants.SESSION_SEPARATOR + session.getEndpoint(),
                            ds3TreeTableItem.getParent());
                    loggingService.logMessage((partialResults.get().size() - 1) + StringConstants.SPACE
                            + resourceBundle.getString("filesAndFolders") + StringConstants.SPACE
                            + ds3TreeTableItem.getParent().getValue().getType().toString()
                            + StringConstants.SPACE + ds3TreeTableItem.getParent().getValue().getFullName(),
                            LogType.SUCCESS);
                }
                partialResults.get().remove(ds3TreeTableItem);
            }
            if (!Guard.isStringNullOrEmpty(marker)) {
                //add a new click to add more button
                final HBox hbox = new HBox();
                hbox.getChildren().add(new Label(StringConstants.EMPTY_STRING));
                hbox.setAlignment(Pos.CENTER);
                final Text clickToLoadMore = new Text(resourceBundle.getString("addMoreButton"));
                clickToLoadMore.setFont(Font.font("Verdana", FontWeight.BOLD, 70));
                final Ds3TreeTableItem addMoreItem = new Ds3TreeTableItem(bucket, session,
                        new Ds3TreeTableValue(bucket, clickToLoadMore.getText(), Ds3TreeTableValue.Type.Loader,
                                -1, StringConstants.EMPTY_STRING, StringConstants.EMPTY_STRING, false, hbox,
                                marker),
                        workers, ds3Common, dateTimeUtils, loggingService);
                partialResults.get().add(addMoreItem);

            }
        });
    } catch (final IOException e) {
        LOG.error("Encountered an error trying to get the next list of items", e);
    }
    return partialResults.get();
}

From source file:com.facebook.buck.artifact_cache.AbstractAsynchronousCache.java

private void doMultiFetch(ImmutableList<ClaimedFetchRequest> requests) {
    boolean gotNonError = false;
    try (CacheEventListener.MultiFetchRequestEvents requestEvents = eventListener.multiFetchStarted(
            requests.stream().map(r -> r.getRequest().getBuildTarget()).filter(Objects::nonNull)
                    .collect(ImmutableList.toImmutableList()),
            requests.stream().map(r -> r.getRequest().getRuleKey()).collect(ImmutableList.toImmutableList()))) {
        try {/*from   www.java2  s  .  c o  m*/
            MultiFetchResult result = multiFetchImpl(requests.stream().map(ClaimedFetchRequest::getRequest)
                    .collect(ImmutableList.toImmutableList()));
            Preconditions.checkState(result.getResults().size() == requests.size());
            // MultiFetch must return a non-skipped result for at least one of the requested keys.
            Preconditions.checkState(result.getResults().stream().anyMatch(
                    fetchResult -> fetchResult.getCacheResult().getType() != CacheResultType.SKIPPED));
            for (int i = 0; i < requests.size(); i++) {
                ClaimedFetchRequest thisRequest = requests.get(i);
                FetchResult thisResult = result.getResults().get(i);
                if (thisResult.getCacheResult().getType() == CacheResultType.SKIPPED) {
                    requestEvents.skipped(i);
                    thisRequest.reschedule();
                } else {
                    requestEvents.finished(i, thisResult);
                    thisRequest.setResult(thisResult.getCacheResult());
                }
            }
            gotNonError = result.getResults().stream()
                    .anyMatch(fetchResult -> fetchResult.getCacheResult().getType() != CacheResultType.ERROR);
        } catch (IOException e) {
            ImmutableList<RuleKey> keys = requests.stream().map(r -> r.getRequest().getRuleKey())
                    .collect(ImmutableList.toImmutableList());
            String msg = String.format("multifetch(<%s>): %s: %s", Joiner.on(", ").join(keys),
                    e.getClass().getName(), e.getMessage());
            // Some of these might already be fulfilled. That's fine, this set() call will just be
            // ignored.
            for (int i = 0; i < requests.size(); i++) {
                CacheResult result = CacheResult.error(name, mode, msg);
                requestEvents.failed(i, e, msg, result);
                requests.get(i).setResult(result);
            }
        }
    } finally {
        if (gotNonError) {
            consecutiveMultiFetchErrorCount.set(0);
        } else {
            if (consecutiveMultiFetchErrorCount.incrementAndGet() == MAX_CONSECUTIVE_MULTI_FETCH_ERRORS) {
                LOG.info("Too many MultiFetch errors, falling back to Fetch only.");
                enableMultiFetch = false;
            }
        }
    }
}

From source file:com.spectralogic.dsbrowser.gui.components.ds3panel.ds3treetable.Ds3TreeTablePresenter.java

private void handleDragDetectedEvent(final Event event) {
    LOG.info("Drag detected...");
    final ObservableList<TreeItem<Ds3TreeTableValue>> selectedItems = ds3TreeTable.getSelectionModel()
            .getSelectedItems();/*from   w  w w  . j a  v  a  2  s.  c o m*/
    if (selectedItems != null) {
        final ImmutableList<Ds3TreeTableValue> selectedI = selectedItems.stream().map(TreeItem::getValue)
                .collect(GuavaCollectors.immutableList());
        final ImmutableList<Ds3TreeTableValueCustom> selected = selectedI.stream()
                .map(v -> new Ds3TreeTableValueCustom(v.getBucketName(), v.getFullName(), v.getType(),
                        v.getSize(), v.getLastModified(), v.getOwner(), v.isSearchOn()))
                .collect(GuavaCollectors.immutableList());
        if (!Guard.isNullOrEmpty(selectedI)) {
            LOG.info("Starting drag and drop event");
            final Dragboard db = ds3TreeTable.startDragAndDrop(TransferMode.COPY);
            final ClipboardContent content = new ClipboardContent();
            content.put(dataFormat, selected);
            content.putString(
                    session.getSessionName() + StringConstants.SESSION_SEPARATOR + session.getEndpoint());
            content.putFilesByPath(selected.stream().map(Ds3TreeTableValueCustom::getName)
                    .collect(GuavaCollectors.immutableList()));
            db.setContent(content);
        }
    }
    event.consume();
}