com.intellij.openapi.externalSystem.util.ExternalSystemUtil Java Examples

The following examples show how to use com.intellij.openapi.externalSystem.util.ExternalSystemUtil. 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: AbstractToolWindowService.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void importData(@Nonnull final Collection<DataNode<T>> toImport, @Nonnull final Project project, boolean synchronous) {
  if (toImport.isEmpty()) {
    return;
  }
  ExternalSystemApiUtil.executeOnEdt(false, new Runnable() {
    @Override
    public void run() {
      ExternalSystemTasksTreeModel model = ExternalSystemUtil.getToolWindowElement(ExternalSystemTasksTreeModel.class,
                                                                                   project,
                                                                                   ExternalSystemDataKeys.ALL_TASKS_MODEL,
                                                                                   toImport.iterator().next().getData().getOwner());
      processData(toImport, project, model);
    }
  });
}
 
Example #2
Source File: RefreshAllExternalProjectsAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {
  final Project project = e.getDataContext().getData(CommonDataKeys.PROJECT);
  if (project == null) {
    e.getPresentation().setEnabled(false);
    return;
  }

  final List<ProjectSystemId> systemIds = getSystemIds(e);
  if (systemIds.isEmpty()) {
    e.getPresentation().setEnabled(false);
    return;
  }

  // We save all documents because there is a possible case that there is an external system config file changed inside the ide.
  FileDocumentManager.getInstance().saveAllDocuments();

  for (ProjectSystemId externalSystemId : systemIds) {
    ExternalSystemUtil.refreshProjects(project, externalSystemId, true);
  }
}
 
Example #3
Source File: PantsOpenProjectProvider.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
private void refresh(VirtualFile file, Project project) {
  ExternalSystemUtil.refreshProject(
    file.getPath(),
    new ImportSpecBuilder(project, PantsConstants.SYSTEM_ID).usePreviewMode().use(ProgressExecutionMode.MODAL_SYNC)
  );
  ExternalSystemUtil.refreshProject(
    file.getPath(),
    new ImportSpecBuilder(project, PantsConstants.SYSTEM_ID)
  );
}
 
Example #4
Source File: ExternalProjectUtil.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
public static void refresh(@NotNull Project project, ProjectSystemId id) {
  // This code needs to run on the dispatch thread, but in some cases
  // refreshAllProjects() is called on a non-dispatch thread; we use
  // invokeLater() to run in the dispatch thread.
  ApplicationManager.getApplication().invokeAndWait(
    () -> {
      ApplicationManager.getApplication().runWriteAction(() -> FileDocumentManager.getInstance().saveAllDocuments());

      final ImportSpecBuilder specBuilder = new ImportSpecBuilder(project, id);
      ProgressExecutionMode executionMode = ApplicationManager.getApplication().isUnitTestMode() ?
                                            ProgressExecutionMode.MODAL_SYNC : ProgressExecutionMode.IN_BACKGROUND_ASYNC;
      specBuilder.use(executionMode);
      ExternalSystemUtil.refreshProjects(specBuilder);
    });
}
 
Example #5
Source File: ExternalSystemImportingTestCase.java    From intellij-quarkus with Eclipse Public License 2.0 4 votes vote down vote up
private void doImportProject() {
  AbstractExternalSystemSettings systemSettings = ExternalSystemApiUtil.getSettings(myProject, getExternalSystemId());
  final ExternalProjectSettings projectSettings = getCurrentExternalProjectSettings();
  projectSettings.setExternalProjectPath(getProjectPath());
  //noinspection unchecked
  Set<ExternalProjectSettings> projects = ContainerUtilRt.newHashSet(systemSettings.getLinkedProjectsSettings());
  projects.remove(projectSettings);
  projects.add(projectSettings);
  //noinspection unchecked
  systemSettings.setLinkedProjectsSettings(projects);

  final Ref<Couple<String>> error = Ref.create();
  ImportSpec importSpec = createImportSpec();
  if (importSpec.getCallback() == null) {
    importSpec = new ImportSpecBuilder(importSpec).callback(new ExternalProjectRefreshCallback() {
      @Override
      public void onSuccess(@Nullable final DataNode<ProjectData> externalProject) {
        if (externalProject == null) {
          System.err.println("Got null External project after import");
          return;
        }
        ServiceManager.getService(ProjectDataManager.class).importData(externalProject, myProject, true);
        System.out.println("External project was successfully imported");
      }

      @Override
      public void onFailure(@NotNull String errorMessage, @Nullable String errorDetails) {
        error.set(Couple.of(errorMessage, errorDetails));
      }
    }).build();
  }

  ExternalSystemProgressNotificationManager notificationManager =
    ServiceManager.getService(ExternalSystemProgressNotificationManager.class);
  ExternalSystemTaskNotificationListenerAdapter listener = new ExternalSystemTaskNotificationListenerAdapter() {
    @Override
    public void onTaskOutput(@NotNull ExternalSystemTaskId id, @NotNull String text, boolean stdOut) {
      if (StringUtil.isEmptyOrSpaces(text)) return;
      (stdOut ? System.out : System.err).print(text);
    }
  };
  notificationManager.addNotificationListener(listener);
  try {
    ExternalSystemUtil.refreshProjects(importSpec);
  }
  finally {
    notificationManager.removeNotificationListener(listener);
  }

  if (!error.isNull()) {
    String failureMsg = "Import failed: " + error.get().first;
    if (StringUtil.isNotEmpty(error.get().second)) {
      failureMsg += "\nError details: \n" + error.get().second;
    }
    fail(failureMsg);
  }
}
 
Example #6
Source File: PantsExternalTaskConfigurationType.java    From intellij-pants-plugin with Apache License 2.0 4 votes vote down vote up
public static PantsExternalTaskConfigurationType getInstance() {
  return (PantsExternalTaskConfigurationType)ExternalSystemUtil.findConfigurationType(PantsConstants.SYSTEM_ID);
}
 
Example #7
Source File: AbstractExternalModuleImportProvider.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
@Override
public void process(@Nonnull ExternalModuleImportContext<C> context, @Nonnull final Project project, @Nonnull ModifiableModuleModel model, @Nonnull Consumer<Module> newModuleConsumer) {
  project.putUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT, Boolean.TRUE);
  final DataNode<ProjectData> externalProjectNode = getExternalProjectNode();
  if (externalProjectNode != null) {
    beforeCommit(externalProjectNode, project);
  }

  StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() {
    @SuppressWarnings("unchecked")
    @Override
    public void run() {
      AbstractExternalSystemSettings systemSettings = ExternalSystemApiUtil.getSettings(project, myExternalSystemId);
      final ExternalProjectSettings projectSettings = getCurrentExternalProjectSettings();
      Set<ExternalProjectSettings> projects = ContainerUtilRt.<ExternalProjectSettings>newHashSet(systemSettings.getLinkedProjectsSettings());
      // add current importing project settings to linked projects settings or replace if similar already exist
      projects.remove(projectSettings);
      projects.add(projectSettings);

      systemSettings.copyFrom(myControl.getSystemSettings());
      systemSettings.setLinkedProjectsSettings(projects);

      if (externalProjectNode != null) {
        ExternalSystemUtil.ensureToolWindowInitialized(project, myExternalSystemId);
        ExternalSystemApiUtil.executeProjectChangeAction(new DisposeAwareProjectChange(project) {
          @RequiredUIAccess
          @Override
          public void execute() {
            ProjectRootManagerEx.getInstanceEx(project).mergeRootsChangesDuring(new Runnable() {
              @Override
              public void run() {
                myProjectDataManager.importData(externalProjectNode.getKey(), Collections.singleton(externalProjectNode), project, true);
                myExternalProjectNode = null;
              }
            });
          }
        });

        final Runnable resolveDependenciesTask = new Runnable() {
          @Override
          public void run() {
            String progressText = ExternalSystemBundle.message("progress.resolve.libraries", myExternalSystemId.getReadableName());
            ProgressManager.getInstance().run(new Task.Backgroundable(project, progressText, false) {
              @Override
              public void run(@Nonnull final ProgressIndicator indicator) {
                if (project.isDisposed()) return;
                ExternalSystemResolveProjectTask task = new ExternalSystemResolveProjectTask(myExternalSystemId, project, projectSettings.getExternalProjectPath(), false);
                task.execute(indicator, ExternalSystemTaskNotificationListener.EP_NAME.getExtensions());
                DataNode<ProjectData> projectWithResolvedLibraries = task.getExternalProject();
                if (projectWithResolvedLibraries == null) {
                  return;
                }

                setupLibraries(projectWithResolvedLibraries, project);
              }
            });
          }
        };
        UIUtil.invokeLaterIfNeeded(resolveDependenciesTask);
      }
    }
  });
}
 
Example #8
Source File: AbstractExternalModuleImportProvider.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Asks current builder to ensure that target external project is defined.
 *
 * @param context current wizard context
 * @throws WizardStepValidationException if gradle project is not defined and can't be constructed
 */
@SuppressWarnings("unchecked")
public void ensureProjectIsDefined(@Nonnull ExternalModuleImportContext<C> context) throws WizardStepValidationException {
  final String externalSystemName = myExternalSystemId.getReadableName();
  File projectFile = getProjectFile();
  if (projectFile == null) {
    throw new WizardStepValidationException(ExternalSystemBundle.message("error.project.undefined"));
  }
  projectFile = getExternalProjectConfigToUse(projectFile);
  final Ref<WizardStepValidationException> error = new Ref<>();
  final ExternalProjectRefreshCallback callback = new ExternalProjectRefreshCallback() {
    @Override
    public void onSuccess(@Nullable DataNode<ProjectData> externalProject) {
      myExternalProjectNode = externalProject;
    }

    @Override
    public void onFailure(@Nonnull String errorMessage, @Nullable String errorDetails) {
      if (!StringUtil.isEmpty(errorDetails)) {
        LOG.warn(errorDetails);
      }
      error.set(new WizardStepValidationException(ExternalSystemBundle.message("error.resolve.with.reason", errorMessage)));
    }
  };

  final Project project = getContextOrDefaultProject(context);
  final File finalProjectFile = projectFile;
  final String externalProjectPath = FileUtil.toCanonicalPath(finalProjectFile.getAbsolutePath());
  final Ref<WizardStepValidationException> exRef = new Ref<>();
  executeAndRestoreDefaultProjectSettings(project, new Runnable() {
    @Override
    public void run() {
      try {
        ExternalSystemUtil.refreshProject(project, myExternalSystemId, externalProjectPath, callback, true, ProgressExecutionMode.MODAL_SYNC);
      }
      catch (IllegalArgumentException e) {
        exRef.set(new WizardStepValidationException(ExternalSystemBundle.message("error.cannot.parse.project", externalSystemName)));
      }
    }
  });
  WizardStepValidationException ex = exRef.get();
  if (ex != null) {
    throw ex;
  }
  if (myExternalProjectNode == null) {
    WizardStepValidationException exception = error.get();
    if (exception != null) {
      throw exception;
    }
  }
  else {
    applyProjectSettings(context);
  }
}
 
Example #9
Source File: ExternalSystemNotificationManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
public void showNotification(@Nonnull final ProjectSystemId externalSystemId, @Nonnull final NotificationData notificationData) {
  myUpdater.execute(new Runnable() {
    @Override
    public void run() {
      if (myProject.isDisposed()) return;

      if (!initializedExternalSystem.contains(externalSystemId)) {
        final Application app = ApplicationManager.getApplication();
        Runnable action = new Runnable() {
          @Override
          public void run() {
            app.runWriteAction(new Runnable() {
              @Override
              public void run() {
                if (myProject.isDisposed()) return;
                ExternalSystemUtil.ensureToolWindowContentInitialized(myProject, externalSystemId);
                initializedExternalSystem.add(externalSystemId);
              }
            });
          }
        };
        if (app.isDispatchThread()) {
          action.run();
        }
        else {
          app.invokeAndWait(action, ModalityState.defaultModalityState());
        }
      }

      final NotificationGroup group = ExternalSystemUtil.getToolWindowElement(
              NotificationGroup.class, myProject, ExternalSystemDataKeys.NOTIFICATION_GROUP, externalSystemId);
      if (group == null) return;

      final Notification notification = group.createNotification(
              notificationData.getTitle(), notificationData.getMessage(),
              notificationData.getNotificationCategory().getNotificationType(), notificationData.getListener());

      myNotifications.add(notification);

      if (notificationData.isBalloonNotification()) {
        applyNotification(notification);
      }
      else {
        addMessage(notification, externalSystemId, notificationData);
      }
    }
  });
}
 
Example #10
Source File: ExternalSystemNotificationManager.java    From consulo with Apache License 2.0 4 votes vote down vote up
private void addMessage(@Nonnull final Notification notification,
                        @Nonnull final ProjectSystemId externalSystemId,
                        @Nonnull final NotificationData notificationData) {
  final VirtualFile virtualFile =
          notificationData.getFilePath() != null ? ExternalSystemUtil.waitForTheFile(notificationData.getFilePath()) : null;
  final String groupName = virtualFile != null ? virtualFile.getPresentableUrl() : notificationData.getTitle();

  myMessageCounter
          .increment(groupName, notificationData.getNotificationSource(), notificationData.getNotificationCategory(), externalSystemId);

  int line = notificationData.getLine() - 1;
  int column = notificationData.getColumn() - 1;
  if (virtualFile == null) line = column = -1;
  final int guiLine = line < 0 ? -1 : line + 1;
  final int guiColumn = column < 0 ? 0 : column + 1;

  final Navigatable navigatable = notificationData.getNavigatable() != null
                                  ? notificationData.getNavigatable()
                                  : virtualFile != null ? new OpenFileDescriptor(myProject, virtualFile, line, column) : null;

  final ErrorTreeElementKind kind =
          ErrorTreeElementKind.convertMessageFromCompilerErrorType(notificationData.getNotificationCategory().getMessageCategory());
  final String[] message = notificationData.getMessage().split("\n");
  final String exportPrefix = NewErrorTreeViewPanel.createExportPrefix(guiLine);
  final String rendererPrefix = NewErrorTreeViewPanel.createRendererPrefix(guiLine, guiColumn);

  UIUtil.invokeLaterIfNeeded(new Runnable() {
    @Override
    public void run() {
      boolean activate =
              notificationData.getNotificationCategory() == NotificationCategory.ERROR ||
              notificationData.getNotificationCategory() == NotificationCategory.WARNING;
      final NewErrorTreeViewPanel errorTreeView =
              prepareMessagesView(externalSystemId, notificationData.getNotificationSource(), activate);
      final GroupingElement groupingElement = errorTreeView.getErrorViewStructure().getGroupingElement(groupName, null, virtualFile);
      final NavigatableMessageElement navigatableMessageElement;
      if (notificationData.hasLinks()) {
        navigatableMessageElement = new EditableNotificationMessageElement(
                notification,
                kind,
                groupingElement,
                message,
                navigatable,
                exportPrefix,
                rendererPrefix);
      }
      else {
        navigatableMessageElement = new NotificationMessageElement(
                kind,
                groupingElement,
                message,
                navigatable,
                exportPrefix,
                rendererPrefix);
      }

      errorTreeView.getErrorViewStructure().addNavigatableMessage(groupName, navigatableMessageElement);
      errorTreeView.updateTree();
    }
  });
}
 
Example #11
Source File: DetachExternalProjectAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  ExternalActionUtil.MyInfo info = ExternalActionUtil.getProcessingInfo(e.getDataContext());
  if (info.settings == null || info.localSettings == null || info.externalProject == null || info.ideProject == null
      || info.externalSystemId == null)
  {
    return;
  }
  
  e.getPresentation().setText(
    ExternalSystemBundle.message("action.detach.external.project.text",info.externalSystemId.getReadableName())
  );

  ExternalSystemTasksTreeModel allTasksModel = e.getDataContext().getData(ExternalSystemDataKeys.ALL_TASKS_MODEL);
  if (allTasksModel != null) {
    allTasksModel.pruneNodes(info.externalProject);
  }

  ExternalSystemRecentTasksList recentTasksList = e.getDataContext().getData(ExternalSystemDataKeys.RECENT_TASKS_LIST);
  if (recentTasksList != null) {
    recentTasksList.getModel().forgetTasksFrom(info.externalProject.getPath());
  }
  
  info.localSettings.forgetExternalProjects(Collections.singleton(info.externalProject.getPath()));
  info.settings.unlinkExternalProject(info.externalProject.getPath());

  // Process orphan modules.
  String externalSystemIdAsString = info.externalSystemId.toString();
  List<Module> orphanModules = ContainerUtilRt.newArrayList();
  for (Module module : ModuleManager.getInstance(info.ideProject).getModules()) {
    String systemId = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY);
    if (!externalSystemIdAsString.equals(systemId)) {
      continue;
    }
    String path = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.LINKED_PROJECT_PATH_KEY);
    if (info.externalProject.getPath().equals(path)) {
      orphanModules.add(module);
    }
  }

  if (!orphanModules.isEmpty()) {
    ExternalSystemUtil.ruleOrphanModules(orphanModules, info.ideProject, info.externalSystemId);
  }
}