KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > tools > tar > TarOutputStream


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. 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
19 /*
20  * This package is based on the work done by Timothy Gerard Endres
21  * (time@ice.com) to whom the Ant project is very grateful for his great code.
22  */

23
24 package org.apache.tools.tar;
25
26 import java.io.FilterOutputStream JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import java.io.IOException JavaDoc;
29
30 /**
31  * The TarOutputStream writes a UNIX tar archive as an OutputStream.
32  * Methods are provided to put entries, and then write their contents
33  * by writing to this stream using write().
34  *
35  */

36 public class TarOutputStream extends FilterOutputStream JavaDoc {
37     /** Fail if a long file name is required in the archive. */
38     public static final int LONGFILE_ERROR = 0;
39
40     /** Long paths will be truncated in the archive. */
41     public static final int LONGFILE_TRUNCATE = 1;
42
43     /** GNU tar extensions are used to store long file names in the archive. */
44     public static final int LONGFILE_GNU = 2;
45
46     // CheckStyle:VisibilityModifier OFF - bc
47
protected boolean debug;
48     protected long currSize;
49     protected String JavaDoc currName;
50     protected long currBytes;
51     protected byte[] oneBuf;
52     protected byte[] recordBuf;
53     protected int assemLen;
54     protected byte[] assemBuf;
55     protected TarBuffer buffer;
56     protected int longFileMode = LONGFILE_ERROR;
57     // CheckStyle:VisibilityModifier ON
58

59     private boolean closed = false;
60
61     /**
62      * Constructor for TarInputStream.
63      * @param os the output stream to use
64      */

65     public TarOutputStream(OutputStream JavaDoc os) {
66         this(os, TarBuffer.DEFAULT_BLKSIZE, TarBuffer.DEFAULT_RCDSIZE);
67     }
68
69     /**
70      * Constructor for TarInputStream.
71      * @param os the output stream to use
72      * @param blockSize the block size to use
73      */

74     public TarOutputStream(OutputStream JavaDoc os, int blockSize) {
75         this(os, blockSize, TarBuffer.DEFAULT_RCDSIZE);
76     }
77
78     /**
79      * Constructor for TarInputStream.
80      * @param os the output stream to use
81      * @param blockSize the block size to use
82      * @param recordSize the record size to use
83      */

84     public TarOutputStream(OutputStream JavaDoc os, int blockSize, int recordSize) {
85         super(os);
86
87         this.buffer = new TarBuffer(os, blockSize, recordSize);
88         this.debug = false;
89         this.assemLen = 0;
90         this.assemBuf = new byte[recordSize];
91         this.recordBuf = new byte[recordSize];
92         this.oneBuf = new byte[1];
93     }
94
95     /**
96      * Set the long file mode.
97      * This can be LONGFILE_ERROR(0), LONGFILE_TRUNCATE(1) or LONGFILE_GNU(2).
98      * This specifies the treatment of long file names (names >= TarConstants.NAMELEN).
99      * Default is LONGFILE_ERROR.
100      * @param longFileMode the mode to use
101      */

102     public void setLongFileMode(int longFileMode) {
103         this.longFileMode = longFileMode;
104     }
105
106
107     /**
108      * Sets the debugging flag.
109      *
110      * @param debugF True to turn on debugging.
111      */

112     public void setDebug(boolean debugF) {
113         this.debug = debugF;
114     }
115
116     /**
117      * Sets the debugging flag in this stream's TarBuffer.
118      *
119      * @param debug True to turn on debugging.
120      */

121     public void setBufferDebug(boolean debug) {
122         this.buffer.setDebug(debug);
123     }
124
125     /**
126      * Ends the TAR archive without closing the underlying OutputStream.
127      * The result is that the two EOF records of nulls are written.
128      * @throws IOException on error
129      */

130     public void finish() throws IOException JavaDoc {
131         // See Bugzilla 28776 for a discussion on this
132
// http://issues.apache.org/bugzilla/show_bug.cgi?id=28776
133
this.writeEOFRecord();
134         this.writeEOFRecord();
135     }
136
137     /**
138      * Ends the TAR archive and closes the underlying OutputStream.
139      * This means that finish() is called followed by calling the
140      * TarBuffer's close().
141      * @throws IOException on error
142      */

143     public void close() throws IOException JavaDoc {
144         if (!closed) {
145             this.finish();
146             this.buffer.close();
147             out.close();
148             closed = true;
149         }
150     }
151
152     /**
153      * Get the record size being used by this stream's TarBuffer.
154      *
155      * @return The TarBuffer record size.
156      */

157     public int getRecordSize() {
158         return this.buffer.getRecordSize();
159     }
160
161     /**
162      * Put an entry on the output stream. This writes the entry's
163      * header record and positions the output stream for writing
164      * the contents of the entry. Once this method is called, the
165      * stream is ready for calls to write() to write the entry's
166      * contents. Once the contents are written, closeEntry()
167      * <B>MUST</B> be called to ensure that all buffered data
168      * is completely written to the output stream.
169      *
170      * @param entry The TarEntry to be written to the archive.
171      * @throws IOException on error
172      */

173     public void putNextEntry(TarEntry entry) throws IOException JavaDoc {
174         if (entry.getName().length() >= TarConstants.NAMELEN) {
175
176             if (longFileMode == LONGFILE_GNU) {
177                 // create a TarEntry for the LongLink, the contents
178
// of which are the entry's name
179
TarEntry longLinkEntry = new TarEntry(TarConstants.GNU_LONGLINK,
180                                                       TarConstants.LF_GNUTYPE_LONGNAME);
181
182                 longLinkEntry.setSize(entry.getName().length() + 1);
183                 putNextEntry(longLinkEntry);
184                 write(entry.getName().getBytes());
185                 write(0);
186                 closeEntry();
187             } else if (longFileMode != LONGFILE_TRUNCATE) {
188                 throw new RuntimeException JavaDoc("file name '" + entry.getName()
189                                              + "' is too long ( > "
190                                              + TarConstants.NAMELEN + " bytes)");
191             }
192         }
193
194         entry.writeEntryHeader(this.recordBuf);
195         this.buffer.writeRecord(this.recordBuf);
196
197         this.currBytes = 0;
198
199         if (entry.isDirectory()) {
200             this.currSize = 0;
201         } else {
202             this.currSize = entry.getSize();
203         }
204         currName = entry.getName();
205     }
206
207     /**
208      * Close an entry. This method MUST be called for all file
209      * entries that contain data. The reason is that we must
210      * buffer data written to the stream in order to satisfy
211      * the buffer's record based writes. Thus, there may be
212      * data fragments still being assembled that must be written
213      * to the output stream before this entry is closed and the
214      * next entry written.
215      * @throws IOException on error
216      */

217     public void closeEntry() throws IOException JavaDoc {
218         if (this.assemLen > 0) {
219             for (int i = this.assemLen; i < this.assemBuf.length; ++i) {
220                 this.assemBuf[i] = 0;
221             }
222
223             this.buffer.writeRecord(this.assemBuf);
224
225             this.currBytes += this.assemLen;
226             this.assemLen = 0;
227         }
228
229         if (this.currBytes < this.currSize) {
230             throw new IOException JavaDoc("entry '" + currName + "' closed at '"
231                                   + this.currBytes
232                                   + "' before the '" + this.currSize
233                                   + "' bytes specified in the header were written");
234         }
235     }
236
237     /**
238      * Writes a byte to the current tar archive entry.
239      *
240      * This method simply calls read( byte[], int, int ).
241      *
242      * @param b The byte written.
243      * @throws IOException on error
244      */

245     public void write(int b) throws IOException JavaDoc {
246         this.oneBuf[0] = (byte) b;
247
248         this.write(this.oneBuf, 0, 1);
249     }
250
251     /**
252      * Writes bytes to the current tar archive entry.
253      *
254      * This method simply calls write( byte[], int, int ).
255      *
256      * @param wBuf The buffer to write to the archive.
257      * @throws IOException on error
258      */

259     public void write(byte[] wBuf) throws IOException JavaDoc {
260         this.write(wBuf, 0, wBuf.length);
261     }
262
263     /**
264      * Writes bytes to the current tar archive entry. This method
265      * is aware of the current entry and will throw an exception if
266      * you attempt to write bytes past the length specified for the
267      * current entry. The method is also (painfully) aware of the
268      * record buffering required by TarBuffer, and manages buffers
269      * that are not a multiple of recordsize in length, including
270      * assembling records from small buffers.
271      *
272      * @param wBuf The buffer to write to the archive.
273      * @param wOffset The offset in the buffer from which to get bytes.
274      * @param numToWrite The number of bytes to write.
275      * @throws IOException on error
276      */

277     public void write(byte[] wBuf, int wOffset, int numToWrite) throws IOException JavaDoc {
278         if ((this.currBytes + numToWrite) > this.currSize) {
279             throw new IOException JavaDoc("request to write '" + numToWrite
280                                   + "' bytes exceeds size in header of '"
281                                   + this.currSize + "' bytes for entry '"
282                                   + currName + "'");
283
284             //
285
// We have to deal with assembly!!!
286
// The programmer can be writing little 32 byte chunks for all
287
// we know, and we must assemble complete records for writing.
288
// REVIEW Maybe this should be in TarBuffer? Could that help to
289
// eliminate some of the buffer copying.
290
//
291
}
292
293         if (this.assemLen > 0) {
294             if ((this.assemLen + numToWrite) >= this.recordBuf.length) {
295                 int aLen = this.recordBuf.length - this.assemLen;
296
297                 System.arraycopy(this.assemBuf, 0, this.recordBuf, 0,
298                                  this.assemLen);
299                 System.arraycopy(wBuf, wOffset, this.recordBuf,
300                                  this.assemLen, aLen);
301                 this.buffer.writeRecord(this.recordBuf);
302
303                 this.currBytes += this.recordBuf.length;
304                 wOffset += aLen;
305                 numToWrite -= aLen;
306                 this.assemLen = 0;
307             } else {
308                 System.arraycopy(wBuf, wOffset, this.assemBuf, this.assemLen,
309                                  numToWrite);
310
311                 wOffset += numToWrite;
312                 this.assemLen += numToWrite;
313                 numToWrite -= numToWrite;
314             }
315         }
316
317         //
318
// When we get here we have EITHER:
319
// o An empty "assemble" buffer.
320
// o No bytes to write (numToWrite == 0)
321
//
322
while (numToWrite > 0) {
323             if (numToWrite < this.recordBuf.length) {
324                 System.arraycopy(wBuf, wOffset, this.assemBuf, this.assemLen,
325                                  numToWrite);
326
327                 this.assemLen += numToWrite;
328
329                 break;
330             }
331
332             this.buffer.writeRecord(wBuf, wOffset);
333
334             int num = this.recordBuf.length;
335
336             this.currBytes += num;
337             numToWrite -= num;
338             wOffset += num;
339         }
340     }
341
342     /**
343      * Write an EOF (end of archive) record to the tar archive.
344      * An EOF record consists of a record of all zeros.
345      */

346     private void writeEOFRecord() throws IOException JavaDoc {
347         for (int i = 0; i < this.recordBuf.length; ++i) {
348             this.recordBuf[i] = 0;
349         }
350
351         this.buffer.writeRecord(this.recordBuf);
352     }
353 }
354
355
356
Popular Tags