Package clientFunction

Source Code of clientFunction.User

package clientFunction;


import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.Vector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
* Class that implement a User
* @author Marco Guarnieri and others
*
*/
public class User {

  /** ID of the user */
  private Integer id = -1;
  /** Name of the user */
  private String name;
  /** Surname of the user */
  private String surname;
  /** Birthdate of the user in string */
  private String stringBirthDate;
  /** Birthdate of the user in Date */
  private java.sql.Date birthDate;
  /** Birthplace of the user*/
  private String birthPlace;
  /** Nationality of the user*/
  private String nationality;
  /** Marital status of the user*/
  private String maritalStatus;
  /** Username of the user*/
  private String username;
  /** Password of the user*/
  private String password = "";
  /** ConfirmedPassword of the user*/
  private String confirmPassword = "";
  /** Indicate if the user is logged or not */
  private Boolean logged = false;
  /** Indicate if the user has already checked his pin*/
  private Boolean  pinChecked = false;

  /**
   * Class constructor
   */
  public User() {

  }

  /**
   * Class constructor
   * @param name
   * @param surname
   * @param birthDate
   * @param birthPlace
   * @param nationality
   * @param maritalStatus
   * @param username
   * @param password
   * @param confirmPassword
   */
  /*public User(String name, String surname, Date birthDate, String birthPlace,
      String nationality, String maritalStatus, String username,
      char[] password, char[] confirmPassword) {

    setName(name);
    setSurname(surname);
    setBirthDate(birthDate);
    setBirthPlace(birthPlace);
    setNationality(nationality);
    setMaritalStatus(maritalStatus);
    setUsername(username);
    setPassword(password);
    setConfirmPassword(confirmPassword);
  }*/

  /**
   * Set the user's parameters
   * @param name - name of the user
   * @param surname - surname of the user
   * @param birthDate - birthdate of the user
   * @param birthPlace - birthplace of the user
   * @param nationality - nationality of the user
   * @param maritalStatus - marital status of the user
   * @param username - username of the user
   * @param password - password of the user
   * @param confirmPassword - confirmed password of the user
   */
  public void setUser(String name, String surname, String birthDate, String birthPlace,
      String nationality, String maritalStatus, String username,
      String password, String confirmPassword) {
    setName(name);
    setSurname(surname);
    setBirthDate(birthDate);
    setBirthPlace(birthPlace);
    setNationality(nationality);
    setMaritalStatus(maritalStatus);
    setUsername(username);
    setPassword(password);
    setConfirmPassword(confirmPassword);
  }


  /**
   * Register the user
   * @throws Exception
   */
  public final void register() throws Exception{
    //createKey();
    save();
    //addDHKPair();
  }

  /**
   * Check if the passed username already exists or not.
   * @param username - username
   * @return true if the user already exists, false otherwise
   * @throws Exception
   */
  public static boolean exists (String username) throws Exception
  {
    DBConnection connection = new DBConnection();
    String sql = "SELECT  subjectid from usertable where username = '"+username+"'";

    ResultSet rset = connection.getConnection().createStatement().executeQuery(sql);
    if(rset.next())
    {  connection.closeConnection();
    return true;
    }
    else
    connection.closeConnection();
    return false;
    }


  }


  /**
   * Check if the passed password is equals to the result of hashing of the password in db
   * @param username - username of the user
   * @param password - password to check
   * @return true if the passed password is equals to the password into DB, false otherwise
   * @throws Exception
   */
  public boolean login(String username, String password) throws Exception{
    boolean ok = false;
    DBConnection connection = new DBConnection();

    //Check if no password temp saved
    ResultSet resTemp = connection.getConnection().createStatement().executeQuery("SELECT * FROM temp WHERE id = 1");
    if(resTemp.next()){
      connection.getConnection().createStatement().execute("DELETE FROM temp WHERE id = 1");
    }
    resTemp.close();

    //Temporary insert of password hash in temp
    PreparedStatement prepStat = connection.getConnection().prepareStatement("INSERT INTO temp values(?, ?)");
    prepStat.setInt(1, 1);
    prepStat.setBytes(2, Utility.SHA1(password));
    prepStat.executeUpdate();

    resTemp = connection.getConnection().createStatement().executeQuery("SELECT * FROM temp WHERE id = 1");
    String passwPassed = "";
    if(resTemp.next()){
      passwPassed = Utility.toStr(resTemp.getBytes("tmp"));
    }
    resTemp.close();

    String sql = "SELECT  subjectid, name, surname, username, password from usertable where username = '%s'";
    sql = String.format(sql, username);

    ResultSet rset = connection.getConnection().createStatement().executeQuery(sql);

    // User found?
    if (rset.next()){
      if ((Utility.toStr(Utility.SHA1(password))).equals(Utility.toStr(rset.getBytes("password")))) {
        setId(rset.getInt("subjectid"));
        setUsername(rset.getString("username"));
        setName(rset.getString("name"));
        setSurname(rset.getString("surname"));
        setLogged(true);
        ok = true;
      } else {
        if(passwPassed.equals(Utility.toStr(rset.getBytes("password")))){
          setId(rset.getInt("subjectid"));
          setUsername(rset.getString("username"));
          setName(rset.getString("name"));
          setSurname(rset.getString("surname"));
          setLogged(true);
          ok = true;
        }
      }
    }
    connection.getConnection().createStatement().execute("DELETE FROM temp WHERE id = 1");
    connection.closeConnection();
    return ok; 
  }

  /**
   * Check if the password of this object is equals to the password contained in the DB for this username.
   * @return true if the passed password is equals to the password into DB, false otherwise
   * @throws Exception
   */
  public boolean login() throws Exception{
    return this.login(getUsername(), getPassword());
  }


  /**
   * Get the key for this user
   * @return byte[] -  contains the key for this user
   * @throws Exception in case of failed retrieve of the key
   */
  public byte[] getKey() throws Exception{
    return Utility.getKey(getUsername());   
  }

  /**
   * Save the user into the DB
   * @throws Exception
   */
  public void save() throws Exception {
    DBConnection connection=new DBConnection();
    check();

    Statement stmt = connection.getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

    ResultSet r = stmt.executeQuery("select * from usertable");

    r.moveToInsertRow();

    r.updateString("name", name);
    r.updateString("surname", surname);
    r.updateDate("birthdate", birthDate);
    r.updateString("birthplace", birthPlace);
    r.updateString("nationality", nationality);
    r.updateString("maritalstatus", maritalStatus);
    r.updateString("username", username);   
    r.updateBytes("password", Utility.SHA1(password));

    r.insertRow();
    stmt.close();
    connection.closeConnection();

  }

  /**
   * Check if the parameters of this user are correct
   * @throws Exception in case of error into the parameters
   */
  public void check() throws Exception {

    String errors = "";

    if (getName().length() < 4)
      errors += "- Name must have at least 4 characters\n";

    if (getSurname().length() < 4)
      errors += "- Surname must have at least 4 characters\n";

    if(Utility.stringToDate(getStringBirthDate()) == null) {
      errors += "- Birth date is not a date\n";
    } else {
      setBirthDate(Utility.stringToDate(getStringBirthDate()));
    }

    if (getBirthPlace().length() < 4)
      errors += "- Birth Place must have at least 4 characters\n";

    if (getNationality().length() < 2)
      errors += "- Nationality must have at least 2 characters\n";

    if (getMaritalStatus().length() == 0)
      errors += "- Marital Status must be selected\n";

    if(getUsername().length() < 4)
      errors += "- Username must have at least 8 characters\n";

    if(getPassword().length() < 4 || getConfirmPassword().length() < 4)
      errors += "- Password must have at least 4 characters\n";

    if(!getPassword().equals(getConfirmPassword()))
      errors += "- Passwords do not match\n";

    if(exists(getUsername()))
      errors += "- Username already exists. Please change it.";

    if(errors.length() > 0)
      throw new Exception(errors);

  }


  /**
   * Load all the groups linked to this user
   * @return Vector<String> - contains all the groups linked to this user
   * @throws Exception
   */
  public Vector<String>  loadGroups() throws Exception{
    Vector<String> vector = new Vector<String>();
    DBConnection connection=new DBConnection();
    String sql = "SELECT name from grouptable where owner = '%s';";
    sql = String.format(sql, getId());

    ResultSet rset = connection.getConnection().createStatement().executeQuery(sql);

    if (rset != null) {
      while (rset.next()) {

        vector.add(rset.getString("name"));

      }
      rset.close();
    }
    connection.closeConnection();
    return vector;
  }


  /**
   * Get the pin of the user
   * @return JSONObject - containing the hashed pin and the ID,name,surname of the user
   * @throws Exception
   */
  public JSONObject getPinInfo() throws Exception{
    JSONObject message = new JSONObject();
    DBConnection connection=new DBConnection();
    String sql = "SELECT  subjectid, name, surname, hashpwd from usertable where subjectid = '%s'";
    sql = String.format(sql, this.getId());

    ResultSet rset = connection.getConnection().createStatement().executeQuery(sql);

    // User found
    if (rset.next()){
      JSONObject ob2 = new JSONObject();
      ob2.put("hashpin", rset.getString("hashpwd"));
      ob2.put("info", rset.getString("subjectid") + rset.getString("name") + rset.getString("surname"));

      JSONArray array = new JSONArray();
      array.put(ob2);

      message.put("values", array);

    }
    connection.closeConnection();
    return message;
  }

  /**
   * Insert into the DB the public and private key. Update the user table with the hashed pin.
   * @param json - string containing the two keys and the hashed pin
   * @throws SQLException
   * @throws Exception
   */
  public void insertDHandHashInDB(String json) throws SQLException, Exception {
    JSONObject root = new JSONObject(json);
    DBConnection connection = new DBConnection();
    String sql = "INSERT INTO dhkatable (subjectid,publickey,privatekey) VALUES('%d', '%s', '%s');";
    sql = String.format(sql, getId(),
        root.getString("public"),
        root.getString("private")
    );

    connection.getConnection().createStatement().execute(sql);

    sql = "UPDATE usertable SET hashpwd = '%s' WHERE subjectid = '%d';";
    sql = String.format(sql,
        root.getString("hash"),
        getId()
    );

    connection.getConnection().createStatement().execute(sql);
    connection.closeConnection();

  }

  /**
   * Return a JSONObject containing the list of the user, excluded this user ( the owner ), for sharing a file
   * @return JSONObject - users list
   * @throws JSONException
   */
  public JSONObject getUsersList() throws JSONException {

    JSONObject response = new JSONObject();
    JSONArray array = new JSONArray();
    DBConnection connection=new DBConnection();
    try {
      Statement stmt = connection.getConnection().createStatement();
      ResultSet rset  = stmt
      .executeQuery("SELECT subjectid,name,surname from usertable where subjectid <> " + getId() + " AND subjectid <> 0 order by surname, name ");

      if (rset != null) {
        while (rset.next()) {
          JSONObject temp = new JSONObject();
          temp.put("id", rset.getString(1));
          temp.put("name", rset.getString(2));
          temp.put("surname", rset.getString(3));
          array.put(temp);
        }

      }

      rset.close();
      stmt.close();

    } catch (Exception e) {
      System.err.println(e.toString());
    }

    response.put("values", array);
    connection.closeConnection();
    return response;
  }

  /**
   * Check if the user is into the DB
   * @return true if the user is into the DB, false otherwise
   * @throws Exception
   */
  boolean isStored() throws Exception{
    return getSubjecID() != -1 ? true : false;
  }

  /**
   * Get the subjectID from the usertable into DB for the user with this username
   * @return Integer - contains the ID. -1 in case of error
   * @throws Exception
   */
  public Integer getSubjecID() throws Exception {

    Integer subjectid  = getId();
    DBConnection connection=new DBConnection();
    // Se non ho ancora letto dal db il codice getId = -1
    if( subjectid == -1){

      String sql = "SELECT subjectid from usertable where username='%s'";
      sql = String.format(sql, username);

      ResultSet rset = connection.getConnection().createStatement().executeQuery(sql);

      if (rset != null) {
        rset.next();
        subjectid = rset.getInt("subjectid");
      } else {
        subjectid = -1;
      }
      rset.close();
    }
    connection.closeConnection();
    return subjectid;
  }


  /**
   * Get the birth date of this user
   * @return Date - birth date
   */
  public Date getBirthDate() {
    return birthDate;
  }

  /**
   * Get the birth date  of this user into a string
   * @return String -  birth date
   */
  public String getStringBirthDate() {
    return stringBirthDate;
  }

  /**
   * Set the birth date of this user
   * @param date - birth date ( Date Object )
   */
  public void setBirthDate(java.sql.Date date) {
    this.birthDate = date;
  }

  /**
   * Set the birth date of this user
   * @param date - birth date ( String Object )
   */
  public void setBirthDate(String birthDate) {
    this.stringBirthDate = birthDate;
  }

  /**
   * Get the birth place of this user
   * @return String - birth place
   */
  public String getBirthPlace() {
    return birthPlace;
  }

  /**
   * Set the birth place of this user
   * @param birthPlace - birth place
   */
  public void setBirthPlace(String birthPlace) {
    this.birthPlace = birthPlace;
  }

  /**
   * Get Marital status of this user
   * @return String - marital status
   */
  public String getMaritalStatus() {
    return maritalStatus;
  }

  /**
   * Set the marital status of this user
   * @param maritalStatus - marital status
   */
  public void setMaritalStatus(String maritalStatus) {
    this.maritalStatus = maritalStatus;
  }

  /**
   * Get the name of this user
   * @return String - name of the user
   */
  public String getName() {
    return name;
  }

  /**
   * Check if the hashpwd into usertable for this user is not null
   * @return true if the hashpwd is not null, false otherwise
   * @throws Exception
   */
  public boolean hasKeys() throws Exception {
    Integer subjectid  = getId();
    Boolean hasKey = false;
    DBConnection connection=new DBConnection();
    // Se non ho ancora letto dal db il codice getId = -1
    if( subjectid != -1){

      String sql = "SELECT hashpwd from usertable where subjectid=" + subjectid;

      ResultSet rset = connection.getConnection().createStatement().executeQuery(sql);

      if (rset != null) {
        rset.next();

        if (rset.getString("hashpwd") != null){
          hasKey = true;
        }
      }
      rset.close();
    }
    connection.closeConnection();
    return hasKey;
  }

  /**
   * Set the name of this user
   * @param name - name of the user
   */
  public void setName(String name) {
    this.name = name;
  }

  /**
   * Get the nationality of this user
   * @return String - Nationality of this user
   */
  public String getNationality() {
    return nationality;
  }

  /**
   * Set the nationality of this user
   * @param nationality - nationality of the user
   */
  public void setNationality(String nationality) {
    this.nationality = nationality;
  }

  /**
   * Get the password of this user
   * @return String - password
   */
  public String getPassword() {
    return password;
  }

  /**
   * Set the password of this user
   * @param password - password to set
   */
  public void setPassword(String password) {
    this.password = password;
  }

  /**
   * Get the surname of this user
   * @return String - surname
   */
  public String getSurname() {
    return surname;
  }

  /**
   * Set the surname of this user
   * @param surname - surname to set
   */
  public void setSurname(String surname) {
    this.surname = surname;
  }

  /**
   * Get the username of this user
   * @return String - username
   */
  public String getUsername() {
    return username;
  }

  /**
   * Set the username of this user
   * @param username - username to set
   */
  public void setUsername(String username) {
    this.username = username;
  }

  /**
   * Get the confirmed password of this user
   * @return String - confirmed password
   */
  public String getConfirmPassword() {
    return confirmPassword;
  }

  /**
   * Set the confirmed password of this user
   * @param confirmpassword - confirmed password to set
   */
  public void setConfirmPassword(String confirmPassword) {
    this.confirmPassword = confirmPassword;
  }

  /**
   * Get the ID of this user
   * @return Integer - ID
   */
  public Integer getId() {
    return this.id;
  }

  /**
   * Set the ID of this user
   * @param ID - ID to set
   */
  public void setId(Integer id) {
    this.id = id;
  }

  /**
   * Set the state of this user
   * @param logged - state to set
   */
  public void setLogged(Boolean logged) {
    this.logged = logged;
  }

  /**
   * Get the state of this user
   * @return Boolean - true if the user is logged, false otherwise
   */
  public Boolean getLogged() {
    return logged;
  }

  /**
   * Set the state of this user
   * @param logged - state to set
   */
  public void setPinChecked(Boolean checked) {
    this.pinChecked = checked;
  }

  /**
   * Get the state of this user
   * @return Boolean - true if the user has already checked his pin, false otherwise
   */
  public Boolean getPinChecked() {
    return pinChecked;
  }

  /**
   * Get the friends of the user
   * @param user - id of the user that do the request
   * @return list of friends
   * @throws SQLException
   * @throws JSONException
   */
  public static JSONObject getFriends(String user) throws SQLException, JSONException{
    DBConnection connection = new DBConnection();

    Statement stmt = connection.getConnection().createStatement();

    ResultSet rset = stmt.executeQuery("SELECT users FROM viewinformations WHERE users like '%-"+user+"'");

    LinkedList<String> friends = new LinkedList<String>();

    while(rset.next()){
      String users = rset.getString(1);
      String[] splitusers = users.split("-");
      String friend = splitusers[0];

      friends.add(friend);
    }
    rset.close();
    JSONObject response = new JSONObject();
    JSONArray array = new JSONArray();

    if(friends.size()!=0){ 
      String s=friends.toString();
      s=s.replace("[", "(");
      s=s.replace("]", ")");
      s=s.replace(", ", ",");

      rset = stmt
      .executeQuery("SELECT subjectid,name,surname from usertable where subjectid in "+s+" order by surname, name ");

      if (rset != null) {
        while (rset.next()) {
          JSONObject temp = new JSONObject();
          temp.put("id", rset.getString(1));
          temp.put("name", rset.getString(2));
          temp.put("surname", rset.getString(3));
          array.put(temp);
        }
      }
    }
    rset.close();
    stmt.close();

    connection.closeConnection();

    response.put("values", array);

    return response;
  }
}
TOP

Related Classes of clientFunction.User

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.