KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > mavenplugins > car > InstallModulesMojo


1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements. See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership. The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License. You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied. See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */

19
20 package org.apache.geronimo.mavenplugins.car;
21
22 import org.apache.geronimo.kernel.config.InvalidConfigException;
23 import org.apache.geronimo.kernel.config.NoSuchConfigException;
24 import org.apache.geronimo.kernel.config.ConfigurationData;
25 import org.apache.geronimo.kernel.repository.Artifact;
26 import org.apache.geronimo.kernel.repository.ArtifactManager;
27 import org.apache.geronimo.kernel.repository.ArtifactResolver;
28 import org.apache.geronimo.kernel.repository.DefaultArtifactManager;
29 import org.apache.geronimo.kernel.repository.Environment;
30 import org.apache.geronimo.kernel.repository.FileWriteMonitor;
31 import org.apache.geronimo.kernel.repository.Dependency;
32 import org.apache.geronimo.kernel.repository.WritableListableRepository;
33 import org.apache.geronimo.kernel.repository.Repository;
34 import org.apache.geronimo.system.repository.Maven2Repository;
35 import org.apache.geronimo.system.configuration.RepositoryConfigurationStore;
36 import org.apache.geronimo.system.resolver.ExplicitDefaultArtifactResolver;
37 import org.apache.geronimo.genesis.dependency.DependencyTree;
38
39 import org.apache.maven.artifact.repository.ArtifactRepository;
40
41 import java.io.File JavaDoc;
42 import java.io.FileInputStream JavaDoc;
43 import java.io.IOException JavaDoc;
44 import java.io.InputStream JavaDoc;
45 import java.io.BufferedInputStream JavaDoc;
46 import java.io.BufferedReader JavaDoc;
47 import java.io.FileReader JavaDoc;
48 import java.io.InputStreamReader JavaDoc;
49
50 import java.util.Iterator JavaDoc;
51 import java.util.HashSet JavaDoc;
52 import java.util.LinkedHashSet JavaDoc;
53 import java.util.Set JavaDoc;
54 import java.util.Collections JavaDoc;
55 import java.util.HashMap JavaDoc;
56 import java.util.zip.ZipEntry JavaDoc;
57 import java.util.jar.JarFile JavaDoc;
58
59 import org.codehaus.plexus.util.FileUtils;
60
61 /**
62  * Installs Geronimo module CAR files into a target repository to support assembly.
63  *
64  * @version $Rev: 480326 $ $Date: 2006-11-28 20:48:06 -0500 (Tue, 28 Nov 2006) $
65  * @goal install-modules
66  */

67 public class InstallModulesMojo
68         extends AbstractCarMojo {
69     /**
70      * The location of the target repository.
71      *
72      * @parameter expression="${project.build.directory}/repository"
73      * @required
74      */

75     private File JavaDoc targetRepositoryDirectory = null;
76
77     /**
78      * Configuration to be installed specified as groupId/artifactId/version/type
79      * if none specified, plugin will install all dependencies of type "car"
80      *
81      * @parameter
82      * @optional
83      */

84     private String JavaDoc artifact = null;
85
86     /**
87      * Location of the source repository for the dependencies
88      *
89      * @parameter expression="${localRepository}"
90      * @required
91      */

92     private ArtifactRepository sourceRepository = null;
93
94     /**
95      * The location where the properties mapping will be generated.
96      *
97      * @parameter expression="${project.build.directory}/explicit-versions.properties"
98      * @required
99      */

100     private File JavaDoc explicitResolutionProperties = null;
101
102     /**
103      * The Geronimo repository artifact resolver.
104      * <p/>
105      * <p/>
106      * Using a custom name here to prevent problems that happen when Plexus
107      * injects the Maven resolver into the base-class.
108      * </p>
109      */

110     private ArtifactResolver geronimoArtifactResolver;
111
112     private WritableListableRepository targetRepo;
113
114     private RepositoryConfigurationStore targetStore;
115
116     private WritableListableRepository sourceRepo;
117
118     private RepositoryConfigurationStore sourceStore;
119
120     /**
121      * Set of artifacts which have already been installed, so we can skip any processing.
122      */

123     private Set JavaDoc installedArtifacts = new HashSet JavaDoc();
124
125     protected void doExecute() throws Exception JavaDoc {
126         DependencyTree dependencies = dependencyHelper.getDependencies(project);
127         generateExplicitVersionProperties(explicitResolutionProperties, dependencies);
128
129         //
130
// TODO: Check if we need to use the Maven2RepositoryAdapter here or not...
131
//
132

133         Maven2RepositoryAdapter.ArtifactLookup lookup = new ArtifactLookupImpl(new HashMap JavaDoc());
134         sourceRepo = new Maven2RepositoryAdapter(dependencies, lookup);
135 // sourceRepo = new Maven2RepositoryAdapter(new File(sourceRepository.getBasedir()));
136
sourceStore = new RepositoryConfigurationStore(sourceRepo);
137
138         FileUtils.forceMkdir(targetRepositoryDirectory);
139
140         targetRepo = new Maven2Repository(targetRepositoryDirectory);
141         targetStore = new RepositoryConfigurationStore(targetRepo);
142
143         ArtifactManager artifactManager = new DefaultArtifactManager();
144         geronimoArtifactResolver = new ExplicitDefaultArtifactResolver(
145                 explicitResolutionProperties.getPath(),
146                 artifactManager,
147                 Collections.singleton(sourceRepo),
148                 null);
149
150         if (artifact != null) {
151             install(Artifact.create(artifact));
152         } else {
153             Iterator JavaDoc iter = getDependencies().iterator();
154             while (iter.hasNext()) {
155
156                 Artifact artifact = mavenToGeronimoArtifact((org.apache.maven.artifact.Artifact) iter.next());
157                 if (isModuleArtifact(artifact)) {
158                     install(artifact);
159                 }
160             }
161         }
162     }
163
164     /**
165      * Retrieves all artifact dependencies.
166      *
167      * @return A HashSet of artifacts
168      */

169     protected Set JavaDoc getDependencies() {
170         Set JavaDoc dependenciesSet = new HashSet JavaDoc();
171
172         org.apache.maven.artifact.Artifact artifact = project.getArtifact();
173         if (artifact != null && artifact.getFile() != null) {
174             dependenciesSet.add(artifact);
175         }
176
177         Set JavaDoc projectArtifacts = project.getArtifacts();
178         if (projectArtifacts != null) {
179             dependenciesSet.addAll(projectArtifacts);
180         }
181
182         return dependenciesSet;
183     }
184
185     /**
186      * Install the given artifact into the target Geronimo repository.
187      *
188      * @param artifact The artifact to be installed; must not be null
189      * @throws Exception Failed to install artifact
190      */

191     private void install(final Artifact artifact) throws Exception JavaDoc {
192         assert artifact != null;
193
194         if (installedArtifacts.contains(artifact)) {
195             log.debug("Skipping artifact; already installed: " + artifact);
196         } else {
197             // The artifact must exist in the source repository
198
if (!sourceRepo.contains(artifact)) {
199                 throw new Exception JavaDoc("Missing artifact in source repository: " + artifact);
200             }
201
202             if (isModuleArtifact(artifact)) {
203                 installModule(artifact);
204             } else {
205                 installDependency(artifact);
206             }
207         }
208     }
209
210     /**
211      * Install a Geornimo module artifact.
212      *
213      * @param artifact The Geronimo module artifact to be installed; must not be null, must be a module
214      * @throws Exception Failed to insall Geronimo module artifact
215      */

216     private void installModule(final Artifact artifact) throws Exception JavaDoc {
217         assert artifact != null;
218         assert isModuleArtifact(artifact);
219
220         boolean install = true;
221
222         // The source store must contain the module artifact
223
if (!sourceStore.containsConfiguration(artifact)) {
224             throw new Exception JavaDoc("Missing module artifact in source repository: " + artifact);
225         }
226
227         // If the target store already contains the module, check if we need to reinstall it
228
if (targetStore.containsConfiguration(artifact)) {
229             if (hasModuleChanged(artifact)) {
230                 log.debug("Old module exists in target store; uninstalling: " + artifact);
231                 targetStore.uninstall(artifact);
232             } else {
233                 log.debug("Same module exists in target store; skipping: " + artifact);
234                 install = false;
235             }
236         }
237
238         // Copy the configuration into the target configuration store
239
if (install) {
240             log.info("Installing module: " + artifact);
241
242             File JavaDoc file = sourceRepo.getLocation(artifact);
243             InputStream JavaDoc input = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(file));
244
245             try {
246                 FileWriteMonitor monitor = new FileWriteMonitor() {
247                     public void writeStarted(final String JavaDoc file, final int bytes) {
248                         log.debug("Installing module: " + file + " (" + bytes + " bytes)");
249                     }
250
251                     public void writeProgress(int bytes) {
252                         // empty
253
}
254
255                     public void writeComplete(int bytes) {
256                         // empty
257
}
258                 };
259
260                 targetStore.install(input, (int) file.length(), artifact, monitor);
261
262                 installedArtifacts.add(artifact);
263             }
264             finally {
265                 input.close();
266             }
267         }
268
269         // Install all dependencies of this module
270
installModuleDependencies(artifact);
271     }
272
273     /**
274      * Install all of the dependencies of the given Geronimo module artifact.
275      *
276      * @param artifact The Geronimo module artifact to be installed; must not be null, must be a module
277      * @throws Exception Failed to install Geronimo module dependencies
278      */

279     private void installModuleDependencies(final Artifact artifact) throws Exception JavaDoc {
280         assert artifact != null;
281         assert isModuleArtifact(artifact);
282
283         log.debug("Installing module dependencies for artifact: " + artifact);
284
285         try {
286             ConfigurationData config = targetStore.loadConfiguration(artifact);
287             Environment env = config.getEnvironment();
288             LinkedHashSet JavaDoc deps = new LinkedHashSet JavaDoc();
289
290             Iterator JavaDoc iter = env.getDependencies().iterator();
291             while (iter.hasNext()) {
292                 Dependency dep = (Dependency) iter.next();
293                 deps.add(dep.getArtifact());
294             }
295
296             installDependencies(deps);
297         }
298         catch (IOException JavaDoc e) {
299             throw new InvalidConfigException("Unable to load module: " + artifact, e);
300         }
301         catch (NoSuchConfigException e) {
302             throw new InvalidConfigException("Unable to load module: " + artifact, e);
303         }
304     }
305
306     /**
307      * Install a dependency artifact into the Geronimo repository.
308      *
309      * @param artifact The artifact to be installed; must not be null, or a module artifact
310      * @throws Exception Failed to install artifact dependencies
311      */

312     private void installDependency(final Artifact artifact) throws Exception JavaDoc {
313         assert artifact != null;
314         assert !isModuleArtifact(artifact);
315
316         boolean install = true;
317
318         // If the dep already exists, then check if we need to reinstall it
319
if (targetRepo.contains(artifact)) {
320             if (hasDependencyChanged(artifact)) {
321                 File JavaDoc file = targetRepo.getLocation(artifact);
322                 log.debug("Old dependency exists in target repo; deleting: " + file);
323                 FileUtils.forceDelete(file);
324             } else {
325                 log.debug("Same dependency exists in target repo; skipping: " + artifact);
326                 install = false;
327             }
328         }
329
330         if (install) {
331             log.info("Installing dependency: " + artifact);
332
333             // Copy the artifact into the target repo
334
File JavaDoc file = sourceRepo.getLocation(artifact);
335             InputStream JavaDoc input = new BufferedInputStream JavaDoc(new FileInputStream JavaDoc(file));
336             try {
337                 FileWriteMonitor monitor = new FileWriteMonitor() {
338                     public void writeStarted(final String JavaDoc file, final int bytes) {
339                         log.debug("Copying dependency: " + file + " (" + bytes + " bytes)");
340                     }
341
342                     public void writeProgress(int bytes) {
343                         // empty
344
}
345
346                     public void writeComplete(int bytes) {
347                         // empty
348
}
349                 };
350
351                 targetRepo.copyToRepository(input, (int) file.length(), artifact, monitor);
352
353                 installedArtifacts.add(artifact);
354             }
355             finally {
356                 input.close();
357             }
358         }
359
360         // Install all dependencies of this artifact
361
installDependencies(sourceRepo.getDependencies(artifact));
362     }
363
364     /**
365      * Install a set of dependency artifacts into the Geronimo repository.
366      *
367      * @param dependencies The set of artifacts to be installed; must not be null.
368      * @throws Exception Failed to install artifacts
369      */

370     private void installDependencies(final Set JavaDoc/*<Artifact>*/ dependencies) throws Exception JavaDoc {
371         assert dependencies != null;
372
373         Set JavaDoc resolved = geronimoArtifactResolver.resolveInClassLoader(dependencies);
374         Iterator JavaDoc iter = resolved.iterator();
375
376         while (iter.hasNext()) {
377             Artifact a = (Artifact) iter.next();
378             install(a);
379         }
380     }
381
382     /**
383      * Check if a module has changed by comparing the checksum in the source and target repos.
384      *
385      * @param module The module to inspect; must not be null.
386      * @return Returns true if the module has changed
387      * @throws IOException Failed to load checksum
388      */

389     private boolean hasModuleChanged(final Artifact module) throws IOException JavaDoc {
390         assert module != null;
391
392         String JavaDoc sourceChecksum = loadChecksum(sourceRepo, module);
393         String JavaDoc targetChecksum = loadChecksum(targetRepo, module);
394
395         return !sourceChecksum.equals(targetChecksum);
396     }
397
398     /**
399      * Load the <tt>config.ser</tt> checksum for the given artifact.
400      *
401      * @param repo The repository to resolve the artifacts location; must not be null.
402      * @param artifact The artifact to retrieve a checksum for; must not be null.
403      * @return Thr artifacts checksum
404      * @throws IOException Failed to load checksums
405      */

406     private String JavaDoc loadChecksum(final Repository repo, final Artifact artifact) throws IOException JavaDoc {
407         assert repo != null;
408         assert artifact != null;
409
410         File JavaDoc file = repo.getLocation(artifact);
411         BufferedReader JavaDoc reader;
412
413         if (file.isDirectory()) {
414             File JavaDoc serFile = new File JavaDoc(file, "META-INF/config.ser.sha1");
415             reader = new BufferedReader JavaDoc(new FileReader JavaDoc(serFile));
416         } else {
417             JarFile JavaDoc jarFile = new JarFile JavaDoc(file);
418             ZipEntry JavaDoc entry = jarFile.getEntry("META-INF/config.ser.sha1");
419             reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(jarFile.getInputStream(entry)));
420         }
421
422         String JavaDoc checksum = reader.readLine();
423         reader.close();
424
425         return checksum;
426     }
427
428     /**
429      * Check if a dependency has changed by checking the file size and last modified for source and target.
430      *
431      * @param artifact The artifact to check; must not be null
432      * @return True if the dependency has changed
433      */

434     private boolean hasDependencyChanged(final Artifact artifact) {
435         assert artifact != null;
436
437         File JavaDoc source = sourceRepo.getLocation(artifact);
438         File JavaDoc target = targetRepo.getLocation(artifact);
439
440         return (source.length() != target.length()) ||
441                 (source.lastModified() > target.lastModified());
442     }
443 }
444
Popular Tags