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.kuromoji;
17  
18  import static org.codelibs.fess.app.web.admin.dict.kuromoji.AdminDictKuromojiAction.createKuromojiItem;
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.KuromojiPager;
28  import org.codelibs.fess.app.service.KuromojiService;
29  import org.codelibs.fess.app.web.CrudMode;
30  import org.codelibs.fess.app.web.admin.dict.kuromoji.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.kuromoji.KuromojiFile;
34  import org.codelibs.fess.dict.kuromoji.KuromojiItem;
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 Kuromoji dictionary management.
43   * Provides REST endpoints for managing Kuromoji dictionary items in the Fess search engine.
44   */
45  public class ApiAdminDictKuromojiAction extends FessApiAdminAction {
46  
47      /**
48       * Default constructor.
49       */
50      public ApiAdminDictKuromojiAction() {
51          super();
52      }
53  
54      private static final Logger logger = LogManager.getLogger(ApiAdminDictKuromojiAction.class);
55  
56      @Resource
57      private KuromojiService kuromojiService;
58  
59      /**
60       * Retrieves Kuromoji 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 Kuromoji dictionary items
65       */
66      // GET /api/admin/dict/kuromoji/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 KuromojiPager pager = copyBeanToNewBean(body, KuromojiPager.class);
72          return asJson(new ApiResult.ApiConfigsResponse<EditBody>().settings(kuromojiService.getKuromojiList(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 Kuromoji dictionary item by ID.
80       *
81       * @param dictId the dictionary ID
82       * @param id the ID of the Kuromoji item to retrieve
83       * @return JSON response containing the Kuromoji dictionary item
84       */
85      // GET /api/admin/dict/kuromoji/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(kuromojiService.getKuromojiItem(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 Kuromoji dictionary item.
99       *
100      * @param dictId the dictionary ID
101      * @param body the request body containing Kuromoji item information
102      * @return JSON response with result status
103      */
104     // POST /api/admin/dict/kuromoji/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 KuromojiItem entity = createKuromojiItem(this, body, () -> {
111             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL));
112             return null;
113         }).orElseGet(() -> {
114             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToCreateInstance(GLOBAL));
115             return null;
116         });
117         kuromojiService.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 Kuromoji dictionary item.
124      *
125      * @param dictId the dictionary ID
126      * @param body the request body containing updated Kuromoji item information
127      * @return JSON response with result status
128      */
129     // PUT /api/admin/dict/kuromoji/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 KuromojiItem entity = createKuromojiItem(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         kuromojiService.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 Kuromoji dictionary item by ID.
149      *
150      * @param dictId the dictionary ID
151      * @param id the ID of the Kuromoji item to delete
152      * @return JSON response indicating the deletion status
153      */
154     // DELETE /api/admin/dict/kuromoji/setting/{dictId}/{id}
155     @Execute
156     public JsonResponse<ApiResult> delete$setting(final String dictId, final long id) {
157         kuromojiService.getKuromojiItem(dictId, id).ifPresent(entity -> {
158             kuromojiService.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 Kuromoji 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/kuromoji/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 KuromojiFile file = kuromojiService.getKuromojiFile(form.dictId).orElseGet(() -> {
179             throwValidationErrorApi(messages -> messages.addErrorsFailedToUploadProtwordsFile(GLOBAL));
180             return null;
181         });
182         try (InputStream inputStream = form.kuromojiFile.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 Kuromoji 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/kuromoji/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 kuromojiService.getKuromojiFile(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 KuromojiItem entity for API responses.
215      *
216      * @param entity the KuromojiItem entity to convert
217      * @param dictId the dictionary ID
218      * @return the converted EditBody object
219      */
220     protected EditBody createEditBody(final KuromojiItem entity, final String dictId) {
221         final EditBody body = new EditBody();
222         body.id = entity.getId();
223         body.dictId = dictId;
224         body.token = entity.getToken();
225         body.reading = entity.getReading();
226         body.pos = entity.getPos();
227         body.segmentation = entity.getSegmentation();
228         return body;
229     }
230 }