Java Code Examples for com.intellij.util.containers.ContainerUtil

The following are top voted examples for showing how to use com.intellij.util.containers.ContainerUtil. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: nullability-annotations-inspection   File: NullabilityAnnotationsWithTypeQualifierDefault.java   View source code 6 votes vote down vote up
private static boolean isNullabilityAnnotationForTypeQualifierDefault(PsiAnnotation annotation,
                                                                      boolean nullable,
                                                                      PsiAnnotation.TargetType[] targetTypes) {
    PsiJavaCodeReferenceElement element = annotation.getNameReferenceElement();
    PsiElement declaration = element == null ? null : element.resolve();
    if (!(declaration instanceof PsiClass)) {
        return false;
    }

    String fqn = nullable ? JAVAX_ANNOTATION_NULLABLE : JAVAX_ANNOTATION_NONNULL;
    PsiClass classDeclaration = (PsiClass) declaration;
    if (!AnnotationUtil.isAnnotated(classDeclaration, fqn, false, true)) {
        return false;
    }

    PsiAnnotation tqDefault = AnnotationUtil.findAnnotation(classDeclaration, true, TYPE_QUALIFIER_DEFAULT);
    if (tqDefault == null) {
        return false;
    }

    Set<PsiAnnotation.TargetType> required = extractRequiredAnnotationTargets(tqDefault.findAttributeValue(null));
    return required != null
            && (required.isEmpty() || ContainerUtil.intersects(required, Arrays.asList(targetTypes)));
}
 
Example 2
Project: hybris-integration-intellij-idea-plugin   File: DefaultSpringConfigurator.java   View source code 6 votes vote down vote up
@Override
public void configureDependencies(
    final @NotNull HybrisProjectDescriptor hybrisProjectDescriptor,
    final @NotNull IdeModifiableModelsProvider modifiableModelsProvider
) {
    final Map<String, ModifiableFacetModel> modifiableFacetModelMap = ContainerUtil.newHashMap();

    for (Module module : modifiableModelsProvider.getModules()) {
        final ModifiableFacetModel modifiableFacetModel = modifiableModelsProvider.getModifiableFacetModel(module);
        modifiableFacetModelMap.put(module.getName(), modifiableFacetModel);
    }

    for (HybrisModuleDescriptor moduleDescriptor : hybrisProjectDescriptor.getModulesChosenForImport()) {
        configureFacetDependencies(moduleDescriptor, modifiableFacetModelMap);
    }
}
 
Example 3
Project: hybris-integration-intellij-idea-plugin   File: FSKeywords.java   View source code 6 votes vote down vote up
/**
 * @return set of keywords.
 */
public static Set<String> topLevelKeywords() {
    return ContainerUtil.newHashSet(
        "SELECT",
        "FROM",
        "WHERE",
        "ORDER",

        // Temporarily place this
        "LEFT",
        "JOIN",
        "ON",

        "BY",
        "ASC",
        "DESC"
    );
}
 
Example 4
Project: hybris-integration-intellij-idea-plugin   File: StatsRequest.java   View source code 6 votes vote down vote up
@Override
public StatsResponse call() throws Exception {
    final RequestConfig.Builder builder = RequestConfig
        .custom()
        .setConnectTimeout(TIMEOUT)
        .setConnectionRequestTimeout(TIMEOUT)
        .setSocketTimeout(TIMEOUT);
    IdeHttpClientHelpers.ApacheHttpClient4.setProxyForUrlIfEnabled(builder, HybrisConstants.STATS_COLLECTOR_URL);
    final RequestConfig config = builder.build();
    final HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();

    final List<NameValuePair> patchedUrlParameters = ContainerUtil.newArrayList(urlParameters);
    patchUrlParameters(patchedUrlParameters);
    final HttpPost post = new HttpPost(HybrisConstants.STATS_COLLECTOR_URL);
    post.setEntity(new UrlEncodedFormEntity(patchedUrlParameters, UTF_8));
    return new StatsResponse(client.execute(post));
}
 
Example 5
Project: hybris-integration-intellij-idea-plugin   File: ImpexMacrosReferenceBase.java   View source code 6 votes vote down vote up
@NotNull
@Override
public ResolveResult[] multiResolve(final boolean incompleteCode) {
    final PsiFile originalFile = getElement().getContainingFile();

    final Collection<ImpexMacroDeclaration> macroDeclarations =
        PsiTreeUtil.findChildrenOfType(
            originalFile,
            ImpexMacroDeclaration.class
        );

    if (!macroDeclarations.isEmpty()) {
        final ArrayList<PsiElement> references = ContainerUtil.newArrayList();
        for (final ImpexMacroDeclaration declaration : macroDeclarations) {
            if (getElement().textMatches(declaration.getFirstChild())) {
                references.add(declaration.getFirstChild());
            }
        }
        return PsiElementResolveResult.createResults(references);
    }
    return ResolveResult.EMPTY_ARRAY;
}
 
Example 6
Project: intellij-csv-validator   File: CsvFormatterTest.java   View source code 6 votes vote down vote up
private void executeTestConfiguration(int binarySettings, String relativeTargetPath, boolean checkResults) {
    if (relativeTargetPath == null || relativeTargetPath.isEmpty()) {
        relativeTargetPath = ".";
    }

    myFixture.configureByFiles(relativeTargetPath + "/TestData.csv");

    initCsvCodeStyleSettings(binarySettings);

    new WriteCommandAction.Simple(getProject()) {
        @Override
        protected void run() throws Throwable {
            CodeStyleManager.getInstance(getProject()).reformatText(myFixture.getFile(),
                    ContainerUtil.newArrayList(myFixture.getFile().getTextRange()));
        }
    }.execute();
    if (checkResults) {
        myFixture.checkResultByFile(relativeTargetPath + String.format("/TestResult%08d.csv", binarySettings));
    }
}
 
Example 7
Project: intellij-csv-validator   File: CsvFormatterTest.java   View source code 6 votes vote down vote up
/**
 * This function should be executed (remove the underscore) if the current results are correct (manual testing).
 *
 * @throws Exception
 */
public void _testResultGenerator() throws Exception {
    for (int binarySettings = 0; binarySettings < 128; ++binarySettings) {
        tearDown();
        setUp();

        myFixture.configureByFiles("/generated/TestData.csv");

        initCsvCodeStyleSettings(binarySettings);

        new WriteCommandAction.Simple(getProject()) {
            @Override
            protected void run() throws Throwable {
                CodeStyleManager.getInstance(getProject()).reformatText(myFixture.getFile(),
                        ContainerUtil.newArrayList(myFixture.getFile().getTextRange()));
            }
        }.execute();

        try (PrintWriter writer = new PrintWriter(getTestDataPath() + String.format("/generated/TestResult%08d.csv", binarySettings))
        ) {
            writer.print(myFixture.getFile().getText());
        }
    }
}
 
Example 8
Project: MultiHighlight   File: ColorChooserPanel.java   View source code 6 votes vote down vote up
@Override
public void reset(@NotNull TextAttributes ta) {
    myCbBold.setEnabled(true);
    myCbItalic.setEnabled(true);

    int fontType = ta.getFontType();
    myCbBold.setSelected(BitUtil.isSet(fontType, Font.BOLD));
    myCbItalic.setSelected(BitUtil.isSet(fontType, Font.ITALIC));

    resetColorChooser(myCbForeground, myForegroundChooser, ta.getForegroundColor());
    resetColorChooser(myCbBackground, myBackgroundChooser, ta.getBackgroundColor());
    resetColorChooser(myCbErrorStripe, myErrorStripeColorChooser, ta.getErrorStripeColor());

    Color effectColor = ta.getEffectColor();
    resetColorChooser(myCbEffects, myEffectsColorChooser, effectColor);

    if (effectColor == null) {
        myEffectsCombo.setEnabled(false);
    } else {
        myEffectsCombo.setEnabled(true);
        myEffectsModel.setSelectedItem(
                ContainerUtil.reverseMap(myEffectsMap).get(ta.getEffectType()));
    }
}
 
Example 9
Project: intellij-ce-playground   File: HgCommitCommand.java   View source code 6 votes vote down vote up
protected void executeChunked(@NotNull List<List<String>> chunkedCommits) throws HgCommandException, VcsException {
  if (chunkedCommits.isEmpty()) {
    commitChunkFiles(ContainerUtil.<String>emptyList(), myAmend, myCloseBranch);
  }
  else {
    int size = chunkedCommits.size();
    if (myShouldCommitWithSubrepos && myRepository.hasSubrepos()) {
      mySubrepos = HgUtil.getNamesWithoutHashes(myRepository.getSubrepos());
    }
    commitChunkFiles(chunkedCommits.get(0), myAmend, !mySubrepos.isEmpty(), myCloseBranch && size == 1);
    HgVcs vcs = HgVcs.getInstance(myProject);
    boolean amendCommit = vcs != null && vcs.getVersion().isAmendSupported();
    for (int i = 1; i < size; i++) {
      List<String> chunk = chunkedCommits.get(i);
      commitChunkFiles(chunk, amendCommit, false, myCloseBranch && i == size - 1);
    }
  }
}
 
Example 10
Project: intellij-ce-playground   File: FileNameCacheMicroBenchmark.java   View source code 6 votes vote down vote up
private static long runThreads(final int[] ids, int threadCount, final int queryCount, final TestIteration testIteration) throws InterruptedException, ExecutionException {
  long start = System.currentTimeMillis();
  List<Future<?>> futures = ContainerUtil.newArrayList();
  Random seedRandom = new Random();
  for (int i = 0; i < threadCount; i++) {
    final Random threadRandom = new Random(seedRandom.nextInt());
    final int finalI = i;
    futures.add(ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
      @Override
      public void run() {
        testIteration.doTest(finalI, ids, threadRandom, queryCount);
      }
    }));
  }
  for (Future<?> future : futures) {
    future.get();
  }
  return System.currentTimeMillis() - start;
}
 
Example 11
Project: intellij-ce-playground   File: HighlightInfo.java   View source code 6 votes vote down vote up
public void registerFix(@Nullable IntentionAction action,
                        @Nullable List<IntentionAction> options,
                        @Nullable String displayName,
                        @Nullable TextRange fixRange,
                        @Nullable HighlightDisplayKey key) {
  if (action == null) return;
  if (fixRange == null) fixRange = new TextRange(startOffset, endOffset);
  if (quickFixActionRanges == null) {
    quickFixActionRanges = ContainerUtil.createLockFreeCopyOnWriteList();
  }
  IntentionActionDescriptor desc = new IntentionActionDescriptor(action, options, displayName, null, key, getProblemGroup(), getSeverity());
  quickFixActionRanges.add(Pair.create(desc, fixRange));
  fixStartOffset = Math.min (fixStartOffset, fixRange.getStartOffset());
  fixEndOffset = Math.max (fixEndOffset, fixRange.getEndOffset());
  if (action instanceof HintAction) {
    setHint(true);
  }
}
 
Example 12
Project: intellij-ce-playground   File: ExternalSystemViewDefaultContributor.java   View source code 6 votes vote down vote up
@Override
@NotNull
public List<ExternalSystemNode<?>> createNodes(final ExternalProjectsView externalProjectsView,
                                               final MultiMap<Key<?>, DataNode<?>> dataNodes) {
  final List<ExternalSystemNode<?>> result = new SmartList<ExternalSystemNode<?>>();

  addModuleNodes(externalProjectsView, dataNodes, result);
  // add tasks
  TasksNode tasksNode = new TasksNode(externalProjectsView, dataNodes.get(ProjectKeys.TASK));
  if(externalProjectsView.useTasksNode()) {
    result.add(tasksNode);
  } else {
    ContainerUtil.addAll(result, tasksNode.getChildren());
  }

  addDependenciesNode(externalProjectsView, dataNodes, result);

  return result;
}
 
Example 13
Project: intellij-ce-playground   File: ConfirmingTrustManager.java   View source code 6 votes vote down vote up
/**
 * Select all available certificates from underlying trust store. Returned list is not supposed to be modified.
 *
 * @return certificates
 */
public List<X509Certificate> getCertificates() {
  myReadLock.lock();
  try {
    List<X509Certificate> certificates = new ArrayList<X509Certificate>();
    for (String alias : Collections.list(myKeyStore.aliases())) {
      certificates.add(getCertificate(alias));
    }
    return ContainerUtil.immutableList(certificates);
  }
  catch (Exception e) {
    LOG.error(e);
    return ContainerUtil.emptyList();
  }
  finally {
    myReadLock.unlock();
  }
}
 
Example 14
Project: intellij-ce-playground   File: AndroidDslContributor.java   View source code 6 votes vote down vote up
private void logClassPathOnce(@NotNull Project project) {
  List<VirtualFile> files = GradleBuildClasspathManager.getInstance(project).getAllClasspathEntries();
  if (ContainerUtil.equalsIdentity(files, myLastClassPath)) {
    return;
  }
  myLastClassPath = files;

  List<String> paths = ContainerUtil.map(files, new NotNullFunction<VirtualFile, String>() {
    @NotNull
    @Override
    public String fun(VirtualFile vf) {
      return vf.getPath();
    }
  });
  String classPath = Joiner.on(':').join(paths);
  LOG.info(String.format("Android DSL resolver classpath (project %1$s): %2$s", project.getName(), classPath));
}
 
Example 15
Project: intellij-ce-playground   File: DomElementAnnotationHolderImpl.java   View source code 6 votes vote down vote up
private LocalQuickFix[] getQuickFixes(final GenericDomValue element, PsiReference reference) {
  if (!myOnTheFly) return LocalQuickFix.EMPTY_ARRAY;

  final List<LocalQuickFix> result = new SmartList<LocalQuickFix>();
  final Converter converter = WrappingConverter.getDeepestConverter(element.getConverter(), element);
  if (converter instanceof ResolvingConverter) {
    final ResolvingConverter resolvingConverter = (ResolvingConverter)converter;
    ContainerUtil
      .addAll(result, resolvingConverter.getQuickFixes(ConvertContextFactory.createConvertContext(DomManagerImpl.getDomInvocationHandler(element))));
  }
  if (reference instanceof LocalQuickFixProvider) {
    final LocalQuickFix[] localQuickFixes = ((LocalQuickFixProvider)reference).getQuickFixes();
    if (localQuickFixes != null) {
      ContainerUtil.addAll(result, localQuickFixes);
    }
  }
  return result.isEmpty() ? LocalQuickFix.EMPTY_ARRAY : result.toArray(new LocalQuickFix[result.size()]);
}
 
Example 16
Project: intellij-ce-playground   File: CoreJavaDirectoryService.java   View source code 6 votes vote down vote up
@NotNull
public static PsiClass[] getPsiClasses(@NotNull PsiDirectory dir, PsiFile[] psiFiles) {
  FileIndexFacade index = FileIndexFacade.getInstance(dir.getProject());
  VirtualFile virtualDir = dir.getVirtualFile();
  boolean onlyCompiled = index.isInLibraryClasses(virtualDir) && !index.isInSourceContent(virtualDir);

  List<PsiClass> classes = null;
  for (PsiFile file : psiFiles) {
    if (onlyCompiled && !(file instanceof ClsFileImpl)) {
      continue;
    }
    if (file instanceof PsiClassOwner && file.getViewProvider().getLanguages().size() == 1) {
      PsiClass[] psiClasses = ((PsiClassOwner)file).getClasses();
      if (psiClasses.length == 0) continue;
      if (classes == null) classes = new ArrayList<PsiClass>();
      ContainerUtil.addAll(classes, psiClasses);
    }
  }
  return classes == null ? PsiClass.EMPTY_ARRAY : classes.toArray(new PsiClass[classes.size()]);
}
 
Example 17
Project: intellij-ce-playground   File: LayoutTree.java   View source code 6 votes vote down vote up
public List<PackagingElementNode<?>> findNodes(final Collection<? extends PackagingElement<?>> elements) {
  final List<PackagingElementNode<?>> nodes = new ArrayList<PackagingElementNode<?>>();
  TreeUtil.traverseDepth(getRootNode(), new TreeUtil.Traverse() {
    @Override
    public boolean accept(Object node) {
      final Object userObject = ((DefaultMutableTreeNode)node).getUserObject();
      if (userObject instanceof PackagingElementNode) {
        final PackagingElementNode<?> packagingNode = (PackagingElementNode<?>)userObject;
        final List<? extends PackagingElement<?>> nodeElements = packagingNode.getPackagingElements();
        if (ContainerUtil.intersects(nodeElements, elements)) {
          nodes.add(packagingNode);
        }
      }
      return true;
    }
  });
  return nodes;
}
 
Example 18
Project: intellij-ce-playground   File: RecentProjectsManagerBase.java   View source code 6 votes vote down vote up
protected void doReopenLastProject() {
  GeneralSettings generalSettings = GeneralSettings.getInstance();
  if (generalSettings.isReopenLastProject()) {
    Set<String> openPaths;
    boolean forceNewFrame = true;
    synchronized (myStateLock) {
      openPaths = ContainerUtil.newLinkedHashSet(myState.openPaths);
      if (openPaths.isEmpty()) {
        openPaths = ContainerUtil.createMaybeSingletonSet(myState.lastPath);
        forceNewFrame = false;
      }
    }
    for (String openPath : openPaths) {
      if (isValidProjectPath(openPath)) {
        doOpenProject(openPath, null, forceNewFrame);
      }
    }
  }
}
 
Example 19
Project: intellij-ce-playground   File: AntDomTargetReference.java   View source code 6 votes vote down vote up
@NotNull
public Object[] getVariants() {
  final TargetResolver.Result result = doResolve(getCanonicalText());
  if (result == null) {
    return EMPTY_ARRAY;
  }
  final Map<String, AntDomTarget> variants = result.getVariants();                                                                          
  final List resVariants = new ArrayList();
  final Set<String> existing = getExistingNames();
  for (String s : variants.keySet()) {
    if (existing.contains(s)){
      continue;
    }
    final LookupElementBuilder builder = LookupElementBuilder.create(s).withCaseSensitivity(false);
    final LookupElement element = AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE.applyPolicy(builder);
    resVariants.add(element);
  }
  return ContainerUtil.toArray(resVariants, new Object[resVariants.size()]);
}
 
Example 20
Project: intellij-ce-playground   File: XmlEmmetParser.java   View source code 6 votes vote down vote up
@NotNull
private Map<String, String> parseSelectors() {
  final Map<String, String> result = ContainerUtil.newLinkedHashMap();
  List<Couple<String>> attrList = parseSelector();
  while (attrList != null) {
    for (Couple<String> attr : attrList) {
      if (getClassAttributeName().equals(attr.first)) {
        result.put(getClassAttributeName(), (StringUtil.notNullize(result.get(getClassAttributeName())) + " " + attr.second).trim());
      }
      else if (HtmlUtil.ID_ATTRIBUTE_NAME.equals(attr.first)) {
        result.put(HtmlUtil.ID_ATTRIBUTE_NAME, (StringUtil.notNullize(result.get(HtmlUtil.ID_ATTRIBUTE_NAME)) + " " + attr.second).trim());
      }
      else {
        result.put(attr.first, attr.second);
      }
    }
    attrList = parseSelector();
  }
  return result;
}
 
Example 21
Project: intellij-ce-playground   File: FileIncludeManagerImpl.java   View source code 6 votes vote down vote up
@Override
protected VirtualFile[] computeFiles(final PsiFile file, final boolean compileTimeOnly) {
  final Set<VirtualFile> files = new THashSet<VirtualFile>();
  processIncludes(file, new Processor<FileIncludeInfo>() {
    @Override
    public boolean process(FileIncludeInfo info) {
      if (compileTimeOnly != info.runtimeOnly) {
        PsiFileSystemItem item = resolveFileInclude(info, file);
        if (item != null) {
          ContainerUtil.addIfNotNull(files, item.getVirtualFile());
        }
      }
      return true;
    }

  });
  return VfsUtilCore.toVirtualFileArray(files);
}
 
Example 22
Project: intellij-ce-playground   File: UnusedPropertyInspection.java   View source code 6 votes vote down vote up
@Nullable
private static GlobalSearchScope getWidestUseScope(@Nullable String key, @NotNull Project project, @NotNull Module ownModule) {
  if (key == null) return null;

  Set<Module> modules = ContainerUtil.newLinkedHashSet();
  for (IProperty property : PropertiesImplUtil.findPropertiesByKey(project, key)) {
    Module module = ModuleUtilCore.findModuleForPsiElement(property.getPsiElement());
    if (module == null) {
      return GlobalSearchScope.allScope(project);
    }
    if (module != ownModule) {
      modules.add(module);
    }
  }
  if (modules.isEmpty()) return null;

  List<Module> list = ContainerUtil.newArrayList(modules);
  GlobalSearchScope result = GlobalSearchScope.moduleWithDependentsScope(list.get(0));
  for (int i = 1; i < list.size(); i++) {
    result = result.uniteWith(GlobalSearchScope.moduleWithDependentsScope(list.get(i)));
  }
  return result;
}
 
Example 23
Project: intellij-ce-playground   File: PluginUpdateInfoDialog.java   View source code 6 votes vote down vote up
public PluginUpdateInfoPanel() {
  myPluginsToUpdateLabel.setVisible(true);
  myPluginsPanel.setVisible(true);

  final DetectedPluginsPanel foundPluginsPanel = new DetectedPluginsPanel();
  foundPluginsPanel.addAll(myUploadedPlugins);
  TableUtil.ensureSelectionExists(foundPluginsPanel.getEntryTable());
  foundPluginsPanel.addStateListener(new DetectedPluginsPanel.Listener() {
    @Override
    public void stateChanged() {
      final Set<String> skipped = foundPluginsPanel.getSkippedPlugins();
      final PluginDownloader any = ContainerUtil.find(myUploadedPlugins, new Condition<PluginDownloader>() {
        @Override
        public boolean value(PluginDownloader plugin) {
          return !skipped.contains(plugin.getPluginId());
        }
      });
      getOKAction().setEnabled(any != null);
    }
  });
  myPluginsPanel.add(foundPluginsPanel, BorderLayout.CENTER);

  configureMessageArea(myMessageArea);
}
 
Example 24
Project: intellij-ce-playground   File: ConfigureTasksActivationDialog.java   View source code 6 votes vote down vote up
private static void moveSelectedRows(@NotNull final SimpleTree tree, final int direction) {
  final TreePath[] selectionPaths = tree.getSelectionPaths();
  if (selectionPaths == null) return;

  ContainerUtil.sort(selectionPaths, new Comparator<TreePath>() {
    @Override
    public int compare(TreePath o1, TreePath o2) {
      return -direction * compare(tree.getRowForPath(o1), tree.getRowForPath(o2));
    }

    private int compare(int x, int y) {
      return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }
  });

  for (TreePath selectionPath : selectionPaths) {
    final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
    final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)treeNode.getParent();
    final int idx = parent.getIndex(treeNode);
    ((DefaultTreeModel)tree.getModel()).removeNodeFromParent(treeNode);
    ((DefaultTreeModel)tree.getModel()).insertNodeInto(treeNode, parent, idx + direction);
  }

  tree.addSelectionPaths(selectionPaths);
}
 
Example 25
Project: intellij-ce-playground   File: DfaUtil.java   View source code 6 votes vote down vote up
private static PsiExpression concatenateExpressions(FList<PsiExpression> concatenation) {
  if (concatenation.size() == 1) {
    return concatenation.getHead();
  }
  String text = StringUtil
    .join(ContainerUtil.reverse(new ArrayList<PsiExpression>(concatenation)), new Function<PsiExpression, String>() {
      @Override
      public String fun(PsiExpression expression) {
        return expression.getText();
      }
    }, "+");
  try {
    return JavaPsiFacade.getElementFactory(concatenation.getHead().getProject()).createExpressionFromText(text, concatenation.getHead());
  }
  catch (IncorrectOperationException e) {
    return concatenation.getHead();
  }
}
 
Example 26
Project: intellij-ce-playground   File: GroovyDslFileIndex.java   View source code 6 votes vote down vote up
private static List<VirtualFile> getProjectGdslFiles(Project project) {
  final List<VirtualFile> result = ContainerUtil.newArrayList();
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  final GlobalSearchScope scope = GlobalSearchScope.allScope(project);

  for (VirtualFile vfile : FileBasedIndex.getInstance().getContainingFiles(NAME, OUR_KEY, scope)) {
    if (!vfile.isValid()) {
      continue;
    }
    if (!GdslUtil.GDSL_FILTER.value(vfile)) {
      LOG.error("Index returned non-gdsl file: " + vfile);
      continue;
    }
    if (fileIndex.isInLibrarySource(vfile)) {
      continue;
    }
    if (!fileIndex.isInLibraryClasses(vfile)) {
      if (!fileIndex.isInSourceContent(vfile) || !isActivated(vfile)) {
        continue;
      }
    }

    result.add(vfile);
  }
  return result;
}
 
Example 27
Project: intellij-ce-playground   File: KeyFMapTest.java   View source code 6 votes vote down vote up
private static void doTestGetKeys(int size) {
  List<Key> keys = ContainerUtil.newArrayList();
  List<Object> values = ContainerUtil.newArrayList();
  for (int i = 0; i < size; i++) {
    keys.add(Key.create("Key#" + i));
    values.add("Value#" + i);
  }

  KeyFMap map = createKeyFMap(keys, values);

  Key[] actualKeys = map.getKeys();

  assertEquals(size, actualKeys.length);

  for (Key key : keys) {
    assertTrue("Key not found: " + key, ArrayUtil.contains(key, actualKeys));
  }
}
 
Example 28
Project: intellij-ce-playground   File: VisiblePackBuilder.java   View source code 6 votes vote down vote up
@Nullable
private Set<Integer> getMatchingHeads(@NotNull VcsLogRefs refs, @NotNull Set<VirtualFile> roots, @NotNull VcsLogFilterCollection filters) {
  VcsLogBranchFilter branchFilter = filters.getBranchFilter();
  VcsLogRootFilter rootFilter = filters.getRootFilter();
  VcsLogStructureFilter structureFilter = filters.getStructureFilter();

  if (branchFilter == null && rootFilter == null && structureFilter == null) return null;

  Set<Integer> filteredByBranch = null;

  if (branchFilter != null) {
    filteredByBranch = getMatchingHeads(refs, branchFilter);
  }

  Set<Integer> filteredByFile = getMatchingHeads(refs, VcsLogUtil
    .getAllVisibleRoots(roots, rootFilter, structureFilter));

  if (filteredByBranch == null) return filteredByFile;
  if (filteredByFile == null) return filteredByBranch;

  return new HashSet<Integer>(ContainerUtil.intersection(filteredByBranch, filteredByFile));
}
 
Example 29
Project: intellij-ce-playground   File: PushController.java   View source code 6 votes vote down vote up
@NotNull
private <R extends Repository, S extends PushSource, T extends PushTarget> List<PushSupport<R, S, T>> getAffectedSupports() {
  Collection<Repository> repositories = myGlobalRepositoryManager.getRepositories();
  Collection<AbstractVcs> vcss = ContainerUtil.map2Set(repositories, new Function<Repository, AbstractVcs>() {
    @Override
    public AbstractVcs fun(@NotNull Repository repository) {
      return repository.getVcs();
    }
  });
  return ContainerUtil.map(vcss, new Function<AbstractVcs, PushSupport<R, S, T>>() {
    @Override
    public PushSupport<R, S, T> fun(AbstractVcs vcs) {
      //noinspection unchecked
      return DvcsUtil.getPushSupport(vcs);
    }
  });
}
 
Example 30
Project: intellij-ce-playground   File: InspectionManagerEx.java   View source code 6 votes vote down vote up
@Nullable
public static SuppressIntentionAction[] getSuppressActions(@NotNull InspectionToolWrapper toolWrapper) {
  final InspectionProfileEntry tool = toolWrapper.getTool();
  if (tool instanceof CustomSuppressableInspectionTool) {
    return ((CustomSuppressableInspectionTool)tool).getSuppressActions(null);
  }
  final List<LocalQuickFix> actions = new ArrayList<LocalQuickFix>(Arrays.asList(tool.getBatchSuppressActions(null)));
  if (actions.isEmpty()) {
    final Language language = Language.findLanguageByID(toolWrapper.getLanguage());
    if (language != null) {
      final List<InspectionSuppressor> suppressors = LanguageInspectionSuppressors.INSTANCE.allForLanguage(language);
      for (InspectionSuppressor suppressor : suppressors) {
        final SuppressQuickFix[] suppressActions = suppressor.getSuppressActions(null, toolWrapper.getID());
        Collections.addAll(actions, suppressActions);
      }
    }
  }
  return ContainerUtil.map2Array(actions, SuppressIntentionAction.class, new Function<LocalQuickFix, SuppressIntentionAction>() {
    @Override
    public SuppressIntentionAction fun(final LocalQuickFix fix) {
      return SuppressIntentionActionFromFix.convertBatchToSuppressIntentionAction((SuppressQuickFix)fix);
    }
  });
}
 
Example 31
Project: intellij-ce-playground   File: GroovyBlockGenerator.java   View source code 6 votes vote down vote up
private void alignSpockTable(List<GrStatement> group) {
  if (group.size() < 2) {
    return;
  }
  GrStatement inner = group.get(0);
  boolean embedded = inner != null && isTablePart(inner);

  GrStatement first = embedded ? inner : group.get(1);
  List<AlignmentProvider.Aligner> alignments = ContainerUtil
    .map2List(getSpockTable(first), new Function<LeafPsiElement, AlignmentProvider.Aligner>() {
      @Override
      public AlignmentProvider.Aligner fun(LeafPsiElement leaf) {
        return myAlignmentProvider.createAligner(leaf, true, Alignment.Anchor.RIGHT);
      }
    });

  int second = embedded ? 1 : 2;
  for (int i = second; i < group.size(); i++) {
    List<LeafPsiElement> table = getSpockTable(group.get(i));
    for (int j = 0; j < Math.min(table.size(), alignments.size()); j++) {
      alignments.get(j).append(table.get(j));
    }
  }
}
 
Example 32
Project: AppleScript-IDEA   File: AppleScriptResolveUtil.java   View source code 5 votes vote down vote up
@NotNull
public static ResolveResult[] toCandidateInfoArray(@Nullable List<? extends PsiElement> elements) {
  if (elements == null) {
    return ResolveResult.EMPTY_ARRAY;
  }
  elements = ContainerUtil.filter(elements, (Condition<PsiElement>) Objects::nonNull);
  final ResolveResult[] result = new ResolveResult[elements.size()];
  for (int i = 0, size = elements.size(); i < size; i++) {
    result[i] = new PsiElementResolveResult(elements.get(i));
  }
  return result;
}
 
Example 33
Project: nullability-annotations-inspection   File: AddPackageInfoWithNullabilityDefaultsFix.java   View source code 5 votes vote down vote up
private void removeRedundantAnnotations(PsiModifierListOwner element,
                                        List<String> redundantAnnotations,
                                        Set<PsiAnnotation.TargetType> targetsForDefaultAnnotation) {
    PsiAnnotation.TargetType[] targetTypes = getTargetsForLocation(element.getModifierList());
    boolean isTargeted = targetsForDefaultAnnotation.isEmpty()
            || ContainerUtil.intersects(targetsForDefaultAnnotation, Arrays.asList(targetTypes));
    if (isTargeted) {
        removePhysicalAnnotations(element, ArrayUtil.toStringArray(redundantAnnotations));
    }
}
 
Example 34
Project: bamboo-soy   File: SoyFormatterTest.java   View source code 5 votes vote down vote up
protected void doTest() throws Throwable {
  myFixture.configureByFiles(getTestName(false) + ".soy");
  new WriteCommandAction.Simple(getProject()) {
    @Override
    protected void run() throws Throwable {
      CodeStyleManager.getInstance(getProject()).reformatText(myFixture.getFile(),
          ContainerUtil.newArrayList(myFixture.getFile().getTextRange()));
    }
  }.execute();
  myFixture.checkResultByFile(getTestName(false) + "_after.soy");
}
 
Example 35
Project: ijphab   File: PhabricatorRepository.java   View source code 5 votes vote down vote up
@Override
public PhabricatorTask[] getIssues(@Nullable String query, int offset, int limit, boolean withClosed) throws Exception {
  // Phabricator will return an error when asked for more than 100 tasks
  int lim = Math.min(limit, 100);
  Params params = new Params()
    .add("queryKey", withClosed ? "all" : "open")
    .add("attachments[projects]", "1")
    .add("limit", String.valueOf(lim));
  // TODO:
  //  .add("offset", String.valueOf(offset));
  if (offset > 0) {
    return new PhabricatorTask[]{};
  }
  if (query != null) {
    Matcher m = TASK_ID.matcher(query);
    if (m.matches()) {
      params.add("constraints[ids][0]", m.group(1));
    } else if (query.length() >= MIN_PHAB_QUERY_LEN) {
      params.add("constraints[query]", query);
    } else {
      return new PhabricatorTask[]{};
    }
  }

  SearchResponse res = apiCall("maniphest.search", SearchResponse.class, params);
  return ContainerUtil
    .map2Array(res.getData(), PhabricatorTask.class, t -> new PhabricatorTask(t, this));
}
 
Example 36
Project: hybris-integration-intellij-idea-plugin   File: ModuleDepDiagramDataModel.java   View source code 5 votes vote down vote up
@NotNull
private Collection<Module> getModulesToShow() {
    final VisibilityLevel visibilityLevel = getVisibilityManager().getCurrentVisibilityLevel();
    final Module[] allModules = myModuleManager.getModules();

    if (ModuleDepDiagramVisibilityManager.LARGE.equals(visibilityLevel)) {
        return Arrays
            .stream(allModules)
            .filter(module -> isCustomExtension(module) || isOotbOrPlatformExtension(module))
            .collect(Collectors.toList());
    }
    final List<Module> customExtModules = Arrays
        .stream(allModules)
        .filter(this::isCustomExtension)
        .collect(Collectors.toList());

    if (ModuleDepDiagramVisibilityManager.SMALL.equals(visibilityLevel)) {
        return customExtModules;
    }
    final List<Module> dependencies = customExtModules
        .stream()
        .flatMap(module -> Arrays.stream(ModuleRootManager.getInstance(module).getDependencies()))
        .filter(this::isOotbOrPlatformExtension)
        .collect(Collectors.toList());

    final List<Module> backwardDependencies = Arrays
        .stream(allModules)
        .filter(module -> Arrays
            .stream(ModuleRootManager.getInstance(module).getDependencies())
            .anyMatch(this::isCustomExtension))
        .filter(this::isOotbOrPlatformExtension)
        .collect(Collectors.toList());

    final Set<Module> result = ContainerUtil.newHashSet();
    result.addAll(customExtModules);
    result.addAll(dependencies);
    result.addAll(backwardDependencies);
    return result;
}
 
Example 37
Project: hybris-integration-intellij-idea-plugin   File: FSKeywords.java   View source code 5 votes vote down vote up
public static Set<String> joinKeywords() {
    return ContainerUtil.newHashSet(
        "LEFT",
        "JOIN",
        "ON"
    );
}
 
Example 38
Project: hybris-integration-intellij-idea-plugin   File: FSKeywords.java   View source code 5 votes vote down vote up
public static Set<String> orderKeywords() {
    return ContainerUtil.newHashSet(
        "BY",
        "ASC",
        "DESC"
    );
}
 
Example 39
Project: hybris-integration-intellij-idea-plugin   File: TSMetaModelBuilder.java   View source code 5 votes vote down vote up
public TSMetaModelBuilder(
    final @NotNull Project project,
    @NotNull final Collection<VirtualFile> filesToExclude
) {
    myProject = project;
    myDomManager = DomManager.getDomManager(project);
    myFilesToExclude = ContainerUtil.newHashSet(filesToExclude);
}
 
Example 40
Project: hybris-integration-intellij-idea-plugin   File: ImpexKeywords.java   View source code 5 votes vote down vote up
/**
 * @return set of keywords.
 */
public static Set<String> keywords() {
    return ContainerUtil.newHashSet(
        "INSERT",
        "UPDATE",
        "INSERT_UPDATE",
        "REMOVE"
    );
}