Ejemplo n.º 1
0
 // update standard user when they edit their account details
 // This method uses JDBCTemplate, a spring class used to reduce the amount of code needed to run
 // queries
 @Override
 public void updateUser(User user, String oldUserID) throws SQLException {
   String query =
       "UPDATE users SET user_id = ?, first_name = ?, last_name = ?, account_type = ?, email = ?, password = AES_ENCRYPT(?,'.key.') WHERE user_id = ?";
   // String query = "UPDATE users SET user_id = ?, first_name = ?, last_name = ?, account_type =
   // ?, email = ?, password = ? WHERE user_id = ?";
   JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
   System.out.println(
       "UPDATE users SET user_id = "
           + user.getUserID()
           + ", first_name = "
           + user.getFirstName()
           + ", last_name = "
           + user.getLastName()
           + ", account_type = "
           + user.getAccountType()
           + ", email = "
           + user.getEmail()
           + ", password = "******" WHERE user_id = "
           + oldUserID);
   Object[] args =
       new Object[] {
         user.getUserID(),
         user.getFirstName(),
         user.getLastName(),
         user.getAccountType(),
         user.getEmail(),
         user.getPassword(),
         oldUserID
       };
   jdbcTemplate.update(query, args);
 }
Ejemplo n.º 2
0
  /**
   * p>사용자그룹(tm_usergroup)에서 수정한다.
   *
   * @param groupID
   * @return
   * @throws DataAccessException
   */
  public int updateUser(User user) throws DataAccessException {

    String sql =
        QueryUtil.getStringQuery(
            "admin_sql", "admin.usergroup.updateuser"); // 쿼리 프로퍼티파일의 키값에 해당되는 sql문을 읽어온다.
    // 넘겨받은 파라미터를 세팅한다.

    Map<String, Object> param = new HashMap<String, Object>();
    param.put("userPWD", user.getUserPWD());
    param.put("userName", user.getUserName());
    param.put("groupID", user.getGroupID());
    param.put("userLevel", user.getUserLevel());
    param.put("description", user.getDescription());
    param.put("useYN", user.getUseYN());
    param.put("userID", user.getUserID());
    param.put("isHelper", user.getIsHelper());
    param.put("senderName", user.getSenderName());
    param.put("email", user.getEmail());
    param.put("cellPhone", user.getCellPhone());
    param.put("senderEmail", user.getSenderEmail());
    param.put("senderCellPhone", user.getSenderCellPhone());

    // SQL문이 실행된다.
    return getSimpleJdbcTemplate().update(sql, param);
  }
Ejemplo n.º 3
0
  /* get/create device list entry */
  public static GroupList getGroupList(User user, String groupID, boolean createOK)
      throws DBException {
    // does not return null, if 'createOK' is true

    /* User specified? */
    if (user == null) {
      throw new DBException("User not specified.");
    }
    String accountID = user.getAccountID();
    String userID = user.getUserID();

    /* group exists? */
    if (StringTools.isBlank(groupID)) {
      throw new DBException("DeviceGroup ID not specified.");
    } else if (!DeviceGroup.exists(accountID, groupID)) {
      throw new DBException("DeviceGroup does not exist: " + accountID + "/" + groupID);
    }

    /* create/save record */
    GroupList.Key grpListKey = new GroupList.Key(accountID, userID, groupID);
    if (grpListKey.exists()) { // may throw DBException
      // already exists
      GroupList listItem = grpListKey.getDBRecord(true);
      listItem.setUser(user);
      return listItem;
    } else if (createOK) {
      GroupList listItem = grpListKey.getDBRecord();
      listItem.setCreationDefaultValues();
      listItem.setUser(user);
      return listItem;
    } else {
      // record doesn't exist, and caller doesn't want us to create it
      return null;
    }
  }
Ejemplo n.º 4
0
  /** Web service operation */
  @WebMethod(operationName = "getUserByToken")
  @WebResult(name = "User")
  public User getUserByToken(@WebParam(name = "token") String token) {
    User user = new User();
    try {
      Statement stmt = conn.createStatement();
      String sql;
      sql = "SELECT user_id FROM token WHERE token_id = ?";
      PreparedStatement dbStatement = conn.prepareStatement(sql);
      dbStatement.setString(1, token);
      ResultSet rs = dbStatement.executeQuery();

      while (rs.next()) {
        user.setUserID(rs.getInt("user_id"));
      }
      rs.close();

      String sql2 = "SELECT * FROM user WHERE user_id = ?";
      PreparedStatement dbStatement2 = conn.prepareStatement(sql);
      dbStatement2.setInt(1, user.getUserID());
      ResultSet rs2 = dbStatement2.executeQuery();

      while (rs2.next()) {
        user.setName(rs.getString("name"));
        user.setEmail(rs.getString("email"));
        user.setPassword(rs.getString("password"));
      }
      rs2.close();
      stmt.close();
    } catch (SQLException ex) {
      Logger.getLogger(UserWS.class.getName()).log(Level.SEVERE, null, ex);
    }

    return user;
  }
Ejemplo n.º 5
0
  // creates a standard user based on user input
  // uses traditional JDBC code
  // AES_ENCRYPT is a way to encrypt your data when entering it into the database; its arguments are
  // the field to encrypt followed by a programmer-selected key
  @Override
  public void register(User user) throws SQLException {
    String query = "INSERT INTO users VALUES (?,?,?,?,?,AES_ENCRYPT(?,'.key.'),'standard')";
    PreparedStatement pstmt = dataSource.getConnection().prepareStatement(query);
    // setString fills in values of each question mark
    pstmt.setString(1, user.getUserID());
    pstmt.setString(2, user.getFirstName());
    pstmt.setString(3, user.getLastName());
    pstmt.setString(4, user.getAccountType());
    pstmt.setString(5, user.getEmail());
    pstmt.setString(6, user.getPassword());
    pstmt.executeUpdate();

    // Automatically create timeline as well
    // get database connection
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
    // Get the Bean from spring.xml
    TimelineDAO tlDao = ctx.getBean("timelineDao", TimelineDAO.class);
    tlDao.createTimeline(user.getUserID());
  }
 /** 初始化 */
 public JTableAdminModel() {
   List<User> userList = usrSvc.get(0, usrSvc.getNums("1"));
   tbData = new Object[userList.size()][tbHeader.length];
   highLightRow = new String[userList.size()];
   SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
   for (int i = 0; i < userList.size(); ++i) {
     User u = userList.get(i);
     tbData[i][0] = String.valueOf(u.getUserID());
     tbData[i][1] = u.getUsername();
     tbData[i][2] = u.getPassword();
     tbData[i][3] = rleSvc.get(u.getRoleID()).getTitle();
     tbData[i][4] = sf.format(u.getRegisteDate());
     tbData[i][5] = sf.format(u.getLastLoginDate());
     highLightRow[i] = "";
   }
   System.out.println("jam inited..");
 }
Ejemplo n.º 7
0
 public Account(User user, double balance, Type type) {
   this.type = type;
   this.user = user;
   this.balance = balance;
   this.joinUserID = user.getUserID();
 }
Ejemplo n.º 8
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");

    HttpSession session = request.getSession();
    String email = session.getAttribute("email").toString();
    DatabaseService db = new DatabaseService();
    User user = db.findUserByEmail(email);

    String lat = request.getParameter("lat");
    String lon = request.getParameter("lon");
    lat = request.getSession().getAttribute("lat").toString();
    lon = request.getSession().getAttribute("lon").toString();
    int placeId = 0;
    placeId = db.findPlaceByLatLon(lat, lon);

    Calendar cal = Calendar.getInstance();
    java.sql.Timestamp timestamp = new java.sql.Timestamp(cal.getTimeInMillis());

    String fileName = null;
    String storyTime = null;
    String placeName = null;
    String tags = null;
    Story story = new Story();
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {

      DiskFileItemFactory factory = new DiskFileItemFactory();
      // sets memory threshold - beyond which files are stored in disk
      factory.setSizeThreshold(MEMORY_THRESHOLD);
      // sets temporary location to store files
      factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

      ServletFileUpload upload = new ServletFileUpload(factory);

      // sets maximum size of upload file
      upload.setFileSizeMax(MAX_FILE_SIZE);

      // sets maximum size of request (include file + form data)
      upload.setSizeMax(MAX_REQUEST_SIZE);

      // constructs the directory path to store upload file
      // this path is relative to application's directory
      String uploadPath =
          getServletContext().getRealPath("")
              + File.separator
              + ".."
              + File.separator
              + UPLOAD_DIRECTORY;

      // creates the directory if it does not exist
      File uploadDir = new File(uploadPath);
      if (!uploadDir.exists()) {
        uploadDir.mkdir();
      }

      try {
        // parses the request's content to extract file data
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
          // iterates over form's fields
          for (FileItem item : formItems) {
            // processes only fields that are not form fields
            if (!item.isFormField()) {
              fileName = item.getName();
              if (fileName != null && !fileName.equals("")) {
                fileName = db.pictureNameGenerator();

                File storeFile = new File(uploadPath, fileName);

                // saves the file on disk
                item.write(storeFile);
                request.setAttribute("message", "Upload has been done successfully!");
              }
            } else {
              String fieldname = item.getFieldName();
              String fieldvalue = item.getString();
              if (fieldname.equals("editStory")) story.setContent(fieldvalue);
              else if (fieldname.equals("theme")) story.setThemeId(Integer.parseInt(fieldvalue));
              else if (fieldname.equals("editStime")) storyTime = fieldvalue;
              else if (fieldname.equals("placeName")) placeName = fieldvalue;
              else if (fieldname.equals("tags")) tags = fieldvalue;
            }
          }
        }
      } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
      }

    } else {

      story.setContent(request.getParameter("editStory").toString());
      story.setThemeId(Integer.parseInt(request.getParameter("theme")));

      storyTime = request.getParameter("editStime");
    }
    story.setUserId(user.getUserID());
    story.setIsDeleted(0);
    story.setReportCount(0);
    story.setAvgRate(0);
    story.setCreatedOn(timestamp);
    story.setUpdatedOn(timestamp);

    if ((storyTime != null) && isValidDate(storyTime)) {
      story.setdateisAbsolute(true);
      try {
        story.setAbsoluteDateString(storyTime);
      } catch (ParseException e) {
        e.printStackTrace();
      }
      story.setApproximateDate("");
    } else {
      story.setdateisAbsolute(false);
      story.setApproximateDate(storyTime);
    }

    if (!(placeId > 0)) {
      placeId = db.insertPlace(placeName, lon, lat);
    }
    // add story to database and get added story id
    int storyId = db.addStory(story);

    if ((storyId != 0) && (placeId != 0)) {
      // gamification
      // Adding new story = +10 points
      db.gamification(user.getUserID(), 10, -1, 0);
      // add tags to database and get added tags ids
      if (tags != null && !tags.equals("")) {
        ArrayList<String> tagIds = db.insertTags(tags);
        db.insertTagStoryConnection(tagIds, storyId);
        db.insertTagPlaceConnection(tagIds, placeId);
      }
      if (db.addStoryAndPlace(storyId, placeId)) {
        request.setAttribute("error", "true");
        request.setAttribute("message", "Story is added.");
        request.getRequestDispatcher("index.jsp").forward(request, response);
        if (fileName != null && !fileName.equals("")) {
          int pictureId = db.insertPhoto(fileName);
          db.insertPhotoStoryConnection(storyId, pictureId);
        }

      } else {
        request.setAttribute("error", "true");
        request.setAttribute("message", "StoriesInPlaces error.");
        request.getRequestDispatcher("index.jsp").forward(request, response);
      }
    } else {

      request.setAttribute("error", "true");
      request.setAttribute("message", "Sorry, Something went wrong.");
      request.getRequestDispatcher("index.jsp").forward(request, response);
    }
  }