Exemple #1
0
  // 新增房屋
  public String addHouse() throws IOException {

    Map<String, Object> session = ActionContext.getContext().getSession();
    User u = (User) session.get("user");
    house.setUser(u);
    System.out.println("u.getName()===" + u.getName());
    System.out.println("house.getHousetype().getId()===" + house.getHousetype().getId());
    System.out.println("house.getStreet().getId()===" + house.getStreet().getId());
    System.out.println("images.getName()==" + imagesFileName);
    System.out.println("images!=null==" + images != null);
    if (images != null) {
      InputStream is = new FileInputStream(images);
      // 上传图片目录;设置图片名称:上传时间+用户名+image.getName().
      Date date = new Date(System.currentTimeMillis());
      String strDate = new SimpleDateFormat("yyyyMMddhhmmss").format(date);
      String fileName = strDate + u.getName() + imagesFileName;
      System.out.println("上传的图片:" + imagesFileName + "存储到:" + getSavePath() + fileName);
      log.info("上传的图片:" + images.getName() + "存储到:" + getSavePath() + fileName);
      // 设置存储目标文件
      File toFile = new File(getSavePath(), fileName);
      OutputStream os = new FileOutputStream(toFile);
      // 设置缓存
      byte[] buffer = new byte[1024];
      while (is.read(buffer) > 0) {
        os.write(buffer);
      }
      is.close();
      os.close();
      house.setPic(fileName);
    }
    houseService.save(house);
    return "houseAddSuccess";
  }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession();
    User user = (User) session.getAttribute("user");
    Comment comment = new Comment();
    comment.setUserId(user.getUserId());
    comment.setNewsId(Integer.parseInt(request.getParameter("news")));
    comment.setText(request.getParameter("text"));
    MessagesBundle messagesBundle = new MessagesBundle();
    String errorMessage = messagesBundle.getMessages().get("addCommentFailed");

    try {
      commentService.addComment(comment);
      List<News> allNews = newsService.getAllNews(user.getUserId());
      List<List<Comment>> allComments = commentService.getAllBy(allNews);
      session.setAttribute("allComments", allComments);
      response.sendRedirect("/home.jsp");
    } catch (DAOException e) {
      LOGGER.error("Database connection problem", e);
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/home.jsp");
      request.setAttribute("errorMessage", errorMessage);
      dispatcher.include(request, response);
    }
  }
 @Override
 @javax.ejb.TransactionAttribute(javax.ejb.TransactionAttributeType.SUPPORTS)
 public List<Attachment> getAttachmentsByUserId(Long userId) {
   User user = em.find(User.class, userId);
   List<Attachment> alist = new ArrayList(user.getAttachments());
   return alist;
 }
 @Secured({"ROLE_ADMIN", "ROLE_USER"})
 @RequestMapping(value = "/api/profile/picture/update", method = RequestMethod.POST)
 public void updateProfilePicture(@RequestBody final Picture picture) {
   Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
   String email = authentication.getName();
   pictureBean.create(picture);
   User user = userBean.findByEmail(email);
   user.setPicture(picture);
   userBean.update(user);
 }
 @RequestMapping(value = "/user/create", method = RequestMethod.POST)
 public void register(@RequestBody final User user) {
   Criteria criteria = new Criteria();
   criteriaBean.create(criteria);
   BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
   Role role = roleBean.findByName("ROLE_USER");
   user.setPassword(passwordEncoder.encode(user.getPassword()));
   user.setRole(role);
   user.setCriteria(criteria);
   userBean.create(user);
 }
  public void save(User user) {
    user.setEnabled(true);
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    user.setPassword(encoder.encode(user.getPassword()));

    List<Role> roles = new ArrayList<Role>();
    roles.add(roleManager.query().hasName("ROLE_USER").find(0, 1).get(0));
    user.setRoles(roles);

    userManager.save(user);
  }
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {
      //            String username = request.getParameter("username");
      //            String role = request.getParameter("role");

      String username = "******";
      String role = "student";

      Group group = groupManager.getGroup(role);
      if (group == null) {
        group = new Group();
        group.setName(role);
        groupManager.saveGroup(group);
      }

      User user = userManager.getUser(username);
      if (user == null) {
        user = new User();
        user.setName(username);
        user.setPassword(Encryption.digest(DUMMY_PASSWORD, EncryptionType.MD5));
        Set<Group> groups = new HashSet<>();
        groups.add(group);
        user.setGroups(groups);
        userManager.saveUser(user);
      }

      request.logout();

      StudentInformation newStudent = new StudentInformation();
      newStudent.setUserName(username);
      newStudent.setPassword(Encryption.digest(DUMMY_PASSWORD, EncryptionType.MD5));

      HttpSession currentSession = request.getSession();
      currentSession.setAttribute("currentUser", newStudent);

      request.login(username, DUMMY_PASSWORD);

      String tos = termsOfServiceManager.getTermsOfServiceById(1).getTermsOfService();
      currentSession.setAttribute("tos", tos);

      response.sendRedirect(request.getContextPath());

    } catch (ServletException e) {
      e.printStackTrace();
      request.getRequestDispatcher("/WEB-INF/login/login_error.jsp").forward(request, response);
    }
  }
 @javax.ejb.TransactionAttribute(javax.ejb.TransactionAttributeType.SUPPORTS)
 private boolean isOwner(User u, Attachment a) {
   for (User usr : a.getUser()) {
     if (usr.getId().equals(u.getId())) {
       if (log.isTraceEnabled()) {
         log.trace("<< isOwner(): true // owner of the file");
       }
       return true;
     }
   }
   if (log.isTraceEnabled()) {
     log.trace("<< isOwner(): false");
   }
   return false;
 }
  @Override
  public Attachment shareFile(Long attachmentId, long who, Long with) {
    if (log.isTraceEnabled()) {
      log.trace(">> shareFile(): attachmentId=" + attachmentId + ", who=" + who + ", with=" + with);
    }

    Attachment att = em.find(Attachment.class, attachmentId);
    if (att == null) {
      if (log.isTraceEnabled()) {
        log.trace("<< shareFile(): null - no such attachment");
      }
      return null;
    }
    boolean canShare = false;
    try {
      // canShare |= um.isAdmin(who);
      User actor = em.find(User.class, who);
      if (actor != null && actor.getUserGroup() == 1) {
        canShare = true;
      }
    } catch (Exception ex) {
    }
    if (!canShare) {
      for (User u : att.getUser()) {
        if (u.getId() == who) {
          canShare = true;
          break;
        }
      }
    }
    if (!canShare) {
      if (log.isTraceEnabled()) {
        log.trace("<< shareFile(): null - operation is not permitted");
      }
      return null;
    }
    User w = em.find(User.class, with);
    if (w == null) {
      if (log.isTraceEnabled()) {
        log.trace("<< shareFile(): cannot share with nobody, and owners list was not modified");
      }
      return att;
    }
    att.getUser().add(w);
    em.persist(att);

    return att;
  }
  public static Result getUserGifts(String userId) {
    if (!Utils.checkCredentials(request())) {
      return unauthorized();
    }
    try {
      User user = UserDAO.getInstance().findUserById(userId);
      ObjectNode result = Json.newObject();
      ArrayNode resultArr = new ArrayNode(JsonNodeFactory.instance);
      for (UserGiftMap userGiftMap : user.getWonGifts())
        resultArr.add(GiftDAO.getInstance().findGiftById(userGiftMap.getGiftId()).toJson());

      result.put("gifts", resultArr);
      return ok(result);
    } catch (Exception e) {
      return generateInternalServer(e.getMessage());
    }
  }
 private Attachment prepareAttachment(
     String fileName, String contentType, User user, byte[] contents, String tags) {
   try {
     Attachment a = new Attachment();
     a.setName(fileName);
     a.setMimeType(contentType);
     File root = new File(DEFAULT_UPLOAD_DIRECTORY, user.getLogin());
     root.mkdirs();
     File tmpFile = File.createTempFile("upload_", ".bin", root);
     FileUtils.writeToFile(tmpFile, contents);
     a.setSize((long) contents.length);
     a.setMD5(FileUtils.getMD5(tmpFile));
     a.setFileName(user.getLogin() + "/" + tmpFile.getName());
     return a;
   } catch (Exception ex) {
     return null;
   }
 }
  @Override
  public Attachment renameAttachment(Long userId, long attachmentId, String name) {
    if (log.isDebugEnabled()) {
      log.debug(">> renameAttachment() : userId =" + userId + ", attachmentId=" + attachmentId);
    }
    if (userId == null) {
      if (log.isTraceEnabled()) {
        log.trace("<< renameAttachment() : null // operation is not permitted");
      }
      return null;
    }

    User u = em.find(User.class, userId);
    if (u == null) {
      if (log.isTraceEnabled()) {
        log.trace("<< renameAttachment() : null // no such user! operation is not permitted");
      }
      return null;
    }
    Attachment att = em.find(Attachment.class, attachmentId);
    if (att == null) {
      if (log.isTraceEnabled()) {
        log.trace("<< renameAttachment() : null // invalid attachmentId=" + attachmentId);
      }
      return null;
    }
    if (!isOwner(u, att) && u.getUserGroup() != User.ADMIN) {
      if (log.isTraceEnabled()) {
        log.trace("<< renameAttachment() : null // operation is not permitted");
      }
      return null;
    }
    att.setName(name);
    if (log.isDebugEnabled()) {
      log.debug(">> renameAttachment() : userId =" + userId + ", attachmentId=" + attachmentId);
    }
    return em.merge(att);
  }
  @Override
  public void contextInitialized(ServletContextEvent sce) {
    Map<String, String> env = System.getenv();
    // If we are running in the OPENSHIFT environment change the pu-name
    if (env.keySet().contains("OPENSHIFT_MYSQL_DB_HOST")) {
      PU_NAME = "PU_OPENSHIFT";
    }
    try {
      ServletContext context = sce.getServletContext();
      EntityManagerFactory emf =
          Persistence.createEntityManagerFactory(DeploymentConfiguration.PU_NAME);
      EntityManager em = emf.createEntityManager();

      // This flag is set in Web.xml -- Make sure to disable for a REAL system
      boolean makeTestUsers =
          context.getInitParameter("makeTestUsers").toLowerCase().equals("true");
      if (!makeTestUsers
          || (em.find(User.class, "user") != null
              && em.find(User.class, "admin") != null
              && em.find(User.class, "user_admin") != null)) {
        return;
      }
      Role userRole = new Role("User");
      Role adminRole = new Role("Admin");

      User user = new User("user", PasswordHash.createHash("test"));
      User admin = new User("admin", PasswordHash.createHash("test"));
      User both = new User("user_admin", PasswordHash.createHash("test"));
      user.AddRole(userRole);
      admin.AddRole(adminRole);
      both.AddRole(userRole);
      both.AddRole(adminRole);

      try {
        em.getTransaction().begin();
        em.persist(userRole);
        em.persist(adminRole);

        em.persist(user);
        em.persist(admin);
        em.persist(both);
        em.getTransaction().commit();
      } finally {
        em.close();
      }
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
      Logger.getLogger(DeploymentConfiguration.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Exemple #14
0
 public String doDeleteUser(User e) {
   dao.delete(e.getId());
   return "listUser.xhtml";
 }
  private Attachment prepareAttachment(User user, List<ReshakaUploadedFile> files, String tags) {
    if (files.isEmpty()) {
      if (log.isDebugEnabled()) {
        log.debug("prepareAttachment() : List of files is empty! Nothing to compress.");
      }
      return null;
    }
    if (files.size() == 1) {
      if (log.isTraceEnabled()) {
        log.trace(
            "prepareAttachment() : Single file is being uploaded. Delegating to uploadFile()");
      }
      try {
        return prepareAttachment(
            files.get(0).getFileName(),
            files.get(0).getContentType(),
            user,
            files.get(0).getContents(),
            tags);
      } catch (IOException ex) {
        if (log.isTraceEnabled()) {
          log.trace("prepareAttachment() : I/O exception" + ex);
        }
        return null;
      }
    }

    try {
      // create zip file
      log.trace("prepareAttachment(): Creating zip-file");

      File root = new File(DEFAULT_UPLOAD_DIRECTORY, user.getLogin());
      root.mkdirs();
      File file = File.createTempFile("upload_", ".zip", root);
      try (ZipOutputStream zos = new ZipOutputStream(file)) {
        zos.setEncoding("utf-8");
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(Deflater.BEST_COMPRESSION);

        for (ReshakaUploadedFile uf : files) {
          addFileToZip(zos, uf, uf.getFileName());
        }
      }

      if (log.isDebugEnabled()) {
        log.debug("prepareAttachment(): Files are saved at " + file);
      }

      if (file.length() > MAX_ZIP_SIZE) {
        file.delete();
        throw new IOException("File too large.");
      }

      // Create attachment
      Attachment att = new Attachment();
      att.setName(file.getName());
      att.setMimeType("application/zip");
      att.setSize(file.length());
      att.setMD5(FileUtils.getMD5(file));
      att.setFileName(user.getLogin() + "/" + file.getName());

      if (log.isTraceEnabled()) {
        log.trace("<< prepareAttachment()");
      }
      return att;
    } catch (IOException ex) {
      log.error("prepareAttachment(): Failed to upload files. ", ex);
      return null;
    }
  }
  /** Checks if user has the right to download specified attachment */
  @javax.ejb.TransactionAttribute(javax.ejb.TransactionAttributeType.SUPPORTS)
  private boolean checkDownloadRights(User u, Attachment a) {
    if (log.isTraceEnabled()) {
      log.trace(">> checkDownloadRights(): user="******"SELECT u FROM User u WHERE u.avatarId = :avatarId", User.class);
    q.setParameter("avatarId", a.getId());
    List<User> lst = q.getResultList();
    if (lst != null && !lst.isEmpty()) {
      if (log.isTraceEnabled()) {
        log.trace("<< checkDownloadRights(): true // this is an avatar");
      }
      return true;
    }

    if (a == null) {
      if (log.isTraceEnabled()) {
        log.trace("<< checkDownloadRights(): false // attachment = null");
      }
      return false;
    }

    // do check if it is a problem statement
    q = em.createQuery("SELECT o FROM Order o WHERE o.conditionId = :conditionId", Order.class);
    q.setParameter("conditionId", a.getId());
    lst = q.getResultList();
    if (lst != null && !lst.isEmpty()) {
      if (log.isTraceEnabled()) {
        log.trace("<< checkDownloadRights(): true // this is a problem statement");
      }
      return true;
    }

    // do check if it is a solution to closed order
    q =
        em.createQuery(
            "SELECT o FROM Order o WHERE o.solutionId = :solutionId and o.status in :statuses",
            Order.class);
    q.setParameter("solutionId", a.getId());
    q.setParameter(
        "statuses",
        new ArrayList() {
          {
            add(Order.CLOSED_OFFLINE_ORDER_STATUS);
            add(Order.FULL_PAYED_OFFLINE_ORDER_STATUS);
            add(Order.EXPIRED_OFFLINE_ORDER_STATUS);
            add(Order.EXPIRED_ONLINE_ORDER_STATUS);
          }
        });
    lst = q.getResultList();
    if (lst != null && !lst.isEmpty()) {
      if (log.isTraceEnabled()) {
        log.trace("<< checkDownloadRights(): true // this is a problem statement");
      }
      return true;
    }

    if (u == null) {
      // guest tries to download file (not condition or avatar)
      if (log.isTraceEnabled()) {
        log.trace("<< checkDownloadRights(): false // user = null");
      }
      return false;
    }

    // Admin ?
    if (u.getUserGroup() == 1) {
      return true;
    }

    try {
      // check whether the requestor is owner of the file
      if (log.isTraceEnabled()) {
        log.trace("checkDownloadRights(): file owners >> " + a.getUser().size());
      }
      if (isOwner(u, a)) return true;
    } catch (Exception ex) {
      if (log.isTraceEnabled()) {
        log.trace("checkDownloadRights(): false // exception while processing owners list", ex);
      }
      return false;
    }

    // we might as well return false...
    if (log.isTraceEnabled()) {
      log.trace("<< checkDownloadRigths(): false");
    }
    return false;
  }