]> git.argeo.org Git - gpl/argeo-slc.git/blob - runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/NormalizeGroup.java
Improve OSGi factory
[gpl/argeo-slc.git] / runtime / org.argeo.slc.repo / src / main / java / org / argeo / slc / repo / osgi / NormalizeGroup.java
1 /*
2 * Copyright (C) 2007-2012 Argeo GmbH
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.argeo.slc.repo.osgi;
17
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Set;
23 import java.util.TreeSet;
24
25 import javax.jcr.Node;
26 import javax.jcr.NodeIterator;
27 import javax.jcr.Repository;
28 import javax.jcr.RepositoryException;
29 import javax.jcr.Session;
30
31 import org.apache.commons.io.FilenameUtils;
32 import org.apache.commons.logging.Log;
33 import org.apache.commons.logging.LogFactory;
34 import org.argeo.ArgeoMonitor;
35 import org.argeo.jcr.JcrUtils;
36 import org.argeo.slc.SlcException;
37 import org.argeo.slc.aether.ArtifactIdComparator;
38 import org.argeo.slc.jcr.SlcNames;
39 import org.argeo.slc.jcr.SlcTypes;
40 import org.argeo.slc.repo.ArtifactIndexer;
41 import org.argeo.slc.repo.RepoConstants;
42 import org.argeo.slc.repo.RepoUtils;
43 import org.argeo.slc.repo.maven.MavenConventionsUtils;
44 import org.osgi.framework.Constants;
45 import org.osgi.framework.Version;
46 import org.sonatype.aether.artifact.Artifact;
47 import org.sonatype.aether.util.artifact.DefaultArtifact;
48
49 /**
50 * Make sure that all JCR metadata and Maven metadata are consistent for this
51 * group of OSGi bundles.
52 */
53 public class NormalizeGroup implements Runnable, SlcNames {
54 private final static Log log = LogFactory.getLog(NormalizeGroup.class);
55
56 private Repository repository;
57 private String workspace;
58 private String groupId;
59 private Boolean overridePoms = false;
60 private String artifactBasePath = "/";
61 private String version = null;
62 private String parentPomCoordinates;
63
64 private List<String> excludedSuffixes = new ArrayList<String>();
65
66 private ArtifactIndexer artifactIndexer = new ArtifactIndexer();
67 // private JarFileIndexer jarFileIndexer = new JarFileIndexer();
68
69 /** TODO make it more generic */
70 private List<String> systemPackages = OsgiProfile.PROFILE_JAVA_SE_1_6
71 .getSystemPackages();
72
73 // indexes
74 private Map<String, String> packagesToSymbolicNames = new HashMap<String, String>();
75 private Map<String, Node> symbolicNamesToNodes = new HashMap<String, Node>();
76
77 private Set<Artifact> binaries = new TreeSet<Artifact>(
78 new ArtifactIdComparator());
79 private Set<Artifact> sources = new TreeSet<Artifact>(
80 new ArtifactIdComparator());
81
82 public void run() {
83 Session session = null;
84 try {
85 session = repository.login(workspace);
86 Node groupNode = session.getNode(MavenConventionsUtils.groupPath(
87 artifactBasePath, groupId));
88 processGroupNode(groupNode, null);
89 } catch (Exception e) {
90 throw new SlcException("Cannot normalize group " + groupId + " in "
91 + workspace, e);
92 } finally {
93 JcrUtils.logoutQuietly(session);
94 }
95 }
96
97 public static void processGroupNode(Node groupNode, String version,
98 Boolean overridePoms, ArgeoMonitor monitor)
99 throws RepositoryException {
100 // TODO set artifactsBase based on group node
101 NormalizeGroup ng = new NormalizeGroup();
102 String groupId = groupNode.getProperty(SlcNames.SLC_GROUP_BASE_ID)
103 .getString();
104 ng.setGroupId(groupId);
105 ng.setVersion(version);
106 ng.setOverridePoms(overridePoms);
107 ng.processGroupNode(groupNode, monitor);
108 }
109
110 protected void processGroupNode(Node groupNode, ArgeoMonitor monitor)
111 throws RepositoryException {
112 if (monitor != null)
113 monitor.subTask("Group " + groupId);
114 Node allArtifactsHighestVersion = null;
115 Session session = groupNode.getSession();
116 aBases: for (NodeIterator aBases = groupNode.getNodes(); aBases
117 .hasNext();) {
118 Node aBase = aBases.nextNode();
119 if (aBase.isNodeType(SlcTypes.SLC_ARTIFACT_BASE)) {
120 Node highestAVersion = null;
121 for (NodeIterator aVersions = aBase.getNodes(); aVersions
122 .hasNext();) {
123 Node aVersion = aVersions.nextNode();
124 if (aVersion.isNodeType(SlcTypes.SLC_ARTIFACT_VERSION_BASE)) {
125 if (highestAVersion == null) {
126 highestAVersion = aVersion;
127 if (allArtifactsHighestVersion == null)
128 allArtifactsHighestVersion = aVersion;
129
130 } else {
131 Version currVersion = extractOsgiVersion(aVersion);
132 Version currentHighestVersion = extractOsgiVersion(highestAVersion);
133 if (currVersion.compareTo(currentHighestVersion) > 0) {
134 highestAVersion = aVersion;
135 }
136 if (currVersion
137 .compareTo(extractOsgiVersion(allArtifactsHighestVersion)) > 0) {
138 allArtifactsHighestVersion = aVersion;
139 }
140 }
141
142 }
143
144 }
145 if (highestAVersion == null)
146 continue aBases;
147 for (NodeIterator files = highestAVersion.getNodes(); files
148 .hasNext();) {
149 Node file = files.nextNode();
150 if (file.isNodeType(SlcTypes.SLC_BUNDLE_ARTIFACT)) {
151 preProcessBundleArtifact(file);
152 file.getSession().save();
153 if (log.isDebugEnabled())
154 log.debug("Pre-processed " + file.getName());
155 }
156
157 }
158 }
159 }
160
161 // if version not set or empty, use the highets version
162 // useful when indexing a product maven repository where
163 // all artifacts have the same version for a given release
164 // => the version can then be left empty
165 if (version == null || version.trim().equals(""))
166 if (allArtifactsHighestVersion != null)
167 version = allArtifactsHighestVersion.getProperty(
168 SLC_ARTIFACT_VERSION).getString();
169 else
170 throw new SlcException("Group version " + version
171 + " is empty.");
172
173 int bundleCount = symbolicNamesToNodes.size();
174 if (log.isDebugEnabled())
175 log.debug("Indexed " + bundleCount + " bundles");
176
177 int count = 1;
178 for (Node bundleNode : symbolicNamesToNodes.values()) {
179 processBundleArtifact(bundleNode);
180 bundleNode.getSession().save();
181 if (log.isDebugEnabled())
182 log.debug(count + "/" + bundleCount + " Processed "
183 + bundleNode.getName());
184 count++;
185 }
186
187 // indexes
188 Set<Artifact> indexes = new TreeSet<Artifact>(
189 new ArtifactIdComparator());
190 Artifact indexArtifact = writeIndex(session, RepoConstants.BINARIES_ARTIFACT_ID,
191 binaries);
192 indexes.add(indexArtifact);
193 indexArtifact = writeIndex(session, RepoConstants.SOURCES_ARTIFACT_ID, sources);
194 indexes.add(indexArtifact);
195 // sdk
196 writeIndex(session, RepoConstants.SDK_ARTIFACT_ID, indexes);
197 if (monitor != null)
198 monitor.worked(1);
199 }
200
201 private Version extractOsgiVersion(Node artifactVersion)
202 throws RepositoryException {
203 String rawVersion = artifactVersion.getProperty(SLC_ARTIFACT_VERSION)
204 .getString();
205 String cleanVersion = rawVersion.replace("-SNAPSHOT", ".SNAPSHOT");
206 return new Version(cleanVersion);
207 }
208
209 private Artifact writeIndex(Session session, String artifactId,
210 Set<Artifact> artifacts) throws RepositoryException {
211 Artifact artifact = new DefaultArtifact(groupId, artifactId, "pom",
212 version);
213 Artifact parentArtifact = parentPomCoordinates != null ? new DefaultArtifact(
214 parentPomCoordinates) : null;
215 String pom = MavenConventionsUtils.artifactsAsDependencyPom(artifact,
216 artifacts, parentArtifact);
217 Node node = RepoUtils.copyBytesAsArtifact(
218 session.getNode(artifactBasePath), artifact, pom.getBytes());
219 artifactIndexer.index(node);
220
221 // TODO factorize
222 String pomSha = JcrUtils.checksumFile(node, "SHA-1");
223 JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".sha1",
224 pomSha.getBytes());
225 String pomMd5 = JcrUtils.checksumFile(node, "MD5");
226 JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".md5",
227 pomMd5.getBytes());
228 session.save();
229 return artifact;
230 }
231
232 protected void preProcessBundleArtifact(Node bundleNode)
233 throws RepositoryException {
234 // we assume nodes are already indexed
235 // artifactIndexer.index(bundleNode);
236 // jarFileIndexer.index(bundleNode);
237
238 String symbolicName = JcrUtils.get(bundleNode, SLC_SYMBOLIC_NAME);
239
240 if (symbolicName.endsWith(".source")) {
241 // TODO make a shared node with classifier 'sources'?
242 String bundleName = RepoUtils
243 .extractBundleNameFromSourceName(symbolicName);
244 for (String excludedSuffix : excludedSuffixes) {
245 if (bundleName.endsWith(excludedSuffix))
246 return;// skip adding to sources
247 }
248 sources.add(RepoUtils.asArtifact(bundleNode));
249 return;
250 }
251
252 NodeIterator exportPackages = bundleNode.getNodes(SLC_
253 + Constants.EXPORT_PACKAGE);
254 while (exportPackages.hasNext()) {
255 Node exportPackage = exportPackages.nextNode();
256 String pkg = JcrUtils.get(exportPackage, SLC_NAME);
257 packagesToSymbolicNames.put(pkg, symbolicName);
258 }
259
260 symbolicNamesToNodes.put(symbolicName, bundleNode);
261 for (String excludedSuffix : excludedSuffixes) {
262 if (symbolicName.endsWith(excludedSuffix))
263 return;// skip adding to binaries
264 }
265 binaries.add(RepoUtils.asArtifact(bundleNode));
266
267 if (bundleNode.getSession().hasPendingChanges())
268 bundleNode.getSession().save();
269 }
270
271 protected void processBundleArtifact(Node bundleNode)
272 throws RepositoryException {
273 Node artifactFolder = bundleNode.getParent();
274 String baseName = FilenameUtils.getBaseName(bundleNode.getName());
275
276 // pom
277 String pomName = baseName + ".pom";
278 if (artifactFolder.hasNode(pomName) && !overridePoms)
279 return;// skip
280
281 String pom = generatePomForBundle(bundleNode);
282 Node pomNode = JcrUtils.copyBytesAsFile(artifactFolder, pomName,
283 pom.getBytes());
284 // checksum
285 String bundleSha = JcrUtils.checksumFile(bundleNode, "SHA-1");
286 JcrUtils.copyBytesAsFile(artifactFolder,
287 bundleNode.getName() + ".sha1", bundleSha.getBytes());
288 String pomSha = JcrUtils.checksumFile(pomNode, "SHA-1");
289 JcrUtils.copyBytesAsFile(artifactFolder, pomNode.getName() + ".sha1",
290 pomSha.getBytes());
291 }
292
293 private String generatePomForBundle(Node n) throws RepositoryException {
294 String ownSymbolicName = JcrUtils.get(n, SLC_SYMBOLIC_NAME);
295
296 StringBuffer p = new StringBuffer();
297
298 // XML header
299 p.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
300 p.append("<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n");
301 p.append("<modelVersion>4.0.0</modelVersion>");
302
303 // Artifact
304 // p.append("<parent><groupId>org.argeo</groupId><artifactId>parent</artifactId><version>1.2.0</version></parent>\n");
305 p.append("<groupId>").append(JcrUtils.get(n, SLC_GROUP_ID))
306 .append("</groupId>\n");
307 p.append("<artifactId>").append(JcrUtils.get(n, SLC_ARTIFACT_ID))
308 .append("</artifactId>\n");
309 p.append("<version>").append(JcrUtils.get(n, SLC_ARTIFACT_VERSION))
310 .append("</version>\n");
311 p.append("<packaging>pom</packaging>\n");
312 if (n.hasProperty(SLC_ + Constants.BUNDLE_NAME))
313 p.append("<name>")
314 .append(JcrUtils.get(n, SLC_ + Constants.BUNDLE_NAME))
315 .append("</name>\n");
316 if (n.hasProperty(SLC_ + Constants.BUNDLE_DESCRIPTION))
317 p.append("<description>")
318 .append(JcrUtils
319 .get(n, SLC_ + Constants.BUNDLE_DESCRIPTION))
320 .append("</description>\n");
321
322 // Dependencies
323 Set<String> dependenciesSymbolicNames = new TreeSet<String>();
324 Set<String> optionalSymbolicNames = new TreeSet<String>();
325 NodeIterator importPackages = n.getNodes(SLC_
326 + Constants.IMPORT_PACKAGE);
327 while (importPackages.hasNext()) {
328 Node importPackage = importPackages.nextNode();
329 String pkg = JcrUtils.get(importPackage, SLC_NAME);
330 if (packagesToSymbolicNames.containsKey(pkg)) {
331 String dependencySymbolicName = packagesToSymbolicNames
332 .get(pkg);
333 if (JcrUtils.check(importPackage, SLC_OPTIONAL))
334 optionalSymbolicNames.add(dependencySymbolicName);
335 else
336 dependenciesSymbolicNames.add(dependencySymbolicName);
337 } else {
338 if (!JcrUtils.check(importPackage, SLC_OPTIONAL)
339 && !systemPackages.contains(pkg))
340 log.warn("No bundle found for pkg " + pkg);
341 }
342 }
343
344 if (n.hasNode(SLC_ + Constants.FRAGMENT_HOST)) {
345 String fragmentHost = JcrUtils.get(
346 n.getNode(SLC_ + Constants.FRAGMENT_HOST),
347 SLC_SYMBOLIC_NAME);
348 dependenciesSymbolicNames.add(fragmentHost);
349 }
350
351 // TODO require bundles
352
353 List<Node> dependencyNodes = new ArrayList<Node>();
354 for (String depSymbName : dependenciesSymbolicNames) {
355 if (depSymbName.equals(ownSymbolicName))
356 continue;// skip self
357
358 if (symbolicNamesToNodes.containsKey(depSymbName))
359 dependencyNodes.add(symbolicNamesToNodes.get(depSymbName));
360 else
361 log.warn("Could not find node for " + depSymbName);
362 }
363 List<Node> optionalDependencyNodes = new ArrayList<Node>();
364 for (String depSymbName : optionalSymbolicNames) {
365 if (symbolicNamesToNodes.containsKey(depSymbName))
366 optionalDependencyNodes.add(symbolicNamesToNodes
367 .get(depSymbName));
368 else
369 log.warn("Could not find node for " + depSymbName);
370 }
371
372 p.append("<dependencies>\n");
373 for (Node dependencyNode : dependencyNodes) {
374 p.append("<dependency>\n");
375 p.append("\t<groupId>")
376 .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
377 .append("</groupId>\n");
378 p.append("\t<artifactId>")
379 .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
380 .append("</artifactId>\n");
381 p.append("</dependency>\n");
382 }
383
384 if (optionalDependencyNodes.size() > 0)
385 p.append("<!-- OPTIONAL -->\n");
386 for (Node dependencyNode : optionalDependencyNodes) {
387 p.append("<dependency>\n");
388 p.append("\t<groupId>")
389 .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
390 .append("</groupId>\n");
391 p.append("\t<artifactId>")
392 .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
393 .append("</artifactId>\n");
394 p.append("\t<optional>true</optional>\n");
395 p.append("</dependency>\n");
396 }
397 p.append("</dependencies>\n");
398
399 // Dependency management
400 p.append("<dependencyManagement>\n");
401 p.append("<dependencies>\n");
402 p.append("<dependency>\n");
403 p.append("\t<groupId>").append(groupId).append("</groupId>\n");
404 p.append("\t<artifactId>")
405 .append(ownSymbolicName.endsWith(".source") ? RepoConstants.SOURCES_ARTIFACT_ID
406 : RepoConstants.BINARIES_ARTIFACT_ID).append("</artifactId>\n");
407 p.append("\t<version>").append(version).append("</version>\n");
408 p.append("\t<type>pom</type>\n");
409 p.append("\t<scope>import</scope>\n");
410 p.append("</dependency>\n");
411 p.append("</dependencies>\n");
412 p.append("</dependencyManagement>\n");
413
414 p.append("</project>\n");
415 return p.toString();
416 }
417
418 public void setRepository(Repository repository) {
419 this.repository = repository;
420 }
421
422 public void setWorkspace(String workspace) {
423 this.workspace = workspace;
424 }
425
426 public void setGroupId(String groupId) {
427 this.groupId = groupId;
428 }
429
430 public void setParentPomCoordinates(String parentPomCoordinates) {
431 this.parentPomCoordinates = parentPomCoordinates;
432 }
433
434 public void setArtifactBasePath(String artifactBasePath) {
435 this.artifactBasePath = artifactBasePath;
436 }
437
438 public void setVersion(String version) {
439 this.version = version;
440 }
441
442 public void setExcludedSuffixes(List<String> excludedSuffixes) {
443 this.excludedSuffixes = excludedSuffixes;
444 }
445
446 public void setOverridePoms(Boolean overridePoms) {
447 this.overridePoms = overridePoms;
448 }
449
450 public void setArtifactIndexer(ArtifactIndexer artifactIndexer) {
451 this.artifactIndexer = artifactIndexer;
452 }
453 }