How to delete an item from a collection in the DOM, GWT - java

I am newbie on GWT. I am writing the code of a page which asks a JSON object that contains two collections and I use one of these collection to fill a Flextable.
This is my JSON Object:
public class Users extends JavaScriptObject {
protected Users() {
}
public final native JsArray<Link> getLinks() /*-{
return this.links;
}-*/;
public final native JsArray<User> getCollection() /*-{
return this.collection;
}-*/;
}
In particular I am using the second collection (called collection) to fill a Flextable. But my problem is that when I delete one row from the table, even if I send a request with an http delete method to the server (and the server delete that item successfully), when I try to refresh the table GWT does not generate the GET request to the server, (even if it is written in the code) and Users Object is the same as before with the deleted item also.
I have tried to delete this item from collection using this method:
public static native void remove(JsArray<?> arr, int index, int count) /*-{
arr.splice(index, count);
}-*/;
....
remove(users.getCollection(), index, users.getCollection().length());
And I also tried this other technique:
users.getCollection().set(index, null);
But in both cases, I do not get the expected result, when I refresh the table I find the deleted items again.
I think that I am not managing the DOM properly, Do you have any suggestions? Any Idea? I am sure it is simple problem to solve for an expert.
EDIT:
The user can refresh the data in the table clicking a button, the handler of this event will perform a request to a server, but this request is sent on the first click only.

Basically there are two alternatives, the first is to set the header Cache Control to no-cache in the server side, while if you cannot modify the code in the server side, for example in the case of legacy applications, you can attach a random number in your request in a parameter. A request will have a uri with an additional parameter which is a random generated number, http:\\mydomain.com\something?random=12345. Two different requests will have different numbers and at the second request the response of the first request, which has been cached it will be ignored. It is not a smart practice, but it works.

For getting data like this better use HTTP POST request, because GET requests are being cached (by GWT, proxy servers...).
Also make sure your server code for deleting items is doing right job, and manually check server response in firebug or in chrome console to see if your response contains deleted records.
Please post code you use to fill flex table, are you clearing it before populating with data again ?
EDIT:
see link.
If you can use celltable http://gwt.googleusercontent.com/samples/Showcase/Showcase.html#!CwCellTable (because it holds List of elements it display underneath) or use some collection (ArrayList) to hold data that your FlexTable is displaying. Then you can easily modify that collection and redraw your flex table from it.

Related

How to get the latest value emitted in spring web flux using sinks?

I am trying to have a system where I add an object (shifts in this context) and the front end receives that and processes that without refreshing the page and making another api call. Currently, I have two functions, getAllShifts and addShift. When I add a shift I expect the getAllShifts to be updated automatically using sinks. However, the response that I get is not something I expect. The code is shown below:
private Sinks.Many<Shift> shiftSink=Sinks.many().replay().latest();
public Mono<Shift> addShift(Shift shift) throws InterruptedException {
Mono<Shift> newshift= shiftRepository.save(shift);
newshift.subscribe(u-> this.shiftSink.tryEmitNext(u));
return newshift;
}
public Flux<Shift> getAllShifts(){
this.shiftRepository.findAll().subscribe(u-> this.shiftSink.tryEmitNext(u));
shiftSink.asFlux().subscribe(u-> System.out.println(u + "UUUUUUUUUUUUU"));
return shiftSink.asFlux();
}
When the getAllShifts endpoint is engaged from the frontend using eventsource and I add a shift, I expect to receive one event containing the data from that newly added shift. Instead multiple events containing that data are emitted as shown in the picture below.
Any help would be appreciated...

Play Framework - How to build a web page with multiple MySQL queries

I've created my first Play Framework Website with Java using the official documentation. It has a single page where I display a list of items that can be filtered or modified.
I have a Controller class with a method:
public CompletionStage<Result> feedpostslist(String domain, String date, String state, int page, int resnum, String search) {
return feedRepository.getArticleList(domain, date, state, page, resnum, search).thenApplyAsync(articles -> {
FeedArticle[] list = new FeedArticle[articles.size()];
articles.toArray(list);
return ok(views.html.feedpostslist.render(list));
}, ec.current());
}
This method does a query to the DB (through feedRepository) and then display the result using the view feedpostslist.
Everything is fine but now I need to get other data from the DB to be used in the same web page (so multiple queries). How do I do this in Play Framework? I don't understand what is the best way to do that.
Should I do multiple DB request inside the method showed before (through feedRepository) and then pass all these informations to my view? I don't want to do a mess or even something too heavy to handle.
If the second query doesn't depend on the first one you can run them in parallel using combineAsync. This is a good example on how to do that:
https://github.com/playframework/play-samples/blob/2.8.x/play-java-ebean-example/app/controllers/HomeController.java#L85
If the second query depends on results on the first then there's nothing you can do but to wait for the first one to complete and run the second one.

Adding links to POST/PUT/PATCH operations in REST Web Controllers

I have a Java-written Web API wherein I have web controllers handling HTTP requests. I'm trying to implement a RESTful architecture with HATEOAS, using Spring Boot. When adding HATEOAS links in methods I can easily add links for GET/DELETE requests, but I'm having trouble with POST/PUT/PATCH requests, mostly because those require me to supply a body of the thing I want to post, usually in JSON format. I've been googling for a while and I can't find out how to do it.
Here's how I'm adding links to GET / DELETE operations.
/**
* Shows all the Rooms present in the database.
*
* #return OK status and a list of Room Minimal DTO.
*/
#GetMapping(path = "/", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getRooms() {
List<RoomDTOMinimal> roomDTOList = roomRepository.getAllDTOWebInformation();
for (RoomDTOMinimal r : roomDTOList) {
if (userService.getUsernameFromToken().equals("ADMIN")) {
Link roomSensors = linkTo(methodOn(RoomsWebController.class).getSensors(r.getName())).withRel("Get Room" +
"Sensors");
Link deleteRoom = linkTo(methodOn(RoomsWebController.class).deleteRoom(r)).withRel("Delete this Room");
r.add(roomSensors);
r.add(deleteRoom);
} else if (userService.getUsernameFromToken().equals("REGULAR_USER")) {
Link roomTemp = linkTo(methodOn(RoomsWebController.class).getCurrentRoomTemperature(r.getName())).
withRel("Get Room Temperature");
r.add(roomTemp);
}
}
return new ResponseEntity<>(roomDTOList, HttpStatus.OK);
}
I want to add a Link to an "editRoom" request, something like:
Link editRoom = linkTo(methodOn(RoomsWebController.class).configureRoom(r.getName(), WHAT GOES HERE???).withSelfRel();
But configureRoom takes in the roomName and a roomDTO in its signature. RoomDTO is a #RequestBody, so I can't give it to the Link. How should I add the link to the objects in a way that then allows me to call on that method?
I'd like to have something like:
ROOM | Delete | Edit
On the client side, where if I click DELETE the room is deleted, and if I click Edit the client side expands, with text boxes, allowing me to insert the required parameters to edit the room. I have the client-side code implemented for the Edit function, with appropriate front-end; but I can't link to it on the server-side without already providing data that should come later, from the user input. What's the best way to do this?
I've since solved it after talking with a team lead. Apparently it's acceptable to either pass null or an empty DTO object as a parameter in the scenario above; the HATEOAS implementation cares specifically about those parameters that are of the path, and roughly speaking ignores the others. Those can then be replaced as needed on the client-side upon a user performing an action / inserting input.

Javascript changes dissapear when going back from servlet to JSP

Good evening,
I have a form on a JSP page that's connected to a servlet, that form has some dynamic parts using JavaScript like adding a row to a table or adding a text field based on the selected option on a select element, Actually my problem is that I have some validations on the servlet-side, so when I go to servlet to check the (National ID) for example if there's any problem or any violations to my validation I force to get back to the form using :
if (dbm.MatchIdNumber(Candidate.getRegNumber(), Candidate.getNationalID()) == false) {
out.println("<script>\n"
+ " alert('Your National Id does not match your Registration Number');\n"
+ "</script>");
out.println("<script>\n"
+ " window.history.go(-1);\n"
+ "</script>");
}
What happens is when I get back to the form I lose all the JavaScript changes, Which's very important.
I've been reading for a while that using ajax might be the optimal solution for me, but here is my questions:
Is there a way to call a java method from JavaScript or JQuery before getting to servlet without using ajax !?!
Is there a way to get back from the servlet to the jsp page with the ability to keep all the JavaScript Chages !?
If not !!, How to use ajax in my case ?!
Thank you so much
No. JavaScript runs on the user's browser and your Java code runs on your webserver, so basically the only way to communicate between the two is via HTTP requests.
If you don't want to use AJAX, you could provide all of the relevant info when you submit the form to the server for validation. You could pass all the info you need to re-generate the form as it was, like which new fields are there and such
First, you'll need to add a new webservice to your Java webapp which performs validation. To achieve this, you could either add additional logic to your servlet (so that it looks for a request parameter like "doValidation=1" and performs validation if it's there) or write a different servlet that handles validation itself. You'll need to decide the format it should expect the form data in and how it should return the validation information.
On your frontend page, you'll need to modify the behavior of the form so that, when you need to do validation, it performs a request to this webservice and passes along the form data. I would probably do this with jQuery and do something like jQuery.ajax(...) and pass the contents of the form as a JSON object.
When your validation servlet returns data from the ajax call, you'll need to update the form based on the data it provides. If I was doing it, I would probably just have the servlet return a JSON object like {errorMessage:"..."} and I would use jQuery to add an element to the form containing the text of the validation error when it occurs. If the servlet returns an empty string or JSON object or something, I would consider it a validation success.

JavaScript EJB variable field holding value?

I have an ajax enabled list of records that I'm going through and each one has a dropdown box that I'm trying to make a required field for the form to submit. To complicate matters the 'Close Record' button is not the submit button so I can't just use required attribute on the select(dropdown box) that I'm using. The value for the selected dropdown box is saved in an Enterprise Java Bean so I thought I could just write a JavaScript function to check the value:
function CheckForm() {
var clearObj = document.getElementById("mySelect");
if(clearObj.value != "") {
return true;
} else {
clearObj.style.backgroundColor ='yellow';
}
return false;
}
This doesn't work because once I close one and go to the next it's maintaining the value of the previous record on the page. Basically I have an update-content event that I need to know how to handle. Any ideas as to how to manipulate the DOM or JSON object to make this select a required field? Thanks.
With the little information given, I would assume that when you close the existing record and then loading the next record, you are doing it through an ajax request. If thats the case, then you can add a call back for the ajax request, which would reset the drop down.
This should be a comment, but as you see, I dont have 50 points :-)

Categories