KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lowagie > text > pdf > MappedRandomAccessFile


1 /*
2  * $Id: MappedRandomAccessFile.java 2515 2006-12-28 12:52:22Z psoares33 $
3  *
4  * Copyright 2006 Joakim Sandstroem
5  *
6  * The contents of this file are subject to the Mozilla Public License Version 1.1
7  * (the "License"); you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
9  *
10  * Software distributed under the License is distributed on an "AS IS" basis,
11  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
12  * for the specific language governing rights and limitations under the License.
13  *
14  * The Original Code is 'iText, a free JAVA-PDF library'.
15  *
16  * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
17  * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
18  * All Rights Reserved.
19  * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
20  * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
21  *
22  * Contributor(s): all the names of the contributors are added in the source code
23  * where applicable.
24  *
25  * Alternatively, the contents of this file may be used under the terms of the
26  * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
27  * provisions of LGPL are applicable instead of those above. If you wish to
28  * allow use of your version of this file only under the terms of the LGPL
29  * License and not to allow others to use your version of this file under
30  * the MPL, indicate your decision by deleting the provisions above and
31  * replace them with the notice and other provisions required by the LGPL.
32  * If you do not delete the provisions above, a recipient may use your version
33  * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
34  *
35  * This library is free software; you can redistribute it and/or modify it
36  * under the terms of the MPL as stated above or under the terms of the GNU
37  * Library General Public License as published by the Free Software Foundation;
38  * either version 2 of the License, or any later version.
39  *
40  * This library is distributed in the hope that it will be useful, but WITHOUT
41  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
42  * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more
43  * details.
44  *
45  * If you didn't download this code from the following link, you should check if
46  * you aren't using an obsolete version:
47  * http://www.lowagie.com/iText/
48  */

49 package com.lowagie.text.pdf;
50
51 import java.io.FileInputStream JavaDoc;
52 import java.io.FileNotFoundException JavaDoc;
53 import java.io.IOException JavaDoc;
54 import java.lang.reflect.Method JavaDoc;
55 import java.nio.BufferUnderflowException JavaDoc;
56 import java.nio.MappedByteBuffer JavaDoc;
57 import java.nio.channels.FileChannel JavaDoc;
58 import java.security.AccessController JavaDoc;
59 import java.security.PrivilegedAction JavaDoc;
60
61 /**
62  * A {@link java.nio.MappedByteBuffer} wrapped as a {@link java.io.RandomAccessFile}
63  *
64  * @author Joakim Sandstroem
65  * Created on 6.9.2006
66  */

67 public class MappedRandomAccessFile {
68     
69     private MappedByteBuffer JavaDoc mappedByteBuffer = null;
70     private FileChannel JavaDoc channel = null;
71     
72     /**
73      * Constructs a new MappedRandomAccessFile instance
74      * @param filename String
75      * @param mode String r, w or rw
76      * @throws FileNotFoundException
77      * @throws IOException
78      */

79     public MappedRandomAccessFile(String JavaDoc filename, String JavaDoc mode)
80     throws FileNotFoundException JavaDoc, IOException JavaDoc {
81         
82         if (mode.equals("rw"))
83             init(
84                     new java.io.RandomAccessFile JavaDoc(filename, mode).getChannel(),
85                     FileChannel.MapMode.READ_WRITE);
86         else
87             init(
88                     new FileInputStream JavaDoc(filename).getChannel(),
89                     FileChannel.MapMode.READ_ONLY);
90         
91     }
92     
93     /**
94      * initializes the channel and mapped bytebuffer
95      * @param channel FileChannel
96      * @param mapMode FileChannel.MapMode
97      * @throws IOException
98      */

99     private void init(FileChannel JavaDoc channel, FileChannel.MapMode JavaDoc mapMode)
100     throws IOException JavaDoc {
101         
102         this.channel = channel;
103         this.mappedByteBuffer = channel.map(mapMode, 0L, channel.size());
104         mappedByteBuffer.load();
105     }
106     
107     /**
108      * @see java.io.RandomAccessFile#read()
109      * @return int next integer or -1 on EOF
110      */

111     public int read() {
112         try {
113             byte b = mappedByteBuffer.get();
114             int n = b & 0xff;
115             
116             return n;
117         } catch (BufferUnderflowException JavaDoc e) {
118             return -1; // EOF
119
}
120     }
121     
122     /**
123      * @see java.io.RandomAccessFile#read(byte[], int, int)
124      * @param bytes byte[]
125      * @param off int offset
126      * @param len int length
127      * @return int bytes read or -1 on EOF
128      */

129     public int read(byte bytes[], int off, int len) {
130         int pos = mappedByteBuffer.position();
131         int limit = mappedByteBuffer.limit();
132         if (pos == limit)
133             return -1; // EOF
134
int newlimit = pos + len - off;
135         if (newlimit > limit) {
136             len = limit - pos; // don't read beyond EOF
137
}
138         mappedByteBuffer.get(bytes, off, len);
139         return len;
140     }
141     
142     /**
143      * @see java.io.RandomAccessFile#getFilePointer()
144      * @return long
145      */

146     public long getFilePointer() {
147         return mappedByteBuffer.position();
148     }
149     
150     /**
151      * @see java.io.RandomAccessFile#seek(long)
152      * @param pos long position
153      */

154     public void seek(long pos) {
155         mappedByteBuffer.position((int) pos);
156     }
157     
158     /**
159      * @see java.io.RandomAccessFile#length()
160      * @return long length
161      */

162     public long length() {
163         return mappedByteBuffer.limit();
164     }
165     
166     /**
167      * @see java.io.RandomAccessFile#close()
168      * Cleans the mapped bytebuffer and closes the channel
169      */

170     public void close() throws IOException JavaDoc {
171         clean(mappedByteBuffer);
172         mappedByteBuffer = null;
173         if (channel != null)
174             channel.close();
175         channel = null;
176     }
177     
178     /**
179      * invokes the close method
180      * @see java.lang.Object#finalize()
181      */

182     protected void finalize() throws Throwable JavaDoc {
183         close();
184         super.finalize();
185     }
186     
187     /**
188      * invokes the clean method on the ByteBuffer's cleaner
189      * @param buffer ByteBuffer
190      * @return boolean true on success
191      */

192     public static boolean clean(final java.nio.ByteBuffer JavaDoc buffer) {
193         if (buffer == null || !buffer.isDirect())
194             return false;
195         
196         Boolean JavaDoc b = (Boolean JavaDoc) AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
197             public Object JavaDoc run() {
198                 Boolean JavaDoc success = Boolean.FALSE;
199                 try {
200                     Method JavaDoc getCleanerMethod = buffer.getClass().getMethod("cleaner", null);
201                     getCleanerMethod.setAccessible(true);
202                     Object JavaDoc cleaner = getCleanerMethod.invoke(buffer, null);
203                     Method JavaDoc clean = cleaner.getClass().getMethod("clean", null);
204                     clean.invoke(cleaner, null);
205                     success = Boolean.TRUE;
206                 } catch (Exception JavaDoc e) {
207                     // This really is a show stopper on windows
208
//e.printStackTrace();
209
}
210                 return success;
211             }
212         });
213         
214         return b.booleanValue();
215     }
216     
217 }
218
Popular Tags