KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > jrcs > diff > print > UnifiedPrint


1 /*
2  * ====================================================================
3  *
4  * The Apache Software License, Version 1.1
5  *
6  * Copyright (c) 1999-2003 The Apache Software Foundation.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if
22  * any, must include the following acknowledgement:
23  * "This product includes software developed by the
24  * Apache Software Foundation (http://www.apache.org/)."
25  * Alternately, this acknowledgement may appear in the software itself,
26  * if and wherever such third-party acknowledgements normally appear.
27  *
28  * 4. The names "The Jakarta Project", "Commons", and "Apache Software
29  * Foundation" must not be used to endorse or promote products derived
30  * from this software without prior written permission. For written
31  * permission, please contact apache@apache.org.
32  *
33  * 5. Products derived from this software may not be called "Apache"
34  * nor may "Apache" appear in their names without prior written
35  * permission of the Apache Software Foundation.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals on behalf of the Apache Software Foundation. For more
53  * information on the Apache Software Foundation, please see
54  * <http://www.apache.org/>.
55  *
56  */

57
58 package org.apache.commons.jrcs.diff.print;
59
60 import java.io.BufferedReader JavaDoc;
61 import java.io.FileReader JavaDoc;
62 import java.io.IOException JavaDoc;
63 import java.text.DateFormat JavaDoc;
64 import java.text.SimpleDateFormat JavaDoc;
65 import java.util.ArrayList JavaDoc;
66 import java.util.Iterator JavaDoc;
67 import java.util.List JavaDoc;
68 import java.util.Locale JavaDoc;
69 import java.util.Stack JavaDoc;
70
71 import org.apache.commons.jrcs.diff.AddDelta;
72 import org.apache.commons.jrcs.diff.ChangeDelta;
73 import org.apache.commons.jrcs.diff.DeleteDelta;
74 import org.apache.commons.jrcs.diff.Delta;
75 import org.apache.commons.jrcs.diff.Revision;
76 import org.apache.commons.jrcs.diff.myers.MyersDiff;
77
78 /**
79  * Prints in the Unified print format.
80  *
81  * close() must be called on this instance after calling Revision.accept(unifiedPrint)
82  * in order to get the StringBuffer filled with all data.
83  *
84  * Sample use: <pre>
85  * String[] orig = getOriginal();
86  * String[] rev = getRevised();
87  * MyersDiff diff = new MyersDiff();
88  * Revision revision = diff.diff(orig, rev);
89  * StringBuffer sb = new StringBuffer();
90  * UnifiedPrint print = new UnifiedPrint(sb, orig, rev);
91  * revision.accept(print);
92  * print.close();
93  * </pre>
94  *
95  * @author <a HREF="mailto:ludovicc@users.sourceforge.net">Ludovic Claude</a>
96  * @version $Revision: 1.1 $ $Date: 2004/10/06 09:47:23 $
97  * @created on 27 janv. 2004
98  */

99 public class UnifiedPrint extends BasePrint {
100
101     private int nbContextLines = 3;
102     private Object JavaDoc[] original;
103     private Object JavaDoc[] revision;
104     private Stack JavaDoc changeBlocks = new Stack JavaDoc();
105     
106     /**
107      * Constructor for ContextPrint
108      * @param sb
109      */

110     public UnifiedPrint(StringBuffer JavaDoc sb, Object JavaDoc[] original, Object JavaDoc[] revision) {
111         super(sb);
112         this.original = original;
113         this.revision = revision;
114     }
115     
116     public void close() {
117         if (changeBlocks.isEmpty()) {
118             return;
119         }
120         ChangeBlock lastChangeBlock = (ChangeBlock) changeBlocks.peek();
121         if (lastChangeBlock != null) {
122             lastChangeBlock.fillEndBlock();
123         }
124         for (Iterator JavaDoc i = changeBlocks.iterator(); i.hasNext();) {
125             ChangeBlock changeBlock = (ChangeBlock) i.next();
126             changeBlock.print(getStringBuffer());
127         }
128     }
129
130     /**
131      * Gets the nbContextLines.
132      * @return the nbContextLines.
133      */

134     public int getNbContextLines() {
135         return nbContextLines;
136     }
137     
138     /**
139      * Sets the nbContextLines.
140      * @param nbContextLines The nbContextLines to set.
141      */

142     public void setNbContextLines(int nbContextLines) {
143         this.nbContextLines = nbContextLines;
144     }
145     
146     protected void printHeader() {
147         if (getFileName() == null) {
148             return;
149         }
150         
151         StringBuffer JavaDoc sb = getStringBuffer();
152         sb.append("Index: ");
153         sb.append(getFileName());
154         sb.append(getEOL());
155
156         sb.append("===================================================================");
157         sb.append(getEOL());
158         
159         sb.append("RCS File: ");
160         sb.append(getRCSFileName());
161         sb.append(getEOL());
162
163         if (getOriginalVersion() != null) {
164             sb.append("retrieving revision ");
165             sb.append(getOriginalVersion());
166             sb.append(getEOL());
167         }
168
169         if (getRevisedVersion() != null) {
170             sb.append("retrieving revision ");
171             sb.append(getRevisedVersion());
172             sb.append(getEOL());
173         }
174
175         sb.append("diff -u");
176         if (getOriginalVersion() != null) {
177             sb.append(" -r");
178             sb.append(getOriginalVersion());
179         }
180         if (getRevisedVersion() != null) {
181             sb.append(" -r");
182             sb.append(getRevisedVersion());
183         }
184         sb.append(" ");
185         String JavaDoc shortFileName = getFileName();
186         int pos = shortFileName.lastIndexOf('/');
187         if (pos >= 0) {
188             shortFileName = shortFileName.substring(pos + 1);
189         }
190         sb.append(shortFileName);
191         sb.append(getEOL());
192
193         DateFormat JavaDoc df = new SimpleDateFormat JavaDoc("d MMM yyyy HH:mm:ss -0000", Locale.US);
194         sb.append("--- ");
195         sb.append(getFileName());
196         if (getOriginalModifDate() != null) {
197             sb.append('\t');
198             sb.append(df.format(getOriginalModifDate()));
199             if (getOriginalVersion() != null) {
200                 sb.append('\t');
201                 sb.append(getOriginalVersion());
202             }
203         }
204         sb.append(getEOL());
205
206         sb.append("+++ ");
207         sb.append(getFileName());
208         if (getRevisedModifDate() != null) {
209             sb.append('\t');
210             sb.append(df.format(getRevisedModifDate()));
211             if (getRevisedVersion() != null) {
212                 sb.append('\t');
213                 sb.append(getRevisedVersion());
214             }
215         }
216         sb.append(getEOL());
217     }
218     
219     /**
220      * {@inheritDoc}
221      * @param delta
222      */

223     public void visit(AddDelta delta) {
224         super.visit(delta);
225         ChangeBlock lastChangeBlock = getLastChangeBlock(delta);
226         lastChangeBlock.addChange(delta);
227     }
228
229     /**
230      * {@inheritDoc}
231      * @param delta
232      */

233     public void visit(ChangeDelta delta) {
234         super.visit(delta);
235         ChangeBlock lastChangeBlock = getLastChangeBlock(delta);
236         lastChangeBlock.addChange(delta);
237     }
238
239     /**
240      * {@inheritDoc}
241      * @param delta
242      */

243     public void visit(DeleteDelta delta) {
244         super.visit(delta);
245         ChangeBlock lastChangeBlock = getLastChangeBlock(delta);
246         lastChangeBlock.addChange(delta);
247     }
248
249     /**
250      * Gets the original.
251      * @return the original.
252      */

253     protected Object JavaDoc[] getOriginal() {
254         return original;
255     }
256
257     /**
258      * Gets the revision.
259      * @return the revision.
260      */

261     protected Object JavaDoc[] getRevision() {
262         return revision;
263     }
264     
265     private ChangeBlock getLastChangeBlock(Delta delta) {
266         ChangeBlock lastChangeBlock = null;
267         if (!changeBlocks.isEmpty()) {
268             lastChangeBlock = (ChangeBlock) changeBlocks.peek();
269         }
270         if (lastChangeBlock == null || lastChangeBlock.getLastChangedLine() < delta.getOriginal().anchor() - getNbContextLines() * 2) {
271             if (lastChangeBlock != null) {
272                 lastChangeBlock.fillEndBlock();
273             }
274             lastChangeBlock = new ChangeBlock();
275             changeBlocks.add(lastChangeBlock);
276         }
277         return lastChangeBlock;
278     }
279
280     private class ChangeBlock {
281         private List JavaDoc deltas = new ArrayList JavaDoc();
282         private List JavaDoc changes = new ArrayList JavaDoc();
283         private int origNbLines = 0;
284         private int revNbLines = 0;
285         private int startOrig = 0;
286         private int startRev = 0;
287         
288         public int getLastChangedLine() {
289             Delta delta = (Delta) deltas.get(deltas.size() - 1);
290             return delta.getOriginal().last();
291         }
292         
293         public void addChange(AddDelta delta) {
294             initChangesBefore(delta);
295             deltas.add(delta);
296             for (int l = delta.getRevised().first(); l <= delta.getRevised().last(); l++) {
297                 changes.add("+" + getRevision()[l]);
298                 revNbLines++;
299             }
300         }
301
302         public void addChange(DeleteDelta delta) {
303             initChangesBefore(delta);
304             deltas.add(delta);
305             for (int l = delta.getOriginal().first(); l <= delta.getOriginal().last(); l++) {
306                 changes.add("-" + getOriginal()[l]);
307                 origNbLines++;
308             }
309         }
310
311         public void addChange(ChangeDelta delta) {
312             initChangesBefore(delta);
313             deltas.add(delta);
314             for (int l = delta.getOriginal().first(); l <= delta.getOriginal().last(); l++) {
315                 changes.add("-" + getOriginal()[l]);
316                 origNbLines++;
317             }
318             for (int l = delta.getRevised().first(); l <= delta.getRevised().last(); l++) {
319                 changes.add("+" + getRevision()[l]);
320                 revNbLines++;
321             }
322         }
323         
324         public void print(StringBuffer JavaDoc sb) {
325             sb.append("@@ -");
326             sb.append(startOrig);
327             sb.append(",");
328             sb.append(origNbLines);
329             sb.append(" +");
330             sb.append(startRev);
331             sb.append(",");
332             sb.append(revNbLines);
333             sb.append(" @@");
334             sb.append(getEOL());
335             for (Iterator JavaDoc i = changes.iterator(); i.hasNext();) {
336                 String JavaDoc line = (String JavaDoc) i.next();
337                 sb.append(line);
338                 sb.append(getEOL());
339             }
340         }
341         
342         public void fillEndBlock() {
343             Delta lastDelta = (Delta) deltas.get(deltas.size() - 1);
344             int l = lastDelta.getOriginal().last();
345             for (int i = l + 1; i <= l + getNbContextLines() && i < getOriginal().length; i++) {
346                 changes.add(" " + getOriginal()[i]);
347                 origNbLines++;
348                 revNbLines++;
349             }
350         }
351          
352         /**
353          * @param delta
354          */

355         private void initChangesBefore(Delta delta) {
356             int anchor = delta.getOriginal().anchor();
357             int lastChange = 0;
358             boolean firstChange = changes.isEmpty();
359             int border = firstChange ? getNbContextLines() : getNbContextLines() * 2;
360             if (firstChange) {
361                 startOrig = delta.getOriginal().rcsfrom();
362                 startRev = delta.getRevised().rcsfrom();
363             } else {
364                 Delta previousDelta = (Delta) deltas.get(deltas.size()-1);
365                 lastChange = previousDelta.getOriginal().last();
366             }
367             
368             for (int i = border; i > 0; i--) {
369                 if (anchor - i > lastChange && anchor >= i) {
370                     changes.add(" " + getOriginal()[anchor - i]);
371                     origNbLines++;
372                     revNbLines++;
373                     if (firstChange) {
374                         startOrig--;
375                         startRev--;
376                     }
377                 }
378             }
379         }
380     }
381     
382     private static final String JavaDoc[] loadFile(String JavaDoc name) throws IOException JavaDoc
383     {
384         BufferedReader JavaDoc data = new BufferedReader JavaDoc(new FileReader JavaDoc(name));
385         List JavaDoc lines = new ArrayList JavaDoc();
386         String JavaDoc s;
387         while ((s = data.readLine()) != null)
388         {
389             lines.add(s);
390         }
391         return (String JavaDoc[])lines.toArray(new String JavaDoc[lines.size()]);
392     }
393
394     
395     public static void main(String JavaDoc[] args) {
396         try {
397         String JavaDoc[] s1 = loadFile("c:/dev/CVSGrabTask.1.6.java");
398         String JavaDoc[] s2 = loadFile("c:/dev/CVSGrabTask.1.7.java");
399         MyersDiff diff = new MyersDiff();
400         Revision revision = diff.diff(s1, s2);
401         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
402         UnifiedPrint print = new UnifiedPrint(sb, s1, s2);
403         print.setFileName("src/java/net/sourceforge/cvsgrab/CVSGrabTask.java");
404         print.setRCSFileName("/cvsroot/cvsgrab/cvsgrab/src/java/net/sourceforge/cvsgrab/CVSGrabTask.java,v");
405         DateFormat JavaDoc df = new SimpleDateFormat JavaDoc("d MMM yyyy HH:mm:ss", Locale.US);
406         print.setOriginalModifDate(df.parse("31 Oct 2003 00:26:54"));
407         print.setOriginalVersion("1.6");
408         print.setRevisedModifDate(df.parse("31 Jan 2004 17:37:47"));
409         revision.accept(print);
410         print.close();
411         System.out.println(sb.toString());
412         } catch (Exception JavaDoc e) {
413             e.printStackTrace();
414         }
415     }
416 }
417
Popular Tags