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.crawlinginfo;
17  
18  import java.util.List;
19  import java.util.stream.Collectors;
20  
21  import org.apache.logging.log4j.LogManager;
22  import org.apache.logging.log4j.Logger;
23  import org.codelibs.fess.app.pager.CrawlingInfoPager;
24  import org.codelibs.fess.app.service.CrawlingInfoService;
25  import org.codelibs.fess.app.web.api.ApiResult;
26  import org.codelibs.fess.app.web.api.ApiResult.ApiLogResponse;
27  import org.codelibs.fess.app.web.api.ApiResult.ApiResponse;
28  import org.codelibs.fess.app.web.api.ApiResult.Status;
29  import org.codelibs.fess.app.web.api.admin.FessApiAdminAction;
30  import org.codelibs.fess.helper.ProcessHelper;
31  import org.codelibs.fess.opensearch.config.exentity.CrawlingInfo;
32  import org.lastaflute.web.Execute;
33  import org.lastaflute.web.response.JsonResponse;
34  
35  import jakarta.annotation.Resource;
36  
37  /**
38   * API action for admin crawling info.
39   *
40   */
41  public class ApiAdminCrawlinginfoAction extends FessApiAdminAction {
42  
43      /**
44       * Default constructor.
45       */
46      public ApiAdminCrawlinginfoAction() {
47          super();
48      }
49  
50      private static final Logger logger = LogManager.getLogger(ApiAdminCrawlinginfoAction.class);
51  
52      // ===================================================================================
53      //                                                                           Attribute
54      //                                                                           =========
55      @Resource
56      private CrawlingInfoService crawlingInfoService;
57  
58      /** Helper for managing crawling processes and session information */
59      @Resource
60      protected ProcessHelper processHelper;
61  
62      // ===================================================================================
63      //                                                                      Search Execute
64      //                                                                      ==============
65  
66      /**
67       * Retrieves crawling info logs with pagination support.
68       *
69       * @param body the search body containing pagination and filter parameters
70       * @return JSON response containing list of crawling info logs
71       */
72      // GET /api/admin/crawlinginfo/logs
73      // PUT /api/admin/crawlinginfo/logs
74      @Execute
75      public JsonResponse<ApiResult> logs(final SearchBody body) {
76          validateApi(body, messages -> {});
77          final CrawlingInfoPager pager = copyBeanToNewBean(body, CrawlingInfoPager.class);
78          final List<CrawlingInfo> list = crawlingInfoService.getCrawlingInfoList(pager);
79          return asJson(new ApiResult.ApiLogsResponse<EditBody>().logs(list.stream().map(this::createEditBody).collect(Collectors.toList()))
80                  .total(pager.getAllRecordCount())
81                  .status(ApiResult.Status.OK)
82                  .result());
83      }
84  
85      /**
86       * Retrieves a specific crawling info log by ID.
87       *
88       * @param id the ID of the crawling info log to retrieve
89       * @return JSON response containing the crawling info log data
90       */
91      // GET /api/admin/crawlinginfo/log/{id}
92      @Execute
93      public JsonResponse<ApiResult> get$log(final String id) {
94          return asJson(new ApiLogResponse().log(crawlingInfoService.getCrawlingInfo(id).map(this::createEditBody).orElseGet(() -> {
95              throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
96              return null;
97          })).status(Status.OK).result());
98      }
99  
100     /**
101      * Deletes a specific crawling info log by ID.
102      *
103      * @param id the ID of the crawling info log to delete
104      * @return JSON response indicating the deletion status
105      */
106     // DELETE /api/admin/crawlinginfo/log/{id}
107     @Execute
108     public JsonResponse<ApiResult> delete$log(final String id) {
109         crawlingInfoService.getCrawlingInfo(id).ifPresent(entity -> {
110             try {
111                 crawlingInfoService.delete(entity);
112                 saveInfo(messages -> messages.addSuccessCrudDeleteCrudTable(GLOBAL));
113             } catch (final Exception e) {
114                 logger.warn("Failed to process a request.", e);
115                 throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToDeleteCrudTable(GLOBAL, buildThrowableMessage(e)));
116             }
117         }).orElse(() -> {
118             throwValidationErrorApi(messages -> messages.addErrorsCrudCouldNotFindCrudTable(GLOBAL, id));
119         });
120         return asJson(new ApiResponse().status(Status.OK).result());
121     }
122 
123     /**
124      * Deletes all old crawling info sessions except currently running ones.
125      *
126      * @return JSON response indicating the deletion status
127      */
128     // DELETE /api/admin/crawlinginfo/all
129     @Execute
130     public JsonResponse<ApiResult> delete$all() {
131         try {
132             crawlingInfoService.deleteOldSessions(processHelper.getRunningSessionIdSet());
133             saveInfo(messages -> messages.addSuccessCrawlingInfoDeleteAll(GLOBAL));
134         } catch (final Exception e) {
135             logger.warn("Failed to process a request.", e);
136             throwValidationErrorApi(messages -> messages.addErrorsCrudFailedToDeleteCrudTable(GLOBAL, buildThrowableMessage(e)));
137         }
138         return asJson(new ApiResponse().status(Status.OK).result());
139     }
140 
141     /**
142      * Creates an EditBody from a CrawlingInfo entity for API responses.
143      *
144      * @param entity the CrawlingInfo entity to convert
145      * @return the converted EditBody object
146      */
147     protected EditBody createEditBody(final CrawlingInfo entity) {
148         final EditBody body = new EditBody();
149         copyBeanToBean(entity, body, copyOp -> {
150             copyOp.excludeNull();
151         });
152         return body;
153     }
154 }