Source Code Cross Referenced for FieldConverter.java in  » Project-Management » OpenProj » com » projity » field » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Project Management » OpenProj » com.projity.field 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:        The contents of this file are subject to the Common Public Attribution License 
003:        Version 1.0 (the "License"); you may not use this file except in compliance with 
004:        the License. You may obtain a copy of the License at 
005:        http://www.projity.com/license . The License is based on the Mozilla Public 
006:        License Version 1.1 but Sections 14 and 15 have been added to cover use of 
007:        software over a computer network and provide for limited attribution for the 
008:        Original Developer. In addition, Exhibit A has been modified to be consistent 
009:        with Exhibit B.
010:
011:        Software distributed under the License is distributed on an "AS IS" basis, 
012:        WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the 
013:        specific language governing rights and limitations under the License. The 
014:        Original Code is OpenProj. The Original Developer is the Initial Developer and 
015:        is Projity, Inc. All portions of the code written by Projity are Copyright (c) 
016:        2006, 2007. All Rights Reserved. Contributors Projity, Inc.
017:
018:        Alternatively, the contents of this file may be used under the terms of the 
019:        Projity End-User License Agreeement (the Projity License), in which case the 
020:        provisions of the Projity License are applicable instead of those above. If you 
021:        wish to allow use of your version of this file only under the terms of the 
022:        Projity License and not to allow others to use your version of this file under 
023:        the CPAL, indicate your decision by deleting the provisions above and replace 
024:        them with the notice and other provisions required by the Projity  License. If 
025:        you do not delete the provisions above, a recipient may use your version of this 
026:        file under either the CPAL or the Projity License.
027:
028:        [NOTE: The text of this license may differ slightly from the text of the notices 
029:        in Exhibits A and B of the license at http://www.projity.com/license. You should 
030:        use the latest text at http://www.projity.com/license for your modifications.
031:        You may not remove this license text from the source files.]
032:
033:        Attribution Information: Attribution Copyright Notice: Copyright © 2006, 2007 
034:        Projity, Inc. Attribution Phrase (not exceeding 10 words): Powered by OpenProj, 
035:        an open source solution from Projity. Attribution URL: http://www.projity.com 
036:        Graphic Image as provided in the Covered Code as file:  openproj_logo.png with 
037:        alternatives listed on http://www.projity.com/logo
038:
039:        Display of Attribution Information is required in Larger Works which are defined 
040:        in the CPAL as a work which combines Covered Code or portions thereof with code 
041:        not governed by the terms of the CPAL. However, in addition to the other notice 
042:        obligations, all copies of the Covered Code in Executable and Source Code form 
043:        distributed must, as a form of attribution of the original author, include on 
044:        each user interface screen the "OpenProj" logo visible to all users.  The 
045:        OpenProj logo should be located horizontally aligned with the menu bar and left 
046:        justified on the top left of the screen adjacent to the File menu.  The logo 
047:        must be at least 100 x 25 pixels.  When users click on the "OpenProj" logo it 
048:        must direct them back to http://www.projity.com.  
049:         */
050:        package com.projity.field;
051:
052:        import java.text.ParseException;
053:        import java.util.Calendar;
054:        import java.util.Date;
055:        import java.util.GregorianCalendar;
056:        import java.util.HashMap;
057:
058:        import org.apache.commons.beanutils.ConversionException;
059:        import org.apache.commons.beanutils.ConvertUtils;
060:        import org.apache.commons.beanutils.Converter;
061:
062:        import com.projity.datatype.Duration;
063:        import com.projity.datatype.DurationFormat;
064:        import com.projity.datatype.Money;
065:        import com.projity.datatype.Work;
066:        import com.projity.options.EditOption;
067:        import com.projity.strings.Messages;
068:        import com.projity.util.DateTime;
069:
070:        /**
071:         * This class decorates ConvertUtils to use Projity specific types and validation
072:         */
073:        public class FieldConverter {
074:            HashMap<FieldContext, HashMap<Class, Converter>> contextMaps = new HashMap<FieldContext, HashMap<Class, Converter>>();
075:            private StringConverter stringConverter;
076:            private StringConverter compactStringConverter;
077:
078:            public static String toString(Object value, Class clazz,
079:                    FieldContext context) {
080:                return getInstance()._toString(value, clazz, context);
081:            }
082:
083:            public static String toString(Object value) {
084:                return getInstance()._toString(value, value.getClass(), null);
085:            }
086:
087:            public static Object fromString(String value, Class clazz) {
088:                return ConvertUtils.convert(value, clazz);
089:            }
090:
091:            /**
092:             * Convert from an object, usually a string, into another object
093:             * @param value.  Convert from this value
094:             * @param clazz. Convert to this clazz type.
095:             * @param context Converter context to use 
096:             * @return object of type clazz.
097:             * @throws FieldParseException
098:             */
099:            public static Object convert(Object value, Class clazz,
100:                    FieldContext context) throws FieldParseException {
101:                return getInstance()._convert(value, clazz, context);
102:            }
103:
104:            private static FieldConverter instance = null;
105:
106:            public static FieldConverter getInstance() {
107:                if (instance == null)
108:                    instance = new FieldConverter();
109:                return instance;
110:            }
111:
112:            public static void reinitialize() {
113:                instance = null;
114:            }
115:
116:            /**
117:             * 
118:             * @param value.  Convert from this value
119:             * @param clazz. Convert to this clazz type.
120:             * @return object of type clazz.
121:             * @throws FieldParseException
122:             */
123:            private Object _convert(Object value, Class clazz,
124:                    FieldContext context) throws FieldParseException {
125:                try {
126:                    if (value instanceof  String) {
127:                        Object result = null;
128:                        if (context == null)
129:                            result = ConvertUtils
130:                                    .convert((String) value, clazz);
131:                        else {
132:                            Converter contextConverter = null;
133:                            HashMap<Class, Converter> contextMap = contextMaps
134:                                    .get(context);
135:                            if (contextMap != null)
136:                                contextConverter = contextMap.get(clazz);
137:                            if (contextConverter != null) {
138:                                contextConverter.convert(clazz, value);
139:                            } else {
140:                                System.out
141:                                        .println("no context converter found ");
142:                                result = ConvertUtils.convert((String) value,
143:                                        clazz);
144:                            }
145:                        }
146:                        //			if (result instanceof java.util.Date) { //  dates need to be normalized
147:                        //				result = new Date(DateTime.gmt((Date) result));
148:                        //			}
149:                        if (result == null) {
150:                            throw new FieldParseException("Invalid type");
151:                        }
152:                        return result;
153:                    }
154:
155:                    // Because of stupidity of beanutils which assumes type string, I implement this by hand
156:                    Converter converter = ConvertUtils.lookup(clazz);
157:                    if (converter == null) {
158:                        System.out.println("converter is null for class "
159:                                + clazz + " instance " + instance.hashCode()
160:                                + " resetting");
161:                        instance = new FieldConverter();
162:                        converter = ConvertUtils.lookup(String.class);
163:                    }
164:                    return converter.convert(clazz, value);
165:                } catch (ConversionException conversionException) {
166:                    throw new FieldParseException(conversionException);
167:                }
168:            }
169:
170:            private String _toString(Object value, Class clazz,
171:                    FieldContext context) {
172:                if (context == COMPACT_CONVERTER_CONTEXT)
173:                    return (String) compactStringConverter
174:                            .convert(clazz, value);
175:                else
176:                    return (String) stringConverter.convert(clazz, value);
177:            }
178:
179:            public static final FieldContext COMPACT_CONVERTER_CONTEXT = new FieldContext();
180:            static {
181:                COMPACT_CONVERTER_CONTEXT.setCompact(true);
182:            }
183:
184:            private FieldConverter() {
185:                instance = this ;
186:                stringConverter = new StringConverter(false);
187:                compactStringConverter = new StringConverter(true);
188:                ConvertUtils.register(stringConverter, String.class); // Wrapper class
189:                ConvertUtils.register(new DateConverter(), Date.class); // Wrapper class
190:                ConvertUtils.register(new CalendarConverter(),
191:                        GregorianCalendar.class); // Wrapper class
192:                ConvertUtils.register(new DurationConverter(), Duration.class); // Wrapper class
193:                ConvertUtils.register(new WorkConverter(), Work.class); // Wrapper class
194:                ConvertUtils.register(new MoneyConverter(), Money.class); // Wrapper class
195:                Converter longConverter = new LongConverter();
196:                ConvertUtils.register(longConverter, Long.TYPE); // Native type
197:                ConvertUtils.register(longConverter, Long.class); // Wrapper class
198:                Converter doubleConverter = new DoubleConverter();
199:                ConvertUtils.register(doubleConverter, Double.TYPE); // Native type
200:                ConvertUtils.register(doubleConverter, Double.class); // Wrapper class
201:
202:                // short context converters
203:                HashMap<Class, Converter> compactMap = new HashMap<Class, Converter>();
204:                contextMaps.put(COMPACT_CONVERTER_CONTEXT, compactMap);
205:                compactMap.put(String.class, compactStringConverter);
206:                // no need for duration or money as parsing is done in long form
207:
208:            }
209:
210:            private static class StringConverter implements  Converter {
211:                private boolean compact = false;
212:
213:                StringConverter(boolean compact) {
214:                    this .compact = compact;
215:                }
216:
217:                public Object convert(Class clazz, Object value) {
218:                    if (value instanceof  Work) {
219:                        if (compact)
220:                            return ((DurationFormat) DurationFormat
221:                                    .getWorkInstance()).formatCompact(value);
222:                        else
223:                            return ((DurationFormat) DurationFormat
224:                                    .getWorkInstance()).format(value);
225:                    } else if (value instanceof  Duration) {
226:                        if (compact)
227:                            return ((DurationFormat) DurationFormat
228:                                    .getInstance()).formatCompact(value);
229:                        else
230:                            return ((DurationFormat) DurationFormat
231:                                    .getInstance()).format(value);
232:                    } else if (value instanceof  Money) {
233:                        return Money.formatCurrency(((Money) value)
234:                                .doubleValue(), compact);
235:                    } else if (value instanceof  Date) {
236:                        if (value.equals(DateTime.getZeroDate()))
237:                            return null;
238:                        return EditOption.getInstance().getDateFormat().format(
239:                                value);
240:                    } else {
241:                        if (value == null)
242:                            return null;
243:                        else
244:                            return value.toString();
245:                    }
246:                }
247:            }
248:
249:            // make a converter for long that can process dates and durations
250:            private static class LongConverter implements  Converter {
251:                Converter baseConverter = new org.apache.commons.beanutils.converters.LongConverter();
252:
253:                public Object convert(Class type, Object value)
254:                        throws ConversionException {
255:                    if (value == null)
256:                        return null;
257:                    if (value != null) {
258:                        if (value instanceof  Date) {
259:                            return new Long(((Date) value).getTime());
260:                        } else if (value instanceof  GregorianCalendar) {
261:                            return new Long(((GregorianCalendar) value)
262:                                    .getTimeInMillis());
263:                        } else if (value instanceof  Duration
264:                                || value instanceof  Work) {
265:                            return new Long(((Duration) value)
266:                                    .getEncodedMillis());
267:                        }
268:                    }
269:                    return baseConverter.convert(type, value);
270:                }
271:            };
272:
273:            private static class DateConverter implements  Converter {
274:                public Object convert(Class type, Object value)
275:                        throws ConversionException {
276:                    if (value == null)
277:                        return null;
278:                    if (value instanceof  Long) {
279:                        long longValue = ((Long) value).longValue();
280:                        if (longValue == 0)
281:                            return null;
282:                        return new Date(longValue);
283:                    } else if (value instanceof  Date) {
284:                        return value;
285:                    } else if (value instanceof  Calendar) {
286:                        return ((Calendar) value).getTime();
287:                    } else if (value instanceof  String) {
288:                        try {
289:                            return EditOption.getInstance().getDateFormat()
290:                                    .parse((String) value);
291:                        } catch (ParseException e) {
292:                            try {
293:                                return DateTime.utcShortDateFormatInstance()
294:                                        .parse((String) value); // try without time
295:                            } catch (ParseException e1) {
296:                                throw new ConversionException(Messages
297:                                        .getString("Message.invalidDate"));
298:                            }
299:                        }
300:                    }
301:
302:                    throw new ConversionException("Error: no conversion from "
303:                            + value.getClass().getName() + " to "
304:                            + type.getName() + " for value" + value);
305:                }
306:            };
307:
308:            // GregorianCalendar converter
309:            private static class CalendarConverter implements  Converter {
310:                private static DateConverter dateConverter = new DateConverter();
311:
312:                public Object convert(Class type, Object value)
313:                        throws ConversionException {
314:                    GregorianCalendar cal = DateTime.calendarInstance();
315:                    if (value == null) {
316:                        return null;
317:                    } else if (value instanceof  Long) {
318:                        long longValue = ((Long) value).longValue();
319:                        if (longValue == 0)
320:                            return null;
321:
322:                        cal.setTimeInMillis(longValue);
323:                        return cal;
324:                    } else if (value instanceof  Date) {
325:                        cal.setTime((Date) value);
326:                        return cal;
327:                    } else if (value instanceof  String) {
328:                        Date d = (Date) dateConverter
329:                                .convert(Date.class, value);
330:                        cal.setTime(d);
331:                        return cal;
332:                    }
333:                    throw new ConversionException("Error: no conversion from "
334:                            + value.getClass().getName() + " to "
335:                            + type.getName() + " for value" + value);
336:                }
337:            };
338:
339:            private static class DurationConverter implements  Converter {
340:                public Object convert(Class type, Object value)
341:                        throws ConversionException {
342:                    if (value == null)
343:                        return Duration.getInstanceFromDouble(null);
344:
345:                    if (value instanceof  Number) {
346:                        return new Duration(((Number) value).longValue());
347:                    } else if (value instanceof  Work) {
348:                        return new Duration(((Work) value).longValue());
349:                    } else if (value instanceof  Duration) {
350:                        return value;
351:                    } else if (value instanceof  String) {
352:                        try {
353:                            return DurationFormat.getInstance().parseObject(
354:                                    (String) value);
355:                        } catch (ParseException e) {
356:                            throw new ConversionException(Messages
357:                                    .getString("Message.invalidDuration"));
358:                        }
359:                    }
360:                    throw new ConversionException("Error: no conversion from "
361:                            + value.getClass().getName() + " to "
362:                            + type.getName() + " for value" + value);
363:                }
364:            };
365:
366:            private static class WorkConverter implements  Converter {
367:                public Object convert(Class type, Object value)
368:                        throws ConversionException {
369:                    if (value == null)
370:                        return Duration.getInstanceFromDouble(null);
371:
372:                    if (value instanceof  Number) {
373:                        return new Work(((Number) value).longValue());
374:                    } else if (value instanceof  Work) {
375:                        return new Work(((Work) value).longValue());
376:                    } else if (value instanceof  Duration) {
377:                        return value;
378:                    } else if (value instanceof  String) {
379:                        try {
380:                            return DurationFormat.getWorkInstance()
381:                                    .parseObject((String) value);
382:                        } catch (ParseException e) {
383:                            throw new ConversionException(Messages
384:                                    .getString("Message.invalidDuration"));
385:                        }
386:                    }
387:                    throw new ConversionException("Error: no conversion from "
388:                            + value.getClass().getName() + " to "
389:                            + type.getName() + " for value" + value);
390:                }
391:            };
392:
393:            private static class DoubleConverter implements  Converter {
394:                Converter baseConverter = new org.apache.commons.beanutils.converters.DoubleConverter();
395:
396:                public Object convert(Class type, Object value)
397:                        throws ConversionException {
398:                    if (value != null) {
399:                        if (value instanceof  Double) {
400:                            return value;
401:                        } else if (value instanceof  Money) {
402:                            double num = ((Number) value).doubleValue();
403:                            if (Double.isInfinite(num) || Double.isNaN(num)) {
404:                                System.out
405:                                        .println("Error: number is invalid double in MoneyConverter "
406:                                                + value);
407:                                num = 0.0;
408:                            }
409:                            return new Double(num);
410:                        }
411:                    }
412:                    return baseConverter.convert(type, value);
413:                }
414:            };
415:
416:            /* TODO I have also experimented with the JADE library's Money class.  It is probably more useful
417:             * for performing currency conversions than as a datatype.  A possible source for currency exchange rates is the 
418:             * web service here: 
419:             * http://www.bindingpoint.com/service.aspx?skey=377e6659-061f-4956-8edb-19b5023bc33b
420:             *  
421:             */
422:            private static class MoneyConverter implements  Converter {
423:                public Object convert(Class type, Object value)
424:                        throws ConversionException {
425:                    if (value == null)
426:                        return Money.getInstance(0);
427:                    if (value instanceof  Money) {
428:                        return value;
429:                    } else if (value instanceof  Number) {
430:                        double num = ((Number) value).doubleValue();
431:                        if (Double.isInfinite(num) || Double.isNaN(num)) {
432:                            System.out
433:                                    .println("Error: number is invalid double in MoneyConverter "
434:                                            + value);
435:                            num = 0.0;
436:                        }
437:                        return Money.getInstance(num);
438:                    } else if (value instanceof  String) {
439:                        try {
440:                            return Money.getFormat(false).parseObject(
441:                                    (String) value);
442:                        } catch (ParseException e) {
443:                            throw new ConversionException(Messages
444:                                    .getString("Message.invalidDuration"));
445:                        }
446:                    }
447:                    throw new ConversionException("Error: no conversion from "
448:                            + value.getClass().getName() + " to "
449:                            + type.getName() + " for value" + value);
450:                }
451:            }
452:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.