2 * Copyright (C) 2007-2012 Argeo GmbH
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org
.argeo
.slc
.repo
;
18 import java
.io
.ByteArrayOutputStream
;
20 import java
.io
.FileInputStream
;
21 import java
.io
.IOException
;
22 import java
.io
.InputStream
;
23 import java
.io
.OutputStream
;
24 import java
.util
.Enumeration
;
25 import java
.util
.Iterator
;
27 import java
.util
.StringTokenizer
;
28 import java
.util
.TreeSet
;
29 import java
.util
.jar
.Attributes
;
30 import java
.util
.jar
.JarEntry
;
31 import java
.util
.jar
.JarFile
;
32 import java
.util
.jar
.JarInputStream
;
33 import java
.util
.jar
.JarOutputStream
;
34 import java
.util
.jar
.Manifest
;
36 import javax
.jcr
.Credentials
;
37 import javax
.jcr
.GuestCredentials
;
38 import javax
.jcr
.Node
;
39 import javax
.jcr
.NodeIterator
;
40 import javax
.jcr
.Property
;
41 import javax
.jcr
.PropertyIterator
;
42 import javax
.jcr
.Repository
;
43 import javax
.jcr
.RepositoryException
;
44 import javax
.jcr
.RepositoryFactory
;
45 import javax
.jcr
.Session
;
46 import javax
.jcr
.SimpleCredentials
;
47 import javax
.jcr
.nodetype
.NodeType
;
49 import org
.apache
.commons
.io
.FilenameUtils
;
50 import org
.apache
.commons
.io
.IOUtils
;
51 import org
.apache
.commons
.logging
.Log
;
52 import org
.apache
.commons
.logging
.LogFactory
;
53 import org
.argeo
.jcr
.ArgeoJcrUtils
;
54 import org
.argeo
.jcr
.ArgeoNames
;
55 import org
.argeo
.jcr
.ArgeoTypes
;
56 import org
.argeo
.jcr
.JcrUtils
;
57 import org
.argeo
.slc
.DefaultNameVersion
;
58 import org
.argeo
.slc
.NameVersion
;
59 import org
.argeo
.slc
.SlcException
;
60 import org
.argeo
.slc
.aether
.ArtifactIdComparator
;
61 import org
.argeo
.slc
.jcr
.SlcNames
;
62 import org
.argeo
.slc
.jcr
.SlcTypes
;
63 import org
.argeo
.slc
.repo
.maven
.MavenConventionsUtils
;
64 import org
.argeo
.util
.security
.Keyring
;
65 import org
.osgi
.framework
.Constants
;
66 import org
.sonatype
.aether
.artifact
.Artifact
;
67 import org
.sonatype
.aether
.util
.artifact
.DefaultArtifact
;
69 /** Utilities around repo */
70 public class RepoUtils
implements ArgeoNames
, SlcNames
{
71 private final static Log log
= LogFactory
.getLog(RepoUtils
.class);
73 /** Packages a regular sources jar as PDE source. */
74 public static void packagesAsPdeSource(File sourceFile
,
75 NameVersion nameVersion
, OutputStream out
) throws IOException
{
76 if (isAlreadyPdeSource(sourceFile
)) {
77 FileInputStream in
= new FileInputStream(sourceFile
);
78 IOUtils
.copy(in
, out
);
79 IOUtils
.closeQuietly(in
);
81 String sourceSymbolicName
= nameVersion
.getName() + ".source";
83 Manifest sourceManifest
= null;
84 sourceManifest
= new Manifest();
85 sourceManifest
.getMainAttributes().put(
86 Attributes
.Name
.MANIFEST_VERSION
, "1.0");
87 sourceManifest
.getMainAttributes().putValue("Bundle-SymbolicName",
89 sourceManifest
.getMainAttributes().putValue("Bundle-Version",
90 nameVersion
.getVersion());
91 sourceManifest
.getMainAttributes().putValue(
92 "Eclipse-SourceBundle",
93 nameVersion
.getName() + ";version="
94 + nameVersion
.getVersion());
95 copyJar(sourceFile
, out
, sourceManifest
);
99 public static byte[] packageAsPdeSource(InputStream sourceJar
,
100 NameVersion nameVersion
) {
101 String sourceSymbolicName
= nameVersion
.getName() + ".source";
103 Manifest sourceManifest
= null;
104 sourceManifest
= new Manifest();
105 sourceManifest
.getMainAttributes().put(
106 Attributes
.Name
.MANIFEST_VERSION
, "1.0");
107 sourceManifest
.getMainAttributes().putValue("Bundle-SymbolicName",
109 sourceManifest
.getMainAttributes().putValue("Bundle-Version",
110 nameVersion
.getVersion());
111 sourceManifest
.getMainAttributes().putValue("Eclipse-SourceBundle",
112 nameVersion
.getName() + ";version=" + nameVersion
.getVersion());
114 return modifyManifest(sourceJar
, sourceManifest
);
118 * Check whether the file as already been packaged as PDE source, in order
119 * not to mess with Jar signing
121 private static boolean isAlreadyPdeSource(File sourceFile
) {
122 JarInputStream jarInputStream
= null;
125 jarInputStream
= new JarInputStream(new FileInputStream(sourceFile
));
127 Manifest manifest
= jarInputStream
.getManifest();
128 Iterator
<?
> it
= manifest
.getMainAttributes().keySet().iterator();
130 // containsKey() does not work, iterating...
132 if (it
.next().toString().equals("Eclipse-SourceBundle")) {
136 // boolean res = manifest.getMainAttributes().get(
137 // "Eclipse-SourceBundle") != null;
139 log
.info(sourceFile
+ " is already a PDE source");
141 } catch (Exception e
) {
142 // probably not a jar, skipping
143 if (log
.isDebugEnabled())
144 log
.debug("Skipping " + sourceFile
+ " because of "
148 IOUtils
.closeQuietly(jarInputStream
);
153 * Copy a jar, replacing its manifest with the provided one
158 private static void copyJar(File source
, OutputStream out
, Manifest manifest
)
160 JarFile sourceJar
= null;
161 JarOutputStream output
= null;
163 output
= manifest
!= null ?
new JarOutputStream(out
, manifest
)
164 : new JarOutputStream(out
);
165 sourceJar
= new JarFile(source
);
167 entries
: for (Enumeration
<?
> entries
= sourceJar
.entries(); entries
168 .hasMoreElements();) {
169 JarEntry entry
= (JarEntry
) entries
.nextElement();
171 && entry
.getName().equals("META-INF/MANIFEST.MF"))
174 InputStream entryStream
= sourceJar
.getInputStream(entry
);
175 JarEntry newEntry
= new JarEntry(entry
.getName());
176 // newEntry.setMethod(JarEntry.DEFLATED);
177 output
.putNextEntry(newEntry
);
178 IOUtils
.copy(entryStream
, output
);
181 IOUtils
.closeQuietly(output
);
183 if (sourceJar
!= null)
185 } catch (IOException e
) {
191 /** Copy a jar changing onlythe manifest */
192 public static void copyJar(InputStream in
, OutputStream out
,
194 JarInputStream jarIn
= null;
195 JarOutputStream jarOut
= null;
197 jarIn
= new JarInputStream(in
);
198 jarOut
= new JarOutputStream(out
, manifest
);
199 JarEntry jarEntry
= null;
200 while ((jarEntry
= jarIn
.getNextJarEntry()) != null) {
201 jarOut
.putNextEntry(jarEntry
);
202 IOUtils
.copy(jarIn
, jarOut
);
206 } catch (IOException e
) {
207 throw new SlcException("Could not copy jar with MANIFEST "
208 + manifest
.getMainAttributes(), e
);
210 IOUtils
.closeQuietly(jarIn
);
211 IOUtils
.closeQuietly(jarOut
);
215 /** Reads a jar file, modify its manifest */
216 public static byte[] modifyManifest(InputStream in
, Manifest manifest
) {
217 ByteArrayOutputStream out
= new ByteArrayOutputStream(200 * 1024);
219 copyJar(in
, out
, manifest
);
220 return out
.toByteArray();
222 IOUtils
.closeQuietly(out
);
226 /** Read the OSGi {@link NameVersion} */
227 public static NameVersion
readNameVersion(Artifact artifact
) {
228 File artifactFile
= artifact
.getFile();
229 if (artifact
.getExtension().equals("pom")) {
230 // hack to process jars which weirdly appear as POMs
231 File jarFile
= new File(artifactFile
.getParentFile(),
232 FilenameUtils
.getBaseName(artifactFile
.getPath()) + ".jar");
233 if (jarFile
.exists()) {
234 log
.warn("Use " + jarFile
+ " instead of " + artifactFile
235 + " for " + artifact
);
236 artifactFile
= jarFile
;
239 return readNameVersion(artifactFile
);
242 /** Read the OSGi {@link NameVersion} */
243 public static NameVersion
readNameVersion(File artifactFile
) {
245 return readNameVersion(new FileInputStream(artifactFile
));
246 } catch (Exception e
) {
247 // probably not a jar, skipping
248 if (log
.isDebugEnabled()) {
249 log
.debug("Skipping " + artifactFile
+ " because of " + e
);
250 // e.printStackTrace();
256 /** Read the OSGi {@link NameVersion} */
257 public static NameVersion
readNameVersion(InputStream in
) {
258 JarInputStream jarInputStream
= null;
260 jarInputStream
= new JarInputStream(in
);
261 return readNameVersion(jarInputStream
.getManifest());
262 } catch (Exception e
) {
263 // probably not a jar, skipping
264 if (log
.isDebugEnabled()) {
265 log
.debug("Skipping because of " + e
);
269 IOUtils
.closeQuietly(jarInputStream
);
274 /** Read the OSGi {@link NameVersion} */
275 public static NameVersion
readNameVersion(Manifest manifest
) {
276 DefaultNameVersion nameVersion
= new DefaultNameVersion();
277 nameVersion
.setName(manifest
.getMainAttributes().getValue(
278 Constants
.BUNDLE_SYMBOLICNAME
));
280 // Skip additional specs such as
282 if (nameVersion
.getName().indexOf(';') > -1) {
284 .setName(new StringTokenizer(nameVersion
.getName(), " ;")
288 nameVersion
.setVersion(manifest
.getMainAttributes().getValue(
289 Constants
.BUNDLE_VERSION
));
297 /** The artifact described by this node */
298 public static Artifact
asArtifact(Node node
) throws RepositoryException
{
299 if (node
.isNodeType(SlcTypes
.SLC_ARTIFACT_VERSION_BASE
)) {
300 // FIXME update data model to store packaging at this level
301 String extension
= "jar";
302 return new DefaultArtifact(node
.getProperty(SLC_GROUP_ID
)
304 node
.getProperty(SLC_ARTIFACT_ID
).getString(), extension
,
305 node
.getProperty(SLC_ARTIFACT_VERSION
).getString());
306 } else if (node
.isNodeType(SlcTypes
.SLC_ARTIFACT
)) {
307 return new DefaultArtifact(node
.getProperty(SLC_GROUP_ID
)
309 node
.getProperty(SLC_ARTIFACT_ID
).getString(), node
310 .getProperty(SLC_ARTIFACT_CLASSIFIER
).getString(),
311 node
.getProperty(SLC_ARTIFACT_EXTENSION
).getString(), node
312 .getProperty(SLC_ARTIFACT_VERSION
).getString());
314 throw new SlcException("Unsupported node type for " + node
);
319 * The path to the PDE source related to this artifact (or artifact version
320 * base). There may or there may not be a node at this location (the
321 * returned path will typically be used to test whether PDE sources are
322 * attached to this artifact).
324 public static String
relatedPdeSourcePath(String artifactBasePath
,
325 Node artifactNode
) throws RepositoryException
{
326 Artifact artifact
= asArtifact(artifactNode
);
327 Artifact pdeSourceArtifact
= new DefaultArtifact(artifact
.getGroupId(),
328 artifact
.getArtifactId() + ".source", artifact
.getExtension(),
329 artifact
.getVersion());
330 return MavenConventionsUtils
.artifactPath(artifactBasePath
,
335 * Copy this bytes array as an artifact, relative to the root of the
336 * repository (typically the workspace root node)
338 public static Node
copyBytesAsArtifact(Node artifactsBase
,
339 Artifact artifact
, byte[] bytes
) throws RepositoryException
{
340 String parentPath
= MavenConventionsUtils
.artifactParentPath(
341 artifactsBase
.getPath(), artifact
);
342 Node folderNode
= JcrUtils
.mkfolders(artifactsBase
.getSession(),
344 return JcrUtils
.copyBytesAsFile(folderNode
,
345 MavenConventionsUtils
.artifactFileName(artifact
), bytes
);
348 private RepoUtils() {
351 /** If a source return the base bundle name, does not change otherwise */
352 public static String
extractBundleNameFromSourceName(String sourceBundleName
) {
353 if (sourceBundleName
.endsWith(".source"))
354 return sourceBundleName
.substring(0, sourceBundleName
.length()
355 - ".source".length());
357 return sourceBundleName
;
361 * SOFTWARE REPOSITORIES
364 /** Retrieve repository based on information in the repo node */
365 public static Repository
getRepository(RepositoryFactory repositoryFactory
,
366 Keyring keyring
, Node repoNode
) {
368 Repository repository
;
369 if (repoNode
.isNodeType(ArgeoTypes
.ARGEO_REMOTE_REPOSITORY
)) {
370 String uri
= repoNode
.getProperty(ARGEO_URI
).getString();
371 if (uri
.startsWith("http")) {// http, https
372 repository
= ArgeoJcrUtils
.getRepositoryByUri(
373 repositoryFactory
, uri
);
374 } else if (uri
.startsWith("vm:")) {// alias
375 repository
= ArgeoJcrUtils
.getRepositoryByUri(
376 repositoryFactory
, uri
);
378 throw new SlcException("Unsupported repository uri " + uri
);
382 throw new SlcException("Unsupported node type " + repoNode
);
384 } catch (RepositoryException e
) {
385 throw new SlcException("Cannot connect to repository " + repoNode
,
391 * Reads credentials from node, using keyring if there is a password. Cann
392 * return null if no credentials needed (local repo) at all, but returns
393 * {@link GuestCredentials} if user id is 'anonymous' .
395 public static Credentials
getRepositoryCredentials(Keyring keyring
,
398 if (repoNode
.isNodeType(ArgeoTypes
.ARGEO_REMOTE_REPOSITORY
)) {
399 if (!repoNode
.hasProperty(ARGEO_USER_ID
))
402 String userId
= repoNode
.getProperty(ARGEO_USER_ID
).getString();
403 if (userId
.equals("anonymous"))// FIXME hardcoded userId
404 return new GuestCredentials();
405 char[] password
= keyring
.getAsChars(repoNode
.getPath() + '/'
407 Credentials credentials
= new SimpleCredentials(userId
,
411 throw new SlcException("Unsupported node type " + repoNode
);
413 } catch (RepositoryException e
) {
414 throw new SlcException("Cannot connect to repository " + repoNode
,
420 * Write group indexes: 'binaries' lists all bundles and their versions,
421 * 'sources' list theire sources, and 'sdk' aggregates both.
423 public static void writeGroupIndexes(Session session
,
424 String artifactBasePath
, String groupId
, String version
,
425 Set
<Artifact
> binaries
, Set
<Artifact
> sources
) {
427 Set
<Artifact
> indexes
= new TreeSet
<Artifact
>(
428 new ArtifactIdComparator());
429 Artifact binariesArtifact
= writeIndex(session
, artifactBasePath
,
430 groupId
, RepoConstants
.BINARIES_ARTIFACT_ID
, version
,
432 indexes
.add(binariesArtifact
);
433 if (sources
!= null) {
434 Artifact sourcesArtifact
= writeIndex(session
,
435 artifactBasePath
, groupId
,
436 RepoConstants
.SOURCES_ARTIFACT_ID
, version
, sources
);
437 indexes
.add(sourcesArtifact
);
440 writeIndex(session
, artifactBasePath
, groupId
,
441 RepoConstants
.SDK_ARTIFACT_ID
, version
, indexes
);
443 } catch (RepositoryException e
) {
444 throw new SlcException("Cannot write indexes for group " + groupId
,
449 /** Write a group index. */
450 private static Artifact
writeIndex(Session session
,
451 String artifactBasePath
, String groupId
, String artifactId
,
452 String version
, Set
<Artifact
> artifacts
) throws RepositoryException
{
453 Artifact artifact
= new DefaultArtifact(groupId
, artifactId
, "pom",
455 String pom
= MavenConventionsUtils
.artifactsAsDependencyPom(artifact
,
457 Node node
= RepoUtils
.copyBytesAsArtifact(
458 session
.getNode(artifactBasePath
), artifact
, pom
.getBytes());
459 addMavenChecksums(node
);
463 /** Add files containing the SHA-1 and MD5 checksums. */
464 public static void addMavenChecksums(Node node
) throws RepositoryException
{
466 String sha
= JcrUtils
.checksumFile(node
, "SHA-1");
467 JcrUtils
.copyBytesAsFile(node
.getParent(), node
.getName() + ".sha1",
469 String md5
= JcrUtils
.checksumFile(node
, "MD5");
470 JcrUtils
.copyBytesAsFile(node
.getParent(), node
.getName() + ".md5",
475 * Custom copy since the one in commons does not fit the needs when copying
476 * a workspace completely.
478 public static void copy(Node fromNode
, Node toNode
) {
480 if (log
.isDebugEnabled())
481 log
.debug("copy node :" + fromNode
.getPath());
483 // FIXME : small hack to enable specific workspace copy
484 if (fromNode
.isNodeType("rep:ACL")
485 || fromNode
.isNodeType("rep:system")) {
486 if (log
.isTraceEnabled())
487 log
.trace("node " + fromNode
+ " skipped");
492 for (NodeType mixinType
: fromNode
.getMixinNodeTypes()) {
493 toNode
.addMixin(mixinType
.getName());
497 for (NodeType mixinType
: toNode
.getMixinNodeTypes()) {
498 if (log
.isDebugEnabled())
499 log
.debug(mixinType
.getName());
502 // process properties
503 PropertyIterator pit
= fromNode
.getProperties();
504 properties
: while (pit
.hasNext()) {
505 Property fromProperty
= pit
.nextProperty();
506 String propName
= fromProperty
.getName();
508 String propertyName
= fromProperty
.getName();
509 if (toNode
.hasProperty(propertyName
)
510 && toNode
.getProperty(propertyName
).getDefinition()
514 if (fromProperty
.getDefinition().isProtected())
517 if (propertyName
.equals("jcr:created")
518 || propertyName
.equals("jcr:createdBy")
519 || propertyName
.equals("jcr:lastModified")
520 || propertyName
.equals("jcr:lastModifiedBy"))
523 if (fromProperty
.isMultiple()) {
524 toNode
.setProperty(propertyName
,
525 fromProperty
.getValues());
527 toNode
.setProperty(propertyName
,
528 fromProperty
.getValue());
530 } catch (RepositoryException e
) {
531 throw new SlcException("Cannot property " + propName
, e
);
535 // recursively process children nodes
536 NodeIterator nit
= fromNode
.getNodes();
537 while (nit
.hasNext()) {
538 Node fromChild
= nit
.nextNode();
539 Integer index
= fromChild
.getIndex();
540 String nodeRelPath
= fromChild
.getName() + "[" + index
+ "]";
542 if (toNode
.hasNode(nodeRelPath
))
543 toChild
= toNode
.getNode(nodeRelPath
);
545 toChild
= toNode
.addNode(fromChild
.getName(), fromChild
546 .getPrimaryNodeType().getName());
547 copy(fromChild
, toChild
);
550 // update jcr:lastModified and jcr:lastModifiedBy in toNode in
553 if (!toNode
.getDefinition().isProtected()
554 && toNode
.isNodeType(NodeType
.MIX_LAST_MODIFIED
))
555 JcrUtils
.updateLastModified(toNode
);
557 // Workaround to reduce session size: artifact is a saveable
559 if (toNode
.isNodeType(SlcTypes
.SLC_ARTIFACT
))
560 toNode
.getSession().save();
562 } catch (RepositoryException e
) {
563 throw new SlcException("Cannot copy " + fromNode
+ " to " + toNode
,