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