01: package org.slf4j.migrator.helper;
02:
03: public class Abbreviator {
04: static final String FILLER = "...";
05:
06: final char folderSeparator;
07: final int invariantPrefixLength;
08: final int desiredLength;
09:
10: public Abbreviator(int invariantPrefixLength, int desiredLength,
11: char folderSeparator) {
12: this .invariantPrefixLength = invariantPrefixLength;
13: this .desiredLength = desiredLength;
14: this .folderSeparator = folderSeparator;
15: }
16:
17: public String abbreviate(String filename) {
18: if (filename.length() <= desiredLength) {
19: return filename;
20: } else {
21:
22: int firstIndex = filename.indexOf(folderSeparator,
23: invariantPrefixLength);
24: if (firstIndex == -1) {
25: // we cant't process this string
26: return filename;
27: }
28: StringBuffer buf = new StringBuffer(desiredLength);
29: buf.append(filename.substring(0, firstIndex + 1));
30: buf.append(FILLER);
31: int nextIndex = computeNextIndex(filename, firstIndex);
32: if (nextIndex != -1) {
33: buf.append(filename.substring(nextIndex));
34: } else {
35: // better long than wrong
36: return filename;
37: }
38:
39: if (buf.length() < filename.length()) {
40: return buf.toString();
41: } else {
42: // we tried our best but we are still could not shorten the input
43: return filename;
44: }
45: }
46: }
47:
48: int computeNextIndex(String filename, int firstIndex) {
49: int nextIndex = firstIndex + 1;
50: int hitCount = 0;
51: int minToRemove = filename.length() - desiredLength
52: + FILLER.length();
53: while (nextIndex < firstIndex + minToRemove) {
54: int tmpIndex = filename.indexOf(folderSeparator,
55: nextIndex + 1);
56: if (tmpIndex == -1) {
57: if (hitCount == 0) {
58: return -1;
59: } else {
60: return nextIndex;
61: }
62: } else {
63: hitCount++;
64: nextIndex = tmpIndex;
65: }
66: }
67: return nextIndex;
68: }
69: }
|