+/*******************************************************************************
+ * Copyright (c) 2017 Association for Decentralized Information Management in
+ * Industry THTH ry.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * VTT Technical Research Centre of Finland - initial API and implementation
+ * Semantum Oy - #7313
+ *******************************************************************************/
+package org.simantics.charts.internal;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+
+import org.simantics.databoard.type.Datatype;
+import org.simantics.db.ReadGraph;
+import org.simantics.db.Resource;
+import org.simantics.db.exception.DatabaseException;
+import org.simantics.db.layer0.request.PossibleActiveVariableFromVariable;
+import org.simantics.db.layer0.variable.RVI;
+import org.simantics.db.layer0.variable.Variable;
+import org.simantics.db.layer0.variable.VariableReference;
+import org.simantics.db.layer0.variable.Variables;
+import org.simantics.modeling.utils.VariableReferences;
+
+/**
+ * @author Tuukka Lehtonen
+ * @since 1.28.1, 1.29.0
+ */
+public class VariableUtils {
+
+ public static Datatype getDatatype(ReadGraph graph, Resource resource, RVI rvi) throws DatabaseException {
+ Variable configuration = Variables.getConfigurationContext(graph, resource);
+ Variable active = graph.syncRequest(new PossibleActiveVariableFromVariable(configuration));
+ Variable var = rvi.resolve(graph, active != null ? active : configuration);
+ return var.getDatatype(graph);
+ }
+
+ /**
+ * @param graph
+ * @param targetModel
+ * @param source
+ * @return <code>null</code> if the value is valid JSON but does not contain
+ * a variable reference
+ * @throws DatabaseException
+ * if the value fails to resolve as either JSON or an RVI string
+ */
+ public static List<VariableReference> getVariableReferencesFromString(ReadGraph graph, Resource targetModel, String source) throws DatabaseException {
+ try {
+ // JSON ?
+ Optional<Variable> v = JsonUtils.tryParseJsonPropertyVariable(graph, source);
+ if (v.isPresent())
+ return graph.syncRequest(VariableReferences.variablesToReferences(targetModel, Collections.singletonList(v.get())));
+ // JSON, but no variable info in it.
+ return null;
+ } catch (DatabaseException e) {
+ // RVI as String?
+ RVI rvi = RVI.fromResourceFormat(graph, source);
+ return Collections.singletonList(new VariableReference(rvi, getDatatype(graph, targetModel, rvi), null));
+ }
+ }
+
+}