xref: /JGit/org.eclipse.jgit.lfs/src/org/eclipse/jgit/lfs/LfsBlobLoader.java (revision 5c5f7c6b146b24f2bd4afae1902df85ad6e57ea3)
1 /*
2  * Copyright (C) 2017, Markus Duft <markus.duft@ssi-schaefer.com> and others
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Distribution License v. 1.0 which is available at
6  * https://www.eclipse.org/org/documents/edl-v10.php.
7  *
8  * SPDX-License-Identifier: BSD-3-Clause
9  */
10 package org.eclipse.jgit.lfs;
11 
12 import java.io.IOException;
13 import java.nio.file.Files;
14 import java.nio.file.Path;
15 import java.nio.file.attribute.BasicFileAttributes;
16 
17 import org.eclipse.jgit.errors.LargeObjectException;
18 import org.eclipse.jgit.errors.MissingObjectException;
19 import org.eclipse.jgit.lib.Constants;
20 import org.eclipse.jgit.lib.ObjectLoader;
21 import org.eclipse.jgit.lib.ObjectStream;
22 import org.eclipse.jgit.storage.pack.PackConfig;
23 import org.eclipse.jgit.util.IO;
24 
25 /**
26  * An {@link ObjectLoader} implementation that reads a media file from the LFS
27  * storage.
28  *
29  * @since 4.11
30  */
31 public class LfsBlobLoader extends ObjectLoader {
32 
33 	private Path mediaFile;
34 
35 	private BasicFileAttributes attributes;
36 
37 	private byte[] cached;
38 
39 	/**
40 	 * Create a loader for the LFS media file at the given path.
41 	 *
42 	 * @param mediaFile
43 	 *            path to the file
44 	 * @throws IOException
45 	 *             in case of an error reading attributes
46 	 */
LfsBlobLoader(Path mediaFile)47 	public LfsBlobLoader(Path mediaFile) throws IOException {
48 		this.mediaFile = mediaFile;
49 		this.attributes = Files.readAttributes(mediaFile,
50 				BasicFileAttributes.class);
51 	}
52 
53 	@Override
getType()54 	public int getType() {
55 		return Constants.OBJ_BLOB;
56 	}
57 
58 	@Override
getSize()59 	public long getSize() {
60 		return attributes.size();
61 	}
62 
63 	@Override
getCachedBytes()64 	public byte[] getCachedBytes() throws LargeObjectException {
65 		if (getSize() > PackConfig.DEFAULT_BIG_FILE_THRESHOLD) {
66 			throw new LargeObjectException();
67 		}
68 
69 		if (cached == null) {
70 			try {
71 				cached = IO.readFully(mediaFile.toFile());
72 			} catch (IOException ioe) {
73 				throw new LargeObjectException(ioe);
74 			}
75 		}
76 		return cached;
77 	}
78 
79 	@Override
openStream()80 	public ObjectStream openStream()
81 			throws MissingObjectException, IOException {
82 		return new ObjectStream.Filter(getType(), getSize(),
83 				Files.newInputStream(mediaFile));
84 	}
85 
86 }
87