Search in sources :

Example 61 with IStatus

use of org.eclipse.core.runtime.IStatus in project cubrid-manager by CUBRID.

the class RenameDatabaseAction method run.

public void run() {
    Object[] obj = this.getSelectedObj();
    if (!isSupported(obj[0])) {
        setEnabled(false);
        return;
    }
    final CubridDatabase database = (CubridDatabase) obj[0];
    ISelectionProvider provider = this.getSelectionProvider();
    final TreeViewer viewer = (TreeViewer) provider;
    String serverName = database.getServer().getName();
    String dbName = database.getName();
    final String jobName = serverName + "-" + dbName + "-" + Messages.msgRenameDBRearJobName;
    final RenameDatabaseDialog dialog = new RenameDatabaseDialog(getShell(), new ITaskExecutorInterceptor() {

        public void completeAll() {
            QueryOptions.removePref(database.getDatabaseInfo());
            CommonUITool.openInformationBox(Messages.titleSuccess, Messages.bind(Messages.msgRenameDBComplete, jobName));
            CommonUITool.refreshNavigatorTree(viewer, database.getParent());
        }

        public IStatus postTaskFinished(ITask task) {
            return Status.OK_STATUS;
        }
    });
    dialog.setDatabase(database);
    final Shell shell = getShell();
    TaskExecutor taskExcutor = new TaskExecutor() {

        @SuppressWarnings("unchecked")
        public boolean exec(final IProgressMonitor monitor) {
            if (monitor.isCanceled()) {
                return false;
            }
            monitor.beginTask(Messages.getDbSpaceInfoTaskName, IProgressMonitor.UNKNOWN);
            for (ITask task : taskList) {
                task.execute();
                final String msg = task.getErrorMsg();
                if (openErrorBox(shell, msg, monitor)) {
                    return false;
                }
                if (monitor.isCanceled()) {
                    return false;
                }
                if (task instanceof CommonQueryTask) {
                    dbSpaceInfo = ((CommonQueryTask<DbSpaceInfoList>) task).getResultModel();
                }
            }
            return true;
        }
    };
    dbSpaceInfo = new DbSpaceInfoList();
    CommonQueryTask<DbSpaceInfoList> task = new CommonQueryTask<DbSpaceInfoList>(database.getServer().getServerInfo(), CommonSendMsg.getCommonDatabaseSendMsg(), dbSpaceInfo);
    task.setDbName(database.getLabel());
    taskExcutor.addTask(task);
    new ExecTaskWithProgress(taskExcutor).busyCursorWhile();
    if (taskExcutor.isSuccess()) {
        dialog.setDbSpaceInfoList(dbSpaceInfo);
        dialog.open();
    }
}
Also used : ITaskExecutorInterceptor(com.cubrid.common.ui.spi.progress.ITaskExecutorInterceptor) ITask(com.cubrid.common.core.task.ITask) IStatus(org.eclipse.core.runtime.IStatus) RenameDatabaseDialog(com.cubrid.cubridmanager.ui.cubrid.database.dialog.RenameDatabaseDialog) TreeViewer(org.eclipse.jface.viewers.TreeViewer) Shell(org.eclipse.swt.widgets.Shell) TaskExecutor(com.cubrid.common.ui.spi.progress.TaskExecutor) IProgressMonitor(org.eclipse.core.runtime.IProgressMonitor) ISelectionProvider(org.eclipse.jface.viewers.ISelectionProvider) DbSpaceInfoList(com.cubrid.cubridmanager.core.cubrid.dbspace.model.DbSpaceInfoList) ExecTaskWithProgress(com.cubrid.common.ui.spi.progress.ExecTaskWithProgress) CommonQueryTask(com.cubrid.cubridmanager.core.common.task.CommonQueryTask) CubridDatabase(com.cubrid.common.ui.spi.model.CubridDatabase)

Example 62 with IStatus

use of org.eclipse.core.runtime.IStatus in project dbeaver by serge-rider.

the class ResultSetCommandHandler method execute.

@Nullable
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
    final ResultSetViewer rsv = (ResultSetViewer) getActiveResultSet(HandlerUtil.getActivePart(event));
    if (rsv == null) {
        return null;
    }
    boolean shiftPressed = event.getTrigger() instanceof Event && ((((Event) event.getTrigger()).stateMask & SWT.SHIFT) == SWT.SHIFT);
    String actionId = event.getCommand().getId();
    IResultSetPresentation presentation = rsv.getActivePresentation();
    switch(actionId) {
        case IWorkbenchCommandConstants.FILE_REFRESH:
            rsv.refreshData(null);
            break;
        case CMD_TOGGLE_MODE:
            rsv.toggleMode();
            break;
        case CMD_TOGGLE_PANELS:
            rsv.showPanels(!rsv.isPanelsVisible());
            break;
        case CMD_SWITCH_PRESENTATION:
            rsv.switchPresentation();
            break;
        case CMD_ROW_PREVIOUS:
        case ITextEditorActionDefinitionIds.WORD_PREVIOUS:
            presentation.scrollToRow(IResultSetPresentation.RowPosition.PREVIOUS);
            break;
        case CMD_ROW_NEXT:
        case ITextEditorActionDefinitionIds.WORD_NEXT:
            presentation.scrollToRow(IResultSetPresentation.RowPosition.NEXT);
            break;
        case CMD_ROW_FIRST:
        case ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS:
            presentation.scrollToRow(IResultSetPresentation.RowPosition.FIRST);
            break;
        case CMD_ROW_LAST:
        case ITextEditorActionDefinitionIds.SELECT_WORD_NEXT:
            presentation.scrollToRow(IResultSetPresentation.RowPosition.LAST);
            break;
        case CMD_FETCH_PAGE:
            rsv.readNextSegment();
            break;
        case CMD_FETCH_ALL:
            rsv.readAllData();
            break;
        case CMD_ROW_EDIT:
            if (presentation instanceof IResultSetEditor) {
                ((IResultSetEditor) presentation).openValueEditor(false);
            }
            break;
        case CMD_ROW_EDIT_INLINE:
            if (presentation instanceof IResultSetEditor) {
                ((IResultSetEditor) presentation).openValueEditor(true);
            }
            break;
        case CMD_ROW_ADD:
            rsv.addNewRow(false, shiftPressed);
            break;
        case CMD_ROW_COPY:
            rsv.addNewRow(true, shiftPressed);
            break;
        case CMD_ROW_DELETE:
        case IWorkbenchCommandConstants.EDIT_DELETE:
            rsv.deleteSelectedRows();
            break;
        case CMD_CELL_SET_NULL:
        case CMD_CELL_RESET:
            {
                IResultSetSelection selection = rsv.getSelection();
                for (Object cell : selection.toArray()) {
                    DBDAttributeBinding attr = selection.getElementAttribute(cell);
                    ResultSetRow row = selection.getElementRow(cell);
                    if (row != null && attr != null) {
                        ResultSetValueController valueController = new ResultSetValueController(rsv, attr, row, IValueController.EditType.NONE, null);
                        if (actionId.equals(CMD_CELL_SET_NULL)) {
                            valueController.updateValue(BaseValueManager.makeNullValue(valueController), false);
                        } else {
                            rsv.getModel().resetCellValue(attr, row);
                        }
                    }
                }
                rsv.redrawData(false, false);
                rsv.updatePanelsContent(false);
                break;
            }
        case CMD_APPLY_CHANGES:
            rsv.applyChanges(null);
            break;
        case CMD_REJECT_CHANGES:
            rsv.rejectChanges();
            break;
        case CMD_GENERATE_SCRIPT:
            {
                try {
                    final List<DBEPersistAction> sqlScript = new ArrayList<>();
                    try {
                        DBeaverUI.runInProgressService(new DBRRunnableWithProgress() {

                            @Override
                            public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
                                List<DBEPersistAction> script = rsv.generateChangesScript(monitor);
                                if (script != null) {
                                    sqlScript.addAll(script);
                                }
                            }
                        });
                    } catch (InterruptedException e) {
                    // ignore
                    }
                    if (!sqlScript.isEmpty()) {
                        String scriptText = SQLUtils.generateScript(rsv.getDataContainer() == null ? null : rsv.getDataContainer().getDataSource(), sqlScript.toArray(new DBEPersistAction[sqlScript.size()]), false);
                        scriptText = SQLUtils.generateCommentLine(rsv.getExecutionContext() == null ? null : rsv.getExecutionContext().getDataSource(), "Actual parameter values may differ, what you see is a default string representation of values") + scriptText;
                        ViewSQLDialog dialog = new ViewSQLDialog(HandlerUtil.getActivePart(event).getSite(), rsv.getExecutionContext(), CoreMessages.editors_entity_dialog_preview_title, UIIcon.SQL_PREVIEW, scriptText);
                        dialog.open();
                    }
                } catch (InvocationTargetException e) {
                    UIUtils.showErrorDialog(HandlerUtil.getActiveShell(event), "Script generation", "Can't generate changes script", e.getTargetException());
                }
                break;
            }
        case CMD_COPY_COLUMN_NAMES:
            {
                StringBuilder buffer = new StringBuilder();
                IResultSetSelection selection = rsv.getSelection();
                Collection<DBDAttributeBinding> attrs = selection.isEmpty() ? rsv.getModel().getVisibleAttributes() : selection.getSelectedAttributes();
                for (DBDAttributeBinding attr : attrs) {
                    if (buffer.length() > 0) {
                        buffer.append("\t");
                    }
                    buffer.append(attr.getName());
                }
                ResultSetUtils.copyToClipboard(buffer.toString());
                break;
            }
        case CMD_COPY_ROW_NAMES:
            {
                StringBuilder buffer = new StringBuilder();
                IResultSetSelection selection = rsv.getSelection();
                for (ResultSetRow row : ((IResultSetSelection) selection).getSelectedRows()) {
                    if (buffer.length() > 0) {
                        buffer.append("\n");
                    }
                    buffer.append(row.getVisualNumber() + 1);
                }
                ResultSetUtils.copyToClipboard(buffer.toString());
                break;
            }
        case IWorkbenchCommandConstants.EDIT_COPY:
            ResultSetUtils.copyToClipboard(presentation.copySelectionToString(new ResultSetCopySettings(false, false, false, true, null, null, DBDDisplayFormat.EDIT)));
            break;
        case IWorkbenchCommandConstants.EDIT_PASTE:
        case CoreCommands.CMD_PASTE_SPECIAL:
            if (presentation instanceof IResultSetEditor) {
                ((IResultSetEditor) presentation).pasteFromClipboard(actionId.equals(CoreCommands.CMD_PASTE_SPECIAL));
            }
            break;
        case IWorkbenchCommandConstants.EDIT_CUT:
            ResultSetUtils.copyToClipboard(presentation.copySelectionToString(new ResultSetCopySettings(false, false, true, true, null, null, DBDDisplayFormat.EDIT)));
            break;
        case IWorkbenchCommandConstants.FILE_PRINT:
            presentation.printResultSet();
            break;
        case ITextEditorActionDefinitionIds.SMART_ENTER:
            if (presentation instanceof IResultSetEditor) {
                ((IResultSetEditor) presentation).openValueEditor(false);
            }
            break;
        case IWorkbenchCommandConstants.EDIT_FIND_AND_REPLACE:
            FindReplaceAction action = new FindReplaceAction(DBeaverActivator.getCoreResourceBundle(), "Editor.FindReplace.", HandlerUtil.getActiveShell(event), rsv.getAdapter(IFindReplaceTarget.class));
            action.run();
            break;
        case CMD_NAVIGATE_LINK:
            final ResultSetRow row = rsv.getCurrentRow();
            final DBDAttributeBinding attr = rsv.getActivePresentation().getCurrentAttribute();
            if (row != null && attr != null) {
                new AbstractJob("Navigate association") {

                    @Override
                    protected IStatus run(DBRProgressMonitor monitor) {
                        try {
                            rsv.navigateAssociation(monitor, attr, row, false);
                        } catch (DBException e) {
                            return GeneralUtils.makeExceptionStatus(e);
                        }
                        return Status.OK_STATUS;
                    }
                }.schedule();
            }
            break;
        case CMD_COUNT:
            rsv.updateRowCount();
            break;
        case IWorkbenchCommandConstants.NAVIGATE_BACKWARD_HISTORY:
            {
                final int hp = rsv.getHistoryPosition();
                if (hp > 0) {
                    rsv.navigateHistory(hp - 1);
                }
                break;
            }
        case IWorkbenchCommandConstants.NAVIGATE_FORWARD_HISTORY:
            {
                final int hp = rsv.getHistoryPosition();
                if (hp < rsv.getHistorySize() - 1) {
                    rsv.navigateHistory(hp + 1);
                }
                break;
            }
        case ITextEditorActionDefinitionIds.LINE_GOTO:
            {
                ResultSetRow currentRow = rsv.getCurrentRow();
                final int rowCount = rsv.getModel().getRowCount();
                if (rowCount <= 0) {
                    break;
                }
                GotoLineDialog d = new GotoLineDialog(HandlerUtil.getActiveShell(event), "Go to Row", "Enter row number (1.." + rowCount + ")", String.valueOf(currentRow == null ? 1 : currentRow.getVisualNumber() + 1), new IInputValidator() {

                    @Override
                    public String isValid(String input) {
                        try {
                            int i = Integer.parseInt(input);
                            if (i <= 0 || rowCount < i) {
                                return "Row number is out of range";
                            }
                        } catch (NumberFormatException x) {
                            return "Not a number";
                        }
                        return null;
                    }
                });
                if (d.open() == Window.OK) {
                    int line = Integer.parseInt(d.getValue());
                    rsv.setCurrentRow(rsv.getModel().getRow(line - 1));
                    rsv.getActivePresentation().scrollToRow(IResultSetPresentation.RowPosition.CURRENT);
                }
                break;
            }
        case CMD_FILTER_MENU:
            {
                rsv.showFiltersMenu();
                break;
            }
    }
    return null;
}
Also used : DBException(org.jkiss.dbeaver.DBException) IStatus(org.eclipse.core.runtime.IStatus) FindReplaceAction(org.eclipse.ui.texteditor.FindReplaceAction) DBDAttributeBinding(org.jkiss.dbeaver.model.data.DBDAttributeBinding) ArrayList(java.util.ArrayList) List(java.util.List) InvocationTargetException(java.lang.reflect.InvocationTargetException) AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) DBEPersistAction(org.jkiss.dbeaver.model.edit.DBEPersistAction) ViewSQLDialog(org.jkiss.dbeaver.ui.dialogs.sql.ViewSQLDialog) ExecutionEvent(org.eclipse.core.commands.ExecutionEvent) Event(org.eclipse.swt.widgets.Event) DBRRunnableWithProgress(org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress) Collection(java.util.Collection) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) IFindReplaceTarget(org.eclipse.jface.text.IFindReplaceTarget) IInputValidator(org.eclipse.jface.dialogs.IInputValidator) Nullable(org.jkiss.code.Nullable)

Example 63 with IStatus

use of org.eclipse.core.runtime.IStatus in project dbeaver by serge-rider.

the class ResultSetModel method releaseAll.

private void releaseAll() {
    final List<ResultSetRow> oldRows = curRows;
    this.curRows = new ArrayList<>();
    this.totalRowCount = null;
    // Cleanup in separate job.
    // Sometimes model cleanup takes much time (e.g. freeing LOB values)
    // So let's do it in separate job to avoid UI locking
    new AbstractJob("Cleanup model") {

        {
            setSystem(true);
        }

        @Override
        protected IStatus run(DBRProgressMonitor monitor) {
            for (ResultSetRow row : oldRows) {
                row.release();
            }
            return Status.OK_STATUS;
        }
    }.schedule();
}
Also used : AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) IStatus(org.eclipse.core.runtime.IStatus) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor) DBVColorOverride(org.jkiss.dbeaver.model.virtual.DBVColorOverride)

Example 64 with IStatus

use of org.eclipse.core.runtime.IStatus in project dbeaver by serge-rider.

the class DataSourceManagementToolbar method changeDataBaseSelection.

private void changeDataBaseSelection() {
    if (databaseCombo == null || databaseCombo.isDisposed() || databaseCombo.getSelectionIndex() < 0) {
        return;
    }
    DBPDataSourceContainer dsContainer = getDataSourceContainer();
    final String newName = databaseCombo.getItemText(databaseCombo.getSelectionIndex());
    if (dsContainer != null && dsContainer.isConnected()) {
        final DBPDataSource dataSource = dsContainer.getDataSource();
        new AbstractJob("Change active database") {

            @Override
            protected IStatus run(DBRProgressMonitor monitor) {
                try {
                    DBSObjectContainer oc = DBUtils.getAdapter(DBSObjectContainer.class, dataSource);
                    DBSObjectSelector os = DBUtils.getAdapter(DBSObjectSelector.class, dataSource);
                    if (os != null) {
                        final DBSObject defObject = os.getDefaultObject();
                        if (defObject instanceof DBSObjectContainer) {
                            // USe seconds level of active object
                            DBSObjectSelector os2 = DBUtils.getAdapter(DBSObjectSelector.class, defObject);
                            if (os2 != null && os2.supportsDefaultChange()) {
                                oc = (DBSObjectContainer) defObject;
                                os = os2;
                            }
                        }
                    }
                    if (oc != null && os != null && os.supportsDefaultChange()) {
                        DBSObject newChild = oc.getChild(monitor, newName);
                        if (newChild != null) {
                            os.setDefaultObject(monitor, newChild);
                        } else {
                            throw new DBException(MessageFormat.format(CoreMessages.toolbar_datasource_selector_error_database_not_found, newName));
                        }
                    } else {
                        throw new DBException(CoreMessages.toolbar_datasource_selector_error_database_change_not_supported);
                    }
                } catch (DBException e) {
                    return GeneralUtils.makeExceptionStatus(e);
                }
                return Status.OK_STATUS;
            }
        }.schedule();
    }
}
Also used : AbstractJob(org.jkiss.dbeaver.model.runtime.AbstractJob) DBSObject(org.jkiss.dbeaver.model.struct.DBSObject) DBException(org.jkiss.dbeaver.DBException) IStatus(org.eclipse.core.runtime.IStatus) DBSObjectContainer(org.jkiss.dbeaver.model.struct.DBSObjectContainer) DBSObjectSelector(org.jkiss.dbeaver.model.struct.DBSObjectSelector) DBRProgressMonitor(org.jkiss.dbeaver.model.runtime.DBRProgressMonitor)

Example 65 with IStatus

use of org.eclipse.core.runtime.IStatus in project dbeaver by serge-rider.

the class SQLQueryJob method run.

@Override
protected IStatus run(DBRProgressMonitor monitor) {
    RuntimeUtils.setThreadName("SQL script execution");
    statistics = new DBCStatistics();
    try {
        DBCExecutionContext context = getExecutionContext();
        DBCTransactionManager txnManager = DBUtils.getTransactionManager(context);
        DBCExecutionPurpose purpose = queries.size() > 1 ? DBCExecutionPurpose.USER_SCRIPT : DBCExecutionPurpose.USER;
        try (DBCSession session = context.openSession(monitor, purpose, "SQL Query")) {
            // Set transaction settings (only if autocommit is off)
            QMUtils.getDefaultHandler().handleScriptBegin(session);
            boolean oldAutoCommit = txnManager == null || txnManager.isAutoCommit();
            boolean newAutoCommit = (commitType == SQLScriptCommitType.AUTOCOMMIT);
            if (txnManager != null && !oldAutoCommit && newAutoCommit) {
                txnManager.setAutoCommit(monitor, true);
            }
            monitor.beginTask(this.getName(), queries.size());
            // Notify job start
            if (listener != null) {
                try {
                    listener.onStartScript();
                } catch (Exception e) {
                    log.error(e);
                }
            }
            resultSetNumber = 0;
            for (int queryNum = 0; queryNum < queries.size(); ) {
                // Execute query
                SQLQuery query = queries.get(queryNum);
                fetchResultSetNumber = resultSetNumber;
                boolean runNext = executeSingleQuery(session, query, true);
                if (!runNext) {
                    // Ask to continue
                    if (lastError != null) {
                        log.error(lastError);
                    }
                    boolean isQueue = queryNum < queries.size() - 1;
                    ExecutionQueueErrorResponse response = ExecutionQueueErrorJob.showError(isQueue ? "SQL script execution" : "SQL query execution", lastError, isQueue);
                    boolean stopScript = false;
                    switch(response) {
                        case STOP:
                            // just stop execution
                            stopScript = true;
                            break;
                        case RETRY:
                            // just make it again
                            continue;
                        case IGNORE:
                            // Just do nothing
                            break;
                        case IGNORE_ALL:
                            errorHandling = SQLScriptErrorHandling.IGNORE;
                            break;
                    }
                    if (stopScript) {
                        break;
                    }
                }
                // Check monitor
                if (monitor.isCanceled()) {
                    break;
                }
                monitor.worked(1);
                queryNum++;
            }
            showExecutionResult(session);
            monitor.done();
            // Commit data
            if (txnManager != null && !oldAutoCommit && commitType != SQLScriptCommitType.AUTOCOMMIT) {
                if (lastError == null || errorHandling == SQLScriptErrorHandling.STOP_COMMIT) {
                    if (commitType != SQLScriptCommitType.NO_COMMIT) {
                        monitor.beginTask("Commit data", 1);
                        txnManager.commit(session);
                        monitor.done();
                    }
                } else {
                    monitor.beginTask("Rollback data", 1);
                    txnManager.rollback(session, null);
                    monitor.done();
                }
            }
            // Restore transactions settings
            if (txnManager != null && !oldAutoCommit && newAutoCommit) {
                txnManager.setAutoCommit(monitor, false);
            }
            QMUtils.getDefaultHandler().handleScriptEnd(session);
            // Return success
            return new Status(Status.OK, DBeaverCore.getCorePluginID(), "SQL job completed");
        }
    } catch (Throwable ex) {
        return new Status(Status.ERROR, DBeaverCore.getCorePluginID(), "Error during SQL job execution: " + ex.getMessage());
    } finally {
        // Notify job end
        if (listener != null) {
            try {
                listener.onEndScript(statistics, lastError != null);
            } catch (Exception e) {
                log.error(e);
            }
        }
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) ExecutionQueueErrorResponse(org.jkiss.dbeaver.ui.dialogs.exec.ExecutionQueueErrorResponse) SQLQuery(org.jkiss.dbeaver.model.sql.SQLQuery) DBException(org.jkiss.dbeaver.DBException)

Aggregations

IStatus (org.eclipse.core.runtime.IStatus)1423 Status (org.eclipse.core.runtime.Status)500 CoreException (org.eclipse.core.runtime.CoreException)369 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)270 File (java.io.File)169 IOException (java.io.IOException)154 ArrayList (java.util.ArrayList)141 IPath (org.eclipse.core.runtime.IPath)138 IFile (org.eclipse.core.resources.IFile)130 Job (org.eclipse.core.runtime.jobs.Job)123 MultiStatus (org.eclipse.core.runtime.MultiStatus)113 InvocationTargetException (java.lang.reflect.InvocationTargetException)106 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)85 IProject (org.eclipse.core.resources.IProject)84 List (java.util.List)83 Path (org.eclipse.core.runtime.Path)52 Test (org.junit.Test)52 IResource (org.eclipse.core.resources.IResource)51 SubMonitor (org.eclipse.core.runtime.SubMonitor)51 Composite (org.eclipse.swt.widgets.Composite)44