KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > bean > CocoonBean


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
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.apache.cocoon.bean;
17
18 import org.apache.cocoon.Constants;
19 import org.apache.cocoon.ProcessingException;
20 import org.apache.cocoon.bean.helpers.Crawler;
21 import org.apache.cocoon.bean.helpers.DelayedOutputStream;
22 import org.apache.cocoon.components.notification.SimpleNotifyingBean;
23 import org.apache.cocoon.components.notification.Notifier;
24 import org.apache.cocoon.components.notification.DefaultNotifyingBuilder;
25 import org.apache.cocoon.components.notification.Notifying;
26 import org.apache.cocoon.matching.helpers.WildcardHelper;
27 import org.apache.commons.lang.SystemUtils;
28
29 import org.apache.excalibur.source.ModifiableSource;
30 import org.apache.excalibur.source.SourceResolver;
31 import org.apache.excalibur.source.Source;
32 import org.apache.excalibur.source.SourceNotFoundException;
33 import org.apache.excalibur.source.SourceUtil;
34
35 import java.io.BufferedReader JavaDoc;
36 import java.io.InputStreamReader JavaDoc;
37 import java.io.IOException JavaDoc;
38 import java.io.OutputStream JavaDoc;
39 import java.io.OutputStreamWriter JavaDoc;
40 import java.io.PrintStream JavaDoc;
41 import java.io.PrintWriter JavaDoc;
42 import java.security.MessageDigest JavaDoc;
43 import java.security.NoSuchAlgorithmException JavaDoc;
44
45 import java.util.ArrayList JavaDoc;
46 import java.util.HashMap JavaDoc;
47 import java.util.Iterator JavaDoc;
48 import java.util.List JavaDoc;
49 import java.util.Map JavaDoc;
50
51 /**
52  * <p>The Cocoon Bean simplifies usage of the Cocoon object. Allows to create,
53  * configure Cocoon instance and process requests, one by one or multiple
54  * with link traversal.</p>
55  *
56  * <p><b>WARNING:</b> This interface is not stable and could be changed in
57  * backward incompatible way without prior notice.</p>
58
59  * @author <a HREF="mailto:stefano@apache.org">Stefano Mazzocchi</a>
60  * @author <a HREF="mailto:nicolaken@apache.org">Nicola Ken Barozzi</a>
61  * @author <a HREF="mailto:vgritsenko@apache.org">Vadim Gritsenko</a>
62  * @author <a HREF="mailto:uv@upaya.co.uk">Upayavira</a>
63  * @version CVS $Id: CocoonBean.java 54079 2004-10-08 13:30:28Z vgritsenko $
64  */

65 public class CocoonBean extends CocoonWrapper {
66
67     // User Supplied Parameters
68
private boolean followLinks = true;
69     private boolean precompileOnly = false;
70     private boolean confirmExtension = true;
71     private String JavaDoc defaultFilename = Constants.INDEX_URI;
72     private boolean brokenLinkGenerate = false;
73     private String JavaDoc brokenLinkExtension = "";
74     private List JavaDoc excludePatterns = new ArrayList JavaDoc();
75     private List JavaDoc includePatterns = new ArrayList JavaDoc();
76     private List JavaDoc includeLinkExtensions = null;
77
78     // Internal Objects
79
private boolean initialized;
80     private List JavaDoc listeners = new ArrayList JavaDoc();
81     private boolean verbose;
82     SourceResolver sourceResolver;
83
84     private Crawler crawler;
85     private String JavaDoc checksumsURI = null;
86     private Map JavaDoc checksums;
87
88     public CocoonBean() {
89         this.crawler = new Crawler();
90     }
91
92     //
93
// INITIALISATION METHOD
94
//
95

96     public void initialize() throws Exception JavaDoc {
97         if (this.initialized == false) {
98             super.initialize();
99
100             this.sourceResolver =
101                 (SourceResolver) getComponentManager().lookup(
102                     SourceResolver.ROLE);
103
104             initialized = true;
105         }
106     }
107
108     protected void finalize() throws Throwable JavaDoc {
109         dispose();
110         super.finalize();
111     }
112
113     //
114
// GETTERS AND SETTERS FOR CONFIGURATION PROPERTIES
115
//
116

117     public void setFollowLinks(boolean follow) {
118         followLinks = follow;
119     }
120
121     public void setConfirmExtensions(boolean confirmExtension) {
122         this.confirmExtension = confirmExtension;
123     }
124
125     public void setPrecompileOnly(boolean precompileOnly) {
126         this.precompileOnly = precompileOnly;
127     }
128
129     public boolean isPrecompileOnly() {
130         return precompileOnly;
131     }
132     
133     public void setVerbose(boolean verbose) {
134         this.verbose = verbose;
135     }
136
137     public void setDefaultFilename(String JavaDoc filename) {
138         defaultFilename = filename;
139     }
140
141     public void setBrokenLinkGenerate(boolean brokenLinkGenerate) {
142         this.brokenLinkGenerate = brokenLinkGenerate;
143     }
144
145     public void setBrokenLinkExtension(String JavaDoc brokenLinkExtension) {
146         this.brokenLinkExtension = brokenLinkExtension;
147     }
148
149     public void setChecksumURI(String JavaDoc uri) {
150         this.checksumsURI = uri;
151     }
152     
153     public boolean followLinks() {
154         return followLinks;
155     }
156
157     public boolean confirmExtensions() {
158         return confirmExtension;
159     }
160     /**
161      * Adds a target for processing
162      *
163      * @param type Type of target - append, replace, insert.
164      * @param root
165      * @param sourceURI URI of the starting page
166      * @param destURI URI specifying destination for the generated pages.
167      * @throws IllegalArgumentException if destURI is missing
168      */

169     public void addTarget(
170             String JavaDoc type,
171             String JavaDoc root,
172             String JavaDoc sourceURI,
173             String JavaDoc destURI)
174             throws IllegalArgumentException JavaDoc {
175         Target target = new Target(type, root, sourceURI, destURI);
176         target.setDefaultFilename(this.defaultFilename);
177         target.setFollowLinks(this.followLinks);
178         target.setConfirmExtension(this.confirmExtension);
179         target.setLogger(this.logger);
180         crawler.addTarget(target);
181     }
182
183     public void addTarget(String JavaDoc type, String JavaDoc sourceURI, String JavaDoc destURI)
184         throws IllegalArgumentException JavaDoc {
185         Target target = new Target(type, sourceURI, destURI);
186         target.setDefaultFilename(this.defaultFilename);
187         target.setFollowLinks(this.followLinks);
188         target.setConfirmExtension(this.confirmExtension);
189         target.setLogger(this.logger);
190         crawler.addTarget(target);
191     }
192
193     public void addTarget(String JavaDoc sourceURI, String JavaDoc destURI)
194         throws IllegalArgumentException JavaDoc {
195         Target target = new Target(sourceURI, destURI);
196         target.setDefaultFilename(this.defaultFilename);
197         target.setFollowLinks(this.followLinks);
198         target.setConfirmExtension(this.confirmExtension);
199         target.setLogger(this.logger);
200         crawler.addTarget(target);
201     }
202
203     public void addTargets(List JavaDoc uris, String JavaDoc destURI)
204         throws IllegalArgumentException JavaDoc {
205         Iterator JavaDoc i = uris.iterator();
206         while (i.hasNext()) {
207             Target target = new Target((String JavaDoc) i.next(), destURI);
208             target.setDefaultFilename(this.defaultFilename);
209             target.setFollowLinks(this.followLinks);
210             target.setConfirmExtension(this.confirmExtension);
211             target.setLogger(this.logger);
212             crawler.addTarget(target);
213         }
214     }
215
216     public void addTarget(
217         String JavaDoc type,
218         String JavaDoc root,
219         String JavaDoc sourceURI,
220         String JavaDoc destURI,
221         boolean followLinks,
222         boolean confirmExtension,
223         String JavaDoc logger)
224         throws IllegalArgumentException JavaDoc {
225
226         Target target;
227         if (root == null && type == null) {
228             target = new Target(sourceURI, destURI);
229         } else if (root == null) {
230             target = new Target(type, sourceURI, destURI);
231         } else {
232             target = new Target(type, root, sourceURI, destURI);
233         }
234         target.setDefaultFilename(this.defaultFilename);
235         target.setFollowLinks(followLinks);
236         target.setConfirmExtension(confirmExtension);
237         target.setLogger(logger);
238         crawler.addTarget(target);
239     }
240
241     public int getTargetCount() {
242         return crawler.getRemainingCount();
243     }
244     
245     public void addExcludePattern(String JavaDoc pattern) {
246         int preparedPattern[] = WildcardHelper.compilePattern(pattern);
247         excludePatterns.add(preparedPattern);
248     }
249
250     public void addIncludePattern(String JavaDoc pattern) {
251         int preparedPattern[] = WildcardHelper.compilePattern(pattern);
252         includePatterns.add(preparedPattern);
253     }
254
255     public void addIncludeLinkExtension(String JavaDoc extension) {
256         if (includeLinkExtensions == null) {
257             includeLinkExtensions = new ArrayList JavaDoc();
258         }
259         includeLinkExtensions.add(extension);
260     }
261
262     public void addListener(BeanListener listener) {
263         this.listeners.add(listener);
264     }
265
266     public void pageGenerated(String JavaDoc sourceURI,
267                               String JavaDoc destURI,
268                               int pageSize,
269                               int linksInPage,
270                               int newLinksInPage,
271                               int pagesRemaining,
272                               int pagesComplete,
273                               long timeTaken) {
274         Iterator JavaDoc i = listeners.iterator();
275         while (i.hasNext()) {
276             BeanListener l = (BeanListener) i.next();
277             l.pageGenerated(sourceURI,
278                             destURI,
279                             pageSize,
280                             linksInPage,
281                             newLinksInPage,
282                             pagesRemaining,
283                             pagesComplete,
284                             timeTaken);
285         }
286     }
287
288     public void sendMessage(String JavaDoc msg) {
289         Iterator JavaDoc i = listeners.iterator();
290         while (i.hasNext()) {
291             BeanListener l = (BeanListener) i.next();
292             l.messageGenerated(msg);
293         }
294     }
295
296     public void sendWarning(String JavaDoc uri, String JavaDoc warning) {
297         Iterator JavaDoc i = listeners.iterator();
298         while (i.hasNext()) {
299             BeanListener l = (BeanListener) i.next();
300             l.warningGenerated(uri, warning);
301         }
302     }
303
304     public void sendBrokenLinkWarning(String JavaDoc uri, String JavaDoc warning) {
305         Iterator JavaDoc i = listeners.iterator();
306         while (i.hasNext()) {
307             BeanListener l = (BeanListener) i.next();
308             l.brokenLinkFound(uri, "", warning, null);
309         }
310     }
311
312     public void pageSkipped(String JavaDoc uri, String JavaDoc message) {
313         Iterator JavaDoc i = listeners.iterator();
314         while (i.hasNext()) {
315             BeanListener l = (BeanListener) i.next();
316             l.pageSkipped(uri, message);
317         }
318     }
319
320     public void dispose() {
321         if (this.initialized) {
322             if (this.sourceResolver != null) {
323                 getComponentManager().release(this.sourceResolver);
324                 this.sourceResolver = null;
325             }
326             super.dispose();
327         }
328     }
329
330     /**
331      * Process the URI list and process them all independently.
332      * @exception Exception if an error occurs
333      */

334     public void process() throws Exception JavaDoc {
335
336         if (!this.initialized) {
337             this.initialize();
338         }
339
340         if (crawler.getRemainingCount() == 0 && !precompileOnly) {
341             log.info("No targets for to be processed.");
342             return;
343         }
344
345         if (this.checksumsURI != null) {
346             readChecksumFile();
347         }
348         
349         if (crawler.getRemainingCount()>=0) {
350             Iterator JavaDoc iterator = crawler.iterator();
351             while (iterator.hasNext()) {
352                 Target target = (Target) iterator.next();
353                 if (!precompileOnly) {
354                     processTarget(crawler, target);
355                                 }
356             }
357         }
358         
359         if (this.checksumsURI != null) {
360             writeChecksumFile();
361         }
362         
363         if (log.isInfoEnabled()) {
364               log.info(
365                   " Memory used: "
366                       + (Runtime.getRuntime().totalMemory()
367                           - Runtime.getRuntime().freeMemory()));
368               log.info(
369                   " Processed, Translated & Left: "
370                       + crawler.getProcessedCount()
371                       + ", "
372                       + crawler.getTranslatedCount()
373                       + ", "
374                       + crawler.getRemainingCount());
375           }
376     }
377
378     /**
379      * Processes the given Target and return all links.
380      *
381      * If links are to be followed, and extensions checked then the algorithm is as
382      * follows:
383      * <ul>
384      * <li>file name for the URI is generated. URI MIME type is checked for
385      * consistency with the URI and, if the extension is inconsistent
386      * or absent, the file name is changed</li>
387      * <li>the link view of the given URI is called and the file names for linked
388      * resources are generated and stored.</li>
389      * <li>for each link, absolute file name is translated to relative path.</li>
390      * <li>after the complete list of links is translated, the link-translating
391      * view of the resource is called to obtain a link-translated version
392      * of the resource with the given link map</li>
393      * <li>list of absolute URI is returned, for every URI which is not yet
394      * present in list of all translated URIs</li>
395      * </ul>
396      *
397      * If links are to be followed, but extensions are not checked, then the
398      * algorithm will be:
399      * <ul>
400      * <li>The content for the page is generated</li>
401      * <li>Whilst generating, all links are gathered by the LinkGatherer</li>
402      * <li>Gathered links are added to the unprocessed links list, and
403      * processing continues until all processing is complete
404      * </li>
405      * </ul>
406      *
407      * @param target a <code>Target</code> target to process
408      * @exception Exception if an error occurs
409      */

410     private void processTarget(Crawler crawler, Target target) throws Exception JavaDoc {
411
412         int status = 0;
413
414         int linkCount = 0;
415         int newLinkCount = 0;
416         int pageSize = 0;
417         long startTimeMillis = System.currentTimeMillis();
418
419         if (target.confirmExtensions()) {
420             if (!crawler.hasTranslatedLink(target)) {
421                 final String JavaDoc mimeType = getType(target.getDeparameterizedSourceURI(), target.getParameters());
422                 target.setMimeType(mimeType);
423                 crawler.addTranslatedLink(target);
424             }
425         }
426
427         // IS THIS STILL NEEDED?
428
//if ("".equals(destinationURI)) {
429
// return new ArrayList();
430
//}
431

432         // Process links
433
final HashMap JavaDoc translatedLinks = new HashMap JavaDoc();
434         if (target.followLinks() && target.confirmExtensions() && isCrawlablePage(target)) {
435             final Iterator JavaDoc i =
436                 this.getLinks(target.getDeparameterizedSourceURI(), target.getParameters()).iterator();
437
438             while (i.hasNext()) {
439                 String JavaDoc linkURI = (String JavaDoc) i.next();
440                 Target linkTarget = target.getDerivedTarget(linkURI);
441
442                 if (linkTarget == null) {
443                     pageSkipped(linkURI, "link does not share same root as parent");
444                     continue;
445                 }
446
447                 if (!isIncluded(linkTarget.getSourceURI())) {
448                     pageSkipped(linkTarget.getSourceURI(), "matched include/exclude rules");
449                     continue;
450                 }
451
452                 if (!crawler.hasTranslatedLink(linkTarget)) {
453                     try {
454                         final String JavaDoc mimeType =
455                                 getType(linkTarget.getDeparameterizedSourceURI(), linkTarget.getParameters());
456                         linkTarget.setMimeType(mimeType);
457                         crawler.addTranslatedLink(linkTarget);
458                         log.info(" Link translated: " + linkTarget.getSourceURI());
459                         if (crawler.addTarget(linkTarget)) {
460                             newLinkCount++;
461                         }
462                     } catch (ProcessingException pe) {
463                         this.sendBrokenLinkWarning(linkTarget.getSourceURI(), pe.getMessage());
464                         if (this.brokenLinkGenerate) {
465                            if (crawler.addTarget(linkTarget)) {
466                                newLinkCount++;
467                            }
468                         }
469                     }
470                 } else {
471                     String JavaDoc originalURI = linkTarget.getOriginalSourceURI();
472                     linkTarget = crawler.getTranslatedLink(linkTarget);
473                     linkTarget.setOriginalURI(originalURI);
474                 }
475
476                 translatedLinks.put(linkTarget.getOriginalSourceURI(), linkTarget.getTranslatedURI(target.getPath()));
477             }
478
479             linkCount = translatedLinks.size();
480         }
481
482         try {
483             // Process URI
484
DelayedOutputStream output = new DelayedOutputStream();
485             try {
486                 List JavaDoc gatheredLinks;
487                 if (!target.confirmExtensions() && target.followLinks() && isCrawlablePage(target)) {
488                     gatheredLinks = new ArrayList JavaDoc();
489                 } else {
490                     gatheredLinks = null;
491                 }
492
493                 status =
494                     getPage(
495                         target.getDeparameterizedSourceURI(),
496                         getLastModified(target),
497                         target.getParameters(),
498                         target.confirmExtensions() ? translatedLinks : null,
499                         gatheredLinks,
500                         output);
501
502                 if (status >= 400) {
503                     throw new ProcessingException(
504                         "Resource not found: " + status);
505                 }
506
507                 if (gatheredLinks != null) {
508                     for (Iterator JavaDoc it = gatheredLinks.iterator();it.hasNext();) {
509                         String JavaDoc linkURI = (String JavaDoc) it.next();
510                         Target linkTarget = target.getDerivedTarget(linkURI);
511
512                         if (linkTarget == null) {
513                             pageSkipped(linkURI, "link does not share same root as parent");
514                             continue;
515                         }
516
517                         if (!isIncluded(linkTarget.getSourceURI())) {
518                             pageSkipped(linkTarget.getSourceURI(), "matched include/exclude rules");
519                             continue;
520                         }
521                         if (crawler.addTarget(linkTarget)) {
522                             newLinkCount++;
523                         }
524                     }
525                     linkCount = gatheredLinks.size();
526                 }
527
528             } catch (ProcessingException pe) {
529                 output.close();
530                 output = null;
531                 this.resourceUnavailable(target);
532                 this.sendBrokenLinkWarning(target.getSourceURI(),
533                     DefaultNotifyingBuilder.getRootCause(pe).getMessage());
534             } finally {
535                 if (output != null && status != -1) {
536
537                     ModifiableSource source = getSource(target);
538                     try {
539                         pageSize = output.size();
540                         
541                         if (this.checksumsURI == null || !isSameContent(output, target)) {
542                             OutputStream stream = source.getOutputStream();
543                             output.setFileOutputStream(stream);
544                             output.flush();
545                             output.close();
546                             pageGenerated(target.getSourceURI(),
547                                           target.getAuthlessDestURI(),
548                                           pageSize,
549                                           linkCount,
550                                           newLinkCount,
551                                           crawler.getRemainingCount(),
552                                           crawler.getProcessedCount(),
553                                           System.currentTimeMillis()- startTimeMillis);
554                         } else {
555                             output.close();
556                             pageSkipped(target.getSourceURI(), "Page not changed");
557                         }
558                     } catch (IOException JavaDoc ioex) {
559                         log.warn(ioex.toString());
560                     } finally {
561                         releaseSource(source);
562                     }
563                 }
564             }
565         } catch (Exception JavaDoc rnfe) {
566             log.warn("Could not process URI: " + target.getSourceURI());
567             rnfe.printStackTrace();
568             this.sendBrokenLinkWarning(target.getSourceURI(), "URI not found: "+rnfe.getMessage());
569         }
570     }
571
572     /**
573      * Generate a <code>resourceUnavailable</code> message.
574      *
575      * @param target being unavailable
576      * @exception IOException if an error occurs
577      */

578     private void resourceUnavailable(Target target)
579         throws IOException JavaDoc, ProcessingException {
580         if (brokenLinkGenerate) {
581             //Why decode this URI now?
582
//String brokenFile = NetUtils.decodePath(destinationURI);
583

584             if (brokenLinkExtension != null) {
585                 target.setExtraExtension(brokenLinkExtension);
586             }
587             SimpleNotifyingBean n = new SimpleNotifyingBean(this);
588             n.setType("resource-not-found");
589             n.setTitle("Resource not Found");
590             n.setSource("Cocoon commandline (Main.java)");
591             n.setMessage("Page Not Available.");
592             n.setDescription("The requested resource couldn't be found.");
593             n.addExtraDescription(Notifying.EXTRA_REQUESTURI, target.getSourceURI());
594             n.addExtraDescription("missing-file", target.getSourceURI());
595
596             ModifiableSource source = getSource(target);
597             try {
598                 OutputStream stream = source.getOutputStream();
599
600                 PrintStream JavaDoc out = new PrintStream JavaDoc(stream);
601                 Notifier.notify(n, out, "text/html");
602                 out.flush();
603                 out.close();
604             } finally {
605                 releaseSource(source);
606             }
607         }
608     }
609
610     public ModifiableSource getSource(Target target)
611         throws IOException JavaDoc, ProcessingException {
612         final String JavaDoc finalDestinationURI = target.getDestinationURI();
613         Source src = sourceResolver.resolveURI(finalDestinationURI);
614         if (!(src instanceof ModifiableSource)) {
615             sourceResolver.release(src);
616             throw new ProcessingException(
617                 "Source is not Modifiable: " + finalDestinationURI);
618         }
619         return (ModifiableSource) src;
620     }
621
622     public long getLastModified(Target target) throws IOException JavaDoc, ProcessingException {
623         Source src = getSource(target);
624         long lastModified = src.getLastModified();
625         this.releaseSource(src);
626         return lastModified;
627     }
628
629     public void releaseSource(Source source) {
630         sourceResolver.release(source);
631     }
632     private boolean isIncluded(String JavaDoc uri) {
633         boolean included;
634         Iterator JavaDoc i;
635         HashMap JavaDoc map = new HashMap JavaDoc();
636
637         if (includePatterns.size() == 0) {
638             included = true;
639         } else {
640             included = false;
641             i = includePatterns.iterator();
642             while (i.hasNext()){
643                 int pattern[] = (int[])i.next();
644                 if (WildcardHelper.match(map, uri, pattern)) {
645                     included=true;
646                     break;
647                 }
648             }
649         }
650         if (excludePatterns.size() != 0) {
651             i = excludePatterns.iterator();
652             while (i.hasNext()) {
653                 int pattern[] = (int[])i.next();
654                 if (WildcardHelper.match(map, uri, pattern)) {
655                     included=false;
656                     break;
657                 }
658             }
659         }
660         return included;
661     }
662     private boolean isCrawlablePage(Target target) {
663         if (includeLinkExtensions == null) {
664             return true;
665         } else {
666             return includeLinkExtensions.contains(target.getExtension());
667         }
668     }
669
670     /* NB. This is a temporary solution - it may well be replaced by storing the checksum info
671      * in the XML 'report' file, along with details of what pages were created, etc.
672      */

673     private void readChecksumFile() throws Exception JavaDoc {
674         checksums = new HashMap JavaDoc();
675         
676         try {
677             Source checksumSource = sourceResolver.resolveURI(checksumsURI);
678             BufferedReader JavaDoc reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(checksumSource.getInputStream()));
679             String JavaDoc line;
680             int lineNo=0;
681             while ((line = reader.readLine())!=null) {
682                 lineNo++;
683                 if (line.trim().startsWith("#") || line.trim().length()==0 ) {
684                     continue;
685                 }
686                 if (line.indexOf("\t")==-1) {
687                     throw new ProcessingException("Missing tab at line "+lineNo+" of " + checksumsURI);
688                 }
689                 String JavaDoc filename = line.substring(0,line.indexOf("\t"));
690                 String JavaDoc checksum = line.substring(line.indexOf("\t")+1);
691                 checksums.put(filename, checksum);
692             }
693             reader.close();
694         } catch (SourceNotFoundException e) {
695             // return leaving checksums map empty
696
}
697     }
698     
699     private void writeChecksumFile() throws Exception JavaDoc {
700         Source checksumSource = sourceResolver.resolveURI(checksumsURI);
701         if (!(checksumSource instanceof ModifiableSource)) {
702             throw new ProcessingException("Checksum file is not Modifiable:" + checksumSource);
703         }
704         ModifiableSource source = (ModifiableSource) checksumSource;
705         PrintWriter JavaDoc writer = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(source.getOutputStream()));
706         Iterator JavaDoc i = checksums.keySet().iterator();
707         while (i.hasNext()){
708             String JavaDoc key = (String JavaDoc) i.next();
709             String JavaDoc checksum = (String JavaDoc) checksums.get(key);
710             writer.println(key + "\t" + checksum);
711         }
712         writer.close();
713     }
714
715     private boolean isSameContent(DelayedOutputStream stream, Target target) {
716         try {
717             MessageDigest JavaDoc md5 = MessageDigest.getInstance("MD5");
718             md5.update(stream.getContent());
719             String JavaDoc streamDigest = SourceUtil.encodeBASE64(new String JavaDoc(md5.digest()));
720             String JavaDoc targetDigest = (String JavaDoc)checksums.get(target.getSourceURI());
721             
722             if (streamDigest.equals(targetDigest)) {
723                 return true;
724             } else {
725                 checksums.put(target.getSourceURI(), streamDigest);
726                 return false;
727             }
728         } catch (NoSuchAlgorithmException JavaDoc e) {
729             // or do something:
730
return false;
731         }
732     }
733     /**
734      * Print a description of the software before running
735      */

736     public static String JavaDoc getProlog() {
737         String JavaDoc lSep = SystemUtils.LINE_SEPARATOR;
738         StringBuffer JavaDoc msg = new StringBuffer JavaDoc();
739         msg.append("------------------------------------------------------------------------ ").append(lSep);
740         msg.append(Constants.NAME).append(" ").append(Constants.VERSION).append(lSep);
741         msg.append("Copyright (c) ").append(Constants.YEAR).append(" Apache Software Foundation. All rights reserved.").append(lSep);
742         msg.append("------------------------------------------------------------------------ ").append(lSep).append(lSep);
743         return msg.toString();
744     }
745 }
746
Popular Tags