Exemplo n.º 1
0
 private static void extractHttpPort() {
   final String javaCommand = System.getProperty("sun.java.command", "");
   jregex.Matcher m = new jregex.Pattern(".* --http.port=({port}\\d+)").matcher(javaCommand);
   if (m.matches()) {
     configuration.setProperty("http.port", m.group("port"));
   }
 }
Exemplo n.º 2
0
 public void addParams(String params) {
   if (params == null || params.length() < 1) {
     return;
   }
   params = params.substring(1, params.length() - 1);
   for (String param : params.split(",")) {
     Matcher matcher = paramPattern.matcher(param);
     if (matcher.matches()) {
       staticArgs.put(matcher.group(1), matcher.group(2));
     } else {
       Logger.warn("Ignoring %s (static params must be specified as key:'value',...)", params);
     }
   }
 }
Exemplo n.º 3
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);
 }
Exemplo n.º 4
0
 static {
   String datasourceName = DBPlugin.getDatasourceName();
   Matcher m =
       new jregex.Pattern(
               "^mysql:(//)?(({user}[a-zA-Z0-9_]+)(:({pwd}[^@]+))?@)?(({host}[^/]+)/)?({name}[^\\s]+)$")
           .matcher(datasourceName);
   if (m.matches()) {
     host = m.group("host") == null ? "localhost" : m.group("host");
     port = "3306";
     if (host.contains(":")) {
       String[] split = host.split(":");
       host = split[0];
       port = split[1];
     }
     username = m.group("user");
     password = m.group("pwd");
     database = m.group("name");
   }
 }
Exemplo n.º 5
0
 static void parse(String content, String prefix, String fileAbsolutePath) {
   int lineNumber = 0;
   for (String line : content.split("\n")) {
     lineNumber++;
     line = line.trim().replaceAll("\\s+", " ");
     if (line.length() == 0 || line.startsWith("#")) {
       continue;
     }
     Matcher matcher = routePattern.matcher(line);
     if (matcher.matches()) {
       String action = matcher.group("action");
       // module:
       if (action.startsWith("module:")) {
         String moduleName = action.substring("module:".length());
         String newPrefix = prefix + matcher.group("path");
         if (newPrefix.length() > 1 && newPrefix.endsWith("/")) {
           newPrefix = newPrefix.substring(0, newPrefix.length() - 1);
         }
         if (moduleName.equals("*")) {
           for (String p : Play.modulesRoutes.keySet()) {
             parse(Play.modulesRoutes.get(p), newPrefix + p);
           }
         } else if (Play.modulesRoutes.containsKey(moduleName)) {
           parse(Play.modulesRoutes.get(moduleName), newPrefix);
         } else {
           Logger.error("Cannot include routes for module %s (not found)", moduleName);
         }
       } else {
         String method = matcher.group("method");
         String path = prefix + matcher.group("path");
         String params = matcher.group("params");
         String headers = matcher.group("headers");
         appendRoute(method, path, action, params, headers, fileAbsolutePath, lineNumber);
       }
     } else {
       Logger.error("Invalid route definition : %s", line);
     }
   }
 }
Exemplo n.º 6
0
  private static boolean changed() {
    Properties p = Play.configuration;

    if ("mem".equals(p.getProperty("db")) && p.getProperty("db.url") == null) {
      p.put("db.driver", "org.h2.Driver");
      p.put("db.url", "jdbc:h2:mem:play;MODE=MYSQL");
      p.put("db.user", "sa");
      p.put("db.pass", "");
    }

    if ("fs".equals(p.getProperty("db")) && p.getProperty("db.url") == null) {
      p.put("db.driver", "org.h2.Driver");
      p.put(
          "db.url",
          "jdbc:h2:"
              + (new File(Play.applicationPath, "db/h2/play").getAbsolutePath())
              + ";MODE=MYSQL");
      p.put("db.user", "sa");
      p.put("db.pass", "");
    }

    if (p.getProperty("db", "").startsWith("java:") && p.getProperty("db.url") == null) {
      if (DB.datasource == null) {
        return true;
      }
    } else {
      // Internal pool is c3p0, we should call the close() method to destroy it.
      check(p, "internal pool", "db.destroyMethod");

      p.put("db.destroyMethod", "close");
    }

    Matcher m =
        new jregex.Pattern(
                "^mysql:(//)?(({user}[a-zA-Z0-9_]+)(:({pwd}[^@]+))?@)?(({host}[^/]+)/)?({name}[^\\s]+)$")
            .matcher(p.getProperty("db", ""));
    if (m.matches()) {
      String user = m.group("user");
      String password = m.group("pwd");
      String name = m.group("name");
      String host = m.group("host");
      p.put("db.driver", "com.mysql.jdbc.Driver");
      p.put(
          "db.url",
          "jdbc:mysql://"
              + (host == null ? "localhost" : host)
              + "/"
              + name
              + "?useUnicode=yes&characterEncoding=UTF-8&connectionCollation=utf8_general_ci");
      if (user != null) {
        p.put("db.user", user);
      }
      if (password != null) {
        p.put("db.pass", password);
      }
    }

    m =
        new jregex.Pattern(
                "^postgres:(//)?(({user}[a-zA-Z0-9_]+)(:({pwd}[^@]+))?@)?(({host}[^/]+)/)?({name}[^\\s]+)$")
            .matcher(p.getProperty("db", ""));
    if (m.matches()) {
      String user = m.group("user");
      String password = m.group("pwd");
      String name = m.group("name");
      String host = m.group("host");
      p.put("db.driver", "org.postgresql.Driver");
      p.put("db.url", "jdbc:postgresql://" + (host == null ? "localhost" : host) + "/" + name);
      if (user != null) {
        p.put("db.user", user);
      }
      if (password != null) {
        p.put("db.pass", password);
      }
    }

    if (p.getProperty("db.url") != null && p.getProperty("db.url").startsWith("jdbc:h2:mem:")) {
      p.put("db.driver", "org.h2.Driver");
      p.put("db.user", "sa");
      p.put("db.pass", "");
    }

    if ((p.getProperty("db.driver") == null) || (p.getProperty("db.url") == null)) {
      return false;
    }

    if (DB.datasource == null) {
      return true;
    } else {
      ComboPooledDataSource ds = (ComboPooledDataSource) DB.datasource;
      if (!p.getProperty("db.driver").equals(ds.getDriverClass())) {
        return true;
      }
      if (!p.getProperty("db.url").equals(ds.getJdbcUrl())) {
        return true;
      }
      if (!p.getProperty("db.user", "").equals(ds.getUser())) {
        return true;
      }
      if (!p.getProperty("db.pass", "").equals(ds.getPassword())) {
        return true;
      }
    }

    if (!p.getProperty("db.destroyMethod", "").equals(DB.destroyMethod)) {
      return true;
    }

    return false;
  }
Exemplo n.º 7
0
    /**
     * Check if the parts of a HTTP request equal this Route.
     *
     * @param method GET/POST/etc.
     * @param path Part after domain and before query-string. Starts with a "/".
     * @param accept Format, e.g. html.
     * @param domain The domain (host without port).
     * @return ???
     */
    public Map<String, String> matches(String method, String path, String accept, String domain) {
      // Normalize
      if (path.equals(Play.ctxPath)) {
        path = path + "/";
      }
      // If method is HEAD and we have a GET
      if (method == null
          || this.method.equals("*")
          || method.equalsIgnoreCase(this.method)
          || (method.equalsIgnoreCase("head") && ("get").equalsIgnoreCase(this.method))) {

        Matcher matcher = pattern.matcher(path);

        boolean hostMatches = (domain == null);
        if (domain != null) {

          Matcher hostMatcher = hostPattern.matcher(domain);
          hostMatches = hostMatcher.matches();
        }
        // Extract the host variable
        if (matcher.matches() && contains(accept) && hostMatches) {
          // 404
          if (action.equals("404")) {
            throw new NotFound(method, path);
          }
          // Static dir
          if (staticDir != null) {
            String resource = null;
            if (!staticFile) {
              resource = matcher.group("resource");
            }
            try {
              String root = new File(staticDir).getCanonicalPath();
              String urlDecodedResource = Utils.urlDecodePath(resource);
              String childResourceName = staticDir + (staticFile ? "" : "/" + urlDecodedResource);
              String child = new File(childResourceName).getCanonicalPath();
              if (child.startsWith(root)) {
                throw new RenderStatic(childResourceName);
              }
            } catch (IOException e) {
            }
            throw new NotFound(resource);
          } else {
            Map<String, String> localArgs = new HashMap<String, String>();
            for (Arg arg : args) {
              // FIXME: Careful with the arguments that are not matching as they are part of the
              // hostname
              // Defaultvalue indicates it is a one of these urls. This is a trick and should be
              // changed.
              if (arg.defaultValue == null) {
                localArgs.put(arg.name, Utils.urlDecodePath(matcher.group(arg.name)));
              }
            }
            if (hostArg != null && domain != null) {
              // Parse the hostname and get only the part we are interested in
              String routeValue = hostArg.defaultValue.replaceAll("\\{.*}", "");
              domain = domain.replace(routeValue, "");
              localArgs.put(hostArg.name, domain);
            }
            localArgs.putAll(staticArgs);
            return localArgs;
          }
        }
      }
      return null;
    }
Exemplo n.º 8
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);
      }
    }
Exemplo n.º 9
0
  public static ActionDefinition reverse(String action, Map<String, Object> args) {

    String encoding =
        Http.Response.current() == null
            ? Play.defaultWebEncoding
            : Http.Response.current().encoding;

    if (action.startsWith("controllers.")) {
      action = action.substring(12);
    }
    Map<String, Object> argsbackup = new HashMap<String, Object>(args);
    // Add routeArgs
    if (Scope.RouteArgs.current() != null) {
      for (String key : Scope.RouteArgs.current().data.keySet()) {
        if (!args.containsKey(key)) {
          args.put(key, Scope.RouteArgs.current().data.get(key));
        }
      }
    }
    for (Route route : routes) {
      if (route.actionPattern != null) {
        Matcher matcher = route.actionPattern.matcher(action);
        if (matcher.matches()) {
          for (String group : route.actionArgs) {
            String v = matcher.group(group);
            if (v == null) {
              continue;
            }
            args.put(group, v.toLowerCase());
          }
          List<String> inPathArgs = new ArrayList<String>(16);
          boolean allRequiredArgsAreHere = true;
          // les noms de parametres matchent ils ?
          for (Route.Arg arg : route.args) {
            inPathArgs.add(arg.name);
            Object value = args.get(arg.name);
            if (value == null) {
              // This is a hack for reverting on hostname that are a regex expression.
              // See [#344] for more into. This is not optimal and should retough. However,
              // it allows us to do things like {(.*}}.domain.com
              String host = route.host.replaceAll("\\{", "").replaceAll("\\}", "");
              if (host.equals(arg.name) || host.matches(arg.name)) {
                args.remove(arg.name);
                route.host = Http.Request.current() == null ? "" : Http.Request.current().domain;
                break;
              } else {
                allRequiredArgsAreHere = false;
                break;
              }
            } else {
              if (value instanceof List<?>) {
                @SuppressWarnings("unchecked")
                List<Object> l = (List<Object>) value;
                value = l.get(0);
              }
              if (!value.toString().startsWith(":") && !arg.constraint.matches(value.toString())) {
                allRequiredArgsAreHere = false;
                break;
              }
            }
          }
          // les parametres codes en dur dans la route matchent-ils ?
          for (String staticKey : route.staticArgs.keySet()) {
            if (staticKey.equals("format")) {
              if (!(Http.Request.current() == null ? "" : Http.Request.current().format)
                  .equals(route.staticArgs.get("format"))) {
                allRequiredArgsAreHere = false;
                break;
              }
              continue; // format is a special key
            }
            if (!args.containsKey(staticKey)
                || (args.get(staticKey) == null)
                || !args.get(staticKey).toString().equals(route.staticArgs.get(staticKey))) {
              allRequiredArgsAreHere = false;
              break;
            }
          }
          if (allRequiredArgsAreHere) {
            StringBuilder queryString = new StringBuilder();
            String path = route.path;
            String host = route.host;
            if (path.endsWith("/?")) {
              path = path.substring(0, path.length() - 2);
            }
            for (Map.Entry<String, Object> entry : args.entrySet()) {
              String key = entry.getKey();
              Object value = entry.getValue();
              if (inPathArgs.contains(key) && value != null) {
                if (List.class.isAssignableFrom(value.getClass())) {
                  @SuppressWarnings("unchecked")
                  List<Object> vals = (List<Object>) value;
                  path =
                      path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", vals.get(0).toString())
                          .replace("$", "\\$");
                } else {
                  path =
                      path.replaceAll(
                          "\\{(<[^>]+>)?" + key + "\\}",
                          value
                              .toString()
                              .replace("$", "\\$")
                              .replace("%3A", ":")
                              .replace("%40", "@"));
                  host =
                      host.replaceAll(
                          "\\{(<[^>]+>)?" + key + "\\}",
                          value
                              .toString()
                              .replace("$", "\\$")
                              .replace("%3A", ":")
                              .replace("%40", "@"));
                }
              } else if (route.staticArgs.containsKey(key)) {
                // Do nothing -> The key is static
              } else if (Scope.RouteArgs.current() != null
                  && Scope.RouteArgs.current().data.containsKey(key)) {
                // Do nothing -> The key is provided in RouteArgs and not used (see #447)
              } else if (value != null) {
                if (List.class.isAssignableFrom(value.getClass())) {
                  @SuppressWarnings("unchecked")
                  List<Object> vals = (List<Object>) value;
                  for (Object object : vals) {
                    try {
                      queryString.append(URLEncoder.encode(key, encoding));
                      queryString.append("=");
                      if (object.toString().startsWith(":")) {
                        queryString.append(object.toString());
                      } else {
                        queryString.append(URLEncoder.encode(object.toString() + "", encoding));
                      }
                      queryString.append("&");
                    } catch (UnsupportedEncodingException ex) {
                    }
                  }
                } else if (value.getClass().equals(Default.class)) {
                  // Skip defaults in queryString
                } else {
                  try {
                    queryString.append(URLEncoder.encode(key, encoding));
                    queryString.append("=");
                    if (value.toString().startsWith(":")) {
                      queryString.append(value.toString());
                    } else {
                      queryString.append(URLEncoder.encode(value.toString() + "", encoding));
                    }
                    queryString.append("&");
                  } catch (UnsupportedEncodingException ex) {
                  }
                }
              }
            }
            String qs = queryString.toString();
            if (qs.endsWith("&")) {
              qs = qs.substring(0, qs.length() - 1);
            }
            ActionDefinition actionDefinition = new ActionDefinition();
            actionDefinition.url = qs.length() == 0 ? path : path + "?" + qs;
            actionDefinition.method =
                route.method == null || route.method.equals("*")
                    ? "GET"
                    : route.method.toUpperCase();
            actionDefinition.star = "*".equals(route.method);
            actionDefinition.action = action;
            actionDefinition.args = argsbackup;
            actionDefinition.host = host;
            return actionDefinition;
          }
        }
      }
    }
    throw new NoRouteFoundException(action, args);
  }