001: /*
002: * @(#)QuarterNameConverter.java 5/8/2006
003: *
004: * Copyright 2002 - 2006 JIDE Software Inc. All rights reserved.
005: */
006:
007: package com.jidesoft.converter;
008:
009: import java.text.MessageFormat;
010: import java.text.ParseException;
011: import java.util.Locale;
012: import java.util.ResourceBundle;
013:
014: /**
015: * Converter which converts quarter to String and converts it back.
016: */
017: public class QuarterNameConverter implements ObjectConverter {
018:
019: /**
020: * Default ConverterContext for MonthConverter.
021: */
022: public static ConverterContext CONTEXT = new ConverterContext(
023: "QuarterName");
024: private static String _quarterNamePattern;
025:
026: /**
027: * Creates a new CalendarConverter.
028: */
029: public QuarterNameConverter() {
030: }
031:
032: public String toString(Object object, ConverterContext context) {
033: if (object == null || !(object instanceof Integer)) {
034: return "";
035: } else {
036: return MessageFormat.format(getQuarterNamePattern(),
037: ((Integer) object + 1));
038: }
039: }
040:
041: public boolean supportToString(Object object,
042: ConverterContext context) {
043: return true;
044: }
045:
046: public Object fromString(String string, ConverterContext context) {
047: String quarterNamePattern = getQuarterNamePattern();
048: try {
049: Object[] values = new MessageFormat(quarterNamePattern)
050: .parse(string);
051: if (values.length > 0) {
052: return Integer.parseInt("" + values[0]);
053: }
054: } catch (ParseException e) {
055: // ignore
056: }
057: return 0;
058: }
059:
060: public boolean supportFromString(String string,
061: ConverterContext context) {
062: return true;
063: }
064:
065: // public static void main(String[] args) {
066: // ObjectConverter converter = new QuarterNameConverter();
067: // for (int i = 0; i < 4; i++) {
068: // String str = converter.toString(new Integer(i), null);
069: // System.out.println(str);
070: // System.out.println(converter.fromString(str, null));
071: // }
072: // }
073:
074: /**
075: * Gets the quarter name pattern when converting from an int to a String. For example, if the int is 0, it will
076: * converted to "Qtr 1" if the quarter name pattern is "Qtr {0}".
077: *
078: * @return the prefix.
079: */
080: public String getQuarterNamePattern() {
081: if (_quarterNamePattern == null) {
082: return getResourceString("Quarter.quarter");
083: }
084: return _quarterNamePattern;
085: }
086:
087: /**
088: * Sets the quarter name pattern. For example, if the int is 0, it will
089: * converted to "Qtr 1" if the pattern is "Qtr {0}".
090: *
091: * @param quarterName
092: */
093: public void setQuarterNamePattern(String quarterName) {
094: _quarterNamePattern = quarterName;
095: }
096:
097: protected String getResourceString(String key) {
098: final ResourceBundle resourceBundle = Resource
099: .getResourceBundle(Locale.getDefault());
100: return resourceBundle.getString(key);
101: }
102:
103: }
|