Example usage for com.intellij.openapi.ui Messages showErrorDialog

List of usage examples for com.intellij.openapi.ui Messages showErrorDialog

Introduction

In this page you can find the example usage for com.intellij.openapi.ui Messages showErrorDialog.

Prototype

public static void showErrorDialog(String message,
        @NotNull @Nls(capitalization = Nls.Capitalization.Title) String title) 

Source Link

Document

Use this method only if you do not know project or component

Usage

From source file:com.intellij.ide.actions.ShowFilePathAction.java

License:Apache License

private static void doOpen(@NotNull File dir, @Nullable File toSelect) throws IOException, ExecutionException {
    dir = new File(FileUtil.toCanonicalPath(dir.getPath()));
    toSelect = toSelect == null ? null : new File(FileUtil.toCanonicalPath(toSelect.getPath()));

    if (SystemInfo.isWindows) {
        String cmd;//from   w w w.  j av a  2 s  . c o m
        if (toSelect != null) {
            cmd = "explorer /select," + toSelect.getAbsolutePath();
        } else {
            cmd = "explorer /root," + dir.getAbsolutePath();
        }
        // no quoting/escaping is needed
        Runtime.getRuntime().exec(cmd);
        return;
    }

    if (SystemInfo.isMac) {
        if (toSelect != null) {
            final String script = String.format("tell application \"Finder\"\n"
                    + "\treveal {\"%s\"} as POSIX file\n" + "\tactivate\n" + "end tell",
                    toSelect.getAbsolutePath());
            new GeneralCommandLine(ExecUtil.getOsascriptPath(), "-e", script).createProcess();
        } else {
            new GeneralCommandLine("open", dir.getAbsolutePath()).createProcess();
        }
        return;
    }

    if (canUseNautilus.getValue()) {
        new GeneralCommandLine("nautilus", (toSelect != null ? toSelect : dir).getAbsolutePath())
                .createProcess();
        return;
    }

    String path = dir.getAbsolutePath();
    if (SystemInfo.hasXdgOpen()) {
        new GeneralCommandLine("/usr/bin/xdg-open", path).createProcess();
    } else if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.OPEN)) {
        Desktop.getDesktop().open(new File(path));
    } else {
        Messages.showErrorDialog("This action isn't supported on the current platform", "Cannot Open File");
    }
}

From source file:com.intellij.ide.browsers.actions.BaseOpenInBrowserAction.java

License:Apache License

public static void open(@Nullable final OpenInBrowserRequest request, boolean preferLocalUrl,
        @Nullable final WebBrowser browser) {
    if (request == null) {
        return;// ww  w  . ja va2s  .c  o  m
    }

    try {
        Collection<Url> urls = WebBrowserService.getInstance().getUrlsToOpen(request, preferLocalUrl);
        if (!urls.isEmpty()) {
            chooseUrl(urls).doWhenDone(url -> {
                ApplicationManager.getApplication().saveAll();
                BrowserLauncher.getInstance().browse(url.toExternalForm(), browser, request.getProject());
            });
        }
    } catch (WebBrowserUrlProvider.BrowserException e1) {
        Messages.showErrorDialog(e1.getMessage(), IdeBundle.message("browser.error"));
    } catch (Exception e1) {
        LOG.error(e1);
    }
}

From source file:com.intellij.ide.browsers.BrowserLauncherAppless.java

License:Apache License

@Nullable
private static String extractFiles(String url) {
    try {//from  ww w.  j a  va2 s. co m
        int sharpPos = url.indexOf('#');
        String anchor = "";
        if (sharpPos != -1) {
            anchor = url.substring(sharpPos);
            url = url.substring(0, sharpPos);
        }

        Pair<String, String> pair = URLUtil.splitJarUrl(url);
        if (pair == null)
            return null;

        File jarFile = new File(FileUtil.toSystemDependentName(pair.first));
        if (!jarFile.canRead())
            return null;

        String jarUrl = StandardFileSystems.FILE_PROTOCOL_PREFIX
                + FileUtil.toSystemIndependentName(jarFile.getPath());
        String jarLocationHash = jarFile.getName() + "." + Integer.toHexString(jarUrl.hashCode());
        final File outputDir = new File(getExtractedFilesDir(), jarLocationHash);

        final String currentTimestamp = String.valueOf(new File(jarFile.getPath()).lastModified());
        final File timestampFile = new File(outputDir, ".idea.timestamp");

        String previousTimestamp = null;
        if (timestampFile.exists()) {
            previousTimestamp = FileUtilRt.loadFile(timestampFile);
        }

        if (!currentTimestamp.equals(previousTimestamp)) {
            final Ref<Boolean> extract = new Ref<Boolean>();
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    final ConfirmExtractDialog dialog = new ConfirmExtractDialog();
                    if (dialog.isToBeShown()) {
                        dialog.show();
                        extract.set(dialog.isOK());
                    } else {
                        dialog.close(DialogWrapper.OK_EXIT_CODE);
                        extract.set(true);
                    }
                }
            };

            try {
                GuiUtils.runOrInvokeAndWait(r);
            } catch (InvocationTargetException ignored) {
                extract.set(false);
            } catch (InterruptedException ignored) {
                extract.set(false);
            }

            if (!extract.get()) {
                return null;
            }

            boolean closeZip = true;
            final ZipFile zipFile = new ZipFile(jarFile);
            try {
                ZipEntry entry = zipFile.getEntry(pair.second);
                if (entry == null) {
                    return null;
                }
                InputStream is = zipFile.getInputStream(entry);
                ZipUtil.extractEntry(entry, is, outputDir);
                closeZip = false;
            } finally {
                if (closeZip) {
                    zipFile.close();
                }
            }

            ApplicationManager.getApplication().invokeLater(new Runnable() {
                @Override
                public void run() {
                    new Task.Backgroundable(null, "Extracting files...", true) {
                        @Override
                        public void run(@NotNull final ProgressIndicator indicator) {
                            final int size = zipFile.size();
                            final int[] counter = new int[] { 0 };

                            class MyFilter implements FilenameFilter {
                                private final Set<File> myImportantDirs = ContainerUtil.newHashSet(outputDir,
                                        new File(outputDir, "resources"));
                                private final boolean myImportantOnly;

                                private MyFilter(boolean importantOnly) {
                                    myImportantOnly = importantOnly;
                                }

                                @Override
                                public boolean accept(@NotNull File dir, @NotNull String name) {
                                    indicator.checkCanceled();
                                    boolean result = myImportantOnly == myImportantDirs.contains(dir);
                                    if (result) {
                                        indicator.setFraction(((double) counter[0]) / size);
                                        counter[0]++;
                                    }
                                    return result;
                                }
                            }

                            try {
                                try {
                                    ZipUtil.extract(zipFile, outputDir, new MyFilter(true));
                                    ZipUtil.extract(zipFile, outputDir, new MyFilter(false));
                                    FileUtil.writeToFile(timestampFile, currentTimestamp);
                                } finally {
                                    zipFile.close();
                                }
                            } catch (IOException ignore) {
                            }
                        }
                    }.queue();
                }
            });
        }

        return VfsUtilCore.pathToUrl(
                FileUtil.toSystemIndependentName(new File(outputDir, pair.second).getPath())) + anchor;
    } catch (IOException e) {
        LOG.warn(e);
        Messages.showErrorDialog("Cannot extract files: " + e.getMessage(), "Error");
        return null;
    }
}

From source file:com.intellij.ide.CommandLineProcessor.java

License:Apache License

@Nullable
private static Project doOpenFileOrProject(String name) {
    final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(name);
    if (virtualFile == null) {
        Messages.showErrorDialog("Cannot find file '" + name + "'", "Cannot find file");
        return null;
    }/*www .  ja  v  a2s.c  o  m*/
    ProjectOpenProcessor provider = ProjectOpenProcessor.getImportProvider(virtualFile);
    if (provider instanceof PlatformProjectOpenProcessor && !virtualFile.isDirectory()) {
        // HACK: PlatformProjectOpenProcessor agrees to open anything
        provider = null;
    }
    if (provider != null || new File(name, Project.DIRECTORY_STORE_FOLDER).exists()) {
        final Project result = ProjectUtil.openOrImport(name, null, true);
        if (result == null) {
            Messages.showErrorDialog("Cannot open project '" + name + "'", "Cannot open project");
        }
        return result;
    } else {
        return doOpenFile(virtualFile, -1);
    }
}

From source file:com.intellij.ide.CommandLineProcessor.java

License:Apache License

@Nullable
public static Project processExternalCommandLine(List<String> args, @Nullable String currentDirectory) {
    if (args.size() > 0) {
        LOG.info("External command line:");
        for (String arg : args) {
            LOG.info(arg);//from   w ww.  java2 s. c  o m
        }
    }
    LOG.info("-----");

    if (args.size() > 0) {
        String command = args.get(0);
        for (ApplicationStarter starter : Extensions.getExtensions(ApplicationStarter.EP_NAME)) {
            if (starter instanceof ApplicationStarterEx && command.equals(starter.getCommandName())) {
                LOG.info("Processing command with " + starter);
                ((ApplicationStarterEx) starter).processExternalCommandLine(ArrayUtil.toStringArray(args),
                        currentDirectory);
                return null;
            }
        }
    }

    Project lastOpenedProject = null;
    int line = -1;
    for (int i = 0, argsSize = args.size(); i < argsSize; i++) {
        String arg = args.get(i);
        if (arg.equals(StartupUtil.NO_SPLASH)) {
            continue;
        }
        if (arg.equals("-l") || arg.equals("--line")) {
            //noinspection AssignmentToForLoopParameter
            i++;
            if (i == args.size()) {
                break;
            }
            try {
                line = Integer.parseInt(args.get(i));
            } catch (NumberFormatException e) {
                line = -1;
            }
        } else {
            if (StringUtil.isQuotedString(arg)) {
                arg = StringUtil.stripQuotesAroundValue(arg);
            }
            if (currentDirectory != null && !new File(arg).isAbsolute()) {
                arg = new File(currentDirectory, arg).getAbsolutePath();
            }
            if (line != -1) {
                final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(arg);
                if (virtualFile != null) {
                    lastOpenedProject = doOpenFile(virtualFile, line);
                } else {
                    Messages.showErrorDialog("Cannot find file '" + arg + "'", "Cannot find file");
                }
            } else {
                lastOpenedProject = doOpenFileOrProject(arg);
            }
        }
    }
    return lastOpenedProject;
}

From source file:com.intellij.ide.fileTemplates.FileTemplateUtil.java

License:Apache License

private static String mergeTemplate(String templateContent, final VelocityContext context,
        boolean useSystemLineSeparators) throws IOException {
    final StringWriter stringWriter = new StringWriter();
    try {// w ww .j  a v a2 s . com
        Velocity.evaluate(context, stringWriter, "", templateContent);
    } catch (final VelocityException e) {
        LOG.error("Error evaluating template:\n" + templateContent, e);
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                Messages.showErrorDialog(IdeBundle.message("error.parsing.file.template", e.getMessage()),
                        IdeBundle.message("title.velocity.error"));
            }
        });
    }
    final String result = stringWriter.toString();

    if (useSystemLineSeparators) {
        final String newSeparator = CodeStyleSettingsManager
                .getSettings(ProjectManagerEx.getInstanceEx().getDefaultProject()).getLineSeparator();
        if (!"\n".equals(newSeparator)) {
            return StringUtil.convertLineSeparators(result, newSeparator);
        }
    }

    return result;
}

From source file:com.intellij.ide.impl.NewProjectUtil.java

License:Apache License

public static Project createFromWizard(AddModuleWizard dialog, Project projectToClose) {
    try {/*from   w  w  w  . j  a v  a  2 s.  c o  m*/
        return doCreate(dialog, projectToClose);
    } catch (final IOException e) {
        UIUtil.invokeLaterIfNeeded(new Runnable() {
            @Override
            public void run() {
                Messages.showErrorDialog(e.getMessage(), "Project Initialization Failed");
            }
        });
        return null;
    }
}

From source file:com.intellij.ide.plugins.InstalledPluginsManagerMain.java

License:Apache License

public InstalledPluginsManagerMain(PluginManagerUISettings uiSettings) {
    super(uiSettings);
    init();// w  ww  .  j  a v  a2s.  c o m
    myActionsPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

    final JButton button = new JButton("Browse repositories...");
    button.setMnemonic('b');
    button.addActionListener(new BrowseRepoListener(null));
    myActionsPanel.add(button);

    final JButton installPluginFromFileSystem = new JButton("Install plugin from disk...");
    installPluginFromFileSystem.setMnemonic('d');
    installPluginFromFileSystem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, false, true, true, false,
                    false) {
                @Override
                public boolean isFileSelectable(VirtualFile file) {
                    return file.getFileType() instanceof ArchiveFileType;
                }
            };
            descriptor.setTitle("Choose Plugin File");
            descriptor.setDescription("JAR and ZIP archives are accepted");
            FileChooser.chooseFile(descriptor, null, myActionsPanel, null, new Consumer<VirtualFile>() {
                @Override
                public void consume(@NotNull VirtualFile virtualFile) {
                    final File file = VfsUtilCore.virtualToIoFile(virtualFile);
                    try {
                        final IdeaPluginDescriptorImpl pluginDescriptor = PluginDownloader
                                .loadDescriptionFromJar(file);
                        if (pluginDescriptor == null) {
                            Messages.showErrorDialog(
                                    "Fail to load plugin descriptor from file " + file.getName(),
                                    CommonBundle.getErrorTitle());
                            return;
                        }
                        if (PluginManagerCore.isIncompatible(pluginDescriptor)) {
                            Messages.showErrorDialog(
                                    "Plugin " + pluginDescriptor.getName()
                                            + " is incompatible with current installation",
                                    CommonBundle.getErrorTitle());
                            return;
                        }
                        final IdeaPluginDescriptor alreadyInstalledPlugin = PluginManager
                                .getPlugin(pluginDescriptor.getPluginId());
                        if (alreadyInstalledPlugin != null) {
                            final File oldFile = alreadyInstalledPlugin.getPath();
                            if (oldFile != null) {
                                StartupActionScriptManager.addActionCommand(
                                        new StartupActionScriptManager.DeleteCommand(oldFile));
                            }
                        }
                        if (((InstalledPluginsTableModel) pluginsModel)
                                .appendOrUpdateDescriptor(pluginDescriptor)) {
                            PluginDownloader.install(file, file.getName(), false);
                            select(pluginDescriptor);
                            checkInstalledPluginDependencies(pluginDescriptor);
                            setRequireShutdown(true);
                        } else {
                            Messages.showInfoMessage(myActionsPanel,
                                    "Plugin " + pluginDescriptor.getName() + " was already installed",
                                    CommonBundle.getWarningTitle());
                        }
                    } catch (IOException ex) {
                        Messages.showErrorDialog(ex.getMessage(), CommonBundle.getErrorTitle());
                    }
                }
            });
        }
    });
    myActionsPanel.add(installPluginFromFileSystem);
    final StatusText emptyText = pluginTable.getEmptyText();
    emptyText.setText("Nothing to show.");
    emptyText.appendText(" Click ");
    emptyText.appendText("Browse", SimpleTextAttributes.LINK_ATTRIBUTES, new BrowseRepoListener(null));
    emptyText.appendText(" to search for non-bundled plugins.");
}

From source file:com.intellij.ide.util.AbstractTreeClassChooserDialog.java

License:Apache License

@Override
protected void doOKAction() {
    mySelectedClass = calcSelectedClass();
    if (mySelectedClass == null)
        return;//from w w w.j a v a 2  s .c o m
    if (!myClassFilter.isAccepted(mySelectedClass)) {
        Messages.showErrorDialog(myTabbedPane.getComponent(),
                SymbolPresentationUtil.getSymbolPresentableText(mySelectedClass) + " is not acceptable");
        return;
    }
    super.doOKAction();
}

From source file:com.intellij.ide.util.newProjectWizard.AddModuleWizard.java

License:Apache License

protected final void doOKAction() {
    int idx = getCurrentStep();
    try {/*  w  w  w  .  ja  v a  2s .c  o  m*/
        do {
            final ModuleWizardStep step = mySteps.get(idx);
            if (step != getCurrentStepObject()) {
                step.updateStep();
            }
            if (!commitStepData(step)) {
                return;
            }
            step.onStepLeaving();
            try {
                step._commit(true);
            } catch (CommitStepException e) {
                String message = e.getMessage();
                if (message != null) {
                    Messages.showErrorDialog(getCurrentStepComponent(), message);
                }
                return;
            }
            if (!isLastStep(idx)) {
                idx = getNextStep(idx);
            } else {
                break;
            }
        } while (true);
    } finally {
        myCurrentStep = idx;
        updateStep();
    }
    super.doOKAction();
}