public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { Set<String> classes = new LinkedHashSet<String>(); Set<String> interfaces = new LinkedHashSet<String>(); Set<String> unknownClasses = new LinkedHashSet<String>(); Set<String> unknownInterfaces = new LinkedHashSet<String>(); if (myExtendsClause != null) { collectRefs( myExtendsClause.getReferenceElementsGroovy(), classes, interfaces, myClass.isInterface() ? unknownInterfaces : unknownClasses); myExtendsClause.delete(); } if (myImplementsClause != null) { collectRefs( myImplementsClause.getReferenceElementsGroovy(), classes, interfaces, unknownInterfaces); myImplementsClause.delete(); } if (myClass.isInterface()) { interfaces.addAll(classes); unknownInterfaces.addAll(unknownClasses); addNewClause(interfaces, unknownInterfaces, project, true); } else { addNewClause(classes, unknownClasses, project, true); addNewClause(interfaces, unknownInterfaces, project, false); } }
private static Set<String> generateNewAssetPaths(Application application, String path) { Set<String> assetPaths = null; if ((path != null) && (assetPathsHistory != null && assetPathsHistory.contains(path))) { // already added, just return null return null; } assetPaths = new LinkedHashSet<String>(); assetPaths.add(application.getApplicationInfo().sourceDir); if (ignoreOpt && Build.VERSION.SDK_INT > 20) { assetPaths.add(WebViewGoogleAssetPath); } // get original asset paths on android above 5.0 in case webview not // added try { if (mOriginAssetsPath == null && Build.VERSION.SDK_INT > 20 && !ignoreOpt) { mOriginAssetsPath = getOriginAssetsPath(application.getResources().getAssets()); assetPaths.addAll(mOriginAssetsPath); } } catch (Throwable e) { } if (assetPathsHistory != null) assetPaths.addAll(assetPathsHistory); if (!TextUtils.isEmpty(path)) assetPaths.add(path); return assetPaths; }
/** * Loads the contents of the given locations into memory. * * @param locations locations to add (of type {@link java.io.File <File>}). * @throws IOException if an I/O error occurred. */ public synchronized void loadAll(List locations) throws IOException { if (locations == null) { return; } Set data = new HashSet(1000); for (Iterator i = locations.iterator(); i.hasNext(); ) { File location = (File) i.next(); ClassRepositoryEntry entry = loadEntry(location); if (entry != null) { data.addAll(entry.getData()); if (Loggers.IO.isDebugEnabled()) { Loggers.IO.debug("ClassRepository: Loaded " + data.size() + " classes from " + location); } } } if (!data.isEmpty()) { data.addAll(Arrays.asList(_content)); _content = (String[]) data.toArray(EMPTY_STRING_ARRAY); Arrays.sort(_content); } }
/** * Retrieve the names of all the public static fields, methods and classes in the clazz * * @param clazz the object to inspect * @return list of all the names of public statics */ public String[] getPublicStaticNames(Class<?> clazz) { Set<String> names = new HashSet<String>(); names.addAll(Arrays.asList(getPublicStaticClassNames(clazz))); names.addAll(Arrays.asList(getPublicStaticFieldNames(clazz))); names.addAll(Arrays.asList(getPublicStaticMethodNames(clazz))); return (String[]) names.toArray(new String[names.size()]); }
private synchronized void updateCurrentFiles() { Set<FileObject> newCurrentFiles = new HashSet<FileObject>(); newCurrentFiles.addAll(fileObjectResult.allInstances()); for (DataObject d : dataObjectResult.allInstances()) { newCurrentFiles.add(d.getPrimaryFile()); } for (Node n : nodeResult.allInstances()) { newCurrentFiles.addAll(n.getLookup().lookupAll(FileObject.class)); for (DataObject d : n.getLookup().lookupAll(DataObject.class)) { newCurrentFiles.add(d.getPrimaryFile()); } } List<FileObject> newCurrentFilesFiltered = OpenedEditors.filterSupportedMIMETypes( new LinkedList<FileObject>(newCurrentFiles), supportedMimeTypes); if (!currentFiles.equals(newCurrentFilesFiltered)) { currentFiles = newCurrentFilesFiltered; lookupContentChanged(); } }
/** * src全てをこのグループに追加します。 結合しているかについて調べないので注意。 * * @param src NOT NULL */ void add(StoneGroupImpl src) { ArgumentChecker.throwIfNull(src); stones_.addAll(src.stones_); neighbors_.addAll(src.neighbors_); lifePoints_.addAll(src.lifePoints_); lifePoints_.removeAll(stones_); }
private Collection<File> getClasspathFiles( ModuleChunk chunk, JpsJavaClasspathKind kind, final boolean excludeMainModuleOutput, ClasspathPart classpathPart, final boolean exportedOnly) { final Set<File> files = new LinkedHashSet<File>(); for (JpsModule module : chunk.getModules()) { JpsJavaDependenciesEnumerator enumerator = JpsJavaExtensionService.dependencies(module).includedIn(kind).recursively(); if (exportedOnly) { enumerator = enumerator.exportedOnly(); } if (classpathPart == ClasspathPart.BEFORE_JDK) { enumerator = enumerator.satisfying(new BeforeJavaSdkItemFilter(module)); } else if (classpathPart == ClasspathPart.AFTER_JDK) { enumerator = enumerator.satisfying(new AfterJavaSdkItemFilter(module)); } JpsJavaDependenciesRootsEnumerator rootsEnumerator = enumerator.classes(); if (excludeMainModuleOutput) { rootsEnumerator = rootsEnumerator.withoutSelfModuleOutput(); } files.addAll(rootsEnumerator.getRoots()); } if (classpathPart == ClasspathPart.BEFORE_JDK) { for (JpsModule module : chunk.getModules()) { JpsSdk<JpsDummyElement> sdk = module.getSdk(JpsJavaSdkType.INSTANCE); if (sdk != null) { files.addAll(sdk.getParent().getFiles(JpsOrderRootType.COMPILED)); } } } return files; }
@Override public void authenticate( Context context, AuthProviderType authProviderType, SocializeAuthListener authListener, String... permissions) { SocializeConfig config = getConfig(); String consumerKey = config.getProperty(SocializeConfig.SOCIALIZE_CONSUMER_KEY); String consumerSecret = config.getProperty(SocializeConfig.SOCIALIZE_CONSUMER_SECRET); if (permissions.length > 0) { if (!Arrays.equals(permissions, FacebookService.DEFAULT_PERMISSIONS)) { // Ensure the requested permissions include the default permissions Set<String> all = new HashSet<String>(); all.addAll(Arrays.asList(permissions)); all.addAll(Arrays.asList(FacebookService.DEFAULT_PERMISSIONS)); permissions = all.toArray(new String[all.size()]); } } AuthProviderInfo authProviderInfo = authProviderInfoBuilder.getFactory(authProviderType).getInstance(permissions); authenticate(context, consumerKey, consumerSecret, authProviderInfo, authListener); }
protected PatternSet doCopyFrom(PatternSet from) { includes.clear(); excludes.clear(); includeSpecs.clear(); excludeSpecs.clear(); caseSensitive = from.caseSensitive; if (from instanceof IntersectionPatternSet) { PatternSet other = ((IntersectionPatternSet) from).other; PatternSet otherCopy = new PatternSet().copyFrom(other); PatternSet intersectCopy = new IntersectionPatternSet(otherCopy); intersectCopy.includes.addAll(from.includes); intersectCopy.excludes.addAll(from.excludes); intersectCopy.includeSpecs.addAll(from.includeSpecs); intersectCopy.excludeSpecs.addAll(from.excludeSpecs); includeSpecs.add(intersectCopy.getAsSpec()); } else { includes.addAll(from.includes); excludes.addAll(from.excludes); includeSpecs.addAll(from.includeSpecs); excludeSpecs.addAll(from.excludeSpecs); } return this; }
/** * Given a set of SCC nodes make this the lead member of the SCC and reroute all incoming and * outgoing links accordingly. This eager rewrite is based on the assumption that there are few * cycles so it is better to rewrite once and keep the graph easy to traverse. */ public void makeLeadNodeFor(Set<GraphNode> members) { // Accumulate all successors Set<GraphNode> newSucc = new HashSet<>(); Set<GraphNode> newSuccClosed = new HashSet<>(); for (GraphNode n : members) { newSucc.addAll(n.succ); newSuccClosed.addAll(n.succClosed); } newSucc.removeAll(members); newSuccClosed.removeAll(members); succ = newSucc; succClosed = newSuccClosed; // Rewrite all direct successors to have us as predecessor for (GraphNode n : succ) { n.pred.removeAll(members); n.pred.add(this); } // Find all predecessor nodes and relink link them to point to us Set<GraphNode> done = new HashSet<>(); Set<GraphNode> newAliases = new HashSet<>(); for (GraphNode member : members) { addSiblings(newAliases, member); } becomeLeaderOf(newAliases); for (GraphNode n : members) { if (n != this) { pred.addAll(n.pred); n.relocateAllRefTo(this, done); n.becomeSubordinateOf(this); } } pred.removeAll(members); }
/** * Adds objects to the a bag for the matches against a set of identifiers. * * @param ids A collection of identifiers * @param bag The bag to add the objects to * @param type The type of this bag * @param extraFieldValue An extra value for disambiguation. * @param unmatchedIds An accumulator to store the failed matches. * @param acceptableIssues the list of issues that are OK to ignore. * @throws ClassNotFoundException if the type is not a valid class. * @throws InterMineException If something goes wrong building the bag. * @throws ObjectStoreException If there is a problem on the database level. */ protected void addIdsToList( final Collection<? extends String> ids, final InterMineBag bag, final String type, final String extraFieldValue, final Set<String> unmatchedIds, final Collection<String> acceptableIssues) throws ClassNotFoundException, InterMineException, ObjectStoreException { final BagQueryResult result = runner.searchForBag( type, new ArrayList<String>(ids), extraFieldValue, acceptableIssues.contains(BagQueryResult.WILDCARD)); bag.addIdsToBag(result.getMatches().keySet(), type); for (final String issueType : result.getIssues().keySet()) { if (acceptableIssues.contains(issueType)) { bag.addIdsToBag(result.getIssueIds(issueType), type); } else { unmatchedIds.addAll(result.getInputIdentifiersForIssue(issueType)); } } unmatchedIds.addAll(result.getUnresolvedIdentifiers()); }
public FloatWritable evaluate(final List<String> a, final List<String> b) { if (a == null && b == null) { return new FloatWritable(0.f); } else if (a == null || b == null) { return new FloatWritable(1.f); } final int asize = a.size(); final int bsize = b.size(); if (asize == 0 && bsize == 0) { return new FloatWritable(0.f); } else if (asize == 0 || bsize == 0) { return new FloatWritable(1.f); } union.addAll(a); union.addAll(b); float unionSize = union.size(); union.clear(); intersect.addAll(a); intersect.retainAll(b); float intersectSize = intersect.size(); intersect.clear(); float j = intersectSize / unionSize; return new FloatWritable(1.f - j); }
/** * Builds the starter set of type names that should be indexed when seen during addType(). This * set is a thread safe instance variable and external logic is free to modify it as further * requirements are discovered. */ private static Set<String> buildInitialTypeNamesToIndex() { Set<String> typeNamesToIndex = Sets.newHashSet(); typeNamesToIndex.addAll( ImmutableList.of( "java.io.Serializable", "java.lang.Object", "java.lang.String", "java.lang.Class", "java.lang.CharSequence", "java.lang.Cloneable", "java.lang.Comparable", "java.lang.Enum", "java.lang.Iterable", "java.util.Iterator", "java.lang.AssertionError", "java.lang.Boolean", "java.lang.Byte", "java.lang.Character", "java.lang.Short", "java.lang.Integer", "java.lang.Long", "java.lang.Float", "java.lang.Double", "java.lang.Throwable", "com.google.gwt.core.client.GWT", JAVASCRIPTOBJECT, CLASS_LITERAL_HOLDER, "com.google.gwt.core.client.RunAsyncCallback", "com.google.gwt.core.client.impl.AsyncFragmentLoader", "com.google.gwt.core.client.impl.Impl", "com.google.gwt.core.client.prefetch.RunAsyncCode")); typeNamesToIndex.addAll(CODEGEN_TYPES_SET); return typeNamesToIndex; }
@Override public Set<SelectionItem> getSelectionItems(SVGHandle handle, Set<Element> elements, int level) { // clearing the stored values rotationSkewCenterPoint = null; // getting the first element of this set Element element = elements.iterator().next(); // the set of the items that will be returned Set<SelectionItem> items = new HashSet<SelectionItem>(); // getting the bounds of the element Rectangle2D bounds = getTransformedShape(handle, element, false).getBounds2D(); // scaling the bounds in the canvas space Rectangle2D scaledWholeBounds = handle.getTransformsManager().getScaledRectangle(bounds, false); // getting the selection items according to the level type switch (level) { case Selection.SELECTION_LEVEL_DRAWING: case Selection.SELECTION_LEVEL_1: items.addAll(getResizeSelectionItems(handle, elements, scaledWholeBounds)); break; case Selection.SELECTION_LEVEL_2: items.addAll(getRotateSelectionItems(handle, elements, scaledWholeBounds)); break; } return items; }
/** * Returns a set of DN that matches the resource and subject indexes. * * @param indexes Resource search indexes. * @param subjectIndexes Subject search indexes * @param bSubTree <code>true</code> for sub tree search mode. * @return A set of DN that matches the resource and subject indexes. */ public Set<String> getMatchingEntries( ResourceSearchIndexes indexes, Set<String> subjectIndexes, boolean bSubTree) { rwlock.readLock().lock(); try { Set<String> results = new HashSet<String>(); boolean hasSubjectIndexes = (subjectIndexes != null) && !subjectIndexes.isEmpty(); if (hasSubjectIndexes) { for (String i : subjectIndexes) { Set<String> r = (Set<String>) subjectIndexCache.get(i); if (r != null) { results.addAll(r); } } results.retainAll(getHostIndexes(indexes)); } else { results.addAll(getHostIndexes(indexes)); } if (bSubTree) { results.retainAll(getPathParentIndexes(indexes)); } else { results.retainAll(getPathIndexes(indexes)); } return results; } finally { rwlock.readLock().unlock(); } }
public List<TemplateMenuItem> findUserMenuByParent(UserInfo user, String parentId) { Set<TemplateMenuItem> userTemplateMenuItem = new HashSet(); // 添加用户额外菜单项 List<TemplateMenuItem> userExtraTemplateMenuItems = menuDao.findTemplateMenuItemInUserExtraMenu(user); userTemplateMenuItem.addAll(userExtraTemplateMenuItems); // 获取用户对应角色菜单项 Set<Role> roles = user.getRoles(); Set<DeptMenu> deptMenus = new HashSet(); for (Role role : roles) { deptMenus.add(role.getDeptMenu()); } for (DeptMenu DeptMenu : deptMenus) { List<TemplateMenuItem> deptTemplateMenuItems = menuDao.findTemplateMenuItemInDeptMenu(DeptMenu); userTemplateMenuItem.addAll(deptTemplateMenuItems); } // 收集模板菜单项 List<TemplateMenuItem> templateMenuItems = null; if ("0".equals(parentId) || StringUtils.isBlank(parentId)) { templateMenuItems = menuDao.findTemplateMenuItemNoParent(); } else { templateMenuItems = menuDao.findTemplateMenuItemByParent(parentId); } List<TemplateMenuItem> userMenuItem = new ArrayList(); for (TemplateMenuItem templateMenuItem : templateMenuItems) { if (userTemplateMenuItem.contains(templateMenuItem)) { userMenuItem.add(templateMenuItem); } } return userMenuItem; }
private static Set<Character> calcAlphaDisjunction( List<Character> remoteCharacters, Set<Character> thisCharacters) { Set<Character> disjunction = new HashSet<Character>(); disjunction.addAll(thisCharacters); disjunction.addAll(remoteCharacters); return disjunction; }
@Override public Set<String> getKnownVariables() { Set<String> knownVariables = new HashSet<String>(); knownVariables.addAll(proxy.keySet()); knownVariables.addAll(context.keySet()); return knownVariables; }
/** * Return a Collection of all certificates or attribute certificates found in the X509Store's that * are matching the certSelect criteriums. * * @param certSelect a {@link Selector} object that will be used to select the certificates * @param certStores a List containing only {@link X509Store} objects. These are used to search * for certificates. * @return a Collection of all found {@link X509Certificate} or {@link * org.bouncycastle.x509.X509AttributeCertificate} objects. May be empty but never <code>null * </code>. */ protected static Collection findCertificates(X509CertStoreSelector certSelect, List certStores) throws AnnotatedException { Set certs = new HashSet(); Iterator iter = certStores.iterator(); while (iter.hasNext()) { Object obj = iter.next(); if (obj instanceof X509Store) { X509Store certStore = (X509Store) obj; try { certs.addAll(certStore.getMatches(certSelect)); } catch (StoreException e) { throw new AnnotatedException("Problem while picking certificates from X.509 store.", e); } } else { CertStore certStore = (CertStore) obj; try { certs.addAll(certStore.getCertificates(certSelect)); } catch (CertStoreException e) { throw new AnnotatedException( "Problem while picking certificates from certificate store.", e); } } } return certs; }
/** * Merges the context of a dependency into this one by adding the contents of all of its * attributes. */ public Builder mergeDependentContext(CppCompilationContext otherContext) { Preconditions.checkNotNull(otherContext); compilationPrerequisites.addAll(otherContext.getTransitiveCompilationPrerequisites()); includeDirs.addAll(otherContext.getIncludeDirs()); quoteIncludeDirs.addAll(otherContext.getQuoteIncludeDirs()); systemIncludeDirs.addAll(otherContext.getSystemIncludeDirs()); declaredIncludeDirs.addTransitive(otherContext.getDeclaredIncludeDirs()); declaredIncludeWarnDirs.addTransitive(otherContext.getDeclaredIncludeWarnDirs()); declaredIncludeSrcs.addTransitive(otherContext.getDeclaredIncludeSrcs()); pregreppedHdrs.addTransitive(otherContext.getPregreppedHeaders()); moduleInfo.addTransitive(otherContext.moduleInfo); picModuleInfo.addTransitive(otherContext.picModuleInfo); NestedSet<Artifact> othersTransitiveModuleMaps = otherContext.getTransitiveModuleMaps(); NestedSet<Artifact> othersDirectModuleMaps = otherContext.getDirectModuleMaps(); // Forward transitive information. // The other target's transitive module maps do not include its direct module maps, so we // add both. transitiveModuleMaps.addTransitive(othersTransitiveModuleMaps); transitiveModuleMaps.addTransitive(othersDirectModuleMaps); // All module maps of direct dependencies are inputs to the current compile independently of // the build type. if (otherContext.getCppModuleMap() != null) { directModuleMaps.add(otherContext.getCppModuleMap().getArtifact()); } defines.addAll(otherContext.getDefines()); return this; }
/** * Returns the list of feed item IDs that are used by a campaign through a given campaign feed. */ private static Set<Long> getFeedItemIdsForCampaign(CampaignFeed campaignFeed) throws Exception { Set<Long> feedItemIds = Sets.newHashSet(); FunctionOperator functionOperator = campaignFeed.getMatchingFunction().getOperator(); if (FunctionOperator.IN.equals(functionOperator)) { // Check if matchingFunction is of the form IN(FEED_ITEM_ID,{xxx,xxx}). // Extract feed items if applicable. feedItemIds.addAll(getFeedItemIdsFromArgument(campaignFeed.getMatchingFunction())); } else if (FunctionOperator.AND.equals(functionOperator)) { for (FunctionArgumentOperand argument : campaignFeed.getMatchingFunction().getLhsOperand()) { // Check if matchingFunction is of the form IN(FEED_ITEM_ID,{xxx,xxx}). // Extract feed items if applicable. if (argument instanceof FunctionOperand) { FunctionOperand operand = (FunctionOperand) argument; if (FunctionOperator.IN.equals(operand.getValue().getOperator())) { feedItemIds.addAll(getFeedItemIdsFromArgument(operand.getValue())); } } } } else { // There are no other matching functions involving feed item IDs. } return feedItemIds; }
/** * Prints a usage message to the given stream. * * @param out The output stream to write to. */ public void printUsage(OutputStream out) { Formatter formatter = new Formatter(out); Set<CommandLineOption> orderedOptions = new TreeSet<CommandLineOption>(new OptionComparator()); orderedOptions.addAll(optionsByString.values()); Map<String, String> lines = new LinkedHashMap<String, String>(); for (CommandLineOption option : orderedOptions) { Set<String> orderedOptionStrings = new TreeSet<String>(new OptionStringComparator()); orderedOptionStrings.addAll(option.getOptions()); List<String> prefixedStrings = new ArrayList<String>(); for (String optionString : orderedOptionStrings) { if (optionString.length() == 1) { prefixedStrings.add("-" + optionString); } else { prefixedStrings.add("--" + optionString); } } lines.put(GUtil.join(prefixedStrings, ", "), GUtil.elvis(option.getDescription(), "")); } int max = 0; for (String optionStr : lines.keySet()) { max = Math.max(max, optionStr.length()); } for (Map.Entry<String, String> entry : lines.entrySet()) { if (entry.getValue().length() == 0) { formatter.format("%s%n", entry.getKey()); } else { formatter.format("%-" + max + "s %s%n", entry.getKey(), entry.getValue()); } } formatter.flush(); }
/** * This method gets all relevant facets. It behaves differently from a simple getFacets() call in * that enumerations are not congealed. */ public static Set getUsefulFacets(XSDSimpleTypeDefinition type) { Set rv = new HashSet(); Iterator itor = type.getFacets().iterator(); while (itor.hasNext()) { XSDConstrainingFacet facet = (XSDConstrainingFacet) itor.next(); if (facet instanceof XSDRepeatableFacet && facet.getElement() == null) { // this is a fake pattern or enum; get the individual entries: if (facet instanceof XSDPatternFacet) { XSDPatternFacet pf = (XSDPatternFacet) facet; XSDSimpleTypeDefinition realParent = (XSDSimpleTypeDefinition) pf.getContainer(); // only add patterns if they belong to this type: if (realParent == type) { rv.addAll(realParent.getPatternFacets()); } // endif } else if (facet instanceof XSDEnumerationFacet) { XSDEnumerationFacet ef = (XSDEnumerationFacet) facet; XSDSimpleTypeDefinition realParent = (XSDSimpleTypeDefinition) ef.getContainer(); // only add enums if they belong to this type: if (realParent == type) { rv.addAll(realParent.getEnumerationFacets()); } // endif } // endif -- which kind of repeatable? } else { rv.add(facet); } // endif -- fake facet } // endwhile -- facets return rv; }
/** @return Collection of IClasses, representing the interfaces this class implements. */ protected Collection<IClass> computeAllInterfacesAsCollection() { Collection<? extends IClass> c = getDirectInterfaces(); Set<IClass> result = HashSetFactory.make(); for (Iterator<? extends IClass> it = c.iterator(); it.hasNext(); ) { IClass klass = it.next(); if (klass.isInterface()) { result.add(klass); } else { Warnings.add(ClassHierarchyWarning.create("expected an interface " + klass)); } } // at this point result holds all interfaces the class directly extends. // now expand to a fixed point. Set<IClass> last = null; do { last = HashSetFactory.make(result); for (IClass i : last) { result.addAll(i.getDirectInterfaces()); } } while (last.size() < result.size()); // now add any interfaces implemented by the super class IClass sup = null; sup = getSuperclass(); if (sup != null) { result.addAll(sup.getAllImplementedInterfaces()); } return result; }
@Override public String analyze(Iterable<Mutation> mutations, HtmlReport report) { List<String> lines = new ArrayList<String>(); for (Mutation mutation : mutations) { if (mutation.isKilled()) { MutationTestResult result = mutation.getMutationResult(); Set<TestMessage> detecting = new HashSet<TestMessage>(); Collection<TestMessage> failures = result.getFailures(); detecting.addAll(failures); Collection<TestMessage> errors = result.getErrors(); detecting.addAll(errors); String tests = getIds(detecting); String line = mutation.getId() + "," + tests; lines.add(line); } } Set<Entry<String, Integer>> entrySet = testsIds.entrySet(); lines.add("Ids"); for (Entry<String, Integer> entry : entrySet) { lines.add(entry.getKey() + "," + entry.getValue()); } try { FileUtils.writeLines(new File("detectedByTest.csv"), lines); } catch (IOException e) { e.printStackTrace(); } return Joiner.on("\n").join(lines); }
public Set<Integer> parseRanges(Collection<String> ranges) { Set<Integer> result = new TreeSet<>(); for (String range : ranges) { range = range.trim(); if (range.isEmpty()) { continue; } Matcher matcher; if (SINGLE_YEAR_PATTERN.matcher(range).matches()) { result.add(Integer.parseInt(range)); } else if ((matcher = FULL_RANGE_YEAR_PATTERN.matcher(range)).matches()) { result.addAll( range(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)))); } else if ((matcher = SHORTEN_RANGE_YEAR_PATTERN.matcher(range)).matches()) { int start = Integer.parseInt(matcher.group(1)); int end = Integer.parseInt(matcher.group(1).substring(0, 2) + matcher.group(2)); result.addAll(range(start, end)); } else if ((matcher = LIST_YEAR_PATTERN.matcher(range)).matches()) { // 1989,1990,1991 String[] years = matcher.group(0).split(","); for (String year : years) { result.add(Integer.parseInt(year)); } } else if ((matcher = FOUR_DIGIT_YEAR_PATTERN.matcher(range)).find()) { int year = Integer.parseInt(matcher.group(0)); if (year == 9999) year = MAX_YEAR; result.add(year); } else { // logger.warn("Range '{}' not matched", range); } } return result; }
private void performImport() { FileDialog dialog = new FileDialog(this.fDialog.getShell(), SWT.OPEN); dialog.setText("Export environment variables to file"); String file = dialog.open(); if (file != null) { File handle = new File(file); if (!handle.exists()) { String text = "Selected file not exists."; showErrorMessage("Environment import", text); return; } EnvironmentVariable[] vars = null; try { vars = EnvironmentVariablesFileUtils.load(file); } catch (Exception e) { showErrorMessage("Environment import", e.getMessage()); } if (vars != null) { EnvironmentVariable[] variables = this.fEnvironmentVariablesContentProvider.getVariables(); Set nvars = new HashSet(); nvars.addAll(Arrays.asList(vars)); nvars.addAll(Arrays.asList(variables)); this.fEnvironmentVariablesContentProvider.setVariables( (EnvironmentVariable[]) nvars.toArray(new EnvironmentVariable[nvars.size()])); } } }
/** * Generates a List of unique identifiers for campaigns based on the parameters. The List is based * on the 'campaignIds' parameter unless it is null in which case the List is based on all * campaigns visible to the user. All parameters except 'request' and 'username' are optional and * each will filter the resulting List of campaign identifiers.<br> * <br> * <br> * For example, if 'campaignIds' was null as were 'endDate' and 'privacyState', then what would be * returned would be the intersection of the following lists:<br> * - All of the campaigns to which the user was associated (because 'campaignIds' was null).<br> * - All of the campaigns that are associated with any of the classes whose unique identifier was * in the 'classIds' list.<br> * - All of the campaigns whose creation timestamp was equal to or after 'startDate'<br> * - All of the campaigns whose running state equaled 'runningState'.<br> * - All of the campaigns to which the user had the campaign role 'role'. <br> * <br> * Therefore, if a campaign was associated with a user only through a single class, but that class * wasn't in the 'classIds' list, then that campaign ID would not be returned even if all of the * other parameters matched. * * @param request The Request that is performing this service. * @param username The username of the user. * @param campaignIds An optional Collection of campaign identifiers from which to base the List. * If this is empty, the resulting List will be empty. If this is null, the base List will be * all campaigns to which the user is associated. * @param classIds A Collection of unique identifiers for classes where the resulting list will * only contain campaign identifiers for campaigns that are associated with any of these * classes. * @param startDate A Calendar where only campaigns whose creation timestamp is equal to or after * this date. * @param endDate A Calendar where only campaigns whose creation timestamp is equal to or before * this date. * @param privacyState A campaign privacy state that trims the resulting list of campaigns to only * those that have this privacy state. * @param runningState A campaign running state that trims the resulting list of campaigns to only * those that have this running state. * @param role A campaign role that trims the resulting list of campaigns to only those where the * user has that role in the campaign. * @return A List of campaign unique identifiers based on the 'campaignIds' parameter and trimmed * by the rest of the parameters. * @throws ServiceException Thrown if there is an error. */ public static List<String> getCampaignsForUser( Request request, String username, Collection<String> campaignIds, Collection<String> classIds, Calendar startDate, Calendar endDate, CampaignPrivacyStateCache.PrivacyState privacyState, CampaignRunningStateCache.RunningState runningState, CampaignRoleCache.Role role) throws ServiceException, DataAccessException { Set<String> desiredCampaignIds = new HashSet<String>(); if (campaignIds == null) { // Initializes the list with all of the campaign IDs for the // requesting user. desiredCampaignIds.addAll(UserCampaignDaos.getCampaignIdsAndNameForUser(username).keySet()); } else { // Initializes the list with the campaign IDs in the query. desiredCampaignIds.addAll(campaignIds); } if (classIds != null) { // Get all of the campaigns associated with all of the classes in // the list. for (String classId : classIds) { desiredCampaignIds.retainAll(CampaignClassDaos.getCampaignsAssociatedWithClass(classId)); } } if (startDate != null) { // Get all of the campaigns whose creation timestamp is greater // than or equal to the start date. desiredCampaignIds.retainAll(CampaignDaos.getCampaignsOnOrAfterDate(startDate)); } if (endDate != null) { // Get all of the campaigns whose creation timestamp is less than // or equal to the end date. desiredCampaignIds.retainAll(CampaignDaos.getCampaignsOnOrBeforeDate(endDate)); } if (privacyState != null) { // Get all of the campaigns with a privacy state of 'privacyState'. desiredCampaignIds.retainAll(CampaignDaos.getCampaignsWithPrivacyState(privacyState)); } if (runningState != null) { // Get all of the campaigns with a running state of 'runningState'. desiredCampaignIds.retainAll(CampaignDaos.getCampaignsWithRunningState(runningState)); } if (role != null) { // Get all of the campaigns where the user's role is 'role'. desiredCampaignIds.retainAll(UserCampaignDaos.getCampaignIdsForUserWithRole(username, role)); } return new ArrayList<String>(desiredCampaignIds); }
// fills collections with of imported languages and devkits. // Languages include directly imported and coming immediately through devkits; listed devkits are // imported directly, without those they extend (why?). public LangAndDevkits collectLanguagesAndDevkits() { Set<SLanguage> usedLanguages = new LinkedHashSet<>(); Set<SModuleReference> devkits = new LinkedHashSet<>(); // perhaps, shall introduce ModuleImports similar to ModelImports to accomplish this? for (SModel m : getModels()) { final SModelInternal modelInternal = (SModelInternal) m; usedLanguages.addAll(modelInternal.importedLanguageIds()); devkits.addAll(modelInternal.importedDevkits()); } // XXX why don't we respect extended devkits here? final SRepository repository = getRepository(); if (repository != null) { for (SModuleReference devkitRef : devkits) { final SModule module = devkitRef.resolve(repository); if (module instanceof DevKit) { for (SLanguage l : ((DevKit) module).getAllExportedLanguageIds()) { usedLanguages.add(l); } } } } usedLanguages.add(BootstrapLanguages.getLangCore()); return new LangAndDevkits(usedLanguages, devkits); }
@Override public Collection<Term> getVariableTerms() { Set<Term> r = new HashSet<Term>(); r.addAll(from.getVariableTerms()); r.addAll(to.getVariableTerms()); return r; }