001    /*
002    // $Id: //open/mondrian/src/main/mondrian/gui/QueryPanel.java#13 $
003    // This software is subject to the terms of the Common Public License
004    // Agreement, available at the following URL:
005    // http://www.opensource.org/licenses/cpl.html.
006    // Copyright (C) 2002-2008 Julian Hyde and others
007    // Copyright (C) 2006-2007 Cincom Systems, Inc.
008    // All Rights Reserved.
009    // You must accept the terms of that agreement to use this software.
010    */
011    package mondrian.gui;
012    
013    import java.awt.Color;
014    import java.awt.Component;
015    import java.awt.FlowLayout;
016    import java.awt.Font;
017    import java.awt.event.ItemEvent;
018    import java.awt.event.ItemListener;
019    import java.awt.event.MouseAdapter;
020    import java.awt.event.MouseEvent;
021    import java.io.ByteArrayOutputStream;
022    import java.io.File;
023    import java.io.PrintStream;
024    import java.util.Iterator;
025    import java.util.Map;
026    import java.util.Vector;
027    import javax.swing.ComboBoxModel;
028    import javax.swing.DefaultComboBoxModel;
029    import javax.swing.JComboBox;
030    import javax.swing.JInternalFrame;
031    import javax.swing.JLabel;
032    import javax.swing.JMenuItem;
033    import javax.swing.JOptionPane;
034    import javax.swing.JPanel;
035    import javax.swing.JPopupMenu;
036    import javax.swing.SwingConstants;
037    import javax.swing.UIManager;
038    import javax.swing.text.DefaultEditorKit;
039    import mondrian.olap.Connection;
040    import mondrian.olap.DriverManager;
041    import mondrian.olap.Query;
042    import mondrian.olap.Result;
043    
044    import org.apache.log4j.Logger;
045    
046    /**
047     *
048     * @author  sean
049     * @version $Id: //open/mondrian/src/main/mondrian/gui/QueryPanel.java#13 $
050     */
051    public class QueryPanel extends javax.swing.JPanel {
052    
053        private static final Logger LOGGER = Logger.getLogger(QueryPanel.class);
054    
055        Connection connection;
056        JMenuItem queryMenuItem;
057        int windowMenuIndex;
058        Map schemaWindowMap;    // map of schema frames and schema menu items
059    
060        Workbench workbench;
061    
062        /** Creates new form QueryPanel */
063        public QueryPanel(Workbench workbench) {
064            this.workbench = workbench;
065            initComponents();
066        }
067    
068        public void setConnection(Connection c) {
069            connection = c;
070        }
071    
072        public Connection getConnection() {
073            return connection;
074        }
075    
076        //====================================================
077    
078        public void setMenuItem(JMenuItem mi) {
079            this.queryMenuItem = mi;
080        }
081    
082        public void setSchemaWindowMap(Map swindowMap) {
083            this.schemaWindowMap = swindowMap;  // MAP OF FILE AND FRAME
084            setCatalogs();
085        }
086    
087        private void setCatalogs() {
088            Vector v = new Vector();
089            Iterator it = schemaWindowMap.values().iterator();  // schema menu items
090            while (it.hasNext()) {
091                JMenuItem elem = (JMenuItem) it.next();
092                v.add(elem.getText());
093            }
094            ComboBoxModel cCatalogs = new DefaultComboBoxModel(v);
095            schemaList.setModel(cCatalogs) ;
096        }
097        public void setWindowMenuIndex(int i) {
098            this.windowMenuIndex = i;
099        }
100    
101        /**
102         * @return the workbench i18n converter
103         */
104        public I18n getResourceConverter() {
105            return workbench.getResourceConverter();
106        }
107    
108        public void initConnection(String smenutext) {
109            schemaList.setSelectedItem(smenutext);
110            connectButtonActionPerformed(null);
111        }
112        //=====================================================
113    
114        /** This method is called from within the constructor to
115         * initialize the form.
116         * WARNING: Do NOT modify this code. The content of this method is
117         * always regenerated by the Form Editor.
118         */
119        private void initComponents() {
120            jScrollPane3 = new javax.swing.JScrollPane();
121            executeButton = new javax.swing.JButton();
122            jSplitPane1 = new javax.swing.JSplitPane();
123            jScrollPane1 = new javax.swing.JScrollPane();
124            queryTextPane = new javax.swing.JTextPane();
125            jScrollPane2 = new javax.swing.JScrollPane();
126            resultTextPane = new javax.swing.JTextPane();
127            connectButton = new javax.swing.JButton();
128            jPopupMenu = new JPopupMenu();
129            jPopupMenu.add(new DefaultEditorKit.CutAction());
130            jPopupMenu.add(new DefaultEditorKit.CopyAction());
131            jPopupMenu.add(new DefaultEditorKit.PasteAction());
132    
133            schemaScrollPane1 = new javax.swing.JScrollPane();
134            schemaLabel = new javax.swing.JLabel();
135            schemaList = new JComboBox(new String[] {getResourceConverter().getString("common.join.title","Join"),
136                                                        getResourceConverter().getString("common.table.title","Table")});
137            //schemaScrollPane1.setViewportView(schemaList);
138            schemaPanel = new JPanel();
139            //schemaPanel.setLayout(new BorderLayout(25,0));
140            schemaPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 0));
141    
142            setLayout(new java.awt.BorderLayout());
143    
144            schemaLabel.setFont(new Font("Dialog", 1, 12));
145            schemaLabel.setForeground((Color) UIManager.getDefaults().get("CheckBoxMenuItem.acceleratorForeground"));
146            schemaLabel.setHorizontalAlignment(SwingConstants.CENTER);
147            schemaLabel.setText(getResourceConverter().getString("common.schema.title","Schema"));
148            //schemaLabel.setBorder(new EtchedBorder());
149    
150            schemaList.setBackground(Color.white);
151            final JPanel qpanel = this;
152            schemaList.addItemListener(new ItemListener() {
153                public void itemStateChanged(ItemEvent e) {
154    
155    
156                }
157            });
158            connectButton.setText(getResourceConverter().getString("queryPanel.connect.title","Connect"));
159            connectButton.addActionListener(new java.awt.event.ActionListener() {
160                public void actionPerformed(java.awt.event.ActionEvent evt) {
161                    connectButtonActionPerformed(evt);
162                }
163            });
164    
165            schemaPanel.add(schemaLabel); //java.awt.BorderLayout.WEST
166            schemaPanel.add(schemaList);
167            schemaPanel.add(connectButton);
168    
169            add(schemaPanel, java.awt.BorderLayout.NORTH);
170    
171            executeButton.setText(getResourceConverter().getString("queryPanel.execute.title","Execute"));
172            executeButton.addActionListener(new java.awt.event.ActionListener() {
173                public void actionPerformed(java.awt.event.ActionEvent evt) {
174                    executeButtonActionPerformed(evt);
175                }
176            });
177    
178            add(executeButton, java.awt.BorderLayout.SOUTH);
179    
180            jSplitPane1.setDividerLocation(100);
181            jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
182            queryTextPane.setFont(new java.awt.Font("Courier New", 0, 12));
183            queryTextPane.setText("");
184            queryTextPane.addMouseListener(new MouseAdapter() {
185                public void mouseReleased(MouseEvent e) {
186                    if (e.isPopupTrigger()) {
187                        int x = e.getX();
188                        int y = e.getY();
189    
190                        jPopupMenu.show(queryTextPane, x, y);
191    
192                    }
193                }
194            });
195    
196            jScrollPane1.setViewportView(queryTextPane);
197    
198            jSplitPane1.setTopComponent(jScrollPane1);
199    
200            resultTextPane.setEditable(false);
201            resultTextPane.setFont(new java.awt.Font("Courier New", 0, 12));
202            jScrollPane2.setViewportView(resultTextPane);
203    
204            jSplitPane1.setBottomComponent(jScrollPane2);
205    
206            add(jSplitPane1, java.awt.BorderLayout.CENTER);
207    
208        }
209    
210        private void executeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:T://event_executeButtonActionPerformed
211            //run the query, and show the results.
212            try {
213                if (connection == null) {
214                    JOptionPane.showMessageDialog(this, getResourceConverter().getString("queryPanel.noConnection.alert","No Mondrian connection. Select a Schema to connect."),
215                            getResourceConverter().getString("common.alertDialog.title","Alert"), JOptionPane.WARNING_MESSAGE);
216                    return;
217                } //common.alertDialog.title
218                Query q = connection.parseQuery(queryTextPane.getText());
219                Result r = connection.execute(q);
220    
221                //document = DOMBuilder.build(getResult());
222                java.io.StringWriter sw = new java.io.StringWriter();
223                java.io.PrintWriter pw = new java.io.PrintWriter(sw);
224    
225                r.print(pw);
226    
227                resultTextPane.setText(sw.getBuffer().toString());
228            } catch (Exception ex) {
229                ByteArrayOutputStream os = new ByteArrayOutputStream();
230    
231                PrintStream p = new PrintStream(os);
232    
233                Throwable e = ex;
234                while (e != null) {
235                    p.println(e.getLocalizedMessage());
236                    LOGGER.error("", e);
237                    Throwable prev = e;
238                    e = e.getCause();
239                    if (e == prev)
240                      break;
241                    p.println();
242                  }
243    
244                resultTextPane.setText(os.toString());
245            }
246    
247        } //GEN-LAST:T://event_executeButtonActionPerformed
248    
249    
250        private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {
251            File sfile = null;
252            try {
253                JInternalFrame sf = null;
254    
255                String sfname = (String) schemaList.getSelectedItem();
256                Iterator it = schemaWindowMap.entrySet().iterator();
257                while (it.hasNext()) {
258                    Map.Entry elem = (Map.Entry) it.next();
259                    if (((JMenuItem) elem.getValue()).getText().equals(sfname)) {
260                        sf = (JInternalFrame) elem.getKey();
261                        break;
262                    }
263                }
264    
265                if (sf == null) {
266                    // this case may arise when a schema file is opened, mdx query is opened and the schema frame is closed
267                    JOptionPane.showMessageDialog(this, getResourceConverter().getString("queryPanel.schemaNotOpen.alert","Schema file is not open"),
268                                    getResourceConverter().getString("common.errorDialog.title","Error"), JOptionPane.ERROR_MESSAGE);
269                    return;
270                }
271    
272                //JInternalFrame sf = (JInternalFrame) schemaWindowMap.get(sfile);
273                SchemaExplorer se = (SchemaExplorer) sf.getContentPane().getComponent(0);
274                if (se.isNewFile()) {
275                    JOptionPane.showMessageDialog(this, getResourceConverter().getString("queryPanel.saveSchemaFirst.alert","You must first save the Schema to open a Mondrian connection"),
276                                    getResourceConverter().getString("common.alertDialog.title","Alert"), JOptionPane.WARNING_MESSAGE);
277                    sf.setSelected(true);
278                    return;
279                }
280                sfile = se.getSchemaFile();
281    
282                String connectString = "Provider=mondrian;" + "Jdbc=" + se.getJdbcConnectionUrl() + ";" + "Catalog=" + se.getSchemaFile().toURL().toString() + ";";
283                if (se.getJdbcUsername() != null && se.getJdbcUsername().length() > 0) {
284                    connectString = connectString + "JdbcUser=" + se.getJdbcUsername() + ";";
285                }
286                if (se.getJdbcPassword() != null && se.getJdbcPassword().length() > 0) {
287                    connectString = connectString + "JdbcPassword=" + se.getJdbcPassword() + ";";
288                }
289    
290                Connection con = DriverManager.getConnection(connectString, null);
291                if (con != null) {
292                    connection = con;
293                    queryMenuItem.setText(getResourceConverter().getFormattedString("queryPanel.successfulConnection.menuItem",
294                            "{0} MDX - {1}",
295                            new String[] { Integer.toString(windowMenuIndex), se.getSchemaFile().getName() }));
296                    Component o =  this;
297                    while (o != null) {
298                        //System.out.println(""+o.getClass());
299                        if (o.getClass() == JInternalFrame.class) {
300                            ((JInternalFrame) o).setTitle(getResourceConverter().getFormattedString("queryPanel.successfulConnection.internalFrame.title",
301                                    "MDX Query - connected to {0}",
302                                    new String[] { se.getSchemaFile().getName() }));
303                            break;
304                        }
305                        o =  o.getParent();
306                    }
307                    JOptionPane.showMessageDialog(this, "Mondrian connection Successful.",
308                            getResourceConverter().getString("common.informationDialog.title","Information") , JOptionPane.INFORMATION_MESSAGE);
309                } else {
310                    JOptionPane.showMessageDialog(this, getResourceConverter().getFormattedString("queryPanel.unsuccessfulConnection.alert",
311                            "Mondrian connection could not be done for - {0}",
312                            new String[] { se.getSchemaFile().getName() }),
313                            getResourceConverter().getString("common.errorDialog.title","Error"), JOptionPane.ERROR_MESSAGE);
314                }
315            } catch (Exception ex) {
316                LOGGER.error("Exception: " + ex.getMessage(), ex);
317                JOptionPane.showMessageDialog(this, getResourceConverter().getFormattedString("queryPanel.unsuccessfulConnection.exception",
318                        "Mondrian connection could not be done for - {0}",
319                        new String[] { sfile == null ? getResourceConverter().getString("queryPanel.selectedSchema.alert","selected Schema") : sfile.getName() }),
320                            getResourceConverter().getString("common.errorDialog.title","Error"), JOptionPane.ERROR_MESSAGE);
321            }
322        }
323        // Variables declaration - do not modify
324        private javax.swing.JScrollPane jScrollPane3;
325        private javax.swing.JScrollPane jScrollPane2;
326        private javax.swing.JTextPane resultTextPane;
327        private javax.swing.JScrollPane jScrollPane1;
328        private javax.swing.JTextPane queryTextPane;
329        private javax.swing.JSplitPane jSplitPane1;
330        private javax.swing.JButton executeButton;
331        private javax.swing.JComboBox schemaList;
332        private JLabel schemaLabel;
333        private JPanel schemaPanel;
334        private javax.swing.JScrollPane schemaScrollPane1;
335        private javax.swing.JButton connectButton;
336        private JPopupMenu jPopupMenu;
337    
338        // End of variables declaration
339    
340    }
341    
342    // End QueryPanel.java