Source Code Cross Referenced for DataTypeShort.java in  » Database-Client » squirrel-sql-2.6.5a » net » sourceforge » squirrel_sql » fw » datasetviewer » cellcomponent » 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 » Database Client » squirrel sql 2.6.5a » net.sourceforge.squirrel_sql.fw.datasetviewer.cellcomponent 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        package net.sourceforge.squirrel_sql.fw.datasetviewer.cellcomponent;
002:
003:        /*
004:         * Copyright (C) 2001-2003 Colin Bell
005:         * colbell@users.sourceforge.net
006:         *
007:         * This library is free software; you can redistribute it and/or
008:         * modify it under the terms of the GNU Lesser General Public
009:         * License as published by the Free Software Foundation; either
010:         * version 2.1 of the License, or (at your option) any later version.
011:         *
012:         * This library is distributed in the hope that it will be useful,
013:         * but WITHOUT ANY WARRANTY; without even the implied warranty of
014:         * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
015:         * Lesser General Public License for more details.
016:         *
017:         * You should have received a copy of the GNU Lesser General Public
018:         * License along with this library; if not, write to the Free Software
019:         * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
020:         */
021:        import java.awt.event.*;
022:
023:        import java.io.FileInputStream;
024:        import java.io.FileOutputStream;
025:        import java.io.InputStreamReader;
026:        import java.io.OutputStreamWriter;
027:        import java.io.IOException;
028:
029:        import javax.swing.JTable;
030:        import javax.swing.JTextField;
031:        import javax.swing.JTextArea;
032:        import javax.swing.SwingUtilities;
033:        import javax.swing.text.JTextComponent;
034:        import java.sql.PreparedStatement;
035:        import java.sql.ResultSet;
036:
037:        import net.sourceforge.squirrel_sql.fw.datasetviewer.CellDataPopup;
038:        import net.sourceforge.squirrel_sql.fw.datasetviewer.ColumnDisplayDefinition;
039:        import net.sourceforge.squirrel_sql.fw.sql.ISQLDatabaseMetaData;
040:
041:        /**
042:         * @author gwg
043:         *
044:         * This class provides the display components for handling Short data types,
045:         * specifically SQL type, SMALLINT.
046:         * The display components are for:
047:         * <UL>
048:         * <LI> read-only display within a table cell
049:         * <LI> editing within a table cell
050:         * <LI> read-only or editing display within a separate window
051:         * </UL>
052:         * The class also contains 
053:         * <UL>
054:         * <LI> a function to compare two display values
055:         * to see if they are equal.  This is needed because the display format
056:         * may not be the same as the internal format, and all internal object
057:         * types may not provide an appropriate equals() function.
058:         * <LI> a function to return a printable text form of the cell contents,
059:         * which is used in the text version of the table.
060:         * </UL>
061:         * <P>
062:         * The components returned from this class extend RestorableJTextField
063:         * and RestorableJTextArea for use in editing table cells that
064:         * contain values of this data type.  It provides the special behavior for null
065:         * handling and resetting the cell to the original value.
066:         */
067:
068:        public class DataTypeShort extends BaseDataTypeComponent implements 
069:                IDataTypeComponent {
070:            /* whether nulls are allowed or not */
071:            private boolean _isNullable;
072:
073:            /* whether number is signed or unsigned */
074:            private boolean _isSigned;
075:
076:            /* the number of decimal digits allowed in the number */
077:            private int _scale;
078:
079:            /* table of which we are part (needed for creating popup dialog) */
080:            private JTable _table;
081:
082:            /* The JTextComponent that is being used for editing */
083:            private IRestorableTextComponent _textComponent;
084:
085:            /* The CellRenderer used for this data type */
086:            //??? For now, use the same renderer as everyone else.
087:            //??
088:            //?? IN FUTURE: change this to use a new instance of renederer
089:            //?? for this data type.
090:            private DefaultColumnRenderer _renderer = DefaultColumnRenderer
091:                    .getInstance();
092:
093:            /**
094:             * Constructor - save the data needed by this data type.
095:             */
096:            public DataTypeShort(JTable table, ColumnDisplayDefinition colDef) {
097:                _table = table;
098:                _colDef = colDef;
099:                _isNullable = colDef.isNullable();
100:                _isSigned = colDef.isSigned();
101:                _scale = colDef.getScale();
102:            }
103:
104:            /**
105:             * Return the name of the java class used to hold this data type.
106:             */
107:            public String getClassName() {
108:                return "java.lang.Short";
109:            }
110:
111:            /**
112:             * Determine if two objects of this data type contain the same value.
113:             * Neither of the objects is null
114:             */
115:            public boolean areEqual(Object obj1, Object obj2) {
116:                return (obj1).equals(obj2);
117:            }
118:
119:            /*
120:             * First we have the methods for in-cell and Text-table operations
121:             */
122:
123:            /**
124:             * Render a value into text for this DataType.
125:             */
126:            public String renderObject(Object value) {
127:                return (String) _renderer.renderObject(value);
128:            }
129:
130:            /**
131:             * This Data Type can be edited in a table cell.
132:             */
133:            public boolean isEditableInCell(Object originalValue) {
134:                return true;
135:            }
136:
137:            /**
138:             * See if a value in a column has been limited in some way and
139:             * needs to be re-read before being used for editing.
140:             * For read-only tables this may actually return true since we want
141:             * to be able to view the entire contents of the cell even if it was not
142:             * completely loaded during the initial table setup.
143:             */
144:            public boolean needToReRead(Object originalValue) {
145:                // this DataType does not limit the data read during the initial load of the table,
146:                // so there is no need to re-read the complete data later
147:                return false;
148:            }
149:
150:            /**
151:             * Return a JTextField usable in a CellEditor.
152:             */
153:            public JTextField getJTextField() {
154:                _textComponent = new RestorableJTextField();
155:
156:                // special handling of operations while editing this data type
157:                ((RestorableJTextField) _textComponent)
158:                        .addKeyListener(new KeyTextHandler());
159:
160:                //
161:                // handle mouse events for double-click creation of popup dialog.
162:                // This happens only in the JTextField, not the JTextArea, so we can
163:                // make this an inner class within this method rather than a separate
164:                // inner class as is done with the KeyTextHandler class.
165:                //
166:                ((RestorableJTextField) _textComponent)
167:                        .addMouseListener(new MouseAdapter() {
168:                            public void mousePressed(MouseEvent evt) {
169:                                if (evt.getClickCount() == 2) {
170:                                    MouseEvent tableEvt = SwingUtilities
171:                                            .convertMouseEvent(
172:                                                    (RestorableJTextField) DataTypeShort.this ._textComponent,
173:                                                    evt,
174:                                                    DataTypeShort.this ._table);
175:                                    CellDataPopup.showDialog(
176:                                            DataTypeShort.this ._table,
177:                                            DataTypeShort.this ._colDef,
178:                                            tableEvt, true);
179:                                }
180:                            }
181:                        }); // end of mouse listener
182:
183:                return (JTextField) _textComponent;
184:            }
185:
186:            /**
187:             * Implement the interface for validating and converting to internal object.
188:             * Null is a valid successful return, so errors are indicated only by
189:             * existance or not of a message in the messageBuffer.
190:             */
191:            public Object validateAndConvert(String value,
192:                    Object originalValue, StringBuffer messageBuffer) {
193:                // handle null, which is shown as the special string "<null>"
194:                if (value.equals("<null>") || value.equals(""))
195:                    return null;
196:
197:                // Do the conversion into the object in a safe manner
198:                try {
199:                    Object obj = new Short(value);
200:                    return obj;
201:                } catch (Exception e) {
202:                    messageBuffer.append(e.toString() + "\n");
203:                    //?? do we need the message also, or is it automatically part of the toString()?
204:                    //messageBuffer.append(e.getMessage());
205:                    return null;
206:                }
207:            }
208:
209:            /**
210:             * If true, this tells the PopupEditableIOPanel to use the
211:             * binary editing panel rather than a pure text panel.
212:             * The binary editing panel assumes the data is an array of bytes,
213:             * converts it into text form, allows the user to change how that
214:             * data is displayed (e.g. Hex, Decimal, etc.), and converts
215:             * the data back from text to bytes when the user editing is completed.
216:             * If this returns false, this DataType class must
217:             * convert the internal data into a text string that
218:             * can be displayed (and edited, if allowed) in a TextField
219:             * or TextArea, and must handle all
220:             * user key strokes related to editing of that data.
221:             */
222:            public boolean useBinaryEditingPanel() {
223:                return false;
224:            }
225:
226:            /*
227:             * Now the functions for the Popup-related operations.
228:             */
229:
230:            /**
231:             * Returns true if data type may be edited in the popup,
232:             * false if not.
233:             */
234:            public boolean isEditableInPopup(Object originalValue) {
235:                return true;
236:            }
237:
238:            /*
239:             * Return a JTextArea usable in the CellPopupDialog
240:             * and fill in the value.
241:             */
242:            public JTextArea getJTextArea(Object value) {
243:                _textComponent = new RestorableJTextArea();
244:
245:                // value is a simple string representation of the data,
246:                // the same one used in Text and in-cell operations.
247:                ((RestorableJTextArea) _textComponent)
248:                        .setText(renderObject(value));
249:
250:                // special handling of operations while editing this data type
251:                ((RestorableJTextArea) _textComponent)
252:                        .addKeyListener(new KeyTextHandler());
253:
254:                return (RestorableJTextArea) _textComponent;
255:            }
256:
257:            /**
258:             * Validating and converting in Popup is identical to cell-related operation.
259:             */
260:            public Object validateAndConvertInPopup(String value,
261:                    Object originalValue, StringBuffer messageBuffer) {
262:                return validateAndConvert(value, originalValue, messageBuffer);
263:            }
264:
265:            /*
266:             * The following is used in both cell and popup operations.
267:             */
268:
269:            /*
270:             * Internal class for handling key events during editing
271:             * of both JTextField and JTextArea.
272:             */
273:            private class KeyTextHandler extends BaseKeyTextHandler {
274:                public void keyTyped(KeyEvent e) {
275:                    char c = e.getKeyChar();
276:
277:                    // as a coding convenience, create a reference to the text component
278:                    // that is typecast to JTextComponent.  this is not essential, as we
279:                    // could typecast every reference, but this makes the code cleaner
280:                    JTextComponent _theComponent = (JTextComponent) DataTypeShort.this ._textComponent;
281:                    String text = _theComponent.getText();
282:
283:                    // look for illegal chars
284:                    if (!DataTypeShort.this ._isSigned && c == '-') {
285:                        // cannot use '-' when unsigned
286:                        _theComponent.getToolkit().beep();
287:                        e.consume();
288:                    }
289:
290:                    // tabs and newlines get put into the text before this check,
291:                    // so remove them
292:                    // This only applies to Popup editing since these chars are
293:                    // not passed to this level by the in-cell editor.
294:                    if (c == KeyEvent.VK_TAB || c == KeyEvent.VK_ENTER) {
295:                        // remove all instances of the offending char
296:                        int index = text.indexOf(c);
297:                        if (index != -1) {
298:                            if (index == text.length() - 1) {
299:                                text = text.substring(0, text.length() - 1); // truncate string
300:                            } else {
301:                                text = text.substring(0, index)
302:                                        + text.substring(index + 1);
303:                            }
304:                            ((IRestorableTextComponent) _theComponent)
305:                                    .updateText(text);
306:                            _theComponent.getToolkit().beep();
307:                        }
308:                        e.consume();
309:                    }
310:
311:                    if (!(Character.isDigit(c) || (c == '-')
312:                            || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE))) {
313:                        _theComponent.getToolkit().beep();
314:                        e.consume();
315:                    }
316:
317:                    // check for max size reached (only works when DB provides non-zero scale info
318:                    if (DataTypeShort.this ._scale > 0
319:                            && text.length() == DataTypeShort.this ._scale
320:                            && c != KeyEvent.VK_BACK_SPACE
321:                            && c != KeyEvent.VK_DELETE) {
322:                        // max size reached
323:                        e.consume();
324:                        _theComponent.getToolkit().beep();
325:                    }
326:
327:                    // handle cases of null
328:                    // The processing is different when nulls are allowed and when they are not.
329:                    //
330:
331:                    if (DataTypeShort.this ._isNullable) {
332:
333:                        // user enters something when field is null
334:                        if (text.equals("<null>")) {
335:                            if ((c == KeyEvent.VK_BACK_SPACE)
336:                                    || (c == KeyEvent.VK_DELETE)) {
337:                                // delete when null => original value
338:                                DataTypeShort.this ._textComponent.restoreText();
339:                                e.consume();
340:                            } else {
341:                                // non-delete when null => clear field and add text
342:                                DataTypeShort.this ._textComponent
343:                                        .updateText("");
344:                                // fall through to normal processing of this key stroke
345:                            }
346:                        } else {
347:                            // check for user deletes last thing in field
348:                            if ((c == KeyEvent.VK_BACK_SPACE)
349:                                    || (c == KeyEvent.VK_DELETE)) {
350:                                if (text.length() <= 1) {
351:                                    // about to delete last thing in field, so replace with null
352:                                    DataTypeShort.this ._textComponent
353:                                            .updateText("<null>");
354:                                    e.consume();
355:                                }
356:                            }
357:                        }
358:                    } else {
359:                        // field is not nullable
360:                        //
361:                        handleNotNullableField(text, c, e, _textComponent);
362:                    }
363:                }
364:            }
365:
366:            /*
367:             * DataBase-related functions
368:             */
369:
370:            /**
371:             * On input from the DB, read the data from the ResultSet into the appropriate
372:             * type of object to be stored in the table cell.
373:             */
374:            public Object readResultSet(ResultSet rs, int index,
375:                    boolean limitDataRead) throws java.sql.SQLException {
376:
377:                short data = rs.getShort(index);
378:                if (rs.wasNull()) {
379:                    return null;
380:                } else {
381:                    return Short.valueOf(data);
382:                }
383:            }
384:
385:            /**
386:             * When updating the database, generate a string form of this object value
387:             * that can be used in the WHERE clause to match the value in the database.
388:             * A return value of null means that this column cannot be used in the WHERE
389:             * clause, while a return of "null" (or "is null", etc) means that the column
390:             * can be used in the WHERE clause and the value is actually a null value.
391:             * This function must also include the column label so that its output
392:             * is of the form:
393:             * 	"columnName = value"
394:             * or
395:             * 	"columnName is null"
396:             * or whatever is appropriate for this column in the database.
397:             */
398:            public String getWhereClauseValue(Object value,
399:                    ISQLDatabaseMetaData md) {
400:                if (value == null || value.toString() == null
401:                        || value.toString().length() == 0)
402:                    return _colDef.getLabel() + " IS NULL";
403:                else
404:                    return _colDef.getLabel() + "=" + value.toString();
405:            }
406:
407:            /**
408:             * When updating the database, insert the appropriate datatype into the
409:             * prepared statment at the given variable position.
410:             */
411:            public void setPreparedStatementValue(PreparedStatement pstmt,
412:                    Object value, int position) throws java.sql.SQLException {
413:                if (value == null) {
414:                    pstmt.setNull(position, _colDef.getSqlType());
415:                } else {
416:                    pstmt.setInt(position, ((Short) value).intValue());
417:                }
418:            }
419:
420:            /**
421:             * Get a default value for the table used to input data for a new row
422:             * to be inserted into the DB.
423:             */
424:            public Object getDefaultValue(String dbDefaultValue) {
425:                if (dbDefaultValue != null) {
426:                    // try to use the DB default value
427:                    StringBuffer mbuf = new StringBuffer();
428:                    Object newObject = validateAndConvert(dbDefaultValue, null,
429:                            mbuf);
430:
431:                    // if there was a problem with converting, then just fall through
432:                    // and continue as if there was no default given in the DB.
433:                    // Otherwise, use the converted object
434:                    if (mbuf.length() == 0)
435:                        return newObject;
436:                }
437:
438:                // no default in DB.  If nullable, use null.
439:                if (_isNullable)
440:                    return null;
441:
442:                // field is not nullable, so create a reasonable default value
443:                return Short.valueOf((short) 0);
444:            }
445:
446:            /*
447:             * File IO related functions
448:             */
449:
450:            /**
451:             * Say whether or not object can be exported to and imported from
452:             * a file.  We put both export and import together in one test
453:             * on the assumption that all conversions can be done both ways.
454:             */
455:            public boolean canDoFileIO() {
456:                return true;
457:            }
458:
459:            /**
460:             * Read a file and construct a valid object from its contents.
461:             * Errors are returned by throwing an IOException containing the
462:             * cause of the problem as its message.
463:             * <P>
464:             * DataType is responsible for validating that the imported
465:             * data can be converted to an object, and then must return
466:             * a text string that can be used in the Popup window text area.
467:             * This object-to-text conversion is the same as is done by
468:             * the DataType object internally in the getJTextArea() method.
469:             * 
470:             * <P>
471:             * File is assumed to be and ASCII string of digits
472:             * representing a value of this data type.
473:             */
474:            public String importObject(FileInputStream inStream)
475:                    throws IOException {
476:
477:                InputStreamReader inReader = new InputStreamReader(inStream);
478:
479:                int fileSize = inStream.available();
480:
481:                char charBuf[] = new char[fileSize];
482:
483:                int count = inReader.read(charBuf, 0, fileSize);
484:
485:                if (count != fileSize)
486:                    throw new IOException("Could read only " + count
487:                            + " chars from a total file size of " + fileSize
488:                            + ". Import failed.");
489:
490:                // convert file text into a string
491:                // Special case: some systems tack a newline at the end of
492:                // the text read.  Assume that if last char is a newline that
493:                // we want everything else in the line.
494:                String fileText;
495:                if (charBuf[count - 1] == KeyEvent.VK_ENTER)
496:                    fileText = new String(charBuf, 0, count - 1);
497:                else
498:                    fileText = new String(charBuf);
499:
500:                // test that the string is valid by converting it into an
501:                // object of this data type
502:                StringBuffer messageBuffer = new StringBuffer();
503:                validateAndConvertInPopup(fileText, null, messageBuffer);
504:                if (messageBuffer.length() > 0) {
505:                    // convert number conversion issue into IO issue for consistancy
506:                    throw new IOException(
507:                            "Text does not represent data of type "
508:                                    + getClassName() + ".  Text was:\n"
509:                                    + fileText);
510:                }
511:
512:                // return the text from the file since it does
513:                // represent a valid data value
514:                return fileText;
515:            }
516:
517:            /**
518:             * Construct an appropriate external representation of the object
519:             * and write it to a file.
520:             * Errors are returned by throwing an IOException containing the
521:             * cause of the problem as its message.
522:             * <P>
523:             * DataType is responsible for validating that the given text
524:             * text from a Popup JTextArea can be converted to an object.
525:             * This text-to-object conversion is the same as validateAndConvertInPopup,
526:             * which may be used internally by the object to do the validation.
527:             * <P>
528:             * The DataType object must flush and close the output stream before returning.
529:             * Typically it will create another object (e.g. an OutputWriter), and
530:             * that is the object that must be flushed and closed.
531:             * 
532:             * <P>
533:             * File is assumed to be and ASCII string of digits
534:             * representing a value of this data type.
535:             */
536:            public void exportObject(FileOutputStream outStream, String text)
537:                    throws IOException {
538:
539:                OutputStreamWriter outWriter = new OutputStreamWriter(outStream);
540:
541:                // check that the text is a valid representation
542:                StringBuffer messageBuffer = new StringBuffer();
543:                validateAndConvertInPopup(text, null, messageBuffer);
544:                if (messageBuffer.length() > 0) {
545:                    // there was an error in the conversion
546:                    throw new IOException(new String(messageBuffer));
547:                }
548:
549:                // just send the text to the output file
550:                outWriter.write(text);
551:                outWriter.flush();
552:                outWriter.close();
553:            }
554:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.