Ejemplo n.º 1
0
 public boolean existsCollection(String collectionName) throws SqlInjectionException {
   if (Logger.isTraceEnabled()) Logger.trace("Method Start");
   OIndex idx = db.getMetadata().getIndexManager().getIndex(COLLECTION_NAME_INDEX);
   OIdentifiable record = (OIdentifiable) idx.get(collectionName);
   if (Logger.isTraceEnabled()) Logger.trace("Method End");
   return (record != null);
 }
  @Override
  public F.Promise<SimpleResult> call(Context ctx) throws Throwable {
    if (Logger.isTraceEnabled()) Logger.trace("Method Start");
    Context.current.set(ctx);

    if (Logger.isDebugEnabled())
      Logger.debug("AnonymousLogin  for resource " + Context.current().request());

    String user = BBConfiguration.getBaasBoxUsername();
    String password = BBConfiguration.getBaasBoxPassword();

    // retrieve AppCode
    String appCode = RequestHeaderHelper.getAppCode(ctx);

    ctx.args.put("username", user);
    ctx.args.put("password", password);
    ctx.args.put("appcode", appCode);

    if (Logger.isDebugEnabled()) Logger.debug("username (defined in conf file): " + user);
    if (Logger.isDebugEnabled()) Logger.debug("password (defined in conf file): " + password);
    if (Logger.isDebugEnabled()) Logger.debug("appcode (from header or querystring): " + appCode);
    if (Logger.isDebugEnabled()) Logger.debug("token: N/A");

    // executes the request
    F.Promise<SimpleResult> tempResult = delegate.call(ctx);

    WrapResponse wr = new WrapResponse();
    // SimpleResult result=wr.wrap(ctx, tempResult);
    F.Promise<SimpleResult> result = wr.wrapAsync(ctx, tempResult);
    if (Logger.isTraceEnabled()) Logger.trace("Method End");
    return result;
  }
Ejemplo n.º 3
0
 @Override
 public ODocument create() throws Throwable {
   if (Logger.isTraceEnabled()) Logger.trace("Method Start");
   DbHelper.requestTransaction();
   ODocument doc = super.create();
   if (Logger.isTraceEnabled()) Logger.trace("Method End");
   return doc;
 } // getNewModelInstance
Ejemplo n.º 4
0
  @Override
  protected void service(
      HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
      throws ServletException, IOException {

    if (!routerInitializedWithContext) {
      loadRouter(httpServletRequest.getContextPath());
    }

    if (Logger.isTraceEnabled()) {
      Logger.trace("ServletWrapper>service " + httpServletRequest.getRequestURI());
    }

    Request request = null;
    try {
      Response response = new Response();
      response.out = new ByteArrayOutputStream();
      Response.current.set(response);
      request = parseRequest(httpServletRequest);

      if (Logger.isTraceEnabled()) {
        Logger.trace("ServletWrapper>service, request: " + request);
      }

      boolean raw = Play.pluginCollection.rawInvocation(request, response);
      if (raw) {
        copyResponse(
            Request.current(), Response.current(), httpServletRequest, httpServletResponse);
      } else {
        Invoker.invokeInThread(
            new ServletInvocation(request, response, httpServletRequest, httpServletResponse));
      }
    } catch (NotFound e) {
      if (Logger.isTraceEnabled()) {
        Logger.trace("ServletWrapper>service, NotFound: " + e);
      }
      serve404(httpServletRequest, httpServletResponse, e);
      return;
    } catch (RenderStatic e) {
      if (Logger.isTraceEnabled()) {
        Logger.trace("ServletWrapper>service, RenderStatic: " + e);
      }
      serveStatic(httpServletResponse, httpServletRequest, e);
      return;
    } catch (Throwable e) {
      throw new ServletException(e);
    } finally {
      Request.current.remove();
      Response.current.remove();
      Scope.Session.current.remove();
      Scope.Params.current.remove();
      Scope.Flash.current.remove();
      Scope.RenderArgs.current.remove();
      Scope.RouteArgs.current.remove();
    }
  }
Ejemplo n.º 5
0
 public static Route getRoute(
     String method,
     String path,
     String action,
     String params,
     String headers,
     String sourceFile,
     int line) {
   Route route = new Route();
   route.method = method;
   route.path = path.replace("//", "/");
   route.action = action;
   route.routesFile = sourceFile;
   route.routesFileLine = line;
   route.addFormat(headers);
   route.addParams(params);
   route.compute();
   if (Logger.isTraceEnabled()) {
     Logger.trace(
         "Adding ["
             + route.toString()
             + "] with params ["
             + params
             + "] and headers ["
             + headers
             + "]");
   }
   return route;
 }
Ejemplo n.º 6
0
 public ODocument getByName(String collectionName) throws SqlInjectionException {
   if (Logger.isTraceEnabled()) Logger.trace("Method Start");
   OIndex idx = db.getMetadata().getIndexManager().getIndex(COLLECTION_NAME_INDEX);
   OIdentifiable record = (OIdentifiable) idx.get(collectionName);
   if (record == null) return null;
   return db.load(record.getIdentity());
 }
Ejemplo n.º 7
0
  public static synchronized Stack<Evolution> listApplicationEvolutions() {
    Stack<Evolution> evolutions = new Stack<Evolution>();
    evolutions.add(new Evolution(0, "", "", true));
    if (evolutionsDirectory.exists()) {
      for (File evolution : evolutionsDirectory.listFiles()) {
        if (evolution.getName().matches("^[0-9]+[.]sql$")) {
          if (Logger.isTraceEnabled()) {
            Logger.trace("Loading evolution %s", evolution);
          }

          int version =
              Integer.parseInt(evolution.getName().substring(0, evolution.getName().indexOf(".")));
          String sql = IO.readContentAsString(evolution);
          StringBuffer sql_up = new StringBuffer();
          StringBuffer sql_down = new StringBuffer();
          StringBuffer current = new StringBuffer();
          for (String line : sql.split("\r?\n")) {
            if (line.trim().matches("^#.*[!]Ups")) {
              current = sql_up;
            } else if (line.trim().matches("^#.*[!]Downs")) {
              current = sql_down;
            } else if (line.trim().startsWith("#")) {
              // skip
            } else if (!StringUtils.isEmpty(line.trim())) {
              current.append(line).append("\n");
            }
          }
          evolutions.add(new Evolution(version, sql_up.toString(), sql_down.toString(), true));
        }
      }
      Collections.sort(evolutions);
    }
    return evolutions;
  }
Ejemplo n.º 8
0
 public static Route route(Http.Request request) {
   if (Logger.isTraceEnabled()) {
     Logger.trace("Route: " + request.path + " - " + request.querystring);
   }
   // request method may be overriden if a x-http-method-override parameter is given
   if (request.querystring != null && methodOverride.matches(request.querystring)) {
     Matcher matcher = methodOverride.matcher(request.querystring);
     if (matcher.matches()) {
       if (Logger.isTraceEnabled()) {
         Logger.trace(
             "request method %s overriden to %s ", request.method, matcher.group("method"));
       }
       request.method = matcher.group("method");
     }
   }
   for (Route route : routes) {
     Map<String, String> args =
         route.matches(request.method, request.path, request.format, request.domain);
     if (args != null) {
       request.routeArgs = args;
       request.action = route.action;
       if (args.containsKey("format")) {
         request.format = args.get("format");
       }
       if (request.action.indexOf("{") > -1) { // more optimization ?
         for (String arg : request.routeArgs.keySet()) {
           request.action = request.action.replace("{" + arg + "}", request.routeArgs.get(arg));
         }
       }
       if (request.action.equals("404")) {
         throw new NotFound(route.path);
       }
       return route;
     }
   }
   // Not found - if the request was a HEAD, let's see if we can find a corresponding GET
   if (request.method.equalsIgnoreCase("head")) {
     request.method = "GET";
     Route route = route(request);
     request.method = "HEAD";
     if (route != null) {
       return route;
     }
   }
   throw new NotFound(request.method, request.path);
 }
Ejemplo n.º 9
0
 private static void registAuthoriable_(String key, RequireRight rr, RequirePrivilege rp) {
   if (Logger.isTraceEnabled()) {
     Plugin.trace(
         "register authoriable [%s: (%s|%s)]",
         key,
         (null == rr) ? "null-right" : rr.value(),
         (null == rp) ? "null-privilege" : rp.value());
   }
   reg_.put(key, new Authority(key, rr, rp));
 }
Ejemplo n.º 10
0
  @SuppressWarnings("unchecked")
  public static void resolve(Http.Request request, Http.Response response)
      throws NotFound, RenderStatic {

    if (!Play.started) {
      return;
    }

    Http.Request.current.set(request);
    Http.Response.current.set(response);

    Scope.Params.current.set(request.params);
    Scope.RenderArgs.current.set(new Scope.RenderArgs());
    Scope.RouteArgs.current.set(new Scope.RouteArgs());
    Scope.Session.current.set(Scope.Session.restore());
    Scope.Flash.current.set(Scope.Flash.restore());
    CachedBoundActionMethodArgs.init();

    ControllersEnhancer.currentAction.set(new Stack<String>());

    if (request.resolved) {
      return;
    }

    // Route and resolve format if not already done
    if (request.action == null) {
      Play.pluginCollection.routeRequest(request);
      Route route = Router.route(request);
      Play.pluginCollection.onRequestRouting(route);
    }
    request.resolveFormat();

    // Find the action method
    try {
      Method actionMethod = null;
      Object[] ca = getActionMethod(request.action);
      actionMethod = (Method) ca[1];
      request.controller = ((Class) ca[0]).getName().substring(12).replace("$", "");
      request.controllerClass = ((Class) ca[0]);
      request.actionMethod = actionMethod.getName();
      request.action = request.controller + "." + request.actionMethod;
      request.invokedMethod = actionMethod;
      if (Logger.isTraceEnabled()) {
        Logger.trace("------- %s", actionMethod);
      }
      request.resolved = true;
    } catch (ActionNotFoundException e) {
      //                Logger.error(e, "%s action not found", e.getAction());
      // bran: avoid excessive messages
      Logger.error("%s action not found", e.getAction());
      throw new NotFound(String.format("%s action not found", e.getAction()));
    }
  }
Ejemplo n.º 11
0
  /**
   * Force all java source and template compilation.
   *
   * @return success ?
   */
  static boolean preCompile() {
    if (usePrecompiled) {
      if (Play.getFile("precompiled").exists()) {
        classloader.getAllClasses();
        Logger.info("Application is precompiled");
        return true;
      }
      Logger.error("Precompiled classes are missing!!");
      fatalServerErrorOccurred();
      return false;
    }
    try {
      Logger.info("Precompiling ...");
      Thread.currentThread().setContextClassLoader(Play.classloader);
      long start = System.currentTimeMillis();
      classloader.getAllClasses();

      if (Logger.isTraceEnabled()) {
        Logger.trace("%sms to precompile the Java stuff", System.currentTimeMillis() - start);
      }

      if (!lazyLoadTemplates) {
        start = System.currentTimeMillis();
        TemplateLoader.getAllTemplate();

        if (Logger.isTraceEnabled()) {
          Logger.trace("%sms to precompile the templates", System.currentTimeMillis() - start);
        }
      }
      return true;
    } catch (Throwable e) {
      Logger.error(e, "Cannot start in PROD mode with errors");
      fatalServerErrorOccurred();
      return false;
    }
  }
Ejemplo n.º 12
0
  public boolean verify() {
    try {
      // Normalize
      String claimedId = normalize(id);
      String server = null;
      String delegate = null;

      // Discover
      HttpResponse response = WS.url(claimedId).get();

      // Try HTML (I know it's bad)
      String html = response.getString();
      server = discoverServer(html);

      if (server == null) {

        // Try YADIS
        Document xrds = null;

        if (response.getContentType().contains("application/xrds+xml")) {
          xrds = getXml(html, response.getEncoding());
        } else if (response.getHeader("X-XRDS-Location") != null) {
          xrds = WS.url(response.getHeader("X-XRDS-Location")).get().getXml();
        } else {
          return false;
        }

        // Ok we have the XRDS file
        server =
            XPath.selectText(
                "//Type[text()='http://specs.openid.net/auth/2.0/server']/following-sibling::URI/text()",
                xrds);
        claimedId =
            XPath.selectText(
                "//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::LocalID/text()",
                xrds);
        if (claimedId == null) {
          claimedId = "http://specs.openid.net/auth/2.0/identifier_select";
        } else {
          server =
              XPath.selectText(
                  "//Type[text()='http://specs.openid.net/auth/2.0/signon']/following-sibling::URI/text()",
                  xrds);
        }

        if (server == null) {
          return false;
        }

      } else {

        // Delegate
        Matcher openid2Localid =
            Pattern.compile("<link[^>]+openid2[.]local_id[^>]+>", Pattern.CASE_INSENSITIVE)
                .matcher(html);
        Matcher openidDelegate =
            Pattern.compile("<link[^>]+openid[.]delegate[^>]+>", Pattern.CASE_INSENSITIVE)
                .matcher(html);
        if (openid2Localid.find()) {
          delegate = extractHref(openid2Localid.group());
        } else if (openidDelegate.find()) {
          delegate = extractHref(openidDelegate.group());
        }
      }

      // Redirect
      String url = server;
      if (!server.contains("?")) {
        url += "?";
      }
      if (!url.endsWith("?") && !url.endsWith("&")) {
        url += "&";
      }

      url += "openid.ns=" + URLEncoder.encode("http://specs.openid.net/auth/2.0", "UTF-8");
      url += "&openid.mode=checkid_setup";
      url += "&openid.claimed_id=" + URLEncoder.encode(claimedId, "utf8");
      url +=
          "&openid.identity=" + URLEncoder.encode(delegate == null ? claimedId : delegate, "utf8");

      if (returnAction != null
          && (returnAction.startsWith("http://") || returnAction.startsWith("https://"))) {
        url += "&openid.return_to=" + URLEncoder.encode(returnAction, "utf8");
      } else {
        url +=
            "&openid.return_to="
                + URLEncoder.encode(
                    Request.current().getBase() + Router.reverse(returnAction), "utf8");
      }
      if (realmAction != null
          && (realmAction.startsWith("http://") || realmAction.startsWith("https://"))) {
        url += "&openid.realm=" + URLEncoder.encode(realmAction, "utf8");
      } else {
        url +=
            "&openid.realm="
                + URLEncoder.encode(
                    Request.current().getBase() + Router.reverse(realmAction), "utf8");
      }

      if (!sregOptional.isEmpty() || !sregRequired.isEmpty()) {
        url +=
            "&openid.ns.sreg="
                + URLEncoder.encode("http://openid.net/extensions/sreg/1.1", "UTF-8");
      }
      String sregO = "";
      for (String a : sregOptional) {
        sregO += URLEncoder.encode(a, "UTF-8") + ",";
      }
      if (!StringUtils.isEmpty(sregO)) {
        url += "&openid.sreg.optional=" + sregO.substring(0, sregO.length() - 1);
      }
      String sregR = "";
      for (String a : sregRequired) {
        sregR += URLEncoder.encode(a, "UTF-8") + ",";
      }
      if (!StringUtils.isEmpty(sregR)) {
        url += "&openid.sreg.required=" + sregR.substring(0, sregR.length() - 1);
      }

      if (!axRequired.isEmpty() || !axOptional.isEmpty()) {
        url += "&openid.ns.ax=http%3A%2F%2Fopenid.net%2Fsrv%2Fax%2F1.0";
        url += "&openid.ax.mode=fetch_request";
        for (String a : axOptional.keySet()) {
          url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axOptional.get(a), "UTF-8");
        }
        for (String a : axRequired.keySet()) {
          url += "&openid.ax.type." + a + "=" + URLEncoder.encode(axRequired.get(a), "UTF-8");
        }
        if (!axRequired.isEmpty()) {
          String r = "";
          for (String a : axRequired.keySet()) {
            r += "," + a;
          }
          r = r.substring(1);
          url += "&openid.ax.required=" + r;
        }
        if (!axOptional.isEmpty()) {
          String r = "";
          for (String a : axOptional.keySet()) {
            r += "," + a;
          }
          r = r.substring(1);
          url += "&openid.ax.if_available=" + r;
        }
      }

      if (Logger.isTraceEnabled()) {
        // Debug
        Logger.trace("Send request %s", url);
      }

      throw new Redirect(url);
    } catch (Redirect e) {
      throw e;
    } catch (PlayException e) {
      throw e;
    } catch (Exception e) {
      return false;
    }
  }
Ejemplo n.º 13
0
    public void compute() {
      this.host = "";
      this.hostPattern = new Pattern(".*");
      if (action.startsWith("staticDir:") || action.startsWith("staticFile:")) {
        // Is there is a host argument, append it.
        if (!path.startsWith("/")) {
          String p = this.path;
          this.path = p.substring(p.indexOf("/"));
          this.host = p.substring(0, p.indexOf("/"));
          if (this.host.contains("{")) {
            Logger.warn("Static route cannot have a dynamic host name");
            return;
          }
        }
        if (!method.equalsIgnoreCase("*") && !method.equalsIgnoreCase("GET")) {
          Logger.warn("Static route only support GET method");
          return;
        }
      }
      // staticDir
      if (action.startsWith("staticDir:")) {
        if (!this.path.endsWith("/") && !this.path.equals("/")) {
          Logger.warn("The path for a staticDir route must end with / (%s)", this);
          this.path += "/";
        }
        this.pattern = new Pattern("^" + path + "({resource}.*)$");
        this.staticDir = action.substring("staticDir:".length());
      } else if (action.startsWith("staticFile:")) {
        this.pattern = new Pattern("^" + path + "$");
        this.staticFile = true;
        this.staticDir = action.substring("staticFile:".length());
      } else {
        // URL pattern
        // Is there is a host argument, append it.
        if (!path.startsWith("/")) {
          String p = this.path;
          this.path = p.substring(p.indexOf("/"));
          this.host = p.substring(0, p.indexOf("/"));
          String pattern = host.replaceAll("\\.", "\\\\.").replaceAll("\\{.*\\}", "(.*)");

          if (Logger.isTraceEnabled()) {
            Logger.trace("pattern [" + pattern + "]");
            Logger.trace("host [" + host + "]");
          }

          Matcher m = new Pattern(pattern).matcher(host);
          this.hostPattern = new Pattern(pattern);

          if (m.matches()) {
            if (this.host.contains("{")) {
              String name = m.group(1).replace("{", "").replace("}", "");
              if (!name.equals("_")) {
                hostArg = new Arg();
                hostArg.name = name;
                if (Logger.isTraceEnabled()) {
                  Logger.trace("hostArg name [" + name + "]");
                }
                // The default value contains the route version of the host ie {client}.bla.com
                // It is temporary and it indicates it is an url route.
                // TODO Check that default value is actually used for other cases.
                hostArg.defaultValue = host;
                hostArg.constraint = new Pattern(".*");

                if (Logger.isTraceEnabled()) {
                  Logger.trace("adding hostArg [" + hostArg + "]");
                }

                args.add(hostArg);
              }
            }
          }
        }
        String patternString = path;
        patternString = customRegexPattern.replacer("\\{<[^/]+>$1\\}").replace(patternString);
        Matcher matcher = argsPattern.matcher(patternString);
        while (matcher.find()) {
          Arg arg = new Arg();
          arg.name = matcher.group(2);
          arg.constraint = new Pattern(matcher.group(1));
          args.add(arg);
        }

        patternString = argsPattern.replacer("({$2}$1)").replace(patternString);
        this.pattern = new Pattern(patternString);
        // Action pattern
        patternString = action;
        patternString = patternString.replace(".", "[.]");
        for (Arg arg : args) {
          if (patternString.contains("{" + arg.name + "}")) {
            patternString =
                patternString.replace(
                    "{" + arg.name + "}", "({" + arg.name + "}" + arg.constraint.toString() + ")");
            actionArgs.add(arg.name);
          }
        }
        actionPattern = new Pattern(patternString, REFlags.IGNORE_CASE);
      }
    }
Ejemplo n.º 14
0
  public static Request parseRequest(HttpServletRequest httpServletRequest) throws Exception {

    URI uri = new URI(httpServletRequest.getRequestURI());
    String method = httpServletRequest.getMethod().intern();
    String path = uri.getRawPath();
    if (path != null) {
      path = URLDecoder.decode(path, "utf-8");
    }
    String querystring =
        httpServletRequest.getQueryString() == null ? "" : httpServletRequest.getQueryString();

    if (Logger.isTraceEnabled()) {
      Logger.trace("httpServletRequest.getContextPath(): " + httpServletRequest.getContextPath());
      Logger.trace("request.path: " + path + ", request.querystring: " + querystring);
    }

    String contentType = null;
    if (httpServletRequest.getHeader("Content-Type") != null) {
      contentType =
          httpServletRequest.getHeader("Content-Type").split(";")[0].trim().toLowerCase().intern();
    } else {
      contentType = "text/html".intern();
    }

    if (httpServletRequest.getHeader("X-HTTP-Method-Override") != null) {
      method = httpServletRequest.getHeader("X-HTTP-Method-Override").intern();
    }

    InputStream body = httpServletRequest.getInputStream();
    boolean secure = httpServletRequest.isSecure();

    String url =
        uri.toString()
            + (httpServletRequest.getQueryString() == null
                ? ""
                : "?" + httpServletRequest.getQueryString());
    String host = httpServletRequest.getHeader("host");
    int port = 0;
    String domain = null;
    if (host.contains(":")) {
      port = Integer.parseInt(host.split(":")[1]);
      domain = host.split(":")[0];
    } else {
      port = 80;
      domain = host;
    }

    String remoteAddress = httpServletRequest.getRemoteAddr();

    boolean isLoopback = host.matches("^127\\.0\\.0\\.1:?[0-9]*$");

    final Request request =
        Request.createRequest(
            remoteAddress,
            method,
            path,
            querystring,
            contentType,
            body,
            url,
            host,
            isLoopback,
            port,
            domain,
            secure,
            getHeaders(httpServletRequest),
            getCookies(httpServletRequest));

    Request.current.set(request);
    Router.routeOnlyStatic(request);

    return request;
  }
Ejemplo n.º 15
0
  /**
   * * Creates an entry into the ODocument-Collection and create a new Class named "collectionName"
   *
   * @param collectionName
   * @return an ODocument instance representing the collection
   * @throws CollectionAlreadyExistsException
   * @throws OpenTransactionException, CollectionAlreadyExistsException, InvalidCollectionException,
   *     InvalidModelException, Throwable
   */
  public ODocument create(String collectionName)
      throws OpenTransactionException, CollectionAlreadyExistsException, InvalidCollectionException,
          InvalidModelException, Throwable {
    if (DbHelper.isInTransaction())
      throw new OpenTransactionException("Cannot create a collection within an open transaction");
    if (Logger.isTraceEnabled()) Logger.trace("Method Start");

    if (Character.isDigit(collectionName.charAt(0))) {
      throw new InvalidCollectionException("Collection names cannot start by a digit");
    }
    if (collectionName.contains(";")) {
      throw new InvalidCollectionException("Collection cannot contain ;");
    }
    if (collectionName.contains(":")) {
      throw new InvalidCollectionException("Collection cannot contain :");
    }
    if (collectionName.contains(".")) {
      throw new InvalidCollectionException("Collection cannot contain .");
    }
    if (collectionName.contains("@")) {
      throw new InvalidCollectionException("Collection cannot contain @");
    }
    if (collectionName.startsWith("_")) {
      throw new InvalidCollectionException("Collection cannot start with _");
    }
    if (!collectionName.matches(COLLECTION_NAME_REGEX)) {
      throw new InvalidCollectionException(
          "Collection name must be complaint with the regular expression: "
              + COLLECTION_NAME_REGEX);
    }
    if (collectionName.toUpperCase().startsWith("_BB_")) {
      throw new InvalidCollectionException(
          "Collection name is not valid: it can't be prefixed with _BB_");
    }
    try {
      if (existsCollection(collectionName))
        throw new CollectionAlreadyExistsException(
            "Collection " + collectionName + " already exists");
    } catch (SqlInjectionException e) {
      throw new InvalidCollectionException(e);
    }
    ODocument doc = super.create();
    doc.field("name", collectionName);

    save(doc);

    // create new class
    OClass documentClass = db.getMetadata().getSchema().getClass(CLASS_NODE_NAME);
    db.getMetadata().getSchema().createClass(collectionName, documentClass);

    // grants to the new class
    ORole registeredRole = RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString());
    ORole anonymousRole = RoleDao.getRole(DefaultRoles.ANONYMOUS_USER.toString());
    registeredRole.addRule(
        ODatabaseSecurityResources.CLASS + "." + collectionName, ORole.PERMISSION_ALL);
    registeredRole.addRule(
        ODatabaseSecurityResources.CLUSTER + "." + collectionName, ORole.PERMISSION_ALL);
    anonymousRole.addRule(
        ODatabaseSecurityResources.CLASS + "." + collectionName, ORole.PERMISSION_READ);
    anonymousRole.addRule(
        ODatabaseSecurityResources.CLUSTER + "." + collectionName, ORole.PERMISSION_READ);
    PermissionsHelper.grantRead(doc, registeredRole);
    PermissionsHelper.grantRead(doc, anonymousRole);
    if (Logger.isTraceEnabled()) Logger.trace("Method End");
    return doc;
  } // getNewModelInstance(String collectionName)
Ejemplo n.º 16
0
  @Override
  public void onApplicationStart() {

    // must check and configure JPA for each DBConfig
    for (DBConfig dbConfig : DB.getDBConfigs()) {
      // check and enable JPA on this config

      // is JPA already configured?
      String configName = dbConfig.getDBConfigName();

      if (JPA.getJPAConfig(configName, true) == null) {
        // must configure it

        // resolve prefix for hibernate config..
        // should be nothing for default, and db_<name> for others
        String propPrefix = "";
        if (!DBConfig.defaultDbConfigName.equalsIgnoreCase(configName)) {
          propPrefix = "db_" + configName + ".";
        }
        List<Class> classes = findEntityClassesForThisConfig(configName, propPrefix);
        if (classes == null) continue;

        // we're ready to configure this instance of JPA
        final String hibernateDataSource =
            Play.configuration.getProperty(propPrefix + "hibernate.connection.datasource");

        if (StringUtils.isEmpty(hibernateDataSource) && dbConfig == null) {
          throw new JPAException(
              "Cannot start a JPA manager without a properly configured database"
                  + getConfigInfoString(configName),
              new NullPointerException("No datasource configured"));
        }

        Ejb3Configuration cfg = new Ejb3Configuration();

        if (dbConfig.getDatasource() != null) {
          cfg.setDataSource(dbConfig.getDatasource());
        }

        if (!Play.configuration
            .getProperty(propPrefix + "jpa.ddl", Play.mode.isDev() ? "update" : "none")
            .equals("none")) {
          cfg.setProperty(
              "hibernate.hbm2ddl.auto",
              Play.configuration.getProperty(propPrefix + "jpa.ddl", "update"));
        }

        String driver = null;
        if (StringUtils.isEmpty(propPrefix)) {
          driver = Play.configuration.getProperty("db.driver");
        } else {
          driver = Play.configuration.getProperty(propPrefix + "driver");
        }
        cfg.setProperty("hibernate.dialect", getDefaultDialect(propPrefix, driver));
        cfg.setProperty("javax.persistence.transaction", "RESOURCE_LOCAL");

        cfg.setInterceptor(new PlayInterceptor());

        // This setting is global for all JPAs - only configure if configuring default JPA
        if (StringUtils.isEmpty(propPrefix)) {
          if (Play.configuration.getProperty(propPrefix + "jpa.debugSQL", "false").equals("true")) {
            org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.ALL);
          } else {
            org.apache.log4j.Logger.getLogger("org.hibernate.SQL").setLevel(Level.OFF);
          }
        }
        // inject additional  hibernate.* settings declared in Play! configuration
        Properties additionalProperties =
            (Properties)
                Utils.Maps.filterMap(Play.configuration, "^" + propPrefix + "hibernate\\..*");
        // We must remove prefix from names
        Properties transformedAdditionalProperties = new Properties();
        for (Map.Entry<Object, Object> entry : additionalProperties.entrySet()) {
          Object key = entry.getKey();
          if (!StringUtils.isEmpty(propPrefix)) {
            key = ((String) key).substring(propPrefix.length()); // chop off the prefix
          }
          transformedAdditionalProperties.put(key, entry.getValue());
        }
        cfg.addProperties(transformedAdditionalProperties);

        try {
          // nice hacking :) I like it..
          Field field = cfg.getClass().getDeclaredField("overridenClassLoader");
          field.setAccessible(true);
          field.set(cfg, Play.classloader);
        } catch (Exception e) {
          Logger.error(
              e, "Error trying to override the hibernate classLoader (new hibernate version ???)");
        }

        for (Class<?> clazz : classes) {
          cfg.addAnnotatedClass(clazz);
          if (Logger.isTraceEnabled()) {
            Logger.trace("JPA Model : %s", clazz);
          }
        }
        String[] moreEntities =
            Play.configuration.getProperty(propPrefix + "jpa.entities", "").split(", ");
        for (String entity : moreEntities) {
          if (entity.trim().equals("")) {
            continue;
          }
          try {
            cfg.addAnnotatedClass(Play.classloader.loadClass(entity));
          } catch (Exception e) {
            Logger.warn("JPA -> Entity not found: %s", entity);
          }
        }

        for (ApplicationClass applicationClass : Play.classes.all()) {
          if (applicationClass.isClass() || applicationClass.javaPackage == null) {
            continue;
          }
          Package p = applicationClass.javaPackage;
          Logger.info("JPA -> Adding package: %s", p.getName());
          cfg.addPackage(p.getName());
        }

        String mappingFile = Play.configuration.getProperty(propPrefix + "jpa.mapping-file", "");
        if (mappingFile != null && mappingFile.length() > 0) {
          cfg.addResource(mappingFile);
        }

        if (Logger.isTraceEnabled()) {
          Logger.trace("Initializing JPA" + getConfigInfoString(configName) + " ...");
        }

        try {
          JPA.addConfiguration(configName, cfg);
        } catch (PersistenceException e) {
          throw new JPAException(
              e.getMessage() + getConfigInfoString(configName),
              e.getCause() != null ? e.getCause() : e);
        }
      }
    }

    // must look for Entity-objects referring to none-existing JPAConfig
    List<Class> allEntityClasses = Play.classloader.getAnnotatedClasses(Entity.class);
    for (Class clazz : allEntityClasses) {
      String configName = Entity2JPAConfigResolver.getJPAConfigNameForEntityClass(clazz);
      if (JPA.getJPAConfig(configName, true) == null) {
        throw new JPAException(
            "Found Entity-class ("
                + clazz.getName()
                + ") referring to none-existing JPAConfig"
                + getConfigInfoString(configName)
                + ". "
                + "Is JPA properly configured?");
      }
    }
  }
Ejemplo n.º 17
0
  /**
   * Init the framework
   *
   * @param root The application path
   * @param id The framework id to use
   */
  public static void init(File root, String id) {
    // Simple things
    Play.id = id;
    Play.started = false;
    Play.applicationPath = root;

    // load all play.static of exists
    initStaticStuff();

    guessFrameworkPath();

    // Read the configuration file
    readConfiguration();

    Play.classes = new ApplicationClasses();

    // Configure logs
    Logger.init();
    String logLevel = configuration.getProperty("application.log", "INFO");

    // only override log-level if Logger was not configured manually
    if (!Logger.configuredManually) {
      Logger.setUp(logLevel);
    }
    Logger.recordCaller =
        Boolean.parseBoolean(configuration.getProperty("application.log.recordCaller", "false"));

    Logger.info("Starting %s", root.getAbsolutePath());

    if (configuration.getProperty("play.tmp", "tmp").equals("none")) {
      tmpDir = null;
      Logger.debug("No tmp folder will be used (play.tmp is set to none)");
    } else {
      tmpDir = new File(configuration.getProperty("play.tmp", "tmp"));
      if (!tmpDir.isAbsolute()) {
        tmpDir = new File(applicationPath, tmpDir.getPath());
      }

      if (Logger.isTraceEnabled()) {
        Logger.trace("Using %s as tmp dir", Play.tmpDir);
      }

      if (!tmpDir.exists()) {
        try {
          if (readOnlyTmp) {
            throw new Exception("ReadOnly tmp");
          }
          tmpDir.mkdirs();
        } catch (Throwable e) {
          tmpDir = null;
          Logger.warn("No tmp folder will be used (cannot create the tmp dir)");
        }
      }
    }

    // Mode
    try {
      mode = Mode.valueOf(configuration.getProperty("application.mode", "DEV").toUpperCase());
    } catch (IllegalArgumentException e) {
      Logger.error(
          "Illegal mode '%s', use either prod or dev",
          configuration.getProperty("application.mode"));
      fatalServerErrorOccurred();
    }

    // Force the Production mode if forceProd or precompile is activate
    // Set to the Prod mode must be done before loadModules call
    // as some modules (e.g. DocViewver) is only available in DEV
    if (usePrecompiled || forceProd || System.getProperty("precompile") != null) {
      mode = Mode.PROD;
    }

    // Context path
    ctxPath = configuration.getProperty("http.path", ctxPath);

    // Build basic java source path
    VirtualFile appRoot = VirtualFile.open(applicationPath);
    roots.add(appRoot);
    javaPath = new CopyOnWriteArrayList<VirtualFile>();
    javaPath.add(appRoot.child("app"));
    javaPath.add(appRoot.child("conf"));

    // Build basic templates path
    if (appRoot.child("app/views").exists()) {
      templatesPath = new ArrayList<VirtualFile>(2);
      templatesPath.add(appRoot.child("app/views"));
    } else {
      templatesPath = new ArrayList<VirtualFile>(1);
    }

    // Main route file
    routes = appRoot.child("conf/routes");

    // Plugin route files
    modulesRoutes = new HashMap<String, VirtualFile>(16);

    // Load modules
    loadModules();

    // Load the templates from the framework after the one from the modules
    templatesPath.add(VirtualFile.open(new File(frameworkPath, "framework/templates")));

    // Enable a first classloader
    classloader = new ApplicationClassloader();

    // Fix ctxPath
    if ("/".equals(Play.ctxPath)) {
      Play.ctxPath = "";
    }

    // Default cookie domain
    Http.Cookie.defaultDomain = configuration.getProperty("application.defaultCookieDomain", null);
    if (Http.Cookie.defaultDomain != null) {
      Logger.info("Using default cookie domain: " + Http.Cookie.defaultDomain);
    }

    // Plugins
    pluginCollection.loadPlugins();

    // Done !
    if (mode == Mode.PROD) {
      if (preCompile() && System.getProperty("precompile") == null) {
        start();
      } else {
        return;
      }
    } else {
      Logger.warn("You're running Play! in DEV mode");
    }

    // Plugins
    pluginCollection.onApplicationReady();

    Play.initialized = true;
  }