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.google.cloud.tools.intellij.debugger.ProjectRepositoryValidator.java

License:Apache License

private void unstash(final @NotNull Project project, @NotNull final Ref<StashInfo> targetStash,
        @NotNull final VirtualFile root) {
    if (repoState.getSourceRepository() == null || repoState.getOriginalBranchName() == null
            || (!repoState.getOriginalBranchName()
                    .equals(repoState.getSourceRepository().getCurrentBranchName())
                    && !repoState.getOriginalBranchName()
                            .equals(repoState.getSourceRepository().getCurrentRevision()))) {
        Messages.showErrorDialog(
                GctBundle.getString("clouddebug.erroroncheckout", repoState.getOriginalBranchName()), "Error");
        return;/*from w  ww  .ja v  a  2s .  c  o  m*/
    }
    final GitLineHandler handler = new GitLineHandler(project, root, GitCommand.STASH);
    handler.addParameters("apply");
    handler.addParameters("--index");
    addStashParameter(project, handler, targetStash.get().getStash());
    final AtomicBoolean conflict = new AtomicBoolean();

    handler.addLineListener(new GitLineHandlerAdapter() {
        @Override
        public void onLineAvailable(String line, Key outputType) {
            if (line.contains("Merge conflict")) {
                conflict.set(true);
            }
        }
    });
    GitUntrackedFilesOverwrittenByOperationDetector untrackedFilesDetector = new GitUntrackedFilesOverwrittenByOperationDetector(
            root);
    GitLocalChangesWouldBeOverwrittenDetector localChangesDetector = new GitLocalChangesWouldBeOverwrittenDetector(
            root, MERGE);
    handler.addLineListener(untrackedFilesDetector);
    handler.addLineListener(localChangesDetector);

    AccessToken token = DvcsUtil.workingTreeChangeStarted(project);
    try {
        final Ref<GitCommandResult> result = Ref.create();
        ProgressManager.getInstance()
                .run(new Task.Modal(handler.project(), GitBundle.getString("unstash.unstashing"), false) {
                    @Override
                    public void run(@NotNull final ProgressIndicator indicator) {
                        indicator.setIndeterminate(true);
                        handler.addLineListener(new GitHandlerUtil.GitLineHandlerListenerProgress(indicator,
                                handler, "stash", false));
                        Git git = ServiceManager.getService(Git.class);
                        result.set(git
                                .runCommand(new Computable.PredefinedValueComputable<GitLineHandler>(handler)));
                    }
                });

        ServiceManager.getService(project, GitPlatformFacade.class).hardRefresh(root);
        GitCommandResult res = result.get();
        if (conflict.get()) {
            Messages.showDialog(GctBundle.getString("clouddebug.unstashmergeconflicts"), "Merge Conflicts",
                    new String[] { "Ok" }, 0, Messages.getErrorIcon());

        } else if (untrackedFilesDetector.wasMessageDetected()) {
            GitUntrackedFilesHelper.notifyUntrackedFilesOverwrittenBy(project, root,
                    untrackedFilesDetector.getRelativeFilePaths(), "unstash", null);
        } else if (localChangesDetector.wasMessageDetected()) {
            LocalChangesWouldBeOverwrittenHelper.showErrorDialog(project, root, "unstash",
                    localChangesDetector.getRelativeFilePaths());
        } else if (!res.success()) {
            GitUIUtil.showOperationErrors(project, handler.errors(), handler.printableCommandLine());
        } else if (res.success()) {
            ProgressManager.getInstance().run(new Task.Modal(project,
                    GctBundle.getString("clouddebug.removestashx", targetStash.get().getStash()), false) {
                @Override
                public void run(@NotNull ProgressIndicator indicator) {
                    if (project == null) {
                        return;
                    }
                    final GitSimpleHandler h = new GitSimpleHandler(project, root, GitCommand.STASH);
                    h.addParameters("drop");
                    addStashParameter(project, h, targetStash.get().getStash());
                    try {
                        h.run();
                        h.unsilence();
                    } catch (final VcsException ex) {
                        ApplicationManager.getApplication().invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                GitUIUtil.showOperationError(project, ex, h.printableCommandLine());
                            }
                        });
                    }
                }
            });

        }
    } finally {
        DvcsUtil.workingTreeChangeFinished(project, token);
    }
}

From source file:com.google.cloud.tools.intellij.login.GoogleLoginUtils.java

License:Apache License

/**
 * Opens an error dialog with the specified title. Ensures that the error dialog is opened on the
 * UI thread./*from  www. j  av a 2 s  . c o m*/
 *
 * @param message The message to be displayed.
 * @param title The title of the error dialog to be displayed
 */
public static void showErrorDialog(final String message, @NotNull final String title) {
    if (ApplicationManager.getApplication().isDispatchThread()) {
        Messages.showErrorDialog(message, title);
    } else {
        ApplicationManager.getApplication().invokeLater(new Runnable() {
            @Override
            public void run() {
                Messages.showErrorDialog(message, title);
            }
        }, ModalityState.defaultModalityState());
    }
}

From source file:com.google.cloud.tools.intellij.settings.ExportSettings.java

License:Apache License

/**
 * Exports IDEA settings.//from ww  w . j  av  a2 s.co  m
 */
public static void doExport(String path) {
    final Set<ExportableComponent> exportableComponents = new HashSet<ExportableComponent>(Arrays
            .asList(ApplicationManager.getApplication().getComponents(ExportableApplicationComponent.class)));
    exportableComponents.addAll(
            ServiceBean.loadServicesFromBeans(ExportableComponent.EXTENSION_POINT, ExportableComponent.class));

    if (exportableComponents.isEmpty()) {
        return;
    }

    Set<File> exportFiles = new HashSet<File>();
    for (final ExportableComponent markedComponent : exportableComponents) {
        ContainerUtil.addAll(exportFiles, markedComponent.getExportFiles());
    }

    ApplicationManager.getApplication().saveSettings();

    final File saveFile = new File(path);
    try {
        if (saveFile.exists()) {
            final int ret = Messages.showOkCancelDialog(
                    IdeBundle.message("prompt.overwrite.settings.file",
                            FileUtil.toSystemDependentName(saveFile.getPath())),
                    IdeBundle.message("title.file.already.exists"), Messages.getWarningIcon());
            if (ret != Messages.OK) {
                return;
            }
        }

        final JarOutputStream output = new JarOutputStream(new FileOutputStream(saveFile));
        try {
            final File configPath = new File(PathManager.getConfigPath());
            final Set<String> writtenItemRelativePaths = new HashSet<String>();
            for (File file : exportFiles) {
                final String rPath = FileUtil.getRelativePath(configPath, file);
                assert rPath != null;
                final String relativePath = FileUtil.toSystemIndependentName(rPath);
                if (file.exists()) {
                    ZipUtil.addFileOrDirRecursively(output, saveFile, file, relativePath, null,
                            writtenItemRelativePaths);
                }
            }

            exportInstalledPlugins(saveFile, output, writtenItemRelativePaths);

            final File magicFile = new File(FileUtil.getTempDirectory(), SETTINGS_JAR_MARKER);
            FileUtil.createIfDoesntExist(magicFile);
            magicFile.deleteOnExit();
            ZipUtil.addFileToZip(output, magicFile, SETTINGS_JAR_MARKER, writtenItemRelativePaths, null);
        } finally {
            output.close();
        }
    } catch (IOException e1) {
        Messages.showErrorDialog(IdeBundle.message("error.writing.settings", e1.toString()),
                IdeBundle.message("title.error.writing.file"));
    }

}

From source file:com.google.cloud.tools.intellij.settings.ImportSettings.java

License:Apache License

/**
 * Parse and update the IDEA settings in the jar at <code>path</code>. Note: This function might
 * require a restart of the application.
 *
 * @param path The location of the jar with the new IDEA settings.
 */// w w w .java  2s .com
public static void doImport(String path) {
    final File saveFile = new File(path);
    ZipFile saveZipFile = null;
    try {
        if (!saveFile.exists()) {
            Messages.showErrorDialog(IdeBundle.message("error.cannot.find.file", presentableFileName(saveFile)),
                    DIALOG_TITLE);
            return;
        }

        // What is this file used for?
        saveZipFile = new ZipFile(saveFile);
        final ZipEntry magicEntry = saveZipFile.getEntry(SETTINGS_JAR_MARKER);
        if (magicEntry == null) {
            Messages.showErrorDialog(
                    "The file " + presentableFileName(saveFile) + " contains no settings to import",
                    DIALOG_TITLE);
            return;
        }

        final List<ExportableComponent> registeredComponents = new ArrayList<ExportableComponent>(Arrays.asList(
                ApplicationManager.getApplication().getComponents(ExportableApplicationComponent.class)));
        registeredComponents.addAll(ServiceBean.loadServicesFromBeans(ExportableComponent.EXTENSION_POINT,
                ExportableComponent.class));

        List<ExportableComponent> storedComponents = getComponentsStored(saveFile, registeredComponents);

        Set<String> relativeNamesToExtract = new HashSet<String>();
        for (final ExportableComponent exportableComponent : storedComponents) {
            final File[] exportFiles = exportableComponent.getExportFiles();
            for (File exportFile : exportFiles) {
                final File configPath = new File(PathManager.getConfigPath());
                final String rPath = FileUtil.getRelativePath(configPath, exportFile);
                assert rPath != null;
                final String relativePath = FileUtil.toSystemIndependentName(rPath);
                relativeNamesToExtract.add(relativePath);
            }
        }

        relativeNamesToExtract.add(PluginManager.INSTALLED_TXT);

        final File tempFile = new File(PathManager.getPluginTempPath() + "/" + saveFile.getName());
        FileUtil.copy(saveFile, tempFile);
        File outDir = new File(PathManager.getConfigPath());
        final ImportSettingsFilenameFilter filenameFilter = new ImportSettingsFilenameFilter(
                relativeNamesToExtract);
        StartupActionScriptManager.ActionCommand unzip = new StartupActionScriptManager.UnzipCommand(tempFile,
                outDir, filenameFilter);
        StartupActionScriptManager.addActionCommand(unzip);

        // remove temp file
        StartupActionScriptManager.ActionCommand deleteTemp = new StartupActionScriptManager.DeleteCommand(
                tempFile);
        StartupActionScriptManager.addActionCommand(deleteTemp);

        UpdateSettings.getInstance().forceCheckForUpdateAfterRestart();

        String key = ApplicationManager.getApplication().isRestartCapable()
                ? "message.settings.imported.successfully.restart"
                : "message.settings.imported.successfully";
        final int ret = Messages.showOkCancelDialog(
                IdeBundle.message(key, ApplicationNamesInfo.getInstance().getProductName(),
                        ApplicationNamesInfo.getInstance().getFullProductName()),
                IdeBundle.message("title.restart.needed"), Messages.getQuestionIcon());
        if (ret == Messages.OK) {
            ((ApplicationEx) ApplicationManager.getApplication()).restart(true);
        }
    } catch (ZipException e1) {
        Messages.showErrorDialog(
                "Error reading file " + presentableFileName(saveFile) + ".\\nThere was " + e1.getMessage(),
                DIALOG_TITLE);
    } catch (IOException e1) {
        Messages.showErrorDialog(IdeBundle.message("error.reading.settings.file.2",
                presentableFileName(saveFile), e1.getMessage()), DIALOG_TITLE);
    } finally {
        try {
            if (saveZipFile != null) {
                saveZipFile.close();
            }
        } catch (IOException e1) {
            Messages.showErrorDialog(GctBundle.message("settings.error.closing.file",
                    presentableFileName(saveFile), e1.getMessage()), DIALOG_TITLE);
        }
    }
}

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

License:Apache License

private static void updateWebXml(Project project, Module module, final String endpointFQClassName,
        boolean isObjectifyEndpoint) {
    AppEngineGradleFacet facet = AppEngineGradleFacet.getAppEngineFacetByModule(module);
    final WebApp webApp = facet.getWebXmlForEdit();
    if (isObjectifyEndpoint && !hasObjectifyFilter(webApp)) {
        CommandProcessor.getInstance().executeCommand(project, new Runnable() {
            @Override/* w  ww  . j  ava  2  s  . co  m*/
            public void run() {
                ApplicationManager.getApplication().runWriteAction(new Runnable() {
                    @Override
                    public void run() {
                        WebApp.Filter objectifyFilter = webApp.addFilter();
                        WebApp.FilterMapping filterMapping = webApp.addFilterMapping();
                        objectifyFilter.getFilterName().setValue(OBJECTIFY_FILTER_NAME);
                        objectifyFilter.getFilterClass().setValue(OBJECTIFY_FQ_FILTER_CLASS);
                        filterMapping.getFilterName().setValue(OBJECTIFY_FILTER_NAME);
                        filterMapping.getUrlPattern().setValue("/*");
                    }
                });
            }
        }, "Update App Engine web.xml", null);
    }

    String result = validateWebXml(webApp);
    if (result != null) {
        Messages.showErrorDialog(result, ERROR_MESSAGE_TITLE);
        return;
    }
    WebApp.Servlet.InitParam.ParamValue endpointServletParamValue = getEndpointServletInitParam(webApp);
    if (endpointServletParamValue == null) {
        Messages.showErrorDialog(
                "Could not find a correctly configured SystemServiceServlet in this module's web.xml",
                ERROR_MESSAGE_TITLE);
    } else {
        addEndpointClassToInitParam(project, endpointServletParamValue, endpointFQClassName);
    }
}

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

License:Apache License

/**
 * Adds missing endpoint dependencies to gradle build file of the specified module.
 *//*  www.ja v  a2s  . com*/
private static void updateBuildFile(@NonNls Project project, @NotNull Module module,
        @NonNls Template template) {
    final VirtualFile buildFile = GradleUtil.getGradleBuildFile(module);
    if (buildFile == null) {
        Messages.showErrorDialog("Cannot find gradle build file for module \"" + module.getName() + "\"",
                ERROR_MESSAGE_TITLE);
        return;
    }

    Parameter appEngineVersionParam = template.getMetadata().getParameter("appEngineVersion");
    String appEngineVersion = (appEngineVersionParam == null) ? "+" : appEngineVersionParam.initial;

    final GradleBuildFile gradleBuildFile = new GradleBuildFile(buildFile, project);
    Dependency endpointDependency = new Dependency(Dependency.Scope.COMPILE, Dependency.Type.EXTERNAL,
            ENDPOINTS_DEPENDENCY + appEngineVersion);
    Dependency endpointDepsDependency = new Dependency(Dependency.Scope.COMPILE, Dependency.Type.EXTERNAL,
            ENDPOINTS_DEPS_DEPENDENCY + appEngineVersion);
    List<Dependency> missingDependencies = Lists.newArrayList();

    // Check if the endpoint dependencies already exist in the gradle file
    if (!gradleBuildFile.hasDependency(endpointDependency)) {
        missingDependencies.add(endpointDependency);
    }

    if (!gradleBuildFile.hasDependency(endpointDepsDependency)) {
        missingDependencies.add(endpointDepsDependency);
    }

    // Add the missing dependencies to the gradle build file
    if (!missingDependencies.isEmpty()) {
        final List<BuildFileStatement> currentDependencies = gradleBuildFile.getDependencies();
        currentDependencies.addAll(missingDependencies);

        WriteCommandAction.runWriteCommandAction(project, new Runnable() {
            @Override
            public void run() {
                gradleBuildFile.setValue(BuildFileKey.DEPENDENCIES, currentDependencies);
            }
        });

        GradleProjectImporter.getInstance().requestProjectSync(project, null);
    }
}

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

License:Apache License

/**
 * Shows a dialog to deploy a module to AppEngine.  Will force a login if required
 * If either the login fails or there are no valid modules to upload, it will return  after
 * displaying an error.//w w w. j  av  a  2 s .  co m
 *
 * @param project The project whose modules will be uploaded.
 * @param selectedModule The module selected by default in the deploy dialog.  Can be null.  If null or not a valid app engine module,
 *                       no module will be selected by default.
 */
static void show(final Project project, Module selectedModule) {

    final java.util.List<Module> modules = new ArrayList<Module>();

    // Filter the module list by whether we can actually deploy them to appengine.
    for (Module module : ModuleManager.getInstance(project).getModules()) {
        AppEngineGradleFacet facet = AppEngineGradleFacet.getAppEngineFacetByModule(module);
        if (facet != null) {
            modules.add(module);
        }
    }

    // Tell the user what he has to do if he has none.
    if (modules.size() == 0) {
        //there are no modules to upload -- or we hit a bug due to gradle sync.
        //TODO do we need to use the mainwindow as owner?
        Messages.showErrorDialog(XmlStringUtil.wrapInHtml(
                "This project does not contain any App Engine modules. To add an App Engine module for your project, <br> open File > New Module? menu and choose one of App Engine modules."),
                "Error");
        return;
    }

    if (selectedModule != null && !modules.contains(selectedModule)) {
        selectedModule = null;
    }

    if (selectedModule == null && modules.size() == 1) {
        selectedModule = modules.get(0);
    }

    // To invoke later, we need a final local.
    final Module passedSelectedModule = selectedModule;

    AppEngineUpdateDialog dialog = new AppEngineUpdateDialog(project, modules, passedSelectedModule);
    dialog.show();
}

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

License:Apache License

private void startUploadingProcess() {
    final Process process;
    final GeneralCommandLine commandLine;

    try {/*w w  w  .j  a  v a2s  . c  o m*/
        JavaParameters parameters = new JavaParameters();
        parameters.configureByModule(myModule, JavaParameters.JDK_ONLY);
        parameters.setMainClass("com.google.appengine.tools.admin.AppCfg");
        AppEngineSdk mySdk = new AppEngineSdk(mySdkPath);
        if (mySdk.getToolsApiJarFile() == null) {
            Messages.showErrorDialog("Cannot start uploading: The tools sdk jar could not be located.",
                    "Error");
            return;
        }
        parameters.getClassPath().add(mySdk.getToolsApiJarFile().getAbsolutePath());

        final List<KeyValue<String, String>> list = HttpConfigurable.getJvmPropertiesList(false, null);
        if (!list.isEmpty()) {
            final ParametersList parametersList = parameters.getVMParametersList();
            for (KeyValue<String, String> value : list) {
                parametersList.defineProperty(value.getKey(), value.getValue());
            }
        }

        final ParametersList programParameters = parameters.getProgramParametersList();
        programParameters.add("--application=" + myAppEngineProject);
        if (!Strings.isNullOrEmpty(myVersion)) {
            programParameters.add("--version=" + myVersion);
        }
        programParameters.add("--oauth2");
        programParameters.add("--oauth2_client_secret=" + myClientSecret);
        programParameters.add("--oauth2_client_id=" + myClientId);
        programParameters.add("--oauth2_refresh_token=" + myRefreshToken);
        programParameters.add("update");
        programParameters.add(FileUtil.toSystemDependentName(myExplodedWarPath));

        commandLine = CommandLineBuilder.createFromJavaParameters(parameters);

        process = commandLine.createProcess();
    } catch (ExecutionException e) {
        final String message = e.getMessage();
        LOG.error("Cannot start uploading: " + message);

        if (!EventQueue.isDispatchThread()) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    Messages.showErrorDialog("Cannot start uploading: " + message, "Error");
                }
            });
        } else {
            Messages.showErrorDialog("Cannot start uploading: " + message, "Error");
        }

        return;
    }

    UsageTracker.getInstance().trackEvent(GctTracking.CATEGORY, GctTracking.DEPLOY, "upload.app", null);

    final ProcessHandler processHandler = new FilteredOSProcessHandler(process,
            commandLine.getCommandLineString(), new String[] { myRefreshToken, myClientSecret, myClientId });
    final Executor executor = DefaultRunExecutor.getRunExecutorInstance();
    final ConsoleView console = TextConsoleBuilderFactory.getInstance().createBuilder(myModule.getProject())
            .getConsole();
    final RunnerLayoutUi ui = RunnerLayoutUi.Factory.getInstance(myModule.getProject()).create("Deploy",
            "Deploy to AppEngine", "Deploy Application", myModule.getProject());
    final DefaultActionGroup group = new DefaultActionGroup();
    ui.getOptions().setLeftToolbar(group, ActionPlaces.UNKNOWN);
    ui.addContent(ui.createContent("upload", console.getComponent(), "Deploy Application", null,
            console.getPreferredFocusableComponent()));

    console.attachToProcess(processHandler);
    final RunContentDescriptor contentDescriptor = new RunContentDescriptor(console, processHandler,
            ui.getComponent(), "Deploy to AppEngine");
    group.add(ActionManager.getInstance().getAction(IdeActions.ACTION_STOP_PROGRAM));
    group.add(new CloseAction(executor, contentDescriptor, myModule.getProject()));

    ExecutionManager.getInstance(myModule.getProject()).getContentManager().showRunContent(executor,
            contentDescriptor);
    processHandler.startNotify();
}

From source file:com.google.gct.idea.appengine.wizard.CloudModuleUtils.java

License:Apache License

static void createModule(@NotNull final Project project, @NotNull final File templateFile,
        @NotNull final String moduleName, @NotNull String packageName,
        @Nullable final String clientModuleName) {
    final File projectRoot = new File(project.getBasePath());
    final File moduleRoot = new File(projectRoot, moduleName);
    FileUtil.createDirectory(moduleRoot);

    final Map<String, Object> replacementMap = Maps.newHashMap();
    try {/*from ww  w  . j  ava2  s  .com*/
        replacementMap.put(TemplateMetadata.ATTR_PROJECT_OUT, moduleRoot.getCanonicalPath());
    } catch (IOException e) {
        Messages.showErrorDialog("Failed to resolve Module output destination : " + e.getMessage(),
                ERROR_MESSAGE_TITLE);
        LOG.error(e);
        return;
    }
    replacementMap.put(ATTR_MODULE_NAME, moduleName);
    replacementMap.put(ATTR_PACKAGE_NAME, packageName);

    if (CloudTemplateUtils.LOCAL_ENDPOINTS_TEMPLATES.contains(templateFile.getName())) {
        populateEndpointParameters(replacementMap, packageName);
    }

    final Template template = Template.createFromPath(templateFile);

    final List<File> allFilesToOpen = Lists.newArrayList();
    template.render(projectRoot, moduleRoot, replacementMap, project);

    UsageTracker.getInstance().trackEvent(GctTracking.CATEGORY, GctTracking.WIZARD, templateFile.getName(),
            null);

    allFilesToOpen.addAll(template.getFilesToOpen());

    ApplicationManager.getApplication().runReadAction(new Runnable() {
        @Override
        public void run() {
            final Module clientModule;
            if (Strings.isNullOrEmpty(clientModuleName)) {
                clientModule = null;
            } else {
                // requires read action
                clientModule = ModuleManager.getInstance(project).findModuleByName(clientModuleName);
            }
            final Template clientTemplate = CloudTemplateUtils.getClientModuleTemplate(templateFile.getName());

            addPropertiesFromClientModule(clientModule, replacementMap);
            DumbService.getInstance(project).smartInvokeLater(new Runnable() {
                // because the previous template render initiates some indexing, if we don't smart invoke later we might
                // cause a IndexNotReadyException when starting this.
                @Override
                public void run() {
                    if (clientModule != null) {
                        patchClientModule(clientModule, clientTemplate, replacementMap, project);
                        allFilesToOpen.addAll(clientTemplate.getFilesToOpen());
                    }
                    TemplateUtils.openEditors(project, allFilesToOpen, true);
                }
            });
        }
    });

    // download SDK, the appengine-gradle-plugin will know what to do
    DumbService.getInstance(project).smartInvokeLater(new Runnable() {
        @Override
        public void run() {
            GradleInvoker.getInstance(project).executeTasks(Collections.singletonList("appengineDownloadSdk"));
        }
    });
}

From source file:com.google.gct.idea.appengine.wizard.NewAppEngineModuleAction.java

License:Apache License

public static void createModule(final Project project, File templateFile, final String moduleName,
        String packageName, final String clientModuleName) {
    final Template template = Template.createFromPath(templateFile);
    final Template clientTemplate = AppEngineTemplates.getClientModuleTemplate(templateFile.getName());
    final Module clientModule = StringUtil.isEmpty(clientModuleName) ? null
            : ModuleManager.getInstance(project).findModuleByName(clientModuleName);

    final File projectRoot = new File(project.getBasePath());
    final File moduleRoot = new File(projectRoot, moduleName);
    FileUtil.createDirectory(moduleRoot);

    final Map<String, Object> replacementMap = new HashMap<String, Object>();
    try {//from  w w  w .  j  ava 2s .c  o  m
        replacementMap.put(TemplateMetadata.ATTR_PROJECT_OUT, moduleRoot.getCanonicalPath());
    } catch (IOException e) {
        Messages.showErrorDialog("Failed to resolve Module output destination : " + e.getMessage(),
                ERROR_MESSAGE_TITLE);
        LOG.error(e);
        return;
    }
    replacementMap.put(ATTR_MODULE_NAME, moduleName);
    replacementMap.put(TemplateMetadata.ATTR_PACKAGE_NAME, packageName);
    addPropertiesFromClientModule(clientModule, replacementMap);

    if (AppEngineTemplates.LOCAL_ENDPOINTS_TEMPLATES.contains(templateFile.getName())) {
        AppEngineTemplates.populateEndpointParameters(replacementMap, packageName);
    }

    ApplicationManager.getApplication().runWriteAction(new Runnable() {
        @Override
        public void run() {
            List<File> allFilesToOpen = new ArrayList<File>();
            template.render(projectRoot, moduleRoot, replacementMap);
            allFilesToOpen.addAll(template.getFilesToOpen());

            if (clientModule != null) {
                patchClientModule(clientModule, clientTemplate, replacementMap);
                allFilesToOpen.addAll(clientTemplate.getFilesToOpen());
            }

            TemplateUtils.openEditors(project, allFilesToOpen, true);

            GradleProjectImporter projectImporter = GradleProjectImporter.getInstance();
            projectImporter.requestProjectSync(project, new GradleSyncListener.Adapter() {

                @Override
                public void syncSucceeded(@NotNull final Project project) {
                    ApplicationManager.getApplication().runWriteAction(new Runnable() {
                        @Override
                        public void run() {
                            Module module = ModuleManager.getInstance(project).findModuleByName(moduleName);
                            createRunConfiguration(project, module);
                        }
                    });
                }

                @Override
                public void syncFailed(@NotNull Project project, @NotNull final String errorMessage) {
                    ApplicationManager.getApplication().invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            Messages.showErrorDialog("Error importing App Engine module : " + errorMessage,
                                    ERROR_MESSAGE_TITLE);
                        }
                    });
                }
            });
        }
    });
}