Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

PageChannel.java 12KB

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