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.reqheader;
17  
18  import static org.codelibs.fess.app.web.admin.reqheader.AdminReqheaderAction.getRequestHeader;
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.ReqHeaderPager;
26  import org.codelibs.fess.app.service.RequestHeaderService;
27  import org.codelibs.fess.app.service.WebConfigService;
28  import org.codelibs.fess.app.web.CrudMode;
29  import org.codelibs.fess.app.web.api.ApiResult;
30  import org.codelibs.fess.app.web.api.ApiResult.ApiConfigResponse;
31  import org.codelibs.fess.app.web.api.ApiResult.ApiErrorResponse;
32  import org.codelibs.fess.app.web.api.ApiResult.ApiResponse;
33  import org.codelibs.fess.app.web.api.ApiResult.ApiUpdateResponse;
34  import org.codelibs.fess.app.web.api.ApiResult.Status;
35  import org.codelibs.fess.app.web.api.admin.FessApiAdminAction;
36  import org.codelibs.fess.opensearch.config.exentity.RequestHeader;
37  import org.lastaflute.web.Execute;
38  import org.lastaflute.web.response.JsonResponse;
39  
40  import jakarta.annotation.Resource;
41  
42  /**
43   * API action for admin request header management.
44   *
45   */
46  public class ApiAdminReqheaderAction extends FessApiAdminAction {
47  
48      /** The logger for this class. */
49      private static final Logger logger = LogManager.getLogger(ApiAdminReqheaderAction.class);
50  
51      // ===================================================================================
52      //                                                                         Constructor
53      //                                                                         ===========
54      /**
55       * Default constructor.
56       */
57      public ApiAdminReqheaderAction() {
58          super();
59      }
60  
61      // ===================================================================================
62      //                                                                           Attribute
63      //                                                                           =========
64  
65      // ===================================================================================
66      //                                                                           Attribute
67      //                                                                           =========
68      /** The request header service for managing request header settings. */
69      @Resource
70      private RequestHeaderService reqHeaderService;
71      /** The web config service for validating web configuration references. */
72      @Resource
73      private WebConfigService webConfigService;
74  
75      // ===================================================================================
76      //                                                                      Search Execute
77      //                                                                      ==============
78  
79      /**
80       * Retrieves request header settings with pagination.
81       *
82       * @param body the search parameters for filtering and pagination
83       * @return JSON response containing request header settings list
84       */
85      // GET /api/admin/reqheader/settings
86      // PUT /api/admin/reqheader/settings
87      @Execute
88      public JsonResponse<ApiResult> settings(final SearchBody body) {
89          validateApi(body, messages -> {});
90          final ReqHeaderPager pager = copyBeanToNewBean(body, ReqHeaderPager.class);
91          final List<RequestHeader> list = reqHeaderService.getRequestHeaderList(pager);
92          return asJson(
93                  new ApiResult.ApiConfigsResponse<EditBody>().settings(list.stream().map(this::createEditBody).collect(Collectors.toList()))
94                          .total(pager.getAllRecordCount())
95                          .status(ApiResult.Status.OK)
96                          .result());
97      }
98  
99      /**
100      * Retrieves a specific request header setting by ID.
101      *
102      * @param id the ID of the request header setting to retrieve
103      * @return JSON response containing the request header setting
104      */
105     // GET /api/admin/reqheader/setting/{id}
106     @Execute
107     public JsonResponse<ApiResult> get$setting(final String id) {
108         return asJson(new ApiConfigResponse().setting(reqHeaderService.getRequestHeader(id).map(this::createEditBody).orElseGet(() -> {
109             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
110             return null;
111         })).status(Status.OK).result());
112     }
113 
114     /**
115      * Creates a new request header setting.
116      *
117      * @param body the request header data to create
118      * @return JSON response containing the created request header setting ID
119      */
120     // POST /api/admin/reqheader/setting
121     @Execute
122     public JsonResponse<ApiResult> post$setting(final CreateBody body) {
123         validateApi(body, messages -> {});
124         if (!isValidWebConfigId(body.webConfigId)) {
125             return asJson(new ApiErrorResponse().message("invalid webConfigId").status(Status.BAD_REQUEST).result());
126         }
127 
128         body.crudMode = CrudMode.CREATE;
129         final RequestHeader reqHeader = getRequestHeader(body).map(entity -> {
130             try {
131                 reqHeaderService.store(entity);
132             } catch (final Exception e) {
133                 logger.warn("Failed to process a request.", e);
134                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateCrudTable(GLOBAL, buildThrowableMessage(e)));
135             }
136             return entity;
137         }).orElseGet(() -> {
138             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL));
139             return null;
140         });
141 
142         return asJson(new ApiUpdateResponse().id(reqHeader.getId()).created(true).status(Status.OK).result());
143     }
144 
145     /**
146      * Updates an existing request header setting.
147      *
148      * @param body the request header data to update
149      * @return JSON response containing the updated request header setting ID
150      */
151     // PUT /api/admin/reqheader/setting
152     @Execute
153     public JsonResponse<ApiResult> put$setting(final EditBody body) {
154         validateApi(body, messages -> {});
155         body.crudMode = CrudMode.EDIT;
156         final RequestHeader reqHeader = getRequestHeader(body).map(entity -> {
157             try {
158                 reqHeaderService.store(entity);
159             } catch (final Exception e) {
160                 logger.warn("Failed to process a request.", e);
161                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToUpdateCrudTable(GLOBAL, buildThrowableMessage(e)));
162             }
163             return entity;
164         }).orElseGet(() -> {
165             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, body.id));
166             return null;
167         });
168         return asJson(new ApiUpdateResponse().id(reqHeader.getId()).created(false).status(Status.OK).result());
169     }
170 
171     /**
172      * Deletes a request header setting by ID.
173      *
174      * @param id the ID of the request header setting to delete
175      * @return JSON response indicating success or failure
176      */
177     // DELETE /api/admin/reqheader/setting/{id}
178     @Execute
179     public JsonResponse<ApiResult> delete$setting(final String id) {
180         reqHeaderService.getRequestHeader(id).ifPresent(entity -> {
181             try {
182                 reqHeaderService.delete(entity);
183                 saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
184             } catch (final Exception e) {
185                 logger.warn("Failed to process a request.", e);
186                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToDeleteCrudTable(GLOBAL, buildThrowableMessage(e)));
187             }
188         }).orElse(() -> {
189             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
190         });
191         return asJson(new ApiResponse().status(Status.OK).result());
192     }
193 
194     /**
195      * Creates an EditBody from a RequestHeader entity.
196      *
197      * @param entity the request header entity to convert
198      * @return the converted EditBody
199      */
200     protected EditBody createEditBody(final RequestHeader entity) {
201         final EditBody body = new EditBody();
202         copyBeanToBean(entity, body, copyOp -> {
203             copyOp.excludeNull();
204         });
205         return body;
206     }
207 
208     /**
209      * Validates if the given web configuration ID exists.
210      *
211      * @param webconfigId the web configuration ID to validate
212      * @return true if the web configuration exists, false otherwise
213      */
214     protected Boolean isValidWebConfigId(final String webconfigId) {
215         return webConfigService.getWebConfig(webconfigId).isPresent();
216     }
217 }