use of com.gitblit.utils.ByteFormat in project gitblit by gitblit.
the class ByteFormatTest method testByteFormat.
@Test
public void testByteFormat() throws Exception {
// sets locale for this test
Locale defaultLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.ENGLISH);
ByteFormat format = new ByteFormat();
assertEquals("10 b", format.format(10));
assertEquals("10 KB", format.format(1024 * 10));
assertEquals("1,000 KB", format.format(1024 * 1000));
assertEquals("2.0 MB", format.format(2 * 1024 * 1000));
assertEquals("1,000.0 MB", format.format(1024 * 1024 * 1000));
assertEquals("2.0 GB", format.format(2 * 1024 * 1024 * 1000));
} finally {
Locale.setDefault(defaultLocale);
}
}
use of com.gitblit.utils.ByteFormat in project gitblit by gitblit.
the class StatusPanel method updateTable.
protected void updateTable(boolean pack) {
ServerStatus status = gitblit.getStatus();
header.setText(Translation.get("gb.status"));
version.setText(Constants.NAME + (status.isGO ? " GO v" : " WAR v") + status.version);
releaseDate.setText(status.releaseDate);
bootDate.setText(status.bootDate.toString() + " (" + Translation.getTimeUtils().timeAgo(status.bootDate) + ")");
url.setText(gitblit.url);
servletContainer.setText(status.servletContainer);
ByteFormat byteFormat = new ByteFormat();
heapMaximum.setText(byteFormat.format(status.heapMaximum));
heapAllocated.setText(byteFormat.format(status.heapAllocated));
heapUsed.setText(byteFormat.format(status.heapAllocated - status.heapFree) + " (" + byteFormat.format(status.heapFree) + " " + Translation.get("gb.free") + ")");
tableModel.setProperties(status.systemProperties);
tableModel.fireTableDataChanged();
}
use of com.gitblit.utils.ByteFormat in project gitblit by gitblit.
the class RawServlet method processRequest.
/**
* Retrieves the specified resource from the specified branch of the
* repository.
*
* @param request
* @param response
* @throws javax.servlet.ServletException
* @throws java.io.IOException
*/
private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getPathInfo();
if (path.toLowerCase().endsWith(".git")) {
// forward to url with trailing /
// this is important for relative pages links
response.sendRedirect(request.getServletPath() + path + "/");
return;
}
if (path.charAt(0) == '/') {
// strip leading /
path = path.substring(1);
}
// determine repository and resource from url
String repository = path;
Repository r = null;
int terminator = repository.length();
do {
repository = repository.substring(0, terminator);
r = repositoryManager.getRepository(repository, false);
terminator = repository.lastIndexOf('/');
} while (r == null && terminator > -1);
ServletContext context = request.getSession().getServletContext();
try {
if (r == null) {
// repository not found!
String mkd = MessageFormat.format("# Error\nSorry, no valid **repository** specified in this url: {0}!", path);
error(response, mkd);
return;
}
// identify the branch
String branch = getBranch(repository, path);
if (StringUtils.isEmpty(branch)) {
branch = r.getBranch();
if (branch == null) {
// no branches found! empty?
String mkd = MessageFormat.format("# Error\nSorry, no valid **branch** specified in this url: {0}!", path);
error(response, mkd);
} else {
// redirect to default branch
String base = request.getRequestURI();
String url = base + branch + "/";
response.sendRedirect(url);
}
return;
}
// identify the requested path
String requestedPath = getPath(repository, branch, path);
// identify the commit
RevCommit commit = JGitUtils.getCommit(r, branch);
if (commit == null) {
// branch not found!
String mkd = MessageFormat.format("# Error\nSorry, the repository {0} does not have a **{1}** branch!", repository, branch);
error(response, mkd);
return;
}
Map<String, String> quickContentTypes = new HashMap<>();
quickContentTypes.put("html", "text/html");
quickContentTypes.put("htm", "text/html");
quickContentTypes.put("xml", "application/xml");
quickContentTypes.put("json", "application/json");
List<PathModel> pathEntries = JGitUtils.getFilesInPath(r, requestedPath, commit);
if (pathEntries.isEmpty()) {
// requested a specific resource
String file = StringUtils.getLastPathElement(requestedPath);
try {
String ext = StringUtils.getFileExtension(file).toLowerCase();
// We can't parse out an extension for classic "dotfiles", so make a general assumption that
// they're text files to allow presenting them in browser instead of only for download.
//
// However, that only holds for files with no other extension included, for files that happen
// to start with a dot but also include an extension, process the extension normally.
// This logic covers .gitattributes, .gitignore, .zshrc, etc., but does not cover .mongorc.js, .zshrc.bak
boolean isExtensionlessDotfile = file.charAt(0) == '.' && (file.length() == 1 || file.indexOf('.', 1) < 0);
String contentType = isExtensionlessDotfile ? "text/plain" : quickContentTypes.get(ext);
if (contentType == null) {
List<String> exts = runtimeManager.getSettings().getStrings(Keys.web.prettyPrintExtensions);
if (exts.contains(ext)) {
// extension is a registered text type for pretty printing
contentType = "text/plain";
} else {
// query Tika for the content type
Tika tika = new Tika();
contentType = tika.detect(file);
}
}
if (contentType == null) {
// ask the container for the content type
contentType = context.getMimeType(requestedPath);
if (contentType == null) {
// still unknown content type, assume binary
contentType = "application/octet-stream";
}
}
if (isTextType(contentType) || isTextDataType(contentType)) {
// load, interpret, and serve text content as UTF-8
String[] encodings = runtimeManager.getSettings().getStrings(Keys.web.blobEncodings).toArray(new String[0]);
String content = JGitUtils.getStringContent(r, commit.getTree(), requestedPath, encodings);
if (content == null) {
logger.error("RawServlet Failed to load {} {} {}", repository, commit.getName(), path);
notFound(response, requestedPath, branch);
return;
}
byte[] bytes = content.getBytes(Constants.ENCODING);
setContentType(response, contentType);
response.setContentLength(bytes.length);
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
sendContent(response, JGitUtils.getCommitDate(commit), is);
} else {
// stream binary content directly from the repository
if (!streamFromRepo(request, response, r, commit, requestedPath)) {
logger.error("RawServlet Failed to load {} {} {}", repository, commit.getName(), path);
notFound(response, requestedPath, branch);
}
}
return;
} catch (Exception e) {
logger.error(null, e);
}
} else {
// path request
if (!request.getPathInfo().endsWith("/")) {
// redirect to trailing '/' url
response.sendRedirect(request.getServletPath() + request.getPathInfo() + "/");
return;
}
if (renderIndex()) {
// locate and render an index file
Map<String, String> names = new TreeMap<String, String>();
for (PathModel entry : pathEntries) {
names.put(entry.name.toLowerCase(), entry.name);
}
List<String> extensions = new ArrayList<String>();
extensions.add("html");
extensions.add("htm");
String content = null;
for (String ext : extensions) {
String key = "index." + ext;
if (names.containsKey(key)) {
String fileName = names.get(key);
String fullPath = fileName;
if (!requestedPath.isEmpty()) {
fullPath = requestedPath + "/" + fileName;
}
String[] encodings = runtimeManager.getSettings().getStrings(Keys.web.blobEncodings).toArray(new String[0]);
String stringContent = JGitUtils.getStringContent(r, commit.getTree(), fullPath, encodings);
if (stringContent == null) {
continue;
}
content = stringContent;
requestedPath = fullPath;
break;
}
}
response.setContentType("text/html; charset=" + Constants.ENCODING);
byte[] bytes = content.getBytes(Constants.ENCODING);
response.setContentLength(bytes.length);
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
sendContent(response, JGitUtils.getCommitDate(commit), is);
return;
}
}
// no content, document list or 404 page
if (pathEntries.isEmpty()) {
// default 404 page
notFound(response, requestedPath, branch);
return;
} else {
//
// directory list
//
response.setContentType("text/html");
response.getWriter().append("<style>table th, table td { min-width: 150px; text-align: left; }</style>");
response.getWriter().append("<table>");
response.getWriter().append("<thead><tr><th>path</th><th>mode</th><th>size</th></tr>");
response.getWriter().append("</thead>");
response.getWriter().append("<tbody>");
String pattern = "<tr><td><a href=\"{0}/{1}\">{1}</a></td><td>{2}</td><td>{3}</td></tr>";
final ByteFormat byteFormat = new ByteFormat();
if (!pathEntries.isEmpty()) {
if (pathEntries.get(0).path.indexOf('/') > -1) {
// we are in a subdirectory, add parent directory link
String pp = URLEncoder.encode(requestedPath, Constants.ENCODING);
pathEntries.add(0, new PathModel("..", pp + "/..", null, 0, FileMode.TREE.getBits(), null, null));
}
}
String basePath = request.getServletPath() + request.getPathInfo();
if (basePath.charAt(basePath.length() - 1) == '/') {
// strip trailing slash
basePath = basePath.substring(0, basePath.length() - 1);
}
for (PathModel entry : pathEntries) {
String pp = URLEncoder.encode(entry.name, Constants.ENCODING);
response.getWriter().append(MessageFormat.format(pattern, basePath, pp, JGitUtils.getPermissionsFromMode(entry.mode), entry.isFile() ? byteFormat.format(entry.size) : ""));
}
response.getWriter().append("</tbody>");
response.getWriter().append("</table>");
}
} catch (Throwable t) {
logger.error("Failed to write page to client", t);
} finally {
r.close();
}
}
use of com.gitblit.utils.ByteFormat in project gitblit by gitblit.
the class RepositoryManager method updateLastChangeFields.
/**
* Updates the last changed fields and optionally calculates the size of the
* repository. Gitblit caches the repository sizes to reduce the performance
* penalty of recursive calculation. The cache is updated if the repository
* has been changed since the last calculation.
*
* @param model
* @return size in bytes of the repository
*/
@Override
public long updateLastChangeFields(Repository r, RepositoryModel model) {
LastChange lc = JGitUtils.getLastChange(r);
model.lastChange = lc.when;
model.lastChangeAuthor = lc.who;
if (!settings.getBoolean(Keys.web.showRepositorySizes, true) || model.skipSizeCalculation) {
model.size = null;
return 0L;
}
if (!repositorySizeCache.hasCurrent(model.name, model.lastChange)) {
File gitDir = r.getDirectory();
long sz = com.gitblit.utils.FileUtils.folderSize(gitDir);
repositorySizeCache.updateObject(model.name, model.lastChange, sz);
}
long size = repositorySizeCache.getObject(model.name);
ByteFormat byteFormat = new ByteFormat();
model.size = byteFormat.format(size);
return size;
}
Aggregations