Java Group Chat Application: Knowing if groups have users currently active - java

For the past 2 weeks, I have been working on a java group chat application. So far a user can login and join groups created by other users. The user can also send chat messages to each other inside of each group. The message distribution is handled by a server and the server only sends the chat messages to clients of the group from which it was sent. A list of groups which the user is a part of is also displayed, and I would like for there to be a small green mark(or anything else to notify the user) to let the user know if there are other users currently active on that chat room group.
Here is how my groups are stored in the database
**TABLE groups**
- id
- user_count
**TABLE group_members**
- groupid
- userid
The sending and receiving of chat messages are handled using sockets, and none of the sent messages are stored on the database. I was thinking of maybe having a field in the groups table where every time a user joins would increment the value in it by 1 and every time a user leaves, the value goes down by 1. This way if the number stored in this field is 0, there are no current users on here. I think there may be a better way to handle this though.

You could have an arraylist for every group that holds the names of every player in that group. Then you could easily get the names of people in the group and the number of people in it. so if you have a class named Group you could have something like:
class Group {
private ArrayList<String> users; // or instead of String if you have a User class use that
public Group(Type par) {
users = new ArrayList<String>();
}
public static void addUser(String userName) {
users.add(userName);
updateUsers();
}
public static void removeUser(String userName) {
for(int i = 0; i < users.size(); i++) {
if(users.get(i).equalsIgnoreCase(userName)) {
users.remove(i);
}
}
updateUsers();
}
public static int getNumberOfUsers() {
return users.size();
}
public static void updateUsers() {
for(String e : users) {
// send the user the necessary info to all users in the group
}
}
}

I just went with my idea as stated in the question. Works well and fast enough for my needs. heres how the database looks
TABLE groups
id
user_count
activity <--- this is where the values are increased or decresed.
TABLE group_members
groupid
userid

Related

session attributes getting replicated for different user sessions

I am building an online hotel reservation system. for that I am using a reservation cart in which I keep track of rooms added by the user. When I am adding some rooms in a browser login in with user1 , now when I log in with some other browser with user2 and add some other rooms in the cart. Now when I try to add another room in cart of user1 , the existing cart of user1 gets replaced by the cart values of user2. I am maintaining different sessions for each user but the cart attribute is getting same for all the sessions . I am currently working on local host. please help
this is how I am adding values to rbList and setting the session attribute.
if(request.getParameter("button").equals("addRoom"))
{ // System.out.println("******************inside addRoom*****************");
if(session!=null)
{
availableRooms = (ArrayList<HotelBean>)session.getAttribute("availableRooms");
int addPos = Integer.parseInt(request.getParameter("roomPosition"));
rb = availableRooms.get(addPos);
String roomID = rb.getRoomId();
HoteDAO hd = new HoteDAO();
boolean available = hd.isAvailable(roomID);
if(available){
if((ArrayList<HotelBean>)session.getAttribute("ReservationCart") == null){
rbList = new ArrayList<HotelBean>();
}
if(rbList == null){
rbList = new ArrayList<HotelBean>();
}
rbList.add(rb);
for(HotelBean room : rbList){
System.out.println(room.getRoomId());
}
session.setAttribute("ReservationCart",rbList);
RequestDispatcher rd=request.getRequestDispatcher("/AvailableRooms.jsp");
rd.forward(request,response);
}
else
{
System.out.println("Sorry the room is not available now");
RequestDispatcher rd=request.getRequestDispatcher("/AvailableRooms.jsp");
rd.forward(request,response);
}
}
}
Your last comment is the answer to your problem. You instantiate the rbList in a class that has only one instance across your web application. Hence you only have only one rbList accross all customers and that causes your problem.
Although I do not have a very clear picture of how your rbList work, I am confident that each customer should have their own unique rbList or at least their own cart.
Also, declaring the customer cart in a controller seems like a poor design choice.
The way that I would go about your problem would be create a separate CartModel class that contains everything cart related.
Create a one to one or one to many relationship from your CustomerModel to your CartModel.
Preferably save the CartModel(s) to your database or at session if your prefer to go with this design.
I hope I helped.

Java/Android studio : For loop - Same data shows multiple times

So I am trying to create this page that compares a user's interest with other users and shows the list of all those users.. Now, with the for loop i created, one particular user's name repeats until the end of the loop. I only one one name per username to appear on the textfield.. However, I don't know how to do that.. Here's my code for showing users with common interests:
Realm realm= Realm.getDefaultInstance();
RealmResults<interests> result=realm.where(interests.class).findAll();
RealmResults<Users> user=realm.where(Users.class).findAll();
for(int i=0;i<result.size();i++)
{
for(int j=0;j<result.size();j++)
{
if(result.get(i).getId().equals(userid))
{
if(result.get(i).getInterest().equals(result.get(j).getInterest()))
{
if(!result.get(j).getId().equals(userid)) {
users = result.get(j).getId();
interestss.append("Interests :" + result.get(i).getInterest());
}
}
id.append("\n"+users);
}
}
}
for(int i=0;i<result.size();i++)
{
for(int j=0;j<result.size();j++)
{
if(result.get(i).getId().equals(userid))
{
if(result.get(i).getInterest().equals(result.get(j).getInterest()))
I'm almost 98% sure that you shouldn't even need to write this kind of code if you use Realm's query system and a link query, instead of looping and comparing things manually.
RealmResults<Interests> interests = realm.where(Interests.class)
.equalTo("user.userId", userId)
.findAll();
Which should be possible if you have a backlink from Interests to Users.
// in Interests class
#LinkingObjects("interest")
private final RealmResults<User> user = null;

Is it possible to add group members to a group using Java Exchange service API for office 365 email?

I am using Java API for exchange web services. Below is the code I have which is currently getting all of the group members from a group, but I wanted to know if I can add a member to the group within the code.
ExchangeService service= instance.getEgrsEmailConnection();
ExpandGroupResults myGroupMembers = service.expandGroup("testgroupone#usepa.onmicrosoft.com");
myGroupMembers.getMembers();
This code gets a group based on that group's email address, but I can't think of a way to add a member. Any tips will be helpful, Thanks.
The api I am using is: ews-java-api-1.3-SNAPSHOT.jar
If testgroupone#usepa.onmicrosoft.com is a Distribution List (eg either a Universal Distribution Group UDG or Mail Enabled Universal Security Group) then no there are no EWS operations that allow you to modify the members of these type of groups. To do that you need to use either LDAP or the Exchange Management Shell. In EWS you an only modify Contact Groups which are Exchange Store objects that exist in a Mailbox or Public Folder.
It looks like you using Office365 so I would suggest using the Graph API https://msdn.microsoft.com/en-us/library/azure/hh974478.aspx you can use the REST interface to easily manage groups from Java https://azure.microsoft.com/en-us/documentation/articles/active-directory-code-samples/
Cheers
Glen
I switched to using a contact group instead of a regular group, and found how to add and delete if anyone was having trouble like me:
ItemView view = new ItemView(111);
//Get all items in the Contacts folder
FindItemsResults<Item> items = service.findItems(WellKnownFolderName.Contacts, view);
for(Item contactItem: items)
{
//If the item is a contactGroup then enter.
if(contactItem instanceof ContactGroup)
{
PropertySet set = new PropertySet(BasePropertySet.FirstClassProperties);
ContactGroup currentContactItem = ContactGroup.bind(service, contactItem.getId(), set);
GroupMemberCollection members = currentContactItem.getMembers();
Iterator<GroupMember> memberList = members.iterator();
ArrayList<GroupMember> removePerson = new ArrayList<GroupMember>();
ArrayList<GroupMember> addPerson = new ArrayList<GroupMember>();
while(memberList.hasNext())
{
GroupMember current = memberList.next();
removePerson.add(current);
if(current.getAddressInformation().getAddress().equalsIgnoreCase("test#gmail.com"))
{
addPerson.add(current);
}
}
for(GroupMember deletion: removePerson)
{
boolean happen = members.remove(deletion);
if(happen)
{
System.out.println("YESSS");
}
}
for(GroupMember addition: addPerson)
{
members.add(addition);
}
if(removePerson.size() > 0 || addPerson.size() > 0)
{
currentContactItem.update(ConflictResolutionMode.AlwaysOverwrite);
}
}
}

Excatly how to test? (Unittest, JUnit, PhpUnit)

Well this question might be too localized.
Lets suppose I have forum system to test. Lets delete an user and his posts. Let me use a pseudo-code for the sake of simplificity:
class User
{
function add() { ... }
function delete (userID)
{
container::getOrCreateUserPostObject.deletePostsByUserID (userID)
DELETE FROM users WHERE ID = userID
}
}
class UserPost
{
function deletePostsByUserID (userID)
{
DELETE FROM posts WHERE USERID = userID
}
}
this now must be tested:
function testDeleteUser()
{
container::getOrCreateUserObject.add();
container::getOrCreateUserObject.add();
container::getOrCreateUserObject.delete (1)
// now check in the DB that how many records left, really one was deleted etc.
}
another test
function testDeletePosts
{
container::getOrCreateUserPostObject.deletePostsByUserID (1);
// again, now check in the DB that how many records left, really one was deleted etc.
}
this looks OK so far. The user deletion and user posts deletion works, and their test standalone.
Yes, standalone. We checked if its OK to delete an user and checked if its OK to delete his post. We didnt check if we delete an user with his posts works! There are two good working "lego" elements but is that OK if we put them together?
If I put this "global" test to testDeleteUser() then I repeat the post-deletion test code...
I don't know if i get you right, but in a test, you should not really rely on specific user id's like you are doing in testDeletePosts(), you should rather add a user here as well, add some posts, and delete these posts again. So your test is completely independent.
Update:
Something like this for checking the referential integrity
function testDeleteUsersAndPosts
{
addedUsers[0] = user.add();
addedPosts[0] = post.add(addedUsers[0], 'first Post')
addedPosts[1] = post.add(addedUsers[0], 'second Post')
addedUsers[1] = user.add();
addedPosts[2] = post.add(addedUsers[1], 'third Post for the second user')
// Check how many posts you have
allPosts = post.get().count()
for (id in addedUsers)
{
user.delete(id)
}
// Check how many posts you have now
allPostsNow = post.get().count();
return allPostsNow == (allPosts -3)
}
And something like this for checking the Post deletion only
function testDeletePosts
{
userID = user.add();
addedPost = post.add(userID, 'first Post')
// Check how many posts you have
allPosts = post.get().count()
post.delete(addedPost)
return post.get(addedPost) == false
}

Reloading a datatable with values from database

I currently have a data table that displays a list of Users obtained from my database (Users Table). My application allows me to do the following:
Select a Group
Select a User
Add
UserGroups datatable displays the Group and User that was added.
The User that is added, will not be displayed in the User data table -- meaning to say, it is only in the view that the user will not be displayed. However, the user still exists in the database table.
(This is happening in my web view)
For example:
Group:
1. Web
2. Projects
3. Management
User:
1. Tom
2. Jane
3. John
I select 1 group and 1 user, and add it to the User Group.
UserGroup:
1. Management, John
AND User and Group tables shows the following:
Group:
1. Web
2. Projects
3. Management
User:
1. Tom
2. Jane
How would I refresh the User table, so that I can obtain a new list of Users from my database for another round of selection ?? because once I add all the Users, the User table is empty, and I want the User datatable to refresh, when I click on a new Group for selection.
Any clues or suggestions on how I might go about doing so... I am clueless.
I currently have the following methods in my managedBean:
My methods for retrieving a list of Users, Groups and UserGroups.
public List<Usuarious> getListOfUsuarios() throws DAOExceptions{
List<Usuarious> usuariosList = userDAO.list();
listOfUsuarios = usuariosList;
return listOfUsuarios;
}
public List<Grupos> getListOfGrps() throws DAOExceptions {
List<Grupos> grpList = grpDAO.list();
listOfGrps = grpList;
return listOfGrps;
}
public List<UsuariousGrupos> getListOfUserGroups() throws DAOExceptions{
List<UsuariousGrupos> usuariosGruposList = userGrpDAO.list(var2);
listOfUserGroups = usuariosGruposList;
return listOfUserGroups;
}
I thought of just creating a refreshList() method:
public void refreshList() throws DAOExceptions{
listOfUsuarios = getListOfUsuarios();
}
And then adding it to my finishAddUser() method list to refresh the datatable:
public void finishAddUsuariosGrupos()throws DAOExceptions {
this.userGroups.setId_grupo(var2);
this.userGroups.setId_usuario(var1);
userGrpDAO.create(userGroups);
refreshList();
}
But it is not working out.
I had a similar datatable refresh issue. I solved it by adding settimeout to the datatable:
<webuijsf:table onClick="setTimeout('#{user$reports.updateGeneratedReportList()}',500);"/>
updateGeneratedReportList is method is equal to your refreshList method.

Categories

Resources