Esempio n. 1
0
 public Object clone() throws CloneNotSupportedException {
   User user = (User) super.clone();
   user.userID = userID;
   user.username = username;
   user.image = new ImageIcon(image.getImage());
   return user;
 }
 private boolean hasJabberContacts() {
   User[] users = myUserModel.getAllUsers();
   for (User user : users) {
     if (user.getTransportCode().equals(getName())) return true;
   }
   return false;
 }
 String getThreadId(User user) {
   String id = myUser2Thread.get(user.getName());
   if (id == null) {
     id = myThreadIdPrefix + myCurrentThreadId++;
     myUser2Thread.put(user.getName(), id);
   }
   return id;
 }
 private void updateIsIDEtalkClient(String jabberId, User user) {
   if (getResource(jabberId)
       .toLowerCase()
       .startsWith(JabberFacade.IDETALK_RESOURCE.toLowerCase())) {
     myIDEtalkUsers.add(user.getName());
   } else {
     myIDEtalkUsers.remove(user.getName());
   }
 }
Esempio n. 5
0
 /**
  * Gets the list of the vnmrj users(operators) for the current unix user logged in
  *
  * @return the list of vnmrj users
  */
 protected Object[] getOperators() {
   String strUser = System.getProperty("user.name");
   User user = LoginService.getDefault().getUser(strUser);
   ArrayList<String> aListOperators = user.getOperators();
   if (aListOperators == null || aListOperators.isEmpty())
     aListOperators = new ArrayList<String>();
   Collections.sort(aListOperators);
   if (aListOperators.contains(strUser)) aListOperators.remove(strUser);
   aListOperators.add(0, strUser);
   return (aListOperators.toArray());
 }
Esempio n. 6
0
 void placeOrder(final User user, String cmd, Company comp, int qty, int id) {
   int cmdID = commID++;
   connect(user.getName(), user.getPassword());
   try {
     out.println(cmdID + ";" + cmd + ":" + comp.name + ":" + Integer.toString(qty) + ":" + id);
     out.flush();
     Shares pen = (Shares) receiveReply(cmdID);
     user.getPendingShares().add(pen);
     user.dataChanged();
   } catch (Exception r) {
     r.printStackTrace();
   }
 }
Esempio n. 7
0
 private void spend() {
   String amountStr =
       JOptionPane.showInputDialog(
           this, "Input an amount to spend:", "Spend", JOptionPane.QUESTION_MESSAGE);
   if (amountStr == null) {
     return;
   }
   String accountNumberStr =
       JOptionPane.showInputDialog(
           this,
           "To what account number? (blank is allowed)",
           "Spend",
           JOptionPane.QUESTION_MESSAGE);
   if (accountNumberStr == null) {
     return;
   }
   try {
     BigDecimal amount = FORMATTER.stringToValue(amountStr);
     Account target;
     if (accountNumberStr.isEmpty()) {
       target = null;
     } else {
       int accountNumber = new IntegerFormatter().stringToValue(accountNumberStr);
       target = null;
       for (User user : Bank.getInstance().getUsers()) {
         for (Account account : user.getAccounts()) {
           if (account.getAccountNumber() == accountNumber) {
             target = account;
           }
         }
       }
     }
     if (target != null
         && (target.getType().isLoan() && target.getBalance().negate().compareTo(amount) < 0)) {
       throw new InvalidInputException(
           accountNumberStr, "account does not exist or cannot accept this deposit");
     }
     account.withdraw(amount);
     if (target != null) {
       target.deposit(amount);
     }
     controller.updateBankDisplay();
   } catch (ParseException px) {
     controller.handleException(this, px);
   } catch (InvalidInputException iix) {
     controller.handleException(this, iix);
   } catch (InsufficientFundsException ifx) {
     controller.handleException(this, ifx);
   }
 }
 private User addJabberUserToUserModelOrUpdateInfo(RosterEntry rosterEntry) {
   //    System.out.println("rosterEntry.getName() = " + rosterEntry.getName());
   //    System.out.println("rosterEntry.getUser() = " + rosterEntry.getUser());
   User user = myUserModel.createUser(getSimpleId(rosterEntry.getUser()), getName());
   String newGroup = getUserGroup(rosterEntry);
   if (newGroup != null) {
     user.setGroup(newGroup, myUserModel);
   }
   user.setDisplayName(rosterEntry.getName(), myUserModel);
   myUserModel.addUser(user);
   String jabberId = getCurrentJabberID(user, rosterEntry);
   updateIsIDEtalkClient(jabberId, user);
   return user;
 }
  private void drawBalance(Graphics g)
        //  POST: Draws the balance of the current player
      {

    Font font; // Font used to draw balance
    String message; // Message for balance
    Color oldColor; // Sets for color
    int x1; // Upper-left x coordinate
    int y1; // Upper-left y coordinate
    int x2; // Bottom-right x coordinate
    int y2; // Bottom-right y coordinate
    int width; // Width of the dialogue box
    int height; // Height of the dialogue box
    int offset; // Offset so the dialogue box is positioned
    int balance; // Offset so the dialogue box is positioned
    User player; // User value for the player

    player = usersArray[0];

    balance = player.getBalance();
    oldColor = g.getColor();

    x1 = ScaledPoint.scalerToX(0.72);
    y1 = ScaledPoint.scalerToY(0.81);
    x2 = ScaledPoint.scalerToX(0.88);
    y2 = ScaledPoint.scalerToY(0.86);
    width = x2 - x1;
    height = y2 - y1;
    message = "Balance:";
    font = Drawing.getFont(message, width, height, FONTNAME, FONTSTYLE);
    offset = (width - getFontMetrics(font).stringWidth(message)) / 2;
    g.setColor(Color.WHITE);
    g.drawString(message, x1 + offset, y2);

    x1 = ScaledPoint.scalerToX(0.72);
    y1 = ScaledPoint.scalerToY(0.865);
    x2 = ScaledPoint.scalerToX(0.88);
    y2 = ScaledPoint.scalerToY(0.915);

    width = x2 - x1;
    height = y2 - y1;
    message = "$" + Integer.toString(balance);
    font = Drawing.getFont(message, width, height, FONTNAME, FONTSTYLE);
    offset = (width - getFontMetrics(font).stringWidth(message)) / 2;
    g.drawString(message, x1 + offset, y2);

    g.setColor(oldColor);
  }
Esempio n. 10
0
    @Override
    public void actionPerformed(ActionEvent e) {
      switch (e.getActionCommand()) {
        case "Cancel":
          screen.show("menu");
          break;

        case "Start game":
          Game startGame = null;
          // 1. if tjekker værdien af hvad der er valgt i comboBoxen og sammenligner med de spil som
          // for-loopet kører igennem
          // 2. if gør så hosten ikke kan joine sit eget spil
          for (Game g : games) {
            if (g.getName().equals(screen.getFindGamePanel().getSelectedGame())) {
              if (g.getHost().getId() != currentUser.getId()) startGame = g;
            }
          }
          if (startGame != null) {

            Gamer opponent = new Gamer();
            opponent.setId(currentUser.getId());
            opponent.setControls(screen.getFindGamePanel().getDirectionsTextfield());
            startGame.setOpponent(opponent);
            String joinGamemessage = api.joinGame(startGame);
            String startGamemessage = api.startGame(startGame);
            System.out.println(startGamemessage);
            String winnerName = "";

            for (User u : users) {

              try {

                if (u.getId() == Integer.parseInt(startGamemessage)) {
                  winnerName = u.getUsername();
                }
              } catch (NumberFormatException e1) {
                e1.printStackTrace();
              }
            }

            JOptionPane.showMessageDialog(
                screen, joinGamemessage + ". The winner was:" + winnerName);
          } else {
            JOptionPane.showMessageDialog(screen, "You can't join a game where you're the host");
          }
          break;
      }
    }
  public void actionPerformed(ActionEvent evt) {
    // Get button clicked
    JButton buttonClicked = (JButton) evt.getSource();
    String actionCommand = new String(buttonClicked.getActionCommand());

    if (actionCommand.equals("Submit")) {
      System.out.println(clientUser.getLogon() + ": updating ticket...");

      // Recover ticket and update it
      Ticket ticketToUpdate = ticket;
      ticketToUpdate.setDesc(clientTicketDialog.getSummaryDescriptionField());
      ticketToUpdate.setResolution(clientTicketDialog.getResolutionDescriptionField());

      // Call checkInTicket() on the RMI object to update the ticket on the server
      try {
        ticketServerObject.checkInTicket(ticketToUpdate);
        // Refresh the activeTickets HashMap
        owner.getActiveTickets();
      } catch (RemoteException re) {
        System.out.println(re.getMessage());
      }

      // Close the ClientTicketDialog
      clientTicketDialog.setVisible(false);
      clientTicketDialog.dispose();
    }
  }
Esempio n. 12
0
  public void actionPerformed(ActionEvent e) {
    try {
      FileInputStream fin = new FileInputStream(obj1.f);
      ObjectInputStream ois = new ObjectInputStream(fin);
      obj1.a1 = (ArrayList) ois.readObject();

      String s3 = obj1.t3.getText();
      String s4 = obj1.t4.getText();
      String s5 = obj1.t5.getText();
      int size = obj1.a1.size();
      int f6 = 0;

      for (int i = 0; i < size; i++) {
        Stdinfo r2 = (Stdinfo) obj1.a1.get(i);
        if (r2.name.equals(s3) && r2.id.equals(s4) && r2.addr.equals(s5)) {
          JOptionPane.showMessageDialog(null, "FOUND", "Welcome", JOptionPane.QUESTION_MESSAGE);
          f6 = 1;
        }
      }

      if (f6 == 0) {
        JOptionPane.showMessageDialog(null, "NOT FOUND", "Welcome", JOptionPane.QUESTION_MESSAGE);
      }

      fin.close();
      ois.close();
    } catch (Exception e1) {
    }
  }
Esempio n. 13
0
  public void actionPerformed(ActionEvent e) {
    try {
      FileInputStream fin = new FileInputStream(obj.f);
      ObjectInputStream ois = new ObjectInputStream(fin);
      obj.a1 = (ArrayList) ois.readObject();

      String s1 = obj.t6.getText();
      String s2 = obj.t7.getText();

      int size = obj.a1.size();
      int f5 = 0;

      for (int i = 0; i < size; i++) {
        Bookinfo r2 = (Bookinfo) obj.a1.get(i);
        if (r2.bkisno.equals(s1) && r2.title.equals(s2)) {
          JOptionPane.showMessageDialog(
              null, "ALREADYEXIT", "Welcome", JOptionPane.QUESTION_MESSAGE);
          f5 = 1;
        }
      }

      if (f5 == 0) {
        JOptionPane.showMessageDialog(null, "ALREADYEXIT", "Welcome", JOptionPane.QUESTION_MESSAGE);
        ;
      }

      fin.close();
      ois.close();
    } catch (Exception e1) {
    }
  }
Esempio n. 14
0
  public void actionPerformed(ActionEvent e) {
    try {
      FileInputStream fin = new FileInputStream(obj.f);
      ObjectInputStream ois = new ObjectInputStream(fin);
      obj.a1 = (ArrayList) ois.readObject();

      String s1 = obj.t1.getText();
      String s2 = obj.t2.getText();

      int size = obj.a1.size();
      int f1 = 0;

      for (int i = 0; i < size; i++) {
        info r = (info) obj.a1.get(i);
        if (r.uid.equals(s1) && r.pass.equals(s2)) {
          JOptionPane.showMessageDialog(null, "VALID", "Welcome", JOptionPane.QUESTION_MESSAGE);
          f1 = 1;
        }
      }

      if (f1 == 0) {
        JOptionPane.showMessageDialog(null, "ALREADYEXIT", "Welcome", JOptionPane.QUESTION_MESSAGE);
      }

      fin.close();
      ois.close();
    } catch (Exception e1) {
    }
  }
Esempio n. 15
0
  public void actionPerformed(ActionEvent e) {
    try {
      FileInputStream fin = new FileInputStream(obj.f);
      ObjectInputStream ois = new ObjectInputStream(fin);
      obj.a1 = (ArrayList) ois.readObject();
    } catch (Exception e1) {
      System.out.print(e1);
    }
    int size = obj.a1.size();
    int f4 = 0;

    for (int i = 0; i < size; i++) {
      Bookinfo r2 = (Bookinfo) obj.a1.get(i);
      if (r2.bkisno.equals(obj.t3.getText()) && r2.title.equals(obj.t4.getText())) {
        JOptionPane.showMessageDialog(null, "ALREADYEXIT", "Welcome", JOptionPane.QUESTION_MESSAGE);
        f4 = 1;
      }
    }
    if (f4 == 0) {
      obj.a1.add(new Bookinfo(obj.t6.getText(), obj.t7.getText(), obj.t8.getText()));
      obj.t6.setText("");
      obj.t7.setText("");
      obj.t8.setText("");
    }
  }
  /**
   * Create a GUI that shows a graph for the specified user's payoff history
   *
   * @param user The user to show the Payoff history for
   */
  public GraphGUI(User user) {
    super(
        user.getUserName()
            + "'s Payoff History (Over "
            + user.getPayoffHistory().size()
            + " Steps)");

    this.userInfo = user;
    this.pack();

    // Set size
    this.setMinimumSize(new Dimension(500, 500));

    // Center the graph
    this.setLocationRelativeTo(null);

    // Create a series collection
    xySeriesCollection = new XYSeriesCollection();

    // Create (refresh) chart data
    refreshChartData();

    // Create an XY Line Chart
    chart =
        ChartFactory.createXYLineChart(
            "User Payoff Over Time",
            "Steps (Simulation Iterations)",
            "User Payoff",
            xySeriesCollection);
    chart.getPlot().setBackgroundPaint(Color.WHITE);
    chart.getPlot().setOutlinePaint(Color.BLACK);

    // Draw the Initial Chart
    chart.draw(
        (Graphics2D) this.getGraphics(),
        (Rectangle2D) new Rectangle2D.Double(0, 0, this.getWidth(), this.getHeight()));

    // Set the content pane to a graphics panel for drawing the graph
    this.setContentPane(new GraphPanel(this));

    // Show the frame
    this.setVisible(true);

    // Subscribe to the user's UserPayoff events
    user.addPayoffListener(this);
  }
Esempio n. 17
0
  private void button3_updateActionPerformed(ActionEvent e) {
    String message = null;
    User temp = (User) list1.getSelectedValue();
    try {
      temp.name = textField1_name.getText();
      temp.emeil = textField2_emeil.getText();
      temp.telefon = Integer.valueOf(textField3_telefon.getText());
      message = "Успешно преобразован";
      textField1_name.setText("");
      textField2_emeil.setText("");
      textField3_telefon.setText("");

    } catch (NumberFormatException ex) {
      message = "Разберитесь с телефоном";
    } finally {
      JOptionPane.showMessageDialog(this, message);
    }
  }
Esempio n. 18
0
  public void actionPerformed(ActionEvent ae) {
    if (ae.getActionCommand().equals("Add User")) {
      jta.append("\n" + userId.getText());

      User user = new User(userId.getText());
    } else if (ae.getActionCommand().equals("Add Group")) {
      jta.append("\n" + groupId.getText());

      Group group = new Group(groupId.getText());
    } else if (ae.getActionCommand().equals("Open User View")) {
      try {
        if (!jta.getSelectedText().equals("null")) {
          userView.setVisible(true);
        }
      } catch (Exception e) {
        JOptionPane.showMessageDialog(
            frame, "Nothing selected", "Error", JOptionPane.ERROR_MESSAGE);
      }
    } else if (ae.getActionCommand().equals("Show User Total")) {
      JOptionPane.showMessageDialog(frame, User.getUserTotal());
    } else if (ae.getActionCommand().equals("Show Group Total")) {
      JOptionPane.showMessageDialog(frame, Group.getGroupTotal());
    } else if (ae.getActionCommand().equals("Show Messages Total")) {
      JOptionPane.showMessageDialog(frame, User.getMessageTotal());
    } else if (ae.getActionCommand().equals("Show Positive Percentage")) {
      String[] newsFeed = User.getNewsFeed();

      int positive = 0;
      int i = 0;
      while (!(newsFeed[i] == null)) {
        if (newsFeed[i].contains("good")
            || newsFeed[i].contains("great")
            || newsFeed[i].contains("excellent")) positive++;
        i++;
      }

      JOptionPane.showMessageDialog(frame, positive * 100.0 / i + "%");
    } else if (ae.getActionCommand().equals("Follow User")) {
      following.append("\n" + userId2.getText());
    } else if (ae.getActionCommand().equals("Post Tweet")) {
      User.postTweet(tweet.getText());
      newsFeed.append("\n" + jta.getSelectedText() + ": " + tweet.getText());
    }
  }
  /**
   * Put User Payoff history into a readable double 2D array for JFreeChart
   *
   * @return A 2D double array of coordinates
   */
  private XYSeries getUserPayoffData() {
    XYSeries xySeries = new XYSeries("User: "******"'s Payoff History (Over "
            + userInfo.getPayoffHistory().size()
            + " Steps)");

    // Set the points of the data set
    for (int i = 0; i < userInfo.getPayoffHistory().size(); i++) {
      xySeries.add(i, userInfo.getPayoffHistory().get(i));
    }

    return xySeries;
  }
Esempio n. 20
0
  public Client() throws ConnectException, IOException, ClassNotFoundException {
    setTitle("Calendar");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    sigve = User.getUser(1); // new User("sigveseb", "Sigve Sebastian", "Farstad", "*****@*****.**");
    new Thread(
            new Runnable() {

              @Override
              public void run() {
                while (true) {
                  Client.setCurrentTime(new GregorianCalendar());
                  try {
                    Thread.sleep(1000);
                  } catch (InterruptedException e) {
                  }
                }
              }
            })
        .start();

    new Thread(
            new Runnable() {

              @Override
              public void run() {
                while (true) {
                  Client.setNotifications(Message.getMessages(Client.user));
                  try {
                    Thread.sleep(15000);
                  } catch (InterruptedException e) {
                  }
                }
              }
            })
        .start();

    inv1 = new Invitation(sigve, app1);
    inv2 = new Invitation(sigve, app2);
    app1 =
        new Appointment(
            "Testappointment",
            "Utendørs",
            "Dette er en test for å teste testen",
            new GregorianCalendar(2012, 3, 23, 10, 30),
            new GregorianCalendar(2012, 3, 23, 11, 30));
    app2 =
        new Appointment(
            "Testappointment nummer 2",
            f1,
            "Dette er en test for å teste testen",
            new GregorianCalendar(2012, 3, 26, 12, 0),
            new GregorianCalendar(2012, 3, 26, 14, 45));
    f1 = new Room("F1", 12, 300, false);
  }
Esempio n. 21
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();
    }
  }
Esempio n. 22
0
    @Override
    public void actionPerformed(ActionEvent e) {

      switch (e.getActionCommand()) {
        case "Cancel":
          screen.show("menu");
          break;

        case "Create":
          Game startGame = new Game();
          startGame.setName(screen.getStartGamePanel().getGameName());
          startGame.setMapSize(25);
          Gamer opponent = new Gamer();
          // For-loop kører brugerne igennem og viser dem i en comboBox
          // 1. if tjekker værdien af hvad der er valgt i comboBoxen og sammenligner med de brugere
          // som for-loopet kører igennem
          for (User u : users) {
            if (u.getUsername().equals(screen.getStartGamePanel().getSelectedUSer())) {
              opponent.setId(u.getId());
            }
          }
          // If tjekker om hosten vil udfordre sig selv og giver fejlmeddelelse og ellers er spillet
          // oprettet.
          if (opponent.getId() == currentUser.getId()) {
            JOptionPane.showMessageDialog(
                screen, "Error: You need to choose a different opponent than yourself");
          } else {
            Gamer host = new Gamer();
            host.setId(currentUser.getId());
            host.setControls(screen.getStartGamePanel().getControlsToSnake());
            startGame.setHost(host);

            startGame.setOpponent(opponent);
            String message = api.createGame(startGame);
            JOptionPane.showMessageDialog(screen, message);
            screen.show("menu");
          }
          break;
      }
    }
Esempio n. 23
0
  public void buyItemFromUser(User buyer, User seller, Item currentItem)
        // PRE:  buyer, seller, currentItem must be initialized
        // POST: Purchases item from the store and has stores it into inventory.
      {

    int buyer_balance; // The new balance of the buyer
    int seller_balance; // The new balance of the seller
    String str; // First query
    String str2; // Second query
    String str3; // Third query

    buyer_balance = buyer.getBalance() - currentItem.getPrice();
    seller_balance = seller.getBalance() + currentItem.getPrice();

    if (buyer_balance > 0) // If the buyer wont go negative
    {
      str =
          String.format(
              "Update users set balance = (%d) where user_name = '%s'",
              buyer_balance, buyer.getUserName());

      str2 =
          String.format(
              "Update users set balance = (%d) where user_name = '%s'",
              seller_balance, seller.getUserName());

      str3 =
          String.format(
              "Update items set owner_id = (%d) where item_name = '%s'",
              buyer.getUserId(), currentItem.getItemName());

      updateTables(str, str2, str3);

    } else {
      // Prompt the user with an error
      JOptionPane.showMessageDialog(
          null, "You will go bankrupt if you try buying that, try selling some items.");
    }
  }
  public void updateTicketList() {
    User user = Application.getCurrentUser();

    TicketDAO dao = TicketDAO.getInstance();
    List<Ticket> openTickets;

    boolean showAllOpenTicket = false;
    if (user.getNewUserType() != null) {
      Set<UserPermission> permissions = user.getNewUserType().getPermissions();
      if (permissions != null) {
        for (UserPermission permission : permissions) {
          if (permission.equals(UserPermission.VIEW_ALL_OPEN_TICKET)) {
            showAllOpenTicket = true;
            break;
          }
        }
      }
    }

    if (showAllOpenTicket) {
      openTickets = dao.findOpenTickets();
    } else {
      openTickets = dao.findOpenTicketsForUser(user);
    }
    openTicketList.setTickets(openTickets);

    lblUserName.setText(
        POSConstants.WELCOME
            + " "
            + user.toString()
            + ". "
            + POSConstants.YOU
            + " "
            + POSConstants.HAVE
            + " "
            + openTickets.size()
            + " "
            + POSConstants.TICKETS);
  }
Esempio n. 25
0
  public void actionPerformed(ActionEvent e) {
    try {
      FileInputStream fin = new FileInputStream(obj.f);
      ObjectInputStream ois = new ObjectInputStream(fin);
      obj.a1 = (ArrayList) ois.readObject();
    } catch (Exception e1) {
      System.out.print(e1);
    }

    obj.a1.add(new info(obj.t1.getText(), obj.t2.getText()));
    obj.t1.setText("");
    obj.t2.setText("");
  }
  private void doClockOut() {
    int option =
        JOptionPane.showOptionDialog(
            this,
            POSConstants.CONFIRM_CLOCK_OUT,
            POSConstants.CONFIRM,
            JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null,
            null,
            null);
    if (option != JOptionPane.YES_OPTION) {
      return;
    }

    User user = Application.getCurrentUser();
    AttendenceHistoryDAO attendenceHistoryDAO = new AttendenceHistoryDAO();
    AttendenceHistory attendenceHistory = attendenceHistoryDAO.findHistoryByClockedInTime(user);
    if (attendenceHistory == null) {
      attendenceHistory = new AttendenceHistory();
      Date lastClockInTime = user.getLastClockInTime();
      Calendar c = Calendar.getInstance();
      c.setTime(lastClockInTime);
      attendenceHistory.setClockInTime(lastClockInTime);
      attendenceHistory.setClockInHour((short) c.get(Calendar.HOUR));
      attendenceHistory.setUser(user);
      attendenceHistory.setTerminal(Application.getInstance().getTerminal());
      attendenceHistory.setShift(user.getCurrentShift());
    }

    Shift shift = user.getCurrentShift();
    Calendar calendar = Calendar.getInstance();

    user.doClockOut(attendenceHistory, shift, calendar);

    Application.getInstance().logout();
  }
Esempio n. 27
0
 /**
  * Logs in user, eventually
  *
  * @param username
  * @param password
  */
 public static Boolean login(String username, String password) {
   Boolean status;
   if (username.equals("sigve") && password.equals("1337")) {
     setUser(User.getUser(1)); // get user 1 for now
     GregorianCalendar now = new GregorianCalendar(2012, 3, 23); // arbitrary date for now
     System.out.println("User logged in");
     pushView(new CalendarView());
     Client.setNotifications(Message.getMessages(Client.user));
     Client.setActiveWeek(
         now.get(GregorianCalendar.YEAR),
         now.get(GregorianCalendar.MONTH),
         now.get(GregorianCalendar.DATE));
     status = true;
   } else {
     System.out.println("Wrong username and/or password");
     status = false;
   }
   return status;
 }
Esempio n. 28
0
  // Constructor receives the filename
  Rolodex(String filename) throws FileNotFoundException {
    File file = new File(filename);
    Scanner scanner = new Scanner(file);

    // Split the line with ~
    while (scanner.hasNext()) {
      tokens = scanner.nextLine().split("~");
      name = tokens[0];
      email = tokens[1];
      pictures = tokens[tokens.length - 1];

      User user = new User();
      user.setUserName(name);
      user.setUserEmail(email);
      user.setPicture(pictures);
      userList.add(user);
    }

    frame = new JFrame("Rolodex");
    frame.setSize(700, 200);

    // Menu
    JMenuBar jmb = new JMenuBar();
    JMenu jmFile = new JMenu("File");
    JMenuItem jmiOpen = new JMenuItem("Open");
    jmiOpen.setEnabled(false);
    JMenuItem jmiExit = new JMenuItem("Exit");
    jmiExit.setMnemonic(KeyEvent.VK_X);
    jmFile.add(jmiOpen);
    jmFile.addSeparator();
    jmFile.add(jmiExit);
    jmb.add(jmFile);

    jmiOpen.addActionListener(this);
    jmiExit.addActionListener(this);

    JMenu jmTabs = new JMenu("Tabs");
    jmTabs.setMnemonic(KeyEvent.VK_T);

    JMenu jmiplacement = new JMenu("Placement");
    JMenuItem jmitop = new JMenuItem("Top");
    JMenuItem jmiright = new JMenuItem("Right");
    JMenuItem jmibottom = new JMenuItem("Bottom");
    JMenuItem jmileft = new JMenuItem("Left");
    jmiplacement.add(jmitop);
    jmiplacement.add(jmiright);
    jmiplacement.add(jmibottom);
    jmiplacement.add(jmileft);

    jmitop.addActionListener(this);
    jmiright.addActionListener(this);
    jmibottom.addActionListener(this);
    jmileft.addActionListener(this);

    JMenu jmilayoutpolicy = new JMenu("Layout policy");
    JMenuItem jmiscroll = new JMenuItem("Scroll");
    JMenuItem jmiwrap = new JMenuItem("Wrap");
    jmilayoutpolicy.add(jmiscroll);
    jmilayoutpolicy.add(jmiwrap);

    jmiscroll.addActionListener(this);
    jmiwrap.addActionListener(this);

    JMenuItem jmidefaults = new JMenuItem("Defaults");
    jmidefaults.setMnemonic(KeyEvent.VK_D);
    jmidefaults.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_MASK));
    jmidefaults.addActionListener(this);
    jmTabs.add(jmiplacement);
    jmTabs.add(jmilayoutpolicy);
    jmTabs.addSeparator();
    jmTabs.add(jmidefaults);
    jmb.add(jmTabs);

    JMenu jmHelp = new JMenu("Help");
    JMenuItem jmiabout = new JMenuItem("About");
    jmiabout.addActionListener(this);
    jmHelp.add(jmiabout);
    jmb.add(jmHelp);

    frame.setJMenuBar(jmb);

    jtp = new JTabbedPane(SwingConstants.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
    topPanel = new JPanel();
    topPanel.setLayout(new BorderLayout());

    for (User user : userList) {
      image = new ImageIcon(user.getPicture());
      panel = new JPanel();
      labname = new JLabel("Name: ");
      txtname = new JTextField(20);
      txtname.setText(user.getUserName());
      labemail = new JLabel("Email: ");
      txtemail = new JTextField(20);
      txtemail.setText(user.getUserEmail());
      l = new JLabel(image);
      l.setHorizontalAlignment(SwingConstants.LEFT);
      panel.add(l);
      panel.add(labname);
      panel.add(txtname);
      panel.add(labemail);
      panel.add(txtemail);
      jtp.addTab(user.getUserName(), panel);
      topPanel.add(jtp);
    }

    frame.add(jtp);
    center(frame);
    frame.setVisible(true);
  }
Esempio n. 29
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;
  }
Esempio n. 30
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();
    }
  }