Package org.mozilla.javascript

Examples of org.mozilla.javascript.ScriptableObject


     */
    private Scriptable prepareScope
  (Context cx, Activity activity, FormalParameter[] formPars, Map map)
        throws RemoteException {
  Scriptable scope = cx.initStandardObjects(null);
  ScriptableObject wfe = new ScriptableObject () {
    public String getClassName() {
        return "ToolAgentContext";
    }
      };
  Function fo = new FunctionBase () {
    public Object call (Context cx, Scriptable scope,
            Scriptable thisObj, Object[] args)
        throws JavaScriptException {
        if (logger.isDebugEnabled ()) {
      logger.debug ("abandon called with: " + args[0]);
        }
        throw new AbandonedException ((String)args[0]);
    }
      };
  wfe.defineProperty ("abandon", fo, ScriptableObject.PERMANENT);
        wfe.defineProperty
            ("activityUniqueKey", Context.javaToJS(activity.uniqueKey(), scope),
             ScriptableObject.PERMANENT | ScriptableObject.READONLY);
  scope.put("scriptingContext", scope, wfe);
       
  prepareArguments(cx, scope, formPars, map);
View Full Code Here


     * @param formPars the formal parameter definitons.
     * @param map the actual parameter values.
     */
    protected void prepareArguments
        (Context cx, Scriptable scope, FormalParameter[] formPars, Map map) {
        ScriptableObject args = new ScriptableObject () {
          public String getClassName() {
              return "Arguments";
          }
            };
        for (int i = 0; i < formPars.length; i++) {
            String fp = formPars[i].id();
            args.defineProperty
          (fp,
                 convertArgument(cx, scope, formPars[i].type(), map.get(fp)),
           formPars[i].mode() == FormalParameter.Mode.IN
           ? ScriptableObject.PERMANENT | ScriptableObject.READONLY
           : ScriptableObject.PERMANENT);
View Full Code Here

      return null;

    Context context = ContextFactory.getGlobal().enterContext();
    context.setApplicationClassLoader( parentClassLoader );

    ScriptableObject scope = context.initStandardObjects();

    try
    {
      for( String name : properties.keySet() )
        ScriptableObject.putProperty( scope, name, Context.javaToJS( properties.get( name ), scope ) );

      Script script = context.compileString( scriptText, "Script", 0, null );

      return script.exec( context, scope );
    }
    finally
    {
      for( String name : properties.keySet() )
        scope.delete( name );

      Context.exit();
    }
  }
View Full Code Here

      String directiveName, Iterable<String> toEscape, String soyUtilsPath)
      throws Exception {
    List<String> output = Lists.newArrayList();
    Context context = new ContextFactory().enterContext();
    context.setOptimizationLevel(-1)// Only running once.
    ScriptableObject globalScope = context.initStandardObjects();
    globalScope.defineProperty(
        "navigator", Context.javaToJS(new Navigator(), globalScope), ScriptableObject.DONTENUM);

    Reader soyutils = new InputStreamReader(new FileInputStream(soyUtilsPath), Charsets.UTF_8);
    try {
      String basename = soyUtilsPath.substring(soyUtilsPath.lastIndexOf('/') + 1);
      context.evaluateReader(globalScope, soyutils, basename, 1, null);
    } finally {
      soyutils.close();
    }

    globalScope.defineProperty(
        "test_toEscape", ImmutableList.copyOf(toEscape), ScriptableObject.DONTENUM);
    globalScope.defineProperty("test_output", output, ScriptableObject.DONTENUM);

    context.evaluateString(
        globalScope,
        Joiner.on('\n').join(
            "(function () {",
View Full Code Here

      }
      generatedJsExprsAsJsArray.append("]");

      Context context = new ContextFactory().enterContext();
      context.setOptimizationLevel(-1)// Only running once.
      ScriptableObject globalScope = context.initStandardObjects();
      NativeObject navigator = new NativeObject();
      ScriptableObject.putConstProperty(navigator, "userAgent", "testZilla");
      globalScope.defineProperty("navigator", navigator, ScriptableObject.DONTENUM);

      try {
        String soyutilsPath = getSoyUtilsPath();
        Reader soyutils = new InputStreamReader(new FileInputStream(soyutilsPath), Charsets.UTF_8);
        try {
View Full Code Here

  }

  private <T> T runInContext(
      Context context, Map<String, ?> actuals, Class<T> expectedResultType)
      throws AbnormalExitException {
    ScriptableObject globalScope = context.initStandardObjects();
    try {
      globalScope.defineProperty(
          "scriptEngine___", new ScriptPowerBox(context, globalScope),
          ScriptableObject.DONTENUM);
      Object eval = actuals.remove("eval___");
      ScriptableObject.putProperty(globalScope, "eval___", eval);
      for (Map.Entry<String, ?> e : actuals.entrySet()) {
        globalScope.defineProperty(
            e.getKey(),
            Context.javaToJS(e.getValue(), globalScope),
            ScriptableObject.DONTENUM);
      }
View Full Code Here

public class SlingContext extends Context {

    @Override
    public ScriptableObject initStandardObjects(ScriptableObject scope,
            boolean sealed) {
        ScriptableObject rootScope = super.initStandardObjects(scope, sealed);

        // prepare the ImporterToplevel host object because it will be
        // used as top level scope for the RhinoJavaScriptEngine but is
        // not initialized with the rest of the standard objects
        ImporterTopLevel.init(this, rootScope, sealed);
View Full Code Here

        // build the code, something like
        //  data = <jsonData> ;
        //  <code>
        final String jsCode = "data=" + jsonData + ";\n" + code;
        final Context rhinoContext = Context.enter();
        final ScriptableObject scope = rhinoContext.initStandardObjects();

        // execute the script, out script variable maps to sw
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        ScriptableObject.putProperty(scope, "out", Context.javaToJS(pw, scope));
View Full Code Here

    Transaction previousTransaction = Transaction.currentTransaction();
    int pathsCount = (int) pathsArray.getLength();
    File jslibFile = null;
    String filename;
    String oldJsLibPath = currentJslibPath;
    ScriptableObject exportObject;
    try {
      if(args[0] instanceof File){
        jslibFile = (File) args[0];
        filename = jslibFile.getCanonicalPath();
        filename = filename.replace(File.separatorChar, '/');
        for(int i = 0; i < pathsCount; i++){
          String path = pathsArray.get(i, pathsArray).toString();
          path = new File(path).getCanonicalPath().replace(File.separatorChar, '/');
          if(path.length() > 0 && !(path.endsWith("/") || path.endsWith(File.separator)))
            path += '/';
          if(filename.indexOf(path) > -1){
            filename = filename.substring(filename.indexOf(path) + path.length());
            break;
          }
        }
      }
      else {
        filename = args[0].toString();
        if(filename.startsWith("."))
          filename = currentJslibPath + filename;
        filename = Pattern.compile("[^\\/]*\\/\\.\\.\\/").matcher(filename).replaceAll("");
        filename = filename.replace("./", "");
        for(int i = 0; i < pathsCount; i++){
          String path = pathsArray.get(i, pathsArray).toString();
          if(path.length() > 0 && !(path.endsWith("/") || path.endsWith(File.separator)))
            path += '/';
          jslibFile = new File(path + filename);
          if(jslibFile.isFile())
            break;
          if(!filename.endsWith(".js")){
            filename += ".js";
            jslibFile = new File(path + filename);
            if(jslibFile.isFile())
              break;
          }
        }
      }
      String id = filename;
      if (filename.endsWith(".js"))
        id = filename.substring(0, filename.length() - 3);
      if(jslibFile == null || !jslibFile.isFile())
        throw ScriptRuntime.constructError("Error", "File not found " + filename);
      exportObject = exports.get(jslibFile);
      Long lastTimeStamp = lastTimeStamps.get(jslibFile);
      if(lastTimeStamp == null || lastTimeStamp < jslibFile.lastModified()){
        Transaction.startTransaction();
        lastTimeStamps.put(jslibFile, jslibFile.lastModified());
        FileInputStream inStream = new FileInputStream(jslibFile);
        exportObject = new NativeObject();
        ScriptRuntime.setObjectProtoAndParent((ScriptableObject) exportObject, global);
        ScriptableObject moduleObject = new NativeObject();
        ScriptRuntime.setObjectProtoAndParent((ScriptableObject) moduleObject, global);
        moduleObject.put("id", moduleObject, id);
        // setup the module scope
        ScriptableObject moduleScope = new NativeObject();
        moduleScope.setParentScope(global);
        int lastSlash = filename.lastIndexOf('/');
        currentJslibPath = lastSlash == -1 ? "" : filename.substring(0,lastSlash + 1);
        moduleScope.put("exports", moduleScope, exportObject);
        moduleScope.put("module", moduleScope, moduleObject);
        // memoize
        exports.put(jslibFile, exportObject);
        // evaluate the script
        try {
          cx.evaluateString(moduleScope, IOUtils.toString(inStream, "UTF-8"), filename, 1, null);
        } catch (RuntimeException e) {
          // revert
          exports.remove(jslibFile);
          throw e;
        }
        // re-retrieve it in case the library changed it
        exportObject = (ScriptableObject) moduleScope.get("exports", moduleScope);
        exports.put(jslibFile, exportObject);

        if("jsgi-app.js".equals(filename)){
          // handle jackconfig.js, setting up the app if it is there
          global.put("app", global, exportObject.get("app", exportObject));
View Full Code Here

      }
    });
  }
  public static void setupSecurity() {
    Scriptable global = GlobalData.getGlobalScope();
    ScriptableObject security = new NativeObject();
    global.put("security", global, security);
   
    global.put("createUser", global, createUserHandler);
    delegateToGlobalHandler(security,"createUser");
    global.put("grantAccess", global, grantAccessHandler);
    delegateToGlobalHandler(security,"grantAccess");
    global.put("authenticate", global, authenticateHandler);
    delegateToGlobalHandler(security,"authenticate");
    global.put("getAccessLevel", global, getAccessLevelHandler);
    delegateToGlobalHandler(security,"getAccessLevel");
    global.put("hasAccessLevel", global, hasAccessLevelHandler);
    delegateToGlobalHandler(security,"hasAccessLevel");
    global.put("hasPermission", global, hasPermissionHandler);
    delegateToGlobalHandler(security,"hasPermission");
    security.put("getCapabilities", security, new PersevereNativeFunction() {
      @Override
      public Object call(final Context cx, final Scriptable scope,
          final Scriptable thisObj, Object[] args) {
        Object user;
        if(args.length == 0 || args[0] == Undefined.instance){
          user = UserSecurity.currentUser();
        }else if (args[0] instanceof String){
          user = CapabilityUser.getUserByUsername((String)args[0]);
        }else
          user = args[0];
        Capability[] capabilities = getCapabilitiesForUser(user);
        List capArray = Persevere.newArray();
        if(capabilities != null)
          capArray.addAll(Arrays.asList(capabilities));
        return capArray;
        }
      public String toString() {
        return "function(target,resource,accessLevel){/*native code*/}";
      }
    });
    security.put("_refresh", security, new PersevereNativeFunction() {
      @Override
      public Object call(final Context cx, final Scriptable scope,
          final Scriptable thisObj, Object[] args) {
        Capability capability = ((Capability)args[0]);
        capability.allGranted = null;
        capability.computedPermissions.clear();
        Transaction currentTransaction = Transaction.suspendTransaction();
        List<Object> oldMembers = new ArrayList(capability.getAllMembers());
        if(currentTransaction!=null) currentTransaction.enterTransaction();
        List<Object> newMembers = args.length == 1 ?
            new ArrayList(capability.getAllMembers()) :
              new ArrayList();
        oldMembers.removeAll(newMembers);
        for (Object member : oldMembers){
          capability.removeFromUserCapabilities(member);
        }
        for (Object member : newMembers){
          capability.addToUserCapabilities(member);
        }
        return true;
        }
      public String toString() {
        return "function(content, target, property){/*native code*/}";
      }
    });
    security.put("changePassword", security, new PersevereNativeFunction() {
      @Override
      public Object call(final Context cx, final Scriptable scope,
          final Scriptable thisObj, Object[] args) {
        final Object user = UserSecurity.currentUser();
        if(user == null){
          throw new SecurityException("Can not change the user's password, no user is logged in");
        }
        if(!(user instanceof CapabilityUser)){
          throw new SecurityException("Can not change the user's password, the current user is not Persevere defined user");
        }
        ((CapabilityUser)user).setPassword(args[0].toString());
        return true;
        }
      public String toString() {
        return "function(newPassword){/*native code*/}";
      }
    });
    security.setGetterOrSetter("currentUser", 0, new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        return UserSecurity.currentUser();
      }
View Full Code Here

TOP

Related Classes of org.mozilla.javascript.ScriptableObject

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.