Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 16f787927d4ad0fe50fe0a9de8c2e6ebc2ad93a2 (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
/*******************************************************************************
 * Copyright (c) 2008-2010 Sonatype, Inc.
 * 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:
 *      Sonatype, Inc. - initial API and implementation
 *******************************************************************************/

package org.eclipse.m2e.core.internal.embedder;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import org.osgi.framework.Constants;
import org.osgi.framework.namespace.BundleNamespace;
import org.osgi.framework.namespace.PackageNamespace;
import org.osgi.framework.wiring.BundleWire;
import org.osgi.framework.wiring.BundleWiring;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.osgi.util.ManifestElement;

import org.codehaus.plexus.util.IOUtil;

import org.eclipse.m2e.core.embedder.IMavenLauncherConfiguration;
import org.eclipse.m2e.core.embedder.MavenRuntime;
import org.eclipse.m2e.core.embedder.MavenRuntimeManager;
import org.eclipse.m2e.core.internal.Messages;
import org.eclipse.m2e.core.internal.e44.DevClassPathHelper;


/**
 * Embedded Maven runtime
 * 
 * @author Eugene Kuleshov
 * @author Igor Fedorenko
 */
public class MavenEmbeddedRuntime implements MavenRuntime {

  private static final String MAVEN_CORE_POM_PROPERTIES = "META-INF/maven/org.apache.maven/maven-core/pom.properties"; //$NON-NLS-1$

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

  private static final String MAVEN_EMBEDDER_BUNDLE_SYMBOLICNAME = "org.eclipse.m2e.maven.runtime"; //$NON-NLS-1$

  private static final String MAVEN_EXECUTOR_CLASS = org.apache.maven.cli.MavenCli.class.getName();

  public static final String PLEXUS_CLASSWORLD_NAME = "plexus.core"; //$NON-NLS-1$

  private static String[] LAUNCHER_CLASSPATH;

  private static String[] CLASSPATH;

  private static volatile String mavenVersion;

  private Bundle m2eCore;

  public MavenEmbeddedRuntime(Bundle m2eCore) {
    this.m2eCore = m2eCore;
  }

  public boolean isEditable() {
    return false;
  }

  public String getLocation() {
    return MavenRuntimeManager.EMBEDDED;
  }

  public String getSettings() {
    return null;
  }

  public boolean isAvailable() {
    return true;
  }

  public void createLauncherConfiguration(IMavenLauncherConfiguration collector, IProgressMonitor monitor)
      throws CoreException {
    collector.setMainType(MAVEN_EXECUTOR_CLASS, PLEXUS_CLASSWORLD_NAME);

    initClasspath(findMavenEmbedderBundle());

    collector.addRealm(IMavenLauncherConfiguration.LAUNCHER_REALM);
    for(String entry : LAUNCHER_CLASSPATH) {
      collector.addArchiveEntry(entry);
    }

    collector.addRealm(PLEXUS_CLASSWORLD_NAME);
    for(String entry : CLASSPATH) {
      // https://issues.sonatype.org/browse/MNGECLIPSE-2507
      if(!entry.contains("plexus-build-api")) {
        collector.addArchiveEntry(entry);
      }
    }
  }

  private synchronized void initClasspath(Bundle mavenRuntimeBundle) {
    if(CLASSPATH == null) {
      LinkedHashSet<String> allentries = new LinkedHashSet<String>();

      addBundleClasspathEntries(allentries, mavenRuntimeBundle);

      // find and add more bundles
      for(String sname : new String[] {"com.ning.async-http-client", "org.jboss.netty", "org.slf4j.api"}) {
        Bundle dependency = findDependencyBundle(mavenRuntimeBundle, sname, new HashSet<Bundle>());
        if(dependency != null) {
          addBundleClasspathEntries(allentries, dependency);
        } else {
          log.warn(
              "Could not find OSGi bundle with symbolic name ''{}'' required to launch embedded maven runtime in external process",
              sname);
        }
      }

      List<String> cp = new ArrayList<String>();
      List<String> lcp = new ArrayList<String>();

      for(String entry : allentries) {
        if(entry.contains("plexus-classworlds")) { //$NON-NLS-1$
          lcp.add(entry);
        } else {
          cp.add(entry);
        }
      }

      CLASSPATH = cp.toArray(new String[cp.size()]);
      LAUNCHER_CLASSPATH = lcp.toArray(new String[lcp.size()]);
    }
  }

  private Bundle findDependencyBundle(Bundle bundle, String dependencyName, Set<Bundle> visited) {
    BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
    if(bundleWiring == null) {
      return null;
    }
    ArrayList<BundleWire> dependencies = new ArrayList<BundleWire>();
    dependencies.addAll(bundleWiring.getRequiredWires(BundleNamespace.BUNDLE_NAMESPACE));
    dependencies.addAll(bundleWiring.getRequiredWires(PackageNamespace.PACKAGE_NAMESPACE));
    for(BundleWire wire : dependencies) {
      Bundle requiredBundle = wire.getProviderWiring().getBundle();
      if(requiredBundle != null && visited.add(requiredBundle)) {
        if(dependencyName.equals(requiredBundle.getSymbolicName())) {
          return requiredBundle;
        }
        Bundle required = findDependencyBundle(requiredBundle, dependencyName, visited);
        if(required != null) {
          return required;
        }
      }
    }
    return null;
  }

  private void addBundleClasspathEntries(Set<String> entries, Bundle bundle) {
    log.debug("addBundleClasspathEntries(Bundle={})", bundle.toString());

    Set<String> cp = new LinkedHashSet<String>();
    if(DevClassPathHelper.inDevelopmentMode()) {
      cp.addAll(Arrays.asList(DevClassPathHelper.getDevClassPath(bundle.getSymbolicName())));
    }
    cp.addAll(Arrays.asList(parseBundleClasspath(bundle)));
    for(String cpe : cp) {
      String entry;
      if(".".equals(cpe)) {
        entry = getNestedJarOrDir(bundle, "/");
      } else {
        entry = getNestedJarOrDir(bundle, cpe);
      }

      if(entry != null) {
        log.debug("\tEntry:{}", entry);
        entries.add(entry);
      }
    }
  }

  private String[] parseBundleClasspath(Bundle bundle) {
    String[] result = new String[] {"."};
    String header = (String) bundle.getHeaders().get(Constants.BUNDLE_CLASSPATH);
    ManifestElement[] classpathEntries = null;
    try {
      classpathEntries = ManifestElement.parseHeader(Constants.BUNDLE_CLASSPATH, header);
    } catch(BundleException ex) {
      log.warn("Could not parse bundle classpath of {}", bundle.toString(), ex);
    }
    if(classpathEntries != null) {
      result = new String[classpathEntries.length];
      for(int i = 0; i < classpathEntries.length; i++ ) {
        result[i] = classpathEntries[i].getValue();
      }
    }
    return result;
  }

  private String getNestedJarOrDir(Bundle bundle, String cp) {
    // try embeded entries first
    URL url = bundle.getEntry(cp);
    if(url != null) {
      try {
        return FileLocator.toFileURL(url).getFile();
      } catch(IOException ex) {
        log.warn("Could not get entry {} for bundle {}", new Object[] {cp, bundle.toString(), ex});
      }
    }

    // in development mode entries can be absolute paths outside of bundle basedir
    if(DevClassPathHelper.inDevelopmentMode()) {
      File file = new File(cp);
      if(file.exists() && file.isAbsolute()) {
        return file.getAbsolutePath();
      }
    }

    log.debug("Bundle {} does not have entry {}", bundle.toString(), cp);
    return null;
  }

  private Bundle findMavenEmbedderBundle() {
    return findDependencyBundle(m2eCore, MAVEN_EMBEDDER_BUNDLE_SYMBOLICNAME, new HashSet<Bundle>());
  }

  public String toString() {
    Bundle embedder = findMavenEmbedderBundle();

    StringBuilder sb = new StringBuilder();
    sb.append("Embedded (").append(getVersion()); //$NON-NLS-1$
    if(embedder != null) {
      String version = (String) embedder.getHeaders().get(Constants.BUNDLE_VERSION);
      sb.append('/').append(version);
    }
    sb.append(')');

    return sb.toString();
  }

  private synchronized String getVersion(Bundle bundle) {
    if(mavenVersion != null) {
      return mavenVersion;
    }
    initClasspath(bundle);
    try {
      String mavenCoreJarPath = null;
      for(String path : CLASSPATH) {
        if(path.contains("maven-core")) {
          mavenCoreJarPath = path;
          break;
        }
      }

      if(mavenCoreJarPath == null) {
        throw new RuntimeException("Could not find maven core jar file");
      }

      Properties pomProperties = new Properties();

      File mavenCoreJar = new File(mavenCoreJarPath);
      if(mavenCoreJar.isFile()) {
        ZipFile zip = new ZipFile(mavenCoreJarPath);
        try {
          ZipEntry zipEntry = zip.getEntry(MAVEN_CORE_POM_PROPERTIES);
          if(zipEntry != null) {
            pomProperties.load(zip.getInputStream(zipEntry));
          }
        } finally {
          zip.close();
        }
      } else if(mavenCoreJar.isDirectory()) {
        InputStream is = new BufferedInputStream(new FileInputStream(new File(mavenCoreJar, MAVEN_CORE_POM_PROPERTIES)));
        try {
          pomProperties.load(is);
        } finally {
          IOUtil.close(is);
        }
      }

      String version = pomProperties.getProperty("version"); //$NON-NLS-1$
      if(version != null) {
        mavenVersion = version;
        return mavenVersion;
      }

    } catch(Exception e) {
      log.warn("Could not determine embedded maven version", e);
    }

    return Messages.MavenEmbeddedRuntime_unknown;
  }

  public String getVersion() {
    Bundle bundle = findMavenEmbedderBundle();
    return getVersion(bundle);
  }
}

Back to the top