KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > outerj > daisy > tools > artifacter > Artifacter


1 /*
2  * Copyright 2004 Outerthought bvba and Schaubroeck nv
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.outerj.daisy.tools.artifacter;
17
18 import org.apache.commons.cli.*;
19 import org.w3c.dom.Document JavaDoc;
20 import org.w3c.dom.Element JavaDoc;
21 import org.w3c.dom.NodeList JavaDoc;
22 import org.jaxen.dom.DOMXPath;
23
24 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
25 import javax.xml.parsers.DocumentBuilder JavaDoc;
26 import javax.xml.transform.TransformerFactory JavaDoc;
27 import javax.xml.transform.Transformer JavaDoc;
28 import javax.xml.transform.stream.StreamResult JavaDoc;
29 import javax.xml.transform.dom.DOMSource JavaDoc;
30 import java.io.*;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Collection JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.List JavaDoc;
35 import java.util.regex.Pattern JavaDoc;
36 import java.util.regex.Matcher JavaDoc;
37 import java.nio.channels.FileChannel JavaDoc;
38
39 /**
40  * A search and refactor tool for artifacts in Maven project.xml and Merlin block.xml files.
41  */

42 public class Artifacter {
43     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
44         new Artifacter().run(args);
45     }
46
47     private Collection JavaDoc mavenProjectXmls;
48     private Collection JavaDoc merlinBlockXmls;
49
50     public void run(String JavaDoc[] args) throws Exception JavaDoc {
51
52         Options options = new Options();
53         options.addOption(new Option("f", "find-usages", true, "Find usages of an artifact <groupId:artifactId>"));
54         options.addOption(new Option("r", "rename", false, "Renames artifact usages, use options o and n to specify original and new artifact name"));
55         options.addOption(new Option("o", "original", true, "original artifact name in rename operation as <groupId:artifactId>"));
56         options.addOption(new Option("n", "new", true, "new artifact name in rename operation as <groupId:artifactId>"));
57         options.addOption(new Option("u", "update", true, "Update artifact version, specify <groupId:artifactId:versionId>"));
58         options.addOption(new Option("g", "global-update", true, "Update version of all artifacts of a certain group, specify <groupId:versionId>"));
59         options.addOption(new Option("c", "create-local-repo", false, "Creates a repository directory structure containing all jars contained in the classloader description of all block.xml files."));
60         options.addOption(new Option("s", "source-repo", true, "Source repository for -c and -l."));
61         options.addOption(new Option("d", "dest-repo", true, "Destination repository for -c and -l."));
62         options.addOption(new Option("l", "copy-deps-into-local-repo", true, "Copies the dependencies from the project.xml given as argument into another maven repository. Needs -s and -d arguments."));
63         options.addOption(new Option("a", "copy-artifact-into-local-repo", true, "Copies the artifact build by the project.xml given as argument into another maven repository. Needs -s and -d arguments."));
64
65         CommandLineParser parser = new PosixParser();
66         CommandLine cmd = parser.parse(options, args);
67
68         if (cmd.hasOption('f')) {
69             String JavaDoc artifactSpec = cmd.getOptionValue('f');
70             findUsages(artifactSpec);
71         } else if (cmd.hasOption('r')) {
72             if (!cmd.hasOption('o') || !cmd.hasOption('n')) {
73                 System.out.println("Missing arguments for rename operation.");
74                 return;
75             }
76             String JavaDoc originalArtifactSpec = cmd.getOptionValue('o');
77             String JavaDoc newArtifactSpec = cmd.getOptionValue('n');
78             renameArtifact(originalArtifactSpec, newArtifactSpec);
79         } else if (cmd.hasOption('u')) {
80             String JavaDoc artifactSpec = cmd.getOptionValue('u');
81             updateArtifactVersion(artifactSpec);
82         } else if (cmd.hasOption('g')) {
83             String JavaDoc spec = cmd.getOptionValue('g');
84             globalVersionUpdate(spec);
85         } else if (cmd.hasOption('c') || cmd.hasOption('l') || cmd.hasOption('a')) {
86             File sourceRepo = new File(cmd.getOptionValue('s'));
87             if (!sourceRepo.exists()) {
88                 System.err.println("Source repository " + sourceRepo.getAbsolutePath() + " does not exist.");
89                 System.exit(1);
90             }
91             File destinationRepo = new File(cmd.getOptionValue('d'));
92             if (!destinationRepo.exists()) {
93                 System.err.println("Destination repository " + destinationRepo.getAbsolutePath() + " does not exist.");
94                 System.exit(1);
95             }
96             if (cmd.hasOption('c')) {
97                 createBlockDepsRepository(sourceRepo, destinationRepo);
98             } else if (cmd.hasOption('l')) {
99                 File projectXml = new File(cmd.getOptionValue('l'));
100                 if (!projectXml.exists()) {
101                     System.err.println("Maven project.xml " + destinationRepo.getAbsolutePath() + " does not exist.");
102                     System.exit(1);
103                 }
104                 copyDepsToRepository(sourceRepo, destinationRepo, projectXml);
105             } else if (cmd.hasOption('a')) {
106                 File projectXml = new File(cmd.getOptionValue('a'));
107                 if (!projectXml.exists()) {
108                     System.err.println("Maven project.xml " + destinationRepo.getAbsolutePath() + " does not exist.");
109                     System.exit(1);
110                 }
111                 copyArtifactToRepository(sourceRepo, destinationRepo, projectXml);
112             }
113         } else {
114             printHelp();
115         }
116
117     }
118
119     private void printHelp() {
120         System.out.println("[help instructions]");
121     }
122
123     private void updateArtifactVersion(String JavaDoc artifact) throws Exception JavaDoc {
124         findFiles();
125
126         Pattern JavaDoc artifactPattern = Pattern.compile("^(.*):(.*):(.*)$");
127         Matcher JavaDoc matcher = artifactPattern.matcher(artifact);
128         if (!matcher.matches()) {
129             System.out.println("Invalid artifact spec: " + artifact);
130             System.exit(1);
131         }
132
133         String JavaDoc groupId = matcher.group(1);
134         String JavaDoc artifactId = matcher.group(2);
135         String JavaDoc version = matcher.group(3);
136
137         updateInProjectXmls(groupId, artifactId, version);
138         updateInBlockXmls(groupId, artifactId, version);
139         saveFiles(mavenProjectXmls);
140         saveFiles(merlinBlockXmls);
141     }
142
143     private void updateInProjectXmls(String JavaDoc groupId, String JavaDoc artifactId, String JavaDoc version) throws Exception JavaDoc {
144         System.out.println("Searching and updating in project.xml files...");
145
146         DOMXPath projectXPath = new DOMXPath("/project[groupId='" + groupId + "' and id='" + artifactId + "']");
147         DOMXPath projectVersionXPath = new DOMXPath("/project/currentVersion");
148
149         DOMXPath xpath = new DOMXPath("/project/dependencies/dependency[groupId='" + groupId + "' and artifactId='" + artifactId + "']");
150         DOMXPath versionXPath = new DOMXPath("version");
151         Iterator JavaDoc mavenProjectXmlsIt = mavenProjectXmls.iterator();
152         while (mavenProjectXmlsIt.hasNext()) {
153             XmlFile xmlFile = (XmlFile)mavenProjectXmlsIt.next();
154             // project itself
155
if (projectXPath.booleanValueOf(xmlFile.document)) {
156                 Element JavaDoc versionEl = (Element JavaDoc)projectVersionXPath.selectSingleNode(xmlFile.document);
157                 setElementValue(versionEl, version);
158                 xmlFile.changed = true;
159             }
160
161             // dependencies
162
List JavaDoc nodes = xpath.selectNodes(xmlFile.document);
163             Iterator JavaDoc nodesIt = nodes.iterator();
164             while (nodesIt.hasNext()) {
165                 Element JavaDoc element = (Element JavaDoc)nodesIt.next();
166                 Element JavaDoc versionEl = (Element JavaDoc)versionXPath.selectSingleNode(element);
167                 setElementValue(versionEl, version);
168                 xmlFile.changed = true;
169             }
170         }
171     }
172
173     private void updateInBlockXmls(String JavaDoc groupId, String JavaDoc artifactId, String JavaDoc version) throws Exception JavaDoc {
174         System.out.println("Searching and updating in block.xml files...");
175         String JavaDoc artifactSpec = groupId + ":" + artifactId;
176         DOMXPath xpath = new DOMXPath("//classloader/classpath/repository/resource[@id='" + artifactSpec + "']");
177         Iterator JavaDoc merlinBlockXmlsIt = merlinBlockXmls.iterator();
178         while (merlinBlockXmlsIt.hasNext()) {
179             XmlFile xmlFile = (XmlFile)merlinBlockXmlsIt.next();
180             List JavaDoc nodes = xpath.selectNodes(xmlFile.document);
181             Iterator JavaDoc nodesIt = nodes.iterator();
182             while (nodesIt.hasNext()) {
183                 Element JavaDoc element = (Element JavaDoc)nodesIt.next();
184                 element.setAttribute("version", version);
185                 xmlFile.changed = true;
186             }
187         }
188     }
189
190     private void globalVersionUpdate(String JavaDoc spec) throws Exception JavaDoc {
191         findFiles();
192
193         Pattern JavaDoc artifactPattern = Pattern.compile("^(.*):(.*)$");
194         Matcher JavaDoc matcher = artifactPattern.matcher(spec);
195         if (!matcher.matches()) {
196             System.out.println("Invalid spec: " + spec);
197             System.exit(1);
198         }
199
200         String JavaDoc groupId = matcher.group(1);
201         String JavaDoc version = matcher.group(2);
202
203         globalUpdateInProjectXmls(groupId, version);
204         globalUpdateInBlockXmls(groupId, version);
205         saveFiles(mavenProjectXmls);
206         saveFiles(merlinBlockXmls);
207     }
208
209     private void globalUpdateInProjectXmls(String JavaDoc groupId, String JavaDoc version) throws Exception JavaDoc {
210         System.out.println("Searching and updating in project.xml files...");
211
212         DOMXPath projectXPath = new DOMXPath("/project[groupId='" + groupId + "']");
213         DOMXPath projectVersionXPath = new DOMXPath("/project/currentVersion");
214
215         DOMXPath xpath = new DOMXPath("/project/dependencies/dependency[groupId='" + groupId + "']");
216         DOMXPath versionXPath = new DOMXPath("version");
217         Iterator JavaDoc mavenProjectXmlsIt = mavenProjectXmls.iterator();
218         while (mavenProjectXmlsIt.hasNext()) {
219             XmlFile xmlFile = (XmlFile)mavenProjectXmlsIt.next();
220             // project itself
221
if (projectXPath.booleanValueOf(xmlFile.document)) {
222                 Element JavaDoc versionEl = (Element JavaDoc)projectVersionXPath.selectSingleNode(xmlFile.document);
223                 setElementValue(versionEl, version);
224                 xmlFile.changed = true;
225             }
226
227             // dependencies
228
List JavaDoc nodes = xpath.selectNodes(xmlFile.document);
229             Iterator JavaDoc nodesIt = nodes.iterator();
230             while (nodesIt.hasNext()) {
231                 Element JavaDoc element = (Element JavaDoc)nodesIt.next();
232                 Element JavaDoc versionEl = (Element JavaDoc)versionXPath.selectSingleNode(element);
233                 setElementValue(versionEl, version);
234                 xmlFile.changed = true;
235             }
236         }
237     }
238
239     private void globalUpdateInBlockXmls(String JavaDoc groupId, String JavaDoc version) throws Exception JavaDoc {
240         System.out.println("Searching and updating in block.xml files...");
241         String JavaDoc artifactSpec = groupId + ":";
242         DOMXPath xpath = new DOMXPath("//classloader/classpath/repository/resource[starts-with(@id,'" + artifactSpec + "')] | //include[starts-with(@id,'" + artifactSpec + "')]");
243         Iterator JavaDoc merlinBlockXmlsIt = merlinBlockXmls.iterator();
244         while (merlinBlockXmlsIt.hasNext()) {
245             XmlFile xmlFile = (XmlFile)merlinBlockXmlsIt.next();
246             List JavaDoc nodes = xpath.selectNodes(xmlFile.document);
247             Iterator JavaDoc nodesIt = nodes.iterator();
248             while (nodesIt.hasNext()) {
249                 Element JavaDoc element = (Element JavaDoc)nodesIt.next();
250                 element.setAttribute("version", version);
251                 xmlFile.changed = true;
252             }
253         }
254     }
255
256     private void renameArtifact(String JavaDoc originalArtifactSpec, String JavaDoc newArtifactSpec) throws Exception JavaDoc{
257         Artifact originalArtifact = parseArtifactSpec(originalArtifactSpec);
258         Artifact newArtifact = parseArtifactSpec(newArtifactSpec);
259
260         findFiles();
261         checkIfNewAlreadyExists(newArtifact);
262         renameInProjectXmls(originalArtifact, newArtifact);
263         renameUsagesInBlockXmls(originalArtifact, newArtifact);
264         saveFiles(mavenProjectXmls);
265         saveFiles(merlinBlockXmls);
266     }
267
268     private void checkIfNewAlreadyExists(Artifact newArtifact) throws Exception JavaDoc {
269         DOMXPath projectXPath = new DOMXPath("/project[groupId='" + newArtifact.groupId + "' and id='" + newArtifact.artifactId + "']");
270
271         Iterator JavaDoc mavenProjectXmlsIt = mavenProjectXmls.iterator();
272         while (mavenProjectXmlsIt.hasNext()) {
273             XmlFile xmlFile = (XmlFile)mavenProjectXmlsIt.next();
274             if (projectXPath.booleanValueOf(xmlFile.document)) {
275                 System.out.println("Warning: the following file:");
276                 System.out.println(xmlFile.file.getAbsolutePath());
277                 System.out.println("already defines the artifact " + newArtifact.groupId + ":" + newArtifact.artifactId);
278                 if (!promptYesNo("Are you sure you want to continue? [yes/no, default = no]", false)) {
279                     System.exit(1);
280                 }
281             }
282         }
283     }
284
285     private void renameInProjectXmls(Artifact originalArtifact, Artifact newArtifact) throws Exception JavaDoc {
286         System.out.println("Searching and renaming in project.xml files...");
287
288         DOMXPath projectXPath = new DOMXPath("/project[groupId='" + originalArtifact.groupId + "' and id='" + originalArtifact.artifactId + "']");
289         DOMXPath projectGroupIdXPath = new DOMXPath("/project/groupId");
290         DOMXPath projectIdXPath = new DOMXPath("/project/id");
291
292         DOMXPath xpath = new DOMXPath("/project/dependencies/dependency[groupId='" + originalArtifact.groupId + "' and artifactId='" + originalArtifact.artifactId + "']");
293         DOMXPath groupIdXPath = new DOMXPath("groupId");
294         DOMXPath artifactIdXPath = new DOMXPath("artifactId");
295         Iterator JavaDoc mavenProjectXmlsIt = mavenProjectXmls.iterator();
296         while (mavenProjectXmlsIt.hasNext()) {
297             XmlFile xmlFile = (XmlFile)mavenProjectXmlsIt.next();
298             // project itself
299
if (projectXPath.booleanValueOf(xmlFile.document)) {
300                 Element JavaDoc groupIdEl = (Element JavaDoc)projectGroupIdXPath.selectSingleNode(xmlFile.document);
301                 Element JavaDoc idEl = (Element JavaDoc)projectIdXPath.selectSingleNode(xmlFile.document);
302                 setElementValue(groupIdEl, newArtifact.groupId);
303                 setElementValue(idEl, newArtifact.artifactId);
304                 xmlFile.changed = true;
305             }
306
307             // dependencies
308
List JavaDoc nodes = xpath.selectNodes(xmlFile.document);
309             Iterator JavaDoc nodesIt = nodes.iterator();
310             while (nodesIt.hasNext()) {
311                 Element JavaDoc element = (Element JavaDoc)nodesIt.next();
312                 Element JavaDoc groupIdEl = (Element JavaDoc)groupIdXPath.selectSingleNode(element);
313                 Element JavaDoc artifactIdEl = (Element JavaDoc)artifactIdXPath.selectSingleNode(element);
314                 setElementValue(groupIdEl, newArtifact.groupId);
315                 setElementValue(artifactIdEl, newArtifact.artifactId);
316                 xmlFile.changed = true;
317             }
318         }
319     }
320
321     private void setElementValue(Element JavaDoc element, String JavaDoc value) {
322         NodeList JavaDoc nodes = element.getChildNodes();
323         for (int i = 0; i < nodes.getLength(); i++)
324             element.removeChild(nodes.item(i));
325
326         element.appendChild(element.getOwnerDocument().createTextNode(value));
327     }
328
329     private void renameUsagesInBlockXmls(Artifact originalArtifact, Artifact newArtifact) throws Exception JavaDoc {
330         System.out.println("Searching and renaming in block.xml files...");
331         String JavaDoc originalArtifactSpec = originalArtifact.groupId + ":" + originalArtifact.artifactId;
332         String JavaDoc newArtifactSpec = newArtifact.groupId + ":" + newArtifact.artifactId;
333         DOMXPath xpath = new DOMXPath("//classloader/classpath/repository/resource[@id='" + originalArtifactSpec + "']");
334         Iterator JavaDoc merlinBlockXmlsIt = merlinBlockXmls.iterator();
335         while (merlinBlockXmlsIt.hasNext()) {
336             XmlFile xmlFile = (XmlFile)merlinBlockXmlsIt.next();
337             List JavaDoc nodes = xpath.selectNodes(xmlFile.document);
338             Iterator JavaDoc nodesIt = nodes.iterator();
339             while (nodesIt.hasNext()) {
340                 Element JavaDoc element = (Element JavaDoc)nodesIt.next();
341                 element.setAttribute("id", newArtifactSpec);
342                 xmlFile.changed = true;
343             }
344         }
345     }
346
347     private void findUsages(String JavaDoc artifactSpec) throws Exception JavaDoc {
348         Artifact artifact = parseArtifactSpec(artifactSpec);
349
350         System.out.println("Will search for groupId '" + artifact.groupId + "' and artifactId '" + artifact.artifactId + "'.");
351
352         findFiles();
353         printUsagesInProjectXmls(artifact);
354         printUsagesInBlockXmls(artifact);
355     }
356
357     private void printUsagesInProjectXmls(Artifact artifact) throws Exception JavaDoc {
358         System.out.println("Searching in project.xml files...");
359         DOMXPath xpath = new DOMXPath("/project/dependencies/dependency[groupId='" + artifact.groupId + "' and artifactId='" + artifact.artifactId + "']");
360         DOMXPath versionXPath = new DOMXPath("string(version)");
361         Iterator JavaDoc mavenProjectXmlsIt = mavenProjectXmls.iterator();
362         while (mavenProjectXmlsIt.hasNext()) {
363             XmlFile xmlFile = (XmlFile)mavenProjectXmlsIt.next();
364             List JavaDoc nodes = xpath.selectNodes(xmlFile.document);
365             Iterator JavaDoc nodesIt = nodes.iterator();
366             while (nodesIt.hasNext()) {
367                 Element JavaDoc element = (Element JavaDoc)nodesIt.next();
368                 String JavaDoc version = versionXPath.stringValueOf(element);
369                 System.out.println(xmlFile.file.getAbsolutePath() + " uses version " + version);
370             }
371         }
372     }
373
374     private void printUsagesInBlockXmls(Artifact artifact) throws Exception JavaDoc {
375         System.out.println("Searching in block.xml files...");
376         String JavaDoc artifactSpec = artifact.groupId + ":" + artifact.artifactId;
377         DOMXPath xpath = new DOMXPath("//classloader/classpath/repository/resource[@id='" + artifactSpec + "']");
378         DOMXPath versionXPath = new DOMXPath("string(@version)");
379         Iterator JavaDoc merlinBlockXmlsIt = merlinBlockXmls.iterator();
380         while (merlinBlockXmlsIt.hasNext()) {
381             XmlFile xmlFile = (XmlFile)merlinBlockXmlsIt.next();
382             List JavaDoc nodes = xpath.selectNodes(xmlFile.document);
383             Iterator JavaDoc nodesIt = nodes.iterator();
384             while (nodesIt.hasNext()) {
385                 Element JavaDoc element = (Element JavaDoc)nodesIt.next();
386                 String JavaDoc version = versionXPath.stringValueOf(element);
387                 System.out.println(xmlFile.file.getAbsolutePath() + " uses version " + version);
388             }
389         }
390     }
391
392     private Document JavaDoc parseFile(File file) throws Exception JavaDoc {
393         DocumentBuilderFactory JavaDoc documentBuilderFactory = DocumentBuilderFactory.newInstance();
394         documentBuilderFactory.setNamespaceAware(true);
395         DocumentBuilder JavaDoc documentBuilder = documentBuilderFactory.newDocumentBuilder();
396         return documentBuilder.parse(file);
397     }
398
399     private void saveFiles(Collection JavaDoc xmlFiles) throws Exception JavaDoc {
400         Iterator JavaDoc it = xmlFiles.iterator();
401         while (it.hasNext()) {
402             XmlFile xmlFile = (XmlFile)it.next();
403             if (xmlFile.changed) {
404                 save(xmlFile.file, xmlFile.document);
405                 System.out.println("Saved updated " + xmlFile.file.getAbsolutePath());
406             }
407         }
408     }
409
410     private void save(File file, Document JavaDoc document) throws Exception JavaDoc {
411         TransformerFactory JavaDoc transformerFactory = TransformerFactory.newInstance();
412         Transformer JavaDoc transformer = transformerFactory.newTransformer();
413         DOMSource JavaDoc source = new DOMSource JavaDoc(document);
414         StreamResult JavaDoc result = new StreamResult JavaDoc(file);
415         transformer.setOutputProperty("encoding", "UTF-8");
416         transformer.transform(source, result);
417     }
418
419     private void findFiles() throws Exception JavaDoc {
420         File workingDir = new File(System.getProperty("user.dir"));
421         System.out.println("Working directory is: " + workingDir);
422
423         findMavenProjectXmls(workingDir);
424         findMerlinBlockXmls(workingDir);
425     }
426
427     private void findMavenProjectXmls(File workingDir) throws Exception JavaDoc {
428         System.out.println("Searching for Maven project.xml files...");
429         mavenProjectXmls = findFiles(workingDir, "project.xml");
430         System.out.println("Found " + mavenProjectXmls.size() + " project.xml files.");
431     }
432
433     private void findMerlinBlockXmls(File workingDir) throws Exception JavaDoc {
434         System.out.println("Searching for Merlin block.xml files...");
435         merlinBlockXmls = findFiles(workingDir, "block.xml");
436         System.out.println("Found " + merlinBlockXmls.size() + " block.xml files.");
437     }
438
439     private Collection JavaDoc findFiles(File startDir, String JavaDoc name) throws Exception JavaDoc {
440         ArrayList JavaDoc result = new ArrayList JavaDoc();
441         File[] files = startDir.listFiles();
442         for (int i = 0; i < files.length; i++) {
443             if (files[i].isDirectory() && !files[i].getName().equals("target")) {
444                 Collection JavaDoc subDirResult = findFiles(files[i], name);
445                 result.addAll(subDirResult);
446             } else if (files[i].getName().equals(name)) {
447                 XmlFile xmlFile = new XmlFile();
448                 xmlFile.file = files[i];
449                 xmlFile.document = parseFile(xmlFile.file);
450                 result.add(xmlFile);
451             }
452         }
453         return result;
454     }
455
456     public Artifact parseArtifactSpec(String JavaDoc artifactSpec) throws Exception JavaDoc {
457         int colonPos = artifactSpec.indexOf(':');
458         if (colonPos == -1)
459             throw new Exception JavaDoc("artifact specification does not contain a colon");
460
461         Artifact artifact = new Artifact();
462         artifact.groupId = artifactSpec.substring(0, colonPos);
463         artifact.artifactId = artifactSpec.substring(colonPos + 1);
464         return artifact;
465     }
466
467     private boolean promptYesNo(String JavaDoc message, boolean defaultInput) throws Exception JavaDoc {
468         String JavaDoc input = "";
469         while (!input.equals("yes") && !input.equals("no")) {
470             input = prompt(message, defaultInput ? "yes" : "no");
471             input = input.toLowerCase();
472         }
473         return input.equals("yes");
474     }
475
476     private String JavaDoc prompt(String JavaDoc message, String JavaDoc defaultInput) throws Exception JavaDoc {
477         System.err.println(message);
478         System.err.flush();
479         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
480         String JavaDoc input;
481         try {
482             input = in.readLine();
483         } catch (IOException e) {
484             throw new Exception JavaDoc("Error reading input from console.", e);
485         }
486         if (input == null || input.trim().equals(""))
487             input = defaultInput;
488         return input;
489     }
490
491     static class Artifact {
492         public String JavaDoc groupId;
493         public String JavaDoc artifactId;
494     }
495
496     static class XmlFile {
497         public File file;
498         public Document JavaDoc document;
499         public boolean changed = false;
500     }
501
502     /**
503      * Creates a repository containing all dependencies from all block.xml's.
504      */

505     private void createBlockDepsRepository(File sourceRepo, File destinationRepo) throws Exception JavaDoc {
506         findFiles();
507
508         DOMXPath xpath = new DOMXPath("//classloader/classpath/repository/resource | //include");
509         Iterator JavaDoc merlinBlockXmlsIt = merlinBlockXmls.iterator();
510         while (merlinBlockXmlsIt.hasNext()) {
511             XmlFile xmlFile = (XmlFile)merlinBlockXmlsIt.next();
512             List JavaDoc nodes = xpath.selectNodes(xmlFile.document);
513             Iterator JavaDoc nodesIt = nodes.iterator();
514             while (nodesIt.hasNext()) {
515                 Element JavaDoc element = (Element JavaDoc)nodesIt.next();
516                 String JavaDoc id = element.getAttribute("id");
517                 String JavaDoc version = element.getAttribute("version");
518                 Artifact artifact = parseArtifactSpec(id);
519
520                 copyArtifact(sourceRepo, destinationRepo, artifact.groupId, artifact.artifactId, version);
521             }
522         }
523     }
524
525     private void copyArtifact(File sourceRepo, File destinationRepo, String JavaDoc groupId, String JavaDoc artifactId, String JavaDoc version) throws Exception JavaDoc {
526         String JavaDoc jarName = artifactId + "-" + version + ".jar";
527
528         File groupDir = new File(sourceRepo, groupId);
529         File jarDir = new File(groupDir, "jars");
530         File artifactFile = new File(jarDir, jarName);
531
532         File destinationGroupDir = new File(destinationRepo, groupId);
533         File destinationJarDir = new File(destinationGroupDir, "jars");
534         if (!destinationJarDir.exists())
535             destinationJarDir.mkdirs();
536         File destinationArtifactFile = new File(destinationJarDir, jarName);
537
538         copyFile(artifactFile, destinationArtifactFile);
539         System.out.println("Copying from: " + artifactFile.getAbsolutePath());
540         System.out.println(" to: " + destinationArtifactFile.getAbsolutePath());
541     }
542
543     private void copyArtifactToRepository(File sourceRepo, File destinationRepo, File projectXml) throws Exception JavaDoc {
544         Document JavaDoc project = parseFile(projectXml);
545
546         DOMXPath xpath = new DOMXPath("/project/groupId");
547         String JavaDoc groupId = xpath.stringValueOf(project);
548         xpath = new DOMXPath("/project/id");
549         String JavaDoc artifactId = xpath.stringValueOf(project);
550         xpath = new DOMXPath("/project/currentVersion");
551         String JavaDoc version = xpath.stringValueOf(project);
552         copyArtifact(sourceRepo, destinationRepo, groupId, artifactId, version);
553     }
554
555     private void copyDepsToRepository(File sourceRepo, File destinationRepo, File projectXml) throws Exception JavaDoc {
556         Document JavaDoc project = parseFile(projectXml);
557
558         DOMXPath xpath = new DOMXPath("/project/dependencies/dependency");
559         List JavaDoc nodes = xpath.selectNodes(project);
560
561         DOMXPath groupXPath = new DOMXPath("groupId");
562         DOMXPath artifactXPath = new DOMXPath("artifactId");
563         DOMXPath versionXPath = new DOMXPath("version");
564
565         Iterator JavaDoc nodesIt = nodes.iterator();
566         while (nodesIt.hasNext()) {
567             Element JavaDoc element = (Element JavaDoc)nodesIt.next();
568             String JavaDoc groupId = groupXPath.stringValueOf(element);
569             String JavaDoc artifactId = artifactXPath.stringValueOf(element);
570             String JavaDoc version = versionXPath.stringValueOf(element);
571             copyArtifact(sourceRepo, destinationRepo, groupId, artifactId, version);
572         }
573     }
574
575     private void copyFile(File source, File destination) throws Exception JavaDoc {
576         FileChannel JavaDoc srcChannel = new FileInputStream(source).getChannel();
577         FileChannel JavaDoc dstChannel = new FileOutputStream(destination).getChannel();
578         dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
579         srcChannel.close();
580         dstChannel.close();
581     }
582 }
583
Popular Tags