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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this list contains no elements.

Usage

From source file:org.caleydo.view.bicluster.sorting.FuzzyClustering.java

public List<IntFloat> filter(float threshold, int maxElements, EThresholdMode mode) {
    if (threshold == 0 && maxElements == UNBOUND_NUMBER) {
        switch (mode) {
        case ABS:
            return memberships.asList();
        case NEGATIVE_ONLY:
            return negatives(0, UNBOUND_NUMBER);
        case POSITVE_ONLY:
            return positives(0, UNBOUND_NUMBER);
        }//from  w w w  . j av a 2  s.c  o m
    }
    ImmutableList<IntFloat> negatives = mode.includeNegatives() ? negatives(threshold, maxElements)
            : ImmutableList.<IntFloat>of();
    ImmutableList<IntFloat> positives = mode.includePositives() ? positives(threshold, maxElements)
            : ImmutableList.<IntFloat>of();
    if (maxElements == UNBOUND_NUMBER || (negatives.size() + positives.size()) <= maxElements) //just add negatives and positives
        return ConcatedList.concat(negatives, positives);

    if (negatives.isEmpty()) {
        return positives.subList(Math.max(0, positives.size() - maxElements), positives.size());
    }
    if (positives.isEmpty())
        return negatives.subList(0, Math.min(negatives.size(), maxElements));

    // take the abs top X elements
    Iterator<IntFloat> negIt = negatives.iterator();
    Iterator<IntFloat> posIt = Lists.reverse(positives).iterator();
    IntFloat negEnd = null;
    IntFloat negAct = negIt.next();
    IntFloat posStart = null;
    IntFloat posAct = posIt.next();

    for (int i = 0; i < maxElements; ++i) {
        if (negAct == null || (posAct != null && posAct.getMembership() > -negAct.getMembership())) {
            posStart = posAct;
            posAct = posIt.hasNext() ? posIt.next() : null;
        } else {
            negEnd = negAct;
            negAct = negIt.hasNext() ? negIt.next() : null;
        }
    }

    ImmutableSortedSet<IntFloat> headSet = negEnd == null ? ImmutableSortedSet.<IntFloat>of()
            : memberships.headSet(negEnd, true);
    ImmutableSortedSet<IntFloat> tailSet = posStart == null ? ImmutableSortedSet.<IntFloat>of()
            : memberships.tailSet(posStart, true);
    return ConcatedList.concat(headSet.asList(), tailSet.asList());
}

From source file:com.facebook.buck.apple.XctoolRunTestsStep.java

@Override
public StepExecutionResult execute(ExecutionContext context) throws InterruptedException {
    ImmutableMap<String, String> env = getEnv(context);

    ProcessExecutorParams.Builder processExecutorParamsBuilder = ProcessExecutorParams.builder()
            .addAllCommand(command).setDirectory(filesystem.getRootPath().toAbsolutePath())
            .setRedirectOutput(ProcessBuilder.Redirect.PIPE).setEnvironment(env);

    if (!testSelectorList.isEmpty()) {
        try {/*from  w  w  w .j  a  v  a2 s.c o  m*/
            ImmutableList.Builder<String> xctoolFilterParamsBuilder = ImmutableList.builder();
            int returnCode = listAndFilterTestsThenFormatXctoolParams(context.getProcessExecutor(),
                    context.getConsole(), testSelectorList,
                    // Copy the entire xctool command and environment but add a -listTestsOnly arg.
                    ProcessExecutorParams.builder().from(processExecutorParamsBuilder.build())
                            .addCommand("-listTestsOnly").build(),
                    xctoolFilterParamsBuilder);
            if (returnCode != 0) {
                context.getConsole().printErrorText("Failed to query tests with xctool");
                return StepExecutionResult.of(returnCode);
            }
            ImmutableList<String> xctoolFilterParams = xctoolFilterParamsBuilder.build();
            if (xctoolFilterParams.isEmpty()) {
                context.getConsole().printBuildFailure(String.format(Locale.US,
                        "No tests found matching specified filter (%s)", testSelectorList.getExplanation()));
                return StepExecutionResult.SUCCESS;
            }
            processExecutorParamsBuilder.addAllCommand(xctoolFilterParams);
        } catch (IOException e) {
            context.getConsole().printErrorText("Failed to get list of tests from test bundle");
            context.getConsole().printBuildFailureWithStacktrace(e);
            return StepExecutionResult.ERROR;
        }
    }

    ProcessExecutorParams processExecutorParams = processExecutorParamsBuilder.build();

    // Only launch one instance of xctool at the time
    final AtomicBoolean stutterLockIsNotified = new AtomicBoolean(false);
    try {
        LOG.debug("Running command: %s", processExecutorParams);

        try {
            acquireStutterLock(stutterLockIsNotified);

            // Start the process.
            ProcessExecutor.LaunchedProcess launchedProcess = context.getProcessExecutor()
                    .launchProcess(processExecutorParams);

            int exitCode = -1;
            String stderr = "Unexpected termination";
            try {
                ProcessStdoutReader stdoutReader = new ProcessStdoutReader(launchedProcess);
                ProcessStderrReader stderrReader = new ProcessStderrReader(launchedProcess);
                Thread stdoutReaderThread = new Thread(stdoutReader);
                Thread stderrReaderThread = new Thread(stderrReader);
                stdoutReaderThread.start();
                stderrReaderThread.start();
                exitCode = waitForProcessAndGetExitCode(context.getProcessExecutor(), launchedProcess,
                        timeoutInMs);
                stdoutReaderThread.join(timeoutInMs.orElse(1000L));
                stderrReaderThread.join(timeoutInMs.orElse(1000L));
                Optional<IOException> exception = stdoutReader.getException();
                if (exception.isPresent()) {
                    throw exception.get();
                }
                stderr = stderrReader.getStdErr();
                LOG.debug("Finished running command, exit code %d, stderr %s", exitCode, stderr);
            } finally {
                context.getProcessExecutor().destroyLaunchedProcess(launchedProcess);
                context.getProcessExecutor().waitForLaunchedProcess(launchedProcess);
            }

            if (exitCode != 0) {
                if (!stderr.isEmpty()) {
                    context.getConsole().printErrorText(
                            String.format(Locale.US, "xctool failed with exit code %d: %s", exitCode, stderr));
                } else {
                    context.getConsole().printErrorText(
                            String.format(Locale.US, "xctool failed with exit code %d", exitCode));
                }
            }

            return StepExecutionResult.of(exitCode);

        } catch (Exception e) {
            LOG.error(e, "Exception while running %s", processExecutorParams.getCommand());
            MoreThrowables.propagateIfInterrupt(e);
            context.getConsole().printBuildFailureWithStacktrace(e);
            return StepExecutionResult.ERROR;
        }
    } finally {
        releaseStutterLock(stutterLockIsNotified);
    }
}

From source file:com.android.builder.testing.SimpleTestRunner.java

@Override
public boolean runTests(@NonNull String projectName, @NonNull String variantName, @NonNull File testApk,
        @NonNull TestData testData, @NonNull List<? extends DeviceConnector> deviceList, int maxThreads,
        int timeoutInMs, @NonNull Collection<String> installOptions, @NonNull File resultsDir,
        @NonNull File coverageDir, @NonNull ILogger logger)
        throws TestException, NoAuthorizedDeviceFoundException, InterruptedException {

    WaitableExecutor<Boolean> executor = new WaitableExecutor<Boolean>(maxThreads);

    int totalDevices = deviceList.size();
    int unauthorizedDevices = 0;
    int compatibleDevices = 0;

    for (final DeviceConnector device : deviceList) {
        if (device.getState() != IDevice.DeviceState.UNAUTHORIZED) {
            if (InstallUtils.checkDeviceApiLevel(device, testData.getMinSdkVersion(), logger, projectName,
                    variantName)) {//from  w ww  .j av  a2 s  .c o  m

                final DeviceConfigProvider deviceConfigProvider;
                try {
                    deviceConfigProvider = new DeviceConfigProviderImpl(device);
                } catch (DeviceException e) {
                    throw new TestException(e);
                }

                // now look for a matching output file
                ImmutableList<File> testedApks = ImmutableList.of();
                if (!testData.isLibrary()) {
                    try {
                        testedApks = testData.getTestedApks(mProcessExecutor, mSplitSelectExec,
                                deviceConfigProvider, logger);
                    } catch (ProcessException e) {
                        throw new TestException(e);
                    }

                    if (testedApks.isEmpty()) {
                        logger.info("Skipping device '%1$s' for '%2$s:%3$s': No matching output file",
                                device.getName(), projectName, variantName);
                        continue;
                    }
                }

                compatibleDevices++;
                executor.execute(new SimpleTestCallable(device, projectName, variantName, testApk, testedApks,
                        testData, resultsDir, coverageDir, timeoutInMs, logger));
            }
        } else {
            unauthorizedDevices++;
        }
    }

    if (totalDevices == 0 || compatibleDevices == 0) {
        CustomTestRunListener fakeRunListener = new CustomTestRunListener("TestRunner", projectName,
                variantName, logger);
        fakeRunListener.setReportDir(resultsDir);

        // create a fake test output
        Map<String, String> emptyMetrics = Collections.emptyMap();
        TestIdentifier fakeTest = new TestIdentifier(variantName,
                totalDevices == 0 ? ": No devices connected." : ": No compatible devices connected.");
        fakeRunListener.testStarted(fakeTest);
        fakeRunListener.testFailed(fakeTest, String.format(
                "Found %d connected device(s), %d of which were compatible.", totalDevices, compatibleDevices));
        fakeRunListener.testEnded(fakeTest, emptyMetrics);

        // end the run to generate the XML file.
        fakeRunListener.testRunEnded(0, emptyMetrics);

        return false;
    } else {

        if (unauthorizedDevices > 0) {
            CustomTestRunListener fakeRunListener = new CustomTestRunListener("TestRunner", projectName,
                    variantName, logger);
            fakeRunListener.setReportDir(resultsDir);

            // create a fake test output
            Map<String, String> emptyMetrics = Collections.emptyMap();
            TestIdentifier fakeTest = new TestIdentifier(variantName, ": found unauthorized devices.");
            fakeRunListener.testStarted(fakeTest);
            fakeRunListener.testFailed(fakeTest,
                    String.format("Found %d unauthorized device(s).", unauthorizedDevices));
            fakeRunListener.testEnded(fakeTest, emptyMetrics);

            // end the run to generate the XML file.
            fakeRunListener.testRunEnded(0, emptyMetrics);
        }

        List<WaitableExecutor.TaskResult<Boolean>> results = executor.waitForAllTasks();

        boolean success = unauthorizedDevices == 0;

        // check if one test failed or if there was an exception.
        for (WaitableExecutor.TaskResult<Boolean> result : results) {
            if (result.value != null) {
                success &= result.value;
            } else {
                success = false;
                logger.error(result.exception, null);
            }
        }
        return success;
    }
}

From source file:com.google.devtools.build.lib.syntax.BaseFunction.java

protected boolean hasSelfArgument() {
    Class<?> clazz = getObjectType();
    if (clazz == null) {
        return false;
    }//from  w  w w . ja v  a  2s . c om
    List<SkylarkType> types = signature.getTypes();
    ImmutableList<String> names = signature.getSignature().getNames();

    return (!types.isEmpty() && types.get(0).canBeCastTo(clazz))
            || (!names.isEmpty() && names.get(0).equals("self"));
}

From source file:li.klass.fhem.service.room.DeviceListParser.java

public RoomDeviceList parseXMLListUnsafe(String xmlList, Context context) throws Exception {
    if (xmlList != null) {
        xmlList = xmlList.trim();/* w  w  w .j a  v a2 s  .c om*/
    }

    RoomDeviceList allDevicesRoom = new RoomDeviceList(RoomDeviceList.ALL_DEVICES_ROOM);

    if (xmlList == null || "".equals(xmlList)) {
        LOG.error("xmlList is null or blank");
        return allDevicesRoom;
    }

    gPlotHolder.reset();
    Map<String, ImmutableList<XmlListDevice>> parsedDevices = parser.parse(xmlList);

    ReadErrorHolder errorHolder = new ReadErrorHolder();

    Map<String, FhemDevice> allDevices = newHashMap();

    for (Map.Entry<String, ImmutableList<XmlListDevice>> entry : parsedDevices.entrySet()) {
        DeviceType deviceType = getDeviceTypeFor(entry.getKey());

        ImmutableList<XmlListDevice> xmlListDevices = parsedDevices.get(entry.getKey());
        if (xmlListDevices == null || xmlListDevices.isEmpty()) {
            continue;
        }

        if (connectionService.mayShowInCurrentConnectionType(deviceType, context)) {

            int localErrorCount = devicesFromDocument(deviceType.getDeviceClass(), xmlListDevices, allDevices,
                    context);

            if (localErrorCount > 0) {
                errorHolder.addErrors(deviceType, localErrorCount);
            }
        }
    }

    ImmutableSet<SvgGraphDefinition> svgGraphDefinitions = createSvgGraphDefinitions(parsedDevices.get("svg"),
            allDevices);
    attachSvgGraphsToDevices(svgGraphDefinitions, allDevices);

    performAfterReadOperations(allDevices, errorHolder);
    RoomDeviceList roomDeviceList = buildRoomDeviceList(allDevices, context);

    handleErrors(errorHolder, context);

    LOG.info("loaded {} devices!", allDevices.size());

    return roomDeviceList;
}

From source file:org.waveprotocol.wave.federation.xmpp.XmppFederationRemote.java

/**
 * Handles a wavelet update message from a foreign Federation Host. Passes the
 * message to the local waveserver (synchronously) and replies.
 *
 * @param updateMessage the incoming XMPP message.
 * @param responseCallback response callback for acks and errors
 */// w w w  .j  av a2 s  .c  om
public void update(final Message updateMessage, final PacketCallback responseCallback) {
    final Element receiptRequested = updateMessage.getChildElement("request",
            XmppNamespace.NAMESPACE_XMPP_RECEIPTS);

    // Check existence of <event>
    Element event = updateMessage.getChildElement("event", XmppNamespace.NAMESPACE_PUBSUB_EVENT);
    if (event == null) {
        responseCallback.error(FederationErrors.badRequest("Event element missing from message"));
        return;
    }

    // Check existence of <items> within <event>
    Element items = event.element("items");
    if (items == null) {
        responseCallback.error(FederationErrors.badRequest("Items element missing from update message"));
        return;
    }

    // Complain if no items have been included.
    List<Element> elements = XmppUtil.toSafeElementList(items.elements("item"));
    if (elements.isEmpty()) {
        responseCallback.error(FederationErrors.badRequest("No items included"));
        return;
    }

    // Create a callback latch counter and corresponding countDown runnable.
    // When the latch reaches zero, send receipt (if it was requested).
    final AtomicInteger callbackCount = new AtomicInteger(1);
    final Runnable countDown = new Runnable() {
        @Override
        public void run() {
            if (callbackCount.decrementAndGet() == 0 && receiptRequested != null) {
                Message response = XmppUtil.createResponseMessage(updateMessage);
                response.addChildElement("received", XmppNamespace.NAMESPACE_XMPP_RECEIPTS);
                responseCallback.run(response);
            }
        }
    };

    WaveletFederationListener.WaveletUpdateCallback callback = new WaveletFederationListener.WaveletUpdateCallback() {
        @Override
        public void onSuccess() {
            countDown.run();
        }

        @Override
        public void onFailure(FederationError error) {
            // Note that we don't propogate the error, we just ack the stanza
            // and continue.
            // TODO(thorogood): We may want to rate-limit misbehaving servers
            // that are sending us invalid/malicious data.
            LOG.warning("Incoming XMPP waveletUpdate failure: " + error);
            countDown.run();
        }
    };

    // We must call callback once on every iteration to ensure that we send
    // response if receiptRequested != null.
    for (Element item : elements) {
        Element waveletUpdate = item.element("wavelet-update");

        if (waveletUpdate == null) {
            callback.onFailure(FederationErrors
                    .badRequest("wavelet-update element missing from message: " + updateMessage));
            continue;
        }

        final WaveletName waveletName;
        try {
            waveletName = XmppUtil.waveletNameCodec
                    .uriToWaveletName(waveletUpdate.attributeValue("wavelet-name"));
        } catch (EncodingException e) {
            callback.onFailure(FederationErrors.badRequest(
                    "Couldn't decode wavelet name: " + waveletUpdate.attributeValue("wavelet-name")));
            continue;
        }

        WaveletFederationListener listener = updatesListenerFactory
                .listenerForDomain(waveletName.waveletId.getDomain());

        // Submit all applied deltas to the domain-focused listener.
        ImmutableList.Builder<ByteString> builder = ImmutableList.builder();
        for (Element appliedDeltaElement : XmppUtil
                .toSafeElementList(waveletUpdate.elements("applied-delta"))) {
            builder.add(Base64Util.decode(appliedDeltaElement.getText()));
        }
        ImmutableList<ByteString> deltas = builder.build();
        if (!deltas.isEmpty()) {
            callbackCount.incrementAndGet(); // Increment required callbacks.
            listener.waveletDeltaUpdate(waveletName, deltas, callback);
        }

        // Optionally submit any received last committed notice.
        Element commitNoticeElement = waveletUpdate.element("commit-notice");
        if (commitNoticeElement != null) {
            ProtocolHashedVersion version = ProtocolHashedVersion.newBuilder()
                    .setHistoryHash(Base64Util.decode(commitNoticeElement.attributeValue("history-hash")))
                    .setVersion(Long.parseLong(commitNoticeElement.attributeValue("version"))).build();
            callbackCount.incrementAndGet(); // Increment required callbacks.
            listener.waveletCommitUpdate(waveletName, version, callback);
        }
    }

    // Release sentinel so that 'expected' callbacks from the WS don't invoke
    // sending a receipt.
    countDown.run();
}

From source file:org.waveprotocol.box.server.waveserver.WaveletContainerImpl.java

protected void notifyOfDeltas(ImmutableList<WaveletDeltaRecord> deltas, ImmutableSet<String> domainsToNotify) {
    Preconditions.checkState(writeLock.isHeldByCurrentThread(), "must hold write lock");
    Preconditions.checkArgument(!deltas.isEmpty(), "empty deltas");
    HashedVersion endVersion = deltas.get(deltas.size() - 1).getResultingVersion();
    HashedVersion currentVersion = getCurrentVersion();
    Preconditions.checkArgument(endVersion.equals(currentVersion),
            "cannot notify of deltas ending in %s != current version %s", endVersion, currentVersion);
    notifiee.waveletUpdate(waveletState.getSnapshot(), deltas, domainsToNotify);
}

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

/**
 * If {@code resolvedBindings} is an unscoped provision binding with no factory arguments or a
 * no-op members injection binding, then we don't need a field to hold its factory. In that case,
 * this method returns the static member select that returns the factory or no-op members
 * injector.//  w w  w.  ja  v  a 2s.  c o m
 */
private static Optional<MemberSelect> staticMemberSelect(ResolvedBindings resolvedBindings) {
    BindingKey bindingKey = resolvedBindings.bindingKey();
    switch (bindingKey.kind()) {
    case CONTRIBUTION:
        ContributionBinding contributionBinding = resolvedBindings.contributionBinding();
        if (contributionBinding.factoryCreationStrategy().equals(SINGLETON_INSTANCE)
                && !contributionBinding.scope().isPresent()) {
            switch (contributionBinding.bindingKind()) {
            case SYNTHETIC_MULTIBOUND_MAP:
                BindingType bindingType = contributionBinding.bindingType();
                MapType mapType = MapType.from(contributionBinding.key());
                return Optional.of(emptyFrameworkMapFactory(bindingType, mapType.keyType(),
                        mapType.unwrappedValueType(bindingType.frameworkClass())));

            case SYNTHETIC_MULTIBOUND_SET:
                return Optional.of(emptySetFactoryStaticMemberSelect(contributionBinding.bindingType(),
                        contributionBinding.key()));

            case INJECTION:
            case PROVISION:
                if (bindingKey.key().type().getKind().equals(DECLARED)) {
                    ImmutableList<TypeVariableName> typeVariables = bindingTypeElementTypeVariableNames(
                            contributionBinding);
                    if (!typeVariables.isEmpty()) {
                        List<? extends TypeMirror> typeArguments = ((DeclaredType) bindingKey.key().type())
                                .getTypeArguments();
                        return Optional.of(MemberSelect.parameterizedFactoryCreateMethod(
                                generatedClassNameForBinding(contributionBinding), typeArguments));
                    }
                }
                // fall through

            default:
                return Optional.of(staticMethod(generatedClassNameForBinding(contributionBinding),
                        CodeBlock.of("create()")));
            }
        }
        break;

    case MEMBERS_INJECTION:
        Optional<MembersInjectionBinding> membersInjectionBinding = resolvedBindings.membersInjectionBinding();
        if (membersInjectionBinding.isPresent() && membersInjectionBinding.get().injectionSites().isEmpty()) {
            return Optional.of(noOpMembersInjector(membersInjectionBinding.get().key().type()));
        }
        break;

    default:
        throw new AssertionError();
    }
    return Optional.empty();
}

From source file:org.apache.atlas.gremlin.GremlinExpressionFactory.java

private List<GroovyExpression> typeTestExpressionUsingInFilter(GraphPersistenceStrategies s,
        GroovyExpression parent, final String typeName) throws AtlasException {
    List<GroovyExpression> typeNames = new ArrayList<>();
    typeNames.add(new LiteralExpression(typeName));

    Map<TYPE_FILTER, String> filters = new HashMap<TYPE_FILTER, String>() {
        {/*  w ww. jav  a 2 s . c  o  m*/
            put(TYPE_FILTER.SUPERTYPE, typeName);
        }
    };

    ImmutableList<String> subTypes = TypeSystem.getInstance().getTypeNames(filters);

    if (!subTypes.isEmpty()) {
        for (String subType : subTypes) {
            typeNames.add(new LiteralExpression(subType));
        }
    }

    GroovyExpression inFilterExpr = generateHasExpression(s, parent, s.typeAttributeName(), IN_OPERATOR,
            new ListExpression(typeNames), null);

    return Collections.singletonList(inFilterExpr);
}

From source file:com.facebook.buck.apple.NewNativeTargetProjectMutator.java

private void addSourcePathToSourcesBuildPhase(SourceWithFlags sourceWithFlags, PBXGroup sourcesGroup,
        PBXSourcesBuildPhase sourcesBuildPhase) {
    SourceTreePath sourceTreePath = new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
            pathRelativizer.outputDirToRootRelative(sourcePathResolver.apply(sourceWithFlags.getSourcePath())),
            Optional.<String>absent());
    PBXFileReference fileReference = sourcesGroup.getOrCreateFileReferenceBySourceTreePath(sourceTreePath);
    PBXBuildFile buildFile = new PBXBuildFile(fileReference);
    sourcesBuildPhase.getFiles().add(buildFile);

    ImmutableList<String> customLangPreprocessorFlags = ImmutableList.of();
    Optional<CxxSource.Type> sourceType = CxxSource.Type
            .fromExtension(Files.getFileExtension(sourceTreePath.toString()));
    if (sourceType.isPresent() && langPreprocessorFlags.containsKey(sourceType.get())) {
        customLangPreprocessorFlags = langPreprocessorFlags.get(sourceType.get());
    }//w  w w .  j  av a  2 s  .  c  om

    ImmutableList<String> customFlags = ImmutableList
            .copyOf(Iterables.concat(customLangPreprocessorFlags, sourceWithFlags.getFlags()));
    if (!customFlags.isEmpty()) {
        NSDictionary settings = new NSDictionary();
        settings.put("COMPILER_FLAGS", Joiner.on(' ').join(customFlags));
        buildFile.setSettings(Optional.of(settings));
    }
    LOG.verbose("Added source path %s to group %s, flags %s, PBXFileReference %s", sourceWithFlags,
            sourcesGroup.getName(), customFlags, fileReference);
}