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.mylasta.direction.sponsor;
17  
18  import java.io.IOException;
19  import java.io.PrintWriter;
20  import java.io.StringWriter;
21  import java.util.UUID;
22  import java.util.function.Supplier;
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.core.lang.StringUtil;
28  import org.codelibs.fess.Constants;
29  import org.codelibs.fess.app.web.api.ApiResult;
30  import org.codelibs.fess.app.web.api.ApiResult.ApiErrorResponse;
31  import org.codelibs.fess.app.web.api.ApiResult.Status;
32  import org.codelibs.fess.util.ComponentUtil;
33  import org.dbflute.optional.OptionalThing;
34  import org.lastaflute.web.api.ApiFailureHook;
35  import org.lastaflute.web.api.ApiFailureResource;
36  import org.lastaflute.web.login.exception.LoginUnauthorizedException;
37  import org.lastaflute.web.response.ApiResponse;
38  import org.lastaflute.web.response.JsonResponse;
39  
40  /**
41   * The hook for API failure.
42   *
43   * @author jflute
44   */
45  public class FessApiFailureHook implements ApiFailureHook { // #change_it for handling API failure
46  
47      private static final Logger logger = LogManager.getLogger(FessApiFailureHook.class);
48  
49      // ===================================================================================
50      //                                                                          Definition
51      //                                                                          ==========
52      protected static final int HTTP_BAD_REQUEST = 400;
53      protected static final int HTTP_UNAUTHORIZED = 401;
54  
55      // ===================================================================================
56      //                                                                    Business Failure
57      //                                                                    ================
58      @Override
59      public ApiResponse handleValidationError(final ApiFailureResource resource) {
60          return asJson(createFailureBean(Status.BAD_REQUEST, createMessage(resource, null))).httpStatus(HTTP_BAD_REQUEST);
61      }
62  
63      @Override
64      public ApiResponse handleApplicationException(final ApiFailureResource resource, final RuntimeException cause) {
65          if (cause instanceof LoginUnauthorizedException) {
66              return asJson(createFailureBean(Status.UNAUTHORIZED, "Unauthorized request.")).httpStatus(HTTP_UNAUTHORIZED);
67          }
68          return asJson(createFailureBean(Status.BAD_REQUEST, createMessage(resource, cause))).httpStatus(HTTP_BAD_REQUEST);
69      }
70  
71      // ===================================================================================
72      //                                                                      System Failure
73      //                                                                      ==============
74      @Override
75      public OptionalThing<ApiResponse> handleClientException(final ApiFailureResource resource, final RuntimeException cause) {
76          return OptionalThing.of(asJson(createFailureBean(Status.BAD_REQUEST, createMessage(resource, cause))));
77      }
78  
79      @Override
80      public OptionalThing<ApiResponse> handleServerException(final ApiFailureResource resource, final Throwable cause) {
81          return OptionalThing.of(asJson(createFailureBean(Status.SYSTEM_ERROR, createMessage(resource, cause))));
82      }
83  
84      // ===================================================================================
85      //                                                                        Assist Logic
86      //                                                                        ============
87      protected JsonResponse<ApiResult> asJson(final ApiResult bean) {
88          return new JsonResponse<>(bean);
89      }
90  
91      protected ApiResult createFailureBean(final Status status, final String message) {
92          return new ApiErrorResponse().message(message).status(status).result();
93      }
94  
95      protected String createMessage(final ApiFailureResource resource, final Throwable cause) {
96          if (!resource.getMessageList().isEmpty()) {
97              return resource.getMessageList().stream().collect(Collectors.joining(" "));
98          }
99  
100         if (cause == null) {
101             return "Unknown error";
102         }
103 
104         final Supplier<String> stacktraceString = () -> {
105             final StringBuilder sb = new StringBuilder();
106             if (StringUtil.isBlank(cause.getMessage())) {
107                 sb.append(cause.getClass().getName());
108             } else {
109                 sb.append(cause.getMessage());
110             }
111             try (final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw)) {
112                 cause.printStackTrace(pw);
113                 pw.flush();
114                 sb.append(" [ ").append(sw.toString()).append(" ]");
115             } catch (final IOException ignore) {}
116             return sb.toString();
117         };
118 
119         if (Constants.TRUE.equalsIgnoreCase(ComponentUtil.getFessConfig().getApiJsonResponseExceptionIncluded())) {
120             return stacktraceString.get();
121         }
122 
123         final String errorCode = UUID.randomUUID().toString();
124         if (logger.isDebugEnabled()) {
125             logger.debug("[{}] {}", errorCode, stacktraceString.get().replace("\n", "\\n"));
126         } else {
127             logger.warn("[{}] {}", errorCode, cause.getMessage());
128         }
129         return "error_code:" + errorCode;
130     }
131 }