KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > batik > util > Base64Test


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

18 package org.apache.batik.util;
19
20 import org.apache.batik.test.AbstractTest;
21 import org.apache.batik.test.DefaultTestReport;
22 import org.apache.batik.test.TestReport;
23
24 import java.io.PipedOutputStream JavaDoc;
25 import java.io.PipedInputStream JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.StringWriter JavaDoc;
30 import java.io.PrintWriter JavaDoc;
31
32 import java.net.URL JavaDoc;
33
34 /**
35  * This test validates that the Base65 encoder/decoders work properly.
36  *
37  * @author <a HREF="mailto:deweese@apache.org">Thomas DeWeese</a>
38  * @version $Id: Base64Test.java,v 1.6 2004/08/18 07:17:15 vhardy Exp $
39  */

40 public class Base64Test extends AbstractTest {
41     /**
42      * Error when bad action string given.
43      * {0} = Bad action string
44      */

45     public static final String JavaDoc ERROR_BAD_ACTION_STRING
46         = "Base64Test.error.bad.action.string";
47
48     /**
49      * Error when unable to read/open in URL
50      * {0} = URL
51      * {1} = exception stack trace.
52      */

53     public static final String JavaDoc ERROR_CANNOT_READ_IN_URL
54         = "Base64Test.error.cannot.read.in.url";
55
56     /**
57      * Error when unable to read/open ref URL
58      * {0} = URL
59      * {1} = exception stack trace.
60      */

61     public static final String JavaDoc ERROR_CANNOT_READ_REF_URL
62         = "Base64Test.error.cannot.read.ref.url";
63
64     /**
65      * Result didn't match reference result.
66      * {0} = first byte of mismatch
67      */

68     public static final String JavaDoc ERROR_WRONG_RESULT
69         = "Base64Test.error.wrong.result";
70
71     public static final String JavaDoc ENTRY_KEY_ERROR_DESCRIPTION
72         = "Base64Test.entry.key.error.description";
73
74     protected String JavaDoc action = null;
75     protected URL JavaDoc in = null;
76     protected URL JavaDoc ref = null;
77
78     /**
79      * Constructor. ref is ignored if action == ROUND.
80      * @param action The action to perform, one of:
81      * ROUND : base64 encode then base64 decode.
82      * ENCODE : encode in to base 64 and compare result to ref.
83      * DECODE : decode in (must be base 64) and compare to ref.
84      * @param in The source file to apply 'action' to.
85      * @param ref The reference file.
86      */

87     public Base64Test(String JavaDoc action, URL JavaDoc in, URL JavaDoc ref) {
88         this.action = action;
89         this.in = in;
90         this.ref = ref;
91     }
92
93     /**
94      * Constructor, for round trip testing (only one file required).
95      * @param in The source file to round trip.
96      */

97     public Base64Test(URL JavaDoc in) {
98         this.action = "ROUND";
99         this.in = in;
100     }
101
102     /**
103      * Returns this Test's name
104      */

105     public String JavaDoc getName() {
106         return action + " -- " + in + " -- " + super.getName();
107     }
108
109     /**
110      * This method will only throw exceptions if some aspect
111      * of the test's internal operation fails.
112      */

113     public TestReport runImpl() throws Exception JavaDoc {
114         DefaultTestReport report
115             = new DefaultTestReport(this);
116
117         InputStream JavaDoc inIS;
118
119         try {
120             inIS = in.openStream();
121         } catch(Exception JavaDoc e) {
122             StringWriter JavaDoc trace = new StringWriter JavaDoc();
123             e.printStackTrace(new PrintWriter JavaDoc(trace));
124             report.setErrorCode(ERROR_CANNOT_READ_IN_URL);
125             report.setDescription(new TestReport.Entry[] {
126                 new TestReport.Entry
127                     (TestMessages.formatMessage
128                      (ENTRY_KEY_ERROR_DESCRIPTION, null),
129                      TestMessages.formatMessage
130                      (ERROR_CANNOT_READ_IN_URL,
131                       new String JavaDoc[]{in.toString(), trace.toString()}))
132                     });
133             report.setPassed(false);
134             return report;
135         }
136
137         if (action.equals("ROUND"))
138             this.ref = in;
139         else if (!action.equals("ENCODE") &&
140                  !action.equals("DECODE")) {
141             report.setErrorCode(ERROR_BAD_ACTION_STRING);
142             report.setDescription(new TestReport.Entry[] {
143                 new TestReport.Entry
144                     (TestMessages.formatMessage
145                      (ENTRY_KEY_ERROR_DESCRIPTION, null),
146                      TestMessages.formatMessage(ERROR_BAD_ACTION_STRING,
147                                             new String JavaDoc[]{action}))
148                     });
149             report.setPassed(false);
150             return report;
151         }
152
153         InputStream JavaDoc refIS;
154         try {
155             refIS = ref.openStream();
156         } catch(Exception JavaDoc e) {
157             StringWriter JavaDoc trace = new StringWriter JavaDoc();
158             e.printStackTrace(new PrintWriter JavaDoc(trace));
159             report.setErrorCode(ERROR_CANNOT_READ_REF_URL);
160             report.setDescription(new TestReport.Entry[] {
161                 new TestReport.Entry
162                     (TestMessages.formatMessage
163                      (ENTRY_KEY_ERROR_DESCRIPTION, null),
164                      TestMessages.formatMessage
165                      (ERROR_CANNOT_READ_REF_URL,
166                       new String JavaDoc[]{ref.toString(), trace.toString()}))
167                     });
168             report.setPassed(false);
169             return report;
170         }
171
172         if (action.equals("ENCODE") ||
173             action.equals("ROUND")) {
174           // We need to encode the incomming data
175
PipedOutputStream JavaDoc pos = new PipedOutputStream JavaDoc();
176           OutputStream JavaDoc os = new Base64EncoderStream(pos);
177
178           // Copy the input to the Base64 Encoder (in a seperate thread).
179
Thread JavaDoc t = new StreamCopier(inIS, os);
180           
181           // Read that from the piped output stream.
182
inIS = new PipedInputStream JavaDoc(pos);
183           t.start();
184         }
185
186         if (action.equals("DECODE")||
187             action.equals("ROUND")) {
188             inIS = new Base64DecodeStream(inIS);
189         }
190
191
192         int mismatch = compareStreams(inIS, refIS, action.equals("ENCODE"));
193         
194         if (mismatch == -1) {
195           report.setPassed(true);
196           return report;
197         }
198
199         report.setErrorCode(ERROR_WRONG_RESULT);
200         report.setDescription(new TestReport.Entry[] {
201           new TestReport.Entry
202             (TestMessages.formatMessage(ENTRY_KEY_ERROR_DESCRIPTION, null),
203              TestMessages.formatMessage(ERROR_WRONG_RESULT,
204                                     new String JavaDoc[]{""+mismatch}))
205             });
206         report.setPassed(false);
207         return report;
208     }
209
210     /**
211      * Returns true if the contents of <tt>is1</tt> match the
212      * contents of <tt>is2</tt>
213      */

214     public static int compareStreams(InputStream JavaDoc is1, InputStream JavaDoc is2,
215                               boolean skipws) {
216         byte [] data1 = new byte[100];
217         byte [] data2 = new byte[100];
218         int off1=0;
219         int off2=0;
220         int idx=0;
221
222         try {
223             while(true) {
224                 int len1 = is1.read(data1, off1, data1.length-off1);
225                 int len2 = is2.read(data2, off2, data2.length-off2);
226
227                 if (off1 != 0) {
228                     if (len1 == -1)
229                         len1 = off1;
230                     else
231                         len1 += off1;
232                 }
233
234                 if (off2 != 0) {
235                     if (len2 == -1)
236                         len2 = off2;
237                     else
238                         len2 += off2;
239                 }
240
241                 if (len1 == -1) {
242                     if (len2 == -1)
243                         break; // Both done...
244

245                     // Only is1 is done...
246
if (!skipws)
247                         return idx;
248
249                     // check if the rest of is2 is whitespace...
250
for (int i2=0; i2<len2; i2++)
251                         if ((data2[i2] != '\n') &&
252                             (data2[i2] != '\r') &&
253                             (data2[i2] != ' '))
254                             return idx+i2;
255                     off1 = off2 = 0;
256                     continue;
257                 }
258
259                 if (len2 == -1) {
260                     // Only is2 is done...
261
if (!skipws)
262                         return idx;
263
264                     // Check if rest of is1 is whitespace...
265
for (int i1=0; i1<len1; i1++)
266                         if ((data1[i1] != '\n') &&
267                             (data1[i1] != '\r') &&
268                             (data1[i1] != ' '))
269                             return idx+i1;
270                     off1 = off2 = 0;
271                     continue;
272                 }
273
274                 int i1=0;
275                 int i2=0;
276                 while((i1<len1) && (i2<len2)) {
277                     if (skipws) {
278                         if ((data1[i1] == '\n') ||
279                             (data1[i1] == '\r') ||
280                             (data1[i1] == ' ')) {
281                             i1++;
282                             continue;
283                         }
284                         if ((data2[i2] == '\n') ||
285                             (data2[i2] == '\r') ||
286                             (data2[i2] == ' ')) {
287                             i2++;
288                             continue;
289                         }
290                     }
291                     if (data1[i1] != data2[i2])
292                         return idx+i2;
293
294                     i1++;
295                     i2++;
296                 }
297
298                 if (i1 != len1)
299                     System.arraycopy(data1, i1, data1, 0, len1-i1);
300                 if (i2 != len2)
301                     System.arraycopy(data2, i2, data2, 0, len2-i2);
302                 off1 = len1-i1;
303                 off2 = len2-i2;
304                 idx+=i2;
305             }
306         } catch(IOException JavaDoc ioe) {
307             ioe.printStackTrace();
308             return idx;
309         }
310
311         return -1;
312     }
313
314
315     static class StreamCopier extends Thread JavaDoc {
316         InputStream JavaDoc src;
317         OutputStream JavaDoc dst;
318
319         public StreamCopier(InputStream JavaDoc src,
320                             OutputStream JavaDoc dst) {
321             this.src = src;
322             this.dst = dst;
323         }
324
325         public void run() {
326             try {
327                 byte [] data = new byte[1000];
328                 while(true) {
329                     int len = src.read(data, 0, data.length);
330                     if (len == -1) break;
331
332                     dst.write(data, 0, len);
333                 }
334             } catch (IOException JavaDoc ioe) {
335                 // Nothing
336
}
337             try {
338                 dst.close();
339             } catch (IOException JavaDoc ioe) {
340                 // Nothing
341
}
342         }
343     }
344 }
345
Popular Tags