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 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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. /** handler for the current database encoding type */
  63. private CodecHandler _codecHandler = DefaultCodecProvider.DUMMY_HANDLER;
  64. /** temp page buffer used when pages cannot be partially encoded */
  65. private final TempPageHolder _fullPageEncodeBufferH =
  66. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  67. /**
  68. * @param channel Channel containing the database
  69. * @param format Format of the database in the channel
  70. */
  71. public PageChannel(FileChannel channel, JetFormat format, boolean autoSync)
  72. throws IOException
  73. {
  74. _channel = channel;
  75. _format = format;
  76. _autoSync = autoSync;
  77. }
  78. /**
  79. * Does second-stage initialization, must be called after construction.
  80. */
  81. public void initialize(Database database, CodecProvider codecProvider)
  82. throws IOException
  83. {
  84. // initialize page en/decoding support
  85. _codecHandler = codecProvider.createHandler(this, database.getCharset());
  86. // note the global usage map is a special map where any page outside of
  87. // the current range is assumed to be "on"
  88. _globalUsageMap = UsageMap.read(database, PAGE_GLOBAL_USAGE_MAP,
  89. ROW_GLOBAL_USAGE_MAP, true);
  90. }
  91. /**
  92. * Only used by unit tests
  93. */
  94. PageChannel(boolean testing) {
  95. if(!testing) {
  96. throw new IllegalArgumentException();
  97. }
  98. _channel = null;
  99. _format = JetFormat.VERSION_4;
  100. _autoSync = false;
  101. }
  102. public JetFormat getFormat() {
  103. return _format;
  104. }
  105. public boolean isAutoSync() {
  106. return _autoSync;
  107. }
  108. /**
  109. * Returns the next page number based on the given file size.
  110. */
  111. private int getNextPageNumber(long size) {
  112. return (int)(size / getFormat().PAGE_SIZE);
  113. }
  114. /**
  115. * Returns the offset for a page within the file.
  116. */
  117. private long getPageOffset(int pageNumber) {
  118. return((long) pageNumber * (long) getFormat().PAGE_SIZE);
  119. }
  120. /**
  121. * Validates that the given pageNumber is valid for this database.
  122. */
  123. private void validatePageNumber(int pageNumber)
  124. throws IOException
  125. {
  126. int nextPageNumber = getNextPageNumber(_channel.size());
  127. if((pageNumber <= INVALID_PAGE_NUMBER) || (pageNumber >= nextPageNumber)) {
  128. throw new IllegalStateException("invalid page number " + pageNumber);
  129. }
  130. }
  131. /**
  132. * @param buffer Buffer to read the page into
  133. * @param pageNumber Number of the page to read in (starting at 0)
  134. */
  135. public void readPage(ByteBuffer buffer, int pageNumber)
  136. throws IOException
  137. {
  138. validatePageNumber(pageNumber);
  139. if (LOG.isDebugEnabled()) {
  140. LOG.debug("Reading in page " + Integer.toHexString(pageNumber));
  141. }
  142. buffer.clear();
  143. int bytesRead = _channel.read(
  144. buffer, (long) pageNumber * (long) getFormat().PAGE_SIZE);
  145. buffer.flip();
  146. if(bytesRead != getFormat().PAGE_SIZE) {
  147. throw new IOException("Failed attempting to read " +
  148. getFormat().PAGE_SIZE + " bytes from page " +
  149. pageNumber + ", only read " + bytesRead);
  150. }
  151. if(pageNumber == 0) {
  152. // de-mask header (note, page 0 never has additional encoding)
  153. applyHeaderMask(buffer);
  154. } else {
  155. _codecHandler.decodePage(buffer, pageNumber);
  156. }
  157. }
  158. /**
  159. * Write a page to disk
  160. * @param page Page to write
  161. * @param pageNumber Page number to write the page to
  162. */
  163. public void writePage(ByteBuffer page, int pageNumber) throws IOException {
  164. writePage(page, pageNumber, 0);
  165. }
  166. /**
  167. * Write a page (or part of a page) to disk
  168. * @param page Page to write
  169. * @param pageNumber Page number to write the page to
  170. * @param pageOffset offset within the page at which to start writing the
  171. * page data
  172. */
  173. public void writePage(ByteBuffer page, int pageNumber, int pageOffset)
  174. throws IOException
  175. {
  176. validatePageNumber(pageNumber);
  177. page.rewind().position(pageOffset);
  178. int writeLen = page.remaining();
  179. if((writeLen + pageOffset) > getFormat().PAGE_SIZE) {
  180. throw new IllegalArgumentException(
  181. "Page buffer is too large, size " + (writeLen + pageOffset));
  182. }
  183. ByteBuffer encodedPage = page;
  184. if(pageNumber == 0) {
  185. // re-mask header
  186. applyHeaderMask(page);
  187. } else {
  188. if(!_codecHandler.canEncodePartialPage()) {
  189. if((pageOffset > 0) && (writeLen < getFormat().PAGE_SIZE)) {
  190. // current codec handler cannot encode part of a page, so need to
  191. // copy the modified part into the current page contents in a temp
  192. // buffer so that we can encode the entire page
  193. ByteBuffer fullPage = _fullPageEncodeBufferH.setPage(
  194. this, pageNumber);
  195. // copy the modified part to the full page
  196. fullPage.position(pageOffset);
  197. fullPage.put(page);
  198. fullPage.rewind();
  199. // reset so we can write the whole page
  200. page = fullPage;
  201. pageOffset = 0;
  202. } else {
  203. _fullPageEncodeBufferH.possiblyInvalidate(pageNumber, null);
  204. }
  205. }
  206. // re-encode page
  207. encodedPage = _codecHandler.encodePage(page, pageNumber, pageOffset);
  208. // reset position/limit in case they were affected by encoding
  209. encodedPage.position(pageOffset).limit(pageOffset + writeLen);
  210. }
  211. try {
  212. _channel.write(encodedPage, (getPageOffset(pageNumber) + pageOffset));
  213. if(_autoSync) {
  214. flush();
  215. }
  216. } finally {
  217. if(pageNumber == 0) {
  218. // de-mask header
  219. applyHeaderMask(page);
  220. }
  221. }
  222. }
  223. /**
  224. * Allocates a new page in the database. Data in the page is undefined
  225. * until it is written in a call to {@link #writePage(ByteBuffer,int)}.
  226. */
  227. public int allocateNewPage() throws IOException {
  228. // this will force the file to be extended with mostly undefined bytes
  229. long size = _channel.size();
  230. if(size >= getFormat().MAX_DATABASE_SIZE) {
  231. throw new IOException("Database is at maximum size " +
  232. getFormat().MAX_DATABASE_SIZE);
  233. }
  234. if((size % getFormat().PAGE_SIZE) != 0L) {
  235. throw new IOException("Database corrupted, file size " + size +
  236. " is not multiple of page size " +
  237. getFormat().PAGE_SIZE);
  238. }
  239. _forceBytes.rewind();
  240. // push the buffer to the end of the page, so that a full page's worth of
  241. // data is written
  242. int pageOffset = (getFormat().PAGE_SIZE - _forceBytes.remaining());
  243. long offset = size + pageOffset;
  244. int pageNumber = getNextPageNumber(size);
  245. // since we are just allocating page space at this point and not writing
  246. // meaningful data, we do _not_ encode the page.
  247. _channel.write(_forceBytes, offset);
  248. // note, we "force" page removal because we know that this is an unused
  249. // page (since we just added it to the file)
  250. _globalUsageMap.removePageNumber(pageNumber, true);
  251. return pageNumber;
  252. }
  253. /**
  254. * Deallocate a previously used page in the database.
  255. */
  256. public void deallocatePage(int pageNumber) throws IOException {
  257. validatePageNumber(pageNumber);
  258. // don't write the whole page, just wipe out the header (which should be
  259. // enough to let us know if we accidentally try to use an invalid page)
  260. _invalidPageBytes.rewind();
  261. _channel.write(_invalidPageBytes, getPageOffset(pageNumber));
  262. _globalUsageMap.addPageNumber(pageNumber); //force is done here
  263. }
  264. /**
  265. * @return A newly-allocated buffer that can be passed to readPage
  266. */
  267. public ByteBuffer createPageBuffer() {
  268. return createBuffer(getFormat().PAGE_SIZE);
  269. }
  270. /**
  271. * @return A newly-allocated buffer of the given size and DEFAULT_BYTE_ORDER
  272. * byte order
  273. */
  274. public ByteBuffer createBuffer(int size) {
  275. return createBuffer(size, DEFAULT_BYTE_ORDER);
  276. }
  277. /**
  278. * @return A newly-allocated buffer of the given size and byte order
  279. */
  280. public ByteBuffer createBuffer(int size, ByteOrder order) {
  281. return ByteBuffer.allocate(size).order(order);
  282. }
  283. public void flush() throws IOException {
  284. _channel.force(true);
  285. }
  286. public void close() throws IOException {
  287. flush();
  288. _channel.close();
  289. }
  290. public boolean isOpen() {
  291. return _channel.isOpen();
  292. }
  293. /**
  294. * Applies the XOR mask to the database header in the given buffer.
  295. */
  296. private void applyHeaderMask(ByteBuffer buffer) {
  297. // de/re-obfuscate the header
  298. byte[] headerMask = _format.HEADER_MASK;
  299. for(int idx = 0; idx < headerMask.length; ++idx) {
  300. int pos = idx + _format.OFFSET_MASKED_HEADER;
  301. byte b = (byte)(buffer.get(pos) ^ headerMask[idx]);
  302. buffer.put(pos, b);
  303. }
  304. }
  305. /**
  306. * @return a duplicate of the current buffer narrowed to the given position
  307. * and limit. mark will be set at the current position.
  308. */
  309. public static ByteBuffer narrowBuffer(ByteBuffer buffer, int position,
  310. int limit)
  311. {
  312. return (ByteBuffer)buffer.duplicate()
  313. .order(buffer.order())
  314. .clear()
  315. .limit(limit)
  316. .position(position)
  317. .mark();
  318. }
  319. }