View Javadoc

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