001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common
008: * Development and Distribution License("CDDL") (collectively, the
009: * "License"). You may not use this file except in compliance with the
010: * License. You can obtain a copy of the License at
011: * http://www.netbeans.org/cddl-gplv2.html
012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013: * specific language governing permissions and limitations under the
014: * License. When distributing the software, include this License Header
015: * Notice in each file and include the License file at
016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
017: * particular file as subject to the "Classpath" exception as provided
018: * by Sun in the GPL Version 2 section of the License file that
019: * accompanied this code. If applicable, add the following below the
020: * License Header, with the fields enclosed by brackets [] replaced by
021: * your own identifying information:
022: * "Portions Copyrighted [year] [name of copyright owner]"
023: *
024: * Contributor(s):
025: *
026: * The Original Software is NetBeans. The Initial Developer of the Original
027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
028: * Microsystems, Inc. All Rights Reserved.
029: *
030: * If you wish your version of this file to be governed by only the CDDL
031: * or only the GPL Version 2, indicate your decision by adding
032: * "[Contributor] elects to include this software in this distribution
033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
034: * single choice of license, a recipient has the option to distribute
035: * your version of this file under either the CDDL, the GPL Version 2 or
036: * to extend the choice of license to its licensees as provided above.
037: * However, if you add GPL Version 2 code and therefore, elected the GPL
038: * Version 2 license, then the option applies only if the new code is
039: * made subject to such option by the copyright holder.
040: */
041: package org.netbeans.modules.sql.framework.ui.output.dataview;
042:
043: import com.sun.sql.framework.exception.DBSQLException;
044: import org.netbeans.modules.sql.framework.ui.view.*;
045: import java.awt.BorderLayout;
046: import java.awt.Color;
047: import java.awt.Dialog;
048: import java.awt.Dimension;
049: import java.awt.GridBagConstraints;
050: import java.awt.GridBagLayout;
051: import java.awt.event.ActionEvent;
052: import java.awt.event.ActionListener;
053: import java.awt.event.KeyAdapter;
054: import java.awt.event.KeyEvent;
055: import java.net.URL;
056: import java.sql.Connection;
057: import java.sql.ResultSet;
058: import java.sql.SQLException;
059: import java.util.ArrayList;
060: import java.util.List;
061:
062: import javax.swing.AbstractAction;
063: import javax.swing.Action;
064: import javax.swing.BorderFactory;
065: import javax.swing.ImageIcon;
066: import javax.swing.JButton;
067: import javax.swing.JLabel;
068: import javax.swing.JPanel;
069: import javax.swing.JTextField;
070: import javax.swing.JToolBar;
071:
072: import org.netbeans.modules.etl.ui.view.ETLCollaborationTopPanel;
073: import org.netbeans.modules.sql.framework.codegen.DB;
074: import org.netbeans.modules.sql.framework.codegen.DBFactory;
075: import org.netbeans.modules.sql.framework.codegen.StatementContext;
076: import org.netbeans.modules.sql.framework.model.SQLDBTable;
077: import org.netbeans.modules.sql.framework.model.SQLDefinition;
078: import org.netbeans.modules.sql.framework.model.SQLJoinOperator;
079: import org.netbeans.modules.sql.framework.model.SQLObject;
080: import org.openide.DialogDescriptor;
081: import org.openide.DialogDisplayer;
082: import org.openide.NotifyDescriptor;
083: import org.openide.NotifyDescriptor.Message;
084: import org.openide.util.Exceptions;
085:
086: import com.sun.sql.framework.jdbc.DBConstants;
087: import com.sun.sql.framework.exception.BaseException;
088: import net.java.hulp.i18n.Logger;
089: import java.sql.PreparedStatement;
090: import org.netbeans.modules.etl.logger.Localizer;
091: import org.netbeans.modules.etl.logger.LogUtil;
092: import org.netbeans.modules.etl.ui.DataObjectProvider;
093: import org.netbeans.modules.sql.framework.common.jdbc.SQLUtils;
094: import org.netbeans.modules.sql.framework.model.RuntimeDatabaseModel;
095: import org.netbeans.modules.sql.framework.ui.graph.ICommand;
096: import org.netbeans.modules.sql.framework.ui.graph.IGraphView;
097: import org.netbeans.modules.sql.framework.ui.output.ETLOutputPanel;
098: import org.netbeans.modules.sql.framework.ui.view.graph.SQLBasicTableArea;
099:
100: /**
101: * TopComponent hosting display of design-level SQL test output.
102: *
103: * @author Ritesh Adval
104: * @author Ahimanikya Satapathy
105: * @version $Revision$
106: */
107: public abstract class DataOutputPanel extends JPanel implements
108: ETLOutputPanel {
109:
110: private static transient final Logger mLogger = LogUtil
111: .getLogger(DataOutputPanel.class.getName());
112: private static transient final Localizer mLoc = Localizer.get();
113: public static final String NL = System.getProperty(
114: "line.separator", "\n");
115: public static final String LOG_CATEGORY = DataOutputPanel.class
116: .getName();
117: public JButton commit;
118: protected JButton refreshButton;
119: protected JButton truncateButton;
120: protected SQLObject table;
121: protected DBTableMetadata meta;
122: protected JButton next;
123: protected JButton last;
124: protected JButton previous;
125: protected JButton first;
126: protected JButton deleteRow;
127: protected JButton insert;
128: protected JTextField refreshField;
129: protected ResultSetTablePanel queryView;
130: protected int recordToRefresh = 10;
131: protected int maxRows = 10;
132: protected JLabel totalRowsLabel;
133: protected int totalCount;
134: protected int nowCount = 1;
135: private SQLDefinition sqlDefinition;
136: private ETLCollaborationTopPanel etlView;
137: private JToolBar toolbar;
138: private JLabel limitRow;
139: private JButton filterButton;
140: private JButton[] btn = new JButton[5];
141:
142: /**
143: * Creates a new instance of DataOutputPanel with the associated instance of
144: * SQLDefinition.
145: *
146: * @param etlDefinition SQLDefinition instance to associate
147: */
148: protected DataOutputPanel(SQLObject etlObject,
149: SQLDefinition sqlDefinition, boolean showTruncate,
150: boolean showFilter) {
151: this .table = etlObject;
152: this .sqlDefinition = sqlDefinition;
153:
154: if (etlObject instanceof SQLDBTable) {
155: this .meta = new DBTableMetadata(((SQLDBTable) this .table));
156: }
157:
158: //do not show tab view if there is only one tab
159: putClientProperty("TabPolicy", "HideWhenAlone"); //NOI18N
160: putClientProperty("PersistenceType", "Never"); //NOI18N
161: this .setLayout(new BorderLayout());
162:
163: String nbBundle = mLoc.t("PRSR001: Output: {0}", sqlDefinition
164: .getDisplayName());
165: this .setName(Localizer.parse(nbBundle));
166: setBorder(BorderFactory.createEmptyBorder());
167:
168: JPanel panel = new JPanel();
169: panel.setBorder(BorderFactory.createEtchedBorder());
170: GridBagLayout gl = new GridBagLayout();
171: GridBagConstraints c = new GridBagConstraints();
172: panel.setLayout(gl);
173:
174: //toolbar panel
175: toolbar = new JToolBar();
176: toolbar.setFloatable(false);
177:
178: c.weightx = 1.0;
179: c.weighty = 1.0;
180: c.fill = GridBagConstraints.NONE;
181: c.gridwidth = GridBagConstraints.RELATIVE;
182: c.anchor = GridBagConstraints.FIRST_LINE_START;
183:
184: panel.add(toolbar, c);
185: validate();
186:
187: URL url = null;
188: String nbBundle14 = mLoc.t("PRSR001: Truncate this table");
189: if (showTruncate) {
190: //create truncate button
191: TruncateTableAction truncAction = new TruncateTableAction(
192: this );
193: truncAction.putValue(Action.SHORT_DESCRIPTION, Localizer
194: .parse(nbBundle14));
195: url = getClass()
196: .getResource(
197: "/org/netbeans/modules/sql/framework/ui/resources/images/stop.gif");
198: truncAction.putValue(Action.SMALL_ICON, new ImageIcon(url));
199: //add truncate button
200: truncateButton = new JButton(truncAction);
201: btn[0] = truncateButton;
202: }
203:
204: if (showFilter) {
205: //add Filter button
206: showDataFilter_ActionPerformed filterAction = new showDataFilter_ActionPerformed();
207: String nbBundle1 = mLoc
208: .t("PRSR001: Enable/Disable of Table Content filtering");
209: filterAction.putValue(Action.SHORT_DESCRIPTION, Localizer
210: .parse(nbBundle1));
211: url = getClass()
212: .getResource(
213: "/org/netbeans/modules/sql/framework/ui/resources/images/funnel.png");
214: filterAction
215: .putValue(Action.SMALL_ICON, new ImageIcon(url));
216: filterButton = new JButton(filterAction);
217: btn[0] = filterButton;
218: }
219:
220: ActionListener outputListener = new ActionListener() {
221:
222: public void actionPerformed(ActionEvent e) {
223: Object src = e.getSource();
224: if (src.equals(refreshButton)) {
225: refreshActionPerformed();
226: } else if (src.equals(first)) {
227: firstActionPerformed();
228: } else if (src.equals(last)) {
229: lastActionPerformed();
230: } else if (src.equals(next)) {
231: nextActionPerformed();
232: } else if (src.equals(previous)) {
233: previousActionPerformed();
234: } else if (src.equals(refreshField)) {
235: setMaxActionPerformed();
236: } else if (src.equals(commit)) {
237: commitActionPerformed();
238: } else if (src.equals(deleteRow)) {
239: deleteRecordActionPerformed();
240: } else if (src.equals(insert)) {
241: insertActionPerformed();
242: }
243: }
244: };
245:
246: //add refresh button
247: url = getClass()
248: .getResource(
249: "/org/netbeans/modules/sql/framework/ui/resources/images/refresh.png");
250: refreshButton = new JButton(new ImageIcon(url));
251: String nbBundle2 = mLoc.t("PRSR001: Refresh records");
252: refreshButton.setToolTipText(Localizer.parse(nbBundle2));
253: refreshButton.addActionListener(outputListener);
254: btn[1] = refreshButton;
255:
256: // add navigation buttons
257: url = getClass()
258: .getResource(
259: "/org/netbeans/modules/sql/framework/ui/resources/images/navigate_beginning.png");
260: first = new JButton(new ImageIcon(url));
261: String nbBundle3 = mLoc.t("PRSR001: Go to the first page");
262: first.setToolTipText(Localizer.parse(nbBundle3));
263: first.addActionListener(outputListener);
264: first.setEnabled(false);
265: toolbar.add(first);
266: toolbar.addSeparator(new Dimension(10, 10));
267:
268: url = getClass()
269: .getResource(
270: "/org/netbeans/modules/sql/framework/ui/resources/images/navigate_left.png");
271: previous = new JButton(new ImageIcon(url));
272: String nbBundle4 = mLoc.t("PRSR001: Go to the previous page");
273: previous.setToolTipText(Localizer.parse(nbBundle4));
274: previous.addActionListener(outputListener);
275: previous.setEnabled(false);
276: toolbar.add(previous);
277: toolbar.addSeparator(new Dimension(10, 10));
278:
279: url = getClass()
280: .getResource(
281: "/org/netbeans/modules/sql/framework/ui/resources/images/navigate_right.png");
282: next = new JButton(new ImageIcon(url));
283: String nbBundle5 = mLoc.t("PRSR001: Go to the next page");
284: next.setToolTipText(Localizer.parse(nbBundle5));
285: next.addActionListener(outputListener);
286: next.setEnabled(false);
287: toolbar.add(next);
288: toolbar.addSeparator(new Dimension(10, 10));
289:
290: url = getClass()
291: .getResource(
292: "/org/netbeans/modules/sql/framework/ui/resources/images/navigate_end.png");
293: last = new JButton(new ImageIcon(url));
294: String nbBundle6 = mLoc.t("PRSR001: Go to the last page");
295: last.setToolTipText(Localizer.parse(nbBundle6));
296: last.addActionListener(outputListener);
297: last.setEnabled(false);
298: toolbar.add(last);
299: toolbar.addSeparator(new Dimension(10, 10));
300: //add limit row label
301: String nbBundle7 = mLoc.t("PRSR001: Page size:");
302: limitRow = new JLabel(Localizer.parse(nbBundle7));
303: limitRow.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 8));
304: toolbar.add(limitRow);
305:
306: //add refresh text field
307: refreshField = new JTextField();
308: refreshField.setText("" + recordToRefresh);
309: refreshField.setPreferredSize(new Dimension(30, refreshField
310: .getHeight()));
311: refreshField.setSize(30, refreshField.getHeight());
312: refreshField.addKeyListener(new KeyAdapter() {
313:
314: @Override
315: public void keyTyped(KeyEvent evt) {
316: if (refreshField.getText().length() >= 3) {
317: evt.consume();
318: }
319: }
320: });
321: refreshField.addActionListener(outputListener);
322: toolbar.add(refreshField);
323:
324: String nbBundle8 = mLoc.t("PRSR001: Total Rows:");
325: JLabel totalRowsNameLabel = new JLabel(Localizer
326: .parse(nbBundle8));
327: totalRowsNameLabel.getAccessibleContext().setAccessibleName(
328: Localizer.parse(nbBundle8));
329: totalRowsNameLabel.setBorder(BorderFactory.createEmptyBorder(0,
330: 5, 0, 8));
331: toolbar.add(totalRowsNameLabel);
332: totalRowsLabel = new JLabel();
333: toolbar.add(totalRowsLabel);
334: toolbar.addSeparator(new Dimension(10, 10));
335:
336: url = getClass()
337: .getResource(
338: "/org/netbeans/modules/sql/framework/ui/resources/images/row_add.png");
339: insert = new JButton(new ImageIcon(url));
340: String nbBundle9 = mLoc.t("PRSR001: Insert a record.");
341: insert.setToolTipText(Localizer.parse(nbBundle9));
342: insert.addActionListener(outputListener);
343: insert.setEnabled(false);
344: btn[2] = insert;
345:
346: url = getClass()
347: .getResource(
348: "/org/netbeans/modules/sql/framework/ui/resources/images/row_delete.png");
349: deleteRow = new JButton(new ImageIcon(url));
350: String nbBundle10 = mLoc.t("PRSR001: Delete Selected Records.");
351: deleteRow.setToolTipText(Localizer.parse(nbBundle10));
352: deleteRow.addActionListener(outputListener);
353: deleteRow.setEnabled(false);
354: btn[3] = deleteRow;
355:
356: url = getClass()
357: .getResource(
358: "/org/netbeans/modules/sql/framework/ui/resources/images/row_preferences.png");
359: commit = new JButton(new ImageIcon(url));
360: String nbBundle11 = mLoc
361: .t("PRSR001: Commit the Changes done on this page.");
362: commit.setToolTipText(Localizer.parse(nbBundle11));
363: commit.addActionListener(outputListener);
364: commit.setEnabled(false);
365: btn[4] = commit;
366:
367: //add panel
368: this .add(panel, BorderLayout.NORTH);
369:
370: //add query view
371: queryView = new ResultSetTablePanel(this );
372: this .add(queryView, BorderLayout.CENTER);
373: }
374:
375: public abstract void generateResult();
376:
377: public abstract void generateResult(SQLObject aTable);
378:
379: public JButton[] getVerticalToolBar() {
380: return btn;
381: }
382:
383: private void executeUpdate(String key)
384: throws NumberFormatException, SQLException, BaseException,
385: DBSQLException {
386: Connection conn = null;
387: PreparedStatement pstmt = null;
388: String errorMsg = "";
389:
390: int row = Integer.parseInt(key.substring(0, key.indexOf(";")));
391: int col = Integer.parseInt(key.substring(key.indexOf(";") + 1,
392: key.length()));
393: String updateStmt = queryView.getUpdateStmt(key);
394: List values = queryView.getValueList(key);
395: List<Integer> types = queryView.getTypeList(key);
396:
397: int rowCount = 0;
398: try {
399: conn = meta.createConnection();
400: conn.setAutoCommit(false);
401: pstmt = conn.prepareStatement(updateStmt);
402: int pos = 1;
403: for (Object val : values) {
404: SQLUtils.setAttributeValue(pstmt, pos, types
405: .get(pos - 1), val);
406: pos++;
407: }
408: rowCount = pstmt.executeUpdate();
409: } catch (SQLException ex) {
410: errorMsg = errorMsg + "Update failed at Row:" + row
411: + "Column:" + col + ";";
412: DialogDisplayer.getDefault().notify(
413: new Message(errorMsg,
414: NotifyDescriptor.ERROR_MESSAGE));
415: } finally {
416: if (rowCount == 0) {
417: errorMsg = "No rows updates using " + updateStmt + ";";
418: DialogDisplayer.getDefault().notify(
419: new Message(errorMsg,
420: NotifyDescriptor.INFORMATION_MESSAGE));
421: } else if (rowCount > 1) {
422: errorMsg = "A Distinct row cannot be updated using "
423: + updateStmt + ";";
424: DialogDisplayer.getDefault().notify(
425: new Message(errorMsg,
426: NotifyDescriptor.ERROR_MESSAGE));
427: conn.rollback();
428: } else {
429: conn.commit();
430: }
431: queryView.closeResources(pstmt, conn);
432: }
433: }
434:
435: protected class showDataFilter_ActionPerformed extends
436: AbstractAction {
437:
438: public void actionPerformed(ActionEvent e) {
439: Object src = e.getSource();
440: if (src.equals(filterButton)) {
441: try {
442: etlView = DataObjectProvider.getProvider()
443: .getActiveDataObject()
444: .getETLEditorTopPanel();
445: SQLBasicTableArea stArea = (SQLBasicTableArea) etlView
446: .getGraphView().findGraphNode(table);
447: SQLObject sqlObject = (SQLObject) stArea
448: .getDataObject();
449: Object[] args = new Object[] { stArea, sqlObject };
450: IGraphView gv = stArea.getGraphView();
451: gv.execute(ICommand.DATA_EXTRACTION, args);
452: } catch (Exception ex) {
453: Exceptions.printStackTrace(ex);
454: }
455: }
456: }
457: }
458:
459: protected void refreshActionPerformed() {
460: if (table instanceof SQLDBTable) {
461: try {
462: meta.refresh((SQLDBTable) table);
463: } catch (DBSQLException ex) {
464: Exceptions.printStackTrace(ex);
465: }
466: }
467:
468: int intVal = totalCount;
469: if (intVal <= 0) {
470: String nbBundle12 = mLoc
471: .t(
472: "PRSR001: Enter a valid number to refresh records.{0}",
473: table.getDisplayName());
474: String errorMsg = Localizer.parse(nbBundle12);
475: DialogDisplayer.getDefault().notify(
476: new Message(errorMsg,
477: NotifyDescriptor.INFORMATION_MESSAGE));
478: return;
479: }
480: recordToRefresh = intVal;
481:
482: // Delegate to concrete class implementation.
483: generateResult(this .table);
484: }
485:
486: protected void setMaxActionPerformed() {
487: try {
488: maxRows = Integer.parseInt(refreshField.getText().trim());
489: } catch (NumberFormatException ex) {
490: if (totalCount < 999) {
491: maxRows = totalCount;
492: } else {
493: maxRows = 999;
494: }
495: }
496: nowCount = 1;
497: if (maxRows > totalCount) {
498: maxRows = totalCount;
499: }
500: recordToRefresh = nowCount + maxRows - 1;
501: if (recordToRefresh > totalCount) {
502: recordToRefresh = totalCount;
503: }
504: // Delegate to concrete class implementation.
505: generateResult(this .table);
506: }
507:
508: protected void firstActionPerformed() {
509: boolean doCalculation = true;
510: if (commit.isEnabled()) {
511: String msg = "You have uncommited Changes in this page. If you continue, you changes will be lost. Do you still want to continue?";
512: NotifyDescriptor d = new NotifyDescriptor.Confirmation(msg,
513: "Confirm navigation",
514: NotifyDescriptor.YES_NO_OPTION);
515: if (DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.NO_OPTION) {
516: doCalculation = false;
517: }
518: }
519: if (doCalculation) {
520: nowCount = 1;
521: recordToRefresh = nowCount + maxRows - 1;
522: if (recordToRefresh > totalCount) {
523: recordToRefresh = totalCount;
524: }
525: commit.setEnabled(false);
526: this .queryView.setDirtyStatus(false);
527: // Delegate to concrete class implementation.
528: generateResult(this .table);
529: }
530: }
531:
532: protected void previousActionPerformed() {
533: boolean doCalculation = true;
534: if (commit.isEnabled()) {
535: String msg = "You have uncommited Changes in this page. If you continue, you changes will be lost. Do you still want to continue?";
536: NotifyDescriptor d = new NotifyDescriptor.Confirmation(msg,
537: "Confirm navigation",
538: NotifyDescriptor.YES_NO_OPTION);
539: if (DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.NO_OPTION) {
540: doCalculation = false;
541: }
542: }
543: if (doCalculation) {
544: nowCount -= maxRows;
545: recordToRefresh = nowCount + maxRows - 1;
546: commit.setEnabled(false);
547: this .queryView.setDirtyStatus(false);
548: // Delegate to concrete class implementation.
549: generateResult(this .table);
550: }
551: }
552:
553: protected void nextActionPerformed() {
554: boolean doCalculation = true;
555: if (commit.isEnabled()) {
556: String msg = "You have uncommited Changes in this page. If you continue, your changes will be lost. Do you still want to continue?";
557: NotifyDescriptor d = new NotifyDescriptor.Confirmation(msg,
558: "Confirm navigation",
559: NotifyDescriptor.YES_NO_OPTION);
560: if (DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.NO_OPTION) {
561: doCalculation = false;
562: }
563: }
564: if (doCalculation) {
565: nowCount += maxRows;
566: recordToRefresh = nowCount + maxRows - 1;
567: // Delegate to concrete class implementation.
568: commit.setEnabled(false);
569: this .queryView.setDirtyStatus(false);
570: generateResult(this .table);
571: }
572: }
573:
574: protected void lastActionPerformed() {
575: boolean doCalculation = true;
576: if (commit.isEnabled()) {
577: String msg = "You have uncommited Changes in this page. If you continue, your changes will be lost. Do you still want to continue?";
578: NotifyDescriptor d = new NotifyDescriptor.Confirmation(msg,
579: "Confirm navigation",
580: NotifyDescriptor.YES_NO_OPTION);
581: if (DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.NO_OPTION) {
582: doCalculation = false;
583: }
584: }
585: if (doCalculation) {
586: try {
587: nowCount = totalCount - maxRows + 1;
588: } finally {
589: }
590: recordToRefresh = totalCount;
591: commit.setEnabled(false);
592: this .queryView.setDirtyStatus(false);
593: // Delegate to concrete class implementation.
594: generateResult(this .table);
595: }
596: }
597:
598: protected void commitActionPerformed() {
599: if (this .queryView.isDirty()) {
600: try {
601: for (String key : queryView.getUpdateKeys()) {
602: executeUpdate(key);
603: }
604: } catch (Exception ex) {
605: String errorMsg = "Check the data field type, precision and other constraints."
606: + ex.getMessage();
607: DialogDisplayer.getDefault().notify(
608: new Message(errorMsg,
609: NotifyDescriptor.ERROR_MESSAGE));
610: } finally {
611: commit.setEnabled(false);
612: this .queryView.setDirtyStatus(false);
613: }
614: }
615: }
616:
617: protected void insertActionPerformed() {
618: String[] data = null;
619: StringBuilder insertSql = new StringBuilder();
620:
621: insertSql.append("Insert into " + meta.getQualifiedTableName()
622: + "Values(");
623: data = getDialogData();
624: if (data != null) {
625: for (int i = 0; i < data.length; i++) {
626: if (i != 0) {
627: insertSql.append(",");
628: }
629: insertSql.append("?");
630: }
631: insertSql.append(")");
632: }
633:
634: PreparedStatement pstmt = null;
635: Connection conn = null;
636: boolean error = false;
637: String errorMsg = null;
638:
639: try {
640: conn = meta.createConnection();
641: conn.setAutoCommit(false);
642: pstmt = conn.prepareStatement(insertSql.toString());
643: int pos = 1;
644: for (Object val : data) {
645: SQLUtils.setAttributeValue(pstmt, pos, meta
646: .getColumnType(pos - 1), val);
647: pos++;
648: }
649: int rows = pstmt.executeUpdate();
650: if (rows != 1) {
651: error = true;
652: errorMsg = errorMsg
653: + "Failed to insert record. Check for datatype mismatch and other key constraints.";
654: }
655:
656: //return rows;
657: } catch (Exception ex) {
658: error = true;
659: errorMsg = errorMsg + ex.getMessage();
660: } finally {
661: if (!error) {
662: try {
663: String msg = "Commit the INSERT Operation to the database?";
664: NotifyDescriptor d = new NotifyDescriptor.Confirmation(
665: msg, "Confirm delete",
666: NotifyDescriptor.YES_NO_OPTION);
667: if (DialogDisplayer.getDefault().notify(d) == NotifyDescriptor.YES_OPTION) {
668: conn.commit();
669: } else {
670: msg = "Discarded the Insert operation.";
671: DialogDisplayer
672: .getDefault()
673: .notify(
674: new Message(
675: msg,
676: NotifyDescriptor.INFORMATION_MESSAGE));
677: conn.rollback();
678: }
679: } catch (SQLException ex) {
680: errorMsg = "Failure while commiting changes to database.";
681: DialogDisplayer
682: .getDefault()
683: .notify(
684: new Message(
685: errorMsg,
686: NotifyDescriptor.INFORMATION_MESSAGE));
687: }
688:
689: if (!error) {
690: errorMsg = "Record successfully inserted.";
691: DialogDisplayer
692: .getDefault()
693: .notify(
694: new Message(
695: errorMsg,
696: NotifyDescriptor.INFORMATION_MESSAGE));
697: }
698:
699: } else {
700: errorMsg = "Insert command failed for " + errorMsg;
701: DialogDisplayer.getDefault().notify(
702: new Message(errorMsg,
703: NotifyDescriptor.INFORMATION_MESSAGE));
704: }
705: queryView.closeResources(pstmt, conn);
706: refreshActionPerformed();
707: }
708:
709: }
710:
711: protected void deleteRecordActionPerformed() {
712: if (queryView.table.getSelectedRowCount() == 0) {
713: String msg = "Please select a row to delete.";
714: DialogDisplayer.getDefault().notify(
715: new Message(msg,
716: NotifyDescriptor.INFORMATION_MESSAGE));
717: } else {
718: try {
719: int i = queryView.table.getSelectedRow();
720: queryView.executeDeleteRow(meta, i);
721: refreshActionPerformed();
722: } catch (Exception ex) {
723: String msg = "Error Deleting Row(s): "
724: + ex.getMessage();
725: DialogDisplayer
726: .getDefault()
727: .notify(
728: new Message(msg,
729: NotifyDescriptor.ERROR_MESSAGE));
730: }
731: }
732: }
733:
734: protected String getJoinSql(SQLJoinOperator op,
735: boolean useSourceTableAlias) {
736: String sql = "";
737: try {
738: DB db = DBFactory.getInstance().getDatabase(
739: DBConstants.ANSI92);
740: StatementContext context = new StatementContext();
741: context.setUseSourceTableAliasName(useSourceTableAlias);
742: if (!useSourceTableAlias) {
743: context.setUsingFullyQualifiedTablePrefix(false);
744: context.putClientProperty(
745: StatementContext.USE_FULLY_QUALIFIED_TABLE,
746: Boolean.FALSE);
747: }
748: sql = sql + db.getGeneratorFactory().generate(op, context);
749: } catch (BaseException ex) {
750: //ignore
751: }
752: return sql;
753: }
754:
755: private String[] getDialogData() {
756: List<JTextField> lst = new ArrayList<JTextField>();
757: String[] data = null;
758: JPanel panel = null;
759: data = new String[meta.getColumnCount()];
760:
761: //Add fields
762: panel = new JPanel();
763: panel.setBorder(BorderFactory.createEtchedBorder());
764: GridBagLayout gl = new GridBagLayout();
765: GridBagConstraints c = new GridBagConstraints();
766: panel.setLayout(gl);
767:
768: String nbBundle52 = mLoc.t("PRSR001: Field Name");
769: JLabel label = new JLabel(Localizer.parse(nbBundle52));
770: label.getAccessibleContext().setAccessibleName(
771: Localizer.parse(nbBundle52));
772: label.setForeground(Color.RED);
773: c.weightx = 0.35;
774: c.gridwidth = GridBagConstraints.RELATIVE;
775: c.fill = GridBagConstraints.HORIZONTAL;
776: panel.add(label, c);
777:
778: String nbBundle53 = mLoc.t("PRSR001: Field Value");
779: label = new JLabel(Localizer.parse(nbBundle53));
780: label.getAccessibleContext().setAccessibleName(
781: Localizer.parse(nbBundle53));
782: label.setForeground(Color.RED);
783: c.weightx = 0.65;
784: c.gridwidth = GridBagConstraints.REMAINDER;
785: c.fill = GridBagConstraints.HORIZONTAL;
786: panel.add(label, c);
787:
788: for (int i = 0; i < meta.getColumnCount(); i++) {
789: label = new JLabel(meta.getColumnName(i));
790: JTextField txt = new JTextField(meta.getColumn(i)
791: .getScale());
792: txt.setToolTipText("Field Type: "
793: + meta.getColumn(i).getJdbcTypeString());
794: txt.setName(meta.getColumnName(i));
795: label.setLabelFor(txt);
796: c.weightx = 0.35;
797: c.gridwidth = GridBagConstraints.RELATIVE;
798: c.fill = GridBagConstraints.HORIZONTAL;
799: panel.add(label, c);
800: c.weightx = 0.65;
801: c.fill = GridBagConstraints.HORIZONTAL;
802: c.gridwidth = GridBagConstraints.REMAINDER;
803: panel.add(txt, c);
804: lst.add(txt);
805: }
806:
807: DialogDescriptor desc = new DialogDescriptor(panel,
808: "Enter the Values");
809: Dialog dialog = DialogDisplayer.getDefault().createDialog(desc);
810: dialog
811: .getAccessibleContext()
812: .setAccessibleDescription(
813: "This is the dialog which helps user input records into database");
814: dialog.setModal(true);
815: dialog.pack();
816: dialog.setVisible(true);
817:
818: if (desc.getValue() == NotifyDescriptor.OK_OPTION) {
819: for (int i = 0; i < lst.size(); i++) {
820: JTextField textField = lst.get(i);
821: for (int j = 0; j < meta.getColumnCount(); j++) {
822: if (meta.getColumnName(j).equals(
823: textField.getName())) {
824: data[j] = textField.getText();
825: break;
826: }
827: }
828: }
829: } else {
830: data = null;
831: }
832: return data;
833: }
834:
835: protected void setTotalCount(ResultSet rs) {
836: try {
837: if (rs == null) {
838: String nbBundle13 = mLoc.t("PRSR001: N/A");
839: totalRowsLabel.setText(Localizer.parse(nbBundle13));
840: } else {
841: if (rs.next()) {
842: int count = rs.getInt(1);
843: totalRowsLabel.setText(String.valueOf(count));
844: totalCount = count;
845: }
846: }
847: } catch (SQLException ex) {
848: mLogger.errorNoloc(mLoc.t(
849: "PRSR145: Could not get total row count{0}",
850: DataOutputPanel.class.getName()), ex);
851: }
852: }
853:
854: protected RuntimeDatabaseModel getRuntimeDbModel() {
855: return sqlDefinition.getRuntimeDbModel();
856: }
857: }
|