Java Code Examples for org.mozilla.javascript.Context#jsToJava()

The following examples show how to use org.mozilla.javascript.Context#jsToJava() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JavaScriptUtils.java    From hop with Apache License 2.0 6 votes vote down vote up
public static Long jsToInteger( Object value, Class<?> clazz ) {
  if ( Number.class.isAssignableFrom( clazz ) ) {
    return ( (Number) value ).longValue();
  } else {
    String classType = clazz.getName();
    if ( classType.equalsIgnoreCase( "java.lang.String" ) ) {
      return ( new Long( (String) value ) );
    } else if ( classType.equalsIgnoreCase( "org.mozilla.javascript.Undefined" ) ) {
      return null;
    } else if ( classType.equalsIgnoreCase( "org.mozilla.javascript.NativeNumber" ) ) {
      Number nb = Context.toNumber( value );
      return nb.longValue();
    } else if ( classType.equalsIgnoreCase( "org.mozilla.javascript.NativeJavaObject" ) ) {
      // Is it a Value?
      //
      try {
        return (Long) Context.jsToJava( value, Long.class );
      } catch ( Exception e2 ) {
        String string = Context.toString( value );
        return Long.parseLong( Const.trim( string ) );
      }
    } else {
      return Long.parseLong( value.toString() );
    }
  }
}
 
Example 2
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 6 votes vote down vote up
public static Object isDate( Context actualContext, Scriptable actualObject, Object[] ArgList,
                             Function FunctionContext ) {

  if ( ArgList.length == 1 ) {
    try {
      if ( isNull( ArgList[ 0 ] ) ) {
        return null;
      } else if ( isUndefined( ArgList[ 0 ] ) ) {
        return Context.getUndefinedValue();
      }
      /* java.util.Date d = (java.util.Date) */
      Context.jsToJava( ArgList[ 0 ], Date.class );
      return Boolean.TRUE;
    } catch ( Exception e ) {
      return Boolean.FALSE;
    }
  } else {
    throw Context.reportRuntimeError( "The function call isDate requires 1 argument." );
  }
}
 
Example 3
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 6 votes vote down vote up
public static Object trunc( Context actualContext, Scriptable actualObject, Object[] ArgList,
                            Function FunctionContext ) {
  try {
    // 1 argument: normal truncation of numbers
    //
    if ( ArgList.length == 1 ) {
      if ( isNull( ArgList[ 0 ] ) ) {
        return null;
      } else if ( isUndefined( ArgList[ 0 ] ) ) {
        return Context.getUndefinedValue();
      }

      // This is the truncation of a number...
      //
      Double dArg1 = (Double) Context.jsToJava( ArgList[ 0 ], Double.class );
      return Double.valueOf( Math.floor( dArg1 ) );

    } else {
      throw Context.reportRuntimeError( "The function call trunc requires 1 argument, a number." );
    }
  } catch ( Exception e ) {
    throw Context.reportRuntimeError( e.toString() );
  }
}
 
Example 4
Source File: JavaScriptUtils.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public static String jsToString( Object value, String classType ) {
  if ( classType.equalsIgnoreCase( JS_NATIVE_JAVA_OBJ )
    || classType.equalsIgnoreCase( JS_UNDEFINED ) ) {
    // Is it a java Value class ?
    try {
      Value v = (Value) Context.jsToJava( value, Value.class );
      return v.toString();
    } catch ( Exception ev ) {
      // convert to a string should work in most cases...
      //
      return Context.toString( value );
    }
  } else {
    // A String perhaps?
    return Context.toString( value );
  }
}
 
Example 5
Source File: DataFrameAdapter.java    From joinery with GNU General Public License v3.0 6 votes vote down vote up
public static Scriptable jsFunction_join(final Context ctx, final Scriptable object, final Object[] args, final Function func) {
    final DataFrame<Object> other = DataFrameAdapter.class.cast(args[0]).df;
    final JoinType type = args.length > 1 && args[1] instanceof NativeJavaObject ?
            JoinType.class.cast(Context.jsToJava(args[1], JoinType.class)) : null;
    if (args.length > 1 && args[args.length - 1] instanceof Function) {
        @SuppressWarnings("unchecked")
        final KeyFunction<Object> f = (KeyFunction<Object>)Context.jsToJava(args[args.length - 1], KeyFunction.class);
        if (type != null) {
            return new DataFrameAdapter(object, cast(object).df.join(other, type, f));
        }
        return new DataFrameAdapter(object, cast(object).df.join(other, f));
    }
    if (type != null) {
        return new DataFrameAdapter(object, cast(object).df.join(other, type));
    }
    return new DataFrameAdapter(object, cast(object).df.join(other));
}
 
Example 6
Source File: JavaScriptEvaluatorScope.java    From jasperreports with GNU Lesser General Public License v3.0 6 votes vote down vote up
public Object evaluateExpression(Script expression)
{
	ensureContext();
	
	Object value = expression.exec(context, scope);
	
	Object javaValue;
	// not converting Number objects because the generic conversion call below
	// always converts to Double
	if (value == null || value instanceof Number)
	{
		javaValue = value;
	}
	else
	{
		try
		{
			javaValue = Context.jsToJava(value, Object.class);
		}
		catch (EvaluatorException e)
		{
			throw new JRRuntimeException(e);
		}
	}
	return javaValue;
}
 
Example 7
Source File: EcmaScriptDataModel.java    From JVoiceXML with GNU Lesser General Public License v2.1 5 votes vote down vote up
private <T extends Object> T readVariable(String variableName, Scope scope,
        final Scriptable start, final Class<T> type) throws SemanticError {
    if (start == null) {
        throw new SemanticError("no scope '" + scope
                + "' present to read '" + variableName + "'");
    }
    final Scriptable subcope = getScope(topmostScope, variableName);
    if (subcope == null) {
        throw new SemanticError("'" + variableName + "' not found");
    }
    final String property;
    int dotPos = variableName.lastIndexOf('.');
    if (dotPos >= 0) {
        property = variableName.substring(dotPos + 1);
    } else {
        property = variableName;
    }
    if (!ScriptableObject.hasProperty(subcope, property)) {
        throw new SemanticError("'" + variableName + "' not found");
    }
    final Object value = ScriptableObject.getProperty(subcope, property);
    if (value == getUndefinedValue()) {
        return null;
    }
    @SuppressWarnings("unchecked")
    final T t = (T) Context.jsToJava(value, type);
    return t;
}
 
Example 8
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static void setVariable( Context actualContext, Scriptable actualObject, Object[] arguments,
  Function functionContext ) {

  if ( arguments.length != 3 ) {
    throw Context.reportRuntimeError( "The function call setVariable requires 3 arguments." );
  }

  Object stepObject = Context.jsToJava( actualObject.get( "_step_", actualObject ), StepInterface.class );
  if ( stepObject instanceof StepInterface ) {
    StepInterface step = (StepInterface) stepObject;
    Trans trans = step.getTrans();
    final String variableName = Context.toString( arguments[ 0 ] );
    final String variableValue = Context.toString( arguments[ 1 ] );
    final VariableScope variableScope = getVariableScope( Context.toString( arguments[ 2 ] ) );

    // Set variable in step's scope so that it can be retrieved in the same step using getVariable
    step.setVariable( variableName, variableValue );

    switch ( variableScope ) {
      case PARENT:
        setParentScopeVariable( trans, variableName, variableValue );
        break;
      case GRAND_PARENT:
        setGrandParentScopeVariable( trans, variableName, variableValue );
        break;
      case ROOT:
        setRootScopeVariable( trans, variableName, variableValue );
        break;
      case SYSTEM:
        setSystemScopeVariable( trans, variableName, variableValue );
        break;
    }
  }
}
 
Example 9
Source File: JavaScriptUtils.java    From hop with Apache License 2.0 5 votes vote down vote up
public static BigDecimal jsToBigNumber( Object value, String classType ) {
  if ( classType.equalsIgnoreCase( "org.mozilla.javascript.Undefined" ) ) {
    return null;
  } else if ( classType.equalsIgnoreCase( "org.mozilla.javascript.NativeNumber" ) ) {
    Number nb = Context.toNumber( value );
    return new BigDecimal( nb.doubleValue() );
  } else if ( classType.equalsIgnoreCase( "org.mozilla.javascript.NativeJavaObject" ) ) {
    // Is it a BigDecimal class ?
    try {
      return (BigDecimal) Context.jsToJava( value, BigDecimal.class );
    } catch ( Exception e ) {
      String string = (String) Context.jsToJava( value, String.class );
      return new BigDecimal( string );
    }
  } else if ( classType.equalsIgnoreCase( "java.lang.Byte" ) ) {
    return new BigDecimal( ( (Byte) value ).longValue() );
  } else if ( classType.equalsIgnoreCase( "java.lang.Short" ) ) {
    return new BigDecimal( ( (Short) value ).longValue() );
  } else if ( classType.equalsIgnoreCase( "java.lang.Integer" ) ) {
    return new BigDecimal( ( (Integer) value ).longValue() );
  } else if ( classType.equalsIgnoreCase( "java.lang.Long" ) ) {
    return new BigDecimal( ( (Long) value ).longValue() );
  } else if ( classType.equalsIgnoreCase( "java.lang.Double" ) ) {
    return new BigDecimal( ( (Double) value ).doubleValue() );
  } else if ( classType.equalsIgnoreCase( "java.lang.String" ) ) {
    return new BigDecimal( ( new Long( (String) value ) ).longValue() );
  } else {
    throw new RuntimeException( "JavaScript conversion to BigNumber not implemented for " + classType );
  }
}
 
Example 10
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static Object quarter( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {
  try {
    if ( ArgList.length == 1 ) {
      if ( isNull( ArgList[0] ) ) {
        return new Double( Double.NaN );
      } else if ( isUndefined( ArgList[0] ) ) {
        return Context.getUndefinedValue();
      }
      java.util.Date dArg1 = (java.util.Date) Context.jsToJava( ArgList[0], java.util.Date.class );
      Calendar cal = Calendar.getInstance();
      cal.setTime( dArg1 );

      // Patch by Ingo Klose: calendar months start at 0 in java.
      int iMonth = cal.get( Calendar.MONTH );
      if ( iMonth <= 2 ) {
        return new Double( 1 );
      } else if ( iMonth <= 5 ) {
        return new Double( 2 );
      } else if ( iMonth <= 8 ) {
        return new Double( 3 );
      } else {
        return new Double( 4 );
      }
    } else {
      throw Context.reportRuntimeError( "The function call quarter requires 1 argument." );
    }
  } catch ( Exception e ) {
    throw Context.reportRuntimeError( e.toString() );
  }
}
 
Example 11
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 5 votes vote down vote up
public static Object quarter( Context actualContext, Scriptable actualObject, Object[] ArgList,
                              Function FunctionContext ) {
  try {
    if ( ArgList.length == 1 ) {
      if ( isNull( ArgList[ 0 ] ) ) {
        return new Double( Double.NaN );
      } else if ( isUndefined( ArgList[ 0 ] ) ) {
        return Context.getUndefinedValue();
      }
      Date dArg1 = (Date) Context.jsToJava( ArgList[ 0 ], Date.class );
      Calendar cal = Calendar.getInstance();
      cal.setTime( dArg1 );

      // Patch by Ingo Klose: calendar months start at 0 in java.
      int iMonth = cal.get( Calendar.MONTH );
      if ( iMonth <= 2 ) {
        return new Double( 1 );
      } else if ( iMonth <= 5 ) {
        return new Double( 2 );
      } else if ( iMonth <= 8 ) {
        return new Double( 3 );
      } else {
        return new Double( 4 );
      }
    } else {
      throw Context.reportRuntimeError( "The function call quarter requires 1 argument." );
    }
  } catch ( Exception e ) {
    throw Context.reportRuntimeError( e.toString() );
  }
}
 
Example 12
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static String getVariable( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {
  String sRC = "";
  String sArg1 = "";
  String sArg2 = "";
  if ( ArgList.length == 2 ) {
    try {
      Object scmo = actualObject.get( "_step_", actualObject );
      Object scmO = Context.jsToJava( scmo, StepInterface.class );

      if ( scmO instanceof StepInterface ) {
        StepInterface scm = (StepInterface) Context.jsToJava( scmO, StepInterface.class );

        sArg1 = Context.toString( ArgList[0] );
        sArg2 = Context.toString( ArgList[1] );
        return scm.getVariable( sArg1, sArg2 );
      } else {
        // running via the Test button in a dialog
        sArg2 = Context.toString( ArgList[1] );
        return sArg2;
      }
    } catch ( Exception e ) {
      sRC = "";
    }
  } else {
    throw Context.reportRuntimeError( "The function call getVariable requires 2 arguments." );
  }
  return sRC;
}
 
Example 13
Source File: JavaScriptUtils.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static Long jsToInteger( Object value, Class<?> clazz ) {
  if ( Number.class.isAssignableFrom( clazz ) ) {
    return ( (Number) value ).longValue();
  } else {
    String classType = clazz.getName();
    if ( classType.equalsIgnoreCase( "java.lang.String" ) ) {
      return ( new Long( (String) value ) );
    } else if ( classType.equalsIgnoreCase( JS_UNDEFINED ) ) {
      return null;
    } else if ( classType.equalsIgnoreCase( JS_NATIVE_NUM ) ) {
      Number nb = Context.toNumber( value );
      return nb.longValue();
    } else if ( classType.equalsIgnoreCase( JS_NATIVE_JAVA_OBJ ) ) {
      // Is it a Value?
      //
      try {
        Value v = (Value) Context.jsToJava( value, Value.class );
        return v.getInteger();
      } catch ( Exception e2 ) {
        String string = Context.toString( value );
        return Long.parseLong( Const.trim( string ) );
      }
    } else {
      return Long.parseLong( value.toString() );
    }
  }
}
 
Example 14
Source File: DataFrameAdapter.java    From joinery with GNU General Public License v3.0 5 votes vote down vote up
public static Scriptable jsFunction_pivot(final Context ctx, final Scriptable object, final Object[] args, final Function func) {
    final Object row = Context.jsToJava(args[0], Object.class);
    final Object col = Context.jsToJava(args[0], Object.class);
    final Object[] values = new Object[args.length - 2];
    for (int i = 0; i < values.length; i++) {
        values[i] = Context.jsToJava(args[i + 2], Object.class);
    }
    return new DataFrameAdapter(object, cast(object).df.pivot(row, col, values));
}
 
Example 15
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings( "fallthrough" )
public static Object truncDate( Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext ) {
    // 2 arguments: truncation of dates to a certain precision
    //
  if ( ArgList.length == 2 ) {
    if ( isNull( ArgList[0] ) ) {
      return null;
    } else if ( isUndefined( ArgList[0] ) ) {
      return Context.getUndefinedValue();
    }

    // This is the truncation of a date...
    // The second argument specifies the level: ms, s, min, hour, day, month, year
    //
    Date dArg1 = null;
    Integer level = null;
    try {
      dArg1 = (java.util.Date) Context.jsToJava( ArgList[0], java.util.Date.class );
      level = (Integer) Context.jsToJava( ArgList[1], Integer.class );
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( e.toString() );
    }
    return truncDate( dArg1, level );
  } else {
    throw Context
      .reportRuntimeError( "The function call truncDate requires 2 arguments: a date and a level (int)" );
  }
}
 
Example 16
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static double getProcessCount( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {

  if ( ArgList.length == 1 ) {
    try {
      Object scmO = actualObject.get( "_step_", actualObject );
      StepInterface scm = (StepInterface) Context.jsToJava( scmO, StepInterface.class );
      String strType = Context.toString( ArgList[0] ).toLowerCase();

      if ( strType.equals( "i" ) ) {
        return scm.getLinesInput();
      } else if ( strType.equals( "o" ) ) {
        return scm.getLinesOutput();
      } else if ( strType.equals( "r" ) ) {
        return scm.getLinesRead();
      } else if ( strType.equals( "u" ) ) {
        return scm.getLinesUpdated();
      } else if ( strType.equals( "w" ) ) {
        return scm.getLinesWritten();
      } else if ( strType.equals( "e" ) ) {
        return scm.getLinesRejected();
      } else {
        return 0;
      }
    } catch ( Exception e ) {
      // throw Context.reportRuntimeError(e.toString());
      return 0;
    }
  } else {
    throw Context.reportRuntimeError( "The function call getProcessCount requires 1 argument." );
  }
}
 
Example 17
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "unused" )
public static Object fireToDB( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {

  Object oRC = new Object();
  if ( ArgList.length == 2 ) {
    try {
      Object scmO = actualObject.get( "_step_", actualObject );
      ScriptValuesMod scm = (ScriptValuesMod) Context.jsToJava( scmO, ScriptValuesMod.class );
      String strDBName = Context.toString( ArgList[0] );
      String strSQL = Context.toString( ArgList[1] );
      DatabaseMeta ci = DatabaseMeta.findDatabase( scm.getTransMeta().getDatabases(), strDBName );
      if ( ci == null ) {
        throw Context.reportRuntimeError( "Database connection not found: " + strDBName );
      }
      ci.shareVariablesWith( scm );

      Database db = new Database( scm, ci );
      db.setQueryLimit( 0 );
      try {
        if ( scm.getTransMeta().isUsingUniqueConnections() ) {
          synchronized ( scm.getTrans() ) {
            db.connect( scm.getTrans().getTransactionId(), scm.getPartitionID() );
          }
        } else {
          db.connect( scm.getPartitionID() );
        }

        ResultSet rs = db.openQuery( strSQL );
        ResultSetMetaData resultSetMetaData = rs.getMetaData();
        int columnCount = resultSetMetaData.getColumnCount();
        if ( rs != null ) {
          List<Object[]> list = new ArrayList<Object[]>();
          while ( rs.next() ) {
            Object[] objRow = new Object[columnCount];
            for ( int i = 0; i < columnCount; i++ ) {
              objRow[i] = rs.getObject( i + 1 );
            }
            list.add( objRow );
          }
          Object[][] resultArr = new Object[list.size()][];
          list.toArray( resultArr );
          db.disconnect();
          return resultArr;
        }
      } catch ( Exception er ) {
        throw Context.reportRuntimeError( er.toString() );
      }
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( e.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call fireToDB requires 2 arguments." );
  }
  return oRC;
}
 
Example 18
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "unused" )
public static Object fireToDB( Context actualContext, Scriptable actualObject, Object[] ArgList,
                               Function FunctionContext ) {

  Object oRC = new Object();
  if ( ArgList.length == 2 ) {
    try {
      Object scmO = actualObject.get( "_transform_", actualObject );
      ScriptValuesMod scm = (ScriptValuesMod) Context.jsToJava( scmO, ScriptValuesMod.class );
      String strDBName = Context.toString( ArgList[ 0 ] );
      String strSql = Context.toString( ArgList[ 1 ] );
      DatabaseMeta ci = DatabaseMeta.findDatabase( scm.getPipelineMeta().getDatabases(), strDBName );
      if ( ci == null ) {
        throw Context.reportRuntimeError( "Database connection not found: " + strDBName );
      }
      ci.shareVariablesWith( scm );

      Database db = new Database( scm, ci );
      db.setQueryLimit( 0 );
      try {
        db.connect( scm.getPartitionId() );

        ResultSet rs = db.openQuery( strSql );
        ResultSetMetaData resultSetMetaData = rs.getMetaData();
        int columnCount = resultSetMetaData.getColumnCount();
        if ( rs != null ) {
          List<Object[]> list = new ArrayList<Object[]>();
          while ( rs.next() ) {
            Object[] objRow = new Object[ columnCount ];
            for ( int i = 0; i < columnCount; i++ ) {
              objRow[ i ] = rs.getObject( i + 1 );
            }
            list.add( objRow );
          }
          Object[][] resultArr = new Object[ list.size() ][];
          list.toArray( resultArr );
          db.disconnect();
          return resultArr;
        }
      } catch ( Exception er ) {
        throw Context.reportRuntimeError( er.toString() );
      }
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( e.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call fireToDB requires 2 arguments." );
  }
  return oRC;
}
 
Example 19
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public static Object dateAdd( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {
  if ( ArgList.length == 3 ) {
    try {
      if ( isNull( ArgList, new int[] { 0, 1, 2 } ) ) {
        return null;
      } else if ( isUndefined( ArgList, new int[] { 0, 1, 2 } ) ) {
        return Context.getUndefinedValue();
      }
      java.util.Date dIn = (java.util.Date) Context.jsToJava( ArgList[0], java.util.Date.class );
      String strType = Context.toString( ArgList[1] ).toLowerCase();
      int iValue = (int) Context.toNumber( ArgList[2] );
      Calendar cal = Calendar.getInstance();
      cal.setTime( dIn );
      if ( strType.equals( "y" ) ) {
        cal.add( Calendar.YEAR, iValue );
      } else if ( strType.equals( "m" ) ) {
        cal.add( Calendar.MONTH, iValue );
      } else if ( strType.equals( "d" ) ) {
        cal.add( Calendar.DATE, iValue );
      } else if ( strType.equals( "w" ) ) {
        cal.add( Calendar.WEEK_OF_YEAR, iValue );
      } else if ( strType.equals( "wd" ) ) {
        int iOffset = 0;
        while ( iOffset < iValue ) {
          cal.add( Calendar.DATE, 1 );
          int day = cal.get( Calendar.DAY_OF_WEEK );
          if ( ( day != Calendar.SATURDAY ) && ( day != Calendar.SUNDAY ) ) {
            iOffset++;
          }
        }
      } else if ( strType.equals( "hh" ) ) {
        cal.add( Calendar.HOUR, iValue );
      } else if ( strType.equals( "mi" ) ) {
        cal.add( Calendar.MINUTE, iValue );
      } else if ( strType.equals( "ss" ) ) {
        cal.add( Calendar.SECOND, iValue );
      }
      return cal.getTime();
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( e.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call dateAdd requires 3 arguments." );
  }
}
 
Example 20
Source File: DataFrameAdapter.java    From joinery with GNU General Public License v3.0 4 votes vote down vote up
public DataFrameAdapter jsFunction_aggregate(final Function function) {
    @SuppressWarnings("unchecked")
    final Aggregate<Object, Object> f = (Aggregate<Object, Object>)Context.jsToJava(function, Aggregate.class);
    return new DataFrameAdapter(this, df.aggregate(f));
}