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
.ArgeoMonitor
;
54 import org
.argeo
.jcr
.ArgeoJcrUtils
;
55 import org
.argeo
.jcr
.ArgeoNames
;
56 import org
.argeo
.jcr
.ArgeoTypes
;
57 import org
.argeo
.jcr
.JcrUtils
;
58 import org
.argeo
.slc
.DefaultNameVersion
;
59 import org
.argeo
.slc
.NameVersion
;
60 import org
.argeo
.slc
.SlcException
;
61 import org
.argeo
.slc
.aether
.ArtifactIdComparator
;
62 import org
.argeo
.slc
.jcr
.SlcNames
;
63 import org
.argeo
.slc
.jcr
.SlcTypes
;
64 import org
.argeo
.slc
.repo
.maven
.MavenConventionsUtils
;
65 import org
.argeo
.util
.security
.Keyring
;
66 import org
.osgi
.framework
.Constants
;
67 import org
.sonatype
.aether
.artifact
.Artifact
;
68 import org
.sonatype
.aether
.util
.artifact
.DefaultArtifact
;
70 /** Utilities around repo */
71 public class RepoUtils
implements ArgeoNames
, SlcNames
{
72 private final static Log log
= LogFactory
.getLog(RepoUtils
.class);
74 /** Packages a regular sources jar as PDE source. */
75 public static void packagesAsPdeSource(File sourceFile
,
76 NameVersion nameVersion
, OutputStream out
) throws IOException
{
77 if (isAlreadyPdeSource(sourceFile
)) {
78 FileInputStream in
= new FileInputStream(sourceFile
);
79 IOUtils
.copy(in
, out
);
80 IOUtils
.closeQuietly(in
);
82 String sourceSymbolicName
= nameVersion
.getName() + ".source";
84 Manifest sourceManifest
= null;
85 sourceManifest
= new Manifest();
86 sourceManifest
.getMainAttributes().put(
87 Attributes
.Name
.MANIFEST_VERSION
, "1.0");
88 sourceManifest
.getMainAttributes().putValue("Bundle-SymbolicName",
90 sourceManifest
.getMainAttributes().putValue("Bundle-Version",
91 nameVersion
.getVersion());
92 sourceManifest
.getMainAttributes().putValue(
93 "Eclipse-SourceBundle",
94 nameVersion
.getName() + ";version="
95 + nameVersion
.getVersion());
96 copyJar(sourceFile
, out
, sourceManifest
);
100 public static byte[] packageAsPdeSource(InputStream sourceJar
,
101 NameVersion nameVersion
) {
102 String sourceSymbolicName
= nameVersion
.getName() + ".source";
104 Manifest sourceManifest
= null;
105 sourceManifest
= new Manifest();
106 sourceManifest
.getMainAttributes().put(
107 Attributes
.Name
.MANIFEST_VERSION
, "1.0");
108 sourceManifest
.getMainAttributes().putValue("Bundle-SymbolicName",
110 sourceManifest
.getMainAttributes().putValue("Bundle-Version",
111 nameVersion
.getVersion());
112 sourceManifest
.getMainAttributes().putValue("Eclipse-SourceBundle",
113 nameVersion
.getName() + ";version=" + nameVersion
.getVersion());
115 return modifyManifest(sourceJar
, sourceManifest
);
119 * Check whether the file as already been packaged as PDE source, in order
120 * not to mess with Jar signing
122 private static boolean isAlreadyPdeSource(File sourceFile
) {
123 JarInputStream jarInputStream
= null;
126 jarInputStream
= new JarInputStream(new FileInputStream(sourceFile
));
128 Manifest manifest
= jarInputStream
.getManifest();
129 Iterator
<?
> it
= manifest
.getMainAttributes().keySet().iterator();
131 // containsKey() does not work, iterating...
133 if (it
.next().toString().equals("Eclipse-SourceBundle")) {
137 // boolean res = manifest.getMainAttributes().get(
138 // "Eclipse-SourceBundle") != null;
140 log
.info(sourceFile
+ " is already a PDE source");
142 } catch (Exception e
) {
143 // probably not a jar, skipping
144 if (log
.isDebugEnabled())
145 log
.debug("Skipping " + sourceFile
+ " because of "
149 IOUtils
.closeQuietly(jarInputStream
);
154 * Copy a jar, replacing its manifest with the provided one
159 private static void copyJar(File source
, OutputStream out
, Manifest manifest
)
161 JarFile sourceJar
= null;
162 JarOutputStream output
= null;
164 output
= manifest
!= null ?
new JarOutputStream(out
, manifest
)
165 : new JarOutputStream(out
);
166 sourceJar
= new JarFile(source
);
168 entries
: for (Enumeration
<?
> entries
= sourceJar
.entries(); entries
169 .hasMoreElements();) {
170 JarEntry entry
= (JarEntry
) entries
.nextElement();
172 && entry
.getName().equals("META-INF/MANIFEST.MF"))
175 InputStream entryStream
= sourceJar
.getInputStream(entry
);
176 JarEntry newEntry
= new JarEntry(entry
.getName());
177 // newEntry.setMethod(JarEntry.DEFLATED);
178 output
.putNextEntry(newEntry
);
179 IOUtils
.copy(entryStream
, output
);
182 IOUtils
.closeQuietly(output
);
184 if (sourceJar
!= null)
186 } catch (IOException e
) {
192 /** Copy a jar changing onlythe manifest */
193 public static void copyJar(InputStream in
, OutputStream out
,
195 JarInputStream jarIn
= null;
196 JarOutputStream jarOut
= null;
198 jarIn
= new JarInputStream(in
);
199 jarOut
= new JarOutputStream(out
, manifest
);
200 JarEntry jarEntry
= null;
201 while ((jarEntry
= jarIn
.getNextJarEntry()) != null) {
202 jarOut
.putNextEntry(jarEntry
);
203 IOUtils
.copy(jarIn
, jarOut
);
207 } catch (IOException e
) {
208 throw new SlcException("Could not copy jar with MANIFEST "
209 + manifest
.getMainAttributes(), e
);
211 IOUtils
.closeQuietly(jarIn
);
212 IOUtils
.closeQuietly(jarOut
);
216 /** Reads a jar file, modify its manifest */
217 public static byte[] modifyManifest(InputStream in
, Manifest manifest
) {
218 ByteArrayOutputStream out
= new ByteArrayOutputStream(200 * 1024);
220 copyJar(in
, out
, manifest
);
221 return out
.toByteArray();
223 IOUtils
.closeQuietly(out
);
227 /** Read the OSGi {@link NameVersion} */
228 public static NameVersion
readNameVersion(Artifact artifact
) {
229 File artifactFile
= artifact
.getFile();
230 if (artifact
.getExtension().equals("pom")) {
231 // hack to process jars which weirdly appear as POMs
232 File jarFile
= new File(artifactFile
.getParentFile(),
233 FilenameUtils
.getBaseName(artifactFile
.getPath()) + ".jar");
234 if (jarFile
.exists()) {
235 log
.warn("Use " + jarFile
+ " instead of " + artifactFile
236 + " for " + artifact
);
237 artifactFile
= jarFile
;
240 return readNameVersion(artifactFile
);
243 /** Read the OSGi {@link NameVersion} */
244 public static NameVersion
readNameVersion(File artifactFile
) {
246 return readNameVersion(new FileInputStream(artifactFile
));
247 } catch (Exception e
) {
248 // probably not a jar, skipping
249 if (log
.isDebugEnabled()) {
250 log
.debug("Skipping " + artifactFile
+ " because of " + e
);
251 // e.printStackTrace();
257 /** Read the OSGi {@link NameVersion} */
258 public static NameVersion
readNameVersion(InputStream in
) {
259 JarInputStream jarInputStream
= null;
261 jarInputStream
= new JarInputStream(in
);
262 return readNameVersion(jarInputStream
.getManifest());
263 } catch (Exception e
) {
264 // probably not a jar, skipping
265 if (log
.isDebugEnabled()) {
266 log
.debug("Skipping because of " + e
);
270 IOUtils
.closeQuietly(jarInputStream
);
275 /** Read the OSGi {@link NameVersion} */
276 public static NameVersion
readNameVersion(Manifest manifest
) {
277 DefaultNameVersion nameVersion
= new DefaultNameVersion();
278 nameVersion
.setName(manifest
.getMainAttributes().getValue(
279 Constants
.BUNDLE_SYMBOLICNAME
));
281 // Skip additional specs such as
283 if (nameVersion
.getName().indexOf(';') > -1) {
285 .setName(new StringTokenizer(nameVersion
.getName(), " ;")
289 nameVersion
.setVersion(manifest
.getMainAttributes().getValue(
290 Constants
.BUNDLE_VERSION
));
298 /** The artifact described by this node */
299 public static Artifact
asArtifact(Node node
) throws RepositoryException
{
300 if (node
.isNodeType(SlcTypes
.SLC_ARTIFACT_VERSION_BASE
)) {
301 // FIXME update data model to store packaging at this level
302 String extension
= "jar";
303 return new DefaultArtifact(node
.getProperty(SLC_GROUP_ID
)
305 node
.getProperty(SLC_ARTIFACT_ID
).getString(), extension
,
306 node
.getProperty(SLC_ARTIFACT_VERSION
).getString());
307 } else if (node
.isNodeType(SlcTypes
.SLC_ARTIFACT
)) {
308 return new DefaultArtifact(node
.getProperty(SLC_GROUP_ID
)
310 node
.getProperty(SLC_ARTIFACT_ID
).getString(), node
311 .getProperty(SLC_ARTIFACT_CLASSIFIER
).getString(),
312 node
.getProperty(SLC_ARTIFACT_EXTENSION
).getString(), node
313 .getProperty(SLC_ARTIFACT_VERSION
).getString());
315 throw new SlcException("Unsupported node type for " + node
);
320 * The path to the PDE source related to this artifact (or artifact version
321 * base). There may or there may not be a node at this location (the
322 * returned path will typically be used to test whether PDE sources are
323 * attached to this artifact).
325 public static String
relatedPdeSourcePath(String artifactBasePath
,
326 Node artifactNode
) throws RepositoryException
{
327 Artifact artifact
= asArtifact(artifactNode
);
328 Artifact pdeSourceArtifact
= new DefaultArtifact(artifact
.getGroupId(),
329 artifact
.getArtifactId() + ".source", artifact
.getExtension(),
330 artifact
.getVersion());
331 return MavenConventionsUtils
.artifactPath(artifactBasePath
,
336 * Copy this bytes array as an artifact, relative to the root of the
337 * repository (typically the workspace root node)
339 public static Node
copyBytesAsArtifact(Node artifactsBase
,
340 Artifact artifact
, byte[] bytes
) throws RepositoryException
{
341 String parentPath
= MavenConventionsUtils
.artifactParentPath(
342 artifactsBase
.getPath(), artifact
);
343 Node folderNode
= JcrUtils
.mkfolders(artifactsBase
.getSession(),
345 return JcrUtils
.copyBytesAsFile(folderNode
,
346 MavenConventionsUtils
.artifactFileName(artifact
), bytes
);
349 private RepoUtils() {
352 /** If a source return the base bundle name, does not change otherwise */
353 public static String
extractBundleNameFromSourceName(String sourceBundleName
) {
354 if (sourceBundleName
.endsWith(".source"))
355 return sourceBundleName
.substring(0, sourceBundleName
.length()
356 - ".source".length());
358 return sourceBundleName
;
362 * SOFTWARE REPOSITORIES
365 /** Retrieve repository based on information in the repo node */
366 public static Repository
getRepository(RepositoryFactory repositoryFactory
,
367 Keyring keyring
, Node repoNode
) {
369 Repository repository
;
370 if (repoNode
.isNodeType(ArgeoTypes
.ARGEO_REMOTE_REPOSITORY
)) {
371 String uri
= repoNode
.getProperty(ARGEO_URI
).getString();
372 if (uri
.startsWith("http")) {// http, https
373 repository
= ArgeoJcrUtils
.getRepositoryByUri(
374 repositoryFactory
, uri
);
375 } else if (uri
.startsWith("vm:")) {// alias
376 repository
= ArgeoJcrUtils
.getRepositoryByUri(
377 repositoryFactory
, uri
);
379 throw new SlcException("Unsupported repository uri " + uri
);
383 throw new SlcException("Unsupported node type " + repoNode
);
385 } catch (RepositoryException e
) {
386 throw new SlcException("Cannot connect to repository " + repoNode
,
392 * Reads credentials from node, using keyring if there is a password. Can
393 * return null if no credentials needed (local repo) at all, but returns
394 * {@link GuestCredentials} if user id is 'anonymous' .
396 public static Credentials
getRepositoryCredentials(Keyring keyring
,
399 if (repoNode
.isNodeType(ArgeoTypes
.ARGEO_REMOTE_REPOSITORY
)) {
400 if (!repoNode
.hasProperty(ARGEO_USER_ID
))
403 String userId
= repoNode
.getProperty(ARGEO_USER_ID
).getString();
404 if (userId
.equals("anonymous"))// FIXME hardcoded userId
405 return new GuestCredentials();
406 char[] password
= keyring
.getAsChars(repoNode
.getPath() + '/'
408 Credentials credentials
= new SimpleCredentials(userId
,
412 throw new SlcException("Unsupported node type " + repoNode
);
414 } catch (RepositoryException e
) {
415 throw new SlcException("Cannot connect to repository " + repoNode
,
421 * Shortcut to retrieve a session given variable information: Handle the
422 * case where we only have an URI of the repository, that we want to connect
423 * as anonymous or the case of a identified connexion to a local or remote
426 * Callers must close the session once it has been used
428 public static Session
getCorrespondingSession(
429 RepositoryFactory repositoryFactory
, Keyring keyring
,
430 Node repoNode
, String uri
, String workspaceName
) {
432 if (repoNode
== null && uri
== null)
433 throw new SlcException(
434 "At least one of repoNode and uri must be defined");
435 Repository currRepo
= null;
436 Credentials credentials
= null;
437 // Anonymous URI only workspace
438 if (repoNode
== null)
440 currRepo
= ArgeoJcrUtils
.getRepositoryByUri(repositoryFactory
,
443 currRepo
= RepoUtils
.getRepository(repositoryFactory
, keyring
,
445 credentials
= RepoUtils
.getRepositoryCredentials(keyring
,
448 return currRepo
.login(credentials
, workspaceName
);
449 } catch (RepositoryException e
) {
450 throw new SlcException("Cannot connect to workspace "
451 + workspaceName
+ " of repository " + repoNode
452 + " with URI " + uri
, e
);
457 * Write group indexes: 'binaries' lists all bundles and their versions,
458 * 'sources' list theire sources, and 'sdk' aggregates both.
460 public static void writeGroupIndexes(Session session
,
461 String artifactBasePath
, String groupId
, String version
,
462 Set
<Artifact
> binaries
, Set
<Artifact
> sources
) {
464 Set
<Artifact
> indexes
= new TreeSet
<Artifact
>(
465 new ArtifactIdComparator());
466 Artifact binariesArtifact
= writeIndex(session
, artifactBasePath
,
467 groupId
, RepoConstants
.BINARIES_ARTIFACT_ID
, version
,
469 indexes
.add(binariesArtifact
);
470 if (sources
!= null) {
471 Artifact sourcesArtifact
= writeIndex(session
,
472 artifactBasePath
, groupId
,
473 RepoConstants
.SOURCES_ARTIFACT_ID
, version
, sources
);
474 indexes
.add(sourcesArtifact
);
477 writeIndex(session
, artifactBasePath
, groupId
,
478 RepoConstants
.SDK_ARTIFACT_ID
, version
, indexes
);
480 } catch (RepositoryException e
) {
481 throw new SlcException("Cannot write indexes for group " + groupId
,
486 /** Write a group index. */
487 private static Artifact
writeIndex(Session session
,
488 String artifactBasePath
, String groupId
, String artifactId
,
489 String version
, Set
<Artifact
> artifacts
) throws RepositoryException
{
490 Artifact artifact
= new DefaultArtifact(groupId
, artifactId
, "pom",
492 String pom
= MavenConventionsUtils
.artifactsAsDependencyPom(artifact
,
494 Node node
= RepoUtils
.copyBytesAsArtifact(
495 session
.getNode(artifactBasePath
), artifact
, pom
.getBytes());
496 addMavenChecksums(node
);
500 /** Add files containing the SHA-1 and MD5 checksums. */
501 public static void addMavenChecksums(Node node
) throws RepositoryException
{
503 String sha
= JcrUtils
.checksumFile(node
, "SHA-1");
504 JcrUtils
.copyBytesAsFile(node
.getParent(), node
.getName() + ".sha1",
506 String md5
= JcrUtils
.checksumFile(node
, "MD5");
507 JcrUtils
.copyBytesAsFile(node
.getParent(), node
.getName() + ".md5",
512 * Custom copy since the one in commons does not fit the needs when copying
513 * a workspace completely.
515 public static void copy(Node fromNode
, Node toNode
) {
516 copy(fromNode
, toNode
, null);
519 public static void copy(Node fromNode
, Node toNode
, ArgeoMonitor monitor
) {
521 String fromPath
= fromNode
.getPath();
523 monitor
.subTask("copying node :" + fromPath
);
524 if (log
.isDebugEnabled())
525 log
.debug("copy node :" + fromPath
);
527 // FIXME : small hack to enable specific workspace copy
528 if (fromNode
.isNodeType("rep:ACL")
529 || fromNode
.isNodeType("rep:system")) {
530 if (log
.isTraceEnabled())
531 log
.trace("node " + fromNode
+ " skipped");
536 for (NodeType mixinType
: fromNode
.getMixinNodeTypes()) {
537 toNode
.addMixin(mixinType
.getName());
541 for (NodeType mixinType
: toNode
.getMixinNodeTypes()) {
542 if (log
.isDebugEnabled())
543 log
.debug(mixinType
.getName());
546 // process properties
547 PropertyIterator pit
= fromNode
.getProperties();
548 properties
: while (pit
.hasNext()) {
549 Property fromProperty
= pit
.nextProperty();
550 String propName
= fromProperty
.getName();
552 String propertyName
= fromProperty
.getName();
553 if (toNode
.hasProperty(propertyName
)
554 && toNode
.getProperty(propertyName
).getDefinition()
558 if (fromProperty
.getDefinition().isProtected())
561 if (propertyName
.equals("jcr:created")
562 || propertyName
.equals("jcr:createdBy")
563 || propertyName
.equals("jcr:lastModified")
564 || propertyName
.equals("jcr:lastModifiedBy"))
567 if (fromProperty
.isMultiple()) {
568 toNode
.setProperty(propertyName
,
569 fromProperty
.getValues());
571 toNode
.setProperty(propertyName
,
572 fromProperty
.getValue());
574 } catch (RepositoryException e
) {
575 throw new SlcException("Cannot property " + propName
, e
);
579 // recursively process children nodes
580 NodeIterator nit
= fromNode
.getNodes();
581 while (nit
.hasNext()) {
582 Node fromChild
= nit
.nextNode();
583 Integer index
= fromChild
.getIndex();
584 String nodeRelPath
= fromChild
.getName() + "[" + index
+ "]";
586 if (toNode
.hasNode(nodeRelPath
))
587 toChild
= toNode
.getNode(nodeRelPath
);
589 toChild
= toNode
.addNode(fromChild
.getName(), fromChild
590 .getPrimaryNodeType().getName());
591 copy(fromChild
, toChild
);
594 // update jcr:lastModified and jcr:lastModifiedBy in toNode in
597 if (!toNode
.getDefinition().isProtected()
598 && toNode
.isNodeType(NodeType
.MIX_LAST_MODIFIED
))
599 JcrUtils
.updateLastModified(toNode
);
601 // Workaround to reduce session size: artifact is a saveable
603 if (toNode
.isNodeType(SlcTypes
.SLC_ARTIFACT
))
604 toNode
.getSession().save();
609 } catch (RepositoryException e
) {
610 throw new SlcException("Cannot copy " + fromNode
+ " to " + toNode
,