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.labeltype;
17  
18  import static org.codelibs.core.stream.StreamUtil.stream;
19  import static org.codelibs.fess.app.web.admin.labeltype.AdminLabeltypeAction.getLabelType;
20  
21  import java.util.List;
22  import java.util.stream.Collectors;
23  
24  import org.apache.logging.log4j.LogManager;
25  import org.apache.logging.log4j.Logger;
26  import org.codelibs.core.lang.StringUtil;
27  import org.codelibs.fess.Constants;
28  import org.codelibs.fess.app.pager.LabelTypePager;
29  import org.codelibs.fess.app.service.LabelTypeService;
30  import org.codelibs.fess.app.web.CrudMode;
31  import org.codelibs.fess.app.web.api.ApiResult;
32  import org.codelibs.fess.app.web.api.ApiResult.ApiConfigResponse;
33  import org.codelibs.fess.app.web.api.ApiResult.ApiResponse;
34  import org.codelibs.fess.app.web.api.ApiResult.ApiUpdateResponse;
35  import org.codelibs.fess.app.web.api.ApiResult.Status;
36  import org.codelibs.fess.app.web.api.admin.FessApiAdminAction;
37  import org.codelibs.fess.helper.PermissionHelper;
38  import org.codelibs.fess.opensearch.config.exentity.LabelType;
39  import org.codelibs.fess.util.ComponentUtil;
40  import org.lastaflute.web.Execute;
41  import org.lastaflute.web.response.JsonResponse;
42  
43  import jakarta.annotation.Resource;
44  
45  /**
46   * API action for admin label type management.
47   *
48   */
49  public class ApiAdminLabeltypeAction extends FessApiAdminAction {
50  
51      /** The logger for this class. */
52      private static final Logger logger = LogManager.getLogger(ApiAdminLabeltypeAction.class);
53  
54      // ===================================================================================
55      //                                                                         Constructor
56      //                                                                         ===========
57      /**
58       * Default constructor.
59       */
60      public ApiAdminLabeltypeAction() {
61          super();
62      }
63  
64      // ===================================================================================
65      //                                                                           Attribute
66      //                                                                           =========
67      /** The label type service for managing label type settings. */
68      @Resource
69      private LabelTypeService labelTypeService;
70  
71      // ===================================================================================
72      //                                                                      Search Execute
73      //                                                                      ==============
74  
75      /**
76       * Retrieves label type settings with pagination.
77       *
78       * @param body the search parameters for filtering and pagination
79       * @return JSON response containing label type settings list
80       */
81      // GET /api/admin/labeltype/settings
82      // PUT /api/admin/labeltype/settings
83      @Execute
84      public JsonResponse<ApiResult> settings(final SearchBody body) {
85          validateApi(body, messages -> {});
86          final LabelTypePager pager = copyBeanToNewBean(body, LabelTypePager.class);
87          final List<LabelType> list = labelTypeService.getLabelTypeList(pager);
88          return asJson(
89                  new ApiResult.ApiConfigsResponse<EditBody>().settings(list.stream().map(this::createEditBody).collect(Collectors.toList()))
90                          .total(pager.getAllRecordCount())
91                          .status(ApiResult.Status.OK)
92                          .result());
93      }
94  
95      /**
96       * Retrieves a specific label type setting by ID.
97       *
98       * @param id the ID of the label type setting to retrieve
99       * @return JSON response containing the label type setting
100      */
101     // GET /api/admin/labeltype/setting/{id}
102     @Execute
103     public JsonResponse<ApiResult> get$setting(final String id) {
104         return asJson(new ApiConfigResponse().setting(labelTypeService.getLabelType(id).map(this::createEditBody).orElseGet(() -> {
105             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
106             return null;
107         })).status(Status.OK).result());
108     }
109 
110     /**
111      * Creates a new label type setting.
112      *
113      * @param body the label type data to create
114      * @return JSON response containing the created label type setting ID
115      */
116     // POST /api/admin/labeltype/setting
117     @Execute
118     public JsonResponse<ApiResult> post$setting(final CreateBody body) {
119         validateApi(body, messages -> {});
120         body.crudMode = CrudMode.CREATE;
121         final LabelType labelType = getLabelType(body).map(entity -> {
122             try {
123                 labelTypeService.store(entity);
124             } catch (final Exception e) {
125                 logger.warn("Failed to process a request.", e);
126                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateCrudTable(GLOBAL, buildThrowableMessage(e)));
127             }
128             return entity;
129         }).orElseGet(() -> {
130             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL));
131             return null;
132         });
133 
134         return asJson(new ApiUpdateResponse().id(labelType.getId()).created(true).status(Status.OK).result());
135     }
136 
137     /**
138      * Updates an existing label type setting.
139      *
140      * @param body the label type data to update
141      * @return JSON response containing the updated label type setting ID
142      */
143     // PUT /api/admin/labeltype/setting
144     @Execute
145     public JsonResponse<ApiResult> put$setting(final EditBody body) {
146         validateApi(body, messages -> {});
147         body.crudMode = CrudMode.EDIT;
148         final LabelType labelType = getLabelType(body).map(entity -> {
149             try {
150                 labelTypeService.store(entity);
151             } catch (final Exception e) {
152                 logger.warn("Failed to process a request.", e);
153                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToUpdateCrudTable(GLOBAL, buildThrowableMessage(e)));
154             }
155             return entity;
156         }).orElseGet(() -> {
157             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, body.id));
158             return null;
159         });
160         return asJson(new ApiUpdateResponse().id(labelType.getId()).created(false).status(Status.OK).result());
161     }
162 
163     /**
164      * Deletes a label type setting by ID.
165      *
166      * @param id the ID of the label type setting to delete
167      * @return JSON response indicating success or failure
168      */
169     // DELETE /api/admin/labeltype/setting/{id}
170     @Execute
171     public JsonResponse<ApiResult> delete$setting(final String id) {
172         labelTypeService.getLabelType(id).ifPresent(entity -> {
173             try {
174                 labelTypeService.delete(entity);
175                 saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
176             } catch (final Exception e) {
177                 logger.warn("Failed to process a request.", e);
178                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToDeleteCrudTable(GLOBAL, buildThrowableMessage(e)));
179             }
180         }).orElse(() -> {
181             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
182         });
183         return asJson(new ApiResponse().status(Status.OK).result());
184     }
185 
186     /**
187      * Creates an EditBody from a LabelType entity.
188      *
189      * @param entity the label type entity to convert
190      * @return the converted EditBody
191      */
192     protected EditBody createEditBody(final LabelType entity) {
193         final EditBody body = new EditBody();
194         copyBeanToBean(entity, body, copyOp -> {
195             copyOp.excludeNull();
196             copyOp.exclude(Constants.PERMISSIONS);
197         });
198         final PermissionHelper permissionHelper = ComponentUtil.getPermissionHelper();
199         body.permissions = stream(entity.getPermissions()).get(stream -> stream.map(s -> permissionHelper.decode(s))
200                 .filter(StringUtil::isNotBlank)
201                 .distinct()
202                 .collect(Collectors.joining("\n")));
203         return body;
204     }
205 }