Examples of PersevereNativeFunction


Examples of org.persvr.javascript.PersevereNativeFunction

  }
  public static void setupQuery() {
    Scriptable global = GlobalData.getGlobalScope();
    Scriptable queryConstructor = (Scriptable) global.get("Query",global);
    Scriptable queryPrototype = (Scriptable) queryConstructor.get("prototype",queryConstructor);
    queryPrototype.put("__iterator__", queryPrototype, new PersevereNativeFunction(){

      @Override
      public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
        IteratorObject iterator = new IteratorObject(((List) thisObj).iterator());
        ScriptRuntime.setObjectProtoAndParent(iterator, GlobalData.getGlobalScope());
View Full Code Here

Examples of org.persvr.javascript.PersevereNativeFunction

  }
  public PjsLibrary() {
    super();
   
   
    set("load", new PersevereNativeFunction("load") {
      @Override
      public Object profilableCall(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        if(args.length < 1 || !(args[0] instanceof String))
          throw ScriptRuntime.constructError("TypeError", "load must be called with a string parameter");
        Identification id = Identification.idForString((String) args[0]);
        if(id instanceof JsonPath){
          // we can add parameters if it is a JsonPath expression
          List parameters = new ArrayList();
          for(int i = 1; i < args.length; i++){
            if(!(args[i] instanceof Function) || i + 1 != args.length){
              parameters.add(args[i]);
            }
          }
          ((JsonPath)id).setParameters(parameters.toArray());
        }
        Object object = id.getTarget();
        if (args.length > 1 && args[args.length - 1] instanceof Function) {// call the callback if necessary
          ((Function)args[args.length - 1]).call(cx, scope, thisObj, new Object[]{object});
        }
        return object;
      }
     
    },true,true);
    set("remove", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        if(args.length == 0 || !(args[0] instanceof Persistable))
          throw ScriptRuntime.constructError("TypeError", "remove requires a persistable object");
        ((Persistable)args[0]).delete();
        return true;
      }
     
    },true,true);
    set("get", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        Object value = ScriptRuntime.getObjectElem(args[0], args[1], cx);
        if (args.length > 2) {// call the callback if necessary
          ((Function)args[2]).call(cx, scope, thisObj, new Object[]{value});
        }
        return value;
      }
    },true,true);
    set("set", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        ((Persistable)args[0]).set((String)args[1], args[2]);
        return args[2];
      }
    },true,true);
    set("commit", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        Transaction.currentTransaction().commit();
        Transaction.startTransaction();
        return null;
      }
    },true,true);
    set("rollback", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        Transaction.startTransaction(); // abandon the old transaction
        return null;
      }
    },true,true);
/*    set("changing", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
       
        return null;
      }
    });
    set("save", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
       
        return null;
      }
    });*/
    set("getAccessLevel", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        if(args.length == 0 || !(args[0] instanceof Persistable))
          throw ScriptRuntime.constructError("TypeError", "getAccessLevel requires a persistable object");
        return ((Persistable)args[0]).getAccessLevel();
      }
    },false,true);
    set("hasAccessLevel", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        if(args.length == 0 || !(args[0] instanceof Persistable))
          throw ScriptRuntime.constructError("TypeError", "hasAccessLevel requires a persistable object");
        Integer level = Capability.getPermissionLevelForString((String) args[1]);
        return level == null ? false : level <= ((Persistable)args[0]).getAccessLevel();
      }
    },true,true);
    set("getId", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        if(args.length == 0 || !(args[0] instanceof Persistable))
          throw ScriptRuntime.constructError("TypeError", "getId requires a persistable object");

        return ((Persistable)args[0]).getId().toString();
      }
    },false,true);
    set("getParent", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        if(args.length == 0 || !(args[0] instanceof Persistable))
          throw ScriptRuntime.constructError("TypeError", "getParent requires a persistable object");

        return ((Persistable)args[0]).getParent();
      }
    },true, false);
    set("getVersions", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        if(args.length == 0 || !(args[0] instanceof Persistable))
          throw ScriptRuntime.constructError("TypeError", "getVersions requires a persistable object");
        // TODO: it would be nice to make a little more lazy version of this
        String baseId = ((Persistable)args[0]).getId() + "-v";
        Version version = ((Persistable)args[0]).getVersion();
        List versions = Persevere.newArray();
        if(version == null)
          return versions;
        int versionCount = version.getVersionNumber();
        for(int i = 0; i < versionCount; i++){
          versions.add(ObjectId.idForString(baseId + (i + 1)));
        }
        return versions;
      }
    },true, false);
    set("isPersisted", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        if(args.length == 0 || !(args[0] instanceof Persistable))
          throw ScriptRuntime.constructError("TypeError", "isPersisted requires a persistable object");

        return ((Persistable)args[0]).getId().isPersisted();
      }
    },false,true);
    set("getUserName", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        return UserSecurity.getUserName();
      }
    },false,true);
    set("getCurrentUser", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        return UserSecurity.currentUser();
      }
    },true,true);
    set("loggedInUsers", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        Boolean onlyConnected = args.length > 0 && Boolean.TRUE.equals(args[0]);
        Set users = new HashSet();
        for (Map.Entry<String, Client> entry : EventStream.streams.entrySet()){
          Client client = entry.getValue();
          if(!onlyConnected || client.isConnected()){
            Object user = client.getAuthorizedUser();
            if(user != null)
              users.add(user);
          }
        }
        return new PersistableArray(users.toArray());
      }
    },false,true);
    set("putHandler", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        // temporarily here until PersistableClass puts it's own version in
        return null;
      }
    },false,true);
    set("deserialize", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        return new JsonReceiver().convertJsonStringToObject((String) args[0]);
      }
    },true,false);
    set("serialize", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        final StringWriter writer = new StringWriter();
       
        IndividualRequest request = Client.getCurrentObjectResponse();
        HttpServletResponse currentResponse = request.getHttpResponse();
        request.setHttpResponse(new HttpServletResponse(){

          public void addCookie(Cookie arg0) {
          }

          public void addDateHeader(String arg0, long arg1) {
          }

          public void addHeader(String arg0, String arg1) {
          }

          public void addIntHeader(String arg0, int arg1) {
          }

          public boolean containsHeader(String arg0) {
            return false;
          }

          public String encodeRedirectUrl(String arg0) {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public String encodeRedirectURL(String arg0) {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public String encodeUrl(String arg0) {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public String encodeURL(String arg0) {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public void sendError(int arg0, String arg1) throws IOException {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public void sendError(int arg0) throws IOException {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public void sendRedirect(String arg0) throws IOException {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public void setDateHeader(String arg0, long arg1) {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public void setHeader(String arg0, String arg1) {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public void setIntHeader(String arg0, int arg1) {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public void setStatus(int arg0, String arg1) {
          }

          public void setStatus(int arg0) {
          }

          public void flushBuffer() throws IOException {
          }

          public int getBufferSize() {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public String getCharacterEncoding() {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public String getContentType() {
            return "application/json";
          }

          public Locale getLocale() {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public ServletOutputStream getOutputStream() throws IOException {
            return new ServletOutputStream(){

              @Override
              public void write(byte[] b) throws IOException {
                writer.write(new String(b));
              }

              @Override
              public void write(int b) throws IOException {
                writer.write(new String(new byte[]{(byte) b}));
               
              }
             
            };
           
          }

          public PrintWriter getWriter() throws IOException {
            return new PrintWriter(writer);
          }

          public boolean isCommitted() {
            throw new UnsupportedOperationException("Not implemented yet");
          }

          public void reset() {
          }

          public void resetBuffer() {
          }

          public void setBufferSize(int arg0) {
          }

          public void setCharacterEncoding(String arg0) {
          }

          public void setContentLength(int arg0) {
          }

          public void setContentType(String arg0) {
          }

          public void setLocale(Locale arg0) {
          }
         
        });
        try{
          DataSerializer.serialize(args[0], args.length > 1 ? (String) args[1] : null);
        }finally{
          request.setHttpResponse(currentResponse);
        }
        return writer.toString();
      }
    },true,false);
    set("_setIdSequence", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        try {
          if(!UserSecurity.hasPermission("setIdSequence")){
            throw ScriptRuntime.constructError("AccessError", "You do not have access to the set the id sequence");
          }
          ((UserAssignableIdSource) DataSourceManager.getSource(((Persistable)args[0]).getId().subObjectId)).setIdSequence(((Number)args[1]).longValue());
        } catch (ClassCastException e) {
          throw ScriptRuntime.constructError("TypeError", "Must pass in a class and a number");
        }
        return null;
      }
    },false,true);
    set("freezeDatabase", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        if(!UserSecurity.hasPermission("freezeDatabase")){
          throw ScriptRuntime.constructError("AccessError", "You do not have access to freeze the database");
        }
        JavaScriptDBSource.getDatabase().freeze();
        return null;
      }
    },false,true);
    set("unfreezeDatabase", new PersevereNativeFunction() {
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        if(!UserSecurity.hasPermission("freezeDatabase")){
          throw ScriptRuntime.constructError("AccessError", "You do not have access to freeze the database");
View Full Code Here

Examples of org.persvr.javascript.PersevereNativeFunction

   
    creating = false;
  }
  static void delegateToGlobalHandler(Scriptable security, final String name){
    final Scriptable global = GlobalData.getGlobalScope();
    security.put(name, security, new PersevereNativeFunction() {
      @Override
      public Object call(final Context cx, final Scriptable scope,
          final Scriptable thisObj, Object[] args) {
        return ((Function)global.get(name, global)).call(cx, scope, thisObj, args);
        }
View Full Code Here

Examples of org.persvr.javascript.PersevereNativeFunction

    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.persvr.javascript.PersevereNativeFunction

    Scriptable global = GlobalData.getGlobalScope();
    createUserHandler = (Function) global.get("createUser", global);
    grantAccessHandler = (Function) global.get("grantAccess", global);
    final Function doAuthentication = (Function) global.get("authenticate", global);
    // create a wrapper to record the authenticated user in the current thread
    authenticateHandler = new PersevereNativeFunction(){
      @Override
      public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
        Object user = doAuthentication.call(cx, scope, thisObj, args);
        UserSecurity.registerThisThread(user);
        return user;
View Full Code Here

Examples of org.persvr.javascript.PersevereNativeFunction

    Object methods = get("methods");
    if (methods instanceof Persistable) {
      for(Map.Entry<String,Object> entry : ((Persistable)methods).entrySet(0)){
        final String name = entry.getKey();
        if (!ScriptableObject.hasProperty(prototypeProperty, name)){
          prototypeProperty.put(name, prototypeProperty, new Method(new PersevereNativeFunction(){
            @Override
            public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
              throw ScriptRuntime.constructError("TypeError", "The method " + name + " has a definition but does not have an implementation on the prototype object");
            }
            @Override
            public Object get(String name, Scriptable start) {
              if ("toString".equals(name)) {
                return new PersevereNativeFunction(){
                  public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
                    return "function(){\n\tthrow new TypeError(\"The method has a definition but does not have an implementation on the prototype object\")\n}";
                  }
                };
              }
View Full Code Here

Examples of org.persvr.javascript.PersevereNativeFunction

   * @param rootSchema
   */
  public static void setupSchema(PersistableClass rootSchema) {
    Scriptable pjsLibrary = (Scriptable) GlobalData.getGlobalScope().get("pjs",GlobalData.getGlobalScope());
    //TODO: move eval into PjsLibrary class
    pjsLibrary.put("eval", pjsLibrary, new PersevereNativeFunction() {
      @Override
      public Object call(final Context cx, final Scriptable scope,
          final Scriptable thisObj, Object[] args) {
        if (!UserSecurity.hasPermission(SystemPermission.javaScriptCoding))
          throw new SecurityException("User is not permitted to execute code on the server");
        return cx.evaluateString(GlobalData.getGlobalScope(), (String) args[0], "console", 0, null);
      }     
    });
    BaseFunction putHandler = new PersevereNativeFunction() {
      @Override
      public Object call(final Context cx, final Scriptable scope,
          final Scriptable thisObj, Object[] args) {
        // check to make sure all the objects are valid after a schema change
        // TODO: The performance of this could be greatly improved with more information from the put
        PersistableClass schema = (PersistableClass) thisObj;
        if (schema != null) {
          Object propertiesDefinitions = schema.get("properties");
          if (propertiesDefinitions instanceof Persistable && schema.getPrototypeProperty() instanceof Persistable) {
            Persistable prototype = (Persistable) schema.getPrototypeProperty();
              for (Object key : prototype.getIds())
                if (key instanceof String)
                  enforceSchemaForProperty(schema, prototype, (String) key, prototype.get((String) key), true, true, false);
              List<Persistable> instances = (List) schema.get("instances");
              Object[] propertyIds = ((Persistable)propertiesDefinitions).getIds();
              List<String> stringList = new ArrayList();
              for (Object property : propertyIds){
                if (property instanceof String)
                  stringList.add((String) property);
              }
              String[] stringKeys = new String[stringList.size()];
              stringList.toArray(stringKeys);
              for (String key : stringKeys) {
                Object propertyDef = ((Persistable)propertiesDefinitions).get(key);
                //TODO: Allow it to point to another a schema's properties object
                if (propertyDef instanceof Persistable && !(propertyDef instanceof PersistableClass)) {
                  if (((Persistable)propertyDef).get("properties") instanceof Persistable)
                    throw new RuntimeException("Can not create an object validator that does not reference an existing schema");
                }
              }
              if(Boolean.TRUE.equals(schema.get("checkAllInstancesOnSchemaChange", schema))) {
                for (Persistable instance : instances){
                  for (String key : stringKeys) {
                    enforceSchemaForProperty(schema, instance, key, ScriptableObject.getProperty(instance, key), true, true, false);
                  }
                }
              }
          }
        }
        return true;
        }
      public String toString() {
        return "function(resource){/*native code*/}";
      }
    };
    putHandler.put("source", putHandler, "function(){[Native code]}");
    pjsLibrary.put("putHandler", pjsLibrary, putHandler);
    putHandler.setPrototype(ScriptableObject.getFunctionPrototype(GlobalData.getGlobalScope()));
  }
View Full Code Here

Examples of org.persvr.javascript.PersevereNativeFunction

          context = PersevereContextFactory.getContext();
          global = GlobalData.getGlobalScope();
          consoleScope = new NativeObject();
          // we may want to make this a prototype, so you can create unscoped variables without errors. Downside is it might mislead users as to what they can do in methods
          consoleScope.setParentScope(global);
          ((NativeObject) consoleScope).setGetterOrSetter("help", 0, new PersevereNativeFunction(){

            @Override
            public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
              String help = "The full Persevere API is available at the console as described in http://docs.persvr.org/documentation/server-side-js\n";
              help += "Additionally there are the following special properties available at the console:\n";
              help += "autocommit - This indicate whether or not each command should be committed immediately (otherwise you must manually commit with commit())\n";
              help += "shutdown - Shuts down Persevere\n";
              return help;
            }
           
          }, false);
          ((NativeObject) consoleScope).setGetterOrSetter("shutdown", 0, new PersevereNativeFunction(){
            @Override
            public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
              System.exit(0);
              return null;
            }
View Full Code Here

Examples of org.persvr.javascript.PersevereNativeFunction

    Scriptable applicationJson = new NativeObject();
    put("representation:application/json", this, applicationJson);
    setAttributes("representation:application/json",ScriptableObject.DONTENUM);
    applicationJson.put("quality", applicationJson, 1.0);
    applicationJson.put("output", applicationJson, new PersevereNativeFunction(){
      @Override
      public Object call(Context cx, Scriptable scope,
          Scriptable thisObj, Object[] args) {
        try {         
          HttpServletResponse response = Client.getCurrentObjectResponse().getHttpResponse();
View Full Code Here

Examples of org.persvr.javascript.PersevereNativeFunction

        else if (body instanceof Scriptable){
          Function forEach = (Function) ScriptableObject.getProperty((Scriptable) body, "forEach");
          Scriptable global = GlobalData.getGlobalScope();
          final ServletOutputStream outputStream = response.getOutputStream();
          forEach.call(PersevereContextFactory.getContext(), global, (Scriptable) body, new Object[]{
            new PersevereNativeFunction(){
              @Override
              public Object profilableCall(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
                try {
                  outputStream.write(args[0].toString().getBytes("UTF-8"));
                } catch (UnsupportedEncodingException e) {
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.