1 17 package org.alfresco.web.ui.common.converter; 18 19 import java.text.DecimalFormat ; 20 21 import javax.faces.component.UIComponent; 22 import javax.faces.context.FacesContext; 23 import javax.faces.convert.Converter; 24 25 import org.alfresco.web.app.Application; 26 27 32 public class ByteSizeConverter implements Converter 33 { 34 37 public static final String CONVERTER_ID = "org.alfresco.faces.ByteSizeConverter"; 38 39 private static final String MSG_POSTFIX_KB = "kilobyte"; 40 private static final String MSG_POSTFIX_MB = "megabyte"; 41 private static final String MSG_POSTFIX_GB = "gigabyte"; 42 43 private static final String NUMBER_PATTERN = "###,###.##"; 44 45 48 public Object getAsObject(FacesContext context, UIComponent component, String value) 49 { 50 return Long.parseLong(value); 51 } 52 53 56 public String getAsString(FacesContext context, UIComponent component, Object value) 57 { 58 long size; 59 if (value instanceof Long ) 60 { 61 size = (Long )value; 62 } 63 else if (value instanceof String ) 64 { 65 try 66 { 67 size = Long.parseLong((String )value); 68 } 69 catch (NumberFormatException ne) 70 { 71 return (String )value; 72 } 73 } 74 else 75 { 76 return ""; 77 } 78 79 DecimalFormat formatter = new DecimalFormat (NUMBER_PATTERN); 82 83 StringBuilder buf = new StringBuilder (); 84 85 if (size < 999999) 86 { 87 double val = ((double)size) / 1024.0; 88 buf.append(formatter.format(val)) 89 .append(' ') 90 .append(Application.getMessage(context, MSG_POSTFIX_KB)); 91 } 92 else if (size < 999999999) 93 { 94 double val = ((double)size) / 1048576.0; 95 buf.append(formatter.format(val)) 96 .append(' ') 97 .append(Application.getMessage(context, MSG_POSTFIX_MB)); 98 } 99 else 100 { 101 double val = ((double)size) / 1073741824.0; 102 buf.append(formatter.format(val)) 103 .append(' ') 104 .append(Application.getMessage(context, MSG_POSTFIX_GB)); 105 } 106 107 return buf.toString(); 108 } 109 } 110 | Popular Tags |