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

The following examples show how to use org.mozilla.javascript.Context#toString() . 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: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public static String ltrim( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {
  try {
    if ( ArgList.length == 1 ) {
      if ( isNull( ArgList[0] ) ) {
        return null;
      } else if ( isUndefined( ArgList[0] ) ) {
        return (String) Context.getUndefinedValue();
      }
      String strValueToTrim = Context.toString( ArgList[0] );
      return strValueToTrim.replaceAll( "^\\s+", "" );
    } else {
      throw Context.reportRuntimeError( "The function call ltrim requires 1 argument." );
    }
  } catch ( Exception e ) {
    throw Context.reportRuntimeError( "The function call ltrim is not valid : " + e.getMessage() );
  }
}
 
Example 2
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public static Object isCodepage( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {
  boolean bRC = false;
  if ( ArgList.length == 2 ) {
    try {
      if ( isNull( ArgList, new int[] { 0, 1 } ) ) {
        return null;
      } else if ( isUndefined( ArgList, new int[] { 0, 1 } ) ) {
        return Context.getUndefinedValue();
      }
      String strValueToCheck = Context.toString( ArgList[0] );
      String strCodePage = Context.toString( ArgList[1] );
      byte[] bytearray = strValueToCheck.getBytes();
      CharsetDecoder d = Charset.forName( strCodePage ).newDecoder();
      CharBuffer r = d.decode( ByteBuffer.wrap( bytearray ) );
      r.toString();
      bRC = true;
    } catch ( Exception e ) {
      bRC = false;
    }
  } else {
    throw Context.reportRuntimeError( "The function call isCodepage requires 2 arguments." );
  }
  return Boolean.valueOf( bRC );
}
 
Example 3
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public static void appendToFile( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {

  if ( !isNull( ArgList ) && !isUndefined( ArgList ) ) {
    try {
      FileOutputStream file = new FileOutputStream( Context.toString( ArgList[0] ), true );
      DataOutputStream out = new DataOutputStream( file );
      out.writeBytes( Context.toString( ArgList[1] ) );
      out.flush();
      out.close();
    } catch ( Exception er ) {
      throw Context.reportRuntimeError( er.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call appendToFile requires arguments." );
  }
}
 
Example 4
Source File: JavascriptTestUtilities.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static String scriptableToString(Scriptable scriptable) {
    StringBuilder builder = new StringBuilder();
    for (Object propid : scriptable.getIds()) {
        String propIdString = Context.toString(propid);
        int propIntKey = -1;
        try {
            propIntKey = Integer.parseInt(propIdString);
        } catch (NumberFormatException nfe) {
            // dummy.
        }
        String propValue;
        if (propIntKey >= 0) {
            propValue = Context.toString(scriptable.get(propIntKey, scriptable));
        } else {
            propValue = Context.toString(scriptable.get(propIdString, scriptable));
        }
        builder.append(propIdString);
        builder.append(": ");
        builder.append(propValue);
        builder.append("; ");
    }
    return builder.toString();
}
 
Example 5
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 6 votes vote down vote up
public static String rpad( Context actualContext, Scriptable actualObject, Object[] ArgList,
                           Function FunctionContext ) {
  try {
    if ( ArgList.length == 3 ) {
      if ( isNull( ArgList, new int[] { 0, 1, 2 } ) ) {
        return null;
      } else if ( isUndefined( ArgList, new int[] { 0, 1, 2 } ) ) {
        return (String) Context.getUndefinedValue();
      }
      String valueToPad = Context.toString( ArgList[ 0 ] );
      String filler = Context.toString( ArgList[ 1 ] );
      int size = (int) Context.toNumber( ArgList[ 2 ] );

      while ( valueToPad.length() < size ) {
        valueToPad = valueToPad + filler;
      }
      return valueToPad;
    }
  } catch ( Exception e ) {
    throw Context.reportRuntimeError( "The function call rpad requires 3 arguments." );
  }
  return null;
}
 
Example 6
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
public static int getOcuranceString( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {
  int nr = 0;
  if ( ArgList.length == 2 ) {
    try {
      if ( isNull( ArgList[0] ) ) {
        return 0;
      } else if ( isUndefined( ArgList[0] ) ) {
        return (Integer) Context.getUndefinedValue();
      }
      if ( isNull( ArgList[1] ) ) {
        return 0;
      } else if ( isUndefined( ArgList[1] ) ) {
        return (Integer) Context.getUndefinedValue();
      }
      String string = Context.toString( ArgList[0] );
      String searchFor = Context.toString( ArgList[1] );
      nr = Const.getOcuranceString( string, searchFor );
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( "The function call getOcuranceString is not valid" );
    }
  } else {
    throw Context.reportRuntimeError( "The function call getOcuranceString is not valid" );
  }
  return nr;
}
 
Example 7
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 6 votes vote down vote up
public static Object isCodepage( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                 Function FunctionContext ) {
  boolean bRC = false;
  if ( ArgList.length == 2 ) {
    try {
      if ( isNull( ArgList, new int[] { 0, 1 } ) ) {
        return null;
      } else if ( isUndefined( ArgList, new int[] { 0, 1 } ) ) {
        return Context.getUndefinedValue();
      }
      String strValueToCheck = Context.toString( ArgList[ 0 ] );
      String strCodePage = Context.toString( ArgList[ 1 ] );
      byte[] bytearray = strValueToCheck.getBytes();
      CharsetDecoder d = Charset.forName( strCodePage ).newDecoder();
      CharBuffer r = d.decode( ByteBuffer.wrap( bytearray ) );
      r.toString();
      bRC = true;
    } catch ( Exception e ) {
      bRC = false;
    }
  } else {
    throw Context.reportRuntimeError( "The function call isCodepage requires 2 arguments." );
  }
  return Boolean.valueOf( bRC );
}
 
Example 8
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 6 votes vote down vote up
public static String lpad( Context actualContext, Scriptable actualObject, Object[] ArgList,
                           Function FunctionContext ) {

  // (String valueToPad, String filler, int size) {
  try {
    if ( ArgList.length == 3 ) {
      if ( isNull( ArgList, new int[] { 0, 1, 2 } ) ) {
        return null;
      } else if ( isUndefined( ArgList, new int[] { 0, 1, 2 } ) ) {
        return (String) Context.getUndefinedValue();
      }
      String valueToPad = Context.toString( ArgList[ 0 ] );
      String filler = Context.toString( ArgList[ 1 ] );
      int size = (int) Context.toNumber( ArgList[ 2 ] );

      while ( valueToPad.length() < size ) {
        valueToPad = filler + valueToPad;
      }
      return valueToPad;
    }
  } catch ( Exception e ) {
    throw Context.reportRuntimeError( "The function call lpad requires 3 arguments." );
  }
  return null;
}
 
Example 9
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 6 votes vote down vote up
public static String Alert( Context actualContext, Scriptable actualObject, Object[] ArgList,
                              Function FunctionContext ) {

    HopGui hopGui = HopGui.getInstance();
    if ( ArgList.length == 1 && hopGui != null ) {
      String strMessage = Context.toString( ArgList[ 0 ] );
      MessageBox mb = new MessageBox( hopGui.getShell(), SWT.OK | SWT.ICON_INFORMATION );
      mb.setMessage( strMessage );
      mb.setText(  "alert"  );
      mb.open();
/*
      boolean ok = hopGui.messageBox( strMessage, "Alert", true, Const.INFO );
      if ( !ok ) {
        throw new RuntimeException( "Alert dialog cancelled by user." );
      }
*/
    }

    return "";
  }
 
Example 10
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 11
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 5 votes vote down vote up
public static Boolean isMailValid( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                   Function FunctionContext ) {
  Boolean isValid;
  if ( ArgList.length == 1 ) {
    try {
      if ( isUndefined( ArgList[ 0 ] ) ) {
        throw new Exception( ArgList[ 0 ] + " is  undefined!" );
      }
      if ( isNull( ArgList[ 0 ] ) ) {
        return Boolean.FALSE;
      }
      if ( Context.toString( ArgList[ 0 ] ).length() == 0 ) {
        return Boolean.FALSE;
      }

      String email = Context.toString( ArgList[ 0 ] );
      if ( email.indexOf( '@' ) == -1 || email.indexOf( '.' ) == -1 ) {
        return Boolean.FALSE;
      }

      isValid = Boolean.TRUE;

    } catch ( Exception e ) {
      throw Context.reportRuntimeError( "Error in isMailValid function: " + e.getMessage() );
    }
    return isValid;
  } else {
    throw Context.reportRuntimeError( "The function call isMailValid is not valid" );
  }
}
 
Example 12
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 5 votes vote down vote up
public static void LoadScriptFromTab( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                      Function FunctionContext ) {
  try {
    for ( int i = 0; i < ArgList.length; i++ ) { // don't worry about "undefined" arguments
      String strToLoad = Context.toString( ArgList[ i ] );
      String strScript = actualObject.get( strToLoad, actualObject ).toString();
      actualContext.evaluateString( actualObject, strScript, "_" + strToLoad + "_", 0, null );
    }
  } catch ( Exception e ) {
    // TODO: DON'T EAT EXCEPTION
    // System.out.println(e.toString());
  }
}
 
Example 13
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 5 votes vote down vote up
public static Object str2RegExp( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                 Function FunctionContext ) {
  String[] strArr = null;
  if ( ArgList.length == 2 ) {
    try {
      if ( isNull( ArgList, new int[] { 0, 1 } ) ) {
        return null;
      } else if ( isUndefined( ArgList, new int[] { 0, 1 } ) ) {
        return Context.getUndefinedValue();
      }
      String strToMatch = Context.toString( ArgList[ 0 ] );
      Pattern p = Pattern.compile( Context.toString( ArgList[ 1 ] ) );
      Matcher m = p.matcher( strToMatch );
      if ( m.matches() && m.groupCount() > 0 ) {
        strArr = new String[ m.groupCount() ];
        for ( int i = 1; i <= m.groupCount(); i++ ) {
          strArr[ i - 1 ] = m.group( i );
        }
      }
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( e.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call str2RegExp requires 2 arguments." );
  }
  return strArr;
}
 
Example 14
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static String getEnvironmentVar( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {
  String sRC = "";
  if ( ArgList.length == 1 ) {
    try {

      String sArg1 = Context.toString( ArgList[0] );
      // PDI-1276 Function getEnvironmentVar() does not work for user defined variables.
      // check if the system property exists, and if it does not, try getting a Kettle var instead
      if ( System.getProperties().containsValue( sArg1 ) ) {
        sRC = System.getProperty( sArg1, "" );
      } else {
        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] );
          sRC = scm.getVariable( sArg1, "" );
        } else {
          // running in test mode, return ""
          sRC = "";
        }

      }

    } catch ( Exception e ) {
      sRC = "";
    }
  } else {
    throw Context.reportRuntimeError( "The function call getEnvironmentVar requires 1 argument." );
  }
  return sRC;
}
 
Example 15
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static void LoadScriptFromTab( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {
  try {
    for ( int i = 0; i < ArgList.length; i++ ) { // don't worry about "undefined" arguments
      String strToLoad = Context.toString( ArgList[i] );
      String strScript = actualObject.get( strToLoad, actualObject ).toString();
      actualContext.evaluateString( actualObject, strScript, "_" + strToLoad + "_", 0, null );
    }
  } catch ( Exception e ) {
    // System.out.println(e.toString());
  }
}
 
Example 16
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static Object getFiscalDate( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {

  if ( ArgList.length == 2 ) {
    try {
      if ( isNull( ArgList ) ) {
        return null;
      } else if ( isUndefined( ArgList ) ) {
        return Context.getUndefinedValue();
      }
      java.util.Date dIn = (java.util.Date) Context.jsToJava( ArgList[0], java.util.Date.class );
      Calendar startDate = Calendar.getInstance();
      Calendar fisStartDate = Calendar.getInstance();
      Calendar fisOffsetDate = Calendar.getInstance();
      startDate.setTime( dIn );
      Format dfFormatter = new SimpleDateFormat( "dd.MM.yyyy" );
      String strOffsetDate = Context.toString( ArgList[1] ) + String.valueOf( startDate.get( Calendar.YEAR ) );
      java.util.Date dOffset = (java.util.Date) dfFormatter.parseObject( strOffsetDate );
      fisOffsetDate.setTime( dOffset );

      String strFisStartDate = "01.01." + String.valueOf( startDate.get( Calendar.YEAR ) + 1 );
      fisStartDate.setTime( (java.util.Date) dfFormatter.parseObject( strFisStartDate ) );
      int iDaysToAdd = (int) ( ( startDate.getTimeInMillis() - fisOffsetDate.getTimeInMillis() ) / 86400000 );
      fisStartDate.add( Calendar.DATE, iDaysToAdd );
      return fisStartDate.getTime();
    } catch ( Exception e ) {
      throw Context.reportRuntimeError( e.toString() );
    }
  } else {
    throw Context.reportRuntimeError( "The function call getFiscalDate requires 2 arguments." );
  }

}
 
Example 17
Source File: DataFrameAdapter.java    From joinery with GNU General Public License v3.0 5 votes vote down vote up
public static Scriptable jsConstructor(final Context ctx, final Object[] args, final Function ctor, final boolean newExpr) {
    if (args.length == 3 && args[0] instanceof NativeArray) {
        final List<List<Object>> data = new ArrayList<>();
        final NativeArray array = NativeArray.class.cast(args[2]);
        final Object[] ids = array.getIds();
        for (int i = 0; i < array.getLength(); i++) {
            data.add(asList(array.get((int)ids[i], null)));
        }
        return new DataFrameAdapter(
                new DataFrame<Object>(
                        asList(args[0]),
                        asList(args[1]),
                        data
                    )
            );
    } else if (args.length == 2 && args[0] instanceof NativeArray) {
        return new DataFrameAdapter(new DataFrame<Object>(
                asList(args[0]),
                asList(args[1])
            ));
    } else if (args.length == 1 && args[0] instanceof NativeArray) {
        return new DataFrameAdapter(new DataFrame<Object>(
                asList(args[0])
            ));
    } else if (args.length > 0) {
        final String[] columns = new String[args.length];
        for (int i = 0; i < args.length; i++) {
            columns[i] = Context.toString(args[i]);
        }
        return new DataFrameAdapter(new DataFrame<>(columns));
    }
    return new DataFrameAdapter(new DataFrame<>());
}
 
Example 18
Source File: ScriptValuesAddedFunctions.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static String Alert( Context actualContext, Scriptable actualObject, Object[] ArgList,
  Function FunctionContext ) {

  SpoonInterface spoon = SpoonFactory.getInstance();
  if ( ArgList.length == 1 && spoon != null ) {
    String strMessage = Context.toString( ArgList[0] );
    boolean ok = spoon.messageBox( strMessage, "Alert", true, Const.INFO );
    if ( !ok ) {
      throw new RuntimeException( "Alert dialog cancelled by user." );
    }
  }

  return "";
}
 
Example 19
Source File: ScriptValuesAddedFunctions.java    From hop with Apache License 2.0 4 votes vote down vote up
public static boolean LuhnCheck( Context actualContext, Scriptable actualObject, Object[] ArgList,
                                 Function FunctionContext ) {

  boolean returnCode = false;

  if ( ArgList.length == 1 ) {
    if ( !isNull( ArgList ) && !isUndefined( ArgList ) ) {
      try {
        int sum = 0;
        int digit = 0;
        int addend = 0;
        boolean timesTwo = false;
        String argstring = Context.toString( ArgList[ 0 ] );

        for ( int i = argstring.length() - 1; i >= 0; i-- ) {
          digit = Integer.parseInt( argstring.substring( i, i + 1 ) );
          if ( timesTwo ) {
            addend = digit * 2;
            if ( addend > 9 ) {
              addend -= 9;
            }
          } else {
            addend = digit;
          }
          sum += addend;
          timesTwo = !timesTwo;
        }

        int modulus = sum % 10;
        if ( modulus == 0 ) {
          returnCode = true;
        }
      } catch ( Exception e ) {
        // No Need to throw exception
        // This means that input can not be parsed to Integer
      }

    }
  } else {
    throw Context.reportRuntimeError( "The function call LuhnCheck requires 1 argument." );

  }
  return returnCode;
}
 
Example 20
Source File: JsThread.java    From JsDroidCmd with Mozilla Public License 2.0 4 votes vote down vote up
private JsResult dowork() {
	String scriptDir = null;
	mJsGlobal.pkg = mJsUseCase.pkg;
	if (mJsUseCase.filename != null) {
		scriptDir = new File(mJsUseCase.filename).getParent();
		mJsGlobal.scriptDir = scriptDir;
		mJsGlobal.put("scriptDir", mJsGlobal, scriptDir);
	} else if (mJsUseCase.directory != null) {
		scriptDir = new File(mJsUseCase.directory).getPath();
		mJsGlobal.put("scriptDir", mJsGlobal, scriptDir);
		mJsGlobal.scriptDir = scriptDir;
	}
	// mJsGlobal.put("config", mJsGlobal, mJsUseCase.options);
	mContext = Context.enter();
	mContext.setOptimizationLevel(-1);
	mContext.setDebugger(JsDebug.getInstance(), null);
	String source = null;
	String sourceName = "<script>";

	switch (mJsUseCase.type) {
	case JsUserCase.TYPE_TEXT:
		source = mJsUseCase.source;
		sourceName = "<script>";
		break;
	case JsUserCase.TYPE_FILE:
		source = JsInclude.readSource(mJsUseCase.filename, scriptDir);
		sourceName = mJsUseCase.filename;
		break;
	case 2:
		mJsUseCase.filename = mJsUseCase.directory + File.separator
				+ "main.js";
		source = JsInclude.readSource(mJsUseCase.filename, scriptDir);
		sourceName = mJsUseCase.filename;
		break;
	}
	JsResult jsResult;
	jsResult = new JsResult();
	try {
		if (source == null) {
			// 加载main.apk
			source = "loadapk('main.apk');include('main.js');";
			sourceName = "<loadapk>";
		}
		jsResult.result = mContext.evaluateString(mJsGlobal, source,
				sourceName, 1, null);
		jsResult.result = Context.toString(jsResult.result);
		jsResult.type = JsResult.RESULT_OK;
	} catch (Throwable e) {
		if (e instanceof JsStopException) {
			jsResult.type = JsResult.RESULT_OK;
			jsResult.result = "停止";
		} else {
			jsResult.type = JsResult.RESULT_ERR;
			jsResult.result = e.getMessage();
		}

	} finally {
		Context.exit();
	}
	return jsResult;
}