javascript - change Dom element based on firebase admin value events -
i have simple html page printed out inside servlet. here have setup firebase admin sdk , have set value event listener path.
when events fire, wish change div element , display results there.
edit: listener work on further testing logs.
but still not know how reflect changes inside div element listeners asynchronous. that's why script isn't working.
can please guide me should do. code follows:
import java.io.ioexception; import java.io.inputstream; import java.io.printwriter; import java.text.simpledateformat; import java.util.arraylist; import java.util.collections; import java.util.comparator; import java.util.date; import javax.servlet.servletexception; import javax.servlet.annotation.webservlet; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import com.google.firebase.firebaseapp; import com.google.firebase.firebaseoptions; import com.google.firebase.auth.firebasecredentials; import com.google.firebase.database.datasnapshot; import com.google.firebase.database.databaseerror; import com.google.firebase.database.databasereference; import com.google.firebase.database.firebasedatabase; import com.google.firebase.database.valueeventlistener; @webservlet("/webwaitlistviewservelet") public class webwaitlistviewservelet extends httpservlet { private static final long serialversionuid = 1l; public webwaitlistviewservelet() { super(); } protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { printwriter pw = response.getwriter(); try { string cityname=request.getparameter("city"); string restid = request.getparameter("restid"); string userid = request.getparameter("userid"); if(cityname == null || restid == null || userid == null){ system.out.println("error getting values"); return; }else{ system.out.println(cityname+" "+restid+" "+userid); } pw.println("<html>"); pw.println("<head>"); pw.println("<script>"); pw.println("function changeposition(position){ document.getelementbyid(\"positioninlist\").innerhtml = position };"); pw.println("function changetimetillturn(timetillturn){ document.getelementbyid(\"timetillturn\").innerhtml = timetillturn };"); pw.println("function showtimetillturn(){ document.getelementbyid(\"timediv\").style.display = \"visible\" };"); pw.println("function hidetimetillturn(){ document.getelementbyid(\"timediv\").style.display = \"hidden\" };"); pw.println("</script>"); pw.println("</head>"); pw.println("<body>"); pw.println("<div align=\"center\">"); pw.println("<b>your position in waitlist is:</b>"); pw.println("</div><br/>"); pw.println("<div id=\"positioninlist\" align=\"center\" style=\"color:blue\">"); pw.println("loading..."); pw.println("</div><br/>"); pw.println("<div id=\"timediv\" align=\"center\">"); pw.println("<b>approximate time till turn is: </b><span id=\"timetillturn\" style=\"color:blue\">loading...</span>"); pw.println("</div>"); pw.println("<body>"); pw.println("</html>"); pw.flush(); inputstream = getservletcontext().getresourceasstream("/web-inf/firebaseauth/firebase_admin_sdk_key.json"); // initialize app service account, granting admin privileges firebaseoptions options = new firebaseoptions.builder() .setcredential(firebasecredentials.fromcertificate(is)) .setdatabaseurl("https://restaurantrepo.firebaseio.com") .build(); try { firebaseapp.initializeapp(options); } catch (exception e) { // } // admin, app has access read , write data, regardless of security rules databasereference waitlistref = firebasedatabase.getinstance().getreference().child(cityname).child(restid).child("waitlist"); comparator<waitlistedperson> sortcomparator = new comparator<waitlistedperson>() { @override public int compare(waitlistedperson lhs, waitlistedperson rhs) { //sort ascending... bigger time entered, later person has joined... higher time entered lower position //on waitlist if(lhs.gettimeentered()<rhs.gettimeentered()){ //if time entered lower, keep person higher in list return -1; }else if(lhs.gettimeentered()==rhs.gettimeentered()){ //if time entered same, there 2 cases possible //1.. 1 person remotely entered , 1 has entered @ resto pos... in case, give priority pos entered user //2.. both people have remotely entered ... in case, give preference person lowest userid (he/she started using our app earlier) // //cases never happen //1.. 2 people same userid entered remotely @ same time .. can't happen second entry overwrites old entry //2.. 2 people same time entered @ pos ... can't happen resto host can enter 1 party @ time.. if(!lhs.isremotelyentered() && rhs.isremotelyentered()){ //log.d("fragmentcreate","lhs userid "+lhs.getuserid()+" lhs remotelyentered "+lhs.isremotelyentered()); //log.d("fragmentcreate","rhs userid "+rhs.getuserid()+" rhs remotelyentered "+rhs.isremotelyentered()); return -1; }else if(lhs.isremotelyentered() && rhs.isremotelyentered()){ //return lowest user id //userid of format uxx ... xx part begining index 1 of string , number int lhsuserid = integer.parseint(lhs.getuserid().substring(1)); int rhsuserid = integer.parseint(rhs.getuserid().substring(1)); //log.d("fragmentcreate"," userids lhsuserid "+lhsuserid+" rhsuserid"+rhsuserid); //do not tempted use string compareto function give wrong results // u11 priority on u4 in string compareto due 1 being lexicographically smaller //thus never use lexicographical sorting ever. //the user ids can never equal 2 remotely entered users never have 2 entries (can't... it's impossible due firebase) if(lhsuserid<rhsuserid){ return -1; }else if(lhsuserid==rhsuserid){ //can never happen in real life... 2 remotely entered users can never have same id ever... made safeguard return 0; }else{ return 1; } }else if(!lhs.isremotelyentered() && !rhs.isremotelyentered()){ //both entered @ pos , have same time //can never happen in real life... //made testing scenarios in case screw , give wrong inputs return 0; }else{ //log.d("fragmentcreate","lhs userid "+lhs.getuserid()+" lhs remotelyentered "+lhs.isremotelyentered()); //log.d("fragmentcreate","rhs userid "+rhs.getuserid()+" rhs remotelyentered "+rhs.isremotelyentered()); return 1; } }else{ return 1; } } }; arraylist<waitlistedperson> listofpeople = new arraylist<>(); valueeventlistener eventlistener = new valueeventlistener(){ @override public void oncancelled(databaseerror error) { pw.println("<script>hidetimetillturn();</script>"); pw.println("<script>changeposition('sorry, error occured');</script>"); system.out.println("sorry. error occured"); } @override public void ondatachange(datasnapshot datasnapshot) { int positioncounter=0; if(datasnapshot.getchildrencount()==1 || datasnapshot.getchildrencount() == 0 ){ //log.d("fragmentcreate","this indicates restaurant closed down , removed customers list"); pw.println("<script>hidetimetillturn();</script>"); pw.println("<script>changeposition('you no longer in waitlist');</script>"); system.out.println("you no longer in waitlist"); }else{ if(datasnapshot.haschild(userid)){ double averagewaittime=0.0d; long timeenteredinmillis=0; listofpeople.clear(); iterable<datasnapshot> peopleinlist = datasnapshot.getchildren(); for(datasnapshot currentperson : peopleinlist){ if(currentperson.getkey().equals("dummy")){ continue; } if(currentperson.getkey().equals(userid)){ //this our node.... break loop , enjoy using counter averagewaittime = currentperson.child("averagewaittimeperparty").getvalue(double.class); timeenteredinmillis = currentperson.child("timeentered").getvalue(long.class); listofpeople.add(new waitlistedperson(currentperson)); }else{ listofpeople.add(new waitlistedperson(currentperson)); } } //sort list using our custom comparator , index collections.sort(listofpeople,sortcomparator); //find position of user for(waitlistedperson person : listofpeople){ ++positioncounter; if(person.getuserid().equals(userid)){ break; } } double timetillturn = math.round(averagewaittime * ((double)positioncounter)); long timeshouldcomeat = timeenteredinmillis + (long)(timetillturn*60000); date timewhenturnarrives = new date(timeshouldcomeat); simpledateformat sdf = new simpledateformat("hh:mm"); pw.println("<script>showtimetillturn();</script>"); pw.println("<script>changeposition('"+positioncounter+"');</script>"); pw.println("<script>changetimetillturn('"+sdf.format(timewhenturnarrives)+"');</script>"); system.out.println(positioncounter+" "+sdf.format(timewhenturnarrives)); }else{ pw.println("<script>hidetimetillturn();</script>"); pw.println("<script>changeposition('you no longer in waitlist');</script>"); system.out.println("you no longer in waitlist"); } } } }; waitlistref.addvalueeventlistener(eventlistener); } catch (exception e) { e.printstacktrace(); }finally{ try { pw.close(); } catch (exception e) { //do nothing here } } } protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { doget(request, response); } }
with servlets, clients won't see page updates until send new request application server. can valueeventlistener
update state of in-memory object. servlet can read latest state of object whenever constructing html output.
Comments
Post a Comment