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(@Nullable Component component, String message,
            @NotNull @Nls(capitalization = Nls.Capitalization.Title) String title) 

Source Link

Usage

From source file:com.google.cloud.tools.intellij.vcs.UploadSourceAction.java

License:Apache License

private static boolean fetchGit(@NotNull final Project project, @NotNull ProgressIndicator indicator,
        @NotNull GitRepository repository, final @NotNull String remote) {

    GitFetcher fetcher = new GitFetcher(project, indicator, true);
    GitFetchResult result = fetcher.fetch(repository);

    if (!result.isSuccess()) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override//from  w w  w  .  java 2s .  c om
            public void run() {
                Messages.showErrorDialog(project, GctBundle.message("uploadtogcp.fetchfailed", remote),
                        GctBundle.message("uploadtogcp.fetchfailedtitle"));
            }
        });
        return false;
    }
    repository.update();
    return true;
}

From source file:com.google.cloud.tools.intellij.vcs.UploadSourceAction.java

License:Apache License

private static boolean hasRemoteBranch(final @NotNull Project project, @NotNull GitRepository repository,
        @NotNull String remoteName, final @NotNull String projectId) {
    for (GitRemoteBranch remoteBranch : repository.getInfo().getRemoteBranches()) {
        if (remoteBranch.getRemote().getName().equalsIgnoreCase(remoteName)) {
            LOG.warn("git repo is not empty, bailing");
            SwingUtilities.invokeLater(new Runnable() {
                @Override/*from  w  w  w . j  a  v a  2 s.  c  om*/
                public void run() {
                    Messages.showErrorDialog(project,
                            GctBundle.message("uploadtogcp.remotenotempty", projectId),
                            GctBundle.message("uploadtogcp.remotenotemptytitle"));
                }
            });
            return true;
        }
    }

    return false;
}

From source file:com.google.cloud.tools.intellij.vcs.UploadSourceAction.java

License:Apache License

private static boolean addGitRemote(final @NotNull Project project, @NotNull GitRepository repository,
        @NotNull String remote, final @NotNull String url) {
    final GitSimpleHandler handler = new GitSimpleHandler(project, repository.getRoot(), GitCommand.REMOTE);
    handler.setSilent(true);//from  w  ww  .j a  v  a  2  s.  com
    try {
        handler.addParameters("add", remote, url);
        handler.run();
        if (handler.getExitCode() != 0) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    Messages.showErrorDialog(project,
                            GctBundle.message("uploadtogcp.addremotefailed", url, handler.getStderr()),
                            GctBundle.message("uploadtogcp.addremotefailedtitle"));
                }
            });
            return false;
        }
        // catch newly added remote
        repository.update();
        return true;
    } catch (final VcsException ex) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Messages.showErrorDialog(project,
                        GctBundle.message("uploadtogcp.addremotefailed", url, ex.toString()),
                        GctBundle.message("uploadtogcp.addremotefailedtitle"));
            }
        });
        return false;
    }
}

From source file:com.google.cloud.tools.intellij.vcs.UploadSourceAction.java

License:Apache License

private static boolean performFirstCommitIfRequired(@NotNull final Project project, @NotNull VirtualFile root,
        @NotNull GitRepository repository, @NotNull ProgressIndicator indicator) {
    // check if there are no commits
    if (!repository.isFresh()) {
        return true;
    }//from www .  j  a v  a2  s .c om

    LOG.info("Trying to commit");
    try {
        LOG.info("Adding files for commit");
        indicator.setText(GctBundle.getString("uploadsourceaction.addfiles"));

        // ask for files to add
        final List<VirtualFile> trackedFiles = ChangeListManager.getInstance(project).getAffectedFiles();
        final Collection<VirtualFile> untrackedFiles = filterOutIgnored(project,
                repository.getUntrackedFilesHolder().retrieveUntrackedFiles());
        trackedFiles.removeAll(untrackedFiles); // fix IDEA-119855

        final List<VirtualFile> allFiles = new ArrayList<VirtualFile>();
        allFiles.addAll(trackedFiles);
        allFiles.addAll(untrackedFiles);

        final Ref<GcpUntrackedFilesDialog> dialogRef = new Ref<GcpUntrackedFilesDialog>();
        ApplicationManager.getApplication().invokeAndWait(new Runnable() {
            @Override
            public void run() {
                GcpUntrackedFilesDialog dialog = new GcpUntrackedFilesDialog(project, allFiles);
                if (!trackedFiles.isEmpty()) {
                    dialog.setSelectedFiles(trackedFiles);
                }
                DialogManager.show(dialog);
                dialogRef.set(dialog);
            }
        }, indicator.getModalityState());
        final GcpUntrackedFilesDialog dialog = dialogRef.get();

        final Collection<VirtualFile> filesToCommit = dialog.getSelectedFiles();
        if (!dialog.isOK() || filesToCommit.isEmpty()) {
            LOG.warn("user canceled out of initial commit.  aborting...");
            return false;
        }

        Set<VirtualFile> filesToCommitAsSet = new HashSet<>(filesToCommit);
        Set<VirtualFile> untrackedFilesAsSet = new HashSet<>(untrackedFiles);
        Set<VirtualFile> trackedFilesAsSet = new HashSet<>(trackedFiles);

        Collection<VirtualFile> filesToAdd = Sets.intersection(untrackedFilesAsSet, filesToCommitAsSet);
        Collection<VirtualFile> filesToRm = Sets.difference(trackedFilesAsSet, filesToCommitAsSet);
        Collection<VirtualFile> modified = new HashSet<VirtualFile>(trackedFiles);
        modified.addAll(filesToCommit);

        GitFileUtils.addFiles(project, root, filesToAdd);
        GitFileUtils.deleteFilesFromCache(project, root, filesToRm);

        // commit
        LOG.info("Performing commit");
        indicator.setText(GctBundle.getString("uploadsourceaction.performingcommit"));
        GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.COMMIT);
        handler.setStdoutSuppressed(false);
        handler.addParameters("-m", dialog.getCommitMessage());
        handler.endOptions();
        handler.run();

        VcsFileUtil.markFilesDirty(project, modified);
    } catch (final VcsException ex) {
        LOG.warn(ex);
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Messages.showErrorDialog(project,
                        GctBundle.message("uploadtogcp.initialcommitfailed", ex.toString()),
                        GctBundle.message("uploadtogcp.initialcommitfailedtitle"));
            }
        });
        return false;
    }
    LOG.info("Successfully created initial commit");
    return true;
}

From source file:com.google.cloud.tools.intellij.vcs.UploadSourceAction.java

License:Apache License

private static boolean pushCurrentBranch(final @NotNull Project project, @NotNull GitRepository repository,
        @NotNull String remoteName, @NotNull String remoteUrl) {
    Git git = ServiceManager.getService(Git.class);

    GitLocalBranch currentBranch = repository.getCurrentBranch();
    if (currentBranch == null) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override/*from   ww  w. j av a 2s.co  m*/
            public void run() {
                Messages.showErrorDialog(project, GctBundle.message("uploadtogcp.initialpushfailed"),
                        GctBundle.message("uploadtogcp.initialpushfailedtitle"));
            }
        });
        return false;
    }
    GitCommandResult result = git.push(repository, remoteName, remoteUrl, currentBranch.getName(), true);
    if (!result.success()) {
        LOG.warn(result.getErrorOutputAsJoinedString());
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Messages.showErrorDialog(project, GctBundle.message("uploadtogcp.initialpushfailed"),
                        GctBundle.message("uploadtogcp.initialpushfailedtitle"));
            }
        });
        return false;
    }
    return true;
}

From source file:com.google.gct.idea.appengine.action.NewEndpointFromClassAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    PsiJavaFile psiJavaFile = PsiUtils.getPsiJavaFileFromContext(e);
    Project project = e.getProject();//w  ww.  ja  v  a2 s  .  c om
    Module module = e.getData(LangDataKeys.MODULE);

    if (psiJavaFile == null || module == null || project == null) {
        Messages.showErrorDialog(project, "Please select a Java file to create an Endpoint for.",
                ERROR_MESSAGE_TITLE);
        return;
    }

    if (!AppEngineUtils.isAppEngineModule(module)) {
        Messages.showErrorDialog(project, "Endpoints can only be generated for App Engine projects.",
                ERROR_MESSAGE_TITLE);
        return;
    }

    String packageName = psiJavaFile.getPackageName();
    PsiDirectory psiJavaFileContainingDirectory = psiJavaFile.getContainingDirectory();
    if (psiJavaFileContainingDirectory == null) {
        Messages.showErrorDialog(project, DEFAULT_ERROR_MESSAGE, ERROR_MESSAGE_TITLE);
    }
    String directory = psiJavaFileContainingDirectory.getVirtualFile().getPath();
    PsiClass[] psiClasses = psiJavaFile.getClasses();
    if (psiClasses.length > 1) {
        Messages.showErrorDialog(project,
                "We only support generating an endpoint from Java files with one top level class.",
                "Error Generating Endpoint");
        return;
    }
    if (psiClasses.length == 0) {
        Messages.showErrorDialog(project, "This Java file does not contain any classes.",
                "Error Generating Endpoint");
        return;
    }
    PsiClass resourcePsiClass = psiClasses[0];
    boolean isObjectifyEntity = AnnotationUtil.isAnnotated(resourcePsiClass, OBJECTIFY_ENTITY_ANNOTATION, true);

    String idType = null;
    String idName = null;
    String idGetterName = null;
    if (isObjectifyEntity) {
        for (PsiField psiField : resourcePsiClass.getAllFields()) {
            if (AnnotationUtil.isAnnotated(psiField, OBJECTIFY_ID_ANNOTATION, false)) {
                idType = psiField.getType().getPresentableText();
                idName = psiField.getName();
            }
        }

        if (idType == null) {
            Messages.showErrorDialog(project,
                    "Please add the required @Id annotation to your entity before trying to generate an endpoint from"
                            + " this class.",
                    "Error Generating Objectify Endpoint.");
            return;
        }
        idGetterName = getIdGetter(resourcePsiClass, idName);
    }

    String fileName = psiJavaFile.getName();
    String classType = fileName.substring(0, fileName.lastIndexOf('.'));
    doAction(project, module, packageName, directory, classType, isObjectifyEntity, idType, idName,
            idGetterName);

    AnAction compileDirty = ActionManager.getInstance().getAction(COMPILE_DIRTY_ACTION_ID);
    if (compileDirty != null) {
        compileDirty.actionPerformed(e);
    }
}

From source file:com.google.gct.idea.appengine.action.NewEndpointFromClassAction.java

License:Apache License

/**
 * Generates an endpoint class in the specified module and updates the gradle build file
 * to include endpoint dependencies if they don't already exist.
 *//*from   www.  j a  v a 2s.c  o  m*/
private static void doAction(Project project, Module module, String packageName, String directory,
        @NonNls String classType, boolean isObjectifyEntity, @Nullable String idType, @Nullable String idName,
        @Nullable String idGetterName) {
    if (classType.isEmpty()) {
        Messages.showErrorDialog(project, "Class object is required for Endpoint generation",
                ERROR_MESSAGE_TITLE);
        return;
    }

    // Check if there is a file with the same name as the file that will contain the endpoint class
    String endpointFileName = directory + "/" + classType + ENDPOINT_CLASS_SUFFIX + ".java";
    String endpointFQClassName = packageName + "." + classType + ENDPOINT_CLASS_SUFFIX;
    File temp = new File(endpointFileName);
    if (temp.exists()) {
        Messages.showErrorDialog(project, "\'" + temp.getName() + "\" already exists", ERROR_MESSAGE_TITLE);
        return;
    }

    CloudTemplateUtils.TemplateInfo templateInfo = CloudTemplateUtils.getTemplate(ENDPOINT_TEMPLATE);

    if (templateInfo == null) {
        LOG.error("Failed to load endpoint template info: " + ENDPOINT_TEMPLATE);
        Messages.showErrorDialog(project, DEFAULT_ERROR_MESSAGE, ERROR_MESSAGE_TITLE);
        return;
    }

    final Template template = Template.createFromPath(templateInfo.getFile());
    final File projectRoot = new File(project.getBasePath());
    final File moduleRoot = new File(projectRoot, module.getName());

    // Create the replacement map
    final Map<String, Object> replacementMap = Maps.newHashMap();
    try {
        replacementMap.put(TemplateMetadata.ATTR_PROJECT_OUT, moduleRoot.getCanonicalPath());
    } catch (IOException e) {
        LOG.error(e);
        Messages.showErrorDialog("Failed to resolve Module output destination : " + e.getMessage(),
                ERROR_MESSAGE_TITLE);
        return;
    }

    String className = String.valueOf(Character.toLowerCase(classType.charAt(0)));
    if (classType.length() > 1) {
        className += classType.substring(1);
    }
    replacementMap.put("isObjectified", isObjectifyEntity);
    replacementMap.put("idType", idType);
    replacementMap.put("idName", idName);
    replacementMap.put("idGetterName", idGetterName);
    replacementMap.put(ENTITY_NAME, className);
    replacementMap.put(ENTITY_TYPE, classType);
    replacementMap.put(TemplateMetadata.ATTR_SRC_DIR, directory);
    replacementMap.put(TemplateMetadata.ATTR_PACKAGE_NAME, packageName);

    // Owner Domain is the reverse of package path.
    replacementMap.put(CloudModuleUtils.ATTR_ENDPOINTS_OWNER,
            StringUtil.join(ArrayUtil.reverseArray(packageName.split("\\.")), "."));
    replacementMap.put(CloudModuleUtils.ATTR_ENDPOINTS_PACKAGE, "");

    ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
            template.render(projectRoot, moduleRoot, replacementMap);
        }
    });

    // Add any missing Endpoint dependency to the build file and sync
    updateBuildFile(project, module, template);
    updateWebXml(project, module, endpointFQClassName, isObjectifyEntity);

    // Open the new Endpoint class in the editor
    VirtualFile endpointFile = LocalFileSystem.getInstance().findFileByPath(endpointFileName);
    new ReformatCodeProcessor(project, PsiManager.getInstance(project).findFile(endpointFile), null, false)
            .run();
    TemplateUtils.openEditor(project, endpointFile);

    UsageTracker.getInstance().trackEvent(GctTracking.CATEGORY, GctTracking.NEW_ENDPOINT,
            isObjectifyEntity ? "objectify" : "pojo", null);
}

From source file:com.google.gct.idea.appengine.deploy.AppEngineUpdateDialog.java

License:Apache License

private void populateFields() {
    myElysiumProjectId.setText("");
    myVersion.setText("");

    Module appEngineModule = myModuleComboBox.getSelectedModule();
    if (appEngineModule != null) {
        AppEngineGradleFacet facet = AppEngineGradleFacet.getAppEngineFacetByModule(appEngineModule);
        if (facet == null) {
            Messages.showErrorDialog(this.getPeer().getOwner(),
                    "Could not acquire App Engine module information.", "Deploy");
            return;
        }//from   ww w  .ja v  a2s  .  c  o  m

        final AppEngineWebApp appEngineWebApp = facet.getAppEngineWebXml();
        if (appEngineWebApp == null) {
            Messages.showErrorDialog(this.getPeer().getOwner(),
                    "Could not locate or parse the appengine-web.xml fle.", "Deploy");
            return;
        }

        String newProjectId = appEngineWebApp.getApplication().getRawText();
        if (!DEFAULT_APPID.equals(newProjectId)) {
            myElysiumProjectId.setText(newProjectId);
        }
        myVersion.setText(appEngineWebApp.getVersion().getRawText());
    }
}

From source file:com.google.gct.idea.appengine.deploy.AppEngineUpdateDialog.java

License:Apache License

@Override
protected void doOKAction() {
    if (getOKAction().isEnabled()) {
        Module selectedModule = myModuleComboBox.getSelectedModule();
        String sdk = "";
        String war = "";
        AppEngineGradleFacet facet = AppEngineGradleFacet.getAppEngineFacetByModule(selectedModule);
        if (facet != null) {
            AppEngineConfigurationProperties model = facet.getConfiguration().getState();
            if (model != null) {
                sdk = model.APPENGINE_SDKROOT;
                war = model.WAR_DIR;/*from   www.ja v a  2 s. c o m*/
            }
        }

        String client_secret = null;
        String client_id = null;
        String refresh_token = null;

        CredentialedUser selectedUser = myElysiumProjectId.getSelectedUser();
        if (selectedUser == null) {
            selectedUser = GoogleLogin.getInstance().getActiveUser();
            // Ask the user if he wants to continue using the active user credentials.
            if (selectedUser != null) {
                if (Messages.showYesNoDialog(this.getPeer().getOwner(),
                        "The Project ID you entered could not be found.  Do you want to deploy anyway using "
                                + GoogleLogin.getInstance().getActiveUser().getEmail() + " for credentials?",
                        "Deploy", Messages.getQuestionIcon()) != Messages.YES) {
                    return;
                }
            } else {
                // This should not happen as its validated.
                Messages.showErrorDialog(this.getPeer().getOwner(), "You need to be logged in to deploy.",
                        "Login");
                return;
            }
        }

        if (selectedUser != null) {
            client_secret = selectedUser.getGoogleLoginState().fetchOAuth2ClientSecret();
            client_id = selectedUser.getGoogleLoginState().fetchOAuth2ClientId();
            refresh_token = selectedUser.getGoogleLoginState().fetchOAuth2RefreshToken();
        }

        if (Strings.isNullOrEmpty(client_secret) || Strings.isNullOrEmpty(client_id)
                || Strings.isNullOrEmpty(refresh_token)) {
            // The login is somehow invalid, bail -- this shouldn't happen.
            LOG.error("StartUploading while logged in, but it doesn't have full credentials.");
            if (Strings.isNullOrEmpty(client_secret)) {
                LOG.error("(null) client_secret");
            }
            if (Strings.isNullOrEmpty(client_id)) {
                LOG.error("(null) client_id");
            }
            if (Strings.isNullOrEmpty(refresh_token)) {
                LOG.error("(null) refresh_token");
            }
            Messages.showErrorDialog(this.getPeer().getOwner(),
                    "The project ID is not a valid Google Console Developer Project.", "Login");
            return;
        }

        // These should not fail as they are a part of the dialog validation.
        if (Strings.isNullOrEmpty(sdk) || Strings.isNullOrEmpty(war)
                || Strings.isNullOrEmpty(myElysiumProjectId.getText()) || selectedModule == null) {
            Messages.showErrorDialog(this.getPeer().getOwner(),
                    "Could not deploy due to missing information (sdk/war/projectid).", "Deploy");
            LOG.error("StartUploading was called with bad module/sdk/war");
            return;
        }

        close(OK_EXIT_CODE); // We close before kicking off the update so it doesn't interfere with the output window coming to focus.

        // Kick off the upload.  detailed status will be shown in an output window.
        new AppEngineUpdater(myProject, selectedModule, sdk, war, myElysiumProjectId.getText(),
                myVersion.getText(), client_secret, client_id, refresh_token).startUploading();
    }
}

From source file:com.google.gct.idea.appengine.gradle.action.GenerateEndpointAction.java

License:Apache License

@Override
public void actionPerformed(AnActionEvent e) {
    PsiJavaFile psiJavaFile = PsiUtils.getPsiJavaFileFromContext(e);
    Project project = e.getProject();//www . j a  v a  2  s  .  c o  m
    Module module = e.getData(LangDataKeys.MODULE);

    if (psiJavaFile == null || module == null || project == null) {
        Messages.showErrorDialog(project, "Please select a Java file to create an Endpoint for.",
                ERROR_MESSAGE_TITLE);
        return;
    }

    try {
        if (!AppEngineUtils.isAppEngineModule(project, module)) {
            Messages.showErrorDialog(project, "Endpoints can only be generated for App Engine projects.",
                    ERROR_MESSAGE_TITLE);
            return;
        }
    } catch (FileNotFoundException error) {
        LOG.error(ERROR_MESSAGE_TITLE, error);
        Messages.showErrorDialog(project, DEFAULT_ERROR_MESSAGE, ERROR_MESSAGE_TITLE);
        return;
    }

    String packageName = psiJavaFile.getPackageName();
    PsiDirectory psiJavaFileContainingDirectory = psiJavaFile.getContainingDirectory();
    if (psiJavaFileContainingDirectory == null) {
        Messages.showErrorDialog(project, DEFAULT_ERROR_MESSAGE, ERROR_MESSAGE_TITLE);
    }
    String directory = psiJavaFileContainingDirectory.getVirtualFile().getPath();

    String classType = psiJavaFile.getName();
    int lastIndexOfDot = psiJavaFile.getName().lastIndexOf('.');
    if (lastIndexOfDot > 0) {
        classType = psiJavaFile.getName().substring(0, psiJavaFile.getName().lastIndexOf('.'));
    }

    doAction(project, module, packageName, directory, classType);
}