View Javadoc

1   /**
2    * Logback: the generic, reliable, fast and flexible logging framework for Java.
3    * 
4    * Copyright (C) 2000-2006, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  package ch.qos.logback.core.util;
11  
12  import java.util.regex.Matcher;
13  import java.util.regex.Pattern;
14  
15  /**
16   * Instances of this class represent the size of a file. Internally, the size is
17   * stored as long.>
18   * 
19   * <p>The {@link #valueOf} method can convert strings such as "3 kb", "5 mb", into
20   * FileSize instances. The recognized unit specifications for file size are the
21   * "kb", "mb", and "gb". The unit name may be followed by an "s". Thus, "2 kbs"
22   * and "2 kb" are equivalent. In the absence of a time unit specification, byte
23   * is assumed.
24   *  
25   * @author Ceki G&uuml;lc&uuml;
26   * 
27   */
28  public class FileSize {
29  
30    private final static String LENGTH_PART = "([0-9]+)";
31    private final static int DOUBLE_GROUP = 1;
32  
33    private final static String UNIT_PART = "(|kb|mb|gb)s?";
34    private final static int UNIT_GROUP = 2;
35  
36    private static final Pattern FILE_SIZE_PATTERN = Pattern.compile(LENGTH_PART
37        + "\\s*" + UNIT_PART, Pattern.CASE_INSENSITIVE);
38  
39    static final long KB_COEFFICIENT = 1024;
40    static final long MB_COEFFICIENT = 1024 * KB_COEFFICIENT;
41    static final long GB_COEFFICIENT = 1024 * MB_COEFFICIENT;
42  
43    final long size;
44  
45    FileSize(long size) {
46      this.size = size;
47    }
48  
49    public long getSize() {
50      return size;
51    }
52  
53    static public FileSize valueOf(String fileSizeStr) {
54      Matcher matcher = FILE_SIZE_PATTERN.matcher(fileSizeStr);
55  
56      long coefficient;
57      if (matcher.matches()) {
58        String lenStr = matcher.group(DOUBLE_GROUP);
59        String unitStr = matcher.group(UNIT_GROUP);
60  
61        long lenValue = Long.valueOf(lenStr);
62        if (unitStr.equalsIgnoreCase("")) {
63          coefficient = 1;
64        } else if (unitStr.equalsIgnoreCase("kb")) {
65          coefficient = KB_COEFFICIENT;
66        } else if (unitStr.equalsIgnoreCase("mb")) {
67          coefficient = MB_COEFFICIENT;
68        } else if (unitStr.equalsIgnoreCase("gb")) {
69          coefficient = GB_COEFFICIENT;
70        } else {
71          throw new IllegalStateException("Unexpected " + unitStr);
72        }
73        return new FileSize(lenValue * coefficient);
74      } else {
75        throw new IllegalArgumentException("String value [" + fileSizeStr
76            + "] is not in the expected format.");
77      }
78  
79    }
80  }