1 package org.collectionspace.services.id.part;
3 import java.util.IllegalFormatException;
4 import java.io.PrintWriter;
5 import java.io.StringWriter;
7 // Uses Java's interpreter for printf-style format strings.
8 // http://java.sun.com/javase/1.6/docs/api/java/util/Formatter.html
10 public class JavaPrintfIDPartOutputFormatter implements IDPartOutputFormatter {
12 StringWriter stringwriter = new StringWriter();
13 private int maxOutputLength = DEFAULT_MAX_OUTPUT_LENGTH;
14 private String formatPattern;
16 public JavaPrintfIDPartOutputFormatter () {
20 public int getMaxOutputLength () {
21 return this.maxOutputLength;
24 public void setMaxOutputLength (int length) {
25 this.maxOutputLength = length;
29 public String getFormatPattern () {
30 return this.formatPattern;
33 public void setFormatPattern(String pattern) {
34 this.formatPattern = pattern;
38 public String format(String id) {
40 String formattedID = id;
42 String pattern = getFormatPattern();
44 // If the formatting pattern is empty, just check length.
45 if (pattern == null || pattern.trim().isEmpty()) {
46 isValidLength(formattedID);
48 // Otherwise, format the ID using the pattern, then check length.
50 // Clear the StringWriter's buffer from its last usage.
51 StringBuffer buf = stringwriter.getBuffer();
53 // Apply the formatting pattern to the ID.
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.
61 isValidLength(formattedID);
67 // Check whether the formatted ID exceeds the specified maximum length.
69 private void isValidLength(String id) {
70 if (id.length() > getMaxOutputLength()) {
71 // @TODO Log error, possibly throw exception.