summaryrefslogtreecommitdiff
path: root/src/com/google/gct/idea/appengine/deploy/AppEngineUpdateDialog.java
blob: bd8c2f146ca199364fdade687d7a4214e6327037 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.gct.idea.appengine.deploy;

import com.google.common.base.Strings;
import com.google.gct.idea.appengine.dom.AppEngineWebApp;
import com.google.gct.idea.appengine.dom.AppEngineWebFileDescription;
import com.google.gct.idea.appengine.gradle.facet.AppEngineConfigurationProperties;
import com.google.gct.idea.appengine.gradle.facet.AppEngineGradleFacet;
import com.google.gct.login.GoogleLogin;
import com.google.gct.login.IGoogleLoginCompletedCallback;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ui.configuration.ModulesCombobox;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.ValidationInfo;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.packaging.artifacts.Artifact;
import com.intellij.packaging.artifacts.ArtifactManager;
import com.intellij.packaging.elements.PackagingElementResolvingContext;
import com.intellij.packaging.impl.artifacts.ArtifactUtil;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.xml.XmlFile;
import com.intellij.ui.SortedComboBoxModel;
import com.intellij.util.xml.DomElement;
import com.intellij.util.xml.DomFileElement;
import com.intellij.util.xml.DomManager;
import com.intellij.xml.util.XmlStringUtil;
import org.eclipse.jgit.util.StringUtils;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * AppEngineUpdateDialog shows a dialog allowing the user to select a module and deploy.
 */
public class AppEngineUpdateDialog extends DialogWrapper {
  private static final Logger LOG = Logger.getInstance(AppEngineUpdateDialog.class);

  private ModulesCombobox myModuleComboBox;
  private JTextField myProjectId;
  private JTextField myVersion;
  private JPanel myPanel;
  private List<Module> myDeployableModules;
  private Project myProject;
  private Module myInitiallySelectedModule;

  private AppEngineUpdateDialog(Project project, List<Module> deployableModules, Module selectedModule) {
    super(project, true);
    myDeployableModules = deployableModules;
    myProject = project;
    myInitiallySelectedModule = selectedModule;

    init();
    initValidation();
    setTitle("Deploy to App Engine");
    setOKButtonText("Deploy");

    Window myWindow = getWindow();
    if (myWindow != null) {
      myWindow.setPreferredSize(new Dimension(285, 135));
    }
  }

  /**
   * 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.
   *
   * @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;

    // Login on demand and queue up the dialog to show after a successful login.
    //if login fails, it already shows an error.
    if (!GoogleLogin.getInstance().isLoggedIn()) {
      // log in on demand...
      GoogleLogin.getInstance().logIn(null, new IGoogleLoginCompletedCallback() {
        @Override
        public void onLoginCompleted() {
          if (GoogleLogin.getInstance().isLoggedIn()) {
            EventQueue.invokeLater(new Runnable() {
              @Override
              public void run() {
                // Success!, lets run the deploy now.
                AppEngineUpdateDialog dialog = new AppEngineUpdateDialog(project, modules, passedSelectedModule);
                dialog.show();
              }
            });
          }
        }
      });
    }
    else {
      AppEngineUpdateDialog dialog = new AppEngineUpdateDialog(project, modules, passedSelectedModule);
      dialog.show();
    }
  }

  @Nullable
  @Override
  protected JComponent createCenterPanel() {
    @SuppressWarnings("unchecked")
    final SortedComboBoxModel<Module> model = (SortedComboBoxModel<Module>)myModuleComboBox.getModel();
    model.clear();
    model.addAll(myDeployableModules);

    if (myInitiallySelectedModule != null) {
      // Auto select if there is only one item
      model.setSelectedItem(myInitiallySelectedModule);
      populateFields();
    }

    myModuleComboBox.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        populateFields();
      }
    });
    return myPanel;
  }

  private void populateFields() {
    myProjectId.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;
      }

      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;
      }

      myProjectId.setText(appEngineWebApp.getApplication().getRawText());
      myVersion.setText(appEngineWebApp.getVersion().getRawText());
    }
  }

  @Override
  protected void doOKAction() {
    if (getOKAction().isEnabled()) {
      GoogleLogin login = GoogleLogin.getInstance();
      Module selectedModule = myModuleComboBox.getSelectedModule();
      String sdk = "";
      String war = "";
      AppEngineGradleFacet facet = AppEngineGradleFacet.getAppEngineFacetByModule(selectedModule);
      if (facet != null) {
        AppEngineConfigurationProperties model = facet.getConfiguration().getState();
        sdk = model.APPENGINE_SDKROOT;
        war = model.WAR_DIR;
      }

      String client_secret = login.fetchOAuth2ClientSecret();
      String client_id = login.fetchOAuth2ClientId();
      String refresh_token = login.fetchOAuth2RefreshToken();

      if (StringUtils.isEmptyOrNull(client_secret) ||
          StringUtils.isEmptyOrNull(client_id) ||
          StringUtils.isEmptyOrNull(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.");
        Messages.showErrorDialog(this.getPeer().getOwner(), "Login credentials are not valid.", "Login");
        return;
      }

      // These should not fail as they are a part of the dialog validation.
      if (Strings.isNullOrEmpty(sdk) ||
          Strings.isNullOrEmpty(war) ||
          Strings.isNullOrEmpty(myProjectId.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, myProjectId.getText(), myVersion.getText(),
                           client_secret, client_id, refresh_token).startUploading();
    }
  }

  @Override
  protected ValidationInfo doValidate() {
    // These should not normally occur..
    if (!GoogleLogin.getInstance().isLoggedIn()) {
      return new ValidationInfo("You must be logged in to perform this action.");
    }

    Module module = myModuleComboBox.getSelectedModule();
    if (module == null) {
      return new ValidationInfo("Select a module");
    }

    AppEngineGradleFacet facet = AppEngineGradleFacet.getAppEngineFacetByModule(module);
    if (facet == null) {
      return new ValidationInfo("Could not find App Engine gradle configuration on Module");
    }

    // We'll let AppCfg error if the project is wrong.  The user can see this in the console window.
    // Note that version can be blank to indicate current version.
    if (Strings.isNullOrEmpty(myProjectId.getText())) {
      return new ValidationInfo("Please enter a Project ID.");
    }

    return null;
  }

}