Java Code Examples for com.intellij.openapi.ui.Messages#showErrorDialog()

The following examples show how to use com.intellij.openapi.ui.Messages#showErrorDialog() . 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: ExternalMergeTool.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void show(@javax.annotation.Nullable final Project project,
                        @Nonnull final MergeRequest request) {
  try {
    if (canShow(request)) {
      showRequest(project, request);
    }
    else {
      DiffManagerEx.getInstance().showMergeBuiltin(project, request);
    }
  }
  catch (ProcessCanceledException ignore) {
  }
  catch (Throwable e) {
    LOG.error(e);
    Messages.showErrorDialog(project, e.getMessage(), "Can't Show Merge In External Tool");
  }
}
 
Example 2
Source File: PatchApplier.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void showError(final Project project, final String message, final boolean error) {
  final Application application = ApplicationManager.getApplication();
  if (application.isUnitTestMode()) {
    return;
  }
  final String title = VcsBundle.message("patch.apply.dialog.title");
  final Runnable messageShower = new Runnable() {
    @Override
    public void run() {
      if (error) {
        Messages.showErrorDialog(project, message, title);
      }
      else {
        Messages.showInfoMessage(project, message, title);
      }
    }
  };
  WaitForProgressToShow.runOrInvokeLaterAboveProgress(new Runnable() {
    @Override
    public void run() {
      messageShower.run();
    }
  }, null, project);
}
 
Example 3
Source File: FlutterProjectCreator.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private VirtualFile getLocationFromModel(@Nullable Project projectToClose, boolean saveLocation) {
  final File location = new File(FileUtil.toSystemDependentName(myModel.projectLocation().get()));
  if (!location.exists() && !location.mkdirs()) {
    String message = ActionsBundle.message("action.NewDirectoryProject.cannot.create.dir", location.getAbsolutePath());
    Messages.showErrorDialog(projectToClose, message, ActionsBundle.message("action.NewDirectoryProject.title"));
    return null;
  }
  final File baseFile = new File(location, myModel.projectName().get());
  //noinspection ResultOfMethodCallIgnored
  baseFile.mkdirs();
  final VirtualFile baseDir = ApplicationManager.getApplication().runWriteAction(
    (Computable<VirtualFile>)() -> LocalFileSystem.getInstance().refreshAndFindFileByIoFile(baseFile));
  if (baseDir == null) {
    FlutterUtils.warn(LOG, "Couldn't find '" + location + "' in VFS");
    return null;
  }
  if (saveLocation) {
    RecentProjectsManager.getInstance().setLastProjectCreationLocation(location.getPath());
  }
  return baseDir;
}
 
Example 4
Source File: ProjectViewEdit.java    From intellij with Apache License 2.0 6 votes vote down vote up
private void apply(boolean isApply) {
  SaveUtil.saveAllFiles();
  for (Modification modification : modifications) {
    ProjectView projectView = isApply ? modification.newProjectView : modification.oldProjectView;
    String projectViewText = ProjectViewParser.projectViewToString(projectView);
    try {
      ProjectViewStorageManager.getInstance()
          .writeProjectView(projectViewText, modification.projectViewFile);
    } catch (IOException e) {
      logger.error(e);
      Messages.showErrorDialog(
          project,
          "Could not write updated project view. Is the file write protected?",
          "Edit Failed");
    }
  }
  // now that we've changed it, reload our in-memory view
  reloadProjectView(project);
}
 
Example 5
Source File: FlutterProjectCreator.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static boolean finalValidityCheckPassed(@NotNull String projectLocation) {
  // See AS NewProjectModel.ProjectTemplateRenderer.doDryRun() for why this is necessary.
  boolean couldEnsureLocationExists = WriteCommandAction.runWriteCommandAction(null, (Computable<Boolean>)() -> {
    try {
      if (VfsUtil.createDirectoryIfMissing(projectLocation) != null && FileOpUtils.create().canWrite(new File(projectLocation))) {
        return true;
      }
    }
    catch (Exception e) {
      LOG.warn(String.format("Exception thrown when creating target project location: %1$s", projectLocation), e);
    }
    return false;
  });
  if (!couldEnsureLocationExists) {
    String msg =
      "Could not ensure the target project location exists and is accessible:\n\n%1$s\n\nPlease try to specify another path.";
    Messages.showErrorDialog(String.format(msg, projectLocation), "Error Creating Project");
    return false;
  }
  return true;
}
 
Example 6
Source File: ToolWindowFactory.java    From adc with Apache License 2.0 6 votes vote down vote up
public void createToolWindowContent(@NotNull final Project project, @NotNull final ToolWindow toolWindow) {
    ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();
    JPanel framePanel = createPanel(project);
    disableAll();

    AndroidDebugBridge adb = AndroidSdkUtils.getDebugBridge(project);
    if (adb == null) {
        return;
    }

    if(adb.isConnected()){
        ToolWindowFactory.this.adBridge = adb;
        Logger.getInstance(ToolWindowFactory.class).info("Successfully obtained debug bridge");
        AndroidDebugBridge.addDeviceChangeListener(deviceChangeListener);
        updateDeviceComboBox();
    } else {
        Logger.getInstance(ToolWindowFactory.class).info("Unable to obtain debug bridge");
        String msg = MessageFormat.format(resourceBundle.getString("error.message.adb"), "");
        Messages.showErrorDialog(msg, resourceBundle.getString("error.title.adb"));
    }

    Content content = contentFactory.createContent(framePanel, "", false);
    toolWindow.getContentManager().addContent(content);
}
 
Example 7
Source File: ProjectOpener.java    From tmc-intellij with MIT License 5 votes vote down vote up
public void openProject(Project project, String path) {
    logger.info("Opening project from {}. @ProjectOpener", path);
    if (Files.isDirectory(Paths.get(path))) {
        if (project == null || !path.equals(project.getBasePath())) {
            try {
                if (project != null) {
                    new ActivateSnapshotsListeners(project).removeListeners();
                }
                ExerciseImport.importExercise(path);
                ProjectUtil.openOrImport(path, project, true);
                if (project != null) {
                    ProjectManager.getInstance().closeProject(project);
                }

                String[] split = PathResolver.getCourseAndExerciseName(path);
                Course course = new ObjectFinder().findCourse(split[split.length - 2], "name");
                TmcSettingsManager.get().setCourse(Optional.of(course));

            } catch (Exception exception) {
                logger.warn(
                        "Could not open project from path. @ProjectOpener",
                        exception,
                        exception.getStackTrace());
                new ErrorMessageService()
                        .showErrorMessageWithExceptionDetails(
                                exception, "Could not open project from path. " + path, true);
            }
        }
    } else {
        logger.warn("Directory no longer exists. @ProjectOpener");
        Messages.showErrorDialog(
                new ObjectFinder().findCurrentProject(),
                "Directory no longer exists",
                "File not found");
        ProjectListManagerHolder.get().refreshAllCourses();
    }
}
 
Example 8
Source File: FlutterConsoleFilter.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void navigate(final Project project) {
  // TODO(skybrian) analytics for clicking the link? (We do log the command.)
  final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
  if (sdk == null) {
    Messages.showErrorDialog(project, "Flutter SDK not found", "Error");
    return;
  }
  if (sdk.flutterDoctor().startInConsole(project) == null) {
    Messages.showErrorDialog(project, "Failed to start 'flutter doctor'", "Error");
  }
}
 
Example 9
Source File: NutzBootMakerChooseWizardStep.java    From NutzCodeInsight with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validate() throws ConfigurationException {
    try {
        if (Strings.isNullOrEmpty(packageName.getText())) {
            Messages.showErrorDialog("顶层包名不能为空", "错误提示");
            return false;
        }
        if (Strings.isNullOrEmpty(groupId.getText())) {
            Messages.showErrorDialog("项目组织名不能为空", "错误提示");
            return false;
        }
        if (Strings.isNullOrEmpty(artifactId.getText())) {
            Messages.showErrorDialog("项目ID不能为空", "错误提示");
            return false;
        }
        if (Strings.isNullOrEmpty(finalName.getText())) {
            Messages.showErrorDialog("发布文件名不能为空", "错误提示");
            return false;
        }
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(new ByteArrayInputStream(gson.toJson(getPostData()).getBytes()));
        String json = HttpUtil.post(makerUrl.getText() + "/maker/make", entity);
        HashMap redata = gson.fromJson(json, HashMap.class);
        boolean ok = Boolean.parseBoolean(String.valueOf(redata.getOrDefault("ok", "false")));
        if (ok) {
            downLoadKey = String.valueOf(redata.get("key"));
            moduleBuilder.setModuleName(finalName.getText());
            return true;
        } else {
            downLoadKey = null;
            Messages.showErrorDialog(redata.getOrDefault("msg", "服务暂不可用!请稍后再试!").toString(), "错误提示");
            return false;
        }
    } catch (Exception e) {
        throw new ConfigurationException("构筑中心发生未知异常! " + e.getMessage());
    }
}
 
Example 10
Source File: AnnotateActionTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Test
public void testExecute_NullContext() {
    when(mockActionContext.getServerContext()).thenReturn(null);
    annotateAction.execute(mockActionContext);

    verifyStatic(times(1));
    Messages.showErrorDialog(mockProject, TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_ANNOTATE_ERROR_MSG),
            TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_ANNOTATE_ERROR_TITLE));
    verifyStatic(times(0));
    BrowserUtil.browse(any(URI.class));
}
 
Example 11
Source File: VcsImplUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Shows error message with specified message text and title.
 * The parent component is the root frame.
 *
 * @param project Current project component
 * @param message information message
 * @param title   Dialog title
 */
public static void showErrorMessage(final Project project, final String message, final String title) {
  Runnable task = new Runnable() {
    public void run() {
      Messages.showErrorDialog(project, message, title);
    }
  };
  WaitForProgressToShow.runOrInvokeLaterAboveProgress(task, null, project);
}
 
Example 12
Source File: GenerateFscElementAction.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent anActionEvent) {

    Project project = anActionEvent.getProject();
    if (project == null) {
        return;
    }

    ToolWindow toolWindow = anActionEvent.getData(PlatformDataKeys.TOOL_WINDOW);
    if (toolWindow == null) {
        return;
    }

    PsiDirectory[] psiDirectories = ActionUtil.findDirectoryFromActionEvent(anActionEvent);
    if (psiDirectories.length == 0) {
        return;
    }

    TYPO3ExtensionDefinition extensionDefinition = TYPO3ExtensionUtil.findContainingExtension(psiDirectories);
    if (extensionDefinition == null) {
        Messages.showErrorDialog(
                "Could not extract extension from working directory. Does your extension contain a composer manifest?",
                "Error While Trying to Find Extension"
        );
        return;
    }

    GenerateFscElementForm.create(toolWindow.getComponent(), project, extensionDefinition);
}
 
Example 13
Source File: ServerPathCellEditorTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Test
public void testCreateBrowserDialog_NoPath() {
    ServerPathCellEditor editor = new ServerPathCellEditor("title", mockProject, mockContext);
    ServerPathCellEditor spy = spy(editor);
    doReturn(StringUtils.EMPTY).when(spy).getServerPath();

    spy.createBrowserDialog();
    verifyStatic(times(1));
    Messages.showErrorDialog(eq(mockProject), eq(TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_MSG)),
            eq(TfPluginBundle.message(TfPluginBundle.KEY_ACTIONS_TFVC_SERVER_TREE_NO_ROOT_TITLE)));
}
 
Example 14
Source File: ManageWorkspacesModelTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Test
public void testReloadWorkspacesWithProgress_Exception() throws Exception {
    final MockObserver observer = new MockObserver(manageWorkspacesModel);
    when(VcsUtil.runVcsProcessWithProgress(any(VcsRunnable.class), eq(TfPluginBundle.message(TfPluginBundle.KEY_TFVC_MANAGE_WORKSPACES_RELOAD_MSG, server.getName())), eq(true), eq(mockProject)))
            .thenThrow(new VcsException(TfPluginBundle.message(TfPluginBundle.KEY_TFVC_MANAGE_WORKSPACES_RELOAD_ERROR_MSG, server.getName())));
    manageWorkspacesModel.reloadWorkspacesWithProgress(server);

    observer.assertAndClearLastUpdate(manageWorkspacesModel, ManageWorkspacesModel.REFRESH_SERVER);
    verifyStatic(times(1));
    Messages.showErrorDialog(eq(mockProject), eq(TfPluginBundle.message(TfPluginBundle.KEY_TFVC_MANAGE_WORKSPACES_RELOAD_ERROR_MSG, server.getName())),
            eq(TfPluginBundle.message(TfPluginBundle.KEY_TFVC_MANAGE_WORKSPACES_RELOAD_ERROR_TITLE)));
}
 
Example 15
Source File: SettingsDialog.java    From PackageTemplates with Apache License 2.0 5 votes vote down vote up
private boolean isDataValid() {
    lvAutoImport.collectDataFromUI();

    for (String path : paths) {
        if (path.trim().isEmpty()) {
            Messages.showErrorDialog(Localizer.get("warning.PathShoudntBeEmpty"), "AutoImport");
            return false;
        }
    }

    return true;
}
 
Example 16
Source File: PluginUtils.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static void notifyPluginEnableFailed(String pluginId) {
  String msg =
      String.format(
          "Failed to enable plugin '%s'. Check for errors in the Event Log, or run 'Help > Check "
              + "for Updates' to check if the plugin needs updating.",
          pluginId);
  Messages.showErrorDialog(msg, "Failed to enable plugin");
}
 
Example 17
Source File: ManageWorkspacesModelTest.java    From azure-devops-intellij with MIT License 5 votes vote down vote up
@Test
public void testEditWorkspaceWithProgress_Happy() throws Exception {
    manageWorkspacesModel.editWorkspaceWithProgress(workspace1, mockRunnable);

    verifyStatic(never());
    Messages.showErrorDialog(any(Project.class), any(String.class), any(String.class));
}
 
Example 18
Source File: SuggestBuildShardingNotification.java    From intellij with Apache License 2.0 5 votes vote down vote up
private static void editProjectViewAndResync(Project project, ProjectViewEditor editor) {
  ProjectViewEdit edit = ProjectViewEdit.editLocalProjectView(project, editor);
  if (edit == null) {
    Messages.showErrorDialog(
        "Could not modify project view. Check for errors in your project view and try again",
        "Error");
    return;
  }
  edit.apply();
  OpenProjectViewAction.openLocalProjectViewFile(project);
  BlazeSyncManager.getInstance(project)
      .incrementalProjectSync(/* reason= */ "SuggestBuildShardingNotification");
}
 
Example 19
Source File: ShowAllAffectedGenericAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static void showSubmittedFiles(final Project project, final VcsRevisionNumber revision, final VirtualFile virtualFile,
                                       final VcsKey vcsKey, final RepositoryLocation location, final boolean isNonLocal) {
  final AbstractVcs vcs = ProjectLevelVcsManager.getInstance(project).findVcsByName(vcsKey.getName());
  if (vcs == null) return;
  if (isNonLocal && ! canPresentNonLocal(project, vcsKey, virtualFile)) return;

  final String title = VcsBundle.message("paths.affected.in.revision",
                                         revision instanceof ShortVcsRevisionNumber
                                             ? ((ShortVcsRevisionNumber) revision).toShortString()
                                             :  revision.asString());
  final CommittedChangeList[] list = new CommittedChangeList[1];
  final VcsException[] exc = new VcsException[1];
  Task.Backgroundable task = new Task.Backgroundable(project, title, true, BackgroundFromStartOption.getInstance()) {
    @Override
    public void run(@Nonnull ProgressIndicator indicator) {
      try {
        final CommittedChangesProvider provider = vcs.getCommittedChangesProvider();
        if (!isNonLocal) {
          final Pair<CommittedChangeList, FilePath> pair = provider.getOneList(virtualFile, revision);
          if (pair != null) {
            list[0] = pair.getFirst();
          }
        }
        else {
          if (location != null) {
            final ChangeBrowserSettings settings = provider.createDefaultSettings();
            settings.USE_CHANGE_BEFORE_FILTER = true;
            settings.CHANGE_BEFORE = revision.asString();
            final List<CommittedChangeList> changes = provider.getCommittedChanges(settings, location, 1);
            if (changes != null && changes.size() == 1) {
              list[0] = changes.get(0);
            }
            return;
          }
          else {
            list[0] = getRemoteList(vcs, revision, virtualFile);
            /*final RepositoryLocation local = provider.getForNonLocal(virtualFile);
            if (local != null) {
              final String number = revision.asString();
              final ChangeBrowserSettings settings = provider.createDefaultSettings();
              final List<CommittedChangeList> changes = provider.getCommittedChanges(settings, local, provider.getUnlimitedCountValue());
              if (changes != null) {
                for (CommittedChangeList change : changes) {
                  if (number.equals(String.valueOf(change.getNumber()))) {
                    list[0] = change;
                  }
                }
              }
            } */
          }
        }
      }
      catch (VcsException e) {
        exc[0] = e;
      }
    }

    @RequiredUIAccess
    @Override
    public void onSuccess() {
      final AbstractVcsHelper instance = AbstractVcsHelper.getInstance(project);
      if (exc[0] != null) {
        instance.showError(exc[0], failedText(virtualFile, revision));
      }
      else if (list[0] == null) {
        Messages.showErrorDialog(project, failedText(virtualFile, revision), getTitle());
      }
      else {
        instance.showChangesListBrowser(list[0], virtualFile, title);
      }
    }
  };
  ProgressManager.getInstance().run(task);
}
 
Example 20
Source File: ImportFromWorkspaceProjectViewOption.java    From intellij with Apache License 2.0 4 votes vote down vote up
private void chooseWorkspacePath() {
  FileChooserDescriptor descriptor =
      new FileChooserDescriptor(true, false, false, false, false, false)
          .withShowHiddenFiles(true) // Show root project view file
          .withHideIgnored(false)
          .withTitle("Select Project View File")
          .withDescription("Select a project view file to import.")
          .withFileFilter(
              virtualFile ->
                  ProjectViewStorageManager.isProjectViewFile(new File(virtualFile.getPath())));
  // File filters are broken for the native Mac file chooser.
  descriptor.setForcedToUseIdeaFileChooser(true);
  FileChooserDialog chooser =
      FileChooserFactory.getInstance().createFileChooser(descriptor, null, null);

  WorkspacePathResolver workspacePathResolver =
      builder.getWorkspaceData().workspacePathResolver();
  File fileBrowserRoot = builder.getWorkspaceData().fileBrowserRoot();
  File startingLocation = fileBrowserRoot;
  String projectViewPath = getProjectViewPath();
  if (!projectViewPath.isEmpty()) {
    // If the user has typed part of the path then clicked the '...', try to start from the
    // partial state
    projectViewPath = StringUtil.trimEnd(projectViewPath, '/');
    if (WorkspacePath.isValid(projectViewPath)) {
      File fileLocation = workspacePathResolver.resolveToFile(new WorkspacePath(projectViewPath));
      if (fileLocation.exists() && FileUtil.isAncestor(fileBrowserRoot, fileLocation, true)) {
        startingLocation = fileLocation;
      }
    }
  }
  VirtualFile toSelect =
      LocalFileSystem.getInstance().refreshAndFindFileByPath(startingLocation.getPath());
  VirtualFile[] files = chooser.choose(null, toSelect);
  if (files.length == 0) {
    return;
  }
  VirtualFile file = files[0];

  if (!FileUtil.startsWith(file.getPath(), fileBrowserRoot.getPath())) {
    Messages.showErrorDialog(
        String.format(
            "You must choose a project view file under %s. "
                + "To use an external project view, please use the 'Copy external' option.",
            fileBrowserRoot.getPath()),
        "Cannot Use Project View File");
    return;
  }

  String newWorkspacePath = FileUtil.getRelativePath(fileBrowserRoot, new File(file.getPath()));
  projectViewPathField.setText(newWorkspacePath);
}