Spring Boot - Calling a controller from another controller without using RedirectAttributes

Viewed 644

What I want to do:

Sending push notification to admin after an user do a specific thing.

Problem:

If I use RedirectAttributes, i need to return a string value for calling another endpoint but I need to return a http response and a model to user as well. So I wonder if there is another way to call another endpoint or what is the proper way to do that with RedirectAttributes.

@GetMapping("get_admin")
public ResponseEntity<Admin> getAdminById(@RequestHeader("lang") String locale,
                                          @RequestParam("id") Integer id,
                                          RedirectAttributes redirectAttrs) throws EntityNotFoundException {
    Admin admin = adminService.getAdminById(id);
    if (admin == null) {
        return new ResponseEntity(new ResponseAdmin(new LangString().getNoSuchAnAdmin(locale),"0"), HttpStatus.OK);
    }

    redirectAttrs.addFlashAttribute("locale",locale);
    redirectAttrs.addFlashAttribute("opType","0");
    redirectAttrs.addFlashAttribute("message","message");
    redirectAttrs.addFlashAttribute("type","type");
    redirectAttrs.addFlashAttribute("data","data");

    return new ResponseEntity(new ResponseAdmin(admin), HttpStatus.OK); 
    >>> I can't write "return redirect:/push_call;" since return type must be ResponseEntity, not String.
}

@GetMapping("push_call")
public ResponseEntity<String> redirectedPush(Model model){

    int opType = (int) model.asMap().get("opType");;
    String locale = (String) model.asMap().get("locale");;

    String messageStr = (String) model.asMap().get("message");;
    String dataStr = (String) model.asMap().get("data");;
    String typeStr = (String) model.asMap().get("type");;

    JSONObject body = new JSONObject();
    body.put("to", "XXXXXX");

    HttpEntity<String> request = new HttpEntity<>(body.toString());

    CompletableFuture<String> pushNotification = androidPushNotificationsService.send(request);

    try {
        String firebaseResponse = pushNotification.get();
        return new ResponseEntity<>(firebaseResponse, HttpStatus.OK);

    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }

    return new ResponseEntity<>("Push Notification ERROR!", HttpStatus.BAD_REQUEST);
}
1 Answers

Just return redirectedPush(model) then

Related