Exemplo n.º 1
0
  @Override
  public void beforeInvocation() {
    //
    // Prevent the regular JPA Plugin from starting a transaction.
    //
    JPA.entityManagerFactory = null;

    //
    //	If we have no databases defined, and we have a directive to permit this state, allow it.
    //
    if (factoryMap.isEmpty()
        && Play.configuration.getProperty("mjpa.runWithNoDB", "").equals("true")) {
      log.debug("Empty factory map--using dummy factory");
      JPA.entityManagerFactory = getDummyFactory();
      return;
    }

    log.debug("Extracting DB key from request: " + Request.current());

    //
    // Find the database key, so that we'll have one for the transaction.
    //
    String dbKey = keyExtractor.extractKey(Request.current());
    log.debug("Found key: " + dbKey);
    try {
      if (dbKey != null) {
        //
        // Start the transaction
        //
        startTx(dbKey, false);
      }
    } catch (InvalidDatabaseException e) {
      throw new NotFound(e.getMessage());
    }
  }
Exemplo n.º 2
0
  @Override
  public Object authenticate(final Context context, final Object payload) throws AuthException {

    final Request request = context.request();
    final String uri = request.uri();

    if (Logger.isDebugEnabled()) {
      Logger.debug("Returned with URL: '" + uri + "'");
    }

    final Configuration c = getConfiguration();

    final ConsumerKey key =
        new ConsumerKey(
            c.getString(SettingKeys.CONSUMER_KEY), c.getString(SettingKeys.CONSUMER_SECRET));
    final String requestTokenURL = c.getString(SettingKeys.REQUEST_TOKEN_URL);
    final String accessTokenURL = c.getString(SettingKeys.ACCESS_TOKEN_URL);
    final String authorizationURL = c.getString(SettingKeys.AUTHORIZATION_URL);
    final ServiceInfo info =
        new ServiceInfo(requestTokenURL, accessTokenURL, authorizationURL, key);
    final OAuth service = new OAuth(info, true);

    checkError(request);

    if (uri.contains(Constants.OAUTH_VERIFIER)) {

      final RequestToken rtoken =
          (RequestToken) PlayAuthenticate.removeFromCache(context.session(), CACHE_TOKEN);
      final String verifier = Authenticate.getQueryString(request, Constants.OAUTH_VERIFIER);
      final Either<OAuthException, RequestToken> retrieveAccessToken =
          service.retrieveAccessToken(rtoken, verifier);

      if (retrieveAccessToken.isLeft()) {
        throw new AuthException(retrieveAccessToken.left().get().getLocalizedMessage());
      } else {
        final I i = buildInfo(retrieveAccessToken.right().get());
        return transform(i);
      }
    } else {

      final String callbackURL = getRedirectUrl(request);

      final Either<OAuthException, RequestToken> reponse =
          service.retrieveRequestToken(callbackURL);

      if (reponse.isLeft()) {
        // Exception happened
        throw new AuthException(reponse.left().get().getLocalizedMessage());
      } else {
        // All good, we have the request token
        final RequestToken rtoken = reponse.right().get();

        final String token = rtoken.token();
        final String redirectUrl = service.redirectUrl(token);

        PlayAuthenticate.storeInCache(context.session(), CACHE_TOKEN, rtoken);
        return redirectUrl;
      }
    }
  }
Exemplo n.º 3
0
  @Test
  public void testUsername() {
    final Request req1 = new RequestBuilder().uri("http://playframework.com/").build();
    final Request req2 = req1.withUsername("user2");

    assertNull(req1.username());
    assertEquals("user2", req2.username());
  }
Exemplo n.º 4
0
 public F.Promise<Result> call(Http.Context ctx) throws Throwable {
   final Request request = ctx.request();
   guiLogger.info(
       request.method()
           + " "
           + request.uri()
           + " ("
           + Controller.session(Users.SESSION_EMAIL)
           + ")");
   return delegate.call(ctx);
 }
Exemplo n.º 5
0
  public void serveStatic(
      HttpServletResponse servletResponse,
      HttpServletRequest servletRequest,
      RenderStatic renderStatic)
      throws IOException {

    VirtualFile file = Play.getVirtualFile(renderStatic.file);
    if (file == null || file.isDirectory() || !file.exists()) {
      serve404(
          servletRequest,
          servletResponse,
          new NotFound("The file " + renderStatic.file + " does not exist"));
    } else {
      servletResponse.setContentType(MimeTypes.getContentType(file.getName()));
      boolean raw = false;
      for (PlayPlugin plugin : Play.plugins) {
        if (plugin.serveStatic(file, Request.current(), Response.current())) {
          raw = true;
          break;
        }
      }
      if (raw) {
        copyResponse(Request.current(), Response.current(), servletRequest, servletResponse);
      } else {
        if (Play.mode == Play.Mode.DEV) {
          servletResponse.setHeader("Cache-Control", "no-cache");
          servletResponse.setHeader("Content-Length", String.valueOf(file.length()));
          if (!servletRequest.getMethod().equals("HEAD")) {
            copyStream(servletResponse, file.inputstream());
          } else {
            copyStream(servletResponse, new ByteArrayInputStream(new byte[0]));
          }
        } else {
          long last = file.lastModified();
          String etag = "\"" + last + "-" + file.hashCode() + "\"";
          if (!isModified(etag, last, servletRequest)) {
            servletResponse.setHeader("Etag", etag);
            servletResponse.setStatus(304);
          } else {
            servletResponse.setHeader(
                "Last-Modified", Utils.getHttpDateFormatter().format(new Date(last)));
            servletResponse.setHeader(
                "Cache-Control",
                "max-age=" + Play.configuration.getProperty("http.cacheControl", "3600"));
            servletResponse.setHeader("Etag", etag);
            copyStream(servletResponse, file.inputstream());
          }
        }
      }
    }
  }
Exemplo n.º 6
0
 public static Result routeAndCall(Router router, RequestBuilder requestBuilder, long timeout) {
   try {
     Request request = requestBuilder.build();
     if (router.routes().isDefinedAt(request._underlyingRequest())) {
       return invokeHandler(router.routes().apply(request._underlyingRequest()), request, timeout);
     } else {
       return null;
     }
   } catch (RuntimeException e) {
     throw e;
   } catch (Throwable t) {
     throw new RuntimeException(t);
   }
 }
Exemplo n.º 7
0
 // default visibility, because we want to use this only from Job.java
 static void addAfterRequestAction(Callable<? extends Object> c) {
   if (Request.current() == null) {
     throw new IllegalStateException(
         "After request actions can be added only from threads that serve requests!");
   }
   afterInvocationActions.get().add(c);
 }
Exemplo n.º 8
0
  public static void serve404(
      NotFound e, ChannelHandlerContext ctx, Request request, HttpRequest nettyRequest) {
    Logger.trace("serve404: begin");
    HttpResponse nettyResponse =
        new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    nettyResponse.setHeader(SERVER, signature);

    nettyResponse.setHeader(CONTENT_TYPE, "text/html");
    Map<String, Object> binding = getBindingForErrors(e, false);

    String format = Request.current().format;
    if (format == null) {
      format = "txt";
    }
    nettyResponse.setHeader(
        CONTENT_TYPE, (MimeTypes.getContentType("404." + format, "text/plain")));

    String errorHtml = TemplateLoader.load("errors/404." + format).render(binding);
    try {
      ChannelBuffer buf = ChannelBuffers.copiedBuffer(errorHtml.getBytes("utf-8"));
      nettyResponse.setContent(buf);
      ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
      writeFuture.addListener(ChannelFutureListener.CLOSE);
    } catch (UnsupportedEncodingException fex) {
      Logger.error(fex, "(utf-8 ?)");
    }
    Logger.trace("serve404: end");
  }
Exemplo n.º 9
0
 /**
  * Check the identity of the user from the current request, that should be the callback from the
  * OpenID server
  */
 public static F.Promise<UserInfo> verifiedId() {
   Request request = Http.Context.current().request();
   scala.concurrent.Future<UserInfo> scalaPromise =
       play.api.libs.openid.OpenID.verifiedId(request.queryString())
           .map(
               new AbstractFunction1<play.api.libs.openid.UserInfo, UserInfo>() {
                 @Override
                 public UserInfo apply(play.api.libs.openid.UserInfo scalaUserInfo) {
                   return new UserInfo(
                       scalaUserInfo.id(),
                       JavaConversions.mapAsJavaMap(scalaUserInfo.attributes()));
                 }
               },
               Invoker.executionContext());
   return F.Promise.wrap(scalaPromise);
 }
Exemplo n.º 10
0
  /**
   * @param template
   * @return
   */
  public static String getTemapletClassName(String template) {
    //
    if (template == null || template.length() == 0) {
      template = template();
    }

    if (template.endsWith(HTML)) {
      template = template.substring(0, template.length() - HTML.length());
    }

    // String action = StackTraceUtils.getCaller(); // too tricky to use
    // stacktrace to track the caller action name
    // something like controllers.japid.SampleController.testFindAction

    if (template.startsWith("@")) {
      // a template in the current directory
      template = Request.current().controller + "/" + template.substring(1);
    }

    // map to default japid view
    if (template.startsWith("controllers.")) {
      template = template.substring(template.indexOf(DOT) + 1);
    }
    String templateClassName =
        template.startsWith(DirUtil.JAPIDVIEWS_ROOT)
            ? template
            : DirUtil.JAPIDVIEWS_ROOT + File.separator + template;

    templateClassName = templateClassName.replace('/', DOT).replace('\\', DOT);
    return templateClassName;
  }
Exemplo n.º 11
0
 @Override
 public String getScheme() {
   if (request.secure()) {
     return "https";
   } else {
     return "http";
   }
 }
Exemplo n.º 12
0
  /**
   * Retrieve the verified OpenID
   *
   * @return A UserInfo object
   */
  public static UserInfo getVerifiedID() {
    try {
      String mode = Params.current().get("openid.mode");

      // Check authentication
      if (mode != null && mode.equals("id_res")) {

        // id
        String id = Params.current().get("openid.claimed_id");
        if (id == null) {
          id = Params.current().get("openid.identity");
        }

        id = normalize(id);

        // server
        String server = Params.current().get("openid.op_endpoint");
        if (server == null) {
          server = discoverServer(id);
        }

        String fields =
            Request.current()
                .querystring
                .replace("openid.mode=id_res", "openid.mode=check_authentication");
        WS.HttpResponse response =
            WS.url(server).mimeType("application/x-www-form-urlencoded").body(fields).post();
        if (response.getStatus() == 200 && response.getString().contains("is_valid:true")) {
          UserInfo userInfo = new UserInfo();
          userInfo.id = id;
          Pattern patternAX = Pattern.compile("^openid[.].+[.]value[.]([^.]+)([.]\\d+)?$");
          Pattern patternSREG = Pattern.compile("^openid[.]sreg[.]([^.]+)$");
          for (String p : Params.current().allSimple().keySet()) {
            Matcher m = patternAX.matcher(p);
            if (m.matches()) {
              String alias = m.group(1);
              userInfo.extensions.put(alias, Params.current().get(p));
            }
            m = patternSREG.matcher(p);
            if (m.matches()) {
              String alias = m.group(1);
              userInfo.extensions.put(alias, Params.current().get(p));
            }
          }
          return userInfo;
        } else {
          return null;
        }
      }

    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    return null;
  }
Exemplo n.º 13
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();
    }
  }
Exemplo n.º 14
0
 @Override
 public Map<String, String[]> getRequestParameters() {
   final Http.RequestBody body = request.body();
   final Map<String, String[]> formParameters;
   if (body != null) {
     formParameters = body.asFormUrlEncoded();
   } else {
     formParameters = new HashMap<>();
   }
   final Map<String, String[]> urlParameters = request.queryString();
   final Map<String, String[]> parameters = new HashMap<>();
   if (formParameters != null) {
     parameters.putAll(formParameters);
   }
   if (urlParameters != null) {
     parameters.putAll(urlParameters);
   }
   return parameters;
 }
 /**
  * 요청 객체에서 라벨ID 를 set 형태로 추출한다.
  *
  * @param request 요청
  * @return 라벨ID set
  */
 public static Set<Long> getLabelIds(final Request request) {
   Set<Long> set = new HashSet<>();
   String[] labelIds = request.queryString().get("labelIds");
   if (labelIds != null) {
     for (String labelId : labelIds) {
       set.add(Long.valueOf(labelId));
     }
   }
   return set;
 }
Exemplo n.º 16
0
  @Override
  public void beforeActionInvocation(Method actionMethod) {
    Scope.RenderArgs binding = Scope.RenderArgs.current();
    Request request = Request.current();
    binding.put("_menu_current", request.url);
    // binding.put("_menu_editing_url", Play.configuration.getProperty("menu.editing.url",
    // Router.reverse("_menu.Configurator.edit").url));

    setRenderArgs_("_menu_context");
    setRenderArgs_("_menu_label");
  }
Exemplo n.º 17
0
  private boolean checkPermission(
      Subject roleHolder, Class<? extends RequestPermission> permissionClass, Context ctx) {
    if (log.isDebugEnabled()) log.debug("checkPermission() <-");

    RequestPermission permission = null;
    try {
      permission = permissionClass.newInstance();
    } catch (Exception e) {
      log.error("cannot create permission", e);
      return false;
    }

    List<? extends Permission> permissions = roleHolder.getPermissions();

    Request request = ctx.request();
    if (log.isDebugEnabled()) log.debug("request : " + request);
    String path = request.path();
    if (log.isDebugEnabled()) log.debug("path : " + path);
    return permission.isAllowed(request, permissions);
  }
Exemplo n.º 18
0
 public static Result routeAndCall(
     Class<? extends Router> router, RequestBuilder requestBuilder, long timeout) {
   try {
     Request request = requestBuilder.build();
     Router routes =
         (Router)
             router
                 .getClassLoader()
                 .loadClass(router.getName() + "$")
                 .getDeclaredField("MODULE$")
                 .get(null);
     if (routes.routes().isDefinedAt(request._underlyingRequest())) {
       return invokeHandler(routes.routes().apply(request._underlyingRequest()), request, timeout);
     } else {
       return null;
     }
   } catch (RuntimeException e) {
     throw e;
   } catch (Throwable t) {
     throw new RuntimeException(t);
   }
 }
Exemplo n.º 19
0
 @Override
 public Object invokeMethod(String name, Object param) {
     try {
         if (controller == null) {
             controller = Request.current().controller;
         }
         String action = controller + "." + name;
         if (action.endsWith(".call")) {
             action = action.substring(0, action.length() - 5);
         }
         try {
             Map<String, Object> r = new HashMap<String, Object>();
             Method actionMethod = (Method) ActionInvoker.getActionMethod(action)[1];
             String[] names = (String[]) actionMethod.getDeclaringClass().getDeclaredField("$" + actionMethod.getName() + LocalVariablesNamesTracer.computeMethodHash(actionMethod.getParameterTypes())).get(null);
             if (param instanceof Object[]) {
                 // too many parameters versus action, possibly a developer error. we must warn him.
                 if (names.length < ((Object[]) param).length) {
                     throw new NoRouteFoundException(action, null);
                 }
                 for (int i = 0; i < ((Object[]) param).length; i++) {
                     if (((Object[]) param)[i] instanceof Router.ActionDefinition && ((Object[]) param)[i] != null) {
                         Unbinder.unBind(r, ((Object[]) param)[i].toString(), i < names.length ? names[i] : "");
                     } else if (isSimpleParam(actionMethod.getParameterTypes()[i])) {
                         if (((Object[]) param)[i] != null) {
                             Unbinder.unBind(r, ((Object[]) param)[i].toString(), i < names.length ? names[i] : "");
                         }
                     } else {
                         Unbinder.unBind(r, ((Object[]) param)[i], i < names.length ? names[i] : "");
                     }
                 }
             }
             Router.ActionDefinition def = Router.reverse(action, r);
             if (absolute) {
                 def.absolute();
             }
             if (template.template.name.endsWith(".html") || template.template.name.endsWith(".xml")) {
                 def.url = def.url.replace("&", "&amp;");
             }
             return def;
         } catch (ActionNotFoundException e) {
             throw new NoRouteFoundException(action, null);
         }
     } catch (Exception e) {
         if (e instanceof PlayException) {
             throw (PlayException) e;
         }
         throw new UnexpectedException(e);
     }
 }
Exemplo n.º 20
0
 @Override
 public Collection<Cookie> getRequestCookies() {
   final List<Cookie> cookies = new ArrayList<>();
   final Http.Cookies httpCookies = request.cookies();
   httpCookies.forEach(
       httpCookie -> {
         final Cookie cookie = new Cookie(httpCookie.name(), httpCookie.value());
         cookie.setDomain(httpCookie.domain());
         cookie.setHttpOnly(httpCookie.httpOnly());
         cookie.setMaxAge(httpCookie.maxAge());
         cookie.setPath(httpCookie.path());
         cookie.setSecure(httpCookie.secure());
         cookies.add(cookie);
       });
   return cookies;
 }
Exemplo n.º 21
0
//
// NOTE: This file was generated from: japidviews/_tags/SampleTag.html
// Change to this file will be lost next time the template file is compiled.
//
@cn.bran.play.NoEnhance
public class SampleTag extends cn.bran.japid.template.JapidTemplateBase {
  public static final String sourceTemplate = "japidviews/_tags/SampleTag.html";

  {
    headers.put("Content-Type", "text/html; charset=utf-8");
  }

  // - add implicit fields with Play

  final Request request = Request.current();
  final Response response = Response.current();
  final Session session = Session.current();
  final RenderArgs renderArgs = RenderArgs.current();
  final Params params = Params.current();
  final Validation validation = Validation.current();
  final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation);
  final play.Play _play = new play.Play();

  // - end of implicit fields with Play

  public SampleTag() {
    super(null);
  }

  public SampleTag(StringBuilder out) {
    super(out);
  }

  private String a;

  public cn.bran.japid.template.RenderResult render(String a) {
    this.a = a;
    long t = -1;
    super.layout();
    return new cn.bran.japid.template.RenderResult(this.headers, getOut(), t);
  }

  @Override
  protected void doLayout() {
    // ------
    ; // line 1
    p("Hi "); // line 1
    p(a); // line 2
    p("!\n"); // line 2
  }
}
Exemplo n.º 22
0
  /**
   * Parses the playframework action expressions. The string inside "()" is evaluated by OGNL in the
   * current context.
   *
   * @param arguments
   * @param attributeValue e.g. "Application.show(obj.id)"
   * @return parsed action path
   */
  @SuppressWarnings("unchecked")
  static String toActionString(final Arguments arguments, String attributeValue) {
    Matcher matcher = PARAM_PATTERN.matcher(attributeValue);
    if (!matcher.matches()) {
      return Router.reverse(attributeValue).toString();
    }

    String exp = matcher.group(1);
    if (StringUtils.isBlank(exp)) {
      return Router.reverse(attributeValue).toString();
    }

    Object obj =
        PlayOgnlVariableExpressionEvaluator.INSTANCE.evaluate(
            arguments.getConfiguration(), arguments, exp, false);
    if (obj instanceof Map) {
      return Router.reverse(attributeValue, (Map<String, Object>) obj).toString();
    }

    List<?> list = obj instanceof List ? (List<?>) obj : Arrays.asList(obj);

    Map<String, Object> paramMap = new HashMap<String, Object>();

    String extracted = StringUtils.substringBefore(attributeValue, "(");
    if (!extracted.contains(".")) {
      extracted = Request.current().controller + "." + extracted;
    }
    Object[] actionMethods = ActionInvoker.getActionMethod(extracted);
    String[] paramNames = null;
    try {
      paramNames = Java.parameterNames((Method) actionMethods[1]);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }

    if (paramNames.length < list.size()) {
      Logger.warn("param length unmatched. %s", Arrays.toString(paramNames));
      throw new ActionNotFoundException(attributeValue, null);
    }

    for (int i = 0; i < list.size(); i++) {
      paramMap.put(paramNames[i], list.get(i));
    }

    return Router.reverse(extracted, paramMap).toString();
  }
Exemplo n.º 23
0
//
// NOTE: This file was generated from: japidviews/more/MyController/myLayout.html
// Change to this file will be lost next time the template file is compiled.
//
@cn.bran.play.NoEnhance
public abstract class myLayout extends cn.bran.japid.template.JapidTemplateBase {
  public static final String sourceTemplate = "japidviews/more/MyController/myLayout.html";

  {
    putHeader("Content-Type", "text/html; charset=utf-8");
  }

  // - add implicit fields with Play

  final Request request = Request.current();
  final Response response = Response.current();
  final Session session = Session.current();
  final RenderArgs renderArgs = RenderArgs.current();
  final Params params = Params.current();
  final Validation validation = Validation.current();
  final cn.bran.play.FieldErrors errors = new cn.bran.play.FieldErrors(validation);
  final play.Play _play = new play.Play();

  // - end of implicit fields with Play

  public myLayout() {
    super(null);
  }

  public myLayout(StringBuilder out) {
    super(out);
  }

  @Override
  public void layout() {
    p("<p>"); // line 1
    title(); // line 1
    p("</p>\n" + "<p>"); // line 1
    side(); // line 2
    p("</p>\n" + "<p>\n"); // line 2
    doLayout(); // line 4
    p("</p>"); // line 4
  }

  protected void title() {};

  protected void side() {};

  protected abstract void doLayout();
}
Exemplo n.º 24
0
 // --
 @SuppressWarnings(value = "unchecked")
 private static Result invokeHandler(
     play.api.mvc.Handler handler, Request requestBuilder, long timeout) {
   if (handler instanceof play.api.mvc.Action) {
     play.api.mvc.Action action = (play.api.mvc.Action) handler;
     return wrapScalaResult(action.apply(requestBuilder._underlyingRequest()), timeout);
   } else if (handler instanceof JavaHandler) {
     return invokeHandler(
         ((JavaHandler) handler)
             .withComponents(
                 Play.application().injector().instanceOf(JavaHandlerComponents.class)),
         requestBuilder,
         timeout);
   } else {
     throw new RuntimeException("This is not a JavaAction and can't be invoked this way.");
   }
 }
Exemplo n.º 25
0
  @Override
  protected void service(
      HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
      throws ServletException, IOException {

    if (!routerInitializedWithContext) {
      // Reload the rules, but this time with the context. Not really efficient through...
      // Servlet 2.4 does not allow you to get the context path from the servletcontext...
      loadRouter(httpServletRequest.getContextPath());
    }

    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);
      Logger.trace("ServletWrapper>service, request: " + request);
      boolean raw = false;
      for (PlayPlugin plugin : Play.plugins) {
        if (plugin.rawInvocation(request, response)) {
          raw = true;
          break;
        }
      }
      if (raw) {
        copyResponse(
            Request.current(), Response.current(), httpServletRequest, httpServletResponse);
      } else {
        Invoker.invokeInThread(
            new ServletInvocation(request, response, httpServletRequest, httpServletResponse));
      }
    } catch (NotFound e) {
      Logger.trace("ServletWrapper>service, NotFound: " + e);
      serve404(httpServletRequest, httpServletResponse, e);
      return;
    } catch (RenderStatic e) {
      Logger.trace("ServletWrapper>service, RenderStatic: " + e);
      serveStatic(httpServletResponse, httpServletRequest, e);
      return;
    } catch (Throwable e) {
      throw new ServletException(e);
    }
  }
Exemplo n.º 26
0
  public static String template() {
    // the super.template() class uses current request object to determine
    // the caller and method to find the matching template
    // this won't work if the current method is called from another action.
    // let's fall back to use the stack trace to deduce the template.
    // String caller2 = StackTraceUtils.getCaller2();

    final StackTraceElement[] stes = new Throwable().getStackTrace();
    // let's iterate back in the stacktrace to find the recent action calls.
    for (StackTraceElement st : stes) {
      String controller = st.getClassName();
      String action = st.getMethodName();
      ApplicationClass conAppClass = Play.classes.getApplicationClass(controller);
      if (conAppClass != null) {
        Class controllerClass = conAppClass.javaClass;
        if (JapidController2.class.isAssignableFrom(controllerClass)) {
          Method actionMethod = /* Java. */ findActionMethod(action, controllerClass);
          if (actionMethod != null) {
            String expr = controller + "." + action;
            // content negotiation
            String format = Request.current().format;
            if ("html".equals(format)) {
              return expr;
            } else {
              String expr_format = expr + "_" + format;
              if (expr_format.startsWith("controllers.")) {
                expr_format = "japidviews" + expr_format.substring(expr_format.indexOf('.'));
              }
              RendererClass rc = JapidPlayRenderer.japidClasses.get(expr_format);
              if (rc != null) return expr_format;
              else {
                // fall back
                return expr;
              }
            }
          }
        }
      }
    }
    throw new RuntimeException(
        "The calling stack does not contain a valid controller. Should not have happended...");
  }
Exemplo n.º 27
0
 public void serve404(
     HttpServletRequest servletRequest, HttpServletResponse servletResponse, NotFound e) {
   Logger.warn(
       "404 -> %s %s (%s)",
       servletRequest.getMethod(), servletRequest.getRequestURI(), e.getMessage());
   servletResponse.setStatus(404);
   servletResponse.setContentType("text/html");
   Map<String, Object> binding = new HashMap<String, Object>();
   binding.put("result", e);
   binding.put("session", Scope.Session.current());
   binding.put("request", Http.Request.current());
   binding.put("flash", Scope.Flash.current());
   binding.put("params", Scope.Params.current());
   binding.put("play", new Play());
   try {
     binding.put("errors", Validation.errors());
   } catch (Exception ex) {
     //
   }
   String format = Request.current().format;
   servletResponse.setStatus(404);
   // Do we have an ajax request? If we have then we want to display some text even if it is html
   // that is requested
   if ("XMLHttpRequest".equals(servletRequest.getHeader("X-Requested-With"))
       && (format == null || format.equals("html"))) {
     format = "txt";
   }
   if (format == null) {
     format = "txt";
   }
   servletResponse.setContentType(MimeTypes.getContentType("404." + format, "text/plain"));
   String errorHtml = TemplateLoader.load("errors/404." + format).render(binding);
   try {
     servletResponse.getOutputStream().write(errorHtml.getBytes(Response.current().encoding));
   } catch (Exception fex) {
     Logger.error(fex, "(encoding ?)");
   }
 }
Exemplo n.º 28
0
  /**
   * GIT RPC 요청을 처리합니다.
   *
   * <p>when: {@link controllers.GitApp#service(String, String, String, boolean)}에서 사용한다.
   *
   * @param project
   * @param service
   * @param request
   * @param response
   * @return
   * @throws IOException
   * @see <a
   *     href="https://www.kernel.org/pub/software/scm/git/docs/git-upload-pack.html">git-upload-pack</a>
   * @see <a
   *     href="https://www.kernel.org/pub/software/scm/git/docs/git-receive-pack.html">git-receive-pack</a>
   */
  public static byte[] gitRpc(Project project, String service, Request request, Response response)
      throws IOException {
    response.setContentType("application/x-" + service + "-result");
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    // FIXME 스트림으로..
    RawBuffer raw = request.body().asRaw();
    byte[] buf = raw.asBytes();
    InputStream in;

    // If the content size is bigger than memoryThreshold,
    // which is defined as 100 * 1024 in play.api.mvc.BodyParsers trait,
    // the content is stored as a file.
    if (buf != null) {
      in = new ByteArrayInputStream(buf);
    } else {
      in = new FileInputStream(raw.asFile());
    }

    Repository repository = createGitRepository(project);

    if (service.equals("git-upload-pack")) {
      UploadPack uploadPack = new UploadPack(repository);
      uploadPack.setBiDirectionalPipe(false);
      uploadPack.upload(in, byteArrayOutputStream, null);
    } else if (service.equals("git-receive-pack")) {
      ReceivePack receivePack = new ReceivePack(repository);
      receivePack.setBiDirectionalPipe(false);
      receivePack.receive(in, byteArrayOutputStream, null);
    }

    // receivePack.setEchoCommandFailures(true);//git버전에 따라서 불린값 설정필요.
    byteArrayOutputStream.close();

    return byteArrayOutputStream.toByteArray();
  }
Exemplo n.º 29
0
 private void renderPDF(OutputStream out, Request request, Response response) throws Exception {
   Map<?, ?> properties = Play.configuration;
   String uri = request.getBase() + request.url;
   if (docs.documents.size() == 1) {
     renderDoc(docs.documents.get(0), uri, properties, out);
   } else {
     // we need to concatenate them all
     Document resultDocument = new Document();
     PdfCopy copy = new PdfCopy(resultDocument, out);
     resultDocument.open();
     ByteArrayOutputStream os = new ByteArrayOutputStream();
     for (PDFDocument doc : docs.documents) {
       os.reset();
       renderDoc(doc, uri, properties, os);
       PdfReader pdfReader = new PdfReader(os.toByteArray());
       int n = pdfReader.getNumberOfPages();
       for (int i = 0; i < n; i++) {
         copy.addPage(copy.getImportedPage(pdfReader, i + 1));
       }
       copy.freeReader(pdfReader);
     }
     resultDocument.close();
   }
 }
Exemplo n.º 30
0
 @Test
 public void testUri_asterisk() {
   Request request = new RequestBuilder().method("OPTIONS").uri("*").build();
   assertEquals("*", request.uri());
 }