Reloading a datatable with values from database - java

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.

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.

Vaadin pass parameter to view

I am currently making a form for film database, using Vaadin. My problem is the whole situation with deep linking. I want to have a url with an id of movie in it, to make possible to get to the form of concrete movie.
localhost:port/filmView/idOfSelectedMovie
I am currently using pushState but there are couple of problems.
1) When I add string "Film/" before Id, the first selection works fine, however with following selections the url just keeps adding this.
http://localhost:8081/Film/Film/Film/Film/Film/4
2) The second option I tried was using just an id. The effect was that the url just keeps the host with port, and gets rid of ViewName
http://localhost:8801/4
I had already tried to use replaceState and Urifragment methods, the effect wasn't better at all.
the function handling selection of movie on the list
this.itemsList.addSelectionListener(selectionEvent -> {
if (selectionEvent.getFirstSelectedItem().isPresent()) {
Film selectedFilm = selectionEvent.getFirstSelectedItem().get();
this.setupForm(selectedFilm);
Page.getCurrent().pushState("Film/" + selectedFilm.getFilmId());
}
});
What you have to do while navigating between views this: let's say you have a View with a list of films, from you can select a film. When you select a film from that list, you move to the film View
getUI().getNavigator().navigateTo(FilmView + "/" + filmId); //let's say id 88
in this way, you will navigate to http://localhost:8081/Film/88
now, in your FilmView you can get and use this id, something like:
public class FilmView extends VerticalLayout implements View{
#Override
public void enter(ViewChangeEvent event) {
String yourPassedId = event.getParameters();
//do stuff with your id, for example loading from DB
}
}
In this way, you can reach every film you want with hard link, like http://localhost:8081/Film/88

Vaadin set selected row of table

Vaadin: I need to set the selected row, after I update table content.
I have a Comboboxbutton containing different customers.
Additionally I have two tables, the first shows main categories and the secound shows subcategories.
Initially, no customer is selected, Main categories are shown, no subcategory is shown.
When I click on a category (lets say product for example!), sub-category table appers and shows sub-categories.
When I change the customer now from empty to a specific customer, both tables are filtered, BUT: The product-selection is lost. I need to set the selection to the one selected before.
I get the table content as an sql-container object from antoher class.
mainCatTable = new Table();
...
mainCatTable.setContainerDataSource(source.getMainCats());
//My Checkboxbutton
Combobox custBox = new ComboBox();
//Get the customers from the Database
custBox.setContainerDataSource(source.getCustomers());
custBox.setItemCaptionPropertyId("Customers");
custBox.addValueChangeListener(new ValueChangeListener() {
public void valueChange(ValueChangeEvent valueEvent) {
//Here I need to store the old selection, before i update the mainCat table to a specific customer
mainCatTable.setContainerDataSource(source.getMainCats(currentCustomer));
//Here I need something to set the selected row to the previous value
subCatTable.setContainerDataSource(source.getSubCats());
}
});
The sql-container which the getMainCats method returns, is created like this:
FreeformQuery subcatExtractionQuery = new FreeformQuery("select customerName from customers", connectionPool);
return new SQLContainer(subcatExtractionQuery);
The problem is, t tried different ways, but it didn't work.
This was my try:
https://vaadin.com/forum/#!/thread/1819417/1819416
But they use an indexcontainer, but I don't.
Can anybody explain how to do this WITHOUT an index container?
What about to use value of the table to get/set "selected" row?
Object value = mainCatTable.getValue();
mainCatTable.setContainerDataSource(source.getMainCats(currentCustomer));
mainCatTable.setValue(value);

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

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

functional test in playframework fails when adding items to cart

I wrote a functional test to check adding items to a shopping cart.For a user to be able to add items to cart,he needs to login.So,I created a method to login the user and another method to add the item.Before and after the addtocart method in test,I am checking the size of content of cart.The addtocart functionality works without any problem when I run the app in dev mode(I can check the db too-which is postgres and not an in memory db).The addtocart fails in test.
the controller method which adds item to cart
public static void addItemToCart(Long productId,Long cartId,String quantity) {
Product product = Product.findById(productId);
ShopCart cart = ShopCart.findById(cartId);
int qty = Integer.parseInt(quantity);
CartItem cartItem = new CartItem(product,qty);
cart.addItem(cartItem);
cart.save();
System.out.println("Controller::addItemToCart()::cart id="+cart.id+" has="+cart.cartItems.size()+" items);
}
my test method is
#Test
public void testUserCanAddItemsToCart() {
Fixtures.loadModels("data.yml");
User user = User.find("byEmail","user#shop.com").first();
loginAsCustomer("user#shop.com","userpass");
ShopCart usercart = new ShopCart(user);
usercart.save();
System.out.println("BEFORE ADD::usercart="+usercart.id+" has :"+usercart.cartItems.size()+" items");
assertTrue(usercart.cartItems.size()==0);
addItemsToCart(usercart);
System.out.println("AFTER ADD::usercart="+usercart.id+" has :"+usercart.cartItems.size()+" items");
assertFalse(usercart.cartItems.size()==0);//why does this fail?
}
private Response addItemsToCart(ShopCart cart) {
Product pdt = Product.find("byIsbn","654-0451160522").first();
assertNotNull(pdt);
System.out.println("addItemsToCart():BEFORE ADD cart="+cart.id+" has="+cart.cartItems.size());
Map<String,String> addtocartParams = new HashMap<String,String>();
addtocartParams.put("cartId", cart.id.toString());
addtocartParams.put("quantity", "2");
String addtocarturl = "/items/addtocart/"+pdt.id.toString();
Response response = POST(addtocarturl,addtocartParams);
System.out.println("addItemsToCart():AFTER ADD cart="+cart.id+" has="+cart.cartItems.size());
return response;
}
The console output I get is
BEFORE ADD::usercart=48 has :0 items
addItemsToCart():BEFORE ADD cart=48 has=0
Controller::addItemToCart()::cart id=48 has=1 items
addItemsToCart():AFTER ADD cart=48 has=0
AFTER ADD::usercart=48 has :0 items
Here, in the controller method, the cart instance (of id=48) has 1 item after it is saved to db.But in the test method ,the cart instance of same id has 0 content.
I commented out the assertFalse method and retrieved the cart from db using the cartId.Even then the cart of same id has 0 content.I can't understand why this is happening..can anyone shed some light?
//test method body ..modified
ShopCart cart = ShopCart.findById(usercart.id);
System.out.println("AFTER ADD::cart="+cart.id+" has :"+cart.cartItems.size()+" items");
assertFalse(cart.cartItems.size()==0);//why does this fail?
It fails because the cart instance used by your test method and the cart instance used by the addItemToCart method are different. Each transaction has its own instance of the entity. And JPA doesn't automagically refresh an entity when some other transaction updates the row mapped by this entity.
You should reload the cart from the database after addItemsToCart has been called to check if something has been added to the cart in database.
I am a slave to object-oriented thinking, so what I'm wondering is, have you thought about making addItemsToCart() a method of your ShopCart class? I'm envisioning something like:
...
ShopCart usercart = new ShopCart(user);
usercart.addItemsToCart(pdt);
usercart.save();
String addtocarturl = "/items/addtocart/"+pdt.id.toString();
Response response = POST(addtocarturl,addtocartParams);
return response;
It's just easier for me to think about making (or retrieving) a ShopCart object, modifying it, and putting it in the database. That's how I would avoid this.
I had the same issue and adding JPA.em().clear() in my test before I get the model from the database solved this issue for me.

Categories

Resources