1 package org.collectionspace.services.id.part;
3 import java.io.PrintWriter;
4 import java.io.StringWriter;
5 import java.util.IllegalFormatException;
7 import org.slf4j.Logger;
8 import org.slf4j.LoggerFactory;
10 // Uses Java's interpreter for printf-style format strings.
11 // http://java.sun.com/javase/1.6/docs/api/java/util/Formatter.html
13 public class JavaPrintfIDPartOutputFormatter implements IDPartOutputFormatter {
16 LoggerFactory.getLogger(JavaPrintfIDPartOutputFormatter.class);
18 StringWriter stringwriter = new StringWriter();
19 private int maxOutputLength = DEFAULT_MAX_OUTPUT_LENGTH;
20 private String formatPattern;
22 public JavaPrintfIDPartOutputFormatter() {
25 public JavaPrintfIDPartOutputFormatter(String formatPattern) {
26 setFormatPattern(formatPattern);
30 public int getMaxOutputLength() {
31 return this.maxOutputLength;
35 public void setMaxOutputLength(int length) {
36 this.maxOutputLength = length;
40 public String getFormatPattern() {
41 return this.formatPattern;
45 public void setFormatPattern(String pattern) {
46 if (pattern == null || pattern.trim().isEmpty()) {
47 logger.error("Format pattern cannot be null or empty.");
49 this.formatPattern = pattern;
55 public String format(String id) {
57 String formattedID = id;
59 String pattern = getFormatPattern();
61 // If the formatting pattern is empty, just check length.
62 if (pattern == null || pattern.trim().isEmpty()) {
64 if (! isValidLength(formattedID)) {
66 "Formatted ID '" + formattedID +
67 "' exceeds maximum length of " +
68 getMaxOutputLength() + " characters." +
69 "Returning ID without formatting.");
73 // Otherwise, format the ID using the pattern, then check length.
75 // Clear the StringWriter's buffer from its last usage.
76 StringBuffer buf = stringwriter.getBuffer();
78 // Apply the formatting pattern to the ID.
80 PrintWriter printwriter = new PrintWriter(stringwriter);
81 printwriter.printf(id, pattern);
82 formattedID = stringwriter.toString();
83 } catch(IllegalFormatException e) {
84 // @TODO Log and handle this exception.
86 isValidLength(formattedID);
92 // Check whether the formatted ID exceeds the specified maximum length.
94 private boolean isValidLength(String id) {
95 if (id.length() <= getMaxOutputLength()) {