List of usage examples for org.eclipse.jgit.lib ObjectLoader getSize
public abstract long getSize();
From source file:com.buildautomation.jgit.api.GetFileAttributes.java
License:Apache License
private static void printFile(Repository repository, RevTree tree) throws IOException { // now try to find a specific file try (TreeWalk treeWalk = new TreeWalk(repository)) { treeWalk.addTree(tree);//from w w w. j a v a2s. co m treeWalk.setRecursive(false); treeWalk.setFilter(PathFilter.create("README.md")); if (!treeWalk.next()) { throw new IllegalStateException("Did not find expected file 'README.md'"); } // FileMode specifies the type of file, FileMode.REGULAR_FILE for normal file, FileMode.EXECUTABLE_FILE for executable bit // set FileMode fileMode = treeWalk.getFileMode(0); ObjectLoader loader = repository.open(treeWalk.getObjectId(0)); System.out.println("README.md: " + getFileMode(fileMode) + ", type: " + fileMode.getObjectType() + ", mode: " + fileMode + " size: " + loader.getSize()); } }
From source file:com.gitblit.utils.CompressionUtils.java
License:Apache License
/** * Zips the contents of the tree at the (optionally) specified revision and * the (optionally) specified basepath to the supplied outputstream. * * @param repository/*from w w w . jav a2s.c o m*/ * @param basePath * if unspecified, entire repository is assumed. * @param objectId * if unspecified, HEAD is assumed. * @param os * @return true if repository was successfully zipped to supplied output * stream */ public static boolean zip(Repository repository, IFilestoreManager filestoreManager, String basePath, String objectId, OutputStream os) { RevCommit commit = JGitUtils.getCommit(repository, objectId); if (commit == null) { return false; } boolean success = false; RevWalk rw = new RevWalk(repository); TreeWalk tw = new TreeWalk(repository); try { tw.reset(); tw.addTree(commit.getTree()); ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); zos.setComment("Generated by Gitblit"); if (!StringUtils.isEmpty(basePath)) { PathFilter f = PathFilter.create(basePath); tw.setFilter(f); } tw.setRecursive(true); MutableObjectId id = new MutableObjectId(); ObjectReader reader = tw.getObjectReader(); long modified = commit.getAuthorIdent().getWhen().getTime(); while (tw.next()) { FileMode mode = tw.getFileMode(0); if (mode == FileMode.GITLINK || mode == FileMode.TREE) { continue; } tw.getObjectId(id, 0); ObjectLoader loader = repository.open(id); ZipArchiveEntry entry = new ZipArchiveEntry(tw.getPathString()); FilestoreModel filestoreItem = null; if (JGitUtils.isPossibleFilestoreItem(loader.getSize())) { filestoreItem = JGitUtils.getFilestoreItem(tw.getObjectReader().open(id)); } final long size = (filestoreItem == null) ? loader.getSize() : filestoreItem.getSize(); entry.setSize(size); entry.setComment(commit.getName()); entry.setUnixMode(mode.getBits()); entry.setTime(modified); zos.putArchiveEntry(entry); if (filestoreItem == null) { //Copy repository stored file loader.copyTo(zos); } else { //Copy filestore file try (FileInputStream streamIn = new FileInputStream( filestoreManager.getStoragePath(filestoreItem.oid))) { IOUtils.copyLarge(streamIn, zos); } catch (Throwable e) { LOGGER.error( MessageFormat.format("Failed to archive filestore item {0}", filestoreItem.oid), e); //Handle as per other errors throw e; } } zos.closeArchiveEntry(); } zos.finish(); success = true; } catch (IOException e) { error(e, repository, "{0} failed to zip files from commit {1}", commit.getName()); } finally { tw.close(); rw.dispose(); } return success; }
From source file:com.gitblit.utils.CompressionUtils.java
License:Apache License
/** * Compresses/archives the contents of the tree at the (optionally) * specified revision and the (optionally) specified basepath to the * supplied outputstream.// ww w. j a va2 s. c o m * * @param algorithm * compression algorithm for tar (optional) * @param repository * @param basePath * if unspecified, entire repository is assumed. * @param objectId * if unspecified, HEAD is assumed. * @param os * @return true if repository was successfully zipped to supplied output * stream */ private static boolean tar(String algorithm, Repository repository, IFilestoreManager filestoreManager, String basePath, String objectId, OutputStream os) { RevCommit commit = JGitUtils.getCommit(repository, objectId); if (commit == null) { return false; } OutputStream cos = os; if (!StringUtils.isEmpty(algorithm)) { try { cos = new CompressorStreamFactory().createCompressorOutputStream(algorithm, os); } catch (CompressorException e1) { error(e1, repository, "{0} failed to open {1} stream", algorithm); } } boolean success = false; RevWalk rw = new RevWalk(repository); TreeWalk tw = new TreeWalk(repository); try { tw.reset(); tw.addTree(commit.getTree()); TarArchiveOutputStream tos = new TarArchiveOutputStream(cos); tos.setAddPaxHeadersForNonAsciiNames(true); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); if (!StringUtils.isEmpty(basePath)) { PathFilter f = PathFilter.create(basePath); tw.setFilter(f); } tw.setRecursive(true); MutableObjectId id = new MutableObjectId(); long modified = commit.getAuthorIdent().getWhen().getTime(); while (tw.next()) { FileMode mode = tw.getFileMode(0); if (mode == FileMode.GITLINK || mode == FileMode.TREE) { continue; } tw.getObjectId(id, 0); ObjectLoader loader = repository.open(id); if (FileMode.SYMLINK == mode) { TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString(), TarArchiveEntry.LF_SYMLINK); ByteArrayOutputStream bos = new ByteArrayOutputStream(); loader.copyTo(bos); entry.setLinkName(bos.toString()); entry.setModTime(modified); tos.putArchiveEntry(entry); tos.closeArchiveEntry(); } else { TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString()); entry.setMode(mode.getBits()); entry.setModTime(modified); FilestoreModel filestoreItem = null; if (JGitUtils.isPossibleFilestoreItem(loader.getSize())) { filestoreItem = JGitUtils.getFilestoreItem(tw.getObjectReader().open(id)); } final long size = (filestoreItem == null) ? loader.getSize() : filestoreItem.getSize(); entry.setSize(size); tos.putArchiveEntry(entry); if (filestoreItem == null) { //Copy repository stored file loader.copyTo(tos); } else { //Copy filestore file try (FileInputStream streamIn = new FileInputStream( filestoreManager.getStoragePath(filestoreItem.oid))) { IOUtils.copyLarge(streamIn, tos); } catch (Throwable e) { LOGGER.error( MessageFormat.format("Failed to archive filestore item {0}", filestoreItem.oid), e); //Handle as per other errors throw e; } } tos.closeArchiveEntry(); } } tos.finish(); tos.close(); cos.close(); success = true; } catch (IOException e) { error(e, repository, "{0} failed to {1} stream files from commit {2}", algorithm, commit.getName()); } finally { tw.close(); rw.dispose(); } return success; }
From source file:com.google.gerrit.httpd.raw.CatServlet.java
License:Apache License
private OutputStream openOutputStream(HttpServletRequest req, HttpServletResponse rsp, ObjectLoader blobLoader, RevCommit fromCommit, long when, String path, String suffix, byte[] raw) throws IOException { MimeType contentType = registry.getMimeType(path, raw); if (!registry.isSafeInline(contentType)) { // The content may not be safe to transmit inline, as a browser might // interpret it as HTML or JavaScript hosted by this site. Such code // might then run in the site's security domain, and may be able to use // the user's cookies to perform unauthorized actions. ///*from w w w . ja v a 2 s . c om*/ // Usually, wrapping the content into a ZIP file forces the browser to // save the content to the local system instead. // rsp.setContentType(ZIP.toString()); rsp.setHeader("Content-Disposition", "attachment; filename=\"" + safeFileName(path, suffix) + ".zip" + "\""); final ZipOutputStream zo = new ZipOutputStream(rsp.getOutputStream()); ZipEntry e = new ZipEntry(safeFileName(path, rand(req, suffix))); e.setComment(fromCommit.name() + ":" + path); e.setSize(blobLoader.getSize()); e.setTime(when); zo.putNextEntry(e); return new FilterOutputStream(zo) { @Override public void close() throws IOException { try { zo.closeEntry(); } finally { super.close(); } } }; } else { rsp.setContentType(contentType.toString()); rsp.setHeader("Content-Length", "" + blobLoader.getSize()); return rsp.getOutputStream(); } }
From source file:com.google.gerrit.server.change.FileContentUtil.java
License:Apache License
private static BinaryResult asBinaryResult(byte[] raw, final ObjectLoader obj) { if (raw != null) { return BinaryResult.create(raw); }//from w w w. j a va 2 s .com BinaryResult result = new BinaryResult() { @Override public void writeTo(OutputStream os) throws IOException { obj.copyTo(os); } }; result.setContentLength(obj.getSize()); return result; }
From source file:com.google.gerrit.server.change.FileContentUtil.java
License:Apache License
@SuppressWarnings("resource") private BinaryResult zipBlob(final String path, final ObjectLoader obj, RevCommit commit, @Nullable final String suffix) { final String commitName = commit.getName(); final long when = commit.getCommitTime() * 1000L; return new BinaryResult() { @Override/*from w ww . j ava 2s . c o m*/ public void writeTo(OutputStream os) throws IOException { try (ZipOutputStream zipOut = new ZipOutputStream(os)) { String decoration = randSuffix(); if (!Strings.isNullOrEmpty(suffix)) { decoration = suffix + '-' + decoration; } ZipEntry e = new ZipEntry(safeFileName(path, decoration)); e.setComment(commitName + ":" + path); e.setSize(obj.getSize()); e.setTime(when); zipOut.putNextEntry(e); obj.copyTo(zipOut); zipOut.closeEntry(); } } }.setContentType(ZIP_TYPE).setAttachmentName(safeFileName(path, suffix) + ".zip").disableGzip(); }
From source file:com.google.gerrit.server.git.ReviewNoteMerger.java
License:Eclipse Distribution License
@Override public Note merge(Note base, Note ours, Note theirs, ObjectReader reader, ObjectInserter inserter) throws IOException { if (ours == null) { return theirs; }//from w w w.j a v a 2s .c o m if (theirs == null) { return ours; } if (ours.getData().equals(theirs.getData())) { return ours; } ObjectLoader lo = reader.open(ours.getData()); byte[] sep = new byte[] { '\n' }; ObjectLoader lt = reader.open(theirs.getData()); try (ObjectStream os = lo.openStream(); ByteArrayInputStream b = new ByteArrayInputStream(sep); ObjectStream ts = lt.openStream(); UnionInputStream union = new UnionInputStream(os, b, ts)) { ObjectId noteData = inserter.insert(Constants.OBJ_BLOB, lo.getSize() + sep.length + lt.getSize(), union); return new Note(ours, noteData); } }
From source file:com.google.gitiles.BlobSoyData.java
License:Open Source License
public Map<String, Object> toSoyData(String path, ObjectId blobId) throws MissingObjectException, IOException { Map<String, Object> data = Maps.newHashMapWithExpectedSize(4); data.put("sha", ObjectId.toString(blobId)); ObjectLoader loader = walk.getObjectReader().open(blobId, Constants.OBJ_BLOB); String content;/* www. j a v a2 s.c o m*/ try { byte[] raw = loader.getCachedBytes(MAX_FILE_SIZE); content = !RawText.isBinary(raw) ? RawParseUtils.decode(raw) : null; } catch (LargeObjectException.OutOfMemory e) { throw e; } catch (LargeObjectException e) { content = null; } data.put("data", content); if (content != null) { data.put("lang", guessPrettifyLang(path, content)); } else if (content == null) { data.put("size", Long.toString(loader.getSize())); } if (path != null && view.getRevision().getPeeledType() == OBJ_COMMIT) { data.put("logUrl", GitilesView.log().copyFrom(view).toUrl()); } return data; }
From source file:com.google.gitiles.PathServlet.java
License:Open Source License
private void showSymlink(HttpServletRequest req, HttpServletResponse res, RevWalk rw, TreeWalk tw) throws IOException { GitilesView view = ViewFilter.getView(req); ObjectId id = tw.getObjectId(0);//from w w w.j a v a 2s .co m Map<String, Object> data = Maps.newHashMap(); ObjectLoader loader = rw.getObjectReader().open(id, OBJ_BLOB); String target; try { target = RawParseUtils.decode(loader.getCachedBytes(TreeSoyData.MAX_SYMLINK_SIZE)); } catch (LargeObjectException.OutOfMemory e) { throw e; } catch (LargeObjectException e) { data.put("sha", ObjectId.toString(id)); data.put("data", null); data.put("size", Long.toString(loader.getSize())); render(req, res, "gitiles.pathDetail", ImmutableMap.of("title", ViewFilter.getView(req).getTreePath(), "type", FileType.REGULAR_FILE.toString(), "data", data)); return; } String url = resolveTargetUrl( GitilesView.path().copyFrom(view).setTreePath(dirname(view.getTreePath())).build(), target); data.put("title", view.getTreePath()); data.put("target", target); if (url != null) { data.put("targetUrl", url); } // TODO(sop): Allow caching files by SHA-1 when no S cookie is sent. render(req, res, "gitiles.pathDetail", ImmutableMap.of("title", ViewFilter.getView(req).getTreePath(), "type", FileType.SYMLINK.toString(), "data", data)); }
From source file:com.mangosolutions.rcloud.rawgist.repository.git.ReadGistOperation.java
private FileContent readContent(Repository repository, TreeWalk treeWalk) { ObjectId objectId = treeWalk.getObjectId(0); String fileName = treeWalk.getPathString(); FileContent content = fileContentCache.load(objectId.getName(), fileName); if (content == null) { content = new FileContent(); try {/*from w ww .ja v a 2s . c o m*/ content.setFilename(fileName); ObjectLoader loader = repository.open(objectId); content.setContent(new String(loader.getBytes(), Charsets.UTF_8)); content.setSize(loader.getSize()); content.setTruncated(false); String language = FilenameUtils.getExtension(fileName); if (!GitGistRepository.B64_BINARY_EXTENSION.equals(language) && !StringUtils.isEmpty(language)) { content.setLanguage(language); } content.setType(MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(fileName)); fileContentCache.save(objectId.getName(), fileName, content); } catch (IOException e) { GistError error = new GistError(GistErrorCode.ERR_GIST_CONTENT_NOT_READABLE, "Could not read content of {} for gist {}", fileName, gistId); logger.error(error.getFormattedMessage() + " with path {}", this.layout.getRootFolder(), e); throw new GistRepositoryError(error, e); } } return content; }