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