com.intellij.util.containers.ContainerUtilRt Java Examples

The following examples show how to use com.intellij.util.containers.ContainerUtilRt. 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: ExternalSystemFacadeManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
public boolean isTaskActive(@Nonnull ExternalSystemTaskId id) {
  Map<IntegrationKey, Pair<RemoteExternalSystemFacade, ExternalSystemExecutionSettings>> copy
    = ContainerUtilRt.newHashMap(myRemoteFacades);
  for (Map.Entry<IntegrationKey, Pair<RemoteExternalSystemFacade, ExternalSystemExecutionSettings>> entry : copy.entrySet()) {
    try {
      if (entry.getValue().first.isTaskInProgress(id)) {
        return true;
      }
    }
    catch (RemoteException e) {
      myLock.lock();
      try {
        myRemoteFacades.remove(entry.getKey());
        myFacadeWrappers.remove(entry.getKey());
      }
      finally {
        myLock.unlock();
      }
    }
  }
  return false;
}
 
Example #2
Source File: ExternalSystemUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void processOrphanModules() {
  if (myProject.isDisposed()) return;
  if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
    LOG.info(String.format("Checking for orphan modules. External paths returned by external system: '%s'", myExternalModulePaths));
  }
  List<Module> orphanIdeModules = ContainerUtilRt.newArrayList();
  String externalSystemIdAsString = myExternalSystemId.toString();

  for (Module module : ModuleManager.getInstance(myProject).getModules()) {
    String s = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY);
    String p = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.LINKED_PROJECT_PATH_KEY);
    if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
      LOG.info(String.format("IDE module: EXTERNAL_SYSTEM_ID_KEY - '%s', LINKED_PROJECT_PATH_KEY - '%s'.", s, p));
    }
    if (externalSystemIdAsString.equals(s) && !myExternalModulePaths.contains(p)) {
      orphanIdeModules.add(module);
      if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
        LOG.info(String.format("External paths doesn't contain IDE module LINKED_PROJECT_PATH_KEY anymore => add to orphan IDE modules."));
      }
    }
  }

  if (!orphanIdeModules.isEmpty()) {
    ruleOrphanModules(orphanIdeModules, myProject, myExternalSystemId);
  }
}
 
Example #3
Source File: ModuleDataService.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@RequiredUIAccess
private Collection<DataNode<ModuleData>> filterExistingModules(@Nonnull Collection<DataNode<ModuleData>> modules, @Nonnull Project project) {
  Collection<DataNode<ModuleData>> result = ContainerUtilRt.newArrayList();
  for (DataNode<ModuleData> node : modules) {
    ModuleData moduleData = node.getData();
    Module module = ProjectStructureHelper.findIdeModule(moduleData, project);
    if (module == null) {
      result.add(node);
    }
    else {
      setModuleOptions(module, null, node);
    }
  }
  return result;
}
 
Example #4
Source File: ProjectDataManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> void importData(@Nonnull Key<T> key, @Nonnull Collection<DataNode<T>> nodes, @Nonnull Project project, boolean synchronous) {
  ensureTheDataIsReadyToUse(nodes);
  List<ProjectDataService<?, ?>> services = myServices.getValue().get(key);
  if (services == null) {
    LOG.warn(String.format(
      "Can't import data nodes '%s'. Reason: no service is registered for key %s. Available services for %s",
      nodes, key, myServices.getValue().keySet()
    ));
  }
  else {
    for (ProjectDataService<?, ?> service : services) {
      ((ProjectDataService<T, ?>)service).importData(nodes, project, synchronous);
    }
  }

  Collection<DataNode<?>> children = ContainerUtilRt.newArrayList();
  for (DataNode<T> node : nodes) {
    children.addAll(node.getChildren());
  }
  importData(children, project, synchronous);
}
 
Example #5
Source File: ExternalSystemRecentTaskListModelTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Test
public void testEnsureSize() throws Exception {
  List<ExternalTaskExecutionInfo> tasks = ContainerUtilRt.newArrayList();

  // test task list widening
  myModel.setTasks(tasks);
  myModel.ensureSize(ExternalSystemConstants.RECENT_TASKS_NUMBER);
  Assert.assertEquals("task list widening failed", ExternalSystemConstants.RECENT_TASKS_NUMBER, myModel.getSize());

  // test task list reduction
  for (int i = 0; i < ExternalSystemConstants.RECENT_TASKS_NUMBER + 1; i++) {
    tasks.add(new ExternalTaskExecutionInfo(new ExternalSystemTaskExecutionSettings(), "task" + i));
  }
  myModel.setTasks(tasks);
  Assert.assertEquals(ExternalSystemConstants.RECENT_TASKS_NUMBER + 1, myModel.getSize());

  myModel.ensureSize(ExternalSystemConstants.RECENT_TASKS_NUMBER);
  Assert.assertEquals("task list reduction failed", ExternalSystemConstants.RECENT_TASKS_NUMBER, myModel.getSize());
}
 
Example #6
Source File: ExternalSystemTestUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void assertMapsEqual(@Nonnull Map<?, ?> expected, @Nonnull Map<?, ?> actual) {
  Map<?, ?> local = ContainerUtilRt.newHashMap(expected);
  for (Map.Entry<?, ?> entry : actual.entrySet()) {
    Object expectedValue = local.remove(entry.getKey());
    if (expectedValue == null) {
      Assert.fail(String.format("Expected to find '%s' -> '%s' mapping but it doesn't exist", entry.getKey(), entry.getValue()));
    }
    if (!expectedValue.equals(entry.getValue())) {
      Assert.fail(
        String.format("Expected to find '%s' value for the key '%s' but got '%s'", expectedValue, entry.getKey(), entry.getValue())
      );
    }
  }
  if (!local.isEmpty()) {
    Assert.fail("No mappings found for the following keys: " + local.keySet());
  }
}
 
Example #7
Source File: StdArrangementEntryMatcher.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
@Override
public Collection<ArrangementEntryMatcher> buildMatchers() {
  List<ArrangementEntryMatcher> result = ContainerUtilRt.newArrayList(myMatchers);
  Collection<ArrangementAtomMatchCondition> entryTokens = context.get(StdArrangementTokenType.ENTRY_TYPE);
  if (entryTokens!= null) {
    result.add(new ByTypeArrangementEntryMatcher(entryTokens));
  }
  Collection<ArrangementAtomMatchCondition> modifierTokens = context.get(StdArrangementTokenType.MODIFIER);
  if (modifierTokens != null) {
    result.add(new ByModifierArrangementEntryMatcher(modifierTokens));
  }
  if (myNamePattern != null) {
    result.add(new ByNameArrangementEntryMatcher(myNamePattern));
  }
  if (myNamespacePattern != null) {
    result.add(new ByNamespaceArrangementEntryMatcher(myNamespacePattern));
  }
  if (myText != null) {
    result.add(new ByTextArrangementEntryMatcher(myText));
  }
  return result;
}
 
Example #8
Source File: ExternalSystemFacadeManager.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static <V> void onProjectRename(@Nonnull Map<IntegrationKey, V> data,
                                        @Nonnull String oldName,
                                        @Nonnull String newName)
{
  Set<IntegrationKey> keys = ContainerUtilRt.newHashSet(data.keySet());
  for (IntegrationKey key : keys) {
    if (!key.getIdeProjectName().equals(oldName)) {
      continue;
    }
    IntegrationKey newKey = new IntegrationKey(newName,
                                               key.getIdeProjectLocationHash(),
                                               key.getExternalSystemId(),
                                               key.getExternalProjectConfigPath());
    V value = data.get(key);
    data.put(newKey, value);
    data.remove(key);
    if (value instanceof Consumer) {
      //noinspection unchecked
      ((Consumer)value).consume(newKey);
    }
  }
}
 
Example #9
Source File: ExternalSystemTasksTree.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Schedules 'collapse/expand' state restoring for the given path. We can't do that immediately from the tree model listener
 * as there is a possible case that other listeners have not been notified about the model state change, hence, attempt to define
 * 'collapse/expand' state may bring us to the inconsistent state.
 *
 * @param path  target path
 */
private void scheduleCollapseStateAppliance(@Nonnull TreePath path) {
  myPathsToProcessCollapseState.add(path);
  myCollapseStateAlarm.cancelAllRequests();
  myCollapseStateAlarm.addRequest(new Runnable() {
    @Override
    public void run() {
      // We assume that the paths collection is modified only from the EDT, so, ConcurrentModificationException doesn't have
      // a chance.
      // Another thing is that we sort the paths in order to process the longest first. That is related to the JTree specifics
      // that it automatically expands parent paths on child path expansion.
      List<TreePath> paths = ContainerUtilRt.newArrayList(myPathsToProcessCollapseState);
      myPathsToProcessCollapseState.clear();
      Collections.sort(paths, PATH_COMPARATOR);
      for (TreePath treePath : paths) {
        applyCollapseState(treePath);
      }
      final TreePath rootPath = new TreePath(getModel().getRoot());
      if (isCollapsed(rootPath)) {
        expandPath(rootPath);
      }
    }
  }, COLLAPSE_STATE_PROCESSING_DELAY_MILLIS);
}
 
Example #10
Source File: StandardArrangementEntryMatcherTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Test
public void atomCondition() {
  ArrangementAtomMatchCondition condition = new ArrangementAtomMatchCondition(FIELD);
  
  StdArrangementEntryMatcher matcher = new StdArrangementEntryMatcher(condition);
  assertEquals(condition, matcher.getCondition());

  final TypeAwareArrangementEntry fieldEntry = myMockery.mock(TypeAwareArrangementEntry.class, "field");
  final TypeAwareArrangementEntry classEntry = myMockery.mock(TypeAwareArrangementEntry.class, "class");
  final ModifierAwareArrangementEntry publicEntry = myMockery.mock(ModifierAwareArrangementEntry.class, "public");
  myMockery.checking(new Expectations() {{
    allowing(fieldEntry).getTypes(); will(returnValue(ContainerUtilRt.newHashSet(FIELD)));
    allowing(classEntry).getTypes(); will(returnValue(ContainerUtilRt.newHashSet(CLASS)));
    allowing(publicEntry).getModifiers(); will(returnValue(ContainerUtilRt.newHashSet(PUBLIC)));
  }});
  
  assertTrue(matcher.isMatched(fieldEntry));
  assertFalse(matcher.isMatched(classEntry));
  assertFalse(matcher.isMatched(publicEntry));
}
 
Example #11
Source File: ExternalSystemExecuteTaskTask.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void doExecute() throws Exception {
  final ExternalSystemFacadeManager manager = ServiceManager.getService(ExternalSystemFacadeManager.class);
  ExternalSystemExecutionSettings settings = ExternalSystemApiUtil.getExecutionSettings(getIdeProject(),
                                                                                        getExternalProjectPath(),
                                                                                        getExternalSystemId());
  RemoteExternalSystemFacade facade = manager.getFacade(getIdeProject(), getExternalProjectPath(), getExternalSystemId());
  RemoteExternalSystemTaskManager taskManager = facade.getTaskManager();
  List<String> taskNames = ContainerUtilRt.map2List(myTasksToExecute, MAPPER);

  final List<String> vmOptions = parseCmdParameters(myVmOptions);
  final List<String> scriptParametersList = parseCmdParameters(myScriptParameters);

  taskManager.executeTasks(getId(), taskNames, getExternalProjectPath(), settings, vmOptions, scriptParametersList, myDebuggerSetup);
}
 
Example #12
Source File: VcsUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static Collection<VcsDirectoryMapping> findRoots(@Nonnull VirtualFile rootDir, @Nonnull Project project)
        throws IllegalArgumentException {
  if (!rootDir.isDirectory()) {
    throw new IllegalArgumentException(
            "Can't find VCS at the target file system path. Reason: expected to find a directory there but it's not. The path: "
            + rootDir.getParent()
    );
  }
  Collection<VcsRoot> roots = ServiceManager.getService(project, VcsRootDetector.class).detect(rootDir);
  Collection<VcsDirectoryMapping> result = ContainerUtilRt.newArrayList();
  for (VcsRoot vcsRoot : roots) {
    VirtualFile vFile = vcsRoot.getPath();
    AbstractVcs rootVcs = vcsRoot.getVcs();
    if (rootVcs != null && vFile != null) {
      result.add(new VcsDirectoryMapping(vFile.getPath(), rootVcs.getName()));
    }
  }
  return result;
}
 
Example #13
Source File: ArrangementMatchingRuleEditor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private Pair<ArrangementMatchCondition, ArrangementSettingsToken> buildCondition() {
  List<ArrangementMatchCondition> conditions = ContainerUtilRt.newArrayList();
  ArrangementSettingsToken orderType = null;
  for (ArrangementUiComponent component : myComponents.values()) {
    if (!component.isEnabled() || !component.isSelected()) {
      continue;
    }
    ArrangementSettingsToken token = component.getToken();
    if (token != null && StdArrangementTokenType.ORDER.is(token)) {
      orderType = token;
    }
    else {
      conditions.add(component.getMatchCondition());
    }
  }
  if (!conditions.isEmpty()) {
    if (orderType == null) {
      orderType = StdArrangementTokens.Order.KEEP;
    }
    return Pair.create(ArrangementUtil.combine(conditions.toArray(new ArrangementMatchCondition[conditions.size()])), orderType);
  }
  else {
    return null;
  }
}
 
Example #14
Source File: ArrangementSettingsPanel.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void resetImpl(CodeStyleSettings settings) {
  StdArrangementSettings s = getSettings(settings);
  if (s == null) {
    myGroupingRulesPanel.setRules(null);
    myMatchingRulesPanel.setSections(null);
  }
  else {
    List<ArrangementGroupingRule> groupings = s.getGroupings();
    myGroupingRulesPanel.setRules(ContainerUtilRt.newArrayList(groupings));
    myMatchingRulesPanel.setSections(copy(s.getSections()));
    if (myForceArrangementPanel != null) {
      myForceArrangementPanel.setSelectedMode(settings.getCommonSettings(myLanguage).FORCE_REARRANGE_MODE);
    }
  }
}
 
Example #15
Source File: ExternalSystemRecentTaskListModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public List<ExternalTaskExecutionInfo> getTasks() {
  List<ExternalTaskExecutionInfo> result = ContainerUtilRt.newArrayList();
  for (int i = 0; i < size(); i++) {
    Object e = getElementAt(i);
    if (e instanceof ExternalTaskExecutionInfo) {
      result.add((ExternalTaskExecutionInfo)e);
    }
  }
  return result;
}
 
Example #16
Source File: ExternalSystemUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public MyMultiExternalProjectRefreshCallback(Project project, ProjectDataManager projectDataManager, int[] counter, ProjectSystemId externalSystemId) {
  myProject = project;
  myProjectDataManager = projectDataManager;
  myCounter = counter;
  myExternalSystemId = externalSystemId;
  myExternalModulePaths = ContainerUtilRt.newHashSet();
}
 
Example #17
Source File: ExternalSystemTasksTreeModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void ensureTasks(@Nonnull String externalProjectConfigPath, @Nonnull Collection<ExternalTaskPojo> tasks) {
    if (tasks.isEmpty()) {
      return;
    }
    ExternalSystemNode<ExternalProjectPojo> moduleNode = findProjectNode(externalProjectConfigPath);
    if (moduleNode == null) {
//      LOG.warn(String.format(
//        "Can't proceed tasks for module which external config path is '%s'. Reason: no such module node is found. Tasks: %s",
//        externalProjectConfigPath, tasks
//      ));
      return;
    }
    Set<ExternalTaskExecutionInfo> toAdd = ContainerUtilRt.newHashSet();
    for (ExternalTaskPojo task : tasks) {
      toAdd.add(buildTaskInfo(task));
    }
    for (int i = 0; i < moduleNode.getChildCount(); i++) {
      ExternalSystemNode<?> childNode = moduleNode.getChildAt(i);
      Object element = childNode.getDescriptor().getElement();
      if (element instanceof ExternalTaskExecutionInfo) {
        if (!toAdd.remove(element)) {
          removeNodeFromParent(childNode);
          //noinspection AssignmentToForLoopParameter
          i--;
        }
      }
    }

    if (!toAdd.isEmpty()) {
      for (ExternalTaskExecutionInfo taskInfo : toAdd) {
        insertNodeInto(new ExternalSystemNode<>(descriptor(taskInfo, taskInfo.getDescription(), myUiAware.getTaskIcon())), moduleNode);
      }
    }
  }
 
Example #18
Source File: ExternalSystemTasksTreeModel.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void ensureSubProjectsStructure(@Nonnull ExternalProjectPojo topLevelProject, @Nonnull Collection<ExternalProjectPojo> subProjects) {
  ExternalSystemNode<ExternalProjectPojo> topLevelProjectNode = ensureProjectNodeExists(topLevelProject);
  Map<String/*config path*/, ExternalProjectPojo> toAdd = ContainerUtilRt.newHashMap();
  for (ExternalProjectPojo subProject : subProjects) {
    toAdd.put(subProject.getPath(), subProject);
  }
  toAdd.remove(topLevelProject.getPath());

  final TObjectIntHashMap<Object> taskWeights = new TObjectIntHashMap<>();
  for (int i = 0; i < topLevelProjectNode.getChildCount(); i++) {
    ExternalSystemNode<?> child = topLevelProjectNode.getChildAt(i);
    Object childElement = child.getDescriptor().getElement();
    if (childElement instanceof ExternalTaskExecutionInfo) {
      taskWeights.put(childElement, subProjects.size() + i);
      continue;
    }
    if (toAdd.remove(((ExternalProjectPojo)childElement).getPath()) == null) {
      removeNodeFromParent(child);
      //noinspection AssignmentToForLoopParameter
      i--;
    }
  }
  if (!toAdd.isEmpty()) {
    for (Map.Entry<String, ExternalProjectPojo> entry : toAdd.entrySet()) {
      ExternalProjectPojo element = new ExternalProjectPojo(entry.getValue().getName(), entry.getValue().getPath());
      insertNodeInto(new ExternalSystemNode<>(descriptor(element, myUiAware.getProjectIcon())), topLevelProjectNode);
    }
  }
}
 
Example #19
Source File: ExternalSystemUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void processOrphanProjectLibraries() {
  List<Library> orphanIdeLibraries = ContainerUtilRt.newArrayList();

  LibraryTable projectLibraryTable = ProjectLibraryTable.getInstance(myProject);
  for (Library library : projectLibraryTable.getLibraries()) {
    if (!ExternalSystemApiUtil.isExternalSystemLibrary(library, myExternalSystemId)) continue;
    if (ProjectStructureHelper.isOrphanProjectLibrary(library, ModuleManager.getInstance(myProject).getModules())) {
      orphanIdeLibraries.add(library);
    }
  }
  for (Library orphanIdeLibrary : orphanIdeLibraries) {
    projectLibraryTable.removeLibrary(orphanIdeLibrary);
  }
}
 
Example #20
Source File: ExternalSystemRecentTaskListModelTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetFirst() throws Exception {
  List<ExternalTaskExecutionInfo> tasks = ContainerUtilRt.newArrayList();
  for (int i = 0; i <= ExternalSystemConstants.RECENT_TASKS_NUMBER; i++) {
    new ExternalTaskExecutionInfo(new ExternalSystemTaskExecutionSettings(), "task" + i);
  }
  myModel.setTasks(tasks);

  myModel.setFirst(new ExternalTaskExecutionInfo(new ExternalSystemTaskExecutionSettings(), "newTask"));

  Assert.assertEquals(ExternalSystemConstants.RECENT_TASKS_NUMBER, myModel.getSize());
  myModel.setFirst(new ExternalTaskExecutionInfo(new ExternalSystemTaskExecutionSettings(), "task1"));
  Assert.assertEquals(ExternalSystemConstants.RECENT_TASKS_NUMBER, myModel.getSize());
}
 
Example #21
Source File: SchemesManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void schemeDeleted(@Nonnull Named scheme) {
  super.schemeDeleted(scheme);

  if (scheme instanceof ExternalizableScheme) {
    ContainerUtilRt.addIfNotNull(myFilesToDelete, ((ExternalizableScheme)scheme).getExternalInfo().getCurrentFileName());
  }
}
 
Example #22
Source File: DefaultArrangementEntryMatcherSerializer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(@Nonnull ArrangementCompositeMatchCondition condition) {
  Element composite = new Element(COMPOSITE_CONDITION_NAME);
  register(composite);
  parent = composite;
  List<ArrangementMatchCondition> operands = ContainerUtilRt.newArrayList(condition.getOperands());
  ContainerUtil.sort(operands, CONDITION_COMPARATOR);
  for (ArrangementMatchCondition c : operands) {
    c.invite(this);
  }
}
 
Example #23
Source File: ArrangementUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static <T> Set<T> flatten(@Nonnull Iterable<? extends Iterable<T>> data) {
  Set<T> result = ContainerUtilRt.newHashSet();
  for (Iterable<T> i : data) {
    for (T t : i) {
      result.add(t);
    }
  }
  return result;
}
 
Example #24
Source File: ArrangementUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static List<CompositeArrangementSettingsToken> flatten(@Nonnull CompositeArrangementSettingsToken base) {
  List<CompositeArrangementSettingsToken> result = ContainerUtilRt.newArrayList();
  Queue<CompositeArrangementSettingsToken> toProcess = ContainerUtilRt.newLinkedList(base);
  while (!toProcess.isEmpty()) {
    CompositeArrangementSettingsToken token = toProcess.remove();
    result.add(token);
    toProcess.addAll(token.getChildren());
  }
  return result;
}
 
Example #25
Source File: StandardArrangementEntryMatcherTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Test
public void compositeAndCondition() {
  ArrangementCompositeMatchCondition condition = new ArrangementCompositeMatchCondition();
  condition.addOperand(new ArrangementAtomMatchCondition(FIELD));
  condition.addOperand(new ArrangementAtomMatchCondition(PUBLIC));

  StdArrangementEntryMatcher matcher = new StdArrangementEntryMatcher(condition);
  assertEquals(condition, matcher.getCondition());

  final TypeAwareArrangementEntry fieldEntry = myMockery.mock(TypeAwareArrangementEntry.class, "field");
  final ModifierAwareArrangementEntry publicEntry = myMockery.mock(ModifierAwareArrangementEntry.class, "public");
  final TypeAndModifierAware privateFieldEntry = myMockery.mock(TypeAndModifierAware.class, "private field");
  final TypeAndModifierAware publicMethodEntry = myMockery.mock(TypeAndModifierAware.class, "public method");
  final TypeAndModifierAware publicFieldEntry = myMockery.mock(TypeAndModifierAware.class, "public field");
  final TypeAndModifierAware publicStaticFieldEntry = myMockery.mock(TypeAndModifierAware.class, "public static field");
  myMockery.checking(new Expectations() {{
    allowing(fieldEntry).getTypes(); will(returnValue(ContainerUtilRt.newHashSet(FIELD)));
    
    allowing(publicEntry).getModifiers(); will(returnValue(ContainerUtilRt.newHashSet(PUBLIC)));
    
    allowing(privateFieldEntry).getTypes(); will(returnValue(ContainerUtilRt.newHashSet(FIELD)));
    allowing(privateFieldEntry).getModifiers(); will(returnValue(ContainerUtilRt.newHashSet(PRIVATE)));
    
    allowing(publicMethodEntry).getTypes(); will(returnValue(ContainerUtilRt.newHashSet(METHOD)));
    allowing(publicMethodEntry).getModifiers(); will(returnValue(ContainerUtilRt.newHashSet(PUBLIC)));
    
    allowing(publicFieldEntry).getTypes(); will(returnValue(ContainerUtilRt.newHashSet(FIELD)));
    allowing(publicFieldEntry).getModifiers(); will(returnValue(ContainerUtilRt.newHashSet(PUBLIC)));

    allowing(publicStaticFieldEntry).getTypes(); will(returnValue(ContainerUtilRt.newHashSet(FIELD)));
    allowing(publicStaticFieldEntry).getModifiers(); will(returnValue(ContainerUtilRt.newHashSet(PUBLIC, STATIC)));
  }});
  
  assertFalse(matcher.isMatched(fieldEntry));
  assertFalse(matcher.isMatched(publicEntry));
  assertFalse(matcher.isMatched(privateFieldEntry));
  assertFalse(matcher.isMatched(publicMethodEntry));
  assertTrue(matcher.isMatched(publicFieldEntry));
  assertTrue(matcher.isMatched(publicStaticFieldEntry));
}
 
Example #26
Source File: VcsAwareFormatChangedTextUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public List<TextRange> getChangedTextRanges(@Nonnull Project project, @Nonnull PsiFile file) throws FilesTooBigForDiffException {
  Document document = PsiDocumentManager.getInstance(project).getDocument(file);
  if (document == null) return ContainerUtil.emptyList();

  List<TextRange> cachedChangedLines = getCachedChangedLines(project, document);
  if (cachedChangedLines != null) {
    return cachedChangedLines;
  }

  if (ApplicationManager.getApplication().isUnitTestMode()) {
    CharSequence testContent = file.getUserData(TEST_REVISION_CONTENT);
    if (testContent != null) {
      return calculateChangedTextRanges(document, testContent);
    }
  }

  Change change = ChangeListManager.getInstance(project).getChange(file.getVirtualFile());
  if (change == null) {
    return ContainerUtilRt.emptyList();
  }
  if (change.getType() == Change.Type.NEW) {
    return ContainerUtil.newArrayList(file.getTextRange());
  }

  String contentFromVcs = getRevisionedContentFrom(change);
  return contentFromVcs != null ? calculateChangedTextRanges(document, contentFromVcs)
                                : ContainerUtil.<TextRange>emptyList();
}
 
Example #27
Source File: AbstractBlock.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private List<Block> buildInjectedBlocks() {
  if (myBuildIndentsOnly) {
    return EMPTY;
  }
  if (!(this instanceof SettingsAwareBlock)) {
    return EMPTY;
  }
  PsiElement psi = myNode.getPsi();
  if (psi == null) {
    return EMPTY;
  }
  PsiFile file = psi.getContainingFile();
  if (file == null) {
    return EMPTY;
  }

  if (InjectedLanguageUtil.getCachedInjectedDocuments(file).isEmpty()) {
    return EMPTY;
  }

  TextRange blockRange = myNode.getTextRange();
  List<DocumentWindow> documentWindows = InjectedLanguageUtil.getCachedInjectedDocuments(file);
  for (DocumentWindow documentWindow : documentWindows) {
    int startOffset = documentWindow.injectedToHost(0);
    int endOffset = startOffset + documentWindow.getTextLength();
    if (blockRange.containsRange(startOffset, endOffset)) {
      PsiFile injected = PsiDocumentManager.getInstance(psi.getProject()).getCachedPsiFile(documentWindow);
      if (injected != null) {
        List<Block> result = ContainerUtilRt.newArrayList();
        DefaultInjectedLanguageBlockBuilder builder = new DefaultInjectedLanguageBlockBuilder(((SettingsAwareBlock)this).getSettings());
        builder.addInjectedBlocks(result, myNode, getWrap(), getAlignment(), getIndent());
        return result;
      }
    }
  }
  return EMPTY;
}
 
Example #28
Source File: LibraryDataService.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public Map<OrderRootType, Collection<File>> prepareLibraryFiles(@Nonnull LibraryData data) {
  Map<OrderRootType, Collection<File>> result = ContainerUtilRt.newHashMap();
  for (LibraryPathType pathType : LibraryPathType.values()) {
    final Set<String> paths = data.getPaths(pathType);
    if (paths.isEmpty()) {
      continue;
    }
    result.put(myLibraryPathTypeMapper.map(pathType), ContainerUtil.map(paths, File::new));
  }
  return result;
}
 
Example #29
Source File: ExternalSystemApiUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * There is a possible case that methods of particular object should be executed with classpath different from the one implied
 * by the current class' class loader. External system offers {@link ParametersEnhancer#enhanceLocalProcessing(List)} method
 * for defining that custom classpath.
 * <p>
 * It's also possible that particular implementation of {@link ParametersEnhancer} is compiled using dependency to classes
 * which are provided by the {@link ParametersEnhancer#enhanceLocalProcessing(List) expanded classpath}. E.g. a class
 * <code>'A'</code> might use method of class <code>'B'</code> and 'A' is located at the current (system/plugin) classpath but
 * <code>'B'</code> is not. We need to reload <code>'A'</code> using its expanded classpath then, i.e. create new class loaded
 * with that expanded classpath and load <code>'A'</code> by it.
 * <p>
 * This method allows to do that.
 *
 * @param clazz custom classpath-aware class which instance should be created (is assumed to have a no-args constructor)
 * @param <T>   target type
 * @return newly created instance of the given class loaded by custom classpath-aware loader
 * @throws IllegalAccessException    as defined by reflection processing
 * @throws InstantiationException    as defined by reflection processing
 * @throws NoSuchMethodException     as defined by reflection processing
 * @throws InvocationTargetException as defined by reflection processing
 * @throws ClassNotFoundException    as defined by reflection processing
 */
@Nonnull
public static <T extends ParametersEnhancer> T reloadIfNecessary(@Nonnull final Class<T> clazz)
        throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException {
  T instance = clazz.newInstance();
  List<URL> urls = ContainerUtilRt.newArrayList();
  instance.enhanceLocalProcessing(urls);
  if (urls.isEmpty()) {
    return instance;
  }

  final ClassLoader baseLoader = clazz.getClassLoader();
  Method method = baseLoader.getClass().getMethod("getUrls");
  if (method != null) {
    //noinspection unchecked
    urls.addAll((Collection<? extends URL>)method.invoke(baseLoader));
  }
  UrlClassLoader loader = new UrlClassLoader(UrlClassLoader.build().urls(urls).parent(baseLoader.getParent())) {
    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
      if (name.equals(clazz.getName())) {
        return super.loadClass(name, resolve);
      }
      else {
        try {
          return baseLoader.loadClass(name);
        }
        catch (ClassNotFoundException e) {
          return super.loadClass(name, resolve);
        }
      }
    }
  };
  //noinspection unchecked
  return (T)loader.loadClass(clazz.getName()).newInstance();
}
 
Example #30
Source File: ExternalSystemApiUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Nonnull
public static <T> Collection<DataNode<T>> findAll(@Nonnull DataNode<?> parent, @Nonnull Key<T> key) {
  Collection<DataNode<T>> result = null;
  for (DataNode<?> child : parent.getChildren()) {
    if (!key.equals(child.getKey())) {
      continue;
    }
    if (result == null) {
      result = ContainerUtilRt.newArrayList();
    }
    result.add((DataNode<T>)child);
  }
  return result == null ? Collections.<DataNode<T>>emptyList() : result;
}