public void startModelValidating() {
   if (!isModelValid() && !validationStarted) {
     validationStarted = true;
     EventQueue.invokeLater(
         () -> {
           Scripts.LocalContext context = Scripts.getContext();
           RP.execute(
               () -> {
                 Scripts.setContext(context);
                 try {
                   validateModel();
                 } catch (Exception ex) {
                   Logger.getLogger(PlatypusDataObject.class.getName())
                       .log(Level.WARNING, ex.getMessage(), ex);
                 } finally {
                   Scripts.setContext(null);
                   EventQueue.invokeLater(
                       () -> {
                         validationStarted = false;
                         setModelValid(true);
                       });
                 }
               });
         });
   }
 }
 public void process(Runnable aTask) {
   Scripts.LocalContext context = Scripts.getContext();
   Runnable taskWrapper =
       () -> {
         Scripts.setContext(context);
         try {
           aTask.run();
         } finally {
           Scripts.setContext(null);
         }
       };
   queue.offer(taskWrapper);
   offerTask(
       () -> {
         // Runnable processedTask = taskWrapper;
         int version;
         int newVersion;
         Thread thisThread = Thread.currentThread();
         do {
           version = queueVersion.get();
           // Zombie counter ...
           newVersion = version + 1;
           if (newVersion == Integer.MAX_VALUE) {
             newVersion = 0;
           }
           /* moved to top of body
           if (processedTask != null) {//Single attempt to offer aTask.
           queue.offer(processedTask);
           processedTask = null;
           }
           */
           if (worker.compareAndSet(null, thisThread)) { // Worker electing.
             try {
               // already single threaded environment
               if (global == null) {
                 Scripts.Space.this.initSpaceGlobal();
               }
               // Zombie processing ...
               Runnable task = queue.poll();
               while (task != null) {
                 task.run();
                 task = queue.poll();
               }
             } catch (Throwable t) {
               Logger.getLogger(Scripts.class.getName()).log(Level.SEVERE, null, t);
             } finally {
               boolean setted = worker.compareAndSet(thisThread, null);
               assert setted : "Worker electing assumption failed"; // Always successfull CAS.
             }
           }
         } while (!queueVersion.compareAndSet(version, newVersion));
       });
 }
 void initSpaceGlobal() {
   Bindings bindings = engine.createBindings();
   scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
   bindings.put("space", this);
   try {
     Scripts.LocalContext ctx = Scripts.createContext(Scripts.Space.this);
     Scripts.setContext(ctx);
     try {
       scriptContext.setAttribute(
           ScriptEngine.FILENAME, PLATYPUS_JS_FILENAME, ScriptContext.ENGINE_SCOPE);
       engine.eval(new URLReader(platypusJsUrl), scriptContext);
     } finally {
       Scripts.setContext(null);
     }
   } catch (ScriptException ex) {
     Logger.getLogger(Scripts.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
 public void schedule(JSObject aJsTask, long aTimeout) {
   Scripts.LocalContext context = Scripts.getContext();
   bio.submit(
       () -> {
         try {
           Thread.sleep(aTimeout);
           Scripts.setContext(context);
           try {
             process(
                 () -> {
                   aJsTask.call(null, new Object[] {});
                 });
           } finally {
             Scripts.setContext(null);
           }
         } catch (InterruptedException ex) {
           Logger.getLogger(Scripts.class.getName()).log(Level.SEVERE, null, ex);
         }
       });
 }
Beispiel #5
0
 public static ImageIcon load(
     String aResourceName, String aCalledFromFile, JSObject onSuccess, JSObject onFailure)
     throws Exception {
   Scripts.Space space = Scripts.getSpace();
   return load(
       aResourceName,
       aCalledFromFile,
       space,
       onSuccess != null
           ? (ImageIcon aLoaded) -> {
             onSuccess.call(null, new Object[] {aLoaded});
           }
           : null,
       onSuccess != null
           ? (Exception ex) -> {
             onFailure.call(null, new Object[] {space.toJs(ex.getMessage())});
           }
           : null);
 }
 /**
  * Checks module roles.
  *
  * @param anAllowedRoles
  * @param aSubjectName
  * @throws AccessControlException
  */
 public static void checkPrincipalPermission(Set<String> anAllowedRoles, String aSubjectName)
     throws AccessControlException {
   if (anAllowedRoles != null && !anAllowedRoles.isEmpty()) {
     try {
       PlatypusPrincipal principal = (PlatypusPrincipal) Scripts.getContext().getPrincipal();
       if (principal == null || !principal.hasAnyRole(anAllowedRoles)) {
         throw new AccessControlException(
             String.format(
                 "Access denied to %s for '%s'.", // NOI18N
                 aSubjectName, principal != null ? principal.getName() : null),
             principal instanceof AnonymousPlatypusPrincipal ? new AuthPermission("*") : null);
       }
     } catch (Exception ex) {
       if (ex instanceof AccessControlException) {
         throw ex;
       } else {
         throw new AccessControlException(ex.getMessage());
       }
     }
   }
 }
 @Override
 public void handle(
     Session aSession, Consumer<CommitRequest.Response> onSuccess, Consumer<Exception> onFailure) {
   try {
     DatabasesClient client = getServerCore().getDatabasesClient();
     List<Change> changes =
         ChangesJSONReader.read(getRequest().getChangesJson(), Scripts.getSpace());
     ChangesSortProcess process =
         new ChangesSortProcess(
             changes,
             (Map<String, List<Change>> changeLogs) -> {
               try {
                 client.commit(
                     changeLogs,
                     (Integer aUpdated) -> {
                       if (onSuccess != null) {
                         onSuccess.accept(new CommitRequest.Response(aUpdated));
                       }
                     },
                     onFailure);
               } catch (Exception ex) {
                 Logger.getLogger(CommitRequestHandler.class.getName())
                     .log(Level.SEVERE, null, ex);
               }
             },
             onFailure);
     if (changes.isEmpty()) {
       if (onSuccess != null) {
         onSuccess.accept(new CommitRequest.Response(0));
       }
     } else {
       changes
           .stream()
           .forEach(
               (change) -> {
                 try {
                   ((LocalQueriesProxy) serverCore.getQueries())
                       .getQuery(
                           change.entityName,
                           Scripts.getSpace(),
                           (SqlQuery aQuery) -> {
                             if (aQuery.isPublicAccess()) {
                               AccessControlException aex =
                                   checkWritePrincipalPermission(
                                       (PlatypusPrincipal) Scripts.getContext().getPrincipal(),
                                       change.entityName,
                                       aQuery.getWriteRoles());
                               if (aex != null) {
                                 process.complete(null, null, aex, null);
                               } else {
                                 process.complete(change, aQuery, null, null);
                               }
                             } else {
                               process.complete(
                                   null,
                                   null,
                                   new AccessControlException(
                                       String.format(
                                           "Public access to query %s is denied while commiting changes for it's entity.",
                                           change.entityName)),
                                   null);
                             }
                           },
                           (Exception ex) -> {
                             process.complete(null, null, null, ex);
                           });
                 } catch (Exception ex) {
                   Logger.getLogger(CommitRequestHandler.class.getName())
                       .log(Level.SEVERE, null, ex);
                 }
               });
     }
   } catch (Exception ex) {
     onFailure.accept(ex);
   }
 }
 public static void offerTask(Runnable aTask) {
   assert tasks != null : "Scripts tasks are not initialized";
   Scripts.getContext().incAsyncsCount();
   tasks.accept(aTask);
 }
Beispiel #9
0
  @Override
  public JSObject execute(
      Scripts.Space aSpace, Consumer<JSObject> onSuccess, Consumer<Exception> onFailure)
      throws Exception {
    assert Scripts.getSpace() == aSpace : "Scripts.Space TLS assumption failed";
    if (onSuccess != null) {
      ScriptedResource._require(
          new String[] {entityName},
          null,
          aSpace,
          new HashSet<>(),
          (Void v) -> {
            JSObject source = aSpace.createModule(entityName);
            if (source.hasMember("fetch")) {
              Object oFetch = source.getMember("fetch");
              if (oFetch instanceof JSObject) {
                JSObject jsFetch = (JSObject) oFetch;
                if (jsFetch.isFunction()) {
                  JSObject jsParams = aSpace.makeObj();
                  for (int i = 0; i < params.getParametersCount(); i++) {
                    Parameter p = params.get(i + 1);
                    jsParams.setMember(p.getName(), aSpace.toJs(p.getValue()));
                  }
                  final ExecutionChecker exChecker = new ExecutionChecker();
                  Object oRowset =
                      jsFetch.call(
                          source,
                          aSpace.toJs(
                              new Object[] {
                                jsParams,
                                new AbstractJSObject() {

                                  @Override
                                  public Object call(final Object thiz, final Object... args) {
                                    if (exChecker.isExecutionNeeded()) {
                                      try {
                                        JSObject jsRowset =
                                            args.length > 0
                                                ? (JSObject) aSpace.toJava(args[0])
                                                : null;
                                        try {
                                          onSuccess.accept(jsRowset);
                                        } catch (Exception ex) {
                                          Logger.getLogger(ScriptedQuery.class.getName())
                                              .log(Level.SEVERE, null, ex);
                                        }
                                      } catch (Exception ex) {
                                        if (onFailure != null) {
                                          onFailure.accept(ex);
                                        }
                                      }
                                    }
                                    return null;
                                  }
                                },
                                new AbstractJSObject() {

                                  @Override
                                  public Object call(final Object thiz, final Object... args) {
                                    if (exChecker.isExecutionNeeded()) {
                                      if (onFailure != null) {
                                        if (args.length > 0) {
                                          if (args[0] instanceof Exception) {
                                            onFailure.accept((Exception) args[0]);
                                          } else {
                                            onFailure.accept(
                                                new Exception(
                                                    String.valueOf(aSpace.toJava(args[0]))));
                                          }
                                        } else {
                                          onFailure.accept(
                                              new Exception(
                                                  "No error information from fetch method"));
                                        }
                                      }
                                    }
                                    return null;
                                  }
                                }
                              }));
                  if (!JSType.nullOrUndefined(oRowset)) {
                    onSuccess.accept((JSObject) aSpace.toJava(oRowset));
                    exChecker.setExecutionNeeded(false);
                  }
                }
              }
            }
          },
          onFailure);
      return null;
    } else {
      JSObject source = aSpace.createModule(entityName);
      if (source.hasMember("fetch")) {
        Object oFetch = source.getMember("fetch");
        if (oFetch instanceof JSObject) {
          JSObject jsFetch = (JSObject) oFetch;
          if (jsFetch.isFunction()) {
            JSObject jsParams = aSpace.makeObj();
            Object oRowset = jsFetch.call(source, aSpace.toJs(new Object[] {jsParams}));
            if (!JSType.nullOrUndefined(oRowset)) {
              return (JSObject) aSpace.toJava(oRowset);
            }
          }
        }
      }
      return null;
    }
  }
  /**
   * @param args the command line arguments
   * @throws IOException
   * @throws Exception
   */
  public static void main(String[] args) throws IOException, Exception {
    checkUserHome();
    GeneralResourceProvider.registerDrivers();
    parseArgs(args);
    if (url == null || url.isEmpty()) {
      throw new IllegalArgumentException("Application url (-url parameter) is required.");
    }
    SSLContext sslContext = PlatypusConnection.createSSLContext();

    ScriptedDatabasesClient serverCoreDbClient;
    if (url.toLowerCase().startsWith("file")) {
      File f = new File(new URI(url));
      if (f.exists() && f.isDirectory()) {
        Logger.getLogger(ServerMain.class.getName())
            .log(Level.INFO, "Application is located at: {0}", f.getPath());
        GeneralResourceProvider.registerDrivers();
        ScriptsConfigs scriptsConfigs = new ScriptsConfigs();
        ServerTasksScanner tasksScanner = new ServerTasksScanner(scriptsConfigs);
        ApplicationSourceIndexer indexer = new ApplicationSourceIndexer(f.getPath(), tasksScanner);
        // TODO: add command line argument "watch" after watcher refactoring
        // indexer.watch();
        Scripts.initBIO(threadsConfig.getMaxServicesTreads());

        int maxWorkerThreads = parseNumWorkerThreads();
        ThreadPoolExecutor serverProcessor =
            new ThreadPoolExecutor(
                maxWorkerThreads,
                maxWorkerThreads,
                3L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(),
                new DeamonThreadFactory("TSA-", false));
        serverProcessor.allowCoreThreadTimeOut(true);

        Scripts.initTasks(
            (Runnable aTask) -> {
              serverProcessor.submit(aTask);
            });
        serverCoreDbClient =
            new ScriptedDatabasesClient(
                defDatasource,
                indexer,
                true,
                tasksScanner.getValidators(),
                threadsConfig.getMaxJdbcTreads());
        QueriesProxy<SqlQuery> queries = new LocalQueriesProxy(serverCoreDbClient, indexer);
        serverCoreDbClient.setQueries(queries);
        PlatypusServer server =
            new PlatypusServer(
                indexer,
                new LocalModulesProxy(indexer, new ModelsDocuments(), appElement),
                queries,
                serverCoreDbClient,
                sslContext,
                parseListenAddresses(),
                parsePortsProtocols(),
                parsePortsSessionIdleTimeouts(),
                parsePortsSessionIdleCheckIntervals(),
                serverProcessor,
                scriptsConfigs,
                appElement);
        serverCoreDbClient.setContextHost(server);
        ScriptedResource.init(server, ScriptedResource.lookupPlatypusJs());
        SensorsFactory.init(server.getAcceptorsFactory());
        RetranslateFactory.init(server.getRetranslateFactory());
        //
        server.start(tasksScanner.getResidents(), tasksScanner.getAcceptors());
      } else {
        throw new IllegalArgumentException(
            "applicationUrl: " + url + " doesn't point to existent directory.");
      }
    } else {
      throw new Exception("Unknown protocol in url: " + url);
    }
  }