Upload/Download of multiple files now possible
[phpeclipse.git] / net.sourceforge.phpeclipse / src / net / sourceforge / phpeclipse / actions / PHPOpenSQLTableEditorAction.java
1 /*******************************************************************************
2  * Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This
3  * program and the accompanying materials are made available under the terms of
4  * the Common Public License v1.0 which accompanies this distribution, and is
5  * available at http://www.eclipse.org/legal/cpl-v10.html
6  * 
7  * Contributors: www.phpeclipse.de
8  ******************************************************************************/
9 package net.sourceforge.phpeclipse.actions;
10
11 import java.sql.Connection;
12 import java.sql.DatabaseMetaData;
13 import java.sql.ResultSet;
14 import java.sql.SQLException;
15 import java.util.ArrayList;
16
17 import net.sourceforge.phpeclipse.PHPeclipsePlugin;
18 import net.sourceforge.phpeclipse.phpeditor.PHPEditor;
19 import net.sourceforge.phpeclipse.ui.WebUI;
20 import net.sourceforge.phpeclipse.ui.overlaypages.ProjectPrefUtil;
21
22 import org.eclipse.core.resources.IContainer;
23 import org.eclipse.core.resources.IFile;
24 import org.eclipse.core.resources.IProject;
25 import org.eclipse.core.runtime.Path;
26 import org.eclipse.jface.action.IAction;
27 import org.eclipse.jface.text.BadLocationException;
28 import org.eclipse.jface.text.IDocument;
29 import org.eclipse.jface.text.ITextSelection;
30 import org.eclipse.jface.text.TextSelection;
31 import org.eclipse.jface.viewers.ISelection;
32 import org.eclipse.jface.viewers.LabelProvider;
33 import org.eclipse.jface.window.Window;
34 import org.eclipse.swt.graphics.Point;
35 import org.eclipse.ui.IEditorActionDelegate;
36 import org.eclipse.ui.IEditorPart;
37 import org.eclipse.ui.IFileEditorInput;
38 import org.eclipse.ui.IViewPart;
39 import org.eclipse.ui.IWorkbenchPage;
40 import org.eclipse.ui.IWorkbenchWindow;
41 import org.eclipse.ui.PartInitException;
42 import org.eclipse.ui.actions.ActionDelegate;
43 import org.eclipse.ui.dialogs.ListSelectionDialog;
44 import org.eclipse.ui.internal.dialogs.ListContentProvider;
45
46 import com.quantum.QuantumPlugin;
47 import com.quantum.adapters.DatabaseAdapter;
48 import com.quantum.model.Bookmark;
49 import com.quantum.model.BookmarkCollection;
50 import com.quantum.model.Entity;
51 import com.quantum.model.EntityFactory;
52 import com.quantum.model.NotConnectedException;
53 import com.quantum.sql.MultiSQLServer;
54 import com.quantum.sql.SQLResultSetCollection;
55 import com.quantum.sql.SQLResultSetResults;
56 import com.quantum.sql.SQLResults;
57 import com.quantum.ui.dialog.ExceptionDisplayDialog;
58 import com.quantum.util.connection.ConnectionUtil;
59 import com.quantum.view.tableview.TableView;
60
61 public class PHPOpenSQLTableEditorAction extends ActionDelegate implements
62     IEditorActionDelegate {
63
64   private IWorkbenchWindow fWindow;
65
66   private PHPEditor fEditor;
67
68   private IProject fProject;
69
70   public void dispose() {
71   }
72
73   public void init(IWorkbenchWindow window) {
74     this.fWindow = window;
75   }
76
77   public void selectionChanged(IAction action, ISelection selection) {
78     if (!selection.isEmpty()) {
79       if (selection instanceof TextSelection) {
80         action.setEnabled(true);
81       } else if (fWindow.getActivePage() != null
82           && fWindow.getActivePage().getActivePart() != null) {
83         //
84       }
85     }
86   }
87
88   private IWorkbenchPage getActivePage() {
89     fWindow = fEditor.getEditorSite()
90         .getWorkbenchWindow();
91     IWorkbenchPage page = fWindow.getActivePage();
92     return page;
93   }
94
95   public IContainer getWorkingLocation(IFileEditorInput editorInput) {
96     if (editorInput == null || editorInput.getFile() == null) {
97       return null;
98     }
99     return editorInput.getFile().getParent();
100   }
101
102   private IFile getIncludeFile(IProject project, IFileEditorInput editorInput,
103       String relativeFilename) {
104     //          IContainer container = getWorkingLocation(editorInput);
105     //          String fullPath = project.getLocation().toString();
106     Path path = new Path(relativeFilename);
107     IFile file = project.getFile(path);
108     return file;
109   }
110
111   public void run(IAction action) {
112     if (fEditor == null) {
113       IEditorPart targetEditor = fWindow.getActivePage().getActiveEditor();
114       if (targetEditor != null && (targetEditor instanceof PHPEditor)) {
115         fEditor = (PHPEditor) targetEditor;
116       }
117     }
118     if (fEditor != null) {
119       //                        TableView view = TableView.getInstance();
120
121       //                        determine the current Project from a (file-based) Editor
122       fWindow = fEditor.getEditorSite().getWorkbenchWindow();
123       IFile f = ((IFileEditorInput) fEditor.getEditorInput()).getFile();
124       fProject = f.getProject();
125
126       ITextSelection selection = (ITextSelection) fEditor
127           .getSelectionProvider().getSelection();
128       IDocument doc = fEditor.getDocumentProvider().getDocument(
129           fEditor.getEditorInput());
130       int pos = selection.getOffset();
131       //  System.out.println(selection.getText());
132       String tableName = getSQLTableName(doc, pos);
133
134       IViewPart viewPart = null;
135       String view = "com.quantum.view.tableview.TableView";
136       try {
137         IWorkbenchPage page = QuantumPlugin.getDefault().getActivePage();
138         viewPart = page.findView(view);
139         if (viewPart == null) {
140           viewPart = page.showView(view);
141         }
142         page.bringToTop(viewPart);
143         getTables((TableView) viewPart, fProject, tableName);
144       } catch (PartInitException e) {
145         e.printStackTrace();
146       }
147
148     }
149   }
150
151   public void setActiveEditor(IAction action, IEditorPart targetEditor) {
152     if (targetEditor != null && (targetEditor instanceof PHPEditor)) {
153       fEditor = (PHPEditor) targetEditor;
154     }
155   }
156
157   private String getSQLTableName(IDocument doc, int pos) {
158     Point word = null;
159     int start = -1;
160     int end = -1;
161
162     try {
163
164       int position = pos;
165       char character;
166
167       while (position >= 0) {
168         character = doc.getChar(position);
169         if (Character.isWhitespace(character) || (character == '\"')
170             || (character == '\'') || (character == '\r')
171             || (character == '\n'))
172           break;
173         --position;
174       }
175
176       start = position;
177
178       position = pos;
179       int length = doc.getLength();
180
181       while (position < length) {
182         character = doc.getChar(position);
183         if (Character.isWhitespace(character) || (character == '\"')
184             || (character == '\'') || (character == '\r')
185             || (character == '\n'))
186           break;
187         ++position;
188       }
189
190       start++;
191       end = position;
192
193       if (end > start)
194         word = new Point(start, end - start);
195
196     } catch (BadLocationException x) {
197     }
198
199     if (word != null) {
200       try {
201         return doc.get(word.x, word.y);
202       } catch (BadLocationException e) {
203       }
204     }
205     return "";
206   }
207
208   public void getTables(TableView tableView, IProject project, String tableName) {
209     // Get The Database bookmark from the Quantum SQL plugin:
210     BookmarkCollection sqlBookMarks = BookmarkCollection.getInstance();
211     if (sqlBookMarks != null) {
212       String bookmarkString = ProjectPrefUtil.getMiscProjectsPreferenceValue(project,
213           WebUI.PHP_BOOKMARK_DEFAULT);
214       if (bookmarkString != null && !bookmarkString.equals("")) {
215         Bookmark bookmark = sqlBookMarks.find(bookmarkString);
216         ArrayList sqlList = new ArrayList();
217         if (bookmark != null && !bookmark.isConnected()) {
218           new ConnectionUtil().connect(bookmark, null);
219         }
220         if (bookmark != null && bookmark.isConnected()) {
221           try {
222             Connection connection = bookmark.getConnection();
223             DatabaseMetaData metaData = connection.getMetaData();
224             ConnectionUtil connectionUtil = new ConnectionUtil();
225             Entity entity;
226             DatabaseAdapter adapter;
227
228             if (metaData != null) {
229               String columnName;
230               String prefixWithoutDollar = tableName;
231               if (prefixWithoutDollar.charAt(0) == '$') {
232                 prefixWithoutDollar = prefixWithoutDollar.substring(1);
233               }
234               ResultSet set;
235               set = metaData.getTables(null, null, "%" + prefixWithoutDollar
236                   + "%", null);
237               while (set.next()) {
238                 tableName = set.getString("TABLE_NAME");
239                 tableName = (tableName == null) ? "" : tableName.trim();
240                 if (tableName != null && tableName.length() > 0) {
241                   sqlList.add(tableName);
242                 }
243               }
244               set.close();
245               EntityFactory entityFactory = EntityFactory.getInstance();
246               if (sqlList.size() == 1) {
247                 adapter = bookmark.getAdapter();
248                 entity = entityFactory.create(bookmark, null, (String) sqlList
249                     .get(0), Entity.TABLE_TYPE, false);
250                 String query = adapter.getTableQuery(entity.getQualifiedName());
251
252                 try {
253                   SQLResults results = MultiSQLServer.getInstance().execute(
254                       bookmark, connectionUtil.connect(bookmark, fWindow.getShell()),  
255                       entity, query);
256
257                   if (results != null && results.isResultSet()) {
258                     SQLResultSetCollection.getInstance().addSQLResultSet(
259                         (SQLResultSetResults) results);
260                   }
261                 } catch (SQLException e) {
262                   ExceptionDisplayDialog.openError(fWindow.getShell(), null, null, e);
263                 }
264                 //                                                              tableView.loadTable(entityFactory.create(
265                 //                                                                              bookmark, null,
266                 //                                                                              (String) sqlList.get(0),
267                 //                                                                              Entity.TABLE_TYPE));
268               } else if (sqlList.size() > 1) {
269                 ListSelectionDialog listSelectionDialog = new ListSelectionDialog(
270                     PHPeclipsePlugin.getDefault().getWorkbench()
271                         .getActiveWorkbenchWindow().getShell(), sqlList,
272                     new ListContentProvider(), new LabelProvider(),
273                     "Select the SQL table to open.");
274                 listSelectionDialog.setTitle("Multiple tablenames found");
275                 if (listSelectionDialog.open() == Window.OK) {
276                   Object[] locations = listSelectionDialog.getResult();
277                   if (locations != null) {
278                     for (int i = 0; i < locations.length; i++) {
279                       adapter = bookmark.getAdapter();
280                       entity = entityFactory.create(bookmark, null,
281                           (String) locations[i], Entity.TABLE_TYPE, false);
282                       String query = adapter.getTableQuery(entity
283                           .getQualifiedName());
284
285                       try {
286                         SQLResults results = MultiSQLServer.getInstance()
287                             .execute(bookmark,
288                                 connectionUtil.connect(bookmark, fWindow.getShell()),
289                                 entity, query);
290
291                         if (results != null && results.isResultSet()) {
292                           SQLResultSetCollection.getInstance().addSQLResultSet(
293                               (SQLResultSetResults) results);
294                         }
295                       } catch (SQLException e) {
296                         ExceptionDisplayDialog.openError(fWindow.getShell(), null, null, e);
297                       }
298
299                       //                                                                                        tableView
300                       //                                                                                                        .loadTable(entityFactory
301                       //                                                                                                                        .create(
302                       //                                                                                                                                        bookmark,
303                       //                                                                                                                                        null,
304                       //                                                                                                                                        (String) locations[i],
305                       //                                                                                                                                        Entity.TABLE_TYPE));
306                     }
307
308                   }
309                 }
310               }
311             }
312           } catch (NotConnectedException e) {
313             // ignore this - not mission critical
314           } catch (SQLException e) {
315             e.printStackTrace();
316           }
317         }
318       }
319     }
320   }
321
322 }