All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.rathravane.till.data.exprEval.ExpressionEvaluator Maven / Gradle / Ivy

There is a newer version: 2.1.1
Show newest version
package com.rathravane.till.data.exprEval;

import java.util.Map;

public class ExpressionEvaluator
{
	/**
	 * Evaluate the given expression against the given root JSON object and return 
	 * a string representation. If the evaluation is null, an empty string is returned.
	 * @param root
	 * @param expression
	 * @return a string
	 */
	public static String evalToString ( ExprDataSource root, String expression )
	{
		final Object result = root.eval ( expression );
		if ( result == null ) return "";
		return result.toString ();
	}

	/**
	 * eval to string using a string map as a data source
	 * @param map
	 * @param expression
	 * @return a string
	 */
	public static String evalToString ( final Map map, String expression )
	{
		return evalToString ( new ExprDataSource(){

			@Override
			public Object eval ( String label )
			{
				return map.get ( label );
			}
			
		}, expression );
	}

	/**
	 * substitute any occurrence of ${<expr>} with the evaluation of that expression 
	 * @param sourceString
	 * @param root
	 * @return a string
	 */
	public static String evaluate ( String sourceString, ExprDataSource root )
	{
		if ( sourceString == null ) return null;

		final StringBuffer sb = new StringBuffer ();
		do
		{
			final int open = sourceString.indexOf ( "${" );
			if ( open < 0 )
			{
				// just straight text left
				sb.append ( sourceString );
				sourceString = "";
			}
			else
			{
				// read to "}", use the content as a key into the json
				final int closer = sourceString.indexOf ( '}' );
				if ( closer < 0 )
				{
					// not found. just treat it like plain text
					sb.append ( sourceString );
					sourceString = "";
				}
				else
				{
					sb.append ( sourceString.substring ( 0, open ) );
					final String key = sourceString.substring ( open+2, closer );
					sb.append ( evalToString ( root, key ) );
					sourceString = sourceString.substring ( closer + 1 );
				}
			}
		}
		while ( sourceString.length () > 0 );
		
		return sb.toString ();
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy