This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.

View | Details | Raw Unified | Return to bug 207172
Collapse All | Expand All

(-)maven/src/org/netbeans/modules/maven/M2AuxilaryConfigImpl.java (-3 / +11 lines)
Lines 47-52 Link Here
47
import java.io.IOException;
47
import java.io.IOException;
48
import java.io.OutputStream;
48
import java.io.OutputStream;
49
import java.io.StringReader;
49
import java.io.StringReader;
50
import java.lang.ref.WeakReference;
50
import java.util.Date;
51
import java.util.Date;
51
import java.util.logging.Level;
52
import java.util.logging.Level;
52
import java.util.logging.Logger;
53
import java.util.logging.Logger;
Lines 94-104 Link Here
94
    private Document cachedDoc;
95
    private Document cachedDoc;
95
    private final Object configIOLock = new Object();
96
    private final Object configIOLock = new Object();
96
    private final FileObject projectDirectory;
97
    private final FileObject projectDirectory;
97
    private final ProblemReporterImpl reporter;
98
    private ProblemReporterImpl reporter;
98
99
99
    public M2AuxilaryConfigImpl(FileObject dir, ProblemReporterImpl problemReporter) {
100
    /** intentionally left without reference to project instance
101
        when using this constructor can only get values, never put or remove */
102
    public M2AuxilaryConfigImpl(FileObject dir) {
100
        this.projectDirectory = dir;
103
        this.projectDirectory = dir;
101
        this.reporter = problemReporter;
104
    }
105
    
106
    public M2AuxilaryConfigImpl(FileObject dir, ProblemReporterImpl impl) {
107
        this(dir);
102
        savingTask = RP.create(new Runnable() {
108
        savingTask = RP.create(new Runnable() {
103
            public @Override void run() {
109
            public @Override void run() {
104
                try {
110
                try {
Lines 190-195 Link Here
190
                        cachedDoc = doc;
196
                        cachedDoc = doc;
191
                        return XMLUtil.findElement(doc.getDocumentElement(), elementName, namespace);
197
                        return XMLUtil.findElement(doc.getDocumentElement(), elementName, namespace);
192
                    } catch (SAXException ex) {
198
                    } catch (SAXException ex) {
199
                        if (reporter != null) {
193
                        if (!reporter.hasReportWithId(BROKEN_NBCONFIG)) {
200
                        if (!reporter.hasReportWithId(BROKEN_NBCONFIG)) {
194
                            ProblemReport rep = new ProblemReport(ProblemReport.SEVERITY_MEDIUM,
201
                            ProblemReport rep = new ProblemReport(ProblemReport.SEVERITY_MEDIUM,
195
                                    TXT_Problem_Broken_Config(),
202
                                    TXT_Problem_Broken_Config(),
Lines 198-203 Link Here
198
                            rep.setId(BROKEN_NBCONFIG);
205
                            rep.setId(BROKEN_NBCONFIG);
199
                            reporter.addReport(rep);
206
                            reporter.addReport(rep);
200
                        }
207
                        }
208
                        }
201
                        LOG.log(Level.INFO, ex.getMessage(), ex);
209
                        LOG.log(Level.INFO, ex.getMessage(), ex);
202
                        cachedDoc = null;
210
                        cachedDoc = null;
203
                    } catch (IOException ex) {
211
                    } catch (IOException ex) {
(-)maven/src/org/netbeans/modules/maven/NbMavenProjectImpl.java (-84 / +26 lines)
Lines 83-92 Link Here
83
import org.netbeans.modules.maven.api.execute.ActiveJ2SEPlatformProvider;
83
import org.netbeans.modules.maven.api.execute.ActiveJ2SEPlatformProvider;
84
import org.netbeans.modules.maven.api.problem.ProblemReport;
84
import org.netbeans.modules.maven.api.problem.ProblemReport;
85
import org.netbeans.modules.maven.configurations.M2ConfigProvider;
85
import org.netbeans.modules.maven.configurations.M2ConfigProvider;
86
import org.netbeans.modules.maven.configurations.M2Configuration;
86
import org.netbeans.modules.maven.configurations.ProjectProfileHandlerImpl;
87
import org.netbeans.modules.maven.configurations.ProjectProfileHandlerImpl;
87
import org.netbeans.modules.maven.embedder.EmbedderFactory;
88
import org.netbeans.modules.maven.embedder.EmbedderFactory;
88
import org.netbeans.modules.maven.embedder.MavenEmbedder;
89
import org.netbeans.modules.maven.embedder.MavenEmbedder;
89
import org.netbeans.modules.maven.execute.AbstractMavenExecutor;
90
import org.netbeans.modules.maven.execute.AbstractMavenExecutor;
91
import org.netbeans.modules.maven.modelcache.MavenProjectCache;
90
import org.netbeans.modules.maven.problems.ProblemReporterImpl;
92
import org.netbeans.modules.maven.problems.ProblemReporterImpl;
91
import org.netbeans.modules.maven.spi.queries.JavaLikeRootProvider;
93
import org.netbeans.modules.maven.spi.queries.JavaLikeRootProvider;
92
import org.netbeans.spi.java.project.support.LookupMergerSupport;
94
import org.netbeans.spi.java.project.support.LookupMergerSupport;
Lines 208-213 Link Here
208
     * @param properties
210
     * @param properties
209
     * @return
211
     * @return
210
     */
212
     */
213
    //TODO revisit usage, eventually should be only reuse MavenProjectCache
211
    public @NonNull MavenProject loadMavenProject(MavenEmbedder embedder, List<String> activeProfiles, Properties properties) {
214
    public @NonNull MavenProject loadMavenProject(MavenEmbedder embedder, List<String> activeProfiles, Properties properties) {
212
        try {
215
        try {
213
            MavenExecutionRequest req = embedder.createMavenExecutionRequest();
216
            MavenExecutionRequest req = embedder.createMavenExecutionRequest();
Lines 215-221 Link Here
215
            req.setPom(projectFile);
218
            req.setPom(projectFile);
216
            req.setNoSnapshotUpdates(true);
219
            req.setNoSnapshotUpdates(true);
217
            req.setUpdateSnapshots(false);
220
            req.setUpdateSnapshots(false);
218
            Properties props = createSystemPropsForProjectLoading();
221
            Properties props = MavenProjectCache.createSystemPropsForProjectLoading(null);
219
            if (properties != null) {
222
            if (properties != null) {
220
                props.putAll(properties);
223
                props.putAll(properties);
221
            }
224
            }
Lines 241-247 Link Here
241
            //#136184 NumberFormatException
244
            //#136184 NumberFormatException
242
            LOG.log(Level.INFO, "Runtime exception thrown while loading maven project at " + getProjectDirectory(), exc); //NOI18N
245
            LOG.log(Level.INFO, "Runtime exception thrown while loading maven project at " + getProjectDirectory(), exc); //NOI18N
243
        }
246
        }
244
        return getFallbackProject();
247
        return MavenProjectCache.getFallbackProject(this.getPOMFile());
245
    }
248
    }
246
249
247
    public List<String> getCurrentActiveProfiles() {
250
    public List<String> getCurrentActiveProfiles() {
Lines 249-283 Link Here
249
        toRet.addAll(configProvider.getActiveConfiguration().getActivatedProfiles());
252
        toRet.addAll(configProvider.getActiveConfiguration().getActivatedProfiles());
250
        return toRet;
253
        return toRet;
251
    }
254
    }
252
    private static final Properties statics = new Properties();
253
255
254
    private static Properties cloneStaticProps() {
255
        synchronized (statics) {
256
            if (statics.isEmpty()) { // not yet initialized
257
                // Now a misnomer, but available to activate profiles only during NB project parse:
258
                statics.setProperty("netbeans.execution", "true"); // NOI18N
259
                EmbedderFactory.fillEnvVars(statics);
260
                statics.putAll(AbstractMavenExecutor.excludeNetBeansProperties(System.getProperties()));
261
            }
262
            Properties toRet = new Properties();
263
            toRet.putAll(statics);
264
            return toRet;
265
        }
266
    }
267
256
268
    //#158700
269
    private Properties createSystemPropsForProjectLoading() {
270
        Properties props = cloneStaticProps();
271
        props.putAll(configProvider.getActiveConfiguration().getProperties());
272
        //TODO the properties for java.home and maybe others shall be relevant to the project setup not ide setup.
273
        // we got a chicken-egg situation here, the jdk used in project can be defined in the pom.xml file.
274
        return props;
275
    }
276
277
    //#172952 for property expression resolution we need this to include
257
    //#172952 for property expression resolution we need this to include
278
    // the properties of the platform to properly resolve stuff like com.sun.boot.class.path
258
    // the properties of the platform to properly resolve stuff like com.sun.boot.class.path
279
    public Map<? extends String,? extends String> createSystemPropsForPropertyExpressions() {
259
    public Map<? extends String,? extends String> createSystemPropsForPropertyExpressions() {
280
        Map<String,String> props = NbCollections.checkedMapByCopy(cloneStaticProps(), String.class, String.class, true);
260
        Map<String,String> props = NbCollections.checkedMapByCopy(MavenProjectCache.cloneStaticProps(), String.class, String.class, true);
281
        ActiveJ2SEPlatformProvider platformProvider = getLookup().lookup(ActiveJ2SEPlatformProvider.class);
261
        ActiveJ2SEPlatformProvider platformProvider = getLookup().lookup(ActiveJ2SEPlatformProvider.class);
282
        if (platformProvider != null) { // may be null inside PackagingProvider
262
        if (platformProvider != null) { // may be null inside PackagingProvider
283
            props.putAll(platformProvider.getJavaPlatform().getSystemProperties());
263
            props.putAll(platformProvider.getJavaPlatform().getSystemProperties());
Lines 293-299 Link Here
293
    public @NonNull synchronized MavenProject getOriginalMavenProject() {
273
    public @NonNull synchronized MavenProject getOriginalMavenProject() {
294
        MavenProject mp = project == null ? null : project.get();
274
        MavenProject mp = project == null ? null : project.get();
295
        if (mp == null) {
275
        if (mp == null) {
296
            mp = loadOriginalMavenProject();
276
            mp = loadOriginalMavenProject(false);
297
        }
277
        }
298
        project = new SoftReference<MavenProject>(mp);
278
        project = new SoftReference<MavenProject>(mp);
299
        return mp;
279
        return mp;
Lines 317-371 Link Here
317
            + "This is preventing the project model from loading properly. \n"
297
            + "This is preventing the project model from loading properly. \n"
318
            + "Please file a bug report with details about your project and the IDE's log file.\n\n"
298
            + "Please file a bug report with details about your project and the IDE's log file.\n\n"
319
    })
299
    })
320
    private @NonNull MavenProject loadOriginalMavenProject() {
300
    private @NonNull MavenProject loadOriginalMavenProject(boolean reload) {
321
        long startLoading = System.currentTimeMillis();
301
        MavenProject newproject;
322
        MavenProject newproject = null;
323
        try {
302
        try {
324
//                ProgressTransferListener.setAggregateHandle(hndl);
303
            newproject = MavenProjectCache.getMavenProject(this.folderFileObject, reload);
325
//                hndl.start();
304
            MavenExecutionResult res = MavenProjectCache.getExecutionResult(newproject);
326
           final  MavenExecutionRequest req = getEmbedder().createMavenExecutionRequest();
327
                
328
            //#172526 have the modellineage cache reset at the same time the project cache resets
329
            profileHandler.clearLineageCache();
330
            req.addActiveProfiles(getCurrentActiveProfiles());
331
            req.setPom(projectFile);
332
            req.setNoSnapshotUpdates(true);
333
            req.setUpdateSnapshots(false);
334
            //MEVENIDE-634 i'm wondering if this fixes the issue
335
            req.setInteractiveMode(false);
336
            // recursive == false is important to avoid checking all submodules for extensions
337
            // that will not be used in current pom anyway..
338
            // #135070
339
            req.setRecursive(false);
340
            req.setOffline(true);
341
            req.setUserProperties(createSystemPropsForProjectLoading());
342
             MavenExecutionResult res = getEmbedder().readProjectWithDependencies(req, true);
343
             newproject = res.getProject();
344
            if (res.hasExceptions()) {
305
            if (res.hasExceptions()) {
345
                problemReporter.reportExceptions(res);
306
                problemReporter.reportExceptions(res);
346
            } else {
307
            } else {
347
                problemReporter.doArtifactChecks(newproject);
308
                problemReporter.doArtifactChecks(newproject);
348
            }
309
            }
349
        } catch (RuntimeException exc) {
310
//        } catch (RuntimeException exc) {
350
            //guard against exceptions that are not processed by the embedder
311
//            //guard against exceptions that are not processed by the embedder
351
            //#136184 NumberFormatException
312
//            //#136184 NumberFormatException
352
            LOG.log(Level.INFO, "Runtime exception thrown while loading maven project at " + getProjectDirectory(), exc); //NOI18N
313
//            LOG.log(Level.INFO, "Runtime exception thrown while loading maven project at " + getProjectDirectory(), exc); //NOI18N
353
            StringWriter wr = new StringWriter();
314
//            StringWriter wr = new StringWriter();
354
            PrintWriter pw = new PrintWriter(wr);
315
//            PrintWriter pw = new PrintWriter(wr);
355
            exc.printStackTrace(pw);
316
//            exc.printStackTrace(pw);
356
            pw.flush();
317
//            pw.flush();
318
//
319
//            ProblemReport report = new ProblemReport(ProblemReport.SEVERITY_HIGH,
320
//                    TXT_RuntimeException(),
321
//                    TXT_RuntimeExceptionLong() + wr.toString(), null);
322
//            problemReporter.addReport(report);
357
323
358
            ProblemReport report = new ProblemReport(ProblemReport.SEVERITY_HIGH,
359
                    TXT_RuntimeException(),
360
                    TXT_RuntimeExceptionLong() + wr.toString(), null);
361
            problemReporter.addReport(report);
362
363
        } finally {
324
        } finally {
364
            if (newproject == null) {
365
                newproject = getFallbackProject();
366
            }
367
            long endLoading = System.currentTimeMillis();
368
            LOG.log(Level.FINE, "Loaded project in {0} msec at {1}", new Object[] {endLoading - startLoading, getProjectDirectory().getPath()});
369
            if (LOG.isLoggable(Level.FINE) && SwingUtilities.isEventDispatchThread()) {
325
            if (LOG.isLoggable(Level.FINE) && SwingUtilities.isEventDispatchThread()) {
370
                LOG.log(Level.FINE, "Project " + getProjectDirectory().getPath() + " loaded in AWT event dispatching thread!", new RuntimeException());
326
                LOG.log(Level.FINE, "Project " + getProjectDirectory().getPath() + " loaded in AWT event dispatching thread!", new RuntimeException());
371
            }
327
            }
Lines 374-395 Link Here
374
        return newproject;
330
        return newproject;
375
    }
331
    }
376
332
377
    @Messages({
378
        "LBL_Incomplete_Project_Name=<partially loaded Maven project>",
379
        "LBL_Incomplete_Project_Desc=Partially loaded Maven project; try building it."
380
    })
381
    private MavenProject getFallbackProject() throws AssertionError {
382
        MavenProject newproject = new MavenProject();
383
        newproject.setGroupId("error");
384
        newproject.setArtifactId("error");
385
        newproject.setVersion("0");
386
        newproject.setPackaging("pom");
387
        newproject.setName(LBL_Incomplete_Project_Name());
388
        newproject.setDescription(LBL_Incomplete_Project_Desc());
389
        newproject.setFile(projectFile);
390
        return newproject;
391
    }
392
333
334
393
    public void fireProjectReload() {
335
    public void fireProjectReload() {
394
        //#149566 prevent project firing squads to execute under project mutex.
336
        //#149566 prevent project firing squads to execute under project mutex.
395
        if (ProjectManager.mutex().isReadAccess()
337
        if (ProjectManager.mutex().isReadAccess()
Lines 405-411 Link Here
405
            return;
347
            return;
406
        }
348
        }
407
        problemReporter.clearReports(); //#167741 -this will trigger node refresh?
349
        problemReporter.clearReports(); //#167741 -this will trigger node refresh?
408
        MavenProject prj = loadOriginalMavenProject();
350
        MavenProject prj = loadOriginalMavenProject(true);
409
        synchronized (this) {
351
        synchronized (this) {
410
            project = new SoftReference<MavenProject>(prj);
352
            project = new SoftReference<MavenProject>(prj);
411
        }
353
        }
(-)maven/src/org/netbeans/modules/maven/configurations/ConfigurationPersistenceConstants.java (+59 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.maven.configurations;
43
44
/**
45
 *
46
 * @author mkleint
47
 */
48
public interface ConfigurationPersistenceConstants {
49
    String NAMESPACE = "http://www.netbeans.org/ns/maven-config-data/1"; 
50
    String ROOT = "config-data"; 
51
    String ENABLED = "enabled"; 
52
    String ACTIVATED = "activated";
53
    String CONFIGURATIONS = "configurations"; 
54
    String CONFIG = "configuration"; 
55
    String PROPERTY = "property"; 
56
    String PROPERTY_NAME_ATTR = "name"; 
57
    String CONFIG_PROFILES_ATTR = "profiles"; 
58
    String CONFIG_ID_ATTR = "id"; 
59
}
(-)maven/src/org/netbeans/modules/maven/configurations/M2ConfigProvider.java (-16 / +7 lines)
Lines 63-68 Link Here
63
import org.netbeans.spi.project.ActionProvider;
63
import org.netbeans.spi.project.ActionProvider;
64
import org.netbeans.spi.project.AuxiliaryConfiguration;
64
import org.netbeans.spi.project.AuxiliaryConfiguration;
65
import org.netbeans.spi.project.ProjectConfigurationProvider;
65
import org.netbeans.spi.project.ProjectConfigurationProvider;
66
import org.openide.filesystems.FileObject;
66
import org.openide.util.Exceptions;
67
import org.openide.util.Exceptions;
67
import org.openide.util.RequestProcessor;
68
import org.openide.util.RequestProcessor;
68
import org.openide.xml.XMLUtil;
69
import org.openide.xml.XMLUtil;
Lines 74-80 Link Here
74
 * in the critical loop (getOriginalMavenproject
75
 * in the critical loop (getOriginalMavenproject
75
 * @author mkleint
76
 * @author mkleint
76
 */
77
 */
77
public class M2ConfigProvider implements ProjectConfigurationProvider<M2Configuration> {
78
public class M2ConfigProvider implements ProjectConfigurationProvider<M2Configuration>, ConfigurationPersistenceConstants {
78
79
79
    private PropertyChangeSupport support = new PropertyChangeSupport(this);
80
    private PropertyChangeSupport support = new PropertyChangeSupport(this);
80
    private NbMavenProjectImpl project;
81
    private NbMavenProjectImpl project;
Lines 89-104 Link Here
89
    private ProjectProfileHandler profileHandler;
90
    private ProjectProfileHandler profileHandler;
90
    private PropertyChangeListener propertyChange;
91
    private PropertyChangeListener propertyChange;
91
92
92
    static String NAMESPACE = "http://www.netbeans.org/ns/maven-config-data/1"; //NOI18N
93
    static String ROOT = "config-data"; //NOI18N
94
    static String ENABLED = "enabled"; //NOI18N
95
    static String ACTIVATED = "activated"; //NOI18N
96
    static String CONFIGURATIONS = "configurations"; //NOI18N
97
    static String CONFIG = "configuration"; //NOI18N
98
    static String PROPERTY = "property"; //NOI18N
99
    static String PROPERTY_NAME_ATTR = "name"; //NOI18N
100
    static String CONFIG_PROFILES_ATTR = "profiles"; //NOI18N
101
    static String CONFIG_ID_ATTR = "id"; //NOI18N
102
93
103
    private static final RequestProcessor RP = new RequestProcessor(M2ConfigProvider.class.getName(),10);
94
    private static final RequestProcessor RP = new RequestProcessor(M2ConfigProvider.class.getName(),10);
104
    
95
    
Lines 153-159 Link Here
153
            Runnable dothis = new Runnable() {
144
            Runnable dothis = new Runnable() {
154
                    public @Override void run() {
145
                    public @Override void run() {
155
                        M2Configuration _active;
146
                        M2Configuration _active;
156
                        synchronized (this) {
147
                        synchronized (M2ConfigProvider.this) {
157
                            _active = active;
148
                            _active = active;
158
                        }
149
                        }
159
                        try {
150
                        try {
Lines 177-187 Link Here
177
        }
168
        }
178
        if (shared == null) {
169
        if (shared == null) {
179
            //read from auxconf
170
            //read from auxconf
180
            shared = readConfiguration(true);
171
            shared = readConfiguration(aux, project.getProjectDirectory(), true);
181
        }
172
        }
182
        if (nonshared == null) {
173
        if (nonshared == null) {
183
            //read from auxconf
174
            //read from auxconf
184
            nonshared = readConfiguration(false);
175
            nonshared = readConfiguration(aux, project.getProjectDirectory(), false);
185
        }
176
        }
186
        Collection<M2Configuration> toRet = new TreeSet<M2Configuration>();
177
        Collection<M2Configuration> toRet = new TreeSet<M2Configuration>();
187
        toRet.add(DEFAULT);
178
        toRet.add(DEFAULT);
Lines 356-362 Link Here
356
        support.firePropertyChange(ProjectConfigurationProvider.PROP_CONFIGURATIONS, null, null);
347
        support.firePropertyChange(ProjectConfigurationProvider.PROP_CONFIGURATIONS, null, null);
357
    }
348
    }
358
    
349
    
359
    private SortedSet<M2Configuration> readConfiguration(boolean shared) {
350
    public static SortedSet<M2Configuration> readConfiguration(AuxiliaryConfiguration aux, FileObject projectDirectory, boolean shared) {
360
        Element el = aux.getConfigurationFragment(ROOT, NAMESPACE, shared);
351
        Element el = aux.getConfigurationFragment(ROOT, NAMESPACE, shared);
361
        if (el != null) {
352
        if (el != null) {
362
            NodeList list = el.getElementsByTagNameNS(NAMESPACE, CONFIG);
353
            NodeList list = el.getElementsByTagNameNS(NAMESPACE, CONFIG);
Lines 366-372 Link Here
366
                for (int i = 0; i < len; i++) {
357
                for (int i = 0; i < len; i++) {
367
                    Element enEl = (Element)list.item(i);
358
                    Element enEl = (Element)list.item(i);
368
                    
359
                    
369
                    M2Configuration c = new M2Configuration(enEl.getAttribute(CONFIG_ID_ATTR), project.getProjectDirectory());
360
                    M2Configuration c = new M2Configuration(enEl.getAttribute(CONFIG_ID_ATTR), projectDirectory);
370
                    String profs = enEl.getAttribute(CONFIG_PROFILES_ATTR);
361
                    String profs = enEl.getAttribute(CONFIG_PROFILES_ATTR);
371
                    if (profs != null) {
362
                    if (profs != null) {
372
                        String[] s = profs.split(" ");
363
                        String[] s = profs.split(" ");
(-)maven/src/org/netbeans/modules/maven/configurations/M2Configuration.java (-1 / +1 lines)
Lines 70-76 Link Here
70
70
71
    public static final String DEFAULT = "%%DEFAULT%%"; //NOI18N
71
    public static final String DEFAULT = "%%DEFAULT%%"; //NOI18N
72
    
72
    
73
    static M2Configuration createDefault(FileObject projectDirectory) {
73
    public static M2Configuration createDefault(FileObject projectDirectory) {
74
        return new M2Configuration(DEFAULT, projectDirectory);
74
        return new M2Configuration(DEFAULT, projectDirectory);
75
    }
75
    }
76
    
76
    
(-)maven/src/org/netbeans/modules/maven/configurations/ProjectProfileHandlerImpl.java (-30 lines)
Lines 77-83 Link Here
77
    private final List<String> sharedProfiles = new ArrayList<String>();
77
    private final List<String> sharedProfiles = new ArrayList<String>();
78
    private final AuxiliaryConfiguration ac;
78
    private final AuxiliaryConfiguration ac;
79
    private final NbMavenProjectImpl nmp;
79
    private final NbMavenProjectImpl nmp;
80
    private List<Model> lineage;
81
80
82
    public ProjectProfileHandlerImpl(NbMavenProjectImpl nmp, AuxiliaryConfiguration ac) {
81
    public ProjectProfileHandlerImpl(NbMavenProjectImpl nmp, AuxiliaryConfiguration ac) {
83
        this.nmp = nmp;
82
        this.nmp = nmp;
Lines 86-113 Link Here
86
        sharedProfiles.addAll(retrieveActiveProfiles(ac, true));
85
        sharedProfiles.addAll(retrieveActiveProfiles(ac, true));
87
    }
86
    }
88
87
89
    /**
90
     * reset caching of the lineage, invoked from MavenProject reloads
91
     */
92
    public synchronized void clearLineageCache() {
93
        lineage = null;
94
    }
95
96
    /**
97
     * cache the lineage for repeated use
98
     */
99
    private synchronized List<Model> getLineage() {
100
        if (lineage == null) {
101
            try {
102
                lineage = nmp.getEmbedder().createModelLineage(nmp.getPOMFile());
103
            } catch (ModelBuildingException ex) {
104
                Logger.getLogger(ProjectProfileHandlerImpl.class.getName()).log(Level.FINE, "Error reading model lineage", ex);//NOI18N
105
                lineage = Collections.emptyList();
106
            }
107
        }
108
        return lineage;
109
    }
110
111
    public @Override List<String> getAllProfiles() {
88
    public @Override List<String> getAllProfiles() {
112
        Set<String> profileIds = new HashSet<String>();
89
        Set<String> profileIds = new HashSet<String>();
113
        //pom profiles come first
90
        //pom profiles come first
Lines 197-213 Link Here
197
    }
174
    }
198
175
199
    private void extractProfiles(Set<String> profileIds) {
176
    private void extractProfiles(Set<String> profileIds) {
200
        /* Cannot use this as it would trigger a stack overflow when loading the project:
201
        for (Profile profile : nmp.getOriginalMavenProject().getModel().getProfiles()) {
177
        for (Profile profile : nmp.getOriginalMavenProject().getModel().getProfiles()) {
202
            profileIds.add(profile.getId());
178
            profileIds.add(profile.getId());
203
        }
179
        }
204
         */
205
        for (Model model : getLineage()) {
206
            for (Profile profile : model.getProfiles()) {
207
                profileIds.add(profile.getId());
208
            }
180
            }
209
        }
210
    }
211
181
212
    private List<String> retrieveActiveProfiles(AuxiliaryConfiguration ac, boolean shared) {
182
    private List<String> retrieveActiveProfiles(AuxiliaryConfiguration ac, boolean shared) {
213
183
(-)maven/src/org/netbeans/modules/maven/modelcache/ActiveConfigurationProvider.java (+98 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.maven.modelcache;
43
44
import java.util.Collections;
45
import java.util.SortedSet;
46
import org.netbeans.modules.maven.configurations.ConfigurationPersistenceConstants;
47
import org.netbeans.modules.maven.configurations.M2ConfigProvider;
48
import org.netbeans.modules.maven.configurations.M2Configuration;
49
import org.netbeans.spi.project.AuxiliaryConfiguration;
50
import org.openide.filesystems.FileObject;
51
import org.w3c.dom.Element;
52
import org.w3c.dom.NodeList;
53
54
/**
55
 *
56
 * @author mkleint
57
 */
58
public class ActiveConfigurationProvider implements ConfigurationPersistenceConstants {
59
    private final AuxiliaryConfiguration aux;
60
    private final FileObject projectDirectory;
61
62
    public ActiveConfigurationProvider(FileObject projectDirectory, AuxiliaryConfiguration aux) {
63
        this.aux = aux;
64
        this.projectDirectory = projectDirectory;
65
    }
66
    
67
    public M2Configuration getActiveConfiguration() {
68
        String active = null;
69
        Element el = aux.getConfigurationFragment(ROOT, NAMESPACE, false);
70
        if (el != null) {
71
            NodeList list = el.getElementsByTagNameNS(NAMESPACE, ACTIVATED);
72
            if (list.getLength() > 0) {
73
                Element enEl = (Element)list.item(0);
74
                active = enEl.getTextContent();
75
            }
76
        }
77
        if (active == null) {
78
            return M2Configuration.createDefault(projectDirectory);
79
        } else {
80
            SortedSet<M2Configuration> configs = M2ConfigProvider.readConfiguration(aux, projectDirectory, true);
81
            for (M2Configuration c : configs) {
82
                if (c.getId().equals(active)) {
83
                    return c;
84
                }
85
            }
86
            configs = M2ConfigProvider.readConfiguration(aux, projectDirectory, false);
87
            for (M2Configuration c : configs) {
88
                if (c.getId().equals(active)) {
89
                    return c;
90
                }
91
            }
92
            // attempt to find the stored configuration, if not found it's a profile
93
            M2Configuration toRet = new M2Configuration(active, projectDirectory);
94
            toRet.setActivatedProfiles(Collections.singletonList(active));
95
            return toRet;
96
        }
97
    }
98
}
(-)maven/src/org/netbeans/modules/maven/modelcache/MavenProjectCache.java (+222 lines)
Line 0 Link Here
1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2012 Oracle and/or its affiliates. All rights reserved.
5
 *
6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
7
 * Other names may be trademarks of their respective owners.
8
 *
9
 * The contents of this file are subject to the terms of either the GNU
10
 * General Public License Version 2 only ("GPL") or the Common
11
 * Development and Distribution License("CDDL") (collectively, the
12
 * "License"). You may not use this file except in compliance with the
13
 * License. You can obtain a copy of the License at
14
 * http://www.netbeans.org/cddl-gplv2.html
15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
16
 * specific language governing permissions and limitations under the
17
 * License.  When distributing the software, include this License Header
18
 * Notice in each file and include the License file at
19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
20
 * particular file as subject to the "Classpath" exception as provided
21
 * by Oracle in the GPL Version 2 section of the License file that
22
 * accompanied this code. If applicable, add the following below the
23
 * License Header, with the fields enclosed by brackets [] replaced by
24
 * your own identifying information:
25
 * "Portions Copyrighted [year] [name of copyright owner]"
26
 *
27
 * If you wish your version of this file to be governed by only the CDDL
28
 * or only the GPL Version 2, indicate your decision by adding
29
 * "[Contributor] elects to include this software in this distribution
30
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
31
 * single choice of license, a recipient has the option to distribute
32
 * your version of this file under either the CDDL, the GPL Version 2 or
33
 * to extend the choice of license to its licensees as provided above.
34
 * However, if you add GPL Version 2 code and therefore, elected the GPL
35
 * Version 2 license, then the option applies only if the new code is
36
 * made subject to such option by the copyright holder.
37
 *
38
 * Contributor(s):
39
 *
40
 * Portions Copyrighted 2012 Sun Microsystems, Inc.
41
 */
42
package org.netbeans.modules.maven.modelcache;
43
44
import java.io.File;
45
import java.lang.ref.WeakReference;
46
import java.util.HashMap;
47
import java.util.Map;
48
import java.util.Properties;
49
import java.util.logging.Level;
50
import java.util.logging.Logger;
51
import javax.swing.SwingUtilities;
52
import org.apache.maven.execution.DefaultMavenExecutionResult;
53
import org.apache.maven.execution.MavenExecutionRequest;
54
import org.apache.maven.execution.MavenExecutionResult;
55
import org.apache.maven.project.MavenProject;
56
import org.netbeans.api.annotations.common.NonNull;
57
import org.netbeans.modules.maven.M2AuxilaryConfigImpl;
58
import org.netbeans.modules.maven.configurations.M2Configuration;
59
import org.netbeans.modules.maven.embedder.EmbedderFactory;
60
import org.netbeans.modules.maven.embedder.MavenEmbedder;
61
import org.netbeans.modules.maven.execute.AbstractMavenExecutor;
62
import org.netbeans.spi.project.AuxiliaryConfiguration;
63
import org.openide.filesystems.FileObject;
64
import org.openide.filesystems.FileUtil;
65
import org.openide.util.Mutex;
66
import org.openide.util.Mutex.Action;
67
import org.openide.util.NbBundle;
68
69
/**
70
 * externalize the creation of MavenProject instances outside of NbMavenProjectImpl
71
 * and be able to access it without a project at hand
72
 * @author mkleint
73
 */
74
public final class MavenProjectCache {
75
    
76
    private static final Logger LOG = Logger.getLogger(MavenProjectCache.class.getName());
77
    private static final String CONTEXT_EXECUTION_RESULT = "NB_Execution_Result";
78
    
79
    //FileObject is referenced during lifetime of the Project.
80
    //TODO should these maps be weak and free values when FileObject is GCed?
81
    private static final Map<FileObject, WeakReference<MavenProject>> file2Project = new HashMap<FileObject, WeakReference<MavenProject>>();
82
    private static final Map<FileObject, Mutex> file2Mutex = new HashMap<FileObject, Mutex>();
83
    
84
    public static MavenProject getMavenProject(final FileObject projectDirectory, final boolean reload) {
85
        Mutex mutex = getMutex(projectDirectory);
86
        MavenProject mp = mutex.writeAccess(new Action<MavenProject>() {
87
            @Override
88
            public MavenProject run() {
89
                if (!reload) {
90
                    WeakReference<MavenProject> ref = file2Project.get(projectDirectory);
91
                    if (ref != null) {
92
                        MavenProject mp = ref.get();
93
                        if (mp != null) {
94
                            return mp;
95
                        }
96
                    }
97
                }
98
                MavenProject mp = loadOriginalMavenProject(projectDirectory);
99
                file2Project.put(projectDirectory, new WeakReference(mp)); //TODO our own referenceQueue to clean up the maps?
100
                return mp;
101
            }
102
        });
103
104
        return mp;
105
    }
106
    
107
    public static MavenExecutionResult getExecutionResult(MavenProject project) {
108
        return (MavenExecutionResult) project.getContextValue(CONTEXT_EXECUTION_RESULT);
109
    }
110
    
111
 
112
    
113
    
114
       @NbBundle.Messages({
115
        "TXT_RuntimeException=RuntimeException occurred in Apache Maven embedder while loading",
116
        "TXT_RuntimeExceptionLong=RuntimeException occurred in Apache Maven embedder while loading the project. \n"
117
            + "This is preventing the project model from loading properly. \n"
118
            + "Please file a bug report with details about your project and the IDE's log file.\n\n"
119
    })
120
    private static @NonNull MavenProject loadOriginalMavenProject(FileObject projectDirectory) {
121
        long startLoading = System.currentTimeMillis();
122
        MavenEmbedder projectEmbedder = EmbedderFactory.getProjectEmbedder();
123
        MavenProject newproject = null;
124
        //TODO have independent from M2AuxiliaryConfigImpl
125
        AuxiliaryConfiguration aux = new M2AuxilaryConfigImpl(projectDirectory);
126
        ActiveConfigurationProvider config = new ActiveConfigurationProvider(projectDirectory, aux);
127
        M2Configuration active = config.getActiveConfiguration();
128
        final File pomFile = new File(FileUtil.toFile(projectDirectory), "pom.xml");
129
        MavenExecutionResult res = null;
130
        try {
131
           final  MavenExecutionRequest req = projectEmbedder.createMavenExecutionRequest();
132
            req.addActiveProfiles(active.getActivatedProfiles());
133
134
            req.setPom(pomFile);
135
            req.setNoSnapshotUpdates(true);
136
            req.setUpdateSnapshots(false);
137
            //MEVENIDE-634 i'm wondering if this fixes the issue
138
            req.setInteractiveMode(false);
139
            // recursive == false is important to avoid checking all submodules for extensions
140
            // that will not be used in current pom anyway..
141
            // #135070
142
            req.setRecursive(false);
143
            req.setOffline(true);
144
            req.setUserProperties(createSystemPropsForProjectLoading(active.getProperties()));
145
            res = projectEmbedder.readProjectWithDependencies(req, true);
146
            newproject = res.getProject();
147
        } catch (RuntimeException exc) {
148
            //guard against exceptions that are not processed by the embedder
149
            //#136184 NumberFormatException
150
            LOG.log(Level.INFO, "Runtime exception thrown while loading maven project at " + projectDirectory, exc); //NOI18N
151
            res = new DefaultMavenExecutionResult();
152
            res.addException(exc);
153
        } finally {
154
            if (newproject == null) {
155
                newproject = getFallbackProject(pomFile);
156
            }
157
            newproject.setContextValue(CONTEXT_EXECUTION_RESULT, res);
158
            long endLoading = System.currentTimeMillis();
159
            LOG.log(Level.FINE, "Loaded project in {0} msec at {1}", new Object[] {endLoading - startLoading, projectDirectory.getPath()});
160
            if (LOG.isLoggable(Level.FINE) && SwingUtilities.isEventDispatchThread()) {
161
                LOG.log(Level.FINE, "Project " + projectDirectory.getPath() + " loaded in AWT event dispatching thread!", new RuntimeException());
162
            }
163
        }
164
        assert newproject != null;
165
        return newproject;
166
    }
167
    @NbBundle.Messages({
168
        "LBL_Incomplete_Project_Name=<partially loaded Maven project>",
169
        "LBL_Incomplete_Project_Desc=Partially loaded Maven project; try building it."
170
    })
171
    public static MavenProject getFallbackProject(File projectFile) throws AssertionError {
172
        MavenProject newproject = new MavenProject();
173
        newproject.setGroupId("error");
174
        newproject.setArtifactId("error");
175
        newproject.setVersion("0");
176
        newproject.setPackaging("pom");
177
        newproject.setName(Bundle.LBL_Incomplete_Project_Name());
178
        newproject.setDescription(Bundle.LBL_Incomplete_Project_Desc());
179
        newproject.setFile(projectFile);
180
        return newproject;
181
    }
182
    
183
    private static final Properties statics = new Properties();
184
185
    public static Properties cloneStaticProps() {
186
        synchronized (statics) {
187
            if (statics.isEmpty()) { // not yet initialized
188
                // Now a misnomer, but available to activate profiles only during NB project parse:
189
                statics.setProperty("netbeans.execution", "true"); // NOI18N
190
                EmbedderFactory.fillEnvVars(statics);
191
                statics.putAll(AbstractMavenExecutor.excludeNetBeansProperties(System.getProperties()));
192
            }
193
            Properties toRet = new Properties();
194
            toRet.putAll(statics);
195
            return toRet;
196
        }
197
    }
198
199
    //#158700
200
    public static Properties createSystemPropsForProjectLoading(Map<String, String> activeConfiguration) {
201
        Properties props = cloneStaticProps();
202
        if (activeConfiguration != null) {
203
            props.putAll(activeConfiguration);
204
        }
205
        //TODO the properties for java.home and maybe others shall be relevant to the project setup not ide setup.
206
        // we got a chicken-egg situation here, the jdk used in project can be defined in the pom.xml file.
207
        return props;
208
    }  
209
    
210
    private static Mutex getMutex(FileObject projectDirectory) {
211
        synchronized (file2Mutex) {
212
            Mutex mutex = file2Mutex.get(projectDirectory);
213
            if (mutex != null) {
214
                return mutex;
215
            }
216
            mutex = new Mutex();
217
            file2Mutex.put(projectDirectory, mutex);
218
            return mutex;
219
        }
220
    }
221
    
222
}
(-)maven/src/org/netbeans/modules/maven/queries/MavenFileOwnerQueryImpl.java (-4 / +9 lines)
Lines 64-69 Link Here
64
import org.netbeans.modules.maven.NbMavenProjectImpl;
64
import org.netbeans.modules.maven.NbMavenProjectImpl;
65
import org.netbeans.modules.maven.api.NbMavenProject;
65
import org.netbeans.modules.maven.api.NbMavenProject;
66
import org.netbeans.modules.maven.embedder.EmbedderFactory;
66
import org.netbeans.modules.maven.embedder.EmbedderFactory;
67
import org.netbeans.modules.maven.modelcache.MavenProjectCache;
67
import org.netbeans.spi.project.FileOwnerQueryImplementation;
68
import org.netbeans.spi.project.FileOwnerQueryImplementation;
68
import org.openide.filesystems.FileObject;
69
import org.openide.filesystems.FileObject;
69
import org.openide.filesystems.FileUtil;
70
import org.openide.filesystems.FileUtil;
Lines 290-295 Link Here
290
        return null;
291
        return null;
291
    }
292
    }
292
293
294
    
295
    //NOTE: called from NBArtifactFixer, cannot contain references to ProjectManager
293
    public File getOwnerPOM(String groupId, String artifactId, String version) {
296
    public File getOwnerPOM(String groupId, String artifactId, String version) {
294
        LOG.log(Level.FINER, "Checking {0} / {1} / {2} (POM only)", new Object[] {groupId, artifactId, version});
297
        LOG.log(Level.FINER, "Checking {0} / {1} / {2} (POM only)", new Object[] {groupId, artifactId, version});
295
        String oldKey = groupId + ":" + artifactId;
298
        String oldKey = groupId + ":" + artifactId;
Lines 324-333 Link Here
324
                            LOG.log(Level.FINE, "mismatch on groupId in {0}", pom);
327
                            LOG.log(Level.FINE, "mismatch on groupId in {0}", pom);
325
                        }
328
                        }
326
                        // Might actually be a match due to use of e.g. string interpolation, so double-check with live project.
329
                        // Might actually be a match due to use of e.g. string interpolation, so double-check with live project.
327
                        Project p = getOwner(groupId, artifactId, version);
330
                        FileObject projectDir = URLMapper.findFileObject(new URI(ownerURI).toURL());
328
                        if (p != null) {
331
                        if (projectDir != null && projectDir.isFolder()) {
329
                            LOG.log(Level.FINE, "live project match for {0}", pom);
332
                            MavenProject prj = MavenProjectCache.getMavenProject(projectDir, false);
330
                            return p.getLookup().lookup(NbMavenProjectImpl.class).getPOMFile();
333
                            if (prj.getGroupId().equals(groupId) && prj.getArtifactId().equals(artifactId) && prj.getVersion().equals(version)) {
334
                                return pom;
335
                            }
331
                        } else {
336
                        } else {
332
                            LOG.log(Level.FINE, "no live project match for {0}", pom);
337
                            LOG.log(Level.FINE, "no live project match for {0}", pom);
333
                        }
338
                        }

Return to bug 207172