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.dataconfig;
17  
18  import static org.codelibs.core.stream.StreamUtil.stream;
19  import static org.codelibs.fess.app.web.admin.dataconfig.AdminDataconfigAction.getDataConfig;
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.DataConfigPager;
29  import org.codelibs.fess.app.service.DataConfigService;
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.DataConfig;
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 data config.
47   *
48   */
49  public class ApiAdminDataconfigAction extends FessApiAdminAction {
50  
51      /**
52       * Default constructor.
53       */
54      public ApiAdminDataconfigAction() {
55          super();
56      }
57  
58      private static final Logger logger = LogManager.getLogger(ApiAdminDataconfigAction.class);
59  
60      // ===================================================================================
61      //                                                                           Attribute
62      //                                                                           =========
63      @Resource
64      private DataConfigService dataConfigService;
65  
66      // ===================================================================================
67      //                                                                      Search Execute
68      //                                                                      ==============
69  
70      /**
71       * Retrieves data config settings with pagination support.
72       *
73       * @param body the search body containing pagination and filter parameters
74       * @return JSON response containing list of data config settings
75       */
76      // GET /api/admin/dataconfig/settings
77      // PUT /api/admin/dataconfig/settings
78      @Execute
79      public JsonResponse<ApiResult> settings(final SearchBody body) {
80          validateApi(body, messages -> {});
81          final DataConfigPager pager = copyBeanToNewBean(body, DataConfigPager.class);
82          final List<DataConfig> list = dataConfigService.getDataConfigList(pager);
83          return asJson(
84                  new ApiResult.ApiConfigsResponse<EditBody>().settings(list.stream().map(this::createEditBody).collect(Collectors.toList()))
85                          .total(pager.getAllRecordCount())
86                          .status(ApiResult.Status.OK)
87                          .result());
88      }
89  
90      /**
91       * Retrieves a specific data config setting by ID.
92       *
93       * @param id the ID of the data config to retrieve
94       * @return JSON response containing the data config setting
95       */
96      // GET /api/admin/dataconfig/setting/{id}
97      @Execute
98      public JsonResponse<ApiResult> get$setting(final String id) {
99          return asJson(new ApiConfigResponse().setting(dataConfigService.getDataConfig(id).map(this::createEditBody).orElseGet(() -> {
100             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
101             return null;
102         })).status(Status.OK).result());
103     }
104 
105     /**
106      * Creates a new data config setting.
107      *
108      * @param body the request body containing data config information
109      * @return JSON response with result status
110      */
111     // POST /api/admin/dataconfig/setting
112     @Execute
113     public JsonResponse<ApiResult> post$setting(final CreateBody body) {
114         validateApi(body, messages -> {});
115         body.crudMode = CrudMode.CREATE;
116         final DataConfig dataConfig = getDataConfig(body).map(entity -> {
117             try {
118                 dataConfigService.store(entity);
119             } catch (final Exception e) {
120                 logger.warn("Failed to process a request.", e);
121                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateCrudTable(GLOBAL, buildThrowableMessage(e)));
122             }
123             return entity;
124         }).orElseGet(() -> {
125             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL));
126             return null;
127         });
128 
129         return asJson(new ApiUpdateResponse().id(dataConfig.getId()).created(true).status(Status.OK).result());
130     }
131 
132     /**
133      * Updates an existing data config setting.
134      *
135      * @param body the request body containing updated data config information
136      * @return JSON response with result status
137      */
138     // PUT /api/admin/dataconfig/setting
139     @Execute
140     public JsonResponse<ApiResult> put$setting(final EditBody body) {
141         validateApi(body, messages -> {});
142         body.crudMode = CrudMode.EDIT;
143         final DataConfig dataConfig = getDataConfig(body).map(entity -> {
144             try {
145                 dataConfigService.store(entity);
146             } catch (final Exception e) {
147                 logger.warn("Failed to process a request.", e);
148                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToUpdateCrudTable(GLOBAL, buildThrowableMessage(e)));
149             }
150             return entity;
151         }).orElseGet(() -> {
152             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, body.id));
153             return null;
154         });
155         return asJson(new ApiUpdateResponse().id(dataConfig.getId()).created(false).status(Status.OK).result());
156     }
157 
158     /**
159      * Deletes a data config setting by ID.
160      *
161      * @param id the ID of the data config to delete
162      * @return JSON response indicating the deletion status
163      */
164     // DELETE /api/admin/dataconfig/setting/{id}
165     @Execute
166     public JsonResponse<ApiResult> delete$setting(final String id) {
167         dataConfigService.getDataConfig(id).ifPresent(entity -> {
168             try {
169                 dataConfigService.delete(entity);
170                 saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
171             } catch (final Exception e) {
172                 logger.warn("Failed to process a request.", e);
173                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToDeleteCrudTable(GLOBAL, buildThrowableMessage(e)));
174             }
175         }).orElse(() -> {
176             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
177         });
178         return asJson(new ApiResponse().status(Status.OK).result());
179     }
180 
181     /**
182      * Creates an EditBody from a DataConfig entity for API responses.
183      * Handles permission and virtual host encoding.
184      *
185      * @param entity the DataConfig entity to convert
186      * @return the converted EditBody object
187      */
188     protected EditBody createEditBody(final DataConfig entity) {
189         final EditBody body = new EditBody();
190         copyBeanToBean(entity, body, copyOp -> {
191             copyOp.excludeNull();
192             copyOp.exclude(Constants.PERMISSIONS, Constants.VIRTUAL_HOSTS);
193         });
194         final PermissionHelper permissionHelper = ComponentUtil.getPermissionHelper();
195         body.permissions = stream(entity.getPermissions()).get(stream -> stream.map(s -> permissionHelper.decode(s))
196                 .filter(StringUtil::isNotBlank)
197                 .distinct()
198                 .collect(Collectors.joining("\n")));
199         body.virtualHosts = stream(entity.getVirtualHosts())
200                 .get(stream -> stream.filter(StringUtil::isNotBlank).distinct().map(String::trim).collect(Collectors.joining("\n")));
201         return body;
202     }
203 }