1    
2    /* ====================================================================
3     * The Apache Software License, Version 1.1
4     *
5     * Copyright (c) 2002 The Apache Software Foundation.  All rights
6     * reserved.
7     *
8     * Redistribution and use in source and binary forms, with or without
9     * modification, are permitted provided that the following conditions
10    * are met:
11    *
12    * 1. Redistributions of source code must retain the above copyright
13    *    notice, this list of conditions and the following disclaimer.
14    *
15    * 2. Redistributions in binary form must reproduce the above copyright
16    *    notice, this list of conditions and the following disclaimer in
17    *    the documentation and/or other materials provided with the
18    *    distribution.
19    *
20    * 3. The end-user documentation included with the redistribution,
21    *    if any, must include the following acknowledgment:
22    *       "This product includes software developed by the
23    *        Apache Software Foundation (http://www.apache.org/)."
24    *    Alternately, this acknowledgment may appear in the software itself,
25    *    if and wherever such third-party acknowledgments normally appear.
26    *
27    * 4. The names "Apache" and "Apache Software Foundation" and
28    *    "Apache POI" must not be used to endorse or promote products
29    *    derived from this software without prior written permission. For
30    *    written permission, please contact apache@apache.org.
31    *
32    * 5. Products derived from this software may not be called "Apache",
33    *    "Apache POI", nor may "Apache" appear in their name, without
34    *    prior written permission of the Apache Software Foundation.
35    *
36    * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37    * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38    * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39    * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40    * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41    * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42    * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43    * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44    * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45    * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46    * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47    * SUCH DAMAGE.
48    * ====================================================================
49    *
50    * This software consists of voluntary contributions made by many
51    * individuals on behalf of the Apache Software Foundation.  For more
52    * information on the Apache Software Foundation, please see
53    * <http://www.apache.org/>.
54    */
55   
56   package org.apache.poi.poifs.storage;
57   
58   import java.io.*;
59   
60   import java.util.*;
61   
62   import org.apache.poi.poifs.common.POIFSConstants;
63   
64   /**
65    * Storage for documents that are too small to use regular
66    * DocumentBlocks for their data
67    *
68    * @author  Marc Johnson (mjohnson at apache dot org)
69    */
70   
71   public class SmallDocumentBlock
72       implements BlockWritable, ListManagedBlock
73   {
74       private byte[]            _data;
75       private static final byte _default_fill         = ( byte ) 0xff;
76       private static final int  _block_size           = 64;
77       private static final int  _blocks_per_big_block =
78           POIFSConstants.BIG_BLOCK_SIZE / _block_size;
79   
80       private SmallDocumentBlock(final byte [] data, final int index)
81       {
82           this();
83           System.arraycopy(data, index * _block_size, _data, 0, _block_size);
84       }
85   
86       private SmallDocumentBlock()
87       {
88           _data = new byte[ _block_size ];
89       }
90   
91       /**
92        * convert a single long array into an array of SmallDocumentBlock
93        * instances
94        *
95        * @param array the byte array to be converted
96        * @param size the intended size of the array (which may be smaller)
97        *
98        * @return an array of SmallDocumentBlock instances, filled from
99        *         the array
100       */
101  
102      public static SmallDocumentBlock [] convert(final byte [] array,
103                                                  final int size)
104      {
105          SmallDocumentBlock[] rval   =
106              new SmallDocumentBlock[ (size + _block_size - 1) / _block_size ];
107          int                  offset = 0;
108  
109          for (int k = 0; k < rval.length; k++)
110          {
111              rval[ k ] = new SmallDocumentBlock();
112              if (offset < array.length)
113              {
114                  int length = Math.min(_block_size, array.length - offset);
115  
116                  System.arraycopy(array, offset, rval[ k ]._data, 0, length);
117                  if (length != _block_size)
118                  {
119                      Arrays.fill(rval[ k ]._data, length, _block_size,
120                                  _default_fill);
121                  }
122              }
123              else
124              {
125                  Arrays.fill(rval[ k ]._data, _default_fill);
126              }
127              offset += _block_size;
128          }
129          return rval;
130      }
131  
132      /**
133       * fill out a List of SmallDocumentBlocks so that it fully occupies
134       * a set of big blocks
135       *
136       * @param blocks the List to be filled out
137       *
138       * @return number of big blocks the list encompasses
139       */
140  
141      public static int fill(final List blocks)
142      {
143          int count           = blocks.size();
144          int big_block_count = (count + _blocks_per_big_block - 1)
145                                / _blocks_per_big_block;
146          int full_count      = big_block_count * _blocks_per_big_block;
147  
148          for (; count < full_count; count++)
149          {
150              blocks.add(makeEmptySmallDocumentBlock());
151          }
152          return big_block_count;
153      }
154  
155      /**
156       * Factory for creating SmallDocumentBlocks from DocumentBlocks
157       *
158       * @param store the original DocumentBlocks
159       * @param size the total document size
160       *
161       * @return an array of new SmallDocumentBlocks instances
162       *
163       * @exception IOException on errors reading from the DocumentBlocks
164       * @exception ArrayIndexOutOfBoundsException if, somehow, the store
165       *            contains less data than size indicates
166       */
167  
168      public static SmallDocumentBlock [] convert(final BlockWritable [] store,
169                                                  final int size)
170          throws IOException, ArrayIndexOutOfBoundsException
171      {
172          ByteArrayOutputStream stream = new ByteArrayOutputStream();
173  
174          for (int j = 0; j < store.length; j++)
175          {
176              store[ j ].writeBlocks(stream);
177          }
178          byte[]               data = stream.toByteArray();
179          SmallDocumentBlock[] rval =
180              new SmallDocumentBlock[ convertToBlockCount(size) ];
181  
182          for (int index = 0; index < rval.length; index++)
183          {
184              rval[ index ] = new SmallDocumentBlock(data, index);
185          }
186          return rval;
187      }
188  
189      /**
190       * create a list of SmallDocumentBlock's from raw data
191       *
192       * @param blocks the raw data containing the SmallDocumentBlock
193       *               data
194       *
195       * @return a List of SmallDocumentBlock's extracted from the input
196       *
197       * @exception IOException
198       */
199  
200      public static List extract(ListManagedBlock [] blocks)
201          throws IOException
202      {
203          List sdbs = new ArrayList();
204  
205          for (int j = 0; j < blocks.length; j++)
206          {
207              byte[] data = blocks[ j ].getData();
208  
209              for (int k = 0; k < _blocks_per_big_block; k++)
210              {
211                  sdbs.add(new SmallDocumentBlock(data, k));
212              }
213          }
214          return sdbs;
215      }
216  
217      /**
218       * read data from an array of SmallDocumentBlocks
219       *
220       * @param blocks the blocks to read from
221       * @param buffer the buffer to write the data into
222       * @param offset the offset into the array of blocks to read from
223       */
224  
225      public static void read(final BlockWritable [] blocks,
226                              final byte [] buffer, final int offset)
227      {
228          int firstBlockIndex  = offset / _block_size;
229          int firstBlockOffset = offset % _block_size;
230          int lastBlockIndex   = (offset + buffer.length - 1) / _block_size;
231  
232          if (firstBlockIndex == lastBlockIndex)
233          {
234              System.arraycopy(
235                  (( SmallDocumentBlock ) blocks[ firstBlockIndex ])._data,
236                  firstBlockOffset, buffer, 0, buffer.length);
237          }
238          else
239          {
240              int buffer_offset = 0;
241  
242              System.arraycopy(
243                  (( SmallDocumentBlock ) blocks[ firstBlockIndex ])._data,
244                  firstBlockOffset, buffer, buffer_offset,
245                  _block_size - firstBlockOffset);
246              buffer_offset += _block_size - firstBlockOffset;
247              for (int j = firstBlockIndex + 1; j < lastBlockIndex; j++)
248              {
249                  System.arraycopy((( SmallDocumentBlock ) blocks[ j ])._data,
250                                   0, buffer, buffer_offset, _block_size);
251                  buffer_offset += _block_size;
252              }
253              System.arraycopy(
254                  (( SmallDocumentBlock ) blocks[ lastBlockIndex ])._data, 0,
255                  buffer, buffer_offset, buffer.length - buffer_offset);
256          }
257      }
258  
259      /**
260       * Calculate the storage size of a set of SmallDocumentBlocks
261       *
262       * @param size number of SmallDocumentBlocks
263       *
264       * @return total size
265       */
266  
267      public static int calcSize(int size)
268      {
269          return size * _block_size;
270      }
271  
272      private static SmallDocumentBlock makeEmptySmallDocumentBlock()
273      {
274          SmallDocumentBlock block = new SmallDocumentBlock();
275  
276          Arrays.fill(block._data, _default_fill);
277          return block;
278      }
279  
280      private static int convertToBlockCount(final int size)
281      {
282          return (size + _block_size - 1) / _block_size;
283      }
284  
285      /* ********** START implementation of BlockWritable ********** */
286  
287      /**
288       * Write the storage to an OutputStream
289       *
290       * @param stream the OutputStream to which the stored data should
291       *               be written
292       *
293       * @exception IOException on problems writing to the specified
294       *            stream
295       */
296  
297      public void writeBlocks(final OutputStream stream)
298          throws IOException
299      {
300          stream.write(_data);
301      }
302  
303      /* **********  END  implementation of BlockWritable ********** */
304      /* ********** START implementation of ListManagedBlock ********** */
305  
306      /**
307       * Get the data from the block
308       *
309       * @return the block's data as a byte array
310       *
311       * @exception IOException if there is no data
312       */
313  
314      public byte [] getData()
315          throws IOException
316      {
317          return _data;
318      }
319  
320      /* **********  END  implementation of ListManagedBlock ********** */
321  }   // end public class SmallDocumentBlock
322  
323