Spring: Implement a share-via-link feature for web application - java

I have a requirement where I need to implement a share-application-state-via-link feature.
My application is a video streaming single page application consisting of some dropdown options for user to filter out available videos and a video player to play the selected videos.
Now first on the basis of dropdown options , a user selects the available videos and add it to video player. At max 4 videos could be added. Now after that, I need to share this state of my application to some other user so I get a share link(just like Share answer in StackOverflow) and I send this to other user. This other user just need to hit this URL and it will load the exact state of application with videos added to player and dropdown populated with respective options.
My Approach:
I have a /getVideo rest service which fetches the video data and send it as json response back to angular based frontend. I have created a Share button which when clicked, creates a link by adding all the selected dropdown options something like:
https://localhost:8080/MyApp/shared?genre=Action&type=web-series
I have created a method /shared which will take these params and call the /getVideo internally.
The problem here is, I need to load index.html when the above link is hit. I also have to send the getVideo data to be loaded with index.html and the application should function properly. Am not able to solve this problem and need help.
Is my approach correct? Is there any alternate way? Am using Spring-Boot for backend and angular2 for frontend.
Here is the /shared API:
#RequestMapping(value = "/shared", method = RequestMethod.GET)
public String getSharedVideo(RedirectAttributes redirectAttributes,
#RequestParam(value="genre", required=false) String genre,
#RequestParam(value="date", required=false) String date,
#RequestParam(value="type", required=false) String type,
#RequestParam(value="version", required=false) String version,
#RequestParam(value="category", required=false) String category
){
List<Lab> lab = null;
try {
lab = videoService.getVideo(genre, date, type, version, category);
redirectAttributes.addAllAttributes(lab); // how to send this data to frontend
return "index.html";
} catch(Exception e) {
LOGGER.error("EXCEPTION - " + e.getMessage());
}
Any help would be appreciated.

Related

Spring boot not saving path variable to database

I currently have a form that allows users to upload data, however, I want to save the path variable to the database for that object.
The thymeleaf form action is as follows.
<form th:action="#{/homepage/{room_id}/saveLayout(room_id=${Room.room_id})}" th:object="${layout}" method="post">
This is the controller that the form corresponds to
#PostMapping("/homepage/{room_id}/saveLayout")
public String saveLayout(#ModelAttribute("layout") Layout layout, #PathVariable(value = "room_id")long room_id) {
layout.setroomid(room_id);
layout.Service.saveLayout(layout);
return "redirect:/homepage";
}
The idea is that when a user sends the form after clicking on say room 2, the URL should be
homepage/2/saveLayout
However, the issue is that the URL does not contain the ID of the room, instead it looks like this
homepage//saveLayout
Which in turn causes spring boot to return an error saying the URL contained malicious content '//'. Even after removing the path variables and hard coding an integer 2 into the setroomid method, the room id does not change in the database. I have another controller which directs the user to the form to input the data, this adds attributes layout and room to the model. There are no red underlines in either of the HTML documents within the thymeleaf code. My setroomID method is
public void setroomid(long room_id){
roomid = roomid;
}
I should also make it clear that the actual data uploading works, however the roomID for a layout remains unchanged. If anyone is able to recommend any changes to make this work, or suggest an alternate way of binding a roomID to a layout in the database then it would be appreciated, thanks.

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.

Dynamic URL issue on JSP in data table

I am using spring and hibernate.
In JSP page I am using data table in which there are 3 columns ie App, Res, and id. The values of three columns are coming dynamically and these three are link.
For Example : Res is "xyz" and App is "abc" and user clicks on this xyz link then my url would be like /admin/<Res>/<App> so url become /admin/xyz/abc.
In controller, I am taking it as a #PathVariable and #RequestMapping is /admin/{res_name}/{app_name} so Res and App become available in controller.
My Problem :
1) If Res is "xvf\y" and App is "abc" and if user clicks on link then url become /admin/xvf/y/abc so it doesn't match with my controller request mapping. Hence , controller method is not getting called.
2) If Res is "xvf\y" and App is "ab\c" then also issue will occur.
How to handle this. Please help.
it should be URL Encoded so xvf\y is transformed to xvf%5Cy
Use e.g. URLEncoder.encode("xvf\y") (or pass desired encoding as the second param)

is there a way to get user created playlists using the youtube java library?

I have code like this; and it works fine. but I would like only user created lists. Is this possible?
*/
ChannelListResponse clr = youtube.channels()
.list("contentDetails").setMine(true).execute();
// Get the user's uploads playlist's id from channel list
// response
String uploadsPlaylistId = clr.getItems().get(0)
.getContentDetails().getRelatedPlaylists()
// I want user created lists not uploads or
// favorites
.getUploads();
I have just looked at youtube data api v3 (I didn't use before just looked at api.).
It seems, it provides PlaylistListResponse then you can get Playlist items and theirs ids.

Categories