PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/file/WindowCursor.java

https://bitbucket.org/cofarrell/jgit
Java | 380 lines | 249 code | 37 blank | 94 comment | 45 complexity | 3968d1a421a92e5491479f6d0f82ccb3 MD5 | raw file
  1. /*
  2. * Copyright (C) 2008-2009, Google Inc.
  3. * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.internal.storage.file;
  45. import java.io.IOException;
  46. import java.security.MessageDigest;
  47. import java.text.MessageFormat;
  48. import java.util.Arrays;
  49. import java.util.Collection;
  50. import java.util.Collections;
  51. import java.util.HashSet;
  52. import java.util.List;
  53. import java.util.Set;
  54. import java.util.zip.DataFormatException;
  55. import java.util.zip.Inflater;
  56. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  57. import org.eclipse.jgit.errors.MissingObjectException;
  58. import org.eclipse.jgit.errors.StoredObjectRepresentationNotAvailableException;
  59. import org.eclipse.jgit.internal.JGitText;
  60. import org.eclipse.jgit.internal.storage.pack.CachedPack;
  61. import org.eclipse.jgit.internal.storage.pack.ObjectReuseAsIs;
  62. import org.eclipse.jgit.internal.storage.pack.ObjectToPack;
  63. import org.eclipse.jgit.internal.storage.pack.PackOutputStream;
  64. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  65. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  66. import org.eclipse.jgit.lib.AnyObjectId;
  67. import org.eclipse.jgit.lib.BitmapIndex;
  68. import org.eclipse.jgit.lib.BitmapIndex.BitmapBuilder;
  69. import org.eclipse.jgit.lib.Constants;
  70. import org.eclipse.jgit.lib.InflaterCache;
  71. import org.eclipse.jgit.lib.ObjectId;
  72. import org.eclipse.jgit.lib.ObjectLoader;
  73. import org.eclipse.jgit.lib.ObjectReader;
  74. import org.eclipse.jgit.lib.ProgressMonitor;
  75. /** Active handle to a ByteWindow. */
  76. final class WindowCursor extends ObjectReader implements ObjectReuseAsIs {
  77. /** Temporary buffer large enough for at least one raw object id. */
  78. final byte[] tempId = new byte[Constants.OBJECT_ID_LENGTH];
  79. private Inflater inf;
  80. private ByteWindow window;
  81. private DeltaBaseCache baseCache;
  82. final FileObjectDatabase db;
  83. WindowCursor(FileObjectDatabase db) {
  84. this.db = db;
  85. }
  86. DeltaBaseCache getDeltaBaseCache() {
  87. if (baseCache == null)
  88. baseCache = new DeltaBaseCache();
  89. return baseCache;
  90. }
  91. @Override
  92. public ObjectReader newReader() {
  93. return new WindowCursor(db);
  94. }
  95. @Override
  96. public BitmapIndex getBitmapIndex() throws IOException {
  97. for (PackFile pack : db.getPacks()) {
  98. PackBitmapIndex index = pack.getBitmapIndex();
  99. if (index != null)
  100. return new BitmapIndexImpl(index);
  101. }
  102. return null;
  103. }
  104. public Collection<CachedPack> getCachedPacksAndUpdate(
  105. BitmapBuilder needBitmap) throws IOException {
  106. for (PackFile pack : db.getPacks()) {
  107. PackBitmapIndex index = pack.getBitmapIndex();
  108. if (needBitmap.removeAllOrNone(index))
  109. return Collections.<CachedPack> singletonList(
  110. new LocalCachedPack(Collections.singletonList(pack)));
  111. }
  112. return Collections.emptyList();
  113. }
  114. @Override
  115. public Collection<ObjectId> resolve(AbbreviatedObjectId id)
  116. throws IOException {
  117. if (id.isComplete())
  118. return Collections.singleton(id.toObjectId());
  119. HashSet<ObjectId> matches = new HashSet<ObjectId>(4);
  120. db.resolve(matches, id);
  121. return matches;
  122. }
  123. public boolean has(AnyObjectId objectId) throws IOException {
  124. return db.has(objectId);
  125. }
  126. @Override
  127. public List<ObjectLoader> openAll(List<AnyObjectId> ids) throws IOException {
  128. return ((ObjectDirectory)db).openAll(this, ids);
  129. }
  130. public ObjectLoader open(AnyObjectId objectId, int typeHint)
  131. throws MissingObjectException, IncorrectObjectTypeException,
  132. IOException {
  133. final ObjectLoader ldr = db.openObject(this, objectId);
  134. if (ldr == null) {
  135. if (typeHint == OBJ_ANY)
  136. throw new MissingObjectException(objectId.copy(), "unknown");
  137. throw new MissingObjectException(objectId.copy(), typeHint);
  138. }
  139. if (typeHint != OBJ_ANY && ldr.getType() != typeHint)
  140. throw new IncorrectObjectTypeException(objectId.copy(), typeHint);
  141. return ldr;
  142. }
  143. @Override
  144. public Set<ObjectId> getShallowCommits() throws IOException {
  145. return db.getShallowCommits();
  146. }
  147. public long getObjectSize(AnyObjectId objectId, int typeHint)
  148. throws MissingObjectException, IncorrectObjectTypeException,
  149. IOException {
  150. long sz = db.getObjectSize(this, objectId);
  151. if (sz < 0) {
  152. if (typeHint == OBJ_ANY)
  153. throw new MissingObjectException(objectId.copy(), "unknown");
  154. throw new MissingObjectException(objectId.copy(), typeHint);
  155. }
  156. return sz;
  157. }
  158. public LocalObjectToPack newObjectToPack(AnyObjectId objectId, int type) {
  159. return new LocalObjectToPack(objectId, type);
  160. }
  161. public void selectObjectRepresentation(PackWriter packer,
  162. ProgressMonitor monitor, Iterable<ObjectToPack> objects)
  163. throws IOException, MissingObjectException {
  164. for (ObjectToPack otp : objects) {
  165. db.selectObjectRepresentation(packer, otp, this);
  166. monitor.update(1);
  167. }
  168. }
  169. public void copyObjectAsIs(PackOutputStream out, ObjectToPack otp,
  170. boolean validate) throws IOException,
  171. StoredObjectRepresentationNotAvailableException {
  172. LocalObjectToPack src = (LocalObjectToPack) otp;
  173. src.pack.copyAsIs(out, src, validate, this);
  174. }
  175. public void writeObjects(PackOutputStream out, List<ObjectToPack> list)
  176. throws IOException {
  177. for (ObjectToPack otp : list)
  178. out.writeObject(otp);
  179. }
  180. /**
  181. * Copy bytes from the window to a caller supplied buffer.
  182. *
  183. * @param pack
  184. * the file the desired window is stored within.
  185. * @param position
  186. * position within the file to read from.
  187. * @param dstbuf
  188. * destination buffer to copy into.
  189. * @param dstoff
  190. * offset within <code>dstbuf</code> to start copying into.
  191. * @param cnt
  192. * number of bytes to copy. This value may exceed the number of
  193. * bytes remaining in the window starting at offset
  194. * <code>pos</code>.
  195. * @return number of bytes actually copied; this may be less than
  196. * <code>cnt</code> if <code>cnt</code> exceeded the number of bytes
  197. * available.
  198. * @throws IOException
  199. * this cursor does not match the provider or id and the proper
  200. * window could not be acquired through the provider's cache.
  201. */
  202. int copy(final PackFile pack, long position, final byte[] dstbuf,
  203. int dstoff, final int cnt) throws IOException {
  204. final long length = pack.length;
  205. int need = cnt;
  206. while (need > 0 && position < length) {
  207. pin(pack, position);
  208. final int r = window.copy(position, dstbuf, dstoff, need);
  209. position += r;
  210. dstoff += r;
  211. need -= r;
  212. }
  213. return cnt - need;
  214. }
  215. public void copyPackAsIs(PackOutputStream out, CachedPack pack,
  216. boolean validate) throws IOException {
  217. ((LocalCachedPack) pack).copyAsIs(out, validate, this);
  218. }
  219. void copyPackAsIs(final PackFile pack, final long length, boolean validate,
  220. final PackOutputStream out) throws IOException {
  221. MessageDigest md = null;
  222. if (validate) {
  223. md = Constants.newMessageDigest();
  224. byte[] buf = out.getCopyBuffer();
  225. pin(pack, 0);
  226. if (window.copy(0, buf, 0, 12) != 12) {
  227. pack.setInvalid();
  228. throw new IOException(JGitText.get().packfileIsTruncated);
  229. }
  230. md.update(buf, 0, 12);
  231. }
  232. long position = 12;
  233. long remaining = length - (12 + 20);
  234. while (0 < remaining) {
  235. pin(pack, position);
  236. int ptr = (int) (position - window.start);
  237. int n = (int) Math.min(window.size() - ptr, remaining);
  238. window.write(out, position, n, md);
  239. position += n;
  240. remaining -= n;
  241. }
  242. if (md != null) {
  243. byte[] buf = new byte[20];
  244. byte[] actHash = md.digest();
  245. pin(pack, position);
  246. if (window.copy(position, buf, 0, 20) != 20) {
  247. pack.setInvalid();
  248. throw new IOException(JGitText.get().packfileIsTruncated);
  249. }
  250. if (!Arrays.equals(actHash, buf)) {
  251. pack.setInvalid();
  252. throw new IOException(MessageFormat.format(
  253. JGitText.get().packfileCorruptionDetected, pack
  254. .getPackFile().getPath()));
  255. }
  256. }
  257. }
  258. /**
  259. * Inflate a region of the pack starting at {@code position}.
  260. *
  261. * @param pack
  262. * the file the desired window is stored within.
  263. * @param position
  264. * position within the file to read from.
  265. * @param dstbuf
  266. * destination buffer the inflater should output decompressed
  267. * data to.
  268. * @param dstoff
  269. * current offset within <code>dstbuf</code> to inflate into.
  270. * @return updated <code>dstoff</code> based on the number of bytes
  271. * successfully inflated into <code>dstbuf</code>.
  272. * @throws IOException
  273. * this cursor does not match the provider or id and the proper
  274. * window could not be acquired through the provider's cache.
  275. * @throws DataFormatException
  276. * the inflater encountered an invalid chunk of data. Data
  277. * stream corruption is likely.
  278. */
  279. int inflate(final PackFile pack, long position, final byte[] dstbuf,
  280. int dstoff) throws IOException, DataFormatException {
  281. prepareInflater();
  282. pin(pack, position);
  283. position += window.setInput(position, inf);
  284. do {
  285. int n = inf.inflate(dstbuf, dstoff, dstbuf.length - dstoff);
  286. if (n == 0) {
  287. if (inf.needsInput()) {
  288. pin(pack, position);
  289. position += window.setInput(position, inf);
  290. } else if (inf.finished())
  291. return dstoff;
  292. else
  293. throw new DataFormatException();
  294. }
  295. dstoff += n;
  296. } while (dstoff < dstbuf.length);
  297. return dstoff;
  298. }
  299. ByteArrayWindow quickCopy(PackFile p, long pos, long cnt)
  300. throws IOException {
  301. pin(p, pos);
  302. if (window instanceof ByteArrayWindow
  303. && window.contains(p, pos + (cnt - 1)))
  304. return (ByteArrayWindow) window;
  305. return null;
  306. }
  307. Inflater inflater() {
  308. prepareInflater();
  309. return inf;
  310. }
  311. private void prepareInflater() {
  312. if (inf == null)
  313. inf = InflaterCache.get();
  314. else
  315. inf.reset();
  316. }
  317. void pin(final PackFile pack, final long position)
  318. throws IOException {
  319. final ByteWindow w = window;
  320. if (w == null || !w.contains(pack, position)) {
  321. // If memory is low, we may need what is in our window field to
  322. // be cleaned up by the GC during the get for the next window.
  323. // So we always clear it, even though we are just going to set
  324. // it again.
  325. //
  326. window = null;
  327. window = WindowCache.get(pack, position);
  328. }
  329. }
  330. int getStreamFileThreshold() {
  331. return WindowCache.getStreamFileThreshold();
  332. }
  333. /** Release the current window cursor. */
  334. public void release() {
  335. window = null;
  336. baseCache = null;
  337. try {
  338. InflaterCache.release(inf);
  339. } finally {
  340. inf = null;
  341. }
  342. }
  343. }