Пример #1
0
 public static void update(User user) {
   if (user.getId() == null) {
     throw new UpdateUserException("require userId");
   }
   User sourceUser = (User) findById(user.getId());
   if (sourceUser == null) {
     throw new UpdateUserException("no matched user, userId is [" + user.getId() + "]");
   }
   boolean needUpdate = false;
   if (!StringUtils.equals(user.name, sourceUser.name)) {
     needUpdate = true;
   }
   if (!needUpdate && !StringUtils.equals(user.profileImageUrl, sourceUser.profileImageUrl)) {
     needUpdate = true;
   }
   if (!needUpdate && !StringUtils.equals(user.screenName, sourceUser.screenName)) {
     needUpdate = true;
   }
   if (!needUpdate && user.uid != sourceUser.uid) {
     needUpdate = true;
   }
   if (needUpdate) {
     user.save();
   }
 }
  // PAS FINI ?
  @Override
  public boolean createUser(User user) throws SQLException {
    if (SQLSettings.getPDS() == null) System.err.println("getPDS() not started.");
    ResultSet rset = null;
    int rset2;
    Statement stmt = null;
    Connection connection = null;

    try {
      connection = SQLSettings.getPDS().getConnection();
      stmt = connection.createStatement();
      String encryptedPass = null;

      rset = stmt.executeQuery("select PASSWORD('" + user.getPassword() + "') ;");
      if (rset != null) {
        while (rset.next()) {
          encryptedPass = rset.getString(1);
        }
        rset2 =
            stmt.executeUpdate(
                "create user '"
                    + user.getLogin()
                    + "'@'%' IDENTIFIED BY PASSWORD '"
                    + encryptedPass
                    + "' ;");

        String[] viewCommand = Scripts.getCreateUserViews(user);
        // On cree les vues utilisateur et on donne les acces
        for (String curcom : viewCommand) rset2 = stmt.executeUpdate(curcom);

        // on insere le tuple dans user_view
        UserViewDAO uvdao = new MySQLUserViewDAO();
        uvdao.addUserView(user.getLogin(), user.getId());

        return true;
      }

      return false;

    } catch (SQLException e) {
      e.printStackTrace();
      throw e;
    } finally {
      try {
        if (rset != null) rset.close();
      } catch (Exception e) {
      }
      ;
      try {
        if (stmt != null) stmt.close();
      } catch (Exception e) {
      }
      ;
      try {
        if (connection != null) connection.close();
      } catch (Exception e) {
      }
      ;
    }
  }
Пример #3
0
  /** This method is used to retrieve data and show it on the screen */
  public void render() {
    jLabelName.setText(this.subscription.getTitle());
    jLabelGender.setText("Man");
    jLabelAge.setText(String.valueOf(this.subscription.getMinimumAge()));
    jLabelDays.setText(CourseInfo.implode(this.subscription.getDays(), ", "));
    jLabelDuration.setText(
        String.valueOf(this.subscription.getStartTime())
            + " - "
            + String.valueOf(this.subscription.getEndTime()));
    jLabelDescription.setText(this.subscription.getDescription());
    jLabelBranch.setText(this.subscription.getBranch().getCity());

    // Empty results
    jLabelUser.setText("");
    jBtnSubmit.setVisible(false);

    // Age range
    if (this.subscription.getMaximumAge() <= 16) jLabelAge.setText("< 16");
    else if (this.subscription.getMaximumAge() <= 18) jLabelAge.setText("16 - 18");
    else if (this.subscription.getMaximumAge() <= 65) jLabelAge.setText("18 - 65");
    else if (this.subscription.getMaximumAge() <= 150) jLabelAge.setText("65+");

    // Enrollments
    ArrayList<User> users = Enrollment.readBySubscriptionId(this.subscription.getId());

    for (User user : users) {
      if (user.getFullName() != "" && user.getFirstname() != null) {
        this.model.insertRow(0, new Object[] {user.getId(), user.getFullName()});
      }
    }

    // Make a selection listener
    this.row = jTableUsers.getSelectionModel();
    this.row.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
  }
Пример #4
0
 private void saveUpdateUser() {
   setAllFildsToUser();
   UserIntf userBc = UserImpl.getInstance();
   if (_user.getId() > 0) {
     userBc.updateUser(_user);
   } else {
     userBc.saveUser(_user);
   }
 }
Пример #5
0
 /**
  * This method registers a new administrator in the system. The authentication object must be from
  * an administrator.
  *
  * @param a the authentication object
  * @param ui the new user's information
  * @param pw the new user's password
  * @return the authentication of the registered user
  */
 public boolean newAdmin(Auth a, UserInfo ui, String pw) {
   if (!dbc.loadUser(a.getUserID()).isAdministrator()) return false;
   User u = new User(ui);
   u.setPassword(pw);
   if (dbc.newUser(u)) {
     User nu = dbc.loadUser(u.getId());
     return nu != null;
   }
   return false;
 }
Пример #6
0
 /**
  * This method registers a new user in the system
  *
  * @param ui the new user's information
  * @param pw the new user's password
  * @return the authentication of the registered user
  */
 public Auth newUser(UserInfo ui, String pw) {
   User u = new User(ui);
   u.setPassword(pw);
   u.setAdministrator(false);
   if (dbc.newUser(u)) {
     User nu = dbc.loadUser(u.getId());
     return new SAuth(Auths.getInstance().login(nu, nu.getPassword()));
   }
   return null;
 }
Пример #7
0
  // Method that allows the user to create a new game in the database
  public void CreateGame(
      ScreenFrame frame, ServerConnection server, User currentUser, Parsers parser) {

    try {

      // Defining variables from typed values in the CreateScreen panel
      String gamename = frame.getCreate().getTfGameName().getText();
      int mapSize = frame.getCreate().getTfMapSize();
      String controls = frame.getCreate().getTfControls().getText();

      // Checks whether the typed in values are legitimate
      // Strings controls and gamename can't be empty and the map size can't be 0
      if (!controls.equals("") && mapSize != 0 && !gamename.equals("")) {

        // Creates objects of/instansialize Game and Gamer classes
        Game game = new Game();
        Gamer gamer = new Gamer();

        // Sets controls equal to the typed controls
        gamer.setControls(controls);

        // Sets id equal to the logged in user (the current user)
        gamer.setId(currentUser.getId());

        // Sets the above defined id as the host of the game
        game.setHost(gamer);

        // Sets the gamename and mapsize equal to the typed values
        game.setName(gamename);
        game.setMapSize(mapSize);

        // All of the above setters are used to @post the variables into the database
        //
        String json = new Gson().toJson(game);
        String message = parser.createParser(server.post(json, "games/"));

        // Checks if the received list of games contains the newly created game
        // If so a confirmation will be shown to the user
        if (message.equals(game.getName())) {

          JOptionPane.showMessageDialog(
              frame,
              "Game was created!\nIt's called " + game.getName(),
              "Success!",
              JOptionPane.INFORMATION_MESSAGE);
        }
      }

      // Prints a stacktrace when catching an unforeseen error
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #8
0
  public static void listUsers(ArrayList<User> userList) {

    for (User user : userList) {
      System.out.println(
          "Id: "
              + user.getId()
              + "\tUser: "******"\tStatus: "
              + user.getStatus());
    }
  }
Пример #9
0
  /**
   * This method searches the user you type in the textfield. The user is searched to add him to the
   * course.
   */
  public void searchUser() {
    // Empty results
    jLabelUser.setText("");
    jBtnSubmit.setVisible(false);

    // Search a user and return a result
    User user = new User();

    try {
      int id = Integer.parseInt(jTextId.getText());
      user.readUser(id);
      if (user.getId() > 0) {
        this.userId = user.getId();
        // Set the label
        jLabelUser.setText(user.getFullName());
        jBtnSubmit.setVisible(true);
      }
    } catch (Exception ex) {
      ExceptionHandler.handle(ex, ExceptionHandler.TYPE_SYSTEM_ERROR);
    }
  }
Пример #10
0
 public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   req.setCharacterEncoding("UTF-8");
   res.setContentType("UTF-8");
   String title = req.getParameter("title");
   String content = req.getParameter("content");
   User user = (User) req.getSession().getAttribute("user");
   LyTable ly = new LyTable();
   ly.setUserId(user.getId());
   ly.setDate(new Date(System.currentTimeMillis()));
   ly.setTitle(title);
   ly.setContent(content);
   if (new DB().addInfo(ly)) {
     res.sendRedirect("success.jsp");
   }
 }
Пример #11
0
  private void jBtnSubmitActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jBtnSubmitActionPerformed
    Enrollment enrollment = new Enrollment();

    enrollment.readEnrollmentBySubscriptionIdAndUserId(this.subscription.getId(), this.userId);

    if (enrollment.isEnrolled() == false) {
      enrollment.subscribe(this.subscription.getId(), this.userId);

      User user = new User();
      user.readUser(this.userId);

      this.model.insertRow(0, new Object[] {user.getId(), user.getFullName()});

      Application.getInstance()
          .showPopup(new SuccessPopup("Deelnemer " + user.getFullName() + " is ingeschreven."));
    } else {
      Application.getInstance().showPopup(new ErrorPopup("De deelnemer is al ingeschreven."));
    }
  } // GEN-LAST:event_jBtnSubmitActionPerformed
Пример #12
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;
  }
Пример #13
0
  // Method that allows the user to join a game and at the same time starting, determining who's the
  // winner
  public void JoinGame(
      ScreenFrame frame, ServerConnection server, User currentUser, Parsers parser) {

    // Try/catch for error handling through exceptions
    try {

      // Defines the variables gameId for the game and controls for the joining user
      // GamId is set as type long because the server apparently sends back long type variables
      long gameId = frame.getJoin().getTfGameId();
      String controls = frame.getJoin().getTfControls().getText();

      // Checks whether the opponent typed controls are legitimate
      if (!controls.equals("")) {

        // Instansierer/create new objects of game and gamer class
        Game game = new Game();
        Gamer gamer = new Gamer();

        // Sets the gamer id equal to the current users id
        gamer.setId(currentUser.getId());

        // Sets the typed in controls equal to gamer controls
        gamer.setControls(controls);

        // Sets the gameId equal to the typed gameId
        game.setGameId(gameId);

        // Sets the gamer to being the opponent
        game.setOpponent(gamer);

        String json = new Gson().toJson(game);

        String message = parser.messageParser(server.put("games/join/", json));

        // Checks whether the PUT-request succeeded
        if (message.equals("Game was joined")) {

          //
          Game joined = parser.joinParser(server.put("games/start/", json));

          joined = parser.joinParser(server.get("game/" + joined.getGameId() + "/"));

          // If the SnakeMasterId is equal to the opponent (current user)
          // the panel shows a message confirming that the opponent won
          if (joined.getSnakeMasterId() == currentUser.getId()) {

            JOptionPane.showMessageDialog(
                frame, "You joined the game and won!", "WINNER!", JOptionPane.INFORMATION_MESSAGE);

            // If the SnakeMasterId isn't equal to the current users
            // the panel shows a message confirming that the host won
          } else if (joined.getSnakeMasterId() != currentUser.getId()) {

            JOptionPane.showMessageDialog(
                frame,
                "You joined the game and lost!\nBuhuu..",
                "LOSER",
                JOptionPane.INFORMATION_MESSAGE);
          }

          // If the PUT-request message equals "Game closed"
          // the panel shows error message to the user
        } else if (message.equals("Game closed")) {

          JOptionPane.showMessageDialog(
              frame,
              "The Game is closed. Check your Game Id again",
              "NOPE",
              JOptionPane.ERROR_MESSAGE);
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #14
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, BiffException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    HttpSession sesion = ((HttpServletRequest) request).getSession();
    RequestDispatcher dispatcher = null;

    // variables
    String action = "",
        user = "",
        password = "",
        file = "",
        nombres = "",
        apellidos = "",
        estado = "";
    String idperfil_str = "", idusuario_str = "", email = "", telefono = "", direccion = "";
    int idperfil = 0, idusuario = 0, modificaciones = 0;

    // interfaces y objetos
    // usuarioInterface U = new usuarioService();
    User Us = new User();
    userHelper userhelp = new userHelper();

    try {
      action = request.getParameter("action");
    } catch (Exception e) {
      action = "";
    }

    if (action.equals("loginAutenticar")) {
      user = request.getParameter("user");
      password = request.getParameter("passw");

      try {
        Us = userhelp.existeUser(user, password);
      } catch (Exception e) {
        Us = null;
      }
      try {
        if (Us != null) {
          // pe= userhelp.getPerfil(Us.getIdPerfil());
          sesion.setAttribute("IdUsuarioSesion", Us.getId());
          sesion.setAttribute("nickUsuarioSesion", Us.getUsername());
          sesion.setAttribute("nombreUsuarioSesion", Us.getForenames());
          sesion.setAttribute("apellidosUsuarioSesion", Us.getSurnames());
          // #################################################################
          // Actualiza ultimo acceso que tiene el usuario al sistema

          // modificaciones= userhelp.editUser(Us, Us.getId());
          // #################################################################
          dispatcher = request.getRequestDispatcher("client.jsp");
          dispatcher.forward(request, response);

        } else {
          // Guargar log en Bitácora
          dispatcher =
              request.getRequestDispatcher(
                  "index.jsp?resp=Usuario y/o " + "contraseña incorrectos");
          dispatcher.forward(request, response);
        }

        // dispatcher.forward(request, response);
      } catch (Exception e) {

      }
    } else if (action.equals("saliraplicacion")) {
      try {
        sesion.setAttribute("IdUsuarioSesion", null);
        sesion.setAttribute("nickUsuarioSesion", null);
        sesion.setAttribute("nombreUsuarioSesion", null);
        sesion.setAttribute("apellidosUsuarioSesion", null);
        sesion.setAttribute("IdPerfilSesion", null);
        sesion.invalidate();
        response.sendRedirect(response.encodeRedirectURL("index.jsp"));

      } catch (Exception e) {
        out.print("error");
      }

    } else if (action.equalsIgnoreCase("cargarCliente")) {
      try {
        file = request.getParameter("fileField");

        System.out.println("este es:" + file);
        Workbook workbook =
            Workbook.getWorkbook(new File(file)); // Pasamos el excel que vamos a leer
        Sheet sheet = workbook.getSheet(0); // Seleccionamos la hoja que vamos a leer
        String nombre;

        for (int fila = 1; fila < sheet.getRows(); fila++) { // recorremos las filas
          for (int columna = 0;
              columna < sheet.getColumns();
              columna++) { // recorremos las columnas
            nombre = sheet.getCell(columna, fila).getContents(); // setear la celda leida a nombre
            System.out.print(nombre + ""); // imprimir nombre
          }
        }

        dispatcher = request.getRequestDispatcher("client.jsp");
        dispatcher.forward(request, response);

        // dispatcher.forward(request, response);
      } catch (Exception e) {

      }
    } else if (action.equalsIgnoreCase("getusuario")) {

      Us = new User();
      idusuario_str = request.getParameter("iduser");
      idusuario = idusuario_str.equals("") ? 0 : Integer.parseInt(idusuario_str);
      Us = userhelp.getUserByID(idusuario);
      String resp = "", separador = "%";

      //         resp =
      // Us.getUsuario()+separador+Us.getNombres()+separador+Us.getApellidos()+separador+Us.getEmail()+separador+
      //
      // Us.getIdPerfil()+separador+idusuario+separador+Us.getContrasena()+separador+Us.getTelefono()+separador+Us.getDireccion();

      // Us.setFechaCreacion(diaHoraActual);
      // Us.setFechaModificacion(diaHoraActual);
      out.write(resp);
    } else if (action.equalsIgnoreCase("getDataUser")) {

      Us = new User();
      idusuario_str = request.getParameter("iduser");
      idusuario = idusuario_str.equals("") ? 0 : Integer.parseInt(idusuario_str);
      Us = userhelp.getUserByID(idusuario);
      String resp = "", separador = "%";

      //         resp =
      // Us.getUsuario()+separador+Us.getNombres()+separador+Us.getApellidos()+separador+Us.getEmail()+separador+
      //
      // Us.getIdPerfil()+separador+idusuario+separador+Us.getContrasena()+separador+Us.getTelefono()+separador+Us.getDireccion();

      // Us.setFechaCreacion(diaHoraActual);
      // Us.setFechaModificacion(diaHoraActual);
      out.write(resp);
    }
  }
Пример #15
0
  public String login() throws Exception {
    final String login_fail = "login_fail";

    this.status = "默认!!!";
    if (ServletActionContext.getRequest().getMethod().equalsIgnoreCase("get")) {
      return ActionSupport.SUCCESS;
    }
    if (username == null || username == "") {
      this.status = "用户名不能为空";
      return login_fail;
    }

    Session session = model.Util.sessionFactory.openSession();
    Criteria q = session.createCriteria(User.class).add(Restrictions.eq("username", username));
    List ul = q.list();

    if (ul.isEmpty()) {
      session.close();
      return login_fail;
    }
    User u = (User) ul.get(0);
    if (!u.getPassword().equals(password)) {
      session.close();
      return login_fail;
    }

    String role = "";
    ul =
        session
            .createCriteria(model.AdminProfile.class)
            .add(Restrictions.eq("user.id", u.getId()))
            .list();
    if (!ul.isEmpty()) {
      role = util.Const.AdminRole;
    } else {
      ul =
          session
              .createCriteria(model.StudentProfile.class)
              .add(Restrictions.eq("user.id", u.getId()))
              .list();
      if (!ul.isEmpty()) {
        model.StudentProfile loginStudent = (StudentProfile) ul.get(0);
        if (loginStudent.isPassed != model.StudentProfile.Passed) {
          session.close();
          return login_fail;
        }

        role = util.Const.StudentRole;
        if (loginStudent.getIsUpgradePrivilege() == 1) {
          role = util.Const.StudentToAdminRole;
        }

        ActionContext.getContext().getSession().put("student_id", loginStudent.getId());
      } else {
        session.close();
        return login_fail;
      }
    }

    session.close();
    //		System.out.println(u.getPassword());
    //		System.out.println(u.username);
    if (!u.getPassword().equals(password)) return login_fail;

    ActionContext.getContext().getSession().put("username", username);
    ActionContext.getContext().getSession().put("fullName", u.getFullName());
    ActionContext.getContext().getSession().put("role", role);
    ActionContext.getContext().getSession().put("user_id", u.getId());
    //		ActionContext.getContext().getSession().containsKey(key)

    if (role.equals(util.Const.AdminRole)) {
      ChooseClass.insertDataToDutyTimeTable();
      ChooseClass.insertDataToChooseClassSwitchTable();
      return "admin_login_success";
    } else if (role.equals(util.Const.StudentRole) || role.equals(util.Const.StudentToAdminRole)) {
      ChooseClass.insertDataToDutyTimeTable();
      ChooseClass.insertDataToChooseClassSwitchTable();
      return "student_login_success";
    }
    System.out.println("ERROR");
    return "SB";
  }