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.boostdoc;
17  
18  import static org.codelibs.fess.app.web.admin.boostdoc.AdminBoostdocAction.getBoostDocumentRule;
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.core.beans.util.CopyOptions;
26  import org.codelibs.fess.app.pager.BoostDocPager;
27  import org.codelibs.fess.app.service.BoostDocumentRuleService;
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.ApiConfigsResponse;
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.BoostDocumentRule;
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 boost doc.
44   *
45   */
46  public class ApiAdminBoostdocAction extends FessApiAdminAction {
47  
48      /**
49       * Default constructor.
50       */
51      public ApiAdminBoostdocAction() {
52          super();
53      }
54  
55      private static final Logger logger = LogManager.getLogger(ApiAdminBoostdocAction.class);
56  
57      // ===================================================================================
58      //                                                                           Attribute
59      //                                                                           =========
60      @Resource
61      private BoostDocumentRuleService boostDocumentRuleService;
62  
63      // ===================================================================================
64      //                                                                      Search Execute
65      //                                                                      ==============
66  
67      /**
68       * Retrieves boost document rule settings with pagination support.
69       *
70       * @param body the search body containing pagination and filter parameters
71       * @return JSON response containing list of boost document rule configurations
72       */
73      // GET /api/admin/boostdoc
74      // PUT /api/admin/boostdoc
75      @Execute
76      public JsonResponse<ApiResult> settings(final SearchBody body) {
77          validateApi(body, messages -> {});
78          final BoostDocPager pager = copyBeanToNewBean(body, BoostDocPager.class);
79          final List<BoostDocumentRule> list = boostDocumentRuleService.getBoostDocumentRuleList(pager);
80          return asJson(new ApiConfigsResponse<EditBody>().settings(list.stream().map(this::createEditBody).collect(Collectors.toList()))
81                  .total(pager.getAllRecordCount())
82                  .status(Status.OK)
83                  .result());
84      }
85  
86      /**
87       * Retrieves a specific boost document rule setting by ID.
88       *
89       * @param id the ID of the boost document rule to retrieve
90       * @return JSON response containing the boost document rule configuration
91       */
92      // GET /api/admin/boostdoc/setting/{id}
93      @Execute
94      public JsonResponse<ApiResult> get$setting(final String id) {
95          return asJson(new ApiConfigResponse()
96                  .setting(boostDocumentRuleService.getBoostDocumentRule(id).map(this::createEditBody).orElseGet(() -> {
97                      throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
98                      return null;
99                  }))
100                 .status(Status.OK)
101                 .result());
102     }
103 
104     /**
105      * Creates a new boost document rule setting.
106      *
107      * @param body the request body containing boost document rule information
108      * @return JSON response with result status
109      */
110     // POST /api/admin/boostdoc/setting
111     @Execute
112     public JsonResponse<ApiResult> post$setting(final CreateBody body) {
113         validateApi(body, messages -> {});
114         body.crudMode = CrudMode.CREATE;
115         final BoostDocumentRule boostDoc = getBoostDocumentRule(body).map(entity -> {
116             try {
117                 boostDocumentRuleService.store(entity);
118             } catch (final Exception e) {
119                 logger.warn("Failed to process a request.", e);
120                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateCrudTable(GLOBAL, buildThrowableMessage(e)));
121             }
122             return entity;
123         }).orElseGet(() -> {
124             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL));
125             return null;
126         });
127         return asJson(new ApiUpdateResponse().id(boostDoc.getId()).created(true).status(Status.OK).result());
128     }
129 
130     /**
131      * Updates an existing boost document rule setting.
132      *
133      * @param body the request body containing updated boost document rule information
134      * @return JSON response with result status
135      */
136     // PUT /api/admin/boostdoc/setting
137     @Execute
138     public JsonResponse<ApiResult> put$setting(final EditBody body) {
139         validateApi(body, messages -> {});
140         body.crudMode = CrudMode.EDIT;
141         final BoostDocumentRule boostDoc = getBoostDocumentRule(body).map(entity -> {
142             try {
143                 boostDocumentRuleService.store(entity);
144             } catch (final Exception e) {
145                 logger.warn("Failed to process a request.", e);
146                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToUpdateCrudTable(GLOBAL, buildThrowableMessage(e)));
147             }
148             return entity;
149         }).orElseGet(() -> {
150             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, body.id));
151             return null;
152         });
153         return asJson(new ApiUpdateResponse().id(boostDoc.getId()).created(false).status(Status.OK).result());
154     }
155 
156     /**
157      * Deletes a boost document rule setting by ID.
158      *
159      * @param id the ID of the boost document rule to delete
160      * @return JSON response indicating the deletion status
161      */
162     // DELETE /api/admin/boostdoc/setting/{id}
163     @Execute
164     public JsonResponse<ApiResult> delete$setting(final String id) {
165         boostDocumentRuleService.getBoostDocumentRule(id).ifPresent(entity -> {
166             try {
167                 boostDocumentRuleService.delete(entity);
168                 saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
169             } catch (final Exception e) {
170                 logger.warn("Failed to process a request.", e);
171                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToDeleteCrudTable(GLOBAL, buildThrowableMessage(e)));
172             }
173         }).orElse(() -> {
174             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
175         });
176         return asJson(new ApiResponse().status(Status.OK).result());
177     }
178 
179     /**
180      * Creates an EditBody from a BoostDocumentRule entity for API responses.
181      *
182      * @param entity the BoostDocumentRule entity to convert
183      * @return the converted EditBody object
184      */
185     protected EditBody createEditBody(final BoostDocumentRule entity) {
186         final EditBody form = new EditBody();
187         copyBeanToBean(entity, form, CopyOptions::excludeNull);
188         form.crudMode = null;
189         return form;
190     }
191 }