Exemple #1
0
 public static Color getConnectionTypeColor(DBPConnectionType connectionType) {
   String rgbString = connectionType.getColor();
   if (CommonUtils.isEmpty(rgbString)) {
     return null;
   }
   return DBeaverUI.getSharedTextColors().getColor(StringConverter.asRGB(rgbString));
 }
  public static List<ERDEntity> generateEntityList(
      final EntityDiagram diagram, Collection<DBPNamedObject> objects) {
    final List<DBSObject> roots = new ArrayList<>();
    for (DBPNamedObject object : objects) {
      if (object instanceof DBSObject) {
        roots.add((DBSObject) object);
      }
    }

    final List<ERDEntity> entities = new ArrayList<>();

    try {
      DBeaverUI.runInProgressService(
          new DBRRunnableWithProgress() {
            @Override
            public void run(DBRProgressMonitor monitor)
                throws InvocationTargetException, InterruptedException {
              DiagramObjectCollector collector = new DiagramObjectCollector(diagram);
              try {
                collector.generateDiagramObjects(monitor, roots);
              } catch (DBException e) {
                throw new InvocationTargetException(e);
              }
              entities.addAll(collector.getDiagramEntities());
            }
          });
    } catch (InvocationTargetException e) {
      log.error(e.getTargetException());
    } catch (InterruptedException e) {
      // interrupted
    }
    return entities;
  }
Exemple #3
0
 public static DBeaverUI getInstance() {
   if (instance == null) {
     instance = new DBeaverUI();
     instance.initialize();
   }
   return instance;
 }
Exemple #4
0
 @Nullable
 public static ISelectionProvider getSelectionProvider(IServiceLocator serviceLocator) {
   ISelectionProvider selectionProvider = serviceLocator.getService(ISelectionProvider.class);
   if (selectionProvider != null) {
     return selectionProvider;
   }
   IWorkbenchPartSite partSite = getWorkbenchPartSite(serviceLocator);
   if (partSite == null) {
     IWorkbenchPart activePart = serviceLocator.getService(IWorkbenchPart.class);
     if (activePart == null) {
       IWorkbenchWindow activeWindow = DBeaverUI.getActiveWorkbenchWindow();
       if (activeWindow != null) {
         activePart = activeWindow.getActivePage().getActivePart();
       }
     }
     if (activePart != null) {
       partSite = activePart.getSite();
     }
   }
   if (partSite != null) {
     return partSite.getSelectionProvider();
   } else {
     return null;
   }
 }
 @Override
 public void resourceChanged(IResourceChangeEvent event) {
   IResourceDelta delta = event.getDelta();
   if (delta == null) {
     return;
   }
   IEditorInput input = getEditorInput();
   IPath localPath = null;
   if (input instanceof IPathEditorInput) {
     localPath = ((IPathEditorInput) input).getPath();
   }
   if (localPath == null) {
     return;
   }
   localPath = ContentUtils.convertPathToWorkspacePath(localPath);
   delta = delta.findMember(localPath);
   if (delta == null) {
     return;
   }
   if (delta.getKind() == IResourceDelta.CHANGED) {
     // Refresh editor
     DBeaverUI.asyncExec(
         new Runnable() {
           @Override
           public void run() {
             loadImage();
           }
         });
   }
 }
Exemple #6
0
 @Override
 public void run() {
   int choice = -1;
   if (saveable instanceof ISaveablePart2) {
     choice = ((ISaveablePart2) saveable).promptToSaveOnClose();
   }
   if (choice == -1 || choice == ISaveablePart2.DEFAULT) {
     Shell shell;
     String saveableName;
     if (saveable instanceof IWorkbenchPart) {
       shell = ((IWorkbenchPart) saveable).getSite().getShell();
       saveableName = ((IWorkbenchPart) saveable).getTitle();
     } else {
       shell = DBeaverUI.getActiveWorkbenchShell();
       saveableName = CommonUtils.toString(saveable);
     }
     int confirmResult =
         ConfirmationDialog.showConfirmDialog(
             shell,
             DBeaverPreferences.CONFIRM_EDITOR_CLOSE,
             ConfirmationDialog.QUESTION_WITH_CANCEL,
             saveableName);
     switch (confirmResult) {
       case IDialogConstants.YES_ID:
         choice = ISaveablePart2.YES;
         break;
       case IDialogConstants.NO_ID:
         choice = ISaveablePart2.NO;
         break;
       default:
         choice = ISaveablePart2.CANCEL;
         break;
     }
   }
   switch (choice) {
     case ISaveablePart2.YES: // yes
       saveable.doSave(monitor.getNestedMonitor());
       result = !saveable.isDirty();
       break;
     case ISaveablePart2.NO: // no
       result = true;
       break;
     case ISaveablePart2.CANCEL: // cancel
     default:
       result = false;
       break;
   }
 }
  @Override
  public boolean performFinish() {
    // Save settings
    getSettings().saveTo(getDialogSettings());
    showError(null);

    // Compare
    final CompareObjectsExecutor executor = new CompareObjectsExecutor(settings);
    try {
      DBeaverUI.run(
          getContainer(),
          true,
          true,
          new DBRRunnableWithProgress() {
            @Override
            public void run(DBRProgressMonitor monitor)
                throws InvocationTargetException, InterruptedException {
              try {
                CompareReport report = generateReport(monitor, executor);

                renderReport(monitor, report);
              } catch (DBException e) {
                throw new InvocationTargetException(e);
              }
            }
          });
      UIUtils.showMessageBox(
          getShell(), "Objects compare", "Objects compare finished", SWT.ICON_INFORMATION);
    } catch (InvocationTargetException e) {
      if (executor.getInitializeError() != null) {
        showError(executor.getInitializeError().getMessage());
      } else {
        log.error(e.getTargetException());
        showError(e.getTargetException().getMessage());
      }
      return false;
    } catch (InterruptedException e) {
      showError("Compare interrupted");
      return false;
    } finally {
      executor.dispose();
    }

    // Done
    return true;
  }
  protected static List<DBNNode> loadTreeState(DBPPreferenceStore store, String propName) {
    final List<DBNNode> result = new ArrayList<>();
    final String sources = store.getString(propName);
    if (!CommonUtils.isEmpty(sources)) {
      try {
        DBeaverUI.runInProgressService(
            new DBRRunnableWithProgress() {
              @Override
              public void run(DBRProgressMonitor monitor) {
                // Keep broken datasources to make connect attempt only once
                Set<DBNDataSource> brokenDataSources = new HashSet<>();

                // Find all nodes
                StringTokenizer st = new StringTokenizer(sources, "|"); // $NON-NLS-1$
                while (st.hasMoreTokens()) {
                  String nodePath = st.nextToken();
                  try {
                    DBNDataSource dsNode =
                        DBeaverCore.getInstance().getNavigatorModel().getDataSourceByPath(nodePath);
                    if (brokenDataSources.contains(dsNode)) {
                      continue;
                    }

                    DBNNode node =
                        DBeaverCore.getInstance()
                            .getNavigatorModel()
                            .getNodeByPath(monitor, nodePath);
                    if (node != null) {
                      result.add(node);
                    } else {
                      brokenDataSources.add(dsNode);
                    }
                  } catch (DBException e) {
                    log.error(e);
                  }
                }
              }
            });
      } catch (InvocationTargetException e) {
        log.error(e.getTargetException());
      } catch (InterruptedException e) {
        // ignore
      }
    }
    return result;
  }
Exemple #9
0
 public static Color getConnectionColor(DBPConnectionConfiguration connectionInfo) {
   String rgbString = connectionInfo.getConnectionColor();
   if (CommonUtils.isEmpty(rgbString)) {
     rgbString = connectionInfo.getConnectionType().getColor();
   }
   if (CommonUtils.isEmpty(rgbString)) {
     return null;
   }
   Color connectionColor =
       DBeaverUI.getSharedTextColors().getColor(StringConverter.asRGB(rgbString));
   if (connectionColor.getBlue() == 255
       && connectionColor.getRed() == 255
       && connectionColor.getGreen() == 255) {
     // For white color return just null to avoid explicit color set.
     // It is important for dark themes
     return null;
   }
   return connectionColor;
 }
Exemple #10
0
 @Nullable
 public static IWorkbenchPartSite getWorkbenchPartSite(IServiceLocator serviceLocator) {
   IWorkbenchPartSite partSite = serviceLocator.getService(IWorkbenchPartSite.class);
   if (partSite == null) {
     IWorkbenchPart activePart = serviceLocator.getService(IWorkbenchPart.class);
     if (activePart == null) {
       IWorkbenchWindow workbenchWindow = DBeaverUI.getActiveWorkbenchWindow();
       if (workbenchWindow != null) {
         IWorkbenchPage activePage = workbenchWindow.getActivePage();
         if (activePage != null) {
           activePart = activePage.getActivePart();
         }
       }
     }
     if (activePart != null) {
       partSite = activePart.getSite();
     }
   }
   return partSite;
 }
Exemple #11
0
 @Override
 public DBAAuthInfo promptUserCredentials(String prompt, String userName, String userPassword) {
   // Ask user
   final Shell shell = DBeaverUI.getActiveWorkbenchShell();
   final BaseAuthDialog authDialog = new BaseAuthDialog(shell, prompt);
   authDialog.setUserName(userName);
   authDialog.setUserPassword(userPassword);
   final RunnableWithResult<Boolean> binder =
       new RunnableWithResult<Boolean>() {
         @Override
         public void run() {
           result = (authDialog.open() == IDialogConstants.OK_ID);
         }
       };
   UIUtils.runInUI(shell, binder);
   if (binder.getResult() != null && binder.getResult()) {
     return authDialog.getAuthInfo();
   } else {
     return null;
   }
 }
  @Override
  protected void fillContributionItems(List<IContributionItem> menuItems) {
    IWorkbenchPart activePart =
        DBeaverUI.getActiveWorkbenchWindow().getActivePage().getActivePart();
    if (activePart == null) {
      return;
    }
    final ISelectionProvider selectionProvider = activePart.getSite().getSelectionProvider();
    if (selectionProvider == null) {
      return;
    }
    ISelection selection = selectionProvider.getSelection();
    if (!(selection instanceof IStructuredSelection)) {
      return;
    }
    DBSObject selectedObject = NavigatorUtils.getSelectedObject((IStructuredSelection) selection);

    if (selectedObject != null) {
      List<ToolDescriptor> tools =
          ToolsRegistry.getInstance().getTools((IStructuredSelection) selection);
      fillToolsMenu(menuItems, tools, selection);
    }
  }
 private static void fillToolsMenu(
     List<IContributionItem> menuItems, List<ToolDescriptor> tools, ISelection selection) {
   boolean hasTools = false;
   if (!CommonUtils.isEmpty(tools)) {
     IWorkbenchWindow workbenchWindow = DBeaverUI.getActiveWorkbenchWindow();
     if (workbenchWindow.getActivePage() != null) {
       IWorkbenchPart activePart = workbenchWindow.getActivePage().getActivePart();
       if (activePart != null) {
         Map<ToolGroupDescriptor, MenuManager> groupsMap = new HashMap<>();
         for (ToolDescriptor tool : tools) {
           hasTools = true;
           MenuManager parentMenu = null;
           if (tool.getGroup() != null) {
             parentMenu = getGroupMenu(menuItems, groupsMap, tool.getGroup());
           }
           IAction action =
               ActionUtils.makeAction(
                   new NavigatorActionExecuteTool(workbenchWindow, tool),
                   activePart.getSite(),
                   selection,
                   tool.getLabel(),
                   tool.getIcon() == null ? null : DBeaverIcons.getImageDescriptor(tool.getIcon()),
                   tool.getDescription());
           if (parentMenu == null) {
             menuItems.add(new ActionContributionItem(action));
           } else {
             parentMenu.add(new ActionContributionItem(action));
           }
         }
       }
     }
   }
   if (!hasTools) {
     menuItems.add(new ActionContributionItem(new EmptyListAction()));
   }
 }
  /**
   * This method returns a list of completion proposals as ICompletionProposal objects. The
   * proposals are based on the word at the offset in the document where the cursor is positioned.
   * In this implementation, we find the word at the document offset and compare it to our list of
   * SQL reserved words. The list is a subset, of those words that match what the user has entered.
   * For example, the text or proposes the SQL keywords OR and ORDER. The list is returned as an
   * array of completion proposals.
   *
   * @see
   *     org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(ITextViewer,
   *     int)
   */
  @Override
  public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
    this.documentOffset = documentOffset;
    this.activeQuery = null;

    this.wordDetector =
        new SQLWordPartDetector(viewer.getDocument(), editor.getSyntaxManager(), documentOffset);
    final String wordPart = wordDetector.getWordPart();

    if (lookupTemplates) {
      return makeTemplateProposals(viewer, documentOffset, wordPart);
    }

    final List<SQLCompletionProposal> proposals = new ArrayList<>();
    QueryType queryType = null;
    {
      final String prevKeyWord = wordDetector.getPrevKeyWord();
      if (!CommonUtils.isEmpty(prevKeyWord)) {
        if (editor.getSyntaxManager().getDialect().isEntityQueryWord(prevKeyWord)) {
          queryType = QueryType.TABLE;
        } else if (editor.getSyntaxManager().getDialect().isAttributeQueryWord(prevKeyWord)) {
          queryType = QueryType.COLUMN;
        }
      }
    }
    if (queryType != null) {
      if (editor.getDataSource() != null) {
        try {
          final QueryType qt = queryType;
          DBeaverUI.runInProgressService(
              new DBRRunnableWithProgress() {
                @Override
                public void run(DBRProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                  monitor.beginTask("Seeking for completion proposals", 1);
                  try {
                    monitor.subTask("Make structure proposals");
                    makeStructureProposals(monitor, proposals, wordPart, qt);
                  } finally {
                    monitor.done();
                  }
                }
              });
        } catch (InvocationTargetException e) {
          log.warn("Error while seeking for structure proposals", e.getTargetException());
        } catch (InterruptedException e) {
          // interrupted - do nothing
        }
      }
    }

    if (proposals.isEmpty() || !wordPart.isEmpty()) {
      // Keyword assist
      List<String> matchedKeywords =
          editor.getSyntaxManager().getDialect().getMatchedKeywords(wordPart);
      for (String keyWord : matchedKeywords) {
        DBPKeywordType keywordType = editor.getSyntaxManager().getDialect().getKeywordType(keyWord);
        if (keywordType != null) {
          proposals.add(
              createCompletionProposal(
                  keyWord, keyWord, keyWord + " (" + keywordType.name() + ")", null, false, null));
        }
      }
    }

    // Remove duplications
    for (int i = 0; i < proposals.size(); i++) {
      SQLCompletionProposal proposal = proposals.get(i);
      for (int j = i + 1; j < proposals.size(); ) {
        SQLCompletionProposal proposal2 = proposals.get(j);
        if (proposal.getDisplayString().equals(proposal2.getDisplayString())) {
          proposals.remove(j);
        } else {
          j++;
        }
      }
    }
    DBSObject selectedObject = getSelectedObject(editor.getDataSource());
    boolean hideDups =
        getPreferences().getBoolean(SQLPreferenceConstants.HIDE_DUPLICATE_PROPOSALS)
            && selectedObject != null;
    if (hideDups) {
      for (int i = 0; i < proposals.size(); i++) {
        SQLCompletionProposal proposal = proposals.get(i);
        for (int j = 0; j < proposals.size(); ) {
          SQLCompletionProposal proposal2 = proposals.get(j);
          if (i != j
              && proposal.hasStructObject()
              && proposal2.hasStructObject()
              && CommonUtils.equalObjects(
                  proposal.getObject().getName(), proposal2.getObject().getName())
              && proposal.getObjectContainer() == selectedObject) {
            proposals.remove(j);
          } else {
            j++;
          }
        }
      }
    }

    if (hideDups) {
      // Remove duplicates from non-active schema

      if (selectedObject instanceof DBSObjectContainer) {
        // List<ICompletionProposal>
      }
    }
    return proposals.toArray(new ICompletionProposal[proposals.size()]);
  }
Exemple #15
0
 static void disposeUI() {
   if (instance != null) {
     instance.dispose();
   }
 }
Exemple #16
0
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    final List<OracleSourceObject> objects = getSelectedObjects(event);
    if (!objects.isEmpty()) {
      final Shell activeShell = HandlerUtil.getActiveShell(event);
      if (objects.size() == 1) {
        final OracleSourceObject unit = objects.get(0);

        DBCSourceHost sourceHost = null;
        final IWorkbenchPart activePart = HandlerUtil.getActiveEditor(event);
        if (activePart != null) {
          sourceHost = RuntimeUtils.getObjectAdapter(activePart, DBCSourceHost.class);
          if (sourceHost == null) {
            sourceHost = activePart.getAdapter(DBCSourceHost.class);
          }
        }
        if (sourceHost != null && sourceHost.getSourceObject() != unit) {
          sourceHost = null;
        }

        final DBCCompileLog compileLog =
            sourceHost == null ? new DBCCompileLogBase() : sourceHost.getCompileLog();
        compileLog.clearLog();
        Throwable error = null;
        try {
          DBeaverUI.runInProgressService(
              new DBRRunnableWithProgress() {
                @Override
                public void run(DBRProgressMonitor monitor)
                    throws InvocationTargetException, InterruptedException {
                  try {
                    compileUnit(monitor, compileLog, unit);
                  } catch (DBCException e) {
                    throw new InvocationTargetException(e);
                  }
                }
              });
          if (compileLog.getError() != null) {
            error = compileLog.getError();
          }
        } catch (InvocationTargetException e) {
          error = e.getTargetException();
        } catch (InterruptedException e) {
          return null;
        }
        if (error != null) {
          UIUtils.showErrorDialog(activeShell, "Unexpected compilation error", null, error);
        } else if (!CommonUtils.isEmpty(compileLog.getErrorStack())) {
          // Show compile errors
          int line = -1, position = -1;
          StringBuilder fullMessage = new StringBuilder();
          for (DBCCompileError oce : compileLog.getErrorStack()) {
            fullMessage.append(oce.toString()).append(GeneralUtils.getDefaultLineSeparator());
            if (line < 0) {
              line = oce.getLine();
              position = oce.getPosition();
            }
          }

          // If compiled object is currently open in editor - try to position on error line
          if (sourceHost != null
              && sourceHost.getSourceObject() == unit
              && line > 0
              && position > 0) {
            sourceHost.positionSource(line, position);
            activePart.getSite().getPage().activate(activePart);
          }

          String errorTitle = unit.getName() + " compilation failed";
          if (sourceHost != null) {
            sourceHost.setCompileInfo(errorTitle, true);
            sourceHost.showCompileLog();
          }
          UIUtils.showErrorDialog(activeShell, errorTitle, fullMessage.toString());
        } else {
          String message = unit.getName() + " compiled successfully";
          if (sourceHost != null) {
            sourceHost.setCompileInfo(message, true);
          }
          UIUtils.showMessageBox(activeShell, "Done", message, SWT.ICON_INFORMATION);
        }
      } else {
        OracleCompilerDialog dialog = new OracleCompilerDialog(activeShell, objects);
        dialog.open();
      }
    }
    return null;
  }