001package jmri.jmrit.logixng.util.parser; 002 003import java.util.*; 004 005import jmri.JmriException; 006import jmri.jmrit.logixng.SymbolTable; 007 008/** 009 * A parsed expression 010 * 011 * @author Daniel Bergqvist 2021 012 */ 013public class ExpressionNodeMap implements ExpressionNodeWithParameter { 014 015 private final ExpressionNode _exprNode; 016 017 public ExpressionNodeMap(ExpressionNode exprNode) throws FunctionNotExistsException { 018 _exprNode = exprNode; 019 } 020 021 @SuppressWarnings("unchecked") 022 @Override 023 public Object calculate(Object parameter, SymbolTable symbolTable) throws JmriException { 024 if (parameter == null) throw new NullPointerException("Parameter is null"); 025 026 Object index = _exprNode.calculate(symbolTable); 027 028 // JSON map node 029 if (parameter instanceof com.fasterxml.jackson.databind.node.ObjectNode) { 030 return ((com.fasterxml.jackson.databind.node.ObjectNode)parameter).findValue(index.toString()); 031 } 032 033// if (!(parameter instanceof Map)) return parameter.getClass().getName(); 034 035 if (!(parameter instanceof Map)) throw new IllegalArgumentException("Parameter is not a Map"); 036 037 return ((Map<Object,Object>)parameter).get(index); 038 } 039 040 /** {@inheritDoc} */ 041 @Override 042 public boolean canBeAssigned() { 043 // We don't know so we assume that it is. 044 return true; 045 } 046 047 /** 048 * Assign a value to this expression from a parameter. 049 * @param parameter the parameter 050 * @param symbolTable the symbol table 051 * @param value the value to assign 052 * @throws jmri.JmriException if an error occurs 053 */ 054 @SuppressWarnings("unchecked") 055 @Override 056 public void assignValue(Object parameter, SymbolTable symbolTable, Object value) throws JmriException { 057 if (parameter == null) throw new NullPointerException("Parameter is null"); 058 if (!(parameter instanceof Map)) throw new IllegalArgumentException("Parameter is not a Map"); 059 060 Object index = _exprNode.calculate(symbolTable); 061 062 ((Map<Object,Object>)parameter).put(index, value); 063 } 064 065 /** {@inheritDoc} */ 066 @Override 067 public String getDefinitionString() { 068 StringBuilder str = new StringBuilder(); 069 str.append("{"); 070 str.append(_exprNode.getDefinitionString()); 071 str.append("}"); 072 return str.toString(); 073 } 074 075}