Ejemplo n.º 1
0
  @Test
  public void usernameMustBePresent() throws Exception {

    User user = new User();
    user.setUsername(null);

    propertyValidationShouldFail("username", user);

    user.setUsername(VALID_USERNAME);

    propertyValidationShouldNotFail("username", user);
  }
Ejemplo n.º 2
0
  @Test
  public void usernameLength() throws Exception {

    User user = new User();
    user.setUsername(StringGenerator.randomString(65));

    propertyValidationShouldFail("username", user);

    user.setUsername(StringGenerator.randomString(64));

    propertyValidationShouldNotFail("username", user);
  }
  @OnClick(R.id.sign_up)
  public void signUpClicked(View view) {
    Utils.hideKeyboard(this);
    Utils.showProgressBar(this, progress, "Signing Up...");

    User user = new User();
    user.setSuperDefaults();
    user.setUsername(username.getText().toString().trim());
    user.setPassword(password.getText().toString().trim());
    user.setEmail(email.getText().toString().trim());
    user.setPhone(phone.getText().toString().trim());
    user.setName(name.getText().toString().trim());
    user.signUpInBackground(
        new SignUpCallback() {
          @Override
          public void done(ParseException exception) {
            Utils.hideProgressBar(progress);
            if (exception == null) {
              Toast.makeText(
                      getApplicationContext(), "Sign up done successfully", Toast.LENGTH_SHORT)
                  .show();
            } else {
              new Builder(SignUpActivity.this)
                  .setTitle(R.string.error_title)
                  .setMessage(exception.getMessage())
                  .setPositiveButton(string.ok, null)
                  .create()
                  .show();
            }
            startActivity(
                new Intent(SignUpActivity.this, MainActivity.class)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
          }
        });
  }
  /**
   * @param customerUser The Customer User
   * @return A HAL representation of the result
   */
  @DELETE
  @Timed
  public Response deregisterUser(@RestrictedTo({Authority.ROLE_CUSTOMER}) User customerUser) {

    Preconditions.checkNotNull(customerUser);

    // Remove all identifying information from the User
    // but leave the entity available for audit purposes
    // We leave the secret key in case the user has been
    // accidentally deleted and the user wants to be
    // reinstated
    customerUser.setApiKey("");
    customerUser.setContactMethodMap(Maps.<ContactMethod, ContactMethodDetail>newHashMap());
    customerUser.setUsername("");
    customerUser.setPasswordDigest("");
    customerUser.setPasswordResetAt(DateUtils.nowUtc());
    customerUser.setLocked(true);
    customerUser.setDeleted(true);
    customerUser.setReasonForDelete("Customer deregistered");
    customerUser.setUserFieldMap(Maps.<UserField, UserFieldDetail>newHashMap());

    // Persist the User with cascade for the Customer
    User persistentUser = userDao.saveOrUpdate(customerUser);

    // Provide a minimal representation to the client
    // so that they can see their secret key as a last resort
    // manual recovery option
    ClientUserBridge bridge = new ClientUserBridge(uriInfo, Optional.of(customerUser));
    URI location = uriInfo.getAbsolutePathBuilder().path(persistentUser.getApiKey()).build();

    return created(bridge, persistentUser, location);
  }
Ejemplo n.º 5
0
  @Override
  public User authenticate(String username, String password) {
    try {
      DBConnectionFactory myFactory = DBConnectionFactory.getInstance(DAOFactory.MYSQL);
      Connection conn = myFactory.getConnection();
      PreparedStatement pstmt =
          conn.prepareStatement("select * from users where username = ? and userpassword = ?");
      pstmt.setString(1, username);
      pstmt.setString(2, password);
      ResultSet rs = pstmt.executeQuery();
      User result = null;

      while (rs.next()) {
        result = new User();
        result.setId(rs.getInt("idusers"));
        result.setUsername(rs.getString("username"));
        result.setUserpassword(rs.getString("userpassword"));
        result.setUsertypeid(rs.getInt("usertypeid"));
        result.setAge(rs.getInt("age"));
        result.setGender(rs.getString("gender"));
        result.setLocation(rs.getString("location"));
        result.setBirthday(rs.getString("birthday"));
      }

      conn.close();
      return result;
    } catch (SQLException ex) {
      Logger.getLogger(UserDAO_MySQL.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
  }
  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);
    }
  }
Ejemplo n.º 7
0
 private User getTestUser() {
   User user;
   user = new User();
   user.setUsername("testuser");
   user.setPasswordHash("testpw");
   user.setLastLogin(new Date());
   return user;
 }
Ejemplo n.º 8
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.");
  }
Ejemplo n.º 9
0
 @Test
 public void testUpdateUser() {
   IUserOperation userOperation = session.getMapper(IUserOperation.class);
   User user = userOperation.selectUserById(7);
   user.setUsername("liangzhuo2");
   user.setAge(25);
   user.setAddress("湖北天门黄潭");
   userOperation.updateUser(user);
 }
Ejemplo n.º 10
0
 @Test
 public void testAddUser() {
   User user = new User();
   user.setUsername("liangzhuo");
   user.setAge(26);
   user.setAddress("湖北天门");
   IUserOperation userOperation = session.getMapper(IUserOperation.class);
   userOperation.addUser(user);
 }
Ejemplo n.º 11
0
 public User getPersonalDetails(User user) {
   user.setUsername(sharedPreferences.getString("username", ""));
   user.setPassword(sharedPreferences.getString("password", ""));
   user.setName(sharedPreferences.getString("name", ""));
   user.setEmail(sharedPreferences.getString("email", ""));
   user.setAge(sharedPreferences.getString("age", ""));
   user.setPhone(sharedPreferences.getString("phone", ""));
   return user;
 }
Ejemplo n.º 12
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);
 }
Ejemplo n.º 13
0
 @GET
 @Produces("application/json")
 public List<User> findUsers() {
   User user = new User();
   user.setId(1l);
   user.setUsername("lee");
   List<User> users = new LinkedList<User>();
   users.add(user);
   return users;
 }
Ejemplo n.º 14
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.");
  }
Ejemplo n.º 15
0
  @Test
  public void usernameFormatMustBeValid() throws Exception {

    final User user = new User();

    List<String> validNames = Arrays.asList("tomas", "TOMAS", "tom_as", "to_-mas", "t0m145_");

    validNames.forEach(
        name -> {
          user.setUsername(name);
          propertyValidationShouldNotFail("username", user);
        });

    List<String> invalidNames = Arrays.asList("i have space", "what?", "...", "nocomma,", "æøå");

    invalidNames.forEach(
        name -> {
          user.setUsername(name);
          propertyValidationShouldFail("username", user);
        });
  }
Ejemplo n.º 16
0
  private Repository() {
    /*
     * Set sensor's author
     * If you don't have LSM account, please visit LSM Home page (http://lsm.deri.ie) to sign up
     */
    User user = new User();
    user.setUsername(PropertiesReader.readProperty(LSM_CONFIG_PROPERTIES_FILE, "username"));
    user.setPass(PropertiesReader.readProperty(LSM_CONFIG_PROPERTIES_FILE, "password"));

    logger.warn(
        "username : "******"username"));
    logger.warn(
        "password : "******"password"));
  }
 private static boolean getUserDetails(Context context) {
   settings = context.getSharedPreferences(app_settings, Context.MODE_PRIVATE);
   String name = settings.getString(path_userName, null);
   String pass = settings.getString(path_password, null);
   if (name != null && pass != null) {
     User user = DBHandlerSingleton.getInstance(context).findUser(name, pass);
     if (user != null) {
       userRegistered.setUsername(name);
       userRegistered.setPassword(pass);
       userRegistered.setID(user.getID());
       return true;
     } else return false;
   }
   return false;
 }
Ejemplo n.º 18
0
  @Transactional
  public boolean createUser(final String username, final String password, final String email) {
    User user = new User();

    user.setUsername(username);
    user.setHash(hashPassword(password));
    user.setEmail(email);

    // todo - create user, remove empty strings check
    try {
      return userDao.createUser(user);
    } catch (Throwable t) {
      LOGGER.warn("Exception occurred while creating new user, error: " + t);
      return false;
    }
  }
Ejemplo n.º 19
0
  @Override
  public Offer mapRow(ResultSet rs, int rowNum) throws SQLException {
    User user = new User();
    user.setAuthority(rs.getString("authority"));
    user.setEmail(rs.getString("email"));
    user.setEnabled(true);
    user.setName(rs.getString("name"));
    user.setUsername(rs.getString("username"));

    Offer offer = new Offer();
    offer.setId(rs.getInt("id"));
    offer.setText(rs.getString("text"));
    offer.setUser(user);

    return offer;
  }
Ejemplo n.º 20
0
  @Test
  public void canSetUsers() {

    final Role role = new Role();

    final User user = new User();
    user.setUsername("username");

    final List<User> users = new ArrayList<>();
    users.add(user);

    role.setUsers(users);

    assertEquals(1, role.getUsers().size());
    assertEquals(role.getUsers().get(0).getUsername(), "username");
  }
Ejemplo n.º 21
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());
  }
Ejemplo n.º 22
0
  public static void main(String args[]) throws Exception {

    /*	   Class clss = User.class;
     User user =(User) clss.newInstance();
     Field[] fields = user.getClass().getFields();
     StringBuffer  sb= new StringBuffer();
     for(Field field: fields){
      BeanUtils.setProperty(user, field.getName(), "55");
      sb.append(field.getName()).append("\t : \t").append(BeanUtils.getProperty(user, field.getName())).append("\n");
     }
     //using the beanUtils grant the properties
    System.out.println(sb);*/

    User user = new User();
    user.setId("1000");
    user.setUsername("Ripper");
    user.setAge(135);
    getObjectString(user);
  }
Ejemplo n.º 23
0
  public boolean setUsersInProject(JFrame frame, User u) {
    if (!Methodes.testConnectie()) {
      JFrame[] frames = {frame};
      Methodes.Disconnect(frames, "Connectie verloren, terug naar login scherm");
    }
    boolean check = false;
    this.entries = new ArrayList<Entry>();
    DefaultHttpClient client = u.getClient();
    HttpGet getRequest =
        new HttpGet("http://" + Methodes.getIp() + "/webservice/getUsersInProject/" + id);
    try {
      HttpResponse resp = client.execute(getRequest);
      // uid,uname,voonaam,achternaam,
      BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
      String output = "";
      while ((output = rd.readLine()) != null) {
        System.out.println(output);
        JSONObject object = new JSONObject(output);
        JSONArray array = object.optJSONArray("users");
        for (int i = 0; i < array.length(); i++) {
          JSONObject json = array.getJSONObject(i);
          int uid = json.getInt("uid");
          String username = json.getString("uname");
          String firstname = json.getString("voornaam");
          String name = json.getString("achternaam");
          User usr = new User(uid, firstname, name);
          usr.setUsername(username);
          if (user == null) user = u;
          usr.getRightsFromDB(frame, this.id, user);
          users.add(usr);
          System.out.println(user);
        }
      }

    } catch (IOException | JSONException e) {
      e.printStackTrace();
    } finally {
      client.getConnectionManager().shutdown();
    }
    return check;
  }
  /** Tests editing user profile (UC 2.4, 10.2) */
  public void testEditUserProfile() {
    UserProfileActivity activity = (UserProfileActivity) getActivity();
    etCity = activity.getEtCity();
    etPhone = activity.getEtPhone();
    etEmail = activity.getEtEmail();
    final String username = "******";
    final UserRegistrationController urc = new UserRegistrationController();

    // Creates user
    User user = new User();
    user.setUsername(username);
    user.setCity("Testlandia");
    user.setPhone("555-555-5555");
    user.setEmail("*****@*****.**");
    urc.getUserList().addUser(user);

    // Set up an ActivityMonitor
    Instrumentation.ActivityMonitor receiverActivityMonitor =
        getInstrumentation().addMonitor(RegisterActivity.class.getName(), null, false);

    activity.runOnUiThread(
        new Runnable() {
          public void run() {
            etCity.setText("Testopia");
            etPhone.setText("555-555-5556");
            etEmail.setText("*****@*****.**");
            if (urc.validateEditedFields(etCity, etPhone, etEmail)) {
              urc.editUser(username, etCity, etPhone, etEmail);
            }
          }
        });
    getInstrumentation().waitForIdleSync();

    assertTrue(urc.getUser(username).getCity().equals("Testopia"));
    assertTrue(urc.getUser(username).getPhone().equals("555-555-5556"));
  }
  /**
   * 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)

    // PRIVS check that hrAdmin user is viewing this page
    if (!StandardCode.getInstance()
        .checkPrivStringArray(
            (String[]) request.getSession(false).getAttribute("userPrivs"), "hrAdmin")) {
      return (mapping.findForward("accessDenied"));
    } // END PRIVS check that hrAdmin user is viewing this page

    // get user to edit from form hidden field
    String hrAdminUserId = request.getParameter("hrAdminUserId");
    User u = UserService.getInstance().getSingleUser(Integer.valueOf(hrAdminUserId));
    User currentUser =
        UserService.getInstance()
            .getSingleUser((String) request.getSession(false).getAttribute("username"));

    // values for update from form; change what is stored in db to these values
    DynaValidatorForm uvg = (DynaValidatorForm) form;

    String username = (String) uvg.get("username");
    String password = (String) uvg.get("password");

    // update the user's values
    if (username.length() > 0) { // if present
      u.setUsername(username);
    }
    if (password.length() > 0) { // if present, hash password for safe db store
      MessageDigest md = null;
      try {
        md = MessageDigest.getInstance("SHA"); // step 2
      } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
      }
      try {
        md.update(password.getBytes("UTF-8")); // step 3
      } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
      }
      byte raw[] = md.digest(); // step 4
      String hash = (new BASE64Encoder()).encode(raw); // step 5
      u.setPassword(hash);
    }

    // set updated values to db
    UserService.getInstance().updateUser(u);
    String firstName = u.getFirstName();
    String msg =
        "<font size='2'><span style='font-family: Verdana,Arial,Helvetica,sans-serif;'>Dear <span style='color: rgb(255, 0, 0);'>"
            + firstName
            + "</span>,<br><br style='font-family: Verdana,Arial,Helvetica,sans-serif;'></span><span style='font-family: Verdana,Arial,Helvetica,sans-serif;'>We have created an account for you on ExcelNet, Excel Translations' proprietary intra/extranet system. <br><br> Below you will find the information you need to enter our system, please keep this only to yourself in a secure place.  </span><br style='font-family: Verdana,Arial,Helvetica,sans-serif;'><span style='font-family: Verdana,Arial,Helvetica,sans-serif;'><br>User Name: "
            + username
            + "</span><br style='font-family: Verdana,Arial,Helvetica,sans-serif;'><span style='font-family: Verdana,Arial,Helvetica,sans-serif;'>Password&nbsp;&nbsp;: "
            + password
            + "</span><br style='font-family: Verdana,Arial,Helvetica,sans-serif;'><br style='font-family: Verdana,Arial,Helvetica,sans-serif;'><span style='font-family: Verdana,Arial,Helvetica,sans-serif;'>You can log in into your Account on by clicking </span><a style='font-family: Verdana,Arial,Helvetica,sans-serif;' href='http://excelnet.xltrans.com'>here</a><span style='font-family: Verdana,Arial,Helvetica,sans-serif;'>.<br><br><br>Best Regards,</span><br style='font-family: Verdana,Arial,Helvetica,sans-serif;'><br style='font-family: Verdana,Arial,Helvetica,sans-serif;'><span style='font-family: Verdana,Arial,Helvetica,sans-serif; Best regards,<br style='font-family: Verdana,Arial,Helvetica,sans-serif;'></font><font style='font-family: Verdana,Arial,Helvetica,sans-serif;' size='2'><span class='Apple-style-span' style='border-collapse: separate; color: rgb(0, 0, 0); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; font-size: medium;'><span class='Apple-style-span' style='color: rgb(59, 105, 119); font-size: 11px; text-align: left;'><br> ExcelNet Administrator<br>Excel Translations, Inc.<br><br><img src=http://excelnet.xltrans.com/logo/images/-1168566039logoExcel.gif></span></span></font><br> ";
    String emailMsgTxt = msg;
    String emailSubjectTxt = "New User Account";
    String adminEmail;
    String userEmailId = "*****@*****.**";
    if (!u.getWorkEmail1().equalsIgnoreCase("")) {

      userEmailId = u.getWorkEmail1();
    } else if (!u.getWorkEmail2().equalsIgnoreCase("")) {
      userEmailId = u.getWorkEmail2();
    } else {
      userEmailId = "*****@*****.**";
    }
    if (currentUser.getWorkEmail1() == null || currentUser.getWorkEmail1().equalsIgnoreCase("")) {
      adminEmail = "*****@*****.**";

    } else adminEmail = currentUser.getWorkEmail1();

    try {
      String[] emailList = {userEmailId, adminEmail};
      SendEmail smtpMailSender = new SendEmail();
      smtpMailSender.postMail(emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
    } catch (Exception e) {

      // String[] emailList = {"niteshwar.kumarpatialideas.com"};
      // SendEmail smtpMailSender = new SendEmail();
      // smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);

    }

    // Forward control to the specified success URI
    return (mapping.findForward("Success"));
  }
Ejemplo n.º 26
0
 public void initDB() {
   Address var1 = new Address();
   var1.setStreet("Mekelweg");
   var1.setCity("Delft");
   var1.setPhone("015");
   Address Mekelweg4 = var1;
   Address var2 = new Address();
   var2.setStreet("Ringwade 1");
   var2.setCity("Nieuwegein");
   var2.setPhone("030");
   Address Ordina = var2;
   Person var3 = new Person();
   var3.setFullname("Eelco Visser");
   var3.setEmail("*****@*****.**");
   var3.setAddress(Mekelweg4);
   var3.setHomepage("http://www.eelcovisser.net");
   var3.setPhoto("/img/eelcovisser.jpg");
   Person EelcoVisser = var3;
   User var4 = new User();
   var4.setUsername("EelcoVisser");
   var4.setPassword("foo");
   var4.setPerson(EelcoVisser);
   EelcoVisser.setUser(var4);
   Person var5 = new Person();
   var5.setFullname("Arie van Deursen");
   var5.setEmail("*****@*****.**");
   var5.setAddress(Mekelweg4);
   var5.setHomepage("http://www.st.ewi.tudelft.nl/~arie/");
   var5.setPhoto("http://www.st.ewi.tudelft.nl/~arie/pictures/arie-in-delft-klein.jpg");
   Person ArieVanDeursen = var5;
   Person var6 = new Person();
   var6.setFullname("Jos Warmer");
   var6.setEmail("*****@*****.**");
   var6.setAddress(Ordina);
   var6.setHomepage("http://www.klasse.nl/who/cv-jos.html");
   var6.setPhoto("http://www.klasse.nl/who/images/jos.gif");
   Person JosWarmer = var6;
   ResearchProject var7 = new ResearchProject();
   var7.setFullname("Model-Driven Software Evolution");
   var7.setAcronym("MoDSE");
   Set var8 = new HashSet();
   var8.add(EelcoVisser);
   var8.add(ArieVanDeursen);
   var8.add(JosWarmer);
   var7.setMembers(var8);
   var7.setDescription(
       "The promise of model-driven engineering (MDE) is that the development and maintenance effort can be reduced by working at the model instead of the code level. Models define what is variable in a system, and code generators produce the functionality that is common in the application domain. The problem with model-driven engineering is that it can lead to a lock-in in the abstractions and generator technology adopted at project initiation. Software systems need to evolve, and systems built using model-driven approaches are no exception. What complicates model-driven engineering is that it requires multiple dimensions of evolution. In regular evolution, the modeling language is used to make the changes. In meta-model evolution, changes are required to the modeling notation. In platform evolution, the code generators and application framework change to reflect new requirements on the target platform. Finally, in abstraction evolution, new modeling languages are added to the set of (modeling) languages to reflect increased understanding of a technical or business domain. While MDE has been optimized for regular evolution, presently little or no support exists for metamodel, platform and abstraction evolution. It is this gap that this project proposes to address. The first fundamental premise of this proposal is that evolution should be a continuous process. Software development is a continuous search for recurring patterns, which can be captured using domain-specific modeling languages. After developing a number of systems using a particular meta-model, new patterns may be recognized that can be captured in a higher-level or richer meta-model. The second premise is that reengineering of legacy systems to the model-driven paradigm should be a special case of this continuous evolution, and should be performed incrementally. The goal of this project is to develop a systematic approach to model-driven software evolution. This approach includes methods, techniques, and underlying tool support. We will develop a prototype programming environment that assists software engineers with the introduction, development, and maintenance of models and domain-specific languages.");
   ResearchProject MoDSE = var7;
   Publication var9 = new Publication();
   var9.setTitle("Domain-Specific Language Engineering");
   List var10 = new ArrayList();
   var10.add(EelcoVisser);
   var9.setAuthors(var10);
   var9.setYear(2007);
   var9.setAbstract(
       "The goal of domain-specific languages (DSLs) is to increase the productivity of software engineers by abstracting from low-level boilerplate code. Introduction of DSLs in the software development process requires a smooth workflow for the production of DSLs themselves. This tutorial gives an overview of all aspects of DSL engineering: domain analysis, language design, syntax definition, code generation, deployment, and evolution, discussing research challenges on the way. The concepts are illustrated with DSLs for web applications built using several DSLs for DSL engineering: SDF for syntax definition, Stratego/XT for code generation, and Nix for software deployment.");
   Set var11 = new HashSet();
   var11.add(MoDSE);
   var9.setProjects(var11);
   Publication GTTSE07 = var9;
   Publication var12 = new Publication();
   var12.setTitle("Model-Driven Software Evolution: A Research Agenda");
   List var13 = new ArrayList();
   var13.add(ArieVanDeursen);
   var13.add(JosWarmer);
   var13.add(EelcoVisser);
   var12.setAuthors(var13);
   var12.setYear(2006);
   var12.setAbstract(
       "Software systems need to evolve, and systems built using model-driven approaches are no exception.  What complicates model-driven engineering is that it requires multiple dimensions of evolution. In regular evolution, the modeling language is used to make the changes. In meta-model evolution, changes are required to the modeling notation.  In platform evolution, the code generators and application framework change to reflect new requirements on the target platform. Finally, in abstraction evolution, new modeling languages are added to the set of (modeling) languages to reflect increased understanding of a technical or business domain.  While MDE has been optimized for regular evolution, presently little or no support exists for metamodel, platform and abstraction evolution. In this paper, we analyze the problems raised by the evolution of model-based software systems and identify challenges to be addressed by research in this area.");
   Set var14 = new HashSet();
   var14.add(MoDSE);
   var12.setProjects(var14);
   Publication MoDSE07 = var12;
   MoDSE.setProposal(MoDSE07);
   Set var15 = new HashSet();
   var15.add(MoDSE07);
   var15.add(GTTSE07);
   MoDSE.setPublications(var15);
   em.persist(MoDSE);
 }
 private User formUser(Document document) {
   User user = new User();
   user.setUsername(document.getString(usernameKey));
   user.setPassword(document.getString(passwordKey));
   return user;
 }
Ejemplo n.º 28
0
  /**
   * menu principal onde são evocados todos os métodos
   *
   * @param user
   * @param pass
   */
  private void showMenu(String user, String pass, User Player) {
    String op = null;
    int option = 0;

    User player = new User("", "", "", 0);

    player.setUsername(user);
    player.setPassword(pass);
    while (true) { // uma vez logado e até fazer logout, cada vez que faz uma chamada de método, no
                   // final
      // retorna aqui, onde o menu é de novo impresso

      try {
        // uma vez logado e até fazer logout, cada vez que faz uma chamada de método, no final
        // retorna aqui, onde o menu é de novo impresso
        synchronized (System.out) {
          System.out.println("###############################################");
          System.out.println(" --------< MyBet-and-Win>-----------------------");
          System.out.println("(1) Credit: shows the current credit of the user.");
          System.out.println(
              "(2) Reset: userʼs credit should default to a certain number of credits (e.g. 100cr).");
          System.out.println("(3) View Current Matches");
          System.out.println("(4) Bet");
          System.out.println("(5) Online Users: shows a list of users who are logged in.");
          System.out.println("(6) Message User: sends a message to a specific user.");
          System.out.println("(7) Message All: sends a message to all the users.");
          System.out.println("(8) Logout.\n>");
        }
        // lê opção do teclado
        // lê opção do teclado
        // ---------------------------
        InputStreamReader input1 = new InputStreamReader(System.in);
        BufferedReader reader1 = new BufferedReader(input1);
        op = reader1.readLine();
        option = Integer.parseInt(op);

        System.out.println("Hi " + player.getUserName() + ". Here are the result of your call");
        switch (option) {
          case 1:
            System.out.println("------ (1) - CREDITS------------------------------------------");
            int receive = server.credits(player);
            System.out.println("[Server]>" + receive + " créditos.");
            System.out.println("-----------------------------------------------------------------");
            break;

          case 2:
            System.out.println(
                "--------(2) - RESET-------------------------------------------------");
            String receive1 = server.reset(player);
            System.out.println("[Server]" + receive1 + " créditos.");
            System.out.println("-----------------------------------------------------------------");
            break;

          case 3:
            System.out.println(
                "-----------(3) - VIEW MATCH-----------------------------------------");
            server.view(player, this);

            System.out.println("-----------------------------------------------------------------");
            break;

          case 4:
            int Crs = Player.getCredit();
            System.out.println("Os seus creditos:" + Crs);

            System.out.println(
                "--------------- (4) - BET ------------------------------------------");
            // tenho de preencher objecto do tpo betmatch (String username, int id, int resul, int
            // valor)
            System.out.println(
                "Para fazer uma aposta, seleccione o jogo através do [id] e utilize o sistema 1 2 3.");
            System.out.println("Insira o id do jogo em que pretende apostar\n>");
            String idJogo = reader1.readLine();
            System.out.println("Insira o número de créditos que pretende apostar\n>");
            String val = reader1.readLine();
            System.out.println(
                "Insira a sua aposta para o jogo. (1). Vitória da equipa da casa; (2).Vitória da equipa Visitante; (3).Empate;\n>");
            String res = reader1.readLine();
            // --------------------------------------------------------------
            // gets:
            String userN = Player.getUserName();

            // parseints:
            int id = Integer.parseInt(idJogo);
            int result = Integer.parseInt(res);
            int valor = Integer.parseInt(val);

            /*TCP«««««
            * BetMatch opt2 = new BetMatch();
                                   opt2.setCrs(value);
                                   opt2.setId(cod);
                                   opt2.setResul(resul);
                                   opt2.setType(1);
                                   opt2.setValor(value);
                                   opt2.setEmissor(user_name);
                                   out.writeObject(opt2);
            */

            BetMatch bM = new BetMatch();
            bM.setType(2);
            bM.setId(id);
            bM.setEmissor(userN);
            bM.setResul(result);
            bM.setValor(valor);
            bM.setCrs(Crs);

            // objecto: public BetMatch(String username, int id, int resul, int valor, int crs) {

            // ENVIO--->  username| id do jogo | resultado do jogo| valor a apostar|
            // BetMatch bM = new BetMatch(userN, id, result, valor, Crs); // chamada em callback
            // equivalente à de tcp

            server.betGame(userN, bM, this);

            // ja estou a enviar dados da aposta

            // preciso de receber

            // String receive3 = server.betGame(player);
            // System.out.println("[Server]" + receive3);

            System.out.println("-----------------------------------------------------------------");
            break;
          case 5:
            System.out.println(
                "----------- (5) - Online -------------------------------------------");
            ArrayList<String> temp = server.viewOnline(player);
            for (int i = 0; i < temp.size(); i++) {
              System.out.println(temp.get(i));
            }
            System.out.println("-----------------------------------------------------------------");
            break;
          case 6:
            System.out.println(
                "----------(6)- SEND MESSAGE to user ---------------------------------------------");
            System.out.println("Insira a mensagem\n>");
            String msg = reader1.readLine();
            System.out.println("Insira o destinatário");
            String receptor = reader1.readLine();

            // chama message User com mensagem (string) a enviar e receptor que é o destinatario
            server.messageS(msg, receptor, player);

            System.out.println("-----------------------------------------------------------------");
            break;
          case 7:
            System.out.println(
                "-----------(7)- SEND MESSAGE TO ALL -----------------------------------------------");
            System.out.println("Insira a mensagem\n>");
            String msg1 = reader1.readLine();

            server.messageA(msg1, player);

            System.out.println("-----------------------------------------------------------------");
            break;
          case 8:
            System.out.println("--------(8)- Logout----------------------------------------------");
            server.lOut(player);

            menu();
            break;
        }
      } catch (IOException ex) {
        Logger.getLogger(ClientRMI.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Ejemplo n.º 29
0
 public User getModel() {
   user.setGender(Gender.BOY);
   user.setUsername("mmmmm");
   user.setPassword("ppppp");
   return user;
 }
Ejemplo n.º 30
0
  // Method that makes it possible for the user to log in
  public User Login(ScreenFrame frame, ServerConnection server, User currentUser, Parsers parser) {

    // Sets variables username and password equal to the typed values in the LoginScreen panel
    String username = frame.getLoginScreen().getTfUsername().getText();
    String password = frame.getLoginScreen().getTfPassword().getText();

    // Try/catch for error handling through exceptions
    try {
      // If-statement for checking the typed values.
      // If the typed values aren't equal to "" (empty textfields) the method will be executed
      if (!username.equals("") & !password.equals("")) {

        User user = new User();

        // Sets the username and password for the logged in user equal to the typed values
        user.setUsername(username);
        user.setPassword(password);

        // Sends
        String json = new Gson().toJson(user);

        // Sends
        String message = parser.loginParser((server.post(json, "login/")), user);

        // Checks whether the received message is equal to the wanted one
        if (message.equals("Login successful")) {

          currentUser = user;

          // Uses the userParser method to get ..
          parser.userParser(server.get("users/" + currentUser.getId() + "/"), currentUser);

          // Leads the user to the usermenu
          frame.show(frame.USERSCREEN);

          // Returns the value/variable/object currentUser to define who's logged in
          return currentUser;

          // If the server can't fit the typed values
          // Responds following received message with a JOptionPane that will warn the user
        } else if (message.equals("Wrong username or password")) {

          JOptionPane.showMessageDialog(
              frame,
              "Wrong username or password. Please try again",
              "Error",
              JOptionPane.ERROR_MESSAGE);

          // If the error is elsewhere than in the typed values
          // Responds following received message with a JOptionPane that will warn the user
        } else if (message.equals("Error in JSON")) {

          JOptionPane.showMessageDialog(frame, "Error", "Error", JOptionPane.ERROR_MESSAGE);
        }
      }

      // Prints a stacktrace when catching an unforeseen error
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }