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.mashup.db.ui.wizard;
042:
043: import java.awt.Dimension;
044: import java.awt.FlowLayout;
045: import java.awt.event.ActionEvent;
046: import java.awt.event.ActionListener;
047: import java.io.File;
048: import java.net.URL;
049: import java.sql.Connection;
050: import java.sql.ResultSet;
051: import java.sql.SQLException;
052: import java.sql.Statement;
053: import java.util.Map;
054: import java.util.MissingResourceException;
055: import java.util.NoSuchElementException;
056:
057: import javax.swing.BorderFactory;
058: import javax.swing.BoxLayout;
059: import javax.swing.ImageIcon;
060: import javax.swing.JButton;
061: import javax.swing.JLabel;
062: import javax.swing.JPanel;
063: import javax.swing.JTextField;
064:
065: import org.netbeans.modules.mashup.db.common.FlatfileDBConnectionFactory;
066: import org.netbeans.modules.mashup.db.common.PropertyKeys;
067: import org.netbeans.modules.mashup.db.model.FlatfileDBTable;
068: import org.netbeans.modules.mashup.db.model.impl.FlatfileDBTableImpl;
069: import org.netbeans.modules.mashup.db.ui.FlatfileResulSetPanel;
070: import org.netbeans.modules.sql.framework.ui.output.dataview.ResultSetTablePanel;
071: import org.openide.DialogDisplayer;
072: import org.openide.NotifyDescriptor;
073: import com.sun.sql.framework.utils.StringUtil;
074: import net.java.hulp.i18n.Logger;
075: import org.netbeans.modules.etl.logger.Localizer;
076: import org.netbeans.modules.etl.logger.LogUtil;
077:
078: /**
079: * @author Ahimanikya Satapathy
080: * @version $Revision$
081: */
082: public class PreviewDataPanel extends JPanel implements ActionListener {
083:
084: private static final String CMD_SHOWDATA = "ShowData"; // NOI18N
085: private static final String LOG_CATEGORY = PreviewDataPanel.class
086: .getName();
087: private static transient final Logger mLogger = LogUtil
088: .getLogger(PreviewDataPanel.class.getName());
089: private static transient final Localizer mLoc = Localizer.get();
090: private FlatfileDBTable currentTable;
091: private JButton previewBtn;
092: private JTextField recordCount;
093: private ResultSetTablePanel recordViewer;
094: private FlatfileColumnTableModel tableModel;
095: private JLabel parseErrorMessage;
096: private JLabel totalRowsLabel;
097:
098: public PreviewDataPanel(FlatfileDBTable table) {
099: currentTable = table;
100: String nbBundle1 = mLoc.t("PRSR001: Preview Table Content");
101: String previewLabel = Localizer.parse(nbBundle1);
102: setBorder(BorderFactory.createTitledBorder(previewLabel));
103: setLayout(new BoxLayout(this , BoxLayout.PAGE_AXIS));
104: add(createPreviewControls());
105: setPreferredSize(new Dimension(205, 120));
106: recordViewer = new ResultSetTablePanel();
107: add(recordViewer);
108: }
109:
110: /**
111: * Invoked when an action occurs.
112: *
113: * @param e ActionEvent to handle
114: */
115: public void actionPerformed(ActionEvent e) {
116: Object src = e.getSource();
117:
118: if (src == recordCount) {
119: previewBtn.requestFocusInWindow();
120: previewBtn.doClick();
121: } else if (src == previewBtn) {
122: tryResulSet();
123: }
124: }
125:
126: public boolean tryResulSet() {
127: int ct = 25;
128: boolean isValid = true;
129:
130: try {
131: ct = Integer.parseInt(recordCount.getText());
132: } catch (NumberFormatException nfe) {
133: recordCount.setText(String.valueOf(25));
134: }
135:
136: // Call helper to obtain result set and display.
137: if (tableModel != null && !tableModel.getRowEntries().isEmpty()) {
138: tableModel.updateColumns(currentTable);
139: }
140:
141: FlatfileDBTable table = (FlatfileDBTable) currentTable.clone();
142:
143: table.setProperty(PropertyKeys.WIZARDFIELDCOUNT, new Integer(
144: table.getColumnList().size()));
145: String fname = table.getProperty(PropertyKeys.FILENAME);
146: if (fname == null || fname.equals("")) {
147: if (table.getLocalFilePath() != null
148: && !table.getLocalFilePath().equals("")
149: && table.getFileName() != null
150: && !table.getFileName().equals("")) {
151: ((FlatfileDBTableImpl) table).setOrPutProperty(
152: PropertyKeys.FILENAME, (new File(table
153: .getLocalFilePath(), table
154: .getFileName())).getAbsolutePath());
155: }
156: }
157: String fileName = StringUtil.escapeControlChars(table
158: .getProperty("URL"));
159: ((FlatfileDBTableImpl) table).setOrPutProperty(
160: PropertyKeys.FILENAME, fileName);
161: if (table.getParserType().equalsIgnoreCase(PropertyKeys.WEB)
162: || table.getParserType().equalsIgnoreCase(
163: PropertyKeys.RSS)) {
164: Map properties = ((FlatfileDBTableImpl) table)
165: .getProperties();
166: properties.remove(PropertyKeys.FILENAME);
167: ((FlatfileDBTableImpl) table).setProperties(properties);
168: }
169:
170: Connection conn = null;
171: File previewDir = new File(
172: System.getProperty("java.io.tmpdir"), ".preview");
173: File metadataDir = new File(previewDir, ".metadata");
174:
175: File lockFile = new File(metadataDir, "lockfile.txt");
176: FlatfileDBConnectionFactory factory = FlatfileDBConnectionFactory
177: .getInstance();
178: Object oldLockFlag = factory.getIgnoreLockProperty();
179: try {
180: factory.setIgnoreLockProperty("true");
181:
182: if (lockFile.exists()) {
183: lockFile.delete();
184: }
185:
186: if (!metadataDir.exists()) {
187: metadataDir.mkdirs();
188: }
189:
190: String url = FlatfileDBConnectionFactory.DEFAULT_FLATFILE_JDBC_URL_PREFIX
191: + "preview:" + metadataDir;
192: mLogger.infoNoloc(mLoc.t("PRSR075: Preview URL: {0}", url));
193: conn = FlatfileDBConnectionFactory.getInstance()
194: .getConnection(url);
195: Statement stmt = conn.createStatement();
196:
197: stmt
198: .execute("DROP TABLE IF EXISTS "
199: + table.getTableName());
200: String create = table.getCreateStatementSQL();
201:
202: mLogger
203: .infoNoloc(mLoc.t(
204: "PRSR076: Generated create statement: {0}",
205: create));
206: stmt.execute(create);
207:
208: ResultSet rs = stmt.executeQuery(table
209: .getSelectStatementSQL(ct));
210: recordViewer.clearView();
211: recordViewer.setResultSet(rs);
212:
213: // get the count of all rows
214: String countSql = "Select count(*) From " + table.getName();
215: mLogger
216: .infoNoloc(mLoc
217: .t(
218: "PRSR077: Select count(*) statement used for total rows:{0}",
219: countSql));
220:
221: stmt = conn.createStatement();
222: ResultSet cntRs = stmt.executeQuery(countSql);
223:
224: // set the count
225: if (cntRs == null) {
226: totalRowsLabel.setText("");
227: } else {
228: if (cntRs.next()) {
229: int count = cntRs.getInt(1);
230: totalRowsLabel.setText(String.valueOf(count));
231: }
232: }
233:
234: stmt.execute("DROP TABLE " + table.getTableName());
235: } catch (NoSuchElementException nse) {
236: String errorMsg = "ERROR: Current sample file may be corrupt, or does not match specified datatypes.";
237: String nbBundle2 = mLoc
238: .t("PRSR001: Could not preview current sample file.One of the column datatypes may not match the sample data,or the sample file may be corrupt.Try changing a column datatype and preview again, or supply a different sample file.");
239: try {
240: errorMsg = Localizer.parse(nbBundle2);
241: } catch (MissingResourceException mre) {
242: mLogger
243: .infoNoloc(mLoc
244: .t(
245: "PRSR078: Could not locate resource string for ERROR_bad_preview:{0}",
246: mre));
247:
248: }
249: showError(
250: "Sample file may be corrupt, or does not match specified datatypes",
251: errorMsg, nse);
252: isValid = false;
253: } catch (SQLException se) {
254: String errorMsg = "ERROR: Current sample file may be corrupt, or does not match specified datatypes.";
255: String sqlExMsg = "Sample file may be corrupt, or does not match specified datatypes";
256: try {
257: sqlExMsg = stripExceptionHeaderFromMessage(se);
258: String nbBundle3 = mLoc
259: .t(
260: "PRSR001: Could not preview current sample file.One or more values for field length, scale, datatype, or nullability do not agree with the current sample file.Review your field specifications and click 'Preview' again.Error:{0}",
261: sqlExMsg);
262: errorMsg = Localizer.parse(nbBundle3);
263: } catch (MissingResourceException mre) {
264: mLogger
265: .errorNoloc(
266: mLoc
267: .t(
268: "PRSR079: Could not locate resource string for ERROR_bad_preview {0}",
269: LOG_CATEGORY), mre);
270: }
271: showError(sqlExMsg, errorMsg, se);
272: isValid = false;
273: } catch (Exception t) {
274: String errMsg = "Unknown error occurred while obtaining ResultSet. ";
275: showError("Unknown error: " + t.getMessage(), errMsg,
276: unwrapThrowable(t));
277: isValid = false;
278: } finally {
279: table.setProperty(PropertyKeys.FILENAME, table
280: .getFileName());
281: if (conn != null) {
282: try {
283: conn.createStatement().execute("shutdown");
284: conn.close();
285: } catch (SQLException ignore) {
286: // ignore
287: }
288: }
289:
290: if (lockFile != null && lockFile.exists()) {
291: lockFile.delete();
292: }
293:
294: if (metadataDir != null && metadataDir.exists()) {
295: metadataDir.deleteOnExit();
296: }
297:
298: if (previewDir != null && previewDir.exists()) {
299: previewDir.deleteOnExit();
300: }
301:
302: FlatfileDBConnectionFactory.getInstance()
303: .setIgnoreLockProperty(oldLockFlag);
304: }
305:
306: return isValid;
307: }
308:
309: private void showError(String shortErrMsg, String errorMsg,
310: Throwable t) {
311: if (parseErrorMessage != null) {
312: parseErrorMessage.setText(shortErrMsg);
313: parseErrorMessage.revalidate();
314: parseErrorMessage.repaint();
315: } else {
316: DialogDisplayer.getDefault().notify(
317: new NotifyDescriptor.Message(errorMsg,
318: NotifyDescriptor.WARNING_MESSAGE));
319: }
320: setEnabled(false);
321: mLogger.errorNoloc(mLoc
322: .t("PRSR080: errorMsg {0}", LOG_CATEGORY), t);
323: }
324:
325: /**
326: * Overrides parent implementation to allow for addition of this instance as a
327: * listener for various child components.
328: */
329: @Override
330: public void addNotify() {
331: super .addNotify();
332: if (previewBtn != null) {
333: previewBtn.removeActionListener(this );
334: previewBtn.addActionListener(this );
335: }
336: }
337:
338: public void clearData() {
339: if (recordViewer != null) {
340: recordViewer.clearView();
341: }
342: }
343:
344: /**
345: * Overrides parent implementation to allow for removal of this instance as a listener
346: * for various child components.
347: */
348: @Override
349: public void removeNotify() {
350: if (previewBtn != null) {
351: previewBtn.removeActionListener(this );
352: }
353: super .removeNotify();
354: }
355:
356: @Override
357: public void setEnabled(boolean enabled) {
358: if (previewBtn != null) {
359: previewBtn.setEnabled(enabled);
360: }
361:
362: if (recordCount != null) {
363: recordCount.setEnabled(enabled);
364: }
365: }
366:
367: public void setTable(FlatfileDBTable table) {
368: currentTable = table;
369: }
370:
371: public void setTableModel(FlatfileColumnTableModel model) {
372: tableModel = model;
373: }
374:
375: public boolean showData(JLabel parseErrMsg) {
376: if (currentTable != null
377: && !currentTable.getColumnList().isEmpty()) {
378: parseErrorMessage = parseErrMsg;
379: return tryResulSet();
380: }
381: return false;
382: }
383:
384: /*
385: * Creates preview button and row count text field to control display of parsed output
386: * colMetaTable.
387: */
388: private JPanel createPreviewControls() {
389: JPanel controlPanel = new JPanel(new FlowLayout(
390: FlowLayout.LEADING));
391:
392: // add refresh button
393: URL url = getClass()
394: .getResource(
395: "/org/netbeans/modules/sql/framework/ui/resources/images/refresh16.png");
396: previewBtn = new JButton(new ImageIcon(url));
397: String nbBundle30 = mLoc
398: .t("PRSR001: Show data for this table definition");
399: previewBtn.setToolTipText(Localizer.parse(nbBundle30));
400: previewBtn.getAccessibleContext().setAccessibleName(
401: Localizer.parse(nbBundle30));
402: previewBtn.setMnemonic(Localizer.parse(nbBundle30).charAt(0));
403: previewBtn.setActionCommand(CMD_SHOWDATA);
404: previewBtn.addActionListener(this );
405:
406: JPanel recordCountPanel = new JPanel();
407: recordCountPanel.setBorder(BorderFactory.createEmptyBorder(0,
408: 10, 0, 0));
409:
410: String nbBundle50 = mLoc.t("PRSR001: Limit rows:");
411: JLabel lbl = new JLabel(Localizer.parse(nbBundle50));
412: lbl.getAccessibleContext().setAccessibleName(
413: Localizer.parse(nbBundle50));
414: lbl.setDisplayedMnemonic('l');
415: recordCountPanel.add(lbl);
416: recordCount = new JTextField("25", 5);
417: recordCountPanel.add(recordCount);
418: lbl.setLabelFor(recordCount);
419: recordCount.addActionListener(this );
420:
421: // add total row count label
422: JPanel totalRowsPanel = new JPanel();
423: FlowLayout fl = new FlowLayout();
424: fl.setAlignment(FlowLayout.LEFT);
425: totalRowsPanel.setLayout(fl);
426:
427: String nbBundle40 = mLoc.t("PRSR001: Total rows:");
428: JLabel totalRowsNameLabel = new JLabel(Localizer
429: .parse(nbBundle40));
430: totalRowsNameLabel.getAccessibleContext().setAccessibleName(
431: Localizer.parse(nbBundle40));
432: totalRowsNameLabel.setDisplayedMnemonic(Localizer.parse(
433: nbBundle40).charAt(0));
434: totalRowsNameLabel.setBorder(BorderFactory.createEmptyBorder(0,
435: 10, 0, 0));
436: totalRowsPanel.add(totalRowsNameLabel);
437:
438: totalRowsLabel = new JLabel();
439: totalRowsPanel.add(totalRowsLabel);
440:
441: controlPanel.add(previewBtn);
442: controlPanel.add(recordCountPanel);
443: controlPanel.add(totalRowsPanel);
444:
445: return controlPanel;
446: }
447:
448: private String stripExceptionHeaderFromMessage(Exception e) {
449: String cookedMsg = null;
450: String rawSqlMsg = e.getMessage();
451: if (!StringUtil.isNullString(rawSqlMsg)) {
452: int beginIndex = rawSqlMsg.lastIndexOf(":");
453: int endIndex = rawSqlMsg.lastIndexOf(")") - 1;
454: if (rawSqlMsg.length() == beginIndex) {
455: beginIndex = -1;
456: }
457:
458: if (endIndex < beginIndex || endIndex == -1) {
459: endIndex = rawSqlMsg.length();
460: }
461: cookedMsg = rawSqlMsg.substring(beginIndex + 1, endIndex);
462: }
463: return cookedMsg;
464: }
465:
466: private Throwable unwrapThrowable(Throwable t) {
467: // Drill down to the root cause, if available.
468: while (t.getCause() != null) {
469: t = t.getCause();
470: // Prevent infinite loops.
471: if (t.getCause() == t) {
472: break;
473: }
474: }
475: return t;
476: }
477: }
|