1:
30:
31: package ;
32:
33: public class DefaultNameGenerator implements NameGenerator
34: {
35: private ContentLocation location;
36: private String defaultNameHint;
37: private String defaultSuffix;
38:
39: public DefaultNameGenerator(final ContentLocation location)
40: {
41: this(location, "file", null);
42: }
43:
44: public DefaultNameGenerator(final ContentLocation location,
45: final String defaultNameHint)
46: {
47: if (location == null)
48: {
49: throw new NullPointerException();
50: }
51: if (defaultNameHint == null)
52: {
53: throw new NullPointerException();
54: }
55:
56: this.location = location;
57:
58:
59: final int pos = defaultNameHint.lastIndexOf('.');
60: if (defaultSuffix == null && pos > 0)
61: {
62: if (pos < (defaultNameHint.length() - 1))
63: {
64: this.defaultNameHint = defaultNameHint.substring(0, pos - 1);
65: this.defaultSuffix = defaultNameHint.substring(pos + 1);
66: }
67: else
68: {
69: this.defaultNameHint = defaultNameHint.substring(0, pos - 1);
70: this.defaultSuffix = null;
71: }
72: }
73: else
74: {
75: this.defaultNameHint = defaultNameHint;
76: this.defaultSuffix = null;
77: }
78: }
79:
80: public DefaultNameGenerator(final ContentLocation location,
81: final String defaultNameHint,
82: final String defaultSuffix)
83: {
84: if (location == null)
85: {
86: throw new NullPointerException();
87: }
88: if (defaultNameHint == null)
89: {
90: throw new NullPointerException();
91: }
92:
93: this.location = location;
94: this.defaultNameHint = defaultNameHint;
95: this.defaultSuffix = defaultSuffix;
96: }
97:
98:
108: public String generateName(final String nameHint, final String mimeType)
109: throws ContentIOException
110: {
111: final String name;
112: if (nameHint != null)
113: {
114: name = nameHint;
115: }
116: else
117: {
118: name = defaultNameHint;
119: }
120:
121: final String suffix;
122: if (defaultSuffix != null)
123: {
124: suffix = defaultSuffix;
125: }
126: else
127: {
128: suffix = getSuffixForType(mimeType, location);
129: }
130:
131: final String firstFileName = name + "." + suffix;
132: if (location.exists(firstFileName) == false)
133: {
134: return firstFileName;
135: }
136: int counter = 0;
137: while (true)
138: {
139: if (counter < 0)
140: {
141: throw new ContentIOException();
142: }
143:
144: final String filename = name + counter + "." + suffix;
145: if (location.exists(filename) == false)
146: {
147: return filename;
148: }
149: counter += 1;
150: }
151: }
152:
153: private String getSuffixForType(final String mimeType,
154: final ContentLocation location)
155: {
156: final Repository repository = location.getRepository();
157: final MimeRegistry mimeRegistry = repository.getMimeRegistry();
158: return mimeRegistry.getSuffix(mimeType);
159: }
160: }