You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PageChannel.java 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /*
  2. Copyright (c) 2005 Health Market Science, Inc.
  3. This library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with this library; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  14. USA
  15. You can contact Health Market Science at info@healthmarketscience.com
  16. or at the following address:
  17. Health Market Science
  18. 2700 Horizon Drive
  19. Suite 200
  20. King of Prussia, PA 19406
  21. */
  22. package com.healthmarketscience.jackcess;
  23. import java.io.Flushable;
  24. import java.io.IOException;
  25. import java.nio.ByteBuffer;
  26. import java.nio.ByteOrder;
  27. import java.nio.channels.Channel;
  28. import java.nio.channels.FileChannel;
  29. import org.apache.commons.logging.Log;
  30. import org.apache.commons.logging.LogFactory;
  31. /**
  32. * Reads and writes individual pages in a database file
  33. * @author Tim McCune
  34. */
  35. public class PageChannel implements Channel, Flushable {
  36. private static final Log LOG = LogFactory.getLog(PageChannel.class);
  37. static final int INVALID_PAGE_NUMBER = -1;
  38. static final ByteOrder DEFAULT_BYTE_ORDER = ByteOrder.LITTLE_ENDIAN;
  39. /** invalid page header, used when deallocating old pages. data pages
  40. generally have 4 interesting bytes at the beginning which we want to
  41. reset. */
  42. private static final byte[] INVALID_PAGE_BYTE_HEADER =
  43. new byte[]{PageTypes.INVALID, (byte)0, (byte)0, (byte)0};
  44. /** Global usage map always lives on page 1 */
  45. static final int PAGE_GLOBAL_USAGE_MAP = 1;
  46. /** Global usage map always lives at row 0 */
  47. static final int ROW_GLOBAL_USAGE_MAP = 0;
  48. /** Channel containing the database */
  49. private final FileChannel _channel;
  50. /** Format of the database in the channel */
  51. private final JetFormat _format;
  52. /** whether or not to force all writes to disk immediately */
  53. private final boolean _autoSync;
  54. /** buffer used when deallocating old pages. data pages generally have 4
  55. interesting bytes at the beginning which we want to reset. */
  56. private final ByteBuffer _invalidPageBytes =
  57. ByteBuffer.wrap(INVALID_PAGE_BYTE_HEADER);
  58. /** dummy buffer used when allocating new pages */
  59. private final ByteBuffer _forceBytes = ByteBuffer.allocate(1);
  60. /** Tracks free pages in the database. */
  61. private UsageMap _globalUsageMap;
  62. /**
  63. * @param channel Channel containing the database
  64. * @param format Format of the database in the channel
  65. */
  66. public PageChannel(FileChannel channel, JetFormat format, boolean autoSync)
  67. throws IOException
  68. {
  69. _channel = channel;
  70. _format = format;
  71. _autoSync = autoSync;
  72. }
  73. /**
  74. * Does second-stage initialization, must be called after construction.
  75. */
  76. public void initialize(Database database)
  77. throws IOException
  78. {
  79. // note the global usage map is a special map where any page outside of
  80. // the current range is assumed to be "on"
  81. _globalUsageMap = UsageMap.read(database, PAGE_GLOBAL_USAGE_MAP,
  82. ROW_GLOBAL_USAGE_MAP, true);
  83. }
  84. /**
  85. * Only used by unit tests
  86. */
  87. PageChannel(boolean testing) {
  88. if(!testing) {
  89. throw new IllegalArgumentException();
  90. }
  91. _channel = null;
  92. _format = JetFormat.VERSION_4;
  93. _autoSync = false;
  94. }
  95. public JetFormat getFormat() {
  96. return _format;
  97. }
  98. /**
  99. * Returns the next page number based on the given file size.
  100. */
  101. private int getNextPageNumber(long size) {
  102. return (int)(size / getFormat().PAGE_SIZE);
  103. }
  104. /**
  105. * Returns the offset for a page within the file.
  106. */
  107. private long getPageOffset(int pageNumber) {
  108. return((long) pageNumber * (long) getFormat().PAGE_SIZE);
  109. }
  110. /**
  111. * Validates that the given pageNumber is valid for this database.
  112. */
  113. private void validatePageNumber(int pageNumber)
  114. throws IOException
  115. {
  116. int nextPageNumber = getNextPageNumber(_channel.size());
  117. if((pageNumber <= INVALID_PAGE_NUMBER) || (pageNumber >= nextPageNumber)) {
  118. throw new IllegalStateException("invalid page number " + pageNumber);
  119. }
  120. }
  121. /**
  122. * @param buffer Buffer to read the page into
  123. * @param pageNumber Number of the page to read in (starting at 0)
  124. */
  125. public void readPage(ByteBuffer buffer, int pageNumber)
  126. throws IOException
  127. {
  128. validatePageNumber(pageNumber);
  129. if (LOG.isDebugEnabled()) {
  130. LOG.debug("Reading in page " + Integer.toHexString(pageNumber));
  131. }
  132. buffer.clear();
  133. int bytesRead = _channel.read(
  134. buffer, (long) pageNumber * (long) getFormat().PAGE_SIZE);
  135. buffer.flip();
  136. if(bytesRead != getFormat().PAGE_SIZE) {
  137. throw new IOException("Failed attempting to read " +
  138. getFormat().PAGE_SIZE + " bytes from page " +
  139. pageNumber + ", only read " + bytesRead);
  140. }
  141. }
  142. /**
  143. * Write a page to disk
  144. * @param page Page to write
  145. * @param pageNumber Page number to write the page to
  146. */
  147. public void writePage(ByteBuffer page, int pageNumber) throws IOException {
  148. writePage(page, pageNumber, 0);
  149. }
  150. /**
  151. * Write a page (or part of a page) to disk
  152. * @param page Page to write
  153. * @param pageNumber Page number to write the page to
  154. * @param pageOffset offset within the page at which to start writing the
  155. * page data
  156. */
  157. public void writePage(ByteBuffer page, int pageNumber,
  158. int pageOffset)
  159. throws IOException
  160. {
  161. validatePageNumber(pageNumber);
  162. page.rewind();
  163. if((page.remaining() - pageOffset) > getFormat().PAGE_SIZE) {
  164. throw new IllegalArgumentException(
  165. "Page buffer is too large, size " + (page.remaining() - pageOffset));
  166. }
  167. page.position(pageOffset);
  168. _channel.write(page, (getPageOffset(pageNumber) + pageOffset));
  169. if(_autoSync) {
  170. flush();
  171. }
  172. }
  173. /**
  174. * Write a page to disk as a new page, appending it to the database
  175. * @param page Page to write
  176. * @return Page number at which the page was written
  177. */
  178. public int writeNewPage(ByteBuffer page) throws IOException
  179. {
  180. long size = _channel.size();
  181. if(size >= getFormat().MAX_DATABASE_SIZE) {
  182. throw new IOException("Database is at maximum size " +
  183. getFormat().MAX_DATABASE_SIZE);
  184. }
  185. if((size % getFormat().PAGE_SIZE) != 0L) {
  186. throw new IOException("Database corrupted, file size " + size +
  187. " is not multiple of page size " +
  188. getFormat().PAGE_SIZE);
  189. }
  190. page.rewind();
  191. if(page.remaining() > getFormat().PAGE_SIZE) {
  192. throw new IllegalArgumentException("Page buffer is too large, size " +
  193. page.remaining());
  194. }
  195. // push the buffer to the end of the page, so that a full page's worth of
  196. // data is written regardless of the incoming buffer size (we use a tiny
  197. // buffer in allocateNewPage)
  198. long offset = size + (getFormat().PAGE_SIZE - page.remaining());
  199. _channel.write(page, offset);
  200. int pageNumber = getNextPageNumber(size);
  201. _globalUsageMap.removePageNumber(pageNumber); //force is done here
  202. return pageNumber;
  203. }
  204. /**
  205. * Allocates a new page in the database. Data in the page is undefined
  206. * until it is written in a call to {@link #writePage(ByteBuffer,int)}.
  207. */
  208. public int allocateNewPage() throws IOException {
  209. // this will force the file to be extended with mostly undefined bytes
  210. return writeNewPage(_forceBytes);
  211. }
  212. /**
  213. * Deallocate a previously used page in the database.
  214. */
  215. public void deallocatePage(int pageNumber) throws IOException {
  216. validatePageNumber(pageNumber);
  217. // don't write the whole page, just wipe out the header (which should be
  218. // enough to let us know if we accidentally try to use an invalid page)
  219. _invalidPageBytes.rewind();
  220. _channel.write(_invalidPageBytes, getPageOffset(pageNumber));
  221. _globalUsageMap.addPageNumber(pageNumber); //force is done here
  222. }
  223. /**
  224. * @return A newly-allocated buffer that can be passed to readPage
  225. */
  226. public ByteBuffer createPageBuffer() {
  227. return createBuffer(getFormat().PAGE_SIZE);
  228. }
  229. /**
  230. * @return A newly-allocated buffer of the given size and LITTLE_ENDIAN byte
  231. * order
  232. */
  233. public ByteBuffer createBuffer(int size) {
  234. return createBuffer(size, ByteOrder.LITTLE_ENDIAN);
  235. }
  236. /**
  237. * @return A newly-allocated buffer of the given size and byte order
  238. */
  239. public ByteBuffer createBuffer(int size, ByteOrder order) {
  240. ByteBuffer rtn = ByteBuffer.allocate(size);
  241. rtn.order(order);
  242. return rtn;
  243. }
  244. public void flush() throws IOException {
  245. _channel.force(true);
  246. }
  247. public void close() throws IOException {
  248. flush();
  249. _channel.close();
  250. }
  251. public boolean isOpen() {
  252. return _channel.isOpen();
  253. }
  254. /**
  255. * @return a duplicate of the current buffer narrowed to the given position
  256. * and limit. mark will be set at the current position.
  257. */
  258. public static ByteBuffer narrowBuffer(ByteBuffer buffer, int position,
  259. int limit)
  260. {
  261. return (ByteBuffer)buffer.duplicate()
  262. .order(buffer.order())
  263. .clear()
  264. .limit(limit)
  265. .position(position)
  266. .mark();
  267. }
  268. }