Search in sources :

Example 1 with Type

use of org.knime.core.node.workflow.FlowVariable.Type in project knime-core by knime.

the class OutFieldsTableModel method validateJavaTypeColumn.

/**
 * Validate java type in the given row.
 * @param row the row to check
 * @return error message if error occurs
 */
@SuppressWarnings("rawtypes")
private String validateJavaTypeColumn(final int row) {
    Object value = this.getValueAt(row, Column.JAVA_TYPE);
    if (null == value) {
        return "Please select a value";
    }
    if (value instanceof JavaToDataCellConverterFactory) {
        if (getValueAt(row, Column.FIELD_TYPE) == FieldType.FlowVariable) {
            return "Cannot use DataCell converters for flow variables.";
        }
    } else if (value instanceof String) {
        final String id = (String) value;
        final Optional<JavaToDataCellConverterFactory<?>> factory = ConverterUtil.getJavaToDataCellConverterFactory(id);
        return factory.isPresent() ? null : "Converter factory " + id + " was not found.";
    } else if (value instanceof Class) {
        Class javaType = (Class) value;
        Object outType = getValueAt(row, Column.DATA_TYPE);
        if (outType instanceof DataType) {
            DataType elemType = (DataType) outType;
            boolean isCollection = (Boolean) getValueAt(row, Column.IS_COLLECTION);
            DataType dataType = isCollection ? ListCell.getCollectionType(elemType) : elemType;
            final Collection<JavaToDataCellConverterFactory<?>> factories = ConverterUtil.getFactoriesForDestinationType(dataType);
            if (factories.isEmpty()) {
                return "The java type \"" + javaType.getSimpleName() + "\" is not supported for output columns.";
            }
            if (dataType.isCollectionType() && !javaType.isArray()) {
                return "Please choose an java array for collection types.";
            }
            if (!dataType.isCollectionType() && javaType.isArray()) {
                return "An array cannot be written to a non collection column";
            }
        } else if (outType instanceof Type) {
            Type type = (Type) outType;
            TypeConverter typeConversion = TypeProvider.getDefault().getTypeConverter(type);
            if (!typeConversion.canProvideJavaType(javaType)) {
                return "The java type \"" + javaType.getSimpleName() + "\" is not supported.";
            }
        }
    } else {
        return "Cannot find class " + value.toString();
    }
    // no error found
    return null;
}
Also used : TypeConverter(org.knime.base.node.jsnippet.type.flowvar.TypeConverter) FieldType(org.knime.base.node.jsnippet.util.field.JavaField.FieldType) Type(org.knime.core.node.workflow.FlowVariable.Type) DataType(org.knime.core.data.DataType) Optional(java.util.Optional) DataType(org.knime.core.data.DataType) JavaToDataCellConverterFactory(org.knime.core.data.convert.datacell.JavaToDataCellConverterFactory)

Example 2 with Type

use of org.knime.core.node.workflow.FlowVariable.Type in project knime-core by knime.

the class OutFieldsTableModel method getAllowedJavaTypes.

/**
 * {@inheritDoc}
 */
@Override
public Object[] getAllowedJavaTypes(final int row) {
    Object input = getValueAt(row, Column.DATA_TYPE);
    if (input instanceof DataType) {
        DataType elemType = (DataType) input;
        boolean isCollection = (Boolean) getValueAt(row, Column.IS_COLLECTION);
        final DataType dataType = isCollection ? ListCell.getCollectionType(elemType) : elemType;
        final Collection<JavaToDataCellConverterFactory<?>> factories = ConverterUtil.getFactoriesForDestinationType(dataType).stream().filter(factory -> JavaSnippet.getBuildPathFromCache(factory.getIdentifier()) != null).collect(Collectors.toList());
        return factories.toArray(new Object[factories.size()]);
    } else if (input instanceof Type) {
        Type type = (Type) input;
        TypeConverter typeConversion = TypeProvider.getDefault().getTypeConverter(type);
        return typeConversion.canCreatedFromJavaTypes();
    } else {
        return new Class[] { String.class };
    }
}
Also used : Array(java.lang.reflect.Array) ListCell(org.knime.core.data.collection.ListCell) Collection(java.util.Collection) FlowVariable(org.knime.core.node.workflow.FlowVariable) TypeConverter(org.knime.base.node.jsnippet.type.flowvar.TypeConverter) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) ArrayToCollectionConverterFactory(org.knime.core.data.convert.datacell.ArrayToCollectionConverterFactory) FieldType(org.knime.base.node.jsnippet.util.field.JavaField.FieldType) JavaToDataCellConverterFactory(org.knime.core.data.convert.datacell.JavaToDataCellConverterFactory) TypeProvider(org.knime.base.node.jsnippet.type.TypeProvider) Type(org.knime.core.node.workflow.FlowVariable.Type) JavaSnippet(org.knime.base.node.jsnippet.JavaSnippet) ConverterUtil(org.knime.base.node.jsnippet.type.ConverterUtil) DataColumnSpec(org.knime.core.data.DataColumnSpec) Map(java.util.Map) Optional(java.util.Optional) DataType(org.knime.core.data.DataType) TypeConverter(org.knime.base.node.jsnippet.type.flowvar.TypeConverter) FieldType(org.knime.base.node.jsnippet.util.field.JavaField.FieldType) Type(org.knime.core.node.workflow.FlowVariable.Type) DataType(org.knime.core.data.DataType) DataType(org.knime.core.data.DataType) JavaToDataCellConverterFactory(org.knime.core.data.convert.datacell.JavaToDataCellConverterFactory)

Example 3 with Type

use of org.knime.core.node.workflow.FlowVariable.Type in project knime-core by knime.

the class JavaSnippetCellFactory method getCells.

/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
@Override
public DataCell[] getCells(final DataRow row) {
    try {
        if (null == m_jsnippet) {
            m_jsnippet = m_snippet.createSnippetInstance();
            // populate the fields in the m_jsnippet that are constant
            // across the rows.
            Field[] fs = m_jsnippet.getClass().getSuperclass().getDeclaredFields();
            for (Field field : fs) {
                if (field.getName().equals("m_flowVars")) {
                    field.setAccessible(true);
                    field.set(m_jsnippet, m_flowVars);
                }
                if (field.getName().equals(JavaSnippet.ROWCOUNT)) {
                    field.setAccessible(true);
                    field.set(m_jsnippet, m_rowCount);
                }
            }
        }
        // populate data structure with the input cells
        Map<String, Cell> cellsMap = createCellsMap(row);
        if (null == m_columns) {
            m_columns = new ArrayList<>();
            m_columns.addAll(cellsMap.keySet());
        }
        Field[] fs = m_jsnippet.getClass().getSuperclass().getDeclaredFields();
        for (Field field : fs) {
            if (field.getName().equals("m_cellsMap")) {
                field.setAccessible(true);
                field.set(m_jsnippet, cellsMap);
            }
            if (field.getName().equals("m_cells")) {
                field.setAccessible(true);
                List<Cell> cells = new ArrayList<>();
                cells.addAll(cellsMap.values());
                field.set(m_jsnippet, cells);
            }
            if (field.getName().equals("m_columns")) {
                field.setAccessible(true);
                field.set(m_jsnippet, m_columns);
            }
            if (field.getName().equals("m_inSpec")) {
                field.setAccessible(true);
                field.set(m_jsnippet, m_spec);
            }
            if (field.getName().equals(JavaSnippet.ROWID)) {
                field.setAccessible(true);
                field.set(m_jsnippet, row.getKey().getString());
            }
            if (field.getName().equals(JavaSnippet.ROWINDEX)) {
                field.setAccessible(true);
                field.set(m_jsnippet, m_rowIndex);
            }
        }
        // populate the system input column fields with data
        for (InCol inCol : m_snippet.getSystemFields().getInColFields()) {
            Field field = m_jsnippet.getClass().getField(inCol.getJavaName());
            final DataCell cell = row.getCell(m_spec.findColumnIndex(inCol.getKnimeName()));
            if (cell.isMissing()) {
                field.set(m_jsnippet, null);
                continue;
            }
            // Get the converter factory for this column
            final Optional<DataCellToJavaConverterFactory<?, ?>> factory = ConverterUtil.getDataCellToJavaConverterFactory(inCol.getConverterFactoryId());
            if (!factory.isPresent()) {
                throw new RuntimeException("Missing converter factory with ID: " + inCol.getConverterFactoryId());
            }
            final Object converted = factory.get().create().convertUnsafe(cell);
            field.set(m_jsnippet, converted);
        }
        // reset the system output fields to null (see also bug 3781)
        for (OutCol outCol : m_snippet.getSystemFields().getOutColFields()) {
            Field field = m_jsnippet.getClass().getField(outCol.getJavaName());
            field.set(m_jsnippet, null);
        }
        // populate the system input flow variable fields with data
        for (InVar inCol : m_snippet.getSystemFields().getInVarFields()) {
            Field field = m_jsnippet.getClass().getField(inCol.getJavaName());
            Object v = m_flowVars.getValueOfType(inCol.getKnimeName(), inCol.getJavaType());
            field.set(m_jsnippet, v);
        }
    } catch (Exception e) {
        // re-throw exception
        throw new RuntimeException(e);
    }
    try {
        // evaluate user script
        m_jsnippet.snippet();
    } catch (Throwable thr) {
        if (thr instanceof Abort) {
            StringBuilder builder = new StringBuilder("Calculation aborted: ");
            String message = thr.getMessage();
            builder.append(message == null ? "<no details>" : message);
            throw new RuntimeException(builder.toString(), thr);
        } else {
            Integer lineNumber = null;
            for (StackTraceElement ste : thr.getStackTrace()) {
                if (ste.getClassName().equals("JSnippet")) {
                    lineNumber = ste.getLineNumber();
                }
            }
            StringBuilder msg = new StringBuilder();
            msg.append("Evaluation of java snippet failed for row \"");
            msg.append(row.getKey());
            msg.append("\". ");
            if (lineNumber != null) {
                msg.append("The exception is caused by line ");
                msg.append(lineNumber);
                msg.append(" of the snippet. ");
            }
            if (thr.getMessage() != null) {
                msg.append("Exception message:");
                msg.append(thr.getMessage());
            }
            LOGGER.warn(msg.toString(), thr);
            OutVarList outVars = m_snippet.getSystemFields().getOutVarFields();
            if (outVars.size() > 0) {
                // Abort if flow variables are defined
                throw new RuntimeException("An error occured in an " + "expression with output flow variables.", thr);
            }
            OutColList outFields = m_snippet.getSystemFields().getOutColFields();
            DataCell[] out = new DataCell[outFields.size()];
            for (int i = 0; i < out.length; i++) {
                // Return missing values for output fields
                out[i] = DataType.getMissingCell();
            }
            m_rowIndex++;
            return out;
        }
    }
    try {
        // update m_flowVars with output flow variable fields.
        for (OutVar var : m_snippet.getSystemFields().getOutVarFields()) {
            Field field = m_jsnippet.getClass().getField(var.getJavaName());
            Object value = field.get(m_jsnippet);
            if (null != value) {
                Type type = var.getFlowVarType();
                FlowVariable flowVar = null;
                if (type.equals(Type.INTEGER)) {
                    flowVar = new FlowVariable(var.getKnimeName(), (Integer) value);
                } else if (type.equals(Type.DOUBLE)) {
                    flowVar = new FlowVariable(var.getKnimeName(), (Double) value);
                } else {
                    // case type.equals(Type.String)
                    flowVar = new FlowVariable(var.getKnimeName(), (String) value);
                }
                m_flowVars.put(flowVar);
            } else {
                throw new RuntimeException("Flow variable \"" + var.getKnimeName() + "\" has no value.");
            }
        }
        // get output column fields
        OutColList outFields = m_snippet.getSystemFields().getOutColFields();
        DataCell[] out = new DataCell[outFields.size()];
        for (int i = 0; i < out.length; i++) {
            OutCol outField = outFields.get(i);
            Field field = m_jsnippet.getClass().getField(outField.getJavaName());
            Object value = field.get(m_jsnippet);
            if (null == value) {
                out[i] = DataType.getMissingCell();
            } else {
                final String id = outField.getConverterFactoryId();
                Optional<JavaToDataCellConverterFactory<?>> factory = ConverterUtil.getJavaToDataCellConverterFactory(id);
                if (!factory.isPresent()) {
                    throw new RuntimeException("Missing converter factory with ID: " + id);
                }
                out[i] = ((JavaToDataCellConverterFactory<Object>) factory.get()).create(m_context).convert(value);
            }
        }
        // Cleanup Closeable inputs
        for (final OutCol outCol : m_snippet.getSystemFields().getOutColFields()) {
            final Field field = m_jsnippet.getClass().getField(outCol.getJavaName());
            final Object value = field.get(m_jsnippet);
            if (value instanceof Closeable) {
                ((Closeable) value).close();
            }
            if (value instanceof AutoCloseable) {
                // From the doc: Calling close more than once *can* have visible side effects!
                ((AutoCloseable) value).close();
            }
        }
        m_rowIndex++;
        return out;
    } catch (Exception e) {
        // but in case re-throw exception
        throw new RuntimeException(e);
    }
}
Also used : OutCol(org.knime.base.node.jsnippet.util.field.OutCol) Closeable(java.io.Closeable) ArrayList(java.util.ArrayList) OutColList(org.knime.base.node.jsnippet.util.JavaFieldList.OutColList) InCol(org.knime.base.node.jsnippet.util.field.InCol) DataCellToJavaConverterFactory(org.knime.core.data.convert.java.DataCellToJavaConverterFactory) Field(java.lang.reflect.Field) Abort(org.knime.base.node.jsnippet.expression.Abort) OutVarList(org.knime.base.node.jsnippet.util.JavaFieldList.OutVarList) InVar(org.knime.base.node.jsnippet.util.field.InVar) Cell(org.knime.base.node.jsnippet.expression.Cell) DataCell(org.knime.core.data.DataCell) OutVar(org.knime.base.node.jsnippet.util.field.OutVar) TypeException(org.knime.base.node.jsnippet.expression.TypeException) Type(org.knime.core.node.workflow.FlowVariable.Type) DataType(org.knime.core.data.DataType) DataCell(org.knime.core.data.DataCell) FlowVariable(org.knime.core.node.workflow.FlowVariable) JavaToDataCellConverterFactory(org.knime.core.data.convert.datacell.JavaToDataCellConverterFactory)

Example 4 with Type

use of org.knime.core.node.workflow.FlowVariable.Type in project knime-core by knime.

the class JavaEditVarNodeModel method performExecute.

/**
 */
private void performExecute(final ExecutionContext exec) {
    FlowVariableRepository flowVarRepo = new FlowVariableRepository(getAvailableInputFlowVariables());
    m_snippet.execute(flowVarRepo, exec);
    for (FlowVariable var : flowVarRepo.getModified()) {
        Type type = var.getType();
        if (type.equals(Type.INTEGER)) {
            pushFlowVariableInt(var.getName(), var.getIntValue());
        } else if (type.equals(Type.DOUBLE)) {
            pushFlowVariableDouble(var.getName(), var.getDoubleValue());
        } else {
            // case: type.equals(Type.STRING)
            pushFlowVariableString(var.getName(), var.getStringValue());
        }
    }
}
Also used : Type(org.knime.core.node.workflow.FlowVariable.Type) PortType(org.knime.core.node.port.PortType) FlowVariableRepository(org.knime.base.node.jsnippet.util.FlowVariableRepository) FlowVariable(org.knime.core.node.workflow.FlowVariable)

Example 5 with Type

use of org.knime.core.node.workflow.FlowVariable.Type in project knime-core by knime.

the class WorkflowVariablesEditDialog method createDialogArea.

/**
 * {@inheritDoc}
 */
@Override
protected Control createDialogArea(final Composite parent) {
    parent.getShell().setText("Add/Edit Workflow Variable");
    Composite twoColComp = new Composite(parent, SWT.NONE);
    twoColComp.setLayout(new GridLayout(3, true));
    GridData horizontalFill = new GridData(SWT.FILL, SWT.CENTER, true, false);
    horizontalFill.horizontalSpan = 2;
    // first row: node settings name
    Label varNameLabel = new Label(twoColComp, SWT.NONE);
    varNameLabel.setText("Variable name: ");
    m_varNameCtrl = new Text(twoColComp, SWT.BORDER);
    m_varNameCtrl.setLayoutData(horizontalFill);
    // add validation (at least some basic "text length > 0)
    m_varNameCtrl.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(final ModifyEvent arg0) {
            String text = m_varNameCtrl.getText();
            for (Scope s : FlowVariable.Scope.values()) {
                if (!Scope.Flow.equals(s) && text.startsWith(s.getPrefix())) {
                    showError("Flow variables must not start with \"" + s.getPrefix() + "\"!");
                    m_varNameCtrl.setText("");
                }
            }
        }
    });
    // second row: parameter type
    Label typeLabel = new Label(twoColComp, SWT.NONE);
    typeLabel.setText("Variable Type:");
    m_typeSelectionCtrl = new Combo(twoColComp, SWT.DROP_DOWN | SWT.READ_ONLY);
    for (FlowVariable.Type t : Arrays.asList(Type.DOUBLE, Type.INTEGER, Type.STRING)) {
        m_typeSelectionCtrl.add(t.name());
    }
    m_typeSelectionCtrl.addSelectionListener(new SelectionListener() {

        @Override
        public void widgetDefaultSelected(final SelectionEvent arg0) {
            widgetSelected(arg0);
        }

        @Override
        public void widgetSelected(final SelectionEvent arg0) {
            m_type = FlowVariable.Type.valueOf(m_typeSelectionCtrl.getItem(m_typeSelectionCtrl.getSelectionIndex()));
        }
    });
    m_typeSelectionCtrl.setLayoutData(horizontalFill);
    m_typeSelectionCtrl.select(0);
    // third row: data set parameter name
    Label defaultValueLabel = new Label(twoColComp, SWT.NONE);
    defaultValueLabel.setText("Default value: ");
    m_varDefaultValueCtrl = new Text(twoColComp, SWT.BORDER);
    m_varDefaultValueCtrl.setLayoutData(horizontalFill);
    return twoColComp;
}
Also used : Composite(org.eclipse.swt.widgets.Composite) ModifyListener(org.eclipse.swt.events.ModifyListener) Label(org.eclipse.swt.widgets.Label) Text(org.eclipse.swt.widgets.Text) Combo(org.eclipse.swt.widgets.Combo) Type(org.knime.core.node.workflow.FlowVariable.Type) GridLayout(org.eclipse.swt.layout.GridLayout) ModifyEvent(org.eclipse.swt.events.ModifyEvent) Scope(org.knime.core.node.workflow.FlowVariable.Scope) GridData(org.eclipse.swt.layout.GridData) SelectionEvent(org.eclipse.swt.events.SelectionEvent) FlowVariable(org.knime.core.node.workflow.FlowVariable) SelectionListener(org.eclipse.swt.events.SelectionListener)

Aggregations

Type (org.knime.core.node.workflow.FlowVariable.Type)10 FlowVariable (org.knime.core.node.workflow.FlowVariable)7 DataType (org.knime.core.data.DataType)5 FieldType (org.knime.base.node.jsnippet.util.field.JavaField.FieldType)3 JavaToDataCellConverterFactory (org.knime.core.data.convert.datacell.JavaToDataCellConverterFactory)3 Optional (java.util.Optional)2 TypeConverter (org.knime.base.node.jsnippet.type.flowvar.TypeConverter)2 FlowVariableRepository (org.knime.base.node.jsnippet.util.FlowVariableRepository)2 OutVarList (org.knime.base.node.jsnippet.util.JavaFieldList.OutVarList)2 OutVar (org.knime.base.node.jsnippet.util.field.OutVar)2 Pair (org.knime.core.util.Pair)2 FontMetrics (java.awt.FontMetrics)1 Closeable (java.io.Closeable)1 Array (java.lang.reflect.Array)1 Field (java.lang.reflect.Field)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 EventObject (java.util.EventObject)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1