content: package com.android.certification.niap.permission.dpctester.common;
  /*
   * Copyright (C) 2024 The Android Open Source Project
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  import android.util.Log;
  
  import com.android.certification.niap.permission.dpctester.test.exception.BypassTestException;
  
  import java.lang.reflect.InvocationTargetException;
  import java.lang.reflect.Method;
  import java.util.Arrays;
  
  /**
   * Common utility functions for reflection. These are intended to be used to test APIs before they
   * are added to the SDK. There should be not uses of this class checked in to the repository.
   */
  public final class ReflectionUtil {
  
      private static final String TAG = ReflectionUtil.class.getSimpleName();
  
      /**
       * Calls a method on an object with the given arguments. This can be used when the method is not
       * in the SDK. If any arguments are {@code null} or primitive types you must use {@link
       * #invoke(Object, String, Class[], Object...)} to avoid {@link NullPointerException}s and
       * autoboxing respectively.
       *
       * <p>ReflectionUtil.invoke(dpm, "clearDeviceOwnerApp", "com.example.deviceowner");
       *
       * @param obj The object to call the method on.
       * @param methodName The name of the method.
       * @param args The arguments to pass to the method. Ensure they are of the same type as the method
       *     parameters. If they are not, use the more verbose {@link #invoke(Object, String, Class[],
       *     Object[])}.
       * @return The result of the invocation. {@code null} if {@code void}.
       */
      public static <T> T invoke(Object obj, String methodName, Object... args)
              throws ReflectionIsTemporaryException {
          return invoke(obj.getClass(), obj, methodName, args);
      }
  
      /** Same as {@link #invoke(Object, String, Object...)} but for static methods. */
      public static <T> T invoke(Class<?> clazz, String methodName, Object... args)
              throws ReflectionIsTemporaryException {
          return invoke(clazz, null, methodName, args);
      }
  
      /**
       * Calls a method on an object with the given arguments. This can be used when the method is not
       * in the SDK. Consider using {@link #invoke(Object, String, Object...)} for less verbosity if the
       * arguments are the same type as the method parameters (subclasses don't work).
       *
       * <p>ReflectionUtil.invoke(dpm, "wipeData", new Class<?>[] {int.class},
       * ReflectionUtil.intConstant(DevicePolicyManager.class, "WIPE_EXTERNAL_STORAGE"));
       *
       * @param obj The object to call the method on.
       * @param methodName The name of the method.
       * @param parameterTypes The method parameter types.
       * @param args The arguments to pass to the method.
       * @return The result of the invocation. {@code null} if {@code void}.
       */
      public static <T> T invoke(
              Object obj, String methodName, Class<?>[] parameterTypes, Object... args)
              throws ReflectionIsTemporaryException {
          return invoke(obj.getClass(), obj, methodName, parameterTypes, args);
      }
  
      /** Same as {@link #invoke(Object, String, Class[], Object...)} but for static methods. */
      public static <T> T invoke(
              Class<?> clazz, String methodName, Class<?>[] parameterTypes, Object... args)
              throws ReflectionIsTemporaryException {
          return invoke(clazz, null, methodName, parameterTypes, args);
      }
  
      /** Resolve the parameter types and invoke the method. */
      private static <T> T invoke(Class<?> clazz, Object obj, String methodName, Object... args)
              throws ReflectionIsTemporaryException {
          Class<?> parameterTypes[] = new Class<?>[args.length];
          for (int i = 0; i < args.length; ++i) {
              parameterTypes[i] = args[i].getClass();
          }
          return invoke(clazz, obj, methodName, parameterTypes, args);
      }
  
      /** Resolve the method and invoke it. */
      private static <T> T invoke(
              Class<?> clazz, Object obj, String methodName, Class<?>[] parameterTypes, Object... args)
              throws ReflectionIsTemporaryException {
          try {
              Method method = clazz.getDeclaredMethod(methodName, parameterTypes);
              method.setAccessible(true);
              T result = (T) method.invoke(obj, args);
              return result;
          } catch (SecurityException
                   | BypassTestException
                   | NoSuchMethodException
                   | IllegalArgumentException
                   | IllegalAccessException
                   | InvocationTargetException e) {
  
              Log.w(TAG, "Reflection failed.:"+e.getCause().getMessage(), e);
              //e.printStackTrace();
              throw new ReflectionIsTemporaryException(
                      "Failed to invoke " + methodName+":"+e+":"+e.getMessage(), e);
              //ReflectionIsTemporaryException.rethrow(e, clazz, methodName, args);
              //return null;
          }
      }
  
      /**
       * Gets the value of a static int constant. This can be used when the constant is not yet in the
       * SDK.
       *
       * <p>ReflectionUtil.intConstant(DevicePolicyManager.class, "WIPE_EXTERNAL_STORAGE");
       *
       * @param clazz The class that contains the constant.
       * @param fieldName The name of the constant field.
       * @return The value of the constant.
       */
      public static int intConstant(Class<?> clazz, String fieldName)
              throws ReflectionIsTemporaryException {
          try {
              return clazz.getField(fieldName).getInt(null);
          } catch (NoSuchFieldException | IllegalAccessException e) {
              throw new ReflectionIsTemporaryException("Failed to retrieve constant", e);
          }
      }
  
      /**
       * Gets the value of a static string constant. This can be used when the constant is not yet in
       * the SDK.
       *
       * <p>ReflectionUtil.stringConstant(DevicePolicyManager.class, "ACTION_ADD_DEVICE_ADMIN");
       *
       * @param clazz The class that contains the constant.
       * @param fieldName The name of the constant field.
       * @return The value of the constant.
       */
      public static String stringConstant(Class<?> clazz, String fieldName)
              throws ReflectionIsTemporaryException {
          try {
              return (String) clazz.getField(fieldName).get(null);
          } catch (NoSuchFieldException | IllegalAccessException e) {
              throw new ReflectionIsTemporaryException("Failed to retrieve constant", e);
          }
      }
  
      /**
       * Gets the value of the given property.
       */
      public static String getSystemProperty(String name) {
          try {
              return (String) invoke(Class.forName("android.os.SystemProperties"), "get",
                      new Class<?>[] { String.class }, name);
          } catch (Exception e) {
              throw new IllegalStateException("Could not read system property " + name, e);
          }
      }
  
      /**
       * Thrown when the temporary use of reflection fails to find and use a new API.
       *
       * <p>This will happen when the API is not yet available in the SDK and TestDPC is running on
       * device that isn't running the latest version of the framework and therefore doesn't support the
       * API.
       *
       * <p>To handle this, gracefully fail the operation in progress.
       */
      public static final class ReflectionIsTemporaryException extends RuntimeException {
  
          private static final long serialVersionUID = 1L;
  
          private ReflectionIsTemporaryException(String message, Throwable cause) {
              super(message, cause);
          }
  
          public static void rethrow(Exception e, Class<?> clazz, String methodName, Object... args)
                  throws ReflectionIsTemporaryException {
              String method =
                      clazz.getSimpleName()
                              + "."
                              + methodName
                              + "("
                              + (args == null || args.length == 0 ? "" : Arrays.toString(args))
                              + ")";
              Log.w(TAG, "Exception calling method " + method + ":", e);
              if (e instanceof InvocationTargetException) {
                  Throwable cause = e.getCause();
                  if(cause instanceof SecurityException){
                      throw (SecurityException) cause;
                  }
  
                  if (cause instanceof RuntimeException) {
                      throw (RuntimeException) cause;
                  }
              }
              throw new ReflectionIsTemporaryException("Failed to invoke " + method, e);
          }
      }
  
      private ReflectionUtil() {
          throw new UnsupportedOperationException("provides only static methods");
      }
  }
  