Java Code Examples for java.util.HashSet

The following examples show how to use java.util.HashSet. These examples are extracted from open source projects. 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: RxUploader   Source File: SimpleUploadDataStoreTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressLint("ApplySharedPref")
@Test
public void testGetInvalidJobId() throws Exception {
    final Job test = createTestJob();
    final String json = gson.toJson(test);
    final String key = SimpleUploadDataStore.jobIdKey(test.id());
    final Set<String> keys = new HashSet<>();
    keys.add(key);

    final SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putStringSet(SimpleUploadDataStore.KEY_JOB_IDS, keys);
    editor.putString(key, json);
    editor.commit();

    final TestSubscriber<Job> ts = TestSubscriber.create();
    dataStore.get("bad_id").subscribe(ts);

    ts.awaitTerminalEvent(1, TimeUnit.SECONDS);
    ts.assertNoErrors();
    ts.assertValueCount(1);
    ts.assertValue(Job.INVALID_JOB);
}
 
Example 2
private static Set<ArrivalCurve> getPermutations(Set<ArrivalCurve> arrival_curves_1,
		Set<ArrivalCurve> arrival_curves_2) {
	if (arrival_curves_1.isEmpty()) {
		return new HashSet<ArrivalCurve>(arrival_curves_2);
	}
	if (arrival_curves_2.isEmpty()) {
		return new HashSet<ArrivalCurve>(arrival_curves_1);
	}

	Set<ArrivalCurve> arrival_bounds_merged = new HashSet<ArrivalCurve>();

	for (ArrivalCurve alpha_1 : arrival_curves_1) {
		for (ArrivalCurve alpha_2 : arrival_curves_2) {
			arrival_bounds_merged.add(Curve.getUtils().add(alpha_1, alpha_2));
		}
	}

	return arrival_bounds_merged;
}
 
Example 3
Source Project: securify   Source File: JumpI.java    License: Apache License 2.0 6 votes vote down vote up
private Set<Instruction> getAllReachableInstructions(Instruction start) {
	Set<Instruction> reachable = new HashSet<>();
	reachable.add(start);
	Queue<Instruction> bfs = new LinkedList<>();
	bfs.add(start);
	while (!bfs.isEmpty()) {
		Instruction i = bfs.poll();
		// add next instruction
		Instruction next = i.getNext();
		if (next != null && !reachable.contains(next)) {
			reachable.add(next);
			bfs.add(next);
		}
		// check for additional jump destinations
		if (i instanceof BranchInstruction && !(i instanceof _VirtualInstruction)) {
			((BranchInstruction)i).getOutgoingBranches().forEach(jdest -> {
				if (!reachable.contains(jdest)) {
					reachable.add(jdest);
					bfs.add(jdest);
				}
			});
		}
	}
	return reachable;
}
 
Example 4
Source Project: steady   Source File: PythonArchiveAnalyzer.java    License: Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public Set<FileAnalyzer> getChilds(boolean _recursive) {
	final Set<FileAnalyzer> nested_fa = new HashSet<FileAnalyzer>();
	if(!_recursive) {
		nested_fa.addAll(this.nestedAnalyzers);
	}
	else {
		for(FileAnalyzer fa: this.nestedAnalyzers) {
			nested_fa.add(fa);
			final Set<FileAnalyzer> nfas = fa.getChilds(true);
			if(nfas!=null && !nfas.isEmpty())
				nested_fa.addAll(nfas);
		}
	}
	return nested_fa;
}
 
Example 5
Source Project: netbeans   Source File: GeneralKnockout.java    License: Apache License 2.0 6 votes vote down vote up
protected void checkCompletionDoesntContainHtmlItems(CompletionJListOperator jlist, String[] invalidList) {
    try {
        List items = jlist.getCompletionItems();
        HashSet<String> completion = new HashSet<>();
        for (Object item : items) {
            if (item instanceof HtmlCompletionItem) {
                completion.add(((HtmlCompletionItem) item).getItemText());
            } else {
                completion.add(item.toString());
            }
        }
            for (String sCode : invalidList) {
            if (completion.contains(sCode)) {
                fail("Completion list contains invalid item:" + sCode);
            }
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 6
Source Project: onos   Source File: NodeSelection.java    License: Apache License 2.0 6 votes vote down vote up
private Set<String> findHosts(Set<String> ids) {
    Set<String> unmatched = new HashSet<>();
    Host host;

    for (String id : ids) {
        try {
            host = hostService.getHost(hostId(id));
            if (host != null) {
                hosts.add(host);
            } else {
                unmatched.add(id);
            }
        } catch (Exception e) {
            unmatched.add(id);
        }
    }
    return unmatched;
}
 
Example 7
Source Project: incubator-retired-blur   Source File: CsvBlurDriver.java    License: Apache License 2.0 6 votes vote down vote up
private static Set<Path> recurisvelyGetPathesContainingFiles(Path path, Configuration configuration)
    throws IOException {
  Set<Path> pathSet = new HashSet<Path>();
  FileSystem fileSystem = path.getFileSystem(configuration);
  if (!fileSystem.exists(path)) {
    LOG.warn("Path not found [{0}]", path);
    return pathSet;
  }
  FileStatus[] listStatus = fileSystem.listStatus(path);
  for (FileStatus status : listStatus) {
    if (status.isDir()) {
      pathSet.addAll(recurisvelyGetPathesContainingFiles(status.getPath(), configuration));
    } else {
      pathSet.add(status.getPath().getParent());
    }
  }
  return pathSet;
}
 
Example 8
Source Project: steady   Source File: PathSimilarity.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>groupPathsByJointNode.</p>
 */
public void groupPathsByJointNode () {
	this.groupedPaths = new HashMap<String, HashSet<Integer>>();
	for (int i = 0; i < this.paths.size(); i++) {
		LinkedList<String> p = this.paths.get(i);
		for(String s : p) {
			if(!this.groupedPaths.containsKey(s)) {
				HashSet<Integer> tmp = new HashSet<Integer>();
				tmp.add(i);
				this.groupedPaths.put(s, tmp);
			} else {
				this.groupedPaths.get(s).add(i);
			}
		}
	}
}
 
Example 9
private static char[] lookUpTable(String src, int index, Locale locale, boolean bLowerCasing) {
    HashSet<Entry> set = entryTable.get(new Integer(src.codePointAt(index)));
    char[] ret = null;

    if (set != null) {
        Iterator<Entry> iter = set.iterator();
        String currentLang = locale.getLanguage();
        while (iter.hasNext()) {
            Entry entry = iter.next();
            String conditionLang = entry.getLanguage();
            if (((conditionLang == null) || (conditionLang.equals(currentLang))) &&
                    isConditionMet(src, index, locale, entry.getCondition())) {
                ret = bLowerCasing ? entry.getLowerCase() : entry.getUpperCase();
                if (conditionLang != null) {
                    break;
                }
            }
        }
    }

    return ret;
}
 
Example 10
/**
 * {@inheritDoc}
 */
@Override
protected void buttonPressed(final int buttonId) {
	if (buttonId == IDialogConstants.OK_ID) {
		fData.setRefactoringAware(true);
		final RefactoringDescriptorProxy[] descriptors= fHistoryControl.getCheckedDescriptors();
		Set<IProject> set= new HashSet<IProject>();
		IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
		for (int index= 0; index < descriptors.length; index++) {
			final String project= descriptors[index].getProject();
			if (project != null && !"".equals(project)) //$NON-NLS-1$
				set.add(root.getProject(project));
		}
		fData.setRefactoringProjects(set.toArray(new IProject[set.size()]));
		fData.setRefactoringDescriptors(descriptors);
		fData.setExportStructuralOnly(fExportStructural.getSelection());
		final IDialogSettings settings= fSettings;
		if (settings != null)
			settings.put(SETTING_SORT, fHistoryControl.isSortByProjects());
	}
	super.buttonPressed(buttonId);
}
 
Example 11
Source Project: BotLibre   Source File: SelfDecompiler.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Print the formula to create a unique instance of it.
 */
public Vertex createUniqueTemplate(Vertex formula, Network network) {
	try {
		StringWriter writer = new StringWriter();
		printTemplate(formula, writer, "", new ArrayList<Vertex>(), new ArrayList<Vertex>(), new HashSet<Vertex>(), network);
		String source = writer.toString();
		if (source.length() > AbstractNetwork.MAX_TEXT) {
			return formula;
		}
		// Maintain identity on formulas through printing them.
		Vertex existingFormula = network.createVertex(source);
		if (!existingFormula.instanceOf(Primitive.FORMULA)) {
			for (Iterator<Relationship> iterator = formula.orderedAllRelationships(); iterator.hasNext(); ) {
				Relationship relationship = iterator.next();
				existingFormula.addRelationship(relationship.getType(), relationship.getTarget(), relationship.getIndex());
			}
		}
		return existingFormula;
	} catch (IOException ignore) {
		throw new BotException(ignore);
	}
}
 
Example 12
Source Project: JGiven   Source File: ProxyClassPerformanceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_creation_of_proxy_classes(){
    Set<Long> results = new HashSet<>();
    for( int i = 0; i < 1000; i++ ) {
        ScenarioBase scenario = new ScenarioBase();
        TestStage testStage = scenario.addStage( TestStage.class );
        testStage.something();
        if( i % 100 == 0 ) {
            System.gc();
            long usedMemory = ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / ( 1024 * 1024 );
            System.out.println( "Used memory: " + usedMemory );
            results.add( usedMemory );
        }
    }

    assertThat( results )
            .describedAs( "Only should contains 1 or 2 items, as first iteration might use more memory might contain 2 items" )
            .hasSizeBetween( 1, 2 );
}
 
Example 13
Source Project: ant-ivy   Source File: SearchEngine.java    License: Apache License 2.0 6 votes vote down vote up
public String[] listModules(String org) {
    Set<String> entries = new HashSet<>();

    Map<String, Object> tokenValues = new HashMap<>();
    tokenValues.put(IvyPatternHelper.ORGANISATION_KEY, org);

    for (DependencyResolver resolver : settings.getResolvers()) {
        Map<String, String>[] modules = resolver.listTokenValues(
            new String[] {IvyPatternHelper.MODULE_KEY}, tokenValues);
        for (Map<String, String> module : modules) {
            entries.add(module.get(IvyPatternHelper.MODULE_KEY));
        }
    }

    return entries.toArray(new String[entries.size()]);
}
 
Example 14
Source Project: nakadi   Source File: EventTypeChangeListener.java    License: MIT License 6 votes vote down vote up
private void onEventTypeInvalidated(final String eventType) {
    final Optional<Set<InternalListener>> toNotify;
    readWriteLock.readLock().lock();
    try {
        toNotify = Optional.ofNullable(eventTypeToListeners.get(eventType))
                .map(HashSet<InternalListener>::new);
    } finally {
        readWriteLock.readLock().unlock();
    }
    if (toNotify.isPresent()) {
        for (final InternalListener listener : toNotify.get()) {
            try {
                listener.authorizationChangeListener.accept(eventType);
            } catch (RuntimeException ex) {
                LOG.error("Failed to notify listener " + listener, ex);
            }
        }
    }
}
 
Example 15
Source Project: TencentKona-8   Source File: Utils.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * A small implementation of UNIX find.
 * @param matchRegex Only collect paths that match this regex.
 * @param pruneRegex Don't recurse down a path that matches this regex. May be null.
 * @throws IOException if File.getCanonicalPath() fails.
 */
public static List<File> find(final File startpath, final String matchRegex, final String pruneRegex) throws IOException{
    final Pattern matchPattern = Pattern.compile(matchRegex, Pattern.CASE_INSENSITIVE);
    final Pattern prunePattern = pruneRegex == null ? null : Pattern.compile(pruneRegex, Pattern.CASE_INSENSITIVE);
    final Set<String> visited = new HashSet<String>();
    final List<File> found = new ArrayList<File>();
    class Search{
        void search(final File path) throws IOException{
            if(prunePattern != null && prunePattern.matcher(path.getAbsolutePath()).matches()) return;
            String cpath = path.getCanonicalPath();
            if(!visited.add(cpath))  return;
            if(matchPattern.matcher(path.getAbsolutePath()).matches())
                found.add(path);
            if(path.isDirectory())
                for(File sub : path.listFiles())
                    search(sub);
        }
    }
    new Search().search(startpath);
    return found;
}
 
Example 16
private void recalculateCheckedState(List<IWorkingSet> addedWorkingSets) {
	Set<IWorkingSet> checkedWorkingSets= new HashSet<IWorkingSet>();
	GrayedCheckedModelElement[] elements= fModel.getChecked();
	for (int i= 0; i < elements.length; i++)
		checkedWorkingSets.add(elements[i].getWorkingSet());

	if (addedWorkingSets != null)
		checkedWorkingSets.addAll(addedWorkingSets);

	fModel= createGrayedCheckedModel(fElements, getAllWorkingSets(), checkedWorkingSets);

	fTableViewer.setInput(fModel);
	fTableViewer.refresh();
	fTableViewer.setCheckedElements(fModel.getChecked());
	fTableViewer.setGrayedElements(fModel.getGrayed());
}
 
Example 17
Source Project: RemotePreferences   Source File: RemotePreferencesTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testStringSetRead() {
    HashSet<String> set = new HashSet<>();
    set.add("Chocola");
    set.add("Vanilla");
    set.add("Coconut");
    set.add("Azuki");
    set.add("Maple");
    set.add("Cinnamon");

    getSharedPreferences()
        .edit()
        .putStringSet("pref", set)
        .apply();

    RemotePreferences remotePrefs = getRemotePreferences(true);
    Assert.assertEquals(set, remotePrefs.getStringSet("pref", null));
}
 
Example 18
Source Project: kylin   Source File: DataModelDesc.java    License: Apache License 2.0 6 votes vote down vote up
private boolean validate() {

        // ensure no dup between dimensions/metrics
        for (ModelDimensionDesc dim : dimensions) {
            String table = dim.getTable();
            for (String c : dim.getColumns()) {
                TblColRef dcol = findColumn(table, c);
                metrics = ArrayUtils.removeElement(metrics, dcol.getIdentity());
            }
        }

        Set<TblColRef> mcols = new HashSet<>();
        for (String m : metrics) {
            mcols.add(findColumn(m));
        }

        // validate PK/FK are in dimensions
        boolean pkfkDimAmended = false;
        for (Chain chain : joinsTree.getTableChains().values()) {
            pkfkDimAmended = validatePkFkDim(chain.join, mcols) || pkfkDimAmended;
        }
        return pkfkDimAmended;
    }
 
Example 19
Source Project: sakai   Source File: SitePermsService.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
 * @return a list of all valid roles names
 */
public List<String> getValidRoles() {
    HashSet<String> roleIds = new HashSet<String>();
    for (String templateRef : getTemplateRoles()) {
        AuthzGroup ag;
        try {
            ag = authzGroupService.getAuthzGroup(templateRef);
            Set<Role> agRoles = ag.getRoles();
            for (Role role : agRoles) {
                roleIds.add(role.getId());
            }
        } catch (GroupNotDefinedException e) {
            // nothing to do here but continue really
        }
    }
    ArrayList<String> roles = new ArrayList<String>(roleIds);
    Collections.sort(roles);
    return roles;
}
 
Example 20
Source Project: component-runtime   Source File: ProjectResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void configuration(final WebTarget target) {
    final FactoryConfiguration config = target
            .path("project/configuration")
            .request(MediaType.APPLICATION_JSON_TYPE)
            .get(FactoryConfiguration.class);
    final String debug = config.toString();
    assertEquals(new HashSet<>(asList("Gradle", "Maven")), new HashSet<>(config.getBuildTypes()), debug);
    assertEquals(new HashMap<String, List<FactoryConfiguration.Facet>>() {

        {
            put("Test", singletonList(new FactoryConfiguration.Facet("Talend Component Kit Testing",
                    "Generates test(s) for each component.")));
            put("Runtime", singletonList(new FactoryConfiguration.Facet("Apache Beam",
                    "Generates some tests using beam runtime instead of Talend Component Kit Testing framework.")));
            put("Libraries", singletonList(new FactoryConfiguration.Facet("WADL Client Generation",
                    "Generates a HTTP client from a WADL.")));
            put("Tool",
                    asList(new FactoryConfiguration.Facet("Codenvy",
                            "Pre-configures the project to be usable with Codenvy."),
                            new FactoryConfiguration.Facet("Travis CI",
                                    "Creates a .travis.yml pre-configured for a component build.")));
        }
    }, new HashMap<>(config.getFacets()), debug);
}
 
Example 21
static Set<String> getAssignedTrackedEntityAttributeUids(List<Program> programs, List<TrackedEntityType> types) {
    Set<String> attributeUids = new HashSet<>();

    for (Program program : programs) {
        List<ProgramTrackedEntityAttribute> attributes =
                ProgramInternalAccessor.accessProgramTrackedEntityAttributes(program);
        if (attributes != null) {
            for (ProgramTrackedEntityAttribute programAttribute : attributes) {
                attributeUids.add(programAttribute.trackedEntityAttribute().uid());
            }
        }
    }

    for (TrackedEntityType type : types) {
        if (type.trackedEntityTypeAttributes() != null) {
            for (TrackedEntityTypeAttribute attribute : type.trackedEntityTypeAttributes()) {
                attributeUids.add(attribute.trackedEntityAttribute().uid());
            }
        }
    }

    return attributeUids;
}
 
Example 22
Source Project: smallrye-graphql   Source File: Bootstrap.java    License: Apache License 2.0 6 votes vote down vote up
private GraphQLSchema generateGraphQLSchema() {
    GraphQLSchema.Builder schemaBuilder = GraphQLSchema.newSchema();

    createGraphQLEnumTypes();
    createGraphQLInterfaceTypes();
    createGraphQLObjectTypes();
    createGraphQLInputObjectTypes();

    addQueries(schemaBuilder);
    addMutations(schemaBuilder);

    schemaBuilder.additionalTypes(new HashSet<>(enumMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(interfaceMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(typeMap.values()));
    schemaBuilder.additionalTypes(new HashSet<>(inputMap.values()));

    codeRegistryBuilder.fieldVisibility(getGraphqlFieldVisibility());
    schemaBuilder = schemaBuilder.codeRegistry(codeRegistryBuilder.build());

    // register error info
    ErrorInfoMap.register(schema.getErrors());

    return schemaBuilder.build();
}
 
Example 23
Source Project: core   Source File: PropTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public static Set<String> getKeys(File f) throws Exception {
    Set<String> keys = new HashSet<>();

    try(BufferedReader br = new BufferedReader(new FileReader(f))) {
        for(String line; (line = br.readLine()) != null; ) {
            if(!line.equals("") && !line.startsWith("#"))
                keys.add(line.split("=")[0]);
        }
    }

    return keys;
}
 
Example 24
public Component getComponentBefore(Container focusCycleRoot,
                                    Component aComponent) {
    Component hardCoded = aComponent, prevHardCoded;
    HashSet<Component> sanity = new HashSet<Component>();

    do {
        prevHardCoded = hardCoded;
        hardCoded = backwardMap.get(hardCoded);
        if (hardCoded == null) {
            if (delegatePolicy != null &&
                prevHardCoded.isFocusCycleRoot(focusCycleRoot)) {
                return delegatePolicy.getComponentBefore(focusCycleRoot,
                                                   prevHardCoded);
            } else if (delegateManager != null) {
                return delegateManager.
                    getComponentBefore(focusCycleRoot, aComponent);
            } else {
                return null;
            }
        }
        if (sanity.contains(hardCoded)) {
            // cycle detected; bail
            return null;
        }
        sanity.add(hardCoded);
    } while (!accept(hardCoded));

    return hardCoded;
}
 
Example 25
Source Project: lams   Source File: SetAttributeHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Set<String> requiredParameters() {
    final Set<String> req = new HashSet<>();
    req.add("value");
    req.add("attribute");
    return req;
}
 
Example 26
Source Project: codebase   Source File: ProcessModel.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
	@Override
	public Collection<FlowNode> getOutputFlowNodes(NonFlowNode obj) {
		Set<FlowNode> result = new HashSet<FlowNode>();
		//given node part of this graph?
		//31.07.2012 Temporary Remove
		//		if (this.nonFlowNodes.contains(obj)){
//			if (obj instanceof IDataNode){
//				result.addAll((Collection<? extends FlowNode>) ((IDataNode) obj).getReadingFlowNodes());
//				result.addAll((Collection<? extends FlowNode>) ((IDataNode) obj).getUnspecifiedFlowNodes());
//			}
//		}
		return result;
	}
 
Example 27
Source Project: hugegraph-studio   Source File: StudioApiConfig.java    License: Apache License 2.0 5 votes vote down vote up
public Set<String> getAppendLimitSuffixes() {
    List<String> gremlins =
            this.config.get(StudioApiOptions.GREMLINS_APPEND_LIMIT_SUFFIX);

    if (gremlins == null || gremlins.size() == 0) {
        return new HashSet<>();
    }
    Set<String> gremlinSet = new HashSet<>(gremlins);
    for (String g : gremlins) {
        gremlinSet.add(g);
    }
    return gremlinSet;
}
 
Example 28
public Set<SchemaDocument> getImportedDocuments(String targetNamespace) {
    if(targetNamespace==null)
        throw new IllegalArgumentException();
    Set<SchemaDocument> r = new HashSet<SchemaDocument>();
    for (SchemaDocumentImpl doc : references) {
        if(doc.getTargetNamespace().equals(targetNamespace))
            r.add(doc);
    }
    return Collections.unmodifiableSet(r);
}
 
Example 29
Source Project: ipst   Source File: UniqueTopologyChecker.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private static Set<Set<String>> toTopoSet(PossibleTopology.Substation ps, ShortIdDictionary dict) {
    Set<Set<String>> sets = new HashSet<>();
    for (PossibleTopology.Bus b : ps.getBuses()) {
        if (isBusValid(b)) {
            Set<String> set = new HashSet<>();
            for (PossibleTopology.Equipment eq : b.getEquipments()) {
                set.add(dict != null ? dict.getShortId(eq.getId()) : eq.getId());
            }
            sets.add(set);
        }
    }
    return sets;
}
 
Example 30
private static Set<Long> getTimes(ITmfStateSystem key, @Nullable List<Long> timeRequested) {
    if (timeRequested == null) {
        return Collections.emptySet();
    }
    Set<@NonNull Long> times = new HashSet<>();
    for (long t : timeRequested) {
        if (key.getStartTime() <= t && t <= key.getCurrentEndTime()) {
            times.add(t);
        }
    }
    return times;
}