From 33a72983d2992d5485433b9b9c037daf960d0a58 Mon Sep 17 00:00:00 2001 From: Telesphoreo Date: Sun, 17 Apr 2022 18:54:38 -0500 Subject: [PATCH] add size --- .../dev/plex/request/AbstractServlet.java | 26 ++++++++++++++++++- .../plex/request/impl/SchematicEndpoint.java | 4 +-- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/main/java/dev/plex/request/AbstractServlet.java b/src/main/java/dev/plex/request/AbstractServlet.java index d32d76f..8c8e201 100644 --- a/src/main/java/dev/plex/request/AbstractServlet.java +++ b/src/main/java/dev/plex/request/AbstractServlet.java @@ -13,6 +13,8 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.text.CharacterIterator; +import java.text.StringCharacterIterator; import java.util.List; import java.util.Objects; import lombok.Data; @@ -73,7 +75,10 @@ public class AbstractServlet extends HttpServlet try { Object object = mapping.method.invoke(this, req, resp); - if (object != null) resp.getWriter().println(object.toString()); + if (object != null) + { + resp.getWriter().println(object.toString()); + } } catch (IOException | IllegalAccessException | InvocationTargetException e) { @@ -101,6 +106,25 @@ public class AbstractServlet extends HttpServlet return contentBuilder.toString(); } + // Code from https://programming.guide/java/formatting-byte-size-to-human-readable-format.html + public static String formattedSize(long bytes) + { + long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes); + if (absB < 1024) + { + return bytes + " B"; + } + long value = absB; + CharacterIterator ci = new StringCharacterIterator("KMGTPE"); + for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) + { + value >>= 10; + ci.next(); + } + value *= Long.signum(bytes); + return String.format("%.1f %ciB", value / 1024.0, ci.current()); + } + @Data public static class Mapping { diff --git a/src/main/java/dev/plex/request/impl/SchematicEndpoint.java b/src/main/java/dev/plex/request/impl/SchematicEndpoint.java index 7249462..e560bf3 100644 --- a/src/main/java/dev/plex/request/impl/SchematicEndpoint.java +++ b/src/main/java/dev/plex/request/impl/SchematicEndpoint.java @@ -22,7 +22,7 @@ public class SchematicEndpoint extends AbstractServlet } else { - OutputStream outputStream = null; + OutputStream outputStream; try { outputStream = response.getOutputStream(); @@ -93,7 +93,7 @@ public class SchematicEndpoint extends AbstractServlet { sb.append("" + "" + worldeditFile.getName() + "" + - "" + worldeditFile.length() + "B" + "" + + "" + formattedSize(worldeditFile.length()) + "" + ""); } file = file.replace("${schematics}", sb.toString());