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.dict.synonym;
17  
18  import static org.codelibs.fess.app.web.admin.dict.synonym.AdminDictSynonymAction.createSynonymItem;
19  
20  import java.io.File;
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.util.stream.Collectors;
24  
25  import org.apache.logging.log4j.LogManager;
26  import org.apache.logging.log4j.Logger;
27  import org.codelibs.fess.app.pager.SynonymPager;
28  import org.codelibs.fess.app.service.SynonymService;
29  import org.codelibs.fess.app.web.CrudMode;
30  import org.codelibs.fess.app.web.admin.dict.synonym.UploadForm;
31  import org.codelibs.fess.app.web.api.ApiResult;
32  import org.codelibs.fess.app.web.api.admin.FessApiAdminAction;
33  import org.codelibs.fess.dict.synonym.SynonymFile;
34  import org.codelibs.fess.dict.synonym.SynonymItem;
35  import org.lastaflute.web.Execute;
36  import org.lastaflute.web.response.JsonResponse;
37  import org.lastaflute.web.response.StreamResponse;
38  
39  import jakarta.annotation.Resource;
40  
41  /**
42   * API action for admin Synonym dictionary management.
43   * Provides REST endpoints for managing synonym dictionary items in the Fess search engine.
44   */
45  public class ApiAdminDictSynonymAction extends FessApiAdminAction {
46  
47      /**
48       * Default constructor.
49       */
50      public ApiAdminDictSynonymAction() {
51          super();
52      }
53  
54      private static final Logger logger = LogManager.getLogger(ApiAdminDictSynonymAction.class);
55  
56      @Resource
57      private SynonymService synonymService;
58  
59      /**
60       * Retrieves synonym dictionary settings with pagination support.
61       *
62       * @param dictId the dictionary ID
63       * @param body the search body containing pagination and filter parameters
64       * @return JSON response containing list of synonym dictionary items
65       */
66      // GET /api/admin/dict/synonym/settings/{dictId}
67      @Execute
68      public JsonResponse<ApiResult> get$settings(final String dictId, final SearchBody body) {
69          body.dictId = dictId;
70          validateApi(body, messages -> {});
71          final SynonymPager pager = copyBeanToNewBean(body, SynonymPager.class);
72          return asJson(new ApiResult.ApiConfigsResponse<EditBody>().settings(synonymService.getSynonymList(body.dictId, pager)
73                  .stream()
74                  .map(protwordsItem -> createEditBody(protwordsItem, dictId))
75                  .collect(Collectors.toList())).status(ApiResult.Status.OK).result());
76      }
77  
78      /**
79       * Retrieves a specific synonym dictionary item by ID.
80       *
81       * @param dictId the dictionary ID
82       * @param id the ID of the synonym item to retrieve
83       * @return JSON response containing the synonym dictionary item
84       */
85      // GET /api/admin/dict/synonym/setting/{dictId}/{id}
86      @Execute
87      public JsonResponse<ApiResult> get$setting(final String dictId, final long id) {
88          return asJson(new ApiResult.ApiConfigResponse()
89                  .setting(synonymService.getSynonymItem(dictId, id).map(entity -> createEditBody(entity, dictId)).orElseGet(() -> {
90                      throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, String.valueOf(id)));
91                      return null;
92                  }))
93                  .status(ApiResult.Status.OK)
94                  .result());
95      }
96  
97      /**
98       * Creates a new synonym dictionary item.
99       *
100      * @param dictId the dictionary ID
101      * @param body the request body containing synonym item information
102      * @return JSON response with result status
103      */
104     // POST /api/admin/dict/synonym/setting/{dictId}
105     @Execute
106     public JsonResponse<ApiResult> post$setting(final String dictId, final CreateBody body) {
107         body.dictId = dictId;
108         validateApi(body, messages -> {});
109         body.crudMode = CrudMode.CREATE;
110         final SynonymItem entity = createSynonymItem(this, body, () -> {
111             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL));
112             return null;
113         }).orElseGet(() -> {
114             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL));
115             return null;
116         });
117         synonymService.store(body.dictId, entity);
118         return asJson(
119                 new ApiResult.ApiUpdateResponse().id(String.valueOf(entity.getId())).created(true).status(ApiResult.Status.OK).result());
120     }
121 
122     /**
123      * Updates an existing synonym dictionary item.
124      *
125      * @param dictId the dictionary ID
126      * @param body the request body containing updated synonym item information
127      * @return JSON response with result status
128      */
129     // PUT /api/admin/dict/synonym/setting/{dictId}
130     @Execute
131     public JsonResponse<ApiResult> put$setting(final String dictId, final EditBody body) {
132         body.dictId = dictId;
133         validateApi(body, messages -> {});
134         body.crudMode = CrudMode.EDIT;
135         final SynonymItem entity = createSynonymItem(this, body, () -> {
136             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToUpdateCrudTable(GLOBAL, String.valueOf(body.id)));
137             return null;
138         }).orElseGet(() -> {
139             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, String.valueOf(body.id)));
140             return null;
141         });
142         synonymService.store(body.dictId, entity);
143         return asJson(
144                 new ApiResult.ApiUpdateResponse().id(String.valueOf(entity.getId())).created(false).status(ApiResult.Status.OK).result());
145     }
146 
147     /**
148      * Deletes a synonym dictionary item by ID.
149      *
150      * @param dictId the dictionary ID
151      * @param id the ID of the synonym item to delete
152      * @return JSON response indicating the deletion status
153      */
154     // DELETE /api/admin/dict/synonym/setting/{dictId}/{id}
155     @Execute
156     public JsonResponse<ApiResult> delete$setting(final String dictId, final long id) {
157         synonymService.getSynonymItem(dictId, id).ifPresent(entity -> {
158             synonymService.delete(dictId, entity);
159             saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
160         }).orElse(() -> {
161             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, String.valueOf(id)));
162         });
163         return asJson(new ApiResult.ApiUpdateResponse().id(String.valueOf(id)).created(false).status(ApiResult.Status.OK).result());
164     }
165 
166     /**
167      * Uploads synonym dictionary file.
168      *
169      * @param dictId the dictionary ID
170      * @param form the upload form containing the dictionary file
171      * @return JSON response with result status
172      */
173     // PUT /api/admin/dict/synonym/upload/{dictId}
174     @Execute
175     public JsonResponse<ApiResult> put$upload(final String dictId, final UploadForm form) {
176         form.dictId = dictId;
177         validateApi(form, messages -> {});
178         final SynonymFile file = synonymService.getSynonymFile(form.dictId).orElseGet(() -> {
179             throwValidationErrorApi(messages -> messages.addErrorsFailedToUploadProtwordsFile(GLOBAL));
180             return null;
181         });
182         try (InputStream inputStream = form.synonymFile.getInputStream()) {
183             file.update(inputStream);
184         } catch (final IOException e) {
185             logger.warn("Failed to process a request.", e);
186             throwValidationErrorApi(messages -> messages.addErrorsFailedToUploadProtwordsFile(GLOBAL));
187         }
188         return asJson(new ApiResult.ApiResponse().status(ApiResult.Status.OK).result());
189     }
190 
191     /**
192      * Downloads synonym dictionary file.
193      *
194      * @param dictId the dictionary ID
195      * @param body the download request body
196      * @return stream response containing the dictionary file data
197      */
198     // GET /api/admin/dict/synonym/download/{dictId}
199     @Execute
200     public StreamResponse get$download(final String dictId, final DownloadBody body) {
201         body.dictId = dictId;
202         validateApi(body, messages -> {});
203         return synonymService.getSynonymFile(body.dictId)
204                 .map(file -> asStream(new File(file.getPath()).getName()).contentTypeOctetStream().stream(out -> {
205                     file.writeOut(out);
206                 }))
207                 .orElseGet(() -> {
208                     throwValidationErrorApi(messages -> messages.addErrorsFailedToDownloadProtwordsFile(GLOBAL));
209                     return null;
210                 });
211     }
212 
213     /**
214      * Creates an EditBody from a SynonymItem entity for API responses.
215      *
216      * @param entity the SynonymItem entity to convert
217      * @param dictId the dictionary ID
218      * @return the converted EditBody object
219      */
220     protected EditBody createEditBody(final SynonymItem entity, final String dictId) {
221         final EditBody body = new EditBody();
222         body.id = entity.getId();
223         body.dictId = dictId;
224         body.inputs = entity.getInputsValue();
225         body.outputs = entity.getOutputsValue();
226         return body;
227     }
228 }