Java 类com.intellij.openapi.util.Pair 实例源码

项目:idea-php-dotenv-plugin    文件:DotEnvLightCodeInsightFixtureTestCase.java   
private Pair<List<ProblemDescriptor>, Integer> getLocalInspectionsAtCaret(String filename, String content) {

        PsiElement psiFile = myFixture.configureByText(filename, content);

        int caretOffset = myFixture.getCaretOffset();
        if(caretOffset <= 0) {
            fail("Please provide <caret> tag");
        }

        ProblemsHolder problemsHolder = new ProblemsHolder(InspectionManager.getInstance(getProject()), psiFile.getContainingFile(), false);

        for (LocalInspectionEP localInspectionEP : LocalInspectionEP.LOCAL_INSPECTION.getExtensions()) {
            Object object = localInspectionEP.getInstance();
            if(!(object instanceof LocalInspectionTool)) {
                continue;
            }

            ((LocalInspectionTool) object).buildVisitor(problemsHolder, false);
        }

        return new Pair<List<ProblemDescriptor>, Integer>(problemsHolder.getResults(), caretOffset);
    }
项目:teamcity-autotools-plugin    文件:RuntestToolProvider.java   
/**
 * Returns need runner parameters dependence current version runtest.
 * @param version current version runtest
 * @return list of need parameters
 */
@NotNull
@VisibleForTesting
static List<Pair<String, String>> getDejagnuParameters(@NotNull final String version){
  final List<Pair<String, String>> params = new ArrayList<Pair<String, String>>();
  params.add(new Pair<String, String>(HAS_RUNTEST_VAR, "1"));
  if (VersionComparatorUtil.compare(version, "1.4.4") <= 0){
    params.add(new Pair<String, String>(MY_RUNTESTFLAGS, "RUNTESTFLAGS=--all"));
    return params;
  }
  if (VersionComparatorUtil.compare(version, "1.5.3") < 0){
      params.add(new Pair<String, String>(MY_RUNTESTFLAGS, "RUNTESTFLAGS=--all --xml"));
    return params;
  }
  params.add(new Pair<String, String>(MY_RUNTESTFLAGS, "RUNTESTFLAGS=--all --xml=\"testresults.xml\""));
  return params;
}
项目:teamcity-autotools-plugin    文件:AutotoolsAgentTest.java   
@Test
public void getDejagnuParametersTest(){
  final Collection<Pair<String, String>> answer = new ArrayList<Pair<String, String>>();
  answer.add(new Pair<String, String>(HAS_RUNTEST_VAR, "1"));
  answer.add(new Pair<String, String>(MY_RUNTESTFLAGS, "RUNTESTFLAGS=--all"));
  Assert.assertEquals(RuntestToolProvider.getDejagnuParameters("1.4.4"), answer,"for version 1.4.4");
  answer.clear();

  answer.add(new Pair<String, String>(HAS_RUNTEST_VAR, "1"));
  answer.add(new Pair<String, String>(MY_RUNTESTFLAGS, "RUNTESTFLAGS=--all --xml"));
  Assert.assertEquals(RuntestToolProvider.getDejagnuParameters("1.5.1"), answer, "for version 1.5.1");
  answer.clear();

  answer.add(new Pair<String, String>(HAS_RUNTEST_VAR, "1"));
  //answer.add(new Pair<String, String>(MY_RUNTESTFLAGS, "'--all --xml'"));
  answer.add(new Pair<String, String>(MY_RUNTESTFLAGS, "RUNTESTFLAGS=--all --xml=\"testresults.xml\""));
  Assert.assertEquals(RuntestToolProvider.getDejagnuParameters("1.5.3"), answer, "for version 1.5.3");
  Assert.assertEquals(RuntestToolProvider.getDejagnuParameters("1.6"), answer, "for version 1.6");
}
项目:AndroidSourceViewer    文件:SearchDownload.java   
@Override
public Pair<Boolean, List<File>> onDownload(@NotNull ClassEntity[] classEntities, @NotNull File outputFolder) {
    String newUrl = null;
    try {
        newUrl = androidOnlineSearch(classEntities[0]);
    } catch (ConnectException | UnknownHostException e1) {
        if (timeoutListener != null) {
            timeoutListener.run();
        }
    } catch (Exception e) {
        Log.e(e);
    }
    if (!Utils.isEmpty(newUrl)) {
        for (ClassEntity entity : classEntities) {
            entity.setDownloadUrl(newUrl);
        }
        Log.debug("SearchDownload => " + newUrl);
        return new XrefDownload().onDownload(classEntities, outputFolder);
    }
    return Pair.create(false, Collections.<File>emptyList());
}
项目:educational-plugin    文件:StudyProjectComponent.java   
private void addShortcut(@NotNull final String actionIdString, @NotNull final String[] shortcuts) {
  KeymapManagerEx keymapManager = KeymapManagerEx.getInstanceEx();
  for (Keymap keymap : keymapManager.getAllKeymaps()) {
    List<Pair<String, String>> pairs = myDeletedShortcuts.get(keymap);
    if (pairs == null) {
      pairs = new ArrayList<>();
      myDeletedShortcuts.put(keymap, pairs);
    }
    for (String shortcutString : shortcuts) {
      Shortcut studyActionShortcut = new KeyboardShortcut(KeyStroke.getKeyStroke(shortcutString), null);
      String[] actionsIds = keymap.getActionIds(studyActionShortcut);
      for (String actionId : actionsIds) {
        pairs.add(Pair.create(actionId, shortcutString));
        keymap.removeShortcut(actionId, studyActionShortcut);
      }
      keymap.addShortcut(actionIdString, studyActionShortcut);
    }
  }
}
项目:educational-plugin    文件:StudyProjectComponent.java   
@Override
public void projectClosed() {
  final Course course = StudyTaskManager.getInstance(myProject).getCourse();
  if (course != null) {
    final ToolWindow toolWindow = ToolWindowManager.getInstance(myProject).getToolWindow(StudyToolWindowFactory.STUDY_TOOL_WINDOW);
    if (toolWindow != null) {
      toolWindow.getContentManager().removeAllContents(false);
    }
    KeymapManagerEx keymapManager = KeymapManagerEx.getInstanceEx();
    for (Keymap keymap : keymapManager.getAllKeymaps()) {
      List<Pair<String, String>> pairs = myDeletedShortcuts.get(keymap);
      if (pairs != null && !pairs.isEmpty()) {
        for (Pair<String, String> actionShortcut : pairs) {
          keymap.addShortcut(actionShortcut.first, new KeyboardShortcut(KeyStroke.getKeyStroke(actionShortcut.second), null));
        }
      }
    }
  }
  myListener = null;
}
项目:educational-plugin    文件:StudyToolWindow.java   
public void updateCourseProgress(@NotNull final Project project) {
  final Course course = StudyTaskManager.getInstance(project).getCourse();
  if (course != null) {
    List<Lesson> lessons = course.getLessons();

    Pair<Integer, Integer> progress = countProgressAsOneTaskWithSubtasks(lessons);
    if (progress == null) {
      progress = countProgressWithoutSubtasks(lessons);
    }

    int taskSolved = progress.getFirst();
    int taskNum = progress.getSecond();
    String completedTasks = String.format("%d of %d tasks completed", taskSolved, taskNum);
    double percent = (taskSolved * 100.0) / taskNum;

    myStatisticLabel.setText(completedTasks);
    myStudyProgressBar.setFraction(percent / 100);
  }
}
项目:educational-plugin    文件:StudyToolWindow.java   
/**
 * Counts current progress for course which consists of only on task with subtasks
 * In this case we count each subtasks as task
 * @return Pair (number of solved tasks, number of tasks) or null if lessons can't be interpreted as one task with subtasks
 */
@Nullable
private static Pair<Integer, Integer> countProgressAsOneTaskWithSubtasks(List<Lesson> lessons) {
  if (lessons.size() == 1 && lessons.get(0).getTaskList().size() == 1) {
    final Lesson lesson = lessons.get(0);
    final Task task = lesson.getTaskList().get(0);
    if (task instanceof TaskWithSubtasks) {
      final int lastSubtaskIndex = ((TaskWithSubtasks)task).getLastSubtaskIndex();
      final int activeSubtaskIndex = ((TaskWithSubtasks)task).getActiveSubtaskIndex();
      int taskNum = lastSubtaskIndex + 1;
      boolean isLastSubtaskSolved = activeSubtaskIndex == lastSubtaskIndex && task.getStatus() == StudyStatus.Solved;
      return Pair.create(isLastSubtaskSolved ? taskNum : activeSubtaskIndex, taskNum);
    }
  }
  return null;
}
项目:educational-plugin    文件:EduAnswerPlaceholderPainter.java   
public static void drawAnswerPlaceholder(@NotNull final Editor editor, @NotNull final AnswerPlaceholder placeholder,
                                         @NotNull final JBColor color) {
  EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme();
  final TextAttributes textAttributes = new TextAttributes(scheme.getDefaultForeground(), scheme.getDefaultBackground(), null,
                                                           EffectType.BOXED, Font.PLAIN);
  textAttributes.setEffectColor(color);
  int startOffset = placeholder.getOffset();
  if (startOffset == -1) {
    return;
  }
  final int length =
    placeholder.isActive() ? placeholder.getRealLength() : placeholder.getVisibleLength(placeholder.getActiveSubtaskIndex());
  Pair<Integer, Integer> offsets = StudyUtils.getPlaceholderOffsets(placeholder, editor.getDocument());
  startOffset = offsets.first;
  int endOffset = offsets.second;
  if (placeholder.isActive()) {
    drawAnswerPlaceholder(editor, startOffset, endOffset, textAttributes, PLACEHOLDERS_LAYER);
  }
  else if (!placeholder.getUseLength() && length != 0) {
    drawAnswerPlaceholderFromPrevStep(editor, startOffset, endOffset);
  }
}
项目:educational-plugin    文件:EduAnswerPlaceholderPainter.java   
public static void createGuardedBlocks(@NotNull final Editor editor, AnswerPlaceholder placeholder) {
  Document document = editor.getDocument();
  if (document instanceof DocumentImpl) {
    DocumentImpl documentImpl = (DocumentImpl)document;
    List<RangeMarker> blocks = documentImpl.getGuardedBlocks();
    Pair<Integer, Integer> offsets = StudyUtils.getPlaceholderOffsets(placeholder, editor.getDocument());
    Integer start = offsets.first;
    Integer end = offsets.second;
    if (start != 0) {
      createGuardedBlock(editor, blocks, start - 1, start);
    }
    if (end != document.getTextLength()) {
      createGuardedBlock(editor, blocks, end, end + 1);
    }
  }
}
项目:educational-plugin    文件:CCShowPreviewTest.java   
private void doTest(String name) {
  VirtualFile file = configureByTaskFile(name + CCTestsUtil.BEFORE_POSTFIX);
  CCShowPreview action = new CCShowPreview();
  TestActionEvent e = getActionEvent(action,PsiManager.getInstance(getProject()).findFile(file));
  action.beforeActionPerformedUpdate(e);
  assertTrue(e.getPresentation().isEnabled() && e.getPresentation().isVisible());
  action.actionPerformed(e);
  Editor editor = EditorFactory.getInstance().getAllEditors()[1];
  try {
    Pair<Document, List<AnswerPlaceholder>> pair = getPlaceholders(name + CCTestsUtil.AFTER_POSTFIX);
    assertEquals("Files don't match", pair.getFirst().getText(), editor.getDocument().getText());
    for (AnswerPlaceholder placeholder : pair.getSecond()) {
      assertNotNull("No highlighter for placeholder:" + CCTestsUtil.getPlaceholderPresentation(placeholder),
                    getHighlighter(editor.getMarkupModel(), placeholder));
    }
  }
  finally {
    EditorFactory.getInstance().releaseEditor(editor);
  }
}
项目:educational-plugin    文件:CCTestCase.java   
public void checkByFile(TaskFile taskFile, String fileName, boolean useLength) {
  Pair<Document, List<AnswerPlaceholder>> placeholders = getPlaceholders(fileName, useLength, true);
  String message = "Placeholders don't match";
  if (taskFile.getActivePlaceholders().size() != placeholders.second.size()) {
    throw new ComparisonFailure(message,
                                CCTestsUtil.getPlaceholdersPresentation(taskFile.getActivePlaceholders()),
                                CCTestsUtil.getPlaceholdersPresentation(placeholders.second));
  }
  for (AnswerPlaceholder answerPlaceholder : placeholders.getSecond()) {
    AnswerPlaceholder placeholder = taskFile.getAnswerPlaceholder(answerPlaceholder.getOffset());
    if (!CCTestsUtil.comparePlaceholders(placeholder, answerPlaceholder)) {
      throw new ComparisonFailure(message,
                                  CCTestsUtil.getPlaceholdersPresentation(taskFile.getActivePlaceholders()),
                                  CCTestsUtil.getPlaceholdersPresentation(placeholders.second));
    }
  }
}
项目:intellij-ce-playground    文件:XBreakpointUtil.java   
@NotNull
public static Pair<GutterIconRenderer, Object> findSelectedBreakpoint(@NotNull final Project project, @NotNull final Editor editor) {
  int offset = editor.getCaretModel().getOffset();
  Document editorDocument = editor.getDocument();

  DebuggerSupport[] debuggerSupports = DebuggerSupport.getDebuggerSupports();
  for (DebuggerSupport debuggerSupport : debuggerSupports) {
    final BreakpointPanelProvider<?> provider = debuggerSupport.getBreakpointPanelProvider();

    final int textLength = editor.getDocument().getTextLength();
    if (offset > textLength) {
      offset = textLength;
    }

    Object breakpoint = provider.findBreakpoint(project, editorDocument, offset);
    if (breakpoint != null) {
      final GutterIconRenderer iconRenderer = provider.getBreakpointGutterIconRenderer(breakpoint);
      return Pair.create(iconRenderer, breakpoint);
    }
  }
  return Pair.create(null, null);
}
项目:intellij-ce-playground    文件:CollectionAddAllCanBeReplacedWithConstructorInspection.java   
private static Pair<Boolean, PsiNewExpression> isProperAssignmentStatementFound(PsiLocalVariable localVariable, PsiMethodCallExpression addAllExpression) {
  PsiStatement currentStatement = PsiTreeUtil.getParentOfType(addAllExpression, PsiStatement.class);
  final PsiStatement localVariableDefinitionStatement = PsiTreeUtil.getParentOfType(localVariable, PsiStatement.class);
  while (currentStatement != null) {
    currentStatement = PsiTreeUtil.getPrevSiblingOfType(currentStatement, PsiStatement.class);
    if (currentStatement == localVariableDefinitionStatement) {
      return Pair.create(true, null);
    }
    for (PsiAssignmentExpression expression : PsiTreeUtil.findChildrenOfType(currentStatement, PsiAssignmentExpression.class)) {
      final PsiExpression lExpression = expression.getLExpression();
      if (lExpression instanceof PsiReferenceExpression && ((PsiReferenceExpression)lExpression).isReferenceTo(localVariable)) {
        final PsiExpression rExpression = expression.getRExpression();
        final boolean isValid = checkLocalVariableAssignmentOrInitializer(rExpression);
        return Pair.create(isValid, isValid ? (PsiNewExpression)rExpression : null);
      }
    }
  }
  return Pair.create(true, null);
}
项目:intellij-ce-playground    文件:ComboControl.java   
static JComboBox initComboBox(final JComboBox comboBox, final Condition<String> validity) {
  comboBox.setEditable(false);
  comboBox.setPrototypeDisplayValue(new ComboBoxItem("A", null));
  comboBox.setRenderer(new DefaultListCellRenderer() {
    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
      super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
      final Pair<String, Icon> pair = (Pair<String, Icon>)value;
      final String text = pair == null ? null : pair.first;
      setText(text);
      final Dimension dimension = getPreferredSize();
      if (!validity.value(text)) {
        setFont(getFont().deriveFont(Font.ITALIC));
        setForeground(JBColor.RED);
      }
      setIcon(pair == null ? null : pair.second);
      setPreferredSize(new Dimension(-1, dimension.height));
      return this;
    }
  });
  return comboBox;
}
项目:intellij-ce-playground    文件:PreparedFragmentedContent.java   
private void setTodoHighlighting(final Document oldDocument, final Document document) {
  final ContentRevisionCache cache = ProjectLevelVcsManager.getInstance(myProject).getContentRevisionCache();
  final List<Pair<TextRange,TextAttributes>> beforeTodoRanges = myBeforeNumber == null ? Collections.<Pair<TextRange,TextAttributes>>emptyList() :
    new TodoForBaseRevision(myProject, getBeforeFragments(), 1, myFileName, oldDocument.getText(), true, myFileType, new Getter<Object>() {
    @Override
    public Object get() {
      return cache.getCustom(myFilePath, myBeforeNumber);
    }
  }, new Consumer<Object>() {
    @Override
    public void consume(Object items) {
      cache.putCustom(myFilePath, myBeforeNumber, items);
    }
  }).execute();

  final List<Pair<TextRange, TextAttributes>> afterTodoRanges = new TodoForExistingFile(myProject, getAfterFragments(), 1,
    myFileName, document.getText(), false, myFileType, myFile).execute();
  setBeforeTodoRanges(beforeTodoRanges);
  setAfterTodoRanges(afterTodoRanges);
}
项目:intellij-ce-playground    文件:FileDownloaderImpl.java   
@Nullable
@Override
public List<Pair<VirtualFile, DownloadableFileDescription>> downloadWithProgress(@Nullable String targetDirectoryPath,
                                                                                 @Nullable Project project,
                                                                                 @Nullable JComponent parentComponent) {
  File dir;
  if (targetDirectoryPath != null) {
    dir = new File(targetDirectoryPath);
  }
  else {
    VirtualFile virtualDir = chooseDirectoryForFiles(project, parentComponent);
    if (virtualDir != null) {
      dir = VfsUtilCore.virtualToIoFile(virtualDir);
    }
    else {
      return null;
    }
  }

  return downloadWithProcess(dir, project, parentComponent);
}
项目:intellij-ce-playground    文件:TypeMigrationStatementProcessor.java   
@Override
public void visitReturnStatement(PsiReturnStatement statement) { // has to change method return type corresponding to new value type 
  super.visitReturnStatement(statement);

  final PsiElement method = PsiTreeUtil.getParentOfType(statement, PsiMethod.class, PsiLambdaExpression.class);
  final PsiExpression value = statement.getReturnValue();

  if (method != null && value != null) {
    if (method instanceof PsiLambdaExpression) {
      //todo [IDEA-133097]
      return;
    }
    final PsiType returnType = ((PsiMethod)method).getReturnType();
    final PsiType valueType = myTypeEvaluator.evaluateType(value);

    if (returnType != null && valueType != null) {
      if (!myLabeler.addMigrationRoot(method, valueType, myStatement, TypeConversionUtil.isAssignable(returnType, valueType), true)
          && TypeMigrationLabeler.typeContainsTypeParameters(returnType)) {
        myLabeler.markFailedConversion(Pair.create(returnType, valueType), value);
      }
    }
  }
}
项目:intellij-ce-playground    文件:FunctionalParserBase.java   
@NotNull
@Override
public Pair<R, State> parse(@NotNull List<Token<T>> tokens, @NotNull State state) throws ParserException {
  if (myKey != state.getKey()) {
    myKey = state.getKey();
    myCache.clear();
  }
  final SoftReference<Pair<R, State>> ref = myCache.get(state.getPos());
  final Pair<R, State> cached = SoftReference.dereference(ref);
  if (cached != null) {
    return cached;
  }
  final Pair<R, State> result = myParser.parse(tokens, state);
  myCache.put(state.getPos(), new SoftReference<Pair<R, State>>(result));
  return result;
}
项目:intellij-ce-playground    文件:XmlRearranger.java   
@Nullable
@Override
public Pair<XmlElementArrangementEntry, List<XmlElementArrangementEntry>> parseWithNew(@NotNull PsiElement root,
                                                                                       @Nullable Document document,
                                                                                       @NotNull Collection<TextRange> ranges,
                                                                                       @NotNull PsiElement element,
                                                                                       @NotNull ArrangementSettings settings)
{
  final XmlArrangementParseInfo newEntryInfo = new XmlArrangementParseInfo();
  element.accept(new XmlArrangementVisitor(newEntryInfo, Collections.singleton(element.getTextRange())));

  if (newEntryInfo.getEntries().size() != 1) {
    return null;
  }
  final XmlElementArrangementEntry entry = newEntryInfo.getEntries().get(0);
  final XmlArrangementParseInfo existingEntriesInfo = new XmlArrangementParseInfo();
  root.accept(new XmlArrangementVisitor(existingEntriesInfo, ranges));
  return Pair.create(entry, existingEntriesInfo.getEntries());
}
项目:intellij-ce-playground    文件:DataFlowInspectionBase.java   
@Override
protected boolean checkNotNullable(DfaMemoryState state, DfaValue value, NullabilityProblem problem, PsiElement anchor) {
  boolean ok = super.checkNotNullable(state, value, problem, anchor);
  if (!ok && anchor != null) {
    myProblems.putValue(problem, anchor);
  }
  Pair<NullabilityProblem, PsiElement> key = Pair.create(problem, anchor);
  StateInfo info = myStateInfos.get(key);
  if (info == null) {
    myStateInfos.put(key, info = new StateInfo());
  }
  if (state.isEphemeral() && !ok) {
    info.ephemeralNpe = true;
  } else if (!state.isEphemeral()) {
    if (ok) info.normalOk = true;
    else info.normalNpe = true;
  }
  return ok;
}
项目:intellij-ce-playground    文件:MarkerType.java   
@Nullable
private static String calculateOverridingSiblingMethodTooltip(@NotNull PsiMethod method) {
  Pair<PsiMethod, PsiClass> pair =
    FindSuperElementsHelper.getSiblingInheritedViaSubClass(method, FindSuperElementsHelper.createSubClassCache());
  if (pair == null) return null;
  PsiMethod superMethod = pair.getFirst();
  PsiClass subClass = pair.getSecond();
  boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT);
  boolean isSuperAbstract = superMethod.hasModifierProperty(PsiModifier.ABSTRACT);

  String postfix = MessageFormat.format(" via sub-class <a href=\"#javaClass/{0}\">{0}</a>", ClassPresentationUtil.getNameForClass(subClass, true));
  @NonNls String pattern = DaemonBundle.message(isSuperAbstract && !isAbstract ?
                                                "method.implements" :
                                                "method.overrides") + postfix;
  return composeText(new PsiElement[]{superMethod}, "", pattern, IdeActions.ACTION_GOTO_SUPER);
}
项目:intellij-ce-playground    文件:GitBranchOperation.java   
protected GitBranchOperation(@NotNull Project project, @NotNull GitPlatformFacade facade, @NotNull Git git,
                             @NotNull GitBranchUiHandler uiHandler, @NotNull Collection<GitRepository> repositories) {
  myProject = project;
  myFacade = facade;
  myGit = git;
  myUiHandler = uiHandler;
  myRepositories = repositories;
  myCurrentHeads = ContainerUtil.map2Map(repositories, new Function<GitRepository, Pair<GitRepository, String>>() {
    @Override
    public Pair<GitRepository, String> fun(GitRepository repository) {
      GitLocalBranch currentBranch = repository.getCurrentBranch();
      return Pair.create(repository, currentBranch == null ? repository.getCurrentRevision() : currentBranch.getName());
    }
  });
  mySuccessfulRepositories = new ArrayList<GitRepository>();
  myRemainingRepositories = new ArrayList<GitRepository>(myRepositories);
  mySettings = myFacade.getSettings(myProject);
}
项目:intellij-ce-playground    文件:AbstractModelBuilderTest.java   
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, new Function<IdeaModule, Pair<String, T>>() {
    @Override
    public Pair<String, T> fun(IdeaModule 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;
}
项目:intellij-ce-playground    文件:GenericsHighlightUtil.java   
@Nullable
static HighlightInfo checkInferredTypeArguments(PsiTypeParameter[] typeParameters,
                                                PsiElement call,
                                                PsiSubstitutor substitutor) {
  final Pair<PsiTypeParameter, PsiType> inferredTypeArgument = GenericsUtil.findTypeParameterWithBoundError(typeParameters, substitutor, call, false);
  if (inferredTypeArgument != null) {
    final PsiType extendsType = inferredTypeArgument.second;
    final PsiTypeParameter typeParameter = inferredTypeArgument.first;
    PsiClass boundClass = extendsType instanceof PsiClassType ? ((PsiClassType)extendsType).resolve() : null;

    @NonNls String messageKey = boundClass == null || typeParameter.isInterface() == boundClass.isInterface()
                                ? "generics.inferred.type.for.type.parameter.is.not.within.its.bound.extend"
                                : "generics.inferred.type.for.type.parameter.is.not.within.its.bound.implement";

    String description = JavaErrorMessages.message(
      messageKey,
      HighlightUtil.formatClass(typeParameter),
      JavaHighlightUtil.formatType(extendsType),
      JavaHighlightUtil.formatType(substitutor.substitute(typeParameter))
    );
    return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(call).descriptionAndTooltip(description).create();
  }

  return null;
}
项目:intellij-ce-playground    文件:PermissionGroupClass.java   
@NotNull
@Override
protected List<Pair<String, String>> doGetFields(@NotNull Manifest manifest) {
  final List<Pair<String, String>> result = new ArrayList<Pair<String, String>>();

  for (PermissionGroup permissionGroup : manifest.getPermissionGroups()) {
    final String name = permissionGroup.getName().getValue();

    if (name != null && name.length() > 0) {
      final int lastDotIndex = name.lastIndexOf('.');
      final String lastId = name.substring(lastDotIndex + 1);

      if (lastId.length() > 0) {
        result.add(Pair.create(AndroidResourceUtil.getFieldNameByResourceName(lastId), name));
      }
    }
  }
  return result;
}
项目:intellij-ce-playground    文件:DictionaryTest.java   
private Pair<Set<String>, Set<String>> createWordSets(Dictionary dictionary, int maxCount, int mod) {
  Set<String> wordsToStore = new THashSet<String>();
  Set<String> wordsToCheck = new THashSet<String>();

  Set<String> words = dictionary.getWords();
  assertNotNull(words);
  int counter = 0;
  for (String s : words) {
    String transformed = myTransformation.transform(s);
    if (transformed != null) {
      (counter % mod == 0 ? wordsToStore : wordsToCheck).add(transformed);
      if (++counter > maxCount) break;
    }
  }

  return pair(wordsToStore, wordsToCheck);
}
项目:intellij-ce-playground    文件:LightQuickFixTestCase.java   
@NotNull
public static Pair<String, Boolean> parseActionHint(@NotNull PsiFile file,
                                                    @NotNull String contents,
                                                    @NotNull @NonNls @RegExp String actionPattern) {
  PsiFile hostFile = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);

  final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(hostFile.getLanguage());
  String comment = commenter.getLineCommentPrefix();
  if (comment == null) {
    comment = commenter.getBlockCommentPrefix();
  }

  // "quick fix action text to perform" "should be available"
  assert comment != null : commenter;
  Pattern pattern = Pattern.compile("^" + comment.replace("*", "\\*") + actionPattern, Pattern.DOTALL);
  Matcher matcher = pattern.matcher(contents);
  assertTrue("No comment found in "+file.getVirtualFile(), matcher.matches());
  final String text = matcher.group(1);
  final Boolean actionShouldBeAvailable = Boolean.valueOf(matcher.group(2));
  return Pair.create(text, actionShouldBeAvailable);
}
项目:intellij-ce-playground    文件:GlobalAnalyzer.java   
private static boolean stepTwoEnds(final MarkedNode currNode, final LinkedList worklist, final TwoEndsFunctor functor) {
  boolean result = false;

  for (Iterator i = currNode.outIterator(); i.hasNext();) {
    final MarkedEdge currEdge = (MarkedEdge)i.next();
    final MarkedNode nextNode = (MarkedNode)currEdge.end();
    final Pair<Mark,Mark> markPair = functor.compute(currNode.getMark(), currEdge.getMark(), nextNode.getMark());

    final Mark leftMark = markPair.getFirst();
    final Mark rightMark = markPair.getSecond();

    if (!leftMark.coincidesWith(currNode.getMark())) {
      result = true;
      currNode.setMark(leftMark);
      worklist.addFirst(currNode);
    }

    if (!rightMark.coincidesWith(nextNode.getMark())) {
      result = true;
      nextNode.setMark(rightMark);
      worklist.addFirst(nextNode);
    }
  }

  return result;
}
项目:intellij-ce-playground    文件:PyStringLiteralExpressionImpl.java   
@Override
@NotNull
public List<Pair<TextRange, String>> getDecodedFragments() {
  if (myDecodedFragments == null) {
    final List<Pair<TextRange, String>> result = new ArrayList<Pair<TextRange, String>>();
    final int elementStart = getTextRange().getStartOffset();
    final boolean unicodeByDefault = isUnicodeByDefault();
    for (ASTNode node : getStringNodes()) {
      final String text = node.getText();
      final TextRange textRange = getNodeTextRange(text);
      final int offset = node.getTextRange().getStartOffset() - elementStart + textRange.getStartOffset();
      final String encoded = textRange.substring(text);
      result.addAll(getDecodedFragments(encoded, offset, isRaw(text), unicodeByDefault || isUnicode(text)));
    }
    myDecodedFragments = result;
  }
  return myDecodedFragments;
}
项目:intellij-ce-playground    文件:PyStringLiteralExpressionImpl.java   
@Override
public boolean decode(@NotNull final TextRange rangeInsideHost, @NotNull final StringBuilder outChars) {
  for (Pair<TextRange, String> fragment : myHost.getDecodedFragments()) {
    final TextRange encodedTextRange = fragment.getFirst();
    final TextRange intersection = encodedTextRange.intersection(rangeInsideHost);
    if (intersection != null && !intersection.isEmpty()) {
      final String value = fragment.getSecond();
      final String intersectedValue;
      if (value.length() == 1 || value.length() == intersection.getLength()) {
        intersectedValue = value;
      }
      else {
        final int start = Math.max(0, rangeInsideHost.getStartOffset() - encodedTextRange.getStartOffset());
        final int end = Math.min(value.length(), start + intersection.getLength());
        intersectedValue = value.substring(start, end);
      }
      outChars.append(intersectedValue);
    }
  }
  return true;
}
项目:intellij-ce-playground    文件:JavaCompletionSorting.java   
public PreferDefaultTypeWeigher(ExpectedTypeInfo[] expectedTypes, CompletionParameters parameters) {
  super("defaultType");
  myExpectedTypes = expectedTypes == null ? null : ContainerUtil.map2Array(expectedTypes, ExpectedTypeInfo.class, new Function<ExpectedTypeInfo, ExpectedTypeInfo>() {
    @Override
    public ExpectedTypeInfo fun(ExpectedTypeInfo info) {
      PsiType type = removeClassWildcard(info.getType());
      PsiType defaultType = removeClassWildcard(info.getDefaultType());
      if (type == info.getType() && defaultType == info.getDefaultType()) {
        return info;
      }
      return new ExpectedTypeInfoImpl(type, info.getKind(), defaultType, info.getTailType(), null, ExpectedTypeInfoImpl.NULL);
    }
  });
  myParameters = parameters;

  final Pair<PsiClass,Integer> pair = TypeArgumentCompletionProvider.getTypeParameterInfo(parameters.getPosition());
  myTypeParameter = pair == null ? null : pair.first.getTypeParameters()[pair.second.intValue()];
  myLocation = new CompletionLocation(myParameters);
}
项目:intellij-ce-playground    文件:JavaDocInfoGenerator.java   
private void generateTypeParametersSection(final StringBuilder buffer, final PsiClass aClass) {
  final LinkedList<ParamInfo> result = new LinkedList<ParamInfo>();
  final PsiTypeParameter[] typeParameters = aClass.getTypeParameters();
  for (int i = 0; i < typeParameters.length; i++) {
    PsiTypeParameter typeParameter = typeParameters[i];
    String name = "<" + typeParameter.getName() + ">";
    final DocTagLocator<PsiDocTag> locator = typeParameterLocator(i);
    final Pair<PsiDocTag, InheritDocProvider<PsiDocTag>> inClassComment = findInClassComment(aClass, locator);
    if (inClassComment != null) {
      result.add(new ParamInfo(name, inClassComment));
    }
    else {
      final Pair<PsiDocTag, InheritDocProvider<PsiDocTag>> pair = findInHierarchy(aClass, locator);
      if (pair != null) {
        result.add(new ParamInfo(name, pair));
      }
    }
  }
  generateParametersSection(buffer, CodeInsightBundle.message("javadoc.type.parameters"), result);
}
项目:intellij-ce-playground    文件:LoadRecentBranchRevisions.java   
private void initialize(@NotNull ContinuationContext context, @NotNull List<Pair<SvnChangeList, LogHierarchyNode>> changeLists) {
  myCommittedChangeLists = getNotMergedChangeLists(changeLists);

  try {
    myHelper = new OneShotMergeInfoHelper(myMergeContext);
    ProgressManager.progress2("Calculating not merged revisions");
    myHelper.prepare();
  }
  catch (VcsException e) {
    context.handleException(e, true);
  }

  myLastLoaded = myCommittedChangeLists.size() < myBunchSize + 1;
  if (myCommittedChangeLists.size() > myBunchSize) {
    myCommittedChangeLists = myCommittedChangeLists.subList(0, myBunchSize);
  }
}
项目:intellij-ce-playground    文件:NamedElementDuplicateHandler.java   
@Override
public void executeWriteAction(Editor editor, DataContext dataContext) {
  Project project = editor.getProject();
  if (project != null && !editor.getSelectionModel().hasSelection()) {
    PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file != null) {
      VisualPosition caret = editor.getCaretModel().getVisualPosition();
      Pair<LogicalPosition, LogicalPosition> lines = EditorUtil.calcSurroundingRange(editor, caret, caret);
      TextRange toDuplicate = new TextRange(editor.logicalPositionToOffset(lines.first), editor.logicalPositionToOffset(lines.second));

      PsiElement name = findNameIdentifier(editor, file, toDuplicate);
      if (name != null && !name.getTextRange().containsOffset(editor.getCaretModel().getOffset())) {
        editor.getCaretModel().moveToOffset(name.getTextOffset());
      }
    }
  }

  myOriginal.execute(editor, dataContext);
}
项目:watchMe    文件:ConsoleErrorInputFilter.java   
@Nullable
@Override
public List<Pair<String, ConsoleViewContentType>> applyFilter(String text, ConsoleViewContentType outputType) {

    if (outputType.equals(ConsoleViewContentType.ERROR_OUTPUT)) {
        this.errorStack += text;
    }
    if (outputType.equals(ConsoleViewContentType.SYSTEM_OUTPUT) && text.trim().startsWith("Process finished with exit code")) {
        HandledMessage hm = HandledMessage.create(this.errorStack, this.projectContent);
        if(hm != null) {
            //System.out.println(hm);
            for (SlackChannel slackChannel: SlackStorage.getInstance().getChannelsRegistry()) {
                SlackPost post = new SlackPost(slackChannel);
                String message = hm.toString();
                //System.out.println(message);
                String detail = slackChannel.getId() + " is in trouble with the following error!";
                try {
                    post.pushMessage(message, detail);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        this.errorStack = "";
    }
    return Collections.singletonList(Pair.create(text, outputType));
}
项目:bamboo-soy    文件:QuoteHandler.java   
private Pair<Character, Character> getMatchingPair(Character charTyped,
    Function<Pair<Character, Character>, Character> getCharacter) {
  for (Pair<Character, Character> charPair : matchingCharacters) {
    if (getCharacter.apply(charPair).equals(charTyped)) {
      return charPair;
    }
  }

  return null;
}
项目:idea-php-dotenv-plugin    文件:DotEnvLightCodeInsightFixtureTestCase.java   
public void assertLocalInspectionContains(String filename, String content, String contains) {
    Set<String> matches = new HashSet<String>();

    Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);
    for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
        TextRange textRange = result.getPsiElement().getTextRange();
        if (textRange.contains(localInspectionsAtCaret.getSecond()) && result.toString().equals(contains)) {
            return;
        }

        matches.add(result.toString());
    }

    fail(String.format("Fail matches '%s' with one of %s", contains, matches));
}
项目:idea-php-dotenv-plugin    文件:DotEnvLightCodeInsightFixtureTestCase.java   
public void assertLocalInspectionContainsNotContains(String filename, String content, String contains) {
    Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);

    for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
        TextRange textRange = result.getPsiElement().getTextRange();
        if (textRange.contains(localInspectionsAtCaret.getSecond())) {
            fail(String.format("Fail inspection not contains '%s'", contains));
        }
    }
}
项目:idea-php-dotenv-plugin    文件:DotEnvLightCodeInsightFixtureTestCase.java   
protected void assertLocalInspectionIsEmpty(String filename, String content) {
    Pair<List<ProblemDescriptor>, Integer> localInspectionsAtCaret = getLocalInspectionsAtCaret(filename, content);

    for (ProblemDescriptor result : localInspectionsAtCaret.getFirst()) {
        TextRange textRange = result.getPsiElement().getTextRange();
        if (textRange.contains(localInspectionsAtCaret.getSecond())) {
            fail("Fail that matches is empty");
        }
    }
}