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 File: ToolsTest.java    From nomulus with 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 #2
Source File: GeoResourceRecordSetCommands.java    From denominator with 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 #3
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 #4
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 #5
Source File: UserServiceImplTest.java    From onboard with 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 #6
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 #7
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 #8
Source File: AccessKeyServiceWithCache.java    From apollo with 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 #9
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 #10
Source File: BroadcastOutputBuffer.java    From presto with 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 #11
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 #12
Source File: SessionRegistry.java    From sofa-registry with 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 #13
Source File: KubeService.java    From singer with 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 #14
Source File: ProjectExplorerAnalysisTest.java    From tracecompass with 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 #15
Source File: ProjectExplorerAnalysisTest.java    From tracecompass with 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 #16
Source File: ProjectExplorerAnalysisTest.java    From tracecompass with 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 #17
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 #18
Source File: UserServiceImpl.java    From onboard with 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 #19
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 #20
Source File: MockTracerouteEngine.java    From batfish with Apache License 2.0 5 votes vote down vote up
@Override
public SortedMap<Flow, List<TraceAndReverseFlow>> computeTracesAndReverseFlows(
    Set<Flow> flows, Set<FirewallSessionTraceInfo> sessions, boolean ignoreFilters) {
  checkArgument(_resultsForSessions.containsKey(sessions), "unexpected sessions");
  Map<Flow, List<TraceAndReverseFlow>> results = _resultsForSessions.get(sessions);
  SetView<Flow> unexpectedFlows = Sets.difference(flows, results.keySet());
  checkArgument(unexpectedFlows.isEmpty(), "unexpected Flows");
  return results.entrySet().stream()
      .filter(entry -> flows.contains(entry.getKey()))
      .collect(
          ImmutableSortedMap.toImmutableSortedMap(
              Ordering.natural(), Entry::getKey, Entry::getValue));
}
 
Example #21
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 #22
Source File: CcToolchainVariables.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Adds all variables to this builder. Cannot override already added variables. Does not add
 * variables defined in the {@code parent} variables.
 */
public Builder addAllNonTransitive(CcToolchainVariables variables) {
  SetView<String> intersection =
      Sets.intersection(variables.getVariablesMap().keySet(), variablesMap.keySet());
  Preconditions.checkArgument(
      intersection.isEmpty(), "Cannot overwrite existing variables: %s", intersection);
  this.variablesMap.putAll(variables.getVariablesMap());
  return this;
}
 
Example #23
Source File: RegistryDiplomaRequest.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public EventType getEventType() {
    final SetView<EventType> eventTypesToUse =
            Sets.intersection(getPossibleEventTypes(), getProgramConclusion().getEventTypes().getTypes());

    if (eventTypesToUse.size() != 1) {
        throw new DomainException("error.program.conclusion.many.event.types");
    }

    return eventTypesToUse.iterator().next();
}
 
Example #24
Source File: BuildRulePipelinesRunner.java    From buck with Apache License 2.0 5 votes vote down vote up
/** Gives the factory a way to construct a {@link RunnableWithFuture} to build the given rule. */
public <T extends RulePipelineState> void addRule(
    SupportsPipelining<T> rule,
    Function<T, RunnableWithFuture<Optional<BuildResult>>> ruleStepRunnerFactory) {
  BuildRulePipelineStage<T> pipelineStage = getPipelineStage(rule);

  SupportsPipelining<T> previousRuleInPipeline = rule.getPreviousRuleInPipeline();
  if (previousRuleInPipeline != null) {
    Preconditions.checkState(
        previousRuleInPipeline.getPipelineStateFactory() == rule.getPipelineStateFactory(),
        "To help ensure that rules have pipeline-compatible rule keys, all rules in a pipeline must share a PipelineStateFactory instance.");
    SortedSet<BuildRule> currentDeps = rule.getBuildDeps();
    SortedSet<BuildRule> previousDeps = previousRuleInPipeline.getBuildDeps();
    Preconditions.checkState(
        currentDeps.contains(previousRuleInPipeline),
        "Each rule in a pipeline must depend on the previous rule in the pipeline.");
    SetView<BuildRule> extraDeps =
        Sets.difference(
            currentDeps, Sets.union(previousDeps, Collections.singleton(previousRuleInPipeline)));
    Preconditions.checkState(
        extraDeps.isEmpty(),
        "Each rule in a pipeline cannot depend on rules which are not also dependencies of the previous rule in the pipeline. "
            + "This ensures that each rule in the pipeline is ready to build as soon as the previous one completes. "
            + "%s has extra deps <%s>.",
        rule,
        Joiner.on(", ").join(extraDeps));
    getPipelineStage(previousRuleInPipeline).setNextStage(pipelineStage);
  }

  pipelineStage.setRuleStepRunnerFactory(ruleStepRunnerFactory);
}
 
Example #25
Source File: ArbitraryOutputBuffer.java    From presto with 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 #26
Source File: MigrationsHelper.java    From android-schema-utils with Apache License 2.0 5 votes vote down vote up
public void performMigrations(SQLiteDatabase db, TableMigration... migrations) {
  for (TableMigration migration : migrations) {
    final String tempTable = "tmp_" + tempTableIndex++;
    db.execSQL("ALTER TABLE " + migration.tableName + " RENAME TO " + tempTable);
    ImmutableSet<String> oldColumns = getColumns(db, tempTable);

    db.execSQL(migration.createTableStatement);
    final String tempNewTable = "tmp_" + tempTableIndex++;
    db.execSQL("ALTER TABLE " + migration.tableName + " RENAME TO " + tempNewTable);
    ImmutableSet<String> newColumns = getColumns(db, tempNewTable);

    db.execSQL("ALTER TABLE " + tempNewTable + " RENAME TO " + migration.tableName);

    Set<String> commonColumns = Sets.intersection(oldColumns, newColumns);
    Set<String> droppedColumns = Sets.difference(oldColumns, newColumns);
    if (!droppedColumns.isEmpty()) {
      Log.w(TAG, "Dropping columns " + Joiner.on(",").join(droppedColumns) + " during migration of " + migration.tableName);
    }

    Set<String> addedColumns = Sets.difference(Sets.difference(newColumns, oldColumns), migration.mappings.keySet());
    if (!addedColumns.isEmpty()) {
      Log.w(TAG, "Will try to add new columns " + Joiner.on(",").join(addedColumns) + " during migration of " + migration.tableName);
    }

    SetView<String> unmappedColumns = Sets.difference(commonColumns, migration.mappings.keySet());
    String insertColumnsString = Joiner.on(",").join(Iterables.concat(unmappedColumns, migration.mappings.keySet()));
    String selectColumnsString = Joiner.on(",").join(Iterables.concat(unmappedColumns, migration.mappings.values()));

    db.execSQL("INSERT INTO " + migration.tableName + "(" + insertColumnsString + ") SELECT " + selectColumnsString + " FROM " + tempTable);
    db.execSQL("DROP TABLE " + tempTable);
  }
}
 
Example #27
Source File: BreakpointManager.java    From binnavi with 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 #28
Source File: SqlIntegrationMembershipTest.java    From nomulus with 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 #29
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 #30
Source File: MethodsPresenceTest.java    From google-ads-java with 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);
}