1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.classic.pattern;
15
16 import static ch.qos.logback.core.CoreConstants.DOT;
17
18 public class TargetLengthBasedClassNameAbbreviator implements Abbreviator {
19
20 final int targetLength;
21
22 public TargetLengthBasedClassNameAbbreviator(int targetLength) {
23 this.targetLength = targetLength;
24 }
25
26 public String abbreviate(String fqClassName) {
27 if (fqClassName == null) {
28 throw new IllegalArgumentException("Class name may not be null");
29 }
30
31 int inLen = fqClassName.length();
32 if (inLen < targetLength) {
33 return fqClassName;
34 }
35
36 StringBuilder buf = new StringBuilder(inLen);
37
38 int rightMostDotIndex = fqClassName.lastIndexOf(DOT);
39
40 if (rightMostDotIndex == -1)
41 return fqClassName;
42
43
44 int lastSegmentLength = inLen - rightMostDotIndex;
45
46 int leftSegments_TargetLen = targetLength - lastSegmentLength;
47 if (leftSegments_TargetLen < 0)
48 leftSegments_TargetLen = 0;
49
50 int leftSegmentsLen = inLen - lastSegmentLength;
51
52
53
54
55 int maxPossibleTrim = leftSegmentsLen - leftSegments_TargetLen;
56
57 int trimmed = 0;
58 boolean inDotState = true;
59
60 int i = 0;
61 for (; i < rightMostDotIndex; i++) {
62 char c = fqClassName.charAt(i);
63 if (c == DOT) {
64
65 if (trimmed >= maxPossibleTrim)
66 break;
67 buf.append(c);
68 inDotState = true;
69 } else {
70 if (inDotState) {
71 buf.append(c);
72 inDotState = false;
73 } else {
74 trimmed++;
75 }
76 }
77 }
78
79 buf.append(fqClassName.substring(i));
80 return buf.toString();
81 }
82 }