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.zanata.client.commands.push.AbstractCommonPushStrategy.java

/**
 * excludes should already contain paths for translation files that are to
 * be excluded.//from w  w  w .  j a  v  a  2 s .  c o  m
 */
public String[] getSrcFiles(File srcDir, ImmutableList<String> includes, ImmutableList<String> excludes,
        ImmutableList<String> fileExtensions, boolean useDefaultExcludes, boolean isCaseSensitive) {
    if (includes.isEmpty()) {
        ImmutableList.Builder<String> builder = ImmutableList.builder();
        for (String fileExtension : fileExtensions) {
            builder.add("**/*" + fileExtension);
        }
        includes = builder.build();
    }

    DirectoryScanner dirScanner = new DirectoryScanner();

    if (useDefaultExcludes) {
        dirScanner.addDefaultExcludes();
    }

    dirScanner.setBasedir(srcDir);

    dirScanner.setCaseSensitive(isCaseSensitive);

    dirScanner.setExcludes(excludes.toArray(new String[excludes.size()]));
    dirScanner.setIncludes(includes.toArray(new String[includes.size()]));
    dirScanner.scan();
    String[] includedFiles = dirScanner.getIncludedFiles();
    for (int i = 0; i < includedFiles.length; i++) {
        // canonicalise file separator (to handle backslash on Windows)
        includedFiles[i] = includedFiles[i].replace(File.separator, "/");
    }
    return includedFiles;
}

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

private Platform getTargetPlatform(ConfigurationRuleResolver configurationRuleResolver,
        ConstraintResolver constraintResolver, Cell rootCell, ImmutableList<String> targetPlatforms) {
    if (targetPlatforms.isEmpty()) {
        return new ConstraintBasedPlatform("", ImmutableSet.of());
    }//from   w w w .j  a  v a 2  s .co  m

    String targetPlatformName = targetPlatforms.get(0);
    ConfigurationRule configurationRule = configurationRuleResolver
            .getRule(unconfiguredBuildTargetFactory.create(rootCell.getCellPathResolver(), targetPlatformName)
                    .configure(EmptyTargetConfiguration.INSTANCE));

    if (!(configurationRule instanceof PlatformRule)) {
        throw new HumanReadableException(
                "%s is used as a target platform, but not declared using `platform` rule", targetPlatformName);
    }

    PlatformRule platformRule = (PlatformRule) configurationRule;

    ImmutableSet<ConstraintValue> constraintValues = platformRule.getConstrainValues().stream()
            .map(constraintResolver::getConstraintValue).collect(ImmutableSet.toImmutableSet());

    return new ConstraintBasedPlatform(targetPlatformName, constraintValues);
}

From source file:org.onosproject.net.intent.impl.compiler.ConnectivityIntentCompiler.java

/**
 * Computes a path between two ConnectPoints.
 *
 * @param intent intent on which behalf path is being computed
 * @param one    start of the path//w w  w .  j a v  a2s .  c  o  m
 * @param two    end of the path
 * @return Path between the two
 * @throws PathNotFoundException if a path cannot be found
 */
protected Path getPath(ConnectivityIntent intent, ElementId one, ElementId two) {
    Set<Path> paths = pathService.getPaths(one, two, weight(intent.constraints()));
    final List<Constraint> constraints = intent.constraints();
    ImmutableList<Path> filtered = FluentIterable.from(paths).filter(path -> checkPath(path, constraints))
            .toList();
    if (filtered.isEmpty()) {
        throw new PathNotFoundException(one, two);
    }
    // TODO: let's be more intelligent about this eventually
    return filtered.iterator().next();
}

From source file:com.facebook.buck.versions.VersionedTargetGraph.java

@Nullable
@Override/*from  w w w  .  ja  va 2  s  .  c  o  m*/
protected TargetNode<?, ?> getInternal(BuildTarget target) {

    // If this node is in the graph under the given name, return it.
    TargetNode<?, ?> node = targetsToNodes.get(target);
    if (node != null) {
        return node;
    }

    ImmutableList<ImmutableSet<Flavor>> flavorList = flavorMap.get(target.getUnflavoredBuildTarget());
    if (flavorList == null) {
        return null;
    }

    // Otherwise, see if this node exists in the graph with a "less" flavored name.  We initially
    // select all targets which contain a subset of the original flavors, which should be sorted by
    // from largest flavor set to smallest.  We then use the first match, and verify the subsequent
    // matches are subsets.
    ImmutableList<ImmutableSet<Flavor>> matches = RichStream.from(flavorList)
            .filter(target.getFlavors()::containsAll).toImmutableList();
    if (!matches.isEmpty()) {
        ImmutableSet<Flavor> firstMatch = matches.get(0);
        for (ImmutableSet<Flavor> subsequentMatch : matches.subList(1, matches.size())) {
            Preconditions.checkState(firstMatch.size() > subsequentMatch.size());
            Preconditions.checkState(firstMatch.containsAll(subsequentMatch),
                    "Found multiple disjoint flavor matches for %s: %s and %s",
                    target.getUnflavoredBuildTarget(), firstMatch, subsequentMatch);
        }
        return Preconditions.checkNotNull(targetsToNodes.get(target.withFlavors(firstMatch)))
                .withFlavors(target.getFlavors());
    }

    // Otherwise, return `null` to indicate this node isn't in the target graph.
    return null;
}

From source file:com.facebook.buck.event.listener.PublicAnnouncementManager.java

public void getAndPostAnnouncements() {
    final ListenableFuture<ImmutableList<Announcement>> message = service.submit(() -> {
        Optional<ClientSideSlb> slb = logConfig.getFrontendConfig().tryCreatingClientSideSlb(clock, eventBus,
                new CommandThreadFactory("PublicAnnouncement"));

        if (slb.isPresent()) {
            try (FrontendService frontendService = new FrontendService(ThriftOverHttpServiceConfig
                    .of(new LoadBalancedService(slb.get(), logConfig.createOkHttpClient(), eventBus)))) {
                AnnouncementRequest announcementRequest = new AnnouncementRequest();
                announcementRequest.setBuckVersion(getBuckVersion());
                announcementRequest.setRepository(repository);
                FrontendRequest request = new FrontendRequest();
                request.setType(FrontendRequestType.ANNOUNCEMENT);
                request.setAnnouncementRequest(announcementRequest);

                FrontendResponse response = frontendService.makeRequest(request);
                return ImmutableList.copyOf(response.announcementResponse.announcements);
            } catch (IOException e) {
                throw new HumanReadableException("Failed to perform request", e);
            }//from  www .j a  va 2 s .  co  m
        } else {
            throw new HumanReadableException("Failed to establish connection to server.");
        }
    });

    Futures.addCallback(message, new FutureCallback<ImmutableList<Announcement>>() {

        @Override
        public void onSuccess(ImmutableList<Announcement> announcements) {
            LOG.info("Public announcements fetched successfully.");
            if (!announcements.isEmpty()) {
                String announcement = HEADER_MSG;
                for (Announcement entry : announcements) {
                    announcement = announcement.concat(String.format(ANNOUNCEMENT_TEMPLATE,
                            entry.getErrorMessage(), entry.getSolutionMessage()));
                }
                consoleEventBusListener.setPublicAnnouncements(eventBus, Optional.of(announcement));
            }
        }

        @Override
        public void onFailure(Throwable t) {
            LOG.warn("Failed to get public announcements. Reason: %s", t.getMessage());
        }
    });
}

From source file:com.facebook.buck.counters.CounterRegistryImpl.java

private void flushCounters() {
    List<Optional<CounterSnapshot>> snapshots;
    synchronized (this) {
        snapshots = Lists.newArrayListWithCapacity(counters.size());
        for (Counter counter : counters) {
            snapshots.add(counter.flush());
        }/* w w  w .j a  va  2 s .c o  m*/
    }

    ImmutableList<CounterSnapshot> presentSnapshots = snapshots.stream().flatMap(Optionals::toStream)
            .collect(MoreCollectors.toImmutableList());
    if (!presentSnapshots.isEmpty()) {
        CountersSnapshotEvent event = new CountersSnapshotEvent(presentSnapshots);
        eventBus.post(event);
    }
}

From source file:de.metas.ui.web.document.filter.DocumentFiltersList.java

public DocumentFiltersList unwrapAndCopy(final DocumentFilterDescriptorsProvider descriptors) {
    if (filters != null) {
        return this;
    }/* ww  w  . jav  a2 s.co  m*/

    if (jsonFilters == null || jsonFilters.isEmpty()) {
        return this;
    }

    final ImmutableList<DocumentFilter> filtersNew = JSONDocumentFilter.unwrapList(jsonFilters, descriptors);
    if (filtersNew.isEmpty()) {
        return EMPTY;
    }

    final ImmutableList<JSONDocumentFilter> jsonFiltersNew = null;
    return new DocumentFiltersList(jsonFiltersNew, filtersNew);
}

From source file:com.google.errorprone.bugpatterns.argumentselectiondefects.Costs.java

Changes computeAssignments() {
    int[] assignments = new HungarianAlgorithm(costMatrix).execute();
    ImmutableList<Parameter> formalsWithChange = formals.stream()
            .filter(f -> assignments[f.index()] != f.index()).collect(toImmutableList());

    if (formalsWithChange.isEmpty()) {
        return Changes.empty();
    }/*from  ww  w.  jav  a  2  s  .  c om*/

    ImmutableList<Double> originalCost = formalsWithChange.stream()
            .map(f2 -> costMatrix[f2.index()][f2.index()]).collect(toImmutableList());

    ImmutableList<Double> assignmentCost = formalsWithChange.stream()
            .map(f1 -> costMatrix[f1.index()][assignments[f1.index()]]).collect(toImmutableList());

    ImmutableList<ParameterPair> changes = formalsWithChange.stream()
            .map(f -> ParameterPair.create(f, actuals.get(assignments[f.index()]))).collect(toImmutableList());

    return Changes.create(originalCost, assignmentCost, changes);
}

From source file:com.sk89q.squirrelid.resolver.HttpRepositoryService.java

@Nullable
@Override//from   ww  w. j  a v  a 2 s.c  om
public Profile findByName(String name) throws IOException, InterruptedException {
    ImmutableList<Profile> profiles = findAllByName(Arrays.asList(name));
    if (!profiles.isEmpty()) {
        return profiles.get(0);
    } else {
        return null;
    }
}

From source file:li.klass.fhem.service.room.xmllist.XmlListParser.java

public Map<String, ImmutableList<XmlListDevice>> parse(String xmlList) throws Exception {
    Map<String, ImmutableList<XmlListDevice>> result = Maps.newHashMap();

    // replace device tag extensions
    xmlList = xmlList.replaceAll("_[0-9]+_LIST", "_LIST");
    xmlList = xmlList.replaceAll("(<[/]?[A-Z0-9]+)_[0-9]+([ >])", "$1$2");
    xmlList = xmlList.replaceAll("</>", "");
    xmlList = xmlList.replaceAll("< [^>]*>", "");
    xmlList = xmlList.replaceAll("< name=[a-zA-Z\"=0-9 ]+>", "");

    Document document = documentFromXmlList(xmlList);
    Node baseNode = findFHZINFONode(document);

    NodeList childNodes = baseNode.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        if (node.getNodeName().endsWith("_LIST")) {
            ImmutableList<XmlListDevice> devices = handleListNode(node);
            if (devices.isEmpty()) {
                continue;
            }//from w w  w .j  av a2 s.  com
            String deviceType = devices.get(0).getType().toLowerCase(Locale.getDefault());
            if (result.containsKey(deviceType)) {
                // In case we have two LISTs for the same device type, we need to merge
                // existing lists. FHEM will not send out those lists, but we replace
                // i.e. SWAP_123_LIST by SWAP_LIST, resulting in two same list names.
                Iterable<XmlListDevice> existing = result.get(deviceType);
                result.put(deviceType, ImmutableList.copyOf(Iterables.concat(existing, devices)));
            } else {
                result.put(deviceType, devices);
            }
        }
    }

    return ImmutableMap.copyOf(result);
}