コード例 #1
0
  /**
   * @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"));
    }
  }
コード例 #2
0
  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"));
  }
コード例 #3
0
  /**
   * @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"));
    }
  }
コード例 #4
0
ファイル: AddEmployee.java プロジェクト: up1/spark-java-demo
 @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;
 }
コード例 #5
0
  /**
   * 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;
  }
コード例 #6
0
 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;
 }
コード例 #7
0
  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;
  }
コード例 #8
0
  /**
   * 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;
  }
コード例 #9
0
  @Test
  public void testGetFeedItemsAndRefresh() {
    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");
    when(request.queryParams("refresh")).thenReturn("true");

    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);
  }
コード例 #10
0
ファイル: HDGPointRequestRoute.java プロジェクト: kreon/jnode
 @Override
 public Object handle(Request req, Response resp) {
   if (!enabled) {
     return "ERROR\r\nAUTOPOINT DISABLED\r\n";
   }
   String name = req.queryParams("_name");
   String email = req.queryParams("_email");
   String password = req.queryParams("_password");
   String about = req.queryParams("_about");
   String error = "";
   // check this shit
   {
     if (!name.matches("^[A-Z][a-z]+ [A-Z][a-z]+$")) {
       error += "NAME_CHECK_FAILED ";
     }
     if (!email.matches(
         "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")) {
       error += "MAIL_CHECK_FAILED ";
     }
     if (password.length() < 8) {
       error += "MIN_PASSWD_LEN=8 ";
     }
     if (!(password.matches(".*[0-9].*")
         && password.matches(".*[A-Z].*")
         && password.matches(".*[a-z].*"))) {
       error += "WEAK_PASSWD ";
     }
     if (error.length() > 0) {
       error(error);
       return "ERROR\r\n" + error;
     }
   }
   // seems ok
   FtnAddress guessedAddress = guessNewPointAddress();
   if (guessedAddress == null) {
     error("NO_PNT_ADDRESS_SPACE");
     return "ERROR\r\nNO_PNT_ADDRESS_SPACE";
   }
   // do point request
   PointRequest pReq = new PointRequest();
   pReq.setAddr(guessedAddress.toString());
   pReq.setEmail(email);
   pReq.setName(name);
   pReq.setPassword(password);
   // save
   ORMManager.get(PointRequest.class).save(pReq);
   // create link
   Link link = new Link();
   link.setLinkAddress(guessedAddress.toString());
   link.setLinkName(name);
   link.setProtocolAddress("-");
   link.setProtocolPassword(password);
   link.setPaketPassword(password);
   ORMManager.get(Link.class).save(link);
   // write echomail
   {
     String techArea = MainHandler.getCurrentInstance().getProperty("stat.area", null);
     String text = guessedAddress + "," + name + "," + about;
     if (techArea != null) {
       Echoarea area = FtnTools.getAreaByName(techArea, null);
       FtnTools.writeEchomail(area, "New HTDGPoint", text);
     }
     FtnTools.writeNetmail(
         guessedAddress,
         FtnTools.getPrimaryFtnAddress(),
         MainHandler.getCurrentInstance().getInfo().getStationName(),
         MainHandler.getCurrentInstance().getInfo().getSysop(),
         "New HTDG point",
         text);
     ok(text);
   }
   return "OK\r\n" + guessedAddress;
 }
コード例 #11
0
  public static Object getRoutes(Request req, Response res) {

    List<Route> routes = new ArrayList<>();
    List<String> feeds = new ArrayList();

    if (req.queryParams("feed") != null) {

      for (String feedId : req.queryParams("feed").split(",")) {
        if (ApiMain.getFeedSource(feedId) != null) {
          feeds.add(feedId);
        }
      }
      if (feeds.size() == 0) {
        halt(404, "Must specify valid feed id.");
      }
      // If feed is only param.
      else if (req.queryParams().size() == 1 && req.params("id") == null) {
        for (String feedId : req.queryParams("feed").split(",")) {
          FeedSource feedSource = ApiMain.getFeedSource(feedId);
          if (feedSource != null) routes.addAll(feedSource.feed.routes.values());
        }
        return routes;
      }
    } else {
      //            res.body("Must specify valid feed id.");
      //            return "Must specify valid feed id.";
      halt(404, "Must specify valid feed id.");
    }

    // get specific route
    if (req.params("id") != null) {
      Route r = ApiMain.getFeedSource(feeds.get(0)).feed.routes.get(req.params("id"));
      if (r != null) // && currentUser(req).hasReadPermission(s.projectId))
      return r;
      else halt(404, "Route " + req.params("id") + " not found");
    }
    // bounding box
    else if (req.queryParams("max_lat") != null
        && req.queryParams("max_lon") != null
        && req.queryParams("min_lat") != null
        && req.queryParams("min_lon") != null) {
      Coordinate maxCoordinate =
          new Coordinate(
              Double.valueOf(req.queryParams("max_lon")),
              Double.valueOf(req.queryParams("max_lat")));
      Coordinate minCoordinate =
          new Coordinate(
              Double.valueOf(req.queryParams("min_lon")),
              Double.valueOf(req.queryParams("min_lat")));
      Envelope searchEnvelope = new Envelope(maxCoordinate, minCoordinate);
      for (String feedId : feeds) {
        // TODO: these are actually patterns being returned, NOT routes
        List<Route> searchResults = ApiMain.getFeedSource(feedId).routeIndex.query(searchEnvelope);
        routes.addAll(searchResults);
      }
      return routes;
    }
    // lat lon + radius
    else if (req.queryParams("lat") != null && req.queryParams("lon") != null) {
      Coordinate latLon =
          new Coordinate(
              Double.valueOf(req.queryParams("lon")), Double.valueOf(req.queryParams("lat")));
      if (req.queryParams("radius") != null) {
        RoutesController.radius = Double.valueOf(req.queryParams("radius"));
      }
      Envelope searchEnvelope = GeomUtil.getBoundingBox(latLon, radius);

      for (String feedId : feeds) {
        List<Route> searchResults = ApiMain.getFeedSource(feedId).routeIndex.query(searchEnvelope);
        routes.addAll(searchResults);
      }
      return routes;
    } else if (req.queryParams("name") != null) {
      System.out.println(req.queryParams("name"));

      for (String feedId : feeds) {
        System.out.println("looping feed: " + feedId);

        // Check if feed is specified in feed sources requested
        // TODO: Check if user has access to feed source? (Put this in the before call.)
        //                if (Arrays.asList(feeds).contains(entry.getKey())) {
        System.out.println("checking feed: " + feedId);

        // search query must be in upper case to match radix tree keys
        Iterable<Route> searchResults =
            ApiMain.getFeedSource(feedId)
                .routeTree
                .getValuesForKeysContaining(req.queryParams("name").toUpperCase());
        for (Route route : searchResults) {
          routes.add(route);
        }
      }

      return routes;
    }
    // query for stop_id (i.e., get all routes that operate along patterns for a given stop)
    else if (req.queryParams("stop") != null) {
      return getRoutesForStop(req, feeds);
    }

    return null;
  }