1 11 package org.apache.catalina.ssi; 12 13 14 import java.io.IOException ; 15 import java.io.PrintWriter ; 16 import java.text.DecimalFormat ; 17 26 public final class SSIFsize implements SSICommand { 27 protected final static int ONE_KILOBYTE = 1024; 28 protected final static int ONE_MEGABYTE = 1024 * 1024; 29 30 31 34 public long process(SSIMediator ssiMediator, String commandName, 35 String [] paramNames, String [] paramValues, PrintWriter writer) { 36 long lastModified = 0; 37 String configErrMsg = ssiMediator.getConfigErrMsg(); 38 for (int i = 0; i < paramNames.length; i++) { 39 String paramName = paramNames[i]; 40 String paramValue = paramValues[i]; 41 String substitutedValue = ssiMediator 42 .substituteVariables(paramValue); 43 try { 44 if (paramName.equalsIgnoreCase("file") 45 || paramName.equalsIgnoreCase("virtual")) { 46 boolean virtual = paramName.equalsIgnoreCase("virtual"); 47 lastModified = ssiMediator.getFileLastModified( 48 substitutedValue, virtual); 49 long size = ssiMediator.getFileSize(substitutedValue, 50 virtual); 51 String configSizeFmt = ssiMediator.getConfigSizeFmt(); 52 writer.write(formatSize(size, configSizeFmt)); 53 } else { 54 ssiMediator.log("#fsize--Invalid attribute: " + paramName); 55 writer.write(configErrMsg); 56 } 57 } catch (IOException e) { 58 ssiMediator.log("#fsize--Couldn't get size for file: " 59 + substitutedValue, e); 60 writer.write(configErrMsg); 61 } 62 } 63 return lastModified; 64 } 65 66 67 public String repeat(char aChar, int numChars) { 68 if (numChars < 0) { 69 throw new IllegalArgumentException ("Num chars can't be negative"); 70 } 71 StringBuffer buf = new StringBuffer (); 72 for (int i = 0; i < numChars; i++) { 73 buf.append(aChar); 74 } 75 return buf.toString(); 76 } 77 78 79 public String padLeft(String str, int maxChars) { 80 String result = str; 81 int charsToAdd = maxChars - str.length(); 82 if (charsToAdd > 0) { 83 result = repeat(' ', charsToAdd) + str; 84 } 85 return result; 86 } 87 88 89 protected String formatSize(long size, String format) { 92 String retString = ""; 93 if (format.equalsIgnoreCase("bytes")) { 94 DecimalFormat decimalFormat = new DecimalFormat ("#,##0"); 95 retString = decimalFormat.format(size); 96 } else { 97 if (size == 0) { 98 retString = "0k"; 99 } else if (size < ONE_KILOBYTE) { 100 retString = "1k"; 101 } else if (size < ONE_MEGABYTE) { 102 retString = Long.toString((size + 512) / ONE_KILOBYTE); 103 retString += "k"; 104 } else if (size < 99 * ONE_MEGABYTE) { 105 DecimalFormat decimalFormat = new DecimalFormat ("0.0M"); 106 retString = decimalFormat.format(size / (double)ONE_MEGABYTE); 107 } else { 108 retString = Long.toString((size + (529 * ONE_KILOBYTE)) 109 / ONE_MEGABYTE); 110 retString += "M"; 111 } 112 retString = padLeft(retString, 5); 113 } 114 return retString; 115 } 116 } | Popular Tags |