Java not whole object returned? - java

I am developing JSF but the problem is in the java I believe. Ok so I have a table with requests, when I press the id of the request that is sent to the reviewRequest page with:
<h:inputHidden id="id" value="#{requestClass.requestID}" />
Now that's working because I load the request details on next page (by taking ID and retrieving object from database). now when I modify the object from reviewRequest and accept, it says it is stored successfully. I then view the same page again from table I click the request id and there it goes bang nullpointerexception. When it is loading the object this time, it pass the id to retrieve method then it only returns the change but not the whole object details like name, contacts, etc. only that the user of type x submitted modification y. retrieve method from DB works for sure because all over the app it is working correctly. Any idea? some of the code below for illustration:
public void callIsValidUser(){
boolean holder = isValidUser();
if(holder == true){
rsvIns = loadDetails();
}else{
try{
FacesContext.getCurrentInstance().getExternalContext().dispatch("pending.xhtml");
}catch(IOException ioe){
System.err.print(ioe);
}
}
}
the method above works the first time but not after modification. in isValid():
public boolean isValidUser(){
boolean valid = false;
try{
rsvLocal = oracleRsv.retrieveReservation(id);
String reqDivHead = rsvLocal.rdhUser.getUserID();
//rsvLocal.rdhUser.getUserResponse();
String supervisor = rsvLocal.sUser.getUserID();
String divHead = rsvLocal.dhUser.getUserID();
String currentUser = System.getProperty("user.name");
.....
now when I inspect the rsvLocal in netbeans debug mode, i see that rdhUser.response holds the modification I entered but all rest is null. How can this happen? how can some data be retrieved from object?
Thanks,

Most likely you did not load the data at the very beginning. Then JSF created an empty bean and sets the values from the form. Now everything not mentioned in the form (and of course every empty field of the form) contains null. This half-baked bean is now stored in the DB overwriting the complete row. If you now load the row again you will see what you call "my modifications" but what is the complete content of the DB. Your old data is lost.
The key point is: JSF and the DB-Layers do not deal with "modifications" of individual fields - they handle complete entities.

Related

Firestore - Use update method for document but with Object (Java)

I want to update a document with a User object that I have, but I do not want the document to be created if it does not exist, and therefore I cannot use "DocumentReference.set" with "SetOptions.Merge()" (to my understanding).
However, according to this post (Difference between set with {merge: true} and update), "update" is actually the command I need. My problem is, it doesn't seem like update accepts a Java object.
I do not want to check whether or not the document exists myself, as this will result in an unnecessary read.
Is there any way around this?
Here is my code (I have removed success and failure listeners for simplicity):
public void saveUser(User user)
{
CollectionReference collection = db.collection("users");
String id = user.getId();
if (id.equals(""))
{
collection.add(user);
}
else
{
// I need to ensure that the ID variable for my user corresponds
// with an existing ID, as I do not want a new ID to be generated by
// my Java code (all IDs should be generated by Firestore auto-ID)
collection.document(ID).set(user);
}
}
It sounds like you:
Want to update an existing document
Are unsure if it already exists
Are unwilling to read the document to see if it exists
If this is the case, simply call update() and let it fail if the document doesn't exist. It won't crash your app. Simply attach an error listener to the task it returns, and decide what you want to do if it fails.
However you will need to construct a Map of fields and values to update using the source object you have. There are no workarounds for that.

Get value of a cookie for login test in Selenium + Java

So, I am doing tests of "Login using cookies" for a website I am working on. I tried to use the method: getValue() to get the value of a named cookie (which holds the info for a user). But the problem is, because the cookie which holds this info, only appears (in Application menu [in F12]). After completing the login process, I keep getting "nullPointerExeption". So my question is this: is there a way to get the cookie's value
before the login process and use it in order to log in?
The method for get value:
public static String getCookieValueFromWebPage(String cookieName){
String value = remoteWebDriver.manage().getCookieNamed(cookieName).getValue();
return value;
}

Populating a table dynamically with the java web-service returns

I'm trying to implement a basic web application from the values that we are getting from web-service, it will include two datatables, each of them need to be populated in server-side.
For example, web-service have a structure like this ( Let's say these are books)
Firstly i am getting the string GUID value for the objects that i want to get an information, after that i am sending a request with the parameter of this GUIDs to service to get information XML for these book objects that includes name, page and author of them.
But as an important information, my servlet needs to get these values dynamically as soon as the page of datatable is changed, if this datatable will include 30 book ( i will get the 30 guid firstly so i can clarify that ) after that, send one request for 10 of them to show them on first page of datatable, if user clicked on page two, server behind needs to send request for the other group of ten and returns me result to show on the table.
I tried to implement the structure below :
http://www.codeproject.com/Articles/359750/jQuery-DataTables-in-Java-Web-Applications#ServerSideProcessing
but it populates a table with the DataRepository ones with all of them, so with this point of view i can't use it dynamically as i totally requested.
The main need for this, XML return for many objects needs so long time.
So do you know any example link or tutorial such a need for this ?
Thank you for informations in advance!
#Hayra, thanks for providing the Code Project link to the JQuery-DataTable example, it is very helpful. This is something that I might implement soon.
What I understood from the example, the JQuery-DataTable keeps track for you specific parameters that will allow you to return the exact number of records. The specific parameters that you need are "iDisplayStart" and the iDisplayLength". The "iDisplayLength" is set when the user specifies 10 records per page and the iDisplayStart, will is set when the page number changes.
So look at the code in the Code Project example doGet Method, this section of the code returns only the subset of records back to your table.
JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request);
if(companies.size()< param.iDisplayStart + param.iDisplayLength) {
companies = companies.subList(param.iDisplayStart, companies.size());
} else {
companies = companies.subList(param.iDisplayStart, param.iDisplayStart + param.iDisplayLength);
}
try {
JsonObject jsonResponse = new JsonObject();
jsonResponse.addProperty("sEcho", sEcho);
jsonResponse.addProperty("iTotalRecords", iTotalRecords);
jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords);
for(Company c : companies){
JsonArray row = new JsonArray();
row.add(new JsonPrimitive(c.getName()));
row.add(new JsonPrimitive(c.getAddress()));
row.add(new JsonPrimitive(c.getTown()));
data.add(row);
}
jsonResponse.add("aaData", data);
response.setContentType("application/Json");
response.getWriter().print(jsonResponse.toString());
} catch (JsonIOException e) {
e.printStackTrace();
response.setContentType("text/html");
response.getWriter().print(e.getMessage());
}
I hope this help

How to prevent duplicate entries when page is refreshed

In my web page after a chain of actions the client sees the details of the reservation. The method used to populate the data to be displayed in these details also stores the reservation in the database:
#RequestMapping(params = { "complete" }, method = RequestMethod.POST, produces = "text/html")
public String completeReservation(Model uiModel, HttpServletRequest httpServletRequest, ...) {
// ...
reservation.persist();
// ...
uiModel.addAttribute(...);
uiModel.addAttribute(...);
// ...
return "reservations/success";
}
The success page is the one that displays the details.
However, if I refresh the page another reservation entry is stored and I don't want this to happen.
Any suggestions on how I should approach this problem?
Commonly this is solved by making two actions - one that's doing the business (stores a reservation) and second one that shows the result to the user.
After successfull storing of reservation in the first action, redirect to the second one. From user point of view it will be one action and if he hits the reload button, only view action is performed again.

How to store data in field from database in Spring MVC

I have a problem which is related to logic than a technology, here is a scenario, (I am using Spring + Hibernate)
I need to read some data from database to return back to page on every get request, but I thought some hack here that what if using some script someone reload page very frequently, this will cause that many calls to server, for this I thought to read data and put them in global variables or class variable, by doing so i end up writing very weird code many global variable and stupid way to give them initial value like for a variable user-status which is a byte type variable I have given -2 as initial value so that my inner logic can understand no value is set for this variable from database, below is my code
#Controller
/* #Secured("hasRole('ROLE_USERS')") */
#RequestMapping("member")
public class ApplyRoles {
#Autowired
private UserInformationForAccessApplication checkUserStatus;
// we will initialize variables to avoid auto-initialize by constructor
private byte userStatus = Constant.IntializationOfGlobalVariable.GLOBALINIT,
requesttype = Constant.IntializationOfGlobalVariable.GLOBALINIT,
access = Constant.IntializationOfGlobalVariable.GLOBALINIT;
Map<String, Object> accessnrole;
Map<String, String> country;
Map<String, String> roleArray;
#Autowired
StudentEnrollmentApplication enrollmentApplication;
#Autowired
SystemProperties systemProperties;
#Autowired
EmployeeEnrollmentApplicationResume employeeEnrollmentApplicationResume;
#Autowired
AccessEnrollmentProcessing accessEnrollmentProcessing;
private String role = Constant.IntializationOfGlobalVariable.ROLENOTSET,
fname, lname;
#RequestMapping(value = "/user", method = RequestMethod.GET)
public String checkingUserStatus(Model model, HttpSession session,
Authentication authentication) {
String sessionemail = "yashprit#gmail.com";// (String) session
// .getAttribute(Constant.SessionAttributes.LOGGEDINUSER);
// first check global value, if found set than don't fetch from database
if (userStatus == Constant.IntializationOfGlobalVariable.GLOBALINIT) {
// get user status from MySQL Database
userStatus = checkUserStatus.checkStatus(sessionemail).get(0);
if (!(userStatus == Constant.UserRoleApplicationStatus.NOTAPPLIED)) {
access = checkUserStatus.checkStatus(sessionemail).get(1);
model.addAttribute(Constant.SystemName.ACCESS, access);
}
}
if (!(userStatus >= Constant.UserRoleApplicationStatus.NOTAPPLIED || userStatus <= Constant.UserRoleApplicationStatus.REJECTED)) {
model.addAttribute("error", "User status is not avaible");
return "redirect:error/pagenotfound";
} else if (userStatus == Constant.UserRoleApplicationStatus.NOTAPPLIED) {
if (requesttype == Constant.IntializationOfGlobalVariable.GLOBALINIT) {
// get request type from MongoDB database
requesttype = checkUserStatus.getRequestType(sessionemail);
}
if (!(requesttype == Constant.RequestType.NORMALEBIT || requesttype == Constant.RequestType.INVITEBIT)) {
model.addAttribute("error",
"Facing Technichal Issue, Please try again");
return "redirect:error/pagenotfound";
}
if (requesttype == Constant.RequestType.INVITEBIT) {
if (!(Byte.parseByte((String) accessnrole
.get(Constant.SystemName.ACCESS)) == Constant.Access.USERBIT)) {
accessnrole = checkUserStatus
.getAccessAndRole(sessionemail);
}
if (accessnrole.get(Constant.SystemName.ACCESS).equals(
Constant.Database.ERRORMESSAGE)
|| accessnrole.get(Constant.SystemName.ROLE).equals(
Constant.Database.ERRORMESSAGE)) {
model.addAttribute("error",
"Facing Technichal Issue, Please try again");
return "redirect:error/pagenotfound";
}
model.addAttribute(Constant.SystemName.ACCESSNROLE, accessnrole);
model.addAttribute(Constant.SystemName.REQUESTTYPE, requesttype);
}
}
model.addAttribute(Constant.SystemName.USERSTATUS, userStatus);
return "member/user";
}
}
to avoid global variable i thought of suing cookies, because I don't want to call database on every page reload in same session, once its loaded for a session than I don't have to call to database.
Anything that can help to to redesign above part of code is much appreciated
thanks
There are really 2 things that you are considering, and correctly me if I'm wrong, but:
Caching on the server (in your Java application) to avoid doing a database lookup multiple times for the same data.
Avoid the client (browser) from sending multiple requests to the server.
The first can be resolved using caching which is available in spring uses annotations on any given method. The documentation is available here.
The second is a bit more tricky and I' leave it for now unless you discover a performance problem. It's again possible to do in Spring and takes advantage of the HTTP protocol and caching controls available in the HTTP header to inform the browser how long to cache responses.
What you are thinking about is called a "cache". It is a standard Computer Science way of doing things and they have been doing research on how to use caches for as long as there have been computers.
You might want to go do some reading on the subject. I found this one by Googling "cache tutorial java" http://javalandscape.blogspot.com/2009/01/cachingcaching-algorithms-and-caching.html
In simplest terms (a one item cache) what you want is to store some data object that you recently took some time to come up with. But you also have to have some sort of identifier so you can tell if the next request is asking for the same data. If it isn't, you have to do all the work over. If it is the same data, you just return it again.
So the algorithm works something like this in this simple case:
if (storedData != null && storedRequestInfo == userRequest.requestInfo) {
return storedData;
}
storedData = youCalculateTheRequestedData();
storedRequestInfo = userRequest.requestInfo;
return storedData;
Its not any real programming language, just something to show you how it works.
The requestInfo is whatever comes in with the request that you use to look up your database stuff. You save it in storedRequestInfo after any calculation.
This shows it as returning some data to the user, that's what is in storedData.
It's a simple, one-element cache.
(To expand on this, you can store the storedRequestInfo and storedData in the session and you end up with one of these stored for each user. You can also use a java Map and store a bunch of storedData. The problem is to decide how to limit your memory use. If you store too many of these for each user, you use up too much memory. So you limit how many each user can have either by size or by count. Then you have to decide which one to delete when it gets too big. In the simple case, you always delete, in essence, the stored one and store a new one.
I noticed your comment. ECache is just a big fancy Map in the terms I used above. I don't know if it's naturally session dependent but it can be made that way by adding the session id to the cache key.)

Categories

Resources