com.google.common.collect.Sets Java Examples
The following examples show how to use
com.google.common.collect.Sets.
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: DataContextImpl.java From cuba with Apache License 2.0 | 6 votes |
@Override public EntitySet merge(Collection<? extends Entity> entities) { checkNotNullArgument(entities, "entity collection is null"); List<Entity> managedList = new ArrayList<>(entities.size()); disableListeners = true; try { Set<Entity> merged = Sets.newIdentityHashSet(); for (Entity entity : entities) { Entity managed = internalMerge(entity, merged, true); managedList.add(managed); } } finally { disableListeners = false; } return EntitySet.of(managedList); }
Example #2
Source File: BlueIssueFactory.java From blueocean-plugin with MIT License | 6 votes |
/** * Finds any issues associated with the changeset * e.g. a commit message could be "TICKET-123 fix all the things" and be associated with TICKET-123 in JIRA * @param changeSetEntry entry * @return issues representing the change */ public static Collection<BlueIssue> resolve(ChangeLogSet.Entry changeSetEntry) { LinkedHashSet<BlueIssue> allIssues = Sets.newLinkedHashSet(); for (BlueIssueFactory factory : ExtensionList.lookup(BlueIssueFactory.class)) { try { Collection<BlueIssue> issues = factory.getIssues(changeSetEntry); if (issues == null) { continue; } allIssues.addAll(issues); } catch (Exception e) { LOGGER.log(Level.WARNING,"Unable to fetch issues for changeSetEntry " + e.getMessage(), e); } } return allIssues; }
Example #3
Source File: AgentControllerTest.java From flow-platform-x with Apache License 2.0 | 6 votes |
@Test public void should_update_agent_resource() throws Throwable { Agent agent = createAgent("hello.agent", Sets.newHashSet("test"), StatusCode.OK); Agent.Resource resource = new Agent.Resource() .setCpu(1) .setFreeDisk(2) .setTotalDisk(5) .setFreeMemory(4) .setTotalMemory(20); ResponseMessage message = mockMvcHelper.expectSuccessAndReturnClass(post("/agents/resource") .header(AgentAuth.HeaderAgentToken, agent.getToken()) .content(objectMapper.writeValueAsBytes(resource)) .contentType(MediaType.APPLICATION_JSON), ResponseMessage.class); Assert.assertEquals(StatusCode.OK, message.getCode()); }
Example #4
Source File: ScorerTest.java From tac-kbp-eal with MIT License | 6 votes |
private AnswerKey makeAnswerKeyFromCorrectAndIncorrect(final ImmutableSet<Response> correct, final ImmutableSet<Response> incorrect, final CorefAnnotation coref) { final ImmutableSet.Builder<AssessedResponse> correctAssessedResponses = ImmutableSet.builder(); for (final Response correctResponse : correct) { correctAssessedResponses.add( AssessedResponse.assessCorrectly(correctResponse, FillerMentionType.NAME)); } final ImmutableSet.Builder<AssessedResponse> incorrectAssessedResponses = ImmutableSet.builder(); for (final Response incorrectResponse : incorrect) { incorrectAssessedResponses .add(AssessedResponse.assessWithIncorrectEventType(incorrectResponse)); } return AnswerKey.from(DOC, Sets.union(correctAssessedResponses.build(), incorrectAssessedResponses.build()), ImmutableSet.<Response>of(), coref); }
Example #5
Source File: ExtractorHelperTest.java From secure-data-service with Apache License 2.0 | 6 votes |
@Test public void testBuildSubToParentEdOrgCache() { EntityToEdOrgCache cache = new EntityToEdOrgCache(); cache.addEntry("lea-1", "school-1"); cache.addEntry("lea-1", "school-2"); cache.addEntry("lea-1", "school-3"); cache.addEntry("lea-2", "school-4"); cache.addEntry("lea-2", "school-5"); cache.addEntry("lea-3", "school-6"); Map<String, Collection<String>> result = helper.buildSubToParentEdOrgCache(cache); Assert.assertEquals(6, result.keySet().size()); Assert.assertEquals(Sets.newHashSet("lea-1"), result.get("school-1")); Assert.assertEquals(Sets.newHashSet("lea-1"), result.get("school-2")); Assert.assertEquals(Sets.newHashSet("lea-1"), result.get("school-3")); Assert.assertEquals(Sets.newHashSet("lea-2"), result.get("school-4")); Assert.assertEquals(Sets.newHashSet("lea-2"), result.get("school-5")); Assert.assertEquals(Sets.newHashSet("lea-3"), result.get("school-6")); }
Example #6
Source File: SolrResponsesComparator.java From SearchServices with GNU Lesser General Public License v3.0 | 6 votes |
public static String compare(Object[] a, Object[] b, int flags, Map<String, Integer> handle) { boolean ordered = (flags & UNORDERED) == 0; if (a.length != b.length) { return ".length:" + a.length + "!=" + b.length; } if (!ordered) { Set<Object> setA = Sets.newHashSet(a); Set<Object> setB = Sets.newHashSet(b); return compare(setA, setB, flags, handle); } for (int i = 0; i < a.length; i++) { String cmp = compare(a[i], b[i], flags, handle); if (cmp != null) return "[" + i + "]" + cmp; } return null; }
Example #7
Source File: AllowAllToken.java From airpal with Apache License 2.0 | 6 votes |
public AllowAllToken(String host, boolean rememberMe, String userName, Iterable<String> groups, String defaultSchema, Duration queryTimeout, String accessLevel) { this.host = host; this.rememberMe = rememberMe; this.userName = userName; this.groups = Sets.newHashSet(groups); this.defaultSchema = defaultSchema; this.queryTimeout = queryTimeout; this.accessLevel = accessLevel; }
Example #8
Source File: AgentHostServiceTest.java From flow-platform-x with Apache License 2.0 | 6 votes |
@Test(expected = NotAvailableException.class) public void should_create_unix_local_host() { // when: create host AgentHost host = new LocalUnixAgentHost(); host.setName("test-host"); host.setTags(Sets.newHashSet("local", "test")); agentHostService.createOrUpdate(host); // then: Assert.assertNotNull(host.getId()); Assert.assertEquals(AgentHost.Type.LocalUnixSocket, host.getType()); Assert.assertEquals(1, agentHostService.list().size()); Assert.assertEquals(host, agentHostService.list().get(0)); // when: create other AgentHost another = new LocalUnixAgentHost(); another.setName("test-host-failure"); another.setTags(Sets.newHashSet("local", "test")); agentHostService.createOrUpdate(another); }
Example #9
Source File: JpaPersistenceServiceImpl.java From genie with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} */ @Override public void setApplicationsForCommand( @NotBlank final String id, @NotNull final List<@NotBlank String> applicationIds ) throws NotFoundException, PreconditionFailedException { log.debug("[setApplicationsForCommand] Called to set {} for {}", applicationIds, id); if (Sets.newHashSet(applicationIds).size() != applicationIds.size()) { throw new PreconditionFailedException("Duplicate application id in " + applicationIds); } final CommandEntity commandEntity = this.commandRepository .getCommandAndApplications(id) .orElseThrow(() -> new NotFoundException("No command with id " + id + " exists")); final List<ApplicationEntity> applicationEntities = Lists.newArrayList(); for (final String applicationId : applicationIds) { applicationEntities.add( this.applicationRepository .getApplicationAndCommands(applicationId) .orElseThrow(() -> new NotFoundException("No application with id " + applicationId + " exists")) ); } commandEntity.setApplications(applicationEntities); }
Example #10
Source File: Matcher.java From Quicksql with MIT License | 6 votes |
public Matcher<E> build() { final Set<String> predicateSymbolsNotInGraph = Sets.newTreeSet(symbolPredicates.keySet()); predicateSymbolsNotInGraph.removeAll(automaton.symbolNames); if (!predicateSymbolsNotInGraph.isEmpty()) { throw new IllegalArgumentException("not all predicate symbols [" + predicateSymbolsNotInGraph + "] are in graph [" + automaton.symbolNames + "]"); } final ImmutableMap.Builder<String, Predicate<MemoryFactory.Memory<E>>> builder = ImmutableMap.builder(); for (String symbolName : automaton.symbolNames) { // If a symbol does not have a predicate, it defaults to true. // By convention, "STRT" is used for the start symbol, but it could be // anything. builder.put(symbolName, symbolPredicates.getOrDefault(symbolName, e -> true)); } return new Matcher<>(automaton, builder.build()); }
Example #11
Source File: LocalizationPopulator.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
private void updateNamespace( AllPropertiesMessageSource source, String namespace, Set<String> messageIds) { Map<String, L10nString> toUpdate = localizationService .getExistingMessages(namespace, messageIds) .collect(toMap(L10nString::getMessageID, identity())); Map<String, L10nString> toAdd = Sets.difference(messageIds, toUpdate.keySet()).stream() .map(msgId -> createL10nString(namespace, msgId)) .collect(toMap(L10nString::getMessageID, identity())); Map<String, L10nString> all = Maps.asMap(messageIds, messageID -> toUpdate.getOrDefault(messageID, toAdd.get(messageID))); all.forEach( (messageID, l10nString) -> updateFromSource(source, namespace, messageID, l10nString)); localizationService.store(toUpdate.values(), toAdd.values()); }
Example #12
Source File: JobLauncher.java From genie with Apache License 2.0 | 6 votes |
/** * Starts the job setup and launch process once the thread is activated. */ @Override public void run() { final long start = System.nanoTime(); final Set<Tag> tags = Sets.newHashSet(); try { this.jobSubmitterService.submitJob( this.jobRequest, this.cluster, this.command, this.applications, this.memory ); MetricsUtils.addSuccessTags(tags); } catch (final GenieException e) { log.error("Unable to submit job due to exception: {}", e.getMessage(), e); MetricsUtils.addFailureTagsWithException(tags, e); } catch (final Throwable t) { MetricsUtils.addFailureTagsWithException(tags, t); throw t; } finally { this.registry.timer(JOB_SUBMIT_TIMER_NAME, tags).record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }
Example #13
Source File: TagPullMessageFilterTest.java From qmq with Apache License 2.0 | 6 votes |
/** * 测试请求 and tag 与消息 tag 不一致的情况 */ @Test public void testAndTagNotMatches() throws Exception { String tag1 = "tag1"; String tag2 = "tag2"; String tag3 = "tag3"; PullRequest request = TestToolBox.createDefaultPullRequest(); request.setFilters(Lists.newArrayList(new TagPullFilter(TagType.AND, Sets.newHashSet(tag1, tag2, tag3)))); BaseMessage message = TestToolBox.createDefaultMessage(); message.addTag(tag1); message.addTag(tag2); Buffer buffer = TestToolBox.messageToBuffer(message); TagPullMessageFilter filter = Mockito.spy(TagPullMessageFilter.class); boolean match = filter.match(request, buffer); assertFalse(match); }
Example #14
Source File: RuntimeTypeCheck.java From astor with GNU General Public License v2.0 | 6 votes |
private void visitFunction(NodeTraversal t, Node n) { FunctionType funType = n.getJSType().toMaybeFunctionType(); if (funType != null && !funType.isConstructor()) { return; } Node nodeToInsertAfter = findNodeToInsertAfter(n); nodeToInsertAfter = addMarker(funType, nodeToInsertAfter, null); TreeSet<ObjectType> stuff = Sets.newTreeSet(ALPHA); Iterables.addAll(stuff, funType.getAllImplementedInterfaces()); for (ObjectType interfaceType : stuff) { nodeToInsertAfter = addMarker(funType, nodeToInsertAfter, interfaceType); } }
Example #15
Source File: Matcher.java From calcite with Apache License 2.0 | 6 votes |
public Matcher<E> build() { final Set<String> predicateSymbolsNotInGraph = Sets.newTreeSet(symbolPredicates.keySet()); predicateSymbolsNotInGraph.removeAll(automaton.symbolNames); if (!predicateSymbolsNotInGraph.isEmpty()) { throw new IllegalArgumentException("not all predicate symbols [" + predicateSymbolsNotInGraph + "] are in graph [" + automaton.symbolNames + "]"); } final ImmutableMap.Builder<String, Predicate<MemoryFactory.Memory<E>>> builder = ImmutableMap.builder(); for (String symbolName : automaton.symbolNames) { // If a symbol does not have a predicate, it defaults to true. // By convention, "STRT" is used for the start symbol, but it could be // anything. builder.put(symbolName, symbolPredicates.getOrDefault(symbolName, e -> true)); } return new Matcher<>(automaton, builder.build()); }
Example #16
Source File: BadCommandTargets.java From estatio with Apache License 2.0 | 6 votes |
@Action(semantics = SemanticsOf.SAFE, restrictTo = RestrictTo.PROTOTYPING) public List<BadTarget> findBadCommandTargets() { Set<String> badObjectTypes = Sets.newTreeSet(); List<Map<String, Object>> rows = isisJdoSupport .executeSql("select distinct(substring(target, 1, charindex(':', target)-1)) as objectType from isiscommand.Command order by 1"); for (Map<String, Object> row : rows) { String targetStr = (String) row.get("objectType"); addIfBad(badObjectTypes, targetStr); } return Lists.newArrayList( FluentIterable.from(badObjectTypes) .transform(x -> new BadTarget(x)) .toList()); }
Example #17
Source File: StandardNiFiServiceFacade.java From localization_nifi with Apache License 2.0 | 6 votes |
@Override public ControllerServiceEntity updateControllerService(final Revision revision, final ControllerServiceDTO controllerServiceDTO) { // get the component, ensure we have access to it, and perform the update request final ControllerServiceNode controllerService = controllerServiceDAO.getControllerService(controllerServiceDTO.getId()); final RevisionUpdate<ControllerServiceDTO> snapshot = updateComponent(revision, controllerService, () -> controllerServiceDAO.updateControllerService(controllerServiceDTO), cs -> { final ControllerServiceDTO dto = dtoFactory.createControllerServiceDto(cs); final ControllerServiceReference ref = controllerService.getReferences(); final ControllerServiceReferencingComponentsEntity referencingComponentsEntity = createControllerServiceReferencingComponentsEntity(ref, Sets.newHashSet(controllerService.getIdentifier())); dto.setReferencingComponents(referencingComponentsEntity.getControllerServiceReferencingComponents()); return dto; }); final PermissionsDTO permissions = dtoFactory.createPermissionsDto(controllerService); final List<BulletinDTO> bulletins = dtoFactory.createBulletinDtos(bulletinRepository.findBulletinsForSource(controllerServiceDTO.getId())); final List<BulletinEntity> bulletinEntities = bulletins.stream().map(bulletin -> entityFactory.createBulletinEntity(bulletin, permissions.getCanRead())).collect(Collectors.toList()); return entityFactory.createControllerServiceEntity(snapshot.getComponent(), dtoFactory.createRevisionDTO(snapshot.getLastModification()), permissions, bulletinEntities); }
Example #18
Source File: TestLogicalPlanner.java From tajo with Apache License 2.0 | 6 votes |
@Test public final void testGenerateCuboids() { Column [] columns = new Column[3]; columns[0] = new Column("col1", Type.INT4); columns[1] = new Column("col2", Type.INT8); columns[2] = new Column("col3", Type.FLOAT4); List<Column[]> cube = LogicalPlanner.generateCuboids(columns); assertEquals(((int)Math.pow(2, numCubeColumns)), cube.size()); Set<Set<Column>> cuboids = Sets.newHashSet(); for (Column [] cols : cube) { cuboids.add(Sets.newHashSet(cols)); } for (Set<Column> result : testGenerateCuboidsResult) { assertTrue(cuboids.contains(result)); } }
Example #19
Source File: ImplementTypeFilterRule.java From fdb-record-layer with Apache License 2.0 | 6 votes |
@Override public void onMatch(@Nonnull PlannerRuleCall call) { final LogicalTypeFilterExpression typeFilter = call.get(root); final RecordQueryPlan child = call.get(childMatcher); Set<String> childRecordTypes = RecordTypesProperty.evaluate(call.getContext(), child); Set<String> filterRecordTypes = Sets.newHashSet(typeFilter.getRecordTypes()); if (filterRecordTypes.containsAll(childRecordTypes)) { // type filter is completely redundant, so remove it entirely call.yield(call.ref(child)); } else { // otherwise, keep a filter on record types which the child might produce and are included in the filter Set<String> unsatisfiedTypeFilters = Sets.intersection(filterRecordTypes, childRecordTypes); call.yield(GroupExpressionRef.of(new RecordQueryTypeFilterPlan(child, unsatisfiedTypeFilters))); } }
Example #20
Source File: UniqueFieldValidatorImpl.java From cm_ext with Apache License 2.0 | 6 votes |
@Override public boolean isValid(Collection<?> list, ConstraintValidatorContext context) { if (list != null) { Set<Object> seenSoFar = Sets.newHashSet(); for (Object obj : list) { Object value = propertyValue(obj, uniqueField.value()); if ((value == null) && this.skipNulls) { continue; } if (seenSoFar.contains(value)) { addViolation(context, uniqueField.value()); return false; } seenSoFar.add(value); } } return true; }
Example #21
Source File: DelegateSentryStore.java From incubator-sentry with Apache License 2.0 | 5 votes |
@Override public Set<String> getGroupsByRoles(String component, Set<String> roles) throws SentryUserException { roles = toTrimmedLower(roles); Set<String> groupNames = Sets.newHashSet(); if (roles.size() == 0) { return groupNames; } PersistenceManager pm = null; try{ pm = openTransaction(); //get groups by roles Query query = pm.newQuery(MSentryGroup.class); StringBuilder filters = new StringBuilder(); query.declareVariables("org.apache.sentry.provider.db.service.model.MSentryRole role"); List<String> rolesFiler = new LinkedList<String>(); for (String role : roles) { rolesFiler.add("role.roleName == \"" + role + "\" "); } filters.append("roles.contains(role) " + "&& (" + Joiner.on(" || ").join(rolesFiler) + ")"); query.setFilter(filters.toString()); List<MSentryGroup> groups = (List<MSentryGroup>)query.execute(); if (groups == null) { return groupNames; } for (MSentryGroup group : groups) { groupNames.add(group.getGroupName()); } return groupNames; } finally { if (pm != null) { commitTransaction(pm); } } }
Example #22
Source File: BandwidthDispatcher.java From joal with Apache License 2.0 | 5 votes |
@Override public void run() { try { while (!this.stop) { Thread.sleep(this.threadPauseInterval); ++this.threadLoopCounter; // refresh bandwidth every 1200000 milliseconds (20 minutes) if (this.threadLoopCounter == 1200000 / this.threadPauseInterval) { this.refreshCurrentBandwidth(); this.threadLoopCounter = 0; } // This method as to run as fast as possible to avoid blocking other ones. Because we wan't this loop // to be scheduled as precise as we can. Locking to much will delay the Thread.sleep and cause stats // to be undervalued this.lock.readLock().lock(); final Set<Map.Entry<InfoHash, TorrentSeedStats>> entrySet = Sets.newHashSet(this.torrentsSeedStats.entrySet()); this.lock.readLock().unlock(); for (final Map.Entry<InfoHash, TorrentSeedStats> entry : entrySet) { final Speed speed = this.speedMap.get(entry.getKey()); final long speedInBytesPerSecond = speed == null ? 0: speed.getBytesPerSeconds(); // avoid Map#getOrDefault as it will trigger a lot of Speed object instantiation for nothing. // Divide by 1000 because of the thread pause interval being in milliseconds // The multiplication HAS to be done before the division, otherwise we're going to have trailing zeroes entry.getValue().addUploaded((speedInBytesPerSecond * this.threadPauseInterval) / 1000); } } } catch (final InterruptedException ignore) { } }
Example #23
Source File: AbstractTestIndexerPolicyEngine.java From incubator-sentry with Apache License 2.0 | 5 votes |
@Test public void testAnalyst() throws Exception { Set<String> expected = Sets.newTreeSet(Sets.newHashSet( ANALYST_PURCHASES_WRITE, ANALYST_ANALYST1_ALL, ANALYST_JRANALYST1_ACTION_ALL, ANALYST_TMPINDEXER_WRITE, ANALYST_TMPINDEXER_READ)); Assert.assertEquals(expected.toString(), new TreeSet<String>(policy.getPrivileges(set("analyst"), ActiveRoleSet.ALL)) .toString()); }
Example #24
Source File: PackratParserGenUtil.java From xtext-extras with Eclipse Public License 2.0 | 5 votes |
private static List<String> getConflictingKeywordsImpl(final Grammar grammar, TerminalRule rule) { final Iterator<Keyword> conflictingKeywords = getConflictingKeywords(rule, Iterators.filter(EcoreUtil.getAllContents(grammar, true), Keyword.class)); Set<String> res = Sets.newLinkedHashSet(); Iterators.addAll(res, Iterators.transform(conflictingKeywords, new Function<Keyword, String>() { @Override public String apply(Keyword param) { return param.getValue(); } })); return Lists.newArrayList(res); }
Example #25
Source File: BindingTester.java From tassal with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static void checkAllBindings(final List<TokenNameBinding> bindings) { final Set<Integer> indexes = Sets.newHashSet(); for (final TokenNameBinding binding : bindings) { BindingTester.checkBinding(binding); assertFalse("Indexes appear only once", indexes.removeAll(binding.nameIndexes)); indexes.addAll(binding.nameIndexes); } }
Example #26
Source File: RRMultiWriter.java From distributedlog with Apache License 2.0 | 5 votes |
static <VALUE> Set<ServiceFactory<VALUE, DLSN>> initializeServices( String[] streams, DistributedLogClient client) { Set<ServiceFactory<VALUE, DLSN>> serviceFactories = Sets.newHashSet(); for (String stream : streams) { Service<VALUE, DLSN> service = new StreamWriter(stream, client); serviceFactories.add(new SingletonFactory<VALUE, DLSN>(service)); } return serviceFactories; }
Example #27
Source File: MemoryStorage.java From cassandra-reaper with Apache License 2.0 | 5 votes |
@Override public SortedSet<UUID> getRepairRunIdsForCluster(String clusterName) { SortedSet<UUID> repairRunIds = Sets.newTreeSet((u0, u1) -> (int)(u0.timestamp() - u1.timestamp())); for (RepairRun repairRun : repairRuns.values()) { if (repairRun.getClusterName().equalsIgnoreCase(clusterName)) { repairRunIds.add(repairRun.getId()); } } return repairRunIds; }
Example #28
Source File: ManagementSystem.java From titan1withtp3.1 with Apache License 2.0 | 5 votes |
private UpdateStatusTrigger(StandardTitanGraph graph, TitanSchemaVertex vertex, SchemaStatus newStatus, Iterable<PropertyKeyVertex> keys) { this.graph = graph; this.schemaVertexId = vertex.longId(); this.newStatus = newStatus; this.propertyKeys = Sets.newHashSet(Iterables.transform(keys, new Function<PropertyKey, Long>() { @Nullable @Override public Long apply(@Nullable PropertyKey propertyKey) { return propertyKey.longId(); } })); }
Example #29
Source File: TemplateDecoratorTest.java From cloudbreak with Apache License 2.0 | 5 votes |
private Template initTemplate() { Template template = new Template(); template.setVolumeTemplates(Sets.newHashSet()); CloudVmTypes cloudVmTypes = new CloudVmTypes(singletonMap(REGION, emptySet()), emptyMap()); when(cloudParameterService.getVmTypesV2(eq(extendedCloudCredential), eq(REGION), eq(VARIANT), eq(CdpResourceType.DATAHUB), anyMap())) .thenReturn(cloudVmTypes); when(locationService.location(REGION, AVAILABILITY_ZONE)).thenReturn(null); return template; }
Example #30
Source File: TestIntegrationOfTSOClientServerBasicFunctionality.java From phoenix-omid with Apache License 2.0 | 5 votes |
@Test(timeOut = 30_000) public void testTransactionStartedBeforeNonOverlapFenceCommits() throws Exception { long startTsTx1 = tsoClient.getNewStartTimestamp().get(); tsoClient.getFence(7).get(); try { tsoClient.commit(startTsTx1, Sets.newHashSet(c1, c2)).get(); } catch (ExecutionException ee) { Assert.fail("TX should successfully commit"); } }