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

The following examples show how to use com.google.common.collect.Sets.SetView#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: LocalDevice.java    From daq with Apache License 2.0 6 votes vote down vote up
public void validatedDeviceDir() {
  try {
    String[] files = deviceDir.list();
    Preconditions.checkNotNull(files, "No files found in " + deviceDir.getAbsolutePath());
    Set<String> actualFiles = ImmutableSet.copyOf(files);
    Set<String> expectedFiles = Sets.union(DEVICE_FILES, keyFiles());
    SetView<String> missing = Sets.difference(expectedFiles, actualFiles);
    if (!missing.isEmpty()) {
      throw new RuntimeException("Missing files: " + missing);
    }
    SetView<String> extra = Sets.difference(Sets.difference(actualFiles, expectedFiles), OPTIONAL_FILES);
    if (!extra.isEmpty()) {
      throw new RuntimeException("Extra files: " + extra);
    }
  } catch (Exception e) {
    throw new RuntimeException("While validating device directory " + deviceId, e);
  }
}
 
Example 2
Source File: TileUpgrade.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
private boolean checkTrackConnectivity(Set<TrackPoint> baseTrack, Set<TrackPoint> targetTrack) {
    SetView<TrackPoint> diffTrack = Sets.difference(baseTrack, targetTrack);
    if (diffTrack.isEmpty()) {
        // target maintains connectivity
        return true;
    } else {
        // if not all connections are maintained,
        Predicate<TrackPoint> checkForStation = new Predicate<TrackPoint>() {
            public boolean apply(TrackPoint p) {
                return (p.getTrackPointType() == TrackPoint.Type.SIDE);
            }
        };
        // check if remaining tracks only lead to other stations
        if (Sets.filter(diffTrack, checkForStation).isEmpty()) {
            return true;
        }
    }
    return false;
}
 
Example 3
Source File: NamespacesBase.java    From pulsar with Apache License 2.0 6 votes vote down vote up
/**
 * It validates that peer-clusters can't coexist in replication-clusters
 *
 * @param clusterName:
 *            given cluster whose peer-clusters can't be present into replication-cluster list
 * @param replicationClusters:
 *            replication-cluster list
 */
private void validatePeerClusterConflict(String clusterName, Set<String> replicationClusters) {
    try {
        ClusterData clusterData = clustersCache().get(path("clusters", clusterName)).orElseThrow(
                () -> new RestException(Status.PRECONDITION_FAILED, "Invalid replication cluster " + clusterName));
        Set<String> peerClusters = clusterData.getPeerClusterNames();
        if (peerClusters != null && !peerClusters.isEmpty()) {
            SetView<String> conflictPeerClusters = Sets.intersection(peerClusters, replicationClusters);
            if (!conflictPeerClusters.isEmpty()) {
                log.warn("[{}] {}'s peer cluster can't be part of replication clusters {}", clientAppId(),
                        clusterName, conflictPeerClusters);
                throw new RestException(Status.CONFLICT,
                        String.format("%s's peer-clusters %s can't be part of replication-clusters %s", clusterName,
                                conflictPeerClusters, replicationClusters));
            }
        }
    } catch (RestException re) {
        throw re;
    } catch (Exception e) {
        log.warn("[{}] Failed to get cluster-data for {}", clientAppId(), clusterName, e);
    }
}
 
Example 4
Source File: PostgreSQLNotificationProvider.java    From binnavi with Apache License 2.0 6 votes vote down vote up
private void syncListenedChannels() {
  if (m_channels.equals(m_currentListenedChannels)) {
    return;
  }

  final Set<NotificationChannel> channels = Sets.newHashSet(m_channels);
  final SetView<NotificationChannel> toUnlisten =
      Sets.difference(m_currentListenedChannels, channels);
  final SetView<NotificationChannel> toListen =
      Sets.difference(channels, m_currentListenedChannels);

  if (!toUnlisten.isEmpty()) {
    sendUnlistens(toUnlisten);
  }
  if (!toListen.isEmpty()) {
    sendListens(toListen);
  }
  if (!toUnlisten.isEmpty() || !toListen.isEmpty()) {
    m_currentListenedChannels.clear();
    m_currentListenedChannels.addAll(channels);
  }
}
 
Example 5
Source File: CreateOrganization.java    From passopolis-server with GNU General Public License v3.0 6 votes vote down vote up
/** Returns an error message if request is not valid. Checks basic request formatting. */
static String validateRequest(RPC.CreateOrganizationRequest request) {
  if (Strings.isNullOrEmpty(request.name)) {
    return "name cannot be empty";
  }
  if (Strings.isNullOrEmpty(request.publicKey)) {
    return "publicKey cannot be empty";
  }
  if (request.adminEncryptedKeys == null || request.adminEncryptedKeys.isEmpty()) {
    return "adminEncryptedKeys cannot be empty";
  }
  if (request.memberGroupKeys == null || request.memberGroupKeys.isEmpty()) {
    return "memberGroupKeys cannot be empty";
  }

  // ensure that every admin is also a member
  SetView<String> adminsNotInMembers = Sets.difference(
      request.adminEncryptedKeys.keySet(), request.memberGroupKeys.keySet());
  if (!adminsNotInMembers.isEmpty()) {
    return "each admin must be a member";
  }
  return null;
}
 
Example 6
Source File: ObserversV2.java    From fluo with Apache License 2.0 6 votes vote down vote up
public ObserversV2(Environment env, JsonObservers jco, Set<Column> strongColumns,
    Set<Column> weakColumns) {

  ObserverProvider obsProvider =
      ObserverStoreV2.newObserverProvider(jco.getObserverProviderClass());

  ObserverProviderContextImpl ctx = new ObserverProviderContextImpl(env);

  ObserverRegistry or = new ObserverRegistry(strongColumns, weakColumns);
  obsProvider.provide(or, ctx);

  this.observers = or.observers;
  this.aliases = or.aliases;
  this.observers.forEach((k, v) -> aliases.computeIfAbsent(k, col -> Hex.encNonAscii(col, ":")));

  // the following check ensures observers are provided for all previously configured columns
  SetView<Column> diff =
      Sets.difference(observers.keySet(), Sets.union(strongColumns, weakColumns));
  if (!diff.isEmpty()) {
    throw new FluoException("ObserverProvider " + jco.getObserverProviderClass()
        + " did not provide observers for columns " + diff);
  }
}
 
Example 7
Source File: DatabaseService.java    From das with Apache License 2.0 5 votes vote down vote up
public ServiceResult isExist(List<String> db_names) throws SQLException {
    List<String> list = dataBaseDao.getAllDbAllinOneNames();
    Set<String> set1 = list.stream().map(i -> i.toLowerCase()).collect(Collectors.toSet());
    Set<String> set2 = db_names.stream().map(i -> i.toLowerCase()).collect(Collectors.toSet());
    SetView<String> intersection = Sets.intersection(set1, set2);
    if (!intersection.isEmpty()) {
        return ServiceResult.success(intersection);
    }
    return ServiceResult.fail(set2);
}
 
Example 8
Source File: BundleConfigValidator.java    From bundletool with Apache License 2.0 5 votes vote down vote up
private void validateMasterResources(BundleConfig bundleConfig, AppBundle bundle) {
  ImmutableSet<Integer> resourcesToBePinned =
      ImmutableSet.copyOf(bundleConfig.getMasterResources().getResourceIdsList());
  if (resourcesToBePinned.isEmpty()) {
    return;
  }

  ImmutableSet<Integer> allResourceIds =
      bundle.getFeatureModules().values().stream()
          .map(BundleModule::getResourceTable)
          .filter(Optional::isPresent)
          .map(Optional::get)
          .flatMap(resourceTable -> ResourcesUtils.entries(resourceTable))
          .map(ResourceTableEntry::getResourceId)
          .map(ResourceId::getFullResourceId)
          .collect(toImmutableSet());

  SetView<Integer> undefinedResources = Sets.difference(resourcesToBePinned, allResourceIds);

  if (!undefinedResources.isEmpty()) {
    throw InvalidBundleException.builder()
        .withUserMessage(
            "Error in BundleConfig. The Master Resources list contains resource IDs not defined "
                + "in any module. For example: 0x%08x",
            undefinedResources.iterator().next())
        .build();
  }
}
 
Example 9
Source File: TextureCompressionFormatMatcher.java    From bundletool with Apache License 2.0 5 votes vote down vote up
@Override
protected void checkDeviceCompatibleInternal(TextureCompressionFormatTargeting targeting) {
  // If there is no targeting, by definition the device is compatible with it.
  if (targeting.equals(TextureCompressionFormatTargeting.getDefaultInstance())) {
    return;
  }

  // If no value is specified but alternative TCFs exist, it means we're inspecting a
  // fallback for other TCFs. By definition of a fallback, the device is compatible with it.
  boolean isFallback =
      targeting.getValueList().isEmpty() && !targeting.getAlternativesList().isEmpty();
  if (isFallback) {
    return;
  }

  ImmutableSet<TextureCompressionFormatAlias> valuesAndAlternativesSet =
      Streams.concat(
              targeting.getValueList().stream().map(TextureCompressionFormat::getAlias),
              targeting.getAlternativesList().stream().map(TextureCompressionFormat::getAlias))
          .collect(toImmutableSet());

  SetView<TextureCompressionFormatAlias> intersection =
      Sets.intersection(valuesAndAlternativesSet, this.deviceSupportedTextureCompressionFormats);

  if (intersection.isEmpty()) {
    throw IncompatibleDeviceException.builder()
        .withUserMessage(
            "The app doesn't support texture compression formats of the device. "
                + "Device formats: %s, app formats: %s.",
            this.deviceSupportedTextureCompressionFormats, valuesAndAlternativesSet)
        .build();
  }
}
 
Example 10
Source File: AbiMatcher.java    From bundletool with Apache License 2.0 5 votes vote down vote up
@Override
protected void checkDeviceCompatibleInternal(AbiTargeting targeting) {
  if (targeting.equals(AbiTargeting.getDefaultInstance())) {
    return;
  }

  ImmutableSet<String> valuesAndAlternativesSet =
      Streams.concat(
              targeting.getValueList().stream()
                  .map(Abi::getAlias)
                  .map(AbiName::fromProto)
                  .map(AbiName::getPlatformName),
              targeting.getAlternativesList().stream()
                  .map(Abi::getAlias)
                  .map(AbiName::fromProto)
                  .map(AbiName::getPlatformName))
          .collect(toImmutableSet());

  ImmutableSet<String> deviceAbis =
      getDeviceSpec().getSupportedAbisList().stream().collect(toImmutableSet());

  SetView<String> intersection = Sets.intersection(valuesAndAlternativesSet, deviceAbis);

  if (intersection.isEmpty()) {
    throw IncompatibleDeviceException.builder()
        .withUserMessage(
            "The app doesn't support ABI architectures of the device. "
                + "Device ABIs: %s, app ABIs: %s.",
            getDeviceSpec().getSupportedAbisList(), valuesAndAlternativesSet)
        .build();
  }
}
 
Example 11
Source File: TileUpgrade.java    From Rails with GNU General Public License v2.0 5 votes vote down vote up
private Rotation processRotations(HexSide side) {

        TrackConfig base = baseTile.getTrackConfig();
        TrackConfig target = targetTile.getTrackConfig();
        // create rotation of target, unless default (= 0) rotation
        if (side != HexSide.get(0)) {
            target = TrackConfig.createByRotation(target, side);
        }
        // check if there are stations to map
        Map<Station, Station> stationMapping = assignStations(base, target);
        if (stationMapping != null && !stationMapping.isEmpty()) {
            if (stationMapping.containsValue(null)) {
                base = TrackConfig.createByDowngrade(base, base.getTile().getStation(1));
            }
            base = TrackConfig.createByStationMapping(base, stationMapping);
        }

        // and finally check if all tracks are maintained
        Set<Track> baseTracks = base.getTracks();
        Set<Track> targetTracks = target.getTracks();
        SetView<Track> diffTrack = Sets.difference(baseTracks, targetTracks);
        if (diffTrack.isEmpty()) {
            SetView<Track> newTracks = Sets.difference(targetTracks, baseTracks);
            boolean allowed = (targetTile.getPossibleRotations().get(side));
            Rotation rotObject = new Rotation(targetTracks, newTracks, side, stationMapping, allowed);
            log.trace("New Rotation for {} => {}: \n{}", baseTile, targetTile, rotObject);
            return rotObject;
        } else {
            log.trace("No Rotation found {} => {}, rotation ={}, remaining Tracks = {}", baseTile, targetTile, side, diffTrack);
            return null;
        }
    }
 
Example 12
Source File: JavaPerformanceDetector.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check whether the given invocation is done as a lazy initialization,
 * e.g. {@code if (foo == null) foo = new Foo();}.
 * <p>
 * This tries to also handle the scenario where the check is on some
 * <b>other</b> variable - e.g.
 * <pre>
 *    if (foo == null) {
 *        foo == init1();
 *        bar = new Bar();
 *    }
 * </pre>
 * or
 * <pre>
 *    if (!initialized) {
 *        initialized = true;
 *        bar = new Bar();
 *    }
 * </pre>
 */
private static boolean isLazilyInitialized(Node node) {
    Node curr = node.getParent();
    while (curr != null) {
        if (curr instanceof MethodDeclaration) {
            return false;
        } else if (curr instanceof If) {
            If ifNode = (If) curr;
            // See if the if block represents a lazy initialization:
            // compute all variable names seen in the condition
            // (e.g. for "if (foo == null || bar != foo)" the result is "foo,bar"),
            // and then compute all variables assigned to in the if body,
            // and if there is an overlap, we'll consider the whole if block
            // guarded (so lazily initialized and an allocation we won't complain
            // about.)
            List<String> assignments = new ArrayList<String>();
            AssignmentTracker visitor = new AssignmentTracker(assignments);
            ifNode.astStatement().accept(visitor);
            if (!assignments.isEmpty()) {
                List<String> references = new ArrayList<String>();
                addReferencedVariables(references, ifNode.astCondition());
                if (!references.isEmpty()) {
                    SetView<String> intersection = Sets.intersection(
                            new HashSet<String>(assignments),
                            new HashSet<String>(references));
                    return !intersection.isEmpty();
                }
            }
            return false;

        }
        curr = curr.getParent();
    }

    return false;
}
 
Example 13
Source File: WorkspaceRuntimes.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Inject
public WorkspaceRuntimes(
    EventService eventService,
    Map<String, InternalEnvironmentFactory> envFactories,
    RuntimeInfrastructure infra,
    WorkspaceSharedPool sharedPool,
    WorkspaceDao workspaceDao,
    @SuppressWarnings("unused") DBInitializer ignored,
    ProbeScheduler probeScheduler,
    WorkspaceStatusCache statuses,
    WorkspaceLockService lockService,
    DevfileConverter devfileConverter) {
  this.probeScheduler = probeScheduler;
  this.runtimes = new ConcurrentHashMap<>();
  this.statuses = statuses;
  this.eventService = eventService;
  this.sharedPool = sharedPool;
  this.workspaceDao = workspaceDao;
  this.isStartRefused = new AtomicBoolean(false);
  this.infrastructure = infra;
  this.environmentFactories = ImmutableMap.copyOf(envFactories);
  this.lockService = lockService;
  this.devfileConverter = devfileConverter;
  LOG.info("Configured factories for environments: '{}'", envFactories.keySet());
  LOG.info("Registered infrastructure '{}'", infra.getName());
  SetView<String> notSupportedByInfra =
      Sets.difference(envFactories.keySet(), infra.getRecipeTypes());
  if (!notSupportedByInfra.isEmpty()) {
    LOG.warn(
        "Configured environment(s) are not supported by infrastructure: '{}'",
        notSupportedByInfra);
  }
  workspaceRuntimesId = NameGenerator.generate("runtimes", 16);
}
 
Example 14
Source File: JcloudsTypeCoercions.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Maybe<T> tryCoerce(Object input, TypeToken<T> targetTypeToken) {
    Class<? super T> targetType = targetTypeToken.getRawType();
    Maybe<?> result = null;
    Maybe<?> firstError = null;

    // If we don't have a map of named params, we can't map it to "@SerializedNames"?
    if (!(input instanceof Map)) {
        return null;
    }

    Optional<Method> method = findCreateMethod(targetType);
    if (!method.isPresent()) return null;
    
    // Do we have a map of args, and need to look at the "@SerializedNames" annotation?
    if (method.get().isAnnotationPresent(SerializedNames.class)) {
        String[] argNames = method.get().getAnnotation(SerializedNames.class).value();
        
        SetView<?> extraArgs = Sets.difference(((Map<?,?>)input).keySet(), ImmutableSet.copyOf(argNames));
        if (!extraArgs.isEmpty()) {
            return Maybe.absent("create() for "+targetType.getCanonicalName()+" does not accept extra args "+extraArgs);
        }
        
        List<Object> orderedArgs = Lists.newArrayList();
        for (String argName : argNames) {
            orderedArgs.add(((Map<?,?>)input).get(argName));
        }
        result = MethodCoercions.tryFindAndInvokeMultiParameterMethod(targetType, ImmutableList.of(method.get()), orderedArgs);
        if (result != null && result.isPresent()) return Maybe.of((T)result.get());
        if (result != null && firstError == null) firstError = result;
    }
    
    //not found
    if (firstError != null) return (Maybe<T>) (Maybe) firstError;
    return null;
}
 
Example 15
Source File: NativeTargetingValidator.java    From bundletool with Apache License 2.0 4 votes vote down vote up
private static void validateTargeting(BundleModule module, NativeLibraries nativeLibraries) {
  for (TargetedNativeDirectory targetedDirectory : nativeLibraries.getDirectoryList()) {
    ZipPath path = ZipPath.create(targetedDirectory.getPath());
    NativeDirectoryTargeting targeting = targetedDirectory.getTargeting();

    if (!targeting.hasAbi()) {
      throw InvalidBundleException.builder()
          .withUserMessage(
              "Targeted native directory '%s' does not have the ABI dimension set.",
              targetedDirectory.getPath())
          .build();
    }

    if (!path.startsWith(LIB_DIRECTORY) || path.getNameCount() != 2) {
      throw InvalidBundleException.builder()
          .withUserMessage(
              "Path of targeted native directory must be in format 'lib/<directory>' but "
                  + "found '%s'.",
              path)
          .build();
    }

    if (BundleValidationUtils.directoryContainsNoFiles(module, path)) {
      throw InvalidBundleException.builder()
          .withUserMessage("Targeted directory '%s' is empty.", path)
          .build();
    }
  }

  SetView<String> libDirsWithoutTargeting =
      Sets.difference(
          module
              .findEntriesUnderPath(LIB_DIRECTORY)
              .map(libFile -> libFile.getPath().subpath(0, 2).toString())
              .collect(toImmutableSet()),
          nativeLibraries.getDirectoryList().stream()
              .map(TargetedNativeDirectory::getPath)
              .collect(toImmutableSet()));
  if (!libDirsWithoutTargeting.isEmpty()) {
    throw InvalidBundleException.builder()
        .withUserMessage(
            "Following native directories are not targeted: %s", libDirsWithoutTargeting)
        .build();
  }
}
 
Example 16
Source File: HighVolumeReadWriteIncludedDocumentsCollection.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 4 votes vote down vote up
@Override
public OrderedDocumentsList getDocumentsByIds(@NonNull final DocumentIdsSelection documentIds)
{
	if (documentIds.isAll())
	{
		return getDocuments(DocumentQueryOrderByList.EMPTY);
	}
	else if (documentIds.isEmpty())
	{
		return OrderedDocumentsList.newEmpty();
	}
	else
	{
		final Map<DocumentId, Document> documentsWithChanges = new LinkedHashMap<>(getInnerDocumentsWithChanges());
		final SetView<DocumentId> documentIdsToLoad = Sets.difference(documentIds.toSet(), documentsWithChanges.keySet());

		final ImmutableMap<DocumentId, Document> loadedDocuments;
		if (!documentIdsToLoad.isEmpty())
		{
			loadedDocuments = DocumentQuery.builder(entityDescriptor)
					.setParentDocument(parentDocument)
					.setRecordIds(documentIdsToLoad)
					.setChangesCollector(NullDocumentChangesCollector.instance)
					.setOrderBys(DocumentQueryOrderByList.EMPTY)
					.retriveDocuments()
					.toImmutableMap();
		}
		else
		{
			loadedDocuments = ImmutableMap.of();
		}

		final OrderedDocumentsList result = OrderedDocumentsList.newEmpty();
		for (final DocumentId documentId : documentIds.toSet())
		{
			final Document documentWithChanges = documentsWithChanges.get(documentId);
			if (documentWithChanges != null)
			{
				result.addDocument(documentWithChanges);
				continue;
			}

			final Document loadedDocument = loadedDocuments.get(documentId);
			if (loadedDocument != null)
			{
				result.addDocument(loadedDocument);
				continue;
			}

			// No document found for documentId. Ignore it.
		}

		return result;
	}
}