Java Code Examples for com.google.common.collect.Iterables#isEmpty()

The following examples show how to use com.google.common.collect.Iterables#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApiConfigValidator.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
/**
 * Validates all configurations for a single API.  Makes sure the API-level configuration matches
 * for all classes and that the contained configuration is valid and can be turned into a *.api
 * file.  Only checks for swarm-specific validity.  Apiary FE may still dislike a config for its
 * own reasons.
 *
 * @throws ApiConfigInvalidException on any invalid API-wide configuration.
 * @throws ApiClassConfigInvalidException on any invalid API class configuration.
 * @throws ApiMethodConfigInvalidException on any invalid API method configuration.
 * @throws ApiParameterConfigInvalidException on any invalid API parameter configuration.
 */
public void validate(Iterable<? extends ApiConfig> apiConfigs)
    throws ApiConfigInvalidException, ApiClassConfigInvalidException,
    ApiMethodConfigInvalidException, ApiParameterConfigInvalidException {
  if (Iterables.isEmpty(apiConfigs)) {
    return;
  }

  Map<String, ApiMethodConfig> restfulSignatures = Maps.newHashMap();

  Iterator<? extends ApiConfig> i = apiConfigs.iterator();
  ApiConfig first = i.next();
  validate(first, restfulSignatures);

  while (i.hasNext()) {
    ApiConfig config = i.next();
    Iterable<ApiConfigInconsistency<Object>> inconsistencies =
        config.getConfigurationInconsistencies(first);
    if (!Iterables.isEmpty(inconsistencies)) {
      throw new InconsistentApiConfigurationException(config, first, inconsistencies);
    }
    validate(config, restfulSignatures);
  }
}
 
Example 2
Source File: VanillaJavaBuilder.java    From bazel with Apache License 2.0 6 votes vote down vote up
/** Sets the compilation search paths and output directories. */
private static void setLocations(
    OptionsParser optionsParser, StandardJavaFileManager fileManager, Path nativeHeaderDir)
    throws IOException {
  fileManager.setLocation(StandardLocation.CLASS_PATH, toFiles(optionsParser.getClassPath()));
  Iterable<File> bootClassPath = toFiles(optionsParser.getBootClassPath());
  // The bootclasspath may legitimately be empty if --release is being used.
  if (!Iterables.isEmpty(bootClassPath)) {
    fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, bootClassPath);
  }
  fileManager.setLocation(
      StandardLocation.ANNOTATION_PROCESSOR_PATH, toFiles(optionsParser.getProcessorPath()));
  if (optionsParser.getSourceGenDir() != null) {
    setOutputLocation(
        fileManager, StandardLocation.SOURCE_OUTPUT, Paths.get(optionsParser.getSourceGenDir()));
  }
  if (optionsParser.getNativeHeaderOutput() != null) {
    setOutputLocation(fileManager, StandardLocation.NATIVE_HEADER_OUTPUT, nativeHeaderDir);
  }
  setOutputLocation(
      fileManager, StandardLocation.CLASS_OUTPUT, Paths.get(optionsParser.getClassDir()));
}
 
Example 3
Source File: DependencyManager.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public void setDependencies(final ReflectionId reflectionId, ExtractedDependencies extracted) throws DependencyException {
  Preconditions.checkState(!extracted.isEmpty(), "expected non empty dependencies");

  Set<DependencyEntry> dependencies = extracted.getPlanDependencies();

  if (Iterables.isEmpty(dependencies)) {
    // no plan dependencies found, use decision dependencies instead
    graph.setDependencies(reflectionId, extracted.getDecisionDependencies());
    return;
  }

  // if P > R1 > R2 and R2 is either FAILED or DEPRECATED we should exclude it from the dependencies and include
  // all datasets instead. We do this to avoid never refreshing R2 again if R1 is never refreshed
  // Note that even though delete(R1) will also update R2 dependencies, it may not be enough if R2 was refreshing
  // while the update happens as setDependencies(R2, ...) would overwrite the update, that's why we include all the datasets
  if (Iterables.any(dependencies, isDeletedReflection)) {
    // filter out deleted reflections, and include all dataset dependencies
    dependencies = FluentIterable.from(dependencies)
      .filter(not(isDeletedReflection))
      .append(extracted.getDecisionDependencies())
      .toSet();
  }

  graph.setDependencies(reflectionId, dependencies);
}
 
Example 4
Source File: Inliner.java    From immutables with Apache License 2.0 6 votes vote down vote up
private void addBodyIfNecessary(
    ForStatement.Builder builder,
    List<Trees.Expression> params,
    Iterable<? extends Trees.TemplatePart> bodyParts) {
  // body goes as one special parameter, don't handle other mismatches
  if (Iterables.isEmpty(bodyParts)) {
    return;
  }

  Preconditions.checkState(inlinable.declaration().parameters().size() == params.size() + 1);

  Trees.Parameter lastParameter = Iterables.getLast(inlinable.declaration().parameters());

  LetStatement.Builder letBuilder = LetStatement.builder()
      .addAllParts(bodyParts)
      .declaration(InvokableDeclaration.builder()
          .name(remappedIdentifier(lastParameter.name()))
          .build());

  remapped.add(lastParameter.name());
  builder.addParts(letBuilder.build());
}
 
Example 5
Source File: AccelerationStoragePlugin.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
private void deleteOwnedRefreshes(Materialization materialization, SchemaConfig schemaConfig) {
  Iterable<Refresh> refreshes = materializationStore.getRefreshesExclusivelyOwnedBy(materialization);
  if (Iterables.isEmpty(refreshes)) {
    logger.debug("deleted materialization {} has no associated refresh");
    return;
  }

  for (Refresh r : refreshes) {
    try {
      //TODO once DX-10850 is fixed we should no longer need to split the refresh path into separate components
      final List<String> tableSchemaPath = ImmutableList.<String>builder()
        .add(ReflectionServiceImpl.ACCELERATOR_STORAGEPLUGIN_NAME)
        .addAll(PathUtils.toPathComponents(r.getPath()))
        .build();
      logger.debug("deleting refresh {}", tableSchemaPath);
      super.dropTable(tableSchemaPath, false, schemaConfig);
    } catch (Exception e) {
      logger.warn("Couldn't delete refresh {}", r.getId().getId(), e);
    } finally {
      materializationStore.delete(r.getId());
    }
  }
}
 
Example 6
Source File: BuildEventStreamer.java    From bazel with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("GuardedBy")
void flush() {
  List<BuildEvent> updateEvents = null;
  synchronized (this) {
    Iterable<String> allOut = ImmutableList.of();
    Iterable<String> allErr = ImmutableList.of();
    if (outErrProvider != null) {
      allOut = orEmpty(outErrProvider.getOut());
      allErr = orEmpty(outErrProvider.getErr());
    }
    if (Iterables.isEmpty(allOut) && Iterables.isEmpty(allErr)) {
      // Nothing to flush; avoid generating an unneeded progress event.
      return;
    }
    if (announcedEvents != null) {
      updateEvents = new ArrayList<>();
      List<BuildEvent> finalUpdateEvents = updateEvents;
      consumeAsPairsofStrings(
          allOut, allErr, (s1, s2) -> finalUpdateEvents.add(flushStdoutStderrEvent(s1, s2)));
    } else {
      consumeAsPairsofStrings(
          allOut, allErr, (s1, s2) -> bufferedStdoutStderrPairs.add(Pair.of(s1, s2)));
    }
  }
  if (updateEvents != null) {
    for (BuildEvent updateEvent : updateEvents) {
      for (BuildEventTransport transport : transports) {
        transport.sendBuildEvent(updateEvent);
      }
    }
  }
}
 
Example 7
Source File: LanguageIdentifierService.java    From spoofax with Apache License 2.0 5 votes vote down vote up
@Override public boolean available(ILanguageImpl impl) {
    final Iterable<IdentificationFacet> facets = impl.facets(IdentificationFacet.class);
    if(Iterables.isEmpty(facets)) {
        return false;
    }
    return true;
}
 
Example 8
Source File: EnrichmentLookup.java    From metron with Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<Boolean> exists(Iterable<KeyWithContext<EnrichmentKey, HBaseContext>> key, boolean logAccess) throws IOException {
  List<Boolean> ret = new ArrayList<>();
  if(Iterables.isEmpty(key)) {
    return Collections.emptyList();
  }
  Table table = Iterables.getFirst(key, null).getContext().getTable();
  for(boolean b : table.existsAll(keysToGets(key))) {
    ret.add(b);
  }
  return ret;
}
 
Example 9
Source File: BasicStartableImpl.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Collection<? extends Location> locations) {
    try {
        ServiceStateLogic.setExpectedState(this, Lifecycle.STARTING);

        // Opportunity to block startup until other dependent components are available
        Object val = config().get(START_LATCH);
        if (val != null) log.debug("{} finished waiting for start-latch; continuing...", this);

        addLocations(locations);
        locations = Locations.getLocationsCheckingAncestors(locations, this);
        log.info("Starting entity "+this+" at "+locations);

        // essentially does StartableMethods.start(this, locations),
        // but optionally filters locations for each child

        Locations.LocationsFilter filter = getConfig(LOCATIONS_FILTER);
        Iterable<Entity> startables = filterStartableManagedEntities(getChildren());
        if (!Iterables.isEmpty(startables)) {
            List<Task<?>> tasks = Lists.newArrayListWithCapacity(Iterables.size(startables));
            for (final Entity entity : startables) {
                Collection<? extends Location> l2 = locations;
                if (filter != null) {
                    l2 = filter.filterForContext(new ArrayList<Location>(locations), entity);
                    log.debug("Child " + entity + " of " + this + " being started in filtered location list: " + l2);
                }
                tasks.add(Entities.invokeEffectorWithArgs(this, entity, Startable.START, l2));
            }
            for (Task<?> t : tasks) {
                t.getUnchecked();
            }
        }
        sensors().set(Attributes.SERVICE_UP, true);
    } finally {
        ServiceStateLogic.setExpectedState(this, Lifecycle.RUNNING);
    }
}
 
Example 10
Source File: ComponentEntityAdapter.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Check for the existence of a component with {@code group}, {@code name}, and {@code version} in {@code bucket}.
 *
 * @since 3.8
 */
public boolean exists(final ODatabaseDocumentTx db,
                      @Nullable final String group,
                      final String name,
                      @Nullable final String version,
                      final Bucket bucket)
{
  Map<String, Object> params = Maps.newHashMap();
  params.put(P_GROUP, group);
  params.put(P_NAME, checkNotNull(name));
  params.put(P_VERSION, version);
  params.put(P_BUCKET, recordIdentity(id(checkNotNull(bucket))));
  OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<>(EXISTS_QUERY_STRING, 1);
  return !Iterables.isEmpty(db.command(query).<Iterable<ODocument>>execute(params));
}
 
Example 11
Source File: YangInstanceIdentifier.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
public static @NonNull YangInstanceIdentifier create(final Iterable<? extends PathArgument> path) {
    if (Iterables.isEmpty(path)) {
        return empty();
    }

    final HashCodeBuilder<PathArgument> hash = new HashCodeBuilder<>();
    for (PathArgument a : path) {
        hash.addArgument(a);
    }

    return FixedYangInstanceIdentifier.create(path, hash.build());
}
 
Example 12
Source File: FixupFontDeclarations.java    From closure-stylesheets with Apache License 2.0 5 votes vote down vote up
private CssPropertyValueNode rebuildFont(
    Iterable<CssValueNode> prefix,
    CssValueNode splitPoint,
    Iterable<CssValueNode> families,
    CssPriorityNode priority,
    final Map<CssValueNode, FontProperty> properties,
    CssPropertyValueNode n) {
  TreeMap<FontProperty, CssValueNode> parts =
      Maps.newTreeMap();
  for (Map.Entry<CssValueNode, FontProperty> p : properties.entrySet()) {
    parts.put(p.getValue(), p.getKey());
  }
  List<CssValueNode> preFamily = Lists.newArrayList();
  Iterables.addAll(preFamily, prefix);
  if (parts.containsKey(FontProperty.SIZE)) {
    preFamily.add(parts.get(FontProperty.SIZE));
  }
  if (parts.containsKey(FontProperty.LINE_HEIGHT)) {
    CssValueNode lineHeight = parts.get(FontProperty.LINE_HEIGHT);
    preFamily.add(new CssLiteralNode("/", getSourceCodeLocation(lineHeight)));
    preFamily.add(lineHeight);
  }
  List<CssValueNode> tail =
      Iterables.isEmpty(families)
      ? ImmutableList.<CssValueNode>of()
      : ImmutableList.<CssValueNode>of(reparseFamilies(
          families,
          SourceCodeLocation.merge(families)));
  ImmutableList.Builder<CssValueNode> resultNodes = ImmutableList.builder();
  resultNodes.addAll(Iterables.concat(preFamily, tail));
  if (priority != null) {
    resultNodes.add(priority);
  }
  CssPropertyValueNode result = new CssPropertyValueNode(resultNodes.build());
  return result.deepCopy();
}
 
Example 13
Source File: LeafRefPath.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create a child path based on concatenation of this path and a relative path.
 *
 * @param relative Relative path
 * @return A new child path
 */
public LeafRefPath createChild(final Iterable<QNameWithPredicate> relative) {
    if (Iterables.isEmpty(relative)) {
        return this;
    }

    LeafRefPath newParent = this;
    for (QNameWithPredicate relativeQname : relative) {
        newParent = newParent.createInstance(newParent, relativeQname);
    }

    return newParent;
}
 
Example 14
Source File: CDebugEventNotifier.java    From binnavi with Apache License 2.0 5 votes vote down vote up
private void internalReceivedReply(final AnyBreakpointRemovedReply reply) {
  final Iterable<Pair<RelocatedAddress, Integer>> failedAddresses = Collections2.filter(
      reply.getAddresses(), new Predicate<Pair<RelocatedAddress, Integer>>() {
        @Override
        public boolean apply(final Pair<RelocatedAddress, Integer> item) {
          return item.second().intValue() != 0;
        }
      });
  if (!Iterables.isEmpty(failedAddresses)) {
    CBreakpointRemovalDialog.show(m_parent, failedAddresses);
  }
}
 
Example 15
Source File: GraphBackedRecursivePackageProvider.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public Map<PackageIdentifier, Package> bulkGetPackages(Iterable<PackageIdentifier> pkgIds)
    throws NoSuchPackageException, InterruptedException {
  Set<SkyKey> pkgKeys = ImmutableSet.copyOf(PackageValue.keys(pkgIds));

  ImmutableMap.Builder<PackageIdentifier, Package> pkgResults = ImmutableMap.builder();
  Map<SkyKey, SkyValue> packages = graph.getSuccessfulValues(pkgKeys);
  for (Map.Entry<SkyKey, SkyValue> pkgEntry : packages.entrySet()) {
    PackageIdentifier pkgId = (PackageIdentifier) pkgEntry.getKey().argument();
    PackageValue pkgValue = (PackageValue) pkgEntry.getValue();
    pkgResults.put(pkgId, Preconditions.checkNotNull(pkgValue.getPackage(), pkgId));
  }

  SetView<SkyKey> unknownKeys = Sets.difference(pkgKeys, packages.keySet());
  if (!Iterables.isEmpty(unknownKeys)) {
    logger.atWarning().log(
        "Unable to find %s in the batch lookup of %s. Successfully looked up %s",
        unknownKeys, pkgKeys, packages.keySet());
  }
  for (Map.Entry<SkyKey, Exception> missingOrExceptionEntry :
      graph.getMissingAndExceptions(unknownKeys).entrySet()) {
    PackageIdentifier pkgIdentifier =
        (PackageIdentifier) missingOrExceptionEntry.getKey().argument();
    Exception exception = missingOrExceptionEntry.getValue();
    if (exception == null) {
      // If the package key does not exist in the graph, then it must not correspond to any
      // package, because the SkyQuery environment has already loaded the universe.
      throw new BuildFileNotFoundException(pkgIdentifier, "Package not found");
    }
    Throwables.propagateIfInstanceOf(exception, NoSuchPackageException.class);
    Throwables.propagate(exception);
  }
  return pkgResults.build();
}
 
Example 16
Source File: AbstractPolymorphicScopeProvider.java    From dsl-devkit with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates a new {@link DelegatingScope} with the given elements as delegates.
 *
 * @param id
 *          Human-readable name of the scope, typically used to identify where the scope was created. Useful for debugging.
 * @param parent
 *          parent scope of new scope
 * @param delegates
 *          delegate objects
 * @param type
 *          context type of originating scope
 * @param scopeName
 *          the scope name
 * @param originalResource
 *          the original Resource this scope provider belongs to
 * @return resulting scope
 */
protected IScope newDelegateScope(final String id, final IScope parent, final Iterable<? extends EObject> delegates, final EClass type, final String scopeName, final Resource originalResource) {
  if (delegates == null) {
    return parent;
  }
  final Iterable<? extends EObject> contexts = EObjectUtil.filterProxies(delegates);
  if (Iterables.isEmpty(contexts)) {
    return parent;
  }
  final IContextSupplier func = new IContextSupplier() {
    @Override
    public Iterable<? extends EObject> get() {
      return contexts;
    }
  };
  return new DelegatingScope(id, this, parent, func, type, scopeName, originalResource);
}
 
Example 17
Source File: GithubChangeLogSet.java    From DotCi with MIT License 4 votes vote down vote up
@Override
public boolean isEmptySet() {
    return logEntries == null || Iterables.isEmpty(logEntries);
}
 
Example 18
Source File: FileOffsetMapper.java    From tracecompass with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Generate the callsite from a given binary file and address offset.
 *
 * Due to function inlining, it is possible for one offset to actually have
 * multiple call sites. We will return the most precise one (inner-most) we
 * have available.
 *
 * @param file
 *            The binary file to look at
 * @param buildId
 *            The expected buildId of the binary file (is not verified at
 *            the moment)
 * @param offset
 *            The memory offset in the file
 * @return The corresponding call site
 */
public static @Nullable TmfCallsite getCallsiteFromOffset(File file, @Nullable String buildId, long offset) {
   Iterable<Addr2lineInfo> output = getAddr2lineInfo(file, buildId, offset);
   if (output == null || Iterables.isEmpty(output)) {
       return null;
   }
   Addr2lineInfo info = Iterables.getLast(output);
   String sourceFile = info.fSourceFileName;
   Long sourceLine = info.fSourceLineNumber;

   if (sourceFile == null) {
       /* Not enough information to provide a callsite */
       return null;
   }
   return new TmfCallsite(sourceFile, sourceLine);
}
 
Example 19
Source File: GoCompileStep.java    From buck with Apache License 2.0 4 votes vote down vote up
@Override
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) {
  ArrayList<String> pathStrings = new ArrayList<>();
  for (Path path : srcs) {
    pathStrings.add(path.toString());
  }
  if (pathStrings.size() > 0) {
    ImmutableList.Builder<String> commandBuilder =
        ImmutableList.<String>builder()
            .addAll(compilerCommandPrefix)
            .add("-p", packageName.toString())
            .add("-pack")
            .add("-trimpath", workingDirectory.toString())
            .add("-nolocalimports")
            .addAll(flags)
            .add("-o", output.toString());

    if (asmSymabisPath.isPresent() && !Iterables.isEmpty(asmSrcs)) {
      commandBuilder.add("-symabis", asmSymabisPath.get().toString());
    }

    for (Path dir : includeDirectories) {
      commandBuilder.add("-I", dir.toString());
    }

    for (Map.Entry<Path, Path> entry : importPathMap.entrySet()) {
      commandBuilder.add("-importmap", entry.getKey() + "=" + entry.getValue());
    }

    if (asmHeaderPath.isPresent()) {
      commandBuilder.add("-asmhdr", asmHeaderPath.get().toString());
    }

    if (!allowExternalReferences) {
      // -complete means the package does not use any non Go code, so external functions
      // (e.g. Cgo, asm) aren't allowed.
      commandBuilder.add("-complete");
    }

    commandBuilder.addAll(pathStrings);

    return commandBuilder.build();
  } else {
    LOG.warn("No source files found in " + workingDirectory);
    return ImmutableList.of();
  }
}
 
Example 20
Source File: CatalogImpl.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public boolean containerExists(NamespaceKey path) {
  final SchemaType type = getType(path, false);
  if(type == SchemaType.UNKNOWN) {
    return false;
  }

  try {
    List<NameSpaceContainer> containers = userNamespaceService.getEntities(ImmutableList.of(path));
    NameSpaceContainer c = containers.get(0);
    if(c != null &&
      (
        (c.getType() == NameSpaceContainer.Type.FOLDER && type != SchemaType.SOURCE) // DX-10186. Bad behavior in tryCreatePhysicalDataset causes problems with extra phantom folders.
          || c.getType() == NameSpaceContainer.Type.HOME
          || c.getType() == NameSpaceContainer.Type.SPACE
          || c.getType() == NameSpaceContainer.Type.SOURCE)) {
      return true;
    }

    if(type != SchemaType.SOURCE) {
      return false;
    }

    // For some sources, some folders aren't automatically existing in namespace, let's be more invasive...

    // let's check for a dataset in this path. We're looking for a dataset who either has this path as the schema of it or has a schema that starts with this path.
    if(!Iterables.isEmpty(userNamespaceService.find(new LegacyFindByCondition().setCondition(
      SearchQueryUtils.and(
        SearchQueryUtils.newTermQuery(NamespaceIndexKeys.ENTITY_TYPE.getIndexFieldName(), NameSpaceContainer.Type.DATASET.getNumber()),
        SearchQueryUtils.or(
          SearchQueryUtils.newTermQuery(DatasetIndexKeys.UNQUOTED_LC_SCHEMA, path.asLowerCase().toUnescapedString()),
          SearchQueryUtils.newPrefixQuery(DatasetIndexKeys.UNQUOTED_LC_SCHEMA.getIndexFieldName(),
            path.asLowerCase().toUnescapedString() + ".")
        )
      )
    )))) {
      return true;
    }

    // could be a filesystem, let's check the source directly (most expensive).
    ManagedStoragePlugin plugin = pluginRetriever.getPlugin(path.getRoot(), false);
    if(plugin == null) {
      // possible race condition where this plugin is no longer still registered.
      return false;
    }

    return plugin.unwrap(StoragePlugin.class).containerExists(new EntityPath(path.getPathComponents()));
  } catch(NamespaceException ex) {
    return false;
  }
}