Ejemplo n.º 1
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());
          }
        }
      }
    }
  }
Ejemplo n.º 2
0
 public static Object bind(Object o, String name, Map<String, String[]> params) {
   for (PlayPlugin plugin : Play.plugins) {
     Object result = plugin.bind(name, o, params);
     if (result != null) {
       return result;
     }
   }
   try {
     return new BeanWrapper(o.getClass()).bind(name, null, params, "", o, null);
   } catch (Exception e) {
     Validation.addError(name, "validation.invalid");
     return null;
   }
 }
Ejemplo n.º 3
0
 private void init_() {
   Properties p = Play.configuration;
   String menuClass = p.getProperty("menu.class");
   if (null == menuClass) {
     for (PlayPlugin pp : Play.pluginCollection.getEnabledPlugins()) {
       String cn = pp.getClass().getName();
       if (cn.contains("Morphia") || cn.contains("Mongo")) {
         menuClass = "models._menu.MongoMenu";
         break;
       }
     }
   }
   if (null == menuClass) menuClass = "models._menu.JPAMenu";
   setMenuClass_(menuClass);
 }
Ejemplo n.º 4
0
 public void _delete() {
   try {
     avoidCascadeSaveLoops.set(new HashSet<JPABase>());
     try {
       saveAndCascade(true);
     } finally {
       avoidCascadeSaveLoops.get().clear();
     }
     em().remove(this);
     try {
       em().flush();
     } catch (PersistenceException e) {
       if (e.getCause() instanceof GenericJDBCException) {
         throw new PersistenceException(((GenericJDBCException) e.getCause()).getSQL(), e);
       } else {
         throw e;
       }
     }
     avoidCascadeSaveLoops.set(new HashSet<JPABase>());
     try {
       saveAndCascade(false);
     } finally {
       avoidCascadeSaveLoops.get().clear();
     }
     PlayPlugin.postEvent("JPASupport.objectDeleted", this);
   } catch (PersistenceException e) {
     throw e;
   } catch (Throwable e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 5
0
 public void _save() {
   if (!em().contains(this)) {
     em().persist(this);
     PlayPlugin.postEvent("JPASupport.objectPersisted", this);
   }
   avoidCascadeSaveLoops.set(new HashSet<JPABase>());
   try {
     saveAndCascade(true);
   } finally {
     avoidCascadeSaveLoops.get().clear();
   }
   try {
     em().flush();
   } catch (PersistenceException e) {
     if (e.getCause() instanceof GenericJDBCException) {
       throw new PersistenceException(((GenericJDBCException) e.getCause()).getSQL(), e);
     } else {
       throw e;
     }
   }
   avoidCascadeSaveLoops.set(new HashSet<JPABase>());
   try {
     saveAndCascade(false);
   } finally {
     avoidCascadeSaveLoops.get().clear();
   }
 }
Ejemplo n.º 6
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);
    }
  }
Ejemplo n.º 7
0
 private void saveAndCascade(boolean willBeSaved) {
   this.willBeSaved = willBeSaved;
   if (avoidCascadeSaveLoops.get().contains(this)) {
     return;
   } else {
     avoidCascadeSaveLoops.get().add(this);
     if (willBeSaved) {
       PlayPlugin.postEvent("JPASupport.objectUpdated", this);
     }
   }
   // Cascade save
   try {
     Set<Field> fields = new HashSet<Field>();
     Class clazz = this.getClass();
     while (!clazz.equals(JPABase.class)) {
       Collections.addAll(fields, clazz.getDeclaredFields());
       clazz = clazz.getSuperclass();
     }
     for (Field field : fields) {
       field.setAccessible(true);
       if (Modifier.isTransient(field.getModifiers())) {
         continue;
       }
       boolean doCascade = false;
       if (field.isAnnotationPresent(OneToOne.class)) {
         doCascade = cascadeAll(field.getAnnotation(OneToOne.class).cascade());
       }
       if (field.isAnnotationPresent(OneToMany.class)) {
         doCascade = cascadeAll(field.getAnnotation(OneToMany.class).cascade());
       }
       if (field.isAnnotationPresent(ManyToOne.class)) {
         doCascade = cascadeAll(field.getAnnotation(ManyToOne.class).cascade());
       }
       if (field.isAnnotationPresent(ManyToMany.class)) {
         doCascade = cascadeAll(field.getAnnotation(ManyToMany.class).cascade());
       }
       if (doCascade) {
         Object value = field.get(this);
         if (value == null) {
           continue;
         }
         if (value instanceof PersistentMap) {
           if (((PersistentMap) value).wasInitialized()) {
             for (Object o : ((Map) value).values()) {
               if (o instanceof JPABase) {
                 ((JPABase) o).saveAndCascade(willBeSaved);
               }
             }
           }
           continue;
         }
         if (value instanceof PersistentCollection) {
           if (((PersistentCollection) value).wasInitialized()) {
             for (Object o : (Collection) value) {
               if (o instanceof JPABase) {
                 ((JPABase) o).saveAndCascade(willBeSaved);
               }
             }
           }
           continue;
         }
         if (value instanceof HibernateProxy && value instanceof JPABase) {
           if (!((HibernateProxy) value).getHibernateLazyInitializer().isUninitialized()) {
             ((JPABase) ((HibernateProxy) value).getHibernateLazyInitializer().getImplementation())
                 .saveAndCascade(willBeSaved);
           }
           continue;
         }
         if (value instanceof JPABase) {
           ((JPABase) value).saveAndCascade(willBeSaved);
           continue;
         }
       }
     }
   } catch (Exception e) {
     throw new UnexpectedException("During cascading save()", e);
   }
 }
Ejemplo n.º 8
0
  @Override
  public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e)
      throws Exception {
    Logger.trace("messageReceived: begin");
    final Object msg = e.getMessage();

    // Http request
    if (msg instanceof HttpRequest) {

      final HttpRequest nettyRequest = (HttpRequest) msg;

      // Websocket upgrade
      if (HttpHeaders.Values.UPGRADE.equalsIgnoreCase(nettyRequest.getHeader(CONNECTION))
          && HttpHeaders.Values.WEBSOCKET.equalsIgnoreCase(
              nettyRequest.getHeader(HttpHeaders.Names.UPGRADE))) {
        websocketHandshake(ctx, nettyRequest, e);
        return;
      }

      // Plain old HttpRequest
      try {
        final Request request = parseRequest(ctx, nettyRequest);

        final Response response = new Response();
        Http.Response.current.set(response);

        // Buffered in memory output
        response.out = new ByteArrayOutputStream();

        // Direct output (will be set later)
        response.direct = null;

        // Streamed output (using response.writeChunk)
        response.onWriteChunk(
            new Action<Object>() {

              public void invoke(Object result) {
                writeChunk(request, response, ctx, nettyRequest, result);
              }
            });

        // Raw invocation
        boolean raw = false;
        for (PlayPlugin plugin : Play.plugins) {
          if (plugin.rawInvocation(request, response)) {
            raw = true;
            break;
          }
        }
        if (raw) {
          copyResponse(ctx, request, response, nettyRequest);
        } else {

          // Deleguate to Play framework
          Invoker.invoke(new NettyInvocation(request, response, ctx, nettyRequest, e));
        }

      } catch (Exception ex) {
        serve500(ex, ctx, nettyRequest);
      }
    }

    // Websocket frame
    if (msg instanceof WebSocketFrame) {
      WebSocketFrame frame = (WebSocketFrame) msg;
      websocketFrameReceived(ctx, frame);
    }

    Logger.trace("messageReceived: end");
  }
Ejemplo n.º 9
0
  public void serveStatic(
      RenderStatic renderStatic,
      ChannelHandlerContext ctx,
      Request request,
      Response response,
      HttpRequest nettyRequest,
      MessageEvent e) {
    Logger.trace("serveStatic: begin");
    HttpResponse nettyResponse =
        new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(response.status));
    if (exposePlayServer) {
      nettyResponse.setHeader(SERVER, signature);
    }
    try {
      VirtualFile file = Play.getVirtualFile(renderStatic.file);
      if (file != null && file.exists() && file.isDirectory()) {
        file = file.child("index.html");
        if (file != null) {
          renderStatic.file = file.relativePath();
        }
      }
      if ((file == null || !file.exists())) {
        serve404(
            new NotFound("The file " + renderStatic.file + " does not exist"),
            ctx,
            request,
            nettyRequest);
      } else {
        boolean raw = false;
        for (PlayPlugin plugin : Play.plugins) {
          if (plugin.serveStatic(file, Request.current(), Response.current())) {
            raw = true;
            break;
          }
        }
        if (raw) {
          copyResponse(ctx, request, response, nettyRequest);
        } else {
          final File localFile = file.getRealFile();
          final boolean keepAlive = isKeepAlive(nettyRequest);
          nettyResponse = addEtag(nettyRequest, nettyResponse, localFile);

          if (nettyResponse.getStatus().equals(HttpResponseStatus.NOT_MODIFIED)) {

            Channel ch = e.getChannel();

            // Write the initial line and the header.
            ChannelFuture writeFuture = ch.write(nettyResponse);
            if (!keepAlive) {
              // Write the content.
              writeFuture.addListener(ChannelFutureListener.CLOSE);
            }
          } else {

            final RandomAccessFile raf = new RandomAccessFile(localFile, "r");
            try {
              long fileLength = raf.length();

              Logger.trace("keep alive " + keepAlive);
              Logger.trace(
                  "content type " + (MimeTypes.getContentType(localFile.getName(), "text/plain")));

              if (keepAlive && !nettyResponse.getStatus().equals(HttpResponseStatus.NOT_MODIFIED)) {
                // Add 'Content-Length' header only for a keep-alive connection.
                Logger.trace("file length " + fileLength);
                setContentLength(nettyResponse, fileLength);
              }

              nettyResponse.setHeader(
                  CONTENT_TYPE, (MimeTypes.getContentType(localFile.getName(), "text/plain")));

              Channel ch = e.getChannel();

              // Write the initial line and the header.
              ChannelFuture writeFuture = ch.write(nettyResponse);

              // Write the content.
              if (!nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
                writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192));
              } else {
                raf.close();
              }

              if (!keepAlive) {
                // Close the connection when the whole content is written out.
                writeFuture.addListener(ChannelFutureListener.CLOSE);
              }
            } catch (Throwable exx) {
              try {
                raf.close();
              } catch (Throwable ex) {
                /* Left empty */
              }
              try {
                ctx.getChannel().close();
              } catch (Throwable ex) {
                /* Left empty */
              }
            }
          }
        }
      }
    } catch (Throwable ez) {
      Logger.error(ez, "serveStatic for request %s", request.method + " " + request.url);
      try {
        HttpResponse errorResponse =
            new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        ChannelBuffer buf =
            ChannelBuffers.copiedBuffer("Internal Error (check logs)".getBytes("utf-8"));
        errorResponse.setContent(buf);
        ChannelFuture future = ctx.getChannel().write(errorResponse);
        future.addListener(ChannelFutureListener.CLOSE);
      } catch (Exception ex) {
        Logger.error(ez, "serveStatic for request %s", request.method + " " + request.url);
      }
    }
    Logger.trace("serveStatic: end");
  }
Ejemplo n.º 10
0
  public static Object bind(
      String name,
      Class<?> clazz,
      Type type,
      Annotation[] annotations,
      Map<String, String[]> params,
      Object o,
      Method method,
      int parameterIndex) {
    Logger.trace("bind: name [" + name + "] annotation [" + Utils.join(annotations, " ") + "] ");

    Object result = null;
    // Let a chance to plugins to bind this object
    for (PlayPlugin plugin : Play.plugins) {
      result = plugin.bind(name, clazz, type, annotations, params);
      if (result != null) {
        return result;
      }
    }
    String[] profiles = null;
    if (annotations != null) {
      for (Annotation annotation : annotations) {
        if (annotation.annotationType().equals(As.class)) {
          As as = ((As) annotation);
          profiles = as.value();
        }
        if (annotation.annotationType().equals(NoBinding.class)) {
          NoBinding bind = ((NoBinding) annotation);
          profiles = bind.value();
        }
      }
    }
    result = bindInternal(name, clazz, type, annotations, params, "", profiles);

    if (result == MISSING) {
      // Try the scala default
      if (o != null && parameterIndex > 0) {
        try {
          Method defaultMethod =
              method
                  .getDeclaringClass()
                  .getDeclaredMethod(method.getName() + "$default$" + parameterIndex);
          return defaultMethod.invoke(o);
        } catch (NoSuchMethodException e) {
          //
        } catch (Exception e) {
          throw new UnexpectedException(e);
        }
      }
      if (clazz.equals(boolean.class)) {
        return false;
      }
      if (clazz.equals(int.class)) {
        return 0;
      }
      if (clazz.equals(long.class)) {
        return 0;
      }
      if (clazz.equals(double.class)) {
        return 0;
      }
      if (clazz.equals(short.class)) {
        return 0;
      }
      if (clazz.equals(byte.class)) {
        return 0;
      }
      if (clazz.equals(char.class)) {
        return ' ';
      }
      return null;
    }
    return result;
  }