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"));
  }
Exemple #2
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();
    }
  }
  /**
   * 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;
  }
  /**
   * @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"));
    }
  }
  @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();
  }
  /**
   * @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"));
    }
  }
  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.";
    }
  }
Exemple #8
0
 @Override
 public Object handle(Request request, Response response) throws Exception {
   String firstName = request.queryParams("firstname");
   String lastName = request.queryParams("lastname");
   Employee employee = new Employee(firstName, lastName);
   Long employeeId = storage.addEmployee(employee);
   return employeeId;
 }
Exemple #9
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;
   }
 }
  /**
   * @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 handleGetByTag(Request request, Response response) throws Exception {

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

    String tag = StringEscapeUtils.escapeHtml4(request.params(":thetag"));
    List<Document> posts = blogPostDAO.findByTagDateDescending(tag);

    root.put("myposts", posts);
    if (username != null) {
      root.put("username", username);
    }

    return templateEngine.render(new ModelAndView(root, "blog_template.ftl"));
  }
Exemple #11
0
 public static Map<String, Object> getBaseModel(Request request) {
   Map<String, Object> model = new HashMap<>();
   model.put("request", request);
   model.put("context", request.contextPath());
   model.put("date", new DateTool());
   return model;
 }
Exemple #12
0
  public static LayoutContent displayHome(spark.Request request, Configuration cfg) {
    String html = "";
    Map<String, String> root = Tools.listLayoutMap();
    root.replace("msg", DBH.getMsg(request.session().id()));
    Template temp;
    try {
      temp = cfg.getTemplate("user-home.htm");
      Writer out = new StringWriter();
      temp.process(root, out);
      html = out.toString();
    } catch (IOException | TemplateException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      html = e.getMessage();
    }
    HashMap<String, String> options = new HashMap<String, String>();
    options.put("addBtn", Tools.getAddBtn("/tramites/agregar", "Iniciar Trámite"));
    options.put(
        "toolBar",
        Tools.getToolbarItem("/tramites/agregar", "Iniciar Trámite", "", "btn red darken-3")
            + Tools.getToolbarItem("/tramites", "Trámites", "", "btn green darken-3"));

    LayoutContent lc = new LayoutContent(html, options);
    return lc;
  }
  @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;
  }
  public VuiBeanResponse doLosQueryService(Request request, Response response) {
    VuiBeanResponse losResponse = new VuiBeanResponse();
    try {
      System.out.println("OnePointServlet : doLOSQuery : Enters");

      RequestObject req = ObjectTransformer.convert(request.queryString(), RequestObject.class);

      String resp = new IntradoService().doLos(req);

      ResObject queryResponse = unmarshall(resp);

      losResponse = queryResponse.getPayload().getLosResponse();

      if (null == losResponse || null == losResponse.getLevelOfService()) {
        String message = queryResponse.getPayload().getErrorResponse().getMessage();
        System.out.println("Message ---> :" + message);
        losResponse = new VuiBeanResponse();
        losResponse.setMessage(message);
      }

      System.out.println("OnePointServlet : doLOSQuery : Exits");
    } catch (Exception e) {
      e.printStackTrace();
    }
    return losResponse;
  }
  /**
   * @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"));
    }
  }
  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");
  }
  @Test
  public void testGetFeedItems() {
    Request request = createRequestMock("logged-in");
    Response response = createResponseMock();
    GetFeedItemsRoute feedsRoute = new GetFeedItemsRoute("/feeds");
    feedsRoute.setFeedItemProvider(createFeedItemProviderMock());
    feedsRoute.setFeedUpdater(createFeedUpdaterMock());
    feedsRoute.setFeedProvider(createFeedProviderMock());

    when(request.params(":categoryId")).thenReturn("1");
    when(request.params(":feedId")).thenReturn("2");

    String jsonResponse = (String) feedsRoute.handle(request, response);
    String expectedJson =
        "[{\"feedItemId\":\"3\",\"username\":\"billblake\",\"catId\":\"1\",\"feedId\":\"2\",\"source\":\"source\",\"title\":\"title\",\"description\":\"description\",\"link\":\"link\",\"imageUrl\":null,\"pubDate\":10000000,\"formattedDate\":\"Jul 28\",\"read\":false,\"saved\":false,\"tags\":null}]";
    assertEquals(expectedJson, jsonResponse);
  }
 private String getUriParam(Request req, String prefix) {
   String ret = req.pathInfo().substring(prefix.length());
   int index = ret.indexOf("?");
   if (index != -1) {
     ret = ret.substring(0, index);
   }
   return ret;
 }
 public static Set<Route> getRoutesForStop(Request req, List<String> feeds) {
   if (req.queryParams("stop") != null) {
     String stopId = req.queryParams("stop");
     System.out.println(stopId);
     Set<Route> routes = new HashSet<>();
     // loop through feeds
     for (String feedId : feeds) {
       // loop through patterns, check for route and return pattern stops
       FeedSource source = ApiMain.getFeedSource(feedId);
       for (Pattern pattern : source.feed.patterns.values()) {
         if (pattern.orderedStops.contains(stopId)) {
           routes.add(source.feed.routes.get(pattern.route_id));
         }
       }
     }
     return routes;
   }
   return null;
 }
Exemple #20
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;
  }
  public VuiBeanResponse doQueryService(Request request, Response response) {

    VuiBeanResponse queryDataResponse = new VuiBeanResponse();
    System.out.println("doQueryService : Enters");

    try {
      String stCPN = request.queryParams("CPN");
      String stExternalKey = request.queryParams("ExternalKey");

      String resp = new IntradoService().queryData(stCPN, stExternalKey);

      ResObject queryResponse = unmarshall(resp);

      queryDataResponse = queryResponse.getPayload().getQueryResponse();

      System.out.println("OnePointServlet : doQueryService : Exits");
    } catch (Exception e) {
      e.printStackTrace();
    }
    return queryDataResponse;
  }
  /**
   * 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 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();
   }
 }
  /**
   * This is where we would normally load up the blog data but this week, we just display a
   * placeholder.
   *
   * @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 handleGetRoot(Request request, Response response) throws Exception {

    SimpleHash root = new SimpleHash();

    String username = sessionDAO.findUserNameBySessionId(request.cookie("session"));
    List<Document> posts = blogPostDAO.findByDateDescending(10);

    root.put("myposts", posts);
    if (username != null) {
      root.put("username", username);
    }

    return templateEngine.render(new ModelAndView(root, "blog_template.ftl"));
  }
Exemple #25
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);
   }
 }
Exemple #26
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;
   }
 }
  /**
   * @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 VuiBeanResponse doInsertOrDel(Request request, Response response, String action) {
    VuiBeanResponse updateResponse = new VuiBeanResponse();
    try {
      System.out.println("OnePointServlet : doInsert : Enters");

      RequestObject req = ObjectTransformer.convert(request.queryString(), RequestObject.class);

      String resp = new IntradoService().doInsertOrDel(req, action);

      ResObject queryResponse = unmarshall(resp);

      updateResponse = queryResponse.getPayload().getUpdateResponse();

      System.out.println("OnePointServlet : doInsert : Exits");
    } catch (Exception e) {
      e.printStackTrace();
    }

    return updateResponse;
  }
 public synchronized String replaceBanks(Request request, Response response) {
   Type collectionType = new TypeToken<HashMap<String, Collection<Account>>>() {}.getType();
   HashMap<String, Collection<Account>> json = gson.fromJson(request.body(), collectionType);
   banks = json;
   return "success";
 }
 private CallingContext getContext(Request req) {
   return ctxs.get(req.session().id());
 }