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.profile.codeInspection.ui.header.InspectionToolsConfigurable.java

License:Apache License

public InspectionToolsConfigurable(@NotNull final InspectionProjectProfileManager projectProfileManager,
        InspectionProfileManager profileManager) {
    myWholePanel = new JPanel(new BorderLayout());

    final JPanel toolbar = new JPanel(new GridBagLayout());
    toolbar.setBorder(BorderFactory.createEmptyBorder(0, 0, 7, 0));

    myPanel = new JPanel();

    myWholePanel.add(toolbar, BorderLayout.PAGE_START);
    myWholePanel.add(myPanel, BorderLayout.CENTER);

    myProfiles = new ProfilesConfigurableComboBox(new ListCellRendererWrapper<Profile>() {
        @Override//from   w  w  w  .  j  a v a2  s .c o m
        public void customize(final JList list, final Profile value, final int index, final boolean selected,
                final boolean hasFocus) {
            final SingleInspectionProfilePanel singleInspectionProfilePanel = myPanels.get(value);
            final boolean isShared = singleInspectionProfilePanel.isProfileShared();
            setIcon(isShared ? AllIcons.General.ProjectSettings : AllIcons.General.Settings);
            setText(singleInspectionProfilePanel.getCurrentProfileName());
        }
    }) {
        @Override
        public void onProfileChosen(InspectionProfileImpl inspectionProfile) {
            myLayout.show(myPanel, getCardName(inspectionProfile));
            myAuxiliaryRightPanel.showDescription(inspectionProfile.getDescription());
        }
    };
    JPanel profilesHolder = new JPanel();
    profilesHolder.setLayout(new CardLayout());

    JComponent manageButton = new ManageButton(new ManageButtonBuilder() {
        @Override
        public boolean isSharedToTeamMembers() {
            SingleInspectionProfilePanel panel = getSelectedPanel();
            return panel != null && panel.isProfileShared();
        }

        @Override
        public void setShareToTeamMembers(boolean shared) {
            final SingleInspectionProfilePanel selectedPanel = getSelectedPanel();
            LOG.assertTrue(selectedPanel != null, "No settings selectedPanel for: " + getSelectedObject());

            final String name = getSelectedPanel().getCurrentProfileName();
            for (SingleInspectionProfilePanel p : myPanels.values()) {
                if (p != selectedPanel && Comparing.equal(p.getCurrentProfileName(), name)) {
                    final boolean curShared = p.isProfileShared();
                    if (curShared == shared) {
                        Messages.showErrorDialog(
                                (shared ? "Shared" : "Application level") + " profile with same name exists.",
                                "Inspections Settings");
                        return;
                    }
                }
            }

            selectedPanel.setProfileShared(shared);
            myProfiles.repaint();
        }

        @Override
        public void copy() {
            final InspectionProfileImpl newProfile = copyToNewProfile(getSelectedObject(), getProject());
            if (newProfile != null) {
                final InspectionProfileImpl modifiableModel = (InspectionProfileImpl) newProfile
                        .getModifiableModel();
                modifiableModel.setModified(true);
                modifiableModel.setProjectLevel(false);
                addProfile(modifiableModel);
                rename(modifiableModel);
            }
        }

        @Override
        public boolean canRename() {
            final InspectionProfileImpl profile = getSelectedObject();
            return !profile.isProfileLocked();
        }

        @Override
        public void rename() {
            rename(getSelectedObject());
        }

        private void rename(@NotNull final InspectionProfileImpl inspectionProfile) {
            final String initialName = getSelectedPanel().getCurrentProfileName();
            myProfiles.showEditCard(initialName, new SaveInputComponentValidator() {
                @Override
                public void doSave(@NotNull String text) {
                    if (!text.equals(initialName)) {
                        getProfilePanel(inspectionProfile).setCurrentProfileName(text);
                    }
                    myProfiles.showComboBoxCard();
                }

                @Override
                public boolean checkValid(@NotNull String text) {
                    final SingleInspectionProfilePanel singleInspectionProfilePanel = myPanels
                            .get(inspectionProfile);
                    if (singleInspectionProfilePanel == null) {
                        return false;
                    }
                    final boolean isValid = text.equals(initialName)
                            || !hasName(text, singleInspectionProfilePanel.isProfileShared());
                    if (isValid) {
                        myAuxiliaryRightPanel.showDescription(getSelectedObject().getDescription());
                    } else {
                        myAuxiliaryRightPanel
                                .showError("Name is already in use. Please change name to unique.");
                    }
                    return isValid;
                }

                @Override
                public void cancel() {
                    myProfiles.showComboBoxCard();
                    myAuxiliaryRightPanel.showDescription(getSelectedObject().getDescription());
                }
            });
        }

        @Override
        public boolean canDelete() {
            return isDeleteEnabled(myProfiles.getSelectedProfile());
        }

        @Override
        public void delete() {
            final InspectionProfileImpl selectedProfile = myProfiles.getSelectedProfile();
            myProfiles.getModel().removeElement(selectedProfile);
            myDeletedProfiles.add(selectedProfile);
        }

        @Override
        public boolean canEditDescription() {
            return true;
        }

        @Override
        public void editDescription() {
            myAuxiliaryRightPanel.editDescription(getSelectedObject().getDescription());
        }

        @Override
        public boolean hasDescription() {
            return !StringUtil.isEmpty(getSelectedObject().getDescription());
        }

        @Override
        public void export() {
            final FileChooserDescriptor descriptor = FileChooserDescriptorFactory
                    .createSingleFolderDescriptor();
            descriptor.setDescription("Choose directory to store profile file");
            FileChooser.chooseFile(descriptor, getProject(), myWholePanel, null, new Consumer<VirtualFile>() {
                @Override
                public void consume(VirtualFile file) {
                    final Element element = new Element("inspections");
                    try {
                        final SingleInspectionProfilePanel panel = getSelectedPanel();
                        LOG.assertTrue(panel != null);
                        final InspectionProfileImpl profile = getSelectedObject();
                        LOG.assertTrue(true);
                        profile.writeExternal(element);
                        final String filePath = FileUtil.toSystemDependentName(file.getPath()) + File.separator
                                + FileUtil.sanitizeFileName(profile.getName()) + ".xml";
                        if (new File(filePath).isFile()) {
                            if (Messages.showOkCancelDialog(myWholePanel,
                                    "File \'" + filePath + "\' already exist. Do you want to overwrite it?",
                                    "Warning", Messages.getQuestionIcon()) != Messages.OK) {
                                return;
                            }
                        }
                        JDOMUtil.writeDocument(new Document(element), filePath,
                                SystemProperties.getLineSeparator());
                    } catch (WriteExternalException e1) {
                        LOG.error(e1);
                    } catch (IOException e1) {
                        LOG.error(e1);
                    }
                }
            });
        }

        @Override
        public void doImport() {
            final FileChooserDescriptor descriptor = new FileChooserDescriptor(true, false, false, false, false,
                    false) {
                @Override
                public boolean isFileSelectable(VirtualFile file) {
                    return file.getFileType().equals(InternalStdFileTypes.XML);
                }
            };
            descriptor.setDescription("Choose profile file");
            FileChooser.chooseFile(descriptor, getProject(), myWholePanel, null, new Consumer<VirtualFile>() {
                @Override
                public void consume(VirtualFile file) {
                    if (file == null)
                        return;
                    InspectionProfileImpl profile = new InspectionProfileImpl("TempProfile",
                            InspectionToolRegistrar.getInstance(), myProfileManager);
                    try {
                        Element rootElement = JDOMUtil.loadDocument(VfsUtilCore.virtualToIoFile(file))
                                .getRootElement();
                        if (Comparing.strEqual(rootElement.getName(), "component")) {//import right from .idea/inspectProfiles/xxx.xml
                            rootElement = rootElement.getChildren().get(0);
                        }
                        final Set<String> levels = new HashSet<String>();
                        for (Object o : rootElement.getChildren("inspection_tool")) {
                            final Element inspectElement = (Element) o;
                            levels.add(inspectElement.getAttributeValue("level"));
                            for (Object s : inspectElement.getChildren("scope")) {
                                levels.add(((Element) s).getAttributeValue("level"));
                            }
                        }
                        for (Iterator<String> iterator = levels.iterator(); iterator.hasNext();) {
                            String level = iterator.next();
                            if (myProfileManager.getOwnSeverityRegistrar().getSeverity(level) != null) {
                                iterator.remove();
                            }
                        }
                        if (!levels.isEmpty()) {
                            if (Messages.showYesNoDialog(myWholePanel,
                                    "Undefined severities detected: " + StringUtil.join(levels, ", ")
                                            + ". Do you want to create them?",
                                    "Warning", Messages.getWarningIcon()) == Messages.YES) {
                                for (String level : levels) {
                                    final TextAttributes textAttributes = CodeInsightColors.WARNINGS_ATTRIBUTES
                                            .getDefaultAttributes();
                                    HighlightInfoType.HighlightInfoTypeImpl info = new HighlightInfoType.HighlightInfoTypeImpl(
                                            new HighlightSeverity(level, 50),
                                            TextAttributesKey.createTextAttributesKey(level));
                                    myProfileManager.getOwnSeverityRegistrar().registerSeverity(
                                            new SeverityRegistrar.SeverityBasedTextAttributes(
                                                    textAttributes.clone(), info),
                                            textAttributes.getErrorStripeColor());
                                }
                            }
                        }
                        profile.readExternal(rootElement);
                        profile.setProjectLevel(false);
                        profile.initInspectionTools(getProject());
                        if (getProfilePanel(profile) != null) {
                            if (Messages.showOkCancelDialog(myWholePanel,
                                    "Profile with name \'" + profile.getName()
                                            + "\' already exists. Do you want to overwrite it?",
                                    "Warning", Messages.getInformationIcon()) != Messages.OK) {
                                return;
                            }
                        }
                        final ModifiableModel model = profile.getModifiableModel();
                        model.setModified(true);
                        addProfile((InspectionProfileImpl) model);

                        //TODO myDeletedProfiles ? really need this
                        myDeletedProfiles.remove(profile);
                    } catch (InvalidDataException e1) {
                        LOG.error(e1);
                    } catch (JDOMException e1) {
                        LOG.error(e1);
                    } catch (IOException e1) {
                        LOG.error(e1);
                    }
                }
            });
        }
    }).build();

    myAuxiliaryRightPanel = new AuxiliaryRightPanel(new AuxiliaryRightPanel.DescriptionSaveListener() {
        @Override
        public void saveDescription(@NotNull String description) {
            final InspectionProfileImpl inspectionProfile = getSelectedObject();
            if (!Comparing.strEqual(description, inspectionProfile.getDescription())) {
                inspectionProfile.setDescription(description);
                inspectionProfile.setModified(true);
            }
            myAuxiliaryRightPanel.showDescription(description);
        }

        @Override
        public void cancel() {
            myAuxiliaryRightPanel.showDescription(getSelectedObject().getDescription());
        }
    });

    toolbar.add(new JLabel(HEADER_TITLE), new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.WEST,
            GridBagConstraints.VERTICAL, new Insets(0, 0, 0, 0), 0, 0));

    toolbar.add(myProfiles.getHintLabel(), new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.WEST,
            GridBagConstraints.VERTICAL, new Insets(0, 6, 6, 0), 0, 0));
    toolbar.add(myProfiles, new GridBagConstraints(1, 1, 1, 1, 0, 1.0, GridBagConstraints.WEST,
            GridBagConstraints.VERTICAL, new Insets(0, 6, 0, 0), 0, 0));

    toolbar.add(manageButton, new GridBagConstraints(2, 1, 1, 1, 0, 0, GridBagConstraints.WEST,
            GridBagConstraints.VERTICAL, new Insets(0, 10, 0, 0), 0, 0));

    toolbar.add(myAuxiliaryRightPanel.getHintLabel(), new GridBagConstraints(3, 0, 1, 1, 0, 0,
            GridBagConstraints.WEST, GridBagConstraints.VERTICAL, new Insets(0, 15, 6, 0), 0, 0));
    toolbar.add(myAuxiliaryRightPanel, new GridBagConstraints(3, 1, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
            GridBagConstraints.BOTH, new Insets(0, 15, 0, 0), 0, 0));

    ((InspectionManagerEx) InspectionManager.getInstance(projectProfileManager.getProject()))
            .buildInspectionSearchIndexIfNecessary();
    myProjectProfileManager = projectProfileManager;
    myProfileManager = profileManager;
}

From source file:com.intellij.profile.codeInspection.ui.ProfilesComboBox.java

License:Apache License

public void createProfilesCombo(final Profile selectedProfile, final Set<Profile> availableProfiles,
        final ProfileManager profileManager) {
    reloadProfiles(profileManager, availableProfiles, selectedProfile);

    setRenderer(new DefaultListCellRenderer() {
        @Override//ww w  .  j av  a2 s.co  m
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            final Component rendererComponent = super.getListCellRendererComponent(list, value, index,
                    isSelected, cellHasFocus);
            if (value instanceof Profile) {
                final Profile profile = (Profile) value;
                setText(profile.getName());
                setIcon(profile.isLocal() ? AllIcons.General.Settings : AllIcons.General.ProjectSettings);
            } else if (value instanceof String) {
                setText((String) value);
            }
            return rendererComponent;
        }
    });
    addItemListener(new ItemListener() {
        private Object myDeselectedItem = null;

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (myFrozenProfilesCombo)
                return; //do not update during reloading
            if (ItemEvent.SELECTED == e.getStateChange()) {
                final Object item = e.getItem();
                if (profileManager instanceof ProjectProfileManager && item instanceof Profile
                        && ((Profile) item).isLocal()) {
                    if (Messages.showOkCancelDialog(
                            InspectionsBundle.message("inspection.new.profile.ide.to.project.warning.message"),
                            InspectionsBundle.message("inspection.new.profile.ide.to.project.warning.title"),
                            Messages.getErrorIcon()) == DialogWrapper.OK_EXIT_CODE) {
                        final String newName = Messages.showInputDialog(
                                InspectionsBundle.message("inspection.new.profile.text"),
                                InspectionsBundle.message("inspection.new.profile.dialog.title"),
                                Messages.getInformationIcon());
                        final Object selectedItem = getSelectedItem();
                        if (newName != null && newName.length() > 0 && selectedItem instanceof Profile) {
                            if (ArrayUtil.find(profileManager.getAvailableProfileNames(), newName) == -1
                                    && ArrayUtil.find(
                                            InspectionProfileManager.getInstance().getAvailableProfileNames(),
                                            newName) == -1) {
                                saveNewProjectProfile(newName, (Profile) selectedItem, profileManager);
                                return;
                            } else {
                                Messages.showErrorDialog(
                                        InspectionsBundle.message("inspection.unable.to.create.profile.message",
                                                newName),
                                        InspectionsBundle
                                                .message("inspection.unable.to.create.profile.dialog.title"));
                            }
                        }
                    }
                    setSelectedItem(myDeselectedItem);
                }
            } else {
                myDeselectedItem = e.getItem();
            }
        }
    });
}

From source file:com.intellij.profile.codeInspection.ui.SingleInspectionProfilePanel.java

License:Apache License

@Nullable
public static ModifiableModel createNewProfile(final int initValue, ModifiableModel selectedProfile,
        JPanel parent, String profileName, Set<String> existingProfileNames, @NotNull Project project) {
    profileName = Messages.showInputDialog(parent, profileName, "Create New Inspection Profile",
            Messages.getQuestionIcon());
    if (profileName == null)
        return null;
    final ProfileManager profileManager = selectedProfile.getProfileManager();
    if (existingProfileNames.contains(profileName)) {
        Messages.showErrorDialog(
                InspectionsBundle.message("inspection.unable.to.create.profile.message", profileName),
                InspectionsBundle.message("inspection.unable.to.create.profile.dialog.title"));
        return null;
    }//from w  ww.  j  a va 2 s .  c  om
    InspectionProfileImpl inspectionProfile = new InspectionProfileImpl(profileName,
            InspectionToolRegistrar.getInstance(), profileManager);
    if (initValue == -1) {
        inspectionProfile.initInspectionTools(project);
        ModifiableModel profileModifiableModel = inspectionProfile.getModifiableModel();
        final InspectionToolWrapper[] profileEntries = profileModifiableModel.getInspectionTools(null);
        for (InspectionToolWrapper toolWrapper : profileEntries) {
            profileModifiableModel.disableTool(toolWrapper.getShortName(), null, project);
        }
        profileModifiableModel.setProjectLevel(false);
        profileModifiableModel.setModified(true);
        return profileModifiableModel;
    } else if (initValue == 0) {
        inspectionProfile.copyFrom(selectedProfile);
        inspectionProfile.setName(profileName);
        inspectionProfile.initInspectionTools(project);
        inspectionProfile.setModified(true);
        return inspectionProfile;
    }
    return null;
}

From source file:com.intellij.refactoring.extractclass.ExtractClassDialog.java

License:Apache License

protected void doAction() {

    final List<PsiField> fields = getFieldsToExtract();
    final List<PsiMethod> methods = getMethodsToExtract();
    final List<PsiClass> classes = getClassesToExtract();
    final String newClassName = getClassName();
    final String packageName = getPackageName();

    Collections.sort(enumConstants, new Comparator<MemberInfo>() {
        public int compare(MemberInfo o1, MemberInfo o2) {
            return o1.getMember().getTextOffset() - o2.getMember().getTextOffset();
        }/*w  w w .j  a  va  2 s .c  om*/
    });
    final ExtractClassProcessor processor = new ExtractClassProcessor(sourceClass, fields, methods, classes,
            packageName,
            myDestinationFolderComboBox
                    .selectDirectory(new PackageWrapper(PsiManager.getInstance(myProject), packageName), false),
            newClassName, myVisibilityPanel.getVisibility(), isGenerateAccessors(),
            isExtractAsEnum() ? enumConstants : Collections.<MemberInfo>emptyList());
    if (processor.getCreatedClass() == null) {
        Messages.showErrorDialog(myVisibilityPanel, "Unable to create class with the given name");
        classNameField.requestFocusInWindow();
        return;
    }
    invokeRefactoring(processor);
}

From source file:com.intellij.slicer.SliceLeafAnalyzer.java

License:Apache License

public static void startAnalyzeValues(@NotNull final AbstractTreeStructure treeStructure,
        @NotNull final Runnable finish) {
    final SliceRootNode root = (SliceRootNode) treeStructure.getRootElement();
    final Ref<Collection<PsiElement>> leafExpressions = Ref.create(null);

    final Map<SliceNode, Collection<PsiElement>> map = createMap();

    ProgressManager.getInstance().run(new Task.Backgroundable(root.getProject(),
            "Expanding all nodes... (may very well take the whole day)", true) {
        @Override//from   w  w w  . j  ava  2s  .  c o  m
        public void run(@NotNull final ProgressIndicator indicator) {
            Collection<PsiElement> l = calcLeafExpressions(root, treeStructure, map);
            leafExpressions.set(l);
        }

        @Override
        public void onCancel() {
            finish.run();
        }

        @Override
        public void onSuccess() {
            try {
                Collection<PsiElement> leaves = leafExpressions.get();
                if (leaves == null)
                    return; //cancelled

                if (leaves.isEmpty()) {
                    Messages.showErrorDialog("Unable to find leaf expressions to group by", "Cannot group");
                    return;
                }

                groupByValues(leaves, root, map);
            } finally {
                finish.run();
            }
        }
    });
}

From source file:com.intellij.ui.debugger.extensions.PlaybackDebugger.java

License:Apache License

private void save() {
    try {//from  w  ww  .j  a v  a2s. c o  m
        VirtualFile file = pathToFile();
        final String toWrite = myCodeEditor.getText();
        String text = toWrite != null ? toWrite : "";
        VfsUtil.saveText(file, text);
        myChanged = false;
    } catch (IOException e) {
        Messages.showErrorDialog(e.getMessage(), "Cannot save script");
    }
}

From source file:com.intellij.ui.debugger.extensions.PlaybackDebugger.java

License:Apache License

private void loadFrom(@NotNull VirtualFile file) {
    try {//from  ww w.jav a  2 s .c  o  m
        final String text = CharsetToolkit.bytesToString(file.contentsToByteArray(),
                EncodingRegistry.getInstance().getDefaultCharset());
        fillDocument(text);
        myChanged = false;
    } catch (IOException e) {
        Messages.showErrorDialog(e.getMessage(), "Cannot load file");
    }
}

From source file:com.intellij.util.descriptors.impl.ConfigFileFactoryImpl.java

License:Apache License

@Nullable
private VirtualFile createFileFromTemplate(@Nullable final Project project, String url,
        final String templateName, final boolean forceNew) {
    final LocalFileSystem fileSystem = LocalFileSystem.getInstance();
    final File file = new File(VfsUtil.urlToPath(url));
    VirtualFile existingFile = fileSystem.refreshAndFindFileByIoFile(file);
    if (existingFile != null) {
        existingFile.refresh(false, false);
        if (!existingFile.isValid()) {
            existingFile = null;// w  ww. j  ava 2s . c om
        }
    }

    if (existingFile != null && !forceNew) {
        return existingFile;
    }
    try {
        String text = getText(templateName);
        final VirtualFile childData;
        if (existingFile == null || existingFile.isDirectory()) {
            final VirtualFile virtualFile;
            if (!FileUtil.createParentDirs(file)
                    || (virtualFile = fileSystem.refreshAndFindFileByIoFile(file.getParentFile())) == null) {
                throw new IOException(IdeBundle.message("error.message.unable.to.create.file", file.getPath()));
            }
            childData = virtualFile.createChildData(this, file.getName());
        } else {
            childData = existingFile;
        }
        FileContentUtil.setFileText(project, childData, text);
        return childData;
    } catch (final IOException e) {
        LOG.info(e);
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            public void run() {
                Messages.showErrorDialog(
                        IdeBundle.message("message.text.error.creating.deployment.descriptor",
                                e.getLocalizedMessage()),
                        IdeBundle.message("message.text.creating.deployment.descriptor"));
            }
        });
    }
    return null;
}

From source file:com.intellij.util.net.HTTPProxySettingsPanel.java

License:Apache License

public HTTPProxySettingsPanel(final HttpConfigurable httpConfigurable) {
    final ButtonGroup group = new ButtonGroup();
    group.add(myUseHTTPProxyRb);/*  w w  w.  java  2  s . c o m*/
    group.add(myAutoDetectProxyRb);
    group.add(myNoProxyRb);
    myNoProxyRb.setSelected(true);

    final ButtonGroup proxyTypeGroup = new ButtonGroup();
    proxyTypeGroup.add(myHTTP);
    proxyTypeGroup.add(mySocks);
    myHTTP.setSelected(true);

    myProxyExceptions.setBorder(UIUtil.getTextFieldBorder());

    final Boolean property = Boolean.getBoolean(JavaProxyProperty.USE_SYSTEM_PROXY);
    mySystemProxyDefined.setVisible(Boolean.TRUE.equals(property));
    if (Boolean.TRUE.equals(property)) {
        mySystemProxyDefined.setIcon(Messages.getWarningIcon());
        mySystemProxyDefined.setFont(mySystemProxyDefined.getFont().deriveFont(Font.BOLD));
        mySystemProxyDefined.setUI(new MultiLineLabelUI());
    }

    myProxyAuthCheckBox.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            enableProxyAuthentication(myProxyAuthCheckBox.isSelected());
        }
    });

    final ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            enableProxy(myUseHTTPProxyRb.isSelected());
        }
    };
    myUseHTTPProxyRb.addActionListener(listener);
    myAutoDetectProxyRb.addActionListener(listener);
    myNoProxyRb.addActionListener(listener);
    myHttpConfigurable = httpConfigurable;

    myClearPasswordsButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            myHttpConfigurable.clearGenericPasswords();
            Messages.showMessageDialog(myMainPanel, "Proxy passwords were cleared.", "Auto-detected proxy",
                    Messages.getInformationIcon());
        }
    });

    if (HttpConfigurable.getInstance() != null) {
        myCheckButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                final String title = "Check Proxy Settings";
                final String answer = Messages.showInputDialog(myMainPanel,
                        "Warning: your settings will be saved.\n\nEnter any URL to check connection to:", title,
                        Messages.getQuestionIcon(), "http://", null);
                if (!StringUtil.isEmptyOrSpaces(answer)) {
                    apply();
                    final HttpConfigurable instance = HttpConfigurable.getInstance();
                    final AtomicReference<IOException> exc = new AtomicReference<IOException>();
                    myCheckButton.setEnabled(false);
                    myCheckButton.setText("Check connection (in progress...)");
                    myConnectionCheckInProgress = true;
                    final Application application = ApplicationManager.getApplication();
                    application.executeOnPooledThread(new Runnable() {
                        @Override
                        public void run() {
                            HttpURLConnection connection = null;
                            try {
                                //already checked for null above
                                //noinspection ConstantConditions
                                connection = instance.openHttpConnection(answer);
                                connection.setReadTimeout(3 * 1000);
                                connection.setConnectTimeout(3 * 1000);
                                connection.connect();
                                final int code = connection.getResponseCode();
                                if (HttpURLConnection.HTTP_OK != code) {
                                    exc.set(new IOException("Error code: " + code));
                                }
                            } catch (IOException e1) {
                                exc.set(e1);
                            } finally {
                                if (connection != null) {
                                    connection.disconnect();
                                }
                            }
                            //noinspection SSBasedInspection
                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    myConnectionCheckInProgress = false;
                                    reset(); // since password might have been set
                                    Component parent = null;
                                    if (myMainPanel.isShowing()) {
                                        parent = myMainPanel;
                                        myCheckButton.setText("Check connection");
                                        myCheckButton.setEnabled(canEnableConnectionCheck());
                                    } else {
                                        final IdeFrame frame = IdeFocusManager.findInstance()
                                                .getLastFocusedFrame();
                                        if (frame == null) {
                                            return;
                                        }
                                        parent = frame.getComponent();
                                    }
                                    //noinspection ThrowableResultOfMethodCallIgnored
                                    final IOException exception = exc.get();
                                    if (exception == null) {
                                        Messages.showMessageDialog(parent, "Connection successful", title,
                                                Messages.getInformationIcon());
                                    } else {
                                        final String message = exception.getMessage();
                                        if (instance.USE_HTTP_PROXY) {
                                            instance.LAST_ERROR = message;
                                        }
                                        Messages.showErrorDialog(parent, errorText(message));
                                    }
                                }
                            });
                        }
                    });
                }
            }
        });
    } else {
        myCheckButton.setVisible(false);
    }
}

From source file:com.intellij.util.net.HttpProxySettingsUi.java

License:Apache License

private void configureCheckButton() {
    if (HttpConfigurable.getInstance() == null) {
        myCheckButton.setVisible(false);
        return;/*from  w ww . j  av a  2  s.c  om*/
    }

    myCheckButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(@NotNull ActionEvent e) {
            final String title = "Check Proxy Settings";
            final String answer = Messages.showInputDialog(myMainPanel,
                    "Warning: your settings will be saved.\n\nEnter any URL to check connection to:", title,
                    Messages.getQuestionIcon(), "http://", null);
            if (StringUtil.isEmptyOrSpaces(answer)) {
                return;
            }

            final HttpConfigurable settings = HttpConfigurable.getInstance();
            apply(settings);
            final AtomicReference<IOException> exceptionReference = new AtomicReference<IOException>();
            myCheckButton.setEnabled(false);
            myCheckButton.setText("Check connection (in progress...)");
            myConnectionCheckInProgress = true;
            ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
                @Override
                public void run() {
                    HttpURLConnection connection = null;
                    try {
                        //already checked for null above
                        //noinspection ConstantConditions
                        connection = settings.openHttpConnection(answer);
                        connection.setReadTimeout(3 * 1000);
                        connection.setConnectTimeout(3 * 1000);
                        connection.connect();
                        final int code = connection.getResponseCode();
                        if (HttpURLConnection.HTTP_OK != code) {
                            exceptionReference.set(new IOException("Error code: " + code));
                        }
                    } catch (IOException e) {
                        exceptionReference.set(e);
                    } finally {
                        if (connection != null) {
                            connection.disconnect();
                        }
                    }
                    //noinspection SSBasedInspection
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            myConnectionCheckInProgress = false;
                            reset(settings); // since password might have been set
                            Component parent;
                            if (myMainPanel.isShowing()) {
                                parent = myMainPanel;
                                myCheckButton.setText("Check connection");
                                myCheckButton.setEnabled(canEnableConnectionCheck());
                            } else {
                                IdeFrame frame = IdeFocusManager.findInstance().getLastFocusedFrame();
                                if (frame == null) {
                                    return;
                                }
                                parent = frame.getComponent();
                            }
                            //noinspection ThrowableResultOfMethodCallIgnored
                            final IOException exception = exceptionReference.get();
                            if (exception == null) {
                                Messages.showMessageDialog(parent, "Connection successful", title,
                                        Messages.getInformationIcon());
                            } else {
                                final String message = exception.getMessage();
                                if (settings.USE_HTTP_PROXY) {
                                    settings.LAST_ERROR = message;
                                }
                                Messages.showErrorDialog(parent, errorText(message));
                            }
                        }
                    });
                }
            });
        }
    });
}