Search in sources :

Example 1 with ExecutionMonitor

use of org.knime.core.node.ExecutionMonitor in project knime-core by knime.

the class LoadMetaNodeTemplateRunnable method run.

/**
 * {@inheritDoc}
 */
@SuppressWarnings("null")
@Override
public void run(final IProgressMonitor pm) {
    try {
        // create progress monitor
        ProgressHandler progressHandler = new ProgressHandler(pm, 101, "Loading metanode template...");
        final CheckCancelNodeProgressMonitor progressMonitor = new CheckCancelNodeProgressMonitor(pm);
        progressMonitor.addProgressListener(progressHandler);
        URI sourceURI = m_templateKNIMEFolder.toURI();
        File parentFile = ResolverUtil.resolveURItoLocalOrTempFile(sourceURI, pm);
        if (pm.isCanceled()) {
            throw new InterruptedException();
        }
        Display d = Display.getDefault();
        GUIWorkflowLoadHelper loadHelper = new GUIWorkflowLoadHelper(d, parentFile.getName(), sourceURI, parentFile, null, true);
        TemplateNodeContainerPersistor loadPersistor = loadHelper.createTemplateLoadPersistor(parentFile, sourceURI);
        MetaNodeLinkUpdateResult loadResult = new MetaNodeLinkUpdateResult("Template from \"" + sourceURI + "\"");
        m_parentWFM.load(loadPersistor, loadResult, new ExecutionMonitor(progressMonitor), false);
        m_result = loadResult;
        if (pm.isCanceled()) {
            throw new InterruptedException();
        }
        pm.subTask("Finished.");
        pm.done();
        final IStatus status = createStatus(m_result, !m_result.getGUIMustReportDataLoadErrors());
        final String message;
        switch(status.getSeverity()) {
            case IStatus.OK:
                message = "No problems during load.";
                break;
            case IStatus.WARNING:
                message = "Warnings during load";
                logPreseveLineBreaks("Warnings during load: " + m_result.getFilteredError("", LoadResultEntryType.Warning), false);
                break;
            default:
                message = "Errors during load";
                logPreseveLineBreaks("Errors during load: " + m_result.getFilteredError("", LoadResultEntryType.Warning), true);
        }
        Display.getDefault().asyncExec(new Runnable() {

            @Override
            public void run() {
                // will not open if status is OK.
                ErrorDialog.openError(Display.getDefault().getActiveShell(), "Workflow Load", message, status);
            }
        });
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        // IMPORTANT: Remove the reference to the file and the
        // editor!!! Otherwise the memory cannot be freed later
        m_parentWFM = null;
        m_templateKNIMEFolder = null;
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) URI(java.net.URI) TemplateNodeContainerPersistor(org.knime.core.node.workflow.TemplateNodeContainerPersistor) MetaNodeLinkUpdateResult(org.knime.core.node.workflow.WorkflowPersistor.MetaNodeLinkUpdateResult) ExecutionMonitor(org.knime.core.node.ExecutionMonitor) File(java.io.File) Display(org.eclipse.swt.widgets.Display)

Example 2 with ExecutionMonitor

use of org.knime.core.node.ExecutionMonitor in project knime-core by knime.

the class RepositoryFactory method loadMetaNode.

private static WorkflowManagerUI loadMetaNode(final String pluginId, final String workflowDir) {
    LOGGER.debug("found pre-installed template " + workflowDir);
    Bundle bundle = Platform.getBundle(pluginId);
    URL url = FileLocator.find(bundle, new Path(workflowDir), null);
    if (url != null) {
        try {
            File f = new File(FileLocator.toFileURL(url).getFile());
            LOGGER.debug("meta node template name: " + f.getName());
            WorkflowLoadHelper loadHelper = new WorkflowLoadHelper(true) {

                /**
                 * {@inheritDoc}
                 */
                @Override
                public String getDotKNIMEFileName() {
                    return WorkflowPersistor.WORKFLOW_FILE;
                }
            };
            // don't lock workflow dir
            FileWorkflowPersistor persistor = WorkflowManager.createLoadPersistor(f, loadHelper);
            WorkflowManager metaNode = WorkflowManager.META_NODE_ROOT.load(persistor, new ExecutionMonitor(), false).getWorkflowManager();
            return WorkflowManagerWrapper.wrap(metaNode);
        } catch (CanceledExecutionException cee) {
            LOGGER.error("Unexpected canceled execution exception", cee);
        } catch (Exception e) {
            LOGGER.error("Failed to load meta workflow repository", e);
        }
    }
    return null;
}
Also used : Path(org.eclipse.core.runtime.Path) CanceledExecutionException(org.knime.core.node.CanceledExecutionException) Bundle(org.osgi.framework.Bundle) WorkflowManager(org.knime.core.node.workflow.WorkflowManager) WorkflowLoadHelper(org.knime.core.node.workflow.WorkflowLoadHelper) ExecutionMonitor(org.knime.core.node.ExecutionMonitor) File(java.io.File) URL(java.net.URL) CanceledExecutionException(org.knime.core.node.CanceledExecutionException) FileWorkflowPersistor(org.knime.core.node.workflow.FileWorkflowPersistor)

Example 3 with ExecutionMonitor

use of org.knime.core.node.ExecutionMonitor in project knime-core by knime.

the class AbstractSaveRunnable method run.

@Override
public final void run(final IProgressMonitor pm) {
    File workflowDir = getSaveLocation();
    try {
        final WorkflowManager wfm = m_editor.getWorkflowManager().get();
        ProgressHandler progressHandler = new ProgressHandler(pm, wfm.getNodeContainers().size(), "Saving workflow... (cannot be canceled)");
        final CheckCancelNodeProgressMonitor progressMonitor = new CheckCancelNodeProgressMonitor(pm);
        progressMonitor.addProgressListener(progressHandler);
        final ExecutionMonitor exec = new ExecutionMonitor(progressMonitor);
        save(wfm, exec);
        // the refresh used to take place in WorkflowEditor#saveTo but
        // was moved to this runnable as part of bug fix 3028
        IResource r = KnimeResourceUtil.getResourceForURI(workflowDir.toURI());
        if (r != null) {
            String pName = r.getName();
            pm.setTaskName("Refreshing " + pName + "...");
            r.refreshLocal(IResource.DEPTH_INFINITE, pm);
        }
    } catch (FileNotFoundException fnfe) {
        m_logger.fatal("File not found", fnfe);
        m_exceptionMessage.append("File access problems: " + fnfe.getMessage());
        m_monitor.setCanceled(true);
    } catch (IOException ioe) {
        if (new File(workflowDir, WorkflowPersistor.WORKFLOW_FILE).length() == 0) {
            m_logger.info("New workflow created.");
        } else {
            m_logger.error("Could not save workflow: " + workflowDir.getName(), ioe);
            m_exceptionMessage.append("File access problems: " + ioe.getMessage());
            m_monitor.setCanceled(true);
        }
    } catch (CanceledExecutionException cee) {
        m_logger.info("Canceled saving workflow: " + workflowDir.getName());
        m_exceptionMessage.append("Saving workflow" + " was canceled.");
        m_monitor.setCanceled(true);
    } catch (Exception e) {
        m_logger.error("Could not save workflow", e);
        m_exceptionMessage.append("Could not save workflow: " + e.getMessage());
        m_monitor.setCanceled(true);
    } finally {
        pm.subTask("Finished.");
        pm.done();
        m_editor = null;
        m_exceptionMessage = null;
        m_monitor = null;
    }
}
Also used : CanceledExecutionException(org.knime.core.node.CanceledExecutionException) WorkflowManager(org.knime.core.node.workflow.WorkflowManager) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) ExecutionMonitor(org.knime.core.node.ExecutionMonitor) File(java.io.File) IResource(org.eclipse.core.resources.IResource) CanceledExecutionException(org.knime.core.node.CanceledExecutionException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) LockFailedException(org.knime.core.util.LockFailedException)

Example 4 with ExecutionMonitor

use of org.knime.core.node.ExecutionMonitor in project knime-core by knime.

the class LoadWorkflowRunnable method run.

/**
 * {@inheritDoc}
 */
@Override
public void run(final IProgressMonitor pm) {
    // indicates whether to create an empty workflow
    // this is done if the file is empty
    boolean createEmptyWorkflow = false;
    // name of workflow will be null (uses directory name then)
    String name = null;
    m_throwable = null;
    try {
        // create progress monitor
        ProgressHandler progressHandler = new ProgressHandler(pm, 101, "Loading workflow...");
        final CheckCancelNodeProgressMonitor progressMonitor = new CheckCancelNodeProgressMonitor(pm);
        progressMonitor.addProgressListener(progressHandler);
        File workflowDirectory = m_workflowFile.getParentFile();
        Display d = Display.getDefault();
        GUIWorkflowLoadHelper loadHelper = new GUIWorkflowLoadHelper(d, workflowDirectory.getName(), m_mountpointURI, workflowDirectory, m_mountpointRoot);
        final WorkflowLoadResult result = WorkflowManager.loadProject(workflowDirectory, new ExecutionMonitor(progressMonitor), loadHelper);
        final WorkflowManager wm = result.getWorkflowManager();
        m_editor.setWorkflowManager(wm);
        pm.subTask("Finished.");
        pm.done();
        if (wm.isDirty()) {
            m_editor.markDirty();
        }
        final IStatus status = createStatus(result, !result.getGUIMustReportDataLoadErrors());
        String message;
        switch(status.getSeverity()) {
            case IStatus.OK:
                message = "No problems during load.";
                break;
            case IStatus.WARNING:
                message = "Warnings during load";
                logPreseveLineBreaks("Warnings during load: " + result.getFilteredError("", LoadResultEntryType.Warning), false);
                break;
            default:
                message = "Errors during load";
                logPreseveLineBreaks("Errors during load: " + result.getFilteredError("", LoadResultEntryType.Warning), true);
        }
        if (!status.isOK()) {
            showLoadErrorDialog(result, status, message);
        }
        final List<NodeID> linkedMNs = wm.getLinkedMetaNodes(true);
        if (!linkedMNs.isEmpty()) {
            final WorkflowEditor editor = m_editor;
            m_editor.addAfterOpenRunnable(new Runnable() {

                @Override
                public void run() {
                    postLoadCheckForMetaNodeUpdates(editor, wm, linkedMNs);
                }
            });
        }
    } catch (FileNotFoundException fnfe) {
        m_throwable = fnfe;
        LOGGER.fatal("File not found", fnfe);
    } catch (IOException ioe) {
        m_throwable = ioe;
        if (m_workflowFile.length() == 0) {
            LOGGER.info("New workflow created.");
            // this is the only place to set this flag to true: we have an
            // empty workflow file, i.e. a new project was created
            // bugfix 1555: if an exception is thrown DO NOT create empty
            // workflow
            createEmptyWorkflow = true;
        } else {
            LOGGER.error("Could not load workflow from: " + m_workflowFile.getName(), ioe);
        }
    } catch (InvalidSettingsException ise) {
        LOGGER.error("Could not load workflow from: " + m_workflowFile.getName(), ise);
        m_throwable = ise;
    } catch (UnsupportedWorkflowVersionException uve) {
        m_loadingCanceledMessage = INCOMPATIBLE_VERSION_MSG;
        LOGGER.info(m_loadingCanceledMessage, uve);
        m_editor.setWorkflowManager(null);
    } catch (CanceledExecutionException cee) {
        m_loadingCanceledMessage = "Canceled loading workflow: " + m_workflowFile.getParentFile().getName();
        LOGGER.info(m_loadingCanceledMessage, cee);
        m_editor.setWorkflowManager(null);
    } catch (LockFailedException lfe) {
        StringBuilder error = new StringBuilder();
        error.append("Unable to load workflow \"");
        error.append(m_workflowFile.getParentFile().getName());
        if (m_workflowFile.getParentFile().exists()) {
            error.append("\"\nIt is in use by another user/instance.");
        } else {
            error.append("\"\nLocation does not exist.");
        }
        m_loadingCanceledMessage = error.toString();
        LOGGER.info(m_loadingCanceledMessage, lfe);
        m_editor.setWorkflowManager(null);
    } catch (Throwable e) {
        m_throwable = e;
        LOGGER.error("Workflow could not be loaded. " + e.getMessage(), e);
        m_editor.setWorkflowManager(null);
    } finally {
        // (empty workflow file)
        if (createEmptyWorkflow) {
            WorkflowCreationHelper creationHelper = new WorkflowCreationHelper();
            WorkflowContext.Factory fac = new WorkflowContext.Factory(m_workflowFile.getParentFile());
            fac.setMountpointRoot(m_mountpointRoot);
            fac.setMountpointURI(m_mountpointURI);
            creationHelper.setWorkflowContext(fac.createContext());
            m_editor.setWorkflowManager(WorkflowManager.ROOT.createAndAddProject(name, creationHelper));
            // save empty project immediately
            // bugfix 1341 -> see WorkflowEditor line 1294
            // (resource delta visitor movedTo)
            Display.getDefault().syncExec(new Runnable() {

                @Override
                public void run() {
                    m_editor.doSave(new NullProgressMonitor());
                }
            });
            m_editor.setIsDirty(false);
        }
        // IMPORTANT: Remove the reference to the file and the
        // editor!!! Otherwise the memory cannot be freed later
        m_editor = null;
        m_workflowFile = null;
        m_mountpointRoot = null;
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) IStatus(org.eclipse.core.runtime.IStatus) UnsupportedWorkflowVersionException(org.knime.core.node.workflow.UnsupportedWorkflowVersionException) WorkflowManager(org.knime.core.node.workflow.WorkflowManager) FileNotFoundException(java.io.FileNotFoundException) WorkflowCreationHelper(org.knime.core.node.workflow.WorkflowCreationHelper) CanceledExecutionException(org.knime.core.node.CanceledExecutionException) NodeID(org.knime.core.node.workflow.NodeID) ExecutionMonitor(org.knime.core.node.ExecutionMonitor) LockFailedException(org.knime.core.util.LockFailedException) WorkflowContext(org.knime.core.node.workflow.WorkflowContext) IOException(java.io.IOException) WorkflowLoadResult(org.knime.core.node.workflow.WorkflowPersistor.WorkflowLoadResult) InvalidSettingsException(org.knime.core.node.InvalidSettingsException) File(java.io.File) Display(org.eclipse.swt.widgets.Display)

Example 5 with ExecutionMonitor

use of org.knime.core.node.ExecutionMonitor in project knime-core by knime.

the class FileWorkflowPersistor method saveContent.

/**
 * @param wm The WFM to save.
 * @param preFilledSettings The settings eventually written to workflow.knime (or workflow.knime.encrypted).
 * For workflows it contains the version number, cipher, template infos etc. The name of the setting defines the
 * output file name (so it's important!)
 * @param rawWorkflowDirRef To save to.
 * @param execMon ...
 * @param saveHelper ...
 * @throws IOException ...
 * @throws CanceledExecutionException ...
 * @throws LockFailedException ...
 */
private static void saveContent(final WorkflowManager wm, final NodeSettings preFilledSettings, final ReferencedFile rawWorkflowDirRef, final ExecutionMonitor execMon, final WorkflowSaveHelper saveHelper) throws IOException, CanceledExecutionException, LockFailedException {
    ReferencedFile workflowDirRef = rawWorkflowDirRef;
    Role r = wm.getTemplateInformation().getRole();
    final String fName = preFilledSettings.getKey();
    if (!workflowDirRef.fileLockRootForVM()) {
        throw new LockFailedException("Can't write workflow to \"" + workflowDirRef + "\" because the directory can't be locked");
    }
    try {
        final ReferencedFile nodeContainerDirectory = wm.getNodeContainerDirectory();
        final ReferencedFile autoSaveDirectory = wm.getAutoSaveDirectory();
        if (!saveHelper.isAutoSave() && workflowDirRef.equals(nodeContainerDirectory)) {
            if (!nodeContainerDirectory.isDirty()) {
                return;
            } else {
                // update variable assignment to do changes on member
                workflowDirRef = nodeContainerDirectory;
                // delete "old" node directories if not saving to the working
                // directory -- do this before saving the nodes (dirs newly created)
                WorkflowManager.deleteObsoleteNodeDirs(nodeContainerDirectory.getDeletedNodesFileLocations());
            }
        }
        if (saveHelper.isAutoSave() && workflowDirRef.equals(autoSaveDirectory)) {
            if (!autoSaveDirectory.isDirty()) {
                return;
            } else {
                workflowDirRef = autoSaveDirectory;
                WorkflowManager.deleteObsoleteNodeDirs(autoSaveDirectory.getDeletedNodesFileLocations());
            }
        }
        File workflowDir = workflowDirRef.getFile();
        workflowDir.mkdirs();
        if (!workflowDir.isDirectory()) {
            throw new IOException("Unable to create or write directory \": " + workflowDir + "\"");
        }
        saveWorkflowName(preFilledSettings, wm.getNameField());
        saveAuthorInformation(wm.getAuthorInformation(), preFilledSettings);
        saveWorkflowCipher(preFilledSettings, wm.getWorkflowCipher());
        FileNodeContainerMetaPersistor.save(preFilledSettings, wm, workflowDirRef);
        saveWorkflowVariables(wm, preFilledSettings);
        saveCredentials(wm, preFilledSettings);
        saveWorkflowAnnotations(wm, preFilledSettings);
        NodeSettingsWO nodesSettings = saveSettingsForNodes(preFilledSettings);
        Collection<NodeContainer> nodes = wm.getNodeContainers();
        double progRatio = 1.0 / (nodes.size() + 1);
        for (NodeContainer nextNode : nodes) {
            int id = nextNode.getID().getIndex();
            ExecutionMonitor subExec = execMon.createSubProgress(progRatio);
            execMon.setMessage(nextNode.getNameWithID());
            NodeSettingsWO sub = nodesSettings.addNodeSettings("node_" + id);
            saveNodeContainer(sub, workflowDirRef, nextNode, subExec, saveHelper);
            subExec.setProgress(1.0);
        }
        execMon.setMessage("connection information");
        NodeSettingsWO connSettings = saveSettingsForConnections(preFilledSettings);
        int connectionNumber = 0;
        for (ConnectionContainer cc : wm.getConnectionContainers()) {
            NodeSettingsWO nextConnectionConfig = connSettings.addNodeSettings("connection_" + connectionNumber);
            saveConnection(nextConnectionConfig, cc);
            connectionNumber += 1;
        }
        int inCount = wm.getNrInPorts();
        NodeSettingsWO inPortsSetts = inCount > 0 ? saveInPortsSetting(preFilledSettings) : null;
        NodeSettingsWO inPortsSettsEnum = null;
        if (inPortsSetts != null) {
            // TODO actually not neccessary to save the class name
            saveInportsBarUIInfoClassName(inPortsSetts, wm.getInPortsBarUIInfo());
            saveInportsBarUIInfoSettings(inPortsSetts, wm.getInPortsBarUIInfo());
            inPortsSettsEnum = saveInPortsEnumSetting(inPortsSetts);
        }
        for (int i = 0; i < inCount; i++) {
            NodeSettingsWO sPort = saveInPortSetting(inPortsSettsEnum, i);
            saveInPort(sPort, wm, i);
        }
        int outCount = wm.getNrOutPorts();
        NodeSettingsWO outPortsSetts = outCount > 0 ? saveOutPortsSetting(preFilledSettings) : null;
        NodeSettingsWO outPortsSettsEnum = null;
        if (outPortsSetts != null) {
            saveOutportsBarUIInfoClassName(outPortsSetts, wm.getOutPortsBarUIInfo());
            saveOutportsBarUIInfoSettings(outPortsSetts, wm.getOutPortsBarUIInfo());
            outPortsSettsEnum = saveOutPortsEnumSetting(outPortsSetts);
        }
        for (int i = 0; i < outCount; i++) {
            NodeSettingsWO singlePort = saveOutPortSetting(outPortsSettsEnum, i);
            saveOutPort(singlePort, wm, i);
        }
        saveEditorUIInformation(wm, preFilledSettings);
        File workflowFile = new File(workflowDir, fName);
        String toBeDeletedFileName = Role.Template.equals(r) ? TEMPLATE_FILE : WORKFLOW_FILE;
        new File(workflowDir, toBeDeletedFileName).delete();
        new File(workflowDir, WorkflowCipher.getCipherFileName(toBeDeletedFileName)).delete();
        OutputStream os = new FileOutputStream(workflowFile);
        os = wm.getDirectNCParent().cipherOutput(os);
        preFilledSettings.saveToXML(os);
        if (saveHelper.isSaveData()) {
            File saveWithDataFile = new File(workflowDir, SAVED_WITH_DATA_FILE);
            BufferedWriter o = new BufferedWriter(new FileWriter(saveWithDataFile));
            o.write("Do not delete this file!");
            o.newLine();
            o.write("This file serves to indicate that the workflow was written as part of the usual save " + "routine (not exported).");
            o.newLine();
            o.newLine();
            o.write("Workflow was last saved by user ");
            o.write(System.getProperty("user.name"));
            o.write(" on " + new Date());
            o.close();
        }
        if (saveHelper.isAutoSave() && autoSaveDirectory == null) {
            wm.setAutoSaveDirectory(workflowDirRef);
        }
        if (!saveHelper.isAutoSave() && nodeContainerDirectory == null) {
            wm.setNodeContainerDirectory(workflowDirRef);
        }
        NodeContainerState wmState = wm.getNodeContainerState();
        // non remote executions
        boolean isExecutingLocally = wmState.isExecutionInProgress() && !wmState.isExecutingRemotely();
        if (workflowDirRef.equals(nodeContainerDirectory) && !isExecutingLocally) {
            wm.unsetDirty();
        }
        workflowDirRef.setDirty(isExecutingLocally);
        execMon.setProgress(1.0);
    } finally {
        workflowDirRef.fileUnlockRootForVM();
    }
}
Also used : LockFailedException(org.knime.core.util.LockFailedException) NodeSettingsWO(org.knime.core.node.NodeSettingsWO) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileWriter(java.io.FileWriter) IOException(java.io.IOException) ReferencedFile(org.knime.core.internal.ReferencedFile) Date(java.util.Date) BufferedWriter(java.io.BufferedWriter) Role(org.knime.core.node.workflow.MetaNodeTemplateInformation.Role) FileOutputStream(java.io.FileOutputStream) ExecutionMonitor(org.knime.core.node.ExecutionMonitor) ReferencedFile(org.knime.core.internal.ReferencedFile) File(java.io.File)

Aggregations

ExecutionMonitor (org.knime.core.node.ExecutionMonitor)160 BufferedDataTable (org.knime.core.node.BufferedDataTable)50 DataTableSpec (org.knime.core.data.DataTableSpec)43 DataRow (org.knime.core.data.DataRow)39 DataCell (org.knime.core.data.DataCell)35 CanceledExecutionException (org.knime.core.node.CanceledExecutionException)35 Test (org.junit.Test)33 InvalidSettingsException (org.knime.core.node.InvalidSettingsException)33 File (java.io.File)29 IOException (java.io.IOException)25 PortObject (org.knime.core.node.port.PortObject)25 ColumnRearranger (org.knime.core.data.container.ColumnRearranger)23 DataColumnSpec (org.knime.core.data.DataColumnSpec)21 RowKey (org.knime.core.data.RowKey)20 ArrayList (java.util.ArrayList)19 WorkflowLoadResult (org.knime.core.node.workflow.WorkflowPersistor.WorkflowLoadResult)17 BufferedDataContainer (org.knime.core.node.BufferedDataContainer)16 ExecutionException (java.util.concurrent.ExecutionException)14 ExecutionContext (org.knime.core.node.ExecutionContext)13 FileOutputStream (java.io.FileOutputStream)12