Example usage for com.google.common.collect Iterables isEmpty

List of usage examples for com.google.common.collect Iterables isEmpty

Introduction

In this page you can find the example usage for com.google.common.collect Iterables isEmpty.

Prototype

public static boolean isEmpty(Iterable<?> iterable) 

Source Link

Document

Determines if the given iterable contains no elements.

Usage

From source file:com.facebook.buck.log.ConsoleHandler.java

private Iterable<ConsoleHandlerState.Writer> getOutputStreamWritersForRecord(LogRecord record) {
    long recordThreadId = record.getThreadID();
    String logRecordCommandId = state.threadIdToCommandId(recordThreadId);
    if (logRecordCommandId != null) {
        ConsoleHandlerState.Writer consoleWriter = state.getWriter(logRecordCommandId);
        if (consoleWriter != null) {
            return ImmutableSet.of(consoleWriter);
        } else {/*ww  w.  j  av a 2 s .co  m*/
            return ImmutableSet.of(defaultOutputStreamWriter);
        }
    } else {
        Iterable<ConsoleHandlerState.Writer> allConsoleWriters = state.getAllAvailableWriters();
        if (Iterables.isEmpty(allConsoleWriters)) {
            return ImmutableSet.of(defaultOutputStreamWriter);
        } else {
            ImmutableSet.Builder<ConsoleHandlerState.Writer> builder = ImmutableSet.builder();
            builder.addAll(allConsoleWriters);
            return builder.build();
        }
    }
}

From source file:org.sonar.plugins.cpd.SonarEngine.java

static void save(SensorContext context, Resource<?> resource, @Nullable Iterable<CloneGroup> duplications) {
    if (duplications == null || Iterables.isEmpty(duplications)) {
        return;/* w  w w. ja  v a  2s.  c  o m*/
    }
    // Calculate number of lines and blocks
    Set<Integer> duplicatedLines = new HashSet<Integer>();
    double duplicatedBlocks = 0;
    for (CloneGroup clone : duplications) {
        ClonePart origin = clone.getOriginPart();
        for (ClonePart part : clone.getCloneParts()) {
            if (part.getResourceId().equals(origin.getResourceId())) {
                duplicatedBlocks++;
                for (int duplicatedLine = part.getStartLine(); duplicatedLine < part.getStartLine()
                        + part.getLines(); duplicatedLine++) {
                    duplicatedLines.add(duplicatedLine);
                }
            }
        }
    }
    // Save
    context.saveMeasure(resource, CoreMetrics.DUPLICATED_FILES, 1.0);
    context.saveMeasure(resource, CoreMetrics.DUPLICATED_LINES, (double) duplicatedLines.size());
    context.saveMeasure(resource, CoreMetrics.DUPLICATED_BLOCKS, duplicatedBlocks);

    Measure data = new Measure(CoreMetrics.DUPLICATIONS_DATA, toXml(duplications))
            .setPersistenceMode(PersistenceMode.DATABASE);
    context.saveMeasure(resource, data);
}

From source file:org.obm.push.protocol.data.MSEmailEncoder.java

private void serializeAttachments(Element parent, Set<MSAttachement> attachments) {
    if (!Iterables.isEmpty(attachments)) {
        Element atts = DOMUtils.createElement(parent, ASAirs.ATTACHMENTS.asASValue());
        for (MSAttachement msAtt : attachments) {
            Element att = DOMUtils.createElement(atts, ASAirs.ATTACHMENT.asASValue());
            DOMUtils.createElementAndText(att, ASAirs.DISPLAY_NAME.asASValue(), msAtt.getDisplayName());
            DOMUtils.createElementAndText(att, ASAirs.FILE_REFERENCE.asASValue(), msAtt.getFileReference());
            DOMUtils.createElementAndText(att, ASAirs.METHOD.asASValue(),
                    msAtt.getMethod().asSpecificationValue());
            DOMUtils.createElementAndText(att, ASAirs.ESTIMATED_DATA_SIZE.asASValue(),
                    msAtt.getEstimatedDataSize().toString());
            DOMUtils.createElementAndTextIfNotNull(att, ASAirs.CONTENT_ID.asASValue(), msAtt.getContentId());
            DOMUtils.createElementAndTextIfNotNull(att, ASAirs.CONTENT_LOCATION.asASValue(),
                    msAtt.getContentLocation());
            DOMUtils.createElementAndText(att, ASAirs.IS_INLINE.asASValue(), msAtt.isInline());
        }/*from w  ww  .ja  v a 2 s  .c om*/
    }
}

From source file:org.sonar.batch.cpd.JavaCpdEngine.java

static void save(org.sonar.api.batch.sensor.SensorContext context, InputFile inputFile,
        @Nullable Iterable<CloneGroup> duplications) {
    if (duplications == null || Iterables.isEmpty(duplications)) {
        return;//from  w w w. jav  a  2  s.c  om
    }
    computeBlockAndLineCount(context, inputFile, duplications);

    saveDuplications(context, inputFile, duplications);
}

From source file:org.apache.brooklyn.rest.resources.BundleResource.java

@Override
public TypeDetail getTypeExplicitVersion(String symbolicName, String version, String typeSymbolicName,
        String typeVersion) {//from  w  ww. j  av a 2s .  c om
    ManagedBundle b = lookup(symbolicName, version);
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.SEE_CATALOG_ITEM,
            typeSymbolicName + ":" + typeVersion)) {
        // TODO best to default to "not found" - unless maybe they have permission to "see null"
        throw WebResourceUtils.forbidden(
                "User '%s' not permitted to see info on this type (including whether or not installed)",
                Entitlements.getEntitlementContext().user());
    }

    Predicate<RegisteredType> pred = RegisteredTypePredicates.nameOrAlias(typeSymbolicName);
    pred = Predicates.and(pred, RegisteredTypePredicates.containingBundle(b.getVersionedName()));
    if (!LATEST.equalsIgnoreCase(typeVersion)) {
        pred = Predicates.and(pred, RegisteredTypePredicates.version(typeVersion));
    }
    Iterable<RegisteredType> items = mgmt().getTypeRegistry().getMatching(pred);

    if (Iterables.isEmpty(items)) {
        throw WebResourceUtils.notFound("Entity with id '%s:%s' not found", typeSymbolicName, typeVersion);
    }

    RegisteredType item = RegisteredTypes.getBestVersion(items);
    return TypeTransformer.detail(brooklyn(), item, ui.getBaseUriBuilder());
}

From source file:org.opendaylight.controller.cluster.datastore.CompositeDataTreeCohort.java

private void processResponses(final Future<Iterable<Object>> resultsFuture, final State currentState,
        final State afterState) throws TimeoutException, ExecutionException {
    final Iterable<Object> results;
    try {//from  www . j  av  a 2s.  c  om
        results = Await.result(resultsFuture, timeout.duration());
    } catch (Exception e) {
        successfulFromPrevious = null;
        Throwables.propagateIfInstanceOf(e, TimeoutException.class);
        throw Throwables.propagate(e);
    }
    Iterable<Failure> failed = Iterables.filter(results, Status.Failure.class);
    Iterable<Success> successful = Iterables.filter(results, DataTreeCohortActor.Success.class);
    successfulFromPrevious = successful;
    if (!Iterables.isEmpty(failed)) {
        changeStateFrom(currentState, State.FAILED);
        Iterator<Failure> it = failed.iterator();
        Throwable firstEx = it.next().cause();
        while (it.hasNext()) {
            firstEx.addSuppressed(it.next().cause());
        }
        Throwables.propagateIfPossible(firstEx, ExecutionException.class);
        Throwables.propagateIfPossible(firstEx, TimeoutException.class);
        throw Throwables.propagate(firstEx);
    }
    changeStateFrom(currentState, afterState);
}

From source file:org.apache.beam.runners.direct.EvaluationContext.java

/**
 * Handle the provided {@link TransformResult}, produced after evaluating the provided
 * {@link CommittedBundle} (potentially null, if the result of a root {@link PTransform}).
 *
 * <p>The result is the output of running the transform contained in the
 * {@link TransformResult} on the contents of the provided bundle.
 *
 * @param completedBundle the bundle that was processed to produce the result. Potentially
 *                        {@code null} if the transform that produced the result is a root
 *                        transform/*from   www.j  av a  2 s  . co  m*/
 * @param completedTimers the timers that were delivered to produce the {@code completedBundle},
 *                        or an empty iterable if no timers were delivered
 * @param result the result of evaluating the input bundle
 * @return the committed bundles contained within the handled {@code result}
 */
public CommittedResult handleResult(@Nullable CommittedBundle<?> completedBundle,
        Iterable<TimerData> completedTimers, TransformResult<?> result) {
    Iterable<? extends CommittedBundle<?>> committedBundles = commitBundles(result.getOutputBundles());
    metrics.commitLogical(completedBundle, result.getLogicalMetricUpdates());

    // Update watermarks and timers
    EnumSet<OutputType> outputTypes = EnumSet.copyOf(result.getOutputTypes());
    if (Iterables.isEmpty(committedBundles)) {
        outputTypes.remove(OutputType.BUNDLE);
    } else {
        outputTypes.add(OutputType.BUNDLE);
    }
    CommittedResult committedResult = CommittedResult.create(result,
            completedBundle == null ? null
                    : completedBundle.withElements((Iterable) result.getUnprocessedElements()),
            committedBundles, outputTypes);
    // Update state internals
    CopyOnAccessInMemoryStateInternals theirState = result.getState();
    if (theirState != null) {
        CopyOnAccessInMemoryStateInternals committedState = theirState.commit();
        StepAndKey stepAndKey = StepAndKey.of(result.getTransform(),
                completedBundle == null ? null : completedBundle.getKey());
        if (!committedState.isEmpty()) {
            applicationStateInternals.put(stepAndKey, committedState);
        } else {
            applicationStateInternals.remove(stepAndKey);
        }
    }
    // Watermarks are updated last to ensure visibility of any global state before progress is
    // permitted
    watermarkManager.updateWatermarks(completedBundle,
            result.getTimerUpdate().withCompletedTimers(completedTimers), committedResult,
            result.getWatermarkHold());
    return committedResult;
}

From source file:mesosphere.marathon.core.leadership.CandidateImpl.java

@Override
public Supplier<Boolean> offerLeadership(final Candidate.Leader leader)
        throws Group.JoinException, Group.WatchException, InterruptedException {

    // start a group watch, but only once in the life time of the the CandidateImpl.
    if (this.cancelWatch == null) {
        this.cancelWatch = this.group.watch(new Group.GroupChangeListener() {
            @Override//from   w w  w.  ja v  a 2s  . c  o  m
            public void onGroupChange(Iterable<String> memberIds) {
                Group.GroupChangeListener listener = groupChangeListener.get();
                if (listener != null) {
                    listener.onGroupChange(memberIds);
                }
            }
        });
    }

    // listen for group member changes
    final AtomicBoolean elected = new AtomicBoolean(false);
    final AtomicBoolean abdicated = new AtomicBoolean(false);
    final AtomicReference<Group.Membership> membershipRef = new AtomicReference<Group.Membership>(null);
    final AtomicReference<Iterable<String>> pendingChange = new AtomicReference<Iterable<String>>(null);
    this.groupChangeListener.set(new Group.GroupChangeListener() {
        @Override
        public void onGroupChange(Iterable<String> memberIds) {
            boolean noCandidates = Iterables.isEmpty(memberIds);
            Group.Membership membership;
            synchronized (CandidateImpl.this) {
                membership = membershipRef.get();
                if (membership == null) {
                    pendingChange.set(memberIds);
                    return;
                } else {
                    pendingChange.set(null);
                }
            }
            String memberId = membership.getMemberId();

            if (noCandidates) {
                LOG.warning("All candidates have temporarily left the group: " + group);
            } else if (!Iterables.contains(memberIds, memberId)) {
                LOG.severe(
                        String.format("Current member ID %s is not a candidate for leader, current voting: %s",
                                memberId, memberIds));
            } else {
                boolean electedLeader = memberId.equals(getLeader(memberIds));
                boolean previouslyElected = elected.getAndSet(electedLeader);

                if (!previouslyElected && electedLeader) {
                    LOG.info(String.format("Candidate %s is now leader of group: %s",
                            membership.getMemberPath(), memberIds));

                    leader.onElected(new ExceptionalCommand<Group.JoinException>() {
                        @Override
                        public void execute() throws Group.JoinException {
                            Group.Membership membership = membershipRef.get();
                            if (membership != null) {
                                membership.cancel();
                            }
                            abdicated.set(true);
                        }
                    });
                } else if (!electedLeader) {
                    if (previouslyElected) {
                        leader.onDefeated();
                    }
                    LOG.info(String.format(
                            "Candidate %s waiting for the next leader election, current voting: %s",
                            membership.getMemberPath(), memberIds));
                }
            }
        }
    });

    // join the group
    membershipRef.set(group.join(dataSupplier, new Command() {
        @Override
        public void execute() {
            membershipRef.set(null);
            leader.onDefeated();
        }
    }));

    // possibly the upper membershipRef.set is not finished yet when the groupChangeListener
    // fires above. Then one onGroupChange call is pending which is executed here:
    synchronized (this) {
        Iterable<String> memberIds = pendingChange.getAndSet(null);
        if (memberIds != null) {
            this.groupChangeListener.get().onGroupChange(memberIds);
        }
    }

    return new Supplier<Boolean>() {
        @Override
        public Boolean get() {
            return !abdicated.get() && elected.get();
        }
    };
}

From source file:org.sonar.scanner.report.MeasuresPublisher.java

private void updateTestExecutionFromTestPlan(final InputFile inputFile) {
    final MutableTestPlan testPlan = testPlanBuilder.getTestPlanByFile(inputFile);
    if (testPlan == null || Iterables.isEmpty(testPlan.testCases())) {
        return;//from  w ww. j ava 2  s . c o m
    }
    long nonSkippedTests = StreamSupport.stream(testPlan.testCases().spliterator(), false)
            .filter(t -> t.status() != Status.SKIPPED).count();
    measureCache.put(inputFile.key(), TESTS_KEY,
            new DefaultMeasure<Integer>().forMetric(TESTS).withValue((int) nonSkippedTests));
    long executionTime = StreamSupport.stream(testPlan.testCases().spliterator(), false)
            .mapToLong(t -> t.durationInMs() != null ? t.durationInMs().longValue() : 0L).sum();
    measureCache.put(inputFile.key(), TEST_EXECUTION_TIME_KEY,
            new DefaultMeasure<Long>().forMetric(TEST_EXECUTION_TIME).withValue(executionTime));
    long errorTests = StreamSupport.stream(testPlan.testCases().spliterator(), false)
            .filter(t -> t.status() == Status.ERROR).count();
    measureCache.put(inputFile.key(), TEST_ERRORS_KEY,
            new DefaultMeasure<Integer>().forMetric(TEST_ERRORS).withValue((int) errorTests));
    long skippedTests = StreamSupport.stream(testPlan.testCases().spliterator(), false)
            .filter(t -> t.status() == Status.SKIPPED).count();
    measureCache.put(inputFile.key(), SKIPPED_TESTS_KEY,
            new DefaultMeasure<Integer>().forMetric(SKIPPED_TESTS).withValue((int) skippedTests));
    long failedTests = StreamSupport.stream(testPlan.testCases().spliterator(), false)
            .filter(t -> t.status() == Status.FAILURE).count();
    measureCache.put(inputFile.key(), TEST_FAILURES_KEY,
            new DefaultMeasure<Integer>().forMetric(TEST_FAILURES).withValue((int) failedTests));
}

From source file:org.eclipse.reqcycle.ocl.utils.OCLUtilities.java

/**
 * Gets operations that could be used to match uml elements to a data type. These operations
 * must have a specific name and signature (no parameter, return boolean).
 *///w  ww . jav  a2  s.  c  o m
public static Iterable<DefOperationCS> getMatchingOperations(final IAttribute attribute,
        BaseResource resource) {
    Collection<DefOperationCS> operations = getOperations(resource);
    if (operations == null || Iterables.isEmpty(operations)) {
        return Collections.emptyList();
    }
    return Iterables.filter(operations, new Predicate<DefOperationCS>() {

        @Override
        public boolean apply(DefOperationCS arg0) {
            TypedRefCS operationReturnType = arg0.getOwnedType();
            if (!arg0.getParameters().isEmpty()) {
                return false;
            }
            if (operationReturnType instanceof PrimitiveTypeRefCS) {
                String returnType = ((PrimitiveTypeRefCS) operationReturnType).getName();
                String attributeTypeName = attribute.getName();
                String lookupResult = ecoreToOCLPrimitiveTypes.get(attributeTypeName);
                if (lookupResult == null || !lookupResult.equals(returnType)) {
                    return false;
                }
            }
            return arg0.getName().equalsIgnoreCase(getOperationRequiredName(attribute));
        }
    });
}