com.intellij.util.Function Java Examples

The following examples show how to use com.intellij.util.Function. 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: VmwareCloudImage.java    From teamcity-vmware-plugin with Apache License 2.0 6 votes vote down vote up
private void processStoppedInstances(final Function<VmwareInstance, Boolean> function)  {
  myApiConnector.processImageInstances(this, new VMWareApiConnector.VmwareInstanceProcessor() {
    public void process(final VmwareInstance vmInstance) {
      if (vmInstance.getInstanceStatus() == InstanceStatus.STOPPED) {

        final String vmName = vmInstance.getName();
        final VmwareCloudInstance instance = findInstanceById(vmName);

        if (instance == null) {
          LOG.warn("Unable to find instance " + vmName + " in myInstances.");
          return;
        }

        // checking if this instance is already starting.
        if (instance.getStatus() != InstanceStatus.STOPPED)
          return;

        // currently value is ignore
        function.fun(vmInstance);
      }
    }
  });
}
 
Example #2
Source File: CSharpElementPresentationUtil.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nonnull
@RequiredReadAction
public static String formatGenericParameters(@Nonnull final DotNetGenericParameterListOwner owner, @Nonnull final DotNetGenericExtractor extractor)
{
	DotNetGenericParameter[] genericParameters = owner.getGenericParameters();
	if(genericParameters.length == 0)
	{
		return "";
	}
	return "<" + StringUtil.join(genericParameters, new Function<DotNetGenericParameter, String>()
	{
		@Override
		@RequiredReadAction
		public String fun(DotNetGenericParameter genericParameter)
		{
			DotNetTypeRef extract = extractor.extract(genericParameter);
			if(extract != null)
			{
				return CSharpTypeRefPresentationUtil.buildShortText(extract, owner);
			}
			return genericParameter.getName();
		}
	}, ", ") + ">";
}
 
Example #3
Source File: JscsFinder.java    From jscs-plugin with MIT License 6 votes vote down vote up
/**
 * find possible jscs rc files
 * @param projectRoot
 * @return
 */
public static List<String> searchForJscsRCFiles(final File projectRoot) {
    FilenameFilter filter = new FilenameFilter() {
        @Override
        public boolean accept(File file, String name) {
            return name.equals(JSCSRC);
        }
    };
    // return Arrays.asList(files);
    List<String> files = FileUtils.recursiveVisitor(projectRoot, filter);
    return ContainerUtil.map(files, new Function<String, String>() {
        public String fun(String curFile) {
            return FileUtils.makeRelative(projectRoot, new File(curFile));
        }
    });
}
 
Example #4
Source File: VirtualFileVisitorTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Test
public void abort() {
  doTest(
    new Function<VirtualFile, Object>() {
      @Override
      public Object fun(VirtualFile file) {
        if ("f11.1".equals(file.getName())) {
          throw new AbortException();
        }
        return VirtualFileVisitor.CONTINUE;
      }
    },
    null,
    "-> / [0]\n" +
    "  -> d1 [1]\n" +
    "    -> d11 [2]\n" +
    "      -> f11.1 [3]\n");
}
 
Example #5
Source File: FilteredTraverserBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
public Meta(@Nonnull Iterable<? extends T> roots,
            @Nonnull TreeTraversal traversal,
            @Nonnull Cond<T> expand,
            @Nonnull Cond<T> regard,
            @Nonnull Cond<T> filter,
            @Nonnull Cond<T> forceIgnore,
            @Nonnull Cond<T> forceDisregard,
            @Nonnull Function<TreeTraversal, TreeTraversal> interceptor) {
  this.roots = roots;
  this.traversal = traversal;
  this.expand = expand;
  this.regard = regard;
  this.filter = filter;
  this.forceIgnore = forceIgnore;
  this.forceDisregard = forceDisregard;
  this.interceptor = interceptor;
}
 
Example #6
Source File: PantsResolverTestBase.java    From intellij-pants-plugin with Apache License 2.0 6 votes vote down vote up
private ProjectInfo getProjectInfo() {
  final ProjectInfo result = new ProjectInfo();
  result.setTargets(
    PantsUtil.mapValues(
      myInfoBuilders,
      new Function<TargetInfoBuilder, TargetInfo>() {
        @Override
        public TargetInfo fun(TargetInfoBuilder builder) {
          return builder.build();
        }
      }
    )
  );

  final Map<String, LibraryInfo> libraries = new HashMap<>();
  for (TargetInfo targetInfo : result.getTargets().values()) {
    for (String libraryId : targetInfo.getLibraries()) {
      libraries.put(libraryId, new LibraryInfo(libraryId.replace('.', File.separatorChar)));
    }
  }
  result.setLibraries(libraries);
  return result;
}
 
Example #7
Source File: FileTemplateTabAsList.java    From consulo with Apache License 2.0 6 votes vote down vote up
FileTemplateTabAsList(String title) {
  super(title);
  myList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
  myList.setCellRenderer(new MyListCellRenderer());
  myList.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e) {
      onTemplateSelected();
    }
  });
  new ListSpeedSearch(myList, new Function<Object, String>() {
    @Override
    public String fun(final Object o) {
      if (o instanceof FileTemplate) {
        return ((FileTemplate)o).getName();
      }
      return null;
    }
  });
}
 
Example #8
Source File: GeneralCommandLineTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Test
public void argumentsPassing() throws Exception {
  String[] parameters = {
    "with space", "\"quoted\"", "\"quoted with spaces\"", "", "  ", "param 1", "\"", "param2", "trailing slash\\"
  };

  GeneralCommandLine commandLine = makeJavaCommand(ParamPassingTest.class, null);
  commandLine.addParameters(parameters);
  String output = execAndGetOutput(commandLine, null);
  assertEquals("=====\n" + StringUtil.join(parameters, new Function<String, String>() {
    @Override
    public String fun(String s) {
      return ParamPassingTest.format(s);
    }
  }, "\n") + "\n=====\n", StringUtil.convertLineSeparators(output));
}
 
Example #9
Source File: InspectionManagerEx.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public static SuppressIntentionAction[] getSuppressActions(@Nonnull 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, tool.getShortName());
        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 #10
Source File: PushController.java    From consulo with Apache License 2.0 6 votes vote down vote up
private Collection<MyRepoModel<?, ?, ?>> getSelectedRepoNode() {
  if (mySingleRepoProject) {
    return myView2Model.values();
  }
  //return all selected despite a loading state;
  return ContainerUtil.mapNotNull(myView2Model.entrySet(),
                                  new Function<Map.Entry<RepositoryNode, MyRepoModel<?, ?, ?>>, MyRepoModel<?, ?, ?>>() {
                                    @Override
                                    public MyRepoModel fun(Map.Entry<RepositoryNode, MyRepoModel<?, ?, ?>> entry) {
                                      MyRepoModel<?, ?, ?> model = entry.getValue();
                                      return model.isSelected() &&
                                             model.getTarget() != null ? model :
                                             null;
                                    }
                                  });
}
 
Example #11
Source File: HaskellCompletionContributor.java    From intellij-haskforce with Apache License 2.0 6 votes vote down vote up
@Nullable
public static PsiElement getFirstElementWhere(Function<PsiElement, PsiElement> modify,
                                              Function<PsiElement, Boolean> where,
                                              PsiElement initialElement) {
    if (initialElement == null) {
        return null;
    }
    PsiElement result = modify.fun(initialElement);
    while (result != null) {
        if (where.fun(result)) {
            return result;
        }
        result = modify.fun(result);
    }
    return null;
}
 
Example #12
Source File: SelectionHistoryDialogModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
private SelectionCalculator getCalculator() {
  if (myCalculatorCache == null) {
    List<Revision> revisionList = new ArrayList<Revision>();
    revisionList.add(getCurrentRevision());
    
    revisionList.addAll(ContainerUtil.map(getRevisions(), new Function<RevisionItem, Revision>() {
      @Override
      public Revision fun(RevisionItem revisionItem) {
        return revisionItem.revision;
      }
    }));
    myCalculatorCache = new SelectionCalculator(myGateway, revisionList, myFrom, myTo);
  }
  return myCalculatorCache;
}
 
Example #13
Source File: TreeTraversal.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the traversal to skip already visited nodes.
 *
 * @param identity function
 */
@Nonnull
public TreeTraversal unique(@Nonnull final Function<?, ?> identity) {
  final TreeTraversal original = this;
  return new TreeTraversal(debugName + " (UNIQUE)") {

    @Nonnull
    @Override
    public <T> It<T> createIterator(@Nonnull Iterable<? extends T> roots, @Nonnull final Function<T, ? extends Iterable<? extends T>> tree) {
      class WrappedTree implements Condition<T>, Function<T, Iterable<? extends T>> {
        HashSet<Object> visited;

        @Override
        public boolean value(T e) {
          if (visited == null) visited = new HashSet<Object>();
          //noinspection unchecked
          return visited.add(((Function<T, Object>)identity).fun(e));
        }

        @Override
        public Iterable<? extends T> fun(T t) {
          return JBIterable.from(tree.fun(t)).filter(this);
        }
      }
      if (tree instanceof WrappedTree) return original.createIterator(roots, tree);
      WrappedTree wrappedTree = new WrappedTree();
      return original.createIterator(JBIterable.from(roots).filter(wrappedTree), wrappedTree);
    }
  };
}
 
Example #14
Source File: GraphStrUtils.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static <CommitId> String commitsInfoToStr(PermanentCommitsInfo<CommitId> commitsInfo, int size, Function<CommitId, String> toStr) {
  StringBuilder s = new StringBuilder();
  for (int i = 0; i < size; i++) {
    if (i != 0) s.append("\n");

    CommitId commitId = commitsInfo.getCommitId(i);
    int commitIndex = commitsInfo.getNodeId(commitId);
    long timestamp = commitsInfo.getTimestamp(i);

    s.append(commitIndex).append(CommitParser.SEPARATOR);
    s.append(toStr.fun(commitId)).append(CommitParser.SEPARATOR);
    s.append(timestamp);
  }
  return s.toString();
}
 
Example #15
Source File: ExpandableTextField.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an expandable text field with the specified line parser/joiner.
 *
 * @see ParametersListUtil
 */
public ExpandableTextField(@Nonnull Function<? super String, ? extends List<String>> parser, @Nonnull Function<? super List<String>, String> joiner) {
  Function<? super String, String> onShow = text -> StringUtil.join(parser.fun(text), "\n");
  Function<? super String, String> onHide = text -> joiner.fun(asList(StringUtil.splitByLines(text)));
  support = new IntelliJExpandableSupport<JTextComponent>(this, onShow, onHide);

  putClientProperty("monospaced", true);
  setExtensions(createExtensions());
}
 
Example #16
Source File: BaseHaxeGenerateHandler.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
  if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;
  final HaxeClass haxeClass =
    PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), HaxeClassDeclaration.class);
  if (haxeClass == null) return;

  final List<HaxeNamedComponent> candidates = new ArrayList<HaxeNamedComponent>();
  collectCandidates(haxeClass, candidates);

  List<HaxeNamedElementNode> selectedElements = Collections.emptyList();
  if (ApplicationManager.getApplication().isUnitTestMode()) {
    selectedElements = ContainerUtil.map(candidates, new Function<HaxeNamedComponent, HaxeNamedElementNode>() {
      @Override
      public HaxeNamedElementNode fun(HaxeNamedComponent namedComponent) {
        return new HaxeNamedElementNode(namedComponent);
      }
    });
  }
  else if (!candidates.isEmpty()) {
    final MemberChooser<HaxeNamedElementNode> chooser =
      createMemberChooserDialog(project, haxeClass, candidates, getTitle());
    chooser.show();
    selectedElements = chooser.getSelectedElements();
  }

  final BaseCreateMethodsFix createMethodsFix = createFix(haxeClass);
  doInvoke(project, editor, file, selectedElements, createMethodsFix);
}
 
Example #17
Source File: Jsr223IdeScriptEngineManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public List<String> getLanguages() {
  return ContainerUtil.map(getScriptEngineManager().getEngineFactories(), new Function<ScriptEngineFactory, String>() {
    @Override
    public String fun(ScriptEngineFactory factory) {
      return factory.getLanguageName();
    }
  });
}
 
Example #18
Source File: DvcsUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String joinShortNames(@Nonnull Collection<? extends Repository> repositories, int limit) {
  return joinWithAnd(ContainerUtil.map(repositories, new Function<Repository, String>() {
    @Override
    public String fun(@Nonnull Repository repository) {
      return getShortRepositoryName(repository);
    }
  }), limit);
}
 
Example #19
Source File: ExtractSuperClassUtil.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
public static RefactoringEventData createBeforeData(final PsiClass subclassClass, final MemberInfo[] members) {
  RefactoringEventData data = new RefactoringEventData();
  data.addElement(subclassClass);
  data.addMembers(members, new Function<MemberInfo, PsiElement>() {
    @Override
    public PsiElement fun(MemberInfo info) {
      return info.getMember();
    }
  });
  return data;
}
 
Example #20
Source File: TreeTraversal.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public final <T> Function<T, JBIterable<T>> traversal(@Nonnull final Function<T, ? extends Iterable<? extends T>> tree) {
  return new Function<T, JBIterable<T>>() {
    @Override
    public JBIterable<T> fun(T t) {
      return traversal(t, tree);
    }
  };
}
 
Example #21
Source File: GLSLDocumentationProvider.java    From glsl4idea with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static String getFunctionDocumentation(@NotNull GLSLFunctionDeclaration decl) {
    return getFunctionDocumentation(decl.getType(), ContainerUtil.map(decl.getParameters(), new Function<GLSLParameterDeclaration, String>() {
        @Override
        public String fun(GLSLParameterDeclaration glslParameterDeclaration) {
            return glslParameterDeclaration.getName();
        }
    }));
}
 
Example #22
Source File: HintUpdateSupply.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void installHintUpdateSupply(@Nonnull final JComponent component, final Function<Object, PsiElement> provider) {
  HintUpdateSupply supply = new HintUpdateSupply(component) {
    @Nullable
    @Override
    protected PsiElement getPsiElementForHint(@Nullable Object selectedValue) {
      return provider.fun(selectedValue);
    }
  };
  if (component instanceof JList) supply.installListListener((JList)component);
  if (component instanceof JTree) supply.installTreeListener((JTree)component);
  if (component instanceof JTable) supply.installTableListener((JTable)component);
}
 
Example #23
Source File: HaskellCompletionTestBase.java    From intellij-haskforce with Apache License 2.0 5 votes vote down vote up
protected void loadVisibleModules(final String... ss) {
    cacheLoaders.add(new Function<HaskellCompletionCacheLoader.Cache, Void>() {
        @Override
        public Void fun(HaskellCompletionCacheLoader.Cache cache) {
            Collections.addAll(cache.visibleModules(), ss);
            return null;
        }
    });
}
 
Example #24
Source File: EdgeStorage.java    From consulo with Apache License 2.0 5 votes vote down vote up
public List<Pair<Integer, GraphEdgeType>> getEdges(int nodeId) {
  return ContainerUtil.map(myEdges.get(nodeId), new Function<Integer, Pair<Integer, GraphEdgeType>>() {
    @Override
    public Pair<Integer, GraphEdgeType> fun(Integer compressEdge) {
      return Pair.create(convertToInteger(retrievedNodeId(compressEdge)), retrievedType(compressEdge));
    }
  });
}
 
Example #25
Source File: RelatedItemLineMarkerInfo.java    From consulo with Apache License 2.0 5 votes vote down vote up
public RelatedItemLineMarkerInfo(@Nonnull T element, @Nonnull TextRange range, Image icon, int updatePass,
                                 @Nullable Function<? super T, String> tooltipProvider,
                                 @Nullable GutterIconNavigationHandler<T> navHandler,
                                 GutterIconRenderer.Alignment alignment,
                                 @Nonnull final Collection<? extends GotoRelatedItem> targets) {
  this(element, range, icon, updatePass, tooltipProvider, navHandler, alignment, new NotNullLazyValue<Collection<? extends GotoRelatedItem>>() {
    @Nonnull
    @Override
    protected Collection<? extends GotoRelatedItem> compute() {
      return targets;
    }
  });
}
 
Example #26
Source File: RelatedItemLineMarkerInfo.java    From consulo with Apache License 2.0 5 votes vote down vote up
public RelatedItemLineMarkerInfo(@Nonnull T element, @Nonnull TextRange range, Image icon, int updatePass,
                                 @Nullable Function<? super T, String> tooltipProvider,
                                 @Nullable GutterIconNavigationHandler<T> navHandler,
                                 GutterIconRenderer.Alignment alignment,
                                 @Nonnull NotNullLazyValue<Collection<? extends GotoRelatedItem>> targets) {
  super(element, range, icon, updatePass, tooltipProvider, navHandler, alignment);
  myTargets = targets;
}
 
Example #27
Source File: HaskellPsiUtil.java    From intellij-haskforce with Apache License 2.0 5 votes vote down vote up
@NotNull
public static Set<String> getImportModuleNames(@NotNull List<Import> imports) {
    return ContainerUtil.map2Set(imports, new Function<Import, String>() {
        @Override
        public String fun(Import anImport) {
            return anImport.module;
        }
    });
}
 
Example #28
Source File: ResolvingTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
protected Function<ResolveResult, String> createReferenceResultBuilder() {
  return new Function<ResolveResult, String>() {
    @Override
    public String fun(ResolveResult resolveResult) {
      PsiElement element = resolveResult.getElement();
      assert element != null;
      throw new UnsupportedOperationException("Please override 'getReferenceResultBuilder()' argument type: " + element.getClass());
    }
  };
}
 
Example #29
Source File: DependenciesPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void actionPerformed(final AnActionEvent e) {
  @NonNls final String delim = "&nbsp;-&gt;&nbsp;";
  final StringBuffer buf = new StringBuffer();
  processDependencies(getSelectedScope(myLeftTree), getSelectedScope(myRightTree), new Processor<List<PsiFile>>() {
    @Override
    public boolean process(final List<PsiFile> path) {
      if (buf.length() > 0) buf.append("<br>");
      buf.append(StringUtil.join(path, new Function<PsiFile, String>() {
        @Override
        public String fun(final PsiFile psiFile) {
          return psiFile.getName();
        }
      }, delim));
      return true;
    }
  });
  final JEditorPane pane = new JEditorPane(UIUtil.HTML_MIME, XmlStringUtil.wrapInHtml(buf));
  pane.setForeground(JBColor.foreground());
  pane.setBackground(HintUtil.INFORMATION_COLOR);
  pane.setOpaque(true);
  final JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(pane);
  final Dimension dimension = pane.getPreferredSize();
  scrollPane.setMinimumSize(new Dimension(dimension.width, dimension.height + 20));
  scrollPane.setPreferredSize(new Dimension(dimension.width, dimension.height + 20));
  JBPopupFactory.getInstance().createComponentPopupBuilder(scrollPane, pane).setTitle("Dependencies")
    .setMovable(true).createPopup().showInBestPositionFor(e.getDataContext());
}
 
Example #30
Source File: AbstractModelBuilderTest.java    From intellij-quarkus with Eclipse Public License 2.0 5 votes vote down vote up
protected <T> Map<String, T> getModulesMap(final Class<T> aClass) {
  final DomainObjectSet<? extends IdeaModule> ideaModules = allModels.getIdeaProject().getModules();

  final String filterKey = "to_filter";
  final Map<String, T> map = ContainerUtil.map2Map(ideaModules, (Function<IdeaModule, Pair<String, T>>)module -> {
    final T value = allModels.getExtraProject(module, aClass);
    final String key = value != null ? module.getGradleProject().getPath() : filterKey;
    return Pair.create(key, value);
  });

  map.remove(filterKey);
  return map;
}