예제 #1
0
 public void load(InputStream inputStream) throws Exception {
   BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
   ArrayList<String> us = new ArrayList<>();
   while (bufferedReader.ready()) {
     us.add(bufferedReader.readLine());
   }
   for (int i = 0; i < us.size(); i += 5) {
     User user = new User();
     user.setFirstName(us.get(i));
     user.setLastName(us.get(i + 1));
     user.setBirthDate(new Date(Long.parseLong(us.get(i + 2))));
     user.setMale(Boolean.valueOf(us.get(i + 3)));
     String country = us.get(i + 4);
     User.Country country1 = null;
     if (country.equals("UKRAINE")) {
       country1 = User.Country.UKRAINE;
     } else if (country.equals("RUSSIA")) {
       country1 = User.Country.RUSSIA;
     } else if (country.equals("OTHER")) {
       country1 = User.Country.OTHER;
     }
     user.setCountry(country1);
     users.add(user);
   }
   bufferedReader.close();
 }
예제 #2
0
 // Get All Books
 public User getUser() {
   List<User> users = new LinkedList<User>();
   // 1. build the query
   String query = "SELECT * FROM " + TABLE_USER;
   // 2. get reference to writable DB
   SQLiteDatabase db = this.getWritableDatabase();
   Cursor cursor = db.rawQuery(query, null);
   // 3. go over each row, build book and add it to list
   User user = null;
   if (cursor.moveToFirst()) {
     do {
       user = new User();
       user.setId(Integer.parseInt(cursor.getString(0)));
       user.setFirstName(cursor.getString(1));
       user.setLastName(cursor.getString(2));
       user.setPhoneNumber(cursor.getString(3));
       user.setEmergencyNumber(cursor.getString(4));
       // Add book to books
       users.add(user);
     } while (cursor.moveToNext());
   }
   Log.d("getAllBooks()", users.toString());
   // Take only the first user - Ideally only once the profile can be created in the db
   if (users.isEmpty()) return null;
   else return users.get(0); // return user
 }
예제 #3
0
  public User getUserDetails(String userId) {

    PreparedStatement ps = null;
    ResultSet rs = null;
    User user = null;

    RegisterService registerService = new RegisterService();

    try {

      ps = connection.prepareStatement("SELECT * FROM user WHERE username=? LIMIT 1");
      ps.setString(1, username);
      rs = ps.executeQuery();

      if (rs != null && rs.next()) {
        user = new User(userId);
        user.setFirstName(rs.getString("firstname"));
        user.setLastName(rs.getString("lastname"));
        user.setEmail(rs.getString("email"));
        user.setPhoneNumber(rs.getString("primaryPhone"));
        user.setCellphone(rs.getString("secondaryPhone"));

        user.setAddress(registerService.createAddressFromID(rs.getInt("addressID")));
        user.setCard(registerService.createCardFromID(rs.getInt("creditCardID")));
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }

    return user;
  }
  public PagedResult<User> readUsers(String source) throws ReviewboardException {

    try {
      JSONObject rootObject = checkedGetJSonRootObject(source);

      int totalResults = rootObject.getInt("total_results");

      JSONArray jsonUsers = rootObject.getJSONArray("users");
      List<User> users = new ArrayList<User>();

      for (int i = 0; i < jsonUsers.length(); i++) {

        JSONObject jsonUser = jsonUsers.getJSONObject(i);

        User user = new User();
        user.setId(jsonUser.getInt("id"));
        user.setUrl(jsonUser.getString("url"));
        user.setUsername(jsonUser.getString("username"));
        // some fields are not set for private profiles
        user.setEmail(jsonUser.has("email") ? jsonUser.getString("email") : "");
        user.setFirstName(jsonUser.has("first_name") ? jsonUser.getString("first_name") : "");
        user.setLastName(jsonUser.has("last_name") ? jsonUser.getString("last_name") : "");

        users.add(user);
      }

      return PagedResult.create(users, totalResults);
    } catch (JSONException e) {
      throw new ReviewboardException(e.getMessage(), e);
    }
  }
 private User makeUser(String name) {
   User u = new User();
   u.setId(nextId++);
   u.setFirstName(name);
   u.setLastName("Test");
   u.setEmail("*****@*****.**");
   return u;
 }
예제 #6
0
  public static Pair<Boolean, String> updateProject(
      ProjectDTO projectDTO, boolean changedProjectName, String originalProjectName) {
    try {
      // Additional duplication control
      Project existingProject;
      if (changedProjectName) {
        existingProject = ProxyManager.getProjectProxy().findProjectByName(projectDTO.getName());
      } else existingProject = null;

      if (existingProject != null && changedProjectName) {
        System.out.println("Existing project exists!");
        return Pair.of(false, "Project with this name already exists!");
      }

      Project p = ProxyManager.getProjectProxy().findProjectByName(originalProjectName);
      p.setProjectId(projectDTO.getProjectId());
      p.setName(projectDTO.getName());
      p.setDescription(projectDTO.getDescription());
      p.setStatus(projectDTO.getStatus());
      Team team = new Team();
      team.setTeamId(projectDTO.getTeamTeamId().getTeamId());
      team.setScrumMasterId(projectDTO.getTeamTeamId().getScrumMasterId());
      team.setProductOwnerId(projectDTO.getTeamTeamId().getProductOwnerId());

      List<User> userList = new ArrayList<User>();
      if (projectDTO.getTeamTeamId().getUserList() != null) {
        for (UserDTO userDTO : projectDTO.getTeamTeamId().getUserList()) {
          User user = new User();
          user.setUserId(userDTO.getUserId());
          user.setUsername(userDTO.getUsername());
          user.setPassword(userDTO.getPassword());
          user.setFirstName(userDTO.getFirstName());
          user.setLastName(userDTO.getLastName());
          user.setEmail(userDTO.getEmail());
          user.setIsAdmin(userDTO.isAdmin());
          user.setSalt(userDTO.getSalt());
          user.setIsActive(userDTO.isActive());
          user.setTimeCreated(userDTO.getTimeCreated());
          userList.add(user);
        }
        team.setUserList(userList);
      } else return Pair.of(false, "No project list when saving team.");
      p.setTeamTeamId(team);
      try {
        if (p == null) return Pair.of(false, "Data error!");
        ProxyManager.getProjectProxy().edit(p);

      } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        return Pair.of(false, e.getMessage());
      }
    } catch (Exception e) {
      e.printStackTrace();
      return Pair.of(false, e.getMessage());
    }
    return Pair.of(true, "Project updated successfully.");
  }
예제 #7
0
 @Override
 public User updateUser(
     long userId, String username, String password, String firstName, String lastName) {
   User user = userRepository.findOne(userId);
   user.setUsername(username);
   user.setFirstName(firstName);
   user.setLastName(lastName);
   user.setPassword(password);
   return this.userRepository.save(user);
 }
예제 #8
0
  public static Pair<Boolean, String> saveNewProject(ProjectDTO projectDTO) {

    // check for project in database
    System.out.println("Project to check in base: " + projectDTO.getName());
    Project existingProject =
        ProxyManager.getProjectProxy().findProjectByName(projectDTO.getName());
    try {
      if (existingProject != null) {
        System.out.println("Existing project exists!");
        return Pair.of(false, "Project with this name already exists!");
      } else System.out.println("Project check passed, no existing project.");

      Project p = new Project();
      p.setName(projectDTO.getName());
      p.setDescription(projectDTO.getDescription());
      p.setStatus(projectDTO.getStatus());
      Team team = new Team();
      team.setTeamId(projectDTO.getTeamTeamId().getTeamId());
      team.setScrumMasterId(projectDTO.getTeamTeamId().getScrumMasterId());
      team.setProductOwnerId(projectDTO.getTeamTeamId().getProductOwnerId());

      List<User> userList = new ArrayList<User>();
      if (projectDTO.getTeamTeamId().getUserList() != null) {
        for (UserDTO userDTO : projectDTO.getTeamTeamId().getUserList()) {
          User user = new User();
          user.setUserId(userDTO.getUserId());
          user.setUsername(userDTO.getUsername());
          user.setPassword(userDTO.getPassword());
          user.setFirstName(userDTO.getFirstName());
          user.setLastName(userDTO.getLastName());
          user.setEmail(userDTO.getEmail());
          user.setIsAdmin(userDTO.isAdmin());
          user.setSalt(userDTO.getSalt());
          user.setIsActive(userDTO.isActive());
          user.setTimeCreated(userDTO.getTimeCreated());
          userList.add(user);
        }
        team.setUserList(userList);
      } else return Pair.of(false, "No user list when saving team.");
      p.setTeamTeamId(team);
      try {
        if (p == null) return Pair.of(false, "Data error!");

        ProxyManager.getProjectProxy().create(p);

      } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        return Pair.of(false, e.getMessage());
      }
    } catch (Exception e) {
      e.printStackTrace();
      return Pair.of(false, e.getMessage());
    }
    return Pair.of(true, "Project saved successfully.");
  }
  private User setUpUser1()
      throws InternalErrorException, WrongAttributeAssignmentException,
          WrongAttributeValueException, WrongReferenceAttributeValueException {
    User user = new User();
    user.setFirstName("James");
    user.setMiddleName("");
    user.setLastName("Bond");
    user.setTitleBefore("");
    user.setTitleAfter("");

    return perun.getUsersManagerBl().createUser(session, user);
  }
예제 #10
0
 // --------------------------------------------------------------------------
 // --------------------------BEANS CREATORS---------------------------------
 private static User createUser(Map<String, String> beanAttr) {
   if (beanAttr == null) return null;
   User user = new User();
   user.setId(Integer.valueOf(beanAttr.get("id")).intValue());
   user.setTitleBefore(BeansUtils.eraseEscaping(beanAttr.get("titleBefore")));
   user.setTitleAfter(BeansUtils.eraseEscaping(beanAttr.get("titleAfter")));
   user.setFirstName(BeansUtils.eraseEscaping(beanAttr.get("firstName")));
   user.setLastName(BeansUtils.eraseEscaping(beanAttr.get("lastName")));
   user.setMiddleName(BeansUtils.eraseEscaping(beanAttr.get("middleName")));
   user.setServiceUser(Boolean.valueOf(beanAttr.get("serviceAccount")).booleanValue());
   return user;
 }
예제 #11
0
  /** GetUser */
  @WebMethod(operationName = "getUser", action = "getUser")
  public User getUser(
      @WebParam(name = "sessionId") String sessionId, @WebParam(name = "login") String login) {
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    User foundUser = null;

    try {
      con =
          DriverManager.getConnection(
              PostgresConfig.url, PostgresConfig.user, PostgresConfig.password);
      // if(!checkSessionId(login, sessionId, con))
      //  return null;

      st = con.createStatement();
      ////////////////////////////////////////////////////////////////////////////////
      rs = st.executeQuery("SELECT * FROM users WHERE login=\'" + login + "\'");

      while (rs.next()) {
        User user = new User();

        user.setFirstName(rs.getString("imie"));
        user.setLastName(rs.getString("nazwisko"));
        user.setLogin(rs.getString("login"));
        user.setMail(rs.getString("mail"));
        user.setPhoneNumber(rs.getString("telefon"));

        foundUser = user;
        break;
      }

      System.out.println("Polaczono");
      ////////////////////////////////////////////////////////////////////////////////
    } catch (SQLException e) {
      System.out.println("Blad polaczenia");
      System.out.println(e.getMessage());
      System.out.println(e.getErrorCode());
    } finally {
      try {
        if (rs != null) rs.close();
        if (st != null) st.close();
        if (con != null) con.close();
      } catch (SQLException ex) {
        System.out.println("Blad zamykania polaczenia");
        System.out.println(ex.getMessage());
        System.out.println(ex.getErrorCode());
      }
    }
    return foundUser;
  }
 private void sendMailOperation() {
   User user = new User();
   user.setEmailAddress("*****@*****.**");
   user.setFirstName("Kaless");
   VerificationToken token =
       new VerificationToken(
           user,
           VerificationToken.VerificationTokenType.emailVerification,
           config.getEmailVerificationTokenExpiryTimeInMinutes());
   user.addVerificationToken(token);
   emailServicesGateway.sendVerificationToken(
       new EmailServiceTokenModel(user, token, getConfig().getHostNameUrl()));
 }
예제 #13
0
 public void load(InputStream inputStream) throws Exception {
   BufferedReader bur = new BufferedReader(new InputStreamReader(inputStream));
   while (bur.ready()) {
     User user = new User();
     user.setFirstName(bur.readLine());
     user.setLastName(bur.readLine());
     user.setBirthDate(new Date(Long.parseLong(bur.readLine())));
     user.setMale(Boolean.parseBoolean(bur.readLine()));
     user.setCountry(User.Country.valueOf(bur.readLine()));
     users.add(user);
   }
   bur.close();
 }
예제 #14
0
  public void testAddAndRemoveUser() throws Exception {
    User user = new User("testuser");
    user.setPassword("testpass");
    user.setFirstName("Test");
    user.setLastName("Last");
    Address address = new Address();
    address.setCity("Denver");
    address.setProvince("CO");
    address.setCountry("USA");
    address.setPostalCode("80210");
    user.setAddress(address);
    user.setEmail("*****@*****.**");
    user.setWebsite("http://tek42.com");
    user.setTimeZone("US/Central");

    // Here we are creating an org that should already be in the database...
    // Ideally, we somehow have an org object... from the other dao or whatever...
    /*
     * Account org = new Account(); org.setName("Tek42"); org.setId(1L);
     */
    Account org = adao.get(2L);
    System.out.println("Have org: " + org);
    user.setAccount(org);

    Role role = rdao.getRoleByName(Constants.USER_ROLE);
    assertNotNull(role.getId());
    user.addRole(role);

    user = dao.saveUser(user);

    assertNotNull(user.getId());

    user = dao.get(user.getId());

    assertEquals("Vigilant", user.getAccount().getName());
    assertEquals("testpass", user.getPassword());
    assertEquals("US/Central", user.getTimeZone());

    dao.remove(user.getId());

    try {
      dao.get(user.getId());
      fail("getUser didn't throw DataAccessException");
    } catch (DataAccessException d) {
      assertNotNull(d);
    }
  }
  @Override
  public long writeWholeData() throws SQLException {
    List<User> users = new LinkedList<User>();
    for (int i = 0; i < NUM_USER_INSERTS; i++) {
      User newUser = new User();
      newUser.setLastName(getRandomString(10));
      newUser.setFirstName(getRandomString(10));

      users.add(newUser);
    }

    List<Message> messages = new LinkedList<Message>();
    for (int i = 0; i < NUM_MESSAGE_INSERTS; i++) {
      Message newMessage = new Message();
      newMessage.setCommandId(i);
      newMessage.setSortedBy(System.nanoTime());
      newMessage.setContent(Util.getRandomString(100));
      newMessage.setClientId(System.currentTimeMillis());
      newMessage.setSenderId(Math.round(Math.random() * NUM_USER_INSERTS));
      newMessage.setChannelId(Math.round(Math.random() * NUM_USER_INSERTS));
      newMessage.setCreatedAt((int) (System.currentTimeMillis() / 1000L));

      messages.add(newMessage);
    }

    long start = System.nanoTime();
    SQLiteDatabase db = mHelper.getWritableDatabase();

    try {
      db.beginTransaction();

      for (User user : users) {
        db.insert(User.TABLE_NAME, null, user.prepareForInsert());
      }
      Log.d(SQLiteExecutor.class.getSimpleName(), "Done, wrote " + NUM_USER_INSERTS + " users");

      for (Message message : messages) {
        db.insert(Message.TABLE_NAME, null, message.prepareForInsert());
      }
      Log.d(
          SQLiteExecutor.class.getSimpleName(), "Done, wrote " + NUM_MESSAGE_INSERTS + " messages");
      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
    }
    return System.nanoTime() - start;
  }
예제 #16
0
  /** ListUsers */
  @WebMethod(operationName = "listUsers", action = "listUsers")
  public List<User> listUsers() {
    List<User> users = new LinkedList<User>();

    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    try {
      con =
          DriverManager.getConnection(
              PostgresConfig.url, PostgresConfig.user, PostgresConfig.password);
      st = con.createStatement();
      ////////////////////////////////////////////////////////////////////////////////
      rs = st.executeQuery("SELECT * FROM users;");

      while (rs.next()) {
        User user = new User();

        user.setFirstName(rs.getString("imie"));
        user.setLastName(rs.getString("nazwisko"));
        user.setLogin(rs.getString("login"));
        user.setMail(rs.getString("mail"));
        user.setPhoneNumber(rs.getString("telefon"));

        users.add(user);
      }

      System.out.println("Polaczono");
      ////////////////////////////////////////////////////////////////////////////////
    } catch (SQLException e) {
      System.out.println("Blad polaczenia");
      System.out.println(e.getMessage());
      System.out.println(e.getErrorCode());
    } finally {
      try {
        if (rs != null) rs.close();
        if (st != null) st.close();
        if (con != null) con.close();
      } catch (SQLException ex) {
        System.out.println("Blad zamykania polaczenia");
        System.out.println(ex.getMessage());
        System.out.println(ex.getErrorCode());
      }
    }
    return users;
  }
예제 #17
0
  @Test
  public void testAddTrialEnvironment() throws Exception {
    loginTestUser();
    List<TrialEnvironment> environments = trialService.getEnvironments(1L);
    int enviroSize = environments.size();

    User user = new User();
    user.setUsername("*****@*****.**");
    user.setFirstName("Test");
    user.setLastName("Test");
    user.setCreatedAt(new Date());
    user.getRoles().add(Role.ROLE_EXTERNAL);
    user.setPassword(securityService.encodePassword("test", user.getCreatedAt()));
    userDao.save(user);

    Product product = new Product();
    product.setShortName("Test");
    product.setName("Test Long");

    productService.addProduct(product);

    ProductVersion productVersion = new ProductVersion();
    productVersion.setName("Test-version");
    productVersion.setCreatedAt(new Date());
    productVersion.setProduct(product);
    productVersion.setIeOnly(true);
    productVersionDao.save(productVersion);
    product.getProductVersions().add(productVersion);
    productDao.save(product);

    emService.flush();

    TrialDto trial = new TrialDto();
    trial.setProductId(product.getId());
    trial.setProductVersionId(productVersion.getId());
    trial.setUserId(user.getId());
    trial.setUrl("http://test/hahahaha");
    trial.setUsername("test");
    trial.setPassword("haha");
    trialService.createTrialEnvironment(trial);
    emService.flush();

    environments = trialService.getEnvironments(product.getId());
    assertEquals(enviroSize + 1, environments.size());
  }
  /* second version, using popup */
  public void onCreateUser() throws ViewFactoryException {
    // create view
    UserView view = this.createView(UserView.class);

    // configure the form with bean item
    this.userForm = view.getUserForm();
    User u = new User();
    u.setUserName("newuser");
    u.setFirstName("First name");
    u.setLastName("Last name");
    BeanItem<User> beanItem = new BeanItem<User>(u);
    this.userForm.setItemDataSource(beanItem);

    // create a window using caption from view
    this.dialog = new Window(view.getCaption());
    view.setCaption(null);
    this.dialog.setModal(true);
    dialog.addComponent(view);
    dialog.setWidth("300px");
    this.eventBus.showDialog(this.dialog);
  }
  public User getUser(MySqlHelper helper, String userName, String password) {
    User user = new User();
    String query =
        "select * "
            + "from login u inner join address a on u.UserId = a.UserId "
            + "inner join personalinfo p on a.AddressId = p.AddressId "
            + "where Email=? and Password= ?";
    System.out.println(query);
    System.out.println("u=" + userName + " p=" + password);
    try {
      java.sql.PreparedStatement loginPreparedStatement =
          helper.conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
      loginPreparedStatement.setString(1, userName);
      loginPreparedStatement.setString(2, password);
      ResultSet rs = loginPreparedStatement.executeQuery();
      while (rs.next()) {
        user.setFirstName(rs.getString("FirstName"));
        user.setLastName(rs.getString("LastName"));
        user.setUserType(Integer.toString(rs.getInt("UserTypeId")));
        user.setEmail(rs.getString("Email"));

        Address address = new Address();
        address.setAddressLine1(rs.getString("AddressLine1"));
        address.setAddressLine2(rs.getString("AddressLine2"));
        address.setCity(rs.getString("City"));
        address.setState(rs.getString("State"));
        address.setZipCode(rs.getString("ZipCode"));
        address.setLattitude(rs.getString("Lattitude"));
        address.setLongitude(rs.getString("Longitude"));

        user.setAddress(address);

        user.setPhoneNumber(rs.getString("PhoneNumber"));
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return user;
  }
예제 #20
0
  public static boolean createAdmin() {
    User myAdmin = new Admin("admin");
    myAdmin.setEmail("*****@*****.**");
    myAdmin.setFirstName("FirstAdmin");
    myAdmin.setLastName("lastAdmin");
    myAdmin.setgNumber("00800000");
    myAdmin.setPassword("password");
    myAdmin.setPhoneNumber("5555555555");

    String username = JOptionPane.showInputDialog(null, "Enter admin username");

    String password = JOptionPane.showInputDialog(null, "Enter admin Password");

    if (username.equals(myAdmin.getUsername()) && password.equals(myAdmin.getPassword())) {

      return true;
    } else {
      JOptionPane.showMessageDialog(
          null, "Bad password: **Hint: username = '******' :: password = '******'");
      return false;
    }
  }
예제 #21
0
파일: jdbc.java 프로젝트: eric62451/aaaaa
 public User getUser(String user) throws SQLException {
   start();
   rs = stmt.executeQuery("SELECT * FROM userInfo WHERE username = '******'");
   User rtrn = null;
   if (rs.next()) {
     rtrn = new User();
     rtrn.setUserName(rs.getString(1));
     rtrn.setPassWord(rs.getString(2));
     rtrn.setFirstName(rs.getString(3));
     rtrn.setLastName(rs.getString(4));
     rtrn.setEmail(rs.getString(5));
     long number = 0;
     String num = rs.getString(6);
     if (num != null)
       number = Long.parseLong(num.replace("-", "").replace("(", "").replace(")", ""));
     rtrn.setPhoneNumber(number);
     rtrn.setCity(rs.getString(7));
     rtrn.setState(rs.getString(8));
     rtrn.setRating(rs.getInt(9));
   }
   close();
   return rtrn;
 }
예제 #22
0
  public String execute() throws Exception {
    UserCredentials currentUserCredentials =
        currentUserService.getCurrentUser() != null
            ? currentUserService.getCurrentUser().getUserCredentials()
            : null;

    // ---------------------------------------------------------------------
    // Prepare values
    // ---------------------------------------------------------------------

    if (email != null && email.trim().length() == 0) {
      email = null;
    }

    if (rawPassword != null && rawPassword.trim().length() == 0) {
      rawPassword = null;
    }

    // ---------------------------------------------------------------------
    // Update userCredentials and user
    // ---------------------------------------------------------------------

    Collection<OrganisationUnit> units =
        selectionTreeManager.getReloadedSelectedOrganisationUnits();

    User user = userService.getUser(id);
    user.setSurname(surname);
    user.setFirstName(firstName);
    user.setEmail(email);
    user.setPhoneNumber(phoneNumber);
    user.updateOrganisationUnits(new HashSet<OrganisationUnit>(units));

    UserCredentials userCredentials = userService.getUserCredentials(user);

    Set<UserAuthorityGroup> userAuthorityGroups = new HashSet<UserAuthorityGroup>();

    for (String id : selectedList) {
      UserAuthorityGroup group = userService.getUserAuthorityGroup(Integer.parseInt(id));

      if (currentUserCredentials != null && currentUserCredentials.canIssue(group)) {
        userAuthorityGroups.add(group);
      }
    }

    userCredentials.setUserAuthorityGroups(userAuthorityGroups);

    if (rawPassword != null) {
      userCredentials.setPassword(
          passwordManager.encodePassword(userCredentials.getUsername(), rawPassword));
    }

    if (jsonAttributeValues != null) {
      AttributeUtils.updateAttributeValuesFromJson(
          user.getAttributeValues(), jsonAttributeValues, attributeService);
    }

    userService.updateUserCredentials(userCredentials);
    userService.updateUser(user);

    if (currentUserService.getCurrentUser() == user) {
      selectionManager.setRootOrganisationUnits(units);
      selectionManager.setSelectedOrganisationUnits(units);

      selectionTreeManager.setRootOrganisationUnits(units);
      selectionTreeManager.setSelectedOrganisationUnits(units);
    }

    if (units.size() > 0) {
      selectionManager.setSelectedOrganisationUnits(units);
    }

    return SUCCESS;
  }
예제 #23
0
  public static void main(String[] args) {
    // you can find your_file_name.tmp in your TMP directory or fix outputStream/inputStream
    // according to your real file location
    // вы можете найти your_file_name.tmp в папке TMP или исправьте outputStream/inputStream в
    // соответствии с путем к вашему реальному файлу
    try {
      File your_file_name = new File("/home/alexey/pro/out");
      OutputStream outputStream = new FileOutputStream(your_file_name);
      InputStream inputStream = new FileInputStream(your_file_name);

      User u1 = new User();
      User u2 = new User();
      u1.setCountry(User.Country.UKRAINE);
      u2.setCountry(User.Country.OTHER);
      u1.setBirthDate(new GregorianCalendar(1991, 2, 21).getTime());
      u2.setBirthDate(new GregorianCalendar(1990, 11, 7).getTime());
      u1.setFirstName("Antonio");
      u2.setFirstName("Joni");
      u1.setLastName("Kokovetzh");
      u2.setLastName("Pakolonetzh");
      u1.setMale(true);
      u2.setMale(true);
      JavaRush javaRush = new JavaRush();
      javaRush.users.add(u1);
      javaRush.users.add(u2);
      javaRush.save(outputStream);
      outputStream.flush();

      JavaRush loadedObject = new JavaRush();
      loadedObject.load(inputStream);

      Comparator<List<User>> c =
          new Comparator<List<User>>() {
            @Override
            public int compare(List<User> u1, List<User> u2) {
              int c = 0;
              if (u1.size() == u2.size())
                for (int i = 0; i < u1.size(); i++) {
                  if (u1.get(i).getBirthDate().equals(u2.get(i).getBirthDate())) c++;
                  if (u1.get(i).getCountry().equals(u2.get(i).getCountry())) c++;
                  if (u1.get(i).getFirstName().equals(u2.get(i).getFirstName())) c++;
                  if (u1.get(i).getLastName().equals(u2.get(i).getLastName())) c++;
                  if (u1.get(i).isMale() == u2.get(i).isMale()) c++;
                }
              return c;
            }
          };

      if (c.compare(javaRush.users, loadedObject.users) == javaRush.users.size() * 5)
        System.out.println("OK");
      else System.out.println("NOT");

      outputStream.close();
      inputStream.close();

    } catch (IOException e) {
      // e.printStackTrace();
      System.out.println("Oops, something wrong with my file");
    } catch (Exception e) {
      // e.printStackTrace();
      System.out.println("Oops, something wrong with save/load method");
    }
  }
예제 #24
0
 public void changeData(View view) {
   user.setFirstName("Christian");
 }
예제 #25
0
  /** @param userList Populate system with list of students accounts from text file */
  public static void populateStudentAccounts(LinkedList<User> userList) {
    Scanner inputStream = null;
    // open text file of accounts
    try {
      inputStream = new Scanner(new FileInputStream("accounts.txt"));
      // System.out.println("accounts file read");
    } catch (FileNotFoundException e) {
      JOptionPane.showMessageDialog(null, "The file \"accounts.txt\" could not be found");
      JOptionPane.showMessageDialog(null, "The system will now exit");
      System.exit(0);
    }

    // Pull line of text to generate a student
    while (inputStream.hasNextLine()) {
      String s1 = inputStream.nextLine();
      // locate first name
      int fNsameStart = (s1.indexOf("-") + 1);
      int fNameEnd = (s1.indexOf(","));
      String fName = s1.substring(fNsameStart, fNameEnd);
      // locate Last name
      int lNameStart = (s1.indexOf(",", fNameEnd) + 1);
      int lNameEnd = (s1.indexOf(",", lNameStart));
      String lName = s1.substring(lNameStart, lNameEnd);
      // locate gNumber
      int gNumberStart = (s1.indexOf(",", lNameEnd) + 1);
      int gNumberEnd = (s1.indexOf(",", gNumberStart));
      String gNumber = s1.substring(gNumberStart, gNumberEnd);
      // locate password
      int passwordStart = (s1.indexOf(",", gNumberEnd) + 1);
      int passwordEnd = (s1.indexOf(",", passwordStart));
      String password = s1.substring(passwordStart, passwordEnd);
      // locate phone number
      int phoneNumberStart = (s1.indexOf(",", passwordEnd + 1));
      int phoneNumberEnd = (s1.indexOf(",", phoneNumberStart));
      String phoneNumber = s1.substring(phoneNumberStart, phoneNumberEnd);
      // locate email
      int emailStart = (s1.indexOf(",", phoneNumberEnd) + 1);
      int emailEnd = (s1.indexOf(",", emailStart));
      String email = s1.substring(emailStart, emailEnd);
      // locate username
      int usernameStart = (s1.indexOf(",", emailEnd) + 1);
      int usernameEnd = (s1.indexOf(",", usernameStart));
      String username = s1.substring(usernameStart, usernameEnd);
      // locate address
      int addressStart = (s1.indexOf(",", usernameEnd) + 1);
      String address = s1.substring(addressStart);

      // create student object and populate info
      User aStudent = new Student(username);
      aStudent.setFirstName(fName);
      aStudent.setLastName(lName);
      aStudent.setgNumber(gNumber);
      aStudent.setPassword(password);
      aStudent.setPhoneNumber(phoneNumber);
      aStudent.setEmail(email);
      if (aStudent instanceof Student) {
        ((Student) aStudent).setShippingAddress(address);
      }

      // add Student to list
      userList.add(aStudent);
      System.out.println(userList.size());
    }
  }
예제 #26
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;
  }
  @Test
  public void testAdd() {
    HibernateDatabaseUserManager userManager = HibernateDatabaseUserManager.getDefault();
    HibernateDatabaseAddressManager addrManager = HibernateDatabaseAddressManager.getDefault();
    HibernateDatabaseArenaManager arenaManager = HibernateDatabaseArenaManager.getDefault();
    HibernateDatabaseGameManager gameManager = HibernateDatabaseGameManager.getDefault();

    addrManager.setupTable();
    arenaManager.setupTable();
    gameManager.setupTable();
    userManager.setupTable();

    Address addr1 = new Address();
    addr1.setStreetAddress("2185 Arch St.");
    addr1.setCity("Ottawa");
    addr1.setPostalOrZipCode("K1G 2H5");
    addr1.setProvinceOrState("Ontario");
    addr1.setCountry("Canada");

    Arena arena1 = new Arena();
    arena1.setArenaName("Cantebury");
    arena1.setAddress(addr1);
    addr1.setArena(arena1);

    Game game1 = new Game();
    game1.setGameDay("Tuesday");
    game1.setGameTime("7:30 PM");

    arena1.addGame(game1);

    Address addr = new Address();
    addr.setStreetAddress("1264 Walkley Rd. ");
    addr.setCity("Ottawa");
    addr.setPostalOrZipCode("K1V 6P9");
    addr.setProvinceOrState("Ontario");
    addr.setCountry("Canada");

    Arena arena = new Arena();
    arena.setArenaName("Jim Durell");

    Game game = new Game();
    game.setGameDay("Monday");
    game.setGameTime("9:30 PM");

    Game game2 = new Game();
    game2.setGameDay("Wednesday");
    game2.setGameTime("10:30 PM");

    Address addr3 = new Address();
    addr3.setStreetAddress("210 Hopewell Ave.");
    addr3.setCity("Ottawa");
    addr3.setPostalOrZipCode("K1S 2Z5");
    addr3.setProvinceOrState("Ontario");
    addr3.setCountry("Canada");

    Arena arena3 = new Arena();
    arena3.setArenaName("Brewer");
    arena3.setAddress(addr3);
    addr3.setArena(arena3);

    Game game3 = new Game();
    game3.setGameDay("Friday");
    game3.setGameTime("10:30 PM");

    arena3.addGame(game3);

    arena.setAddress(addr);
    addr.setArena(arena);

    arena.addGame(game);
    arena.addGame(game2);

    arenaManager.add(arena);
    arenaManager.add(arena1);
    arenaManager.add(arena3);

    User client = new User();
    client.setFirstName("John");
    client.setLastName("Marsh");
    client.setEmailAddress("*****@*****.**");
    client.setPassword(BCrypt.hashpw("password", BCrypt.gensalt()));
    client.setCity("Ottawa");
    client.setCountry("Canada");
    client.setProvinceORstate("Ontario");
    client.setBirthdate(Timestamp.valueOf("1993-07-21 00:00:00"));

    User client2 = new User();
    client2.setFirstName("Dougall");
    client2.setLastName("Percival");
    client2.setEmailAddress("*****@*****.**");
    client2.setPassword(BCrypt.hashpw("password", BCrypt.gensalt()));
    client2.setCity("Ottawa");
    client2.setCountry("Canada");
    client2.setProvinceORstate("Ontario");
    client2.setBirthdate(Timestamp.valueOf("1993-12-21 00:00:00"));
    client2.addGame(game2);

    assertTrue(userManager.add(client));
    assertTrue(userManager.add(client2));

    userManager.update(client2);
    userManager.update(client);
  }