예제 #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);
 }
 /* (non-Javadoc)
  * @see gov.nih.nci.security.dao.SearchCriteria#getFieldAndValues()
  */
 public Hashtable getFieldAndValues() {
   // TODO Auto-generated method stub
   Hashtable ht = new Hashtable();
   if (user.getLoginName() != null) {
     ht.put("loginName", user.getLoginName());
   }
   if (user.getPreMigrationLoginName() != null) {
     ht.put("preMigrationLoginName", user.getPreMigrationLoginName());
   }
   if (user.getLastName() != null) {
     ht.put("lastName", getEncryptedString(user.getLastName()));
   }
   if (user.getFirstName() != null) {
     ht.put("firstName", getEncryptedString(user.getFirstName()));
   }
   if (user.getOrganization() != null) {
     ht.put("organization", getEncryptedString(user.getOrganization()));
   }
   if (user.getDepartment() != null) {
     ht.put("department", getEncryptedString(user.getDepartment()));
   }
   if (user.getEmailId() != null) {
     ht.put("emailId", getEncryptedString(user.getEmailId()));
   }
   if (ht.size() == 0) {
     ht.put("loginName", "%");
   }
   return ht;
 }
예제 #3
0
  /**
   * Validation de l'object m�tier User.<br>
   * Les r�gles sont les suivantes:
   *
   * <ul>
   *   <li>le login est obligatoire
   *   <li>le login est unique
   *   <li>le mot de passse est obligatoire
   *   <li>le nom est obligatoire
   *   <li>le pr�nom est obligatoire
   *   <li>l'email est obligatoire
   *   <li>Le login doit avoir entre 5 et 10 carat�res.
   *   <li>Le mot de passe doit avoir entre 5 et 10 caract�res.
   *   <li>Le format de l'adresse email doit �tre valide
   * </ul>
   *
   * @param object user � valider
   */
  public Errors validate(final Object object) {

    User user = (User) object;

    Errors errors = CoreObjectFactory.getErrors();

    if (user.getLogin() == null || user.getLogin().trim() == "") {

      errors.rejectValue("login", "user.loginMandatory");

    } else if (user.getLogin().length() < 5 || user.getLogin().length() > 10) {

      // le login doit avoir entre 5 et 10 caract�res
      errors.rejectValue("login", "user.loginIncorrectSize");

    } else if (user.getPersistanceId() == 0
        && userRepository.findUserByLogin(user.getLogin()) != null) {

      // le login doit �tre unique
      errors.rejectValue("login", "user.loginAlreadyExists");
    }

    if (user.getPassword() == null || user.getPassword().trim() == "") {

      errors.rejectValue("password", "user.passwordMandatory");

    } else if (user.getPassword().length() < 5 || user.getPassword().length() > 10) {

      // le password doit avoir entre 5 et 10 caract�res
      errors.rejectValue("password", "user.passwordIncorrectSize");
    }

    if (user.getLastName() == null || user.getLastName().trim() == "") {

      errors.rejectValue("lastName", "user.lastNameMandatory");
    }

    if (user.getFirstName() == null || user.getFirstName().trim() == "") {

      errors.rejectValue("firstName", "user.firstNameMandatory");
    }

    if (user.getEmail() == null || user.getEmail().trim() == "") {

      errors.rejectValue("email", "user.emailMandatory");

    } else if (!EmailValidator.getInstance().isValid(user.getEmail())) {

      // Le format de l'adresse email doit �tre valide

      errors.rejectValue("email", "user.incorrectEmail");
    }

    return errors;
  }
예제 #4
0
  public void addUser(User toAdd) {
    connect();
    try {
      // Create a stmt object
      stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

      // Query the database, storing the result
      // in an object of type ResultSet
      rs =
          stmt.executeQuery(
              "SELECT * from User WHERE "
                  + "FirstName='"
                  + toAdd.getFirstName()
                  + "' AND "
                  + "LastName='"
                  + toAdd.getLastName()
                  + "' AND "
                  + "Email='"
                  + toAdd.getEmail()
                  + "'");

      // Check if User is already in the database
      while (rs.next()) {
        System.out.println("User already exists in DB.");
        disconnect();
        return;
      } // end while loop

      digest = MessageDigest.getInstance("MD5");
      byte[] byteArray = toAdd.getPassword().getBytes();
      digest.update(byteArray);
      // digest.digest( );
      byte[] md5sum = digest.digest();
      BigInteger bigInt = new BigInteger(1, md5sum);
      String md5 = bigInt.toString(16);

      stmt.executeUpdate(
          "INSERT INTO User(FirstName, LastName, Email, "
              + "Password) VALUES ('"
              + toAdd.getFirstName()
              + "', '"
              + toAdd.getLastName()
              + "', '"
              + toAdd.getEmail()
              + "', '"
              + md5
              + "')");
    } catch (Exception e) {
      e.printStackTrace();
    } // end catch
    finally {
      disconnect();
    }
  }
  /**
   * Un boolean qui permet de dire si la requête a été envoyé ou reçue et qui permet d'initialiser
   * l'utilisateur user
   */
  public FriendRequest(User sender, User receiver, boolean isReceived) {

    received = isReceived;
    setSent(!received);

    if (received) user = receiver;
    else user = sender;

    senderID = sender.getId();
    receiverID = receiver.getId();
    senderName = sender.getFirstName() + " " + sender.getLastName();
    receiverName = receiver.getFirstName() + " " + receiver.getLastName();
  }
예제 #6
0
  @RequestMapping(value = "/kkn1234/create", method = RequestMethod.POST)
  public String formSubmit(@ModelAttribute User user, Model model)
      throws MalformedURLException, IOException {
    model.addAttribute("user", user);
    HttpPost post =
        new HttpPost(
            "http://ec2-52-4-138-196.compute-1.amazonaws.com/magento/index.php/customer/account/createpost/");
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient =
        HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("firstname", user.getFirstName()));
    nameValuePairs.add(new BasicNameValuePair("lastname", user.getLastName()));
    nameValuePairs.add(new BasicNameValuePair("email", user.getEmail()));
    nameValuePairs.add(new BasicNameValuePair("password", user.getPassword()));
    nameValuePairs.add(new BasicNameValuePair("confirmation", user.getConfirmation()));

    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(post);
    response = httpclient.execute(post);
    System.out.println("Status code is " + response.getStatusLine().getStatusCode());
    System.out.println(response.toString());
    System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++");
    System.out.println(response.getFirstHeader("Location"));
    HttpEntity entity = response.getEntity();
    EntityUtils.consume(entity);
    EntityUtils.consume(response.getEntity());

    /*File newTextFile = new File("C:\\Users\\Kris\\Desktop\\temp.html");
    FileWriter fileWriter = new FileWriter(newTextFile);
    fileWriter.write(response.toString());
    fileWriter.close();*/
    return "result";
  }
예제 #7
0
  @Test
  public void updateTest() {
    User user = getUser(UserRole.ROLE_ORG_USER, UserRole.ROLE_GROUP_USER);
    user.setLastName("Tester");

    user = userService.getByEmail(user.getEmail());
    userService.update(user);
    assertEquals(user.getLastName(), "Tester");
  }
예제 #8
0
 @Test
 public void List_Keys() {
   User u =
       where(user.firstName.eq("Jaakko")).list(user.firstName, user.mainAddress().street).get(0);
   assertEquals("Jaakko", u.getFirstName());
   assertNull(u.getLastName());
   assertEquals("Aakatu", u.getMainAddress().street);
   assertNull(u.getMainAddress().postCode);
 }
 // User local Database constructor
 public void storeUserData(User user) {
   SharedPreferences.Editor spEditor = userLocalDatabase.edit();
   spEditor.putString("username", user.getUsername());
   spEditor.putString("password", user.getPassword());
   spEditor.putString("email", user.getEmail());
   spEditor.putString("lastname", user.getLastName());
   spEditor.putString("firstname", user.getFirstName());
   spEditor.apply();
 }
예제 #10
0
 @Override
 public void onBindViewHolder(ViewHolder viewHolder, int position) {
   Photo photo = mPhotos.get(position);
   User user = photo.getUser();
   Picasso.with(mContext).load(photo.getFile()).into(viewHolder.mPhoto);
   viewHolder.mCaption.setText(photo.getDescription());
   viewHolder.mUsername.setText(user.getFirstName() + " " + user.getLastName());
   Picasso.with(mContext).load(user.getAvatarURL()).into(viewHolder.mAvatar);
 }
예제 #11
0
 public void save(OutputStream outputStream) throws Exception {
   PrintWriter pw = new PrintWriter(outputStream);
   for (User us : users) {
     pw.println(us.getFirstName());
     pw.println(us.getLastName());
     pw.println(us.getBirthDate().getTime());
     pw.println(us.isMale());
     pw.println(us.getCountry().toString());
   }
   pw.close();
 }
예제 #12
0
    @Override
    protected void update(final int position, final User user) {

        Picasso.with(BootstrapApplication.getInstance())
                .load(user.getAvatarUrl())
                .placeholder(R.drawable.gravatar_icon)
                .into(imageView(0));

        setText(1, String.format("%1$s %2$s", user.getFirstName(), user.getLastName()));

    }
 private void printUserInformation(PrintWriter out, User user) {
   out.println("<table>");
   out.println("<tr><th>username</th>");
   out.println("<th>user first name</th>");
   out.println("<th>user last name</th>");
   out.println("<th>user E-mail</th></tr>");
   out.println("<tr><td>" + user.getUserName() + "</td>");
   out.println("<td>" + user.getFirstName() + " </td>");
   out.println("<td>" + user.getLastName() + "</td>");
   out.println("<td>" + user.getEmail() + "</td></tr>");
   out.println("</table>");
 }
예제 #14
0
 @Override
 public void check(User user) {
   Preconditions.checkNotNull(user);
   Preconditions.checkNotNull(user.getCreateDate());
   Preconditions.checkNotNull(user.getFirstName());
   Preconditions.checkNotNull(user.getLastName());
   Preconditions.checkNotNull(user.getEmail());
   Preconditions.checkNotNull(user.getUsername());
   Preconditions.checkNotNull(user.getPassword());
   Preconditions.checkState(user.getUsername().length() >= 1);
   Preconditions.checkState(user.getPassword().length() >= 1);
 }
예제 #15
0
  @Test
  public void testDeserialization() throws Exception {
    final InputStream stream = getClass().getResourceAsStream("/project/project-user.json");
    final User user = new ObjectMapper().readValue(stream, User.class);

    assertThat(user, notNullValue());
    assertThat(user.getEmail(), is("*****@*****.**"));
    assertThat(user.getFirstName(), is("ateam"));
    assertThat(user.getUserRoles(), hasItem("/gdc/projects/PROJECT_ID/roles/ROLE1"));
    assertThat(user.getPhoneNumber(), is("123456789"));
    assertThat(user.getStatus(), is("ENABLED"));
    assertThat(user.getLastName(), is("ads-testing"));
    assertThat(user.getLogin(), is("*****@*****.**"));
  }
예제 #16
0
  public static UserSoap toSoapModel(User model) {
    UserSoap soapModel = new UserSoap();

    soapModel.setMvccVersion(model.getMvccVersion());
    soapModel.setUuid(model.getUuid());
    soapModel.setUserId(model.getUserId());
    soapModel.setCompanyId(model.getCompanyId());
    soapModel.setCreateDate(model.getCreateDate());
    soapModel.setModifiedDate(model.getModifiedDate());
    soapModel.setDefaultUser(model.getDefaultUser());
    soapModel.setContactId(model.getContactId());
    soapModel.setPassword(model.getPassword());
    soapModel.setPasswordEncrypted(model.getPasswordEncrypted());
    soapModel.setPasswordReset(model.getPasswordReset());
    soapModel.setPasswordModifiedDate(model.getPasswordModifiedDate());
    soapModel.setDigest(model.getDigest());
    soapModel.setReminderQueryQuestion(model.getReminderQueryQuestion());
    soapModel.setReminderQueryAnswer(model.getReminderQueryAnswer());
    soapModel.setGraceLoginCount(model.getGraceLoginCount());
    soapModel.setScreenName(model.getScreenName());
    soapModel.setEmailAddress(model.getEmailAddress());
    soapModel.setFacebookId(model.getFacebookId());
    soapModel.setLdapServerId(model.getLdapServerId());
    soapModel.setOpenId(model.getOpenId());
    soapModel.setPortraitId(model.getPortraitId());
    soapModel.setLanguageId(model.getLanguageId());
    soapModel.setTimeZoneId(model.getTimeZoneId());
    soapModel.setGreeting(model.getGreeting());
    soapModel.setComments(model.getComments());
    soapModel.setFirstName(model.getFirstName());
    soapModel.setMiddleName(model.getMiddleName());
    soapModel.setLastName(model.getLastName());
    soapModel.setJobTitle(model.getJobTitle());
    soapModel.setLoginDate(model.getLoginDate());
    soapModel.setLoginIP(model.getLoginIP());
    soapModel.setLastLoginDate(model.getLastLoginDate());
    soapModel.setLastLoginIP(model.getLastLoginIP());
    soapModel.setLastFailedLoginDate(model.getLastFailedLoginDate());
    soapModel.setFailedLoginAttempts(model.getFailedLoginAttempts());
    soapModel.setLockout(model.getLockout());
    soapModel.setLockoutDate(model.getLockoutDate());
    soapModel.setAgreedToTermsOfUse(model.getAgreedToTermsOfUse());
    soapModel.setEmailAddressVerified(model.getEmailAddressVerified());
    soapModel.setLastPublishDate(model.getLastPublishDate());
    soapModel.setStatus(model.getStatus());

    return soapModel;
  }
예제 #17
0
 public void save(OutputStream outputStream) throws Exception {
   BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
   for (User u : users) {
     bufferedWriter.write(u.getFirstName());
     bufferedWriter.newLine();
     bufferedWriter.write(u.getLastName());
     bufferedWriter.newLine();
     bufferedWriter.write(String.valueOf(u.getBirthDate().getTime()));
     bufferedWriter.newLine();
     bufferedWriter.write(String.valueOf(u.isMale()));
     bufferedWriter.newLine();
     bufferedWriter.write(String.valueOf(u.getCountry()));
     bufferedWriter.newLine();
   }
   bufferedWriter.close();
 }
예제 #18
0
 public void addEmergencyProfile(User user) {
   // TODO Auto-generated method stub
   Log.d("addEmergencyProfile", user.toString());
   // 1. get reference to writable DB
   SQLiteDatabase db = this.getWritableDatabase();
   // 2. create ContentValues to add key "column"/value
   ContentValues values = new ContentValues();
   values.put(KEY_FIRST_NAME, user.getFirstName()); // get firstName
   values.put(KEY_LAST_NAME, user.getLastName()); // get lastName
   values.put(KEY_PHONE, user.getPhoneNumber()); // get phoneNumber
   values.put(KEY_EMERGENCY, user.getEmergencyNumber()); // get emergencyNumber
   // 3. insert
   db.insert(
       TABLE_USER, // table
       null, // nullColumnHack
       values); // key/value -> keys = column names/values
   // 4. Close dbase
   db.close();
 }
예제 #19
0
  /**
   * Process the specified HTTP request, and create the corresponding HTTP response (or forward to
   * another web component that will create it). Return an <code>ActionForward</code> instance
   * describing where and how control should be forwarded, or <code>null</code> if the response has
   * already been completed.
   *
   * @param mapping The ActionMapping used to select this instance
   * @param form The optional ActionForm bean for this request (if any)
   * @param request The HTTP request we are processing
   * @param response The HTTP response we are creating
   * @exception Exception if business logic throws an exception
   */
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    // Extract attributes we will need
    MessageResources messages = getResources(request);

    // save errors
    ActionMessages errors = new ActionMessages();

    // START check for login (security)
    if (!SecurityService.getInstance().checkForLogin(request.getSession(false))) {
      return (mapping.findForward("welcome"));
    }
    // END check for login (security)

    // get the current user for displaying personal info, such as "My Projects"
    User u =
        UserService.getInstance()
            .getSingleUser((String) request.getSession(false).getAttribute("username"));
    System.out.println(
        "local addresss sssssssssssssss"
            + request.getLocalAddr()
            + "          "
            + request.getLocalName());
    long startProjects = System.currentTimeMillis();
    String myName = u.getFirstName() + " " + u.getLastName();
    List myHr = HrHelper.getAllEmployeesFormer(u);
    long endProjects = System.currentTimeMillis();
    System.out.println("GetMyHrAction took:" + ((endProjects - startProjects) / 1000.0));
    response.setContentType("text/html");
    response.setHeader("Cache-Control", "no-cache");
    // System.out.println(actResponse.toXML());
    PrintWriter out = response.getWriter();
    out.println(new JSONArray(myHr.toArray()));
    out.flush();

    // Forward control to the specified success URI
    return (null);
  }
예제 #20
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());
  }
예제 #21
0
  public static List<ProjectDTO> getAllProject() {
    // Get project list
    List<Project> projectList;
    // retrieve project list from JPA controller
    projectList = ProxyManager.getProjectProxy().getProjectsList();

    ArrayList<ProjectDTO> resList = new ArrayList<ProjectDTO>();
    ProjectDTO projectDTO;
    for (Project p : projectList) {
      projectDTO = new ProjectDTO();
      projectDTO.setName(p.getName());
      projectDTO.setDescription(p.getDescription());
      projectDTO.setStatus(p.getStatus());
      Team team = p.getTeamTeamId();
      if (team != null) {
        TeamDTO teamDTO = new TeamDTO();
        teamDTO.setTeamId(team.getTeamId());
        teamDTO.setProductOwnerId(team.getProductOwnerId());
        teamDTO.setScrumMasterId(team.getScrumMasterId());
        ArrayList<UserDTO> userDTOList = new ArrayList<UserDTO>();
        for (User user : team.getUserList()) {
          UserDTO userDTO = new UserDTO();
          userDTO.setUserId(user.getUserId());
          userDTO.setUsername(user.getUsername());
          userDTO.setPassword(user.getPassword());
          userDTO.setFirstName(user.getFirstName());
          userDTO.setLastName(user.getLastName());
          userDTO.setEmail(user.getEmail());
          userDTO.setAdmin(user.getIsAdmin());
          userDTO.setSalt(user.getSalt());
          userDTO.setActive(user.getIsActive());
          userDTO.setTimeCreated(user.getTimeCreated());
          userDTOList.add(userDTO);
        }
        teamDTO.setUserList(userDTOList);
        projectDTO.setTeamTeamId(teamDTO);
      } else projectDTO.setTeamTeamId(null); // TODO: possible break
      resList.add(projectDTO);
    }
    return resList;
  }
예제 #22
0
  public void createUser(User user) throws InternalErrorException {
    // Create a set of attributes
    Attributes attributes = new BasicAttributes();

    // Create the objectclass to add
    Attribute objClasses = new BasicAttribute("objectClass");
    objClasses.add("top");
    objClasses.add("person");
    objClasses.add("organizationalPerson");
    objClasses.add("inetOrgPerson");
    objClasses.add("perunUser");
    objClasses.add("tenOperEntry");
    objClasses.add("inetUser");

    String firstName = user.getFirstName();
    String lastName = user.getLastName();
    if (firstName == null) firstName = "";
    if (lastName == null || lastName.isEmpty()) lastName = "N/A";

    // Add attributes
    attributes.put(objClasses);
    attributes.put("entryStatus", "active");
    attributes.put("sn", lastName);
    attributes.put("cn", firstName + " " + lastName);
    if (!firstName.isEmpty()) attributes.put("givenName", firstName);
    attributes.put("perunUserId", String.valueOf(user.getId()));
    if (user.isServiceUser()) attributes.put("isServiceUser", "1");
    else attributes.put("isServiceUser", "0");
    if (user.isSponsoredUser()) attributes.put("isSponsoredUser", "1");
    else attributes.put("isSponsoredUser", "0");

    // Create the entry
    try {
      ldapTemplate.bind(getUserDN(String.valueOf(user.getId())), null, attributes);
      log.debug("New entry created in LDAP: User {} in Group with Id=" + user.getId() + ".", user);
    } catch (NameNotFoundException e) {
      throw new InternalErrorException(e);
    }
  }
  public int registerPersonalInfoOfUser(MySqlHelper helper, User user, int userId, int addressId) {
    String query =
        "insert into personalinfo(UserId, AddressId, FirstName, LastName, PhoneNumber) values(?,?,?,?,?)";
    try {
      java.sql.PreparedStatement personalInfoPreparedStatement =
          helper.conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);

      personalInfoPreparedStatement.setInt(1, userId);
      personalInfoPreparedStatement.setInt(2, addressId);
      personalInfoPreparedStatement.setString(3, user.getFirstName());
      personalInfoPreparedStatement.setString(4, user.getLastName());
      personalInfoPreparedStatement.setString(5, user.getPhoneNumber());

      personalInfoPreparedStatement.executeUpdate();
      ResultSet rs = personalInfoPreparedStatement.getGeneratedKeys();
      if (rs.next()) {
        int last_inserted_id = rs.getInt(1);
        return last_inserted_id;
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return -1;
  }
예제 #24
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // Loginse user bilgilerini al, textboxlari readonly yap, degilse textboxtakileri al

    User user = (User) request.getSession().getAttribute("user");
    if (user == null) {

      String name = request.getParameter("reservation-name");
      String lastName = request.getParameter("reservation-lastname");
      String email = request.getParameter("reservation-email");
      String phone = request.getParameter("reservation-phone");

    } else {
      String name = user.getFirstName();
      String lastName = user.getLastName();
      String email = user.getEmail();
      String phone = user.getPhoneNumber();
    }

    Address pickup = new Address();
    pickup.setBuildingNo(Integer.parseInt(request.getParameter("pickupbuilding-no")));
    pickup.setStreet(request.getParameter("pickupstreet"));
    pickup.setCity(request.getParameter("pickuphomecity"));
    pickup.setState(request.getParameter("pickupstate"));
    pickup.setZip(Integer.parseInt(request.getParameter("pickuphomezip")));
    pickup.setCountry(request.getParameter("pickupcountry"));

    Address destination = new Address();
    destination.setBuildingNo(Integer.parseInt(request.getParameter("destinationbuilding-no")));
    destination.setStreet(request.getParameter("destinationstreet"));
    destination.setCity(request.getParameter("destinationhomecity"));
    destination.setState(request.getParameter("destinationstate"));
    destination.setZip(Integer.parseInt(request.getParameter("destinationzip")));
    destination.setCountry(request.getParameter("destinationcountry"));

    int passengerNo = Integer.parseInt(request.getParameter("passenger-no"));
    int luggageNo = Integer.parseInt(request.getParameter("luggage-no"));

    double fareMultiplier = 0;
    String vehicleType = request.getParameter("vehicle-radio");
    if ("sedan".equals(vehicleType)) {
      fareMultiplier = 3;
    } else if ("suv".equals(vehicleType)) {
      fareMultiplier = 5;
    } else if ("blackcar".equals(vehicleType)) {
      fareMultiplier = 4.5;
    }

    ReservationService service = new ReservationService();
    double distance = service.calculateDistance(pickup, destination);
    double initialFare = 10;

    double amount = fareMultiplier * distance + initialFare;
    boolean isPet = false;
    // isPet is going to be retrieved from checkbox

    // boolean isCash = request.getParameter("payment-method");
    boolean isCash = false;

    Payment payment = new Payment(isCash);
    payment.setAmount(amount);

    if (!isCash) {
      if (!payment.isPaid()) {
        // chargeCustormer();
      }
      //	payment.setCredit()

    }

    Reservation reservation = new Reservation();
    reservation.setComment("Write a comment");
  }
예제 #25
0
  /*
   * (non-Javadoc)
   *
   * @see
   * org.openiam.idm.srvc.user.service.UserDataService#getUserAsMap(java.lang
   * .String)
   */
  @Transactional(readOnly = true)
  public Map<String, UserAttribute> getUserAsMap(String userId) {
    User usr = getUser(userId);
    if (usr == null) {
      return null;
    }

    Map<String, UserAttribute> attrMap = getAllAttributes(userId);
    if (attrMap == null) {
      attrMap = new HashMap<String, UserAttribute>();
    }
    // assign the predefined properties

    attrMap.put("USER_ID", new UserAttribute(null, userId, null, "USER_ID", userId));
    attrMap.put(
        "FIRST_NAME", new UserAttribute(null, userId, null, "FIRST_NAME", usr.getFirstName()));
    attrMap.put("LAST_NAME", new UserAttribute(null, userId, null, "LAST_NAME", usr.getLastName()));
    attrMap.put(
        "MIDDLE_INIT",
        new UserAttribute(null, userId, null, "MIDDLE_INIT", String.valueOf(usr.getMiddleInit())));
    attrMap.put("TITLE", new UserAttribute(null, userId, null, "TITLE", usr.getTitle()));
    attrMap.put("DEPT", new UserAttribute(null, userId, null, "DEPT", usr.getDeptCd()));
    attrMap.put(
        "STATUS", new UserAttribute(null, userId, null, "STATUS", usr.getStatus().toString()));
    if (usr.getBirthdate() != null) {
      attrMap.put(
          "BIRTHDATE",
          new UserAttribute(null, userId, null, "BIRTHDATE", usr.getBirthdate().toString()));
    } else {
      attrMap.put("BIRTHDATE", new UserAttribute(null, userId, null, "BIRTHDATE", null));
    }
    attrMap.put("SEX", new UserAttribute(null, userId, null, "SEX", String.valueOf(usr.getSex())));
    if (usr.getCreateDate() != null) {
      attrMap.put(
          "CREATE_DATE",
          new UserAttribute(null, userId, null, "CREATE_DATE", usr.getCreateDate().toString()));
    } else {
      attrMap.put("CREATE_DATE", new UserAttribute(null, userId, null, "CREATE_DATE", null));
    }
    attrMap.put(
        "CREATED_BY", new UserAttribute(null, userId, null, "CREATED_BY", usr.getCreatedBy()));
    if (usr.getLastUpdate() != null) {
      attrMap.put(
          "LAST_UPDATE",
          new UserAttribute(null, userId, null, "LAST_UPDATE", usr.getLastUpdate().toString()));
    } else {
      attrMap.put("LAST_UPDATE", new UserAttribute(null, userId, null, "LAST_UPDATE", null));
    }
    attrMap.put(
        "LAST_UPDATEDBY",
        new UserAttribute(null, userId, null, "LAST_UPDATEDBY", usr.getLastUpdatedBy()));
    attrMap.put("PREFIX", new UserAttribute(null, userId, null, "PREFIX", usr.getPrefix()));
    attrMap.put("SUFFIX", new UserAttribute(null, userId, null, "SUFFIX", usr.getSuffix()));
    attrMap.put(
        "USER_TYPE_IND",
        new UserAttribute(null, userId, null, "USER_TYPE_IND", usr.getUserTypeInd()));
    attrMap.put(
        "EMPLOYEE_ID", new UserAttribute(null, userId, null, "EMPLOYEE_ID", usr.getEmployeeId()));
    attrMap.put(
        "EMPLOYEE_TYPE",
        new UserAttribute(null, userId, null, "EMPLOYEE_TYPE", usr.getEmployeeType()));
    attrMap.put(
        "LOCATION_ID", new UserAttribute(null, userId, null, "LOCATION_ID", usr.getLocationCd()));
    attrMap.put(
        "ORGANIZATION_ID",
        new UserAttribute(null, userId, null, "ORGANIZATION_ID", usr.getCompanyId()));
    attrMap.put(
        "COMPANY_OWNER_ID",
        new UserAttribute(null, userId, null, "COMPANY_OWNER_ID", usr.getCompanyOwnerId()));

    attrMap.put(
        "MANAGER_ID", new UserAttribute(null, userId, null, "MANAGER_ID", usr.getManagerId()));
    attrMap.put("JOB_CODE", new UserAttribute(null, userId, null, "JOB_CODE", usr.getJobCode()));

    return attrMap;
  }
예제 #26
0
  public static ProjectDTO getProjectByName(String name) {
    Project p;
    p = ProxyManager.getProjectProxy().findProjectByName(name);
    if (p != null) {
      ProjectDTO projectDTO = new ProjectDTO();
      projectDTO.setProjectId(p.getProjectId());
      projectDTO.setName(p.getName());
      projectDTO.setDescription(p.getDescription());
      projectDTO.setStatus(p.getStatus());
      Team team = p.getTeamTeamId();
      if (team != null) {
        TeamDTO teamDTO = new TeamDTO();
        teamDTO.setTeamId(team.getTeamId());
        teamDTO.setProductOwnerId(team.getProductOwnerId());
        teamDTO.setScrumMasterId(team.getScrumMasterId());
        ArrayList<UserDTO> userDTOList = new ArrayList<UserDTO>();
        for (User user : team.getUserList()) {
          UserDTO userDTO = new UserDTO();
          userDTO.setUserId(user.getUserId());
          userDTO.setUsername(user.getUsername());
          userDTO.setPassword(user.getPassword());
          userDTO.setFirstName(user.getFirstName());
          userDTO.setLastName(user.getLastName());
          userDTO.setEmail(user.getEmail());
          userDTO.setAdmin(user.getIsAdmin());
          userDTO.setSalt(user.getSalt());
          userDTO.setActive(user.getIsActive());
          userDTO.setTimeCreated(user.getTimeCreated());
          userDTOList.add(userDTO);
        }
        teamDTO.setUserList(userDTOList);
        projectDTO.setTeamTeamId(teamDTO);
      } else projectDTO.setTeamTeamId(null);

      List<SprintDTO> sprintDTOList = new ArrayList<SprintDTO>();
      if (p.getSprintList() != null) {
        for (Sprint s : p.getSprintList()) {
          s = ProxyManager.getSprintProxy().findSprint(s.getSprintPK());
          SprintDTO sprintDTO = new SprintDTO();
          SprintPKDTO sprintPKDTO = new SprintPKDTO();
          sprintPKDTO.setSprintId(s.getSprintPK().getSprintId());
          sprintPKDTO.setProjectProjectId(s.getSprintPK().getProjectProjectId());
          sprintDTO.setSprintPK(sprintPKDTO);
          sprintDTO.setSeqNumber(s.getSeqNumber());
          sprintDTO.setStatus(s.getStatus());
          sprintDTO.setStartDate(s.getStartDate());
          sprintDTO.setEndDate(s.getEndDate());
          sprintDTO.setVelocity(s.getVelocity());
          if (s.getUserStoryList() != null) {
            List<UserStoryDTO> userStoryDTOList = new ArrayList<UserStoryDTO>();
            for (UserStory userStory : s.getUserStoryList()) {
              userStory = ProxyManager.getUserStoryProxy().findUserStory(userStory.getStoryId());
              UserStoryDTO userStoryDTO = new UserStoryDTO();
              userStoryDTO.setStoryId(userStory.getStoryId());
              userStoryDTO.setName(userStory.getName());
              userStoryDTO.setContent(userStory.getContent());
              userStoryDTO.setBusinessValue(userStory.getBusinessValue());
              userStoryDTO.setStatus(userStory.getStatus());
              if (userStory.getEstimateTime() != null) {
                userStoryDTO.setEstimateTime(userStory.getEstimateTime().doubleValue());
              } else userStoryDTO.setEstimateTime(null);
              userStoryDTO.setStoryId(userStory.getStoryId());
              userStoryDTO.setProjectProjectId(projectDTO);
              userStoryDTO.setComment(userStory.getComment());
              userStoryDTO.setSprint(sprintDTO);

              PriorityDTO priorityDTO = new PriorityDTO();
              priorityDTO.setPriorityId(userStory.getPriorityPriorityId().getPriorityId());
              priorityDTO.setName(userStory.getPriorityPriorityId().getName());
              userStoryDTO.setPriorityPriorityId(priorityDTO);

              List<AcceptanceTestDTO> acceptanceTestDTOList = new ArrayList<AcceptanceTestDTO>();
              for (AcceptanceTest at : userStory.getAcceptanceTestList()) {
                AcceptanceTestDTO acceptanceTestDTO = new AcceptanceTestDTO();
                acceptanceTestDTO.setAcceptanceTestId(at.getAcceptanceTestId());
                acceptanceTestDTO.setContent(at.getContent());
                acceptanceTestDTOList.add(acceptanceTestDTO);
              }
              userStoryDTO.setAcceptanceTestList(acceptanceTestDTOList);

              if (userStory.getTaskList() != null) {
                List<TaskDTO> taskDTOList = new ArrayList<TaskDTO>();
                for (Task task : userStory.getTaskList()) {
                  task = ProxyManager.getTaskProxy().findTask(task.getTaskPK());
                  TaskDTO taskDTO = new TaskDTO();
                  taskDTO.setDescription(task.getDescription());
                  taskDTO.setTimeRemaining(task.getTimeRemaining());
                  taskDTO.setEstimatedTime(task.getEstimatedTime());
                  taskDTO.setStatus(task.getStatus());
                  taskDTO.setPreassignedUserName(task.getPreassignedUserName());
                  taskDTO.setAssignedDate(task.getAssignedDate());

                  taskDTO.setUserStory(userStoryDTO);

                  TaskPKDTO taskPKDTO = new TaskPKDTO();
                  taskPKDTO.setTaskId(task.getTaskPK().getTaskId());
                  taskPKDTO.setUserStoryStoryId(task.getTaskPK().getUserStoryStoryId());
                  taskDTO.setTaskPK(taskPKDTO);

                  if (task.getUserUserId() != null) {
                    User user =
                        ProxyManager.getUserProxy().findUser(task.getUserUserId().getUserId());
                    UserDTO userDTO = new UserDTO();
                    userDTO.setUserId(user.getUserId());
                    userDTO.setUsername(user.getUsername());
                    userDTO.setPassword(user.getPassword());
                    userDTO.setFirstName(user.getFirstName());
                    userDTO.setLastName(user.getLastName());
                    userDTO.setEmail(user.getEmail());
                    userDTO.setAdmin(user.getIsAdmin());
                    userDTO.setSalt(user.getSalt());
                    userDTO.setActive(user.getIsActive());
                    userDTO.setTimeCreated(user.getTimeCreated());
                    taskDTO.setUserUserId(userDTO);
                  }

                  List<WorkloadDTO> workloadDTOList = new ArrayList<WorkloadDTO>();
                  for (Workload workload : task.getWorkloadList()) {
                    workload =
                        ProxyManager.getWorkloadProxy().findWorkload(workload.getWorkloadPK());
                    WorkloadDTO workloadDTO = new WorkloadDTO();
                    workloadDTO.setDay(workload.getDay());
                    workloadDTO.setTimeRemaining(workload.getTimeRemaining());
                    workloadDTO.setTimeSpent(workload.getTimeSpent());
                    workloadDTO.setStarted(workload.getStarted());
                    workloadDTO.setStartTime(workload.getStartTime());
                    workloadDTO.setStopTime(workload.getStopTime());

                    User user =
                        ProxyManager.getUserProxy().findUser(workload.getUser().getUserId());
                    UserDTO userDTO = new UserDTO();
                    userDTO.setUserId(user.getUserId());
                    userDTO.setUsername(user.getUsername());
                    userDTO.setPassword(user.getPassword());
                    userDTO.setFirstName(user.getFirstName());
                    userDTO.setLastName(user.getLastName());
                    userDTO.setEmail(user.getEmail());
                    userDTO.setAdmin(user.getIsAdmin());
                    userDTO.setSalt(user.getSalt());
                    userDTO.setActive(user.getIsActive());
                    userDTO.setTimeCreated(user.getTimeCreated());
                    workloadDTO.setUser(userDTO);

                    workloadDTO.setTask(taskDTO);

                    WorkloadPKDTO workloadPKDTO = new WorkloadPKDTO();
                    WorkloadPK workloadPK = workload.getWorkloadPK();
                    workloadPKDTO.setTaskTaskId(workloadPK.getTaskTaskId());
                    workloadPKDTO.setTaskUserStoryStoryId(workloadPK.getTaskUserStoryStoryId());
                    workloadPKDTO.setUserUserId(workloadPK.getUserUserId());
                    workloadPKDTO.setWorkloadId(workloadPK.getWorkloadId());
                    workloadDTO.setWorkloadPK(workloadPKDTO);

                    List<WorkblockDTO> workblockDTOList = new ArrayList<WorkblockDTO>();
                    for (Workblock workblock : workload.getWorkblockList()) {
                      workblock =
                          ProxyManager.getWorkblockProxy()
                              .findWorkblock(workblock.getWorkblockPK());
                      WorkblockDTO workblockDTO = new WorkblockDTO();
                      workblockDTO.setTimeStart(workblock.getTimeStart());
                      workblockDTO.setTimeStop(workblock.getTimeStop());

                      workblockDTO.setWorkload(workloadDTO);

                      WorkblockPKDTO workblockPKDTO = new WorkblockPKDTO();
                      WorkblockPK workblockPK = workblock.getWorkblockPK();
                      workloadPKDTO.setWorkloadId(workblockPK.getWorkloadWorkloadId());
                      workblockPKDTO.setWorkloadTaskTaskId(workloadPK.getTaskTaskId());
                      workblockPKDTO.setWorkloadTaskUserStoryStoryId(
                          workblockPK.getWorkloadTaskUserStoryStoryId());
                      workblockPKDTO.setWorkloadUserUserId(workblockPK.getWorkloadUserUserId());
                      workblockPKDTO.setWorkloadWorkloadId(workblockPK.getWorkloadWorkloadId());
                      workblockDTO.setWorkblockPK(workblockPKDTO);

                      workblockDTOList.add(workblockDTO);
                    }
                    workloadDTO.setWorkblockList(workblockDTOList);

                    workloadDTOList.add(workloadDTO);
                  }
                  taskDTO.setWorkloadList(workloadDTOList);

                  taskDTOList.add(taskDTO);
                }
                userStoryDTO.setTaskList(taskDTOList);
              }
              userStoryDTOList.add(userStoryDTO);
            }
            sprintDTO.setUserStoryList(userStoryDTOList);
          }
          sprintDTOList.add(sprintDTO);
        }
        projectDTO.setSprintList(sprintDTOList);

      } else projectDTO.setSprintList(null);

      List<UserStoryDTO> userStoryDTOList = new ArrayList<UserStoryDTO>();
      if (p.getUserStoryList() != null) {
        for (UserStory us : p.getUserStoryList()) {
          UserStoryDTO userStoryDTO = new UserStoryDTO();
          userStoryDTO.setStoryId(us.getStoryId());
          userStoryDTO.setName(us.getName());
          userStoryDTO.setContent(us.getContent());
          userStoryDTO.setBusinessValue(us.getBusinessValue());
          userStoryDTO.setStatus(us.getStatus());
          if (us.getEstimateTime() != null) {
            userStoryDTO.setEstimateTime(us.getEstimateTime().doubleValue());
          } else userStoryDTO.setEstimateTime(null);
          userStoryDTO.setStoryId(us.getStoryId());
          userStoryDTO.setProjectProjectId(projectDTO);

          PriorityDTO priorityDTO = new PriorityDTO();
          priorityDTO.setPriorityId(us.getPriorityPriorityId().getPriorityId());
          priorityDTO.setName(us.getPriorityPriorityId().getName());
          userStoryDTO.setPriorityPriorityId(priorityDTO);

          List<AcceptanceTestDTO> acceptanceTestDTOList = new ArrayList<AcceptanceTestDTO>();
          for (AcceptanceTest at : us.getAcceptanceTestList()) {
            AcceptanceTestDTO acceptanceTestDTO = new AcceptanceTestDTO();
            acceptanceTestDTO.setAcceptanceTestId(at.getAcceptanceTestId());
            acceptanceTestDTO.setContent(at.getContent());
            acceptanceTestDTOList.add(acceptanceTestDTO);
          }
          userStoryDTO.setAcceptanceTestList(acceptanceTestDTOList);

          // TODO: Set taskList to userStoryDTO
          if (us.getTaskList() != null) {
            List<TaskDTO> taskDTOList = new ArrayList<TaskDTO>();
            for (Task task : us.getTaskList()) {
              task = ProxyManager.getTaskProxy().findTask(task.getTaskPK());
              TaskDTO taskDTO = new TaskDTO();
              taskDTO.setDescription(task.getDescription());
              taskDTO.setTimeRemaining(task.getTimeRemaining());
              taskDTO.setEstimatedTime(task.getEstimatedTime());
              taskDTO.setStatus(task.getStatus());
              taskDTO.setPreassignedUserName(task.getPreassignedUserName());
              taskDTO.setAssignedDate(task.getAssignedDate());

              taskDTO.setUserStory(userStoryDTO);

              TaskPKDTO taskPKDTO = new TaskPKDTO();
              taskPKDTO.setTaskId(task.getTaskPK().getTaskId());
              taskPKDTO.setUserStoryStoryId(task.getTaskPK().getUserStoryStoryId());
              taskDTO.setTaskPK(taskPKDTO);

              if (task.getUserUserId() != null) {
                User user = ProxyManager.getUserProxy().findUser(task.getUserUserId().getUserId());
                UserDTO userDTO = new UserDTO();
                userDTO.setUserId(user.getUserId());
                userDTO.setUsername(user.getUsername());
                userDTO.setPassword(user.getPassword());
                userDTO.setFirstName(user.getFirstName());
                userDTO.setLastName(user.getLastName());
                userDTO.setEmail(user.getEmail());
                userDTO.setAdmin(user.getIsAdmin());
                userDTO.setSalt(user.getSalt());
                userDTO.setActive(user.getIsActive());
                userDTO.setTimeCreated(user.getTimeCreated());
                taskDTO.setUserUserId(userDTO);
              }

              List<WorkloadDTO> workloadDTOList = new ArrayList<WorkloadDTO>();
              for (Workload workload : task.getWorkloadList()) {
                workload = ProxyManager.getWorkloadProxy().findWorkload(workload.getWorkloadPK());
                WorkloadDTO workloadDTO = new WorkloadDTO();
                workloadDTO.setDay(workload.getDay());
                workloadDTO.setTimeRemaining(workload.getTimeRemaining());
                workloadDTO.setTimeSpent(workload.getTimeSpent());

                User user = ProxyManager.getUserProxy().findUser(workload.getUser().getUserId());
                UserDTO userDTO = new UserDTO();
                userDTO.setUserId(user.getUserId());
                userDTO.setUsername(user.getUsername());
                userDTO.setPassword(user.getPassword());
                userDTO.setFirstName(user.getFirstName());
                userDTO.setLastName(user.getLastName());
                userDTO.setEmail(user.getEmail());
                userDTO.setAdmin(user.getIsAdmin());
                userDTO.setSalt(user.getSalt());
                userDTO.setActive(user.getIsActive());
                userDTO.setTimeCreated(user.getTimeCreated());
                workloadDTO.setUser(userDTO);

                workloadDTO.setTask(taskDTO);

                WorkloadPKDTO workloadPKDTO = new WorkloadPKDTO();
                WorkloadPK workloadPK = workload.getWorkloadPK();
                workloadPKDTO.setTaskTaskId(workloadPK.getTaskTaskId());
                workloadPKDTO.setTaskUserStoryStoryId(workloadPK.getTaskUserStoryStoryId());
                workloadPKDTO.setUserUserId(workloadPK.getUserUserId());
                workloadPKDTO.setWorkloadId(workloadPK.getWorkloadId());
                workloadDTO.setWorkloadPK(workloadPKDTO);

                List<WorkblockDTO> workblockDTOList = new ArrayList<WorkblockDTO>();
                for (Workblock workblock : workload.getWorkblockList()) {
                  workblock =
                      ProxyManager.getWorkblockProxy().findWorkblock(workblock.getWorkblockPK());
                  WorkblockDTO workblockDTO = new WorkblockDTO();
                  workblockDTO.setTimeStart(workblock.getTimeStart());
                  workblockDTO.setTimeStop(workblock.getTimeStop());

                  workblockDTO.setWorkload(workloadDTO);

                  WorkblockPKDTO workblockPKDTO = new WorkblockPKDTO();
                  WorkblockPK workblockPK = workblock.getWorkblockPK();
                  workloadPKDTO.setWorkloadId(workblockPK.getWorkloadWorkloadId());
                  workblockPKDTO.setWorkloadTaskTaskId(workloadPK.getTaskTaskId());
                  workblockPKDTO.setWorkloadTaskUserStoryStoryId(
                      workblockPK.getWorkloadTaskUserStoryStoryId());
                  workblockPKDTO.setWorkloadUserUserId(workblockPK.getWorkloadUserUserId());
                  workblockPKDTO.setWorkloadWorkloadId(workblockPK.getWorkloadWorkloadId());
                  workblockDTO.setWorkblockPK(workblockPKDTO);

                  workblockDTOList.add(workblockDTO);
                }
                workloadDTO.setWorkblockList(workblockDTOList);

                workloadDTOList.add(workloadDTO);
              }
              taskDTO.setWorkloadList(workloadDTOList);

              taskDTOList.add(taskDTO);
            }
            userStoryDTO.setTaskList(taskDTOList);
          } else userStoryDTO.setTaskList(null);

          SprintDTO sprintDTO = new SprintDTO();
          if (us.getSprint() != null) {
            SprintPKDTO sprintPKDTO = new SprintPKDTO();
            sprintPKDTO.setSprintId(us.getSprint().getSprintPK().getSprintId());
            sprintPKDTO.setProjectProjectId(us.getSprint().getSprintPK().getProjectProjectId());
            sprintDTO.setSprintPK(sprintPKDTO);
            sprintDTO.setSeqNumber(us.getSprint().getSeqNumber());
            sprintDTO.setStatus(us.getSprint().getStatus());
            sprintDTO.setStartDate(us.getSprint().getStartDate());
            sprintDTO.setEndDate(us.getSprint().getEndDate());
            sprintDTO.setVelocity(us.getSprint().getVelocity());
          } else sprintDTO = null;
          userStoryDTO.setSprint(sprintDTO);
          userStoryDTOList.add(userStoryDTO);
        }
        projectDTO.setUserStoryList(userStoryDTOList);
      }
      return projectDTO;
    } else return null;
  }
예제 #27
0
 @Test
 public void SingleResult_Keys() {
   User u = where(user.firstName.eq("Jaakko")).singleResult(user.firstName);
   assertEquals("Jaakko", u.getFirstName());
   assertNull(u.getLastName());
 }
예제 #28
0
  /**
   * @param userList
   * @return Student Register new student by prompting them for user info
   */
  public static Student registerStudentAccount(LinkedList<User> userList) {
    String username = "";
    String password = "";
    String first = "";
    String last = "";
    String GNum = "";
    String phoneNum = "";
    String email = "";
    String address = "";
    User aStudent = null;

    // prompt for username until available username is entered
    do {
      username = JOptionPane.showInputDialog("Please enter desired username");
      aStudent = validateUsername(username, userList);
      if (aStudent != null) {
        JOptionPane.showMessageDialog(null, "This username is already in use!\nPlease try again");
      }
    } while (aStudent != null);

    // create student object
    aStudent = new Student(username);

    // prompt for password until valid entry is given
    do {
      password = JOptionPane.showInputDialog("Please enter desired password");
      if (!aStudent.setPassword(password)) {
        JOptionPane.showMessageDialog(
            null,
            "Password does not meet requirements. Minimum 8 characters\nTry Again.",
            "Error",
            JOptionPane.ERROR_MESSAGE);
      }
    } while (!aStudent.setPassword(password));

    // prompt for first name until valid entry is made
    do {
      first = JOptionPane.showInputDialog("Please enter your first name");
      if (!aStudent.setFirstName(first)) {
        JOptionPane.showMessageDialog(null, "Invalid entry \nPlease try again.");
      }
    } while (!aStudent.setFirstName(first));

    // prompt for last name until valid entry is made
    do {
      last = (JOptionPane.showInputDialog("Please enter your last name"));
      if (!aStudent.setLastName(last)) {
        JOptionPane.showMessageDialog(null, "Invalid entry \nPlease try again");
      }
    } while (!aStudent.setLastName(last));

    // prompt for G-Number until valid entry is made
    do {
      GNum = (JOptionPane.showInputDialog("Please enter your G-number"));
      if (!aStudent.setgNumber(GNum)) {
        JOptionPane.showMessageDialog(
            null,
            "Invalid entry! Please write your GNumber in this format 00XXXXXX \nPlease try again",
            "Error",
            JOptionPane.ERROR_MESSAGE);
      }
    } while (!aStudent.setgNumber(GNum));

    // prompt for phone number until valid entry is made
    do {
      phoneNum = (JOptionPane.showInputDialog("Please enter your phone number"));
      if (!aStudent.setPhoneNumber(phoneNum)) {
        JOptionPane.showMessageDialog(
            null,
            "Invalid entry. Please write your phone number in XXXXXXXXXX format \nPlease try again",
            "Error",
            JOptionPane.ERROR_MESSAGE);
      }
    } while (!aStudent.setPhoneNumber(phoneNum));

    // prompt for email until valid entry is made
    do {
      email = (JOptionPane.showInputDialog("Please enter your Email address"));
      if (!aStudent.setEmail(email)) {
        JOptionPane.showMessageDialog(
            null,
            "Invalid entry, correct format: [email protected] \nPlease try again",
            "Error",
            JOptionPane.ERROR_MESSAGE);
      }
    } while (!aStudent.setEmail(email));

    // prompt for address until valid entry is made
    Student nStudent = (Student) aStudent;

    do {
      address = (JOptionPane.showInputDialog("Please enter your shipping address"));
      if (!nStudent.setShippingAddress(address)) {
        JOptionPane.showMessageDialog(null, "Invalid entry \nPlease try again");
      }
    } while (!nStudent.setShippingAddress(address));

    JOptionPane.showMessageDialog(null, "Your account has been created");
    try {
      PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("accounts.txt", true)));

      pw.println(
          "\r\n-"
              + aStudent.getFirstName()
              + ","
              + aStudent.getLastName()
              + ","
              + aStudent.getgNumber()
              + ","
              + aStudent.getPassword()
              + ","
              + aStudent.getPhoneNumber()
              + ","
              + aStudent.getEmail()
              + ","
              + aStudent.getUsername()
              + ","
              + nStudent.getShippingAddress());
      pw.close();

    } catch (IOException e) {
      e.printStackTrace();
    }

    userList.add(aStudent);
    return nStudent;
  }
예제 #29
0
  @Override
  public void transform(Object object) {
    User user = (User) object;
    String currentUserOrgUid = UserGroupSupport.getUserOrganizationUid();
    Organization organization = user.getOrganization();
    String organizationUid = null;
    if (organization != null) {
      organizationUid = user.getOrganization().getPartyUid();
      defaultOrganizatiomName = user.getOrganization().getPartyName();
    } else {
      organizationUid = user.getOrganizationUid();
    }
    boolean hasSubOrgPermission = false;
    if (organizationUid != null) {
      hasSubOrgPermission = hasSubOrgPermission(organizationUid);
    }

    boolean sharedSecretMatched = false;
    if (UserGroupSupport.getUserCredential() != null) {
      String storedSecret = UserGroupSupport.getUserCredential().getStoredSecretKey();
      String receivedSecret = UserGroupSupport.getUserCredential().getSharedSecretKey();
      if (receivedSecret != null && storedSecret != null && storedSecret.equals(receivedSecret)) {
        sharedSecretMatched = true;
      }
    }

    boolean isGooruUser = false;

    if (currentUserOrgUid != null
        && currentUserOrgUid.equals(GOORU_ORG_UID)
        && organizationUid != null) {
      isGooruUser = true;
    }

    if (user != null
        && currentUserOrgUid != null
        && organizationUid != null
        && (organizationUid.equals(currentUserOrgUid)
            || hasSubOrgPermission
            || sharedSecretMatched
            || isGooruUser)) {

      if (deepSerialize) {
        try {
          user = (User) xStream.fromXML(xStream.toXML(user));
        } catch (Exception ex) {
          deepSerialize = false;
        }
      }

      UserTransModel userModel = new UserTransModel();
      //	if(currentUserOrgUid )
      userModel.setPartyUid(user.getPartyUid());
      userModel.setGooruUId(user.getPartyUid());
      userModel.setConfirmStatus(user.getConfirmStatus());
      userModel.setEmailId(user.getEmailId());
      userModel.setFirstName(user.getFirstName());
      userModel.setGooruUId(user.getGooruUId());
      userModel.setLastName(user.getLastName());
      userModel.setRegisterToken(user.getRegisterToken());
      userModel.setUserId(user.getUserId());
      userModel.setUsername(user.getUsername());
      userModel.setRegisterToken(user.getRegisterToken());
      userModel.setConfirmStatus(user.getConfirmStatus());
      userModel.setParentUser(user.getParentUser());
      userModel.setAccountTypeId(user.getAccountTypeId());
      userModel.setUserRoleSet(user.getUserRoleSet());
      userModel.setViewFlag(user.getViewFlag());
      userModel.setCreatedOn(user.getCreatedOn() != null ? user.getCreatedOn().toString() : null);
      userModel.setRegisteredOn(user.getCreatedOn());
      userModel.setIsDeleted(user.getIsDeleted());
      userModel.setCustomFields(user.getCustomFields());
      userModel.setMeta(user.getMeta());
      userModel.setToken(user.getToken());
      userModel.setProfileImageUrl(
          UserGroupSupport.getProfileAssetURI() + user.getPartyUid() + ".png");
      if (user.getIdentities() != null) {
        Iterator<Identity> iter = user.getIdentities().iterator();
        if (iter != null && iter.hasNext()) {
          Identity identity = iter.next();
          userModel.setLoginType(identity != null ? identity.getLoginType() : null);
          userModel.setActive(identity.getActive());
          userModel.setAccountCreatedType(
              identity != null ? identity.getAccountCreatedType() : null);
          if (identity != null && identity.getExternalId() != null) {
            String email =
                identity.getExternalId().contains("@")
                    ? identity.getExternalId().split("@")[1]
                    : null;
            userModel.setLastLogin(identity.getLastLogin());
            if (email != null && email.contains(RUSD_ORGANIZATION_NAME)) {
              userModel.setOrganizationName(RUSD_ORGANIZATION_NAME);
            }
          }
        }
      }
      if (userModel.getOrganizationName() == null) {
        userModel.setOrganizationName(defaultOrganizatiomName);
      }

      if (deepSerialize) {
        userModel.setIdentities(user.getIdentities());
      }

      getContext().transform(userModel);

    } else {
      logger.error("Serialization failed for user transformer");
      getContext().write(null);
    }
  }