Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 5009e62868b0afcc3c33c384ab0b2f5e129d65af (plain) (blame)
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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/*************************************************************************************
 * Copyright (c) 2011-2018 Red Hat, Inc. and others.
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     Fred Bricon / JBoss by Red Hat - Initial implementation.
 ************************************************************************************/

package org.eclipse.m2e.profiles.ui.internal.actions;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.IJobChangeListener;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;

import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.internal.IMavenConstants;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.core.ui.internal.actions.SelectionUtil;
import org.eclipse.m2e.profiles.core.internal.IProfileManager;
import org.eclipse.m2e.profiles.core.internal.MavenProfilesCoreActivator;
import org.eclipse.m2e.profiles.core.internal.ProfileData;
import org.eclipse.m2e.profiles.core.internal.ProfileState;
import org.eclipse.m2e.profiles.ui.internal.MavenProfilesUIActivator;
import org.eclipse.m2e.profiles.ui.internal.Messages;
import org.eclipse.m2e.profiles.ui.internal.dialog.ProfileSelection;
import org.eclipse.m2e.profiles.ui.internal.dialog.SelectProfilesDialog;


/**
 * Handles profile selection commands.
 * 
 * @author Fred Bricon
 * @since 1.5
 */
public class ProfileSelectionHandler extends AbstractHandler {

  private static final Logger log = LoggerFactory.getLogger(ProfileSelectionHandler.class);

  /**
   * Opens the Maven profile selection Dialog window.
   */
  public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    IProject[] projects = getSelectedProjects(event);
    return execute(window.getShell(), projects);
  }

  private IProject[] getSelectedProjects(ExecutionEvent event) {
    ISelection selection = HandlerUtil.getCurrentSelection(event);
    IProject[] projects = SelectionUtil.getProjects(selection, false);
    if(projects.length == 0) {
      IEditorInput input = HandlerUtil.getActiveEditorInput(event);
      if(input instanceof IFileEditorInput) {
        IFileEditorInput fileInput = (IFileEditorInput) input;
        projects = new IProject[] {fileInput.getFile().getProject()};
      }
    }
    return projects;
  }

  public IStatus execute(Shell shell, IProject... projects) throws ExecutionException {
    Set<IMavenProjectFacade> facades = getMavenProjects(projects);
    if(facades.isEmpty()) {
      display(shell, Messages.ProfileSelectionHandler_Select_some_maven_projects);
      return null;
    }

    final IProfileManager profileManager = MavenProfilesCoreActivator.getDefault().getProfileManager();

    GetProfilesJob getProfilesJob = new GetProfilesJob(facades, profileManager);
    getProfilesJob.addJobChangeListener(onProfilesFetched(getProfilesJob, facades, profileManager, shell));
    getProfilesJob.setUser(true);
    getProfilesJob.schedule();
    return Status.OK_STATUS;
  }

  private IJobChangeListener onProfilesFetched(final GetProfilesJob getProfilesJob,
      final Set<IMavenProjectFacade> facades, final IProfileManager profileManager, final Shell shell) {

    return new JobChangeAdapter() {

      @Override
      public void done(IJobChangeEvent event) {
        if(getProfilesJob.getResult().isOK()) {
          shell.getDisplay().syncExec(new Runnable() {

            public void run() {
              List<ProfileSelection> sharedProfiles = getProfilesJob.getSharedProfiles();
              Map<IMavenProjectFacade, List<ProfileData>> allProfiles = getProfilesJob.getAllProfiles();
              final SelectProfilesDialog dialog = new SelectProfilesDialog(shell, facades, sharedProfiles);
              if(dialog.open() == Dialog.OK) {
                Job job = new UpdateProfilesJob(allProfiles, sharedProfiles, profileManager, dialog);
                job.setRule(MavenPlugin.getProjectConfigurationManager().getRule());
                job.schedule();
              }
            }
          });

        }
      }
    };
  }

  private void display(Shell shell, String message) {
    MessageDialog.openInformation(shell, Messages.SelectProfilesDialog_Select_Maven_profiles, message);
  }

  /**
   * Returns an IMavenProjectFacade from the selected IResource, or from the active editor
   * 
   * @param event
   * @return the selected IMavenProjectFacade
   */
  private Set<IMavenProjectFacade> getMavenProjects(IProject[] projects) {
    if(projects == null || projects.length == 0) {
      return Collections.emptySet();
    }
    Set<IMavenProjectFacade> facades = new HashSet<IMavenProjectFacade>(projects.length);
    try {
      IProgressMonitor monitor = new NullProgressMonitor();
      for(IProject p : projects) {
        if(p != null && p.isAccessible() && p.hasNature(IMavenConstants.NATURE_ID)) {
          IFile pom = p.getFile(IMavenConstants.POM_FILE_NAME);
          IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry().create(pom, true, monitor);
          facades.add(facade);
        }
      }
    } catch(CoreException e) {
      log.error("Unable to select Maven projects", e);
    }

    return facades;
  }

  class GetProfilesJob extends Job {

    private IProfileManager profileManager;

    private Set<IMavenProjectFacade> facades;

    private Map<IMavenProjectFacade, List<ProfileData>> allProfiles;

    private List<ProfileSelection> sharedProfiles;

    private GetProfilesJob(final Set<IMavenProjectFacade> facades, IProfileManager profileManager) {
      super(Messages.ProfileSelectionHandler_Loading_maven_profiles);
      this.facades = facades;
      this.profileManager = profileManager;
    }

    @Override
    protected IStatus run(IProgressMonitor monitor) {
      try {
        this.allProfiles = getAllProfiles(facades, profileManager);
        this.sharedProfiles = getSharedProfiles(allProfiles);
      } catch(CoreException e) {
        return new Status(IStatus.ERROR, MavenProfilesUIActivator.PLUGIN_ID,
            Messages.ProfileSelectionHandler_Unable_to_open_profile_dialog, e);
      }
      return Status.OK_STATUS;
    }

    private List<ProfileSelection> getSharedProfiles(Map<IMavenProjectFacade, List<ProfileData>> projectProfilesMap) {

      List<ProfileData> currentSelection = null;
      List<List<ProfileData>> projectProfiles = new ArrayList<List<ProfileData>>(projectProfilesMap.values());
      int smallestSize = Integer.MAX_VALUE;
      for(List<ProfileData> profiles : projectProfiles) {
        int size = profiles.size();
        if(size < smallestSize) {
          smallestSize = size;
          currentSelection = profiles;
        }
      }
      projectProfiles.remove(currentSelection);

      // Init the smallest profiles selection possible
      List<ProfileSelection> selection = new ArrayList<ProfileSelection>();
      for(ProfileData p : currentSelection) {
        ProfileSelection ps = new ProfileSelection();
        ps.setId(p.getId());
        ps.setActivationState(p.getActivationState());
        ps.setAutoActive(p.isAutoActive());
        ps.setSource(p.getSource());
        ps.setSelected(p.isUserSelected());
        selection.add(ps);
      }

      if(!projectProfiles.isEmpty()) {
        // Restrict to the common profiles only
        Iterator<ProfileSelection> ite = selection.iterator();

        while(ite.hasNext()) {
          ProfileSelection p = ite.next();
          for(List<ProfileData> statuses : projectProfiles) {
            ProfileData s = hasProfile(p.getId(), statuses);
            if(s == null) {
              // remove any non-common profile selection
              ite.remove();
              break;
            }
            // reset non common settings
            if(p.getAutoActive() != null && !p.getAutoActive().equals(s.isAutoActive())) {
              p.setAutoActive(null);
            }
            if(p.getSource() != null && !p.getSource().equals(s.getSource())) {
              p.setSource(Messages.ProfileSelectionHandler_multiple_definitions);
            }
            if(p.getSelected() != null && !p.getSelected().equals(s.isUserSelected())) {
              p.setSelected(null);
            }
            if(p.getActivationState() != null && !p.getActivationState().equals(s.getActivationState())) {
              p.setActivationState(null);
              p.setAutoActive(null);
            }
          }
        }
      }

      return selection;
    }

    private ProfileData hasProfile(String id, List<ProfileData> statuses) {
      for(ProfileData p : statuses) {
        if(id.equals(p.getId())) {
          return p;
        }
      }
      return null;
    }

    private Map<IMavenProjectFacade, List<ProfileData>> getAllProfiles(final Set<IMavenProjectFacade> facades,
        final IProfileManager profileManager) throws CoreException {
      Map<IMavenProjectFacade, List<ProfileData>> allProfiles = new HashMap<IMavenProjectFacade, List<ProfileData>>(
          facades.size());
      IProgressMonitor monitor = new NullProgressMonitor();
      for(IMavenProjectFacade facade : facades) {
        allProfiles.put(facade, profileManager.getProfileDatas(facade, monitor));
      }
      return allProfiles;
    }

    public List<ProfileSelection> getSharedProfiles() {
      return sharedProfiles;
    }

    public Map<IMavenProjectFacade, List<ProfileData>> getAllProfiles() {
      return allProfiles;
    }
  }

  class UpdateProfilesJob extends WorkspaceJob {

    private Map<IMavenProjectFacade, List<ProfileData>> allProfiles;

    private List<ProfileSelection> sharedProfiles;

    private IProfileManager profileManager;

    private SelectProfilesDialog dialog;

    private UpdateProfilesJob(Map<IMavenProjectFacade, List<ProfileData>> allProfiles,
        List<ProfileSelection> sharedProfiles, IProfileManager profileManager, SelectProfilesDialog dialog) {
      super(Messages.ProfileManager_Updating_maven_profiles);
      this.allProfiles = allProfiles;
      this.sharedProfiles = sharedProfiles;
      this.profileManager = profileManager;
      this.dialog = dialog;
    }

    public IStatus runInWorkspace(IProgressMonitor monitor) {
      try {
        SubMonitor progress = SubMonitor.convert(monitor, Messages.ProfileManager_Updating_maven_profiles, 100);
        SubMonitor subProgress = SubMonitor.convert(progress.newChild(5), allProfiles.size() * 100);
        for(Map.Entry<IMavenProjectFacade, List<ProfileData>> entry : allProfiles.entrySet()) {
          if(progress.isCanceled()) {
            throw new OperationCanceledException();
          }
          IMavenProjectFacade facade = entry.getKey();
          List<String> activeProfiles = getActiveProfiles(sharedProfiles, entry.getValue());

          profileManager.updateActiveProfiles(facade, activeProfiles, dialog.isOffline(), dialog.isForceUpdate(),
              subProgress.newChild(100));
        }
      } catch(CoreException ex) {
        log.error("Unable to update Maven profiles", ex);
        return ex.getStatus();
      }
      return Status.OK_STATUS;
    }

    private List<String> getActiveProfiles(List<ProfileSelection> sharedProfiles, List<ProfileData> availableProfiles) {
      List<String> ids = new ArrayList<String>();

      for(ProfileData st : availableProfiles) {
        ProfileSelection selection = findSelectedProfile(st.getId(), sharedProfiles);
        String id = null;
        boolean isDisabled = false;
        if(selection == null) {
          // was not displayed. Use existing value.
          if(st.isUserSelected()) {
            id = st.getId();
            isDisabled = st.getActivationState().equals(ProfileState.Disabled);
          }
        } else {
          if(null == selection.getSelected()) {
            // Value was displayed but its state is unknown, use
            // previous state
            if(st.isUserSelected()) {
              id = st.getId();
              isDisabled = st.getActivationState().equals(ProfileState.Disabled);
            }
          } else {
            // Value was displayed and is consistent
            if(Boolean.TRUE.equals(selection.getSelected())) {
              id = selection.getId();
              isDisabled = selection.getActivationState().equals(ProfileState.Disabled);
            }
          }
        }

        if(id != null) {
          if(isDisabled) {
            id = "!" + id; //$NON-NLS-1$
          }
          ids.add(id);
        }
      }
      return ids;
    }

    private ProfileSelection findSelectedProfile(String id, List<ProfileSelection> sharedProfiles) {
      for(ProfileSelection sel : sharedProfiles) {
        if(id.equals(sel.getId())) {
          return sel;
        }
      }
      return null;
    }
  }
}

Back to the top