コード例 #1
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String result = HttpUtil.handleRequest(request);
    System.out.println("GetFriendsServlet:" + result);

    try {
      JSONObject jsonObject = new JSONObject(result);
      String phone = jsonObject.getString("phone");

      List<User> friends = new Database().getFriends(phone);
      JSONArray jsonArray = new JSONArray();

      for (User friend : friends) {
        String friendName = friend.getName();
        String friendPhone = friend.getPhone();

        JSONObject friendObj = new JSONObject();
        friendObj.put("phone", friendPhone);
        friendObj.put("name", friendName);

        jsonArray.put(friendObj);
      }

      System.out.println("GetFriendsServlet:" + jsonArray.toString());
      HttpUtil.handleResponse(response, jsonArray.toString());
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
コード例 #2
0
ファイル: AttachmentApp.java プロジェクト: keesun/hive
  /**
   * 파일의 목록을 가져온다.
   *
   * <p>이슈, 게시물, 댓글을 볼 때, 첨부된 파일들의 목록을 보여주기 위해 이슈, 게시물, 댓글을 편집할 때, 첨부된 파일들의 목록 및 사용자 파일들의 목록을 보여주기
   * 위해
   *
   * <p>로그인한 사용자의 파일들의 목록을 {@code tempFiles} 프로퍼티로 넘겨준다. 첨부 파일들의 목록을 {@code attachments} 프로퍼티로 넘겨준다.
   * 첨부 파일들 중 로그인한 사용자가 읽기 권한을 갖지 못한 것이 하나라도 있다면 403 Forbidden 으로 응답한다.
   *
   * @return json 포맷으로 된 파일 목록을 본문으로 하는 응답. 다음고 같은 형식이다. {@code {tempFiles: 사용자 파일 목록, attachments:
   *     첨부 파일 목록 }}
   */
  public static Result getFileList() {
    Map<String, List<Map<String, String>>> files = new HashMap<String, List<Map<String, String>>>();

    // Get files from the user's area.
    List<Map<String, String>> userFiles = new ArrayList<Map<String, String>>();
    for (Attachment attach : Attachment.findByContainer(UserApp.currentUser().asResource())) {
      userFiles.add(extractFileMetaDataFromAttachementAsMap(attach));
    }
    files.put("tempFiles", userFiles);

    // Get attached files only if the user has permission to read it.
    Map<String, String[]> query = request().queryString();
    String containerType = HttpUtil.getFirstValueFromQuery(query, "containerType");
    String containerId = HttpUtil.getFirstValueFromQuery(query, "containerId");

    if (containerType != null && containerId != null) {
      List<Map<String, String>> attachments = new ArrayList<Map<String, String>>();
      for (Attachment attach :
          Attachment.findByContainer(
              ResourceType.valueOf(containerType), Long.parseLong(containerId))) {
        if (!AccessControl.isAllowed(UserApp.currentUser(), attach.asResource(), Operation.READ)) {
          return forbidden();
        }
        attachments.add(extractFileMetaDataFromAttachementAsMap(attach));
      }
      files.put("attachments", attachments);
    }

    // Return the list of files as JSON.
    response().setHeader("Content-Type", "application/json");
    return ok(toJson(files));
  }
コード例 #3
0
ファイル: AttachmentApp.java プロジェクト: keesun/hive
  /**
   * {@code id}에 해당하는 첨부파일을 지운다.
   *
   * <p>게시물, 이슈, 댓글들의 첨부파일을 지울때 사용한다.
   *
   * <p>폼의 필드에 {@code _method}가 존재하고 값이 delete로 지정되어 있지 않으면 Bad Request로 응답한다. 파일을 못 찾으면 Not Found
   * 삭제 권한이 없으면 Forbidden
   *
   * <p>첨부내용을 삭제한 후 해당 첨부의 origin 파일 유효검증
   *
   * @param id 첨부파일 id
   * @return attachment 삭제 결과 (하지만 해당 메시지를 쓰고 있지는 않다. 아까운 네크워크 자원..)
   * @throws NoSuchAlgorithmException
   * @throws IOException
   */
  public static Result deleteFile(Long id) throws NoSuchAlgorithmException, IOException {
    // _method must be 'delete'
    Map<String, String[]> data = request().body().asMultipartFormData().asFormUrlEncoded();
    if (!HttpUtil.getFirstValueFromQuery(data, "_method").toLowerCase().equals("delete")) {
      return badRequest("_method must be 'delete'.");
    }

    // Remove the attachment.
    Attachment attach = Attachment.find.byId(id);
    if (attach == null) {
      return notFound();
    }

    if (!AccessControl.isAllowed(UserApp.currentUser(), attach.asResource(), Operation.DELETE)) {
      return forbidden();
    }

    attach.delete();

    logIfOriginFileIsNotValid(attach.hash);

    if (Attachment.fileExists(attach.hash)) {
      return ok("The attachment is removed successfully, but its origin file still exists.");
    } else {
      return ok("Both the attachment and its origin file are removed successfully.");
    }
  }
コード例 #4
0
ファイル: SiteApp.java プロジェクト: jasonseok/yobi
  /**
   * 메일을 발송한다.
   *
   * <p>when 메일발송 페이지에서 발송시
   *
   * <p>입력폼으로부터 보내는 메일주소, 받는사람 제목, 본문내용을 입력받고 {@code email} 객체에 할당한다. 메일을 발송하고 결과를 {@code sended}에
   * 할당한다. {@code writeMail()} 을 통해 메일 전송여부와 오류메세지를 설정하고 메일발송 페이지로 이동한다.
   *
   * @return the result
   * @throws EmailException the email exception
   * @see {@link SiteApp#writeMail(String, boolean)}
   */
  public static Result sendMail() throws EmailException {
    SimpleEmail email = new SimpleEmail();

    Map<String, String[]> formData = request().body().asFormUrlEncoded();
    email.setFrom(utils.HttpUtil.getFirstValueFromQuery(formData, "from"));
    email.setSubject(utils.HttpUtil.getFirstValueFromQuery(formData, "subject"));
    email.addTo(utils.HttpUtil.getFirstValueFromQuery(formData, "to"));
    email.setMsg(utils.HttpUtil.getFirstValueFromQuery(formData, "body"));
    email.setCharset("utf-8");

    String errorMessage = null;
    boolean sended;
    String result = Mailer.send(email);
    Logger.info(">>>" + result);
    sended = true;
    return writeMail(errorMessage, sended);
  }
コード例 #5
0
ファイル: IssueLabelApp.java プロジェクト: hoyajigi/yobi
  /**
   * Responds to a request for issue labels of the specified project.
   *
   * <p>This method is used when put a label on an issue and list labels in issue list page.
   *
   * <p>Returns 403 Forbidden if the user has no permission to access to the project.
   *
   * @param ownerName the name of a project owner
   * @param projectName the name of a project
   * @return the response to the request for issue labels
   */
  @IsAllowed(Operation.READ)
  public static Result labels(String ownerName, String projectName) {
    if (HttpUtil.isPJAXRequest(request())) {
      return labelsAsPjax(ownerName, projectName);
    }

    return labelsAsJSON(ownerName, projectName);
  }
コード例 #6
0
    @Override
    protected String doInBackground(Void... params) {
      try {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("phone", MyApplication.getPhone());

        return HttpUtil.post(URLs.GET_USER_INFO_URL, jsonObject.toString());
      } catch (JSONException e) {
        e.printStackTrace();
        return null;
      }
    }
コード例 #7
0
ファイル: SiteApp.java プロジェクト: Ryu-Hojong/nforge4
  public static Result sendMail() {
    Mailer email = new Mailer(play.Play.application());

    Map<String, String[]> formData = request().body().asFormUrlEncoded();
    email.addFrom(utils.HttpUtil.getFirstValueFromQuery(formData, "from"));
    email.setSubject(utils.HttpUtil.getFirstValueFromQuery(formData, "subject"));
    email.addRecipient(utils.HttpUtil.getFirstValueFromQuery(formData, "to"));

    String errorMessage = null;
    boolean sended = false;
    try {
      email.send(utils.HttpUtil.getFirstValueFromQuery(formData, "body"));
      sended = true;
    } catch (EmailException e) {
      errorMessage = e.toString();
      if (e.getCause() != null) {
        errorMessage += "<br/>Caused by: " + e.getCause();
      }
    }

    return writeMail(errorMessage, sended);
  }
コード例 #8
0
ファイル: UserApp.java プロジェクト: bluemir/hive
  /**
   * 로그인 처리 시스템 설정에서 가입승인 기능이 활성화 되어 있고 사용자 상태가 잠금상태(미승인?)라면 계정이 잠겼다는 메시지를 노출하고 로그인 폼으로 돌아감 시스템 설정에서
   * 가입승인 기능이 활성화 되어 있지 않다면, 사용자 상태가 잠금상태라도 로그인이 가능하다 (스펙확인 필요) 요청의 정보로 사용자 인증에 성공하면 로그인쿠키를 생성하고
   * 로그인유지하기가 선택되었다면, 로그인유지를 위한 쿠키를 별도로 생성한다 인증에 실패하면 관련된 메시지를 노출하고 로그인 폼으로 돌아간다
   *
   * @return
   */
  public static Result login() {
    Form<User> userForm = form(User.class).bindFromRequest();
    if (userForm.hasErrors()) {
      return badRequest(login.render("title.login", userForm, null));
    }
    User sourceUser = form(User.class).bindFromRequest().get();

    Map<String, String[]> params = request().body().asFormUrlEncoded();
    String redirectUrl = HttpUtil.getFirstValueFromQuery(params, "redirectUrl");

    String loginFormUrl = routes.UserApp.loginForm().absoluteURL(request());
    loginFormUrl += "?redirectUrl=" + redirectUrl;

    if (isUseSignUpConfirm()) {
      if (User.findByLoginId(sourceUser.loginId).state == UserState.LOCKED) {
        flash(Constants.WARNING, "user.locked");
        return redirect(loginFormUrl);
      }
    }

    if (User.findByLoginId(sourceUser.loginId).state == UserState.DELETED) {
      flash(Constants.WARNING, "user.deleted");
      return redirect(loginFormUrl);
    }

    User authenticate = authenticateWithPlainPassword(sourceUser.loginId, sourceUser.password);

    if (authenticate != null) {
      addUserInfoToSession(authenticate);
      if (sourceUser.rememberMe) {
        setupRememberMe(authenticate);
      }

      authenticate.lang = play.mvc.Http.Context.current().lang().code();
      authenticate.update();

      if (StringUtils.isEmpty(redirectUrl)) {
        return redirect(routes.Application.index());
      } else {
        return redirect(redirectUrl);
      }
    }

    flash(Constants.WARNING, "user.login.failed");
    return redirect(routes.UserApp.loginForm());
  }
コード例 #9
0
ファイル: AttachmentApp.java プロジェクト: keesun/hive
  /**
   * {@code id}로 파일을 찾아서 첨부파일로 돌려준다.
   *
   * <p>when: 첨부파일을 다운로드 받을 때
   *
   * <p>주의사항: 파일명이 깨지지 않도록 {@link utils.HttpUtil#encodeContentDisposition)}로 인코딩한다.
   *
   * @param id 첨부파일 id
   * @return 파일이 첨부된 응답
   * @throws NoSuchAlgorithmException
   * @throws IOException
   */
  public static Result getFile(Long id) throws NoSuchAlgorithmException, IOException {
    Attachment attachment = Attachment.find.byId(id);

    if (attachment == null) {
      return notFound();
    }

    if (!AccessControl.isAllowed(UserApp.currentUser(), attachment.asResource(), Operation.READ)) {
      return forbidden();
    }

    File file = attachment.getFile();

    String filename = HttpUtil.encodeContentDisposition(attachment.name);

    response().setHeader("Content-Type", attachment.mimeType);
    response().setHeader("Content-Disposition", "attachment; " + filename);

    return ok(file);
  }