Search in sources :

Example 1 with ValidationError

use of org.knime.core.node.web.ValidationError in project knime-core by knime.

the class TestSubnodeView method testSubnodeViewableModel.

/**
 * Creates and tests the {@link SubnodeViewableModel}
 * @throws Exception
 */
@Test
public void testSubnodeViewableModel() throws Exception {
    initialExecute();
    SubNodeContainer snc = getManager().getNodeContainer(m_subnodeID, SubNodeContainer.class, true);
    SubnodeViewableModel svm = new SubnodeViewableModel(snc, "testView");
    JSONWebNodePage page = svm.getViewRepresentation();
    validateJSONPage(page);
    SubnodeViewValue viewValue = svm.getViewValue();
    assertNotNull("Combined view value should exist", viewValue);
    assertNotNull("Combined view value map should exist", viewValue.getViewValues());
    assertEquals("Combined view value should contain three entries", 3, viewValue.getViewValues().size());
    Map<String, String> changedValueMap = new HashMap<String, String>(3);
    changedValueMap.putAll(viewValue.getViewValues());
    changedValueMap = changeStringInputTo("foo", changedValueMap);
    SubnodeViewValue newViewValue = new SubnodeViewValue();
    newViewValue.setViewValues(changedValueMap);
    ValidationError validationError = svm.validateViewValue(newViewValue);
    assertTrue("Validation error should be instance of CollectionValidationError", validationError instanceof CollectionValidationError);
    Map<String, String> errorMap = ((CollectionValidationError) validationError).getErrorMap();
    assertNotNull("Error map should exist", errorMap);
    changedValueMap.putAll(viewValue.getViewValues());
    changeStringInputTo(CHANGED_URL, changedValueMap);
    selectRowInTable(changedValueMap);
    validationError = svm.validateViewValue(newViewValue);
    assertNull("There should not be any validation errors", validationError);
    svm.loadViewValue(newViewValue, false);
    waitWhileNodeInExecution(m_subnodeID);
    assertTrue("Subnode should be executed.", getManager().getNodeContainer(m_subnodeID).getNodeContainerState().isExecuted());
    validateReexecutionResult();
    svm.discard();
    assertNull("Page should be null after reset", svm.getViewRepresentation());
    assertNull("View value should be null after reset", svm.getViewValue());
}
Also used : HashMap(java.util.HashMap) SubnodeViewableModel(org.knime.core.wizard.SubnodeViewableModel) ValidationError(org.knime.core.node.web.ValidationError) CollectionValidationError(org.knime.core.wizard.SubnodeViewableModel.CollectionValidationError) CollectionValidationError(org.knime.core.wizard.SubnodeViewableModel.CollectionValidationError) JSONWebNodePage(org.knime.js.core.JSONWebNodePage) SubnodeViewValue(org.knime.core.wizard.SubnodeViewValue) Test(org.junit.Test)

Example 2 with ValidationError

use of org.knime.core.node.web.ValidationError in project knime-core by knime.

the class AbstractWizardNodeView method applyTriggered.

/**
 * @param useAsDefault true if changed values are supposed to be applied as new node default, false otherwise
 * @return true if apply was successful, false otherwise
 * @since 3.4
 */
protected boolean applyTriggered(final boolean useAsDefault) {
    if (!viewInteractionPossible() || !checkSettingsChanged()) {
        return true;
    }
    boolean valid = validateCurrentValueInView();
    if (valid) {
        String jsonString = retrieveCurrentValueFromView();
        // compare to not existing or default value @see use of WizardNodeView.EMPTY_OBJECT_STRING
        if (jsonString == null || jsonString.equals("{}")) {
            return false;
        }
        try {
            VAL viewValue = getModel().createEmptyViewValue();
            viewValue.loadFromStream(new ByteArrayInputStream(jsonString.getBytes(Charset.forName("UTF-8"))));
            setLastRetrievedValue(viewValue);
            ValidationError error = getModel().validateViewValue(viewValue);
            if (error != null) {
                showValidationErrorInView(error.getError());
                return false;
            }
            if (getModel() instanceof NodeModel) {
                triggerReExecution(viewValue, useAsDefault, new DefaultReexecutionCallback());
            } else {
                getModel().loadViewValue(viewValue, useAsDefault);
            }
            return true;
        } catch (Exception e) {
            LOGGER.error("Could not set error message or trigger re-execution: " + e.getMessage(), e);
            return false;
        }
    } else {
        return false;
    }
}
Also used : NodeModel(org.knime.core.node.NodeModel) DefaultReexecutionCallback(org.knime.core.node.interactive.DefaultReexecutionCallback) ByteArrayInputStream(java.io.ByteArrayInputStream) ValidationError(org.knime.core.node.web.ValidationError) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 3 with ValidationError

use of org.knime.core.node.web.ValidationError in project knime-core by knime.

the class TestWizardExec_LoadValuesInSubnode method testWizardStepThroughWithSeveralLoopIterations.

@Test
public void testWizardStepThroughWithSeveralLoopIterations() throws Exception {
    final int numLoops = 3;
    final WorkflowManager wfm = getManager();
    assertTrue("Should have new wizard execution", WebResourceController.hasWizardExecution(wfm));
    checkState(m_filterSubnode, InternalNodeContainerState.CONFIGURED);
    WizardExecutionController wizardController = wfm.getWizardExecutionController();
    wizardController.stepFirst();
    waitWhile(wfm, new WizardHold(), -1);
    assertTrue("Should have steps", wizardController.hasCurrentWizardPage());
    checkState(m_colFilterInFilterSubnode, InternalNodeContainerState.EXECUTED);
    WizardPage currentWizardPage = wizardController.getCurrentWizardPage();
    // don't load anything here, just execute to next subnode (all columns included)
    wizardController.stepNext();
    waitWhile(wfm, new WizardHold(), -1);
    checkState(m_noClustersSubnode, InternalNodeContainerState.EXECUTED);
    currentWizardPage = wizardController.getCurrentWizardPage();
    Map<String, String> valueMap = new HashMap<String, String>();
    // setting number of clusters to be found (and loop iterations)
    String intInputID = m_noClustersSubnode.getIndex() + ":0:" + m_intInputInNoClusterSubnode.getIndex();
    valueMap.put(intInputID, "{\"integer\":" + numLoops + "}");
    Map<String, ValidationError> errorMap = wizardController.loadValuesIntoCurrentPage(valueMap);
    assertEquals("Loading number of clusters should not have caused errors", 0, errorMap.size());
    // looping over clusters
    for (int curLoop = 1; curLoop <= numLoops; curLoop++) {
        String stringInputID = m_labelClustersSubnode.getIndex() + ":0:" + m_stringInputInLabelClustersSubnode.getIndex();
        wizardController.stepNext();
        waitWhile(wfm, new WizardHold(), -1);
        checkState(m_labelClustersSubnode, InternalNodeContainerState.EXECUTED);
        checkState(m_loopEndNode, InternalNodeContainerState.CONFIGURED_MARKEDFOREXEC);
        currentWizardPage = wizardController.getCurrentWizardPage();
        assertEquals("Labeling page should have 3 components", 3, currentWizardPage.getPageMap().size());
        assertNotNull("Labeling page should contain string input", currentWizardPage.getPageMap().get(NodeIDSuffix.fromString(stringInputID)));
        valueMap.clear();
        // label for cluster
        valueMap.put(stringInputID, "{\"string\":\"Cluster " + curLoop + "\"}");
        errorMap = wizardController.loadValuesIntoCurrentPage(valueMap);
        assertEquals("Loading cluster label should not have caused errors", 0, errorMap.size());
    }
    // display result of labeling
    wizardController.stepNext();
    waitWhile(wfm, new WizardHold(), -1);
    checkState(m_showClustersSubnode, InternalNodeContainerState.EXECUTED);
    currentWizardPage = wizardController.getCurrentWizardPage();
    assertEquals("Result page should have 2 components", 2, currentWizardPage.getPageMap().size());
    // finish execute
    wizardController.stepNext();
    waitWhile(wfm, new WizardHold(), -1);
    assertFalse("Should have no more pages", wizardController.hasCurrentWizardPage());
    checkState(wfm, InternalNodeContainerState.EXECUTED);
}
Also used : WizardHold(org.knime.core.node.workflow.TestWizardExec_Loop_Simple.WizardHold) HashMap(java.util.HashMap) WizardPage(org.knime.core.node.wizard.page.WizardPage) ValidationError(org.knime.core.node.web.ValidationError) Test(org.junit.Test)

Example 4 with ValidationError

use of org.knime.core.node.web.ValidationError in project knime-core by knime.

the class WebResourceController method validateViewValuesInternal.

/**
 * Validates a given set of serialized view values for a given subnode.
 *
 * @param viewValues the values to validate
 * @param subnodeID the id of the subnode containing the appropriate view nodes
 * @param wizardNodeSet the set of view nodes that the view values correspond to.
 * @return an empty map if validation succeeds, map of errors otherwise
 * @throws IllegalArgumentException if the provided subnode id is <code>null</code>
 * @throws IllegalStateException if there are no nodes with the provided id prefixes in the page or the provided
 *             wizard-node-set doesn't contain the required wizard nodes
 */
@SuppressWarnings({ "rawtypes" })
protected Map<String, ValidationError> validateViewValuesInternal(final Map<String, String> viewValues, final NodeID subnodeID, final Map<NodeID, NativeNodeContainer> wizardNodeSet) {
    if (subnodeID == null) {
        throw new IllegalArgumentException("No node ID supplied for validating view values of wizard page");
    }
    WorkflowManager manager = m_manager;
    assert manager.isLockedByCurrentThread();
    Map<String, ValidationError> resultMap = new LinkedHashMap<>();
    for (Map.Entry<String, String> entry : viewValues.entrySet()) {
        NodeID.NodeIDSuffix suffix = NodeID.NodeIDSuffix.fromString(entry.getKey());
        NodeID id = suffix.prependParent(manager.getProjectWFM().getID());
        CheckUtils.checkState(id.hasPrefix(subnodeID), "The wizard page content for ID %s (suffix %s) does not belong to the current Component (ID %s)", id, entry.getKey(), subnodeID);
        NativeNodeContainer wizardNode = wizardNodeSet.get(id);
        CheckUtils.checkState(wizardNode != null, "No wizard node with ID %s in Component, valid IDs are: " + "%s", id, ConvenienceMethods.getShortStringFrom(wizardNodeSet.entrySet(), 10));
        ValidationError validationError = null;
        try {
            if (wizardNode.getNodeModel() instanceof WizardNode) {
                validationError = validateViewValueForWizardNode((WizardNode) wizardNode.getNodeModel(), entry.getValue());
            } else if (wizardNode.getNode().getFactory() instanceof WizardPageContribution) {
                validationError = ((WizardPageContribution) wizardNode.getNode().getFactory()).validateViewValue(wizardNode, entry.getValue()).map(ValidationError::new).orElse(null);
            }
        } catch (Exception e) {
            // NOSONAR
            validationError = new ValidationError("An unexpected error occurred while validating the view value: " + entry.getValue() + ": \n" + e.getMessage());
        }
        if (validationError != null) {
            resultMap.put(entry.getKey(), validationError);
        }
    }
    if (!resultMap.isEmpty()) {
        return resultMap;
    }
    return Collections.emptyMap();
}
Also used : WizardNode(org.knime.core.node.wizard.WizardNode) NodeIDSuffix(org.knime.core.node.workflow.NodeID.NodeIDSuffix) WizardPageContribution(org.knime.core.node.wizard.page.WizardPageContribution) CanceledExecutionException(org.knime.core.node.CanceledExecutionException) IOException(java.io.IOException) ViewRequestHandlingException(org.knime.core.node.interactive.ViewRequestHandlingException) LinkedHashMap(java.util.LinkedHashMap) ValidationError(org.knime.core.node.web.ValidationError) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 5 with ValidationError

use of org.knime.core.node.web.ValidationError in project knime-core by knime.

the class TestSubnodeView method testValidationError.

/**
 * Tests if changing the value of one of the nodes to an invalid string causes the correct validation error
 * @throws Exception
 */
@Test
public void testValidationError() throws Exception {
    initialExecute();
    Map<String, String> valueMap = changeStringInputTo("foo", buildValueMap());
    Map<String, ValidationError> errorMap = m_spm.validateViewValues(valueMap, m_subnodeID);
    assertNotNull("Error map should exist", errorMap);
    assertEquals("Error map should contain one entry", 1, errorMap.size());
    ValidationError error = errorMap.get(m_stringInputID.toString());
    assertNotNull("Error for string input should exist", error);
    assertEquals("Error for string input incorrect", "The given input 'foo' is not a valid URL", error.getError());
}
Also used : ValidationError(org.knime.core.node.web.ValidationError) CollectionValidationError(org.knime.core.wizard.SubnodeViewableModel.CollectionValidationError) Test(org.junit.Test)

Aggregations

ValidationError (org.knime.core.node.web.ValidationError)9 ByteArrayInputStream (java.io.ByteArrayInputStream)4 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 LinkedHashMap (java.util.LinkedHashMap)3 Map (java.util.Map)3 Test (org.junit.Test)3 WebViewContent (org.knime.core.node.web.WebViewContent)3 WizardNode (org.knime.core.node.wizard.WizardNode)3 NodeIDSuffix (org.knime.core.node.workflow.NodeID.NodeIDSuffix)3 InvalidSettingsException (org.knime.core.node.InvalidSettingsException)2 CollectionValidationError (org.knime.core.wizard.SubnodeViewableModel.CollectionValidationError)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 CanceledExecutionException (org.knime.core.node.CanceledExecutionException)1 NodeModel (org.knime.core.node.NodeModel)1 DefaultReexecutionCallback (org.knime.core.node.interactive.DefaultReexecutionCallback)1 ViewRequestHandlingException (org.knime.core.node.interactive.ViewRequestHandlingException)1 WizardPage (org.knime.core.node.wizard.page.WizardPage)1 WizardPageContribution (org.knime.core.node.wizard.page.WizardPageContribution)1 WizardHold (org.knime.core.node.workflow.TestWizardExec_Loop_Simple.WizardHold)1