labheshr
labheshr

Reputation: 3056

Java 8: Functional interface to check permissions and return a response

I am trying to create a function withCheckPermissions which checks if the user has permissions,

  1. If the user is not permission'd return a "Bad Response"
  2. otherwise Return a "success" if it was a POST
  3. otherwise return the contents of a GET request

Here's what I have so far:

  public <A extends Response> Response withCheckPermissions(Supplier<A> code) {
    User user = getCurrentUser();
    if (isAllowed(user)) {
      try {
        return code.get();
      } catch (Exception e) {
        return handleError(ERROR_MESSAGE, e);
      }
    } else {
      log.warn("User not allowed...");
      return sendBadRequest(NO_ACCESS_MESSAGE);
    }
  } 

I am calling it as:

  @POST
  @Path("myJob")
  public Response sendMail() {
      return withCheckPermissions(() -> {
        try {
          manager.generateEmail();
        } catch (Exception e) {
          return handleError("Problem sending email", e);
        }
        return sendSuccess();
      });
    }

I get errors such as:

Could not find MessageBodyWriter for response object of type: java.util.HashMap of media type: application/octet-stream

Is there a proper way to do it?

I am trying to avoid a construct such as:

if isAllowed(User) {
   doSomething()
} else {
return errorResponse 
}

Upvotes: 1

Views: 344

Answers (1)

Paulo Ricardo Almeida
Paulo Ricardo Almeida

Reputation: 527

As you didnt define the Media Type that your endpoint produces, the type will be "application/octet-stream", unless you inform it on the request header (Accept = "text/plain").

Put @Produces(MediaType.TEXT_PLAIN) to your method and try, should work.

Upvotes: 2

Related Questions