Role3Resource.java
/*
* Copyright © 2024-2025 The CTAN Team and individual authors
*
* This file is distributed under the 3-clause BSD license.
* See file LICENSE for details.
*/
package org.ctan.site.resources.site;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.ctan.site.domain.account.Role;
import org.ctan.site.stores.base.GeneralPage;
import io.dropwizard.hibernate.UnitOfWork;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.MediaType;
/**
* The class <code>Role3Resource</code> contains the CRUD controller for the
* roles resource.
*
* @author <a href="mailto:gene@ctan.org">Gerd Neugebauer</a>
*/
@Path("/3.0/admin")
@Produces(MediaType.APPLICATION_JSON)
public class Role3Resource {
/**
* The method <code>list</code> provides means to retrieve a page of roles.
*
* @param query the name pattern
* @param page the page
* @param size the page size
* @param orderBy the order
* @param asc the indicator for ascending
* @return the page for the roles or {@code null}
*/
@GET
@Path("/roles")
@RolesAllowed({"admin"})
@UnitOfWork(value = "siteDb")
public GeneralPage list(@QueryParam("q") String query,
@QueryParam("page") int page,
@QueryParam("size") long size,
@QueryParam("order") String orderBy,
@QueryParam("asc") boolean asc) {
Stream<Role> stream = Arrays.stream(Role.values());
if (query != null && !query.isEmpty()) {
final String qq = query.toUpperCase();
stream = stream.filter(role -> role.toString().startsWith(qq));
}
if ("authority".equals(orderBy)) {
stream = stream.sorted((a, b) -> asc
? a.toString().compareTo(b.toString())
: b.toString().compareTo(a.toString()));
} else if (orderBy != null && !orderBy.isEmpty()) {
throw new IllegalArgumentException(
"order field is unknown: " + orderBy);
}
return new GeneralPage(Role.values().length,
stream
.limit(size)
.skip((page - 1) * size)
.map(role -> Map.of("authority", (Object) role.toString()))
.collect(Collectors.toList()));
}
}