Ejemplo n.º 1
1
  public static void viewAd(String id) {

    Ad ad = Ad.findById(Long.parseLong(id));
    List<Category> cats = Category.find("categorytype_id=?1 order by id", "1").fetch();

    EntityManager entityManager = play.db.jpa.JPA.em();
    List<BigInteger> bCounts =
        entityManager
            .createNativeQuery(
                "select count(*) as maxCount from Ad as a group by category_id order by maxCount")
            .getResultList();
    int min = bCounts.get(0).intValue();
    int max = bCounts.get(bCounts.size() - 1).intValue();
    bCounts =
        entityManager
            .createNativeQuery(
                "select count(*) as maxCount from Ad as a group by category_id order by category_id ")
            .getResultList();
    List<String> fonts = new ArrayList<String>();
    for (int i = 0; i < bCounts.size(); i++) {
      BigInteger count = bCounts.get(i);
      int x = Ads.getFontSize(count.intValue(), min, max);
      fonts.add(String.valueOf(x));
    }

    render(ad, fonts, min, max, cats);
  }
Ejemplo n.º 2
0
  @Check("isAdmin")
  public static void edit(String idSession) {
    Session sessions = Session.getSessionById(Long.parseLong(idSession));
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
    String dateDebut = sdf.format(sessions.dateDepart);
    String dateFin = sdf.format(sessions.dateFin);

    List<ProduitType> listProduitTypes = Arrays.asList(ProduitType.values());

    Circuit tempCircuit = sessions.circuit;

    sessions.circuit = null;
    sessions.save();

    sessions = Session.getSessionById(Long.parseLong(idSession));
    sessions.circuit = tempCircuit;

    boolean isAvailableCircuit =
        Circuit.isAvailableCircuitByAgence(sessions.dateDepart, sessions.dateFin, sessions.agence);

    Agence agence = sessions.agence;
    render(
        "Sessions/add.html",
        sessions,
        dateDebut,
        dateFin,
        isAvailableCircuit,
        listProduitTypes,
        agence);
  }
Ejemplo n.º 3
0
  @Check("isAdmin")
  public static void save() {
    Session session;
    String idSession = params.get("session.id");
    System.out.println(idSession);
    if (idSession != null && !idSession.equals("")) {
      session = Session.getSessionById(Long.parseLong(params.get("session.id")));
    } else {
      session = new Session();
    }

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");

    try {
      session.dateDepart = sdf.parse(params.get("session.dateDebut"));
      session.dateFin = sdf.parse(params.get("session.dateFin"));
    } catch (ParseException ex) {
      Logger.getLogger(Disponibilites.class.getName()).log(Level.SEVERE, null, ex);
    }

    session.commentaires = params.get("session.commentaires");
    String nbPlace = params.get("session.nbMaxPlaces");
    if (nbPlace != null && !nbPlace.equals("")) {
      session.nbMaxPlaces = Integer.parseInt(nbPlace);
    }

    Agence agence = Agence.getAgenceById(Long.parseLong(params.get("session.agence").toString()));
    session.agence = agence;
    String resultCircuit = params.get("session.circuit");
    if (resultCircuit.equals("indisponible") || resultCircuit.equals("false")) {
      session.circuit = null;
    } else {
      session.circuit = Circuit.getCircuitByAgence(agence);
    }
    session.typeProduit = ProduitType.valueOf(params.get("session.type"));
    session.employe = Employe.getEmployeById(Long.parseLong(params.get("session.employe")));
    session.vehicule = Vehicule.getVehiculeById(Long.parseLong(params.get("session.vehicule")));

    validation.valid(session);

    if (Validation.hasErrors()) {
      params.flash();
      Validation.keep();
      if (idSession != null && !idSession.equals("")) {
        Sessions.edit(idSession);
      } else {
        Sessions.add(
            formatDateToCalendar(params.get("session.dateDebut").toString()),
            formatDateToCalendar(params.get("session.dateFin").toString()),
            params.get("session.agence").toString());
      }
    } else {
      session.save();
      Sessions.show();
    }
  }
Ejemplo n.º 4
0
  @Check("isAdmin")
  public static void add(String startDate, String endDate, String idAgence) {
    String dateDebut = formatDateToDisplay(startDate);
    String dateFin = formatDateToDisplay(endDate);
    Agence agence = Agence.getAgenceById(Long.parseLong(idAgence));
    SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyyHHmm");
    try {
      Date sDate = dateFormat.parse(startDate);
      Date eDate = dateFormat.parse(endDate);
      List<Employe> listEmployes = Employe.getAvailableEmployes(sDate, eDate);
      List<Vehicule> listVehicules = Vehicule.getAvailableVehiculesByAgence(sDate, eDate, agence);
      boolean isAvailableCircuit = Circuit.isAvailableCircuitByAgence(sDate, eDate, agence);
      List<ProduitType> listProduitTypes = Arrays.asList(ProduitType.values());

      render(
          dateDebut,
          dateFin,
          listEmployes,
          listVehicules,
          isAvailableCircuit,
          agence,
          listProduitTypes);
    } catch (ParseException ex) {
      Logger.getLogger(Sessions.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Ejemplo n.º 5
0
  public static void projects() {
    Long id = Long.parseLong(Session.current().get("user_id"));

    User u = User.findById(id);

    List<Project> projects = Project.find("owner = ?", u).fetch();

    render(projects);
  }
Ejemplo n.º 6
0
 @Check("isAdmin")
 public static void remove() {
   Session session;
   String idSession = params.get("session.id");
   session = Session.getSessionById(Long.parseLong(idSession));
   if (session != null) {
     session.delete();
   }
   Sessions.show();
 }
Ejemplo n.º 7
0
  /**
   * Obtains the currently uploaded file from the session variable.
   *
   * @return uploaded file
   * @throws FileNotFoundException
   */
  private static File getCurrentUpload() throws FileNotFoundException {
    String uploadFileId = session().get("uploadFileId");
    UserUpload uploadFile = UserUpload.find.byId(Long.parseLong(uploadFileId));
    File file = new File(uploadFile.absolutePath);

    if (!file.exists()) {
      throw new FileNotFoundException("Could not load input from file.");
    }

    return file;
  }
Ejemplo n.º 8
0
 @Check("isAdmin")
 public static void move() {
   try {
     Session session = Session.getSessionById(Long.parseLong(params.get("id")));
     SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmm");
     session.dateDepart = sdf.parse(params.get("start"));
     session.dateFin = sdf.parse(params.get("end"));
     session.save();
   } catch (ParseException ex) {
     Logger.getLogger(Disponibilites.class.getName()).log(Level.SEVERE, null, ex);
   }
 }
Ejemplo n.º 9
0
  public static void project(Long id) {
    Project project = Project.findById(id);

    Long UID = Long.parseLong(Session.current().get("user_id"));
    User u = User.findById(UID);

    if (project.canBeSeenBy(u)) {
      render(project);
    } else {
      projects();
    }
  }
Ejemplo n.º 10
0
 /**
  * 세션에 저장된 정보를 이용해서 사용자 객체를 생성한다 세션에 저장된 정보가 없다면 anonymous 객체가 리턴된다
  *
  * @return 세션 정보 기준 조회된 사용자 객체
  */
 public static User currentUser() {
   String userId = session().get(SESSION_USERID);
   if (StringUtils.isEmpty(userId) || !StringUtils.isNumeric(userId)) {
     return User.anonymous;
   }
   User foundUser = User.find.byId(Long.valueOf(userId));
   if (foundUser == null) {
     processLogout();
     return User.anonymous;
   }
   return foundUser;
 }
Ejemplo n.º 11
0
  public static void createproject(String projectname, String projectdescription) {
    if (projectname != null && projectdescription != null) {
      Long id = Long.parseLong(Session.current().get("user_id"));
      User u = User.findById(id);

      Project p = new Project(projectname, projectdescription, u);
      p.save();

      projects();
    } else {
      render();
    }
  }
Ejemplo n.º 12
0
 /**
  * 세션 정보를 이용해서 사용자 객체를 가져온다. 세션 정보가 없거나 잘못된 정보라면 anonymous 객체를 반환한다. 잘못된 정보의 경우 세션 정보를 삭제한다.
  *
  * @return
  */
 private static User getUserFromSession() {
   String userId = session().get(SESSION_USERID);
   if (userId == null) {
     return User.anonymous;
   }
   if (!StringUtils.isNumeric(userId)) {
     return invalidSession();
   }
   User user = User.find.byId(Long.valueOf(userId));
   if (user == null) {
     return invalidSession();
   }
   return user;
 }
 public static Admin getCurrentAdmin() {
   /**
    * get currently logged in admin for Candidate (CandidateController.java) + Office
    * (OfficeController.java) constructors via new logged_in_adminid written to session on admin
    * login
    */
   String adminId = session.get("logged_in_adminid");
   if (adminId == null) {
     return null;
   }
   Admin logged_in_admin = Admin.findById(Long.parseLong(adminId));
   Logger.info("In Admin controller: Logged in admin is " + logged_in_admin.username);
   return logged_in_admin;
 }
Ejemplo n.º 14
0
  /**
   * 사용자 정보 수정
   *
   * @return
   */
  @With(AnonymousCheckAction.class)
  @Transactional
  public static Result editUserInfo() {
    Form<User> userForm = new Form<>(User.class).bindFromRequest("name", "email");
    String newEmail = userForm.data().get("email");
    String newName = userForm.data().get("name");
    User user = UserApp.currentUser();

    if (StringUtils.isEmpty(newEmail)) {
      userForm.reject("email", "user.wrongEmail.alert");
    } else {
      if (!StringUtils.equals(user.email, newEmail) && User.isEmailExist(newEmail)) {
        userForm.reject("email", "user.email.duplicate");
      }
    }

    if (userForm.error("email") != null) {
      flash(Constants.WARNING, userForm.error("email").message());
      return badRequest(edit.render(userForm, user));
    }
    user.email = newEmail;
    user.name = newName;

    try {
      Long avatarId = Long.valueOf(userForm.data().get("avatarId"));
      if (avatarId != null) {
        Attachment attachment = Attachment.find.byId(avatarId);
        String primary = attachment.mimeType.split("/")[0].toLowerCase();

        if (attachment.size > AVATAR_FILE_LIMIT_SIZE) {
          userForm.reject("avatarId", "user.avatar.fileSizeAlert");
        }

        if (primary.equals("image")) {
          Attachment.deleteAll(currentUser().avatarAsResource());
          attachment.moveTo(currentUser().avatarAsResource());
        }
      }
    } catch (NumberFormatException ignored) {
    }

    Email.deleteOtherInvalidEmails(user.email);
    user.update();
    return redirect(
        routes.UserApp.userInfo(user.loginId, DEFAULT_GROUP, DAYS_AGO, DEFAULT_SELECTED_TAB));
  }
Ejemplo n.º 15
0
  @Security.Authenticated(Secured.class)
  public static Result viewMyConversation(Long id) {
    Student s = Student.find.byId(request().username());
    Conversation c = Conversation.find.byId(id.toString());

    if (!c.getParticipants().contains(s)) { // unauthorized access!
      return redirect(routes.Application.viewMyConversations());
    } else {
      // mark all read
      for (Message m : c.messages) {
        if (!m.sender.email.equals(s.email)) {
          m.setRead();
          m.save();
        }
      }

      return ok(viewConversation.render(s, c, form(MessageForm.class)));
    }
  }
Ejemplo n.º 16
0
  @Security.Authenticated(Secured.class)
  public static Result addNewMessageForm(Long id) {
    Form<MessageForm> mesForm = Form.form(MessageForm.class).bindFromRequest();
    if (mesForm.hasErrors()) {
      return badRequest(postNewMessage.render(mesForm, id));
    } else {

      Message m =
          new Message(
              mesForm.field("text").value().toString(), Student.find.byId(request().username()));

      Conversation c = null;

      c = Conversation.find.byId(id.toString());
      c.messages.add(m);
      c.save();

      return redirect(routes.Application.viewMyConversation(id));
    }
  }
Ejemplo n.º 17
0
  public Result onLabel() {
    long millis = System.currentTimeMillis() % 1000;
    long result = millis - currentTimestamp;
    currentTimestamp = System.currentTimeMillis() % 1000;

    String label = request().getQueryString("action");
    String id = request().getQueryString("id");
    String reason =
        request()
            .getQueryString(
                "reason"); // remove the cluster header from Tweets and add it to labelled at the
                           // end.
    String databaseName = request().getQueryString("databaseName");
    String timestamp = Long.toString(result);

    DataAccess.labelTweet(databaseName, id, label, timestamp);

    TweetDTO tweetDTO = DataAccess.getNextTweet(databaseName);
    return ok(labelling.render(tweetDTO, databaseName));
  }
Ejemplo n.º 18
0
 public static void cambiarContrasenia() {
   String clave = params.get("clave");
   Long coUsuario = Long.parseLong(params.get("coUsuario"));
   Map result = new HashMap();
   String deUsuario = session.get("usuario");
   VmdbUsuario usuario = VmdbUsuario.find("coUsuario = ? and stUsuario = '1'", coUsuario).first();
   usuario.setDeClave(clave);
   usuario.setDaFechaModificacion(new Date());
   usuario.setCoUsuarioModificacion(deUsuario);
   usuario.save();
   /** Actualizar clave en Persona * */
   VmdbPersona objPersona = VmdbPersona.findById(usuario.getVmdbPersona().getCoPersona());
   objPersona.setDeClave(clave);
   objPersona.setCoUsuarioModificacion(deUsuario);
   objPersona.setDaFechaModificacion(new Date());
   objPersona.save();
   /** -----------------------------* */
   result.put("status", 1);
   result.put("message", "Su clave fue actualizado correctamente");
   JSONSerializer mapeo = new JSONSerializer();
   renderJSON(mapeo.serialize(result));
 }
Ejemplo n.º 19
0
 public static void viewCambiarContrasenia() {
   Long coPersona = Long.parseLong(session.get("idPersona"));
   VmdbUsuario usuario =
       VmdbUsuario.find("vmdbPersona.coPersona = ? and stUsuario = '1'", coPersona).first();
   render("Usuarios/editPassword.html", usuario);
 }
Ejemplo n.º 20
0
  @Check("isAdmin")
  public static void findEvents(String idAgence) {
    Agence agence = Agence.getAgenceById(Long.parseLong(idAgence));
    List<Session> listSessions = Session.getSessionsByAgence(agence);

    List<FullCalendarEvent> listEvents = new ArrayList<FullCalendarEvent>();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    FullCalendarEvent event;
    for (Session session : listSessions) {
      event = new FullCalendarEvent();
      event.start = dateFormat.format(session.dateDepart);
      event.end = dateFormat.format(session.dateFin);
      event.id = session.id.toString();
      event.title = session.commentaires + " (" + session.id + ")";
      event.allDay = "";

      switch (session.typeProduit) {
        case CirculationMoto:
          event.color = "blue";
          break;
        case CirculationScooter125:
          event.color = "red";
          break;
        case CirculationScooter50:
          event.color = "yellow";
          event.textColor = "black";
          break;
        case CirculationVoiture:
          event.color = "green";
          break;
        case EvaluationAuto:
          event.color = "DarkOrchid";
          break;
        case PlateauMoto:
          event.color = "Orange";
          break;
        case PlateauScooter125:
          event.color = "Pink";
          event.textColor = "black";
          break;
        case PlateauScooter50:
          event.color = "Magenta";
          break;
        case PlateauScooterMP3:
          event.color = "Silver";
          break;
        case PlateauVoiture:
          event.color = "Turquoise";
          break;
        case Stage1:
          event.color = "Lime";
          break;
        case Stage2:
          event.color = "DeepSkyBlue";
          break;
        case Stage3:
          event.color = "Beige";
          break;
        case Code:
          event.color = "Maroon";
          break;
        default:
          event.color = "white";
      }

      listEvents.add(event);
    }

    Gson gson = new Gson();
    System.out.println(gson.toJson(listEvents));
    renderJSON(gson.toJson(listEvents));
  }
Ejemplo n.º 21
0
 // TODO pull this out into something reusable
 static User current() {
   User current = null;
   String idString = session.get("user");
   if (idString != null) current = User.findById(Long.parseLong(idString));
   return current;
 }
Ejemplo n.º 22
0
 public static User connectedUser() {
   String userId = session.get("logged");
   return userId == null ? null : (User) User.findById(Long.parseLong(userId));
 }
Ejemplo n.º 23
0
/** Helper functions to run tests. */
public class Helpers implements play.mvc.Http.Status, play.mvc.Http.HeaderNames {

  public static String GET = "GET";
  public static String POST = "POST";
  public static String PUT = "PUT";
  public static String DELETE = "DELETE";
  public static String HEAD = "HEAD";

  // --

  public static Class<? extends WebDriver> HTMLUNIT = HtmlUnitDriver.class;
  public static Class<? extends WebDriver> FIREFOX = FirefoxDriver.class;

  // --
  @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.");
    }
  }

  /**
   * Default Timeout (milliseconds) for fake requests issued by these Helpers. This value is
   * determined from System property <b>test.timeout</b>. The default value is <b>30000</b> (30
   * seconds).
   */
  public static final long DEFAULT_TIMEOUT = Long.getLong("test.timeout", 30000L);

  private static Result wrapScalaResult(
      scala.concurrent.Future<play.api.mvc.Result> result, long timeout) {
    if (result == null) {
      return null;
    } else {
      final play.api.mvc.Result scalaResult = Promise.wrap(result).get(timeout);
      return scalaResult.asJava();
    }
  }

  // --

  /** Calls a Callable which invokes a Controller or some other method with a Context */
  public static <V> V invokeWithContext(RequestBuilder requestBuilder, Callable<V> callable) {
    try {
      Context.current.set(new Context(requestBuilder));
      return callable.call();
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      Context.current.remove();
    }
  }

  /** Build a new GET / fake request. */
  public static RequestBuilder fakeRequest() {
    return fakeRequest("GET", "/");
  }

  /** Build a new fake request. */
  public static RequestBuilder fakeRequest(String method, String uri) {
    return new RequestBuilder().method(method).uri(uri);
  }

  /** Build a new fake request corresponding to a given route call */
  public static RequestBuilder fakeRequest(Call call) {
    return fakeRequest(call.method(), call.url());
  }

  /** Build a new fake application. */
  public static FakeApplication fakeApplication() {
    return new FakeApplication(
        new java.io.File("."), Helpers.class.getClassLoader(), new HashMap<String, Object>(), null);
  }

  /**
   * Build a new fake application.
   *
   * @deprecated Use dependency injection (since 2.5.0)
   */
  @Deprecated
  public static FakeApplication fakeApplication(GlobalSettings global) {
    return new FakeApplication(
        new java.io.File("."),
        Helpers.class.getClassLoader(),
        new HashMap<String, Object>(),
        global);
  }

  /**
   * A fake Global.
   *
   * @deprecated Use dependency injection (since 2.5.0)
   */
  @Deprecated
  public static GlobalSettings fakeGlobal() {
    return new GlobalSettings();
  }

  /** Constructs a in-memory (h2) database configuration to add to a FakeApplication. */
  public static Map<String, String> inMemoryDatabase() {
    return inMemoryDatabase("default");
  }

  /** Constructs a in-memory (h2) database configuration to add to a FakeApplication. */
  public static Map<String, String> inMemoryDatabase(String name) {
    return inMemoryDatabase(name, Collections.<String, String>emptyMap());
  }

  /** Constructs a in-memory (h2) database configuration to add to a FakeApplication. */
  public static Map<String, String> inMemoryDatabase(String name, Map<String, String> options) {
    return Scala.asJava(play.api.test.Helpers.inMemoryDatabase(name, Scala.asScala(options)));
  }

  /** Build a new fake application. */
  public static FakeApplication fakeApplication(
      Map<String, ? extends Object> additionalConfiguration) {
    return new FakeApplication(
        new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration);
  }

  /**
   * Build a new fake application.
   *
   * @deprecated Use the version without GlobalSettings (since 2.5.0)
   */
  @Deprecated
  public static FakeApplication fakeApplication(
      Map<String, ? extends Object> additionalConfiguration, GlobalSettings global) {
    return new FakeApplication(
        new java.io.File("."), Helpers.class.getClassLoader(), additionalConfiguration, global);
  }

  /**
   * Extracts the content as a {@link akka.util.ByteString}.
   *
   * <p>This method is only capable of extracting the content of results with strict entities. To
   * extract the content of results with streamed entities, use {@link #contentAsBytes(Result,
   * Materializer)}.
   *
   * @param result The result to extract the content from.
   * @return The content of the result as a ByteString.
   * @throws UnsupportedOperationException if the result does not have a strict entity.
   */
  public static ByteString contentAsBytes(Result result) {
    if (result.body() instanceof HttpEntity.Strict) {
      return ((HttpEntity.Strict) result.body()).data();
    } else {
      throw new UnsupportedOperationException(
          "Tried to extract body from a non strict HTTP entity without a materializer, use the version of this method that accepts a materializer instead");
    }
  }

  /**
   * Extracts the content as a {@link akka.util.ByteString}.
   *
   * @param result The result to extract the content from.
   * @param mat The materialiser to use to extract the body from the result stream.
   * @return The content of the result as a ByteString.
   */
  public static ByteString contentAsBytes(Result result, Materializer mat) {
    return contentAsBytes(result, mat, DEFAULT_TIMEOUT);
  }

  /**
   * Extracts the content as a {@link akka.util.ByteString}.
   *
   * @param result The result to extract the content from.
   * @param mat The materialiser to use to extract the body from the result stream.
   * @param timeout The amount of time, in milliseconds, to wait for the body to be produced.
   * @return The content of the result as a ByteString.
   */
  public static ByteString contentAsBytes(Result result, Materializer mat, long timeout) {
    try {
      return result
          .body()
          .consumeData(mat)
          .thenApply(Function.identity())
          .toCompletableFuture()
          .get(timeout, TimeUnit.MILLISECONDS);
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /** Extracts the content as bytes. */
  public static ByteString contentAsBytes(Content content) {
    return ByteString.fromString(content.body());
  }

  /** Extracts the content as a String. */
  public static String contentAsString(Content content) {
    return content.body();
  }

  /**
   * Extracts the content as a String.
   *
   * <p>This method is only capable of extracting the content of results with strict entities. To
   * extract the content of results with streamed entities, use {@link #contentAsString(Result,
   * Materializer)}.
   *
   * @param result The result to extract the content from.
   * @return The content of the result as a String.
   * @throws UnsupportedOperationException if the result does not have a strict entity.
   */
  public static String contentAsString(Result result) {
    return contentAsBytes(result).decodeString(result.charset().orElse("utf-8"));
  }

  /**
   * Extracts the content as a String.
   *
   * @param result The result to extract the content from.
   * @param mat The materialiser to use to extract the body from the result stream.
   * @return The content of the result as a String.
   */
  public static String contentAsString(Result result, Materializer mat) {
    return contentAsBytes(result, mat, DEFAULT_TIMEOUT)
        .decodeString(result.charset().orElse("utf-8"));
  }

  /**
   * Extracts the content as a String.
   *
   * @param result The result to extract the content from.
   * @param mat The materialiser to use to extract the body from the result stream.
   * @param timeout The amount of time, in milliseconds, to wait for the body to be produced.
   * @return The content of the result as a String.
   */
  public static String contentAsString(Result result, Materializer mat, long timeout) {
    return contentAsBytes(result, mat, timeout).decodeString(result.charset().orElse("utf-8"));
  }

  @SuppressWarnings(value = "unchecked")
  public static Result routeAndCall(RequestBuilder requestBuilder, long timeout) {
    try {
      return routeAndCall(
          (Class<? extends Router>) RequestBuilder.class.getClassLoader().loadClass("Routes"),
          requestBuilder,
          timeout);
    } catch (RuntimeException e) {
      throw e;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }

  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);
    }
  }

  public static Result routeAndCall(Router router, RequestBuilder requestBuilder) {
    return routeAndCall(router, requestBuilder, DEFAULT_TIMEOUT);
  }

  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);
    }
  }

  public static Result route(Call call) {
    return route(fakeRequest(call));
  }

  public static Result route(Call call, long timeout) {
    return route(fakeRequest(call), timeout);
  }

  public static Result route(Application app, Call call) {
    return route(app, fakeRequest(call));
  }

  public static Result route(Application app, Call call, long timeout) {
    return route(app, fakeRequest(call), timeout);
  }

  public static Result route(RequestBuilder requestBuilder) {
    return route(requestBuilder, DEFAULT_TIMEOUT);
  }

  public static Result route(RequestBuilder requestBuilder, long timeout) {
    return route(play.Play.application(), requestBuilder, timeout);
  }

  public static Result route(Application app, RequestBuilder requestBuilder) {
    return route(app, requestBuilder, DEFAULT_TIMEOUT);
  }

  @SuppressWarnings("unchecked")
  public static Result route(Application app, RequestBuilder requestBuilder, long timeout) {
    final scala.Option<scala.concurrent.Future<play.api.mvc.Result>> opt =
        play.api.test.Helpers.jRoute(
            app.getWrappedApplication(),
            requestBuilder.build()._underlyingRequest(),
            requestBuilder.body());
    return wrapScalaResult(Scala.orNull(opt), timeout);
  }

  /** Starts a new application. */
  public static void start(Application application) {
    play.api.Play.start(application.getWrappedApplication());
  }

  /** Stops an application. */
  public static void stop(Application application) {
    play.api.Play.stop(application.getWrappedApplication());
  }

  /** Executes a block of code in a running application. */
  public static void running(Application application, final Runnable block) {
    synchronized (PlayRunners$.MODULE$.mutex()) {
      try {
        start(application);
        block.run();
      } finally {
        stop(application);
      }
    }
  }

  /**
   * Creates a new Test server listening on port defined by configuration setting "testserver.port"
   * (defaults to 19001).
   */
  public static TestServer testServer() {
    return testServer(play.api.test.Helpers.testServerPort());
  }

  /**
   * Creates a new Test server listening on port defined by configuration setting "testserver.port"
   * (defaults to 19001) and using the given FakeApplication.
   */
  public static TestServer testServer(Application app) {
    return testServer(play.api.test.Helpers.testServerPort(), app);
  }

  /** Creates a new Test server. */
  public static TestServer testServer(int port) {
    return new TestServer(port, fakeApplication());
  }

  /** Creates a new Test server. */
  public static TestServer testServer(int port, Application app) {
    return new TestServer(port, app);
  }

  /** Starts a Test server. */
  public static void start(TestServer server) {
    server.start();
  }

  /** Stops a Test server. */
  public static void stop(TestServer server) {
    server.stop();
  }

  /** Executes a block of code in a running server. */
  public static void running(TestServer server, final Runnable block) {
    synchronized (PlayRunners$.MODULE$.mutex()) {
      try {
        start(server);
        block.run();
      } finally {
        stop(server);
      }
    }
  }

  /** Executes a block of code in a running server, with a test browser. */
  public static void running(
      TestServer server, Class<? extends WebDriver> webDriver, final Consumer<TestBrowser> block) {
    running(server, play.api.test.WebDriverFactory.apply(webDriver), block);
  }

  /** Executes a block of code in a running server, with a test browser. */
  public static void running(
      TestServer server, WebDriver webDriver, final Consumer<TestBrowser> block) {
    synchronized (PlayRunners$.MODULE$.mutex()) {
      TestBrowser browser = null;
      TestServer startedServer = null;
      try {
        start(server);
        startedServer = server;
        browser = testBrowser(webDriver, server.port());
        block.accept(browser);
      } finally {
        if (browser != null) {
          browser.quit();
        }
        if (startedServer != null) {
          stop(startedServer);
        }
      }
    }
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser() {
    return testBrowser(HTMLUNIT);
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser(int port) {
    return testBrowser(HTMLUNIT, port);
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver) {
    return testBrowser(webDriver, Helpers$.MODULE$.testServerPort());
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver, int port) {
    try {
      return new TestBrowser(webDriver, "http://localhost:" + port);
    } catch (RuntimeException e) {
      throw e;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser(WebDriver of, int port) {
    return new TestBrowser(of, "http://localhost:" + port);
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser(WebDriver of) {
    return testBrowser(of, Helpers$.MODULE$.testServerPort());
  }
}
Ejemplo n.º 24
0
  public static void list(
      String search, int category, Integer size, Integer page, int firstPage, int lastPage) {
    List<Ad> ads = null;

    List<Category> cats = Category.find("categorytype_id=?1", "1").fetch();

    EntityManager entityManager = play.db.jpa.JPA.em();
    List<BigInteger> bCounts =
        entityManager
            .createNativeQuery(
                "select count(*) as maxCount from Ad as a group by category_id order by maxCount")
            .getResultList();
    int min = bCounts.get(0).intValue();
    int max = bCounts.get(bCounts.size() - 1).intValue();
    bCounts =
        entityManager
            .createNativeQuery(
                "select count(*) as maxCount from Ad as a group by category_id order by category_id ")
            .getResultList();
    List<String> fonts = new ArrayList<String>();
    for (int i = 0; i < bCounts.size(); i++) {
      BigInteger count = bCounts.get(i);
      int x = Ads.getFontSize(count.intValue(), min, max);
      fonts.add(String.valueOf(x));
    }

    int pagesCount = 0;

    page = page != null ? page : 1;
    if (search.trim().length() == 0) {
      Long l = null;
      if (category == 0) {

        ads = Ad.find("order by createDate desc").fetch(page, size);
        l = Ad.count();
      } else {

        ads = Ad.find(" category_id=?1 order by createDate desc", category).fetch(page, size);
        l = Ad.count(" category_id=?1 ", category);
      }

      Long l2 = (l / 10);
      if ((l % 10) > 0) l2 = (long) (Math.floor(l2) + 1);
      pagesCount = Integer.valueOf(l2.intValue());

    } else {
      search = search.toLowerCase();
      Long l = null;
      if (category == 0) {
        ads =
            Ad.find(
                    "(lower(headline) like ?1 OR lower(description) like ?2)",
                    "%" + search + "%",
                    "%" + search + "%")
                .fetch(page, size);
        l =
            Ad.count(
                "(lower(headline) like ?1 OR lower(description) like ?2)",
                "%" + search + "%",
                "%" + search + "%");
      } else {
        ads =
            Ad.find(
                    " category_id=?1 and (lower(headline) like ?2 OR lower(description) like ?3)",
                    category,
                    "%" + search + "%",
                    "%" + search + "%")
                .fetch(page, size);
        l =
            Ad.count(
                "category_id=?1 and (lower(headline) like ?2 OR lower(description) like ?3)",
                category,
                "%" + search + "%",
                "%" + search + "%");
      }

      Long l2 = (l / 10);
      if ((l % 10) > 0) l2 = (long) (Math.floor(l2) + 1);
      pagesCount = Integer.valueOf(l2.intValue());
    }

    if ((lastPage - page) <= 2) {
      firstPage = page - 2;
      lastPage = page + 7;
      if (lastPage > pagesCount) lastPage = pagesCount;

    } else if ((page - firstPage) <= 2) {
      firstPage = page - 7;
      lastPage = page + 2;
      if (firstPage < 1) {
        firstPage = 1;
        lastPage = 10;
      }
    }

    if (lastPage > pagesCount) lastPage = pagesCount;

    render(ads, search, size, page, pagesCount, firstPage, lastPage, cats, fonts);
  }
  // ----------------------------------------------------------------
  // ---- Image Database---------------------------------------------
  public static void addImagesToDB(Instagram instagram) {
    Logger.info("  --Add images to db-------------");

    TagMediaFeed mediaFeed = getMediaFeed(instagram);

    List<MediaFeedData> images = mediaFeed.getData();
    List<MediaFeedData> imagesAll = new ArrayList<MediaFeedData>();

    // add first media feeds to imagesAll
    for (int i = 0; i < images.size(); i++) {
      if (imagesAll.size() < maxNumberOfImagesInst) {
        imagesAll.add(0, images.get(i));
      }
    }

    // add additional media feed to imagesAll[maxNumberOfImagesInst]
    String nextMaxId = getPagination(mediaFeed);
    while ((imagesAll.size() < maxNumberOfImagesInst) && (nextMaxId != null)) {
      // get new set of images
      TagMediaFeed nextMediaFeed = getNextMediaFeed(instagram, nextMaxId);
      List<MediaFeedData> imagesNext = nextMediaFeed.getData();

      // add  imagesNext to imagesAll
      for (int i = 0; i < imagesNext.size(); i++) {
        if (imagesAll.size() < maxNumberOfImagesInst) {
          imagesAll.add(0, imagesNext.get(i));
        }
      }

      nextMaxId = getPagination(nextMediaFeed);

      // Logger.info("imagesNext: "+imagesNext.size());
      Logger.info("imagesAll: " + imagesAll.size());
    } // while

    // print all images and add them to the db
    Logger.info("imagesAll: " + imagesAll.size());
    if (imagesAll != null) {
      int counter = 1;
      for (MediaFeedData image : imagesAll) {
        if (image != null) {
          Date d = new Date(Long.parseLong(image.getCreatedTime()) * 1000);
          Caption caption = image.getCaption();
          Logger.info(
              "   " + (counter++) + "." + " id:" + image.getId() + " time: " + d.toString() + " ");

          if (caption != null) {
            Logger.info("       from, full name: " + caption.getFrom().getFullName());
            // add image to db
            MImages.addNew(
                new MImages(
                    image.getId(),
                    image.getImages().getLowResolution().getImageUrl(),
                    "instagram",
                    caption.getFrom().getFullName(),
                    caption.getFrom().getProfilePicture(),
                    image.getCreatedTime(),
                    (long) image.getLikes().getCount(),
                    (long) 0));
          } // if
        } // if
      } // for
    } // if
  } // addImagesToDB
Ejemplo n.º 26
0
  @Check("isClient")
  public static void validPosition() {
    Session session = Session.getSessionById(Long.parseLong(params.get("session_id")));
    String result = params.get("positionSession");
    Client client = Client.getClientByUsername(Security.connected());

    Calendar calendar1 = new GregorianCalendar();
    calendar1.setTime(session.dateDepart);

    Calendar calendar2 = new GregorianCalendar();
    calendar2.setTime(session.dateFin);

    int nbrH = (int) calendar2.get(Calendar.HOUR) - calendar1.get(Calendar.HOUR);

    boolean alreadyPosition = false;
    for (Session s : client.sessions) {
      if (s.id == session.id) {
        alreadyPosition = true;
      }
    }

    if (result.equals("true")) {
      if (!alreadyPosition) {
        client.sessions.add(session);
        switch (session.typeProduit) {
          case CirculationMoto:
            client.heureCirculationMoto -= nbrH;
            break;
          case CirculationScooter125:
            client.heureCirculationScooter -= nbrH;
            break;
          case CirculationScooter50:
            client.heureCirculationScooter -= nbrH;
            break;
          case CirculationVoiture:
            client.heureCirculationVoiture -= nbrH;
            break;
          case EvaluationAuto:
            client.heureEvaluationAuto -= nbrH;
            break;
          case PlateauMoto:
            client.heurePlateauMoto -= nbrH;
            break;
          case PlateauScooter125:
            client.heurePlateauScooter -= nbrH;
            break;
          case PlateauScooter50:
            client.heurePlateauScooter -= nbrH;
            break;
          case PlateauScooterMP3:
            client.heurePlateauScooter -= nbrH;
            break;
          case PlateauVoiture:
            client.heurePlateauVoiture -= nbrH;
            break;
          case Stage1:
            client.heureStage1 -= nbrH;
            break;
          case Stage2:
            client.heureStage2 -= nbrH;
            break;
          case Stage3:
            client.heureStage3 -= nbrH;
            break;
          case Code:
            client.heureCode -= nbrH;
            break;
        }
      }
    } else {
      if (alreadyPosition) {
        client.sessions.remove(session);
        switch (session.typeProduit) {
          case CirculationMoto:
            client.heureCirculationMoto += nbrH;
            break;
          case CirculationScooter125:
            client.heureCirculationScooter += nbrH;
            break;
          case CirculationScooter50:
            client.heureCirculationScooter += nbrH;
            break;
          case CirculationVoiture:
            client.heureCirculationVoiture += nbrH;
            break;
          case EvaluationAuto:
            client.heureEvaluationAuto += nbrH;
            break;
          case PlateauMoto:
            client.heurePlateauMoto += nbrH;
            break;
          case PlateauScooter125:
            client.heurePlateauScooter += nbrH;
            break;
          case PlateauScooter50:
            client.heurePlateauScooter += nbrH;
            break;
          case PlateauScooterMP3:
            client.heurePlateauScooter += nbrH;
            break;
          case PlateauVoiture:
            client.heurePlateauVoiture += nbrH;
            break;
          case Stage1:
            client.heureStage1 += nbrH;
            break;
          case Stage2:
            client.heureStage2 += nbrH;
            break;
          case Stage3:
            client.heureStage3 += nbrH;
            break;
          case Code:
            client.heureCode += nbrH;
            break;
        }
      }
    }

    client.save();
    Sessions.showSessions();
  }
Ejemplo n.º 27
0
  @Check("isClient")
  public static void positionSession(String idSession) {
    long nbrH = 0;
    Session sessions = Session.getSessionById(Long.parseLong(idSession));

    Calendar calendar1 = new GregorianCalendar();
    calendar1.setTime(sessions.dateDepart);

    Calendar calendar2 = new GregorianCalendar();
    calendar2.setTime(sessions.dateFin);

    nbrH = calendar2.get(Calendar.HOUR) - calendar1.get(Calendar.HOUR);

    Client client = Client.getClientByUsername(Security.connected());

    boolean alreadyPosition = false;

    for (Session s : client.sessions) {
      if (s.id == sessions.id) {
        alreadyPosition = true;
      }
    }

    boolean canPositionSession = false;
    switch (sessions.typeProduit) {
      case CirculationMoto:
        if (client.heureCirculationMoto >= nbrH) {
          canPositionSession = true;
        }
        break;
      case CirculationScooter125:
        if (client.heureCirculationScooter >= nbrH) {
          canPositionSession = true;
        }
        break;
      case CirculationScooter50:
        if (client.heureCirculationScooter >= nbrH) {
          canPositionSession = true;
        }
        break;
      case CirculationVoiture:
        if (client.heureCirculationVoiture >= nbrH) {
          canPositionSession = true;
        }
        break;
      case EvaluationAuto:
        if (client.heureEvaluationAuto >= nbrH) {
          canPositionSession = true;
        }
        break;
      case PlateauMoto:
        if (client.heurePlateauMoto >= nbrH) {
          canPositionSession = true;
        }
        break;
      case PlateauScooter125:
        if (client.heurePlateauScooter >= nbrH) {
          canPositionSession = true;
        }
        break;
      case PlateauScooter50:
        if (client.heurePlateauScooter >= nbrH) {
          canPositionSession = true;
        }
        break;
      case PlateauScooterMP3:
        if (client.heurePlateauScooter >= nbrH) {
          canPositionSession = true;
        }
        break;
      case PlateauVoiture:
        if (client.heurePlateauVoiture >= nbrH) {
          canPositionSession = true;
        }
        break;
      case Stage1:
        if (client.heureStage1 >= nbrH) {
          canPositionSession = true;
        }
        break;
      case Stage2:
        if (client.heureStage2 >= nbrH) {
          canPositionSession = true;
        }
        break;
      case Stage3:
        if (client.heureStage3 >= nbrH) {
          canPositionSession = true;
        }
        break;
      case Code:
        if (client.heureCode >= nbrH) {
          canPositionSession = true;
        }
        break;
    }

    render(canPositionSession, alreadyPosition, sessions);
  }
Ejemplo n.º 28
0
/** Helper functions to run tests. */
public class Helpers implements play.mvc.Http.Status, play.mvc.Http.HeaderNames {

  public static String GET = "GET";
  public static String POST = "POST";
  public static String PUT = "PUT";
  public static String DELETE = "DELETE";
  public static String HEAD = "HEAD";

  // --

  public static Class<? extends WebDriver> HTMLUNIT = HtmlUnitDriver.class;
  public static Class<? extends WebDriver> FIREFOX = FirefoxDriver.class;

  // --
  @SuppressWarnings(value = "unchecked")
  private static Result invokeHandler(
      play.api.mvc.Handler handler, FakeRequest fakeRequest, long timeout) {
    if (handler instanceof play.core.j.JavaAction) {
      play.api.mvc.Action action = (play.api.mvc.Action) handler;
      return wrapScalaResult(action.apply(fakeRequest.getWrappedRequest()), timeout);
    } else {
      throw new RuntimeException("This is not a JavaAction and can't be invoked this way.");
    }
  }

  /**
   * Default Timeout (milliseconds) for fake requests issued by these Helpers. This value is
   * determined from System property <b>test.timeout</b>. The default value is <b>30000</b> (30
   * seconds).
   */
  public static final long DEFAULT_TIMEOUT = Long.getLong("test.timeout", 30000L);

  private static Result wrapScalaResult(
      scala.concurrent.Future<play.api.mvc.Result> result, long timeout) {
    if (result == null) {
      return null;
    } else {
      final play.api.mvc.Result scalaResult = Promise.wrap(result).get(timeout);
      return new Result() {
        public play.api.mvc.Result toScala() {
          return scalaResult;
        }
      };
    }
  }

  // --

  /** Call an action method while decorating it with the right @With interceptors. */
  public static Result callAction(HandlerRef actionReference) {
    return callAction(actionReference, DEFAULT_TIMEOUT);
  }

  public static Result callAction(HandlerRef actionReference, long timeout) {
    return callAction(actionReference, fakeRequest(), timeout);
  }

  /** Call an action method while decorating it with the right @With interceptors. */
  public static Result callAction(HandlerRef actionReference, FakeRequest fakeRequest) {
    return callAction(actionReference, fakeRequest, DEFAULT_TIMEOUT);
  }

  public static Result callAction(
      HandlerRef actionReference, FakeRequest fakeRequest, long timeout) {
    play.api.mvc.HandlerRef handlerRef = (play.api.mvc.HandlerRef) actionReference;
    return invokeHandler(handlerRef.handler(), fakeRequest, timeout);
  }

  /** Build a new GET / fake request. */
  public static FakeRequest fakeRequest() {
    return new FakeRequest();
  }

  /** Build a new fake request. */
  public static FakeRequest fakeRequest(String method, String uri) {
    return new FakeRequest(method, uri);
  }

  /** Build a new fake request corresponding to a given route call */
  public static FakeRequest fakeRequest(Call call) {
    return fakeRequest(call.method(), call.url());
  }

  /** Build a new fake application. */
  public static FakeApplication fakeApplication() {
    return new FakeApplication(
        new java.io.File("."),
        Helpers.class.getClassLoader(),
        new HashMap<String, Object>(),
        new ArrayList<String>(),
        null);
  }

  /** Build a new fake application. */
  public static FakeApplication fakeApplication(GlobalSettings global) {
    return new FakeApplication(
        new java.io.File("."),
        Helpers.class.getClassLoader(),
        new HashMap<String, Object>(),
        new ArrayList<String>(),
        global);
  }

  /** A fake Global */
  public static GlobalSettings fakeGlobal() {
    return new GlobalSettings();
  }

  /** Constructs a in-memory (h2) database configuration to add to a FakeApplication. */
  public static Map<String, String> inMemoryDatabase() {
    return inMemoryDatabase("default");
  }

  /** Constructs a in-memory (h2) database configuration to add to a FakeApplication. */
  public static Map<String, String> inMemoryDatabase(String name) {
    return inMemoryDatabase(name, Collections.<String, String>emptyMap());
  }

  /** Constructs a in-memory (h2) database configuration to add to a FakeApplication. */
  public static Map<String, String> inMemoryDatabase(String name, Map<String, String> options) {
    return Scala.asJava(play.api.test.Helpers.inMemoryDatabase(name, Scala.asScala(options)));
  }

  /** Build a new fake application. */
  public static FakeApplication fakeApplication(
      Map<String, ? extends Object> additionalConfiguration) {
    return new FakeApplication(
        new java.io.File("."),
        Helpers.class.getClassLoader(),
        additionalConfiguration,
        new ArrayList<String>(),
        null);
  }

  /** Build a new fake application. */
  public static FakeApplication fakeApplication(
      Map<String, ? extends Object> additionalConfiguration, GlobalSettings global) {
    return new FakeApplication(
        new java.io.File("."),
        Helpers.class.getClassLoader(),
        additionalConfiguration,
        new ArrayList<String>(),
        global);
  }

  /** Build a new fake application. */
  public static FakeApplication fakeApplication(
      Map<String, ? extends Object> additionalConfiguration, List<String> additionalPlugin) {
    return new FakeApplication(
        new java.io.File("."),
        Helpers.class.getClassLoader(),
        additionalConfiguration,
        additionalPlugin,
        null);
  }

  /** Build a new fake application. */
  public static FakeApplication fakeApplication(
      Map<String, ? extends Object> additionalConfiguration,
      List<String> additionalPlugin,
      GlobalSettings global) {
    return new FakeApplication(
        new java.io.File("."),
        Helpers.class.getClassLoader(),
        additionalConfiguration,
        additionalPlugin,
        global);
  }

  /** Build a new fake application. */
  public static FakeApplication fakeApplication(
      Map<String, ? extends Object> additionalConfiguration,
      List<String> additionalPlugins,
      List<String> withoutPlugins) {
    return new FakeApplication(
        new java.io.File("."),
        Helpers.class.getClassLoader(),
        additionalConfiguration,
        additionalPlugins,
        withoutPlugins,
        null);
  }

  /** Build a new fake application. */
  public static FakeApplication fakeApplication(
      Map<String, ? extends Object> additionalConfiguration,
      List<String> additionalPlugins,
      List<String> withoutPlugins,
      GlobalSettings global) {
    return new FakeApplication(
        new java.io.File("."),
        Helpers.class.getClassLoader(),
        additionalConfiguration,
        additionalPlugins,
        withoutPlugins,
        global);
  }

  /** Extracts the Status code of this Result value. */
  public static int status(Result result) {
    return result.toScala().header().status();
  }

  /** Extracts the Location header of this Result value if this Result is a Redirect. */
  public static String redirectLocation(Result result) {
    return header(LOCATION, result);
  }

  /** Extracts the Flash values of this Result value. */
  public static Flash flash(Result result) {
    return JavaResultExtractor.getFlash(result);
  }

  /** Extracts the Session of this Result value. */
  public static Session session(Result result) {
    return JavaResultExtractor.getSession(result);
  }

  /** Extracts a Cookie value from this Result value */
  public static Cookie cookie(String name, Result result) {
    return JavaResultExtractor.getCookies(result).get(name);
  }

  /** Extracts the Cookies (an iterator) from this result value. */
  public static Cookies cookies(Result result) {
    return play.core.j.JavaResultExtractor.getCookies(result);
  }

  /** Extracts an Header value of this Result value. */
  public static String header(String header, Result result) {
    return JavaResultExtractor.getHeaders(result).get(header);
  }

  /** Extracts all Headers of this Result value. */
  public static Map<String, String> headers(Result result) {
    return JavaResultExtractor.getHeaders(result);
  }

  /** Extracts the Content-Type of this Content value. */
  public static String contentType(Content content) {
    return content.contentType();
  }

  /** Extracts the Content-Type of this Result value. */
  public static String contentType(Result result) {
    String h = header(CONTENT_TYPE, result);
    if (h == null) return null;
    if (h.contains(";")) {
      return h.substring(0, h.indexOf(";")).trim();
    } else {
      return h.trim();
    }
  }

  /** Extracts the Charset of this Result value. */
  public static String charset(Result result) {
    String h = header(CONTENT_TYPE, result);
    if (h == null) return null;
    if (h.contains("; charset=")) {
      return h.substring(h.indexOf("; charset=") + 10, h.length()).trim();
    } else {
      return null;
    }
  }

  /** Extracts the content as bytes. */
  public static byte[] contentAsBytes(Result result) {
    return contentAsBytes(result, DEFAULT_TIMEOUT);
  }

  public static byte[] contentAsBytes(Result result, long timeout) {
    return JavaResultExtractor.getBody(result, timeout);
  }

  /** Extracts the content as bytes. */
  public static byte[] contentAsBytes(Content content) {
    return content.body().getBytes();
  }

  /** Extracts the content as String. */
  public static String contentAsString(Content content) {
    return content.body();
  }

  /** Extracts the content as String. */
  public static String contentAsString(Result result) {
    return contentAsString(result, DEFAULT_TIMEOUT);
  }

  public static String contentAsString(Result result, long timeout) {
    try {
      String charset = charset(result);
      if (charset == null) {
        charset = "utf-8";
      }
      return new String(contentAsBytes(result, timeout), charset);
    } catch (RuntimeException e) {
      throw e;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }

  @SuppressWarnings(value = "unchecked")
  public static Result routeAndCall(FakeRequest fakeRequest, long timeout) {
    try {
      return routeAndCall(
          (Class<? extends Routes>) FakeRequest.class.getClassLoader().loadClass("Routes"),
          fakeRequest,
          timeout);
    } catch (RuntimeException e) {
      throw e;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }

  public static Result routeAndCall(
      Class<? extends Routes> router, FakeRequest fakeRequest, long timeout) {
    try {
      Routes routes =
          (Routes)
              router
                  .getClassLoader()
                  .loadClass(router.getName() + "$")
                  .getDeclaredField("MODULE$")
                  .get(null);
      if (routes.routes().isDefinedAt(fakeRequest.getWrappedRequest())) {
        return invokeHandler(
            routes.routes().apply(fakeRequest.getWrappedRequest()), fakeRequest, timeout);
      } else {
        return null;
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }

  public static Result route(FakeRequest fakeRequest) {
    return route(fakeRequest, DEFAULT_TIMEOUT);
  }

  public static Result route(FakeRequest fakeRequest, long timeout) {
    return route(play.Play.application(), fakeRequest, timeout);
  }

  public static Result route(Application app, FakeRequest fakeRequest) {
    return route(app, fakeRequest, DEFAULT_TIMEOUT);
  }

  public static Result route(Application app, FakeRequest fakeRequest, long timeout) {
    final scala.Option<scala.concurrent.Future<play.api.mvc.Result>> opt =
        play.api.test.Helpers.jRoute(app.getWrappedApplication(), fakeRequest.fake);
    return wrapScalaResult(Scala.orNull(opt), timeout);
  }

  public static Result route(Application app, FakeRequest fakeRequest, byte[] body) {
    return route(app, fakeRequest, body, DEFAULT_TIMEOUT);
  }

  public static Result route(Application app, FakeRequest fakeRequest, byte[] body, long timeout) {
    return wrapScalaResult(
        Scala.orNull(
            play.api.test.Helpers.jRoute(
                app.getWrappedApplication(), fakeRequest.getWrappedRequest(), body)),
        timeout);
  }

  public static Result route(FakeRequest fakeRequest, byte[] body) {
    return route(fakeRequest, body, DEFAULT_TIMEOUT);
  }

  public static Result route(FakeRequest fakeRequest, byte[] body, long timeout) {
    return route(play.Play.application(), fakeRequest, body, timeout);
  }

  /** Starts a new application. */
  public static void start(FakeApplication fakeApplication) {

    play.api.Play.start(fakeApplication.getWrappedApplication());
  }

  /** Stops an application. */
  public static void stop(FakeApplication fakeApplication) {
    play.api.Play.stop();
  }

  /** Executes a block of code in a running application. */
  public static void running(FakeApplication fakeApplication, final Runnable block) {
    synchronized (PlayRunners$.MODULE$.mutex()) {
      try {
        start(fakeApplication);
        block.run();
      } finally {
        stop(fakeApplication);
      }
    }
  }

  /**
   * Creates a new Test server listening on port defined by configuration setting "testserver.port"
   * (defaults to 19001).
   */
  public static TestServer testServer() {
    return testServer(play.api.test.Helpers.testServerPort());
  }

  /**
   * Creates a new Test server listening on port defined by configuration setting "testserver.port"
   * (defaults to 19001) and using the given FakeApplication.
   */
  public static TestServer testServer(FakeApplication app) {
    return testServer(play.api.test.Helpers.testServerPort(), app);
  }

  /** Creates a new Test server. */
  public static TestServer testServer(int port) {
    return new TestServer(port, fakeApplication());
  }

  /** Creates a new Test server. */
  public static TestServer testServer(int port, FakeApplication app) {
    return new TestServer(port, app);
  }

  /** Starts a Test server. */
  public static void start(TestServer server) {
    server.start();
  }

  /** Stops a Test server. */
  public static void stop(TestServer server) {
    server.stop();
  }

  /** Executes a block of code in a running server. */
  public static void running(TestServer server, final Runnable block) {
    synchronized (PlayRunners$.MODULE$.mutex()) {
      try {
        start(server);
        block.run();
      } finally {
        stop(server);
      }
    }
  }

  /** Executes a block of code in a running server, with a test browser. */
  public static void running(
      TestServer server, Class<? extends WebDriver> webDriver, final Callback<TestBrowser> block) {
    running(server, play.api.test.WebDriverFactory.apply(webDriver), block);
  }

  /** Executes a block of code in a running server, with a test browser. */
  public static void running(
      TestServer server, WebDriver webDriver, final Callback<TestBrowser> block) {
    synchronized (PlayRunners$.MODULE$.mutex()) {
      TestBrowser browser = null;
      TestServer startedServer = null;
      try {
        start(server);
        startedServer = server;
        browser = testBrowser(webDriver);
        block.invoke(browser);
      } catch (Error e) {
        throw e;
      } catch (RuntimeException re) {
        throw re;
      } catch (Throwable t) {
        throw new RuntimeException(t);
      } finally {
        if (browser != null) {
          browser.quit();
        }
        if (startedServer != null) {
          stop(startedServer);
        }
      }
    }
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser() {
    return testBrowser(HTMLUNIT);
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser(int port) {
    return testBrowser(HTMLUNIT, port);
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver) {
    return testBrowser(webDriver, Helpers$.MODULE$.testServerPort());
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser(Class<? extends WebDriver> webDriver, int port) {
    try {
      return new TestBrowser(webDriver, "http://localhost:" + port);
    } catch (RuntimeException e) {
      throw e;
    } catch (Throwable t) {
      throw new RuntimeException(t);
    }
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser(WebDriver of, int port) {
    return new TestBrowser(of, "http://localhost:" + port);
  }

  /** Creates a Test Browser. */
  public static TestBrowser testBrowser(WebDriver of) {
    return testBrowser(of, Helpers$.MODULE$.testServerPort());
  }
}