]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
ac06702c73a32f3c1050a152b26189cce8f0d208
[tmp/jakarta-migration.git] /
1 package org.collectionspace.services.id.part;
2
3 import java.util.IllegalFormatException;
4 import java.io.PrintWriter;
5 import java.io.StringWriter;
6
7 // Uses Java's interpreter for printf-style format strings.
8 // http://java.sun.com/javase/1.6/docs/api/java/util/Formatter.html
9
10 public class JavaPrintfIDPartOutputFormatter implements IDPartOutputFormatter {
11
12     StringWriter stringwriter = new StringWriter();
13     private int maxOutputLength = DEFAULT_MAX_OUTPUT_LENGTH;
14     private String formatPattern;
15
16     public JavaPrintfIDPartOutputFormatter () {
17     }
18
19     @Override
20     public int getMaxOutputLength () {
21         return this.maxOutputLength;
22     }
23
24     public void setMaxOutputLength (int length) {
25         this.maxOutputLength = length;
26     }
27
28     @Override
29     public String getFormatPattern () {
30         return this.formatPattern;
31     }
32
33     public void setFormatPattern(String pattern) {
34         this.formatPattern = pattern;
35     }
36
37     @Override
38     public String format(String id) {
39
40         String formattedID = id;
41
42         String pattern = getFormatPattern();
43
44         // If the formatting pattern is empty, just check length.
45         if (pattern == null || pattern.trim().isEmpty()) {
46             isValidLength(formattedID);
47
48         // Otherwise, format the ID using the pattern, then check length.
49         } else {
50             // Clear the StringWriter's buffer from its last usage. 
51             StringBuffer buf = stringwriter.getBuffer();
52             buf.setLength(0);
53             // Apply the formatting pattern to the ID.
54             try {
55                 PrintWriter printwriter = new PrintWriter(stringwriter);
56                 printwriter.printf(id, pattern);
57                 formattedID = stringwriter.toString();
58             } catch(IllegalFormatException e) {
59                 // @TODO Log and handle this exception.
60             }
61             isValidLength(formattedID);
62         }
63
64         return formattedID;
65     }
66
67     // Check whether the formatted ID exceeds the specified maximum length.
68
69     private void isValidLength(String id) {
70         if (id.length() > getMaxOutputLength()) {
71             // @TODO Log error, possibly throw exception.
72         }
73
74     }
75
76 }
77