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.keymatch;
17  
18  import static org.codelibs.fess.app.web.admin.keymatch.AdminKeymatchAction.getKeyMatch;
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.KeyMatchPager;
26  import org.codelibs.fess.app.service.KeyMatchService;
27  import org.codelibs.fess.app.web.CrudMode;
28  import org.codelibs.fess.app.web.api.ApiResult;
29  import org.codelibs.fess.app.web.api.ApiResult.ApiConfigResponse;
30  import org.codelibs.fess.app.web.api.ApiResult.ApiResponse;
31  import org.codelibs.fess.app.web.api.ApiResult.ApiUpdateResponse;
32  import org.codelibs.fess.app.web.api.ApiResult.Status;
33  import org.codelibs.fess.app.web.api.admin.FessApiAdminAction;
34  import org.codelibs.fess.opensearch.config.exentity.KeyMatch;
35  import org.lastaflute.web.Execute;
36  import org.lastaflute.web.response.JsonResponse;
37  
38  import jakarta.annotation.Resource;
39  
40  /**
41   * API action for admin key match management.
42   *
43   */
44  public class ApiAdminKeymatchAction extends FessApiAdminAction {
45  
46      /** The logger for this class. */
47      private static final Logger logger = LogManager.getLogger(ApiAdminKeymatchAction.class);
48  
49      // ===================================================================================
50      //                                                                         Constructor
51      //                                                                         ===========
52      /**
53       * Default constructor.
54       */
55      public ApiAdminKeymatchAction() {
56          super();
57      }
58  
59      // ===================================================================================
60      //                                                                           Attribute
61      //                                                                           =========
62      /** The key match service for managing key match settings. */
63      @Resource
64      private KeyMatchService keyMatchService;
65  
66      // ===================================================================================
67      //                                                                      Search Execute
68      //                                                                      ==============
69  
70      /**
71       * Retrieves key match settings with pagination.
72       *
73       * @param body the search parameters for filtering and pagination
74       * @return JSON response containing key match settings list
75       */
76      // GET /api/admin/keymatch/settings
77      // PUT /api/admin/keymatch/settings
78      @Execute
79      public JsonResponse<ApiResult> settings(final SearchBody body) {
80          validateApi(body, messages -> {});
81          final KeyMatchPager pager = copyBeanToNewBean(body, KeyMatchPager.class);
82          final List<KeyMatch> list = keyMatchService.getKeyMatchList(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 key match setting by ID.
92       *
93       * @param id the ID of the key match setting to retrieve
94       * @return JSON response containing the key match setting
95       */
96      // GET /api/admin/keymatch/setting/{id}
97      @Execute
98      public JsonResponse<ApiResult> get$setting(final String id) {
99          return asJson(new ApiConfigResponse().setting(keyMatchService.getKeyMatch(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 key match setting.
107      *
108      * @param body the key match data to create
109      * @return JSON response containing the created key match setting ID
110      */
111     // POST /api/admin/keymatch/setting
112     @Execute
113     public JsonResponse<ApiResult> post$setting(final CreateBody body) {
114         validateApi(body, messages -> {});
115         body.crudMode = CrudMode.CREATE;
116         final KeyMatch keyMatch = getKeyMatch(body).map(entity -> {
117             try {
118                 keyMatchService.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(keyMatch.getId()).created(true).status(Status.OK).result());
130     }
131 
132     /**
133      * Updates an existing key match setting.
134      *
135      * @param body the key match data to update
136      * @return JSON response containing the updated key match setting ID
137      */
138     // PUT /api/admin/keymatch/setting
139     @Execute
140     public JsonResponse<ApiResult> put$setting(final EditBody body) {
141         validateApi(body, messages -> {});
142         body.crudMode = CrudMode.EDIT;
143         final KeyMatch keyMatch = getKeyMatch(body).map(entity -> {
144             try {
145                 keyMatchService.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(keyMatch.getId()).created(false).status(Status.OK).result());
156     }
157 
158     /**
159      * Deletes a key match setting by ID.
160      *
161      * @param id the ID of the key match setting to delete
162      * @return JSON response indicating success or failure
163      */
164     // DELETE /api/admin/keymatch/setting/{id}
165     @Execute
166     public JsonResponse<ApiResult> delete$setting(final String id) {
167         keyMatchService.getKeyMatch(id).ifPresent(entity -> {
168             try {
169                 keyMatchService.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 KeyMatch entity.
183      *
184      * @param entity the key match entity to convert
185      * @return the converted EditBody
186      */
187     protected EditBody createEditBody(final KeyMatch entity) {
188         final EditBody body = new EditBody();
189         copyBeanToBean(entity, body, copyOp -> {
190             copyOp.excludeNull();
191         });
192         return body;
193     }
194 }