]> git.argeo.org Git - gpl/argeo-slc.git/blob - runtime/org.argeo.slc.repo/src/main/java/org/argeo/slc/repo/osgi/NormalizeGroup.java
Work on the binaries indexer.
[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 // BS will fail if artifacts arrive in this order
131 // Name1 - V1, name2 - V3, V1 will remain the
132 // allArtifactsHighestVersion
133 // Fixed below
134 else {
135 Version currVersion = extractOsgiVersion(aVersion);
136 Version highestVersion = extractOsgiVersion(allArtifactsHighestVersion);
137 if (currVersion.compareTo(highestVersion) > 0)
138 allArtifactsHighestVersion = aVersion;
139 }
140
141 } else {
142 Version currVersion = extractOsgiVersion(aVersion);
143 Version currentHighestVersion = extractOsgiVersion(highestAVersion);
144 if (currVersion.compareTo(currentHighestVersion) > 0) {
145 highestAVersion = aVersion;
146 }
147 if (currVersion
148 .compareTo(extractOsgiVersion(allArtifactsHighestVersion)) > 0) {
149 allArtifactsHighestVersion = aVersion;
150 }
151 }
152
153 }
154
155 }
156 if (highestAVersion == null)
157 continue aBases;
158 for (NodeIterator files = highestAVersion.getNodes(); files
159 .hasNext();) {
160 Node file = files.nextNode();
161 if (file.isNodeType(SlcTypes.SLC_BUNDLE_ARTIFACT)) {
162 preProcessBundleArtifact(file);
163 file.getSession().save();
164 if (log.isDebugEnabled())
165 log.debug("Pre-processed " + file.getName());
166 }
167
168 }
169 }
170 }
171
172 // if version not set or empty, use the highest version
173 // useful when indexing a product maven repository where
174 // all artifacts have the same version for a given release
175 // => the version can then be left empty
176 if (version == null || version.trim().equals(""))
177 if (allArtifactsHighestVersion != null)
178 version = allArtifactsHighestVersion.getProperty(
179 SLC_ARTIFACT_VERSION).getString();
180 else
181 version = "0.0";
182 // throw new SlcException("Group version " + version
183 // + " is empty.");
184
185 int bundleCount = symbolicNamesToNodes.size();
186 if (log.isDebugEnabled())
187 log.debug("Indexed " + bundleCount + " bundles");
188
189 int count = 1;
190 for (Node bundleNode : symbolicNamesToNodes.values()) {
191 processBundleArtifact(bundleNode);
192 bundleNode.getSession().save();
193 if (log.isDebugEnabled())
194 log.debug(count + "/" + bundleCount + " Processed "
195 + bundleNode.getName());
196 count++;
197 }
198
199 // indexes
200 Set<Artifact> indexes = new TreeSet<Artifact>(
201 new ArtifactIdComparator());
202 Artifact indexArtifact = writeIndex(session,
203 RepoConstants.BINARIES_ARTIFACT_ID, binaries);
204 indexes.add(indexArtifact);
205 indexArtifact = writeIndex(session, RepoConstants.SOURCES_ARTIFACT_ID,
206 sources);
207 indexes.add(indexArtifact);
208 // sdk
209 writeIndex(session, RepoConstants.SDK_ARTIFACT_ID, indexes);
210 if (monitor != null)
211 monitor.worked(1);
212 }
213
214 private Version extractOsgiVersion(Node artifactVersion)
215 throws RepositoryException {
216 String rawVersion = artifactVersion.getProperty(SLC_ARTIFACT_VERSION)
217 .getString();
218 String cleanVersion = rawVersion.replace("-SNAPSHOT", ".SNAPSHOT");
219 return new Version(cleanVersion);
220 }
221
222 private Artifact writeIndex(Session session, String artifactId,
223 Set<Artifact> artifacts) throws RepositoryException {
224 Artifact artifact = new DefaultArtifact(groupId, artifactId, "pom",
225 version);
226 Artifact parentArtifact = parentPomCoordinates != null ? new DefaultArtifact(
227 parentPomCoordinates) : null;
228 String pom = MavenConventionsUtils.artifactsAsDependencyPom(artifact,
229 artifacts, parentArtifact);
230 Node node = RepoUtils.copyBytesAsArtifact(
231 session.getNode(artifactBasePath), artifact, pom.getBytes());
232 artifactIndexer.index(node);
233
234 // TODO factorize
235 String pomSha = JcrUtils.checksumFile(node, "SHA-1");
236 JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".sha1",
237 pomSha.getBytes());
238 String pomMd5 = JcrUtils.checksumFile(node, "MD5");
239 JcrUtils.copyBytesAsFile(node.getParent(), node.getName() + ".md5",
240 pomMd5.getBytes());
241 session.save();
242 return artifact;
243 }
244
245 protected void preProcessBundleArtifact(Node bundleNode)
246 throws RepositoryException {
247
248 String symbolicName = JcrUtils.get(bundleNode, SLC_SYMBOLIC_NAME);
249 if (symbolicName.endsWith(".source")) {
250 // TODO make a shared node with classifier 'sources'?
251 String bundleName = RepoUtils
252 .extractBundleNameFromSourceName(symbolicName);
253 for (String excludedSuffix : excludedSuffixes) {
254 if (bundleName.endsWith(excludedSuffix))
255 return;// skip adding to sources
256 }
257 sources.add(RepoUtils.asArtifact(bundleNode));
258 return;
259 }
260
261 NodeIterator exportPackages = bundleNode.getNodes(SLC_
262 + Constants.EXPORT_PACKAGE);
263 while (exportPackages.hasNext()) {
264 Node exportPackage = exportPackages.nextNode();
265 String pkg = JcrUtils.get(exportPackage, SLC_NAME);
266 packagesToSymbolicNames.put(pkg, symbolicName);
267 }
268
269 symbolicNamesToNodes.put(symbolicName, bundleNode);
270 for (String excludedSuffix : excludedSuffixes) {
271 if (symbolicName.endsWith(excludedSuffix))
272 return;// skip adding to binaries
273 }
274 binaries.add(RepoUtils.asArtifact(bundleNode));
275
276 if (bundleNode.getSession().hasPendingChanges())
277 bundleNode.getSession().save();
278 }
279
280 protected void processBundleArtifact(Node bundleNode)
281 throws RepositoryException {
282 Node artifactFolder = bundleNode.getParent();
283 String baseName = FilenameUtils.getBaseName(bundleNode.getName());
284
285 // pom
286 String pomName = baseName + ".pom";
287 if (artifactFolder.hasNode(pomName) && !overridePoms)
288 return;// skip
289
290 String pom = generatePomForBundle(bundleNode);
291 Node pomNode = JcrUtils.copyBytesAsFile(artifactFolder, pomName,
292 pom.getBytes());
293 // checksum
294 String bundleSha = JcrUtils.checksumFile(bundleNode, "SHA-1");
295 JcrUtils.copyBytesAsFile(artifactFolder,
296 bundleNode.getName() + ".sha1", bundleSha.getBytes());
297 String pomSha = JcrUtils.checksumFile(pomNode, "SHA-1");
298 JcrUtils.copyBytesAsFile(artifactFolder, pomNode.getName() + ".sha1",
299 pomSha.getBytes());
300 }
301
302 private String generatePomForBundle(Node n) throws RepositoryException {
303 String ownSymbolicName = JcrUtils.get(n, SLC_SYMBOLIC_NAME);
304
305 StringBuffer p = new StringBuffer();
306
307 // XML header
308 p.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
309 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");
310 p.append("<modelVersion>4.0.0</modelVersion>");
311
312 // Artifact
313 p.append("<groupId>").append(JcrUtils.get(n, SLC_GROUP_ID))
314 .append("</groupId>\n");
315 p.append("<artifactId>").append(JcrUtils.get(n, SLC_ARTIFACT_ID))
316 .append("</artifactId>\n");
317 p.append("<version>").append(JcrUtils.get(n, SLC_ARTIFACT_VERSION))
318 .append("</version>\n");
319 p.append("<packaging>pom</packaging>\n");
320 if (n.hasProperty(SLC_ + Constants.BUNDLE_NAME))
321 p.append("<name>")
322 .append(JcrUtils.get(n, SLC_ + Constants.BUNDLE_NAME))
323 .append("</name>\n");
324 if (n.hasProperty(SLC_ + Constants.BUNDLE_DESCRIPTION))
325 p.append("<description>")
326 .append(JcrUtils
327 .get(n, SLC_ + Constants.BUNDLE_DESCRIPTION))
328 .append("</description>\n");
329
330 // Dependencies
331 Set<String> dependenciesSymbolicNames = new TreeSet<String>();
332 Set<String> optionalSymbolicNames = new TreeSet<String>();
333 NodeIterator importPackages = n.getNodes(SLC_
334 + Constants.IMPORT_PACKAGE);
335 while (importPackages.hasNext()) {
336 Node importPackage = importPackages.nextNode();
337 String pkg = JcrUtils.get(importPackage, SLC_NAME);
338 if (packagesToSymbolicNames.containsKey(pkg)) {
339 String dependencySymbolicName = packagesToSymbolicNames
340 .get(pkg);
341 if (JcrUtils.check(importPackage, SLC_OPTIONAL))
342 optionalSymbolicNames.add(dependencySymbolicName);
343 else
344 dependenciesSymbolicNames.add(dependencySymbolicName);
345 } else {
346 if (!JcrUtils.check(importPackage, SLC_OPTIONAL)
347 && !systemPackages.contains(pkg))
348 log.warn("No bundle found for pkg " + pkg);
349 }
350 }
351
352 if (n.hasNode(SLC_ + Constants.FRAGMENT_HOST)) {
353 String fragmentHost = JcrUtils.get(
354 n.getNode(SLC_ + Constants.FRAGMENT_HOST),
355 SLC_SYMBOLIC_NAME);
356 dependenciesSymbolicNames.add(fragmentHost);
357 }
358
359 // TODO require bundles
360
361
362
363 List<Node> dependencyNodes = new ArrayList<Node>();
364 for (String depSymbName : dependenciesSymbolicNames) {
365 if (depSymbName.equals(ownSymbolicName))
366 continue;// skip self
367
368 if (symbolicNamesToNodes.containsKey(depSymbName))
369 dependencyNodes.add(symbolicNamesToNodes.get(depSymbName));
370 else
371 log.warn("Could not find node for " + depSymbName);
372 }
373 List<Node> optionalDependencyNodes = new ArrayList<Node>();
374 for (String depSymbName : optionalSymbolicNames) {
375 if (symbolicNamesToNodes.containsKey(depSymbName))
376 optionalDependencyNodes.add(symbolicNamesToNodes
377 .get(depSymbName));
378 else
379 log.warn("Could not find node for " + depSymbName);
380 }
381
382 p.append("<dependencies>\n");
383 for (Node dependencyNode : dependencyNodes) {
384 p.append("<dependency>\n");
385 p.append("\t<groupId>")
386 .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
387 .append("</groupId>\n");
388 p.append("\t<artifactId>")
389 .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
390 .append("</artifactId>\n");
391 p.append("</dependency>\n");
392 }
393
394 if (optionalDependencyNodes.size() > 0)
395 p.append("<!-- OPTIONAL -->\n");
396 for (Node dependencyNode : optionalDependencyNodes) {
397 p.append("<dependency>\n");
398 p.append("\t<groupId>")
399 .append(JcrUtils.get(dependencyNode, SLC_GROUP_ID))
400 .append("</groupId>\n");
401 p.append("\t<artifactId>")
402 .append(JcrUtils.get(dependencyNode, SLC_ARTIFACT_ID))
403 .append("</artifactId>\n");
404 p.append("\t<optional>true</optional>\n");
405 p.append("</dependency>\n");
406 }
407 p.append("</dependencies>\n");
408
409 // Dependency management
410 p.append("<dependencyManagement>\n");
411 p.append("<dependencies>\n");
412 p.append("<dependency>\n");
413 p.append("\t<groupId>").append(groupId).append("</groupId>\n");
414 p.append("\t<artifactId>")
415 .append(ownSymbolicName.endsWith(".source") ? RepoConstants.SOURCES_ARTIFACT_ID
416 : RepoConstants.BINARIES_ARTIFACT_ID)
417 .append("</artifactId>\n");
418 p.append("\t<version>").append(version).append("</version>\n");
419 p.append("\t<type>pom</type>\n");
420 p.append("\t<scope>import</scope>\n");
421 p.append("</dependency>\n");
422 p.append("</dependencies>\n");
423 p.append("</dependencyManagement>\n");
424
425 p.append("</project>\n");
426 return p.toString();
427 }
428
429 public void setRepository(Repository repository) {
430 this.repository = repository;
431 }
432
433 public void setWorkspace(String workspace) {
434 this.workspace = workspace;
435 }
436
437 public void setGroupId(String groupId) {
438 this.groupId = groupId;
439 }
440
441 public void setParentPomCoordinates(String parentPomCoordinates) {
442 this.parentPomCoordinates = parentPomCoordinates;
443 }
444
445 public void setArtifactBasePath(String artifactBasePath) {
446 this.artifactBasePath = artifactBasePath;
447 }
448
449 public void setVersion(String version) {
450 this.version = version;
451 }
452
453 public void setExcludedSuffixes(List<String> excludedSuffixes) {
454 this.excludedSuffixes = excludedSuffixes;
455 }
456
457 public void setOverridePoms(Boolean overridePoms) {
458 this.overridePoms = overridePoms;
459 }
460
461 public void setArtifactIndexer(ArtifactIndexer artifactIndexer) {
462 this.artifactIndexer = artifactIndexer;
463 }
464 }