Esempio n. 1
0
  /**
   * @param id ID of the user you want to find.
   * @return The user with given ID.
   */
  public User getUserByID(String id) {
    if (null == users) return null;
    for (User user : users) {
      if (null != user && null != user.getID() && user.getID().equalsIgnoreCase(id)) return user;
    }

    return null; // Not found, return null.
  }
Esempio n. 2
0
 /**
  * Converts the contents of the GroupInvite to a {@link java.lang.String} in order to save it to
  * file. The toString method will save the invite as follows: Sender: senderID Receiver:
  * receiverID Text: text ID : groupID
  */
 public String toString() {
   return ("Type:"
       + type
       + "\nSender:"
       + sender.getID()
       + "\nReceiver:"
       + receiver.getID()
       + "\nGroup:"
       + group.getID()
       + "\nText:"
       + text
       + "\n"); // Just for compile
 }
Esempio n. 3
0
  public void signUp(View view) {
    EditText email = (EditText) findViewById(R.id.email);
    EditText pw = (EditText) findViewById(R.id.password);
    EditText nameField = (EditText) findViewById(R.id.name);
    String username = email.getText().toString();
    String password = pw.getText().toString();
    String name = nameField.getText().toString();
    try {
      URI uri = new URI("http://severe-leaf-6733.herokuapp.com/users");
      DefaultHttpClient client = new DefaultHttpClient();
      HttpPost post = new HttpPost(uri);

      JSONObject json = new JSONObject();
      JSONObject m = new JSONObject();
      m.put("name", name);
      m.put("email", username);
      m.put("password", password);
      json.put("user", m);

      StringEntity se = new StringEntity(json.toString());
      post.setEntity(se);
      post.setHeader("Accept", "application/json");
      post.setHeader("Content-type", "application/json");
      BasicResponseHandler responseHandler = new BasicResponseHandler();
      String responseString = client.execute(post, responseHandler);

      GsonBuilder g = new GsonBuilder();
      g.setDateFormat("E MMM d HH:mm:ss Z y");
      Gson gson = g.create();
      User um = gson.fromJson(responseString, User.class);

      if (um.getID() != 0) {
        CookieStore cookieStore = client.getCookieStore();
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        Global.localContext = localContext;
        Global.client = client;
        Global.user_id = um.getID();

        Intent myIntent = new Intent(getApplicationContext(), Root.class);
        startActivity(myIntent);
      } else {
        Toast.makeText(this, "Unable to Sign Up", Toast.LENGTH_LONG).show();
      }
    } catch (Exception e) {
      Log.e("Sign Up Error", e.getMessage());
    }
  }
  private void insert() {
    if (mID >= 0) {
      LOGGER.warning("message already in db, ID: " + mID);
      return;
    }
    Database db = Database.getInstance();

    List<Object> values = new LinkedList<>();
    values.add(mThread.getID());
    values.add(mDir);
    values.add(mUser.getID());
    values.add(mJID);
    values.add(Database.setString(mXMPPID));
    values.add(mDate);
    values.add(mReceiptStatus);
    // i simply don't like to save all possible content explicitly in the
    // database, so we use JSON here
    values.add(mContent.toJSONString());
    values.add(mCoderStatus.getEncryption());
    values.add(mCoderStatus.getSigning());
    values.add(mCoderStatus.getErrors());
    values.add(mServerError.toJSON());
    values.add(mServerDate);

    int id = db.execInsert(TABLE, values);
    if (id <= 0) {
      LOGGER.log(Level.WARNING, "db, could not insert message");
      mID = -2;
      return;
    }
    mID = id;
  }
 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;
 }
Esempio n. 6
0
  void sendGroupFile(final String path, final int type, final int code, boolean isBroadcast) {
    final File photoFile = new File(path);
    user = ((SochatApplication) getApplication()).getCurrentUser();
    final String sender = user.getName();
    final String IMEI = user.getID();

    final String group;
    if (isBroadcast) group = "all";
    else group = user.getGroup();

    Thread sendThread =
        new Thread() {
          public void run() {

            try {

              // Create a file object for the photo selected
              String photoName = photoFile.getName();

              // Construct the DTN message
              DtnMessage message = new DtnMessage();
              // Data part
              message.addData();
              message
                  .writeString(String.valueOf(System.currentTimeMillis()))
                  .writeInt(type)
                  .writeInt(code)
                  .writeString(sender)
                  .writeString(IMEI)
                  .writeString(group)
                  .writeString(photoName);
              message.addFile(photoFile);

              // Broadcast the message using the fwd layer interface
              fwdLayer.sendMessage(descriptor, message, "everyone", null);

              // Tell the user that the message has been sent

            } catch (Exception e) {
              // Log the exception
              Log.e("PhotoSharingApp", "Exception while sending photo", e);
              // Inform the user

            }
          }
        };
    sendThread.start();
  }
Esempio n. 7
0
  void sendGroupMessage(
      final String receiver,
      final int type,
      final int code,
      final String chatMessage,
      boolean isBroadcast) {
    user = ((SochatApplication) getApplication()).getCurrentUser();
    final String sender = user.getName();
    final String IMEI = user.getID();
    final String group;
    if (isBroadcast) group = "all";
    else group = user.getGroup();
    Log.d("kk", group);

    Thread sendThread =
        new Thread() {
          public void run() {
            DtnMessage message = new DtnMessage();
            // Data part
            try {
              message.addData();
              message
                  .writeString(String.valueOf(System.currentTimeMillis()))
                  .writeInt(type)
                  .writeInt(code)
                  .writeString(sender)
                  .writeString(IMEI)
                  .writeString(group)
                  .writeString(chatMessage);
              Log.d("chatMessage", chatMessage);

              // Log.d("Type", type + "");
              // Log.d("code", code + "");
            } catch (DtnMessageException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } // Chat message
            // Send the message using the multihop interface
            try {
              fwdLayer.sendMessage(descriptor, message, receiver, null);
            } catch (ForwardingLayerException e) {
              e.printStackTrace();
            }
          }
        };
    sendThread.start();
  }
Esempio n. 8
0
 GroupInvite(User sender, User receiver, Group group) {
   this.sender = sender;
   this.receiver = receiver;
   this.group = group;
   this.text =
       "<a href = profile.jsp?ID="
           + sender.getID()
           + ">"
           + sender.getDisplayName()
           + "</a>"
           + " has invited you to join "
           + "<a href profile.jsp?ID="
           + group.getID()
           + ">"
           + group.getDisplayName()
           + "</a>";
   type = "GroupInvite";
 }
 /** checks database for this user */
 private boolean realAuthentication(HttpServletRequest request, ConnectionPool conPool)
     throws SQLException {
   // user authentication is required!
   User user = (User) request.getSession().getAttribute(StringInterface.USERATTR);
   if (user == null) {
     return false;
   }
   Connection con = conPool.getConnection();
   boolean authenticated = false;
   try {
     authenticated = userUtils.confirmUserWithEncrypted(user.getID(), user.getEncrypted(), con);
   } catch (Exception e) {
     throw new SQLException(e.getMessage());
   } finally {
     conPool.free(con);
     con = null;
   }
   return authenticated;
 } // end realAuthentication
Esempio n. 10
0
 private void update() {
   try {
     group.subscribeTo(receiver);
     receiver.addGroup(group);
     Date date = new Date();
     receiver.post(
         "<a href = profile.jsp?ID="
             + receiver.getID()
             + ">"
             + receiver.getDisplayName()
             + "</a>"
             + " joined "
             + "<a href = profile.jsp?ID="
             + group.getID()
             + ">"
             + group.getDisplayName()
             + "</a>",
         receiver,
         date);
   } catch (Exception e) { // Fix to later return some sort of bs
     e.printStackTrace();
   }
 }
 public boolean removeStudent(User student) {
   boolean success = this.getMembers().remove(student.getID()) && this.save();
   student.setResidence(null);
   success = success && student.save();
   return success;
 }
Esempio n. 12
0
  private String processRequest(
      HttpServletRequest request, HttpServletResponse response, ConnectionPool conPool)
      throws Exception {
    // getting id parameters
    ParameterParser parameter = new ParameterParser(request);
    String bookID = parameter.getString(bookInterface.FIELD_ID, null);
    String sellerID = parameter.getString(bookInterface.FIELD_SELLERID, null);
    String message = parameter.getString(FIELD_MESSAGE, null);
    int codeID = parameter.getInt(bookInterface.FIELD_HIDDENID, 0);
    // get buyer's user object
    User user = (User) request.getSession().getAttribute(StringInterface.USERATTR);
    // security feauture:
    // if one of ids is missing or incorrect return false
    if (bookID == null
        || sellerID == null
        || codeID == 0
        || bookID.length() != booksTable.ID_LENGTH
        || sellerID.length() != usersTable.ID_LENGTH
        || codeID != Math.abs(bookID.hashCode())) {
      return "We were unable to find the book you specified! Please make sure that the book id is correct.";
    }
    if (user.getID().equals(sellerID)) {
      return "You may not purchase an item from yourself!";
    }
    // get connection
    Connection con = conPool.getConnection();
    try {
      booksTable book = generalUtils.getBook(bookID, con);
      /*security feauture:
       *check seller id == passed hidden id
       *book != null
       */
      if (book == null || !book.getSellerID().equals(sellerID)) {
        return "We were unable to find the book you specified! Please make sure that the book id is correct.";
      }
      usersTable sellerInfo = userUtils.getUserInfo(sellerID, con);
      usersTable buyerInfo = userUtils.getUserInfo(user.getID(), con);
      collegeTable college = getCollege(book.getCollegeID() + "", con);
      // if still here continue
      if (message == null) {
        request.setAttribute(ATTR_BOOK, book);
        request.setAttribute(ATTR_SELLER, sellerInfo);
        request.setAttribute(ATTR_BUYER, buyerInfo);
        request.setAttribute(ATTR_COLLEGE, college.getFull());
        RequestDispatcher rd = getServletContext().getRequestDispatcher(PATH_BUY_CONFIRM);
        rd.include(request, response);
        return null;
      } else if (buy(book, user, con)) {
        // sending email to buyer
        request.setAttribute(mailInterface.USERATTR, buyerInfo.getUsername());
        request.setAttribute(mailInterface.EMAILATTR, buyerInfo.getEmail());
        request.setAttribute(mailInterface.BOOKATTR, book);
        request.setAttribute("book_id", bookID);
        request.setAttribute("seller_id", sellerID);

        RequestDispatcher rd = getServletContext().getRequestDispatcher(PATHBIDCONFIRMATION);
        rd.include(request, response);
        // sending email to seller
        request.setAttribute(ATTR_COLLEGE, college.getFull());
        request.setAttribute(mailInterface.USERATTR, sellerInfo.getUsername());
        request.setAttribute(mailInterface.EMAILATTR, sellerInfo.getEmail());
        request.setAttribute(mailInterface.MESSAGEATTR, message);
        request.setAttribute(mailInterface.BOOKATTR, book);
        request.setAttribute(mailInterface.MOREATTR, buyerInfo);

        request.setAttribute("book_id", bookID);
        request.setAttribute("buyer_id", user.getID());
        rd = getServletContext().getRequestDispatcher(PATHBOOKUPDATE);
        rd.include(request, response);
        // showing success message
        rd = getServletContext().getRequestDispatcher(PATH_BUY_SUCCESS);
        rd.include(request, response);
        return null;
      } else {
        throw new Exception("failed to process with buy");
      }
    } catch (Exception e) {
      throw e;
    } finally {
      // recycle
      conPool.free(con);
      con = null;
    }
  }
Esempio n. 13
0
 /**
  * Removes User from the room.
  *
  * @param user User to remove.
  */
 public void removeUser(User user) {
   if (userList.containsKey(user.getID())) {
     userList.remove(user.getID());
   }
 }
Esempio n. 14
0
 /**
  * Adds User to the room.
  *
  * @param user The User to add.
  */
 public void addUser(User user) {
   String id = user.getID();
   if (userList.containsKey(id)) return;
   userList.put(id, user);
   bot.getDatabase().getUserRank(id);
 }
 public boolean addStudent(User student) {
   boolean success = this.getMembers().add(student.getID()) && this.save();
   student.setResidence(this.getID());
   success = success && student.save();
   return success;
 }
Esempio n. 16
0
 public boolean remove(User u) {
   return remove(u.getID());
 }
Esempio n. 17
0
 /** moves data into certain tables to simulate the buying process */
 private boolean buy(booksTable book, User buyer, Connection con) throws SQLException {
   try {
     Statement st = con.createStatement();
     /*all parameters are considered to be full--
      *book is completed and so as buyer object
      */
     con.setAutoCommit(false);
     // 1st add purchase to buyers table
     st.addBatch(
         "INSERT INTO "
             + TABLEBUYERS
             + " ("
             + buyersTable.BOOKID
             + ","
             + buyersTable.BUYERID
             + ","
             + buyersTable.DATE
             + ") values (\""
             + book.getID()
             + "\",\""
             + buyer.getID()
             + "\",\""
             + new DateObject().getDate()
             + "\")");
     // 2nd add the book to old books
     String[] oldbooksFields = {
       oldBooksTable.SELLERID, oldBooksTable.BUYERID,
       oldBooksTable.BOOKID, oldBooksTable.TITLE,
       oldBooksTable.AUTHOR, oldBooksTable.ISBN,
       oldBooksTable.CONDITION, oldBooksTable.PRICE,
       oldBooksTable.COMMENT, oldBooksTable.COLLEGE,
       oldBooksTable.DATE
     };
     String[] oldbooksValues = {
       book.getSellerID(),
       buyer.getID(),
       book.getID(),
       book.getTitle(),
       book.getAuthor(),
       book.getISBN(),
       book.getCondition() + "",
       book.getPrice() + "",
       book.getComment(),
       book.getCollegeID() + "",
       new DateObject().getDate()
     };
     st.addBatch(
         "INSERT INTO "
             + TABLEOLDBOOKS
             + " ("
             + sqlUtils.sql_fields(oldbooksFields)
             + ") values ("
             + sqlUtils.sql_values(oldbooksValues)
             + ")");
     // 3rd delete record from booksTable
     st.addBatch(
         "DELETE FROM " + TABLEBOOKS + " WHERE " + booksTable.ID + " = '" + book.getID() + "'");
     // execute all 3 steps and set auto commit mode
     int[] updateCounts = st.executeBatch();
     if (updateCounts[0] == 1 && updateCounts[1] == 1 && updateCounts[2] == 1) {
       return true;
     } else {
       return false;
     }
   } catch (SQLException e) {
     log.writeException(e.getMessage());
     throw e;
   } finally {
     con.setAutoCommit(true);
   }
 }