forked from kameshsampath/m2e.wtp
/
WebProjectConfiguratorDelegate.java
500 lines (421 loc) · 22.1 KB
/
WebProjectConfiguratorDelegate.java
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/*******************************************************************************
* Copyright (c) 2008, 2013 Sonatype, 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:
* Darryl L. Miles <darryl.miles@darrylmiles.org> - bug fixes
*
*******************************************************************************/
package org.eclipse.m2e.wtp;
import static org.eclipse.m2e.wtp.WTPProjectsUtil.removeConflictingFacets;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.StringUtils;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jst.j2ee.classpathdep.IClasspathDependencyConstants;
import org.eclipse.jst.j2ee.internal.project.J2EEProjectUtilities;
import org.eclipse.jst.j2ee.project.facet.IJ2EEModuleFacetInstallDataModelProperties;
import org.eclipse.jst.j2ee.web.project.facet.IWebFacetInstallDataModelProperties;
import org.eclipse.jst.j2ee.web.project.facet.WebFacetInstallDataModelProvider;
import org.eclipse.jst.j2ee.web.project.facet.WebFacetUtils;
import org.eclipse.m2e.core.MavenPlugin;
import org.eclipse.m2e.core.embedder.ArtifactKey;
import org.eclipse.m2e.core.internal.IMavenConstants;
import org.eclipse.m2e.core.project.IMavenProjectFacade;
import org.eclipse.m2e.jdt.IClasspathDescriptor;
import org.eclipse.m2e.jdt.IClasspathEntryDescriptor;
import org.eclipse.m2e.wtp.internal.ExtensionReader;
import org.eclipse.m2e.wtp.internal.filtering.WebResourceFilteringConfiguration;
import org.eclipse.m2e.wtp.internal.utilities.DebugUtilities;
import org.eclipse.m2e.wtp.namemapping.FileNameMapping;
import org.eclipse.wst.common.componentcore.ComponentCore;
import org.eclipse.wst.common.componentcore.ModuleCoreNature;
import org.eclipse.wst.common.componentcore.resources.IVirtualComponent;
import org.eclipse.wst.common.componentcore.resources.IVirtualReference;
import org.eclipse.wst.common.componentcore.resources.IVirtualResource;
import org.eclipse.wst.common.frameworks.datamodel.DataModelFactory;
import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
import org.eclipse.wst.common.project.facet.core.IFacetedProject;
import org.eclipse.wst.common.project.facet.core.IFacetedProject.Action;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
import org.eclipse.wst.common.project.facet.core.ProjectFacetsManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Configures web projects based on their maven-war-plugin configuration.
*
* @author Igor Fedorenko
* @author Fred Bricon
*/
@SuppressWarnings("restriction")
class WebProjectConfiguratorDelegate extends AbstractProjectConfiguratorDelegate {
private static final Logger LOG = LoggerFactory.getLogger(WebProjectConfiguratorDelegate.class);
/**
* See http://wiki.eclipse.org/ClasspathEntriesPublishExportSupport
*/
static final IClasspathAttribute DEPENDENCY_ATTRIBUTE = JavaCore.newClasspathAttribute(
IClasspathDependencyConstants.CLASSPATH_COMPONENT_DEPENDENCY, "/WEB-INF/lib");
/**
* Name of maven property that overrides WTP context root.
*/
private static final String M2ECLIPSE_WTP_CONTEXT_ROOT = "m2eclipse.wtp.contextRoot";
protected void configure(IProject project, MavenProject mavenProject, IProgressMonitor monitor)
throws CoreException {
IFacetedProject facetedProject = ProjectFacetsManager.create(project, true, monitor);
IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry().create(project.getFile(IMavenConstants.POM_FILE_NAME), true, monitor);
// make sure to update the main deployment folder
WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project);
String warSourceDirectory = config.getWarSourceDirectory();
IFolder contentFolder = project.getFolder(warSourceDirectory);
Set<Action> actions = new LinkedHashSet<Action>();
installJavaFacet(actions, project, facetedProject);
IVirtualComponent component = ComponentCore.createComponent(project, true);
//MNGECLIPSE-2279 get the context root from the final name of the project, or artifactId by default.
String contextRoot = getContextRoot(mavenProject, config.getWarName());
IProjectFacetVersion webFv = config.getWebFacetVersion(project);
IDataModel webModelCfg = getWebModelConfig(warSourceDirectory, contextRoot);
if(!facetedProject.hasProjectFacet(WebFacetUtils.WEB_FACET)) {
removeConflictingFacets(facetedProject, webFv, actions);
actions.add(new IFacetedProject.Action(IFacetedProject.Action.Type.INSTALL, webFv, webModelCfg));
} else {
IProjectFacetVersion projectFacetVersion = facetedProject.getProjectFacetVersion(WebFacetUtils.WEB_FACET);
if(webFv.getVersionString() != null && !webFv.getVersionString().equals(projectFacetVersion.getVersionString())){
actions.add(new IFacetedProject.Action(IFacetedProject.Action.Type.VERSION_CHANGE, webFv, webModelCfg));
}
}
String customWebXml = config.getCustomWebXml(project);
if(!actions.isEmpty()) {
ResourceCleaner fileCleaner = new ResourceCleaner(project, contentFolder);
try {
addFoldersToClean(fileCleaner, facade);
fileCleaner.addFiles(contentFolder.getFile("META-INF/MANIFEST.MF").getProjectRelativePath());
fileCleaner.addFolder(contentFolder.getFolder("WEB-INF/lib"));
if (customWebXml != null) {
fileCleaner.addFiles(contentFolder.getFile("WEB-INF/web.xml").getProjectRelativePath());
}
facetedProject.modify(actions, monitor);
} finally {
//Remove any unwanted MANIFEST.MF the Facet installation has created
fileCleaner.cleanUp();
}
}
//MECLIPSEWTP-41 Fix the missing moduleCoreNature
fixMissingModuleCoreNature(project, monitor);
// MNGECLIPSE-632 remove test sources/resources from WEB-INF/classes
removeTestFolderLinks(project, mavenProject, monitor, "/WEB-INF/classes");
addContainerAttribute(project, DEPENDENCY_ATTRIBUTE, monitor);
//MNGECLIPSE-2279 change the context root if needed
if (!contextRoot.equals(J2EEProjectUtilities.getServerContextRoot(project))) {
J2EEProjectUtilities.setServerContextRoot(project, contextRoot);
}
if (customWebXml != null) {
linkFileFirst(project, customWebXml, "/WEB-INF/web.xml", monitor);
}
component = ComponentCore.createComponent(project, true);
if(component != null) {
IPath warPath = new Path("/").append(contentFolder.getProjectRelativePath());
List<IPath> sourcePaths = new ArrayList<IPath>();
sourcePaths.add(warPath);
if (!WTPProjectsUtil.hasLink(project, ROOT_PATH, warPath, monitor)) {
component.getRootFolder().createLink(warPath, IVirtualResource.NONE, monitor);
}
//MECLIPSEWTP-22 support web filtered resources. Filtered resources directory must be declared BEFORE
//the regular web source directory. First resources discovered take precedence on deployment
IPath filteredFolder = new Path("/").append(WebResourceFilteringConfiguration.getTargetFolder(mavenProject, project));
boolean useBuildDir = MavenWtpPlugin.getDefault().getMavenWtpPreferencesManager().getPreferences(project).isWebMavenArchiverUsesBuildDirectory();
boolean useWebresourcefiltering = config.getWebResources() != null
&& config.getWebResources().length > 0
|| config.isFilteringDeploymentDescriptorsEnabled();
if (useBuildDir || useWebresourcefiltering) {
if (!useBuildDir && useWebresourcefiltering) {
mavenMarkerManager.addMarker(project, MavenWtpConstants.WTP_MARKER_CONFIGURATION_ERROR_ID,
Messages.markers_mavenarchiver_output_settings_ignored_warning, -1, IMarker.SEVERITY_WARNING);
}
sourcePaths.add(filteredFolder);
WTPProjectsUtil.insertLinkBefore(project, filteredFolder, warPath, new Path("/"), monitor);
} else {
component.getRootFolder().removeLink(filteredFolder,IVirtualResource.NONE, monitor);
}
WTPProjectsUtil.deleteLinks(project, ROOT_PATH, sourcePaths, monitor);
WTPProjectsUtil.setDefaultDeploymentDescriptorFolder(component.getRootFolder(), warPath, monitor);
addComponentExclusionPatterns(component, config);
}
WTPProjectsUtil.removeWTPClasspathContainer(project);
}
private IDataModel getWebModelConfig(String warSourceDirectory, String contextRoot) {
IDataModel webModelCfg = DataModelFactory.createDataModel(new WebFacetInstallDataModelProvider());
webModelCfg.setProperty(IJ2EEModuleFacetInstallDataModelProperties.CONFIG_FOLDER, warSourceDirectory);
webModelCfg.setProperty(IWebFacetInstallDataModelProperties.CONTEXT_ROOT, contextRoot);
webModelCfg.setProperty(IJ2EEModuleFacetInstallDataModelProperties.GENERATE_DD, false);
webModelCfg.setBooleanProperty(IWebFacetInstallDataModelProperties.ADD_TO_EAR, false);
return webModelCfg;
}
public void setModuleDependencies(IProject project, MavenProject mavenProject, IProgressMonitor monitor)
throws CoreException {
IVirtualComponent component = ComponentCore.createComponent(project);
//if the attempt to create dependencies happens before the project is actually created, abort.
//this will be created again when the project exists.
if(component == null){
return;
}
//MECLIPSEWTP-41 Fix the missing moduleCoreNature
fixMissingModuleCoreNature(project, monitor);
DebugUtilities.debug("==============Processing "+project.getName()+" dependencies ===============");
WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project);
IPackagingConfiguration opts = new PackagingConfiguration(config.getPackagingIncludes(), config.getPackagingExcludes());
FileNameMapping fileNameMapping = config.getFileNameMapping();
List<AbstractDependencyConfigurator> depConfigurators = ExtensionReader.readDependencyConfiguratorExtensions(projectManager,
MavenPlugin.getMavenRuntimeManager(), mavenMarkerManager);
Set<IVirtualReference> references = new LinkedHashSet<IVirtualReference>();
List<IMavenProjectFacade> exportedDependencies = getWorkspaceDependencies(project, mavenProject);
Set<String> dups = new HashSet<String>();
Set<String> names = new HashSet<String>();
Map<IVirtualReference, Artifact> referenceMapping = new HashMap<IVirtualReference, Artifact>(exportedDependencies.size());
for(IMavenProjectFacade dependency : exportedDependencies) {
String depPackaging = dependency.getPackaging();
if ("pom".equals(depPackaging) //MNGECLIPSE-744 pom dependencies shouldn't be deployed
|| "war".equals(depPackaging) //Overlays are dealt with the overlay configurator
|| "zip".equals(depPackaging)) {
continue;
}
try {
preConfigureDependencyProject(dependency, monitor);
if (!ModuleCoreNature.isFlexibleProject(dependency.getProject())) {
//Projects unsupported by WTP (ex. adobe flex projects) should not be added as references
continue;
}
MavenProject depMavenProject = dependency.getMavenProject(monitor);
IVirtualComponent depComponent = ComponentCore.createComponent(dependency.getProject());
ArtifactKey artifactKey = ArtifactHelper.toArtifactKey(depMavenProject.getArtifact());
//Get artifact using the proper classifier
Artifact artifact = ArtifactHelper.getArtifact(mavenProject.getArtifacts(), artifactKey);
if (artifact == null) {
//could not map key to artifact
artifact = depMavenProject.getArtifact();
}
ArtifactHelper.fixArtifactHandler(artifact.getArtifactHandler());
String deployedName = fileNameMapping.mapFileName(artifact);
boolean isDeployed = !artifact.isOptional() && opts.isPackaged("WEB-INF/lib/"+deployedName);
//an artifact in mavenProject.getArtifacts() doesn't have the "optional" value as depMavenProject.getArtifact();
if (isDeployed) {
IVirtualReference reference = ComponentCore.createReference(component, depComponent);
IPath path = new Path("/WEB-INF/lib");
reference.setArchiveName(deployedName);
reference.setRuntimePath(path);
references.add(reference);
referenceMapping.put(reference, artifact);
if (!names.add(deployedName)) {
dups.add(deployedName);
}
}
} catch(RuntimeException ex) {
//Should probably be NPEs at this point
String dump = DebugUtilities.dumpProjectState("An error occured while configuring a dependency of "+project.getName()+DebugUtilities.SEP, dependency.getProject());
LOG.error(dump);
throw ex;
}
}
for (IVirtualReference reference : references) {
if (dups.contains(reference.getArchiveName())) {
Artifact a = referenceMapping.get(reference);
String newName = a.getGroupId() + "-" + reference.getArchiveName();
reference.setArchiveName(newName);
}
}
IVirtualReference[] oldRefs = WTPProjectsUtil.extractHardReferences(component, false);
IVirtualReference[] newRefs = references.toArray(new IVirtualReference[references.size()]);
if (WTPProjectsUtil.hasChanged(oldRefs, newRefs)){
//Only write in the .component file if necessary
IVirtualReference[] overlayRefs = WTPProjectsUtil.extractHardReferences(component, true);
IVirtualReference[] allRefs = new IVirtualReference[overlayRefs.length + newRefs.length];
System.arraycopy(newRefs, 0, allRefs, 0, newRefs.length);
System.arraycopy(overlayRefs, 0, allRefs, newRefs.length, overlayRefs.length);
component.setReferences(allRefs);
}
//TODO why a 2nd loop???
for(IMavenProjectFacade dependency : exportedDependencies) {
MavenProject depMavenProject = dependency.getMavenProject(monitor);
Iterator<AbstractDependencyConfigurator> configurators = depConfigurators.iterator();
while (configurators.hasNext()) {
try {
configurators.next().configureDependency(mavenProject, project, depMavenProject, dependency.getProject(), monitor);
} catch(MarkedException ex) {
//XXX handle this
}
}
}
}
/**
* Get the context root from a maven web project
* @param mavenProject
* @param warName
* @return the final name of the project if it exists, or the project's artifactId.
*/
protected String getContextRoot(MavenProject mavenProject, String warName) {
String contextRoot;
//MECLIPSEWTP-43 : Override with maven property
String property = mavenProject.getProperties().getProperty(M2ECLIPSE_WTP_CONTEXT_ROOT);
if (StringUtils.isBlank(property)) {
String finalName = warName;
if (StringUtils.isBlank(finalName)
|| finalName.equals(mavenProject.getArtifactId() + "-" + mavenProject.getVersion())) {
contextRoot = mavenProject.getArtifactId();
} else {
contextRoot = finalName;
}
} else {
contextRoot = property;
}
return contextRoot.trim().replace(" ", "_");
}
public void configureClasspath(IProject project, MavenProject mavenProject, IClasspathDescriptor classpath,
IProgressMonitor monitor) throws CoreException {
//Improve skinny war support by generating the manifest classpath
//similar to mvn eclipse:eclipse
//http://maven.apache.org/plugins/maven-war-plugin/examples/skinny-wars.html
WarPluginConfiguration config = new WarPluginConfiguration(mavenProject, project);
IPackagingConfiguration opts = new PackagingConfiguration(config.getPackagingIncludes(), config.getPackagingExcludes());
/*
* Need to take care of three separate cases
*
* 1. remove any project dependencies (they are represented as J2EE module dependencies)
* 2. add non-dependency attribute for entries originated by artifacts with
* runtime, system, test scopes or optional dependencies (not sure about the last one)
* 3. make sure all dependency JAR files have unique file names, i.e. artifactId/version collisions
*/
Set<String> dups = new LinkedHashSet<String>();
Set<String> names = new HashSet<String>();
IVirtualComponent component = ComponentCore.createComponent(project);
if (component != null) {
for (IVirtualReference vr : component.getReferences()) {
if (!vr.getReferencedComponent().isBinary()) {
names.add(vr.getArchiveName());
}
}
}
FileNameMapping fileNameMapping = config.getFileNameMapping();
IPath m2eWtpFolderPath = ProjectUtils.getM2eclipseWtpFolder(mavenProject, project);
m2eWtpFolderPath = project.getFolder(m2eWtpFolderPath).getLocation();
IPath targetPath = m2eWtpFolderPath.append(MavenWtpConstants.JAR_RENAME_FOLDER);
String targetDir = targetPath.toOSString();
// first pass removes projects, adds non-dependency attribute and collects colliding filenames
Iterator<IClasspathEntryDescriptor> iter = classpath.getEntryDescriptors().iterator();
while (iter.hasNext()) {
IClasspathEntryDescriptor descriptor = iter.next();
String scope = descriptor.getScope();
Artifact artifact = ArtifactHelper.getArtifact(mavenProject.getArtifacts(), descriptor.getArtifactKey());
ArtifactHelper.fixArtifactHandler(artifact.getArtifactHandler());
String deployedName = fileNameMapping.mapFileName(artifact);
boolean isDeployed = (Artifact.SCOPE_COMPILE.equals(scope) || Artifact.SCOPE_RUNTIME.equals(scope))
&& !descriptor.isOptionalDependency()
&& opts.isPackaged("WEB-INF/lib/"+deployedName)
&& !isWorkspaceProject(artifact);
// add non-dependency attribute if this classpathentry is not meant to be deployed
// or if it's a workspace project (projects already have a reference created in configure())
if(!isDeployed) {
descriptor.setClasspathAttribute(NONDEPENDENCY_ATTRIBUTE.getName(), NONDEPENDENCY_ATTRIBUTE.getValue());
//Bug #382078 : no need to rename non-deployed artifacts.
continue;
}
//If custom fileName is used, check if the underlying file already exists
// if it doesn't, copy and rename the artifact under the build dir
String fileName = descriptor.getPath().lastSegment();
if (!deployedName.equals(fileName)) {
// The renameArtifact() method already checks existence and timestamp for us,
// it is important the timestamp is checked each time as it is possible to be
// working with a 0.0.1-SNAPSHOT jar from a repository that you keep
// installing a new copy of while you develop/test it.
IPath newPath = renameArtifact(targetDir, descriptor.getPath(), deployedName );
if (newPath != null) {
descriptor.setPath(newPath);
}
}
if (!names.add(deployedName)) {
dups.add(deployedName);
}
}
// second pass disambiguates colliding entry file names
iter = classpath.getEntryDescriptors().iterator();
while (iter.hasNext()) {
IClasspathEntryDescriptor descriptor = iter.next();
if (descriptor.getClasspathAttributes().containsKey(NONDEPENDENCY_ATTRIBUTE.getName())) {
//No need to rename if not deployed
continue;
}
if (dups.contains(descriptor.getPath().lastSegment())) {
String newName = descriptor.getGroupId() + "-" + descriptor.getPath().lastSegment();
IPath newPath = renameArtifact(targetDir, descriptor.getPath(), newName );
if (newPath != null) {
descriptor.setPath(newPath);
}
}
}
// We do this at the end, this causes any JAR items we copied to be marked as
// hidden=true and derived=true.
ProjectUtils.hideM2eclipseWtpFolder(mavenProject, project);
}
// returns null on error, or when the copy was not performed due to being identical
private IPath renameArtifact(String targetDir, IPath source, String newName) {
File src = new File(source.toOSString());
File dstDir = new File(targetDir);
if (!dstDir.exists()) {
try {
if (src.isFile() && src.canRead()) {
if(!dstDir.mkdirs()) // do this once rather than for each JAR
throw new Exception("mkdirs(): " + dstDir);
}
} catch(Exception ex) {
LOG.error("Mkdirs failed", ex);
}
}
File dst = new File(targetDir, newName);
try {
if (src.isFile() && src.canRead()) {
if (isDifferent(src, dst)) { // uses lastModified
FileUtils.copyFile(src, dst);
dst.setLastModified(src.lastModified());
return Path.fromOSString(dst.getCanonicalPath());
}
}
} catch(IOException ex) {
LOG.error("File copy failed", ex);
}
return null;
}
private boolean isWorkspaceProject(Artifact artifact) {
IMavenProjectFacade facade = projectManager.getMavenProject(artifact.getGroupId(),
artifact.getArtifactId(),
artifact.getVersion());
return facade != null
&& facade.getFullPath(artifact.getFile()) != null;
}
private static boolean isDifferent(File src, File dst) {
if (!dst.exists()) {
return true;
}
return src.length() != dst.length()
|| src.lastModified() != dst.lastModified();
}
}