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;
042:
043: import java.awt.BorderLayout;
044: import java.awt.Color;
045: import java.awt.FlowLayout;
046: import java.awt.Font;
047: import java.awt.event.ActionEvent;
048: import java.awt.event.ActionListener;
049: import java.net.URL;
050: import java.util.ArrayList;
051: import java.util.Iterator;
052: import java.util.List;
053:
054: import javax.swing.BorderFactory;
055: import javax.swing.ImageIcon;
056: import javax.swing.JButton;
057: import javax.swing.JLabel;
058: import javax.swing.JPanel;
059: import javax.swing.JScrollPane;
060: import javax.swing.JTextField;
061: import javax.swing.JToolBar;
062: import javax.swing.text.BadLocationException;
063:
064: import org.netbeans.modules.sql.framework.common.jdbc.SQLDBConnectionDefinition;
065: import org.netbeans.modules.sql.framework.common.jdbc.SQLUtils;
066: import org.netbeans.modules.sql.framework.codegen.DB;
067: import org.netbeans.modules.sql.framework.codegen.DBFactory;
068: import org.netbeans.modules.sql.framework.codegen.StatementContext;
069: import org.netbeans.modules.sql.framework.model.SQLConstants;
070: import org.netbeans.modules.sql.framework.model.SQLDefinition;
071: import org.netbeans.modules.sql.framework.model.SQLObject;
072: import org.netbeans.modules.sql.framework.model.SourceTable;
073: import org.netbeans.modules.sql.framework.model.ValidationInfo;
074: import org.netbeans.modules.sql.framework.model.utils.SQLObjectUtil;
075: import org.netbeans.modules.sql.framework.model.visitors.SQLValidationVisitor;
076: import org.netbeans.modules.sql.framework.model.visitors.SQLVisitedObject;
077: import org.netbeans.modules.sql.framework.ui.SwingWorker;
078: import org.netbeans.modules.sql.framework.ui.graph.ICommand;
079: import org.netbeans.modules.sql.framework.ui.utils.UIUtil;
080: import org.netbeans.modules.sql.framework.ui.view.conditionbuilder.ConditionBuilderUtil;
081: import org.openide.DialogDisplayer;
082: import org.openide.NotifyDescriptor;
083: import org.openide.NotifyDescriptor.Message;
084:
085: import com.sun.sql.framework.exception.BaseException;
086: import com.sun.sql.framework.jdbc.DBConstants;
087: import net.java.hulp.i18n.Logger;
088: import com.sun.sql.framework.utils.StringUtil;
089: import org.netbeans.modules.etl.logger.Localizer;
090: import org.netbeans.modules.etl.logger.LogUtil;
091: import org.netbeans.modules.sql.framework.model.DBMetaDataFactory;
092: import org.netbeans.modules.sql.framework.model.DBTable;
093: import org.netbeans.modules.sql.framework.ui.view.IGraphViewContainer;
094:
095: /**
096: * This is a view to show sql code.
097: *
098: * @author Ritesh Adval
099: * @author Ahimanikya Satapathy
100: * @version $Revision$
101: */
102: public class SQLStatementPanel extends JPanel implements IMessageView,
103: ETLOutputPanel {
104:
105: private static transient final Logger mLogger = LogUtil
106: .getLogger(SQLStatementPanel.class.getName());
107: private static transient final Localizer mLoc = Localizer.get();
108: private JButton[] btn = new JButton[1];
109:
110: private class SQLViewActionListener implements ActionListener {
111:
112: public void actionPerformed(ActionEvent e) {
113: Object src = e.getSource();
114: if (src.equals(refreshButton)) {
115: sqlView.execute(ICommand.SHOW_SQL_CMD,
116: new Object[] { sqlObj });
117: }
118: }
119: }
120:
121: public class ShowSQLWorkerThread extends SwingWorker {
122:
123: protected Exception ex;
124: protected SQLObject sqlObjectLocalRef;
125: protected String sqlText = "";
126:
127: public ShowSQLWorkerThread() {
128: sqlObjectLocalRef = sqlObj;
129: }
130:
131: /** Must be executed in AWT Thread and before stopProgressBar() is called. **/
132: protected void startProgressBar() {
133: String nbBundle1 = mLoc.t("PRSR001: Show SQL");
134: String title = Localizer.parse(nbBundle1);
135: String nbBundle2 = mLoc
136: .t("PRSR001: Generating SQL, please wait...");
137: String message = Localizer.parse(nbBundle2);
138: UIUtil.startProgressDialog(title, message);
139: }
140:
141: protected void stopProgressBar() {
142: UIUtil.stopProgressDialog();
143: }
144:
145: public boolean hasValidationErrors() throws BaseException {
146: return hasValidationErrorsDisplayed(sqlObj);
147: }
148:
149: public Object construct() {
150: try {
151: startProgressBar();
152:
153: String sql = null;
154: SQLStatementPanel.this .textArea.setText("");
155:
156: // Sql object is not valid we just want to show validation messages
157: if (hasValidationErrors()) {
158: return "";
159: }
160:
161: refreshDBType();
162:
163: DB db = DBFactory.getInstance().getDatabase(
164: currentDbType);
165: StatementContext context = new StatementContext();
166:
167: if (sqlObjectLocalRef.getObjectType() == SQLConstants.SOURCE_TABLE) {
168: String nbBundle3 = mLoc
169: .t(
170: "PRSR001: -- Select statement for Source Table {0}",
171: NL);
172: sql = Localizer.parse(nbBundle3);
173: sql += db.getStatements().getSelectStatement(
174: (SourceTable) sqlObj, context).getSQL();
175: } else {
176: context.setUseSourceTableAliasName(true);
177: sql = db.getGeneratorFactory().generate(sqlObj,
178: context);
179: }
180:
181: if (sql != null) {
182: sqlText = sql;
183: }
184:
185: } catch (Exception exp) {
186: this .ex = exp;
187: String nbBundle4 = mLoc.t(
188: "PRSR001: Cannot evaluate SQL:{0}", sqlObj
189: .getDisplayName());
190: sqlText = Localizer.parse(nbBundle4);
191: mLogger.errorNoloc(mLoc.t(
192: "PRSR151: Cannot evaluate SQL for{0}", sqlObj
193: .getDisplayName()), ex);
194: mLogger.errorNoloc(mLoc
195: .t("PRSR152: Can't get contents for table{0}",
196: (sqlObj != null) ? sqlObj
197: .getDisplayName() : ""), ex);
198:
199: }
200: return "";
201: }
202:
203: // Runs on the event-dispatching thread.
204: @Override
205: public void finished() {
206: SQLStatementPanel.this .textArea.setText(this .sqlText);
207: stopProgressBar();
208: if (this .ex != null) {
209: String nbBundle5 = mLoc
210: .t(
211: "PRSR001: Error fetching data for table {0}.Cause: {1}",
212: sqlObj.getDisplayName(), this .ex
213: .getMessage());
214: String errorMsg = Localizer.parse(nbBundle5);
215: DialogDisplayer.getDefault().notify(
216: new Message(errorMsg,
217: NotifyDescriptor.ERROR_MESSAGE));
218: }
219: }
220: }
221:
222: private static final String NL = System.getProperty(
223: "line.separator", "\n");
224: /* Indicates initial DB type name as indicated by the SQLObject or its parent. */
225: private String actualDbTypeName;
226: /* Indicates current DB type; determines "flavor" of generated SQL */
227: private int currentDbType;
228: private JTextField dbTypesBox;
229: private JButton refreshButton;
230: /* SQLObject whose applicable SQL content will be generated */
231: private SQLObject sqlObj;
232: private IGraphViewContainer sqlView;
233: /* Text area to contain SQL content */
234: private SQLEditorPanel textArea;
235:
236: /**
237: * Creates a new instance of SQLSqlView associated with the given SQLObject.
238: *
239: * @param sqlView TopComponent which will host this view
240: * @param obj SQLObject whose SQL content will be generated
241: */
242: public SQLStatementPanel(IGraphViewContainer sqlView, SQLObject obj) {
243: this .sqlObj = obj;
244: this .sqlView = sqlView;
245:
246: //do not show tab view if there is only one tab
247: putClientProperty("TabPolicy", "HideWhenAlone"); //NOI18N
248: putClientProperty("PersistenceType", "Never"); //NOI18N
249: this .setLayout(new BorderLayout());
250: String nbBundle6 = mLoc.t("PRSR001: SQL: {0}", obj
251: .getDisplayName());
252: this .setName(Localizer.parse(nbBundle6));
253:
254: JPanel panel = new JPanel();
255: panel.setLayout(new FlowLayout(FlowLayout.LEFT));
256: panel.setBorder(BorderFactory.createEmptyBorder());
257:
258: JToolBar toolbar = new JToolBar();
259: toolbar.setFloatable(false);
260: panel.add(toolbar);
261:
262: String nbBundle7 = mLoc.t("PRSR001: Database Type:");
263: JLabel dbTypeLabel = new JLabel(Localizer.parse(nbBundle7));
264: dbTypeLabel.getAccessibleContext().setAccessibleName(
265: Localizer.parse(nbBundle7));
266: dbTypeLabel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0,
267: 8));
268: toolbar.add(dbTypeLabel);
269:
270: String dbName = getDBType(obj);
271: actualDbTypeName = dbName;
272: SQLDefinition sqlDefinition = SQLObjectUtil
273: .getAncestralSQLDefinition(sqlObj);
274: if (sqlDefinition != null
275: && sqlDefinition.requiresPipelineProcess()) {
276: dbName = DBConstants.AXION_STR;
277: }
278:
279: currentDbType = SQLUtils.getSupportedDBType(dbName);
280: dbTypesBox = new JTextField(dbName);
281: toolbar.add(dbTypesBox);
282: dbTypesBox.setEnabled(false);
283:
284: SQLViewActionListener aListener = new SQLViewActionListener();
285:
286: //add refresh button
287: URL url = getClass()
288: .getResource(
289: "/org/netbeans/modules/sql/framework/ui/resources/images/refresh.png");
290: refreshButton = new JButton(new ImageIcon(url));
291: refreshButton.setMnemonic('R');
292: refreshButton.setToolTipText("Refresh SQL");
293: refreshButton.addActionListener(aListener);
294: btn[0] = refreshButton;
295: this .add(panel, BorderLayout.NORTH);
296:
297: textArea = new SQLEditorPanel();
298: textArea.setBackground(Color.white);
299: textArea.setBorder(BorderFactory.createEmptyBorder());
300: textArea.setEditable(false);
301: textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
302:
303: List<DBTable> tableList = new ArrayList<DBTable>();
304: tableList.addAll(sqlDefinition.getSourceTables());
305: tableList.addAll(sqlDefinition.getTargetTables());
306: textArea.setTables(tableList);
307:
308: JScrollPane sPane = new JScrollPane(textArea);
309: this .add(sPane, BorderLayout.CENTER);
310: }
311:
312: /**
313: * Appends given String to the conetnt view.
314: *
315: * @param str String to append
316: */
317: public synchronized void appendToView(String str) {
318: try {
319: textArea.getDocument().insertString(
320: textArea.getDocument().getLength(), str, null);
321: } catch (BadLocationException e) {
322: //ignore
323: }
324: }
325:
326: public void clearView() {
327: textArea.setText(" ");
328: }
329:
330: /**
331: * Writes validation errors, if any, associated with the given SQLObject.
332: *
333: * @param sqlObj2
334: * @return
335: */
336: public boolean hasValidationErrorsDisplayed(SQLObject object)
337: throws BaseException {
338: boolean validationErrors = false;
339: String errMsg = "";
340:
341: if (object instanceof SQLVisitedObject) {
342: SQLVisitedObject vObject = (SQLVisitedObject) object;
343: SQLValidationVisitor vVisitor = new SQLValidationVisitor();
344: vObject.visit(vVisitor);
345: List invalidObjectList = vVisitor.getValidationInfoList();
346: // Ignore validation errors related to custom operator as they can be deferred
347: // to test colloboration. validation at this stage has no meaning as
348: // the reference for validation is only the host database
349: invalidObjectList = ConditionBuilderUtil
350: .filterValidations(invalidObjectList);
351: if (invalidObjectList.size() > 0) {
352: Iterator iter = invalidObjectList.iterator();
353: while (iter.hasNext()) {
354: ValidationInfo invalidObj = (ValidationInfo) iter
355: .next();
356: if (invalidObj.getValidationType() == ValidationInfo.VALIDATION_ERROR) {
357: errMsg += invalidObj.getDescription().trim()
358: + NL;
359: validationErrors = true;
360: }
361: }
362: if (validationErrors) {
363: throw new BaseException(errMsg);
364: }
365: }
366: }
367:
368: return validationErrors;
369: }
370:
371: /**
372: * Regenerates SQL content based on current settings and state of the associated
373: * SQLObject.
374: */
375: public synchronized void refreshSql() {
376: ShowSQLWorkerThread showSqlThread = new ShowSQLWorkerThread();
377: showSqlThread.start();
378: }
379:
380: /**
381: * refresh view with this new string
382: *
383: * @param str String to refresh with
384: */
385: public void refreshView(String str) {
386: refreshDBType();
387: textArea.setText(str);
388: }
389:
390: public void updateSQLObject(SQLObject obj) {
391: this .sqlObj = obj;
392: String nbBundle8 = mLoc.t("PRSR001: SQL: {0}", obj
393: .getDisplayName());
394: this .setName(Localizer.parse(nbBundle8));
395: }
396:
397: private String getDBType(SQLObject obj) {
398: String dbType = DBConstants.ANSI92_STR;
399: if (obj instanceof DBTable) {
400: DBTable tbl = (DBTable) obj;
401:
402: // Connection definition should always be of ETL
403: SQLDBConnectionDefinition connDef = (SQLDBConnectionDefinition) tbl
404: .getParent().getConnectionDefinition();
405: dbType = connDef.getDBType();
406: if (StringUtil.isNullString(dbType)) {
407: try {
408: dbType = DBMetaDataFactory.getDBTypeFromURL(connDef
409: .getConnectionURL());
410: } catch (Exception ex) {
411: //Ignore, assume JDBC/ANSI
412: }
413: }
414: }
415: return dbType;
416: }
417:
418: private void refreshDBType() {
419: //here we check if we need to force use of axion db
420: SQLDefinition sqlDefinition = SQLObjectUtil
421: .getAncestralSQLDefinition(sqlObj);
422: if (sqlDefinition != null
423: && sqlDefinition.requiresPipelineProcess()) {
424: currentDbType = DBConstants.AXION;
425: dbTypesBox.setText(DBConstants.AXION_STR);
426: } else {
427: currentDbType = SQLUtils
428: .getSupportedDBType(actualDbTypeName);
429: dbTypesBox.setText(actualDbTypeName);
430: }
431: }
432:
433: public JButton[] getVerticalToolBar() {
434: return btn;
435: }
436: }
|