content: package org.pmiops.workbench.interceptors;
  
  import io.swagger.v3.oas.annotations.Operation;
  import java.lang.reflect.Method;
  import java.util.regex.Pattern;
  import org.springframework.web.method.HandlerMethod;
  
  public class InterceptorUtils {
    private static final String CLOUD_TASK_TAG = "cloudTask";
    private static final Pattern API_CONTROLLER_PATTERN =
        Pattern.compile("(.*\\.[^.]+)Api(Controller)");
  
    private InterceptorUtils() {}
  
    public static Method getControllerMethod(HandlerMethod handlerMethod) {
      String apiControllerName = handlerMethod.getBeanType().getName();
      String handlerMethodName = handlerMethod.getMethod().getName();
      Class<?>[] handlerParameterTypes = handlerMethod.getMethod().getParameterTypes();
  
      // The matcher assumes that all Controllers are within the same package as the generated
      // ApiController (api package)
      // There's no concise way to find out what class implements the delegate interface, so instead
      // depend on naming conventions. This removes "Api" from the class name when the classname
      // includes the word Controller.
      final String controllerName =
          API_CONTROLLER_PATTERN.matcher(apiControllerName).replaceAll("$1$2");
  
      Class<?> controllerClass;
      try {
        controllerClass = Class.forName(controllerName);
      } catch (ClassNotFoundException e) {
        throw new RuntimeException(
            "Missing " + controllerName + " by name derived from " + apiControllerName + ".", e);
      }
  
      try {
        return controllerClass.getMethod(handlerMethodName, handlerParameterTypes);
      } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
      }
    }
  
    /**
     * Returns true when this endpoint is categorized as Cloud Task in Swagger.
     *
     * <p>For cloud task endpoint has cloudTask tag generated by swagger.
     */
    public static boolean isCloudTaskRequest(Operation apiOp) {
      for (String tag : apiOp.tags()) {
        if (CLOUD_TASK_TAG.equals(tag)) {
          return true;
        }
      }
      return false;
    }
  }
  