com.google.common.collect.Sets.SetView Java Examples

The following examples show how to use com.google.common.collect.Sets.SetView. 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 Project: presto   Author: prestosql   File: BroadcastOutputBuffer.java    License: Apache License 2.0 6 votes vote down vote up
private void noMoreBuffers()
{
    checkState(!Thread.holdsLock(this), "Cannot set no more buffers while holding a lock on this");
    List<SerializedPageReference> pages;
    synchronized (this) {
        pages = ImmutableList.copyOf(initialPagesForNewBuffers);
        initialPagesForNewBuffers.clear();

        if (outputBuffers.isNoMoreBufferIds()) {
            // verify all created buffers have been declared
            SetView<OutputBufferId> undeclaredCreatedBuffers = Sets.difference(buffers.keySet(), outputBuffers.getBuffers().keySet());
            checkState(undeclaredCreatedBuffers.isEmpty(), "Final output buffers does not contain all created buffer ids: %s", undeclaredCreatedBuffers);
        }
    }

    // dereference outside of synchronized to avoid making a callback while holding a lock
    pages.forEach(SerializedPageReference::dereferencePage);
}
 
Example #2
Source Project: singer   Author: pinterest   File: KubeService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Clear the set of Pod Names and update it with the latest fetch from kubelet
 * 
 * Following a listener design, currently we only have 1 listener but in future
 * if we want to do something else as well when these events happen then this
 * might come in handy.
 * 
 * @throws IOException
 */
public void updatePodNames() throws IOException {
    LOG.debug("Active podset:" + activePodSet);
    Set<String> updatedPodNames = fetchPodNamesFromMetadata();
    SetView<String> deletedNames = Sets.difference(activePodSet, updatedPodNames);

    // ignore new pods, pod discovery is done by watching directories

    for (String podName : deletedNames) {
        updatePodWatchers(podName, true);
        // update metrics since pods have been deleted
        Stats.incr(SingerMetrics.PODS_DELETED);
        Stats.incr(SingerMetrics.NUMBER_OF_PODS, -1);
    }
    LOG.debug("Fired events for registered watchers");

    activePodSet.clear();
    activePodSet.addAll(updatedPodNames);
    LOG.debug("Cleared and updated pod names:" + activePodSet);
}
 
Example #3
Source Project: sofa-registry   Author: sofastack   File: SessionRegistry.java    License: Apache License 2.0 6 votes vote down vote up
public void cleanClientConnect() {

        SetView<String> intersection = Sets.union(sessionDataStore.getConnectPublishers().keySet(),
            sessionInterests.getConnectSubscribers().keySet());

        Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort());

        List<String> connectIds = new ArrayList<>();
        for (String connectId : intersection) {
            Channel channel = sessionServer.getChannel(URL.valueOf(connectId));
            if (channel == null) {
                connectIds.add(connectId);
                LOGGER.warn("Client connect has not existed!it must be remove!connectId:{}",
                    connectId);
            }
        }
        if (!connectIds.isEmpty()) {
            cancel(connectIds);
        }
    }
 
Example #4
Source Project: daq   Author: faucetsdn   File: LocalDevice.java    License: 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 #5
Source Project: Rails   Author: Rails-18xx   File: TileUpgrade.java    License: 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 #6
Source Project: apollo   Author: ctripcorp   File: AccessKeyServiceWithCache.java    License: Apache License 2.0 6 votes vote down vote up
private void deleteAccessKeyCache() {
  List<Long> ids = Lists.newArrayList(accessKeyIdCache.keySet());
  if (CollectionUtils.isEmpty(ids)) {
    return;
  }

  List<List<Long>> partitionIds = Lists.partition(ids, 500);
  for (List<Long> toRebuildIds : partitionIds) {
    Iterable<AccessKey> accessKeys = accessKeyRepository.findAllById(toRebuildIds);

    Set<Long> foundIds = Sets.newHashSet();
    for (AccessKey accessKey : accessKeys) {
      foundIds.add(accessKey.getId());
    }

    //handle deleted
    SetView<Long> deletedIds = Sets.difference(Sets.newHashSet(toRebuildIds), foundIds);
    handleDeletedAccessKeys(deletedIds);
  }
}
 
Example #7
Source Project: pulsar   Author: apache   File: NamespacesBase.java    License: 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 #8
Source Project: nomulus   Author: google   File: ToolsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_commandMap_includesAllCommands() throws Exception {
  ImmutableSet<?> registryToolCommands = ImmutableSet.copyOf(RegistryTool.COMMAND_MAP.values());
  ImmutableSet<?> devToolCommands = ImmutableSet.copyOf(DevTool.COMMAND_MAP.values());
  assertWithMessage("RegistryTool and DevTool have overlapping commands")
      .that(Sets.intersection(registryToolCommands, devToolCommands))
      .isEmpty();
  SetView<?> allCommandsInTools = Sets.union(registryToolCommands, devToolCommands);
  ImmutableSet<?> classLoaderClasses = getAllCommandClasses();
  // Not using plain old containsExactlyElementsIn() since it produces a huge unreadable blob.
  assertWithMessage("command classes in COMMAND_MAP but not found by class loader")
      .that(Sets.difference(allCommandsInTools, classLoaderClasses))
      .isEmpty();
  assertWithMessage("command classes found by class loader but not in COMMAND_MAP")
      .that(Sets.difference(classLoaderClasses, allCommandsInTools))
      .isEmpty();
}
 
Example #9
Source Project: binnavi   Author: google   File: PostgreSQLNotificationProvider.java    License: 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 #10
Source Project: onboard   Author: sercxtyf   File: UserServiceImplTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @author 胡天翔
 */
@Test
public void testFilterProjectMembers() {
    List<User> list1 = new ArrayList<User>(), list2 = new ArrayList<User>();
    list1.add(getASampleUser(0));
    list1.add(getASampleUser(1));
    list1.add(getASampleUser(2));
    list2.add(getASampleUser(1));
    list2.add(getASampleUser(2));
    list2.add(getASampleUser(3));
    SetView<User> intersection = Sets.intersection(new HashSet<User>(list1), new HashSet<User>(list2));
    
    UserServiceImpl spyUserServiceImpl = Mockito.spy(testedUserServiceImpl);
    Mockito.doReturn(list2).when(spyUserServiceImpl).getUserByProjectId(ModuleHelper.projectId);
    
    List<User> user = spyUserServiceImpl.filterProjectMembers(list1, ModuleHelper.projectId);
    
    Mockito.verify(spyUserServiceImpl).filterProjectMembers(list1, ModuleHelper.projectId);
    Mockito.verify(spyUserServiceImpl).getUserByProjectId(ModuleHelper.projectId);
    Mockito.verifyNoMoreInteractions(spyUserServiceImpl);
    
    assertEquals(intersection.size(), Sets.intersection(intersection, new HashSet<User>(user)).size());
}
 
Example #11
Source Project: passopolis-server   Author: WeAreWizards   File: CreateOrganization.java    License: 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 #12
Source Project: fluo   Author: apache   File: ObserversV2.java    License: 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 #13
Source Project: denominator   Author: Netflix   File: GeoResourceRecordSetCommands.java    License: Apache License 2.0 6 votes vote down vote up
static void validateRegions(Map<String, Collection<String>> regionsToAdd,
                            Map<String, Collection<String>> supportedRegions) {
  MapDifference<String, Collection<String>>
      comparison =
      Maps.difference(regionsToAdd, supportedRegions);
  checkArgument(comparison.entriesOnlyOnLeft().isEmpty(), "unsupported regions: %s", comparison
      .entriesOnlyOnLeft().keySet());
  for (Entry<String, Collection<String>> entry : regionsToAdd.entrySet()) {
    ImmutableSet<String> toAdd = ImmutableSet.copyOf(entry.getValue());
    SetView<String> intersection = Sets.intersection(toAdd,
                                                     ImmutableSet.copyOf(
                                                         supportedRegions.get(entry.getKey())));
    SetView<String> unsupported = Sets.difference(toAdd, intersection);
    checkArgument(unsupported.isEmpty(), "unsupported territories in %s:", entry.getKey(),
                  unsupported);
  }
}
 
Example #14
Source Project: das   Author: ppdaicorp   File: DatabaseService.java    License: 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 #15
Source Project: presto   Author: prestosql   File: ArbitraryOutputBuffer.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void noMoreBuffers()
{
    if (outputBuffers.isNoMoreBufferIds()) {
        // verify all created buffers have been declared
        SetView<OutputBufferId> undeclaredCreatedBuffers = Sets.difference(buffers.keySet(), outputBuffers.getBuffers().keySet());
        checkState(undeclaredCreatedBuffers.isEmpty(), "Final output buffers does not contain all created buffer ids: %s", undeclaredCreatedBuffers);
    }
}
 
Example #16
Source Project: google-ads-java   Author: googleads   File: MethodsPresenceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Verifies that the list of all service client methods in a given GoogleAdsVersion class matches
 * that provided in the testdata/avail_service_clients.txt file.
 *
 * <p>The avail_service_clients.txt file should be the standard against which all releases are
 * compared. In the event the list of services changes in the API, this test will fail. Then,
 * avail_service_clients.txt should be updated so that this test passes.
 */
@Test
public void methodsListMatches()
    throws ClassNotFoundException, NoSuchMethodException, IOException {
  // Gets the fully qualified return type of the GoogleAdsAllVersions getLatestVersion method,
  // which is the class from which the methods will be retrieved.
  Method latestVersionMethod = GoogleAdsAllVersions.class.getMethod("getLatestVersion");
  Class cls = Class.forName(latestVersionMethod.getReturnType().getName());

  // Retrieves a list of the methods in the GoogleAdsVersion class using reflection and adds
  // each to a set.
  List<Method> methods = Arrays.asList(cls.getDeclaredMethods());
  Set<String> serviceListReflection = new HashSet<>();
  for (Method method : methods) {
    serviceListReflection.add(method.toString());
  }

  // Retrieves the list of service client methods in the provided avail_service_clients.txt file.
  URL resource = Resources.getResource(CONFIG_FILE_RESOURCE_PATH);
  Set<String> serviceListResource =
      new HashSet<>(Resources.asCharSource(resource, Charsets.UTF_8).readLines());

  SetView<String> newlyAdded = Sets.difference(serviceListReflection, serviceListResource);
  SetView<String> newlyRemoved = Sets.difference(serviceListResource, serviceListReflection);

  assertEquals(
      "Service clients have been newly added: "
          + newlyAdded
          + " Please verify this is expected and update "
          + CONFIG_FILE_RESOURCE_PATH,
      Collections.emptySet(),
      newlyAdded);
  assertEquals(
      "Service clients have been newly removed: "
          + newlyRemoved
          + " Please verify this is expected and update "
          + CONFIG_FILE_RESOURCE_PATH,
      Collections.emptySet(),
      newlyRemoved);
}
 
Example #17
Source Project: bundletool   Author: google   File: BundleConfigValidator.java    License: 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 #18
Source Project: bundletool   Author: google   File: TextureCompressionFormatMatcher.java    License: 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 #19
Source Project: bundletool   Author: google   File: AbiMatcher.java    License: 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 #20
Source Project: Rails   Author: Rails-18xx   File: TileUpgrade.java    License: 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 #21
Source Project: javaide   Author: tranleduy2000   File: JavaPerformanceDetector.java    License: 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 #22
Source Project: google-cloud-eclipse   Author: GoogleCloudPlatform   File: LaunchHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Look for servers that may match.
 * 
 * @param modules the web modules to search for
 * @param exact if true, look for exact module match
 * @return an existing server
 */
@VisibleForTesting
Collection<IServer> findExistingServers(IModule[] modules, boolean exact,
    SubMonitor progress) {
  if (modules.length == 1) {
    IServer defaultServer = ServerCore.getDefaultServer(modules[0]);
    if (defaultServer != null && defaultServer.getServerType() != null
        && LocalAppEngineServerDelegate.SERVER_TYPE_ID
            .equals(defaultServer.getServerType().getId())) {
      return Collections.singletonList(defaultServer);
    }
  }
  Set<IModule> myModules = ImmutableSet.copyOf(modules);
  List<IServer> matches = new ArrayList<>();
  // Look for servers that contain these modules
  // Could prioritize servers that have *exactly* these modules,
  // or that have the smallest overlap
  for (IServer server : ServerCore.getServers()) {
    // obsolete or unavailable server definitions have serverType == null
    if (server.getServerType() == null
        || !LocalAppEngineServerDelegate.SERVER_TYPE_ID.equals(server.getServerType().getId())) {
      continue;
    }
    Set<IModule> serverModules = ImmutableSet.copyOf(server.getModules());
    SetView<IModule> overlap = Sets.intersection(myModules, serverModules);
    if (overlap.size() == myModules.size()
        && (!exact || overlap.size() == serverModules.size())) {
      matches.add(server);
    }
  }
  return matches;
}
 
Example #23
Source Project: nomulus   Author: google   File: SqlIntegrationMembershipTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Ignore
public void sqlIntegrationMembershipComplete() {
  ImmutableSet<String> sqlDependentTests;
  try (ScanResult scanResult =
      new ClassGraph().enableAnnotationInfo().whitelistPackages("google.registry").scan()) {
    sqlDependentTests =
        scanResult.getClassesWithAnnotation(RunWith.class.getName()).stream()
            .filter(clazz -> clazz.getSimpleName().endsWith("Test"))
            .map(clazz -> clazz.loadClass())
            .filter(SqlIntegrationMembershipTest::isSqlDependent)
            .map(Class::getName)
            .collect(ImmutableSet.toImmutableSet());
  }
  ImmutableSet<String> declaredTests =
      Stream.of(SqlIntegrationTestSuite.class.getAnnotation(SuiteClasses.class).value())
          .map(Class::getName)
          .collect(ImmutableSet.toImmutableSet());
  SetView<String> undeclaredTests = Sets.difference(sqlDependentTests, declaredTests);
  expect
      .withMessage(
          "Undeclared sql-dependent tests found. "
              + "Please add them to SqlIntegrationTestSuite.java.")
      .that(undeclaredTests)
      .isEmpty();
  SetView<String> unnecessaryDeclarations = Sets.difference(declaredTests, sqlDependentTests);
  expect
      .withMessage("Found tests that should not be included in SqlIntegrationTestSuite.java.")
      .that(unnecessaryDeclarations)
      .isEmpty();
}
 
Example #24
Source Project: binnavi   Author: google   File: BreakpointManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This function enforces the type hierarchy of breakpoints.
 *
 * @param addresses The set of addresses for the breakpoints to be added.
 * @param type The type of the breakpoints to be added.
 *
 * @return The Set of breakpoints which has been set.
 */
private Set<BreakpointAddress> enforceBreakpointHierarchy(
    final Set<BreakpointAddress> addresses, final BreakpointType type) {
  final SetView<BreakpointAddress> alreadyRegularBreakpoints =
      Sets.intersection(addresses, indexedBreakpointStorage.getBreakPointAddresses());
  final SetView<BreakpointAddress> alreadySteppingBreakpoints =
      Sets.intersection(addresses, stepBreakpointStorage.getBreakPointAddresses());
  final SetView<BreakpointAddress> alreadyEchoBreakpoints =
      Sets.intersection(addresses, echoBreakpointStorage.getBreakPointAddresses());

  Set<BreakpointAddress> addressesSet = null;

  switch (type) {
    case REGULAR:
      final SetView<BreakpointAddress> notInRegularBreakpoints =
          Sets.difference(addresses, indexedBreakpointStorage.getBreakPointAddresses());
      removeBreakpoints(alreadySteppingBreakpoints, stepBreakpointStorage);
      removeBreakpoints(alreadyEchoBreakpoints, echoBreakpointStorage);
      addressesSet = notInRegularBreakpoints;
      break;

    case STEP:
      final SetView<BreakpointAddress> notInSteppingBreakpoints =
          Sets.difference(addresses, stepBreakpointStorage.getBreakPointAddresses());
      removeBreakpoints(alreadyEchoBreakpoints, echoBreakpointStorage);
      addressesSet = Sets.difference(notInSteppingBreakpoints, alreadyRegularBreakpoints);
      break;

    case ECHO:
      final SetView<BreakpointAddress> notInEchoBreakPoints =
          Sets.difference(addresses, echoBreakpointStorage.getBreakPointAddresses());
      addressesSet = Sets.difference(notInEchoBreakPoints,
          Sets.union(alreadySteppingBreakpoints, alreadyRegularBreakpoints));
      break;
    default:
      throw new IllegalStateException("IE00722: Breakpoint of invalid type");

  }
  return addressesSet;
}
 
Example #25
Source Project: tracecompass   Author: tracecompass   File: ProjectExplorerAnalysisTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test which analyses are present for a kernel trace
 */
@Test
public void testKernelAnalyses() {
    Set<AnalysisNode> actualNodes = getAnalysisNodes(fBot, fKernelTraceFile, false);
    StringJoiner sj = new StringJoiner(", ", "{", "}");
    actualNodes.forEach(node -> sj.add(node.fTitle));
    assertTrue(sj.toString(), actualNodes.containsAll(KERNEL_ANALYSIS_NODES));
    if (!KERNEL_ANALYSIS_NODES.containsAll(actualNodes)) {
        SetView<AnalysisNode> diff = Sets.difference(KERNEL_ANALYSIS_NODES, actualNodes);
        diff.forEach(elem -> System.err.println("New untested analysis : " + elem));
    }
}
 
Example #26
Source Project: tracecompass   Author: tracecompass   File: ProjectExplorerAnalysisTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test which analyses are present for a user space trace
 */
@Test
public void testUstAnalyses() {
    Set<AnalysisNode> actualNodes = getAnalysisNodes(fBot, fUstTraceFile, false);
    StringJoiner sj = new StringJoiner(", ", "{", "}");
    actualNodes.forEach(node -> sj.add(node.fTitle));
    assertTrue(sj.toString(), actualNodes.containsAll(UST_ANALYSIS_NODES));

    if (!UST_ANALYSIS_NODES.containsAll(actualNodes)) {
        SetView<AnalysisNode> diff = Sets.difference(UST_ANALYSIS_NODES, actualNodes);
        diff.forEach(elem -> System.err.println("New untested analysis : " + elem));
    }
}
 
Example #27
Source Project: tracecompass   Author: tracecompass   File: ProjectExplorerAnalysisTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Test which analyses are present for a experiment with kernel and ust trace
 */
@Test
public void testExperimentAnalyses() {
    Set<AnalysisNode> actualNodes = getAnalysisNodes(fBot, EXPERIMENT_NAME, true);
    StringJoiner sj = new StringJoiner(", ", "{", "}");
    actualNodes.forEach(node -> sj.add(node.fTitle));

    assertTrue(sj.toString(), actualNodes.containsAll(EXPERIMENT_NODES));
    if (!EXPERIMENT_NODES.containsAll(actualNodes)) {
        SetView<AnalysisNode> diff = Sets.difference(EXPERIMENT_NODES, actualNodes);
        diff.forEach(elem -> System.err.println("New untested analysis : " + elem));
    }
}
 
Example #28
Source Project: che   Author: eclipse   File: WorkspaceRuntimes.java    License: 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 #29
Source Project: onboard   Author: sercxtyf   File: UserServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<User> filterProjectMembers(List<User> users, int projectId) {
    List<User> members = getUserByProjectId(projectId);
    SetView<User> intersection = Sets.intersection(new HashSet<User>(users), new HashSet<User>(members));
    List<User> legalUsers = Lists.newArrayList();
    for (User user : intersection)
        legalUsers.add(user);
    return legalUsers;
}
 
Example #30
Source Project: brooklyn-server   Author: apache   File: JcloudsTypeCoercions.java    License: 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;
}