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.webconfig;
17  
18  import static org.codelibs.core.stream.StreamUtil.stream;
19  import static org.codelibs.fess.app.web.admin.webconfig.AdminWebconfigAction.getWebConfig;
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.WebConfigPager;
29  import org.codelibs.fess.app.service.WebConfigService;
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.WebConfig;
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 web configuration management.
47   *
48   */
49  public class ApiAdminWebconfigAction extends FessApiAdminAction {
50  
51      /** The logger for this class. */
52      private static final Logger logger = LogManager.getLogger(ApiAdminWebconfigAction.class);
53  
54      // ===================================================================================
55      //                                                                         Constructor
56      //                                                                         ===========
57      /**
58       * Default constructor.
59       */
60      public ApiAdminWebconfigAction() {
61          super();
62      }
63  
64      // ===================================================================================
65      //                                                                           Attribute
66      //                                                                           =========
67      /** The web config service for managing web configuration settings. */
68      @Resource
69      private WebConfigService webConfigService;
70  
71      // ===================================================================================
72      //                                                                      Search Execute
73      //                                                                      ==============
74  
75      /**
76       * Retrieves web configuration settings with pagination.
77       *
78       * @param body the search parameters for filtering and pagination
79       * @return JSON response containing web configuration settings list
80       */
81      // GET /api/admin/webconfig/settings
82      // PUT /api/admin/webconfig/settings
83      @Execute
84      public JsonResponse<ApiResult> settings(final SearchBody body) {
85          validateApi(body, messages -> {});
86          final WebConfigPager pager = copyBeanToNewBean(body, WebConfigPager.class);
87          final List<WebConfig> list = webConfigService.getWebConfigList(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 web configuration setting by ID.
97       *
98       * @param id the ID of the web configuration setting to retrieve
99       * @return JSON response containing the web configuration setting
100      */
101     // GET /api/admin/webconfig/setting/{id}
102     @Execute
103     public JsonResponse<ApiResult> get$setting(final String id) {
104         return asJson(new ApiConfigResponse().setting(webConfigService.getWebConfig(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 web configuration setting.
112      *
113      * @param body the web configuration data to create
114      * @return JSON response containing the created web configuration setting ID
115      */
116     // POST /api/admin/webconfig/setting
117     @Execute
118     public JsonResponse<ApiResult> post$setting(final CreateBody body) {
119         validateApi(body, messages -> {});
120         body.crudMode = CrudMode.CREATE;
121         final WebConfig webConfig = getWebConfig(body).map(entity -> {
122             try {
123                 webConfigService.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(webConfig.getId()).created(true).status(Status.OK).result());
135     }
136 
137     /**
138      * Updates an existing web configuration setting.
139      *
140      * @param body the web configuration data to update
141      * @return JSON response containing the updated web configuration setting ID
142      */
143     // PUT /api/admin/webconfig/setting
144     @Execute
145     public JsonResponse<ApiResult> put$setting(final EditBody body) {
146         validateApi(body, messages -> {});
147         body.crudMode = CrudMode.EDIT;
148         final WebConfig webConfig = getWebConfig(body).map(entity -> {
149             try {
150                 webConfigService.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(webConfig.getId()).created(false).status(Status.OK).result());
161     }
162 
163     /**
164      * Deletes a web configuration setting by ID.
165      *
166      * @param id the ID of the web configuration setting to delete
167      * @return JSON response indicating success or failure
168      */
169     // DELETE /api/admin/webconfig/setting/{id}
170     @Execute
171     public JsonResponse<ApiResult> delete$setting(final String id) {
172         webConfigService.getWebConfig(id).ifPresent(entity -> {
173             try {
174                 webConfigService.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 WebConfig entity.
188      *
189      * @param entity the web configuration entity to convert
190      * @return the converted EditBody
191      */
192     protected EditBody createEditBody(final WebConfig entity) {
193         final EditBody body = new EditBody();
194         copyBeanToBean(entity, body, copyOp -> {
195             copyOp.excludeNull();
196             copyOp.exclude(Constants.PERMISSIONS, Constants.VIRTUAL_HOSTS);
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         body.virtualHosts = stream(entity.getVirtualHosts())
204                 .get(stream -> stream.filter(StringUtil::isNotBlank).distinct().map(String::trim).collect(Collectors.joining("\n")));
205         return body;
206     }
207 }