@Path("/samples")
@PermitAll // we bypass JAAS' protections, as we want to perform the checks inside the methods
@Stateless
public class SampleEndpoint {
@Inject @HawkularAccountsSample
EntityManager em;
@Inject
Instance<Persona> currentPersonaInstance;
/**
* A managed instance of the {@link PermissionChecker}, ready to be used.
*/
@Inject
PermissionChecker permissionChecker;
/**
* We need the {@link ResourceService} as we need to tell Hawkular Accounts about who created "what". A resource
* is this "what".
*/
@Inject
ResourceService resourceService;
/**
* For this example, we have four operations. We get an instance of each of them injected and qualified by its name.
*/
@Inject
@NamedOperation("sample-create")
Operation operationCreate;
@Inject
@NamedOperation("sample-read")
Operation operationRead;
@Inject
@NamedOperation("sample-update")
Operation operationUpdate;
@Inject
@NamedOperation("sample-delete")
Operation operationDelete;
@GET
public Response getAllSamples() {
Persona currentPersona = currentPersonaInstance.get();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Sample> query = builder.createQuery(Sample.class);
Root<Sample> root = query.from(Sample.class);
query.select(root);
query.where(builder.equal(root.get(Sample_.ownerId), currentPersona.getId()));
return Response.ok().entity(em.createQuery(query).getResultList()).build();
}
@GET
@Path("{sampleId}")
public Response getSample(@PathParam("sampleId") String sampleId) {
Sample sample = em.find(Sample.class, sampleId);
// before returning, we check if the current persona has permissions to access this.
if (permissionChecker.isAllowedTo(operationRead, sample.getId())) {
return Response.ok().entity(sample).build();
}
// the current persona is not allowed, so, return a 404.
return Response.status(Response.Status.NOT_FOUND).build();
}
@POST
public Response createSample(SampleRequest request) {
Persona currentPersona = currentPersonaInstance.get();
// for this example, we allow everybody to create a sample, but there might be situations where an user can
// only create resources if they are allowed access to some other resource.
Sample sample = new Sample(UUID.randomUUID().toString(), currentPersona.getId());
resourceService.create(sample.getId(), currentPersona);
sample.setName(request.getName());
em.persist(sample);
return Response.ok().entity(sample).build();
}
@DELETE
@Path("{sampleId}")
public Response removeSample(@PathParam("sampleId") String sampleId) {
Sample sample = em.find(Sample.class, sampleId);
Resource resource = resourceService.get(sampleId);
// check if the current user can perform this operation
if (permissionChecker.isAllowedTo(operationDelete, resource)) {
em.remove(sample);
return Response.noContent().build();
}
return Response.status(Response.Status.NOT_FOUND).build();
}
}