Examples of ScriptableObject


Examples of org.mozilla.javascript.ScriptableObject

      }
      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

Examples of org.mozilla.javascript.ScriptableObject

  }

  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

Examples of org.mozilla.javascript.ScriptableObject

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

Examples of org.mozilla.javascript.ScriptableObject

        // 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

Examples of org.mozilla.javascript.ScriptableObject

    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

Examples of org.mozilla.javascript.ScriptableObject

      }
    });
  }
  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

Examples of org.mozilla.javascript.ScriptableObject

        }
        initializer.setLastModified(lastModified);
        initializer.setVersion(new ObjectVersion(objectReference, previousVersionReference, lastTableChange, versionNumber,
            (objectAttributes & OBJECT_ATTRIBUTE_IS_CURRENT) == OBJECT_ATTRIBUTE_IS_CURRENT,
            (objectAttributes & OBJECT_ATTRIBUTE_IS_DELETED) == OBJECT_ATTRIBUTE_IS_DELETED));
        ScriptableObject loadedObject = (ScriptableObject) initializer.getInitializingObject();
        assert ((ObjectVersion) ((Persistable) loadedObject).getVersion()).currentVersionReference == objectReference;
        if (historic) {
          synchronized (referenceToVersions) {
            referenceToVersions.put(objectReference, (Persistable) loadedObject);
          }
          if(!(loadedObject instanceof PersistableArray)){
            //TODO: make the persistable array load everything up front so we don't have to do this
            loadedObject.sealObject();
          }
        } else
          synchronized (referenceToInstances) {
            referenceToInstances.put(objectReference, (Persistable) loadedObject);
          }
View Full Code Here

Examples of org.mozilla.javascript.ScriptableObject

  public static PersistableClass Object;
  public static PersistableClass Array;
  // create a new object when the constructor is called
  public Scriptable construct(Context cx, Scriptable scope, Object[] args) {
    if(this == Object){
      ScriptableObject newObject = new PersistableObject();
      newObject.setParentScope(globalScope);
      newObject.setPrototype(objectPrototype);
      return newObject;
    }
    if(this == Array){
      ScriptableObject newObject;
      if(args.length == 0)
        newObject = new PersistableArray(0);
      else if(args.length == 1)
        newObject = new PersistableArray(((Number)args[0]).longValue());
      else
        newObject = new PersistableArray(args);
      newObject.setParentScope(globalScope);
      newObject.setPrototype(arrayPrototype);
      return newObject;
    }
    return instantiate(cx, scope, args, true);
  }
View Full Code Here

Examples of org.mozilla.javascript.ScriptableObject

   */
  public static void serialize(Object value, String acceptTypeHeader){
    serialize(value, acceptTypeHeader, true);
  }
  public static void serialize(Object value, String acceptTypeHeader, boolean setType){
    ScriptableObject object;
    if (value instanceof Persistable){
      object = ((ScriptableObject)value);
    }else{
      object = (ScriptableObject) ScriptableObject.getClassPrototype(GlobalData.getGlobalScope(),"Object");
    }
     
    Scriptable bestRep = null;
    double bestQuality = 0;
    String bestType = null;
    if(acceptTypeHeader==null)
      acceptTypeHeader = "*/*";
    String[] acceptTypes = acceptTypeHeader.split("\\s*,\\s*");
    PersistableObject.enableSecurity(false);
    Client.getCurrentObjectResponse().requestRoot = value;
    for (String acceptType : acceptTypes){
      String[] parts = acceptType.split("\\s*;\\s*");
      String type = parts[0];
      double clientQuality = 1;
      for(String part: parts){
        if(part.startsWith("q=")){
          try {
            clientQuality = Double.parseDouble(part.substring(2));
          } catch (NumberFormatException e) {
            e.printStackTrace();
          }
        }
      }
      if("*/*".equals(type)){
        ScriptableObject proto = object;
        do {
          for (Map.Entry<String,Object> entry : PersistableObject.entrySet(proto, 5)){
            if(entry.getKey().startsWith("representation:")){
              Object rep = entry.getValue();
              if(rep instanceof ObjectId){
                rep = ((ObjectId)rep).getTarget();
              }
              if(rep instanceof Scriptable){
                Number serverQuality = (Number) ScriptableObject.getProperty((Scriptable)rep,"quality");
                double quality = serverQuality.doubleValue() + clientQuality;
                if(quality > bestQuality){
                  bestRep = (Scriptable) rep;
                  bestQuality = quality;
                  bestType = entry.getKey().substring("representation:".length());
                }
              }
             
            }
          }
          proto = (ScriptableObject) proto.getPrototype();
         
        }while(proto != null);
       
      }
      else{
View Full Code Here

Examples of org.mozilla.javascript.ScriptableObject

      // if we post to a schema, we can just consider this a post to the table
      target = (Persistable) Identification.idForString(((PersistableClass) target).getId().toString() + "/").getTarget();
    }
    if (bodyData instanceof Persistable) {
      Persistable newObject = (Persistable) bodyData;
      ScriptableObject arrayProto = (ScriptableObject) ScriptableObject.getClassPrototype(GlobalData.getGlobalScope(), "Array");
      ScriptableObject objectProto = (ScriptableObject) ScriptableObject.getClassPrototype(GlobalData.getGlobalScope(), "Object");

      if ("".equals(((Persistable) target).getId().subObjectId)
          && (((Persistable) bodyData).getPrototype() == objectProto || ((Persistable) bodyData).getPrototype() == arrayProto)) {
        // this means it is a generic object or list, we need to make it be the right class
        DataSource thisSource = ((Persistable) target).getId().source;
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.