Package org.mozilla.javascript

Examples of org.mozilla.javascript.NativeObject


      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

   * @param target
   * @param jsonPath
   * @return
   */
  private Object doJsonPath(Persistable target, String jsonPath) {
    Scriptable paramScope = new NativeObject();
    if (jsonPath.matches("new "))
      throw new RuntimeException("Invalid query");
    if (jsonPath.matches("[^\\?\\+\\=\\-\\*\\/\\!]\\("))
      throw new RuntimeException("Invalid query");
    if (parameters != null) {
      int poundIndex;
      while((poundIndex = jsonPath.indexOf('$', 1)) > -1) {
        int i = Integer.parseInt(jsonPath.substring(poundIndex + 1, poundIndex + 2)) - 1;
        jsonPath = jsonPath.substring(0,poundIndex) + "args.param" + i + jsonPath.substring(poundIndex + 2)
        paramScope.put("param" + i, paramScope, parameters[i]);
      }
    }
    //TODO: Once we have more of the JSONQuery expressions being handled at the data source
    //  level, we should set the optimization level to -1 for quicker evaluation:
    PersevereContextFactory.getContext().setOptimizationLevel(-1);
View Full Code Here

        log.warn("no test files found - exiting");
        System.exit(1);
      }
      for (final File testFile : testFiles){
        log.info("Testing " + testFile.getName());
        final Scriptable scope = new NativeObject();
        scope.setParentScope(GlobalData.getGlobalScope());

        // execute the script, the TestRunner will provide the necessary API
        UserSecurity.doPriviledgedAction(new PrivilegedAction(){
          public Object run() {
            try {
View Full Code Here

    public static final int EXECUTE = 3;
    public static final int APPEND = 4;
    public static final int ACCESS_PERMISSION_LEVEL = 6;
    /** Creates a new instance of ObjectAccessDeniedException */
    public ObjectAccessDeniedException(final Persistable data, final int requestedAction) {
    super(new NativeObject(){
      public Object getDefaultValue(Class typeHint){
            if (requestedAction == BROWSE || requestedAction == LIMITED)
                return "Access denied to " + data + " you do not have any permission";
            if (requestedAction == READ)
                return "Access denied to " + data + " you do not have read permission";
View Full Code Here

        }
       
        return parameters;
  }
  public NativeObject getParametersAndHeadersAsJsObject() {
    NativeObject parameters = Persevere.newObject();
       
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
          String name = (String) headerNames.nextElement();
            parameters.put(name,parameters,request.getHeader(name));
        }
        if (request.getQueryString() != null)
          try {
        // _MUST NOT_ read the body (getInputStream) or call getParameter, because that destroys it for later use
        for (String nameValueStr : request.getQueryString().split("&")) { // parse the query string
          String[] nameValue = nameValueStr.split("=",2);
          if (nameValue.length == 2)
            parameters.put(URLDecoder.decode(nameValue[0],"UTF-8"), parameters, URLDecoder.decode(nameValue[1],"UTF-8"));
        }
          }
          catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
          }
View Full Code Here

          Client connection = new Client("console");
          // give this thread a context/user
          Client.registerThisConnection(connection.getIndividualRequest(null, null));
          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
View Full Code Here

  public static SMD instance = new SMD();
  static SMDServices servicesInstance;
  private SMD(){           
    setPrototype(ScriptableObject.getClassPrototype(GlobalData.getGlobalScope(),"Object"));

    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

public class ObjectNotFoundException extends EcmaError {
 

  public ObjectNotFoundException(final DataSource source, final String resource) {
    super(new NativeObject(){
      public Object getDefaultValue(Class typeHint){
        return (source == null ? "" : source.getId() + '/') + resource + " not found";
      }
    }, null,0,0,null);
    this.source = source;
View Full Code Here

        }
        if(seqId>=0){
          client.addSequenceId(seqId);
        }
      }
      NativeObject env = new PersistableObject() {
        public Object get(String key, Scriptable start) {
          Object storedValue = super.get(key, start);
          if(storedValue != ScriptableObject.NOT_FOUND)
            return storedValue;
          if ("REQUEST_METHOD".equals(key)) {
            return request.getMethod();
          }
          if ("SERVLET_REQUEST".equals(key)) {
            return request;
          }
          if ("SERVLET_RESPONSE".equals(key)) {
            return response;
          }
          if ("PERSEVERE_REQUEST_HELPER".equals(key)) {
            return rh;
          }
          if ("SERVLET_FILTER_CHAIN".equals(key)) {
            return filterChain;
          }
          if ("SCRIPT_NAME".equals(key)) {
            return request.getServletPath();
          }
          if ("PATH_INFO".equals(key)) {
            String path = request.getRequestURI();
            return path.substring(request.getContextPath().length());
          }
          if ("CONTENT_TYPE".equals(key)) {
            return request.getContentType();
          }
          if ("CONTENT_LENGTH".equals(key)) {
            return request.getContentLength();
          }
          if ("QUERY_STRING".equals(key)) {
            return request.getQueryString();
          }
          if ("SERVER_NAME".equals(key)) {
            return request.getServerName();
          }
          if ("SERVER_PORT".equals(key)) {
            return request.getServerPort();
          }
          if ("SERVER_PROTOCOL".equals(key)) {
            return request.getProtocol();
          }
          if ("jsgi.version".equals(key)) {
            List array = Persevere.newArray();
            array.add(0);
            array.add(1);
            return array;
          }
          if ("jsgi.url_scheme".equals(key)) {
            return request.getScheme();
          }
          if ("jsgi.input".equals(key)) {
            try {
              return request.getInputStream();
            } catch (IOException e) {
              throw new RuntimeException(e);
            }
          }
          if ("jsgi.error".equals(key)) {
            return System.err;
          }
          if ("jsgi.multithread".equals(key)) {
            return true;
          }
          if ("jsgi.multiprocess".equals(key)) {
            return false;
          }
          if ("jsgi.run_once".equals(key)) {
            return false;
          }
          return Undefined.instance;
        }
        public Object getCoreValue(String name){
          return get(name, this);
        }
        @Override
        public Object[] getIds() {
          List list = new ArrayList();
          list.addAll(Arrays.asList(super.getIds()));
          list.addAll(Arrays.asList(new String[]{"REQUEST_METHOD","SCRIPT_NAME","PATH_INFO","CONTENT_TYPE","CONTENT_LENGTH","QUERY_STRING","SERVER_NAME","SERVER_PORT","SERVER_PROTOCOL","jsgi.version","jsgi.url_scheme","jsgi.input","jsgi.error","jsgi.multithread","jsgi.multiprocess","jsgi.run_once"}));
          return list.toArray();
        }

      };
      try {
        ScriptRuntime.setObjectProtoAndParent(env, global);
      } catch (Exception e1) {
      }
      Enumeration headerNames = request.getHeaderNames();
      while(headerNames.hasMoreElements()){
        String headerName = (String) headerNames.nextElement();
        if(!(headerName.equals("Content-Type") || headerName.equals("Content-Length")))
          env.put("HTTP_" + headerName.toUpperCase(), env, request.getHeader(headerName));
      }
      Object result = ((Function) global.get("coreApp", global)).call(PersevereContextFactory.getContext(), global, global,
          new Object[] { env });
      if (result instanceof Scriptable) {
        Object status = ((Scriptable) result).get("status", (Scriptable) result);
View Full Code Here

TOP

Related Classes of org.mozilla.javascript.NativeObject

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.