/**
   * @param request The request object providing information about the HTTP request
   * @param response The response object providing functionality for modifying the response
   * @return The content to be set in the response
   * @throws Exception implementation can choose to throw exception
   */
  public String handlePostNewComment(Request request, Response response) throws Exception {

    String name = StringEscapeUtils.escapeHtml4(request.queryParams("commentName"));
    String email = StringEscapeUtils.escapeHtml4(request.queryParams("commentEmail"));
    String body = StringEscapeUtils.escapeHtml4(request.queryParams("commentBody"));
    String permalink = request.queryParams("permalink");

    Document post = blogPostDAO.findByPermalink(permalink);
    if (post == null) {
      response.redirect("/post_not_found");
      return templateEngine.render(new ModelAndView(null, "redirect.ftl"));
    }

    // check that comment is good
    else if (name.equals("") || body.equals("")) {
      // bounce this back to the user for correction
      SimpleHash comment = new SimpleHash();
      comment.put("name", name);
      comment.put("email", email);
      comment.put("body", body);

      SimpleHash root = new SimpleHash();
      root.put("comment", comment);
      root.put("post", post);
      root.put("errors", "Post must contain your name and an actual comment");
      return templateEngine.render(new ModelAndView(root, "entry_template.ftl"));

    } else {
      blogPostDAO.addPostComment(name, email, body, permalink);
      response.redirect("/post/" + permalink);
      return templateEngine.render(new ModelAndView(null, "redirect.ftl"));
    }
  }
  /**
   * @param request The request object providing information about the HTTP request
   * @param response The response object providing functionality for modifying the response
   * @return The content to be set in the response
   * @throws Exception implementation can choose to throw exception
   */
  public String handlePostNewPost(Request request, Response response) throws Exception {

    String title = StringEscapeUtils.escapeHtml4(request.queryParams("subject"));
    String post = StringEscapeUtils.escapeHtml4(request.queryParams("body"));
    String tags = StringEscapeUtils.escapeHtml4(request.queryParams("tags"));

    String username = sessionDAO.findUserNameBySessionId(request.cookie("session"));

    if (username == null) {
      response.redirect("/login"); // only logged in users can post to blog
      return templateEngine.render(new ModelAndView(null, "redirect.ftl"));
    } else if (title.equals("") || post.equals("")) {
      SimpleHash root = new SimpleHash();

      // redisplay page with errors
      root.put("errors", "post must contain a title and blog entry.");
      root.put("subject", title);
      root.put("username", username);
      root.put("tags", tags);
      root.put("body", post);
      return templateEngine.render(new ModelAndView(root, "newpost_template.ftl"));
    } else {
      // extract tags
      List<String> tagsArray = extractTags(tags);

      // substitute some <p> for the paragraph breaks
      post = post.replaceAll("\\r?\\n", "<p>");

      String permalink = blogPostDAO.addPost(title, post, tagsArray, username);

      // now redirect to the blog permalink
      response.redirect("/post/" + permalink);
      return templateEngine.render(new ModelAndView(null, "redirect.ftl"));
    }
  }
  /**
   * Metodo para inicial la sesion del usuario.
   *
   * @param request
   * @param response
   * @return
   */
  public Object doLogin(Request request, Response response) {
    String nickname = request.queryParams("nickname").toLowerCase();
    String password = request.queryParams("password");

    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();

    User user =
        (User)
            session
                .createCriteria(User.class)
                .add(Restrictions.eq("nickname", nickname))
                .add(Restrictions.eq("password", password))
                .uniqueResult();

    UserValidator validator = new UserValidator(request.session());
    validator.validateUser(user);

    if (null != user) {
      request.session(true);
      request.session().attribute("user", user);
      response.redirect("/orders");
    } else {
      response.redirect("/");
    }

    return null;
  }
  public Object handlePostLike(Request request, Response response) {

    String permalink = request.queryParams("permalink");
    String commentOrdinalStr = request.queryParams("comment_ordinal");

    // look up the post in question

    int ordinal = Integer.parseInt(commentOrdinalStr);

    // TODO: check return or have checkSession throw
    String username = sessionDAO.findUserNameBySessionId(request.cookie("session"));
    Document post = blogPostDAO.findByPermalink(permalink);

    //  if post not found, redirect to post not found error
    if (post == null) {
      response.redirect("/post_not_found");
    } else {
      blogPostDAO.likePost(permalink, ordinal);

      response.redirect("/post/" + permalink);
    }

    SimpleHash root = new SimpleHash();

    return templateEngine.render(new ModelAndView(root, "entry_template.ftl"));
  }
  public synchronized String transferFromBankToPlayer(Request request, Response response) {
    lamport.Add();
    if (banks.containsKey(request.params(":gameid"))) {
      Collection<Account> accounts = banks.get(request.params(":gameid"));
      for (Account account : accounts) {
        if (account.getPlayer().getId().equals(request.params(":to"))) {
          int am = Integer.parseInt(request.params(":amount"));
          account.AddAmount(am);
          banks.put(request.params(":gameid"), accounts);

          String uri = localUri + "transfers/" + UniqueId++;
          Transfer trans =
              new Transfer(
                  request.params(":from"), request.params(":to"), am, request.body(), "", uri);
          Event event =
              new Event(
                  "bank transfer",
                  request.body(),
                  request.body(),
                  uri,
                  account.getPlayer().getId());
          transfers.add(trans);
          BanksService.sendUpdate(trans, request.params(":gameid"));

          response.status(201);
          return gson.toJson(event);
        }
      }
      response.status(404);
      return "Player not found.";
    } else {
      response.status(404);
      return "Game not found.";
    }
  }
  @Override
  public Object handle(final Request request, final Response response) throws Exception {
    if (!CreateGameDTO.isValidRequestJson(request.body())) {
      response.status(400);
      return BAD_JSON_MESSAGE;
    }

    final CommandExecutionResult result =
        GamesController.createGame(new CreateGameDTO(request.body()));

    if (result.errorOccurred()) {
      response.status(result.getStatus());
    } else {
      response.status(200);
    }

    // set any new cookies
    if (result.hasNewCookies()) {
      Map<String, String> cookies = result.getNewCookies();
      for (String key : cookies.keySet()) {
        Cookie cookie = new Cookie(key, cookies.get(key));
        cookie.setPath("/");
        response.raw().addCookie(cookie);
      }
    }

    return result.getBody();
  }
 @Override
 public Object handle(Request request, Response response) throws Exception {
   try {
     String serviceName = request.params(":serviceName");
     deleteServiceJob(serviceName, user, password, tenant, dbClient);
     response.status(HttpConstants.HTTP_OK);
     response.type(HttpConstants.APPLICATION_JSON);
     return "Deletion scheduled for service " + serviceName;
   } catch (Exception e) {
     response.status(HTTP_BAD_REQUEST);
     return e.toString();
   }
 }
Exemple #8
0
 private String upsertUser(Request request, Response response) throws UsersRepositoryException {
   try {
     return userService.upsertUser(
         request.params(USER_NAME), jsonExtractor.parse(request.body()).getPassword(), response);
   } catch (JsonExtractException e) {
     LOGGER.info("Error while deserializing addUser request", e);
     response.status(400);
     return Constants.EMPTY_BODY;
   } catch (IllegalArgumentException e) {
     LOGGER.info("Invalid user path", e);
     response.status(400);
     return Constants.EMPTY_BODY;
   }
 }
Exemple #9
0
 private String removeUser(Request request, Response response) {
   String username = request.params(USER_NAME);
   try {
     userService.removeUser(username);
     response.status(204);
     return Constants.EMPTY_BODY;
   } catch (UsersRepositoryException e) {
     response.status(204);
     return "The user " + username + " does not exists";
   } catch (IllegalArgumentException e) {
     LOGGER.info("Invalid user path", e);
     response.status(400);
     return Constants.EMPTY_BODY;
   }
 }
  @Override
  public Object handle(Request request, Response response) {

    JSONObject result;

    try {
      JSONObject requestJSON = new JSONObject(request.body());
      SudokuGame game =
          new SudokuGame(convertJSONObjectToStringArray(requestJSON.getJSONArray("data")));
      game.solve();
      result = convertStringToJSONObject(game.toString());
    } catch (CannotProceedException e) {
      result = createErrorMessage("cannot solve");
      logger.error(e.getMessage());
    } catch (Exception e) {
      result = createErrorMessage("unknown");
      logger.error(e.getMessage());
    }

    response.type("application/json");
    /*try {
        Thread.sleep(15000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }*/
    return result;
  }
Exemple #11
0
  @Override
  public void handle(Request request, Response response)
      throws UnauthorizedException, ForbiddenException, InternalServerException {
    Boolean authenticated, authorized;
    String challenge;

    try {
      authenticated =
          getAuth()
              .authenticate(
                  request.requestMethod(), request.uri(), request.headers("Authorization"));
      authorized = getAuth().authorize(request.requestMethod());
      challenge = getAuth().challenge();
    } catch (UnloadableConfigException | InvalidPropertyException | RuntimeException e) {
      throw new InternalServerException(e);
    }

    if (!authenticated) {
      response.header("WWW-Authenticate", challenge);
      throw new UnauthorizedException();
    }

    if (!authorized) {
      throw new ForbiddenException();
    }
  }
  /**
   * @param request The request object providing information about the HTTP request
   * @param response The response object providing functionality for modifying the response
   * @return The content to be set in the response
   * @throws Exception implementation can choose to throw exception
   */
  public String handleGetPermaLinkPost(Request request, Response response) throws Exception {

    String permalink = request.params(":permalink");

    System.out.println("/post: get " + permalink);

    Document post = blogPostDAO.findByPermalink(permalink);

    if (post == null) {
      response.redirect("/post_not_found");
      return templateEngine.render(new ModelAndView(null, "redirect.ftl"));

    } else {
      // empty comment to hold new comment in form at bottom of blog entry detail page
      SimpleHash newComment = new SimpleHash();
      newComment.put("name", "");
      newComment.put("email", "");
      newComment.put("body", "");

      SimpleHash root = new SimpleHash();
      root.put("post", post);
      root.put("comments", newComment);
      return templateEngine.render(new ModelAndView(root, "entry_template.ftl"));
    }
  }
Exemple #13
0
  public Object create(Request request, Response response) throws Exception {
    final Map<String, String[]> project = request.queryMap("project").toMap();

    Project p = Project.fromMap(project);

    repository.save(p);

    response.redirect("/#/index/dashboard");
    return null;
  }
Exemple #14
0
 public static byte[] getOrigin(Request req, Response res) {
   res.header("Content-Type", "application/octet-stream");
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   int x = Integer.parseInt(req.params("x"));
   int y = Integer.parseInt(req.params("y").replaceFirst("\\.dat$", ""));
   StaticSiteRequest.PointRequest pr = staticSiteRequest.getPointRequest(x, y);
   StaticComputer computer = new StaticComputer(pr, network, new TaskStatistics());
   try {
     computer.write(baos);
     return baos.toByteArray();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
  /**
   * @param request The request object providing information about the HTTP request
   * @param response The response object providing functionality for modifying the response
   * @return The content to be set in the response
   * @throws Exception implementation can choose to throw exception
   */
  public String handleGetNewPost(Request request, Response response) throws Exception {

    // get cookie
    String username = sessionDAO.findUserNameBySessionId(request.cookie("session"));

    if (username == null) {
      // looks like a bad request. user is not logged in
      response.redirect("/login");
      return templateEngine.render(new ModelAndView(null, "redirect.ftl"));
    } else {
      SimpleHash root = new SimpleHash();
      root.put("username", username);
      return templateEngine.render(new ModelAndView(root, "newpost_template.ftl"));
    }
  }
  public ModelAndView handle(Request request, Response response) throws Exception {
    // On regarde si l'utilisateur a accès
    ModelAndView modelAndView = Authentification.checkEnseignant(request, response);
    if (modelAndView != null) return modelAndView;

    Map<String, Object> attributes = new HashMap<String, Object>();
    attributes.put("title", "Inscription au créneau");
    attributes.put("connected", (request.session().attribute("email") != null));
    attributes.put("labo", (request.session().attribute("labo") != null));
    attributes.put("enseignant", (request.session().attribute("enseignant") != null));

    Integer idEnseignant = request.session().attribute("enseignant");

    if (idEnseignant == null) response.redirect("/enseignant");

    return new ModelAndView(attributes, "inscription-creneau.ftl");
  }
  /**
   * Metodo para registrar a un usuario.
   *
   * @param request
   * @param response
   * @return
   */
  public Object doSignup(Request request, Response response) {
    String name = request.queryParams("name");
    String lastName = request.queryParams("last_name");
    String nickname = request.queryParams("nickname").toLowerCase();
    String password = request.queryParams("password");
    String confirmPassword = request.queryParams("confirm_password");

    UserValidator validator = new UserValidator(request.session());

    validator.validateUserName(name);
    validator.validateUserLastName(lastName);
    validator.validateNickname(nickname);
    validator.validatePassword(password, confirmPassword);

    if (!validator.error()) {
      SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
      Session session = sessionFactory.openSession();

      Transaction transaction = session.beginTransaction();

      User user = new User();
      user.setName(name);
      user.setLastName(lastName);
      user.setNickname(nickname);
      user.setPassword(password);
      user.setIsAdmin(false);

      session.save(user);

      transaction.commit();
      session.close();

      doLogin(request, response);
    } else {
      response.redirect("/");
    }

    return null;
  }
 @Override
 public HttpServletResponse raw() {
   return delegate.raw();
 }
 @Override
 public void removeCookie(String name) {
   delegate.removeCookie(name);
 }
 @Override
 public void body(String body) {
   delegate.body(body);
 }
 @Override
 public void status(int statusCode) {
   delegate.status(statusCode);
 }
 @Override
 public int hashCode() {
   return delegate.hashCode();
 }
 @Override
 public boolean equals(Object obj) {
   return delegate.equals(obj);
 }
 @Override
 public void cookie(String name, String value, int maxAge) {
   delegate.cookie(name, value, maxAge);
 }
 @Override
 public void cookie(String path, String name, String value, int maxAge, boolean secured) {
   delegate.cookie(path, name, value, maxAge, secured);
 }
 @Override
 public void type(String contentType) {
   delegate.type(contentType);
 }
 @Override
 public String toString() {
   return delegate.toString();
 }
 @Override
 public void header(String header, String value) {
   delegate.header(header, value);
 }
 @Override
 public void redirect(String location, int httpStatusCode) {
   delegate.redirect(location, httpStatusCode);
 }
 @Override
 public void redirect(String location) {
   delegate.redirect(location);
 }