View Javadoc
1   /*
2    * Copyright 2012-2025 CodeLibs Project and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.app.web.api.admin.role;
17  
18  import static org.codelibs.fess.app.web.admin.role.AdminRoleAction.getRole;
19  
20  import java.util.List;
21  import java.util.stream.Collectors;
22  
23  import org.apache.logging.log4j.LogManager;
24  import org.apache.logging.log4j.Logger;
25  import org.codelibs.fess.app.pager.RolePager;
26  import org.codelibs.fess.app.service.RoleService;
27  import org.codelibs.fess.app.web.CrudMode;
28  import org.codelibs.fess.app.web.api.ApiResult;
29  import org.codelibs.fess.app.web.api.admin.FessApiAdminAction;
30  import org.codelibs.fess.opensearch.user.exentity.Role;
31  import org.lastaflute.web.Execute;
32  import org.lastaflute.web.response.JsonResponse;
33  
34  import jakarta.annotation.Resource;
35  
36  /**
37   * API action for admin role management.
38   */
39  public class ApiAdminRoleAction extends FessApiAdminAction {
40  
41      /** The logger for this class. */
42      private static final Logger logger = LogManager.getLogger(ApiAdminRoleAction.class);
43  
44      // ===================================================================================
45      //                                                                         Constructor
46      //                                                                         ===========
47      /**
48       * Default constructor.
49       */
50      public ApiAdminRoleAction() {
51          super();
52      }
53  
54      // ===================================================================================
55      //                                                                           Attribute
56      //                                                                           =========
57  
58      /** The role service for managing role settings. */
59      @Resource
60      private RoleService roleService;
61  
62      /**
63       * Retrieves role settings with pagination.
64       *
65       * @param body the search parameters for filtering and pagination
66       * @return JSON response containing role settings list
67       */
68      // GET /api/admin/role/settings
69      // PUT /api/admin/role/settings
70      @Execute
71      public JsonResponse<ApiResult> settings(final SearchBody body) {
72          validateApi(body, messages -> {});
73          final RolePager pager = copyBeanToNewBean(body, RolePager.class);
74          final List<Role> list = roleService.getRoleList(pager);
75          return asJson(
76                  new ApiResult.ApiConfigsResponse<EditBody>().settings(list.stream().map(this::createEditBody).collect(Collectors.toList()))
77                          .total(pager.getAllRecordCount())
78                          .status(ApiResult.Status.OK)
79                          .result());
80      }
81  
82      /**
83       * Retrieves a specific role setting by ID.
84       *
85       * @param id the ID of the role setting to retrieve
86       * @return JSON response containing the role setting
87       */
88      // GET /api/admin/role/setting/{id}
89      @Execute
90      public JsonResponse<ApiResult> get$setting(final String id) {
91          return asJson(new ApiResult.ApiConfigResponse().setting(roleService.getRole(id).map(this::createEditBody).orElseGet(() -> {
92              throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
93              return null;
94          })).status(ApiResult.Status.OK).result());
95      }
96  
97      /**
98       * Creates a new role setting.
99       *
100      * @param body the role data to create
101      * @return JSON response containing the created role setting ID
102      */
103     // POST /api/admin/role/setting
104     @Execute
105     public JsonResponse<ApiResult> post$setting(final CreateBody body) {
106         validateApi(body, messages -> {});
107         body.crudMode = CrudMode.CREATE;
108         final Role entity = getRole(body).orElseGet(() -> {
109             throwValidationErrorApi(messages -> {
110                 messages.addErrorsCrudFailedToCreateInstance(GLOBAL);
111             });
112             return null;
113         });
114         try {
115             roleService.store(entity);
116         } catch (final Exception e) {
117             logger.warn("Failed to process a request.", e);
118             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateCrudTable(GLOBAL, buildThrowableMessage(e)));
119         }
120         return asJson(new ApiResult.ApiUpdateResponse().id(entity.getId()).created(true).status(ApiResult.Status.OK).result());
121     }
122 
123     /**
124      * Updates an existing role setting.
125      *
126      * @param body the role data to update
127      * @return JSON response containing the updated role setting ID
128      */
129     // PUT /api/admin/role/setting
130     @Execute
131     public JsonResponse<ApiResult> put$setting(final EditBody body) {
132         validateApi(body, messages -> {});
133         body.crudMode = CrudMode.EDIT;
134         final Role entity = getRole(body).orElseGet(() -> {
135             throwValidationErrorApi(messages -> {
136                 messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, body.id);
137             });
138             return null;
139         });
140         try {
141             roleService.store(entity);
142         } catch (final Exception e) {
143             logger.warn("Failed to process a request.", e);
144             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToUpdateCrudTable(GLOBAL, buildThrowableMessage(e)));
145         }
146         return asJson(new ApiResult.ApiUpdateResponse().id(entity.getId()).created(false).status(ApiResult.Status.OK).result());
147     }
148 
149     /**
150      * Deletes a role setting by ID.
151      *
152      * @param id the ID of the role setting to delete
153      * @return JSON response indicating success or failure
154      */
155     // DELETE /api/admin/role/setting/{id}
156     @Execute
157     public JsonResponse<ApiResult> delete$setting(final String id) {
158         final Role entity = roleService.getRole(id).orElseGet(() -> {
159             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
160             return null;
161         });
162         try {
163             roleService.delete(entity);
164         } catch (final Exception e) {
165             logger.warn("Failed to process a request.", e);
166             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToDeleteCrudTable(GLOBAL, buildThrowableMessage(e)));
167         }
168         return asJson(new ApiResult.ApiUpdateResponse().id(id).created(false).status(ApiResult.Status.OK).result());
169     }
170 
171     /**
172      * Creates an EditBody from a Role entity.
173      *
174      * @param entity the role entity to convert
175      * @return the converted EditBody
176      */
177     protected EditBody createEditBody(final Role entity) {
178         final EditBody body = new EditBody();
179         copyBeanToBean(entity, body, copyOp -> {
180             copyOp.excludeNull();
181         });
182         return body;
183     }
184 }